@everfur/sdk 0.5.1 → 0.5.2

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 (130) hide show
  1. package/CHANGELOG.md +337 -0
  2. package/dist/BookedScreen-BJPbXLCG.d.ts +54 -0
  3. package/dist/BookedScreen-Cnld-jB_.d.cts +54 -0
  4. package/dist/{Chat-ypo6miKm.d.cts → Chat-B43wIXCv.d.cts} +3 -3
  5. package/dist/{Chat-Rzplrf5M.d.ts → Chat-my5aJLz5.d.ts} +3 -3
  6. package/dist/{DepthViews-ClykXOJj.d.cts → DepthViews-BBTv9VAs.d.cts} +1 -1
  7. package/dist/{DepthViews-Cui3oonj.d.cts → DepthViews-BLK0kgza.d.cts} +1 -1
  8. package/dist/{DepthViews-baYLMNQ-.d.ts → DepthViews-CNqAyjne.d.ts} +1 -1
  9. package/dist/{DepthViews-CeTfPUBX.d.ts → DepthViews-G-7YRtOX.d.ts} +1 -1
  10. package/dist/animations/index.d.cts +3 -3
  11. package/dist/animations/index.d.ts +3 -3
  12. package/dist/{attachments-CwsR-bPN.d.cts → attachments-CEmT52IA.d.cts} +5 -5
  13. package/dist/{attachments-D3HCBmOE.d.ts → attachments-CMNWE6YT.d.ts} +2 -2
  14. package/dist/{attachments-CzZ7in24.d.ts → attachments-DU1djTNd.d.ts} +5 -5
  15. package/dist/{attachments-Nk73Lll8.d.cts → attachments-ZyjWsZdI.d.cts} +2 -2
  16. package/dist/{bookingCopy-SDkXaxDf.d.ts → bookingCopy-BVhEt1bj.d.ts} +38 -200
  17. package/dist/{bookingCopy-Dv8rKqyV.d.cts → bookingCopy-ChZR5mtd.d.cts} +38 -200
  18. package/dist/bookingTypes-DCs8mmBb.d.cts +188 -0
  19. package/dist/bookingTypes-DCs8mmBb.d.ts +188 -0
  20. package/dist/{callCopy-rDH9JTFo.d.cts → callCopy-CPe9mbwG.d.cts} +7 -2
  21. package/dist/{callCopy-rDH9JTFo.d.ts → callCopy-CPe9mbwG.d.ts} +7 -2
  22. package/dist/{casesRepository-BTAecTnF.d.ts → casesRepository-C5zrCcaE.d.ts} +1 -1
  23. package/dist/{casesRepository-aryld7fJ.d.cts → casesRepository-q2ak9AW0.d.cts} +1 -1
  24. package/dist/chat/index.cjs +1 -1
  25. package/dist/chat/index.d.cts +14 -10
  26. package/dist/chat/index.d.ts +14 -10
  27. package/dist/chat/index.js +1 -1
  28. package/dist/client/index.cjs +1 -1
  29. package/dist/client/index.d.cts +6 -6
  30. package/dist/client/index.d.ts +6 -6
  31. package/dist/client/index.js +1 -1
  32. package/dist/{config-X6BtwDwQ.d.ts → config-DBpKJJbg.d.ts} +1 -1
  33. package/dist/{config-6qS7Sohy.d.cts → config-jocy3q66.d.cts} +1 -1
  34. package/dist/consent/index.d.cts +5 -5
  35. package/dist/consent/index.d.ts +5 -5
  36. package/dist/{context-CkqPM4Ml.d.cts → context-BfVBRgro.d.cts} +5 -5
  37. package/dist/{context-7f3Nb_xE.d.ts → context-C3n9s4aG.d.ts} +5 -5
  38. package/dist/{copy-Bd__Pw5s.d.cts → copy-IysFx8yL.d.cts} +2 -2
  39. package/dist/{copy-NgKgOOET.d.ts → copy-KP91zgtW.d.ts} +2 -2
  40. package/dist/core/index.cjs +5 -5
  41. package/dist/core/index.d.cts +12 -12
  42. package/dist/core/index.d.ts +12 -12
  43. package/dist/core/index.js +5 -5
  44. package/dist/{depth-CYPH92jE.d.ts → depth-BsMLLrQo.d.ts} +2 -2
  45. package/dist/{depth-CyjaJJ6V.d.cts → depth-O9kiVUjs.d.cts} +2 -2
  46. package/dist/{entitlementRepository-DdeFuEKp.d.ts → entitlementRepository-CHsY2kF3.d.ts} +2 -2
  47. package/dist/{entitlementRepository-Dl1qRLcJ.d.cts → entitlementRepository-DIG16pso.d.cts} +2 -2
  48. package/dist/{identity-DjqhDm5Z.d.cts → identity-D7GKfOE7.d.cts} +1 -1
  49. package/dist/{identity-Dy_L7Yq4.d.ts → identity-k8nCQ_qM.d.ts} +1 -1
  50. package/dist/index.cjs +6 -6
  51. package/dist/index.d.cts +13 -13
  52. package/dist/index.d.ts +13 -13
  53. package/dist/index.js +6 -6
  54. package/dist/notifications/index.d.cts +2 -2
  55. package/dist/notifications/index.d.ts +2 -2
  56. package/dist/{pets-BSG2qbr_.d.cts → pets-Bod_DDiW.d.cts} +1 -1
  57. package/dist/{pets-D7cZutrX.d.ts → pets-C_QX8s5f.d.ts} +1 -1
  58. package/dist/{petsRepository-D1bnxDZg.d.cts → petsRepository-B3vr628I.d.cts} +1 -1
  59. package/dist/{petsRepository-DhsX3GLw.d.ts → petsRepository-DdzgINfF.d.ts} +1 -1
  60. package/dist/{ports-DNXyyzZF.d.cts → ports-BSm48zIC.d.cts} +16 -5
  61. package/dist/{ports-C0m1G1fS.d.ts → ports-DHhxhn95.d.ts} +16 -5
  62. package/dist/records/depth/index.d.cts +7 -7
  63. package/dist/records/depth/index.d.ts +7 -7
  64. package/dist/records/index.cjs +3 -3
  65. package/dist/records/index.d.cts +10 -10
  66. package/dist/records/index.d.ts +10 -10
  67. package/dist/records/index.js +3 -3
  68. package/dist/{requestFunnel-FvE5yLDD.d.ts → requestFunnel-CTG-wNc3.d.ts} +2 -2
  69. package/dist/{requestFunnel-Bqc1inM9.d.cts → requestFunnel-Dcjyh0j2.d.cts} +2 -2
  70. package/dist/{runtimeTypes-RN-VXTFV.d.cts → runtimeTypes-4qptUulD.d.cts} +4 -4
  71. package/dist/{runtimeTypes-C0yPBz89.d.ts → runtimeTypes-CmpdQaE2.d.ts} +4 -4
  72. package/dist/server/events/index.cjs +1 -1
  73. package/dist/server/events/index.d.cts +2 -2
  74. package/dist/server/events/index.d.ts +2 -2
  75. package/dist/server/events/index.js +1 -1
  76. package/dist/server/index.cjs +2 -2
  77. package/dist/server/index.d.cts +3 -3
  78. package/dist/server/index.d.ts +3 -3
  79. package/dist/server/index.js +2 -2
  80. package/dist/televet/booking/index.cjs +1 -1
  81. package/dist/televet/booking/index.d.cts +17 -9
  82. package/dist/televet/booking/index.d.ts +17 -9
  83. package/dist/televet/booking/index.js +1 -1
  84. package/dist/televet/call/index.cjs +1 -1
  85. package/dist/televet/call/index.d.cts +13 -1
  86. package/dist/televet/call/index.d.ts +13 -1
  87. package/dist/televet/call/index.js +1 -1
  88. package/dist/televet/index.cjs +1 -1
  89. package/dist/televet/index.js +1 -1
  90. package/dist/testing/index.d.cts +1 -1
  91. package/dist/testing/index.d.ts +1 -1
  92. package/dist/testing/rn/index.d.cts +7 -7
  93. package/dist/testing/rn/index.d.ts +7 -7
  94. package/dist/testing/web/index.d.cts +7 -7
  95. package/dist/testing/web/index.d.ts +7 -7
  96. package/dist/{timelineRows-DAB5dpjF.d.cts → timelineRows-BkLhRUDt.d.cts} +1 -1
  97. package/dist/{timelineRows-D4U6A8zE.d.ts → timelineRows-Dp4ZSnAo.d.ts} +1 -1
  98. package/dist/{uploadTransport-DKJHs3Yj.d.cts → uploadTransport-C1p8FuG8.d.cts} +5 -1
  99. package/dist/{uploadTransport-D0M0T4hN.d.ts → uploadTransport-bZIKBTyK.d.ts} +5 -1
  100. package/dist/{useRecordsDepth-B35y8bV-.d.cts → useRecordsDepth-DRNry1r9.d.cts} +1 -1
  101. package/dist/{useRecordsDepth--ObtMyjH.d.ts → useRecordsDepth-DnDhTaUL.d.ts} +1 -1
  102. package/dist/{view-D9JqNQai.d.ts → view-CwuOPIJc.d.ts} +7 -4
  103. package/dist/{view-B-Toym_j.d.cts → view-D4VdPKCa.d.cts} +7 -4
  104. package/dist/web/consent/index.d.cts +5 -5
  105. package/dist/web/consent/index.d.ts +5 -5
  106. package/dist/web/index.cjs +10 -10
  107. package/dist/web/index.d.cts +14 -14
  108. package/dist/web/index.d.ts +14 -14
  109. package/dist/web/index.js +10 -10
  110. package/dist/web/notifications/index.d.cts +3 -3
  111. package/dist/web/notifications/index.d.ts +3 -3
  112. package/dist/web/records/depth/index.d.cts +7 -7
  113. package/dist/web/records/depth/index.d.ts +7 -7
  114. package/dist/web/records/index.cjs +3 -3
  115. package/dist/web/records/index.d.cts +9 -9
  116. package/dist/web/records/index.d.ts +9 -9
  117. package/dist/web/records/index.js +3 -3
  118. package/dist/web/televet/booking/index.cjs +2 -2
  119. package/dist/web/televet/booking/index.d.cts +35 -50
  120. package/dist/web/televet/booking/index.d.ts +35 -50
  121. package/dist/web/televet/booking/index.js +2 -2
  122. package/dist/web/televet/call/index.cjs +1 -1
  123. package/dist/web/televet/call/index.d.cts +12 -5
  124. package/dist/web/televet/call/index.d.ts +12 -5
  125. package/dist/web/televet/call/index.js +1 -1
  126. package/dist/web/televet/index.cjs +4 -1
  127. package/dist/web/televet/index.d.cts +31 -2
  128. package/dist/web/televet/index.d.ts +31 -2
  129. package/dist/web/televet/index.js +4 -1
  130. package/package.json +4 -3
@@ -1,4 +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 Ec=Object.defineProperty;var i=(e,r)=>Ec(e,"name",{value:r,configurable:true});var Vo=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(Vo.map(e=>e.wireCode));var xc=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"}),Ia=Object.freeze(Vo.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:xc[e.wireCode]}))),Sc=new Map(Ia.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),wc=Object.freeze(["http_envelope",...[...new Set(Ia.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Hn(e,r){if(typeof e!="string")return;let t=e.trim().toUpperCase();if(t.length!==0)for(let o of [r??"http_envelope",...wc]){let n=Sc.get(o+t);if(n)return n}}i(Hn,"contractErrorFor");function kc(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(kc,"contractDocUrl");function Aa(e){return null}i(Aa,"publishedDocUrl");var _c=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 qa(e){return _c[e]}i(qa,"categoryFor");function Na(e){let r=Hn(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":case "TELEVETRATELIMITED":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(Na,"fromWire");var Pc=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Go(e){return Pc.has(e)}i(Go,"isAutoRetryable");var Tc=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function La(e){return Go(e)||Tc.has(e)}i(La,"isRetryableCode");var Dc=500,Wo=8e3,Fa=4;function za(e,r=Math.random){let t=Math.max(0,e),o=Math.min(Dc*2**t,Wo);return Math.floor(r()*o)}i(za,"backoffDelayMs");var Oc=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 Yo(e){return Oc[e]}i(Yo,"userFacingError");function Ma(e,r,t){Object.defineProperty(e,r,{value:t,enumerable:false,writable:false,configurable:false});}i(Ma,"defineHidden");var Ic=/^[a-z][a-z0-9_]{0,63}$/;function z(e,r){let t=Hn(r?.wireCode,r?.wireEnvelope),o={code:e,category:qa(e),retryable:r?.retryable??La(e),displayMessage:Yo(e)};if(r?.httpStatus!==void 0&&(o.httpStatus=r.httpStatus),r?.requestId&&(o.requestId=r.requestId),typeof r?.reasonCode=="string"&&Ic.test(r.reasonCode)&&(o.reasonCode=r.reasonCode),t);return r?.wireMessage&&Ma(o,"wireMessage",r.wireMessage),r?.raw!==void 0&&r.raw!==null&&Ma(o,"raw",r.raw),Object.freeze(o)}i(z,"makeEverfurError");function we(e,r){return Object.freeze(r===void 0?{ok:true,value:e}:{ok:true,value:e,warning:r})}i(we,"ok");function G(e){return Object.freeze({ok:false,error:e})}i(G,"err");var Vn=class Vn extends Error{constructor(r,t){super(t),this.name="EverfurConfigError",this.kind=r,Object.setPrototypeOf(this,Vn.prototype);}};i(Vn,"EverfurConfigError");var cn=Vn;var Ha=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),$a=Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function Ac(e){let r=Object.prototype.hasOwnProperty.call($a,e)?$a[e]:void 0;if(r!==void 0)return r;let t=e;return Ha.has(t)?t:"parsing"}i(Ac,"normalizeStatus");function Va(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Va,"normalizeOrigin");var qc=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 lt(e){let r=qc.safeParse(e);if(!r.success)return null;let t=r.data,o=Lc(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??Ac(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:Ba(t.document_count,0),heldItemCount:Ba(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(lt,"mapRequestView");var Nc=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 Ga(e){let r=Nc.safeParse(e);if(!r.success)return null;let t=r.data,o=Ko(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(Ga,"mapRequestGroup");function Lc(e){return !e||e==="awaiting_upload"||e==="in_review"?null:Ha.has(e)?e:null}i(Lc,"normalizeSimpleStatus");function Ko(e){let r=Array.isArray(e)?e:[],t=[];for(let o of r){let n=lt(o);n!==null&&t.push(n);}return Object.freeze(t)}i(Ko,"mapRequestList");var Fc=z$1.object({source_doc_id:z$1.string().min(1),request_id:z$1.string().min(1)});function Wa(e){let r=Fc.safeParse(e);return r.success?Object.freeze({documentId:r.data.source_doc_id,requestId:r.data.request_id,status:"received"}):null}i(Wa,"mapUploadedDocument");var zc=z$1.object({label:z$1.string(),value:z$1.string()}),Qo=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()}),Mc=z$1.object({at:z$1.string(),value:z$1.number().nullish(),display:z$1.string().nullish(),origin:z$1.string().nullish()}),$c=z$1.object({key:z$1.string(),label:z$1.string().optional(),points:z$1.array(Mc).optional()}),Uc=z$1.object({title:z$1.string(),detail:z$1.string().nullish(),due_at:z$1.string().nullish()}),Xo=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 Jo(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:Va(e.origin),canonicalKey:e.canonical_key??null})}i(Jo,"mapEntityRow");function Zo(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(Zo,"mapDocumentRow");var Bc=z$1.object({identity:z$1.array(zc).optional(),entities:z$1.array(Qo).optional(),entity_series:z$1.array($c).optional(),forward_looking:z$1.array(Uc).optional(),documents:z$1.array(Xo).optional()});function Ya(e,r){let t=Hc(r)?r:{},o=ja(t.schema_version,"epdf/1.0"),n=ja(t.disclaimer,""),l=typeof t.pet_ref=="string"&&t.pet_ref.length>0?t.pet_ref:e;if(t.withheld===true)return Ua(l,o,n);let a=Bc.safeParse(t);if(!a.success)return Ua(l,o,n);let d=a.data,s=(d.identity??[]).map(y=>Object.freeze({label:y.label,value:y.value})),c=(d.entities??[]).map(Jo),u=(d.entity_series??[]).map(y=>Object.freeze({key:y.key,label:y.label??y.key,points:Object.freeze((y.points??[]).map(m=>Object.freeze({at:m.at,value:m.value??null,display:m.display??null,origin:Va(m.origin)})))})),p=(d.forward_looking??[]).map(y=>Object.freeze({title:y.title,detail:y.detail??null,dueAt:y.due_at??null})),f={};for(let y of d.documents??[])f[y.doc_id]=Zo(y);let R=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:R,withheld:false,generatedAt:Vc(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(Ya,"mapRecordView");function Ua(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(Ua,"withheldView");var jc=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 Gn(e,r){let t=jc.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(Gn,"mapConsent");function Hc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Hc,"isObject");function Ba(e,r){return typeof e=="number"&&Number.isFinite(e)?e:r}i(Ba,"numberOr");function ja(e,r){return typeof e=="string"&&e.length>0?e:r}i(ja,"strOr");function Vc(e){return typeof e=="string"&&e.length>0?e:null}i(Vc,"strOrNull");var Ka=Object.freeze(["published","failed","revoked"]);function Mt(e){return Ka.includes(e)}i(Mt,"isTerminalStatus");function dt(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(dt,"recordsDenialReasonOf");var Gc="records_consent_required";function Wc(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(Wc,"recordsWireCodeOf");function Jr(e){return e===null||e.httpStatus!==409?false:Wc(e)===Gc}i(Jr,"isRecordsConsentRequired");var Yc=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Wn(e){return e!==Yc}i(Wn,"isUploadTransportAvailable");var Qa=Object.freeze({record(){}}),Br=25*1024*1024,Xa=64,un=128,or=128,ct="application/pdf",Ja=9e4;function es(e){return new ei(e)}i(es,"createRecordsController");var ri=class ri{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??Qa,this.newIdempotencyKey=r.newIdempotencyKey??Zc(),this.timers=r.timers??Xc,this.uploadDeadlineMs=r.uploadDeadlineMs??Ja;}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=lt(t.value);return o===null?G(Yn()):(this.observeRequest(o),we(o))}async getRequest(r){let t=await this.repository.getRequest(r);if(!t.ok)return this.onRequestError(t.error);let o=lt(t.value);return o===null?G(Yn()):(this.observeRequest(o),we(o))}async listRequests(){let r=await this.repository.listRequests();if(!r.ok)return this.onRequestError(r.error);let t=Ko(r.value);for(let o of t)this.observeRequest(o);return we(t)}async uploadDocument(r){let{requestId:t,file:o}=r,n=Kc(o);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),G(Za(`upload rejected: ${n}`));let l=await this.repository.initiateUpload(t,{content_type:ct,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}),G(Za(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:Qc(d.error)??"corrupt"}),this.onRequestError(d.error);let s=Wa(d.value);return s===null?G(Yn()):we(s)}async postToS3(r,t,o){let n=new AbortController,l=Jc(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 G(Object.freeze({...z("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!o.ok){let l=dt(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}),G(o.error)}let n=Ya(r,o.value);return n.petRef!==r?G(Yn()):n.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:r}),this.recordCache.delete(r),we(n)):(this.recordCache.set(r,n),we(n))}peekCachedRecord(r){return this.recordCache.get(r)??null}async getConsent(r){let t=await this.repository.getConsent(r);return t.ok?we(Gn(r,t.value)):G(t.error)}async grantConsent(r){let t=await this.repository.putConsent(r.petRef,{consent_version:r.consentVersion,idempotency_key:r.idempotencyKey});return t.ok?we(Gn(r.petRef,t.value)):(dt(t.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:r.petRef}),G(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),we(Gn(r,t.value))):G(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 dt(r)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),G(r)}};i(ri,"RecordsControllerImpl");var ei=ri;function Kc(e){if(e.mimeType!==ct)return "unsupported_format";let r=e.sizeBytes;return typeof r!="number"||!Number.isFinite(r)||r<=0||r>Br?"oversize":null}i(Kc,"validateFile");function Qc(e){let r=e.wireMessage;return r==="unsupported_format"||r==="oversize"||r==="corrupt"?r:null}i(Qc,"reasonFromWire");function Za(e){return z("mediaUploadFailed",{retryable:false,wireMessage:e})}i(Za,"uploadFailed");function Yn(){return z("internalError",{retryable:true})}i(Yn,"internal");var Xc={setTimeout:i((e,r)=>setTimeout(e,r),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function Jc(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(Jc,"mergeSignals");function Zc(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(Zc,"defaultIdempotencyFactory");function Dr(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Dr,"assertNever");function rs(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(rs,"errorFrame");function tu(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(tu,"authHeaders");function pn(e,r){return {...e,headers:{...nu(e.headers),...tu(r)}}}i(pn,"withAuthHeaders");function nu(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(nu,"stripAuthHeaders");async function ts(e,r){if(r.mode==="anonymous")return r.transport.request(pn(e,{mode:"anonymous",publishableKey:r.publishableKey,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));let t;try{t=await r.identity.currentToken();}catch{return G(ti())}let o=await r.transport.request(pn(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 G(ti())}let l=await r.transport.request(pn(e,{mode:"personalized",token:n,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));return !l.ok&&l.error.httpStatus===401?G(ti(l.error.httpStatus)):l}i(ts,"authedSend");function ti(e){return z("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(ti,"authRejectedError");function ns(e){return z("internalError",{retryable:true,wireMessage:ou(e)})}i(ns,"networkError");function ou(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(ou,"describeCause");var iu=3e4,au=Wo*2,su="idempotency-key",lu=new Set(["POST","PUT","PATCH","DELETE"]),du=Object.freeze({onEvent(){}}),cu=Object.freeze({setTimeout:i((e,r)=>setTimeout(e,r),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function uu(e){let r=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return r.length===0?null:`efs_${r}`.slice(0,128)}i(uu,"seededIdempotencyKey");function ut(e){let r=e.observer??du,t=e.timers??cu,o=e.rng??Math.random,n=e.sleep??((f,R)=>Su(f,t,R)),l=e.maxAttempts??Fa,a=e.unaryTimeoutMs??iu,d=e.newIdempotencyKey??Zr(),s=i(f=>{try{r.onEvent(f);}catch{}},"emit");async function c(f,R,y){let m=y?.maxAttempts,h=Math.max(1,m??l),v=y?.idempotent??lu.has(R.method),E=y?.idempotencyKey===void 0?null:uu(y.idempotencyKey),g=v?E??d():null,b=pu(R,g),S=0;for(;;){let C=i($=>Object.freeze({call:f,method:R.method,path:R.path,attempt:S,...g?{idempotencyKey:g}:{},...$}),"stamp");s(C({phase:"attempt"}));let _=Eu(a,t),k=xu(_.signal,R.signal),T;try{T=await ts({...b,signal:k.signal},e.auth);}catch($){T=G(ns($));}finally{k.dispose(),_.cancel();}if(T.ok)return s(C({phase:"settled",ok:true,reason:"ok"})),T;let I=T.error,q=fu(I,S,{maxAttempts:h,rng:o,now:t.now(),aborted:R.signal?.aborted===true,...m!==void 0?{perCallMaxAttempts:m}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),L={ok:false,code:I.code,reason:q.reason,...I.httpStatus!==void 0?{httpStatus:I.httpStatus}:{},...I.requestId!==void 0?{requestId:I.requestId}:{}};if(!q.retry)return s(C({phase:"settled",...L})),G(I);if(s(C({phase:"retry",...L,delayMs:q.delayMs})),await n(q.delayMs,R.signal),R.signal?.aborted===true)return s(C({phase:"settled",...L,reason:"aborted"})),G(I);S+=1;}}i(c,"send");async function u(f){return pn(f,await Cu(e.auth))}i(u,"authorize");async function*p(f,R,y){s(Object.freeze({call:f,phase:"stream.open",method:R.method,path:R.path,attempt:0}));try{yield*e.auth.transport.stream(R,y);}catch{yield rs({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(ut,"createRequestFunnel");function pu(e,r){let t={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==su&&(t[o]=n);return r!==null&&(t["Idempotency-Key"]=r),{...e,headers:t}}i(pu,"assembleHeaders");function Zr(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(Zr,"defaultIdempotencyKeyFactory");var mu=10;function fu(e,r,t){if(t.aborted)return {retry:false,reason:"aborted"};let o=yu(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(mu,Math.floor(c)))},"policyCeiling"),d=t.perCallMaxAttempts??a()??t.maxAttempts;if(r+1>=d)return {retry:false,reason:"attempts-exhausted"};let s=gu(e,t.now);return s!==null?s>au?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:s}:{retry:true,reason:n,delayMs:za(r,t.rng)}}i(fu,"decideRetry");function yu(e){let r=e.code==="unknown"?Na(vu(e.raw)):e.code;return r==="quotaExceeded"?"quota":r==="rateLimited"||e.httpStatus===429?"burst":null}i(yu,"throttleKind");function gu(e,r){let t=Ru(e.raw);if(t!==null){let n=t-r;return n>0?n:0}let o=bu(e.raw);return o===null?null:Math.round(o*1e3)}i(gu,"retryOverrideMs");function bu(e){for(let r of ni(e)){let t=r.retry_after_seconds;if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return t}return null}i(bu,"findRetryAfterSeconds");function Ru(e){for(let r of ni(e)){let t=r.resets_at,o=hu(t);if(o!==null)return o}return null}i(Ru,"findResetsAt");function ni(e){if(!os(e))return [];let r=[e];for(let t of ["error","detail"]){let o=e[t];os(o)&&r.push(o);}return r}i(ni,"candidateScopes");function hu(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(hu,"parseInstantMs");function vu(e){for(let r of ni(e)){let t=r.code;if(typeof t=="string"&&t.length>0)return t}return null}i(vu,"rawWireCode");function os(e){return typeof e=="object"&&e!==null}i(os,"isRecord");async function Cu(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(Cu,"resolveDeviceAuth");function Eu(e,r){let t=new AbortController,o=r.setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>r.clearTimeout(o),"cancel")}}i(Eu,"boundedSignal");function xu(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(xu,"mergeSignals");function Su(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(Su,"delayAbortable");function pt(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(pt,"hasLoneSurrogate");var et="/widget/v1/records";function as(e){let{auth:r}=e,t=r.mode,o=e.funnel??ut({auth:r,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=i(async(s,c,u)=>{let p=await o.send(s,c);return p.ok?p:G(_u(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`}):pt(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 R=[...c].length;return R>u?z("validationFailed",{retryable:false,wireMessage:`${s} is ${R} 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,un),a("pet_ref",s.pet_ref,or));return c?Promise.resolve(G(c)):n("records.createRequest",oi(`${et}/requests`,s),"request")},"createRequest"),initiateUpload:i((s,c)=>{let u=l("request_id",s);return u?Promise.resolve(G(u)):n("records.initiateUpload",oi(`${et}/requests/${encodeURIComponent(s)}/uploads/initiate`,c),"request")},"initiateUpload"),completeUpload:i((s,c)=>{let u=l("request_id",s);return u?Promise.resolve(G(u)):n("records.completeUpload",oi(`${et}/requests/${encodeURIComponent(s)}/uploads/complete`,c),"request")},"completeUpload"),getRequest:i(s=>{let c=l("request_id",s);return c?Promise.resolve(G(c)):n("records.getRequest",Kn(`${et}/requests/${encodeURIComponent(s)}`),"request")},"getRequest"),listRequests:i(async()=>{let s=await n("records.listRequests",Kn(`${et}/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,or);return c?Promise.resolve(G(c)):n("records.getRecord",Kn(`${et}/pets/${encodeURIComponent(s)}/record`),"content")},"getRecord"),getConsent:i(s=>{let c=a("pet_ref",s,or);return c?Promise.resolve(G(c)):n("records.getConsent",Kn(`${et}/pets/${encodeURIComponent(s)}/consent`),"consent")},"getConsent"),putConsent:i((s,c)=>{let u=d(a("consent_version",c.consent_version,Xa),a("idempotency_key",c.idempotency_key,un),a("pet_ref",s,or));return u?Promise.resolve(G(u)):n("records.putConsent",Pu(`${et}/pets/${encodeURIComponent(s)}/consent`,c),"consent")},"putConsent"),deleteConsent:i(s=>{let c=a("pet_ref",s,or);return c?Promise.resolve(G(c)):n("records.deleteConsent",Tu(`${et}/pets/${encodeURIComponent(s)}/consent`),"consent")},"deleteConsent")}}i(as,"createHttpRecordsRepository");function is(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(is,"withReason");var wu="pet_not_registered";function ku(e){return e.httpStatus!==404?null:e.reasonCode===wu?"pet_not_found":"entitlement"}i(ku,"recordsErrorReasonFor");function _u(e,r,t){let o=ku(e);return o!==null?is(e,o):e.code!=="accessDenied"?e:is(e,r==="anonymous"?"session_required":t==="content"?"consent_required":"entitlement")}i(_u,"tagReason");function Kn(e){return {method:"GET",path:e}}i(Kn,"get");function oi(e,r){return {method:"POST",path:e,body:r}}i(oi,"post");function Pu(e,r){return {method:"PUT",path:e,body:r}}i(Pu,"put");function Tu(e){return {method:"DELETE",path:e}}i(Tu,"del");var ss=Symbol.for("@everfur/sdk#EverfurContext@v1"),ls=globalThis,ds=ls[ss]??(ls[ss]=createContext(null));ds.displayName??="EverfurContext";function ee(){let e=useContext(ds);if(e===null)throw new cn("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(ee,"useEverfurContext");var ii=new Map,ai=new Set;function cs(e){ii.set(e,(ii.get(e)??0)+1);for(let r of [...ai])r();}i(cs,"notifyRecordsConsentWithdrawn");function qu(e){return ii.get(e)??0}i(qu,"recordsConsentEpochOf");function Nu(e){return ai.add(e),()=>{ai.delete(e);}}i(Nu,"subscribe");function Qn(e){let r=useCallback(()=>qu(e),[e]);return useSyncExternalStore(Nu,r,r)}i(Qn,"useRecordsConsentEpoch");var li={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[]},ps=4e3,Fu=30;function Ge(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}=ee(),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,R]=useState({scope:d,value:li}),y=f.scope===d?f.value:li,m=useCallback(w=>{R(x=>x.scope===d?{scope:d,value:w(x.value)}:x);},[d]),h=useRef(0);useEffect(()=>(s.current=d,R({scope:d,value:li}),()=>{s.current=null,h.current+=1;}),[d]),useEffect(()=>{if(e.controller)return;let{services:w}=n.registry,x={record:i((D,H)=>w.telemetry.track(D,H),"record")},A=n.registry.acquire("records",`${l??""}|${r}${o?"|own-upload":""}`,()=>es({repository:as({auth:w.authFor(l),...w.errorPolicy?{errorPolicy:w.errorPolicy}:{}}),uploads:o?{postMultipart:i((D,H,de)=>(t.current??w.uploadTransport).postMultipart(D,H,de),"postMultipart")}:w.uploadTransport,telemetry:x}),()=>{});return u({scope:d,controller:A}),()=>{n.registry.release(A);}},[n,l,r,e.controller,a,d,o]);let v=useCallback(w=>{m(x=>({...x,...w}));},[m]),E=useCallback(async()=>{if(!p||s.current!==d)return;let w=h.current+=1;C.current=0,T(),v({loading:true,error:null,denialReason:null,withheld:false});let[x,A]=await Promise.all([p.getConsent(r),p.listRequests()]);if(w!==h.current)return;let D=x.ok?x.value:null,H=A.ok?A.value.filter(Ae=>Ae.petRef===r):[],de=A.ok?null:A.error;if(D&&D.granted){let Ae=await p.getRecord(r);if(w!==h.current)return;if(Ae.ok){v({consent:D,requests:H,record:Ae.value,withheld:Ae.value.withheld,error:Ae.value.withheld?Bu():de,denialReason:null,loading:false});return}v({consent:D,requests:H,record:null,error:Ae.error,denialReason:dt(Ae.error),withheld:false,loading:false});return}v({consent:D,requests:H,record:null,error:x.ok?de:x.error,denialReason:D?"consent_required":Uu(x),withheld:false,loading:false});},[p,r,v,d]);useEffect(()=>(E(),()=>{h.current+=1;}),[E]);let g=useMemo(()=>$u(y.requests),[y.requests]),b=g?.id??null,S=g?.status??null,C=useRef(0),_=useRef(null),[k,T]=useReducer(w=>w+1,0);useEffect(()=>{if(!p||b===null||S===null||Mt(S)||S==="in_review")return;_.current!==String(b)&&(_.current=String(b),C.current=0);let w=false,x=i(async()=>{if(w||C.current>=Fu)return;C.current+=1;let D=await p.getRequest(b);if(!w){if(D.ok&&D.value.petRef===r){if(m(H=>({...H,requests:Jn(H.requests,D.value)})),Mt(D.value.status)){D.value.status==="published"&&E();return}if(D.value.status==="in_review")return}A=setTimeout(()=>{x();},ps);}},"tick"),A=setTimeout(()=>{x();},ps);return ()=>{w=true,clearTimeout(A);}},[p,b,S,E,k,r,m]);let I=useCallback(async w=>{if(!p||s.current!==d)return Zn();let x=await p.createUploadRequest({petRef:r,idempotencyKey:w});return s.current===d&&x.ok&&x.value.petRef===r&&m(A=>({...A,requests:Jn(A.requests,x.value)})),x},[p,r,d,m]),q=useCallback((w,x)=>{m(A=>({...A,uploadQueue:A.uploadQueue.map(D=>D.key===w?x(D):D)}));},[m]),L=useCallback(async(w,x)=>{let A=Date.now().toString(36),D=x.map((de,Ae)=>{let oe=zu(de);return {key:`${A}-${Ae}`,name:de.name??null,status:oe===null?"queued":"skipped",progress:0,skipReason:oe,error:null}}),H=[...D];if(!p||s.current!==d)return Object.freeze(H);m(de=>({...de,uploadQueue:D,isUploading:true,uploadProgress:0}));for(let[de,Ae]of x.entries()){let oe=D[de];if(oe.status==="skipped")continue;if(s.current!==d)break;q(oe.key,Ke=>({...Ke,status:"uploading",progress:0})),v({uploadProgress:0});let ve=await p.uploadDocument({requestId:w,file:Ae,onProgress:i(Ke=>{if(s.current!==d)return;let _r=Math.min(1,Math.max(0,Ke));q(oe.key,Pr=>({...Pr,progress:Math.max(Pr.progress,_r)})),v({uploadProgress:_r});},"onProgress")});if(s.current!==d)break;let ar=ve.ok?{...oe,status:"done",progress:1}:{...oe,status:"failed",error:ve.error};if(H[de]=ar,q(oe.key,()=>ar),ve.ok){let Ke=await p.getRequest(w);s.current===d&&Ke.ok&&Ke.value.petRef===r&&m(_r=>({..._r,requests:Jn(_r.requests,Ke.value)}));}}return s.current===d&&v({isUploading:false,uploadProgress:null}),Object.freeze(H)},[p,v,q,r,d,m]),$=useCallback(async(w,x)=>{if(!p||s.current!==d)return Zn();let A=`${Date.now().toString(36)}-0`;m(H=>({...H,isUploading:true,uploadProgress:0,uploadQueue:[{key:A,name:x.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let D=await p.uploadDocument({requestId:w,file:x,onProgress:i(H=>{s.current===d&&(v({uploadProgress:H}),q(A,de=>({...de,progress:Math.max(de.progress,Math.min(1,H))})));},"onProgress")});if(s.current!==d)return D;if(v({isUploading:false,uploadProgress:null}),q(A,H=>D.ok?{...H,status:"done",progress:1}:{...H,status:"failed",error:D.error}),D.ok){let H=await p.getRequest(w);s.current===d&&H.ok&&H.value.petRef===r&&m(de=>({...de,requests:Jn(de.requests,H.value)}));}return D},[p,v,q,r,d,m]),Y=useCallback(async(w,x)=>{if(!p||s.current!==d)return Zn();let A=await p.grantConsent({petRef:r,consentVersion:w,idempotencyKey:x});return A.ok&&s.current===d&&E(),A},[p,r,E,d]),K=useCallback(async()=>{if(!p||s.current!==d)return Zn();let w=await p.revokeConsent(r);return w.ok&&cs(r),w.ok&&s.current===d&&(h.current+=1,v({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:w.value})),w},[p,r,v,d]),re=useCallback(()=>{E();},[E]),Q=Mu(y,p!==null);return useMemo(()=>({status:Q,record:y.record,requests:y.requests,activeRequest:g,consent:y.consent,error:y.error,denialReason:y.denialReason,withheld:y.withheld,isUploading:y.isUploading,uploadProgress:y.uploadProgress,uploadQueue:y.uploadQueue,createRequest:I,uploadDocument:$,uploadDocuments:L,grantConsent:Y,revokeConsent:K,refresh:re}),[Q,y,g,I,$,L,Y,K,re])}i(Ge,"useEverfurRecords");function zu(e){if(e.mimeType!==ct)return "unsupported";let r=e.sizeBytes;return typeof r!="number"||!Number.isFinite(r)||r<=0||r>Br?"too_large":null}i(zu,"skipReasonFor");function Mu(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(Mu,"selectStatus");function $u(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($u,"newestRequest");function Jn(e,r){let t=e.filter(o=>o.id!==r.id);return [r,...t]}i(Jn,"replaceRequest");function Uu(e){return e.ok?"consent_required":dt(e.error)??"consent_required"}i(Uu,"consentDenial");function Bu(){return z("internalError",{retryable:false})}i(Bu,"withheldSentinel");function Zn(){return {ok:false,error:z("internalError",{retryable:true})}}i(Zn,"notReady");function di(e){let r=globalThis.console;try{r?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(di,"reportHostFailure");function ju(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(ju,"isThenable");function Hu(e,...r){if(typeof e=="function")try{let t=e(...r);return ju(t)&&Promise.resolve(t).then(void 0,di),t}catch(t){di(t);return}}i(Hu,"callHost");var ms=new WeakMap;function fn(e){if(typeof e!="function")return;let r=ms.get(e);if(r!==void 0)return r;let t=i((...o)=>{Hu(e,...o);},"guarded");return ms.set(e,t),t}i(fn,"guardHost");function _e(e,r){let t=null;for(let o of r){let n=e[o];typeof n=="function"&&(t??={...e},t[o]=fn(n));}return t??e}i(_e,"guardHostProps");function Et(e,...r){let t;try{t=e(...r);}catch(o){return di(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(t).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(Et,"callHostAsync");var Vu="your pet";function Pe(e){let r=e?.trim()??"";return r.length>0?r:Vu}i(Pe,"petNameOr");var lr=Object.freeze({title:"Health records",openTimeline:"Open timeline",loading:"Loading health records",lead:i(e=>`${Pe(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")}),ci=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")}),rt=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")}),dr=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"}),$t=Object.freeze({title:i(e=>`${Pe(e)}\u2019s records request`,"title"),body:i(e=>`We\u2019re requesting ${Pe(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 ${Pe(e)}.`,"a11y"),openA11y:i((e,r)=>`Open ${Pe(e)}\u2019s records request. ${r}`,"openA11y"),ask:"Ask about this request",askA11y:"Ask Everfur about this records request"}),xt=Object.freeze({title:i(e=>`Add ${Pe(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 ${Pe(e)}\u2019s records from a clinic`,"requestFromClinicA11y"),uploadDocument:"Upload a document",uploadDocumentA11y:i(e=>`Upload one of ${Pe(e)}\u2019s records`,"uploadDocumentA11y")});var Se=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 ${Pe(e)}`,"requestsFor"),uploadPromptTitle:i(e=>`Do you already have ${Pe(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.",requestRecords:"Request records",requestTimeline:"Request timeline",requestTimelineA11y:i(e=>`Request timeline, ${e}`,"requestTimelineA11y"),ownerProvided:"Records you provided",askA11y:i(e=>`Ask Everfur about ${Pe(e)}'s medical records`,"askA11y")});function fs(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(fs,"buildRecordsPageAskPrompt");function eo(e){if(e.convertedToUploadAt)return Se.ownerProvided;let r=e.clinicName?.trim()??"";return r.length>0?r:Se.ownerProvided}i(eo,"consumerRequestSource");var V=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 ys(e){return !Mt(e.status)}i(ys,"isRecordsInProgress");function ro(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(ys).sort((l,a)=>a.updatedAt.localeCompare(l.updatedAt))[0]??null}i(ro,"pickPetRecordsRequest");function ui(e){if(e.hasMarkers)return "published";let r=ro(e.requests,e.petRef);return r===null?"none":r.status==="published"||ys(r)?"in_progress":"none"}i(ui,"deriveRecordsDashboardState");function Gu(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i(Gu,"selectDashboardLoading");function pi(e){return Gu(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(pi,"selectDashboardView");function Qe(e){return e?.httpStatus===429?"rate_limited":e?.httpStatus===502?"service_unavailable":"error"}i(Qe,"recordsEmptyVariantForError");var gs=Object.freeze({name:"dashboard"});function Ut(e=gs){return Object.freeze({stack:Object.freeze([e])})}i(Ut,"initialRecordsNav");function to(e){return e.stack[e.stack.length-1]??gs}i(to,"currentRecordsScreen");function mi(e,r){return Object.freeze({stack:Object.freeze([...e.stack,r])})}i(mi,"pushRecordsNav");function fi(e,r){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),r])})}i(fi,"replaceRecordsNav");function yi(e){return Ut(e)}i(yi,"resetRecordsNav");function no(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(no,"popRecordsNav");function bs(e,r){return r.name==="dashboard"?yi(r):to(e).name==="upload"&&r.name==="request"?fi(e,r):mi(e,r)}i(bs,"transitionRecordsNav");function yn(e,r){switch(r.type){case "push":return mi(e,r.screen);case "pop":return no(e).state;case "replace":return fi(e,r.screen);case "reset":return yi(r.screen);case "navigate":return bs(e,r.screen);default:return e}}i(yn,"recordsNavReducer");function Hr(e,r){return e??r?.version??""}i(Hr,"resolveConsentVersion");function tt(e,r){return Hr(e,r).length>0}i(tt,"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 oo(e){let r=e.clinicName?.trim()??"";return r.length>0?r:e.source==="owner_provided"?Rs.ownerUpload:Rs.clinicRequest}i(oo,"selectRequestTitle");var Rs=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function gi(e){return `${e} ${V.beingReviewed}`}i(gi,"heldItemsLabel");function bi(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(bi,"selectRequestList");function gn(e){let r=e.actionNeededLabel?.trim()??"";return r.length>0?r:e.statusLabel}i(gn,"selectPrimaryLabel");function io(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(io,"selectClinicCall");function hs(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(hs,"selectRequestStatusTone");var vi=class vi 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(vi,"HostRenderBoundary");var Ri=vi;function Yu({render:e}){return e()}i(Yu,"RenderHost");function hi({render:e,fallback:r,resetKey:t}){return createElement(Ri,{fallback:r,resetKey:t,children:createElement(Yu,{render:e})})}i(hi,"HostRender");function xi(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let r of Object.keys(e))xi(e[r]);}return e}i(xi,"deepFreeze");var Ku=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Es={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},xs={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},Cs={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},Qu={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Xu={regular:"400",medium:"500",bold:"700"},Ju={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Zu=0,ao="System",so="monospace",ep=["content","heading","control","compact","badge"];function rp(e){let r={};for(let t of ep)r[t]=e;return r}i(rp,"authoredTierSizes");function Ss(){return {family:ao,mono:so,fontUrl:null,families:{regular:ao,medium:ao,bold:ao,mono:so,monoMedium:so,monoBold:so},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:Cs,tierSizes:rp(Cs),lineHeight:Qu,weight:Xu,letterSpacing:Ju,scale:1,maxScale:Zu,scaleCaps:Ku}}i(Ss,"baseType");var ws={},Ci=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function Ei(e){return `cubic-bezier(${e.join(", ")})`}i(Ei,"cssCubicBezier");var ks={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:Ei(Ci.standard),emphasized:Ei(Ci.emphasized),exit:Ei(Ci.exit)},reducedMotion:false},tp={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#B91C1C",errorRed:"#FF1B00",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},_s=xi({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:tp,space:Es,radius:xs,type:Ss(),motion:ks,slots:ws}),np={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)"};xi({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:np,space:Es,radius:xs,type:Ss(),motion:ks,slots:ws});var Ps=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Ts=globalThis,Si=Ts[Ps]??(Ts[Ps]=createContext(_s));Si.displayName??="EverfurThemeContext";function ce(){return useContext(Si)}i(ce,"useEverfurTheme");var Ds=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});var Os='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',ap="System";function sp(e){let r=e.trim();return r.length===0||r===ap?Os:`${Is(r)}, ${Os}`}i(sp,"cssFontFamily");function lp(e){let r=e.trim();return r.length===0||r==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${Is(r)}, ui-monospace, Menlo, Consolas, monospace`}i(lp,"cssMonoFamily");function Is(e){return `"${e.replace(/[\\"]/g,"\\$&")}"`}i(Is,"quote");function O(e,r){let t=e.type,o=t.families[r];return {fontFamily:r==="mono"||r==="monoMedium"||r==="monoBold"?lp(o):sp(o),fontWeight:t.namedFaces[r]?t.weight.regular:t.weight[Ds[r]]}}i(O,"faceCss");var mt=Object.freeze({textAlign:"start"});var dp=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 cp(e){return dp[e]}i(cp,"requires");function As(e,r,t){let o=cp(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 wi({name:e,enabled:false,isPending:true,limits:{}});let l=up(o,n);return o.filter(d=>n.get(d)?.granted!==true).length===0?wi({name:e,enabled:true,isPending:false,limits:l}):wi({name:e,enabled:false,isPending:false,limits:l,disabled:pp(o,n)})}i(As,"decideCapability");function up(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(up,"mergeLimits");function pp(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:Yo("accessDenied"),level:"user_entitlement",recoverable:false})}i(pp,"disabledFor");function wi(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(wi,"freezeDecision");function St(e){let{runtime:r}=ee(),t=r.entitlements,o=useSyncExternalStore(t.subscribe,t.getSnapshot,t.getSnapshot);return useMemo(()=>As(e,o.decisions,{isPending:o.isPending}),[e,o])}i(St,"useCapability");var yp=48;function gp(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(gp,"selectView");function Te(e){let{capability:r,children:t,renderDisabled:o,renderPending:n,style:l,className:a}=e,d=St(r),s=useMemo(()=>gp(d),[d]);switch(s){case "enabled":return t;case "pending":return n?jsx(hi,{render:n,fallback:jsx(qs,{capability:r,style:l,className:a})}):jsx(qs,{capability:r,style:l,className:a});case "disabled":return o?jsx(hi,{render:()=>o(d),fallback:jsx(Ns,{decision:d,style:l,className:a}),resetKey:d}):jsx(Ns,{decision:d,style:l,className:a});default:return Dr(s)}}i(Te,"CapabilityGate");function qs({capability:e,style:r,className:t}){let o=ce(),n=useMemo(()=>Ls(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(qs,"PendingSkeleton");function Ns({decision:e,style:r,className:t}){let o=ce(),n=useMemo(()=>Ls(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(Ns,"OffState");function Ls(e){let{color:r,space:t,radius:o,type:n}=e;return {offstate:{...mt,boxSizing:"border-box",minHeight:yp,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,...O(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(Ls,"makeStyles");var lo=2;function Fs(e){return typeof e!="number"||!Number.isInteger(e)?lo:e<1?1:e>6?6:e}i(Fs,"headingLevel");function _i(e){return e>=6?6:e+1}i(_i,"nextHeadingLevel");function co(e){return `h${String(e)}`}i(co,"headingTag");var Rp=_i(lo);createContext(Rp);var Pi=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 De(e){let r=ce(),t=useMemo(()=>vp(r),[r]);return jsxs("div",{role:"note",className:e.className,style:{...t.container,...e.style},children:[jsx("p",{style:t.title,children:Pi.title}),jsx("p",{style:t.body,children:Pi.body})]})}i(De,"ClinicalDisclaimer");function vp(e){let{color:r,space:t,type:o}=e,n=`${Math.round(o.size.caption*o.lineHeight.snug)}px`;return {container:{...mt,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,...O(e,"bold"),fontSize:o.size.caption,lineHeight:n,color:r.text.secondary,letterSpacing:o.letterSpacing.eyebrow},body:{margin:0,...O(e,"regular"),fontSize:o.size.caption,lineHeight:n,color:r.text.muted}}}i(vp,"makeStyles");var X=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"}),Ms=100;var xe=Object.freeze({title:X.title,placeholder:X.placeholder,searchA11y:X.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:X.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 $s(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($s,"clinicEmailStatusBadge");function Us(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} km`}i(Us,"formatClinicDistanceLabel");function Bs(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} ${e===1?"kilometer":"kilometers"} away`}i(Bs,"formatClinicDistanceForA11y");var js=300,Ti=2;var ue=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 Ep(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(Ep,"fallbackFailureTitle");function Hs(e){let r=e.failureReason?.trim()??"";return r.length>0?r:Ep(e)}i(Hs,"failureTitle");var xp=1440*60*1e3;function Di(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/xp)}i(Di,"requestElapsedDays");var Sp=7;function Vs(e,r){return e.wireStatus!=="awaiting_response"?false:Di(e,r)>=Sp}i(Vs,"requestWaitingTooLong");function Oi(e){return e.status==="failed"}i(Oi,"isTerminalFailure");function Gs(e){return Oi(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i(Gs,"shouldOfferRecovery");function Ks(e,r){let[t,o]=useState(""),[n,l]=useState(""),[a,d]=useState([]),[s,c]=useState(null),[u,p]=useState([]),[f,R]=useState(true),[y,m]=useState(false),[h,v]=useState(false),[E,g]=useState(null),[b,S]=useState(null),[C,_]=useState(0),k=useRef(0),T=useRef(true),I=r?.latitude,q=r?.longitude,L=useMemo(()=>I!==void 0&&q!==void 0?{latitude:I,longitude:q}:void 0,[I,q]);useEffect(()=>(T.current=true,()=>{T.current=false,k.current+=1;}),[e]),useEffect(()=>{let Q=true;return R(true),e.recentClinics({limit:5}).then(w=>{Q&&(w.ok&&p(w.value.clinics),R(false));}).catch(()=>{Q&&R(false);}),()=>{Q=false;}},[e]),useEffect(()=>{let Q=t.trim();if(Q.length<Ti){l("");return}let w=setTimeout(()=>l(Q),js);return ()=>clearTimeout(w)},[t]);let $=n.length>=Ti;useEffect(()=>{let Q=k.current+=1;if(d([]),c(null),g(null),S(null),!$){m(false);return}m(true),e.searchClinics({query:n,limit:25,...L?{location:L}:{}}).then(w=>{!T.current||Q!==k.current||(w.ok?(d(w.value.clinics),c(w.value.nextCursor)):g(w.error),m(false));}).catch(()=>{T.current&&Q===k.current&&m(false);});},[e,n,$,L,C]);let Y=useCallback(()=>{if(!$||s===null||h)return;let Q=k.current;v(true),S(null),e.searchClinics({query:n,limit:25,cursor:s,...L?{location:L}:{}}).then(w=>{!T.current||Q!==k.current||(w.ok?(d(x=>[...x,...w.value.clinics]),c(w.value.nextCursor)):S(w.error),v(false));}).catch(()=>{T.current&&Q===k.current&&v(false);});},[e,s,n,$,h,L]),K=useCallback(Q=>o(Q),[]),re=useCallback(()=>_(Q=>Q+1),[]);return useMemo(()=>({query:t,debouncedQuery:n,isSearchActive:$,clinics:a,recent:u,recentLoading:f,initialLoading:y,loadingMore:h,hasNextPage:s!==null,error:E,pageError:b,setQuery:K,loadMore:Y,retry:re}),[t,n,$,a,u,f,y,h,s,E,b,K,Y,re])}i(Ks,"useClinicPicker");function Ai(e,r,t,o){return Object.freeze({key:e?.id??`free:${r??""}`,clinic:e,freeText:r,email:t,idempotencyKey:o})}i(Ai,"clinicDraftFor");var Bt=10,po=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),bn=i((e,r=1)=>z$1.string().refine(t=>!pt(t)&&[...t].length>=r&&[...t].length<=e),"text"),Xs=i(e=>[...e].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===127),"hasControl"),wp=z$1.object({clinicId:po.optional(),clinicFreeText:bn(200).refine(e=>e.trim().length>0).optional(),clinicEmail:bn(320,3).refine(e=>!Xs(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:po.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)),kp=z$1.object({petRef:bn(128),ownerName:bn(200).refine(e=>e.trim().length>0&&!Xs(e)),authorizationVersion:bn(64),clinics:z$1.array(wp).min(1).max(Bt)}).strict(),_p=z$1.object({request_group_id:po,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:po.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 Js(e){let r=e.funnel??ut({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(t){if(!kp.safeParse(t).success)return G(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=_p.safeParse(o.value);if(!n.success||n.data.pet_ref!==t.petRef)return Qs();let l=[];for(let a of n.data.results){let d=a.request===void 0||a.request===null?null:lt(a.request);if(a.created!==(d!==null))return Qs();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 we(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(Js,"createRecordsClinicBatchClient");function Qs(){return G(z("internalError",{retryable:false}))}i(Qs,"malformed");var Zs=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),Pp=z$1.object({clinics:z$1.array(z$1.object({clinic_id:Zs,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()}),Tp=z$1.object({authorization_version:z$1.string().min(1),scope_template:z$1.string().min(1),authorization_template:z$1.string().min(1)}),Dp=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 el(e){let{repository:r}=e,t=i(async n=>{let l=await n;if(!l.ok)return l;let a=lt(l.value);return a===null?wt():we(a)},"request"),o=i(async n=>{let l=await n;if(!l.ok)return l;let a=Pp.safeParse(l.value);return a.success?we(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})):wt()},"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=Ga(l.value);return a===null?wt():we(a)},async getAuthorizationCopy(){let n=await r.getAuthorizationCopy();if(!n.ok)return n;let l=Tp.safeParse(n.value);return l.success?we(Object.freeze({authorizationVersion:l.data.authorization_version,scopeTemplate:l.data.scope_template,authorizationTemplate:l.data.authorization_template})):wt()},async createClinicRequest(n){let l=await t(r.createClinicRequest(n));return l.ok&&l.value.petRef!==n.petRef?wt():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=Dp.safeParse(l.value);return a.success?we(Object.freeze({uploadId:a.data.upload_id,uploadUrl:a.data.upload_url,uploadFields:Object.freeze(a.data.upload_fields)})):wt()},async completeSignatureUpload(n){let l=await r.completeSignatureUpload(n);if(!l.ok)return l;let a=z$1.object({signature_id:Zs}).safeParse(l.value);return a.success?we(a.data.signature_id):wt()}}}i(el,"createRecordsClinicController");function wt(){return G(z("internalError",{retryable:false}))}i(wt,"malformed");var ft="/widget/v1/records",rl=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),gt=i((e,r=1)=>z$1.string().refine(t=>!pt(t)&&[...t].length>=r&&[...t].length<=e),"text"),nl=i(e=>[...e].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===127),"hasControl"),ol=gt(320,3).refine(e=>!nl(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),tl=gt(64),Op=z$1.object({limit:z$1.number().int().min(1).max(25).optional()}).strict(),Ip=z$1.object({query:gt(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:gt(512,0).optional()}).strict(),Ap=z$1.object({petRef:gt(128),ownerName:gt(200).refine(e=>e.trim().length>0&&!nl(e)),authorizationVersion:gt(64),clinicId:rl.optional(),clinicFreeText:gt(200).refine(e=>e.trim().length>0).optional(),clinicEmail:ol.optional(),signatureId:rl.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 il(e){let r=e.funnel??ut({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)=>tl.safeParse(n).success?t(l,{method:"POST",path:`${ft}/requests/${encodeURIComponent(n)}/${l}`,...a?{body:a}:{}}):yt(),"recover");return {searchClinics(n){return Ip.safeParse(n).success?t("search",{method:"GET",path:`${ft}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):yt()},recentClinics(n){return Op.safeParse(n).success?t("recent",{method:"GET",path:`${ft}/clinics/recent`,query:{limit:n.limit}}):yt()},getRequestGroup(n){return tl.safeParse(n).success?t("requestGroup",{method:"GET",path:`${ft}/request-groups/${encodeURIComponent(n)}`}):yt()},getAuthorizationCopy:i(()=>t("authorizationCopy",{method:"GET",path:`${ft}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return Ap.safeParse(n).success?t("create",{method:"POST",path:`${ft}/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):yt()},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 ol.safeParse(l).success?o(n,"clinic-email",{clinic_email:l}):yt()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?yt():t("signatureInitiate",{method:"POST",path:`${ft}/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:`${ft}/signatures/complete`,body:{upload_id:n}}):yt()}}}i(il,"createHttpRecordsClinicRepository");function yt(){return Promise.resolve(G(z("validationFailed",{retryable:false})))}i(yt,"invalid");function Ir(){let{runtime:e,userRef:r,scopeEpoch:t}=ee(),o=useMemo(()=>{let{services:l}=e.registry;return el({repository:il({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 G(z("accessDenied"));let d=await a();return n.current===o?d:G(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(Ir,"useEverfurRecordsClinic");function qi(){let{runtime:e,userRef:r,scopeEpoch:t}=ee(),o=useMemo(()=>{let{services:l}=e.registry;return Js({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 G(z("accessDenied"));let a=await o.createClinicRequestBatch(l);return n.current===o?a:G(z("accessDenied"))}}),[o,r])}i(qi,"useEverfurRecordsClinicBatch");var qp=120,Np=44;function Lp({reason:e,onExit:r,exitLabel:t,style:o,className:n}){let{color:l,space:a,radius:d,type:s}=ce();return jsxs("div",{className:n,"data-testid":"records-gate-off",style:{boxSizing:"border-box",minHeight:qp,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:Np,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(Lp,"RecordsGateOffState");function Oe(e,r){return e===void 0?{}:{renderDisabled:i(t=>jsx(Lp,{reason:t.disabled?.reason??"",onExit:e,exitLabel:r}),"renderDisabled")}}i(Oe,"recordsGateExit");function zp(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(zp,"slotBox");function Wr(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(Wr,"slotText");function Ar(e,r){let t=zp(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(Ar,"slotBoxCss");var Rn="data-ef-screen-heading";function dl(e){return e.focus(),document.activeElement===e}i(dl,"focusTook");function $p(e){let r=e.querySelector(`[${Rn}]`);if(r!==null&&(r.textContent??"").trim().length>0&&dl(r)||dl(e))return;let t=e.firstElementChild;t instanceof HTMLElement&&(t.hasAttribute("tabindex")||(t.setAttribute("tabindex","-1"),t.style.outline="none"),t.focus());}i($p,"focusScreen");function jt(e){let r=useRef(null),t=useRef(e);return useEffect(()=>{if(Object.is(t.current,e))return;t.current=e;let o=r.current;o!==null&&$p(o);},[e]),r}i(jt,"useFocusScreenOnChange");var Bp=120,hn=44,Le="Back";function B(){let e=ce(),r=useMemo(()=>jp(e),[e]);return {theme:e,styles:r}}i(B,"useScreenStyles");function He({title:e,onBack:r,right:t,testID:o,variant:n="brand"}){let{styles:l}=B();return jsxs("header",{style:l.headerRow,"data-testid":o,children:[r?jsx("button",{type:"button",onClick:r,"aria-label":Le,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",{tabIndex:-1,[Rn]:"",style:n==="document"?l.documentTitle:l.headerTitle,children:e}),jsx("div",{style:l.headerRight,children:t??jsx("span",{style:l.iconButton})})]})}i(He,"ScreenHeader");function bt({disclaimer:e,style:r}){let{styles:t}=B();return e.trim().length===0?null:jsxs("p",{role:"note","aria-label":lr.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(bt,"DisclaimerBand");function U({label:e,onClick:r,kind:t="primary",disabled:o=false,busy:n=false,ariaLabel:l,ariaDescribedBy:a,testID:d,style:s}){let{styles:c}=B(),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(U,"Pill");function cr({label:e,tone:r="neutral",testID:t}){let{styles:o}=B();return jsx("span",{style:{...o.chip,...o.chipTones[r]},"data-testid":t,children:e})}i(cr,"Chip");function qr({title:e,count:r}){let{styles:t}=B();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(qr,"SectionHeader");function Li({name:e,color:r}){return jsx("svg",{"aria-hidden":"true",focusable:"false",width:18,height:18,viewBox:"0 0 24 24",fill:"none",stroke:r,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block",flexShrink:0},"data-glyph":e,children:e==="send"?jsxs(Fragment,{children:[jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}):jsxs(Fragment,{children:[jsx("circle",{cx:"18",cy:"5",r:"3"}),jsx("circle",{cx:"6",cy:"12",r:"3"}),jsx("circle",{cx:"18",cy:"19",r:"3"}),jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]})})}i(Li,"HeaderGlyph");function kt({direction:e="right"}){let{styles:r}=B(),t=e==="right"?"45deg":e==="down"?"135deg":"-45deg";return jsx("span",{"aria-hidden":"true",style:{...r.chevron,transform:`rotate(${t})`}})}i(kt,"Chevron");function jp(e){let{color:r,space:t,radius:o,type:n,slots:l}=e,a=i((R,y)=>`${Math.round(R*y)}px`,"lh"),d=i((R,y,m,h="regular")=>({margin:0,...O(e,h),fontSize:R,lineHeight:a(R,y),color:m}),"text"),s=Wr(l.recordCard),c=`1px solid ${r.brandBorder}`,u=e.brightness==="dark"?r.errorRed:r.danger,p=i((R,y)=>({backgroundColor:R,color:y}),"tone"),f={boxSizing:"border-box",minHeight:hn,minWidth:hn,padding:`${t.md}px ${t.lg+t.xs/2}px`,borderRadius:o.pill,...O(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:{...mt,boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:Bp,height:"100%",backgroundColor:r.background,color:r.text.primary,...O(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:hn,height:hn,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",...Ar(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,...Ar(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`,...O(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,...Ar(l.primaryButton),...Wr(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",...O(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:hn,padding:`${t.sm}px ${t.md}px`,border:`1px solid ${r.borderHairlineGreen}`,borderRadius:o.sm,color:r.text.primary,backgroundColor:r.surface,...O(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:O(e,"mono"),plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},dialogFrame:{boxSizing:"border-box",position:"fixed",top:0,right:0,bottom:0,left:0,width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",margin:0,padding:0,border:0,backgroundColor:"transparent",overflow:"hidden"},dialogScrim:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",padding:t.lg,backgroundColor:"rgba(0,0,0,0.4)"},dialogScrimSide:{boxSizing:"border-box",display:"flex",alignItems:"stretch",justifyContent:"flex-end",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.4)"},dialogPanel:{boxSizing:"border-box",width:"100%",maxWidth:560,maxHeight:"100%",overflowY:"auto",backgroundColor:r.surface,borderRadius:o.xl-1,padding:`${t.lg}px ${t.lg+t.xs+t.xs/2}px`,display:"flex",flexDirection:"column",gap:t.md,...O(e,"regular"),color:r.text.primary},dialogPanelSide:{boxSizing:"border-box",width:"min(100vw, 480px)",height:"100%",maxHeight:"100%",overflowY:"auto",backgroundColor:r.surface,padding:`${t.lg}px ${t.lg+t.xs+t.xs/2}px`,display:"flex",flexDirection:"column",gap:t.md,...O(e,"regular"),color:r.text.primary},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(jp,"makeScreenStyles");function Ht(e,r){return e===null?"":r?`${e} ${r}`:e}i(Ht,"formatEntityValue");function Fi(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(Fi,"formatShortDate");var ul=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function J(e){if(!e)return "-";let r=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(r!==null){let n=ul[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 `${ul[o.getUTCMonth()]} ${o.getUTCDate()}, ${o.getUTCFullYear()}`}i(J,"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 Yr(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(Yr,"markerStatusLabel");function Vt(e,r){return r<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${r} visits`}i(Vt,"trajectoryLabel");function Kr(e){let r=e.replace(/_/g," ").trim();return r.length===0?e:r.charAt(0).toUpperCase()+r.slice(1)}i(Kr,"humanize");var pl=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 Gt(e){return Object.prototype.hasOwnProperty.call(pl,e)?pl[e]:Kr(e)}i(Gt,"bodySystemLabel");var ml=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 Wt(e){return Object.prototype.hasOwnProperty.call(ml,e)?ml[e]:Kr(e)}i(Wt,"soapSectionLabel");function fl(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(fl,"formatWeightKg");function ur(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(ur,"formatMarkerReading");function zi(e,r,t){let o=Vt(r,t);return e?`${me.measured(J(e))}${o?` \xB7 ${o}`:""}`:o}i(zi,"labDetailLine");var fo=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"})}),Mi=60;function yl(e){return `Try again in ${e}s`}i(yl,"coolingActionLabel");var gl="Try again, available shortly";var se=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.",shareMessage:i(e=>`View this medical record: ${e}`,"shareMessage"),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.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",turnedOff:"Link turned off."})});function Hp(e,r){if(!e)return false;let t=Date.parse(e);return Number.isNaN(t)?false:t<=r}i(Hp,"isShareExpired");function Vp(e,r){let t=J(e);return t==="-"?r?"Expired":"No expiry date":r?`Expired ${t}`:`Expires ${t}`}i(Vp,"formatShareExpiry");function bl(e,r,t){let o=e.map(n=>{let l=Hp(n.expiresAt,t),a=Vp(n.expiresAt,l),d=J(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(bl,"buildShareRows");function _t(e,r){let t=e?.httpStatus;if(Jr(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(_t,"shareErrorMessage");function fe({width:e,height:r,radius:t,style:o}){let{color:n,radius:l}=ce();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 $i=180,hl=44,Ui=62;function Yt({testID:e}){let r=Kt(),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":lr.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:$i,height:$i,radius:$i/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:hl,radius:12})}),jsxs("div",{style:{...r.inset,...r.actions},children:[t("a"),t("b")]})]})}i(Yt,"DashboardSkeleton");function yo({testID:e}){let r=Kt();return jsxs("div",{role:"progressbar","aria-label":ue.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(yo,"RequestSkeleton");function vl({testID:e}){let r=Kt();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:hl,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(vl,"TimelineSkeleton");function Cl({testID:e}){let r=Kt();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(Cl,"ClinicsSkeleton");function El({testID:e}){let r=Kt();return jsx("div",{role:"progressbar","aria-label":se.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(El,"SharesSkeleton");function Fe({variant:e,onAction:r,message:t,testID:o}){let n=Kt(),l=fo[e],[a,d]=useState(e==="rate_limited"?Mi:0);useEffect(()=>{e==="rate_limited"&&d(Mi);},[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?yl(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?gl:c,style:{...n.emptyAction,...s?n.emptyActionDisabled:{}},"data-testid":o?`${o}-action`:`records-empty-${e}-action`,children:c}):null]})}i(Fe,"RecordsEmptyState");function Kt(){let e=ce();return useMemo(()=>Yp(e),[e])}i(Kt,"useStyles");function Yp(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:Ui},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,...O(e,"bold"),fontSize:n.size.subtitle,lineHeight:`${Math.round(n.size.subtitle*n.lineHeight.snug)-1}px`,color:r.brand},emptyBody:{margin:0,...O(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",...O(e,"bold"),fontSize:n.size.bodyTight},emptyActionDisabled:{opacity:.5,cursor:"default"}}}i(Yp,"makeStyles");var Xp=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Cn(e){let{userRef:r,scopeEpoch:t}=ee();return jsx(Te,{capability:"recordsClinic",style:e.style,className:e.className,...Oe(e.onBack,Le),children:r===null?jsx("p",{role:"alert",children:V.sessionRequired}):jsx(Jp,{..._e(e,["onNavigate","onBack"])},JSON.stringify([r,t,e.petRef]))})}i(Cn,"EverfurClinicPicker");function Jp({petRef:e,controller:r,recordsController:t,location:o,onNavigate:n,onBack:l,style:a,className:d}){let{theme:s,styles:c}=B(),u=Ir(),p=Ks(r??u,o),f=Ge(t?{petRef:e,controller:t}:{petRef:e}),R=useRef(Zr()),[y,m]=useState(false),[h,v]=useState(null),[E,g]=useState(false),[b,S]=useState(""),[C,_]=useState(false),[k,T]=useState(""),[I,q]=useState(false),L=useCallback(D=>{n?.({name:"consent",clinic:Ai(D,null,"",R.current())});},[n]),$=i(()=>{y||(m(true),v(null),f.createRequest(`records-upload-${Date.now().toString(36)}`).then(D=>{if(m(false),!D.ok){v(ue.errors.start);return}n?.({name:"request",requestId:D.value.id});}));},"startUpload"),Y=C?b:p.query,K=Xp.test(k.trim()),re=Y.trim().length>0&&K,Q=p.isSearchActive?p.clinics:p.recent,w=p.isSearchActive?p.error?Qe(p.error):!p.initialLoading&&p.clinics.length===0?"idle":null:p.recent.length>0||p.recentLoading?null:"idle",x={display:"flex",flexDirection:"column",gap:s.space.sm},A=i(D=>{let H=D.currentTarget;H.scrollTop+H.clientHeight>=H.scrollHeight-H.clientHeight*.6&&p.loadMore();},"onScroll");return jsxs("div",{className:d,style:{...c.root,...a},"data-testid":"records-clinic-picker",children:[jsx(He,{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:D=>p.setQuery(D.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:{...x,padding:`0 ${s.space.lg}px ${s.space.md}px`},children:[h?jsx("p",{role:"alert",style:c.errorBanner,children:h}):null,jsx(U,{label:y?xe.uploadOwnStarting:xe.uploadOwn,kind:"outline",ariaLabel:xe.uploadOwnA11y,busy:y,onClick:$,testID:"records-clinic-upload-own"})]}):null,jsxs("div",{style:{...c.body,...c.content,gap:s.space.md},onScroll:p.isSearchActive?A: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:()=>g(D=>!D),"aria-expanded":E,"aria-label":E?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,...O(s,"bold")},children:xe.fallback.title}),jsx("span",{style:c.muted,children:xe.fallback.subtitle})]}),jsx(kt,{direction:E?"up":"down"})]}),E?jsxs("div",{style:x,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:Y,onChange:D=>{S(D.target.value),_(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:k,onChange:D=>{T(D.target.value),q(false);},onBlur:()=>q(true),placeholder:xe.fallback.emailPlaceholder,maxLength:320,autoComplete:"off","data-testid":"records-clinic-fallback-email"}),I&&k.trim().length>0&&!K?jsx("p",{role:"alert",style:c.errorText,children:ue.errors.invalidEmail}):null,jsx("p",{style:c.muted,children:xe.fallback.reviewNote}),jsx(U,{label:xe.fallback.submit,ariaLabel:xe.fallback.submitA11y,disabled:!re||!n,onClick:()=>n?.({name:"consent",clinic:Ai(null,Y.trim(),k.trim().toLowerCase(),R.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):p.recent.length>0?jsx("h3",{style:{...c.fieldLabel,...O(s,"bold"),textTransform:"uppercase",marginBottom:0},"data-testid":"records-clinic-recent-label",children:xe.recentlyUsed}):null,p.isSearchActive&&p.initialLoading?jsx(Cl,{testID:"records-clinic-page-loading"}):null,jsx("ul",{style:{...c.plainList,gap:s.space.md},children:Q.map(D=>{let H=$s(D.emailStatus),de=Us(D.distanceKm),Ae=[D.name,D.address,D.phone?`phone ${D.phone}`:null,de?Bs(D.distanceKm):null,H.a11y].filter(Boolean).join(", "),oe=H.tone==="positive"?{backgroundColor:s.color.badgeBgPositive,color:s.color.success}:H.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:()=>L(D),"aria-label":xe.selectA11y(Ae),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-${D.id}`,children:[jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.space.sm},children:[jsx("span",{style:{...c.rowTitle,...O(s,"bold"),color:s.color.brand},children:D.name}),de?jsx("span",{"aria-hidden":"true",style:{...c.muted,...c.mono},children:de}):null]}),D.address?jsx("span",{style:c.rowDetail,children:D.address}):null,D.phone?jsx("span",{"aria-hidden":"true",style:c.rowMuted,children:D.phone}):null,jsx("span",{"aria-hidden":"true",style:{...c.chip,...oe,...O(s,"bold"),fontSize:s.type.size.micro,alignSelf:"flex-start"},children:H.label})]})},D.id)})}),w&&!p.initialLoading?jsx(Fe,{variant:w,message:p.isSearchActive&&w==="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:x,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(De,{})]})}i(Jp,"PickerBody");var ze=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${Bt} 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 En(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(En,"renderClinicScope");function xn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(xn,"clinicNeedsEmail");function xl(e,r,t){let[o,n]=useState(e.ownerName),[l,a]=useState(""),[d,s]=useState(null),[c,u]=useState(""),[p,f]=useState([]),[R,y]=useState([]),[m,h]=useState(null),[v,E]=useState(null),[g,b]=useState(false),[S,C]=useState(false),[_,k]=useState(null),[T,I]=useState(0),q=useRef(false),L=useRef(false),$=useRef(0),Y=useRef(Zr()),K=useRef(null),re=useRef(null),Q=useRef(0);useEffect(()=>(q.current=true,L.current=false,b(false),()=>{q.current=false,Q.current+=1,$.current+=1,K.current=null,re.current?.abort();}),[r]),useEffect(()=>{let oe=true;return h(null),K.current=null,r.getAuthorizationCopy().then(ve=>{oe&&(ve.ok?(h(ve.value),E(null)):E(ve.error));}).catch(()=>{oe&&E(z("internalError"));}),()=>{oe=false;}},[r,T]),useEffect(()=>{let oe=true;return y([]),r.recentClinics({limit:5}).then(ve=>{oe&&ve.ok&&y(ve.value.clinics);}).catch(()=>{}),()=>{oe=false;}},[r]);let w=i(()=>{K.current=null,E(null);},"invalidate"),x=d?.name??l.trim(),A=m?En(m,o.trim(),e.petName,x):null,D=xn(d),H=!!(m&&A&&o.trim()&&e.petName.trim()&&x&&(!D||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(c.trim()))&&t),de=i(async()=>{if(L.current)return;let oe=++$.current;C(true);try{let ve=await r.searchClinics({query:l.trim(),limit:100});if(!q.current||oe!==$.current)return;ve.ok?(f(ve.value.clinics),E(null)):E(ve.error);}catch{q.current&&oe===$.current&&E(z("internalError"));}finally{q.current&&oe===$.current&&C(false);}},"search"),Ae=i(async()=>{if(L.current||_||!H||!m||!A||!t)return;L.current=true;let oe=Q.current,ve=i(()=>q.current&&Q.current===oe,"current");b(true),E(null);try{if(!K.current){re.current=new AbortController;let Ke=await t({petRef:e.petRef,petName:e.petName,ownerName:o.trim(),clinicName:x,authorizationVersion:m.authorizationVersion,scopeText:A,signal:re.current.signal});if(!ve()||Ke===null)return;let _r=d&&(!D||d.emailStatus==="none")?{clinicId:d.id}:{clinicFreeText:x};K.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:m.authorizationVersion,..._r,...D?{clinicEmail:c.trim().toLowerCase()}:{},...Ke.signatureId!==void 0?{signatureId:Ke.signatureId}:{signaturePngBase64:Ke.signaturePngBase64},idempotencyKey:Y.current()};}if(!ve())return;let ar=await r.createClinicRequest(K.current);if(!ve())return;if(!ar.ok){E(ar.error);return}if(ar.value.petRef!==e.petRef){E(z("internalError"));return}k(ar.value),K.current=null,e.onCreated?.(ar.value);}catch{ve()&&E(z("internalError"));}finally{L.current=false,ve()&&b(false);}},"submit");return {ownerName:o,query:l,clinic:d,email:c,clinics:p,copy:m,scope:A,error:v,busy:g,searching:S,created:_,ready:H,needsEmail:D,recent:p.length===0&&d===null?R:[],setOwnerName(oe){L.current||(w(),n(oe));},setQuery(oe){L.current||(w(),$.current+=1,C(false),f([]),s(null),u(""),a(oe));},setEmail(oe){L.current||(w(),u(oe));},selectClinic(oe){L.current||(w(),$.current+=1,C(false),f([]),s(oe),a(oe.name),u(""));},invalidate:w,search:de,submit:Ae,retryCopy(){E(null),I(oe=>oe+1);}}}i(xl,"useClinicRequestForm");var Zp=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Xt(e){return e.clinic?.name??e.freeText??""}i(Xt,"draftName");function Qt(e){return xn(e.clinic)}i(Qt,"draftNeedsEmail");function Sl(e,r,t,o,n){let[l,a]=useState(e.ownerName),[d,s]=useState(""),[c,u]=useState([]),[p,f]=useState([]),[R,y]=useState([]),[m,h]=useState(null),[v,E]=useState(null),[g,b]=useState(false),[S,C]=useState(false),[_,k]=useState(null),[T,I]=useState(null),[q,L]=useState(0),$=useRef(false),Y=useRef(false),K=useRef(0),re=useRef(0),Q=useRef(Zr()),w=useRef(null),x=useRef(null);useEffect(()=>($.current=true,Y.current=false,b(false),()=>{$.current=false,re.current+=1,K.current+=1,w.current=null,x.current?.abort();}),[r,t]),useEffect(()=>{let M=true;return h(null),w.current=null,r.getAuthorizationCopy().then(Re=>{M&&(Re.ok?(h(Re.value),E(null)):E(Re.error));}).catch(()=>{M&&E(z("internalError"));}),()=>{M=false;}},[r,q]),useEffect(()=>{let M=true;return f([]),r.recentClinics({limit:5}).then(Re=>{M&&Re.ok&&f(Re.value.clinics);}).catch(()=>{}),()=>{M=false;}},[r]);let A=i(()=>{w.current=null,E(null);},"invalidate"),D=R.map(Xt),H=m?D.map(M=>En(m,l.trim(),e.petName,M)):[],de=H.every(M=>M!==null)?H.join(`
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 xc=Object.defineProperty;var i=(e,r)=>xc(e,"name",{value:r,configurable:true});var Go=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(Go.map(e=>e.wireCode));var Sc=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"}),Ia=Object.freeze(Go.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:Sc[e.wireCode]}))),wc=new Map(Ia.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),kc=Object.freeze(["http_envelope",...[...new Set(Ia.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Hn(e,r){if(typeof e!="string")return;let t=e.trim().toUpperCase();if(t.length!==0)for(let o of [r??"http_envelope",...kc]){let n=wc.get(o+t);if(n)return n}}i(Hn,"contractErrorFor");function _c(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(_c,"contractDocUrl");function Aa(e){return null}i(Aa,"publishedDocUrl");var Pc=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 qa(e){return Pc[e]}i(qa,"categoryFor");function Na(e){let r=Hn(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":case "TELEVETRATELIMITED":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(Na,"fromWire");var Tc=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Wo(e){return Tc.has(e)}i(Wo,"isAutoRetryable");var Dc=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function La(e){return Wo(e)||Dc.has(e)}i(La,"isRetryableCode");var Oc=500,Yo=8e3,Fa=4;function za(e,r=Math.random){let t=Math.max(0,e),o=Math.min(Oc*2**t,Yo);return Math.floor(r()*o)}i(za,"backoffDelayMs");var Ic=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 Ko(e){return Ic[e]}i(Ko,"userFacingError");function Ma(e,r,t){Object.defineProperty(e,r,{value:t,enumerable:false,writable:false,configurable:false});}i(Ma,"defineHidden");var Ac=/^[a-z][a-z0-9_]{0,63}$/;function z(e,r){let t=Hn(r?.wireCode,r?.wireEnvelope),o={code:e,category:qa(e),retryable:r?.retryable??La(e),displayMessage:Ko(e)};if(r?.httpStatus!==void 0&&(o.httpStatus=r.httpStatus),r?.requestId&&(o.requestId=r.requestId),typeof r?.reasonCode=="string"&&Ac.test(r.reasonCode)&&(o.reasonCode=r.reasonCode),t);return r?.wireMessage&&Ma(o,"wireMessage",r.wireMessage),r?.raw!==void 0&&r.raw!==null&&Ma(o,"raw",r.raw),Object.freeze(o)}i(z,"makeEverfurError");function we(e,r){return Object.freeze(r===void 0?{ok:true,value:e}:{ok:true,value:e,warning:r})}i(we,"ok");function Y(e){return Object.freeze({ok:false,error:e})}i(Y,"err");var Vn=class Vn extends Error{constructor(r,t){super(t),this.name="EverfurConfigError",this.kind=r,Object.setPrototypeOf(this,Vn.prototype);}};i(Vn,"EverfurConfigError");var cn=Vn;var Ha=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),$a=Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function qc(e){let r=Object.prototype.hasOwnProperty.call($a,e)?$a[e]:void 0;if(r!==void 0)return r;let t=e;return Ha.has(t)?t:"parsing"}i(qc,"normalizeStatus");function Va(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(Va,"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 lt(e){let r=Nc.safeParse(e);if(!r.success)return null;let t=r.data,o=Fc(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??qc(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:Ba(t.document_count,0),heldItemCount:Ba(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(lt,"mapRequestView");var Lc=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 Ga(e){let r=Lc.safeParse(e);if(!r.success)return null;let t=r.data,o=Qo(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(Ga,"mapRequestGroup");function Fc(e){return !e||e==="awaiting_upload"||e==="in_review"?null:Ha.has(e)?e:null}i(Fc,"normalizeSimpleStatus");function Qo(e){let r=Array.isArray(e)?e:[],t=[];for(let o of r){let n=lt(o);n!==null&&t.push(n);}return Object.freeze(t)}i(Qo,"mapRequestList");var zc=z$1.object({source_doc_id:z$1.string().min(1),request_id:z$1.string().min(1)});function Wa(e){let r=zc.safeParse(e);return r.success?Object.freeze({documentId:r.data.source_doc_id,requestId:r.data.request_id,status:"received"}):null}i(Wa,"mapUploadedDocument");var Mc=z$1.object({label:z$1.string(),value:z$1.string()}),Xo=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()}),$c=z$1.object({at:z$1.string(),value:z$1.number().nullish(),display:z$1.string().nullish(),origin:z$1.string().nullish()}),Uc=z$1.object({key:z$1.string(),label:z$1.string().optional(),points:z$1.array($c).optional()}),Bc=z$1.object({title:z$1.string(),detail:z$1.string().nullish(),due_at:z$1.string().nullish()}),Jo=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 Zo(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:Va(e.origin),canonicalKey:e.canonical_key??null})}i(Zo,"mapEntityRow");function ei(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(ei,"mapDocumentRow");var jc=z$1.object({identity:z$1.array(Mc).optional(),entities:z$1.array(Xo).optional(),entity_series:z$1.array(Uc).optional(),forward_looking:z$1.array(Bc).optional(),documents:z$1.array(Jo).optional()});function Ya(e,r){let t=Vc(r)?r:{},o=ja(t.schema_version,"epdf/1.0"),n=ja(t.disclaimer,""),l=typeof t.pet_ref=="string"&&t.pet_ref.length>0?t.pet_ref:e;if(t.withheld===true)return Ua(l,o,n);let a=jc.safeParse(t);if(!a.success)return Ua(l,o,n);let d=a.data,s=(d.identity??[]).map(y=>Object.freeze({label:y.label,value:y.value})),c=(d.entities??[]).map(Zo),u=(d.entity_series??[]).map(y=>Object.freeze({key:y.key,label:y.label??y.key,points:Object.freeze((y.points??[]).map(m=>Object.freeze({at:m.at,value:m.value??null,display:m.display??null,origin:Va(m.origin)})))})),p=(d.forward_looking??[]).map(y=>Object.freeze({title:y.title,detail:y.detail??null,dueAt:y.due_at??null})),f={};for(let y of d.documents??[])f[y.doc_id]=ei(y);let b=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:b,withheld:false,generatedAt:Gc(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(Ya,"mapRecordView");function Ua(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(Ua,"withheldView");var Hc=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 Gn(e,r){let t=Hc.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(Gn,"mapConsent");function Vc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Vc,"isObject");function Ba(e,r){return typeof e=="number"&&Number.isFinite(e)?e:r}i(Ba,"numberOr");function ja(e,r){return typeof e=="string"&&e.length>0?e:r}i(ja,"strOr");function Gc(e){return typeof e=="string"&&e.length>0?e:null}i(Gc,"strOrNull");var Ka=Object.freeze(["published","failed","revoked"]);function Mt(e){return Ka.includes(e)}i(Mt,"isTerminalStatus");function dt(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(dt,"recordsDenialReasonOf");var Wc="records_consent_required";function Yc(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(Yc,"recordsWireCodeOf");function Jr(e){return e===null||e.httpStatus!==409?false:Yc(e)===Wc}i(Jr,"isRecordsConsentRequired");var Kc=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Wn(e){return e!==Kc}i(Wn,"isUploadTransportAvailable");var Qa=Object.freeze({record(){}}),Br=25*1024*1024,Xa=64,un=128,or=128,ct="application/pdf",Ja=9e4;function es(e){return new ri(e)}i(es,"createRecordsController");var ti=class ti{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??Qa,this.newIdempotencyKey=r.newIdempotencyKey??eu(),this.timers=r.timers??Jc,this.uploadDeadlineMs=r.uploadDeadlineMs??Ja;}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=lt(t.value);return o===null?Y(Yn()):(this.observeRequest(o),we(o))}async getRequest(r){let t=await this.repository.getRequest(r);if(!t.ok)return this.onRequestError(t.error);let o=lt(t.value);return o===null?Y(Yn()):(this.observeRequest(o),we(o))}async listRequests(){let r=await this.repository.listRequests();if(!r.ok)return this.onRequestError(r.error);let t=Qo(r.value);for(let o of t)this.observeRequest(o);return we(t)}async uploadDocument(r){let{requestId:t,file:o}=r,n=Qc(o);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),Y(Za(`upload rejected: ${n}`));let l=await this.repository.initiateUpload(t,{content_type:ct,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}),Y(Za(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:Xc(d.error)??"corrupt"}),this.onRequestError(d.error);let s=Wa(d.value);return s===null?Y(Yn()):we(s)}async postToS3(r,t,o){let n=new AbortController,l=Zc(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 Y(Object.freeze({...z("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!o.ok){let l=dt(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}),Y(o.error)}let n=Ya(r,o.value);return n.petRef!==r?Y(Yn()):n.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:r}),this.recordCache.delete(r),we(n)):(this.recordCache.set(r,n),we(n))}peekCachedRecord(r){return this.recordCache.get(r)??null}async getConsent(r){let t=await this.repository.getConsent(r);return t.ok?we(Gn(r,t.value)):Y(t.error)}async grantConsent(r){let t=await this.repository.putConsent(r.petRef,{consent_version:r.consentVersion,idempotency_key:r.idempotencyKey});return t.ok?we(Gn(r.petRef,t.value)):(dt(t.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:r.petRef}),Y(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),we(Gn(r,t.value))):Y(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 dt(r)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),Y(r)}};i(ti,"RecordsControllerImpl");var ri=ti;function Qc(e){if(e.mimeType!==ct)return "unsupported_format";let r=e.sizeBytes;return typeof r!="number"||!Number.isFinite(r)||r<=0||r>Br?"oversize":null}i(Qc,"validateFile");function Xc(e){let r=e.wireMessage;return r==="unsupported_format"||r==="oversize"||r==="corrupt"?r:null}i(Xc,"reasonFromWire");function Za(e){return z("mediaUploadFailed",{retryable:false,wireMessage:e})}i(Za,"uploadFailed");function Yn(){return z("internalError",{retryable:true})}i(Yn,"internal");var Jc={setTimeout:i((e,r)=>setTimeout(e,r),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function Zc(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(Zc,"mergeSignals");function eu(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(eu,"defaultIdempotencyFactory");function Dr(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Dr,"assertNever");function rs(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(rs,"errorFrame");function nu(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(nu,"authHeaders");function pn(e,r){return {...e,headers:{...ou(e.headers),...nu(r)}}}i(pn,"withAuthHeaders");function ou(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(ou,"stripAuthHeaders");async function ts(e,r){if(r.mode==="anonymous")return r.transport.request(pn(e,{mode:"anonymous",publishableKey:r.publishableKey,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));let t;try{t=await r.identity.currentToken();}catch{return Y(ni())}let o=await r.transport.request(pn(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 Y(ni())}let l=await r.transport.request(pn(e,{mode:"personalized",token:n,userRef:r.userRef,...r.sessionId?{sessionId:r.sessionId}:{}}));return !l.ok&&l.error.httpStatus===401?Y(ni(l.error.httpStatus)):l}i(ts,"authedSend");function ni(e){return z("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(ni,"authRejectedError");function ns(e){return z("internalError",{retryable:true,wireMessage:iu(e)})}i(ns,"networkError");function iu(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(iu,"describeCause");var au=3e4,su=Yo*2,lu="idempotency-key",du=new Set(["POST","PUT","PATCH","DELETE"]),cu=Object.freeze({onEvent(){}}),uu=Object.freeze({setTimeout:i((e,r)=>setTimeout(e,r),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function pu(e){let r=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return r.length===0?null:`efs_${r}`.slice(0,128)}i(pu,"seededIdempotencyKey");function ut(e){let r=e.observer??cu,t=e.timers??uu,o=e.rng??Math.random,n=e.sleep??((f,b)=>wu(f,t,b)),l=e.maxAttempts??Fa,a=e.unaryTimeoutMs??au,d=e.newIdempotencyKey??Zr(),s=i(f=>{try{r.onEvent(f);}catch{}},"emit");async function c(f,b,y){let m=y?.maxAttempts,h=Math.max(1,m??l),v=y?.idempotent??du.has(b.method),E=y?.idempotencyKey===void 0?null:pu(y.idempotencyKey),g=v?E??d():null,R=mu(b,g),S=0;for(;;){let C=i(M=>Object.freeze({call:f,method:b.method,path:b.path,attempt:S,...g?{idempotencyKey:g}:{},...M}),"stamp");s(C({phase:"attempt"}));let k=xu(a,t),_=Su(k.signal,b.signal),T;try{T=await ts({...R,signal:_.signal},e.auth);}catch(M){T=Y(ns(M));}finally{_.dispose(),k.cancel();}if(T.ok)return s(C({phase:"settled",ok:true,reason:"ok"})),T;let I=T.error,F=yu(I,S,{maxAttempts:h,rng:o,now:t.now(),aborted:b.signal?.aborted===true,...m!==void 0?{perCallMaxAttempts:m}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),q={ok:false,code:I.code,reason:F.reason,...I.httpStatus!==void 0?{httpStatus:I.httpStatus}:{},...I.requestId!==void 0?{requestId:I.requestId}:{}};if(!F.retry)return s(C({phase:"settled",...q})),Y(I);if(s(C({phase:"retry",...q,delayMs:F.delayMs})),await n(F.delayMs,b.signal),b.signal?.aborted===true)return s(C({phase:"settled",...q,reason:"aborted"})),Y(I);S+=1;}}i(c,"send");async function u(f){return pn(f,await Eu(e.auth))}i(u,"authorize");async function*p(f,b,y){s(Object.freeze({call:f,phase:"stream.open",method:b.method,path:b.path,attempt:0}));try{yield*e.auth.transport.stream(b,y);}catch{yield rs({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(ut,"createRequestFunnel");function mu(e,r){let t={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==lu&&(t[o]=n);return r!==null&&(t["Idempotency-Key"]=r),{...e,headers:t}}i(mu,"assembleHeaders");function Zr(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(Zr,"defaultIdempotencyKeyFactory");var fu=10;function yu(e,r,t){if(t.aborted)return {retry:false,reason:"aborted"};let o=gu(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!Wo(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(fu,Math.floor(c)))},"policyCeiling"),d=t.perCallMaxAttempts??a()??t.maxAttempts;if(r+1>=d)return {retry:false,reason:"attempts-exhausted"};let s=bu(e,t.now);return s!==null?s>su?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:s}:{retry:true,reason:n,delayMs:za(r,t.rng)}}i(yu,"decideRetry");function gu(e){let r=e.code==="unknown"?Na(Cu(e.raw)):e.code;return r==="quotaExceeded"?"quota":r==="rateLimited"||e.httpStatus===429?"burst":null}i(gu,"throttleKind");function bu(e,r){let t=hu(e.raw);if(t!==null){let n=t-r;return n>0?n:0}let o=Ru(e.raw);return o===null?null:Math.round(o*1e3)}i(bu,"retryOverrideMs");function Ru(e){for(let r of oi(e)){let t=r.retry_after_seconds;if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return t}return null}i(Ru,"findRetryAfterSeconds");function hu(e){for(let r of oi(e)){let t=r.resets_at,o=vu(t);if(o!==null)return o}return null}i(hu,"findResetsAt");function oi(e){if(!os(e))return [];let r=[e];for(let t of ["error","detail"]){let o=e[t];os(o)&&r.push(o);}return r}i(oi,"candidateScopes");function vu(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(vu,"parseInstantMs");function Cu(e){for(let r of oi(e)){let t=r.code;if(typeof t=="string"&&t.length>0)return t}return null}i(Cu,"rawWireCode");function os(e){return typeof e=="object"&&e!==null}i(os,"isRecord");async function Eu(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(Eu,"resolveDeviceAuth");function xu(e,r){let t=new AbortController,o=r.setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>r.clearTimeout(o),"cancel")}}i(xu,"boundedSignal");function Su(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(Su,"mergeSignals");function wu(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(wu,"delayAbortable");function pt(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(pt,"hasLoneSurrogate");var et="/widget/v1/records";function as(e){let{auth:r}=e,t=r.mode,o=e.funnel??ut({auth:r,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=i(async(s,c,u)=>{let p=await o.send(s,c);return p.ok?p:Y(Pu(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`}):pt(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 b=[...c].length;return b>u?z("validationFailed",{retryable:false,wireMessage:`${s} is ${b} 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,un),a("pet_ref",s.pet_ref,or));return c?Promise.resolve(Y(c)):n("records.createRequest",ii(`${et}/requests`,s),"request")},"createRequest"),initiateUpload:i((s,c)=>{let u=l("request_id",s);return u?Promise.resolve(Y(u)):n("records.initiateUpload",ii(`${et}/requests/${encodeURIComponent(s)}/uploads/initiate`,c),"request")},"initiateUpload"),completeUpload:i((s,c)=>{let u=l("request_id",s);return u?Promise.resolve(Y(u)):n("records.completeUpload",ii(`${et}/requests/${encodeURIComponent(s)}/uploads/complete`,c),"request")},"completeUpload"),getRequest:i(s=>{let c=l("request_id",s);return c?Promise.resolve(Y(c)):n("records.getRequest",Kn(`${et}/requests/${encodeURIComponent(s)}`),"request")},"getRequest"),listRequests:i(async()=>{let s=await n("records.listRequests",Kn(`${et}/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,or);return c?Promise.resolve(Y(c)):n("records.getRecord",Kn(`${et}/pets/${encodeURIComponent(s)}/record`),"content")},"getRecord"),getConsent:i(s=>{let c=a("pet_ref",s,or);return c?Promise.resolve(Y(c)):n("records.getConsent",Kn(`${et}/pets/${encodeURIComponent(s)}/consent`),"consent")},"getConsent"),putConsent:i((s,c)=>{let u=d(a("consent_version",c.consent_version,Xa),a("idempotency_key",c.idempotency_key,un),a("pet_ref",s,or));return u?Promise.resolve(Y(u)):n("records.putConsent",Tu(`${et}/pets/${encodeURIComponent(s)}/consent`,c),"consent")},"putConsent"),deleteConsent:i(s=>{let c=a("pet_ref",s,or);return c?Promise.resolve(Y(c)):n("records.deleteConsent",Du(`${et}/pets/${encodeURIComponent(s)}/consent`),"consent")},"deleteConsent")}}i(as,"createHttpRecordsRepository");function is(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(is,"withReason");var ku="pet_not_registered";function _u(e){return e.httpStatus!==404?null:e.reasonCode===ku?"pet_not_found":"entitlement"}i(_u,"recordsErrorReasonFor");function Pu(e,r,t){let o=_u(e);return o!==null?is(e,o):e.code!=="accessDenied"?e:is(e,r==="anonymous"?"session_required":t==="content"?"consent_required":"entitlement")}i(Pu,"tagReason");function Kn(e){return {method:"GET",path:e}}i(Kn,"get");function ii(e,r){return {method:"POST",path:e,body:r}}i(ii,"post");function Tu(e,r){return {method:"PUT",path:e,body:r}}i(Tu,"put");function Du(e){return {method:"DELETE",path:e}}i(Du,"del");var ss=Symbol.for("@everfur/sdk#EverfurContext@v1"),ls=globalThis,ds=ls[ss]??(ls[ss]=createContext(null));ds.displayName??="EverfurContext";function ee(){let e=useContext(ds);if(e===null)throw new cn("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(ee,"useEverfurContext");var ai=new Map,si=new Set;function cs(e){ai.set(e,(ai.get(e)??0)+1);for(let r of [...si])r();}i(cs,"notifyRecordsConsentWithdrawn");function Nu(e){return ai.get(e)??0}i(Nu,"recordsConsentEpochOf");function Lu(e){return si.add(e),()=>{si.delete(e);}}i(Lu,"subscribe");function Qn(e){let r=useCallback(()=>Nu(e),[e]);return useSyncExternalStore(Lu,r,r)}i(Qn,"useRecordsConsentEpoch");var di={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[]},ps=4e3,zu=30;function Ge(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}=ee(),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,b]=useState({scope:d,value:di}),y=f.scope===d?f.value:di,m=useCallback(w=>{b(x=>x.scope===d?{scope:d,value:w(x.value)}:x);},[d]),h=useRef(0);useEffect(()=>(s.current=d,b({scope:d,value:di}),()=>{s.current=null,h.current+=1;}),[d]),useEffect(()=>{if(e.controller)return;let{services:w}=n.registry,x={record:i((D,G)=>w.telemetry.track(D,G),"record")},A=n.registry.acquire("records",`${l??""}|${r}${o?"|own-upload":""}`,()=>es({repository:as({auth:w.authFor(l),...w.errorPolicy?{errorPolicy:w.errorPolicy}:{}}),uploads:o?{postMultipart:i((D,G,de)=>(t.current??w.uploadTransport).postMultipart(D,G,de),"postMultipart")}:w.uploadTransport,telemetry:x}),()=>{});return u({scope:d,controller:A}),()=>{n.registry.release(A);}},[n,l,r,e.controller,a,d,o]);let v=useCallback(w=>{m(x=>({...x,...w}));},[m]),E=useCallback(async()=>{if(!p||s.current!==d)return;let w=h.current+=1;C.current=0,T(),v({loading:true,error:null,denialReason:null,withheld:false});let[x,A]=await Promise.all([p.getConsent(r),p.listRequests()]);if(w!==h.current)return;let D=x.ok?x.value:null,G=A.ok?A.value.filter(Ae=>Ae.petRef===r):[],de=A.ok?null:A.error;if(D&&D.granted){let Ae=await p.getRecord(r);if(w!==h.current)return;if(Ae.ok){v({consent:D,requests:G,record:Ae.value,withheld:Ae.value.withheld,error:Ae.value.withheld?Bu():de,denialReason:null,loading:false});return}v({consent:D,requests:G,record:null,error:Ae.error,denialReason:dt(Ae.error),withheld:false,loading:false});return}v({consent:D,requests:G,record:null,error:x.ok?de:x.error,denialReason:D?"consent_required":Uu(x),withheld:false,loading:false});},[p,r,v,d]);useEffect(()=>(E(),()=>{h.current+=1;}),[E]);let g=useMemo(()=>$u(y.requests),[y.requests]),R=g?.id??null,S=g?.status??null,C=useRef(0),k=useRef(null),[_,T]=useReducer(w=>w+1,0);useEffect(()=>{if(!p||R===null||S===null||Mt(S)||S==="in_review")return;k.current!==String(R)&&(k.current=String(R),C.current=0);let w=false,x=i(async()=>{if(w||C.current>=zu)return;C.current+=1;let D=await p.getRequest(R);if(!w){if(D.ok&&D.value.petRef===r){if(m(G=>({...G,requests:Jn(G.requests,D.value)})),Mt(D.value.status)){D.value.status==="published"&&E();return}if(D.value.status==="in_review")return}A=setTimeout(()=>{x();},ps);}},"tick"),A=setTimeout(()=>{x();},ps);return ()=>{w=true,clearTimeout(A);}},[p,R,S,E,_,r,m]);let I=useCallback(async w=>{if(!p||s.current!==d)return Zn();let x=await p.createUploadRequest({petRef:r,idempotencyKey:w});return s.current===d&&x.ok&&x.value.petRef===r&&m(A=>({...A,requests:Jn(A.requests,x.value)})),x},[p,r,d,m]),F=useCallback((w,x)=>{m(A=>({...A,uploadQueue:A.uploadQueue.map(D=>D.key===w?x(D):D)}));},[m]),q=useCallback(async(w,x)=>{let A=Date.now().toString(36),D=x.map((de,Ae)=>{let oe=ms(de);return {key:`${A}-${Ae}`,name:de.name??null,status:oe===null?"queued":"skipped",progress:0,skipReason:oe,error:null}}),G=[...D];if(!p||s.current!==d)return Object.freeze(G);m(de=>({...de,uploadQueue:D,isUploading:true,uploadProgress:0}));for(let[de,Ae]of x.entries()){let oe=D[de];if(oe.status==="skipped")continue;if(s.current!==d)break;F(oe.key,Ke=>({...Ke,status:"uploading",progress:0})),v({uploadProgress:0});let ve=await p.uploadDocument({requestId:w,file:Ae,onProgress:i(Ke=>{if(s.current!==d)return;let _r=Math.min(1,Math.max(0,Ke));F(oe.key,Pr=>({...Pr,progress:Math.max(Pr.progress,_r)})),v({uploadProgress:_r});},"onProgress")});if(s.current!==d)break;let ar=ve.ok?{...oe,status:"done",progress:1}:{...oe,status:"failed",error:ve.error};if(G[de]=ar,F(oe.key,()=>ar),ve.ok){let Ke=await p.getRequest(w);s.current===d&&Ke.ok&&Ke.value.petRef===r&&m(_r=>({..._r,requests:Jn(_r.requests,Ke.value)}));}}return s.current===d&&v({isUploading:false,uploadProgress:null}),Object.freeze(G)},[p,v,F,r,d,m]),M=useCallback(async(w,x)=>{if(!p||s.current!==d)return Zn();let A=`${Date.now().toString(36)}-0`;m(G=>({...G,isUploading:true,uploadProgress:0,uploadQueue:[{key:A,name:x.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let D=await p.uploadDocument({requestId:w,file:x,onProgress:i(G=>{s.current===d&&(v({uploadProgress:G}),F(A,de=>({...de,progress:Math.max(de.progress,Math.min(1,G))})));},"onProgress")});if(s.current!==d)return D;if(v({isUploading:false,uploadProgress:null}),F(A,G=>D.ok?{...G,status:"done",progress:1}:{...G,status:"failed",error:D.error}),D.ok){let G=await p.getRequest(w);s.current===d&&G.ok&&G.value.petRef===r&&m(de=>({...de,requests:Jn(de.requests,G.value)}));}return D},[p,v,F,r,d,m]),$=useCallback(async(w,x)=>{if(!p||s.current!==d)return Zn();let A=await p.grantConsent({petRef:r,consentVersion:w,idempotencyKey:x});return A.ok&&s.current===d&&E(),A},[p,r,E,d]),V=useCallback(async()=>{if(!p||s.current!==d)return Zn();let w=await p.revokeConsent(r);return w.ok&&cs(r),w.ok&&s.current===d&&(h.current+=1,v({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:w.value})),w},[p,r,v,d]),re=useCallback(()=>E(),[E]),Q=Mu(y,p!==null);return useMemo(()=>({status:Q,record:y.record,requests:y.requests,activeRequest:g,consent:y.consent,error:y.error,denialReason:y.denialReason,withheld:y.withheld,isUploading:y.isUploading,uploadProgress:y.uploadProgress,uploadQueue:y.uploadQueue,createRequest:I,uploadDocument:M,uploadDocuments:q,grantConsent:$,revokeConsent:V,refresh:re}),[Q,y,g,I,M,q,$,V,re])}i(Ge,"useEverfurRecords");function ms(e){if(e.mimeType!==ct)return "unsupported";let r=e.sizeBytes;return typeof r!="number"||!Number.isFinite(r)||r<=0||r>Br?"too_large":null}i(ms,"skipReasonFor");function fs(e){let r=[],t=[];for(let o of e){let n=ms(o);n===null?r.push(o):t.push({name:o.name??null,reason:n});}return {uploadable:r,skipped:t}}i(fs,"classifyPick");function Mu(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(Mu,"selectStatus");function $u(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($u,"newestRequest");function Jn(e,r){let t=e.filter(o=>o.id!==r.id);return [r,...t]}i(Jn,"replaceRequest");function Uu(e){return e.ok?"consent_required":dt(e.error)??"consent_required"}i(Uu,"consentDenial");function Bu(){return z("internalError",{retryable:false})}i(Bu,"withheldSentinel");function Zn(){return {ok:false,error:z("internalError",{retryable:true})}}i(Zn,"notReady");function ci(e){let r=globalThis.console;try{r?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(ci,"reportHostFailure");function ju(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(ju,"isThenable");function Hu(e,...r){if(typeof e=="function")try{let t=e(...r);return ju(t)&&Promise.resolve(t).then(void 0,ci),t}catch(t){ci(t);return}}i(Hu,"callHost");var ys=new WeakMap;function fn(e){if(typeof e!="function")return;let r=ys.get(e);if(r!==void 0)return r;let t=i((...o)=>{Hu(e,...o);},"guarded");return ys.set(e,t),t}i(fn,"guardHost");function _e(e,r){let t=null;for(let o of r){let n=e[o];typeof n=="function"&&(t??={...e},t[o]=fn(n));}return t??e}i(_e,"guardHostProps");function Et(e,...r){let t;try{t=e(...r);}catch(o){return ci(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(t).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(Et,"callHostAsync");var Vu="your pet";function Pe(e){let r=e?.trim()??"";return r.length>0?r:Vu}i(Pe,"petNameOr");var lr=Object.freeze({title:"Health records",openTimeline:"Open timeline",loading:"Loading health records",lead:i(e=>`${Pe(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")}),ui=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")}),rt=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")}),dr=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"}),$t=Object.freeze({title:i(e=>`${Pe(e)}\u2019s records request`,"title"),body:i(e=>`We\u2019re requesting ${Pe(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 ${Pe(e)}.`,"a11y"),openA11y:i((e,r)=>`Open ${Pe(e)}\u2019s records request. ${r}`,"openA11y"),ask:"Ask about this request",askA11y:"Ask Everfur about this records request"}),xt=Object.freeze({title:i(e=>`Add ${Pe(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 ${Pe(e)}\u2019s records from a clinic`,"requestFromClinicA11y"),uploadDocument:"Upload a document",uploadDocumentA11y:i(e=>`Upload one of ${Pe(e)}\u2019s records`,"uploadDocumentA11y")});var Se=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 ${Pe(e)}`,"requestsFor"),uploadPromptTitle:i(e=>`Do you already have ${Pe(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.",requestRecords:"Request records",requestTimeline:"Request timeline",requestTimelineA11y:i(e=>`Request timeline, ${e}`,"requestTimelineA11y"),ownerProvided:"Records you provided",askA11y:i(e=>`Ask Everfur about ${Pe(e)}'s medical records`,"askA11y")});function gs(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(gs,"buildRecordsPageAskPrompt");function eo(e){if(e.convertedToUploadAt)return Se.ownerProvided;let r=e.clinicName?.trim()??"";return r.length>0?r:Se.ownerProvided}i(eo,"consumerRequestSource");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 bs(e){return !Mt(e.status)}i(bs,"isRecordsInProgress");function ro(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(bs).sort((l,a)=>a.updatedAt.localeCompare(l.updatedAt))[0]??null}i(ro,"pickPetRecordsRequest");function pi(e){if(e.hasMarkers)return "published";let r=ro(e.requests,e.petRef);return r===null?"none":r.status==="published"||bs(r)?"in_progress":"none"}i(pi,"deriveRecordsDashboardState");function Gu(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i(Gu,"selectDashboardLoading");function mi(e){return Gu(e)?"loading":e.hasFullRecord?"record":e.markersError||e.recordError&&!e.hasMarkers?"error":e.dashboardState==="in_progress"&&e.drivingRequest!==null?"in_progress":e.dashboardState==="none"?"none":"labs_only"}i(mi,"selectDashboardView");function Qe(e){return e?.httpStatus===429?"rate_limited":e?.httpStatus===502?"service_unavailable":"error"}i(Qe,"recordsEmptyVariantForError");var Rs=Object.freeze({name:"dashboard"});function Ut(e=Rs){return Object.freeze({stack:Object.freeze([e])})}i(Ut,"initialRecordsNav");function to(e){return e.stack[e.stack.length-1]??Rs}i(to,"currentRecordsScreen");function fi(e,r){return Object.freeze({stack:Object.freeze([...e.stack,r])})}i(fi,"pushRecordsNav");function yi(e,r){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),r])})}i(yi,"replaceRecordsNav");function gi(e){return Ut(e)}i(gi,"resetRecordsNav");function no(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(no,"popRecordsNav");function hs(e,r){return r.name==="dashboard"?gi(r):to(e).name==="upload"&&r.name==="request"?yi(e,r):fi(e,r)}i(hs,"transitionRecordsNav");function yn(e,r){switch(r.type){case "push":return fi(e,r.screen);case "pop":return no(e).state;case "replace":return yi(e,r.screen);case "reset":return gi(r.screen);case "navigate":return hs(e,r.screen);default:return e}}i(yn,"recordsNavReducer");function Hr(e,r){return e??r?.version??""}i(Hr,"resolveConsentVersion");function tt(e,r){return Hr(e,r).length>0}i(tt,"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 oo(e){let r=e.clinicName?.trim()??"";return r.length>0?r:e.source==="owner_provided"?vs.ownerUpload:vs.clinicRequest}i(oo,"selectRequestTitle");var vs=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function bi(e){return `${e} ${W.beingReviewed}`}i(bi,"heldItemsLabel");function Ri(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(Ri,"selectRequestList");function gn(e){let r=e.actionNeededLabel?.trim()??"";return r.length>0?r:e.statusLabel}i(gn,"selectPrimaryLabel");function io(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(io,"selectClinicCall");function Cs(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(Cs,"selectRequestStatusTone");var Ci=class Ci 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(Ci,"HostRenderBoundary");var hi=Ci;function Yu({render:e}){return e()}i(Yu,"RenderHost");function vi({render:e,fallback:r,resetKey:t}){return createElement(hi,{fallback:r,resetKey:t,children:createElement(Yu,{render:e})})}i(vi,"HostRender");function Si(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let r of Object.keys(e))Si(e[r]);}return e}i(Si,"deepFreeze");var Ku=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Ss={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},ws={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},xs={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},Qu={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Xu={regular:"400",medium:"500",bold:"700"},Ju={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Zu=0,ao="System",so="monospace",ep=["content","heading","control","compact","badge"];function rp(e){let r={};for(let t of ep)r[t]=e;return r}i(rp,"authoredTierSizes");function ks(){return {family:ao,mono:so,fontUrl:null,families:{regular:ao,medium:ao,bold:ao,mono:so,monoMedium:so,monoBold:so},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:xs,tierSizes:rp(xs),lineHeight:Qu,weight:Xu,letterSpacing:Ju,scale:1,maxScale:Zu,scaleCaps:Ku}}i(ks,"baseType");var _s={},Ei=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function xi(e){return `cubic-bezier(${e.join(", ")})`}i(xi,"cssCubicBezier");var Ps={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:xi(Ei.standard),emphasized:xi(Ei.emphasized),exit:xi(Ei.exit)},reducedMotion:false},tp={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)"},Ts=Si({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:tp,space:Ss,radius:ws,type:ks(),motion:Ps,slots:_s}),np={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)"};Si({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:np,space:Ss,radius:ws,type:ks(),motion:Ps,slots:_s});var Ds=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Os=globalThis,wi=Os[Ds]??(Os[Ds]=createContext(Ts));wi.displayName??="EverfurThemeContext";function ce(){return useContext(wi)}i(ce,"useEverfurTheme");var Is=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});var As='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',ap="System";function sp(e){let r=e.trim();return r.length===0||r===ap?As:`${qs(r)}, ${As}`}i(sp,"cssFontFamily");function lp(e){let r=e.trim();return r.length===0||r==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${qs(r)}, ui-monospace, Menlo, Consolas, monospace`}i(lp,"cssMonoFamily");function qs(e){return `"${e.replace(/[\\"]/g,"\\$&")}"`}i(qs,"quote");function O(e,r){let t=e.type,o=t.families[r];return {fontFamily:r==="mono"||r==="monoMedium"||r==="monoBold"?lp(o):sp(o),fontWeight:t.namedFaces[r]?t.weight.regular:t.weight[Is[r]]}}i(O,"faceCss");var mt=Object.freeze({textAlign:"start"});var dp=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 cp(e){return dp[e]}i(cp,"requires");function Ns(e,r,t){let o=cp(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 ki({name:e,enabled:false,isPending:true,limits:{}});let l=up(o,n);return o.filter(d=>n.get(d)?.granted!==true).length===0?ki({name:e,enabled:true,isPending:false,limits:l}):ki({name:e,enabled:false,isPending:false,limits:l,disabled:pp(o,n)})}i(Ns,"decideCapability");function up(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(up,"mergeLimits");function pp(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:Ko("accessDenied"),level:"user_entitlement",recoverable:false})}i(pp,"disabledFor");function ki(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(ki,"freezeDecision");function St(e){let{runtime:r}=ee(),t=r.entitlements,o=useSyncExternalStore(t.subscribe,t.getSnapshot,t.getSnapshot);return useMemo(()=>Ns(e,o.decisions,{isPending:o.isPending}),[e,o])}i(St,"useCapability");var yp=48;function gp(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(gp,"selectView");function Te(e){let{capability:r,children:t,renderDisabled:o,renderPending:n,style:l,className:a}=e,d=St(r),s=useMemo(()=>gp(d),[d]);switch(s){case "enabled":return t;case "pending":return n?jsx(vi,{render:n,fallback:jsx(Ls,{capability:r,style:l,className:a})}):jsx(Ls,{capability:r,style:l,className:a});case "disabled":return o?jsx(vi,{render:()=>o(d),fallback:jsx(Fs,{decision:d,style:l,className:a}),resetKey:d}):jsx(Fs,{decision:d,style:l,className:a});default:return Dr(s)}}i(Te,"CapabilityGate");function Ls({capability:e,style:r,className:t}){let o=ce(),n=useMemo(()=>zs(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(Ls,"PendingSkeleton");function Fs({decision:e,style:r,className:t}){let o=ce(),n=useMemo(()=>zs(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(Fs,"OffState");function zs(e){let{color:r,space:t,radius:o,type:n}=e;return {offstate:{...mt,boxSizing:"border-box",minHeight:yp,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,...O(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(zs,"makeStyles");var lo=2;function Ms(e){return typeof e!="number"||!Number.isInteger(e)?lo:e<1?1:e>6?6:e}i(Ms,"headingLevel");function Pi(e){return e>=6?6:e+1}i(Pi,"nextHeadingLevel");function co(e){return `h${String(e)}`}i(co,"headingTag");var Rp=Pi(lo);createContext(Rp);var Ti=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 De(e){let r=ce(),t=useMemo(()=>vp(r),[r]);return jsxs("div",{role:"note",className:e.className,style:{...t.container,...e.style},children:[jsx("p",{style:t.title,children:Ti.title}),jsx("p",{style:t.body,children:Ti.body})]})}i(De,"ClinicalDisclaimer");function vp(e){let{color:r,space:t,type:o}=e,n=`${Math.round(o.size.caption*o.lineHeight.snug)}px`;return {container:{...mt,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,...O(e,"bold"),fontSize:o.size.caption,lineHeight:n,color:r.text.secondary,letterSpacing:o.letterSpacing.eyebrow},body:{margin:0,...O(e,"regular"),fontSize:o.size.caption,lineHeight:n,color:r.text.muted}}}i(vp,"makeStyles");var X=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"}),Us=100;var xe=Object.freeze({title:X.title,placeholder:X.placeholder,searchA11y:X.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:X.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 Bs(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(Bs,"clinicEmailStatusBadge");function js(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} km`}i(js,"formatClinicDistanceLabel");function Hs(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} ${e===1?"kilometer":"kilometers"} away`}i(Hs,"formatClinicDistanceForA11y");var Vs=300,Di=2;var ue=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 Ep(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(Ep,"fallbackFailureTitle");function Gs(e){let r=e.failureReason?.trim()??"";return r.length>0?r:Ep(e)}i(Gs,"failureTitle");var xp=1440*60*1e3;function Oi(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/xp)}i(Oi,"requestElapsedDays");var Sp=7;function Ws(e,r){return e.wireStatus!=="awaiting_response"?false:Oi(e,r)>=Sp}i(Ws,"requestWaitingTooLong");function Ii(e){return e.status==="failed"}i(Ii,"isTerminalFailure");function Ys(e){return Ii(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i(Ys,"shouldOfferRecovery");function Xs(e,r){let[t,o]=useState(""),[n,l]=useState(""),[a,d]=useState([]),[s,c]=useState(null),[u,p]=useState([]),[f,b]=useState(true),[y,m]=useState(false),[h,v]=useState(false),[E,g]=useState(null),[R,S]=useState(null),[C,k]=useState(0),_=useRef(0),T=useRef(true),I=r?.latitude,F=r?.longitude,q=useMemo(()=>I!==void 0&&F!==void 0?{latitude:I,longitude:F}:void 0,[I,F]);useEffect(()=>(T.current=true,()=>{T.current=false,_.current+=1;}),[e]),useEffect(()=>{let Q=true;return b(true),e.recentClinics({limit:5}).then(w=>{Q&&(w.ok&&p(w.value.clinics),b(false));}).catch(()=>{Q&&b(false);}),()=>{Q=false;}},[e]),useEffect(()=>{let Q=t.trim();if(Q.length<Di){l("");return}let w=setTimeout(()=>l(Q),Vs);return ()=>clearTimeout(w)},[t]);let M=n.length>=Di;useEffect(()=>{let Q=_.current+=1;if(d([]),c(null),g(null),S(null),!M){m(false);return}m(true),e.searchClinics({query:n,limit:25,...q?{location:q}:{}}).then(w=>{!T.current||Q!==_.current||(w.ok?(d(w.value.clinics),c(w.value.nextCursor)):g(w.error),m(false));}).catch(()=>{T.current&&Q===_.current&&m(false);});},[e,n,M,q,C]);let $=useCallback(()=>{if(!M||s===null||h)return;let Q=_.current;v(true),S(null),e.searchClinics({query:n,limit:25,cursor:s,...q?{location:q}:{}}).then(w=>{!T.current||Q!==_.current||(w.ok?(d(x=>[...x,...w.value.clinics]),c(w.value.nextCursor)):S(w.error),v(false));}).catch(()=>{T.current&&Q===_.current&&v(false);});},[e,s,n,M,h,q]),V=useCallback(Q=>o(Q),[]),re=useCallback(()=>k(Q=>Q+1),[]);return useMemo(()=>({query:t,debouncedQuery:n,isSearchActive:M,clinics:a,recent:u,recentLoading:f,initialLoading:y,loadingMore:h,hasNextPage:s!==null,error:E,pageError:R,setQuery:V,loadMore:$,retry:re}),[t,n,M,a,u,f,y,h,s,E,R,V,$,re])}i(Xs,"useClinicPicker");function qi(e,r,t,o){return Object.freeze({key:e?.id??`free:${r??""}`,clinic:e,freeText:r,email:t,idempotencyKey:o})}i(qi,"clinicDraftFor");var Bt=10,po=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),bn=i((e,r=1)=>z$1.string().refine(t=>!pt(t)&&[...t].length>=r&&[...t].length<=e),"text"),Zs=i(e=>[...e].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===127),"hasControl"),wp=z$1.object({clinicId:po.optional(),clinicFreeText:bn(200).refine(e=>e.trim().length>0).optional(),clinicEmail:bn(320,3).refine(e=>!Zs(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:po.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)),kp=z$1.object({petRef:bn(128),ownerName:bn(200).refine(e=>e.trim().length>0&&!Zs(e)),authorizationVersion:bn(64),clinics:z$1.array(wp).min(1).max(Bt)}).strict(),_p=z$1.object({request_group_id:po,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:po.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 el(e){let r=e.funnel??ut({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(t){if(!kp.safeParse(t).success)return Y(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=_p.safeParse(o.value);if(!n.success||n.data.pet_ref!==t.petRef)return Js();let l=[];for(let a of n.data.results){let d=a.request===void 0||a.request===null?null:lt(a.request);if(a.created!==(d!==null))return Js();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 we(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(el,"createRecordsClinicBatchClient");function Js(){return Y(z("internalError",{retryable:false}))}i(Js,"malformed");var rl=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),Pp=z$1.object({clinics:z$1.array(z$1.object({clinic_id:rl,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()}),Tp=z$1.object({authorization_version:z$1.string().min(1),scope_template:z$1.string().min(1),authorization_template:z$1.string().min(1)}),Dp=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 tl(e){let{repository:r}=e,t=i(async n=>{let l=await n;if(!l.ok)return l;let a=lt(l.value);return a===null?wt():we(a)},"request"),o=i(async n=>{let l=await n;if(!l.ok)return l;let a=Pp.safeParse(l.value);return a.success?we(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})):wt()},"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=Ga(l.value);return a===null?wt():we(a)},async getAuthorizationCopy(){let n=await r.getAuthorizationCopy();if(!n.ok)return n;let l=Tp.safeParse(n.value);return l.success?we(Object.freeze({authorizationVersion:l.data.authorization_version,scopeTemplate:l.data.scope_template,authorizationTemplate:l.data.authorization_template})):wt()},async createClinicRequest(n){let l=await t(r.createClinicRequest(n));return l.ok&&l.value.petRef!==n.petRef?wt():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=Dp.safeParse(l.value);return a.success?we(Object.freeze({uploadId:a.data.upload_id,uploadUrl:a.data.upload_url,uploadFields:Object.freeze(a.data.upload_fields)})):wt()},async completeSignatureUpload(n){let l=await r.completeSignatureUpload(n);if(!l.ok)return l;let a=z$1.object({signature_id:rl}).safeParse(l.value);return a.success?we(a.data.signature_id):wt()}}}i(tl,"createRecordsClinicController");function wt(){return Y(z("internalError",{retryable:false}))}i(wt,"malformed");var ft="/widget/v1/records",nl=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),gt=i((e,r=1)=>z$1.string().refine(t=>!pt(t)&&[...t].length>=r&&[...t].length<=e),"text"),il=i(e=>[...e].some(r=>r.charCodeAt(0)<32||r.charCodeAt(0)===127),"hasControl"),al=gt(320,3).refine(e=>!il(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),ol=gt(64),Op=z$1.object({limit:z$1.number().int().min(1).max(25).optional()}).strict(),Ip=z$1.object({query:gt(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:gt(512,0).optional()}).strict(),Ap=z$1.object({petRef:gt(128),ownerName:gt(200).refine(e=>e.trim().length>0&&!il(e)),authorizationVersion:gt(64),clinicId:nl.optional(),clinicFreeText:gt(200).refine(e=>e.trim().length>0).optional(),clinicEmail:al.optional(),signatureId:nl.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 sl(e){let r=e.funnel??ut({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)=>ol.safeParse(n).success?t(l,{method:"POST",path:`${ft}/requests/${encodeURIComponent(n)}/${l}`,...a?{body:a}:{}}):yt(),"recover");return {searchClinics(n){return Ip.safeParse(n).success?t("search",{method:"GET",path:`${ft}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):yt()},recentClinics(n){return Op.safeParse(n).success?t("recent",{method:"GET",path:`${ft}/clinics/recent`,query:{limit:n.limit}}):yt()},getRequestGroup(n){return ol.safeParse(n).success?t("requestGroup",{method:"GET",path:`${ft}/request-groups/${encodeURIComponent(n)}`}):yt()},getAuthorizationCopy:i(()=>t("authorizationCopy",{method:"GET",path:`${ft}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return Ap.safeParse(n).success?t("create",{method:"POST",path:`${ft}/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):yt()},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 al.safeParse(l).success?o(n,"clinic-email",{clinic_email:l}):yt()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?yt():t("signatureInitiate",{method:"POST",path:`${ft}/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:`${ft}/signatures/complete`,body:{upload_id:n}}):yt()}}}i(sl,"createHttpRecordsClinicRepository");function yt(){return Promise.resolve(Y(z("validationFailed",{retryable:false})))}i(yt,"invalid");function Ir(){let{runtime:e,userRef:r,scopeEpoch:t}=ee(),o=useMemo(()=>{let{services:l}=e.registry;return tl({repository:sl({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 Y(z("accessDenied"));let d=await a();return n.current===o?d:Y(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(Ir,"useEverfurRecordsClinic");function Ni(){let{runtime:e,userRef:r,scopeEpoch:t}=ee(),o=useMemo(()=>{let{services:l}=e.registry;return el({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 Y(z("accessDenied"));let a=await o.createClinicRequestBatch(l);return n.current===o?a:Y(z("accessDenied"))}}),[o,r])}i(Ni,"useEverfurRecordsClinicBatch");var qp=120,Np=44;function Lp({reason:e,onExit:r,exitLabel:t,style:o,className:n}){let{color:l,space:a,radius:d,type:s}=ce();return jsxs("div",{className:n,"data-testid":"records-gate-off",style:{boxSizing:"border-box",minHeight:qp,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:Np,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(Lp,"RecordsGateOffState");function Oe(e,r){return e===void 0?{}:{renderDisabled:i(t=>jsx(Lp,{reason:t.disabled?.reason??"",onExit:e,exitLabel:r}),"renderDisabled")}}i(Oe,"recordsGateExit");function zp(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(zp,"slotBox");function Wr(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(Wr,"slotText");function Ar(e,r){let t=zp(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(Ar,"slotBoxCss");var Rn="data-ef-screen-heading";function ul(e){return e.focus(),document.activeElement===e}i(ul,"focusTook");function $p(e){let r=e.querySelector(`[${Rn}]`);if(r!==null&&(r.textContent??"").trim().length>0&&ul(r)||ul(e))return;let t=e.firstElementChild;t instanceof HTMLElement&&(t.hasAttribute("tabindex")||(t.setAttribute("tabindex","-1"),t.style.outline="none"),t.focus());}i($p,"focusScreen");function jt(e){let r=useRef(null),t=useRef(e);return useEffect(()=>{if(Object.is(t.current,e))return;t.current=e;let o=r.current;o!==null&&$p(o);},[e]),r}i(jt,"useFocusScreenOnChange");var Bp=120,hn=44,Le="Back";function j(){let e=ce(),r=useMemo(()=>jp(e),[e]);return {theme:e,styles:r}}i(j,"useScreenStyles");function He({title:e,onBack:r,right:t,testID:o,variant:n="brand"}){let{styles:l}=j();return jsxs("header",{style:l.headerRow,"data-testid":o,children:[r?jsx("button",{type:"button",onClick:r,"aria-label":Le,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",{tabIndex:-1,[Rn]:"",style:n==="document"?l.documentTitle:l.headerTitle,children:e}),jsx("div",{style:l.headerRight,children:t??jsx("span",{style:l.iconButton})})]})}i(He,"ScreenHeader");function bt({disclaimer:e,style:r}){let{styles:t}=j();return e.trim().length===0?null:jsxs("p",{role:"note","aria-label":lr.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(bt,"DisclaimerBand");function B({label:e,onClick:r,kind:t="primary",disabled:o=false,busy:n=false,ariaLabel:l,ariaDescribedBy:a,testID:d,style:s}){let{styles:c}=j(),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(B,"Pill");function cr({label:e,tone:r="neutral",testID:t}){let{styles:o}=j();return jsx("span",{style:{...o.chip,...o.chipTones[r]},"data-testid":t,children:e})}i(cr,"Chip");function qr({title:e,count:r}){let{styles:t}=j();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(qr,"SectionHeader");function Fi({name:e,color:r}){return jsx("svg",{"aria-hidden":"true",focusable:"false",width:18,height:18,viewBox:"0 0 24 24",fill:"none",stroke:r,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block",flexShrink:0},"data-glyph":e,children:e==="send"?jsxs(Fragment,{children:[jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}):jsxs(Fragment,{children:[jsx("circle",{cx:"18",cy:"5",r:"3"}),jsx("circle",{cx:"6",cy:"12",r:"3"}),jsx("circle",{cx:"18",cy:"19",r:"3"}),jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]})})}i(Fi,"HeaderGlyph");function kt({direction:e="right"}){let{styles:r}=j(),t=e==="right"?"45deg":e==="down"?"135deg":"-45deg";return jsx("span",{"aria-hidden":"true",style:{...r.chevron,transform:`rotate(${t})`}})}i(kt,"Chevron");function jp(e){let{color:r,space:t,radius:o,type:n,slots:l}=e,a=i((b,y)=>`${Math.round(b*y)}px`,"lh"),d=i((b,y,m,h="regular")=>({margin:0,...O(e,h),fontSize:b,lineHeight:a(b,y),color:m}),"text"),s=Wr(l.recordCard),c=`1px solid ${r.brandBorder}`,u=e.brightness==="dark"?r.errorRed:r.danger,p=i((b,y)=>({backgroundColor:b,color:y}),"tone"),f={boxSizing:"border-box",minHeight:hn,minWidth:hn,padding:`${t.md}px ${t.lg+t.xs/2}px`,borderRadius:o.pill,...O(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:{...mt,boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:Bp,height:"100%",backgroundColor:r.background,color:r.text.primary,...O(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:hn,height:hn,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",...Ar(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,...Ar(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`,...O(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,...Ar(l.primaryButton),...Wr(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",...O(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:hn,padding:`${t.sm}px ${t.md}px`,border:`1px solid ${r.borderHairlineGreen}`,borderRadius:o.sm,color:r.text.primary,backgroundColor:r.surface,...O(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:O(e,"mono"),plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},dialogFrame:{boxSizing:"border-box",position:"fixed",top:0,right:0,bottom:0,left:0,width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",margin:0,padding:0,border:0,backgroundColor:"transparent",overflow:"hidden"},dialogScrim:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",padding:t.lg,backgroundColor:"rgba(0,0,0,0.4)"},dialogScrimSide:{boxSizing:"border-box",display:"flex",alignItems:"stretch",justifyContent:"flex-end",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.4)"},dialogPanel:{boxSizing:"border-box",width:"100%",maxWidth:560,maxHeight:"100%",overflowY:"auto",backgroundColor:r.surface,borderRadius:o.xl-1,padding:`${t.lg}px ${t.lg+t.xs+t.xs/2}px`,display:"flex",flexDirection:"column",gap:t.md,...O(e,"regular"),color:r.text.primary},dialogPanelSide:{boxSizing:"border-box",width:"min(100vw, 480px)",height:"100%",maxHeight:"100%",overflowY:"auto",backgroundColor:r.surface,padding:`${t.lg}px ${t.lg+t.xs+t.xs/2}px`,display:"flex",flexDirection:"column",gap:t.md,...O(e,"regular"),color:r.text.primary},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(jp,"makeScreenStyles");function Ht(e,r){return e===null?"":r?`${e} ${r}`:e}i(Ht,"formatEntityValue");function zi(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(zi,"formatShortDate");var ml=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function J(e){if(!e)return "-";let r=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(r!==null){let n=ml[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 `${ml[o.getUTCMonth()]} ${o.getUTCDate()}, ${o.getUTCFullYear()}`}i(J,"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 Yr(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(Yr,"markerStatusLabel");function Vt(e,r){return r<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${r} visits`}i(Vt,"trajectoryLabel");function Kr(e){let r=e.replace(/_/g," ").trim();return r.length===0?e:r.charAt(0).toUpperCase()+r.slice(1)}i(Kr,"humanize");var fl=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 Gt(e){return Object.prototype.hasOwnProperty.call(fl,e)?fl[e]:Kr(e)}i(Gt,"bodySystemLabel");var yl=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 Wt(e){return Object.prototype.hasOwnProperty.call(yl,e)?yl[e]:Kr(e)}i(Wt,"soapSectionLabel");function gl(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(gl,"formatWeightKg");function ur(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(ur,"formatMarkerReading");function Mi(e,r,t){let o=Vt(r,t);return e?`${me.measured(J(e))}${o?` \xB7 ${o}`:""}`:o}i(Mi,"labDetailLine");var fo=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"})}),$i=60;function bl(e){return `Try again in ${e}s`}i(bl,"coolingActionLabel");var Rl="Try again, available shortly";var se=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.",shareMessage:i(e=>`View this medical record: ${e}`,"shareMessage"),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.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",turnedOff:"Link turned off."})});function Hp(e,r){if(!e)return false;let t=Date.parse(e);return Number.isNaN(t)?false:t<=r}i(Hp,"isShareExpired");function Vp(e,r){let t=J(e);return t==="-"?r?"Expired":"No expiry date":r?`Expired ${t}`:`Expires ${t}`}i(Vp,"formatShareExpiry");function hl(e,r,t){let o=e.map(n=>{let l=Hp(n.expiresAt,t),a=Vp(n.expiresAt,l),d=J(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(hl,"buildShareRows");function _t(e,r){let t=e?.httpStatus;if(Jr(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(_t,"shareErrorMessage");function fe({width:e,height:r,radius:t,style:o}){let{color:n,radius:l}=ce();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 Ui=180,Cl=44,Bi=62;function Yt({testID:e}){let r=Kt(),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":lr.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:Ui,height:Ui,radius:Ui/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:Cl,radius:12})}),jsxs("div",{style:{...r.inset,...r.actions},children:[t("a"),t("b")]})]})}i(Yt,"DashboardSkeleton");function yo({testID:e}){let r=Kt();return jsxs("div",{role:"progressbar","aria-label":ue.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(yo,"RequestSkeleton");function El({testID:e}){let r=Kt();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:Cl,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(El,"TimelineSkeleton");function xl({testID:e}){let r=Kt();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(xl,"ClinicsSkeleton");function Sl({testID:e}){let r=Kt();return jsx("div",{role:"progressbar","aria-label":se.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(Sl,"SharesSkeleton");function Fe({variant:e,onAction:r,message:t,testID:o}){let n=Kt(),l=fo[e],[a,d]=useState(e==="rate_limited"?$i:0);useEffect(()=>{e==="rate_limited"&&d($i);},[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?bl(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?Rl:c,style:{...n.emptyAction,...s?n.emptyActionDisabled:{}},"data-testid":o?`${o}-action`:`records-empty-${e}-action`,children:c}):null]})}i(Fe,"RecordsEmptyState");function Kt(){let e=ce();return useMemo(()=>Yp(e),[e])}i(Kt,"useStyles");function Yp(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:Bi},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,...O(e,"bold"),fontSize:n.size.subtitle,lineHeight:`${Math.round(n.size.subtitle*n.lineHeight.snug)-1}px`,color:r.brand},emptyBody:{margin:0,...O(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",...O(e,"bold"),fontSize:n.size.bodyTight},emptyActionDisabled:{opacity:.5,cursor:"default"}}}i(Yp,"makeStyles");var Xp=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Cn(e){let{userRef:r,scopeEpoch:t}=ee();return jsx(Te,{capability:"recordsClinic",style:e.style,className:e.className,...Oe(e.onBack,Le),children:r===null?jsx("p",{role:"alert",children:W.sessionRequired}):jsx(Jp,{..._e(e,["onNavigate","onBack"])},JSON.stringify([r,t,e.petRef]))})}i(Cn,"EverfurClinicPicker");function Jp({petRef:e,controller:r,recordsController:t,location:o,onNavigate:n,onBack:l,style:a,className:d}){let{theme:s,styles:c}=j(),u=Ir(),p=Xs(r??u,o),f=Ge(t?{petRef:e,controller:t}:{petRef:e}),b=useRef(Zr()),[y,m]=useState(false),[h,v]=useState(null),[E,g]=useState(false),[R,S]=useState(""),[C,k]=useState(false),[_,T]=useState(""),[I,F]=useState(false),q=useCallback(D=>{n?.({name:"consent",clinic:qi(D,null,"",b.current())});},[n]),M=i(()=>{y||(m(true),v(null),f.createRequest(`records-upload-${Date.now().toString(36)}`).then(D=>{if(m(false),!D.ok){v(ue.errors.start);return}n?.({name:"request",requestId:D.value.id});}));},"startUpload"),$=C?R:p.query,V=Xp.test(_.trim()),re=$.trim().length>0&&V,Q=p.isSearchActive?p.clinics:p.recent,w=p.isSearchActive?p.error?Qe(p.error):!p.initialLoading&&p.clinics.length===0?"idle":null:p.recent.length>0||p.recentLoading?null:"idle",x={display:"flex",flexDirection:"column",gap:s.space.sm},A=i(D=>{let G=D.currentTarget;G.scrollTop+G.clientHeight>=G.scrollHeight-G.clientHeight*.6&&p.loadMore();},"onScroll");return jsxs("div",{className:d,style:{...c.root,...a},"data-testid":"records-clinic-picker",children:[jsx(He,{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:D=>p.setQuery(D.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:{...x,padding:`0 ${s.space.lg}px ${s.space.md}px`},children:[h?jsx("p",{role:"alert",style:c.errorBanner,children:h}):null,jsx(B,{label:y?xe.uploadOwnStarting:xe.uploadOwn,kind:"outline",ariaLabel:xe.uploadOwnA11y,busy:y,onClick:M,testID:"records-clinic-upload-own"})]}):null,jsxs("div",{style:{...c.body,...c.content,gap:s.space.md},onScroll:p.isSearchActive?A: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:()=>g(D=>!D),"aria-expanded":E,"aria-label":E?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,...O(s,"bold")},children:xe.fallback.title}),jsx("span",{style:c.muted,children:xe.fallback.subtitle})]}),jsx(kt,{direction:E?"up":"down"})]}),E?jsxs("div",{style:x,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:$,onChange:D=>{S(D.target.value),k(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:_,onChange:D=>{T(D.target.value),F(false);},onBlur:()=>F(true),placeholder:xe.fallback.emailPlaceholder,maxLength:320,autoComplete:"off","data-testid":"records-clinic-fallback-email"}),I&&_.trim().length>0&&!V?jsx("p",{role:"alert",style:c.errorText,children:ue.errors.invalidEmail}):null,jsx("p",{style:c.muted,children:xe.fallback.reviewNote}),jsx(B,{label:xe.fallback.submit,ariaLabel:xe.fallback.submitA11y,disabled:!re||!n,onClick:()=>n?.({name:"consent",clinic:qi(null,$.trim(),_.trim().toLowerCase(),b.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):p.recent.length>0?jsx("h3",{style:{...c.fieldLabel,...O(s,"bold"),textTransform:"uppercase",marginBottom:0},"data-testid":"records-clinic-recent-label",children:xe.recentlyUsed}):null,p.isSearchActive&&p.initialLoading?jsx(xl,{testID:"records-clinic-page-loading"}):null,jsx("ul",{style:{...c.plainList,gap:s.space.md},children:Q.map(D=>{let G=Bs(D.emailStatus),de=js(D.distanceKm),Ae=[D.name,D.address,D.phone?`phone ${D.phone}`:null,de?Hs(D.distanceKm):null,G.a11y].filter(Boolean).join(", "),oe=G.tone==="positive"?{backgroundColor:s.color.badgeBgPositive,color:s.color.success}:G.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:()=>q(D),"aria-label":xe.selectA11y(Ae),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-${D.id}`,children:[jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.space.sm},children:[jsx("span",{style:{...c.rowTitle,...O(s,"bold"),color:s.color.brand},children:D.name}),de?jsx("span",{"aria-hidden":"true",style:{...c.muted,...c.mono},children:de}):null]}),D.address?jsx("span",{style:c.rowDetail,children:D.address}):null,D.phone?jsx("span",{"aria-hidden":"true",style:c.rowMuted,children:D.phone}):null,jsx("span",{"aria-hidden":"true",style:{...c.chip,...oe,...O(s,"bold"),fontSize:s.type.size.micro,alignSelf:"flex-start"},children:G.label})]})},D.id)})}),w&&!p.initialLoading?jsx(Fe,{variant:w,message:p.isSearchActive&&w==="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:x,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(De,{})]})}i(Jp,"PickerBody");var ze=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${Bt} 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 En(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(En,"renderClinicScope");function xn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(xn,"clinicNeedsEmail");function wl(e,r,t){let[o,n]=useState(e.ownerName),[l,a]=useState(""),[d,s]=useState(null),[c,u]=useState(""),[p,f]=useState([]),[b,y]=useState([]),[m,h]=useState(null),[v,E]=useState(null),[g,R]=useState(false),[S,C]=useState(false),[k,_]=useState(null),[T,I]=useState(0),F=useRef(false),q=useRef(false),M=useRef(0),$=useRef(Zr()),V=useRef(null),re=useRef(null),Q=useRef(0);useEffect(()=>(F.current=true,q.current=false,R(false),()=>{F.current=false,Q.current+=1,M.current+=1,V.current=null,re.current?.abort();}),[r]),useEffect(()=>{let oe=true;return h(null),V.current=null,r.getAuthorizationCopy().then(ve=>{oe&&(ve.ok?(h(ve.value),E(null)):E(ve.error));}).catch(()=>{oe&&E(z("internalError"));}),()=>{oe=false;}},[r,T]),useEffect(()=>{let oe=true;return y([]),r.recentClinics({limit:5}).then(ve=>{oe&&ve.ok&&y(ve.value.clinics);}).catch(()=>{}),()=>{oe=false;}},[r]);let w=i(()=>{V.current=null,E(null);},"invalidate"),x=d?.name??l.trim(),A=m?En(m,o.trim(),e.petName,x):null,D=xn(d),G=!!(m&&A&&o.trim()&&e.petName.trim()&&x&&(!D||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(c.trim()))&&t),de=i(async()=>{if(q.current)return;let oe=++M.current;C(true);try{let ve=await r.searchClinics({query:l.trim(),limit:100});if(!F.current||oe!==M.current)return;ve.ok?(f(ve.value.clinics),E(null)):E(ve.error);}catch{F.current&&oe===M.current&&E(z("internalError"));}finally{F.current&&oe===M.current&&C(false);}},"search"),Ae=i(async()=>{if(q.current||k||!G||!m||!A||!t)return;q.current=true;let oe=Q.current,ve=i(()=>F.current&&Q.current===oe,"current");R(true),E(null);try{if(!V.current){re.current=new AbortController;let Ke=await t({petRef:e.petRef,petName:e.petName,ownerName:o.trim(),clinicName:x,authorizationVersion:m.authorizationVersion,scopeText:A,signal:re.current.signal});if(!ve()||Ke===null)return;let _r=d&&(!D||d.emailStatus==="none")?{clinicId:d.id}:{clinicFreeText:x};V.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:m.authorizationVersion,..._r,...D?{clinicEmail:c.trim().toLowerCase()}:{},...Ke.signatureId!==void 0?{signatureId:Ke.signatureId}:{signaturePngBase64:Ke.signaturePngBase64},idempotencyKey:$.current()};}if(!ve())return;let ar=await r.createClinicRequest(V.current);if(!ve())return;if(!ar.ok){E(ar.error);return}if(ar.value.petRef!==e.petRef){E(z("internalError"));return}_(ar.value),V.current=null,e.onCreated?.(ar.value);}catch{ve()&&E(z("internalError"));}finally{q.current=false,ve()&&R(false);}},"submit");return {ownerName:o,query:l,clinic:d,email:c,clinics:p,copy:m,scope:A,error:v,busy:g,searching:S,created:k,ready:G,needsEmail:D,recent:p.length===0&&d===null?b:[],setOwnerName(oe){q.current||(w(),n(oe));},setQuery(oe){q.current||(w(),M.current+=1,C(false),f([]),s(null),u(""),a(oe));},setEmail(oe){q.current||(w(),u(oe));},selectClinic(oe){q.current||(w(),M.current+=1,C(false),f([]),s(oe),a(oe.name),u(""));},invalidate:w,search:de,submit:Ae,retryCopy(){E(null),I(oe=>oe+1);}}}i(wl,"useClinicRequestForm");var Zp=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Xt(e){return e.clinic?.name??e.freeText??""}i(Xt,"draftName");function Qt(e){return xn(e.clinic)}i(Qt,"draftNeedsEmail");function kl(e,r,t,o,n){let[l,a]=useState(e.ownerName),[d,s]=useState(""),[c,u]=useState([]),[p,f]=useState([]),[b,y]=useState([]),[m,h]=useState(null),[v,E]=useState(null),[g,R]=useState(false),[S,C]=useState(false),[k,_]=useState(null),[T,I]=useState(null),[F,q]=useState(0),M=useRef(false),$=useRef(false),V=useRef(0),re=useRef(0),Q=useRef(Zr()),w=useRef(null),x=useRef(null);useEffect(()=>(M.current=true,$.current=false,R(false),()=>{M.current=false,re.current+=1,V.current+=1,w.current=null,x.current?.abort();}),[r,t]),useEffect(()=>{let U=true;return h(null),w.current=null,r.getAuthorizationCopy().then(Re=>{U&&(Re.ok?(h(Re.value),E(null)):E(Re.error));}).catch(()=>{U&&E(z("internalError"));}),()=>{U=false;}},[r,F]),useEffect(()=>{let U=true;return f([]),r.recentClinics({limit:5}).then(Re=>{U&&Re.ok&&f(Re.value.clinics);}).catch(()=>{}),()=>{U=false;}},[r]);let A=i(()=>{w.current=null,E(null);},"invalidate"),D=b.map(Xt),G=m?D.map(U=>En(m,l.trim(),e.petName,U)):[],de=G.every(U=>U!==null)?G.join(`
2
2
 
3
- `):null,Ae=R.length>0&&R.every(M=>!Qt(M)||Zp.test(M.email.trim())),oe=R.length>=Bt,ve=!!(m&&de&&l.trim()&&e.petName.trim()&&Ae&&o)&&_===null,ar=i(async()=>{if(Y.current)return;let M=++K.current;C(true);try{let Re=await r.searchClinics({query:d.trim(),limit:100});if(!$.current||M!==K.current)return;Re.ok?(u(Re.value.clinics),E(null)):E(Re.error);}catch{$.current&&M===K.current&&E(z("internalError"));}finally{$.current&&M===K.current&&C(false);}},"search"),Ke=i(M=>{Y.current||oe||_!==null||M.clinic!==null&&R.some(Re=>Re.clinic?.id===M.clinic?.id)||(A(),y(Re=>[...Re,{...M,key:Q.current(),idempotencyKey:Q.current()}]),u([]),s(""));},"add"),_r=i(async()=>{if(Y.current||_!==null||!ve||!m||!de||!o)return;Y.current=true;let M=re.current,Re=i(()=>$.current&&re.current===M,"current");b(true),E(null);try{if(w.current===null){x.current=new AbortController;let sr=await o({petRef:e.petRef,petName:e.petName,ownerName:l.trim(),clinicName:D.join(", "),authorizationVersion:m.authorizationVersion,scopeText:de,signal:x.current.signal});if(!Re()||sr===null)return;if(w.current=sr,sr.signaturePngBase64!==void 0&&n!==void 0){let Cc=await n(sr.signaturePngBase64,x.current.signal);if(!Re())return;w.current={signatureId:Cc.signatureId};}}let Tr=w.current,ln=R.map(sr=>({...sr.clinic!==null&&(!Qt(sr)||sr.clinic.emailStatus==="none")?{clinicId:sr.clinic.id}:{clinicFreeText:Xt(sr)},...Qt(sr)?{clinicEmail:sr.email.trim().toLowerCase()}:{},...Tr.signatureId!==void 0?{signatureId:Tr.signatureId}:{signaturePngBase64:Tr.signaturePngBase64},idempotencyKey:sr.idempotencyKey})),dn=await t.createClinicRequestBatch({petRef:e.petRef,ownerName:l.trim(),authorizationVersion:m.authorizationVersion,clinics:ln});if(!Re())return;if(!dn.ok){E(dn.error);return}k(dn.value),e.onCreated?.(dn.value),Pr(dn.value.requestGroupId,M);}catch{Re()&&E(z("internalError"));}finally{Y.current=false,Re()&&b(false);}},"submit"),Pr=i(async(M,Re)=>{try{let Tr=await r.getRequestGroup(M);if(!$.current||re.current!==Re)return;Tr.ok&&Tr.value.petRef===e.petRef&&I(Tr.value);}catch{}},"loadGroup"),Ee=i(async()=>{_===null||Y.current||await Pr(_.requestGroupId,re.current);},"refreshGroup");return {ownerName:l,query:d,clinics:c,copy:m,scopeText:de,error:v,busy:g,searching:S,drafts:R,outcome:_,group:T,ready:ve,atCap:oe,recent:c.length===0?p.filter(M=>!R.some(Re=>Re.clinic?.id===M.id)):[],setOwnerName(M){Y.current||(A(),a(M));},setQuery(M){Y.current||(K.current+=1,C(false),u([]),s(M));},search:ar,addClinic(M){Ke({clinic:M,freeText:null,email:""});},addFreeText(){let M=d.trim();M.length!==0&&Ke({clinic:null,freeText:M,email:""});},setDraftEmail(M,Re){Y.current||(A(),y(Tr=>Tr.map(ln=>ln.key===M?{...ln,email:Re}:ln)));},removeDraft(M){Y.current||_!==null||(A(),y(Re=>Re.filter(Tr=>Tr.key!==M)));},submit:_r,refreshGroup:Ee,retryCopy(){E(null),L(M=>M+1);}}}i(Sl,"useClinicBatchForm");function wl(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(wl,"trustedSignatureUploadUrl");function kl(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(kl,"paintClinicTypedSignature");function _l(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(_l,"paintSignatureStrokes");async function Pl(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||!wl(a.value.uploadUrl))throw n();let d=new FormData;for(let[f,R]of Object.entries(a.value.uploadFields))d.append(f,R);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(Pl,"registerClinicSignature");var rm=8,tm=480,nm=160;function Ot(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,h=m?.getContext("2d");if(!m||!h)return;let v=typeof window<"u"&&window.devicePixelRatio||1;h.setTransform(v,0,0,v,0,0);let E=m.width/v,g=m.height/v;if(u.current.trim().length>0){h.fillStyle="#111",kl(h,u.current,E,g);return}h.lineWidth=2,h.lineCap="round",h.lineJoin="round",h.strokeStyle="#111",_l(h,o.current,E,g);},[]);useEffect(()=>{let m=r.current;if(!m)return;let h=i(()=>{let E=m.getBoundingClientRect(),g=typeof window<"u"&&window.devicePixelRatio||1,b=Math.max(1,Math.round((E.width||m.clientWidth||tm)*g)),S=Math.max(1,Math.round((E.height||m.clientHeight||nm)*g));m.width!==b&&(m.width=b),m.height!==S&&(m.height=S),p();},"resize");if(h(),typeof ResizeObserver>"u")return;let v=new ResizeObserver(h);return v.observe(m),()=>v.disconnect()},[p]);let f=useCallback(()=>{e?.(),o.current=[],c(false),d(""),u.current="",p();},[e,p]),R=i(m=>{let h=m.currentTarget.getBoundingClientRect();return [m.clientX-h.left,m.clientY-h.top]},"point"),y=i(()=>o.current.reduce((m,h)=>m+h.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,[R(m)]],p());},onPointerMove(m){if(!t.current||n!=="draw")return;let h=o.current[o.current.length-1];h!==void 0&&(o.current=[...o.current.slice(0,-1),[...h,R(m)]],p(),c(y()>=rm));},onPointerUp(){t.current=false;},register(m,h){return !r.current||!s?Promise.reject(new Error("Signature upload failed")):Pl(r.current,m,h)}}}i(Ot,"useSignatureCanvas");function It({pad:e,disabled:r}){let t=ce(),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"?X.draw:X.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"?X.toType:X.toDraw}),e.mode==="type"&&jsx("input",{"aria-label":X.type,style:{...n,display:"block",width:"100%",boxSizing:"border-box"},maxLength:Ms,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?X.typedSignatureA11y(o):X.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":X.drawHint}),e.mode==="type"?null:jsx("button",{type:"button",style:l,disabled:r,onClick:e.clear,"aria-label":X.clearA11y,"data-testid":"records-signature-clear",children:X.clear})]})]})}i(It,"SignatureCanvas");function Sn(e){let{userRef:r,scopeEpoch:t}=ee();return jsx(Te,{capability:"recordsClinic",...Oe(e.onClose,X.cancel),children:r===null?jsx("p",{role:"alert",children:V.sessionRequired}):jsx(om,{..._e(e,["onClose","onCreated"])},JSON.stringify([r,t,e.petRef,e.petName]))})}i(Sn,"EverfurClinicRequestBatch");function om(e){let r=Ir(),t=qi(),o=e.controller??r,n=ce(),l=Ot(),a=Sl(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"),R=a.busy?ze.sending:a.drafts.length===0?ze.addToContinue:a.error?ze.tryAgain:ze.send(a.drafts.length),y=a.outcome?ze.resultTitle:ze.title;return jsxs("section",{className:e.className,"aria-label":y,style:{...mt,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:y}),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?ze.allFailed:a.outcome.failedCount>0?ze.partial(a.outcome.createdCount,a.outcome.results.length,a.outcome.failedCount):ze.allSent(a.outcome.createdCount)}),jsx("h3",{style:{margin:0,fontSize:n.type.size.subtitle},children:ze.perClinic}),jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"grid",gap:n.space.sm},children:a.outcome.results.map((m,h)=>{let v=m.request?.clinicName??a.drafts[h]?.clinic?.name??m.clinicFreeText??"";return jsxs("li",{"data-testid":`records-batch-row-${m.created?"created":"failed"}`,children:[jsx("span",{children:v})," ",jsx("span",{style:p,children:m.created?ze.sent:ze.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:ze.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:[X.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:Xt(m)}),Qt(m)?jsxs("label",{children:[X.email,jsx("input",{style:c,type:"email",placeholder:X.emailPlaceholder,maxLength:320,autoComplete:"off",value:m.email,disabled:a.busy,onChange:h=>{l.clear(),a.setDraftEmail(m.key,h.target.value);}})]}):null,Qt(m)&&!m.email.trim()?jsx("p",{style:p,children:ze.emailToAdd}):null,jsx("button",{type:"button",style:u,disabled:a.busy,"aria-label":ze.remove(Xt(m)),onClick:()=>{l.clear(),a.removeDraft(m.key);},children:ze.remove(Xt(m))})]},m.key))}),jsx("p",{style:{margin:0},children:a.atCap?ze.atCap:ze.addClinic}),!a.atCap&&jsxs(Fragment,{children:[jsxs("label",{children:[X.clinic,jsx("input",{style:c,placeholder:X.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:X.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:ze.addClinic}),a.searching&&jsx("p",{role:"status",children:V.loading}),a.recent.length>0&&jsx("h3",{style:{margin:0,fontSize:n.type.size.subtitle},children:X.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:X.scopeHeading}),a.copy?jsx("p",{style:{whiteSpace:"pre-wrap",margin:0},children:a.drafts.length>0&&a.ownerName.trim()?a.scopeText??z("internalError").displayMessage:V.consentRequired}):!a.error&&jsx("p",{role:"status",children:V.loading}),!e.onCaptureSignature&&jsx(It,{pad:l,disabled:a.busy}),!d&&jsx("p",{role:"alert",children:X.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:V.retry}),jsx("button",{type:"button","aria-label":ze.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:R})]}),e.onClose&&jsx("button",{type:"button",style:u,disabled:a.busy,onClick:e.onClose,children:X.cancel}),jsx(De,{})]})}i(om,"BatchBody");var he=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 ${Pe(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 ${Pe(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 am="value_text",Ol=64,Il=512;function Al(e){return e!==null&&e.httpStatus===409&&!Jr(e)}i(Al,"isFactReviewerLocked");var wn=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:am}),ql=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,Nl=/^\d{4}-\d{2}-\d{2}$/;function Ll(e){if(e==null)return "text";let r=e.trim();return ql.test(r)?"num":Nl.test(r)&&!Number.isNaN(Date.parse(r))?"date":r==="true"||r==="false"?"bool":"text"}i(Ll,"inferFactValueKind");function Vi(e,r){let t=r.trim(),o=Ll(e);if(o==="num"&&ql.test(t)){let n=Number(t);if(Number.isFinite(n))return Object.freeze({[wn.num]:n})}return o==="date"&&Nl.test(t)&&!Number.isNaN(Date.parse(t))?Object.freeze({[wn.date]:t}):Object.freeze(o==="bool"&&(t==="true"||t==="false")?{[wn.bool]:t==="true"}:{[wn.text]:t})}i(Vi,"factCorrectionFor");var Ie=z$1.string().nullish(),bo=z$1.number().nullish(),sm=z$1.object({collected_at:Ie,at:Ie,value:bo,unit:Ie,qualitative_result:Ie,ref_low:bo,ref_high:bo,status:Ie,source_clinic:Ie,source_doc_id:Ie,doc_id:Ie,reviewed:z$1.boolean().nullish()}),lm=z$1.object({collected_at:Ie,at:Ie,value:bo,unit:Ie,qualitative_result:Ie,status:Ie}),dm=z$1.object({marker_id:z$1.string().min(1),canonical_name:Ie,name:Ie,loinc_code:Ie,canonical_unit:Ie,unit:Ie,panel_name:Ie,panel:Ie,meaning_text:Ie,meaning:Ie,latest:lm.nullish(),trajectory:Ie,points:z$1.array(sm).optional()}),cm=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()}),um=z$1.object({markers:z$1.array(dm).optional(),summary:cm.nullish(),disclaimer:z$1.string().optional(),featured_marker_id:Ie});function pm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(pm,"isObject");function Fl(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(Fl,"withheldMarkers");function zl(e,r){let t=pm(r)?r:{},o=typeof t.pet_ref=="string"&&t.pet_ref.length>0?t.pet_ref:e;if(t.withheld===true)return Fl(o);let n=um.safeParse(t);if(!n.success)return Fl(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(zl,"mapRecordMarkers");var mm=z$1.string().min(1).refine(e=>e.startsWith("https://")),fm=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:mm,expires_in_seconds:z$1.number().int().nonnegative().nullish()}),ym=z$1.object({items:z$1.array(z$1.unknown()).optional()});function Ml(e){let r=ym.safeParse(e);if(!r.success)return null;let t=[];for(let o of r.data.items??[]){let n=fm.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(Ml,"mapRequestDocuments");var gm=z$1.string().min(1).refine(e=>e.startsWith("https://")),kn=z$1.string().nullish(),bm=z$1.object({share_id:z$1.string().min(1),share_url:z$1.string().min(1),expires_at:kn}),Rm=z$1.object({shares:z$1.array(z$1.object({share_id:z$1.string().min(1),expires_at:kn,created_at:kn,view_count:z$1.number().int().nonnegative().nullish(),last_viewed_at:kn})).optional()}),hm=z$1.object({download_url:gm,expires_at:kn});function vm(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(vm,"resolveShareUrl");function $l(e,r){let t=bm.safeParse(e);if(!t.success)return null;let o=vm(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($l,"mapRecordShareLink");function Ul(e){let r=Rm.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(Ul,"mapRecordShareList");function Bl(e){let r=hm.safeParse(e);return r.success?Object.freeze({downloadUrl:r.data.download_url,expiresAt:r.data.expires_at??null}):null}i(Bl,"mapRecordPdfLink");var Cm=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 jl(e){let r=Cm.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(jl,"mapSignatureSuggestions");var j=z$1.string().nullish(),_n=z$1.number().nullish(),Em=z$1.object({at:j,value:_n,unit:j,qualitative_result:j,ref_low:_n,ref_high:_n,status:j,doc_id:j}),xm=z$1.object({marker_id:z$1.string(),name:z$1.string(),loinc_code:j,unit:j,panel:j,meaning:j,latest:z$1.object({at:j,value:_n,unit:j,qualitative_result:j,status:j}).nullish(),trajectory:j,points:z$1.array(Em).optional()}),Sm=z$1.object({encounter_id:z$1.string(),date:j,type:j,clinic_name:j,veterinarian:j,doc_id:j}),wm=z$1.object({note_id:z$1.string(),encounter_id:j,observed_on:j,sections:z$1.array(z$1.object({section:z$1.string(),text:z$1.string()})).optional()}),km=z$1.object({exam_id:z$1.string(),encounter_id:j,observed_on:j,doc_id:j,systems:z$1.record(z$1.object({finding_status:j,finding:j})).optional()}),_m=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:j,latest_record_at:j,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()}),Pm=z$1.object({conflict_id:z$1.string(),entity_type:z$1.string(),field:j,severity:j,candidates:z$1.array(z$1.object({value:z$1.string(),source_doc_id:j,doc_id:j,collected_at:j})).optional()}),Tm=z$1.object({lab_results:z$1.array(xm).optional(),encounters:z$1.array(Sm).optional(),clinician_notes:z$1.array(wm).optional(),physical_exams:z$1.array(km).optional(),completeness:_m.nullish(),conflicts:z$1.array(Pm).optional()}),Dm=z$1.object({visits:z$1.array(z$1.object({visit_id:z$1.string(),visit_date:j,veterinarian:j,summary:j,doc_id:j})),vaccines:z$1.array(z$1.object({vaccine_id:z$1.string(),product:j,lot:j,administered_on:j,expires_on:j,doc_id:j})),weights:z$1.array(z$1.object({weight_id:z$1.string(),observed_on:j,weight_kg:_n,doc_id:j})),medications:z$1.array(z$1.object({medication_id:z$1.string(),drug_name:j,dose:j,route:j,frequency:j,sig:j,rx_number:j,started_on:j,stopped_on:j,doc_id:j})),disclaimer:z$1.string().optional()}),Om=z$1.object({document:Xo,contributions:z$1.array(Qo),contribution_count:z$1.number().int().nonnegative().optional()});function Wi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Wi,"isObject");function Yi(e,r){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:r}i(Yi,"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 Im(e,r){let t=Wi(r)?r:{},o=Yi(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=Tm.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(Im,"mapRecordDepth");function Hl(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(Hl,"withheldTimeline");function Am(e,r){let t=Wi(r)?r:{},o=Yi(t,e);if(t.withheld===true)return Hl(o);let n=Dm.safeParse(t);if(!n.success)return Hl(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(Am,"mapRecordsTimeline");function qm(e,r){let t=Wi(r)?r:{},o=Yi(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=Om.safeParse(t);if(!l.success)return n();let a=Object.freeze(l.data.contributions.map(Jo));return Object.freeze({petRef:o,withheld:false,document:Zo(l.data.document),contributions:a,contributionCount:l.data.contribution_count??a.length})}i(qm,"mapDocumentContributions");var Nm="/widget/v1/records/pets";function Vl(e){let r=e.funnel??ut({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),t=i((s,c)=>typeof s=="string"&&s.length>0&&!pt(s)&&[...s].length<=c,"segment"),o=i(async(s,c,u,p)=>{if(!t(c,or))return ot();let f=await r.send(s,{method:"GET",path:u});if(!f.ok)return f;let R=p(f.value);return R.petRef===c?we(R):G(z("internalError",{retryable:false}))},"read"),n=i(s=>`${Nm}/${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?G(z("internalError",{retryable:false})):we(f)},"parsed"),d=i((s,c)=>!t(s.entityType,Ol)||!t(s.canonicalKey,Il)||s.idempotencyKey!==void 0&&!t(s.idempotencyKey,un)||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=>Im(s,c)),"getRecordDepth"),getTimeline:i(s=>o("records.depth.timeline",s,`${n(s)}/timeline`,c=>Am(s,c)),"getTimeline"),getDocumentContributions(s,c){return t(c,64)?o("records.depth.contributions",s,`${n(s)}/documents/${encodeURIComponent(c)}/contributions`,u=>qm(s,u)):ot()},getMarkers:i(s=>o("records.depth.markers",s,`${n(s)}/markers`,c=>zl(s,c)),"getMarkers"),createShare(s){return t(s,or)?a("records.share.create",{method:"POST",path:`${l(s)}/share`},c=>$l(c,e.apiBaseUrl)):ot()},listShares(s){return t(s,or)?a("records.share.list",{method:"GET",path:`${l(s)}/shares`},Ul):ot()},async revokeShare(s,c){if(!t(s,or)||!t(c,64))return ot();let u=await r.send("records.share.revoke",{method:"DELETE",path:`${l(s)}/shares/${encodeURIComponent(c)}`},{idempotent:false,maxAttempts:1});return u.ok?we(void 0):u},getPdfLink(s){return t(s,or)?a("records.pdf.link",{method:"GET",path:`${l(s)}/pdf-link`},Bl):ot()},async editFact(s,c){let u=t(s,or)?d(c,c.correctedFields):null;if(u===null)return ot();let p=await r.send("records.fact.edit",{method:"POST",path:`${l(s)}/facts/edit`,body:u},{idempotent:false,maxAttempts:1});return p.ok?we(void 0):p},async removeFact(s,c){let u=t(s,or)?d(c):null;if(u===null)return ot();let p=await r.send("records.fact.remove",{method:"POST",path:`${l(s)}/facts/remove`,body:u},{idempotent:false,maxAttempts:1});return p.ok?we(void 0):p},listRequestDocuments(s){return t(s,64)?a("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(s)}/documents`},Ml):ot()},listAuthorizationSignatures:i(()=>a("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},jl),"listAuthorizationSignatures")}}i(Vl,"createRecordsDepthClient");function ot(){return Promise.resolve(G(z("validationFailed",{retryable:false})))}i(ot,"invalid");function pr(){let{runtime:e,userRef:r,scopeEpoch:t}=ee();return useMemo(()=>{let{services:o}=e.registry;return Vl({auth:o.authFor(r),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,r,t])}i(pr,"useEverfurRecordsDepthClient");function zr(e,r,t,o=""){let n=pr(),{userRef:l}=ee(),a=Qn(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 v=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 E=await r(n,e);v===u.current&&(E.ok?c({scope:d,value:E.value,error:null,loading:false}):c({scope:d,value:null,error:E.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},R=useCallback(()=>{p();},[p]),y=f.error===null||f.error.httpStatus!==404,m=y?f.error:null,h=f.loading?"loading":m!==null?"error":f.value===null?"empty":f.value.withheld?"populated":t(f.value)?"empty":"populated";return useMemo(()=>({status:h,value:f.value,error:m,available:y,refresh:R}),[h,f.value,m,y,R])}i(zr,"useRecordsDepthRead");function Rt(e){return e!==null&&e.httpStatus===404}i(Rt,"isDarkRouteError");var $m=i((e,r)=>e.getMarkers(r),"readMarkers"),Um=i(e=>e.markers.length===0,"markersEmpty");function Qi(e){let r=zr(e,$m,Um);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(Qi,"useRecordsMarkers");var Bm=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Yl(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,R]=useState(r.email),[y,m]=useState(false),[h,v]=useState(null),[E,g]=useState(null),[b,S]=useState(0),[C,_]=useState(null),[k,T]=useState(false),[I,q]=useState(null),[L,$]=useState([]),[Y,K]=useState(null),[re,Q]=useState(false),w=useRef(false),x=useRef(true),A=useRef(Zr()),D=useRef(null);useEffect(()=>(x.current=true,()=>{x.current=false,D.current=null;}),[t]),useEffect(()=>{let Ee=true;return v(null),D.current=null,t.getAuthorizationCopy().then(M=>{Ee&&(M.ok?(v(M.value),g(null)):g(M.error));}).catch(()=>{Ee&&g(z("internalError"));}),()=>{Ee=false;}},[t,b]),useEffect(()=>{if(o===void 0)return;let Ee=true;return o.listAuthorizationSignatures().then(M=>{Ee&&(M.ok?$(M.value):Rt(M.error)||$([]));}).catch(()=>{}),()=>{Ee=false;}},[o]);let H=xn(r.clinic),de=f.trim().toLowerCase(),Ae=Bm.test(de),oe=H&&(y||de.length>0)&&!Ae?he.emailRequired:null,ve=h?En(h,u.trim(),Pe(e.petName),a):null,ar=e.hostCapture===true||re||Y!==null,Ke=!!(s&&h&&ve&&u.trim()&&a&&ar&&(!H||Ae)),_r=useCallback(async()=>{if(!(w.current||I!==null||!h||!ve)){if(!a){_(he.missingDraftError);return}if(H&&!Ae){m(true),_(he.emailRequired);return}if(!(!s||!u.trim())){w.current=true,T(true),_(null);try{if(D.current===null){let M=Y!==null?{signatureId:Y}:await n();if(!x.current)return;if(M===null){_(he.missingSignatureError);return}let Re=r.clinic&&(!H||r.clinic.emailStatus==="none")?{clinicId:r.clinic.id}:{clinicFreeText:a};D.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:h.authorizationVersion,...Re,...H?{clinicEmail:de}:{},...M.signatureId!==void 0?{signatureId:M.signatureId}:{signaturePngBase64:M.signaturePngBase64},idempotencyKey:A.current()};}let Ee=await t.createClinicRequest(D.current);if(!x.current)return;if(!Ee.ok){_(Ee.error.displayMessage);return}if(Ee.value.petRef!==e.petRef){_(z("internalError").displayMessage);return}q(Ee.value),D.current=null,l?.(Ee.value);}catch{x.current&&_(z("internalError").displayMessage);}finally{w.current=false,x.current&&T(false);}}}},[s,n,r.clinic,a,t,h,I,e.petRef,H,de,l,u,Y,ve,Ae]),Pr=useCallback(()=>{D.current=null,_(null);},[]);return {title:d?he.titleFreeText:he.titleDirectory,clinicName:a,isFreeText:d,authorized:s,ownerName:u,email:f,emailError:oe,needsEmail:H,directoryClinicNoEmail:H&&r.clinic!==null,copy:h,copyError:E,scope:ve,error:C,busy:k,created:I,ready:Ke,signatures:L,reuseSignatureId:Y,hasSignature:ar,setAuthorized(Ee){w.current||(Pr(),c(Ee));},setOwnerName(Ee){w.current||(Pr(),p(Ee));},setEmail(Ee){w.current||(Pr(),m(false),R(Ee));},setSigned(Ee){w.current||(Pr(),Q(Ee),Ee&&K(null));},pickReuseSignature(Ee){w.current||(Pr(),K(Ee));},retryCopy(){g(null),S(Ee=>Ee+1);},submit:_r}}i(Yl,"useRecordsConsentForm");function Pn(e){let{userRef:r,scopeEpoch:t}=ee();return jsx(Te,{capability:"recordsClinic",style:e.style,className:e.className,...Oe(e.onBack,Le),children:r===null?jsx("p",{role:"alert",children:V.sessionRequired}):jsx(Vm,{..._e(e,["onCreated","onNavigate","onBack"])},JSON.stringify([r,t,e.petRef,e.clinic.key]))})}i(Pn,"EverfurRecordsConsent");function Vm({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}=B(),R=Ir(),y=a??R,m=pr(),h=Ot(),v=Yl({petRef:e,petName:r,ownerName:o??"",clinic:t,controller:y,depthClient:m,capture:n?()=>n({petRef:e,petName:Pe(r),ownerName:v.ownerName,clinicName:v.clinicName,authorizationVersion:v.copy?.authorizationVersion??"",scopeText:v.scope??"",signal:new AbortController().signal}):async()=>h.signed?h.register(y,new AbortController().signal):null,hostCapture:n!==void 0,onCreated:i(k=>{l?.(k),d?.({name:"dashboard"});},"onCreated")}),E=h.signed,g=useRef(v);g.current=v,useEffect(()=>{g.current.setSigned(E);},[E]);let b=v.busy,S={display:"flex",flexDirection:"column",gap:p.space.sm},C="records-consent-owner-name",_="records-consent-clinic-email";return jsxs("div",{className:u,style:{...f.root,...c},"data-testid":"records-consent-screen",children:[jsx(He,{title:v.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":he.scopeHeading,children:[jsx("h3",{style:{...f.sectionTitle,color:p.color.brand},children:he.scopeHeading}),jsx("p",{style:f.bodyText,children:he.scopeBody}),jsx("ul",{style:{...f.plainList,gap:p.space.sm},children:he.whatWeDo.map(k=>jsxs("li",{style:{...f.bodyText,display:"flex",gap:p.space.sm},children:[jsx("span",{"aria-hidden":"true",style:{color:p.color.brand,...O(p,"bold")},children:"\u2713"}),jsx("span",{children:k})]},k))}),jsx("p",{style:{...f.muted,paddingTop:p.space.xs,borderTop:`1px solid ${p.color.borderHairlineGreen}`},children:he.retentionNote}),v.copy&&v.scope?jsx("p",{style:{...f.rowDetail,whiteSpace:"pre-wrap"},"data-testid":"records-consent-scope",children:v.scope}):v.copyError?jsxs(Fragment,{children:[jsx("p",{role:"alert",style:f.errorText,children:v.copyError.displayMessage}),jsx(U,{label:V.retry,kind:"outline",onClick:v.retryCopy,testID:"records-consent-copy-retry"})]}):jsx("p",{role:"status",style:f.muted,children:V.loading})]}),jsxs("button",{type:"button",role:"checkbox","aria-checked":v.authorized,onClick:()=>v.setAuthorized(!v.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 ${v.authorized?p.color.brand:p.color.brandBorder}`,backgroundColor:v.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:v.authorized?p.color.brand:p.color.surface,color:p.color.onPrimary,display:"inline-flex",alignItems:"center",justifyContent:"center",...O(p,"bold")},children:v.authorized?"\u2713":""}),jsx("span",{style:{...f.rowTitle,...O(p,"bold"),fontSize:p.type.size.bodyTight},children:he.authorizeLabel(r,v.clinicName)})]}),jsxs("div",{style:S,children:[jsx("label",{htmlFor:C,style:f.fieldLabel,children:he.fullName}),jsx("input",{id:C,style:f.field,value:v.ownerName,placeholder:he.fullNamePlaceholder,maxLength:200,disabled:b,autoComplete:"name",onChange:k=>v.setOwnerName(k.target.value),"data-testid":"records-consent-owner-name"})]}),v.needsEmail?jsxs("div",{style:S,"data-testid":"records-consent-email-block",children:[v.directoryClinicNoEmail?jsx("p",{style:f.cautionNote,"data-testid":"records-consent-no-email-note",children:he.noEmailNote(r,v.clinicName)}):null,jsx("label",{htmlFor:_,style:f.fieldLabel,children:he.emailLabel}),jsx("input",{id:_,type:"email",style:f.field,value:v.email,placeholder:he.emailPlaceholder,maxLength:320,disabled:b,autoComplete:"off",onChange:k=>v.setEmail(k.target.value),"data-testid":"records-consent-clinic-email"}),v.emailError?jsx("p",{role:"alert",style:f.errorText,children:v.emailError}):null,jsx("p",{style:f.muted,"data-testid":"records-consent-review-note",children:he.newClinicDirectSendNote})]}):null,n?null:jsxs("div",{style:S,children:[v.signatures.length>0?jsxs("div",{style:S,children:[jsx("span",{style:f.fieldLabel,children:he.reuseSignature}),jsx("div",{style:{display:"flex",gap:p.space.sm,overflowX:"auto",padding:`${p.space.xs}px 0`},children:v.signatures.map(k=>{let T=v.reuseSignatureId===k.signatureId;return jsx("button",{type:"button",onClick:()=>v.pickReuseSignature(T?null:k.signatureId),"aria-label":T?he.reuseTileSelectedA11y:he.reuseTileA11y,"aria-pressed":T,style:{flexShrink:0,width:112,height:56,borderRadius:p.radius.sm,border:T?`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-${k.signatureId}`,children:jsx("img",{src:k.previewUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"contain"}})},k.signatureId)})}),jsx("p",{style:f.muted,children:he.reuseHint})]}):null,jsx(It,{pad:h,disabled:b}),jsx("p",{style:f.muted,children:he.signatureHint(v.clinicName)}),!v.hasSignature&&v.clinicName.length>0?jsx("p",{style:f.muted,"data-testid":"records-consent-signature-required",children:he.missingSignatureError}):null]}),v.error?jsx("p",{role:"alert","aria-live":"assertive",style:f.errorBanner,children:v.error}):null,v.created?jsx("p",{role:"status",style:f.bodyText,children:v.created.statusLabel||V.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(U,{label:X.cancel,kind:"link",disabled:b,onClick:s,style:{flex:"0 0 auto"},testID:"records-consent-cancel"}):null,jsx(U,{label:b?he.submitting:he.submit,ariaLabel:he.submitA11y,disabled:!v.ready,busy:b,onClick:()=>{v.submit();},style:{flex:"1 1 12rem",minWidth:0,minHeight:54},testID:"records-consent-submit"})]}),jsx(De,{})]})}i(Vm,"ConsentBody");var ho=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function Kl(e){if(!e)return null;let r=Date.parse(e);return Number.isNaN(r)?null:r}i(Kl,"toMillis");function Ql(e){let r=[...e.visits.map((t,o)=>({key:`visit-${o}-${t.visitId}`,kind:"visit",kindLabel:me.kind.visit,at:t.visitDate,date:J(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(J(t.expiresOn))),{key:`vaccine-${o}-${t.vaccineId}`,kind:"vaccine",kindLabel:me.kind.vaccine,at:t.administeredOn,date:J(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:J(t.observedOn),title:fl(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:J(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=Kl(t.at),l=Kl(o.at);return n===null&&l===null?ho[t.kind]-ho[o.kind]:n===null?1:l===null?-1:l!==n?l-n:ho[t.kind]-ho[o.kind]}))}i(Ql,"buildTimelineRows");var Xm=300,Xl=120,Jl=44,Jm=i((e,r)=>e.getTimeline(r),"readTimeline"),Zm=i(e=>e.isEmpty,"timelineEmpty");var ef=i(e=>e.contributions.length===0,"contributionsEmpty");function vo({petRef:e,style:r,className:t,onBack:o}){let n=zr(e,Jm,Zm);return jsx(Zl,{state:n,style:r,className:t,onBack:o,header:jsx(He,{title:me.timeline,onBack:fn(o),testID:"timeline-header"}),loading:jsx(vl,{testID:"timeline-loading"}),empty:jsx(Fe,{variant:"no_records",testID:"timeline-empty"}),render:l=>jsx(nf,{timeline:l})})}i(vo,"EverfurRecordsTimeline");function Co({petRef:e,docId:r,style:t,className:o,onBack:n}){let l=useCallback((s,c)=>s.getDocumentContributions(c,r),[r]),a=zr(e,l,ef,r),d=a.value?.document?.title?.trim()||me.uploadedDocument;return jsx(Zl,{state:a,style:t,className:o,onBack:n,header:jsx(He,{title:d,onBack:fn(n),testID:"contributions-header"}),empty:jsx(Fe,{variant:"no_records",testID:"contributions-empty"}),render:s=>jsx(of,{view:s})})}i(Co,"EverfurDocumentContributions");function Zl({state:e,style:r,className:t,header:o,loading:n,empty:l,render:a,onBack:d}){let{styles:s}=Ji(),{userRef:c}=ee();return jsx(Te,{capability:"records",style:r,className:t,...Oe(fn(d),Le),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:V.sessionRequired}):rf(e,a,s,n,l)}),jsx(De,{})]})})}i(Zl,"DepthSurface");function rf(e,r,t,o,n){switch(e.status){case "loading":return o??jsx(tf,{styles:t});case "empty":return n??jsx("div",{style:t.centered,children:jsx("div",{role:"img","aria-label":V.empty,style:t.emptyGlyph})});case "error":return e.error?jsx(Fe,{variant:Qe(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(rf,"renderState");function tf({styles:e}){let[r,t]=useState(false);return useEffect(()=>{let o=setTimeout(()=>t(true),Xm);return ()=>clearTimeout(o)},[]),jsx("div",{role:"status","aria-busy":"true","aria-label":V.loading,style:e.centered,children:r?jsx("div",{"aria-hidden":"true",style:e.spinner}):null})}i(tf,"LoadingState");function nf({timeline:e}){let{styles:r}=Ji(),t=Ql(e);return jsxs("section",{"aria-label":me.timeline,style:r.timelineList,children:[e.disclaimer.length>0?jsx("p",{role:"note","aria-label":lr.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 of({view:e}){let{styles:r}=Ji();return jsxs("section",{"aria-label":V.records,style:r.list,children:[e.document?.receivedAt?jsx("p",{style:r.rowDetail,children:J(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:Ht(t.value,t.unit)}),t.observedAt?jsx("dd",{style:r.rowDetail,children:J(t.observedAt)}):null]},t.key))})]})}i(of,"ContributionsBody");function Ji(){let e=ce(),r=useMemo(()=>af(e),[e]);return {theme:e,styles:r}}i(Ji,"useDepthTheme");function af(e){let{color:r,space:t,radius:o,type:n,slots:l}=e,a=i((f,R)=>`${Math.round(f*R)}px`,"lh"),d=i((f,R,y,m="regular")=>({margin:0,...O(e,m),fontSize:f,lineHeight:a(f,R),color:y}),"text"),s=Wr(l.recordCard),c=i((f,R,y,m="regular")=>({...d(f,R,y,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:Xl,height:"100%",backgroundColor:r.background,color:r.text.primary,...O(e,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:Xl,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:Jl,minWidth:Jl,padding:`${t.md}px ${t.xl}px`,borderRadius:o.pill,...O(e,"bold"),fontSize:n.size.body,border:0,cursor:"pointer",backgroundColor:r.primary,color:r.onPrimary,...Ar(l.primaryButton),...Wr(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,...Ar(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:Ui,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:{...O(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(af,"makeStyles");var W=Object.freeze({title:"Full medical record",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:i(e=>`${e} ${e===1?"document":"documents"} from your vet ${e===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,"inReview"),needsAttention:"Needs your attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:i(e=>`${e} ${e===1?"document":"documents"} on file`,"documentsOnFile"),inReviewChip:i(e=>`${e} in review`,"inReviewChip"),beingVerified:i(e=>`${e} being verified`,"beingVerified"),beingVerifiedA11y:i(e=>`${e} ${e===1?"fact is":"facts are"} being verified`,"beingVerifiedA11y"),pendingReview:"Pending review: ",dateRange:i((e,r)=>`${J(e)} to ${J(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 ${J(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"})}),ed=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 qt(e){return Object.prototype.hasOwnProperty.call(ed,e)?ed[e]:Kr(e)}i(qt,"entityTypeLabel");var Eo=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function rd(e){let r=Eo.filter(o=>e.includes(o)),t=e.filter(o=>!Eo.includes(o));return [...r,...t]}i(rd,"orderEntityTypes");function xo(e){switch(e){case "identity_risk":return {label:"Identity mismatch",rank:0,tone:"critical"};case "benign":return {label:"Minor difference",rank:2,tone:"neutral"};default:return {label:"Needs review",rank:1,tone:"warning"}}}i(xo,"conflictSeverityMeta");function Tn(e,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?W.overdue:W.due(J(e)),overdue:o}}i(Tn,"dueBadge");function td(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(td,"formatReferenceBand");function Zi(e,r={}){let t=pr(),{userRef:o}=ee(),n=r.now??Date.now,[l,a]=useState(null),[d,s]=useState(true),[c,u]=useState(null),[p,f]=useState(null),R=p===true,[y,m]=useState({}),[h,v]=useState(false),[E,g]=useState(null),[b,S]=useState(false),[C,_]=useState(false),k=Qn(e),T=useRef(0),I=useRef(true),q=useCallback(async()=>{let x=T.current+=1;if(s(true),u(null),o===null){a(null),s(false);return}let A=await t.listShares(e);x!==T.current||!I.current||(A.ok?(a(A.value),f(true)):Rt(A.error)?(a(null),f(false)):(a(null),u(A.error),nd(A)&&f(true)),s(false));},[t,e,o]);useEffect(()=>(I.current=true,q(),()=>{I.current=false,T.current+=1;}),[q]);let L=useRef(k);useEffect(()=>{L.current!==k&&(L.current=k,m({}),_(true),q());},[k,q]);let $=useCallback(async()=>{v(true);let x=await t.createShare(e);return I.current&&(v(false),x.ok?(m(A=>({...A,[x.value.shareId]:x.value.shareUrl})),q()):Rt(x.error)?f(false):Jr(x.error)&&_(true)),x},[t,e,q]),Y=useCallback(async x=>{g(x);let A=await t.revokeShare(e,x);return I.current&&(g(null),q()),A},[t,e,q]),K=useCallback(async()=>{S(true);let x=await t.getPdfLink(e);return I.current&&(S(false),!x.ok&&Jr(x.error)&&_(true)),x},[t,e]),re=useCallback(()=>{_(false),q();},[q]),Q=useMemo(()=>bl(l??[],y,n()),[l,y,n]),w=d?"loading":c!==null?"error":Q.length===0?"empty":"populated";return useMemo(()=>({status:w,rows:Q,available:R,consentRequired:C,error:c,creating:h,revokingId:E,preparingPdf:b,createLink:$,revoke:Y,pdfLink:K,refresh:re}),[w,Q,R,C,c,h,E,b,$,Y,K,re])}i(Zi,"useRecordShares");function nd(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(nd,"answeredBehindGate");function od(e){return e.available||e.status!=="empty"}i(od,"sharesListShown");function ea(e){let r=pr(),{userRef:t}=ee(),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&&Rt(s.error)?l({scope:o,lit:false}):nd(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(ea,"useRecordsDepthProbe");function ra(e){let r=pr(),o=ea(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(ra,"useRecordPdfLink");var On=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(Br/(1024*1024)),Nt=Object.freeze({queued:"Queued",verifying:"Verifying\u2026",done:"Done",failed:"Failed",uploading:i((e,r)=>`Uploading ${Math.min(e+1,r)} 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 Nt.done;case "failed":return Nt.failed;case "uploading":return e.progress>=1?Nt.verifying:`${r}%`;case "queued":return Nt.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 ta=[37,80,68,70,45],ko="application/pdf,.pdf",sf="application/octet-stream",lf="file:web-document";async function df(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(df,"readHead");async function dd(e){if(e.size<ta.length)return false;let r=await df(e,ta.length);return ta.every((t,o)=>r[o]===t)}i(dd,"isPdfBlob");async function _o(e){let r=await dd(e),t=e.name,o=typeof t=="string"?t:void 0;return Object.freeze({uri:lf,mimeType:r?ct:sf,sizeBytes:e.size,blob:e,...o!==void 0?{name:o}:{}})}i(_o,"fileToHandle");function na(e){let r=e.sizeBytes;return e.mimeType===ct&&typeof r=="number"&&Number.isFinite(r)&&r>0&&r<=Br}i(na,"isUploadableHandle");function cf(e=document){return new Promise(r=>{let t=e.createElement("input");t.type="file",t.accept=ko,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}_o(n).then(r);},{once:true}),t.addEventListener("cancel",()=>{o(),r(null);},{once:true}),e.body.appendChild(t),t.click();})}i(cf,"pickDocument");var $r=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,R]=useState(null),y=useRef(false),m=useRef(false),h=useRef(0);useEffect(()=>(m.current=true,()=>{m.current=false,h.current+=1;}),[o]);let v=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,E=n.trim(),g=E.length<=320&&!Array.from(E).some(T=>T.charCodeAt(0)<=32||T.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(E),b=v.canUpdateClinicEmail===true&&E.length>0,S=v.canRetrySend===true&&!a&&!b,C=v.canUpdateClinicEmail===true&&!a&&g,_=v.canConvertToUpload===true&&t,k=i(async T=>{let I={retry:S,email:C,revoke:v.canRevoke===true&&u,convert:_};if(y.current||!m.current||!I[T])return;y.current=true,d(true),c(null);let q=h.current,L=i(()=>m.current&&q===h.current,"live");try{let $=T==="retry"?await o.retryRequest(e.id):T==="email"?await o.updateClinicEmail(e.id,E):T==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!L())return;if(!$.ok){c($.error);return}if($.value.id!==e.id||$.value.petRef!==e.petRef){c(z("internalError"));return}R({before:e.updatedAt,value:$.value}),l(""),p(!1),r();}catch{L()&&c(z("internalError"));}finally{y.current=false,L()&&d(false);}},"run");return {request:v,email:n,busy:a,error:s,canRetry:S,canUpdateEmail:C,canConvert:_,hasEmailEdit:b,confirmingRevoke:u&&v.canRevoke===true,emailInvalid:E.length>0&&!g,setEmail(T){y.current||(l(T),c(null));},retry:i(()=>k("retry"),"retry"),updateEmail:i(()=>k("email"),"updateEmail"),revoke:i(()=>k("revoke"),"revoke"),convert:i(()=>k("convert"),"convert"),askRevoke(){!y.current&&v.canRevoke===true&&p(true);},keepRequest(){y.current||p(false);}}}i(cd,"useRecordsRecovery");var pf=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],mf=["requested","awaiting_upload","records_received","processing","ready"],ff=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],An=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"}),yf=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"}),gf=Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function bf(e){return e.wireStatus??gf[e.status]??"sent"}i(bf,"wireStatusOf");function Rf(e,r){return e!=="awaiting_response"||r<=0?null:`${r} ${r===1?"reminder":"reminders"} sent`}i(Rf,"reminderProgressLabel");function hf(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(hf,"reachedRailIndex");function vf(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(vf,"deliveryDetail");function Cf(e,r){return Rf(r,e.reminderCount??0)??fr.waiting}i(Cf,"awaitingDetail");function qn(e){return e.source==="owner_provided"||!!e.convertedToUploadAt}i(qn,"isOwnerSourcedRequest");function Ef(e,r,t){let o=qn(r);switch(e){case "sent_to_clinic":return vf(r);case "awaiting_clinic":return Cf(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(Ef,"railDetail");function xf(e,r){return !!e.reviewStartedAt||r==="parsing_failed"||r==="review_email_failed"}i(xf,"tookReviewBranch");function Sf(e,r,t){if(e.key!=="processing"||!xf(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:An.parsing_failed,detail:fr.parsingFailed,at:null,state:l},{key:"manual_review",title:An.manual_review,detail:fr.manualReview,at:r.reviewStartedAt??null,state:a}]}i(Sf,"expandProcessingPhase");function wf(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(wf,"convertedReachedIndex");function ud(e){return {key:"awaiting_clinic",title:fr.switchedTitle,detail:fr.switched,at:e.convertedToUploadAt??null,state:"done"}}i(ud,"convertedClinicSwitchEvent");function kf(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(kf,"ownerReachedIndex");function _f(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(_f,"railTimestamp");function pd(e,r,t,o){return {key:e,title:An[e],detail:Ef(e,r,t),at:_f(e,r,t),state:o}}i(pd,"railEvent");function it(e,r){return {key:e,title:An[e],detail:yf[e]??null,at:r.updatedAt||null,state:"failed"}}i(it,"terminalEvent");function ia(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=>Sf(l,t,o))}i(ia,"walkRail");function aa(e){let r=bf(e),t=i(n=>pd(n,e,r,"done"),"done");if(r==="revoked")return [t("requested"),it("revoked",e)];if(e.convertedToUploadAt)return r==="failed"?[t("requested"),t("sent_to_clinic"),ud(e),t("awaiting_upload"),t("records_received"),it("processing_failed",e)]:ia(ff,wf(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"),it("processing_failed",e)];let n=kf(r);return ia(mf,n<0?1:n,e,r)}if(r==="clinic_declined")return [t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),it("clinic_declined",e)];if(r==="clinic_responded_no_records")return [t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),it("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"),it("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[t("requested"),it("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),t("records_received"),it("processing_failed",e)]:[t("requested"),it("delivery_failed",e)]}let o=hf(r);return ia(pf,o<0?1:o,e,r)}i(aa,"buildRequestTimeline");var Tf=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),Po=24;function rn({request:e}){let r=If(),t=aa(e);return jsx("ol",{style:r.list,"aria-label":ue.timelineA11y,"data-testid":"records-timeline",children:t.map((o,n)=>jsx(Df,{event:o,isLast:n===t.length-1,styles:r},o.key))})}i(rn,"RequestTimeline");function Df({event:e,isLast:r,styles:t}){let o=e.at?J(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(Of,{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:Tf[e.state]})]})]})}i(Df,"TimelineRow");function Of({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(Of,"Dot");function If(){let e=ce();return useMemo(()=>Af(e),[e])}i(If,"useStyles");function Af(e){let{color:r}=e,t={boxSizing:"border-box",width:Po,height:Po,borderRadius:Po/2,display:"flex",alignItems:"center",justifyContent:"center",...O(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:Po,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,...O(e,"bold"),fontSize:14,lineHeight:"18px",color:r.text.primary},titleCurrent:{color:r.brand},titleFailed:{color:r.danger},titleUpcoming:{color:r.text.muted,...O(e,"regular")},date:{...O(e,"regular"),fontSize:12,lineHeight:"16px",color:r.text.muted},detail:{...O(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(Af,"makeStyles");function md(e){return e.value!==null&&Number.isFinite(e.value)}i(md,"isFinitePoint");function Do(e){return e.display!==null&&e.display.length>0?e.display:e.value!==null?String(e.value):""}i(Do,"pointDisplay");function fd(e){let r=e.find(C=>C.points.some(md));if(r===void 0)return null;let t=r.points.filter(md),o=t[0];if(o===void 0)return null;let n=t.map(C=>C.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,R=t.map((C,_)=>({xPct:f<=1?50:p+_/(f-1)*(100-2*p),yPct:(c-C.value)/u*100})),y=(c-a)/u*100,m=(c-l)/u*100,h=t.reduce((C,_)=>_.value<C.value?_:C,o),v=t.reduce((C,_)=>_.value>C.value?_:C,o),E=t[t.length-1]??o,g=r.points[r.points.length-1]??E,b=Do(g),S=b.length>0?b:Do(E);return {label:r.label,heroDisplay:S,minDisplay:Do(h),maxDisplay:Do(v),firstDate:Fi(r.points[0]?.at??null),lastDate:Fi(g.at),points:R,bandTopPct:y,bandBottomPct:m}}i(fd,"buildTrendModel");function qf(e){let r=e.indexOf(":");return r<=0?null:e.slice(0,r)}i(qf,"entityTypeOf");function yd(e,r,t){let o=new Map,n=[];for(let d of e){let s=qf(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(yd,"groupSeriesByEntityType");function gd({series:e}){let r=ce(),t=useMemo(()=>Ff(r),[r]),o=useMemo(()=>yd(e,Eo,qt),[e]);return o.length===0?null:jsxs("section",{"aria-label":W.careTimeline,style:t.section,children:[jsxs("div",{children:[jsx("h3",{style:t.sectionTitle,children:W.careTimeline}),jsx("p",{style:t.sectionSub,children:W.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(Nf,{series:l,styles:t},l.key))]},n.entityType??"_"))]})}i(gd,"TrendRangeCard");function Nf({series:e,styles:r}){let t=useMemo(()=>fd([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(Lf,{model:t,styles:r})}i(Nf,"SeriesChart");function Lf({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(Lf,"TrendChart");function Ff(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,...O(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`,...O(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,...O(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,...O(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,...O(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",...O(e,"regular"),fontSize:n.size.tiny,lineHeight:l(n.size.tiny,n.lineHeight.normal),color:r.text.muted}}}i(Ff,"makeStyles");var Uf=300,Bf=900,Rd=120,hd=44,vd=40,Cd=24,jf=3;function vt(e,r,t){let o=Vr(e,t);switch(o.kind){case "consent_required":return jsx(Hf,{onGrant:r});case "consent_unavailable":return jsx(Xe,{label:V.consentRequired,glyph:"empty"});case "session_required":return jsx(Xe,{label:V.sessionRequired,glyph:"empty"});case "withheld":return jsx(Xe,{label:V.recordUnavailable,glyph:"withheld"});case "pet_not_found":case "error":return jsx(Vf,{error:o.error,onRetry:e.refresh});default:return Dr(o)}}i(vt,"renderErrorFamily");function Ed(){let{theme:e,styles:r}=nn(),[t,o]=useState(false),n=useRef(null);useEffect(()=>{let a=setTimeout(()=>o(true),Uf);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:Bf,iterations:1/0});return ()=>d.cancel()},[l]),jsx("div",{role:"status","aria-busy":"true","aria-label":V.loading,style:r.centered,children:t?jsx("div",{ref:n,"aria-hidden":"true",style:r.spinner}):null})}i(Ed,"LoadingState");function xd({records:e}){let{styles:r}=nn(),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?Nt.uploading(n,o.length):Nt.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(xd,"UploadQueue");function Hf({onGrant:e}){let{styles:r}=nn();return jsxs("div",{role:"alert","aria-live":"assertive",style:r.centered,children:[jsx("p",{style:r.alertText,children:V.consentRequired}),jsx("button",{type:"button",onClick:e,style:r.primaryButton,children:V.allow})]})}i(Hf,"ConsentRequiredState");function Xe({label:e,glyph:r}){let{styles:t}=nn();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(Xe,"AlertState");function Vf({error:e,onRetry:r}){let{styles:t}=nn();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:V.retry}):null]})}i(Vf,"ErrorState");function Sd({call:e,prompt:r}){let{styles:t}=nn(),o=r.trim().length>0?r:On.fallbackPrompt;return jsxs("div",{style:t.callCard,children:[jsx("p",{style:t.timelineLabel,children:On.heading}),jsx("p",{style:t.timelineMeta,children:o}),jsx("a",{href:e.dial,"aria-label":On.callAt(e.phone),style:t.linkButton,"data-testid":"records-call-clinic",children:On.call})]})}i(Sd,"ClinicCallCard");function nn(){let e=ce(),r=useMemo(()=>Gf(e),[e]);return {theme:e,styles:r}}i(nn,"useRecordsTheme");function Gf(e){let{color:r,space:t,radius:o,type:n,slots:l}=e,a=i((m,h)=>`${Math.round(m*h)}px`,"lh"),d=`1px solid ${r.brandBorder}`,s=Ar(l.recordCard,1),c=Wr(l.recordCard),u=i((m,h,v,E="regular")=>({margin:0,...O(e,E),fontSize:m,lineHeight:a(m,h),color:v}),"text"),p=i((m,h,v,E="regular")=>({...u(m,h,v,E),...c}),"inCard"),f={boxSizing:"border-box",minHeight:hd,minWidth:hd,padding:`${t.md}px ${t.xl}px`,borderRadius:o.pill,...O(e,"bold"),fontSize:n.size.body,letterSpacing:n.letterSpacing.tight},R={boxSizing:"border-box",width:vd,height:vd},y=e.brightness==="dark"?r.errorRed:r.danger;return {container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:Rd,height:"100%",backgroundColor:r.background,color:r.text.primary,...O(e,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:Rd,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:t.lg,padding:t.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:Cd,height:Cd,borderRadius:o.pill,border:`${jf}px solid ${r.brandSofter}`,borderTopColor:r.brand},emptyGlyph:{...R,borderRadius:o.lg,backgroundColor:r.brandSoft,border:d},withheldGlyph:{...R,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,y),primaryButton:{...f,border:0,cursor:"pointer",backgroundColor:r.primary,color:r.onPrimary,...Ar(l.primaryButton),...Wr(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,...Ar(l.primaryButton),...Wr(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(Gf,"makeStyles");var Oo="everfur-record.pdf";function Io(e){return typeof navigator>"u"||!navigator.clipboard?Promise.reject(new Error("clipboard unavailable")):navigator.clipboard.writeText(e)}i(Io,"copyText");function Wf(e){return typeof e=="object"&&e!==null&&e.name==="AbortError"}i(Wf,"isAbort");async function kd(e,r=Io){let t=typeof navigator>"u"?void 0:navigator;if(t!==void 0&&typeof t.share=="function")try{return await t.share({url:e}),"shared"}catch(o){if(Wf(o))return "dismissed"}return await r(e),"copied"}i(kd,"shareLinkInPlace");function Yf(e,r){let t;try{t=new URL(e,r);}catch{return null}if(t.protocol==="blob:"||t.protocol==="data:")return "download";if(r!==void 0)try{if(new URL(r).origin===t.origin)return "download"}catch{}let o=t.searchParams.get("response-content-disposition");return o!==null&&/^\s*attachment\b/i.test(o)?"attachment":null}i(Yf,"inPlaceRoute");function Kf(){return typeof location>"u"?void 0:location.href}i(Kf,"locationHref");function Qf(e=typeof window>"u"?void 0:window){if(e===void 0)return false;try{return e.self!==e.top}catch{return true}}i(Qf,"isFramedDocument");function wd(e,r){let t=document.createElement("a");t.href=e,t.download=r,t.rel="noopener",t.style.display="none",document.body.appendChild(t);try{t.click();}finally{t.remove();}}i(wd,"clickDownload");var Xf=6e4;function Jf(e){let r=document.createElement("iframe");r.setAttribute("sandbox","allow-downloads"),r.setAttribute("aria-hidden","true"),r.tabIndex=-1,r.style.display="none",r.src=e,document.body.appendChild(r),setTimeout(()=>r.remove(),Xf);}i(Jf,"saveThroughNestedFrame");async function on(e,r,t=Qf()){if(typeof document>"u")return false;let o=Yf(e,Kf());if(o==="attachment"&&t)return Jf(e),true;if(o!==null)return wd(e,r),true;let n;try{let a=await fetch(e,{credentials:"omit"});if(!a.ok)return !1;n=await a.blob();}catch{return false}let l=URL.createObjectURL(n);try{wd(l,r);}finally{setTimeout(()=>URL.revokeObjectURL(l),1e4);}return true}i(on,"downloadInPlace");var gr=W.document,_d=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),ey=i((e,r)=>e.getRecordDepth(r),"readDepth"),ry=i(e=>!e.available,"depthEmpty");function ty(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(ty,"documentIsEmpty");function Nn(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onBack"]),{userRef:l}=ee(),{theme:a,styles:d}=B();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),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(Xe,{label:V.sessionRequired,glyph:"empty"})}):jsx(ny,{...n}),jsx(De,{})]})})}i(Nn,"EverfurRecordDocument");function ny({petRef:e,petName:r,controller:t,consentVersion:o,onBack:n,onOpenUrl:l}){let{theme:a,styles:d}=B(),s=Pd(),c=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),u=Ge(c),p=zr(e,ey,ry),f=ra(e),R=tt(o,u.consent),y=i(()=>{let C=Hr(o,u.consent);C.length!==0&&u.grantConsent(C,`records-consent-${Date.now().toString(36)}`);},"onGrant"),m=p.value!==null&&!p.value.withheld&&p.value.available?p.value:null,h=u.record,[v,E]=useState(false),g=i(()=>{E(false),f.pdfLink().then(C=>{C.ok&&(l?Et(l,C.value.downloadUrl,"record_pdf"):on(C.value.downloadUrl,Oo).then(_=>E(!_)));});},"download"),b,S=false;if(u.status==="loading"||p.status==="loading"&&h!==null)b=jsx("div",{"data-testid":"record-document-loading",children:jsx(Ed,{})});else if(u.status==="error"){let C=Vr(u,R);b=C.kind==="error"||C.kind==="pet_not_found"?jsx(Fe,{variant:Qe(C.error),message:C.error.displayMessage,onAction:C.error.retryable?()=>{u.refresh(),p.refresh();}:void 0,testID:"record-document-error"}):vt(u,y,R);}else h===null||ty(h,m)?b=jsx("p",{style:s.empty,"data-testid":"record-document-empty",children:gr.empty}):(S=true,b=jsx(oy,{record:h,depth:m,petName:r,wordmark:a.meta.displayName}));return jsxs(Fragment,{children:[jsx(He,{title:gr.title,variant:"document",onBack:n,testID:"record-document-header",right:f.available&&S?jsx("button",{type:"button",onClick:g,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}):v?jsx("p",{role:"alert",style:{...d.errorText,padding:`0 ${a.space.lg}px`},"data-testid":"record-document-save-failed",children:_t(null,"download")}):null,jsx("div",{style:d.body,children:b})]})}i(ny,"DocumentBody");function oy({record:e,depth:r,petName:t,wordmark:o}){let n=Pd(),l=useMemo(()=>{let c=[],u=new Map;for(let R of e.entities){let y=R.category.trim();if(y.length===0)continue;let m=u.get(y);m===void 0?(c.push(y),u.set(y,[R])):m.push(R);}let p=_d.filter(R=>c.includes(R)),f=c.filter(R=>!_d.includes(R));return [...p,...f].map(R=>({type:R,rows:u.get(R)??[]}))},[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=Yr(c.latest.status),f=td(c.points[c.points.length-1]??null),R=ur(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 ${J(c.latest.at)}`:""]})]}),jsxs("span",{style:n.rowRight,children:[R!=="-"?jsx("span",{style:{...n.rowValue,...p.outOfRange?n.alert:{}},children:R}):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(qt(c),u.map((p,f)=>{let R=[Ht(p.value,p.unit),p.observedAt?J(p.observedAt):null].filter(y=>y&&y.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}),R?jsx("span",{style:n.rowMeta,children:R}):null]})},p.key)}),`record-document-${c}`)),e.forwardLooking.length>0?d(gr.upcomingCare,e.forwardLooking.map((c,u)=>{let p=Tn(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:J(c.observedOn)}):null,c.systems.filter(p=>p.finding).map(p=>jsxs("div",{style:n.fieldRow,children:[jsx("span",{style:n.fieldLabel,children:Gt(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:J(c.observedOn)}):null,c.sections.filter(p=>p.text).map((p,f)=>jsxs("div",{style:n.noteSection,children:[jsx("span",{style:n.noteLabel,children:Wt(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(oy,"RecordDocument");function Pd(){let e=ce();return useMemo(()=>iy(e),[e])}i(Pd,"useDocStyles");function iy(e){let{color:r,space:t,radius:o,type:n}=e,l=i((s,c,u,p="regular")=>({margin:0,...O(e,p),fontSize:s,lineHeight:`${Math.round(s*c)}px`,color:u}),"text"),a=i((s,c)=>({margin:0,...O(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`,...O(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,...O(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(iy,"makeDocStyles");var rr=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 Td(e,r){return Jr(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(Td,"factEditErrorMessage");var sy=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function da(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(da,"applyFactOverlay");function ca(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(ca,"isFactEditable");function ly(){return `records-fact-${Date.now().toString(36)}`}i(ly,"defaultFactKey");function ua(e,r={}){let t=pr(),{userRef:o}=ee(),[n,l]=useState(sy),[a,d]=useState(false),[s,c]=useState(null),u=useMemo(()=>({}),[t,e,o]),[p,f]=useState(null),R=useCallback(()=>f(u),[u]),y=o!==null&&p!==u,m=useRef(false),h=useRef(r.newIdempotencyKey);h.current=r.newIdempotencyKey;let v=useCallback(()=>(h.current??ly)(),[]),E=useCallback((C,_,k)=>{if(d(false),!C.ok){if(_(),Rt(C.error)){R();return}c(Td(C.error,k));}},[R]),g=useCallback(async(C,_)=>{let k=C.canonicalKey??"",T=_.trim();if(m.current||k.length===0||T.length===0)return G(z("validationFailed",{retryable:false}));m.current=true,d(true),c(null);let I=n;l(L=>({...L,edits:{...L.edits,[k]:T}}));let q=await t.editFact(e,{entityType:C.category,canonicalKey:k,correctedFields:Vi(C.value,T),idempotencyKey:v()});return m.current=false,E(q,()=>l(I),"edit"),q},[t,e,n,E,v]),b=useCallback(async C=>{let _=C.canonicalKey??"";if(m.current||_.length===0)return G(z("validationFailed",{retryable:false}));m.current=true,d(true),c(null);let k=n;l(I=>({...I,removed:[...I.removed,_]}));let T=await t.removeFact(e,{entityType:C.category,canonicalKey:_,idempotencyKey:v()});return m.current=false,E(T,()=>l(k),"remove"),T},[t,e,n,E,v]),S=useCallback(()=>c(null),[]);return useMemo(()=>({overlay:n,busy:a,error:s,available:y,edit:g,remove:b,clearError:S}),[n,a,s,y,g,b,S])}i(ua,"useRecordFactEdit");var dy=Object.freeze({vaccination:"Vaccination",medication:"Medication",problem:"Problem",body_weight:"Weight",allergy:"Allergy",vital:"Vital",lab_result:"Lab result",parasite_prevention:"Preventive"}),cy="Given",uy=/^\d{4}-\d{2}-\d{2}/,py=" \xB7 ";function at(e){let r=e.filter(t=>t!==null&&t.trim().length>0);return r.length>0?r.join(py):null}i(at,"joinDetail");function my(e,r){let t=e.label.trim();if(t.length>0)return t;let o=dy[e.category];return o!==void 0?o:r(e.category)}i(my,"rowTitle");function Id(e,r){let t=my(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&&uy.test(e.value.trim()),s=d?r.formatRecordsDate(e.value):a;return s!==null&&s!=="-"?{title:t,detail:at([`${cy} ${s}`,d?null:n])}:{title:t,detail:at([n])}}case "medication":return {title:t,detail:at([a])};case "problem":return {title:t,detail:at([a])};case "body_weight":return {title:t,detail:at([a])};case "allergy":return {title:t,detail:at([a])};case "vital":return {title:t,detail:at([n,a])};case "lab_result":return {title:t,detail:at([n,a])};default:return {title:t,detail:at([n,a])}}}i(Id,"entityRowSummary");function qo(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(qo,"markerStatusTone");function fy(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(fy,"markerStatusSpoken");function yy(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(yy,"rangePhrase");function No(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(No,"formatReferenceRange");function pa(e,r){let t=r.reviewed?", reviewed by our team":"",o=r.sourceClinic?`, from ${r.sourceClinic}`:"";return `${J(r.at)}: ${ur(r.value,e.unit,r.qualitativeResult)}, ${fy(r.status)}${yy(r)}${o}${t}`}i(pa,"markerPointSpoken");function Ve(e){return e?.trim()||"my pet"}i(Ve,"lead");function Ad(e){let r=e.trim();return /[.!?]$/.test(r)?r:`${r}.`}i(Ad,"clause");function qd(e,r){let t=r.canonicalName.trim()||"a lab marker",o=[`I'm looking at ${Ve(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(Ad(r.meaningText)),o.push(`What does this trend tell me, and should I do anything differently for ${Ve(e)}?`),{prompt:o.join(" "),entityRef:{type:"marker",id:r.markerId,payload:{marker:t,...r.statusText?.trim()?{status:r.statusText.trim()}:{}}}}}i(qd,"buildMarkerAskPrompt");function Nd(e,r,t){let{totalMarkers:o,inRangeCount:n,outOfRangeCount:l,unknownCount:a}=r;if(o===0)return {prompt:`I'm looking at ${Ve(e)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${Ve(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 ${Ve(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(Nd,"buildMarkerSummaryAskPrompt");function Ld(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 ${Ve(e)}'s ${o.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:r.entityId,payload:n}}}i(Ld,"buildMarkerReadingAskPrompt");function Fd(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 ${Ve(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(Fd,"buildRecordsRequestAskPrompt");var gy=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function zd(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 ${Ve(e)}'s ${n.toLowerCase()}: ${l}${a?`, ${a}`:""}. What does this mean, and what should I keep on top of for ${Ve(e)}?`,entityRef:{type:gy[t]??t,id:o,payload:{kind:n,title:l,...a?{detail:a}:{}}}}}i(zd,"buildEntityRowAskPrompt");function Md(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 ${Ve(e)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${Ve(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 ${Ve(e)}'s upcoming care: ${l.join(", ")}. What should I prioritize for ${Ve(e)}, and how do I stay on top of these?`,entityRef:n}}i(Md,"buildUpcomingCareAskPrompt");function $d(e,r,t){let o=[`I'm looking at ${Ve(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 ${Ve(e)}?`)):o.push(`Everything examined came back normal. What does this tell me about ${Ve(e)}'s health?`),{prompt:o.join(" "),entityRef:{type:"physical_exam",id:t}}}i($d,"buildPhysicalExamAskPrompt");function Ud(e,r,t){let o=[`I'm looking at ${Ve(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"}: ${Ad(n.text)}`);return o.push(`Can you summarize what happened and what I should follow up on for ${Ve(e)}?`),{prompt:o.join(" "),entityRef:{type:"visit",id:t}}}i(Ud,"buildVisitNoteAskPrompt");function Bd(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 ${Ve(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(Bd,"buildConflictAskPrompt");var Hd='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function Vd(e){return e.tagName==="DIALOG"}i(Vd,"isDialogElement");function Gd(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(!Vd(u)){u.contains(document.activeElement)||(u.querySelector(Hd)??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"&&!Vd(p)){u.preventDefault(),u.stopPropagation(),r();return}if(u.key!=="Tab")return;let f=Array.from(p.querySelectorAll(Hd)),R=f[0],y=f[f.length-1];if(!R||!y){u.preventDefault();return}let m=document.activeElement;u.shiftKey&&(m===R||!p.contains(m))?(u.preventDefault(),y.focus()):!u.shiftKey&&(m===y||!p.contains(m))&&(u.preventDefault(),R.focus());},[r]),c=useCallback(u=>{u.preventDefault(),r();},[r]);return {dialogRef:o,onKeyDown:s,onCancel:c}}i(Gd,"useModalDialog");var Ry='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function Ct({label:e,onClose:r,shape:t="modal",returnFocusTo:o,panelStyle:n,testID:l,children:a}){let{styles:d}=B(),s=Gd(true,r,o);useEffect(()=>{let u=s.dialogRef.current;u===null||u.contains(document.activeElement)||(u.querySelector(Ry)??u).focus();},[s.dialogRef]);let c=t==="side";return jsx("dialog",{ref:s.dialogRef,"aria-label":e,"aria-modal":"true",onCancel:s.onCancel,onKeyDown:s.onKeyDown,style:d.dialogFrame,"data-testid":l,children:jsx("div",{style:c?d.dialogScrimSide:d.dialogScrim,onClick:u=>{u.target===u.currentTarget&&r();},"data-testid":l?`${l}-scrim`:void 0,children:jsx("div",{style:{...c?d.dialogPanelSide:d.dialogPanel,...n},children:a})})})}i(Ct,"RecordsDialog");function Wd({entity:e,factEdit:r,children:t}){let{theme:o,styles:n}=B(),[l,a]=useState(false),d=useRef(null),s=e.label.trim()||rr.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":rr.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(Cy,{entity:e,title:s,factEdit:r,onClose:()=>a(false),returnFocusTo:d}):null]})}i(Wd,"FactEditAffordance");function Cy({entity:e,title:r,factEdit:t,onClose:o,returnFocusTo:n}){let{theme:l,styles:a}=B(),[d,s]=useState(e.value??""),[c,u]=useState(null),[p,f]=useState(false);useEffect(()=>{t.clearError();},[t]);let R=d.trim().length>0&&d.trim()!==(e.value??"").trim(),y=c??t.error,m=t.busy,h=i(()=>{if(!R){u(rr.noChange);return}u(null),t.edit(e,d).then(g=>{g.ok&&o();});},"submitEdit"),v=i(()=>{u(null),t.remove(e).then(g=>{g.ok?o():f(false);});},"submitRemove"),E=`fact-edit-${e.key}`;return jsxs(Ct,{label:rr.title(r),onClose:o,returnFocusTo:n,testID:"fact-edit-sheet",children:[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:rr.title(r)}),jsx("p",{role:"status","aria-live":"polite",style:{...a.sheetHelper,...y?a.errorText:{}},children:y??rr.helper})]}),jsx("button",{type:"button",onClick:o,"aria-label":rr.close,style:a.iconButton,"data-testid":"fact-edit-close",children:jsx("span",{style:a.closeGlyph,"aria-hidden":"true",children:"\xD7"})})]}),jsx("label",{htmlFor:E,style:a.fieldLabel,children:e.label}),jsx("input",{id:E,style:a.field,value:d,onChange:g=>{s(g.target.value),u(null);},disabled:m,maxLength:512,"data-testid":"fact-edit-field"}),p?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:rr.confirmRemove}),jsxs("div",{style:{display:"flex",gap:l.space.sm},children:[jsx(U,{label:m?rr.removing:rr.removeConfirm,kind:"danger",busy:m,onClick:v,style:{flex:1},testID:"fact-edit-remove-confirm"}),jsx(U,{label:rr.keep,kind:"outline",disabled:m,onClick:()=>f(false),style:{flex:1},testID:"fact-edit-remove-cancel"})]})]}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:l.space.sm},children:[jsx(U,{label:m?rr.saving:rr.save,busy:m,disabled:!R,onClick:h,testID:"fact-edit-save"}),jsx("button",{type:"button","aria-label":rr.removeA11y(r),disabled:m,onClick:()=>{u(null),f(true);},style:{...a.pill,...a.pillLink,color:l.color.danger,...m?a.pillDisabled:{}},"data-testid":"fact-edit-remove",children:rr.remove})]})]})}i(Cy,"FactEditSheet");function zo({record:e,depth:r,petName:t,showLabs:o=true,onNavigate:n,onAsk:l,factEdit:a,nowMs:d}){let{theme:s,styles:c}=B(),u=d??Date.now(),p=useMemo(()=>a?da(e.entities,a.overlay):e.entities,[e.entities,a]),f=useMemo(()=>{let g=[],b=new Map;for(let S of p){let C=S.category.trim();if(C.length===0)continue;let _=b.get(C);_===void 0?(g.push(C),b.set(C,[S])):_.push(S);}return {order:rd(g),groups:b}},[p]),R=Object.values(e.documents),y=a!==void 0&&a.available,m=i((g,b,S)=>l?jsx("button",{type:"button",onClick:()=>{let C=g();l(C.prompt,C.entityRef);},"aria-label":b,style:{...c.pill,...c.pillAsk,marginTop:s.space.lg,alignSelf:"flex-start"},"data-testid":S,children:b}):null,"ask"),h={display:"flex",flexDirection:"column",gap:s.space.lg+s.space.xs},v=i(g=>({...c.row,...g>0?c.rowDivider:{}}),"rowStyle"),E={...c.card,padding:`${s.space.md}px ${s.space.lg}px`,display:"flex",flexDirection:"column"};return jsxs(Fragment,{children:[jsxs("div",{style:h,children:[r&&r.conflicts.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-conflicts",children:[jsx(qr,{title:W.needsAttention,count:r.conflicts.length}),[...r.conflicts].sort((g,b)=>xo(g.severity).rank-xo(b.severity).rank).map(g=>{let b=xo(g.severity),S=Kr(g.field??g.entityType);return jsxs("div",{style:{...E,borderColor:c.chipTones[b.tone].color,gap:s.space.sm},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.space.sm},children:[jsx("span",{style:{...c.rowTitle,...O(s,"bold"),flex:1},children:b.label}),jsx(cr,{label:S,tone:b.tone})]}),jsx("p",{style:c.rowDetail,children:W.conflictSub}),g.candidates.map((C,_)=>jsxs("div",{style:{borderTop:`1px solid ${s.color.borderHairlineGreen}`,paddingTop:s.space.sm},children:[jsx("p",{style:c.rowTitle,children:C.value}),jsx("p",{style:c.rowMuted,children:[C.docId?e.documents[C.docId]?.title??W.uploadedDocument:W.uploadedDocument,C.collectedAt?J(C.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},_)),m(()=>Bd(t,{scopeLabel:S,severity:g.severity,candidates:g.candidates.map(C=>({value:C.value,clinicName:C.docId?e.documents[C.docId]?.title??null:null}))},g.conflictId),W.askConflict,`records-ask-conflict-${g.conflictId}`)]},g.conflictId)})]}):null,r?.completeness?jsxs("section",{style:c.section,"data-testid":"record-section-completeness",children:[jsx(qr,{title:W.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:[[W.coverage.labs,r.completeness.hasLabHistory],[W.coverage.vaccines,r.completeness.hasVaccinationHistory],[W.coverage.weight,r.completeness.hasWeightHistory],[W.coverage.vitals,r.completeness.hasVitalsHistory],[W.coverage.exams,r.completeness.hasPhysicalExamHistory],[W.coverage.procedures,r.completeness.hasProcedureHistory],[W.coverage.genetics,r.completeness.hasGeneticHistory],[W.coverage.parasite,r.completeness.hasParasitePreventionHistory],[W.coverage.reproductive,r.completeness.hasReproductiveHistory]].map(([g,b])=>jsx("span",{"aria-label":`${g}: ${b?W.onFile:W.noneOnFile}`,style:{...c.chip,...b?c.chipTones.positive:{backgroundColor:s.color.badgeBgNeutral,color:s.color.text.muted},fontSize:s.type.size.caption},children:g},g))}),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:W.documentsOnFile(r.completeness.documentsIngested)}),r.completeness.documentsInReview>0?jsx(cr,{label:W.inReviewChip(r.completeness.documentsInReview),tone:"warning"}):null,ya(r.completeness.heldTotal,r.completeness.entitiesPendingReview)>0?jsx("span",{"aria-label":W.beingVerifiedA11y(ya(r.completeness.heldTotal,r.completeness.entitiesPendingReview)),children:jsx(cr,{label:W.beingVerified(ya(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:W.dateRange(r.completeness.earliestRecordAt,r.completeness.latestRecordAt)}):null,Object.entries(r.completeness.entitiesPendingReview).filter(([,g])=>g>0).length>0?jsxs("p",{style:{...c.rowMuted,paddingBottom:s.space.md},children:[W.pendingReview,Object.entries(r.completeness.entitiesPendingReview).filter(([,g])=>g>0).map(([g,b])=>`${qt(g)} (${b})`).join(", ")]}):null]})]}):null,R.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-documents",children:[jsx(qr,{title:W.documents,count:R.length}),jsx("ul",{style:c.card,children:R.map((g,b)=>{let S=g.title?.trim()||W.uploadedDocument,C=g.receivedAt?J(g.receivedAt):null,_=jsxs(Fragment,{children:[jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:S}),C?jsx("span",{style:{...c.rowDetail,display:"block"},children:C}):null]}),n?jsx(kt,{}):null]});return jsx("li",{style:v(b),children:n?jsx("button",{type:"button",onClick:()=>n({name:"contributions",docId:g.docId}),"aria-label":W.documentRowA11y(S),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-${g.docId}`,children:_}):_},g.docId)})})]}):null,e.identity.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-identity",children:[jsx(qr,{title:W.identity}),jsx("dl",{style:c.card,children:e.identity.map((g,b)=>jsxs("div",{style:v(b),children:[jsx("dt",{style:{...c.rowDetail,...O(s,"medium"),marginTop:0},children:g.label}),jsx("dd",{style:{...c.rowTitle,margin:0,textAlign:"right"},children:g.value})]},`${b}:${g.label}`))})]}):null,jsx(gd,{series:e.entitySeries}),e.forwardLooking.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-upcoming",children:[jsx(qr,{title:W.upcomingCare,count:e.forwardLooking.length}),jsx("ul",{style:c.card,children:e.forwardLooking.map((g,b)=>{let S=Tn(g.dueAt,u);return jsxs("li",{style:v(b),children:[jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:g.title}),g.detail?jsx("span",{style:{...c.rowDetail,display:"block"},children:g.detail}):null]}),S?jsx(cr,{label:S.label,tone:S.overdue?"critical":"info"}):null]},`${g.title}-${b}`)})}),m(()=>Md(t,e.forwardLooking.map(g=>{let b=Tn(g.dueAt,u);return {label:g.title,relativeText:b?.label??"",tone:b?.overdue?"overdue":"upcoming"}}),e.petRef),W.askUpcomingCare,"records-ask-upcoming-care")]}):null,f.order.map(g=>{let b=f.groups.get(g)??[];if(b.length===0)return null;let S=qt(g);return jsxs("section",{style:c.section,"data-testid":`record-section-${g}`,children:[jsx(qr,{title:S,count:b.length}),jsx("ul",{style:c.card,children:b.map((C,_)=>{let k=Id(C,{formatEntityValue:Ht,formatRecordsDate:J,humanize:Kr}),T=k.detail,I=jsxs("div",{style:v(_),children:[jsxs("div",{style:{...c.rowMain,display:"flex",flexDirection:"column"},children:[jsx("span",{style:c.rowTitle,children:k.title}),T?jsx("span",{style:c.rowDetail,children:T}):null,m(()=>zd(t,{entityTypeLabel:S,title:k.title,detail:T},g,C.key),W.askEverfur,`records-ask-entity-${C.key}`)]}),C.status?jsx(cr,{label:Kr(C.status)}):null]});return jsx("li",{children:y&&ca(C)&&a?jsx(Wd,{entity:C,factEdit:a,children:I}):I},C.key)})})]},g)}),r&&r.physicalExams.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-exams",children:[jsx(qr,{title:W.physicalExams,count:r.physicalExams.length}),r.physicalExams.map(g=>jsxs("div",{style:E,children:[jsx("h4",{style:{...c.rowTitle,paddingTop:s.space.sm},children:g.observedOn?J(g.observedOn):me.exam}),jsx("ul",{style:c.plainList,children:g.systems.map((b,S)=>{let C=b.findingStatus==="abnormal",_=C?me.abnormal:b.findingStatus==="not_examined"?me.notExamined:me.normal;return jsxs("li",{style:v(S),children:[jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:Gt(b.system)}),C&&b.finding?jsx("span",{style:{...c.rowDetail,display:"block"},children:b.finding}):null]}),jsx(cr,{label:_,tone:C?"warning":b.findingStatus==="not_examined"?"neutral":"positive"})]},b.system)})}),m(()=>$d(t,{observedOn:g.observedOn?J(g.observedOn):null,abnormal:g.systems.filter(b=>b.findingStatus==="abnormal").map(b=>({system:Gt(b.system),finding:b.finding??""}))},g.examId),W.askExam,`records-ask-exam-${g.examId}`)]},g.examId))]}):null,r&&r.clinicianNotes.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-notes",children:[jsx(qr,{title:W.visitNotes,count:r.clinicianNotes.length}),r.clinicianNotes.map(g=>jsxs("div",{style:E,children:[jsx("h4",{style:{...c.rowTitle,paddingTop:s.space.sm},children:g.observedOn?J(g.observedOn):me.visitNote}),jsx("dl",{style:c.plainList,children:g.sections.map((b,S)=>jsxs("div",{style:{padding:`${s.space.md}px 0`,...S>0?c.rowDivider:{}},children:[jsx("dt",{style:{...c.rowDetail,...O(s,"bold"),marginTop:0,textTransform:"uppercase"},children:Wt(b.section)}),jsx("dd",{style:{...c.bodyText,marginLeft:0,...b.text?{}:{color:s.color.text.muted,fontStyle:"italic"}},children:b.text||me.notRecorded})]},`${b.section}:${S}`))}),m(()=>Ud(t,{observedOn:g.observedOn?J(g.observedOn):null,sections:g.sections.map(b=>({label:Wt(b.section),text:b.text}))},g.noteId),W.askVisit,`records-ask-note-${g.noteId}`)]},g.noteId))]}):null,o&&r&&r.labResults.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-labs",children:[jsx(qr,{title:W.labResults,count:r.labResults.length}),jsx("ul",{style:c.card,children:r.labResults.map((g,b)=>{let S=Yr(g.latest.status),C=zi(g.latest.at,g.trajectory,g.points.length);return jsxs("li",{style:v(b),children:[jsxs("span",{style:{...c.rowMain,display:"flex",flexDirection:"column"},children:[jsx("span",{style:c.rowTitle,children:g.name}),jsx("span",{style:c.rowValue,children:ur(g.latest.value,g.latest.unit,g.latest.qualitativeResult)}),C?jsx("span",{style:c.rowDetail,children:C}):null]}),jsx(cr,{label:S.label,tone:qo(g.latest.status)})]},g.markerId)})})]}):null,r&&r.encounters.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-visits",children:[jsx(qr,{title:W.visits,count:r.encounters.length}),jsx("ul",{style:c.card,children:r.encounters.map((g,b)=>{let S=[g.date?J(g.date):null,g.clinicName,g.veterinarian].filter(C=>C&&C!=="-").join(" \xB7 ");return jsx("li",{style:v(b),children:jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:g.type?Kr(g.type):me.visit}),S?jsx("span",{style:{...c.rowDetail,display:"block"},children:S}):null]})},g.encounterId)})})]}):null]}),jsx(bt,{disclaimer:e.disclaimer})]})}i(zo,"RecordSections");function ya(e,r){return e>0?e:Object.values(r).reduce((t,o)=>t+o,0)}i(ya,"heldCount");function Xd({petRef:e,onClose:r,onNavigate:t,onOpenUrl:o,onCopy:n,returnFocusTo:l}){let{theme:a,styles:d}=B(),s=Zi(e),[c,u]=useState(null),[p,f]=useState(null),R=s.available&&!s.consentRequired,y=i((b,S)=>{if(o){Et(o,b,S).then(C=>{C.ok||u(se.toasts.shareSheet);});return}if(S==="share_link"){kd(b,n??Io).then(C=>{C==="copied"&&u(se.toasts.copied);},()=>u(se.toasts.shareSheet));return}on(b,Oo).then(C=>{C||u(_t(null,"download"));});},"open"),m=i(()=>{u(null),s.createLink().then(b=>{b.ok?y(b.value.shareUrl,"share_link"):u(_t(b.error,"create"));});},"onCreateLink"),h=i(()=>{u(null),s.pdfLink().then(b=>{b.ok?y(b.value.downloadUrl,"record_pdf"):u(_t(b.error,"download"));});},"onDownload"),v=i(b=>{b.shareUrl!==null&&Et(n??Io,b.shareUrl).then(S=>u(S.ok?se.toasts.copied:se.toasts.copyFailed));},"onCopyRow"),E=i(b=>{s.revoke(b).then(S=>{f(null),u(S.ok?se.toasts.turnedOff:_t(S.error,"revoke"));});},"onConfirmRevoke"),g={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 jsxs(Ct,{label:se.title,onClose:r,shape:"side",returnFocusTo:l,testID:"share-record-sheet",children:[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:se.title}),jsx("p",{style:d.sheetHelper,children:se.helper})]}),jsx("button",{type:"button",onClick:r,"aria-label":se.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(U,{label:se.viewDocument,onClick:()=>{r(),t({name:"document"});},testID:"share-view-document"}):null,R?jsx(U,{label:s.creating?se.creatingLink:se.createLink,kind:"outline",busy:s.creating,onClick:m,testID:"share-create-link"}):null,R?jsx(U,{label:s.preparingPdf?se.preparingPdf:se.downloadPdf,kind:"outline",busy:s.preparingPdf,onClick:h,testID:"share-download-pdf"}):null]}),s.consentRequired?jsxs("div",{style:g,"data-testid":"share-consent-off",children:[jsx("p",{style:d.rowTitle,children:se.consentOffTitle}),jsx("p",{style:d.muted,children:se.consentOffBody}),jsx(U,{label:se.retry,kind:"outline",onClick:s.refresh,testID:"share-consent-retry"})]}):null,c?jsx("p",{role:"status","aria-live":"polite",style:d.infoNote,"data-testid":"share-notice",children:c}):null,od(s)?jsxs("section",{"aria-label":se.activeLinks,style:{display:"flex",flexDirection:"column",gap:a.space.sm},children:[jsx("h4",{style:{...d.fieldLabel,...O(a,"bold"),textTransform:"uppercase"},children:se.activeLinks}),s.status==="loading"?jsx(El,{testID:"share-record-loading"}):s.status==="error"?jsxs("div",{style:g,"data-testid":"share-record-error",children:[jsx("p",{style:d.rowTitle,children:se.errorTitle}),jsx("p",{style:d.muted,children:se.errorBody}),jsx(U,{label:se.retry,kind:"outline",onClick:s.refresh,testID:"share-record-retry"})]}):s.rows.length===0?jsxs("div",{style:g,"data-testid":"share-record-empty",children:[jsx("p",{style:d.rowTitle,children:se.emptyTitle}),jsx("p",{style:d.muted,children:se.emptyBody})]}):jsx("ul",{style:{...d.plainList,gap:a.space.md},children:s.rows.map(b=>jsxs("li",{style:{...g},"data-testid":`share-row-${b.shareId}`,children:[jsxs("div",{"aria-label":b.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:b.active?a.color.success:a.color.text.muted}}),jsx("span",{style:{...d.rowTitle,...O(a,"bold")},children:b.statusLabel}),jsx("span",{style:d.muted,children:b.expiryLabel})]}),b.createdLabel?jsx("p",{style:d.muted,children:b.createdLabel}):null]}),p===b.shareId?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:a.space.sm},"data-testid":`share-revoke-confirm-${b.shareId}`,children:[jsx("p",{style:d.bodyText,children:se.confirmTurnOff}),jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:a.space.sm},children:[jsx(U,{label:s.revokingId===b.shareId?se.turningOff:se.turnOff,kind:"danger",busy:s.revokingId===b.shareId,onClick:()=>E(b.shareId),testID:`share-revoke-do-${b.shareId}`}),jsx(U,{label:se.keep,kind:"outline",disabled:s.revokingId===b.shareId,onClick:()=>f(null),testID:`share-revoke-cancel-${b.shareId}`})]})]}):jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:a.space.sm},children:[jsx(U,{label:se.copyLink,kind:"outline",disabled:b.shareUrl===null,ariaLabel:se.copyLinkA11y(b.actionContext),onClick:()=>v(b),testID:`share-copy-${b.shareId}`}),jsx(U,{label:se.turnOff,kind:"danger",ariaLabel:se.turnOffA11y(b.actionContext),onClick:()=>f(b.shareId),testID:`share-ask-revoke-${b.shareId}`})]})]},b.shareId))})]}):null]})}i(Xd,"ShareSheet");var wy=i((e,r)=>e.getRecordDepth(r),"readDepth"),ky=i(e=>!e.available,"depthEmpty");function Ln(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack","onAsk"]),{userRef:l}=ee(),{styles:a}=B();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"everfur-record-screen",children:[l===null?jsx("div",{style:a.body,children:jsx(Xe,{label:V.sessionRequired,glyph:"empty"})}):jsx(_y,{...n}),jsx(De,{})]})})}i(Ln,"EverfurRecordDetail");function _y({petRef:e,petName:r,controller:t,consentVersion:o,onNavigate:n,onBack:l,onAsk:a,onOpenUrl:d,onCopy:s}){let{theme:c,styles:u}=B(),p=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),f=Ge(p),R=zr(e,wy,ky),y=ua(e),m=ea(e),[h,v]=useState(false),E=useRef(null),g=tt(o,f.consent),b=i(()=>{let I=Hr(o,f.consent);I.length!==0&&f.grantConsent(I,`records-consent-${Date.now().toString(36)}`);},"onGrant"),S=R.value!==null&&!R.value.withheld&&R.value.available?R.value:null,C=f.record,_=i(()=>{f.refresh(),R.refresh();},"retry"),k=n!==void 0||m.lit===true,T;if(f.status==="loading"||R.status==="loading"&&C!==null&&!C.isEmpty)T=jsx(Yt,{testID:"everfur-record-loading"});else if(f.status==="error"){let I=Vr(f,g);T=I.kind==="error"||I.kind==="pet_not_found"?jsx(Fe,{variant:Qe(I.error),message:I.error.displayMessage,onAction:I.error.retryable?_:void 0,testID:"everfur-record-error"}):vt(f,b,g);}else if(C===null||C.isEmpty){let I=S?.completeness?.documentsInReview??0;T=jsxs("div",{style:u.content,"data-testid":"everfur-record-empty",children:[jsx(Fe,{variant:"no_records",message:I>0?W.inReview(I):void 0}),jsx(bt,{disclaimer:C?.disclaimer??""})]});}else T=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(zo,{record:C,depth:S,petName:r,onNavigate:n,onAsk:a,factEdit:y})});return jsxs(Fragment,{children:[jsx(He,{title:W.title,onBack:l,testID:"everfur-record-header",right:k||n?jsxs(Fragment,{children:[n?jsx("button",{type:"button",onClick:()=>n({name:"clinicBatch"}),"aria-label":W.requestClinicsA11y,style:u.iconButton,"data-testid":"everfur-record-request-clinics",children:jsx(Li,{name:"send",color:c.color.brand})}):null,k?jsx("button",{ref:E,type:"button",onClick:()=>v(true),"aria-label":W.shareA11y,style:u.iconButton,"data-testid":"everfur-record-share",children:jsx(Li,{name:"share2",color:c.color.brand})}):null]}):void 0}),jsx("div",{style:u.body,children:T}),h?jsx(Xd,{petRef:e,onClose:()=>v(false),returnFocusTo:E,onNavigate:n,...d?{onOpenUrl:d}:{},...s?{onCopy:s}:{}}):null]})}i(_y,"RecordBody");var $o=Object.freeze({download:"Download",downloadA11y:i(e=>`Download, ${e}`,"downloadA11y"),listA11y:"You added these records"});function Py(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(Py,"formatBytes");function Ty(e){let r=e?.trim();return r?r.toUpperCase():null}i(Ty,"formatLabel");function ga(e){return Object.freeze(e.map(r=>{let t=Ty(r.docFormat),o=r.receivedAt?J(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?Py(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(ga,"requestDocumentRows");function Zd(e){let r=e.fileName?.trim()||e.sourceDocId,t=e.docFormat?.trim().toLowerCase().replace(/^\./,"")??"";return t.length===0||r.toLowerCase().endsWith(`.${t}`)?r:`${r}.${t}`}i(Zd,"requestDocumentFileName");function Ra(e,r={}){let t=r.enabled??true,o=pr(),{userRef:n}=ee(),[l,a]=useState(null),[d,s]=useState(t),[c,u]=useState(null),p=useRef(0),f=useRef(true),R=useCallback(async()=>{let v=p.current+=1;if(!t||n===null){a(null),u(null),s(false);return}s(true),u(null);let E=await o.listRequestDocuments(e);v!==p.current||!f.current||(E.ok?a(E.value):(a(null),u(E.error)),s(false));},[o,t,e,n]);useEffect(()=>(f.current=true,R(),()=>{f.current=false,p.current+=1;}),[R]);let y=useMemo(()=>l===null?[]:ga(l),[l]),m=useCallback(()=>{R();},[R]),h=d?"loading":c!==null?"error":y.length===0?"empty":"populated";return useMemo(()=>({status:h,rows:y,error:c,refresh:m}),[h,y,c,m])}i(Ra,"useRequestDocuments");function Fn({requestId:e,open:r=true,onOpenUrl:t,testID:o="records-request-documents"}){let{theme:n,styles:l}=B(),a=Ra(e,{enabled:r}),d=pr(),[s,c]=useState(null),[u,p]=useState(null),f=useRef(true);useEffect(()=>(f.current=true,()=>{f.current=false;}),[]);let R=i(async y=>{c(y.key),p(null);let m=await d.listRequestDocuments(e),h=m.ok?m.value.find(E=>E.sourceDocId===y.key)??null:null,v=h===null;h!==null&&f.current&&(t?await Et(t,h.downloadUrl,"request_document"):v=!await on(h.downloadUrl,Zd(h))),f.current&&(c(null),v&&p(y.key));},"save");return r?a.status==="loading"?jsx("div",{style:{paddingTop:n.space.sm},"aria-busy":"true","data-testid":`${o}-loading`,children:jsx(fe,{width:"100%",height:n.space.lg+n.space.md})}):a.status==="error"?jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:n.space.sm,paddingTop:n.space.sm},"data-testid":`${o}-error`,children:[jsx("p",{style:{...l.muted,margin:0},role:"alert",children:a.error?.displayMessage??""}),a.error?.retryable===true?jsx(U,{label:V.retry,kind:"outline",onClick:a.refresh,testID:`${o}-retry`}):null]}):a.status==="empty"?null:jsx("ul",{"aria-label":$o.listA11y,style:{...l.plainList,paddingTop:n.space.sm},"data-testid":o,children:a.rows.map((y,m)=>jsxs("li",{style:Ay(n.space.sm,m===0?null:n.color.brandBorder),children:[jsxs("div",{style:{minWidth:0},children:[jsx("p",{style:{...l.rowTitle,margin:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y.title}),y.meta!==null?jsx("p",{style:{...l.muted,margin:0,fontVariantNumeric:"tabular-nums"},children:y.meta}):null]}),jsx(U,{label:$o.download,kind:"outline",ariaLabel:$o.downloadA11y(y.title),busy:s===y.key,onClick:()=>{R(y);},testID:`${o}-download-${y.key}`}),u===y.key?jsx("p",{role:"alert",style:{...l.errorText,flexBasis:"100%"},"data-testid":`${o}-save-failed-${y.key}`,children:fo.error.title}):null]},y.key))}):null}i(Fn,"RequestDocumentsList");function Ay(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(Ay,"rowStyle");var qy=Math.round(Br/(1024*1024)),Je=Object.freeze({title:i(e=>`Upload ${Pe(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 ${Pe(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 ${qy} 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 ${Math.min(e+1,r)} 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 zn(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack"]),{userRef:l}=ee(),{styles:a}=B();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"upload-screen",children:[l===null?jsx("div",{style:a.body,children:jsx(Xe,{label:V.sessionRequired,glyph:"empty"})}):jsx(Fy,{...n}),jsx(De,{})]})})}i(zn,"EverfurRecordsUpload");function Fy({petRef:e,petName:r,controller:t,onNavigate:o,onBack:n}){let{theme:l,styles:a}=B(),{runtime:d}=ee(),s=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),c=Ge(s),u=t!==void 0||Wn(d.registry.services.uploadTransport);return jsxs(Fragment,{children:[jsx(He,{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:Je.title(r)}),jsx("p",{style:{...a.muted,fontSize:l.type.size.body,maxWidth:340},children:Je.subtitle(r)})]}),jsx(Ea,{records:c,requestId:null,canUpload:u,onDone:o?p=>o({name:"request",requestId:p}):void 0})]})]})}i(Fy,"UploadBody");function Ea({records:e,requestId:r,canUpload:t,onDone:o}){let{theme:n,styles:l}=B(),a=useRef(null),d=`records-upload-format-hint-${r??"new"}`,[s,c]=useState(null),[u,p]=useState(0),[f,R]=useState(false),y=useRef(r),m=useRef([]),h=e.uploadQueue.filter(k=>k.status!=="skipped"),v=h.filter(k=>k.status==="done").length,E=h.filter(k=>k.status==="failed").length,g=!e.isUploading&&!f&&u>0,b=useCallback(async k=>{if(k.length!==0){c(null),R(true);try{let T=y.current;if(T===null){let q=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!q.ok){c(Je.errors.start);return}T=q.value.id,y.current=T;}p(q=>q+1);let I=await e.uploadDocuments(T,k);m.current=I.flatMap((q,L)=>q.status==="failed"&&k[L]!==void 0?[k[L]]:[]);}finally{R(false);}}},[e]),S=i(k=>{let T=Array.from(k.currentTarget.files??[]);k.currentTarget.value="",!(T.length===0||!t)&&(async()=>{let I=[];for(let q of T)I.push(await _o(q));if(I.length===1&&!na(I[0])){c(Je.errors.upload);return}await b(I);})();},"onChange"),C=i(()=>a.current?.click(),"pick"),_=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,...O(n,"bold"),fontSize:n.type.size.subtitle},children:Je.cardTitle}),jsx("p",{id:d,style:l.muted,children:Je.cardSubtitle}),jsx("input",{ref:a,type:"file",accept:ko,multiple:true,tabIndex:-1,"aria-hidden":"true",hidden:true,disabled:!t,onChange:S,"data-testid":"records-upload-input"}),s?jsx("p",{role:"alert",style:l.errorBanner,children:s}):null,jsx(xd,{records:e}),_?jsx("p",{style:l.muted,children:Je.uploading(v,h.length)}):g?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:n.space.sm},children:[v>0?jsx("p",{role:"status",style:l.bodyText,children:Je.received(v)}):null,E>0?jsx(U,{label:Je.retryFailed(E),kind:"link",ariaLabel:Je.retryFailedA11y(E),onClick:()=>{b(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(U,{label:Je.addMore,kind:"link",ariaLabel:Je.addMoreA11y,ariaDescribedBy:d,disabled:!t,onClick:C,testID:"records-upload-another"}),o&&y.current!==null&&v>0?jsx(U,{label:Je.done,ariaLabel:Je.doneA11y,onClick:()=>o(y.current),testID:"records-upload-done"}):null]})]}):jsx(U,{label:Je.chooseFiles,ariaLabel:Je.chooseFilesA11y,ariaDescribedBy:d,disabled:!t,onClick:C,testID:"records-upload-choose"})]})}i(Ea,"UploadRecordCard");function Mn(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack"]),{userRef:l}=ee(),{styles:a}=B();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"records-request-screen",children:[l===null?jsx("div",{style:a.body,children:jsx(Xe,{label:V.sessionRequired,glyph:"empty"})}):jsx(Uy,{...n}),jsx(De,{})]})})}i(Mn,"EverfurRecordsRequest");function Uy({petRef:e,requestId:r,controller:t,onNavigate:o,onBack:n,onOpenUrl:l,nowMs:a}){let{styles:d}=B(),{runtime:s,userRef:c,scopeEpoch:u}=ee(),p=Ge(t?{petRef:e,controller:t}:{petRef:e}),f=p.requests.find(m=>m.id===r)??null,R=t!==void 0||Wn(s.registry.services.uploadTransport),y;return p.status==="loading"?y=jsx(yo,{testID:"records-request-loading"}):p.status==="error"&&p.error?y=jsx(Fe,{variant:Qe(p.error),message:p.error.displayMessage,onAction:p.error.retryable?p.refresh:void 0,testID:"records-request-error"}):f===null?y=jsx(Fe,{variant:"no_requests",testID:"records-request-missing"}):y=jsx(By,{request:f,records:p,canUpload:R,onNavigate:o,onOpenUrl:l,nowMs:a},JSON.stringify([c,u,f.id])),jsxs(Fragment,{children:[jsx(He,{title:f?oo(f):"",onBack:n,testID:"records-request-header"}),jsx("div",{style:d.body,children:y})]})}i(Uy,"RequestBody");function By({request:e,records:r,canUpload:t,onNavigate:o,onOpenUrl:n,nowMs:l}){let{theme:a,styles:d}=B(),s=cd({request:e,onRecovered:r.refresh,canUpload:t},Ir()),[c,u]=useState(null),[p,f]=useState(false),[R,y]=useState(null),m=useRef(true);useEffect(()=>(m.current=true,()=>{m.current=false;}),[]);let h=s.request,v=l??Date.now(),E=h.status==="published",g=h.status==="published"||h.status==="failed"||h.status==="revoked",b=Oi(h),S=h.wireStatus==="clinic_responded_no_records",C=Vs(h,v),_=g?null:h.waitingExpectation?.trim()||null,k=io(h),T=s.error!==null&&c!==null?c==="revoke"?ue.errors.cancel:ue.errors[c]:null,I=i((K,re)=>{u(K),re();},"run"),q=i(()=>{p||(f(true),y(null),r.createRequest(`records-upload-${Date.now().toString(36)}`).then(K=>{if(m.current){if(f(false),!K.ok){y(ue.errors.start);return}o?.({name:"request",requestId:K.value.id});}}));},"startFresh"),L={display:"flex",flexDirection:"column",gap:a.space.sm},$=i(K=>jsx("p",{role:"alert",style:d.errorBanner,children:K}),"errorBanner"),Y=`records-failure-clinic-email-${h.id}`;return jsxs("div",{style:{...d.content,gap:a.space.lg+a.space.xs/2},"data-testid":`records-request-${h.id}`,children:[h.statusLabel.length>0||h.heldItemCount>0?jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:a.space.sm},"data-testid":"records-request-status-row",children:[h.statusLabel.length>0?jsx(cr,{label:h.statusLabel,tone:hs(h),testID:"records-request-status-chip"}):null,h.heldItemCount>0?jsx(cr,{label:gi(h.heldItemCount),tone:"neutral",testID:"records-request-held-count"}):null]}):null,h.status==="awaiting_upload"?jsx(Ea,{records:r,requestId:h.id,canUpload:t}):null,_&&!C?jsx("p",{style:d.infoNote,children:_}):h.wireStatus==="awaiting_response"&&!C?jsx("p",{style:d.infoNote,children:ue.awaitingNote}):null,C?jsx("p",{style:d.cautionNote,"data-testid":"records-request-waiting-banner",children:ue.waitingBanner(Di(h,v))}):null,E&&o?jsx(U,{label:ue.viewRecords,onClick:()=>o({name:"dashboard"}),testID:"records-request-view-dashboard"}):null,Gs(h)?jsxs("section",{style:{...L,gap:a.space.md,borderRadius:a.radius.lg-a.space.xs,padding:a.space.md+a.space.xs/2,backgroundColor:b?a.color.badgeBgCritical:a.color.badgeBgCaution},"data-testid":"records-failure-card",children:[jsx("p",{style:{...d.rowTitle,...O(a,"bold"),color:b?a.color.danger:a.color.warningStrong},children:Hs(h)}),h.canUpdateClinicEmail!==true&&h.canRetrySend!==true?jsx("p",{style:d.rowDetail,children:ue.nextStep}):null,h.canUpdateClinicEmail===true?jsxs("div",{style:L,children:[jsx("label",{htmlFor:Y,style:d.fieldLabel,children:$r.email}),jsx("input",{id:Y,type:"email",style:d.field,placeholder:$r.emailPlaceholder,autoComplete:"off",maxLength:320,value:s.email,disabled:s.busy,onChange:K=>s.setEmail(K.target.value),"data-testid":"records-failure-clinic-email"}),s.emailInvalid?jsx("p",{role:"alert",style:d.errorText,children:ue.errors.invalidEmail}):null,jsx(U,{label:$r.updateEmail,ariaLabel:$r.updateEmailA11y,disabled:!s.canUpdateEmail,busy:s.busy&&c==="email",onClick:()=>I("email",s.updateEmail),testID:"records-failure-update-email"})]}):null,h.canRetrySend===true?jsx(U,{label:$r.retry,kind:"outline",ariaLabel:$r.retryA11y,disabled:!s.canRetry,busy:s.busy&&c==="retry",onClick:()=>I("retry",s.retry),testID:"records-failure-retry-send"}):null,h.canRetrySend===true&&s.hasEmailEdit?jsx("p",{style:d.rowDetail,children:$r.retryHint}):null,T&&(c==="email"||c==="retry")?$(T):null]}):null,(b||S)&&o?jsx(U,{label:ue.tryAnotherClinic,kind:"outline",ariaLabel:ue.tryAnotherClinicA11y,onClick:()=>o({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,k!==null?jsxs("div",{style:L,children:[jsx(Sd,{call:k,prompt:h.statusLabel}),h.canRetrySend===true?jsx(U,{label:s.busy&&c==="retry"?ue.resending:ue.resend,kind:"outline",ariaLabel:s.busy&&c==="retry"?ue.resendingA11y:ue.resendA11y,disabled:!s.canRetry,onClick:()=>I("retry",s.retry),testID:"records-resend-authorization"}):null]}):null,s.canConvert?jsxs("div",{style:L,children:[jsx(U,{label:s.busy&&c==="convert"?ue.converting:ue.convert,busy:s.busy&&c==="convert",onClick:()=>I("convert",s.convert),testID:"records-convert-upload"}),jsx("p",{style:d.muted,children:ue.convertHint}),T&&c==="convert"?$(T):null]}):null,g&&!E?jsxs("div",{style:L,children:[jsx(U,{label:p?ue.freshUploadStarting:ue.freshUpload,kind:b||S?"outline":"primary",busy:p,onClick:q,testID:"records-upload-own-fresh"}),R?$(R):null]}):null,T&&c==="revoke"?$(T):null,h.canRevoke===true?s.confirmingRevoke?jsxs("div",{style:L,"data-testid":"records-revoke-confirm",children:[jsx("p",{style:{...d.rowTitle,...O(a,"bold"),fontSize:a.type.size.subtitle},children:$r.cancelQuestion}),jsx("p",{style:d.bodyText,children:$r.cancelConsequence}),jsx(U,{label:s.busy&&c==="revoke"?ue.cancelling:ue.cancel,kind:"danger",ariaLabel:s.busy&&c==="revoke"?ue.cancellingA11y:ue.cancelA11y,busy:s.busy&&c==="revoke",onClick:()=>I("revoke",s.revoke),testID:"records-revoke-do"}),jsx(U,{label:$r.keepRequest,kind:"outline",disabled:s.busy,onClick:s.keepRequest,testID:"records-revoke-keep"})]}):jsx(U,{label:ue.cancel,kind:"danger",ariaLabel:ue.cancelA11y,disabled:s.busy,onClick:s.askRevoke,testID:"records-revoke"}):null,jsx("div",{"aria-hidden":"true",style:{height:1,backgroundColor:a.color.borderHairlineGreen,margin:`${a.space.xs}px 0`}}),jsx(rn,{request:h}),qn(h)?jsx(Fn,{requestId:h.id,...n?{onOpenUrl:n}:{}}):null]})}i(By,"RequestDetail");function Un(e){return e.name==="request"||e.name==="clinicPicker"||e.name==="consent"||e.name==="clinicBatch"||e.name==="upload"}i(Un,"isOverlayScreen");function oc(e,r){if(r.type!=="closeOverlay")return yn(e,r);let t=e.stack.length;for(;t>1&&Un(e.stack[t-1]);)t-=1;return t===e.stack.length?e:Object.freeze({stack:Object.freeze(e.stack.slice(0,t))})}i(oc,"recordsPageNavReducer");function ic(e){let{stack:r}=e,t=r[r.length-1],o=Un(t)?t:null,n=r.length-1;for(;n>0&&Un(r[n]);)n-=1;let l=r[n],a=Un(l)?{name:"dashboard"}:l,d=o===null?null:r[r.length-2];return Object.freeze({body:a,overlay:o,overlayCanStepBack:d!=null&&Un(d),bodyCanGoBack:n>0})}i(ic,"splitRecordsPageNav");function ac(e){return {...e.petName!==void 0?{petName:e.petName}:{},...e.onOpenUrl?{onOpenUrl:e.onOpenUrl}:{},...e.onCopy?{onCopy:e.onCopy}:{},...e.onAsk?{onAsk:e.onAsk}:{},...e.location?{location:e.location}:{}}}i(ac,"seamsOf");function sc({screen:e,ctx:r,onBack:t}){let o={...ac(r),onNavigate:r.navigate,onBack:t},n={...r.controller?{controller:r.controller}:{},...r.consentVersion!==void 0?{consentVersion:r.consentVersion}:{}},l=Gy;switch(e.name){case "record":return jsx(Ln,{petRef:r.petRef,...o,...n,style:l});case "timeline":return jsx(vo,{petRef:r.petRef,...o,style:l});case "document":return jsx(Nn,{petRef:r.petRef,...o,...n,style:l});case "contributions":return jsx(Co,{petRef:r.petRef,docId:e.docId,...o,style:l});default:return Dr(e)}}i(sc,"RecordsPageBodyScreenView");function lc({screen:e,ctx:r,requests:t,onBack:o,onClose:n}){let l=jt(e),a=useMemo(()=>Vy(e,t),[e,t]),d=r.onAsk,s=d?{onAsk:i((R,y)=>{n(),d(R,y);},"onAsk")}:{},c={...ac(r),...s,onNavigate:r.navigate,onBack:o},u=r.clinicController?{controller:r.clinicController}:{},p=r.onCaptureSignature?{onCaptureSignature:r.onCaptureSignature}:{},f;switch(e.name){case "request":f=jsx(Mn,{petRef:r.petRef,requestId:e.requestId,...c,...r.controller?{controller:r.controller}:{},style:$n});break;case "clinicPicker":f=jsx(Cn,{petRef:r.petRef,...c,...u,...r.controller?{recordsController:r.controller}:{},style:$n});break;case "consent":f=jsx(Pn,{petRef:r.petRef,clinic:e.clinic,...c,...r.ownerName!==void 0?{ownerName:r.ownerName}:{},...p,...u,style:$n});break;case "clinicBatch":f=jsx(Sn,{petRef:r.petRef,petName:r.petName??"",ownerName:r.ownerName??"",onClose:o,onCreated:()=>r.navigate({name:"dashboard"}),...p,...u,style:$n});break;case "upload":f=jsx(zn,{petRef:r.petRef,...c,...r.controller?{controller:r.controller}:{},style:$n});break;default:f=Dr(e);}return jsx(Ct,{label:a,onClose:n,shape:"side",panelStyle:Wy,testID:"everfur-records-page-sheet",children:jsx("div",{ref:l,tabIndex:-1,style:Yy,children:f})})}i(lc,"RecordsPageOverlay");function Vy(e,r){if(e.name==="upload")return Se.uploadAction;if(e.name!=="request")return Se.requestRecords;let t=r.find(o=>o.id===e.requestId);return t?eo(t):Se.requestTimeline}i(Vy,"overlayLabel");var Gy=Object.freeze({height:"auto"}),Wy=Object.freeze({padding:0,gap:0}),Yy=Object.freeze({height:"100%",outline:"none"}),$n=Object.freeze({height:"100%"});function Uo({requests:e,petName:r,level:t,headingId:o,onOpenRequest:n,onUpload:l,onOpenUrl:a}){let{theme:d,styles:s}=B(),c=co(t),u=e.length>0;return jsxs("section",{"aria-labelledby":o,style:s.section,"data-testid":"everfur-records-page-requests",children:[jsxs("div",{style:s.sectionHeader,children:[jsx(c,{id:o,style:{...s.sectionTitle,color:d.color.brand},children:Se.requestsFor(r)}),u?jsx("span",{style:s.sectionCount,"data-testid":"everfur-records-page-requests-count",children:e.length}):null]}),u?jsx("ul",{style:{...s.plainList,gap:d.space.md},children:e.map(p=>{let f=eo(p);return jsxs("li",{style:s.creamCard,"data-testid":`everfur-records-page-request-${p.id}`,children:[jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:d.space.sm},children:[jsx("span",{style:{...s.rowTitle,fontSize:d.type.size.subtitle},children:f}),n?jsx(U,{label:Se.requestTimeline,kind:"outline",ariaLabel:Se.requestTimelineA11y(f),onClick:()=>n(p),testID:`everfur-records-page-open-${p.id}`}):null]}),jsx(rn,{request:p}),qn(p)?jsx(Fn,{requestId:p.id,...a?{onOpenUrl:a}:{}}):null]},p.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:Se.uploadPromptTitle(r)}),jsx("p",{style:s.bodyText,children:Se.uploadPromptBody}),l?jsx(U,{label:Se.uploadAction,onClick:l,testID:"everfur-records-page-upload"}):null]})]})}i(Uo,"RecordsPageRequests");var rg=1248,tg=Object.freeze({height:"auto"}),Bo=Object.freeze({overflowY:"visible",flex:"0 0 auto"});function ng(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack","onAsk"]),{userRef:l}=ee(),{styles:a}=B();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...tg,...r},"data-testid":"everfur-records-page",children:[l===null?jsx("div",{style:{...a.body,...Bo},children:jsx(Xe,{label:V.sessionRequired,glyph:"empty"})}):jsx(og,{...n}),jsx(De,{})]})})}i(ng,"EverfurRecordsPage");function og(e){let{petRef:r,petName:t,controller:o,clinicController:n,consentVersion:l,ownerName:a,onCaptureSignature:d,onNavigate:s,onOpenUrl:c,onCopy:u,onAsk:p,location:f}=e,[R,y]=useReducer(oc,void 0,()=>Ut()),m=useCallback(q=>{s?s(q):y({type:"navigate",screen:q});},[s]),{body:h,overlay:v,overlayCanStepBack:E,bodyCanGoBack:g}=ic(R),b=useMemo(()=>o?{petRef:r,controller:o}:{petRef:r},[r,o]),S=Ge(b),{refresh:C}=S,_=useRef(false);useEffect(()=>{v!==null?_.current=true:_.current&&(_.current=false,C());},[v,C]);let k=jt(h),T={petRef:r,petName:t,controller:o,clinicController:n,consentVersion:l,ownerName:a,onCaptureSignature:d,navigate:m,...c?{onOpenUrl:c}:{},...u?{onCopy:u}:{},...p?{onAsk:p}:{},...f?{location:f}:{}},I=h.name==="dashboard"||h.name==="requests";return jsxs(Fragment,{children:[jsx("div",{ref:k,tabIndex:-1,style:ig,children:I?jsx(ag,{...e,records:S,navigate:m}):jsx(sc,{screen:h,ctx:T,onBack:g?()=>y({type:"pop"}):()=>m({name:"dashboard"})})}),v!==null?jsx(lc,{screen:v,ctx:T,requests:S.requests,onBack:E?()=>y({type:"pop"}):()=>y({type:"closeOverlay"}),onClose:()=>y({type:"closeOverlay"})}):null]})}i(og,"RecordsPageBody");var ig=Object.freeze({outline:"none"});function ag({petRef:e,petName:r,consentVersion:t,onAsk:o,onOpenUrl:n,headingLevel:l,records:a,navigate:d}){let{theme:s,styles:c}=B(),u=St("recordsClinic"),p=u.enabled||u.isPending,f=Fs(l??lo),R=co(f),y=`${useId()}-requests-heading`,m=tt(t,a.consent),h=i(()=>{let E=Hr(t,a.consent);E.length!==0&&a.grantConsent(E,`records-consent-${Date.now().toString(36)}`);},"onGrant"),v={boxSizing:"border-box",width:"100%",maxWidth:rg,margin:"0 auto",display:"flex",flexDirection:"column",gap:s.space.lg+s.space.xs,padding:`${s.space.lg}px ${s.space.lg}px ${s.space.xxl}px`};if(a.status==="loading")return jsx("div",{style:{...c.body,...Bo},children:jsx("div",{style:v,children:jsx(Yt,{testID:"everfur-records-page-loading"})})});if(a.status==="error"){let E=Vr(a,m),g=E.kind==="error"||E.kind==="pet_not_found"?jsx(Fe,{variant:Qe(E.error),message:E.error.displayMessage,onAction:E.error.retryable?()=>a.refresh():void 0,testID:"everfur-records-page-error"}):vt(a,h,m);return jsx("div",{style:{...c.body,...Bo},children:jsx("div",{style:v,children:g})})}return jsx("div",{style:{...c.body,...Bo},children:jsxs("div",{style:v,"data-testid":"everfur-records-page-content",children:[jsxs("header",{style:{...c.creamCard,gap:s.space.md,padding:`${s.space.lg+s.space.xs}px ${s.space.lg+s.space.md}px`},"data-testid":"everfur-records-page-header",children:[jsx(R,{tabIndex:-1,[Rn]:"",style:{...c.headerTitle,whiteSpace:"normal",overflow:"visible"},children:Se.title}),jsx("p",{style:c.bodyText,children:Se.lead}),jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:s.space.sm},"data-testid":"everfur-records-page-actions",children:[p?jsx(U,{label:Se.requestRecords,onClick:()=>d({name:"clinicPicker"}),testID:"everfur-records-page-request-records"}):null,jsx(U,{label:Se.uploadAction,kind:"outline",onClick:()=>d({name:"upload"}),testID:"everfur-records-page-upload-action"}),o?jsx(U,{label:Se.askA11y(r),kind:"ask",ariaLabel:Se.askA11y(r),onClick:()=>o(fs(r),{type:"marker_summary",id:e}),testID:"everfur-records-page-ask"}):null]}),jsxs("nav",{style:{display:"flex",flexWrap:"wrap",columnGap:s.space.lg,rowGap:s.space.xs},"data-testid":"everfur-records-page-links",children:[jsx(dc,{label:Se.viewRecord,onClick:()=>d({name:"record"}),testID:"everfur-records-page-link-record"}),jsx(dc,{label:Se.viewTimeline,onClick:()=>d({name:"timeline"}),testID:"everfur-records-page-link-timeline"})]})]}),jsx(Uo,{requests:a.requests,petName:r,level:_i(f),headingId:y,onOpenRequest:E=>d({name:"request",requestId:E.id}),onUpload:()=>d({name:"upload"}),...n?{onOpenUrl:n}:{}})]})})}i(ag,"RecordsPageContent");function dc({label:e,onClick:r,testID:t}){let{theme:o,styles:n}=B();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(dc,"PageLink");var br=200,Sa=16,wa=(br-Sa)/2,cc=2*Math.PI*wa;function pc({summary:e,onAsk:r,testID:t}){let o=lg(),{theme:n,styles:l}=B(),{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}],R=0;return f.filter(y=>y.count>0).map(y=>{let m=y.count/u*cc,h=-R;return R+=m,{key:y.key,color:y.color,length:m,offset:h}})},[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:br,height:br,viewBox:`0 0 ${br} ${br}`,"aria-hidden":"true",focusable:"false",children:[jsx("circle",{cx:br/2,cy:br/2,r:wa,stroke:n.color.surfaceSubtle,strokeWidth:Sa,fill:"none"}),jsx("g",{transform:`rotate(-90 ${br/2} ${br/2})`,children:p.map(f=>jsx("circle",{cx:br/2,cy:br/2,r:wa,stroke:f.color,strokeWidth:Sa,fill:"none",strokeDasharray:`${f.length} ${cc}`,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(pc,"MarkerSummaryCard");function lg(){let e=ce();return useMemo(()=>dg(e),[e])}i(lg,"useStyles");function dg(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,...O(e,"bold"),fontSize:n.size.body,color:r.brand,letterSpacing:n.letterSpacing.headerBrand},ringRow:{display:"flex",justifyContent:"center"},ringWrap:{position:"relative",width:br,height:br},center:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",pointerEvents:"none"},centerCount:{...O(e,"medium"),fontSize:n.size.verdict*2,lineHeight:1.1,color:r.text.primary},centerLabel:{...O(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`,...O(e,"mono"),fontSize:n.size.nano,lineHeight:`${n.size.tiny}px`,textTransform:"uppercase",letterSpacing:n.letterSpacing.headerBrand/2},subtitle:{margin:0,...O(e,"regular"),fontSize:n.size.caption,lineHeight:`${Math.round(n.size.caption*n.lineHeight.relaxed)}px`,color:r.text.primary}}}i(dg,"makeStyles");function cg(e){return e.value!==null&&Number.isFinite(e.value)}i(cg,"numeric");function mc(e){let r=e.points.filter(cg);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(v=>v.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(v=>(u-v)/p*100,"y"),R=6,y=r.length,m=r.map((v,E)=>({index:E,xPct:y<=1?50:R+E/(y-1)*(100-2*R),yPct:f(v.value),status:v.status,point:v})),h=o!==null||n!==null?{topPct:n!==null?f(n):0,bottomPct:o!==null?f(o):100}:null;return {points:m,band:h,firstDate:r[0]?.at??null,lastDate:r[r.length-1]?.at??null}}i(mc,"buildMarkerChart");var fc=100,jo=44;function pg({marker:e,onPointPress:r,onAsk:t}){let o=ka(),{theme:n,styles:l}=B(),a=Yr(e.latest?.status??null),d=Vt(e.trajectory,e.points.length),s=useMemo(()=>mc(e),[e]),c=e.latest?ur(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":rt.status(a.label),children:jsx(cr,{label:a.label,tone:qo(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":rt.latestA11y(c,a.label,J(e.latest.at)),children:c}),jsx("span",{style:o.latestDate,children:J(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 ${fc} ${jo}`,preserveAspectRatio:"none",style:o.plot,"aria-hidden":"true",focusable:"false",children:[s.band?jsx("rect",{x:0,y:s.band.topPct/100*jo,width:fc,height:Math.max(0,(s.band.bottomPct-s.band.topPct)/100*jo),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*jo}`).join(" ")}):null]}),jsx("div",{style:o.dotLayer,children:s.points.map(u=>jsx("button",{type:"button",onClick:()=>r(e,u.point),"aria-label":pa(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":rt.readingsA11y(e.name),style:o.a11yTable,children:e.points.map((u,p)=>jsx("li",{children:pa(e,u)},p))}),jsx("p",{style:e.points.length===1?o.singleHint:o.tapHint,children:e.points.length===1?rt.singleHint:rt.tapHint})]}):jsx("p",{style:o.emptyBody,children:rt.empty}),t?jsx("button",{type:"button",onClick:()=>t(e),"aria-label":rt.askA11y(e.name),style:{...l.pill,...l.pillAsk},"data-testid":`marker-ask-${e.markerId}`,children:rt.ask}):null]})})}i(pg,"MarkerTrendCard");function gc({markers:e,onPointPress:r,onAsk:t}){let o=ka(),[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(pg,{marker:s,onPointPress:r,onAsk:t},s.markerId))}),jsxs("div",{style:o.footer,"aria-label":ci.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:ci.counter(n,e.length)})]})]})}i(gc,"MarkerTrendCarousel");function bc({marker:e,point:r,onClose:t,onAsk:o}){let n=ka(),{styles:l}=B();if(e===null||r===null)return null;let a=i((d,s)=>jsxs("div",{style:n.detailRow,children:[jsx("dt",{style:n.detailLabel,children:d}),jsx("dd",{style:n.detailValue,children:s})]},d),"row");return jsxs(Ct,{label:dr.title,onClose:t,panelStyle:n.sheetBg,testID:"marker-provenance-sheet",children:[jsxs("div",{style:l.sheetHeader,children:[jsx("h3",{style:l.sheetTitle,children:dr.title}),jsx("button",{type:"button",onClick:t,"aria-label":dr.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:ur(r.value,e.unit,r.qualitativeResult)})]}),r.reviewed?jsx("span",{style:n.reviewed,children:dr.reviewed}):null,jsxs("dl",{style:n.details,children:[a(dr.collected,J(r.at)),r.sourceClinic?a(dr.clinic,r.sourceClinic):null,a(dr.referenceRange,r.refLow!==null||r.refHigh!==null?No(r,e.unit):dr.noRange),r.docId?a(dr.sourceDocument,r.docId):null]}),r.reviewed?null:jsx("p",{style:n.unverified,children:dr.unverified}),o?jsx("button",{type:"button",onClick:o,"aria-label":dr.askA11y,style:{...l.pill,...l.pillAsk},"data-testid":"marker-provenance-ask",children:dr.ask}):null]})}i(bc,"MarkerProvenanceDialog");function ka(){let e=ce();return useMemo(()=>mg(e),[e])}i(ka,"useStyles");function mg(e){let{color:r,space:t,radius:o,type:n}=e,l=i((d,s,c,u="regular")=>({margin:0,...O(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:{...O(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:{...O(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(mg,"makeStyles");var bg=i((e,r)=>e.getRecordDepth(r),"readDepth"),Rg=i(e=>!e.available,"depthEmpty");function Pa(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack","onAsk"]),{userRef:l}=ee(),{styles:a}=B();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"records-dashboard",children:[l===null?jsx("div",{style:a.body,children:jsx(Xe,{label:V.sessionRequired,glyph:"empty"})}):jsx(hg,{...n}),jsx(De,{})]})})}i(Pa,"EverfurRecordsDashboard");function hg({petRef:e,petName:r,controller:t,consentVersion:o,onNavigate:n,onBack:l,onAsk:a}){let{theme:d,styles:s}=B(),c=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),u=Ge(c),p=Qi(e),f=zr(e,bg,Rg),[R,y]=useState(null),m=useCallback((x,A)=>y({marker:x,point:A}),[]),h=tt(o,u.consent),v=i(()=>{let x=Hr(o,u.consent);x.length!==0&&u.grantConsent(x,`records-consent-${Date.now().toString(36)}`);},"onGrant"),E=p.markers?.markers??[],g=E.length>0,b=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,S=ro(u.requests,e),C=ui({hasMarkers:g,requests:u.requests,petRef:e}),_=pi({recordLoading:u.status==="loading",hasFullRecord:b,recordError:u.status==="error",markersLoading:p.status==="loading",markersError:p.status==="error",hasMarkers:g,requestsLoading:u.status==="loading",dashboardState:C,drivingRequest:S}),k=p.markers?.disclaimer??u.record?.disclaimer??"",T=i(()=>{u.refresh(),p.refresh(),f.refresh();},"retryAll"),I=f.value!==null&&!f.value.withheld&&f.value.available?f.value:null,q=Pe(r),L=a&&p.markers?.summary?()=>{let x=Nd(r,p.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);a(x.prompt,x.entityRef);}:void 0,$=a?x=>{let A=qd(r,{canonicalName:x.name,markerId:x.markerId,latestValueText:x.latest?ur(x.latest.value,x.unit,x.latest.qualitativeResult):null,statusText:x.latest?Yr(x.latest.status).label:null,trajectoryText:Vt(x.trajectory,x.points.length),meaningText:x.meaning});a(A.prompt,A.entityRef);}:void 0,Y=a&&R?()=>{let{marker:x,point:A}=R,D=Ld(r,{canonicalName:x.name,valueText:ur(A.value,x.unit,A.qualitativeResult),collectedAt:J(A.at),sourceClinic:A.sourceClinic,referenceText:A.refLow!==null||A.refHigh!==null?No(A,x.unit):null,flagged:A.status==="above"?"above":A.status==="below"?"below":null,reviewed:A.reviewed,entityId:A.docId??x.markerId});y(null),a(D.prompt,D.entityRef);}:void 0,K=i((x,A,D)=>jsxs("button",{type:"button",onClick:A,"aria-label":x,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":D,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:x})]}),jsx(kt,{})]}),"actionRow"),re=jsxs(Fragment,{children:[p.markers?.summary?jsx("div",{style:s.inset,children:jsx(pc,{summary:p.markers.summary,onAsk:L,testID:"dashboard-marker-summary"})}):null,jsx("p",{style:s.lead,children:lr.lead(r)}),jsx(gc,{markers:E,onPointPress:m,onAsk:$})]}),Q=i(x=>n?jsxs("div",{style:{...s.inset,display:"flex",flexDirection:"column",gap:d.space.sm+d.space.xs/2},children:[x?K(lr.viewFullRecord,()=>n({name:"record"}),"dashboard-full-record-action"):null,K(lr.viewTimeline,()=>n({name:"timeline"}),"dashboard-timeline-action")]}):null,"actions"),w;if(u.status==="error"){let x=Vr(u,h);w=x.kind==="error"||x.kind==="pet_not_found"?jsx(Fe,{variant:Qe(x.error),message:x.error.displayMessage,onAction:x.error.retryable?T:void 0,testID:"dashboard-error"}):vt(u,v,h);}else switch(_){case "loading":w=jsx(Yt,{testID:"dashboard-loading"});break;case "record":w=jsxs("div",{style:s.contentTight,"data-testid":"dashboard-record",children:[g?re:p.status==="error"?jsx("div",{style:s.inset,children:K(lr.retryMarkers,T,"dashboard-markers-retry")}):null,jsx("div",{style:s.inset,children:u.record?jsx(zo,{record:u.record,depth:I,petName:r,showLabs:!g,onNavigate:n,onAsk:a}):null}),Q(true)]});break;case "error":{let x=p.error??u.error;w=jsx(Fe,{variant:Qe(x),message:x?.displayMessage,onAction:x?.retryable?T:void 0,testID:"dashboard-error"});break}case "in_progress":w=jsxs("div",{style:s.content,"data-testid":"dashboard-in-progress",children:[S?jsx(vg,{request:S,petName:q,onOpen:n?()=>n({name:"request",requestId:S.id}):void 0,onAsk:a?()=>{let x=Fd(r,{clinicName:S.clinicName??null,statusLabel:gn(S),status:S.status,heldItemCount:S.heldItemCount},S.id);a(x.prompt,x.entityRef);}:void 0}):null,jsx(bt,{disclaimer:k})]});break;case "none":w=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:xt.title(r)}),jsx("p",{style:s.bodyText,children:xt.body}),n?jsxs(Fragment,{children:[jsx(U,{label:xt.requestFromClinic,ariaLabel:xt.requestFromClinicA11y(r),onClick:()=>n({name:"clinicPicker"}),testID:"dashboard-request-prompt-clinic"}),jsx(U,{label:xt.uploadDocument,kind:"outline",ariaLabel:xt.uploadDocumentA11y(r),onClick:()=>n({name:"upload"}),testID:"dashboard-request-prompt-upload"})]}):null]}),jsx(bt,{disclaimer:k})]});break;case "labs_only":w=jsxs("div",{style:s.contentTight,"data-testid":"dashboard-labs-only",children:[re,jsx("div",{style:s.inset,children:jsx(bt,{disclaimer:k})}),Q(false)]});break;default:w=Dr(_);}return jsxs(Fragment,{children:[jsx(He,{title:lr.title,onBack:l,testID:"dashboard-header",right:n?jsx("button",{type:"button",onClick:()=>n({name:"timeline"}),"aria-label":lr.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(x=>jsx("span",{style:{display:"block",width:18,height:2,borderRadius:2,backgroundColor:d.color.brand}},x))})}):void 0}),jsx("div",{style:s.body,children:w}),jsx(bc,{marker:R?.marker??null,point:R?.point??null,onClose:()=>y(null),onAsk:Y})]})}i(hg,"DashboardBody");function vg({request:e,petName:r,onOpen:t,onAsk:o}){let{theme:n,styles:l}=B(),a=e.clinicName?.trim()||$t.title(r),d=gn(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,...O(n,"bold"),fontSize:n.type.size.subtitle},children:a}),t?jsx(kt,{}):null]}),jsx(rn,{request:e}),d.length>0?jsx("p",{style:l.statusCard,children:d}):null]});return jsxs("section",{"aria-label":t?void 0:$t.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":$t.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(U,{label:$t.ask,kind:"ask",ariaLabel:$t.askA11y,onClick:o,testID:"dashboard-in-progress-ask"}):null]})}i(vg,"InProgressCard");function Ta(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack"]),{userRef:l}=ee(),{styles:a}=B();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"records-requests-screen",children:[l===null?jsx("div",{style:a.body,children:jsx(Xe,{label:V.sessionRequired,glyph:"empty"})}):jsx(xg,{...n}),jsx(De,{})]})})}i(Ta,"EverfurRecordsRequests");function xg({petRef:e,petName:r,controller:t,onNavigate:o,onBack:n,onOpenUrl:l}){let{theme:a,styles:d}=B(),s=Ge(t?{petRef:e,controller:t}:{petRef:e}),c=useMemo(()=>bi(s.requests.filter(R=>R.petRef===e)),[s.requests,e]),u=St("recordsClinic"),p=`${useId()}-requests-heading`,f;return s.status==="loading"&&c.length===0?f=jsx(yo,{testID:"records-requests-loading"}):s.status==="error"&&s.error&&c.length===0?f=jsx(Fe,{variant:Qe(s.error),message:s.error.displayMessage,onAction:s.error.retryable?s.refresh:void 0,testID:"records-requests-error"}):f=jsx(Uo,{requests:c,petName:r,level:3,headingId:p,onOpenRequest:o?R=>o({name:"request",requestId:R.id}):void 0,onUpload:o?()=>o({name:"upload"}):void 0,...l?{onOpenUrl:l}:{}}),jsxs(Fragment,{children:[jsx(He,{title:Se.title,onBack:n,testID:"records-requests-header"}),jsx("div",{style:d.body,children:jsxs("div",{style:{...d.content,gap:a.space.lg},children:[o?jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:a.space.sm},"data-testid":"records-requests-actions",children:[u.enabled||u.isPending?jsx(U,{label:Se.requestRecords,onClick:()=>o({name:"clinicPicker"}),testID:"records-requests-request-records"}):null,jsx(U,{label:Se.uploadAction,kind:"outline",onClick:()=>o({name:"upload"}),testID:"records-requests-upload"})]}):null,f]})})]})}i(xg,"RequestsBody");function hc(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:R,onOpenUrl:y,onCopy:m,onAsk:h,location:v}=_e(e,["onExit"]),[E,g]=useReducer(yn,s,Ut),b=to(E),S=E.stack.length,C=useRef(S);C.current=S;let _=useRef(S),k=useRef(false);useEffect(()=>{if(c!=="browser"||typeof window>"u")return;let Q=i(w=>{let x=w.state;(typeof x?.efRecords=="number"?x.efRecords:1)<C.current&&(k.current=true,g({type:"pop"}));},"onPopState");return window.addEventListener("popstate",Q),()=>window.removeEventListener("popstate",Q)},[c]),useEffect(()=>{if(c!=="browser"||typeof window>"u")return;let Q=_.current;S>Q?window.history.pushState({efRecords:S},""):S<Q&&!k.current&&window.history.go(S-Q),k.current=false,_.current=S;},[c,S]);let T=useCallback(Q=>g({type:"navigate",screen:Q}),[]),I=useMemo(()=>no(E).handled?()=>g({type:"pop"}):u,[E,u]),q=jt(b),L={onNavigate:T,...I?{onBack:I}:{},...t!==void 0?{petName:t}:{},...y?{onOpenUrl:y}:{},...m?{onCopy:m}:{},...h?{onAsk:h}:{},...v?{location:v}:{}},$={...o?{controller:o}:{},...l!==void 0?{consentVersion:l}:{}},Y={...p?{style:p}:{},...f!==void 0?{className:f}:{}},K=R?{renderPending:R}:{},re;switch(b.name){case "dashboard":re=jsx(Pa,{petRef:r,...L,...$,...K,...Y});break;case "request":re=jsx(Mn,{petRef:r,requestId:b.requestId,...L,...o?{controller:o}:{},...K,...Y});break;case "timeline":re=jsx(vo,{petRef:r,...L,...Y});break;case "record":re=jsx(Ln,{petRef:r,...L,...$,...K,...Y});break;case "document":re=jsx(Nn,{petRef:r,...L,...$,...K,...Y});break;case "contributions":re=jsx(Co,{petRef:r,docId:b.docId,...L,...Y});break;case "clinicPicker":re=jsx(Cn,{petRef:r,...L,...n?{controller:n}:{},...o?{recordsController:o}:{},...Y});break;case "clinicBatch":re=jsx(Sn,{petRef:r,petName:t??"",ownerName:a??"",...I?{onClose:I}:{},onCreated:()=>g({type:"navigate",screen:{name:"dashboard"}}),...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},...Y});break;case "consent":re=jsx(Pn,{petRef:r,clinic:b.clinic,...L,...a!==void 0?{ownerName:a}:{},...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},...Y});break;case "upload":re=jsx(zn,{petRef:r,...L,...o?{controller:o}:{},...K,...Y});break;case "requests":re=jsx(Ta,{petRef:r,...L,...o?{controller:o}:{},...K,...Y});break;default:re=Dr(b);}return jsx("div",{ref:q,style:Pg,"data-testid":"everfur-records-flow",children:re})}i(hc,"EverfurRecordsFlow");var Pg=Object.freeze({display:"contents"}),Tg=hc;function Dg(e){let{userRef:r,scopeEpoch:t}=ee();return jsx(Te,{capability:"recordsClinic",...Oe(e.onClose,X.cancel),children:r===null?jsx("p",{role:"alert",children:V.sessionRequired}):jsx(Og,{..._e(e,["onClose","onCreated"])},JSON.stringify([r,t,e.petRef,e.petName]))})}i(Dg,"EverfurClinicRequest");function Og(e){let r=Ir(),t=e.controller??r,o=ce(),n={current:null},l=Ot(()=>n.current?.invalidate()),a=xl(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":X.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:X.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||V.records}):jsxs("div",{style:{display:"grid",gap:o.space.md},children:[jsxs("label",{children:[X.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:[X.clinic,jsx("input",{style:{...d,display:"block",width:"100%",boxSizing:"border-box"},placeholder:X.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:X.search}),a.searching&&jsx("p",{role:"status",children:V.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:X.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:[X.email,jsx("input",{style:{...d,display:"block",width:"100%",boxSizing:"border-box"},type:"email",placeholder:X.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:X.scopeHeading}),a.copy?jsx("p",{style:{whiteSpace:"pre-wrap",margin:0},children:a.query.trim()&&a.ownerName.trim()?a.scope??z("internalError").displayMessage:V.consentRequired}):!a.error&&jsx("p",{role:"status",children:V.loading}),!e.onCaptureSignature&&jsx(It,{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:V.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?X.sending:X.send})]}),e.onClose&&jsx("button",{type:"button",style:s,disabled:a.busy,onClick:e.onClose,children:X.cancel}),jsx(De,{})]})}i(Og,"ClinicRequestBody");var Ig="file",Ag="document.pdf",qg="records upload: the file handle carries no bytes",vc="records upload failed";function Ng(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(qg));return}let{signal:s,onProgress:c}=n;if(s?.aborted===true){a(new Error(vc));return}let u=new FormData;for(let[m,h]of Object.entries(t.upload_fields))u.append(m,h);u.append(Ig,d,Ag);let p=r(),f=false,R=i(m=>{f||(f=true,s?.removeEventListener("abort",y),m?l():a(new Error(vc)));},"settle"),y=i(()=>{p.abort(),R(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=()=>R(p.status>=200&&p.status<300),p.onerror=()=>R(false),p.onabort=()=>R(false),p.ontimeout=()=>R(false),s?.addEventListener("abort",y,{once:true}),p.send(u);})}})}i(Ng,"createWebRecordsUploadTransport");
4
- export{Cn as EverfurClinicPicker,Dg as EverfurClinicRequest,Sn as EverfurClinicRequestBatch,Ln as EverfurRecordDetail,Nn as EverfurRecordDocument,Tg as EverfurRecords,Pn as EverfurRecordsConsent,Pa as EverfurRecordsDashboard,hc as EverfurRecordsFlow,ng as EverfurRecordsPage,Mn as EverfurRecordsRequest,Ta as EverfurRecordsRequests,zn as EverfurRecordsUpload,Bt as RECORDS_CLINIC_BATCH_MAX,ko as RECORDS_DOCUMENT_ACCEPT,Ka as RECORDS_TERMINAL,An as REQUEST_TIMELINE_TITLES,Fn as RequestDocumentsList,It as SignatureCanvas,da as applyFactOverlay,aa as buildRequestTimeline,Ng as createWebRecordsUploadTransport,to as currentRecordsScreen,ui as deriveRecordsDashboardState,_o as fileToHandle,Ut as initialRecordsNav,ca as isFactEditable,dd as isPdfBlob,Mt as isTerminalStatus,na as isUploadableHandle,cf as pickDocument,ro as pickPetRecordsRequest,no as popRecordsNav,mi as pushRecordsNav,dt as recordsDenialReasonOf,yn as recordsNavReducer,fi as replaceRecordsNav,ga as requestDocumentRows,yi as resetRecordsNav,io as selectClinicCall,pi as selectDashboardView,gn as selectPrimaryLabel,bi as selectRequestList,oo as selectRequestTitle,bs as transitionRecordsNav,Ge as useEverfurRecords,Ir as useEverfurRecordsClinic,qi as useEverfurRecordsClinicBatch,ua as useRecordFactEdit,ra as useRecordPdfLink,Zi as useRecordShares,Qi as useRecordsMarkers,Ra as useRequestDocuments,Ot as useSignatureCanvas};
3
+ `):null,Ae=b.length>0&&b.every(U=>!Qt(U)||Zp.test(U.email.trim())),oe=b.length>=Bt,ve=!!(m&&de&&l.trim()&&e.petName.trim()&&Ae&&o)&&k===null,ar=i(async()=>{if($.current)return;let U=++V.current;C(true);try{let Re=await r.searchClinics({query:d.trim(),limit:100});if(!M.current||U!==V.current)return;Re.ok?(u(Re.value.clinics),E(null)):E(Re.error);}catch{M.current&&U===V.current&&E(z("internalError"));}finally{M.current&&U===V.current&&C(false);}},"search"),Ke=i(U=>{$.current||oe||k!==null||U.clinic!==null&&b.some(Re=>Re.clinic?.id===U.clinic?.id)||(A(),y(Re=>[...Re,{...U,key:Q.current(),idempotencyKey:Q.current()}]),u([]),s(""));},"add"),_r=i(async()=>{if($.current||k!==null||!ve||!m||!de||!o)return;$.current=true;let U=re.current,Re=i(()=>M.current&&re.current===U,"current");R(true),E(null);try{if(w.current===null){x.current=new AbortController;let sr=await o({petRef:e.petRef,petName:e.petName,ownerName:l.trim(),clinicName:D.join(", "),authorizationVersion:m.authorizationVersion,scopeText:de,signal:x.current.signal});if(!Re()||sr===null)return;if(w.current=sr,sr.signaturePngBase64!==void 0&&n!==void 0){let Ec=await n(sr.signaturePngBase64,x.current.signal);if(!Re())return;w.current={signatureId:Ec.signatureId};}}let Tr=w.current,ln=b.map(sr=>({...sr.clinic!==null&&(!Qt(sr)||sr.clinic.emailStatus==="none")?{clinicId:sr.clinic.id}:{clinicFreeText:Xt(sr)},...Qt(sr)?{clinicEmail:sr.email.trim().toLowerCase()}:{},...Tr.signatureId!==void 0?{signatureId:Tr.signatureId}:{signaturePngBase64:Tr.signaturePngBase64},idempotencyKey:sr.idempotencyKey})),dn=await t.createClinicRequestBatch({petRef:e.petRef,ownerName:l.trim(),authorizationVersion:m.authorizationVersion,clinics:ln});if(!Re())return;if(!dn.ok){E(dn.error);return}_(dn.value),e.onCreated?.(dn.value),Pr(dn.value.requestGroupId,U);}catch{Re()&&E(z("internalError"));}finally{$.current=false,Re()&&R(false);}},"submit"),Pr=i(async(U,Re)=>{try{let Tr=await r.getRequestGroup(U);if(!M.current||re.current!==Re)return;Tr.ok&&Tr.value.petRef===e.petRef&&I(Tr.value);}catch{}},"loadGroup"),Ee=i(async()=>{k===null||$.current||await Pr(k.requestGroupId,re.current);},"refreshGroup");return {ownerName:l,query:d,clinics:c,copy:m,scopeText:de,error:v,busy:g,searching:S,drafts:b,outcome:k,group:T,ready:ve,atCap:oe,recent:c.length===0?p.filter(U=>!b.some(Re=>Re.clinic?.id===U.id)):[],setOwnerName(U){$.current||(A(),a(U));},setQuery(U){$.current||(V.current+=1,C(false),u([]),s(U));},search:ar,addClinic(U){Ke({clinic:U,freeText:null,email:""});},addFreeText(){let U=d.trim();U.length!==0&&Ke({clinic:null,freeText:U,email:""});},setDraftEmail(U,Re){$.current||(A(),y(Tr=>Tr.map(ln=>ln.key===U?{...ln,email:Re}:ln)));},removeDraft(U){$.current||k!==null||(A(),y(Re=>Re.filter(Tr=>Tr.key!==U)));},submit:_r,refreshGroup:Ee,retryCopy(){E(null),q(U=>U+1);}}}i(kl,"useClinicBatchForm");function _l(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(_l,"trustedSignatureUploadUrl");function Pl(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(Pl,"paintClinicTypedSignature");function Tl(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(Tl,"paintSignatureStrokes");async function Dl(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||!_l(a.value.uploadUrl))throw n();let d=new FormData;for(let[f,b]of Object.entries(a.value.uploadFields))d.append(f,b);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(Dl,"registerClinicSignature");var rm=8,tm=480,nm=160;function Ot(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,h=m?.getContext("2d");if(!m||!h)return;let v=typeof window<"u"&&window.devicePixelRatio||1;h.setTransform(v,0,0,v,0,0);let E=m.width/v,g=m.height/v;if(u.current.trim().length>0){h.fillStyle="#111",Pl(h,u.current,E,g);return}h.lineWidth=2,h.lineCap="round",h.lineJoin="round",h.strokeStyle="#111",Tl(h,o.current,E,g);},[]);useEffect(()=>{let m=r.current;if(!m)return;let h=i(()=>{let E=m.getBoundingClientRect(),g=typeof window<"u"&&window.devicePixelRatio||1,R=Math.max(1,Math.round((E.width||m.clientWidth||tm)*g)),S=Math.max(1,Math.round((E.height||m.clientHeight||nm)*g));m.width!==R&&(m.width=R),m.height!==S&&(m.height=S),p();},"resize");if(h(),typeof ResizeObserver>"u")return;let v=new ResizeObserver(h);return v.observe(m),()=>v.disconnect()},[p]);let f=useCallback(()=>{e?.(),o.current=[],c(false),d(""),u.current="",p();},[e,p]),b=i(m=>{let h=m.currentTarget.getBoundingClientRect();return [m.clientX-h.left,m.clientY-h.top]},"point"),y=i(()=>o.current.reduce((m,h)=>m+h.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,[b(m)]],p());},onPointerMove(m){if(!t.current||n!=="draw")return;let h=o.current[o.current.length-1];h!==void 0&&(o.current=[...o.current.slice(0,-1),[...h,b(m)]],p(),c(y()>=rm));},onPointerUp(){t.current=false;},register(m,h){return !r.current||!s?Promise.reject(new Error("Signature upload failed")):Dl(r.current,m,h)}}}i(Ot,"useSignatureCanvas");function It({pad:e,disabled:r}){let t=ce(),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"?X.draw:X.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"?X.toType:X.toDraw}),e.mode==="type"&&jsx("input",{"aria-label":X.type,style:{...n,display:"block",width:"100%",boxSizing:"border-box"},maxLength:Us,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?X.typedSignatureA11y(o):X.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":X.drawHint}),e.mode==="type"?null:jsx("button",{type:"button",style:l,disabled:r,onClick:e.clear,"aria-label":X.clearA11y,"data-testid":"records-signature-clear",children:X.clear})]})]})}i(It,"SignatureCanvas");function Sn(e){let{userRef:r,scopeEpoch:t}=ee();return jsx(Te,{capability:"recordsClinic",...Oe(e.onClose,X.cancel),children:r===null?jsx("p",{role:"alert",children:W.sessionRequired}):jsx(om,{..._e(e,["onClose","onCreated"])},JSON.stringify([r,t,e.petRef,e.petName]))})}i(Sn,"EverfurClinicRequestBatch");function om(e){let r=Ir(),t=Ni(),o=e.controller??r,n=ce(),l=Ot(),a=kl(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"),b=a.busy?ze.sending:a.drafts.length===0?ze.addToContinue:a.error?ze.tryAgain:ze.send(a.drafts.length),y=a.outcome?ze.resultTitle:ze.title;return jsxs("section",{className:e.className,"aria-label":y,style:{...mt,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:y}),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?ze.allFailed:a.outcome.failedCount>0?ze.partial(a.outcome.createdCount,a.outcome.results.length,a.outcome.failedCount):ze.allSent(a.outcome.createdCount)}),jsx("h3",{style:{margin:0,fontSize:n.type.size.subtitle},children:ze.perClinic}),jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"grid",gap:n.space.sm},children:a.outcome.results.map((m,h)=>{let v=m.request?.clinicName??a.drafts[h]?.clinic?.name??m.clinicFreeText??"";return jsxs("li",{"data-testid":`records-batch-row-${m.created?"created":"failed"}`,children:[jsx("span",{children:v})," ",jsx("span",{style:p,children:m.created?ze.sent:ze.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:ze.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:[X.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:Xt(m)}),Qt(m)?jsxs("label",{children:[X.email,jsx("input",{style:c,type:"email",placeholder:X.emailPlaceholder,maxLength:320,autoComplete:"off",value:m.email,disabled:a.busy,onChange:h=>{l.clear(),a.setDraftEmail(m.key,h.target.value);}})]}):null,Qt(m)&&!m.email.trim()?jsx("p",{style:p,children:ze.emailToAdd}):null,jsx("button",{type:"button",style:u,disabled:a.busy,"aria-label":ze.remove(Xt(m)),onClick:()=>{l.clear(),a.removeDraft(m.key);},children:ze.remove(Xt(m))})]},m.key))}),jsx("p",{style:{margin:0},children:a.atCap?ze.atCap:ze.addClinic}),!a.atCap&&jsxs(Fragment,{children:[jsxs("label",{children:[X.clinic,jsx("input",{style:c,placeholder:X.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:X.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:ze.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:X.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:X.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(It,{pad:l,disabled:a.busy}),!d&&jsx("p",{role:"alert",children:X.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":ze.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:b})]}),e.onClose&&jsx("button",{type:"button",style:u,disabled:a.busy,onClick:e.onClose,children:X.cancel}),jsx(De,{})]})}i(om,"BatchBody");var he=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 ${Pe(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 ${Pe(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 am="value_text",Al=64,ql=512;function Nl(e){return e!==null&&e.httpStatus===409&&!Jr(e)}i(Nl,"isFactReviewerLocked");var wn=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:am}),Ll=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,Fl=/^\d{4}-\d{2}-\d{2}$/;function zl(e){if(e==null)return "text";let r=e.trim();return Ll.test(r)?"num":Fl.test(r)&&!Number.isNaN(Date.parse(r))?"date":r==="true"||r==="false"?"bool":"text"}i(zl,"inferFactValueKind");function Gi(e,r){let t=r.trim(),o=zl(e);if(o==="num"&&Ll.test(t)){let n=Number(t);if(Number.isFinite(n))return Object.freeze({[wn.num]:n})}return o==="date"&&Fl.test(t)&&!Number.isNaN(Date.parse(t))?Object.freeze({[wn.date]:t}):Object.freeze(o==="bool"&&(t==="true"||t==="false")?{[wn.bool]:t==="true"}:{[wn.text]:t})}i(Gi,"factCorrectionFor");var Ie=z$1.string().nullish(),bo=z$1.number().nullish(),sm=z$1.object({collected_at:Ie,at:Ie,value:bo,unit:Ie,qualitative_result:Ie,ref_low:bo,ref_high:bo,status:Ie,source_clinic:Ie,source_doc_id:Ie,doc_id:Ie,reviewed:z$1.boolean().nullish()}),lm=z$1.object({collected_at:Ie,at:Ie,value:bo,unit:Ie,qualitative_result:Ie,status:Ie}),dm=z$1.object({marker_id:z$1.string().min(1),canonical_name:Ie,name:Ie,loinc_code:Ie,canonical_unit:Ie,unit:Ie,panel_name:Ie,panel:Ie,meaning_text:Ie,meaning:Ie,latest:lm.nullish(),trajectory:Ie,points:z$1.array(sm).optional()}),cm=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()}),um=z$1.object({markers:z$1.array(dm).optional(),summary:cm.nullish(),disclaimer:z$1.string().optional(),featured_marker_id:Ie});function pm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(pm,"isObject");function Ml(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(Ml,"withheldMarkers");function $l(e,r){let t=pm(r)?r:{},o=typeof t.pet_ref=="string"&&t.pet_ref.length>0?t.pet_ref:e;if(t.withheld===true)return Ml(o);let n=um.safeParse(t);if(!n.success)return Ml(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($l,"mapRecordMarkers");var mm=z$1.string().min(1).refine(e=>e.startsWith("https://")),fm=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:mm,expires_in_seconds:z$1.number().int().nonnegative().nullish()}),ym=z$1.object({items:z$1.array(z$1.unknown()).optional()});function Ul(e){let r=ym.safeParse(e);if(!r.success)return null;let t=[];for(let o of r.data.items??[]){let n=fm.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(Ul,"mapRequestDocuments");var gm=z$1.string().min(1).refine(e=>e.startsWith("https://")),kn=z$1.string().nullish(),bm=z$1.object({share_id:z$1.string().min(1),share_url:z$1.string().min(1),expires_at:kn}),Rm=z$1.object({shares:z$1.array(z$1.object({share_id:z$1.string().min(1),expires_at:kn,created_at:kn,view_count:z$1.number().int().nonnegative().nullish(),last_viewed_at:kn})).optional()}),hm=z$1.object({download_url:gm,expires_at:kn});function vm(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(vm,"resolveShareUrl");function Bl(e,r){let t=bm.safeParse(e);if(!t.success)return null;let o=vm(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(Bl,"mapRecordShareLink");function jl(e){let r=Rm.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(jl,"mapRecordShareList");function Hl(e){let r=hm.safeParse(e);return r.success?Object.freeze({downloadUrl:r.data.download_url,expiresAt:r.data.expires_at??null}):null}i(Hl,"mapRecordPdfLink");var Cm=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 Vl(e){let r=Cm.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(Vl,"mapSignatureSuggestions");var H=z$1.string().nullish(),_n=z$1.number().nullish(),Em=z$1.object({at:H,value:_n,unit:H,qualitative_result:H,ref_low:_n,ref_high:_n,status:H,doc_id:H}),xm=z$1.object({marker_id:z$1.string(),name:z$1.string(),loinc_code:H,unit:H,panel:H,meaning:H,latest:z$1.object({at:H,value:_n,unit:H,qualitative_result:H,status:H}).nullish(),trajectory:H,points:z$1.array(Em).optional()}),Sm=z$1.object({encounter_id:z$1.string(),date:H,type:H,clinic_name:H,veterinarian:H,doc_id:H}),wm=z$1.object({note_id:z$1.string(),encounter_id:H,observed_on:H,sections:z$1.array(z$1.object({section:z$1.string(),text:z$1.string()})).optional()}),km=z$1.object({exam_id:z$1.string(),encounter_id:H,observed_on:H,doc_id:H,systems:z$1.record(z$1.object({finding_status:H,finding:H})).optional()}),_m=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:H,latest_record_at:H,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()}),Pm=z$1.object({conflict_id:z$1.string(),entity_type:z$1.string(),field:H,severity:H,candidates:z$1.array(z$1.object({value:z$1.string(),source_doc_id:H,doc_id:H,collected_at:H})).optional()}),Tm=z$1.object({lab_results:z$1.array(xm).optional(),encounters:z$1.array(Sm).optional(),clinician_notes:z$1.array(wm).optional(),physical_exams:z$1.array(km).optional(),completeness:_m.nullish(),conflicts:z$1.array(Pm).optional()}),Dm=z$1.object({visits:z$1.array(z$1.object({visit_id:z$1.string(),visit_date:H,veterinarian:H,summary:H,doc_id:H})),vaccines:z$1.array(z$1.object({vaccine_id:z$1.string(),product:H,lot:H,administered_on:H,expires_on:H,doc_id:H})),weights:z$1.array(z$1.object({weight_id:z$1.string(),observed_on:H,weight_kg:_n,doc_id:H})),medications:z$1.array(z$1.object({medication_id:z$1.string(),drug_name:H,dose:H,route:H,frequency:H,sig:H,rx_number:H,started_on:H,stopped_on:H,doc_id:H})),disclaimer:z$1.string().optional()}),Om=z$1.object({document:Jo,contributions:z$1.array(Xo),contribution_count:z$1.number().int().nonnegative().optional()});function Yi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Yi,"isObject");function Ki(e,r){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:r}i(Ki,"petOf");function Wi(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(Wi,"emptyDepth");function Im(e,r){let t=Yi(r)?r:{},o=Ki(t,e);if(t.withheld===true)return Wi(o,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(s=>s in t))return Wi(o,false);let l=Tm.safeParse(t);if(!l.success)return Wi(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(Im,"mapRecordDepth");function Gl(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(Gl,"withheldTimeline");function Am(e,r){let t=Yi(r)?r:{},o=Ki(t,e);if(t.withheld===true)return Gl(o);let n=Dm.safeParse(t);if(!n.success)return Gl(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(Am,"mapRecordsTimeline");function qm(e,r){let t=Yi(r)?r:{},o=Ki(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=Om.safeParse(t);if(!l.success)return n();let a=Object.freeze(l.data.contributions.map(Zo));return Object.freeze({petRef:o,withheld:false,document:ei(l.data.document),contributions:a,contributionCount:l.data.contribution_count??a.length})}i(qm,"mapDocumentContributions");var Nm="/widget/v1/records/pets";function Wl(e){let r=e.funnel??ut({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),t=i((s,c)=>typeof s=="string"&&s.length>0&&!pt(s)&&[...s].length<=c,"segment"),o=i(async(s,c,u,p)=>{if(!t(c,or))return ot();let f=await r.send(s,{method:"GET",path:u});if(!f.ok)return f;let b=p(f.value);return b.petRef===c?we(b):Y(z("internalError",{retryable:false}))},"read"),n=i(s=>`${Nm}/${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?Y(z("internalError",{retryable:false})):we(f)},"parsed"),d=i((s,c)=>!t(s.entityType,Al)||!t(s.canonicalKey,ql)||s.idempotencyKey!==void 0&&!t(s.idempotencyKey,un)||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=>Im(s,c)),"getRecordDepth"),getTimeline:i(s=>o("records.depth.timeline",s,`${n(s)}/timeline`,c=>Am(s,c)),"getTimeline"),getDocumentContributions(s,c){return t(c,64)?o("records.depth.contributions",s,`${n(s)}/documents/${encodeURIComponent(c)}/contributions`,u=>qm(s,u)):ot()},getMarkers:i(s=>o("records.depth.markers",s,`${n(s)}/markers`,c=>$l(s,c)),"getMarkers"),createShare(s){return t(s,or)?a("records.share.create",{method:"POST",path:`${l(s)}/share`},c=>Bl(c,e.apiBaseUrl)):ot()},listShares(s){return t(s,or)?a("records.share.list",{method:"GET",path:`${l(s)}/shares`},jl):ot()},async revokeShare(s,c){if(!t(s,or)||!t(c,64))return ot();let u=await r.send("records.share.revoke",{method:"DELETE",path:`${l(s)}/shares/${encodeURIComponent(c)}`},{idempotent:false,maxAttempts:1});return u.ok?we(void 0):u},getPdfLink(s){return t(s,or)?a("records.pdf.link",{method:"GET",path:`${l(s)}/pdf-link`},Hl):ot()},async editFact(s,c){let u=t(s,or)?d(c,c.correctedFields):null;if(u===null)return ot();let p=await r.send("records.fact.edit",{method:"POST",path:`${l(s)}/facts/edit`,body:u},{idempotent:false,maxAttempts:1});return p.ok?we(void 0):p},async removeFact(s,c){let u=t(s,or)?d(c):null;if(u===null)return ot();let p=await r.send("records.fact.remove",{method:"POST",path:`${l(s)}/facts/remove`,body:u},{idempotent:false,maxAttempts:1});return p.ok?we(void 0):p},listRequestDocuments(s){return t(s,64)?a("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(s)}/documents`},Ul):ot()},listAuthorizationSignatures:i(()=>a("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},Vl),"listAuthorizationSignatures")}}i(Wl,"createRecordsDepthClient");function ot(){return Promise.resolve(Y(z("validationFailed",{retryable:false})))}i(ot,"invalid");function pr(){let{runtime:e,userRef:r,scopeEpoch:t}=ee();return useMemo(()=>{let{services:o}=e.registry;return Wl({auth:o.authFor(r),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,r,t])}i(pr,"useEverfurRecordsDepthClient");function zr(e,r,t,o=""){let n=pr(),{userRef:l}=ee(),a=Qn(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 v=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 E=await r(n,e);v===u.current&&(E.ok?c({scope:d,value:E.value,error:null,loading:false}):c({scope:d,value:null,error:E.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},b=useCallback(()=>{p();},[p]),y=f.error===null||f.error.httpStatus!==404,m=y?f.error:null,h=f.loading?"loading":m!==null?"error":f.value===null?"empty":f.value.withheld?"populated":t(f.value)?"empty":"populated";return useMemo(()=>({status:h,value:f.value,error:m,available:y,refresh:b}),[h,f.value,m,y,b])}i(zr,"useRecordsDepthRead");function Rt(e){return e!==null&&e.httpStatus===404}i(Rt,"isDarkRouteError");var $m=i((e,r)=>e.getMarkers(r),"readMarkers"),Um=i(e=>e.markers.length===0,"markersEmpty");function Xi(e){let r=zr(e,$m,Um);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(Xi,"useRecordsMarkers");var Bm=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Ql(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,b]=useState(r.email),[y,m]=useState(false),[h,v]=useState(null),[E,g]=useState(null),[R,S]=useState(0),[C,k]=useState(null),[_,T]=useState(false),[I,F]=useState(null),[q,M]=useState([]),[$,V]=useState(null),[re,Q]=useState(false),w=useRef(false),x=useRef(true),A=useRef(Zr()),D=useRef(null);useEffect(()=>(x.current=true,()=>{x.current=false,D.current=null;}),[t]),useEffect(()=>{let Ee=true;return v(null),D.current=null,t.getAuthorizationCopy().then(U=>{Ee&&(U.ok?(v(U.value),g(null)):g(U.error));}).catch(()=>{Ee&&g(z("internalError"));}),()=>{Ee=false;}},[t,R]),useEffect(()=>{if(o===void 0)return;let Ee=true;return o.listAuthorizationSignatures().then(U=>{Ee&&(U.ok?M(U.value):Rt(U.error)||M([]));}).catch(()=>{}),()=>{Ee=false;}},[o]);let G=xn(r.clinic),de=f.trim().toLowerCase(),Ae=Bm.test(de),oe=G&&(y||de.length>0)&&!Ae?he.emailRequired:null,ve=h?En(h,u.trim(),Pe(e.petName),a):null,ar=e.hostCapture===true||re||$!==null,Ke=!!(s&&h&&ve&&u.trim()&&a&&ar&&(!G||Ae)),_r=useCallback(async()=>{if(!(w.current||I!==null||!h||!ve)){if(!a){k(he.missingDraftError);return}if(G&&!Ae){m(true),k(he.emailRequired);return}if(!(!s||!u.trim())){w.current=true,T(true),k(null);try{if(D.current===null){let U=$!==null?{signatureId:$}:await n();if(!x.current)return;if(U===null){k(he.missingSignatureError);return}let Re=r.clinic&&(!G||r.clinic.emailStatus==="none")?{clinicId:r.clinic.id}:{clinicFreeText:a};D.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:h.authorizationVersion,...Re,...G?{clinicEmail:de}:{},...U.signatureId!==void 0?{signatureId:U.signatureId}:{signaturePngBase64:U.signaturePngBase64},idempotencyKey:A.current()};}let Ee=await t.createClinicRequest(D.current);if(!x.current)return;if(!Ee.ok){k(Ee.error.displayMessage);return}if(Ee.value.petRef!==e.petRef){k(z("internalError").displayMessage);return}F(Ee.value),D.current=null,l?.(Ee.value);}catch{x.current&&k(z("internalError").displayMessage);}finally{w.current=false,x.current&&T(false);}}}},[s,n,r.clinic,a,t,h,I,e.petRef,G,de,l,u,$,ve,Ae]),Pr=useCallback(()=>{D.current=null,k(null);},[]);return {title:d?he.titleFreeText:he.titleDirectory,clinicName:a,isFreeText:d,authorized:s,ownerName:u,email:f,emailError:oe,needsEmail:G,directoryClinicNoEmail:G&&r.clinic!==null,copy:h,copyError:E,scope:ve,error:C,busy:_,created:I,ready:Ke,signatures:q,reuseSignatureId:$,hasSignature:ar,setAuthorized(Ee){w.current||(Pr(),c(Ee));},setOwnerName(Ee){w.current||(Pr(),p(Ee));},setEmail(Ee){w.current||(Pr(),m(false),b(Ee));},setSigned(Ee){w.current||(Pr(),Q(Ee),Ee&&V(null));},pickReuseSignature(Ee){w.current||(Pr(),V(Ee));},retryCopy(){g(null),S(Ee=>Ee+1);},submit:_r}}i(Ql,"useRecordsConsentForm");function Pn(e){let{userRef:r,scopeEpoch:t}=ee();return jsx(Te,{capability:"recordsClinic",style:e.style,className:e.className,...Oe(e.onBack,Le),children:r===null?jsx("p",{role:"alert",children:W.sessionRequired}):jsx(Vm,{..._e(e,["onCreated","onNavigate","onBack"])},JSON.stringify([r,t,e.petRef,e.clinic.key]))})}i(Pn,"EverfurRecordsConsent");function Vm({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}=j(),b=Ir(),y=a??b,m=pr(),h=Ot(),v=Ql({petRef:e,petName:r,ownerName:o??"",clinic:t,controller:y,depthClient:m,capture:n?()=>n({petRef:e,petName:Pe(r),ownerName:v.ownerName,clinicName:v.clinicName,authorizationVersion:v.copy?.authorizationVersion??"",scopeText:v.scope??"",signal:new AbortController().signal}):async()=>h.signed?h.register(y,new AbortController().signal):null,hostCapture:n!==void 0,onCreated:i(_=>{l?.(_),d?.({name:"dashboard"});},"onCreated")}),E=h.signed,g=useRef(v);g.current=v,useEffect(()=>{g.current.setSigned(E);},[E]);let R=v.busy,S={display:"flex",flexDirection:"column",gap:p.space.sm},C="records-consent-owner-name",k="records-consent-clinic-email";return jsxs("div",{className:u,style:{...f.root,...c},"data-testid":"records-consent-screen",children:[jsx(He,{title:v.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":he.scopeHeading,children:[jsx("h3",{style:{...f.sectionTitle,color:p.color.brand},children:he.scopeHeading}),jsx("p",{style:f.bodyText,children:he.scopeBody}),jsx("ul",{style:{...f.plainList,gap:p.space.sm},children:he.whatWeDo.map(_=>jsxs("li",{style:{...f.bodyText,display:"flex",gap:p.space.sm},children:[jsx("span",{"aria-hidden":"true",style:{color:p.color.brand,...O(p,"bold")},children:"\u2713"}),jsx("span",{children:_})]},_))}),jsx("p",{style:{...f.muted,paddingTop:p.space.xs,borderTop:`1px solid ${p.color.borderHairlineGreen}`},children:he.retentionNote}),v.copy&&v.scope?jsx("p",{style:{...f.rowDetail,whiteSpace:"pre-wrap"},"data-testid":"records-consent-scope",children:v.scope}):v.copyError?jsxs(Fragment,{children:[jsx("p",{role:"alert",style:f.errorText,children:v.copyError.displayMessage}),jsx(B,{label:W.retry,kind:"outline",onClick:v.retryCopy,testID:"records-consent-copy-retry"})]}):jsx("p",{role:"status",style:f.muted,children:W.loading})]}),jsxs("button",{type:"button",role:"checkbox","aria-checked":v.authorized,onClick:()=>v.setAuthorized(!v.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 ${v.authorized?p.color.brand:p.color.brandBorder}`,backgroundColor:v.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:v.authorized?p.color.brand:p.color.surface,color:p.color.onPrimary,display:"inline-flex",alignItems:"center",justifyContent:"center",...O(p,"bold")},children:v.authorized?"\u2713":""}),jsx("span",{style:{...f.rowTitle,...O(p,"bold"),fontSize:p.type.size.bodyTight},children:he.authorizeLabel(r,v.clinicName)})]}),jsxs("div",{style:S,children:[jsx("label",{htmlFor:C,style:f.fieldLabel,children:he.fullName}),jsx("input",{id:C,style:f.field,value:v.ownerName,placeholder:he.fullNamePlaceholder,maxLength:200,disabled:R,autoComplete:"name",onChange:_=>v.setOwnerName(_.target.value),"data-testid":"records-consent-owner-name"})]}),v.needsEmail?jsxs("div",{style:S,"data-testid":"records-consent-email-block",children:[v.directoryClinicNoEmail?jsx("p",{style:f.cautionNote,"data-testid":"records-consent-no-email-note",children:he.noEmailNote(r,v.clinicName)}):null,jsx("label",{htmlFor:k,style:f.fieldLabel,children:he.emailLabel}),jsx("input",{id:k,type:"email",style:f.field,value:v.email,placeholder:he.emailPlaceholder,maxLength:320,disabled:R,autoComplete:"off",onChange:_=>v.setEmail(_.target.value),"data-testid":"records-consent-clinic-email"}),v.emailError?jsx("p",{role:"alert",style:f.errorText,children:v.emailError}):null,jsx("p",{style:f.muted,"data-testid":"records-consent-review-note",children:he.newClinicDirectSendNote})]}):null,n?null:jsxs("div",{style:S,children:[v.signatures.length>0?jsxs("div",{style:S,children:[jsx("span",{style:f.fieldLabel,children:he.reuseSignature}),jsx("div",{style:{display:"flex",gap:p.space.sm,overflowX:"auto",padding:`${p.space.xs}px 0`},children:v.signatures.map(_=>{let T=v.reuseSignatureId===_.signatureId;return jsx("button",{type:"button",onClick:()=>v.pickReuseSignature(T?null:_.signatureId),"aria-label":T?he.reuseTileSelectedA11y:he.reuseTileA11y,"aria-pressed":T,style:{flexShrink:0,width:112,height:56,borderRadius:p.radius.sm,border:T?`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-${_.signatureId}`,children:jsx("img",{src:_.previewUrl,alt:"",style:{width:"100%",height:"100%",objectFit:"contain"}})},_.signatureId)})}),jsx("p",{style:f.muted,children:he.reuseHint})]}):null,jsx(It,{pad:h,disabled:R}),jsx("p",{style:f.muted,children:he.signatureHint(v.clinicName)}),!v.hasSignature&&v.clinicName.length>0?jsx("p",{style:f.muted,"data-testid":"records-consent-signature-required",children:he.missingSignatureError}):null]}),v.error?jsx("p",{role:"alert","aria-live":"assertive",style:f.errorBanner,children:v.error}):null,v.created?jsx("p",{role:"status",style:f.bodyText,children:v.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(B,{label:X.cancel,kind:"link",disabled:R,onClick:s,style:{flex:"0 0 auto"},testID:"records-consent-cancel"}):null,jsx(B,{label:R?he.submitting:he.submit,ariaLabel:he.submitA11y,disabled:!v.ready,busy:R,onClick:()=>{v.submit();},style:{flex:"1 1 12rem",minWidth:0,minHeight:54},testID:"records-consent-submit"})]}),jsx(De,{})]})}i(Vm,"ConsentBody");var ho=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function Xl(e){if(!e)return null;let r=Date.parse(e);return Number.isNaN(r)?null:r}i(Xl,"toMillis");function Jl(e){let r=[...e.visits.map((t,o)=>({key:`visit-${o}-${t.visitId}`,kind:"visit",kindLabel:me.kind.visit,at:t.visitDate,date:J(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(J(t.expiresOn))),{key:`vaccine-${o}-${t.vaccineId}`,kind:"vaccine",kindLabel:me.kind.vaccine,at:t.administeredOn,date:J(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:J(t.observedOn),title:gl(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:J(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=Xl(t.at),l=Xl(o.at);return n===null&&l===null?ho[t.kind]-ho[o.kind]:n===null?1:l===null?-1:l!==n?l-n:ho[t.kind]-ho[o.kind]}))}i(Jl,"buildTimelineRows");var Xm=300,Zl=120,ed=44,Jm=i((e,r)=>e.getTimeline(r),"readTimeline"),Zm=i(e=>e.isEmpty,"timelineEmpty");var ef=i(e=>e.contributions.length===0,"contributionsEmpty");function vo({petRef:e,style:r,className:t,onBack:o}){let n=zr(e,Jm,Zm);return jsx(rd,{state:n,style:r,className:t,onBack:o,header:jsx(He,{title:me.timeline,onBack:fn(o),testID:"timeline-header"}),loading:jsx(El,{testID:"timeline-loading"}),empty:jsx(Fe,{variant:"no_records",testID:"timeline-empty"}),render:l=>jsx(nf,{timeline:l})})}i(vo,"EverfurRecordsTimeline");function Co({petRef:e,docId:r,style:t,className:o,onBack:n}){let l=useCallback((s,c)=>s.getDocumentContributions(c,r),[r]),a=zr(e,l,ef,r),d=a.value?.document?.title?.trim()||me.uploadedDocument;return jsx(rd,{state:a,style:t,className:o,onBack:n,header:jsx(He,{title:d,onBack:fn(n),testID:"contributions-header"}),empty:jsx(Fe,{variant:"no_records",testID:"contributions-empty"}),render:s=>jsx(of,{view:s})})}i(Co,"EverfurDocumentContributions");function rd({state:e,style:r,className:t,header:o,loading:n,empty:l,render:a,onBack:d}){let{styles:s}=Zi(),{userRef:c}=ee();return jsx(Te,{capability:"records",style:r,className:t,...Oe(fn(d),Le),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}):rf(e,a,s,n,l)}),jsx(De,{})]})})}i(rd,"DepthSurface");function rf(e,r,t,o,n){switch(e.status){case "loading":return o??jsx(tf,{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(Fe,{variant:Qe(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(rf,"renderState");function tf({styles:e}){let[r,t]=useState(false);return useEffect(()=>{let o=setTimeout(()=>t(true),Xm);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(tf,"LoadingState");function nf({timeline:e}){let{styles:r}=Zi(),t=Jl(e);return jsxs("section",{"aria-label":me.timeline,style:r.timelineList,children:[e.disclaimer.length>0?jsx("p",{role:"note","aria-label":lr.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 of({view:e}){let{styles:r}=Zi();return jsxs("section",{"aria-label":W.records,style:r.list,children:[e.document?.receivedAt?jsx("p",{style:r.rowDetail,children:J(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:Ht(t.value,t.unit)}),t.observedAt?jsx("dd",{style:r.rowDetail,children:J(t.observedAt)}):null]},t.key))})]})}i(of,"ContributionsBody");function Zi(){let e=ce(),r=useMemo(()=>af(e),[e]);return {theme:e,styles:r}}i(Zi,"useDepthTheme");function af(e){let{color:r,space:t,radius:o,type:n,slots:l}=e,a=i((f,b)=>`${Math.round(f*b)}px`,"lh"),d=i((f,b,y,m="regular")=>({margin:0,...O(e,m),fontSize:f,lineHeight:a(f,b),color:y}),"text"),s=Wr(l.recordCard),c=i((f,b,y,m="regular")=>({...d(f,b,y,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:Zl,height:"100%",backgroundColor:r.background,color:r.text.primary,...O(e,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:Zl,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:ed,minWidth:ed,padding:`${t.md}px ${t.xl}px`,borderRadius:o.pill,...O(e,"bold"),fontSize:n.size.body,border:0,cursor:"pointer",backgroundColor:r.primary,color:r.onPrimary,...Ar(l.primaryButton),...Wr(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,...Ar(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:Bi,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:{...O(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(af,"makeStyles");var K=Object.freeze({title:"Full medical record",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:i(e=>`${e} ${e===1?"document":"documents"} from your vet ${e===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,"inReview"),needsAttention:"Needs your attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:i(e=>`${e} ${e===1?"document":"documents"} on file`,"documentsOnFile"),inReviewChip:i(e=>`${e} in review`,"inReviewChip"),beingVerified:i(e=>`${e} being verified`,"beingVerified"),beingVerifiedA11y:i(e=>`${e} ${e===1?"fact is":"facts are"} being verified`,"beingVerifiedA11y"),pendingReview:"Pending review: ",dateRange:i((e,r)=>`${J(e)} to ${J(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 ${J(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"})}),td=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 qt(e){return Object.prototype.hasOwnProperty.call(td,e)?td[e]:Kr(e)}i(qt,"entityTypeLabel");var Eo=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function nd(e){let r=Eo.filter(o=>e.includes(o)),t=e.filter(o=>!Eo.includes(o));return [...r,...t]}i(nd,"orderEntityTypes");function xo(e){switch(e){case "identity_risk":return {label:"Identity mismatch",rank:0,tone:"critical"};case "benign":return {label:"Minor difference",rank:2,tone:"neutral"};default:return {label:"Needs review",rank:1,tone:"warning"}}}i(xo,"conflictSeverityMeta");function Tn(e,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?K.overdue:K.due(J(e)),overdue:o}}i(Tn,"dueBadge");function od(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(od,"formatReferenceBand");function ea(e,r={}){let t=pr(),{userRef:o}=ee(),n=r.now??Date.now,[l,a]=useState(null),[d,s]=useState(true),[c,u]=useState(null),[p,f]=useState(null),b=p===true,[y,m]=useState({}),[h,v]=useState(false),[E,g]=useState(null),[R,S]=useState(false),[C,k]=useState(false),_=Qn(e),T=useRef(0),I=useRef(true),F=useCallback(async()=>{let x=T.current+=1;if(s(true),u(null),o===null){a(null),s(false);return}let A=await t.listShares(e);x!==T.current||!I.current||(A.ok?(a(A.value),f(true)):Rt(A.error)?(a(null),f(false)):(a(null),u(A.error),id(A)&&f(true)),s(false));},[t,e,o]);useEffect(()=>(I.current=true,F(),()=>{I.current=false,T.current+=1;}),[F]);let q=useRef(_);useEffect(()=>{q.current!==_&&(q.current=_,m({}),k(true),F());},[_,F]);let M=useCallback(async()=>{v(true);let x=await t.createShare(e);return I.current&&(v(false),x.ok?(m(A=>({...A,[x.value.shareId]:x.value.shareUrl})),F()):Rt(x.error)?f(false):Jr(x.error)&&k(true)),x},[t,e,F]),$=useCallback(async x=>{g(x);let A=await t.revokeShare(e,x);return I.current&&(g(null),F()),A},[t,e,F]),V=useCallback(async()=>{S(true);let x=await t.getPdfLink(e);return I.current&&(S(false),!x.ok&&Jr(x.error)&&k(true)),x},[t,e]),re=useCallback(()=>{k(false),F();},[F]),Q=useMemo(()=>hl(l??[],y,n()),[l,y,n]),w=d?"loading":c!==null?"error":Q.length===0?"empty":"populated";return useMemo(()=>({status:w,rows:Q,available:b,consentRequired:C,error:c,creating:h,revokingId:E,preparingPdf:R,createLink:M,revoke:$,pdfLink:V,refresh:re}),[w,Q,b,C,c,h,E,R,M,$,V,re])}i(ea,"useRecordShares");function id(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(id,"answeredBehindGate");function ad(e){return e.available||e.status!=="empty"}i(ad,"sharesListShown");function ra(e){let r=pr(),{userRef:t}=ee(),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&&Rt(s.error)?l({scope:o,lit:false}):id(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(ra,"useRecordsDepthProbe");function ta(e){let r=pr(),o=ra(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(ta,"useRecordPdfLink");var On=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 sd=Math.round(Br/(1024*1024)),Nt=Object.freeze({queued:"Queued",verifying:"Verifying\u2026",done:"Done",failed:"Failed",uploading:i((e,r)=>`Uploading ${Math.min(e+1,r)} of ${r} records`,"uploading"),uploaded:i((e,r)=>`${e} of ${r} records uploaded`,"uploaded")});function ld(e){let r=Math.round(e.progress*100);switch(e.status){case "done":return Nt.done;case "failed":return Nt.failed;case "uploading":return e.progress>=1?Nt.verifying:`${r}%`;case "queued":return Nt.queued;default:return null}}i(ld,"uploadItemStatusLabel");function ko(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 ${sd} MB`),`Didn\u2019t upload: ${n.join("; ")}. We can only read PDFs up to ${sd} MB right now.`}i(ko,"skippedFilesMessage");function dd(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(dd,"skippedOf");var na=[37,80,68,70,45],_o="application/pdf,.pdf",sf="application/octet-stream",lf="file:web-document";async function df(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(df,"readHead");async function cd(e){if(e.size<na.length)return false;let r=await df(e,na.length);return na.every((t,o)=>r[o]===t)}i(cd,"isPdfBlob");async function Po(e){let r=await cd(e),t=e.name,o=typeof t=="string"?t:void 0;return Object.freeze({uri:lf,mimeType:r?ct:sf,sizeBytes:e.size,blob:e,...o!==void 0?{name:o}:{}})}i(Po,"fileToHandle");function cf(e){let r=e.sizeBytes;return e.mimeType===ct&&typeof r=="number"&&Number.isFinite(r)&&r>0&&r<=Br}i(cf,"isUploadableHandle");function uf(e=document){return new Promise(r=>{let t=e.createElement("input");t.type="file",t.accept=_o,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}Po(n).then(r);},{once:true}),t.addEventListener("cancel",()=>{o(),r(null);},{once:true}),e.body.appendChild(t),t.click();})}i(uf,"pickDocument");var $r=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 ud({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,b]=useState(null),y=useRef(false),m=useRef(false),h=useRef(0);useEffect(()=>(m.current=true,()=>{m.current=false,h.current+=1;}),[o]);let v=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,E=n.trim(),g=E.length<=320&&!Array.from(E).some(T=>T.charCodeAt(0)<=32||T.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(E),R=v.canUpdateClinicEmail===true&&E.length>0,S=v.canRetrySend===true&&!a&&!R,C=v.canUpdateClinicEmail===true&&!a&&g,k=v.canConvertToUpload===true&&t,_=i(async T=>{let I={retry:S,email:C,revoke:v.canRevoke===true&&u,convert:k};if(y.current||!m.current||!I[T])return;y.current=true,d(true),c(null);let F=h.current,q=i(()=>m.current&&F===h.current,"live");try{let M=T==="retry"?await o.retryRequest(e.id):T==="email"?await o.updateClinicEmail(e.id,E):T==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!q())return;if(!M.ok){c(M.error);return}if(M.value.id!==e.id||M.value.petRef!==e.petRef){c(z("internalError"));return}b({before:e.updatedAt,value:M.value}),l(""),p(!1),r();}catch{q()&&c(z("internalError"));}finally{y.current=false,q()&&d(false);}},"run");return {request:v,email:n,busy:a,error:s,canRetry:S,canUpdateEmail:C,canConvert:k,hasEmailEdit:R,confirmingRevoke:u&&v.canRevoke===true,emailInvalid:E.length>0&&!g,setEmail(T){y.current||(l(T),c(null));},retry:i(()=>_("retry"),"retry"),updateEmail:i(()=>_("email"),"updateEmail"),revoke:i(()=>_("revoke"),"revoke"),convert:i(()=>_("convert"),"convert"),askRevoke(){!y.current&&v.canRevoke===true&&p(true);},keepRequest(){y.current||p(false);}}}i(ud,"useRecordsRecovery");var mf=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],ff=["requested","awaiting_upload","records_received","processing","ready"],yf=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],An=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"}),gf=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"}),bf=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 Rf(e){return e.wireStatus??bf[e.status]??"sent"}i(Rf,"wireStatusOf");function hf(e,r){return e!=="awaiting_response"||r<=0?null:`${r} ${r===1?"reminder":"reminders"} sent`}i(hf,"reminderProgressLabel");function vf(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(vf,"reachedRailIndex");function Cf(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(Cf,"deliveryDetail");function Ef(e,r){return hf(r,e.reminderCount??0)??fr.waiting}i(Ef,"awaitingDetail");function qn(e){return e.source==="owner_provided"||!!e.convertedToUploadAt}i(qn,"isOwnerSourcedRequest");function xf(e,r,t){let o=qn(r);switch(e){case "sent_to_clinic":return Cf(r);case "awaiting_clinic":return Ef(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(xf,"railDetail");function Sf(e,r){return !!e.reviewStartedAt||r==="parsing_failed"||r==="review_email_failed"}i(Sf,"tookReviewBranch");function wf(e,r,t){if(e.key!=="processing"||!Sf(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:An.parsing_failed,detail:fr.parsingFailed,at:null,state:l},{key:"manual_review",title:An.manual_review,detail:fr.manualReview,at:r.reviewStartedAt??null,state:a}]}i(wf,"expandProcessingPhase");function kf(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(kf,"convertedReachedIndex");function pd(e){return {key:"awaiting_clinic",title:fr.switchedTitle,detail:fr.switched,at:e.convertedToUploadAt??null,state:"done"}}i(pd,"convertedClinicSwitchEvent");function _f(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(_f,"ownerReachedIndex");function Pf(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(Pf,"railTimestamp");function md(e,r,t,o){return {key:e,title:An[e],detail:xf(e,r,t),at:Pf(e,r,t),state:o}}i(md,"railEvent");function it(e,r){return {key:e,title:An[e],detail:gf[e]??null,at:r.updatedAt||null,state:"failed"}}i(it,"terminalEvent");function ia(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 md(l,t,o,s)}).flatMap(l=>wf(l,t,o))}i(ia,"walkRail");function aa(e){let r=Rf(e),t=i(n=>md(n,e,r,"done"),"done");if(r==="revoked")return [t("requested"),it("revoked",e)];if(e.convertedToUploadAt)return r==="failed"?[t("requested"),t("sent_to_clinic"),pd(e),t("awaiting_upload"),t("records_received"),it("processing_failed",e)]:ia(yf,kf(r),e,r,n=>n==="awaiting_clinic"?pd(e):null);if(e.source==="owner_provided"){if(r==="failed"||r==="clinic_declined")return [t("requested"),t("awaiting_upload"),t("records_received"),it("processing_failed",e)];let n=_f(r);return ia(ff,n<0?1:n,e,r)}if(r==="clinic_declined")return [t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),it("clinic_declined",e)];if(r==="clinic_responded_no_records")return [t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),it("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"),it("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[t("requested"),it("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[t("requested"),t("sent_to_clinic"),t("awaiting_clinic"),t("records_received"),it("processing_failed",e)]:[t("requested"),it("delivery_failed",e)]}let o=vf(r);return ia(mf,o<0?1:o,e,r)}i(aa,"buildRequestTimeline");var Df=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),To=24;function rn({request:e}){let r=Af(),t=aa(e);return jsx("ol",{style:r.list,"aria-label":ue.timelineA11y,"data-testid":"records-timeline",children:t.map((o,n)=>jsx(Of,{event:o,isLast:n===t.length-1,styles:r},o.key))})}i(rn,"RequestTimeline");function Of({event:e,isLast:r,styles:t}){let o=e.at?J(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(If,{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:Df[e.state]})]})]})}i(Of,"TimelineRow");function If({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(If,"Dot");function Af(){let e=ce();return useMemo(()=>qf(e),[e])}i(Af,"useStyles");function qf(e){let{color:r}=e,t={boxSizing:"border-box",width:To,height:To,borderRadius:To/2,display:"flex",alignItems:"center",justifyContent:"center",...O(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:To,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,...O(e,"bold"),fontSize:14,lineHeight:"18px",color:r.text.primary},titleCurrent:{color:r.brand},titleFailed:{color:r.danger},titleUpcoming:{color:r.text.muted,...O(e,"regular")},date:{...O(e,"regular"),fontSize:12,lineHeight:"16px",color:r.text.muted},detail:{...O(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(qf,"makeStyles");function fd(e){return e.value!==null&&Number.isFinite(e.value)}i(fd,"isFinitePoint");function Oo(e){return e.display!==null&&e.display.length>0?e.display:e.value!==null?String(e.value):""}i(Oo,"pointDisplay");function yd(e){let r=e.find(C=>C.points.some(fd));if(r===void 0)return null;let t=r.points.filter(fd),o=t[0];if(o===void 0)return null;let n=t.map(C=>C.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,b=t.map((C,k)=>({xPct:f<=1?50:p+k/(f-1)*(100-2*p),yPct:(c-C.value)/u*100})),y=(c-a)/u*100,m=(c-l)/u*100,h=t.reduce((C,k)=>k.value<C.value?k:C,o),v=t.reduce((C,k)=>k.value>C.value?k:C,o),E=t[t.length-1]??o,g=r.points[r.points.length-1]??E,R=Oo(g),S=R.length>0?R:Oo(E);return {label:r.label,heroDisplay:S,minDisplay:Oo(h),maxDisplay:Oo(v),firstDate:zi(r.points[0]?.at??null),lastDate:zi(g.at),points:b,bandTopPct:y,bandBottomPct:m}}i(yd,"buildTrendModel");function Nf(e){let r=e.indexOf(":");return r<=0?null:e.slice(0,r)}i(Nf,"entityTypeOf");function gd(e,r,t){let o=new Map,n=[];for(let d of e){let s=Nf(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(gd,"groupSeriesByEntityType");function bd({series:e}){let r=ce(),t=useMemo(()=>zf(r),[r]),o=useMemo(()=>gd(e,Eo,qt),[e]);return o.length===0?null:jsxs("section",{"aria-label":K.careTimeline,style:t.section,children:[jsxs("div",{children:[jsx("h3",{style:t.sectionTitle,children:K.careTimeline}),jsx("p",{style:t.sectionSub,children:K.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(Lf,{series:l,styles:t},l.key))]},n.entityType??"_"))]})}i(bd,"TrendRangeCard");function Lf({series:e,styles:r}){let t=useMemo(()=>yd([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(Ff,{model:t,styles:r})}i(Lf,"SeriesChart");function Ff({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(Ff,"TrendChart");function zf(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,...O(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`,...O(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,...O(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,...O(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,...O(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",...O(e,"regular"),fontSize:n.size.tiny,lineHeight:l(n.size.tiny,n.lineHeight.normal),color:r.text.muted}}}i(zf,"makeStyles");var Bf=300,jf=900,hd=120,vd=44,Cd=40,Ed=24,Hf=3;function vt(e,r,t){let o=Vr(e,t);switch(o.kind){case "consent_required":return jsx(Vf,{onGrant:r});case "consent_unavailable":return jsx(Xe,{label:W.consentRequired,glyph:"empty"});case "session_required":return jsx(Xe,{label:W.sessionRequired,glyph:"empty"});case "withheld":return jsx(Xe,{label:W.recordUnavailable,glyph:"withheld"});case "pet_not_found":case "error":return jsx(Gf,{error:o.error,onRetry:e.refresh});default:return Dr(o)}}i(vt,"renderErrorFamily");function xd(){let{theme:e,styles:r}=nn(),[t,o]=useState(false),n=useRef(null);useEffect(()=>{let a=setTimeout(()=>o(true),Bf);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:jf,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(xd,"LoadingState");function Sd({records:e}){let{styles:r}=nn(),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=ko(dd(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?Nt.uploading(n,o.length):Nt.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:ld(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(Sd,"UploadQueue");function Vf({onGrant:e}){let{styles:r}=nn();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(Vf,"ConsentRequiredState");function Xe({label:e,glyph:r}){let{styles:t}=nn();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(Xe,"AlertState");function Gf({error:e,onRetry:r}){let{styles:t}=nn();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 wd({call:e,prompt:r}){let{styles:t}=nn(),o=r.trim().length>0?r:On.fallbackPrompt;return jsxs("div",{style:t.callCard,children:[jsx("p",{style:t.timelineLabel,children:On.heading}),jsx("p",{style:t.timelineMeta,children:o}),jsx("a",{href:e.dial,"aria-label":On.callAt(e.phone),style:t.linkButton,"data-testid":"records-call-clinic",children:On.call})]})}i(wd,"ClinicCallCard");function nn(){let e=ce(),r=useMemo(()=>Wf(e),[e]);return {theme:e,styles:r}}i(nn,"useRecordsTheme");function Wf(e){let{color:r,space:t,radius:o,type:n,slots:l}=e,a=i((m,h)=>`${Math.round(m*h)}px`,"lh"),d=`1px solid ${r.brandBorder}`,s=Ar(l.recordCard,1),c=Wr(l.recordCard),u=i((m,h,v,E="regular")=>({margin:0,...O(e,E),fontSize:m,lineHeight:a(m,h),color:v}),"text"),p=i((m,h,v,E="regular")=>({...u(m,h,v,E),...c}),"inCard"),f={boxSizing:"border-box",minHeight:vd,minWidth:vd,padding:`${t.md}px ${t.xl}px`,borderRadius:o.pill,...O(e,"bold"),fontSize:n.size.body,letterSpacing:n.letterSpacing.tight},b={boxSizing:"border-box",width:Cd,height:Cd},y=e.brightness==="dark"?r.errorRed:r.danger;return {container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:hd,height:"100%",backgroundColor:r.background,color:r.text.primary,...O(e,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:hd,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:t.lg,padding:t.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:Ed,height:Ed,borderRadius:o.pill,border:`${Hf}px solid ${r.brandSofter}`,borderTopColor:r.brand},emptyGlyph:{...b,borderRadius:o.lg,backgroundColor:r.brandSoft,border:d},withheldGlyph:{...b,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,y),primaryButton:{...f,border:0,cursor:"pointer",backgroundColor:r.primary,color:r.onPrimary,...Ar(l.primaryButton),...Wr(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,...Ar(l.primaryButton),...Wr(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(Wf,"makeStyles");var Io="everfur-record.pdf";function Ao(e){return typeof navigator>"u"||!navigator.clipboard?Promise.reject(new Error("clipboard unavailable")):navigator.clipboard.writeText(e)}i(Ao,"copyText");function Yf(e){return typeof e=="object"&&e!==null&&e.name==="AbortError"}i(Yf,"isAbort");async function _d(e,r=Ao){let t=typeof navigator>"u"?void 0:navigator;if(t!==void 0&&typeof t.share=="function")try{return await t.share({url:e}),"shared"}catch(o){if(Yf(o))return "dismissed"}return await r(e),"copied"}i(_d,"shareLinkInPlace");function Kf(e,r){let t;try{t=new URL(e,r);}catch{return null}if(t.protocol==="blob:"||t.protocol==="data:")return "download";if(r!==void 0)try{if(new URL(r).origin===t.origin)return "download"}catch{}let o=t.searchParams.get("response-content-disposition");return o!==null&&/^\s*attachment\b/i.test(o)?"attachment":null}i(Kf,"inPlaceRoute");function Qf(){return typeof location>"u"?void 0:location.href}i(Qf,"locationHref");function Xf(e=typeof window>"u"?void 0:window){if(e===void 0)return false;try{return e.self!==e.top}catch{return true}}i(Xf,"isFramedDocument");function kd(e,r){let t=document.createElement("a");t.href=e,t.download=r,t.rel="noopener",t.style.display="none",document.body.appendChild(t);try{t.click();}finally{t.remove();}}i(kd,"clickDownload");var Jf=6e4;function Zf(e){let r=document.createElement("iframe");r.setAttribute("sandbox","allow-downloads"),r.setAttribute("aria-hidden","true"),r.tabIndex=-1,r.style.display="none",r.src=e,document.body.appendChild(r),setTimeout(()=>r.remove(),Jf);}i(Zf,"saveThroughNestedFrame");async function on(e,r,t=Xf()){if(typeof document>"u")return false;let o=Kf(e,Qf());if(o==="attachment"&&t)return Zf(e),true;if(o!==null)return kd(e,r),true;let n;try{let a=await fetch(e,{credentials:"omit"});if(!a.ok)return !1;n=await a.blob();}catch{return false}let l=URL.createObjectURL(n);try{kd(l,r);}finally{setTimeout(()=>URL.revokeObjectURL(l),1e4);}return true}i(on,"downloadInPlace");var gr=K.document,Pd=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),ry=i((e,r)=>e.getRecordDepth(r),"readDepth"),ty=i(e=>!e.available,"depthEmpty");function ny(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(ny,"documentIsEmpty");function Nn(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onBack"]),{userRef:l}=ee(),{theme:a,styles:d}=j();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),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(Xe,{label:W.sessionRequired,glyph:"empty"})}):jsx(oy,{...n}),jsx(De,{})]})})}i(Nn,"EverfurRecordDocument");function oy({petRef:e,petName:r,controller:t,consentVersion:o,onBack:n,onOpenUrl:l}){let{theme:a,styles:d}=j(),s=Td(),c=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),u=Ge(c),p=zr(e,ry,ty),f=ta(e),b=tt(o,u.consent),y=i(()=>{let C=Hr(o,u.consent);C.length!==0&&u.grantConsent(C,`records-consent-${Date.now().toString(36)}`);},"onGrant"),m=p.value!==null&&!p.value.withheld&&p.value.available?p.value:null,h=u.record,[v,E]=useState(false),g=i(()=>{E(false),f.pdfLink().then(C=>{C.ok&&(l?Et(l,C.value.downloadUrl,"record_pdf"):on(C.value.downloadUrl,Io).then(k=>E(!k)));});},"download"),R,S=false;if(u.status==="loading"||p.status==="loading"&&h!==null)R=jsx("div",{"data-testid":"record-document-loading",children:jsx(xd,{})});else if(u.status==="error"){let C=Vr(u,b);R=C.kind==="error"||C.kind==="pet_not_found"?jsx(Fe,{variant:Qe(C.error),message:C.error.displayMessage,onAction:C.error.retryable?()=>{u.refresh(),p.refresh();}:void 0,testID:"record-document-error"}):vt(u,y,b);}else h===null||ny(h,m)?R=jsx("p",{style:s.empty,"data-testid":"record-document-empty",children:gr.empty}):(S=true,R=jsx(iy,{record:h,depth:m,petName:r,wordmark:a.meta.displayName}));return jsxs(Fragment,{children:[jsx(He,{title:gr.title,variant:"document",onBack:n,testID:"record-document-header",right:f.available&&S?jsx("button",{type:"button",onClick:g,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}):v?jsx("p",{role:"alert",style:{...d.errorText,padding:`0 ${a.space.lg}px`},"data-testid":"record-document-save-failed",children:_t(null,"download")}):null,jsx("div",{style:d.body,children:R})]})}i(oy,"DocumentBody");function iy({record:e,depth:r,petName:t,wordmark:o}){let n=Td(),l=useMemo(()=>{let c=[],u=new Map;for(let b of e.entities){let y=b.category.trim();if(y.length===0)continue;let m=u.get(y);m===void 0?(c.push(y),u.set(y,[b])):m.push(b);}let p=Pd.filter(b=>c.includes(b)),f=c.filter(b=>!Pd.includes(b));return [...p,...f].map(b=>({type:b,rows:u.get(b)??[]}))},[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=Yr(c.latest.status),f=od(c.points[c.points.length-1]??null),b=ur(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 ${J(c.latest.at)}`:""]})]}),jsxs("span",{style:n.rowRight,children:[b!=="-"?jsx("span",{style:{...n.rowValue,...p.outOfRange?n.alert:{}},children:b}):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(qt(c),u.map((p,f)=>{let b=[Ht(p.value,p.unit),p.observedAt?J(p.observedAt):null].filter(y=>y&&y.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}),b?jsx("span",{style:n.rowMeta,children:b}):null]})},p.key)}),`record-document-${c}`)),e.forwardLooking.length>0?d(gr.upcomingCare,e.forwardLooking.map((c,u)=>{let p=Tn(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:J(c.observedOn)}):null,c.systems.filter(p=>p.finding).map(p=>jsxs("div",{style:n.fieldRow,children:[jsx("span",{style:n.fieldLabel,children:Gt(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:J(c.observedOn)}):null,c.sections.filter(p=>p.text).map((p,f)=>jsxs("div",{style:n.noteSection,children:[jsx("span",{style:n.noteLabel,children:Wt(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(iy,"RecordDocument");function Td(){let e=ce();return useMemo(()=>ay(e),[e])}i(Td,"useDocStyles");function ay(e){let{color:r,space:t,radius:o,type:n}=e,l=i((s,c,u,p="regular")=>({margin:0,...O(e,p),fontSize:s,lineHeight:`${Math.round(s*c)}px`,color:u}),"text"),a=i((s,c)=>({margin:0,...O(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`,...O(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,...O(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(ay,"makeDocStyles");var er=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 Dd(e,r){return Jr(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.":Nl(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(Dd,"factEditErrorMessage");var ly=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function da(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(da,"applyFactOverlay");function ca(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(ca,"isFactEditable");function dy(){return `records-fact-${Date.now().toString(36)}`}i(dy,"defaultFactKey");function ua(e,r={}){let t=pr(),{userRef:o}=ee(),[n,l]=useState(ly),[a,d]=useState(false),[s,c]=useState(null),u=useMemo(()=>({}),[t,e,o]),[p,f]=useState(null),b=useCallback(()=>f(u),[u]),y=o!==null&&p!==u,m=useRef(false),h=useRef(r.newIdempotencyKey);h.current=r.newIdempotencyKey;let v=useCallback(()=>(h.current??dy)(),[]),E=useCallback((C,k,_)=>{if(d(false),!C.ok){if(k(),Rt(C.error)){b();return}c(Dd(C.error,_));}},[b]),g=useCallback(async(C,k)=>{let _=C.canonicalKey??"",T=k.trim();if(m.current||_.length===0||T.length===0)return Y(z("validationFailed",{retryable:false}));m.current=true,d(true),c(null);let I=n;l(q=>({...q,edits:{...q.edits,[_]:T}}));let F=await t.editFact(e,{entityType:C.category,canonicalKey:_,correctedFields:Gi(C.value,T),idempotencyKey:v()});return m.current=false,E(F,()=>l(I),"edit"),F},[t,e,n,E,v]),R=useCallback(async C=>{let k=C.canonicalKey??"";if(m.current||k.length===0)return Y(z("validationFailed",{retryable:false}));m.current=true,d(true),c(null);let _=n;l(I=>({...I,removed:[...I.removed,k]}));let T=await t.removeFact(e,{entityType:C.category,canonicalKey:k,idempotencyKey:v()});return m.current=false,E(T,()=>l(_),"remove"),T},[t,e,n,E,v]),S=useCallback(()=>c(null),[]);return useMemo(()=>({overlay:n,busy:a,error:s,available:y,edit:g,remove:R,clearError:S}),[n,a,s,y,g,R,S])}i(ua,"useRecordFactEdit");var cy=Object.freeze({vaccination:"Vaccination",medication:"Medication",problem:"Problem",body_weight:"Weight",allergy:"Allergy",vital:"Vital",lab_result:"Lab result",parasite_prevention:"Preventive"}),uy="Given",py=/^\d{4}-\d{2}-\d{2}/,my=" \xB7 ";function at(e){let r=e.filter(t=>t!==null&&t.trim().length>0);return r.length>0?r.join(my):null}i(at,"joinDetail");function fy(e,r){let t=e.label.trim();if(t.length>0)return t;let o=cy[e.category];return o!==void 0?o:r(e.category)}i(fy,"rowTitle");function Ad(e,r){let t=fy(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&&py.test(e.value.trim()),s=d?r.formatRecordsDate(e.value):a;return s!==null&&s!=="-"?{title:t,detail:at([`${uy} ${s}`,d?null:n])}:{title:t,detail:at([n])}}case "medication":return {title:t,detail:at([a])};case "problem":return {title:t,detail:at([a])};case "body_weight":return {title:t,detail:at([a])};case "allergy":return {title:t,detail:at([a])};case "vital":return {title:t,detail:at([n,a])};case "lab_result":return {title:t,detail:at([n,a])};default:return {title:t,detail:at([n,a])}}}i(Ad,"entityRowSummary");function No(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(No,"markerStatusTone");function yy(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(yy,"markerStatusSpoken");function gy(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(gy,"rangePhrase");function Lo(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(Lo,"formatReferenceRange");function pa(e,r){let t=r.reviewed?", reviewed by our team":"",o=r.sourceClinic?`, from ${r.sourceClinic}`:"";return `${J(r.at)}: ${ur(r.value,e.unit,r.qualitativeResult)}, ${yy(r.status)}${gy(r)}${o}${t}`}i(pa,"markerPointSpoken");function Ve(e){return e?.trim()||"my pet"}i(Ve,"lead");function qd(e){let r=e.trim();return /[.!?]$/.test(r)?r:`${r}.`}i(qd,"clause");function Nd(e,r){let t=r.canonicalName.trim()||"a lab marker",o=[`I'm looking at ${Ve(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(qd(r.meaningText)),o.push(`What does this trend tell me, and should I do anything differently for ${Ve(e)}?`),{prompt:o.join(" "),entityRef:{type:"marker",id:r.markerId,payload:{marker:t,...r.statusText?.trim()?{status:r.statusText.trim()}:{}}}}}i(Nd,"buildMarkerAskPrompt");function Ld(e,r,t){let{totalMarkers:o,inRangeCount:n,outOfRangeCount:l,unknownCount:a}=r;if(o===0)return {prompt:`I'm looking at ${Ve(e)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${Ve(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 ${Ve(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(Ld,"buildMarkerSummaryAskPrompt");function Fd(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 ${Ve(e)}'s ${o.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:r.entityId,payload:n}}}i(Fd,"buildMarkerReadingAskPrompt");function zd(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 ${Ve(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(zd,"buildRecordsRequestAskPrompt");var by=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function Md(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 ${Ve(e)}'s ${n.toLowerCase()}: ${l}${a?`, ${a}`:""}. What does this mean, and what should I keep on top of for ${Ve(e)}?`,entityRef:{type:by[t]??t,id:o,payload:{kind:n,title:l,...a?{detail:a}:{}}}}}i(Md,"buildEntityRowAskPrompt");function $d(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 ${Ve(e)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${Ve(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 ${Ve(e)}'s upcoming care: ${l.join(", ")}. What should I prioritize for ${Ve(e)}, and how do I stay on top of these?`,entityRef:n}}i($d,"buildUpcomingCareAskPrompt");function Ud(e,r,t){let o=[`I'm looking at ${Ve(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 ${Ve(e)}?`)):o.push(`Everything examined came back normal. What does this tell me about ${Ve(e)}'s health?`),{prompt:o.join(" "),entityRef:{type:"physical_exam",id:t}}}i(Ud,"buildPhysicalExamAskPrompt");function Bd(e,r,t){let o=[`I'm looking at ${Ve(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"}: ${qd(n.text)}`);return o.push(`Can you summarize what happened and what I should follow up on for ${Ve(e)}?`),{prompt:o.join(" "),entityRef:{type:"visit",id:t}}}i(Bd,"buildVisitNoteAskPrompt");function jd(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 ${Ve(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(jd,"buildConflictAskPrompt");var Vd='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function Gd(e){return e.tagName==="DIALOG"}i(Gd,"isDialogElement");function Wd(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;u&&u.isConnected&&u.focus(),(!u||!u.isConnected||document.activeElement===u)&&(l.current=null);},[]);useEffect(()=>{if(!e){d();return}let u=o.current;if(!n.current){let f=typeof document>"u"?null:document.activeElement;f!==null&&u!==null&&u.contains(f)||(l.current=f instanceof HTMLElement?f:null);}if(n.current=true,u===null)return;if(!Gd(u)){u.contains(document.activeElement)||(u.querySelector(Vd)??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"&&!Gd(p)){u.preventDefault(),u.stopPropagation(),r();return}if(u.key!=="Tab")return;let f=Array.from(p.querySelectorAll(Vd)),b=f[0],y=f[f.length-1];if(!b||!y){u.preventDefault();return}let m=document.activeElement;u.shiftKey&&(m===b||!p.contains(m))?(u.preventDefault(),y.focus()):!u.shiftKey&&(m===y||!p.contains(m))&&(u.preventDefault(),b.focus());},[r]),c=useCallback(u=>{u.preventDefault(),r();},[r]);return {dialogRef:o,onKeyDown:s,onCancel:c}}i(Wd,"useModalDialog");var hy='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function Ct({label:e,onClose:r,shape:t="modal",returnFocusTo:o,panelStyle:n,testID:l,children:a}){let{styles:d}=j(),s=Wd(true,r,o);useEffect(()=>{let u=s.dialogRef.current;u===null||u.contains(document.activeElement)||(u.querySelector(hy)??u).focus();},[s.dialogRef]);let c=t==="side";return jsx("dialog",{ref:s.dialogRef,"aria-label":e,"aria-modal":"true",onCancel:s.onCancel,onKeyDown:s.onKeyDown,style:d.dialogFrame,"data-testid":l,children:jsx("div",{style:c?d.dialogScrimSide:d.dialogScrim,onClick:u=>{u.target===u.currentTarget&&r();},"data-testid":l?`${l}-scrim`:void 0,children:jsx("div",{style:{...c?d.dialogPanelSide:d.dialogPanel,...n},children:a})})})}i(Ct,"RecordsDialog");function Yd({entity:e,factEdit:r,children:t}){let{theme:o,styles:n}=j(),[l,a]=useState(false),d=useRef(null),s=e.label.trim()||er.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":er.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(Ey,{entity:e,title:s,factEdit:r,onClose:()=>a(false),returnFocusTo:d}):null]})}i(Yd,"FactEditAffordance");function Ey({entity:e,title:r,factEdit:t,onClose:o,returnFocusTo:n}){let{theme:l,styles:a}=j(),[d,s]=useState(e.value??""),[c,u]=useState(null),[p,f]=useState(false);useEffect(()=>{t.clearError();},[t]);let b=d.trim().length>0&&d.trim()!==(e.value??"").trim(),y=c??t.error,m=t.busy,h=i(()=>{if(!b){u(er.noChange);return}u(null),t.edit(e,d).then(g=>{g.ok&&o();});},"submitEdit"),v=i(()=>{u(null),t.remove(e).then(g=>{g.ok?o():f(false);});},"submitRemove"),E=`fact-edit-${e.key}`;return jsxs(Ct,{label:er.title(r),onClose:o,returnFocusTo:n,testID:"fact-edit-sheet",children:[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:er.title(r)}),jsx("p",{role:"status","aria-live":"polite",style:{...a.sheetHelper,...y?a.errorText:{}},children:y??er.helper})]}),jsx("button",{type:"button",onClick:o,"aria-label":er.close,style:a.iconButton,"data-testid":"fact-edit-close",children:jsx("span",{style:a.closeGlyph,"aria-hidden":"true",children:"\xD7"})})]}),jsx("label",{htmlFor:E,style:a.fieldLabel,children:e.label}),jsx("input",{id:E,style:a.field,value:d,onChange:g=>{s(g.target.value),u(null);},disabled:m,maxLength:512,"data-testid":"fact-edit-field"}),p?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:er.confirmRemove}),jsxs("div",{style:{display:"flex",gap:l.space.sm},children:[jsx(B,{label:m?er.removing:er.removeConfirm,kind:"danger",busy:m,onClick:v,style:{flex:1},testID:"fact-edit-remove-confirm"}),jsx(B,{label:er.keep,kind:"outline",disabled:m,onClick:()=>f(false),style:{flex:1},testID:"fact-edit-remove-cancel"})]})]}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:l.space.sm},children:[jsx(B,{label:m?er.saving:er.save,busy:m,disabled:!b,onClick:h,testID:"fact-edit-save"}),jsx("button",{type:"button","aria-label":er.removeA11y(r),disabled:m,onClick:()=>{u(null),f(true);},style:{...a.pill,...a.pillLink,color:l.color.danger,...m?a.pillDisabled:{}},"data-testid":"fact-edit-remove",children:er.remove})]})]})}i(Ey,"FactEditSheet");function Mo({record:e,depth:r,petName:t,showLabs:o=true,onNavigate:n,onAsk:l,factEdit:a,nowMs:d}){let{theme:s,styles:c}=j(),u=d??Date.now(),p=useMemo(()=>a?da(e.entities,a.overlay):e.entities,[e.entities,a]),f=useMemo(()=>{let g=[],R=new Map;for(let S of p){let C=S.category.trim();if(C.length===0)continue;let k=R.get(C);k===void 0?(g.push(C),R.set(C,[S])):k.push(S);}return {order:nd(g),groups:R}},[p]),b=Object.values(e.documents),y=a!==void 0&&a.available,m=i((g,R,S)=>l?jsx("button",{type:"button",onClick:()=>{let C=g();l(C.prompt,C.entityRef);},"aria-label":R,style:{...c.pill,...c.pillAsk,marginTop:s.space.lg,alignSelf:"flex-start"},"data-testid":S,children:R}):null,"ask"),h={display:"flex",flexDirection:"column",gap:s.space.lg+s.space.xs},v=i(g=>({...c.row,...g>0?c.rowDivider:{}}),"rowStyle"),E={...c.card,padding:`${s.space.md}px ${s.space.lg}px`,display:"flex",flexDirection:"column"};return jsxs(Fragment,{children:[jsxs("div",{style:h,children:[r&&r.conflicts.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-conflicts",children:[jsx(qr,{title:K.needsAttention,count:r.conflicts.length}),[...r.conflicts].sort((g,R)=>xo(g.severity).rank-xo(R.severity).rank).map(g=>{let R=xo(g.severity),S=Kr(g.field??g.entityType);return jsxs("div",{style:{...E,borderColor:c.chipTones[R.tone].color,gap:s.space.sm},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.space.sm},children:[jsx("span",{style:{...c.rowTitle,...O(s,"bold"),flex:1},children:R.label}),jsx(cr,{label:S,tone:R.tone})]}),jsx("p",{style:c.rowDetail,children:K.conflictSub}),g.candidates.map((C,k)=>jsxs("div",{style:{borderTop:`1px solid ${s.color.borderHairlineGreen}`,paddingTop:s.space.sm},children:[jsx("p",{style:c.rowTitle,children:C.value}),jsx("p",{style:c.rowMuted,children:[C.docId?e.documents[C.docId]?.title??K.uploadedDocument:K.uploadedDocument,C.collectedAt?J(C.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},k)),m(()=>jd(t,{scopeLabel:S,severity:g.severity,candidates:g.candidates.map(C=>({value:C.value,clinicName:C.docId?e.documents[C.docId]?.title??null:null}))},g.conflictId),K.askConflict,`records-ask-conflict-${g.conflictId}`)]},g.conflictId)})]}):null,r?.completeness?jsxs("section",{style:c.section,"data-testid":"record-section-completeness",children:[jsx(qr,{title:K.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:[[K.coverage.labs,r.completeness.hasLabHistory],[K.coverage.vaccines,r.completeness.hasVaccinationHistory],[K.coverage.weight,r.completeness.hasWeightHistory],[K.coverage.vitals,r.completeness.hasVitalsHistory],[K.coverage.exams,r.completeness.hasPhysicalExamHistory],[K.coverage.procedures,r.completeness.hasProcedureHistory],[K.coverage.genetics,r.completeness.hasGeneticHistory],[K.coverage.parasite,r.completeness.hasParasitePreventionHistory],[K.coverage.reproductive,r.completeness.hasReproductiveHistory]].map(([g,R])=>jsx("span",{"aria-label":`${g}: ${R?K.onFile:K.noneOnFile}`,style:{...c.chip,...R?c.chipTones.positive:{backgroundColor:s.color.badgeBgNeutral,color:s.color.text.muted},fontSize:s.type.size.caption},children:g},g))}),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:K.documentsOnFile(r.completeness.documentsIngested)}),r.completeness.documentsInReview>0?jsx(cr,{label:K.inReviewChip(r.completeness.documentsInReview),tone:"warning"}):null,ya(r.completeness.heldTotal,r.completeness.entitiesPendingReview)>0?jsx("span",{"aria-label":K.beingVerifiedA11y(ya(r.completeness.heldTotal,r.completeness.entitiesPendingReview)),children:jsx(cr,{label:K.beingVerified(ya(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:K.dateRange(r.completeness.earliestRecordAt,r.completeness.latestRecordAt)}):null,Object.entries(r.completeness.entitiesPendingReview).filter(([,g])=>g>0).length>0?jsxs("p",{style:{...c.rowMuted,paddingBottom:s.space.md},children:[K.pendingReview,Object.entries(r.completeness.entitiesPendingReview).filter(([,g])=>g>0).map(([g,R])=>`${qt(g)} (${R})`).join(", ")]}):null]})]}):null,b.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-documents",children:[jsx(qr,{title:K.documents,count:b.length}),jsx("ul",{style:c.card,children:b.map((g,R)=>{let S=g.title?.trim()||K.uploadedDocument,C=g.receivedAt?J(g.receivedAt):null,k=jsxs(Fragment,{children:[jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:S}),C?jsx("span",{style:{...c.rowDetail,display:"block"},children:C}):null]}),n?jsx(kt,{}):null]});return jsx("li",{style:v(R),children:n?jsx("button",{type:"button",onClick:()=>n({name:"contributions",docId:g.docId}),"aria-label":K.documentRowA11y(S),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-${g.docId}`,children:k}):k},g.docId)})})]}):null,e.identity.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-identity",children:[jsx(qr,{title:K.identity}),jsx("dl",{style:c.card,children:e.identity.map((g,R)=>jsxs("div",{style:v(R),children:[jsx("dt",{style:{...c.rowDetail,...O(s,"medium"),marginTop:0},children:g.label}),jsx("dd",{style:{...c.rowTitle,margin:0,textAlign:"right"},children:g.value})]},`${R}:${g.label}`))})]}):null,jsx(bd,{series:e.entitySeries}),e.forwardLooking.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-upcoming",children:[jsx(qr,{title:K.upcomingCare,count:e.forwardLooking.length}),jsx("ul",{style:c.card,children:e.forwardLooking.map((g,R)=>{let S=Tn(g.dueAt,u);return jsxs("li",{style:v(R),children:[jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:g.title}),g.detail?jsx("span",{style:{...c.rowDetail,display:"block"},children:g.detail}):null]}),S?jsx(cr,{label:S.label,tone:S.overdue?"critical":"info"}):null]},`${g.title}-${R}`)})}),m(()=>$d(t,e.forwardLooking.map(g=>{let R=Tn(g.dueAt,u);return {label:g.title,relativeText:R?.label??"",tone:R?.overdue?"overdue":"upcoming"}}),e.petRef),K.askUpcomingCare,"records-ask-upcoming-care")]}):null,f.order.map(g=>{let R=f.groups.get(g)??[];if(R.length===0)return null;let S=qt(g);return jsxs("section",{style:c.section,"data-testid":`record-section-${g}`,children:[jsx(qr,{title:S,count:R.length}),jsx("ul",{style:c.card,children:R.map((C,k)=>{let _=Ad(C,{formatEntityValue:Ht,formatRecordsDate:J,humanize:Kr}),T=_.detail,I=jsxs("div",{style:v(k),children:[jsxs("div",{style:{...c.rowMain,display:"flex",flexDirection:"column"},children:[jsx("span",{style:c.rowTitle,children:_.title}),T?jsx("span",{style:c.rowDetail,children:T}):null,m(()=>Md(t,{entityTypeLabel:S,title:_.title,detail:T},g,C.key),K.askEverfur,`records-ask-entity-${C.key}`)]}),C.status?jsx(cr,{label:Kr(C.status)}):null]});return jsx("li",{children:y&&ca(C)&&a?jsx(Yd,{entity:C,factEdit:a,children:I}):I},C.key)})})]},g)}),r&&r.physicalExams.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-exams",children:[jsx(qr,{title:K.physicalExams,count:r.physicalExams.length}),r.physicalExams.map(g=>jsxs("div",{style:E,children:[jsx("h4",{style:{...c.rowTitle,paddingTop:s.space.sm},children:g.observedOn?J(g.observedOn):me.exam}),jsx("ul",{style:c.plainList,children:g.systems.map((R,S)=>{let C=R.findingStatus==="abnormal",k=C?me.abnormal:R.findingStatus==="not_examined"?me.notExamined:me.normal;return jsxs("li",{style:v(S),children:[jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:Gt(R.system)}),C&&R.finding?jsx("span",{style:{...c.rowDetail,display:"block"},children:R.finding}):null]}),jsx(cr,{label:k,tone:C?"warning":R.findingStatus==="not_examined"?"neutral":"positive"})]},R.system)})}),m(()=>Ud(t,{observedOn:g.observedOn?J(g.observedOn):null,abnormal:g.systems.filter(R=>R.findingStatus==="abnormal").map(R=>({system:Gt(R.system),finding:R.finding??""}))},g.examId),K.askExam,`records-ask-exam-${g.examId}`)]},g.examId))]}):null,r&&r.clinicianNotes.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-notes",children:[jsx(qr,{title:K.visitNotes,count:r.clinicianNotes.length}),r.clinicianNotes.map(g=>jsxs("div",{style:E,children:[jsx("h4",{style:{...c.rowTitle,paddingTop:s.space.sm},children:g.observedOn?J(g.observedOn):me.visitNote}),jsx("dl",{style:c.plainList,children:g.sections.map((R,S)=>jsxs("div",{style:{padding:`${s.space.md}px 0`,...S>0?c.rowDivider:{}},children:[jsx("dt",{style:{...c.rowDetail,...O(s,"bold"),marginTop:0,textTransform:"uppercase"},children:Wt(R.section)}),jsx("dd",{style:{...c.bodyText,marginLeft:0,...R.text?{}:{color:s.color.text.muted,fontStyle:"italic"}},children:R.text||me.notRecorded})]},`${R.section}:${S}`))}),m(()=>Bd(t,{observedOn:g.observedOn?J(g.observedOn):null,sections:g.sections.map(R=>({label:Wt(R.section),text:R.text}))},g.noteId),K.askVisit,`records-ask-note-${g.noteId}`)]},g.noteId))]}):null,o&&r&&r.labResults.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-labs",children:[jsx(qr,{title:K.labResults,count:r.labResults.length}),jsx("ul",{style:c.card,children:r.labResults.map((g,R)=>{let S=Yr(g.latest.status),C=Mi(g.latest.at,g.trajectory,g.points.length);return jsxs("li",{style:v(R),children:[jsxs("span",{style:{...c.rowMain,display:"flex",flexDirection:"column"},children:[jsx("span",{style:c.rowTitle,children:g.name}),jsx("span",{style:c.rowValue,children:ur(g.latest.value,g.latest.unit,g.latest.qualitativeResult)}),C?jsx("span",{style:c.rowDetail,children:C}):null]}),jsx(cr,{label:S.label,tone:No(g.latest.status)})]},g.markerId)})})]}):null,r&&r.encounters.length>0?jsxs("section",{style:c.section,"data-testid":"record-section-visits",children:[jsx(qr,{title:K.visits,count:r.encounters.length}),jsx("ul",{style:c.card,children:r.encounters.map((g,R)=>{let S=[g.date?J(g.date):null,g.clinicName,g.veterinarian].filter(C=>C&&C!=="-").join(" \xB7 ");return jsx("li",{style:v(R),children:jsxs("span",{style:c.rowMain,children:[jsx("span",{style:c.rowTitle,children:g.type?Kr(g.type):me.visit}),S?jsx("span",{style:{...c.rowDetail,display:"block"},children:S}):null]})},g.encounterId)})})]}):null]}),jsx(bt,{disclaimer:e.disclaimer})]})}i(Mo,"RecordSections");function ya(e,r){return e>0?e:Object.values(r).reduce((t,o)=>t+o,0)}i(ya,"heldCount");function Jd({petRef:e,onClose:r,onNavigate:t,onOpenUrl:o,onCopy:n,returnFocusTo:l}){let{theme:a,styles:d}=j(),s=ea(e),[c,u]=useState(null),[p,f]=useState(null),b=s.available&&!s.consentRequired,y=i((R,S)=>{if(o){Et(o,R,S).then(C=>{C.ok||u(se.toasts.shareSheet);});return}if(S==="share_link"){_d(R,n??Ao).then(C=>{C==="copied"&&u(se.toasts.copied);},()=>u(se.toasts.shareSheet));return}on(R,Io).then(C=>{C||u(_t(null,"download"));});},"open"),m=i(()=>{u(null),s.createLink().then(R=>{R.ok?y(R.value.shareUrl,"share_link"):u(_t(R.error,"create"));});},"onCreateLink"),h=i(()=>{u(null),s.pdfLink().then(R=>{R.ok?y(R.value.downloadUrl,"record_pdf"):u(_t(R.error,"download"));});},"onDownload"),v=i(R=>{R.shareUrl!==null&&Et(n??Ao,R.shareUrl).then(S=>u(S.ok?se.toasts.copied:se.toasts.copyFailed));},"onCopyRow"),E=i(R=>{s.revoke(R).then(S=>{f(null),u(S.ok?se.toasts.turnedOff:_t(S.error,"revoke"));});},"onConfirmRevoke"),g={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 jsxs(Ct,{label:se.title,onClose:r,shape:"side",returnFocusTo:l,testID:"share-record-sheet",children:[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:se.title}),jsx("p",{style:d.sheetHelper,children:se.helper})]}),jsx("button",{type:"button",onClick:r,"aria-label":se.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(B,{label:se.viewDocument,onClick:()=>{r(),t({name:"document"});},testID:"share-view-document"}):null,b?jsx(B,{label:s.creating?se.creatingLink:se.createLink,kind:"outline",busy:s.creating,onClick:m,testID:"share-create-link"}):null,b?jsx(B,{label:s.preparingPdf?se.preparingPdf:se.downloadPdf,kind:"outline",busy:s.preparingPdf,onClick:h,testID:"share-download-pdf"}):null]}),s.consentRequired?jsxs("div",{style:g,"data-testid":"share-consent-off",children:[jsx("p",{style:d.rowTitle,children:se.consentOffTitle}),jsx("p",{style:d.muted,children:se.consentOffBody}),jsx(B,{label:se.retry,kind:"outline",onClick:s.refresh,testID:"share-consent-retry"})]}):null,c?jsx("p",{role:"status","aria-live":"polite",style:d.infoNote,"data-testid":"share-notice",children:c}):null,ad(s)?jsxs("section",{"aria-label":se.activeLinks,style:{display:"flex",flexDirection:"column",gap:a.space.sm},children:[jsx("h4",{style:{...d.fieldLabel,...O(a,"bold"),textTransform:"uppercase"},children:se.activeLinks}),s.status==="loading"?jsx(Sl,{testID:"share-record-loading"}):s.status==="error"?jsxs("div",{style:g,"data-testid":"share-record-error",children:[jsx("p",{style:d.rowTitle,children:se.errorTitle}),jsx("p",{style:d.muted,children:se.errorBody}),jsx(B,{label:se.retry,kind:"outline",onClick:s.refresh,testID:"share-record-retry"})]}):s.rows.length===0?jsxs("div",{style:g,"data-testid":"share-record-empty",children:[jsx("p",{style:d.rowTitle,children:se.emptyTitle}),jsx("p",{style:d.muted,children:se.emptyBody})]}):jsx("ul",{style:{...d.plainList,gap:a.space.md},children:s.rows.map(R=>jsxs("li",{style:{...g},"data-testid":`share-row-${R.shareId}`,children:[jsxs("div",{"aria-label":R.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:R.active?a.color.success:a.color.text.muted}}),jsx("span",{style:{...d.rowTitle,...O(a,"bold")},children:R.statusLabel}),jsx("span",{style:d.muted,children:R.expiryLabel})]}),R.createdLabel?jsx("p",{style:d.muted,children:R.createdLabel}):null]}),p===R.shareId?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:a.space.sm},"data-testid":`share-revoke-confirm-${R.shareId}`,children:[jsx("p",{style:d.bodyText,children:se.confirmTurnOff}),jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:a.space.sm},children:[jsx(B,{label:s.revokingId===R.shareId?se.turningOff:se.turnOff,kind:"danger",busy:s.revokingId===R.shareId,onClick:()=>E(R.shareId),testID:`share-revoke-do-${R.shareId}`}),jsx(B,{label:se.keep,kind:"outline",disabled:s.revokingId===R.shareId,onClick:()=>f(null),testID:`share-revoke-cancel-${R.shareId}`})]})]}):jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:a.space.sm},children:[jsx(B,{label:se.copyLink,kind:"outline",disabled:R.shareUrl===null,ariaLabel:se.copyLinkA11y(R.actionContext),onClick:()=>v(R),testID:`share-copy-${R.shareId}`}),jsx(B,{label:se.turnOff,kind:"danger",ariaLabel:se.turnOffA11y(R.actionContext),onClick:()=>f(R.shareId),testID:`share-ask-revoke-${R.shareId}`})]})]},R.shareId))})]}):null]})}i(Jd,"ShareSheet");var ky=i((e,r)=>e.getRecordDepth(r),"readDepth"),_y=i(e=>!e.available,"depthEmpty");function Ln(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack","onAsk"]),{userRef:l}=ee(),{styles:a}=j();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"everfur-record-screen",children:[l===null?jsx("div",{style:a.body,children:jsx(Xe,{label:W.sessionRequired,glyph:"empty"})}):jsx(Py,{...n}),jsx(De,{})]})})}i(Ln,"EverfurRecordDetail");function Py({petRef:e,petName:r,controller:t,consentVersion:o,onNavigate:n,onBack:l,onAsk:a,onOpenUrl:d,onCopy:s}){let{theme:c,styles:u}=j(),p=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),f=Ge(p),b=zr(e,ky,_y),y=ua(e),m=ra(e),[h,v]=useState(false),E=useRef(null),g=tt(o,f.consent),R=i(()=>{let I=Hr(o,f.consent);I.length!==0&&f.grantConsent(I,`records-consent-${Date.now().toString(36)}`);},"onGrant"),S=b.value!==null&&!b.value.withheld&&b.value.available?b.value:null,C=f.record,k=i(()=>{f.refresh(),b.refresh();},"retry"),_=n!==void 0||m.lit===true,T;if(f.status==="loading"||b.status==="loading"&&C!==null&&!C.isEmpty)T=jsx(Yt,{testID:"everfur-record-loading"});else if(f.status==="error"){let I=Vr(f,g);T=I.kind==="error"||I.kind==="pet_not_found"?jsx(Fe,{variant:Qe(I.error),message:I.error.displayMessage,onAction:I.error.retryable?k:void 0,testID:"everfur-record-error"}):vt(f,R,g);}else if(C===null||C.isEmpty){let I=S?.completeness?.documentsInReview??0;T=jsxs("div",{style:u.content,"data-testid":"everfur-record-empty",children:[jsx(Fe,{variant:"no_records",message:I>0?K.inReview(I):void 0}),jsx(bt,{disclaimer:C?.disclaimer??""})]});}else T=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(Mo,{record:C,depth:S,petName:r,onNavigate:n,onAsk:a,factEdit:y})});return jsxs(Fragment,{children:[jsx(He,{title:K.title,onBack:l,testID:"everfur-record-header",right:_||n?jsxs(Fragment,{children:[n?jsx("button",{type:"button",onClick:()=>n({name:"clinicBatch"}),"aria-label":K.requestClinicsA11y,style:u.iconButton,"data-testid":"everfur-record-request-clinics",children:jsx(Fi,{name:"send",color:c.color.brand})}):null,_?jsx("button",{ref:E,type:"button",onClick:()=>v(true),"aria-label":K.shareA11y,style:u.iconButton,"data-testid":"everfur-record-share",children:jsx(Fi,{name:"share2",color:c.color.brand})}):null]}):void 0}),jsx("div",{style:u.body,children:T}),h?jsx(Jd,{petRef:e,onClose:()=>v(false),returnFocusTo:E,onNavigate:n,...d?{onOpenUrl:d}:{},...s?{onCopy:s}:{}}):null]})}i(Py,"RecordBody");var Uo=Object.freeze({download:"Download",downloadA11y:i(e=>`Download, ${e}`,"downloadA11y"),listA11y:"You added these records"});function Ty(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(Ty,"formatBytes");function Dy(e){let r=e?.trim();return r?r.toUpperCase():null}i(Dy,"formatLabel");function ga(e){return Object.freeze(e.map(r=>{let t=Dy(r.docFormat),o=r.receivedAt?J(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?Ty(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(ga,"requestDocumentRows");function ec(e){let r=e.fileName?.trim()||e.sourceDocId,t=e.docFormat?.trim().toLowerCase().replace(/^\./,"")??"";return t.length===0||r.toLowerCase().endsWith(`.${t}`)?r:`${r}.${t}`}i(ec,"requestDocumentFileName");function Ra(e,r={}){let t=r.enabled??true,o=pr(),{userRef:n}=ee(),[l,a]=useState(null),[d,s]=useState(t),[c,u]=useState(null),p=useRef(0),f=useRef(true),b=useCallback(async()=>{let v=p.current+=1;if(!t||n===null){a(null),u(null),s(false);return}s(true),u(null);let E=await o.listRequestDocuments(e);v!==p.current||!f.current||(E.ok?a(E.value):(a(null),u(E.error)),s(false));},[o,t,e,n]);useEffect(()=>(f.current=true,b(),()=>{f.current=false,p.current+=1;}),[b]);let y=useMemo(()=>l===null?[]:ga(l),[l]),m=useCallback(()=>{b();},[b]),h=d?"loading":c!==null?"error":y.length===0?"empty":"populated";return useMemo(()=>({status:h,rows:y,error:c,refresh:m}),[h,y,c,m])}i(Ra,"useRequestDocuments");function Fn({requestId:e,open:r=true,onOpenUrl:t,testID:o="records-request-documents"}){let{theme:n,styles:l}=j(),a=Ra(e,{enabled:r}),d=pr(),[s,c]=useState(null),[u,p]=useState(null),f=useRef(true);useEffect(()=>(f.current=true,()=>{f.current=false;}),[]);let b=i(async y=>{c(y.key),p(null);let m=await d.listRequestDocuments(e),h=m.ok?m.value.find(E=>E.sourceDocId===y.key)??null:null,v=h===null;h!==null&&f.current&&(t?await Et(t,h.downloadUrl,"request_document"):v=!await on(h.downloadUrl,ec(h))),f.current&&(c(null),v&&p(y.key));},"save");return r?a.status==="loading"?jsx("div",{style:{paddingTop:n.space.sm},"aria-busy":"true","data-testid":`${o}-loading`,children:jsx(fe,{width:"100%",height:n.space.lg+n.space.md})}):a.status==="error"?jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:n.space.sm,paddingTop:n.space.sm},"data-testid":`${o}-error`,children:[jsx("p",{style:{...l.muted,margin:0},role:"alert",children:a.error?.displayMessage??""}),a.error?.retryable===true?jsx(B,{label:W.retry,kind:"outline",onClick:a.refresh,testID:`${o}-retry`}):null]}):a.status==="empty"?null:jsx("ul",{"aria-label":Uo.listA11y,style:{...l.plainList,paddingTop:n.space.sm},"data-testid":o,children:a.rows.map((y,m)=>jsxs("li",{style:qy(n.space.sm,m===0?null:n.color.brandBorder),children:[jsxs("div",{style:{minWidth:0},children:[jsx("p",{style:{...l.rowTitle,margin:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:y.title}),y.meta!==null?jsx("p",{style:{...l.muted,margin:0,fontVariantNumeric:"tabular-nums"},children:y.meta}):null]}),jsx(B,{label:Uo.download,kind:"outline",ariaLabel:Uo.downloadA11y(y.title),busy:s===y.key,onClick:()=>{b(y);},testID:`${o}-download-${y.key}`}),u===y.key?jsx("p",{role:"alert",style:{...l.errorText,flexBasis:"100%"},"data-testid":`${o}-save-failed-${y.key}`,children:fo.error.title}):null]},y.key))}):null}i(Fn,"RequestDocumentsList");function qy(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(qy,"rowStyle");var Ny=Math.round(Br/(1024*1024)),rr=Object.freeze({title:i(e=>`Upload ${Pe(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 ${Pe(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 ${Ny} 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 ${Math.min(e+1,r)} 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 zn(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack"]),{userRef:l}=ee(),{styles:a}=j();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"upload-screen",children:[l===null?jsx("div",{style:a.body,children:jsx(Xe,{label:W.sessionRequired,glyph:"empty"})}):jsx(zy,{...n}),jsx(De,{})]})})}i(zn,"EverfurRecordsUpload");function zy({petRef:e,petName:r,controller:t,onNavigate:o,onBack:n}){let{theme:l,styles:a}=j(),{runtime:d}=ee(),s=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),c=Ge(s),u=t!==void 0||Wn(d.registry.services.uploadTransport);return jsxs(Fragment,{children:[jsx(He,{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:rr.title(r)}),jsx("p",{style:{...a.muted,fontSize:l.type.size.body,maxWidth:340},children:rr.subtitle(r)})]}),jsx(Ea,{records:c,requestId:null,canUpload:u,onDone:o?p=>o({name:"request",requestId:p}):void 0})]})]})}i(zy,"UploadBody");function Ea({records:e,requestId:r,canUpload:t,onDone:o}){let{theme:n,styles:l}=j(),a=useRef(null),d=`records-upload-format-hint-${r??"new"}`,[s,c]=useState(null),[u,p]=useState(0),[f,b]=useState(false),y=useRef(r),m=useRef([]),h=e.uploadQueue.filter(_=>_.status!=="skipped"),v=h.filter(_=>_.status==="done").length,E=h.filter(_=>_.status==="failed").length,g=!e.isUploading&&!f&&u>0,R=useCallback(async _=>{let{uploadable:T,skipped:I}=fs(_),F=ko(I);if(T.length===0){F!==null&&c(F);return}c(F),b(true);try{let q=y.current;if(q===null){let $=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!$.ok){c(rr.errors.start);return}q=$.value.id,y.current=q;}p($=>$+1);let M=await e.uploadDocuments(q,T);m.current=M.flatMap(($,V)=>$.status==="failed"&&T[V]!==void 0?[T[V]]:[]);}finally{b(false);}},[e]),S=i(_=>{let T=Array.from(_.currentTarget.files??[]);_.currentTarget.value="",!(T.length===0||!t)&&(async()=>{let I=[];for(let F of T)I.push(await Po(F));await R(I);})();},"onChange"),C=i(()=>a.current?.click(),"pick"),k=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,...O(n,"bold"),fontSize:n.type.size.subtitle},children:rr.cardTitle}),jsx("p",{id:d,style:l.muted,children:rr.cardSubtitle}),jsx("input",{ref:a,type:"file",accept:_o,multiple:true,tabIndex:-1,"aria-hidden":"true",hidden:true,disabled:!t,onChange:S,"data-testid":"records-upload-input"}),s?jsx("p",{role:"alert",style:l.errorBanner,children:s}):null,jsx(Sd,{records:e}),k?jsx("p",{style:l.muted,children:rr.uploading(v,h.length)}):g?jsxs("div",{style:{display:"flex",flexDirection:"column",gap:n.space.sm},children:[v>0?jsx("p",{role:"status",style:l.bodyText,children:rr.received(v)}):null,E>0?jsx(B,{label:rr.retryFailed(E),kind:"link",ariaLabel:rr.retryFailedA11y(E),onClick:()=>{R(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(B,{label:rr.addMore,kind:"link",ariaLabel:rr.addMoreA11y,ariaDescribedBy:d,disabled:!t,onClick:C,testID:"records-upload-another"}),o&&y.current!==null&&v>0?jsx(B,{label:rr.done,ariaLabel:rr.doneA11y,onClick:()=>o(y.current),testID:"records-upload-done"}):null]})]}):jsx(B,{label:rr.chooseFiles,ariaLabel:rr.chooseFilesA11y,ariaDescribedBy:d,disabled:!t,onClick:C,testID:"records-upload-choose"})]})}i(Ea,"UploadRecordCard");function Mn(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack"]),{userRef:l}=ee(),{styles:a}=j();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"records-request-screen",children:[l===null?jsx("div",{style:a.body,children:jsx(Xe,{label:W.sessionRequired,glyph:"empty"})}):jsx(By,{...n}),jsx(De,{})]})})}i(Mn,"EverfurRecordsRequest");function By({petRef:e,requestId:r,controller:t,onNavigate:o,onBack:n,onOpenUrl:l,nowMs:a}){let{styles:d}=j(),{runtime:s,userRef:c,scopeEpoch:u}=ee(),p=Ge(t?{petRef:e,controller:t}:{petRef:e}),f=p.requests.find(m=>m.id===r)??null,b=t!==void 0||Wn(s.registry.services.uploadTransport),y;return p.status==="loading"?y=jsx(yo,{testID:"records-request-loading"}):p.status==="error"&&p.error?y=jsx(Fe,{variant:Qe(p.error),message:p.error.displayMessage,onAction:p.error.retryable?p.refresh:void 0,testID:"records-request-error"}):f===null?y=jsx(Fe,{variant:"no_requests",testID:"records-request-missing"}):y=jsx(jy,{request:f,records:p,canUpload:b,onNavigate:o,onOpenUrl:l,nowMs:a},JSON.stringify([c,u,f.id])),jsxs(Fragment,{children:[jsx(He,{title:f?oo(f):"",onBack:n,testID:"records-request-header"}),jsx("div",{style:d.body,children:y})]})}i(By,"RequestBody");function jy({request:e,records:r,canUpload:t,onNavigate:o,onOpenUrl:n,nowMs:l}){let{theme:a,styles:d}=j(),s=ud({request:e,onRecovered:r.refresh,canUpload:t},Ir()),[c,u]=useState(null),[p,f]=useState(false),[b,y]=useState(null),m=useRef(true);useEffect(()=>(m.current=true,()=>{m.current=false;}),[]);let h=s.request,v=l??Date.now(),E=h.status==="published",g=h.status==="published"||h.status==="failed"||h.status==="revoked",R=Ii(h),S=h.wireStatus==="clinic_responded_no_records",C=Ws(h,v),k=g?null:h.waitingExpectation?.trim()||null,_=io(h),T=s.error!==null&&c!==null?c==="revoke"?ue.errors.cancel:ue.errors[c]:null,I=i((V,re)=>{u(V),re();},"run"),F=i(()=>{p||(f(true),y(null),r.createRequest(`records-upload-${Date.now().toString(36)}`).then(V=>{if(m.current){if(f(false),!V.ok){y(ue.errors.start);return}o?.({name:"request",requestId:V.value.id});}}));},"startFresh"),q={display:"flex",flexDirection:"column",gap:a.space.sm},M=i(V=>jsx("p",{role:"alert",style:d.errorBanner,children:V}),"errorBanner"),$=`records-failure-clinic-email-${h.id}`;return jsxs("div",{style:{...d.content,gap:a.space.lg+a.space.xs/2},"data-testid":`records-request-${h.id}`,children:[h.statusLabel.length>0||h.heldItemCount>0?jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:a.space.sm},"data-testid":"records-request-status-row",children:[h.statusLabel.length>0?jsx(cr,{label:h.statusLabel,tone:Cs(h),testID:"records-request-status-chip"}):null,h.heldItemCount>0?jsx(cr,{label:bi(h.heldItemCount),tone:"neutral",testID:"records-request-held-count"}):null]}):null,h.status==="awaiting_upload"?jsx(Ea,{records:r,requestId:h.id,canUpload:t}):null,k&&!C?jsx("p",{style:d.infoNote,children:k}):h.wireStatus==="awaiting_response"&&!C?jsx("p",{style:d.infoNote,children:ue.awaitingNote}):null,C?jsx("p",{style:d.cautionNote,"data-testid":"records-request-waiting-banner",children:ue.waitingBanner(Oi(h,v))}):null,E&&o?jsx(B,{label:ue.viewRecords,onClick:()=>o({name:"dashboard"}),testID:"records-request-view-dashboard"}):null,Ys(h)?jsxs("section",{style:{...q,gap:a.space.md,borderRadius:a.radius.lg-a.space.xs,padding:a.space.md+a.space.xs/2,backgroundColor:R?a.color.badgeBgCritical:a.color.badgeBgCaution},"data-testid":"records-failure-card",children:[jsx("p",{style:{...d.rowTitle,...O(a,"bold"),color:R?a.color.danger:a.color.warningStrong},children:Gs(h)}),h.canUpdateClinicEmail!==true&&h.canRetrySend!==true?jsx("p",{style:d.rowDetail,children:ue.nextStep}):null,h.canUpdateClinicEmail===true?jsxs("div",{style:q,children:[jsx("label",{htmlFor:$,style:d.fieldLabel,children:$r.email}),jsx("input",{id:$,type:"email",style:d.field,placeholder:$r.emailPlaceholder,autoComplete:"off",maxLength:320,value:s.email,disabled:s.busy,onChange:V=>s.setEmail(V.target.value),"data-testid":"records-failure-clinic-email"}),s.emailInvalid?jsx("p",{role:"alert",style:d.errorText,children:ue.errors.invalidEmail}):null,jsx(B,{label:$r.updateEmail,ariaLabel:$r.updateEmailA11y,disabled:!s.canUpdateEmail,busy:s.busy&&c==="email",onClick:()=>I("email",s.updateEmail),testID:"records-failure-update-email"})]}):null,h.canRetrySend===true?jsx(B,{label:$r.retry,kind:"outline",ariaLabel:$r.retryA11y,disabled:!s.canRetry,busy:s.busy&&c==="retry",onClick:()=>I("retry",s.retry),testID:"records-failure-retry-send"}):null,h.canRetrySend===true&&s.hasEmailEdit?jsx("p",{style:d.rowDetail,children:$r.retryHint}):null,T&&(c==="email"||c==="retry")?M(T):null]}):null,(R||S)&&o?jsx(B,{label:ue.tryAnotherClinic,kind:"outline",ariaLabel:ue.tryAnotherClinicA11y,onClick:()=>o({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,_!==null?jsxs("div",{style:q,children:[jsx(wd,{call:_,prompt:h.statusLabel}),h.canRetrySend===true?jsx(B,{label:s.busy&&c==="retry"?ue.resending:ue.resend,kind:"outline",ariaLabel:s.busy&&c==="retry"?ue.resendingA11y:ue.resendA11y,disabled:!s.canRetry,onClick:()=>I("retry",s.retry),testID:"records-resend-authorization"}):null]}):null,s.canConvert?jsxs("div",{style:q,children:[jsx(B,{label:s.busy&&c==="convert"?ue.converting:ue.convert,busy:s.busy&&c==="convert",onClick:()=>I("convert",s.convert),testID:"records-convert-upload"}),jsx("p",{style:d.muted,children:ue.convertHint}),T&&c==="convert"?M(T):null]}):null,g&&!E?jsxs("div",{style:q,children:[jsx(B,{label:p?ue.freshUploadStarting:ue.freshUpload,kind:R||S?"outline":"primary",busy:p,onClick:F,testID:"records-upload-own-fresh"}),b?M(b):null]}):null,T&&c==="revoke"?M(T):null,h.canRevoke===true?s.confirmingRevoke?jsxs("div",{style:q,"data-testid":"records-revoke-confirm",children:[jsx("p",{style:{...d.rowTitle,...O(a,"bold"),fontSize:a.type.size.subtitle},children:$r.cancelQuestion}),jsx("p",{style:d.bodyText,children:$r.cancelConsequence}),jsx(B,{label:s.busy&&c==="revoke"?ue.cancelling:ue.cancel,kind:"danger",ariaLabel:s.busy&&c==="revoke"?ue.cancellingA11y:ue.cancelA11y,busy:s.busy&&c==="revoke",onClick:()=>I("revoke",s.revoke),testID:"records-revoke-do"}),jsx(B,{label:$r.keepRequest,kind:"outline",disabled:s.busy,onClick:s.keepRequest,testID:"records-revoke-keep"})]}):jsx(B,{label:ue.cancel,kind:"danger",ariaLabel:ue.cancelA11y,disabled:s.busy,onClick:s.askRevoke,testID:"records-revoke"}):null,jsx("div",{"aria-hidden":"true",style:{height:1,backgroundColor:a.color.borderHairlineGreen,margin:`${a.space.xs}px 0`}}),jsx(rn,{request:h}),qn(h)?jsx(Fn,{requestId:h.id,...n?{onOpenUrl:n}:{}}):null]})}i(jy,"RequestDetail");function Un(e){return e.name==="request"||e.name==="clinicPicker"||e.name==="consent"||e.name==="clinicBatch"||e.name==="upload"}i(Un,"isOverlayScreen");function ic(e,r){if(r.type!=="closeOverlay")return yn(e,r);let t=e.stack.length;for(;t>1&&Un(e.stack[t-1]);)t-=1;return t===e.stack.length?e:Object.freeze({stack:Object.freeze(e.stack.slice(0,t))})}i(ic,"recordsPageNavReducer");function ac(e){let{stack:r}=e,t=r[r.length-1],o=Un(t)?t:null,n=r.length-1;for(;n>0&&Un(r[n]);)n-=1;let l=r[n],a=Un(l)?{name:"dashboard"}:l,d=o===null?null:r[r.length-2];return Object.freeze({body:a,overlay:o,overlayCanStepBack:d!=null&&Un(d),bodyCanGoBack:n>0})}i(ac,"splitRecordsPageNav");function sc(e){return {...e.petName!==void 0?{petName:e.petName}:{},...e.onOpenUrl?{onOpenUrl:e.onOpenUrl}:{},...e.onCopy?{onCopy:e.onCopy}:{},...e.onAsk?{onAsk:e.onAsk}:{},...e.location?{location:e.location}:{}}}i(sc,"seamsOf");function lc({screen:e,ctx:r,onBack:t}){let o={...sc(r),onNavigate:r.navigate,onBack:t},n={...r.controller?{controller:r.controller}:{},...r.consentVersion!==void 0?{consentVersion:r.consentVersion}:{}},l=Wy;switch(e.name){case "record":return jsx(Ln,{petRef:r.petRef,...o,...n,style:l});case "timeline":return jsx(vo,{petRef:r.petRef,...o,style:l});case "document":return jsx(Nn,{petRef:r.petRef,...o,...n,style:l});case "contributions":return jsx(Co,{petRef:r.petRef,docId:e.docId,...o,style:l});default:return Dr(e)}}i(lc,"RecordsPageBodyScreenView");function dc({screen:e,ctx:r,requests:t,onBack:o,onClose:n}){let l=jt(e),a=useMemo(()=>Gy(e,t),[e,t]),d=r.onAsk,s=d?{onAsk:i((b,y)=>{n(),d(b,y);},"onAsk")}:{},c={...sc(r),...s,onNavigate:r.navigate,onBack:o},u=r.clinicController?{controller:r.clinicController}:{},p=r.onCaptureSignature?{onCaptureSignature:r.onCaptureSignature}:{},f;switch(e.name){case "request":f=jsx(Mn,{petRef:r.petRef,requestId:e.requestId,...c,...r.controller?{controller:r.controller}:{},style:$n});break;case "clinicPicker":f=jsx(Cn,{petRef:r.petRef,...c,...u,...r.controller?{recordsController:r.controller}:{},style:$n});break;case "consent":f=jsx(Pn,{petRef:r.petRef,clinic:e.clinic,...c,...r.ownerName!==void 0?{ownerName:r.ownerName}:{},...p,...u,style:$n});break;case "clinicBatch":f=jsx(Sn,{petRef:r.petRef,petName:r.petName??"",ownerName:r.ownerName??"",onClose:o,onCreated:()=>r.navigate({name:"dashboard"}),...p,...u,style:$n});break;case "upload":f=jsx(zn,{petRef:r.petRef,...c,...r.controller?{controller:r.controller}:{},style:$n});break;default:f=Dr(e);}return jsx(Ct,{label:a,onClose:n,shape:"side",panelStyle:Yy,testID:"everfur-records-page-sheet",children:jsx("div",{ref:l,tabIndex:-1,style:Ky,children:f})})}i(dc,"RecordsPageOverlay");function Gy(e,r){if(e.name==="upload")return Se.uploadAction;if(e.name!=="request")return Se.requestRecords;let t=r.find(o=>o.id===e.requestId);return t?eo(t):Se.requestTimeline}i(Gy,"overlayLabel");var Wy=Object.freeze({height:"auto"}),Yy=Object.freeze({padding:0,gap:0}),Ky=Object.freeze({height:"100%",outline:"none"}),$n=Object.freeze({height:"100%"});function Bo({requests:e,petName:r,level:t,headingId:o,onOpenRequest:n,onUpload:l,onOpenUrl:a}){let{theme:d,styles:s}=j(),c=co(t),u=e.length>0;return jsxs("section",{"aria-labelledby":o,style:s.section,"data-testid":"everfur-records-page-requests",children:[jsxs("div",{style:s.sectionHeader,children:[jsx(c,{id:o,style:{...s.sectionTitle,color:d.color.brand},children:Se.requestsFor(r)}),u?jsx("span",{style:s.sectionCount,"data-testid":"everfur-records-page-requests-count",children:e.length}):null]}),u?jsx("ul",{style:{...s.plainList,gap:d.space.md},children:e.map(p=>{let f=eo(p);return jsxs("li",{style:s.creamCard,"data-testid":`everfur-records-page-request-${p.id}`,children:[jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:d.space.sm},children:[jsx("span",{style:{...s.rowTitle,fontSize:d.type.size.subtitle},children:f}),n?jsx(B,{label:Se.requestTimeline,kind:"outline",ariaLabel:Se.requestTimelineA11y(f),onClick:()=>n(p),testID:`everfur-records-page-open-${p.id}`}):null]}),jsx(rn,{request:p}),qn(p)?jsx(Fn,{requestId:p.id,...a?{onOpenUrl:a}:{}}):null]},p.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:Se.uploadPromptTitle(r)}),jsx("p",{style:s.bodyText,children:Se.uploadPromptBody}),l?jsx(B,{label:Se.uploadAction,onClick:l,testID:"everfur-records-page-upload"}):null]})]})}i(Bo,"RecordsPageRequests");var tg=1248,ng=Object.freeze({height:"auto"}),jo=Object.freeze({overflowY:"visible",flex:"0 0 auto"});function og(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack","onAsk"]),{userRef:l}=ee(),{styles:a}=j();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...ng,...r},"data-testid":"everfur-records-page",children:[l===null?jsx("div",{style:{...a.body,...jo},children:jsx(Xe,{label:W.sessionRequired,glyph:"empty"})}):jsx(ig,{...n}),jsx(De,{})]})})}i(og,"EverfurRecordsPage");function ig(e){let{petRef:r,petName:t,controller:o,clinicController:n,consentVersion:l,ownerName:a,onCaptureSignature:d,onNavigate:s,onOpenUrl:c,onCopy:u,onAsk:p,location:f}=e,[b,y]=useReducer(ic,void 0,()=>Ut()),m=useCallback(F=>{s?s(F):y({type:"navigate",screen:F});},[s]),{body:h,overlay:v,overlayCanStepBack:E,bodyCanGoBack:g}=ac(b),R=useMemo(()=>o?{petRef:r,controller:o}:{petRef:r},[r,o]),S=Ge(R),{refresh:C}=S,k=useRef(false);useEffect(()=>{v!==null?k.current=true:k.current&&(k.current=false,C());},[v,C]);let _=jt(h),T={petRef:r,petName:t,controller:o,clinicController:n,consentVersion:l,ownerName:a,onCaptureSignature:d,navigate:m,...c?{onOpenUrl:c}:{},...u?{onCopy:u}:{},...p?{onAsk:p}:{},...f?{location:f}:{}},I=h.name==="dashboard"||h.name==="requests";return jsxs(Fragment,{children:[jsx("div",{ref:_,tabIndex:-1,style:ag,children:I?jsx(sg,{...e,records:S,navigate:m}):jsx(lc,{screen:h,ctx:T,onBack:g?()=>y({type:"pop"}):()=>m({name:"dashboard"})})}),v!==null?jsx(dc,{screen:v,ctx:T,requests:S.requests,onBack:E?()=>y({type:"pop"}):()=>y({type:"closeOverlay"}),onClose:()=>y({type:"closeOverlay"})}):null]})}i(ig,"RecordsPageBody");var ag=Object.freeze({outline:"none"});function sg({petRef:e,petName:r,consentVersion:t,onAsk:o,onOpenUrl:n,headingLevel:l,records:a,navigate:d}){let{theme:s,styles:c}=j(),u=St("recordsClinic"),p=u.enabled||u.isPending,f=Ms(l??lo),b=co(f),y=`${useId()}-requests-heading`,m=tt(t,a.consent),h=i(()=>{let E=Hr(t,a.consent);E.length!==0&&a.grantConsent(E,`records-consent-${Date.now().toString(36)}`);},"onGrant"),v={boxSizing:"border-box",width:"100%",maxWidth:tg,margin:"0 auto",display:"flex",flexDirection:"column",gap:s.space.lg+s.space.xs,padding:`${s.space.lg}px ${s.space.lg}px ${s.space.xxl}px`};if(a.status==="loading")return jsx("div",{style:{...c.body,...jo},children:jsx("div",{style:v,children:jsx(Yt,{testID:"everfur-records-page-loading"})})});if(a.status==="error"){let E=Vr(a,m),g=E.kind==="error"||E.kind==="pet_not_found"?jsx(Fe,{variant:Qe(E.error),message:E.error.displayMessage,onAction:E.error.retryable?()=>a.refresh():void 0,testID:"everfur-records-page-error"}):vt(a,h,m);return jsx("div",{style:{...c.body,...jo},children:jsx("div",{style:v,children:g})})}return jsx("div",{style:{...c.body,...jo},children:jsxs("div",{style:v,"data-testid":"everfur-records-page-content",children:[jsxs("header",{style:{...c.creamCard,gap:s.space.md,padding:`${s.space.lg+s.space.xs}px ${s.space.lg+s.space.md}px`},"data-testid":"everfur-records-page-header",children:[jsx(b,{tabIndex:-1,[Rn]:"",style:{...c.headerTitle,whiteSpace:"normal",overflow:"visible"},children:Se.title}),jsx("p",{style:c.bodyText,children:Se.lead}),jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:s.space.sm},"data-testid":"everfur-records-page-actions",children:[p?jsx(B,{label:Se.requestRecords,onClick:()=>d({name:"clinicPicker"}),testID:"everfur-records-page-request-records"}):null,jsx(B,{label:Se.uploadAction,kind:"outline",onClick:()=>d({name:"upload"}),testID:"everfur-records-page-upload-action"}),o?jsx(B,{label:Se.askA11y(r),kind:"ask",ariaLabel:Se.askA11y(r),onClick:()=>o(gs(r),{type:"marker_summary",id:e}),testID:"everfur-records-page-ask"}):null]}),jsxs("nav",{style:{display:"flex",flexWrap:"wrap",columnGap:s.space.lg,rowGap:s.space.xs},"data-testid":"everfur-records-page-links",children:[jsx(cc,{label:Se.viewRecord,onClick:()=>d({name:"record"}),testID:"everfur-records-page-link-record"}),jsx(cc,{label:Se.viewTimeline,onClick:()=>d({name:"timeline"}),testID:"everfur-records-page-link-timeline"})]})]}),jsx(Bo,{requests:a.requests,petName:r,level:Pi(f),headingId:y,onOpenRequest:E=>d({name:"request",requestId:E.id}),onUpload:()=>d({name:"upload"}),...n?{onOpenUrl:n}:{}})]})})}i(sg,"RecordsPageContent");function cc({label:e,onClick:r,testID:t}){let{theme:o,styles:n}=j();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(cc,"PageLink");var br=200,Sa=16,wa=(br-Sa)/2,uc=2*Math.PI*wa;function mc({summary:e,onAsk:r,testID:t}){let o=dg(),{theme:n,styles:l}=j(),{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}],b=0;return f.filter(y=>y.count>0).map(y=>{let m=y.count/u*uc,h=-b;return b+=m,{key:y.key,color:y.color,length:m,offset:h}})},[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:br,height:br,viewBox:`0 0 ${br} ${br}`,"aria-hidden":"true",focusable:"false",children:[jsx("circle",{cx:br/2,cy:br/2,r:wa,stroke:n.color.surfaceSubtle,strokeWidth:Sa,fill:"none"}),jsx("g",{transform:`rotate(-90 ${br/2} ${br/2})`,children:p.map(f=>jsx("circle",{cx:br/2,cy:br/2,r:wa,stroke:f.color,strokeWidth:Sa,fill:"none",strokeDasharray:`${f.length} ${uc}`,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(mc,"MarkerSummaryCard");function dg(){let e=ce();return useMemo(()=>cg(e),[e])}i(dg,"useStyles");function cg(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,...O(e,"bold"),fontSize:n.size.body,color:r.brand,letterSpacing:n.letterSpacing.headerBrand},ringRow:{display:"flex",justifyContent:"center"},ringWrap:{position:"relative",width:br,height:br},center:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",pointerEvents:"none"},centerCount:{...O(e,"medium"),fontSize:n.size.verdict*2,lineHeight:1.1,color:r.text.primary},centerLabel:{...O(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`,...O(e,"mono"),fontSize:n.size.nano,lineHeight:`${n.size.tiny}px`,textTransform:"uppercase",letterSpacing:n.letterSpacing.headerBrand/2},subtitle:{margin:0,...O(e,"regular"),fontSize:n.size.caption,lineHeight:`${Math.round(n.size.caption*n.lineHeight.relaxed)}px`,color:r.text.primary}}}i(cg,"makeStyles");function ug(e){return e.value!==null&&Number.isFinite(e.value)}i(ug,"numeric");function fc(e){let r=e.points.filter(ug);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(v=>v.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(v=>(u-v)/p*100,"y"),b=6,y=r.length,m=r.map((v,E)=>({index:E,xPct:y<=1?50:b+E/(y-1)*(100-2*b),yPct:f(v.value),status:v.status,point:v})),h=o!==null||n!==null?{topPct:n!==null?f(n):0,bottomPct:o!==null?f(o):100}:null;return {points:m,band:h,firstDate:r[0]?.at??null,lastDate:r[r.length-1]?.at??null}}i(fc,"buildMarkerChart");var yc=100,Ho=44;function mg({marker:e,onPointPress:r,onAsk:t}){let o=ka(),{theme:n,styles:l}=j(),a=Yr(e.latest?.status??null),d=Vt(e.trajectory,e.points.length),s=useMemo(()=>fc(e),[e]),c=e.latest?ur(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":rt.status(a.label),children:jsx(cr,{label:a.label,tone:No(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":rt.latestA11y(c,a.label,J(e.latest.at)),children:c}),jsx("span",{style:o.latestDate,children:J(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 ${yc} ${Ho}`,preserveAspectRatio:"none",style:o.plot,"aria-hidden":"true",focusable:"false",children:[s.band?jsx("rect",{x:0,y:s.band.topPct/100*Ho,width:yc,height:Math.max(0,(s.band.bottomPct-s.band.topPct)/100*Ho),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*Ho}`).join(" ")}):null]}),jsx("div",{style:o.dotLayer,children:s.points.map(u=>jsx("button",{type:"button",onClick:()=>r(e,u.point),"aria-label":pa(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":rt.readingsA11y(e.name),style:o.a11yTable,children:e.points.map((u,p)=>jsx("li",{children:pa(e,u)},p))}),jsx("p",{style:e.points.length===1?o.singleHint:o.tapHint,children:e.points.length===1?rt.singleHint:rt.tapHint})]}):jsx("p",{style:o.emptyBody,children:rt.empty}),t?jsx("button",{type:"button",onClick:()=>t(e),"aria-label":rt.askA11y(e.name),style:{...l.pill,...l.pillAsk},"data-testid":`marker-ask-${e.markerId}`,children:rt.ask}):null]})})}i(mg,"MarkerTrendCard");function bc({markers:e,onPointPress:r,onAsk:t}){let o=ka(),[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(mg,{marker:s,onPointPress:r,onAsk:t},s.markerId))}),jsxs("div",{style:o.footer,"aria-label":ui.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:ui.counter(n,e.length)})]})]})}i(bc,"MarkerTrendCarousel");function Rc({marker:e,point:r,onClose:t,onAsk:o}){let n=ka(),{styles:l}=j();if(e===null||r===null)return null;let a=i((d,s)=>jsxs("div",{style:n.detailRow,children:[jsx("dt",{style:n.detailLabel,children:d}),jsx("dd",{style:n.detailValue,children:s})]},d),"row");return jsxs(Ct,{label:dr.title,onClose:t,panelStyle:n.sheetBg,testID:"marker-provenance-sheet",children:[jsxs("div",{style:l.sheetHeader,children:[jsx("h3",{style:l.sheetTitle,children:dr.title}),jsx("button",{type:"button",onClick:t,"aria-label":dr.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:ur(r.value,e.unit,r.qualitativeResult)})]}),r.reviewed?jsx("span",{style:n.reviewed,children:dr.reviewed}):null,jsxs("dl",{style:n.details,children:[a(dr.collected,J(r.at)),r.sourceClinic?a(dr.clinic,r.sourceClinic):null,a(dr.referenceRange,r.refLow!==null||r.refHigh!==null?Lo(r,e.unit):dr.noRange),r.docId?a(dr.sourceDocument,r.docId):null]}),r.reviewed?null:jsx("p",{style:n.unverified,children:dr.unverified}),o?jsx("button",{type:"button",onClick:o,"aria-label":dr.askA11y,style:{...l.pill,...l.pillAsk},"data-testid":"marker-provenance-ask",children:dr.ask}):null]})}i(Rc,"MarkerProvenanceDialog");function ka(){let e=ce();return useMemo(()=>fg(e),[e])}i(ka,"useStyles");function fg(e){let{color:r,space:t,radius:o,type:n}=e,l=i((d,s,c,u="regular")=>({margin:0,...O(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:{...O(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:{...O(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(fg,"makeStyles");var Rg=i((e,r)=>e.getRecordDepth(r),"readDepth"),hg=i(e=>!e.available,"depthEmpty");function Pa(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack","onAsk"]),{userRef:l}=ee(),{styles:a}=j();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"records-dashboard",children:[l===null?jsx("div",{style:a.body,children:jsx(Xe,{label:W.sessionRequired,glyph:"empty"})}):jsx(vg,{...n}),jsx(De,{})]})})}i(Pa,"EverfurRecordsDashboard");function vg({petRef:e,petName:r,controller:t,consentVersion:o,onNavigate:n,onBack:l,onAsk:a}){let{theme:d,styles:s}=j(),c=useMemo(()=>t?{petRef:e,controller:t}:{petRef:e},[e,t]),u=Ge(c),p=Xi(e),f=zr(e,Rg,hg),[b,y]=useState(null),m=useCallback((x,A)=>y({marker:x,point:A}),[]),h=tt(o,u.consent),v=i(()=>{let x=Hr(o,u.consent);x.length!==0&&u.grantConsent(x,`records-consent-${Date.now().toString(36)}`);},"onGrant"),E=p.markers?.markers??[],g=E.length>0,R=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,S=ro(u.requests,e),C=pi({hasMarkers:g,requests:u.requests,petRef:e}),k=mi({recordLoading:u.status==="loading",hasFullRecord:R,recordError:u.status==="error",markersLoading:p.status==="loading",markersError:p.status==="error",hasMarkers:g,requestsLoading:u.status==="loading",dashboardState:C,drivingRequest:S}),_=p.markers?.disclaimer??u.record?.disclaimer??"",T=i(()=>{u.refresh(),p.refresh(),f.refresh();},"retryAll"),I=f.value!==null&&!f.value.withheld&&f.value.available?f.value:null,F=Pe(r),q=a&&p.markers?.summary?()=>{let x=Ld(r,p.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);a(x.prompt,x.entityRef);}:void 0,M=a?x=>{let A=Nd(r,{canonicalName:x.name,markerId:x.markerId,latestValueText:x.latest?ur(x.latest.value,x.unit,x.latest.qualitativeResult):null,statusText:x.latest?Yr(x.latest.status).label:null,trajectoryText:Vt(x.trajectory,x.points.length),meaningText:x.meaning});a(A.prompt,A.entityRef);}:void 0,$=a&&b?()=>{let{marker:x,point:A}=b,D=Fd(r,{canonicalName:x.name,valueText:ur(A.value,x.unit,A.qualitativeResult),collectedAt:J(A.at),sourceClinic:A.sourceClinic,referenceText:A.refLow!==null||A.refHigh!==null?Lo(A,x.unit):null,flagged:A.status==="above"?"above":A.status==="below"?"below":null,reviewed:A.reviewed,entityId:A.docId??x.markerId});y(null),a(D.prompt,D.entityRef);}:void 0,V=i((x,A,D)=>jsxs("button",{type:"button",onClick:A,"aria-label":x,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":D,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:x})]}),jsx(kt,{})]}),"actionRow"),re=jsxs(Fragment,{children:[p.markers?.summary?jsx("div",{style:s.inset,children:jsx(mc,{summary:p.markers.summary,onAsk:q,testID:"dashboard-marker-summary"})}):null,jsx("p",{style:s.lead,children:lr.lead(r)}),jsx(bc,{markers:E,onPointPress:m,onAsk:M})]}),Q=i(x=>n?jsxs("div",{style:{...s.inset,display:"flex",flexDirection:"column",gap:d.space.sm+d.space.xs/2},children:[x?V(lr.viewFullRecord,()=>n({name:"record"}),"dashboard-full-record-action"):null,V(lr.viewTimeline,()=>n({name:"timeline"}),"dashboard-timeline-action")]}):null,"actions"),w;if(u.status==="error"){let x=Vr(u,h);w=x.kind==="error"||x.kind==="pet_not_found"?jsx(Fe,{variant:Qe(x.error),message:x.error.displayMessage,onAction:x.error.retryable?T:void 0,testID:"dashboard-error"}):vt(u,v,h);}else switch(k){case "loading":w=jsx(Yt,{testID:"dashboard-loading"});break;case "record":w=jsxs("div",{style:s.contentTight,"data-testid":"dashboard-record",children:[g?re:p.status==="error"?jsx("div",{style:s.inset,children:V(lr.retryMarkers,T,"dashboard-markers-retry")}):null,jsx("div",{style:s.inset,children:u.record?jsx(Mo,{record:u.record,depth:I,petName:r,showLabs:!g,onNavigate:n,onAsk:a}):null}),Q(true)]});break;case "error":{let x=p.error??u.error;w=jsx(Fe,{variant:Qe(x),message:x?.displayMessage,onAction:x?.retryable?T:void 0,testID:"dashboard-error"});break}case "in_progress":w=jsxs("div",{style:s.content,"data-testid":"dashboard-in-progress",children:[S?jsx(Cg,{request:S,petName:F,onOpen:n?()=>n({name:"request",requestId:S.id}):void 0,onAsk:a?()=>{let x=zd(r,{clinicName:S.clinicName??null,statusLabel:gn(S),status:S.status,heldItemCount:S.heldItemCount},S.id);a(x.prompt,x.entityRef);}:void 0}):null,jsx(bt,{disclaimer:_})]});break;case "none":w=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:xt.title(r)}),jsx("p",{style:s.bodyText,children:xt.body}),n?jsxs(Fragment,{children:[jsx(B,{label:xt.requestFromClinic,ariaLabel:xt.requestFromClinicA11y(r),onClick:()=>n({name:"clinicPicker"}),testID:"dashboard-request-prompt-clinic"}),jsx(B,{label:xt.uploadDocument,kind:"outline",ariaLabel:xt.uploadDocumentA11y(r),onClick:()=>n({name:"upload"}),testID:"dashboard-request-prompt-upload"})]}):null]}),jsx(bt,{disclaimer:_})]});break;case "labs_only":w=jsxs("div",{style:s.contentTight,"data-testid":"dashboard-labs-only",children:[re,jsx("div",{style:s.inset,children:jsx(bt,{disclaimer:_})}),Q(false)]});break;default:w=Dr(k);}return jsxs(Fragment,{children:[jsx(He,{title:lr.title,onBack:l,testID:"dashboard-header",right:n?jsx("button",{type:"button",onClick:()=>n({name:"timeline"}),"aria-label":lr.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(x=>jsx("span",{style:{display:"block",width:18,height:2,borderRadius:2,backgroundColor:d.color.brand}},x))})}):void 0}),jsx("div",{style:s.body,children:w}),jsx(Rc,{marker:b?.marker??null,point:b?.point??null,onClose:()=>y(null),onAsk:$})]})}i(vg,"DashboardBody");function Cg({request:e,petName:r,onOpen:t,onAsk:o}){let{theme:n,styles:l}=j(),a=e.clinicName?.trim()||$t.title(r),d=gn(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,...O(n,"bold"),fontSize:n.type.size.subtitle},children:a}),t?jsx(kt,{}):null]}),jsx(rn,{request:e}),d.length>0?jsx("p",{style:l.statusCard,children:d}):null]});return jsxs("section",{"aria-label":t?void 0:$t.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":$t.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(B,{label:$t.ask,kind:"ask",ariaLabel:$t.askA11y,onClick:o,testID:"dashboard-in-progress-ask"}):null]})}i(Cg,"InProgressCard");function Ta(e){let{style:r,className:t,renderPending:o,...n}=_e(e,["onNavigate","onBack"]),{userRef:l}=ee(),{styles:a}=j();return jsx(Te,{capability:"records",style:r,className:t,...o?{renderPending:o}:{},...Oe(n.onBack,Le),children:jsxs("div",{className:t,style:{...a.root,...r},"data-testid":"records-requests-screen",children:[l===null?jsx("div",{style:a.body,children:jsx(Xe,{label:W.sessionRequired,glyph:"empty"})}):jsx(Sg,{...n}),jsx(De,{})]})})}i(Ta,"EverfurRecordsRequests");function Sg({petRef:e,petName:r,controller:t,onNavigate:o,onBack:n,onOpenUrl:l}){let{theme:a,styles:d}=j(),s=Ge(t?{petRef:e,controller:t}:{petRef:e}),c=useMemo(()=>Ri(s.requests.filter(b=>b.petRef===e)),[s.requests,e]),u=St("recordsClinic"),p=`${useId()}-requests-heading`,f;return s.status==="loading"&&c.length===0?f=jsx(yo,{testID:"records-requests-loading"}):s.status==="error"&&s.error&&c.length===0?f=jsx(Fe,{variant:Qe(s.error),message:s.error.displayMessage,onAction:s.error.retryable?s.refresh:void 0,testID:"records-requests-error"}):f=jsx(Bo,{requests:c,petName:r,level:3,headingId:p,onOpenRequest:o?b=>o({name:"request",requestId:b.id}):void 0,onUpload:o?()=>o({name:"upload"}):void 0,...l?{onOpenUrl:l}:{}}),jsxs(Fragment,{children:[jsx(He,{title:Se.title,onBack:n,testID:"records-requests-header"}),jsx("div",{style:d.body,children:jsxs("div",{style:{...d.content,gap:a.space.lg},children:[o?jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:a.space.sm},"data-testid":"records-requests-actions",children:[u.enabled||u.isPending?jsx(B,{label:Se.requestRecords,onClick:()=>o({name:"clinicPicker"}),testID:"records-requests-request-records"}):null,jsx(B,{label:Se.uploadAction,kind:"outline",onClick:()=>o({name:"upload"}),testID:"records-requests-upload"})]}):null,f]})})]})}i(Sg,"RequestsBody");function vc(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:b,onOpenUrl:y,onCopy:m,onAsk:h,location:v}=_e(e,["onExit"]),[E,g]=useReducer(yn,s,Ut),R=to(E),S=E.stack.length,C=useRef(S);C.current=S;let k=useRef(S),_=useRef(false);useEffect(()=>{if(c!=="browser"||typeof window>"u")return;let Q=i(w=>{let x=w.state;(typeof x?.efRecords=="number"?x.efRecords:1)<C.current&&(_.current=true,g({type:"pop"}));},"onPopState");return window.addEventListener("popstate",Q),()=>window.removeEventListener("popstate",Q)},[c]),useEffect(()=>{if(c!=="browser"||typeof window>"u")return;let Q=k.current;S>Q?window.history.pushState({efRecords:S},""):S<Q&&!_.current&&window.history.go(S-Q),_.current=false,k.current=S;},[c,S]);let T=useCallback(Q=>g({type:"navigate",screen:Q}),[]),I=useMemo(()=>no(E).handled?()=>g({type:"pop"}):u,[E,u]),F=jt(R),q={onNavigate:T,...I?{onBack:I}:{},...t!==void 0?{petName:t}:{},...y?{onOpenUrl:y}:{},...m?{onCopy:m}:{},...h?{onAsk:h}:{},...v?{location:v}:{}},M={...o?{controller:o}:{},...l!==void 0?{consentVersion:l}:{}},$={...p?{style:p}:{},...f!==void 0?{className:f}:{}},V=b?{renderPending:b}:{},re;switch(R.name){case "dashboard":re=jsx(Pa,{petRef:r,...q,...M,...V,...$});break;case "request":re=jsx(Mn,{petRef:r,requestId:R.requestId,...q,...o?{controller:o}:{},...V,...$});break;case "timeline":re=jsx(vo,{petRef:r,...q,...$});break;case "record":re=jsx(Ln,{petRef:r,...q,...M,...V,...$});break;case "document":re=jsx(Nn,{petRef:r,...q,...M,...V,...$});break;case "contributions":re=jsx(Co,{petRef:r,docId:R.docId,...q,...$});break;case "clinicPicker":re=jsx(Cn,{petRef:r,...q,...n?{controller:n}:{},...o?{recordsController:o}:{},...$});break;case "clinicBatch":re=jsx(Sn,{petRef:r,petName:t??"",ownerName:a??"",...I?{onClose:I}:{},onCreated:()=>g({type:"navigate",screen:{name:"dashboard"}}),...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},...$});break;case "consent":re=jsx(Pn,{petRef:r,clinic:R.clinic,...q,...a!==void 0?{ownerName:a}:{},...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},...$});break;case "upload":re=jsx(zn,{petRef:r,...q,...o?{controller:o}:{},...V,...$});break;case "requests":re=jsx(Ta,{petRef:r,...q,...o?{controller:o}:{},...V,...$});break;default:re=Dr(R);}return jsx("div",{ref:F,style:Tg,"data-testid":"everfur-records-flow",children:re})}i(vc,"EverfurRecordsFlow");var Tg=Object.freeze({display:"contents"}),Dg=vc;function Og(e){let{userRef:r,scopeEpoch:t}=ee();return jsx(Te,{capability:"recordsClinic",...Oe(e.onClose,X.cancel),children:r===null?jsx("p",{role:"alert",children:W.sessionRequired}):jsx(Ig,{..._e(e,["onClose","onCreated"])},JSON.stringify([r,t,e.petRef,e.petName]))})}i(Og,"EverfurClinicRequest");function Ig(e){let r=Ir(),t=e.controller??r,o=ce(),n={current:null},l=Ot(()=>n.current?.invalidate()),a=wl(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":X.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:X.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:[X.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:[X.clinic,jsx("input",{style:{...d,display:"block",width:"100%",boxSizing:"border-box"},placeholder:X.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:X.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:X.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:[X.email,jsx("input",{style:{...d,display:"block",width:"100%",boxSizing:"border-box"},type:"email",placeholder:X.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:X.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(It,{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?X.sending:X.send})]}),e.onClose&&jsx("button",{type:"button",style:s,disabled:a.busy,onClick:e.onClose,children:X.cancel}),jsx(De,{})]})}i(Ig,"ClinicRequestBody");var Ag="file",qg="document.pdf",Ng="records upload: the file handle carries no bytes",Cc="records upload failed";function Lg(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(Ng));return}let{signal:s,onProgress:c}=n;if(s?.aborted===true){a(new Error(Cc));return}let u=new FormData;for(let[m,h]of Object.entries(t.upload_fields))u.append(m,h);u.append(Ag,d,qg);let p=r(),f=false,b=i(m=>{f||(f=true,s?.removeEventListener("abort",y),m?l():a(new Error(Cc)));},"settle"),y=i(()=>{p.abort(),b(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=()=>b(p.status>=200&&p.status<300),p.onerror=()=>b(false),p.onabort=()=>b(false),p.ontimeout=()=>b(false),s?.addEventListener("abort",y,{once:true}),p.send(u);})}})}i(Lg,"createWebRecordsUploadTransport");
4
+ export{Cn as EverfurClinicPicker,Og as EverfurClinicRequest,Sn as EverfurClinicRequestBatch,Ln as EverfurRecordDetail,Nn as EverfurRecordDocument,Dg as EverfurRecords,Pn as EverfurRecordsConsent,Pa as EverfurRecordsDashboard,vc as EverfurRecordsFlow,og as EverfurRecordsPage,Mn as EverfurRecordsRequest,Ta as EverfurRecordsRequests,zn as EverfurRecordsUpload,Bt as RECORDS_CLINIC_BATCH_MAX,_o as RECORDS_DOCUMENT_ACCEPT,Ka as RECORDS_TERMINAL,An as REQUEST_TIMELINE_TITLES,Fn as RequestDocumentsList,It as SignatureCanvas,da as applyFactOverlay,aa as buildRequestTimeline,Lg as createWebRecordsUploadTransport,to as currentRecordsScreen,pi as deriveRecordsDashboardState,Po as fileToHandle,Ut as initialRecordsNav,ca as isFactEditable,cd as isPdfBlob,Mt as isTerminalStatus,cf as isUploadableHandle,uf as pickDocument,ro as pickPetRecordsRequest,no as popRecordsNav,fi as pushRecordsNav,dt as recordsDenialReasonOf,yn as recordsNavReducer,yi as replaceRecordsNav,ga as requestDocumentRows,gi as resetRecordsNav,io as selectClinicCall,mi as selectDashboardView,gn as selectPrimaryLabel,Ri as selectRequestList,oo as selectRequestTitle,hs as transitionRecordsNav,Ge as useEverfurRecords,Ir as useEverfurRecordsClinic,Ni as useEverfurRecordsClinicBatch,ua as useRecordFactEdit,ta as useRecordPdfLink,ea as useRecordShares,Xi as useRecordsMarkers,Ra as useRequestDocuments,Ot as useSignatureCanvas};