@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.
- package/CHANGELOG.md +337 -0
- package/dist/BookedScreen-BJPbXLCG.d.ts +54 -0
- package/dist/BookedScreen-Cnld-jB_.d.cts +54 -0
- package/dist/{Chat-ypo6miKm.d.cts → Chat-B43wIXCv.d.cts} +3 -3
- package/dist/{Chat-Rzplrf5M.d.ts → Chat-my5aJLz5.d.ts} +3 -3
- package/dist/{DepthViews-ClykXOJj.d.cts → DepthViews-BBTv9VAs.d.cts} +1 -1
- package/dist/{DepthViews-Cui3oonj.d.cts → DepthViews-BLK0kgza.d.cts} +1 -1
- package/dist/{DepthViews-baYLMNQ-.d.ts → DepthViews-CNqAyjne.d.ts} +1 -1
- package/dist/{DepthViews-CeTfPUBX.d.ts → DepthViews-G-7YRtOX.d.ts} +1 -1
- package/dist/animations/index.d.cts +3 -3
- package/dist/animations/index.d.ts +3 -3
- package/dist/{attachments-CwsR-bPN.d.cts → attachments-CEmT52IA.d.cts} +5 -5
- package/dist/{attachments-D3HCBmOE.d.ts → attachments-CMNWE6YT.d.ts} +2 -2
- package/dist/{attachments-CzZ7in24.d.ts → attachments-DU1djTNd.d.ts} +5 -5
- package/dist/{attachments-Nk73Lll8.d.cts → attachments-ZyjWsZdI.d.cts} +2 -2
- package/dist/{bookingCopy-SDkXaxDf.d.ts → bookingCopy-BVhEt1bj.d.ts} +38 -200
- package/dist/{bookingCopy-Dv8rKqyV.d.cts → bookingCopy-ChZR5mtd.d.cts} +38 -200
- package/dist/bookingTypes-DCs8mmBb.d.cts +188 -0
- package/dist/bookingTypes-DCs8mmBb.d.ts +188 -0
- package/dist/{callCopy-rDH9JTFo.d.cts → callCopy-CPe9mbwG.d.cts} +7 -2
- package/dist/{callCopy-rDH9JTFo.d.ts → callCopy-CPe9mbwG.d.ts} +7 -2
- package/dist/{casesRepository-BTAecTnF.d.ts → casesRepository-C5zrCcaE.d.ts} +1 -1
- package/dist/{casesRepository-aryld7fJ.d.cts → casesRepository-q2ak9AW0.d.cts} +1 -1
- package/dist/chat/index.cjs +1 -1
- package/dist/chat/index.d.cts +14 -10
- package/dist/chat/index.d.ts +14 -10
- package/dist/chat/index.js +1 -1
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +6 -6
- package/dist/client/index.d.ts +6 -6
- package/dist/client/index.js +1 -1
- package/dist/{config-X6BtwDwQ.d.ts → config-DBpKJJbg.d.ts} +1 -1
- package/dist/{config-6qS7Sohy.d.cts → config-jocy3q66.d.cts} +1 -1
- package/dist/consent/index.d.cts +5 -5
- package/dist/consent/index.d.ts +5 -5
- package/dist/{context-CkqPM4Ml.d.cts → context-BfVBRgro.d.cts} +5 -5
- package/dist/{context-7f3Nb_xE.d.ts → context-C3n9s4aG.d.ts} +5 -5
- package/dist/{copy-Bd__Pw5s.d.cts → copy-IysFx8yL.d.cts} +2 -2
- package/dist/{copy-NgKgOOET.d.ts → copy-KP91zgtW.d.ts} +2 -2
- package/dist/core/index.cjs +5 -5
- package/dist/core/index.d.cts +12 -12
- package/dist/core/index.d.ts +12 -12
- package/dist/core/index.js +5 -5
- package/dist/{depth-CYPH92jE.d.ts → depth-BsMLLrQo.d.ts} +2 -2
- package/dist/{depth-CyjaJJ6V.d.cts → depth-O9kiVUjs.d.cts} +2 -2
- package/dist/{entitlementRepository-DdeFuEKp.d.ts → entitlementRepository-CHsY2kF3.d.ts} +2 -2
- package/dist/{entitlementRepository-Dl1qRLcJ.d.cts → entitlementRepository-DIG16pso.d.cts} +2 -2
- package/dist/{identity-DjqhDm5Z.d.cts → identity-D7GKfOE7.d.cts} +1 -1
- package/dist/{identity-Dy_L7Yq4.d.ts → identity-k8nCQ_qM.d.ts} +1 -1
- package/dist/index.cjs +6 -6
- package/dist/index.d.cts +13 -13
- package/dist/index.d.ts +13 -13
- package/dist/index.js +6 -6
- package/dist/notifications/index.d.cts +2 -2
- package/dist/notifications/index.d.ts +2 -2
- package/dist/{pets-BSG2qbr_.d.cts → pets-Bod_DDiW.d.cts} +1 -1
- package/dist/{pets-D7cZutrX.d.ts → pets-C_QX8s5f.d.ts} +1 -1
- package/dist/{petsRepository-D1bnxDZg.d.cts → petsRepository-B3vr628I.d.cts} +1 -1
- package/dist/{petsRepository-DhsX3GLw.d.ts → petsRepository-DdzgINfF.d.ts} +1 -1
- package/dist/{ports-DNXyyzZF.d.cts → ports-BSm48zIC.d.cts} +16 -5
- package/dist/{ports-C0m1G1fS.d.ts → ports-DHhxhn95.d.ts} +16 -5
- package/dist/records/depth/index.d.cts +7 -7
- package/dist/records/depth/index.d.ts +7 -7
- package/dist/records/index.cjs +3 -3
- package/dist/records/index.d.cts +10 -10
- package/dist/records/index.d.ts +10 -10
- package/dist/records/index.js +3 -3
- package/dist/{requestFunnel-FvE5yLDD.d.ts → requestFunnel-CTG-wNc3.d.ts} +2 -2
- package/dist/{requestFunnel-Bqc1inM9.d.cts → requestFunnel-Dcjyh0j2.d.cts} +2 -2
- package/dist/{runtimeTypes-RN-VXTFV.d.cts → runtimeTypes-4qptUulD.d.cts} +4 -4
- package/dist/{runtimeTypes-C0yPBz89.d.ts → runtimeTypes-CmpdQaE2.d.ts} +4 -4
- package/dist/server/events/index.cjs +1 -1
- package/dist/server/events/index.d.cts +2 -2
- package/dist/server/events/index.d.ts +2 -2
- package/dist/server/events/index.js +1 -1
- package/dist/server/index.cjs +2 -2
- package/dist/server/index.d.cts +3 -3
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +2 -2
- package/dist/televet/booking/index.cjs +1 -1
- package/dist/televet/booking/index.d.cts +17 -9
- package/dist/televet/booking/index.d.ts +17 -9
- package/dist/televet/booking/index.js +1 -1
- package/dist/televet/call/index.cjs +1 -1
- package/dist/televet/call/index.d.cts +13 -1
- package/dist/televet/call/index.d.ts +13 -1
- package/dist/televet/call/index.js +1 -1
- package/dist/televet/index.cjs +1 -1
- package/dist/televet/index.js +1 -1
- package/dist/testing/index.d.cts +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/rn/index.d.cts +7 -7
- package/dist/testing/rn/index.d.ts +7 -7
- package/dist/testing/web/index.d.cts +7 -7
- package/dist/testing/web/index.d.ts +7 -7
- package/dist/{timelineRows-DAB5dpjF.d.cts → timelineRows-BkLhRUDt.d.cts} +1 -1
- package/dist/{timelineRows-D4U6A8zE.d.ts → timelineRows-Dp4ZSnAo.d.ts} +1 -1
- package/dist/{uploadTransport-DKJHs3Yj.d.cts → uploadTransport-C1p8FuG8.d.cts} +5 -1
- package/dist/{uploadTransport-D0M0T4hN.d.ts → uploadTransport-bZIKBTyK.d.ts} +5 -1
- package/dist/{useRecordsDepth-B35y8bV-.d.cts → useRecordsDepth-DRNry1r9.d.cts} +1 -1
- package/dist/{useRecordsDepth--ObtMyjH.d.ts → useRecordsDepth-DnDhTaUL.d.ts} +1 -1
- package/dist/{view-D9JqNQai.d.ts → view-CwuOPIJc.d.ts} +7 -4
- package/dist/{view-B-Toym_j.d.cts → view-D4VdPKCa.d.cts} +7 -4
- package/dist/web/consent/index.d.cts +5 -5
- package/dist/web/consent/index.d.ts +5 -5
- package/dist/web/index.cjs +10 -10
- package/dist/web/index.d.cts +14 -14
- package/dist/web/index.d.ts +14 -14
- package/dist/web/index.js +10 -10
- package/dist/web/notifications/index.d.cts +3 -3
- package/dist/web/notifications/index.d.ts +3 -3
- package/dist/web/records/depth/index.d.cts +7 -7
- package/dist/web/records/depth/index.d.ts +7 -7
- package/dist/web/records/index.cjs +3 -3
- package/dist/web/records/index.d.cts +9 -9
- package/dist/web/records/index.d.ts +9 -9
- package/dist/web/records/index.js +3 -3
- package/dist/web/televet/booking/index.cjs +2 -2
- package/dist/web/televet/booking/index.d.cts +35 -50
- package/dist/web/televet/booking/index.d.ts +35 -50
- package/dist/web/televet/booking/index.js +2 -2
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.d.cts +12 -5
- package/dist/web/televet/call/index.d.ts +12 -5
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/televet/index.cjs +4 -1
- package/dist/web/televet/index.d.cts +31 -2
- package/dist/web/televet/index.d.ts +31 -2
- package/dist/web/televet/index.js +4 -1
- package/package.json +4 -3
package/dist/records/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {createContext,forwardRef,useRef,useMemo,useState,useCallback,useEffect,useReducer,createElement,useContext,useSyncExternalStore,Component}from'react';import {z}from'zod';import {TextInput,View,Pressable,ScrollView,ActivityIndicator,StyleSheet,PanResponder,KeyboardAvoidingView,Image,BackHandler,Text,Modal,AccessibilityInfo,Linking,Share,Platform}from'react-native';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var au=Object.defineProperty;var i=(e,t)=>au(e,"name",{value:t,configurable:true});var Yo=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(Yo.map(e=>e.wireCode));var lu=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"}),ra=Object.freeze(Yo.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:lu[e.wireCode]}))),cu=new Map(ra.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),du=Object.freeze(["http_envelope",...[...new Set(ra.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Nn(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let o of [t??"http_envelope",...du]){let n=cu.get(o+r);if(n)return n}}i(Nn,"contractErrorFor");function uu(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(uu,"contractDocUrl");function na(e){return null}i(na,"publishedDocUrl");var pu=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 oa(e){return pu[e]}i(oa,"categoryFor");function ia(e){let t=Nn(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),o=r.replace(/[^A-Z0-9]/g,"");if(o==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(o){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":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(ia,"fromWire");var mu=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Ko(e){return mu.has(e)}i(Ko,"isAutoRetryable");var yu=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function sa(e){return Ko(e)||yu.has(e)}i(sa,"isRetryableCode");var fu=500,Qo=8e3,aa=4;function la(e,t=Math.random){let r=Math.max(0,e),o=Math.min(fu*2**r,Qo);return Math.floor(t()*o)}i(la,"backoffDelayMs");var gu=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 Xo(e){return gu[e]}i(Xo,"userFacingError");function ca(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(ca,"defineHidden");var bu=/^[a-z][a-z0-9_]{0,63}$/;function F(e,t){let r=Nn(t?.wireCode,t?.wireEnvelope),o={code:e,category:oa(e),retryable:t?.retryable??sa(e),displayMessage:Xo(e)};if(t?.httpStatus!==void 0&&(o.httpStatus=t.httpStatus),t?.requestId&&(o.requestId=t.requestId),typeof t?.reasonCode=="string"&&bu.test(t.reasonCode)&&(o.reasonCode=t.reasonCode),r);return t?.wireMessage&&ca(o,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&ca(o,"raw",t.raw),Object.freeze(o)}i(F,"makeEverfurError");function Pe(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(Pe,"ok");function H(e){return Object.freeze({ok:false,error:e})}i(H,"err");var Mn=class Mn extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Mn.prototype);}};i(Mn,"EverfurConfigError");var ln=Mn;var ya=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),da=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 hu(e){let t=Object.prototype.hasOwnProperty.call(da,e)?da[e]:void 0;if(t!==void 0)return t;let r=e;return ya.has(r)?r:"parsing"}i(hu,"normalizeStatus");function fa(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(fa,"normalizeOrigin");var Ru=z.object({request_id:z.string().min(1),pet_ref:z.string().min(1),status:z.string(),simple_status:z.string().nullish(),simple_status_detail:z.string().nullish(),status_label:z.string().optional(),dispatch_status:z.string().nullish(),can_retry_send:z.boolean().optional(),can_revoke:z.boolean().optional(),can_convert_to_upload:z.boolean().optional(),can_update_clinic_email:z.boolean().optional(),reminder_count:z.number().int().nonnegative().optional(),last_reminder_at:z.string().nullish(),waiting_expectation:z.string().nullish(),document_count:z.number().optional(),held_item_count:z.number().optional(),received_at:z.string().nullish(),parsing_started_at:z.string().nullish(),review_started_at:z.string().nullish(),created_at:z.string().optional(),updated_at:z.string().optional(),source:z.string().nullish().catch(null),action_needed_label:z.string().nullish().catch(null),failure_reason:z.string().nullish().catch(null),failure_code:z.string().nullish().catch(null),recovery_stage:z.string().nullish().catch(null),show_clinic_phone:z.boolean().optional().catch(void 0),clinic_name:z.string().nullish().catch(null),clinic_email:z.string().nullish().catch(null),clinic_phone:z.string().nullish().catch(null),converted_to_upload_at:z.string().nullish().catch(null),request_group_id:z.string().nullish().catch(null)}).passthrough();function fr(e){let t=Ru.safeParse(e);if(!t.success)return null;let r=t.data,o=wu(r.simple_status),n=o==="requested"&&(r.status==="awaiting_upload"||r.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":o==="parsing"&&(r.simple_status_detail==="in_review"||r.simple_status_detail==="review_email_failed")?"in_review":o??hu(r.status);return Object.freeze({id:r.request_id,petRef:r.pet_ref,status:n,simpleStatus:o,simpleStatusDetail:r.simple_status_detail??null,statusLabel:r.status_label??"",dispatchStatus:r.dispatch_status??null,canRetrySend:r.can_retry_send===true,canRevoke:r.can_revoke===true,canConvertToUpload:r.can_convert_to_upload===true,canUpdateClinicEmail:r.can_update_clinic_email===true,reminderCount:r.reminder_count??0,lastReminderAt:r.last_reminder_at??null,waitingExpectation:r.waiting_expectation??null,documentCount:pa(r.document_count,0),heldItemCount:pa(r.held_item_count,0),receivedAt:r.received_at??null,parsingStartedAt:r.parsing_started_at??null,reviewStartedAt:r.review_started_at??null,createdAt:r.created_at??"",updatedAt:r.updated_at??"",wireStatus:r.status,source:r.source??null,actionNeededLabel:r.action_needed_label??null,failureReason:r.failure_reason??null,failureCode:r.failure_code??null,recoveryStage:r.recovery_stage??null,showClinicPhone:r.show_clinic_phone===true,clinicName:r.clinic_name??null,clinicEmail:r.clinic_email??null,clinicPhone:r.clinic_phone??null,convertedToUploadAt:r.converted_to_upload_at??null,requestGroupId:r.request_group_id??null})}i(fr,"mapRequestView");var vu=z.object({request_group_id:z.string().min(1),pet_ref:z.string().min(1),total:z.number().int().nonnegative(),responded:z.number().int().nonnegative(),pending:z.number().int().nonnegative(),members:z.array(z.unknown())});function ga(e){let t=vu.safeParse(e);if(!t.success)return null;let r=t.data,o=Jo(r.members);return o.some(n=>n.petRef!==r.pet_ref)?null:Object.freeze({requestGroupId:r.request_group_id,petRef:r.pet_ref,total:r.total,responded:r.responded,pending:r.pending,members:o})}i(ga,"mapRequestGroup");function wu(e){return !e||e==="awaiting_upload"||e==="in_review"?null:ya.has(e)?e:null}i(wu,"normalizeSimpleStatus");function Jo(e){let t=Array.isArray(e)?e:[],r=[];for(let o of t){let n=fr(o);n!==null&&r.push(n);}return Object.freeze(r)}i(Jo,"mapRequestList");var xu=z.object({source_doc_id:z.string().min(1),request_id:z.string().min(1)});function ba(e){let t=xu.safeParse(e);return t.success?Object.freeze({documentId:t.data.source_doc_id,requestId:t.data.request_id,status:"received"}):null}i(ba,"mapUploadedDocument");var Cu=z.object({label:z.string(),value:z.string()}),Zo=z.object({key:z.string(),category:z.string().optional(),label:z.string().optional(),value:z.string().nullish(),unit:z.string().nullish(),observed_at:z.string().nullish(),status:z.string().nullish(),origin:z.string().nullish(),canonical_key:z.string().nullish()}),Eu=z.object({at:z.string(),value:z.number().nullish(),display:z.string().nullish(),origin:z.string().nullish()}),Su=z.object({key:z.string(),label:z.string().optional(),points:z.array(Eu).optional()}),ku=z.object({title:z.string(),detail:z.string().nullish(),due_at:z.string().nullish()}),ei=z.object({doc_id:z.string(),title:z.string().nullish(),page_count:z.number().nullish(),received_at:z.string().nullish()});function ti(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:fa(e.origin),canonicalKey:e.canonical_key??null})}i(ti,"mapEntityRow");function ri(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(ri,"mapDocumentRow");var Tu=z.object({identity:z.array(Cu).optional(),entities:z.array(Zo).optional(),entity_series:z.array(Su).optional(),forward_looking:z.array(ku).optional(),documents:z.array(ei).optional()});function ha(e,t){let r=Pu(t)?t:{},o=ma(r.schema_version,"epdf/1.0"),n=ma(r.disclaimer,""),l=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return ua(l,o,n);let a=Tu.safeParse(r);if(!a.success)return ua(l,o,n);let c=a.data,s=(c.identity??[]).map(R=>Object.freeze({label:R.label,value:R.value})),d=(c.entities??[]).map(ti),u=(c.entity_series??[]).map(R=>Object.freeze({key:R.key,label:R.label??R.key,points:Object.freeze((R.points??[]).map(v=>Object.freeze({at:v.at,value:v.value??null,display:v.display??null,origin:fa(v.origin)})))})),p=(c.forward_looking??[]).map(R=>Object.freeze({title:R.title,detail:R.detail??null,dueAt:R.due_at??null})),g={};for(let R of c.documents??[])g[R.doc_id]=ri(R);let b=r.is_empty===true||s.length===0&&d.length===0&&u.length===0&&p.length===0&&Object.keys(g).length===0;return Object.freeze({petRef:l,schemaVersion:o,isEmpty:b,withheld:false,generatedAt:Iu(r.generated_at),identity:Object.freeze(s),entities:Object.freeze(d),entitySeries:Object.freeze(u),forwardLooking:Object.freeze(p),documents:Object.freeze(g),disclaimer:n})}i(ha,"mapRecordView");function ua(e,t,r){return Object.freeze({petRef:e,schemaVersion:t,isEmpty:false,withheld:true,generatedAt:null,identity:Object.freeze([]),entities:Object.freeze([]),entitySeries:Object.freeze([]),forwardLooking:Object.freeze([]),documents:Object.freeze({}),disclaimer:r})}i(ua,"withheldView");var _u=z.object({pet_ref:z.string().optional(),granted:z.boolean().optional(),version:z.string().nullish(),granted_at:z.string().nullish()});function Bn(e,t){let r=_u.safeParse(t),o=r.success?r.data:{};return Object.freeze({petRef:typeof o.pet_ref=="string"&&o.pet_ref.length>0?o.pet_ref:e,granted:o.granted===true,version:o.version??null,grantedAt:o.granted_at??null})}i(Bn,"mapConsent");function Pu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Pu,"isObject");function pa(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(pa,"numberOr");function ma(e,t){return typeof e=="string"&&e.length>0?e:t}i(ma,"strOr");function Iu(e){return typeof e=="string"&&e.length>0?e:null}i(Iu,"strOrNull");var Ra=Object.freeze(["published","failed","revoked"]);function gr(e){return Ra.includes(e)}i(gr,"isTerminalStatus");function br(e){if(e===null)return null;let t=e.recordsReason;return t==="consent_required"||t==="session_required"||t==="entitlement"||t==="pet_not_found"?t:null}i(br,"recordsDenialReasonOf");var Du="records_consent_required";function Au(e){let t=e.raw;if(t===null||typeof t!="object")return null;let r=t,o=typeof r.error=="object"&&r.error!==null?r.error.code:r.code;return typeof o=="string"&&o.length>0?o:null}i(Au,"recordsWireCodeOf");function sr(e){return e===null||e.httpStatus!==409?false:Au(e)===Du}i(sr,"isRecordsConsentRequired");var Ou=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Hn(e){return e!==Ou}i(Hn,"isUploadTransportAvailable");var va=Object.freeze({record(){}}),hr=25*1024*1024,wa=64,cn=128,gt=128,dn="application/pdf",xa=9e4;function Ea(e){return new ni(e)}i(Ea,"createRecordsController");var oi=class oi{constructor(t){this.recordCache=new Map;this.consentEpoch=new Map;this.reportedGaps=new Set;this.repository=t.repository,this.uploads=t.uploads,this.telemetry=t.telemetry??va,this.newIdempotencyKey=t.newIdempotencyKey??Fu(),this.timers=t.timers??qu,this.uploadDeadlineMs=t.uploadDeadlineMs??xa;}async createUploadRequest(t){let r=await this.repository.createRequest({pet_ref:t.petRef,idempotency_key:t.idempotencyKey});if(!r.ok)return this.onRequestError(r.error);let o=fr(r.value);return o===null?H(Un()):(this.observeRequest(o),Pe(o))}async getRequest(t){let r=await this.repository.getRequest(t);if(!r.ok)return this.onRequestError(r.error);let o=fr(r.value);return o===null?H(Un()):(this.observeRequest(o),Pe(o))}async listRequests(){let t=await this.repository.listRequests();if(!t.ok)return this.onRequestError(t.error);let r=Jo(t.value);for(let o of r)this.observeRequest(o);return Pe(r)}async uploadDocument(t){let{requestId:r,file:o}=t,n=Lu(o);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),H(Ca(`upload rejected: ${n}`));let l=await this.repository.initiateUpload(r,{content_type:dn,file_size:o.sizeBytes});if(!l.ok)return this.onRequestError(l.error);let a=await this.postToS3(l.value,o,t);if(!a.ok)return this.telemetry.record("records.upload.failed",{reason:a.reason}),H(Ca(a.reason));let c=await this.repository.completeUpload(r,{upload_id:l.value.upload_id});if(!c.ok)return c.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:Vu(c.error)??"corrupt"}),this.onRequestError(c.error);let s=ba(c.value);return s===null?H(Un()):Pe(s)}async postToS3(t,r,o){let n=new AbortController,l=zu(n.signal,o.signal),a=this.timers.setTimeout(()=>n.abort(),this.uploadDeadlineMs);try{let c={signal:l};return o.onProgress&&(c.onProgress=o.onProgress),await this.uploads.postMultipart(t,r,c),{ok:!0}}catch{return {ok:false,reason:n.signal.aborted&&o.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(a);}}async getRecord(t){let r=this.consentEpoch.get(t)??0,o=await this.repository.getRecord(t);if(r!==(this.consentEpoch.get(t)??0))return H(Object.freeze({...F("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!o.ok){let l=br(o.error);return l==="consent_required"?(this.recordCache.delete(t),this.telemetry.record("records.consent.denied",{pet_ref:t})):l==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t}),H(o.error)}let n=ha(t,o.value);return n.petRef!==t?H(Un()):n.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:t}),this.recordCache.delete(t),Pe(n)):(this.recordCache.set(t,n),Pe(n))}peekCachedRecord(t){return this.recordCache.get(t)??null}async getConsent(t){let r=await this.repository.getConsent(t);return r.ok?Pe(Bn(t,r.value)):H(r.error)}async grantConsent(t){let r=await this.repository.putConsent(t.petRef,{consent_version:t.consentVersion,idempotency_key:t.idempotencyKey});return r.ok?Pe(Bn(t.petRef,r.value)):(br(r.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t.petRef}),H(r.error))}async revokeConsent(t){let r=await this.repository.deleteConsent(t);return r.ok?(this.consentEpoch.set(t,(this.consentEpoch.get(t)??0)+1),this.recordCache.delete(t),Pe(Bn(t,r.value))):H(r.error)}reportCapabilityDenied(t){this.telemetry.record("records.capability.denied",t?{pet_ref:t}:{});}observeRequest(t){t.reviewStartedAt!==null&&!this.reportedGaps.has(t.id)&&(this.reportedGaps.add(t.id),this.telemetry.record("records.parse.gap",{request_id:t.id}));}onRequestError(t){return br(t)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),H(t)}};i(oi,"RecordsControllerImpl");var ni=oi;function Lu(e){if(e.mimeType!==dn)return "unsupported_format";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>hr?"oversize":null}i(Lu,"validateFile");function Vu(e){let t=e.wireMessage;return t==="unsupported_format"||t==="oversize"||t==="corrupt"?t:null}i(Vu,"reasonFromWire");function Ca(e){return F("mediaUploadFailed",{retryable:false,wireMessage:e})}i(Ca,"uploadFailed");function Un(){return F("internalError",{retryable:true})}i(Un,"internal");var qu={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function zu(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let o=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),r.signal}i(zu,"mergeSignals");function Fu(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(Fu,"defaultIdempotencyFactory");function Rr(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Rr,"assertNever");function Sa(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(Sa,"errorFrame");function Bu(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(Bu,"authHeaders");function un(e,t){return {...e,headers:{...Hu(e.headers),...Bu(t)}}}i(un,"withAuthHeaders");function Hu(e){if(!e)return {};let t={};for(let[r,o]of Object.entries(e)){let n=r.toLowerCase();n==="authorization"||n==="x-everfur-partner-key"||(t[r]=o);}return t}i(Hu,"stripAuthHeaders");async function ka(e,t){if(t.mode==="anonymous")return t.transport.request(un(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return H(ii())}let o=await t.transport.request(un(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(o.ok||o.error.httpStatus!==401)return o;let n;try{n=await t.identity.currentToken({forceRefresh:!0});}catch{return H(ii())}let l=await t.transport.request(un(e,{mode:"personalized",token:n,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !l.ok&&l.error.httpStatus===401?H(ii(l.error.httpStatus)):l}i(ka,"authedSend");function ii(e){return F("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(ii,"authRejectedError");function Ta(e){return F("internalError",{retryable:true,wireMessage:Uu(e)})}i(Ta,"networkError");function Uu(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Uu,"describeCause");var ju=3e4,$u=Qo*2,Wu="idempotency-key",Gu=new Set(["POST","PUT","PATCH","DELETE"]),Yu=Object.freeze({onEvent(){}}),Ku=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Qu(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(Qu,"seededIdempotencyKey");function vr(e){let t=e.observer??Yu,r=e.timers??Ku,o=e.rng??Math.random,n=e.sleep??((g,b)=>cp(g,r,b)),l=e.maxAttempts??aa,a=e.unaryTimeoutMs??ju,c=e.newIdempotencyKey??ar(),s=i(g=>{try{t.onEvent(g);}catch{}},"emit");async function d(g,b,R){let v=R?.maxAttempts,w=Math.max(1,v??l),y=R?.idempotent??Gu.has(b.method),f=R?.idempotencyKey===void 0?null:Qu(R.idempotencyKey),x=y?f??c():null,h=Xu(b,x),_=0;for(;;){let S=i(j=>Object.freeze({call:g,method:b.method,path:b.path,attempt:_,...x?{idempotencyKey:x}:{},...j}),"stamp");s(S({phase:"attempt"}));let k=ap(a,r),E=lp(k.signal,b.signal),A;try{A=await ka({...h,signal:E.signal},e.auth);}catch(j){A=H(Ta(j));}finally{E.dispose(),k.cancel();}if(A.ok)return s(S({phase:"settled",ok:true,reason:"ok"})),A;let B=A.error,z=Zu(B,_,{maxAttempts:w,rng:o,now:r.now(),aborted:b.signal?.aborted===true,...v!==void 0?{perCallMaxAttempts:v}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),U={ok:false,code:B.code,reason:z.reason,...B.httpStatus!==void 0?{httpStatus:B.httpStatus}:{},...B.requestId!==void 0?{requestId:B.requestId}:{}};if(!z.retry)return s(S({phase:"settled",...U})),H(B);if(s(S({phase:"retry",...U,delayMs:z.delayMs})),await n(z.delayMs,b.signal),b.signal?.aborted===true)return s(S({phase:"settled",...U,reason:"aborted"})),H(B);_+=1;}}i(d,"send");async function u(g){return un(g,await sp(e.auth))}i(u,"authorize");async function*p(g,b,R){s(Object.freeze({call:g,phase:"stream.open",method:b.method,path:b.path,attempt:0}));try{yield*e.auth.transport.stream(b,R);}catch{yield Sa({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:u,stream:p})}i(vr,"createRequestFunnel");function Xu(e,t){let r={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==Wu&&(r[o]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(Xu,"assembleHeaders");function ar(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(ar,"defaultIdempotencyKeyFactory");var Ju=10;function Zu(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let o=ep(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!Ko(e.code))return {retry:false,reason:"terminal-code"};let n=o==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let a=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(Ju,Math.floor(d)))},"policyCeiling"),c=r.perCallMaxAttempts??a()??r.maxAttempts;if(t+1>=c)return {retry:false,reason:"attempts-exhausted"};let s=tp(e,r.now);return s!==null?s>$u?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:s}:{retry:true,reason:n,delayMs:la(t,r.rng)}}i(Zu,"decideRetry");function ep(e){let t=e.code==="unknown"?ia(ip(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(ep,"throttleKind");function tp(e,t){let r=np(e.raw);if(r!==null){let n=r-t;return n>0?n:0}let o=rp(e.raw);return o===null?null:Math.round(o*1e3)}i(tp,"retryOverrideMs");function rp(e){for(let t of si(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(rp,"findRetryAfterSeconds");function np(e){for(let t of si(e)){let r=t.resets_at,o=op(r);if(o!==null)return o}return null}i(np,"findResetsAt");function si(e){if(!_a(e))return [];let t=[e];for(let r of ["error","detail"]){let o=e[r];_a(o)&&t.push(o);}return t}i(si,"candidateScopes");function op(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(op,"parseInstantMs");function ip(e){for(let t of si(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(ip,"rawWireCode");function _a(e){return typeof e=="object"&&e!==null}i(_a,"isRecord");async function sp(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(sp,"resolveDeviceAuth");function ap(e,t){let r=new AbortController,o=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(o),"cancel")}}i(ap,"boundedSignal");function lp(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let o=new AbortController;if(e.aborted||t.aborted)return o.abort(),{signal:o.signal,dispose:r};let n=i(()=>o.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),{signal:o.signal,dispose:i(()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",n);},"dispose")}}i(lp,"mergeSignals");function cp(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(o=>{let n=t.setTimeout(()=>{r?.removeEventListener("abort",l),o();},e),l=i(()=>{t.clearTimeout(n),o();},"onAbort");r?.addEventListener("abort",l,{once:true});})}i(cp,"delayAbortable");function wr(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let o=e.charCodeAt(t+1);if(!(o>=56320&&o<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(wr,"hasLoneSurrogate");var lr="/widget/v1/records";function Ia(e){let{auth:t}=e,r=t.mode,o=e.funnel??vr({auth:t,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=i(async(s,d,u)=>{let p=await o.send(s,d);return p.ok?p:H(pp(p.error,r,u))},"send"),l=i((s,d)=>typeof d!="string"||d.length===0?F("validationFailed",{retryable:false,wireMessage:`${s} is required and must be a non-empty string`}):wr(d)?F("validationFailed",{retryable:false,wireMessage:`${s} contains an unpaired surrogate and cannot be encoded`}):null,"segmentError"),a=i((s,d,u)=>{let p=l(s,d);if(p!==null)return p;let b=[...d].length;return b>u?F("validationFailed",{retryable:false,wireMessage:`${s} is ${b} characters; the server accepts at most ${u}`}):null},"boundsError"),c=i((...s)=>s.find(d=>d!==null)??null,"firstError");return {createRequest:i(s=>{let d=c(a("idempotency_key",s.idempotency_key,cn),a("pet_ref",s.pet_ref,gt));return d?Promise.resolve(H(d)):n("records.createRequest",ai(`${lr}/requests`,s),"request")},"createRequest"),initiateUpload:i((s,d)=>{let u=l("request_id",s);return u?Promise.resolve(H(u)):n("records.initiateUpload",ai(`${lr}/requests/${encodeURIComponent(s)}/uploads/initiate`,d),"request")},"initiateUpload"),completeUpload:i((s,d)=>{let u=l("request_id",s);return u?Promise.resolve(H(u)):n("records.completeUpload",ai(`${lr}/requests/${encodeURIComponent(s)}/uploads/complete`,d),"request")},"completeUpload"),getRequest:i(s=>{let d=l("request_id",s);return d?Promise.resolve(H(d)):n("records.getRequest",jn(`${lr}/requests/${encodeURIComponent(s)}`),"request")},"getRequest"),listRequests:i(async()=>{let s=await n("records.listRequests",jn(`${lr}/requests`),"request");if(!s.ok)return s;let d=s.value;return {ok:true,value:Array.isArray(d)?d:d.items??[]}},"listRequests"),getRecord:i(s=>{let d=a("pet_ref",s,gt);return d?Promise.resolve(H(d)):n("records.getRecord",jn(`${lr}/pets/${encodeURIComponent(s)}/record`),"content")},"getRecord"),getConsent:i(s=>{let d=a("pet_ref",s,gt);return d?Promise.resolve(H(d)):n("records.getConsent",jn(`${lr}/pets/${encodeURIComponent(s)}/consent`),"consent")},"getConsent"),putConsent:i((s,d)=>{let u=c(a("consent_version",d.consent_version,wa),a("idempotency_key",d.idempotency_key,cn),a("pet_ref",s,gt));return u?Promise.resolve(H(u)):n("records.putConsent",mp(`${lr}/pets/${encodeURIComponent(s)}/consent`,d),"consent")},"putConsent"),deleteConsent:i(s=>{let d=a("pet_ref",s,gt);return d?Promise.resolve(H(d)):n("records.deleteConsent",yp(`${lr}/pets/${encodeURIComponent(s)}/consent`),"consent")},"deleteConsent")}}i(Ia,"createHttpRecordsRepository");function Pa(e,t){let r={...e,recordsReason:t};for(let o of ["wireMessage","raw"]){let n=Object.getOwnPropertyDescriptor(e,o);n!==void 0&&Object.defineProperty(r,o,n);}return Object.freeze(r)}i(Pa,"withReason");var dp="pet_not_registered";function up(e){return e.httpStatus!==404?null:e.reasonCode===dp?"pet_not_found":"entitlement"}i(up,"recordsErrorReasonFor");function pp(e,t,r){let o=up(e);return o!==null?Pa(e,o):e.code!=="accessDenied"?e:Pa(e,t==="anonymous"?"session_required":r==="content"?"consent_required":"entitlement")}i(pp,"tagReason");function jn(e){return {method:"GET",path:e}}i(jn,"get");function ai(e,t){return {method:"POST",path:e,body:t}}i(ai,"post");function mp(e,t){return {method:"PUT",path:e,body:t}}i(mp,"put");function yp(e){return {method:"DELETE",path:e}}i(yp,"del");var Da=Symbol.for("@everfur/sdk#EverfurContext@v1"),Aa=globalThis,Oa=Aa[Da]??(Aa[Da]=createContext(null));Oa.displayName??="EverfurContext";function Se(){let e=useContext(Oa);if(e===null)throw new ln("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(Se,"useEverfurContext");var li=new Map,ci=new Set;function La(e){li.set(e,(li.get(e)??0)+1);for(let t of [...ci])t();}i(La,"notifyRecordsConsentWithdrawn");function Rp(e){return li.get(e)??0}i(Rp,"recordsConsentEpochOf");function vp(e){return ci.add(e),()=>{ci.delete(e);}}i(vp,"subscribe");function $n(e){let t=useCallback(()=>Rp(e),[e]);return useSyncExternalStore(vp,t,t)}i($n,"useRecordsConsentEpoch");var ui={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[]},qa=4e3,xp=30;function st(e){let{petRef:t}=e,r=useRef(e.uploadTransport);r.current=e.uploadTransport;let o=e.uploadTransport!==void 0,{runtime:n,userRef:l,scopeEpoch:a}=Se(),c=useMemo(()=>({}),[n,l,t,a,e.controller]),s=useRef(c),[d,u]=useState({scope:c,controller:e.controller??null}),p=e.controller??(d.scope===c?d.controller:null),[g,b]=useState({scope:c,value:ui}),R=g.scope===c?g.value:ui,v=useCallback(I=>{b(D=>D.scope===c?{scope:c,value:I(D.value)}:D);},[c]),w=useRef(0);useEffect(()=>(s.current=c,b({scope:c,value:ui}),()=>{s.current=null,w.current+=1;}),[c]),useEffect(()=>{if(e.controller)return;let{services:I}=n.registry,D={record:i((L,X)=>I.telemetry.track(L,X),"record")},C=n.registry.acquire("records",`${l??""}|${t}${o?"|own-upload":""}`,()=>Ea({repository:Ia({auth:I.authFor(l),...I.errorPolicy?{errorPolicy:I.errorPolicy}:{}}),uploads:o?{postMultipart:i((L,X,fe)=>(r.current??I.uploadTransport).postMultipart(L,X,fe),"postMultipart")}:I.uploadTransport,telemetry:D}),()=>{});return u({scope:c,controller:C}),()=>{n.registry.release(C);}},[n,l,t,e.controller,a,c,o]);let y=useCallback(I=>{v(D=>({...D,...I}));},[v]),f=useCallback(async()=>{if(!p||s.current!==c)return;let I=w.current+=1;S.current=0,A(),y({loading:true,error:null,denialReason:null,withheld:false});let[D,C]=await Promise.all([p.getConsent(t),p.listRequests()]);if(I!==w.current)return;let L=D.ok?D.value:null,X=C.ok?C.value.filter(Be=>Be.petRef===t):[],fe=C.ok?null:C.error;if(L&&L.granted){let Be=await p.getRecord(t);if(I!==w.current)return;if(Be.ok){y({consent:L,requests:X,record:Be.value,withheld:Be.value.withheld,error:Be.value.withheld?Tp():fe,denialReason:null,loading:false});return}y({consent:L,requests:X,record:null,error:Be.error,denialReason:br(Be.error),withheld:false,loading:false});return}y({consent:L,requests:X,record:null,error:D.ok?fe:D.error,denialReason:L?"consent_required":kp(D),withheld:false,loading:false});},[p,t,y,c]);useEffect(()=>(f(),()=>{w.current+=1;}),[f]);let x=useMemo(()=>Sp(R.requests),[R.requests]),h=x?.id??null,_=x?.status??null,S=useRef(0),k=useRef(null),[E,A]=useReducer(I=>I+1,0);useEffect(()=>{if(!p||h===null||_===null||gr(_)||_==="in_review")return;k.current!==String(h)&&(k.current=String(h),S.current=0);let I=false,D=i(async()=>{if(I||S.current>=xp)return;S.current+=1;let L=await p.getRequest(h);if(!I){if(L.ok&&L.value.petRef===t){if(v(X=>({...X,requests:Gn(X.requests,L.value)})),gr(L.value.status)){L.value.status==="published"&&f();return}if(L.value.status==="in_review")return}C=setTimeout(()=>{D();},qa);}},"tick"),C=setTimeout(()=>{D();},qa);return ()=>{I=true,clearTimeout(C);}},[p,h,_,f,E,t,v]);let B=useCallback(async I=>{if(!p||s.current!==c)return Yn();let D=await p.createUploadRequest({petRef:t,idempotencyKey:I});return s.current===c&&D.ok&&D.value.petRef===t&&v(C=>({...C,requests:Gn(C.requests,D.value)})),D},[p,t,c,v]),z=useCallback((I,D)=>{v(C=>({...C,uploadQueue:C.uploadQueue.map(L=>L.key===I?D(L):L)}));},[v]),U=useCallback(async(I,D)=>{let C=Date.now().toString(36),L=D.map((fe,Be)=>{let oe=Cp(fe);return {key:`${C}-${Be}`,name:fe.name??null,status:oe===null?"queued":"skipped",progress:0,skipReason:oe,error:null}}),X=[...L];if(!p||s.current!==c)return Object.freeze(X);v(fe=>({...fe,uploadQueue:L,isUploading:true,uploadProgress:0}));for(let[fe,Be]of D.entries()){let oe=L[fe];if(oe.status==="skipped")continue;if(s.current!==c)break;z(oe.key,tt=>({...tt,status:"uploading",progress:0})),y({uploadProgress:0});let xe=await p.uploadDocument({requestId:I,file:Be,onProgress:i(tt=>{if(s.current!==c)return;let Nt=Math.min(1,Math.max(0,tt));z(oe.key,Mt=>({...Mt,progress:Math.max(Mt.progress,Nt)})),y({uploadProgress:Nt});},"onProgress")});if(s.current!==c)break;let xt=xe.ok?{...oe,status:"done",progress:1}:{...oe,status:"failed",error:xe.error};if(X[fe]=xt,z(oe.key,()=>xt),xe.ok){let tt=await p.getRequest(I);s.current===c&&tt.ok&&tt.value.petRef===t&&v(Nt=>({...Nt,requests:Gn(Nt.requests,tt.value)}));}}return s.current===c&&y({isUploading:false,uploadProgress:null}),Object.freeze(X)},[p,y,z,t,c,v]),j=useCallback(async(I,D)=>{if(!p||s.current!==c)return Yn();let C=`${Date.now().toString(36)}-0`;v(X=>({...X,isUploading:true,uploadProgress:0,uploadQueue:[{key:C,name:D.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let L=await p.uploadDocument({requestId:I,file:D,onProgress:i(X=>{s.current===c&&(y({uploadProgress:X}),z(C,fe=>({...fe,progress:Math.max(fe.progress,Math.min(1,X))})));},"onProgress")});if(s.current!==c)return L;if(y({isUploading:false,uploadProgress:null}),z(C,X=>L.ok?{...X,status:"done",progress:1}:{...X,status:"failed",error:L.error}),L.ok){let X=await p.getRequest(I);s.current===c&&X.ok&&X.value.petRef===t&&v(fe=>({...fe,requests:Gn(fe.requests,X.value)}));}return L},[p,y,z,t,c,v]),re=useCallback(async(I,D)=>{if(!p||s.current!==c)return Yn();let C=await p.grantConsent({petRef:t,consentVersion:I,idempotencyKey:D});return C.ok&&s.current===c&&f(),C},[p,t,f,c]),se=useCallback(async()=>{if(!p||s.current!==c)return Yn();let I=await p.revokeConsent(t);return I.ok&&La(t),I.ok&&s.current===c&&(w.current+=1,y({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:I.value})),I},[p,t,y,c]),Te=useCallback(()=>{f();},[f]),ee=Ep(R,p!==null);return useMemo(()=>({status:ee,record:R.record,requests:R.requests,activeRequest:x,consent:R.consent,error:R.error,denialReason:R.denialReason,withheld:R.withheld,isUploading:R.isUploading,uploadProgress:R.uploadProgress,uploadQueue:R.uploadQueue,createRequest:B,uploadDocument:j,uploadDocuments:U,grantConsent:re,revokeConsent:se,refresh:Te}),[ee,R,x,B,j,U,re,se,Te])}i(st,"useEverfurRecords");function Cp(e){if(e.mimeType!==dn)return "unsupported";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>hr?"too_large":null}i(Cp,"skipReasonFor");function Ep(e,t){return e.loading||!t?"loading":e.withheld||e.denialReason!==null||e.error!==null?"error":e.record!==null&&!e.record.isEmpty||e.requests.length>0?"populated":"empty"}i(Ep,"selectStatus");function Sp(e){if(e.length===0)return null;let t=e[0];for(let r of e)r.updatedAt>t.updatedAt&&(t=r);return t}i(Sp,"newestRequest");function Gn(e,t){let r=e.filter(o=>o.id!==t.id);return [t,...r]}i(Gn,"replaceRequest");function kp(e){return e.ok?"consent_required":br(e.error)??"consent_required"}i(kp,"consentDenial");function Tp(){return F("internalError",{retryable:false})}i(Tp,"withheldSentinel");function Yn(){return {ok:false,error:F("internalError",{retryable:true})}}i(Yn,"notReady");function pi(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(pi,"reportHostFailure");function _p(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(_p,"isThenable");function Kn(e,...t){if(typeof e=="function")try{let r=e(...t);return _p(r)&&Promise.resolve(r).then(void 0,pi),r}catch(r){pi(r);return}}i(Kn,"callHost");var za=new WeakMap;function mn(e){if(typeof e!="function")return;let t=za.get(e);if(t!==void 0)return t;let r=i((...o)=>{Kn(e,...o);},"guarded");return za.set(e,r),r}i(mn,"guardHost");function Oe(e,t){let r=null;for(let o of t){let n=e[o];typeof n=="function"&&(r??={...e},r[o]=mn(n));}return r??e}i(Oe,"guardHostProps");function Or(e,...t){let r;try{r=e(...t);}catch(o){return pi(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(r).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(Or,"callHostAsync");var Fa=Object.freeze({name:"dashboard"});function Qn(e=Fa){return Object.freeze({stack:Object.freeze([e])})}i(Qn,"initialRecordsNav");function Xn(e){return e.stack[e.stack.length-1]??Fa}i(Xn,"currentRecordsScreen");function mi(e,t){return Object.freeze({stack:Object.freeze([...e.stack,t])})}i(mi,"pushRecordsNav");function yi(e,t){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),t])})}i(yi,"replaceRecordsNav");function fi(e){return Qn(e)}i(fi,"resetRecordsNav");function Jn(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(Jn,"popRecordsNav");function Na(e,t){return t.name==="dashboard"?fi(t):Xn(e).name==="upload"&&t.name==="request"?yi(e,t):mi(e,t)}i(Na,"transitionRecordsNav");function gi(e,t){switch(t.type){case "push":return mi(e,t.screen);case "pop":return Jn(e).state;case "replace":return yi(e,t.screen);case "reset":return fi(t.screen);case "navigate":return Na(e,t.screen);default:return e}}i(gi,"recordsNavReducer");function Ri(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))Ri(e[t]);}return e}i(Ri,"deepFreeze");var Pp=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),Ba={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},Ha={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},Ma={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},Ip={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Dp={regular:"400",medium:"500",bold:"700"},Ap={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Op=0,Zn="System",eo="monospace",Lp=["content","heading","control","compact","badge"];function Vp(e){let t={};for(let r of Lp)t[r]=e;return t}i(Vp,"authoredTierSizes");function Ua(){return {family:Zn,mono:eo,fontUrl:null,families:{regular:Zn,medium:Zn,bold:Zn,mono:eo,monoMedium:eo,monoBold:eo},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:Ma,tierSizes:Vp(Ma),lineHeight:Ip,weight:Dp,letterSpacing:Ap,scale:1,maxScale:Op,scaleCaps:Pp}}i(Ua,"baseType");var ja={},bi=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function hi(e){return `cubic-bezier(${e.join(", ")})`}i(hi,"cssCubicBezier");var $a={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:hi(bi.standard),emphasized:hi(bi.emphasized),exit:hi(bi.exit)},reducedMotion:false},qp={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)"},Wa=Ri({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:qp,space:Ba,radius:Ha,type:Ua(),motion:$a,slots:ja}),zp={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)"};Ri({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:zp,space:Ba,radius:Ha,type:Ua(),motion:$a,slots:ja});var Ga=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Ya=globalThis,vi=Ya[Ga]??(Ya[Ga]=createContext(Wa));vi.displayName??="EverfurThemeContext";function V(){return useContext(vi)}i(V,"useEverfurTheme");function Up(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i(Up,"tierMultiplier");function m({tier:e="content",...t}){let{type:r}=V(),o=Up(r,e);return createElement(Text,o===void 0?t:{maxFontSizeMultiplier:o,...t})}i(m,"Text");var He=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var jp=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function T(e,t){let r=e.type,o=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:o}:{fontFamily:o,fontWeight:r.weight[jp[t]]}}i(T,"face");var W=Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you\u2019re authorizing",send:"Send request",sending:"Sending\u2026",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can\u2019t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:i(e=>`Typed signature: ${e}`,"typedSignatureA11y"),missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used"});var we=Object.freeze({title:W.title,placeholder:W.placeholder,searchA11y:W.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:W.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 Qa(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(Qa,"clinicEmailStatusBadge");function Xa(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} km`}i(Xa,"formatClinicDistanceLabel");function Ja(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} ${e===1?"kilometer":"kilometers"} away`}i(Ja,"formatClinicDistanceForA11y");var Za=300,wi=2;var pe=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 el(e){return !gr(e.status)}i(el,"isRecordsInProgress");function to(e,t){if(t===null)return null;let r=e.filter(l=>l.petRef===t);if(r.length===0)return null;let o=r.find(l=>l.status==="published");return o!==void 0?o:r.filter(el).sort((l,a)=>a.updatedAt.localeCompare(l.updatedAt))[0]??null}i(to,"pickPetRecordsRequest");function xi(e){if(e.hasMarkers)return "published";let t=to(e.requests,e.petRef);return t===null?"none":t.status==="published"||el(t)?"in_progress":"none"}i(xi,"deriveRecordsDashboardState");function $p(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i($p,"selectDashboardLoading");function Ci(e){return $p(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(Ci,"selectDashboardView");function pt(e){return e?.httpStatus===429?"rate_limited":e?.httpStatus===502?"service_unavailable":"error"}i(pt,"recordsEmptyVariantForError");var be=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 Wp(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(Wp,"fallbackFailureTitle");function tl(e){let t=e.failureReason?.trim()??"";return t.length>0?t:Wp(e)}i(tl,"failureTitle");var Gp=1440*60*1e3;function Ei(e,t){if(!e.createdAt)return 0;let r=Date.parse(e.createdAt);if(Number.isNaN(r))return 0;let o=t-r;return o<=0?0:Math.floor(o/Gp)}i(Ei,"requestElapsedDays");var Yp=7;function rl(e,t){return e.wireStatus!=="awaiting_response"?false:Ei(e,t)>=Yp}i(rl,"requestWaitingTooLong");function Si(e){return e.status==="failed"}i(Si,"isTerminalFailure");function nl(e){return Si(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i(nl,"shouldOfferRecovery");function sl(e,t){let[r,o]=useState(""),[n,l]=useState(""),[a,c]=useState([]),[s,d]=useState(null),[u,p]=useState([]),[g,b]=useState(true),[R,v]=useState(false),[w,y]=useState(false),[f,x]=useState(null),[h,_]=useState(null),[S,k]=useState(0),E=useRef(0),A=useRef(true),B=t?.latitude,z=t?.longitude,U=useMemo(()=>B!==void 0&&z!==void 0?{latitude:B,longitude:z}:void 0,[B,z]);useEffect(()=>(A.current=true,()=>{A.current=false,E.current+=1;}),[e]),useEffect(()=>{let ee=true;return b(true),e.recentClinics({limit:5}).then(I=>{ee&&(I.ok&&p(I.value.clinics),b(false));}).catch(()=>{ee&&b(false);}),()=>{ee=false;}},[e]),useEffect(()=>{let ee=r.trim();if(ee.length<wi){l("");return}let I=setTimeout(()=>l(ee),Za);return ()=>clearTimeout(I)},[r]);let j=n.length>=wi;useEffect(()=>{let ee=E.current+=1;if(c([]),d(null),x(null),_(null),!j){v(false);return}v(true),e.searchClinics({query:n,limit:25,...U?{location:U}:{}}).then(I=>{!A.current||ee!==E.current||(I.ok?(c(I.value.clinics),d(I.value.nextCursor)):x(I.error),v(false));}).catch(()=>{A.current&&ee===E.current&&v(false);});},[e,n,j,U,S]);let re=useCallback(()=>{if(!j||s===null||w)return;let ee=E.current;y(true),_(null),e.searchClinics({query:n,limit:25,cursor:s,...U?{location:U}:{}}).then(I=>{!A.current||ee!==E.current||(I.ok?(c(D=>[...D,...I.value.clinics]),d(I.value.nextCursor)):_(I.error),y(false));}).catch(()=>{A.current&&ee===E.current&&y(false);});},[e,s,n,j,w,U]),se=useCallback(ee=>o(ee),[]),Te=useCallback(()=>k(ee=>ee+1),[]);return useMemo(()=>({query:r,debouncedQuery:n,isSearchActive:j,clinics:a,recent:u,recentLoading:g,initialLoading:R,loadingMore:w,hasNextPage:s!==null,error:f,pageError:h,setQuery:se,loadMore:re,retry:Te}),[r,n,j,a,u,g,R,w,s,f,h,se,re,Te])}i(sl,"useClinicPicker");function Ti(e,t,r,o){return Object.freeze({key:e?.id??`free:${t??""}`,clinic:e,freeText:t,email:r,idempotencyKey:o})}i(Ti,"clinicDraftFor");var Gr=10,no=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),yn=i((e,t=1)=>z.string().refine(r=>!wr(r)&&[...r].length>=t&&[...r].length<=e),"text"),ll=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),Kp=z.object({clinicId:no.optional(),clinicFreeText:yn(200).refine(e=>e.trim().length>0).optional(),clinicEmail:yn(320,3).refine(e=>!ll(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:no.optional(),signaturePngBase64:z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0)),Qp=z.object({petRef:yn(128),ownerName:yn(200).refine(e=>e.trim().length>0&&!ll(e)),authorizationVersion:yn(64),clinics:z.array(Kp).min(1).max(Gr)}).strict(),Xp=z.object({request_group_id:no,pet_ref:z.string(),created_count:z.number().int().nonnegative(),failed_count:z.number().int().nonnegative(),results:z.array(z.object({idempotency_key:z.string(),clinic_id:no.nullable().optional(),clinic_free_text:z.string().nullable().optional(),created:z.boolean(),request:z.unknown().optional(),failure_code:z.string().nullable().optional(),failure_reason:z.string().nullable().optional()}))});function cl(e){let t=e.funnel??vr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!Qp.safeParse(r).success)return H(F("validationFailed",{retryable:false}));let o=await t.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:r.petRef,owner_name:r.ownerName,authorization_version:r.authorizationVersion,clinics:r.clinics.map(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=Xp.safeParse(o.value);if(!n.success||n.data.pet_ref!==r.petRef)return al();let l=[];for(let a of n.data.results){let c=a.request===void 0||a.request===null?null:fr(a.request);if(a.created!==(c!==null))return al();l.push(Object.freeze({idempotencyKey:a.idempotency_key,clinicId:a.clinic_id??null,clinicFreeText:a.clinic_free_text??null,created:a.created,request:c,failureCode:a.failure_code??null,failureReason:a.failure_reason??null}));}return Pe(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(cl,"createRecordsClinicBatchClient");function al(){return H(F("internalError",{retryable:false}))}i(al,"malformed");var dl=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Jp=z.object({clinics:z.array(z.object({clinic_id:dl,name:z.string().min(1),address:z.string().nullable(),phone:z.string().nullable(),email_status:z.string(),distance_km:z.number().finite().nonnegative().nullable()})),next_cursor:z.string().nullable().optional()}),Zp=z.object({authorization_version:z.string().min(1),scope_template:z.string().min(1),authorization_template:z.string().min(1)}),em=z.object({upload_id:z.string().min(1),upload_url:z.string().url().refine(e=>e.startsWith("https://")),upload_fields:z.record(z.string())});function ul(e){let{repository:t}=e,r=i(async n=>{let l=await n;if(!l.ok)return l;let a=fr(l.value);return a===null?Lr():Pe(a)},"request"),o=i(async n=>{let l=await n;if(!l.ok)return l;let a=Jp.safeParse(l.value);return a.success?Pe(Object.freeze({clinics:Object.freeze(a.data.clinics.map(c=>Object.freeze({id:c.clinic_id,name:c.name,address:c.address,phone:c.phone,emailStatus:c.email_status,distanceKm:c.distance_km}))),nextCursor:a.data.next_cursor??null})):Lr()},"page");return {searchClinics:i((n={})=>o(t.searchClinics(n)),"searchClinics"),recentClinics:i((n={})=>o(t.recentClinics(n)),"recentClinics"),async getRequestGroup(n){let l=await t.getRequestGroup(n);if(!l.ok)return l;let a=ga(l.value);return a===null?Lr():Pe(a)},async getAuthorizationCopy(){let n=await t.getAuthorizationCopy();if(!n.ok)return n;let l=Zp.safeParse(n.value);return l.success?Pe(Object.freeze({authorizationVersion:l.data.authorization_version,scopeTemplate:l.data.scope_template,authorizationTemplate:l.data.authorization_template})):Lr()},async createClinicRequest(n){let l=await r(t.createClinicRequest(n));return l.ok&&l.value.petRef!==n.petRef?Lr():l},retryRequest:i(n=>r(t.retryRequest(n)),"retryRequest"),revokeRequest:i(n=>r(t.revokeRequest(n)),"revokeRequest"),updateClinicEmail:i((n,l)=>r(t.updateClinicEmail(n,l)),"updateClinicEmail"),convertToUpload:i(n=>r(t.convertToUpload(n)),"convertToUpload"),async initiateSignatureUpload(n){let l=await t.initiateSignatureUpload(n);if(!l.ok)return l;let a=em.safeParse(l.value);return a.success?Pe(Object.freeze({uploadId:a.data.upload_id,uploadUrl:a.data.upload_url,uploadFields:Object.freeze(a.data.upload_fields)})):Lr()},async completeSignatureUpload(n){let l=await t.completeSignatureUpload(n);if(!l.ok)return l;let a=z.object({signature_id:dl}).safeParse(l.value);return a.success?Pe(a.data.signature_id):Lr()}}}i(ul,"createRecordsClinicController");function Lr(){return H(F("internalError",{retryable:false}))}i(Lr,"malformed");var xr="/widget/v1/records",pl=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Er=i((e,t=1)=>z.string().refine(r=>!wr(r)&&[...r].length>=t&&[...r].length<=e),"text"),yl=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),fl=Er(320,3).refine(e=>!yl(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),ml=Er(64),tm=z.object({limit:z.number().int().min(1).max(25).optional()}).strict(),rm=z.object({query:Er(200,0).optional(),location:z.object({latitude:z.number().finite().min(-90).max(90),longitude:z.number().finite().min(-180).max(180)}).strict().optional(),limit:z.number().int().min(1).max(100).optional(),cursor:Er(512,0).optional()}).strict(),nm=z.object({petRef:Er(128),ownerName:Er(200).refine(e=>e.trim().length>0&&!yl(e)),authorizationVersion:Er(64),clinicId:pl.optional(),clinicFreeText:Er(200).refine(e=>e.trim().length>0).optional(),clinicEmail:fl.optional(),signatureId:pl.optional(),signaturePngBase64:z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0));function gl(e){let t=e.funnel??vr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((n,l,a=false)=>t.send(`records.clinic.${n}`,l,l.method==="GET"||a?void 0:{idempotent:false,maxAttempts:1}),"send"),o=i((n,l,a)=>ml.safeParse(n).success?r(l,{method:"POST",path:`${xr}/requests/${encodeURIComponent(n)}/${l}`,...a?{body:a}:{}}):Cr(),"recover");return {searchClinics(n){return rm.safeParse(n).success?r("search",{method:"GET",path:`${xr}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):Cr()},recentClinics(n){return tm.safeParse(n).success?r("recent",{method:"GET",path:`${xr}/clinics/recent`,query:{limit:n.limit}}):Cr()},getRequestGroup(n){return ml.safeParse(n).success?r("requestGroup",{method:"GET",path:`${xr}/request-groups/${encodeURIComponent(n)}`}):Cr()},getAuthorizationCopy:i(()=>r("authorizationCopy",{method:"GET",path:`${xr}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return nm.safeParse(n).success?r("create",{method:"POST",path:`${xr}/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):Cr()},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 fl.safeParse(l).success?o(n,"clinic-email",{clinic_email:l}):Cr()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?Cr():r("signatureInitiate",{method:"POST",path:`${xr}/signatures/initiate`,body:{content_type:"image/png",file_size:n}})},completeSignatureUpload(n){return /^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n)?r("signatureComplete",{method:"POST",path:`${xr}/signatures/complete`,body:{upload_id:n}}):Cr()}}}i(gl,"createHttpRecordsClinicRepository");function Cr(){return Promise.resolve(H(F("validationFailed",{retryable:false})))}i(Cr,"invalid");function Ut(){let{runtime:e,userRef:t,scopeEpoch:r}=Se(),o=useMemo(()=>{let{services:l}=e.registry;return ul({repository:gl({auth:l.authFor(t),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})})},[e,t,r]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>{let l=i(async a=>{if(t===null||n.current!==o)return H(F("accessDenied"));let c=await a();return n.current===o?c:H(F("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,c)=>l(()=>o.updateClinicEmail(a,c)),"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,t])}i(Ut,"useEverfurRecordsClinic");function _i(){let{runtime:e,userRef:t,scopeEpoch:r}=Se(),o=useMemo(()=>{let{services:l}=e.registry;return cl({auth:l.authFor(t),...l.errorPolicy?{errorPolicy:l.errorPolicy}:{}})},[e,t,r]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>({async createClinicRequestBatch(l){if(t===null||n.current!==o)return H(F("accessDenied"));let a=await o.createClinicRequestBatch(l);return n.current===o?a:H(F("accessDenied"))}}),[o,t])}i(_i,"useEverfurRecordsClinicBatch");var Di=class Di extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,o){return Object.is(r.resetKey,o.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(Di,"HostRenderBoundary");var Pi=Di;function im({render:e}){return e()}i(im,"RenderHost");function Ii({render:e,fallback:t,resetKey:r}){return createElement(Pi,{fallback:t,resetKey:r,children:createElement(im,{render:e})})}i(Ii,"HostRender");var sm=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 am(e){return sm[e]}i(am,"requires");function vl(e,t,r){let o=am(e),n=new Map;for(let c of t)n.set(c.resource,c);if(r?.isPending===true&&o.some(c=>!n.has(c)))return Ai({name:e,enabled:false,isPending:true,limits:{}});let l=lm(o,n);return o.filter(c=>n.get(c)?.granted!==true).length===0?Ai({name:e,enabled:true,isPending:false,limits:l}):Ai({name:e,enabled:false,isPending:false,limits:l,disabled:cm(o,n)})}i(vl,"decideCapability");function lm(e,t){let r={};for(let o of e){let n=t.get(o)?.limits;if(n)for(let[l,a]of Object.entries(n)){let c=r[l];r[l]=c===void 0?a:Math.min(c,a);}}return r}i(lm,"mergeLimits");function cm(e,t){for(let r of e){let o=t.get(r)?.disabled;if(o)return Object.freeze({reason:o.reason,level:o.level,recoverable:o.recoverable})}return Object.freeze({reason:Xo("accessDenied"),level:"user_entitlement",recoverable:false})}i(cm,"disabledFor");function Ai(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(Ai,"freezeDecision");function Oi(e){let{runtime:t}=Se(),r=t.entitlements,o=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>vl(e,o.decisions,{isPending:o.isPending}),[e,o])}i(Oi,"useCapability");var pm=48;function mm(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(mm,"selectView");function Le(e){let{capability:t,children:r,renderDisabled:o,renderPending:n,style:l}=e,a=Oi(t),c=useMemo(()=>mm(a),[a]);switch(c){case "enabled":return r;case "pending":return n?jsx(Ii,{render:n,fallback:jsx(xl,{capability:t,style:l})}):jsx(xl,{capability:t,style:l});case "disabled":return o?jsx(Ii,{render:()=>o(a),fallback:jsx(Cl,{decision:a,style:l}),resetKey:a}):jsx(Cl,{decision:a,style:l});default:return Rr(c)}}i(Le,"CapabilityGate");function xl({capability:e,style:t}){let r=V(),o=useMemo(()=>El(r),[r]);return jsx(View,{style:[o.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:o.skeletonBar})})}i(xl,"PendingSkeleton");function Cl({decision:e,style:t}){let r=V(),o=useMemo(()=>El(r),[r]),n=e.disabled?.reason??"";return jsx(View,{style:[o.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:n,children:n.length>0?jsx(m,{style:o.offstateText,children:n}):null})}i(Cl,"OffState");function El(e){let{color:t,space:r,radius:o,type:n}=e;return StyleSheet.create({offstate:{minHeight:pm,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:o.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...T(e,"regular"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:o.xs,backgroundColor:t.brandSofter}})}i(El,"makeStyles");var fn=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 Ve(e){let t=V(),r=useMemo(()=>gm(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${fn.title}. ${fn.body}`,children:[jsx(m,{style:r.title,children:fn.title}),jsx(m,{style:r.body,children:fn.body})]})}i(Ve,"ClinicalDisclaimer");function gm(e){let{color:t,space:r,type:o}=e;return StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:StyleSheet.hairlineWidth,borderTopColor:t.borderHairlineGreen,backgroundColor:t.surfaceCream,gap:r.xs},title:{...T(e,"bold"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.secondary,letterSpacing:o.letterSpacing.eyebrow},body:{...T(e,"regular"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.muted}})}i(gm,"makeStyles");function rt(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(rt,"slotBox");function at(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(at,"slotText");var Tl=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"})}),qi=60;function _l(e){return `Try again in ${e}s`}i(_l,"coolingActionLabel");var Pl="Try again, available shortly";function Ue({variant:e,onAction:t,message:r,testID:o}){let n=wm(),l=Tl[e],[a,c]=useState(e==="rate_limited"?qi:0);useEffect(()=>{e==="rate_limited"&&c(qi);},[e]),useEffect(()=>{if(a<=0)return;let u=setTimeout(()=>c(p=>Math.max(0,p-1)),1e3);return ()=>clearTimeout(u)},[a]);let s=e==="rate_limited"&&a>0,d=s?_l(a):l.action;return jsxs(View,{style:n.container,accessibilityRole:"summary",testID:o,children:[jsx(View,{style:n.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:n.title,children:l.title}),jsx(m,{style:n.body,children:r??l.body}),d!==null&&t?jsx(Pressable,{onPress:t,disabled:s,accessibilityRole:"button",accessibilityLabel:s?Pl:d,accessibilityState:{disabled:s},style:[n.action,s?n.actionDisabled:null],testID:o?`${o}-action`:`records-empty-${e}-action`,children:jsx(m,{style:n.actionLabel,children:d})}):null]})}i(Ue,"RecordsEmptyState");function wm(){let e=V();return useMemo(()=>xm(e),[e])}i(wm,"useStyles");function xm(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,a=r.lg+r.xs+r.xs/2;return StyleSheet.create({container:{paddingVertical:r.xxl,paddingHorizontal:r.xl,alignItems:"center",gap:r.sm+r.xs/2},glyph:{width:a,height:a,borderRadius:a/2,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{...T(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug)-1,color:t.brandInk,textAlign:"center"},body:{...T(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.normal),color:t.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:r.sm,minHeight:r.xxl+r.sm,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,backgroundColor:t.brand,alignItems:"center",justifyContent:"center",...rt(l.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{...T(e,"bold"),color:t.onPrimary,fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug)-1,...at(l.primaryButton)}})}i(xm,"makeStyles");var Ye="Back";function Ke({title:e,onBack:t,right:r,testID:o,variant:n="brand"}){let l=bn();return jsxs(View,{style:l.row,testID:o,children:[t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Ye,hitSlop:12,style:l.back,testID:o?`${o}-back`:void 0,children:jsx(View,{style:l.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):jsx(View,{style:l.back}),jsx(m,{style:n==="document"?l.documentTitle:l.title,accessibilityRole:"header",numberOfLines:1,children:e}),jsx(View,{style:l.right,children:r??jsx(View,{style:l.back})})]})}i(Ke,"ScreenHeader");function Ol(){let e=bn();return jsxs(View,{style:e.listGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.listBar}),jsx(View,{style:e.listBar}),jsx(View,{style:e.listBar})]})}i(Ol,"ListGlyph");function Ll(){let e=bn();return jsxs(View,{style:e.shareGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:[e.shareDot,e.shareDotTop]}),jsx(View,{style:[e.shareDot,e.shareDotLeft]}),jsx(View,{style:[e.shareDot,e.shareDotBottom]}),jsx(View,{style:[e.shareStroke,e.shareStrokeUp]}),jsx(View,{style:[e.shareStroke,e.shareStrokeDown]})]})}i(Ll,"ShareGlyph");function Vl(){let e=bn();return jsxs(View,{style:e.sendGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.sendBody}),jsx(View,{style:e.sendFold})]})}i(Vl,"SendGlyph");function ql(){let e=bn();return jsxs(View,{style:e.downloadGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.downloadStem}),jsx(View,{style:e.downloadHead}),jsx(View,{style:e.downloadTray})]})}i(ql,"DownloadGlyph");function bn(){let e=V();return useMemo(()=>Tm(e),[e])}i(bn,"useStyles");function Tm(e){let{color:t,space:r,type:o}=e,n=r.xxl+r.md,l=r.md,a=r.xs/2,c=r.lg+r.xs+r.xs/2;return StyleSheet.create({row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md,gap:r.sm},back:{width:n,height:n,alignItems:"center",justifyContent:"center"},chevron:{width:l,height:l,borderLeftWidth:a,borderBottomWidth:a,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginLeft:r.xs},title:{flex:1,...T(e,"bold"),fontSize:o.size.heading,lineHeight:Math.round(o.size.heading*o.lineHeight.tight)+1,color:t.brandInk},documentTitle:{flex:1,textAlign:"center",...T(e,"bold"),fontSize:o.size.subtitle,lineHeight:Math.round(o.size.subtitle*o.lineHeight.snug),color:t.text.primary},right:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2},listGlyph:{width:c,height:c,justifyContent:"space-evenly"},listBar:{height:a,borderRadius:a,backgroundColor:t.brandInk},shareGlyph:{width:c-r.xs,height:c-r.xs},shareDot:{position:"absolute",width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs,borderWidth:a,borderColor:t.brandInk},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:r.xs+r.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:r.xs,top:r.sm,width:r.sm+r.xs/2,height:a,backgroundColor:t.brandInk},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:c-r.xs,height:c-r.xs},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:a,borderColor:t.brandInk,transform:[{rotate:"45deg"}],borderRadius:a},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:a,backgroundColor:t.brandInk},downloadGlyph:{width:c-r.xs,height:c-r.xs,alignItems:"center"},downloadStem:{width:a,height:r.sm+r.xs/2,backgroundColor:t.brandInk},downloadHead:{width:r.sm,height:r.sm,borderRightWidth:a,borderBottomWidth:a,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginTop:-r.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:r.xs+r.xs/2,borderLeftWidth:a,borderRightWidth:a,borderBottomWidth:a,borderColor:t.brandInk}})}i(Tm,"makeStyles");var Im=120,Dm=44;function Am({reason:e,onExit:t,exitLabel:r,style:o}){let{color:n,space:l,radius:a,type:c}=V();return jsxs(View,{testID:"records-gate-off",style:[{minHeight:Im,justifyContent:"center",gap:l.md,padding:l.lg,borderRadius:a.md,borderWidth:1,borderColor:n.brandBorder,backgroundColor:n.surfaceCream},o],children:[e.length>0?jsx(m,{style:{fontSize:c.size.bodyTight,color:n.text.muted},children:e}):null,jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:r,testID:"records-gate-off-exit",style:{minHeight:Dm,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:l.lg,borderRadius:a.pill,borderWidth:1.5,borderColor:n.brand},children:jsx(m,{style:{fontSize:c.size.body,color:n.brand},children:r})})]})}i(Am,"RecordsGateOffState");function ze(e,t){return e===void 0?{}:{renderDisabled:i(r=>jsx(Am,{reason:r.disabled?.reason??"",onExit:e,exitLabel:t}),"renderDisabled")}}i(ze,"recordsGateExit");var Lm="your pet";function Fe(e){let t=e?.trim()??"";return t.length>0?t:Lm}i(Fe,"petNameOr");var mt=Object.freeze({title:"Health records",openTimeline:"Open timeline",loading:"Loading health records",lead:i(e=>`${Fe(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")}),jt=Object.freeze({title:"Marker Summary",marker:"Marker",markers:"Markers",outOfRange:"OUT OF RANGE",inRange:"IN RANGE",noRange:"NO RANGE",subtitle:"Summary of your pet\u2019s biomarkers",ask:"Ask about these markers",askA11y:"Ask Everfur about these markers",a11y:i((e,t,r,o)=>`Marker summary: ${e} ${e===1?"marker":"markers"}, ${t} in range, ${r} out of range${o>0?`, ${o} without a range`:""}.`,"a11y")}),zi=Object.freeze({counter:i((e,t)=>`${e+1} of ${t}`,"counter"),a11y:i((e,t,r)=>e!==null?`${e}, marker ${t+1} of ${r}. Swipe left or right to see more markers.`:`Marker ${t+1} of ${r}`,"a11y")}),cr=Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we\u2019ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askA11y:i(e=>`Ask Everfur about ${e}`,"askA11y"),status:i(e=>`Status: ${e}`,"status"),latestA11y:i((e,t,r)=>`Latest reading ${e}, ${t}, collected ${r}`,"latestA11y"),readingsA11y:i(e=>`${e} readings, oldest to newest`,"readingsA11y")}),Et=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"}),Sr=Object.freeze({title:i(e=>`${Fe(e)}\u2019s records request`,"title"),body:i(e=>`We\u2019re requesting ${Fe(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 ${Fe(e)}.`,"a11y"),openA11y:i((e,t)=>`Open ${Fe(e)}\u2019s records request. ${t}`,"openA11y"),ask:"Ask about this request",askA11y:"Ask Everfur about this records request"}),Vr=Object.freeze({title:i(e=>`Add ${Fe(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 ${Fe(e)}\u2019s records from a clinic`,"requestFromClinicA11y"),uploadDocument:"Upload a document",uploadDocumentA11y:i(e=>`Upload one of ${Fe(e)}\u2019s records`,"uploadDocumentA11y")});var so="rgba(0,0,0,0.4)";function ue(){let e=V();return useMemo(()=>Fm(e),[e])}i(ue,"useScreenStyles");function kr({disclaimer:e,style:t}){let r=ue();return e.trim().length===0?null:jsxs(View,{style:[r.band,t],accessible:true,accessibilityRole:"text",accessibilityLabel:mt.important(e),testID:"records-disclaimer-band",children:[jsx(View,{style:r.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{style:r.infoGlyphText,children:"i"})}),jsx(m,{style:r.bandText,children:e})]})}i(kr,"DisclaimerBand");function J({label:e,onPress:t,kind:r="primary",disabled:o=false,busy:n=false,accessibilityLabel:l,testID:a,style:c}){let s=ue(),d=V(),u=r==="primary"?s.pillPrimary:r==="outline"?s.pillOutline:r==="danger"?s.pillDanger:r==="ask"?s.pillAsk:s.pillLink,p=r==="primary"?s.pillPrimaryLabel:r==="danger"?s.pillDangerLabel:r==="ask"?s.pillAskLabel:r==="link"?s.pillLinkLabel:s.pillOutlineLabel;return jsxs(Pressable,{onPress:t,disabled:o||n,accessibilityRole:"button",accessibilityLabel:l??e,accessibilityState:{disabled:o||n,busy:n},style:[s.pill,u,o?s.pillDisabled:null,c],testID:a,children:[n?jsx(ActivityIndicator,{size:"small",color:r==="primary"?d.color.onPrimary:d.color.brandInk}):null,jsx(m,{style:p,children:e})]})}i(J,"Pill");function St({label:e,tone:t="neutral",testID:r}){let o=ue(),{bg:n,fg:l}=o.chipTones[t];return jsx(View,{style:[o.chip,n],testID:r,children:jsx(m,{style:[o.chipText,l],children:e})})}i(St,"Chip");function Dt({title:e,count:t}){let r=ue();return jsxs(View,{style:r.sectionHeader,children:[jsx(m,{style:r.sectionTitle,accessibilityRole:"header",children:e}),t!==void 0?jsx(m,{style:r.sectionCount,children:t}):null]})}i(Dt,"SectionHeader");function er({direction:e="right"}){let t=ue(),r=e==="right"?"45deg":e==="down"?"135deg":"-45deg";return jsx(View,{style:[t.chevron,{transform:[{rotate:r}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(er,"Chevron");function Fm(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:a,lineHeight:c}=n,s=i((v,w)=>Math.round(v*w),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl+r.md,p=i((v,w,y,f="regular")=>({...T(e,f),fontSize:v,lineHeight:s(v,w),color:y}),"text"),g=at(l.recordCard),b=e.brightness==="dark"?t.errorRed:t.danger,R=i((v,w)=>({bg:{backgroundColor:v},fg:{color:w}}),"tone");return {chipTones:{neutral:R(t.badgeBgNeutral,t.text.secondary),info:R(t.brandSoft,t.brandInk),warning:R(t.badgeBgCaution,t.warningStrong),critical:R(t.badgeBgCritical,t.danger),positive:R(t.badgeBgPositive,t.success)},...StyleSheet.create({root:{flex:1,backgroundColor:t.background},body:{flex:1},content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg},contentTight:{paddingHorizontal:r.sm,paddingBottom:r.xxl,gap:r.lg},inset:{paddingHorizontal:r.sm},section:{gap:r.sm+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.xs},sectionTitle:{...p(a.body+1,c.snug,t.text.primary,"bold")},sectionCount:{...p(a.bodyTight,c.snug,t.text.muted,"medium")},card:{borderRadius:o.lg-r.xs,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.xs,...rt(l.recordCard,d)},creamCard:{borderRadius:o.lg-r.xs/2,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md,...rt(l.recordCard,d)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,paddingVertical:r.md},rowDivider:{borderTopWidth:d,borderTopColor:t.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:r.xs+r.xs/2},rowTitle:{...p(a.body,c.snug,t.text.primary,"medium"),...g},rowDetail:{...p(a.caption,c.normal,t.text.secondary),marginTop:r.xs/2,...g},rowValue:{...p(a.body+1,c.snug,t.text.primary,"bold"),marginTop:r.xs/2,...g},rowMuted:{...p(a.caption,c.normal,t.text.muted),...g},chip:{borderRadius:o.pill,paddingHorizontal:r.sm,paddingVertical:r.xs-1,alignSelf:"flex-start"},chipText:{...p(a.tiny,c.snug,t.text.primary,"medium")},pill:{minHeight:u,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm},pillPrimary:{backgroundColor:t.brand,...rt(l.primaryButton)},pillPrimaryLabel:{...p(a.body,c.snug,t.onPrimary,"bold"),...at(l.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:t.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...p(a.body,c.snug,t.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:t.danger,backgroundColor:t.surface},pillDangerLabel:{...p(a.bodyTight,c.snug,t.danger,"bold")},pillAsk:{borderWidth:d,borderColor:t.borderRingCream,backgroundColor:t.surface},pillAskLabel:{...p(a.body,c.snug,t.text.primary,"bold")},pillLink:{backgroundColor:"transparent",paddingHorizontal:r.sm},pillLinkLabel:{...p(a.body,c.snug,t.linkInk,"bold")},pillDisabled:{opacity:.5},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},infoNoteText:{flex:1,...p(a.bodyTight,c.normal,t.text.primary)},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCaution,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},cautionNoteText:{flex:1,...p(a.bodyTight,c.normal,t.warningStrong)},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2},statusText:p(a.bodyTight,c.relaxed,t.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCritical,padding:r.md},errorText:{flex:1,...p(a.bodyTight,c.normal,b)},band:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft},bandText:{flex:1,...p(a.caption,c.normal,t.text.secondary)},infoGlyph:{width:r.md+r.xs/2,height:r.md+r.xs/2,borderRadius:o.pill,borderWidth:1,borderColor:t.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...p(a.small,c.tight,t.text.secondary,"bold")},chevron:{width:r.sm,height:r.sm,borderTopWidth:r.xs/2,borderRightWidth:r.xs/2,borderColor:t.text.muted},lead:{paddingHorizontal:r.sm,...p(a.body+1,c.snug,t.text.primary,"bold")},field:{minHeight:u,paddingHorizontal:r.md,paddingVertical:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,...T(e,"regular"),fontSize:a.body},fieldLabel:{...p(a.bodyTight,c.normal,t.text.secondary,"medium")},muted:p(a.caption,c.normal,t.text.muted),bodyText:p(a.body,c.normal,t.text.primary)})}}i(Fm,"makeScreenStyles");function Yr(e,t){return e===null?"":t?`${e} ${t}`:e}i(Yr,"formatEntityValue");var Fl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Y(e){if(!e)return "-";let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(t!==null){let n=Fl[Number(t[2])-1];return n===void 0?"-":`${n} ${Number(t[3])}, ${t[1]}`}let r=Date.parse(e);if(Number.isNaN(r))return "-";let o=new Date(r);return `${Fl[o.getUTCMonth()]} ${o.getUTCDate()}, ${o.getUTCFullYear()}`}i(Y,"formatRecordsDate");var ge=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 tr(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(tr,"markerStatusLabel");function Kr(e,t){return t<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${t} visits`}i(Kr,"trajectoryLabel");function dr(e){let t=e.replace(/_/g," ").trim();return t.length===0?e:t.charAt(0).toUpperCase()+t.slice(1)}i(dr,"humanize");var Nl=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 qr(e){return Object.prototype.hasOwnProperty.call(Nl,e)?Nl[e]:dr(e)}i(qr,"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 Qr(e){return Object.prototype.hasOwnProperty.call(Ml,e)?Ml[e]:dr(e)}i(Qr,"soapSectionLabel");function Bl(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(Bl,"formatWeightKg");function kt(e,t,r){if((e===null||!Number.isFinite(e))&&r)return r;if(e===null||!Number.isFinite(e))return "-";let o=e.toFixed(3).replace(/\.?0+$/,"");return t?`${o} ${t}`:o}i(kt,"formatMarkerReading");function Ni(e,t,r){let o=Kr(t,r);return e?`${ge.measured(Y(e))}${o?` \xB7 ${o}`:""}`:o}i(Ni,"labDetailLine");var ie=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 Nm(e,t){if(!e)return false;let r=Date.parse(e);return Number.isNaN(r)?false:r<=t}i(Nm,"isShareExpired");function Mm(e,t){let r=Y(e);return r==="-"?t?"Expired":"No expiry date":t?`Expired ${r}`:`Expires ${r}`}i(Mm,"formatShareExpiry");function Hl(e,t,r){let o=e.map(n=>{let l=Nm(n.expiresAt,r),a=Mm(n.expiresAt,l),c=Y(n.createdAt),s=l?"Expired":"Active",d=a.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return {shareId:n.shareId,shareUrl:t[n.shareId]??null,active:!l,statusLabel:s,expiryLabel:a,createdLabel:c==="-"?null:`Created ${c}`,a11yLabel:`Share link. ${s}. ${a}.`,actionContext:d}});return Object.freeze([...o.filter(n=>n.active),...o.filter(n=>!n.active)])}i(Hl,"buildShareRows");function ao(e,t){let r=e?.httpStatus;if(sr(e)){if(t==="create")return "Records access for this pet is off, so a new link cannot be created.";if(t==="download")return "Records access for this pet is off, so the PDF cannot be downloaded."}if(r===429)return "You are creating links a little too fast. Wait a moment, then try again.";if(t==="revoke"&&(r===404||r===409||r===410))return "That link was already turned off.";if(r===401||r===403)return "You need to be signed in as this pet's owner to do that.";switch(t){case "create":return "Could not create a share link. Please try again.";case "revoke":return "Could not turn off that link. Please try again.";default:return "Could not download the record PDF. Please try again."}}i(ao,"shareErrorMessage");function ve({width:e,height:t,radius:r,style:o}){let{color:n,radius:l}=V();return jsx(View,{style:[{width:e,height:t,borderRadius:r??l.xs,backgroundColor:n.skeleton},o],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(ve,"SkeletonBlock");var Mi=180,jl=70,lo=22,Hm=300,$l=44,co=24,Bi=34,Um=6,jm=5;function uo({testID:e}){let t=vn(),r=i(o=>jsxs(View,{style:t.actionRow,children:[jsxs(View,{style:t.actionLeft,children:[jsx(ve,{width:18,height:18,radius:9}),jsx(ve,{width:"55%",height:14,radius:7})]}),jsx(ve,{width:18,height:18,radius:9})]},o),"action");return jsxs(View,{style:t.dashboard,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:mt.loading,testID:e,children:[jsx(View,{style:t.inset,children:jsxs(View,{style:t.summaryCard,children:[jsx(ve,{width:Mi,height:Mi,radius:Mi/2}),jsxs(View,{style:t.badges,children:[jsx(ve,{width:jl,height:lo,radius:lo/2}),jsx(ve,{width:jl,height:lo,radius:lo/2})]})]})}),jsx(ve,{width:150,height:16,radius:8,style:t.inset}),jsx(View,{style:t.carouselCard,children:jsx(ve,{width:"100%",height:Hm,radius:14})}),jsxs(View,{style:t.dots,children:[jsx(ve,{width:6,height:6,radius:3}),jsx(ve,{width:18,height:6,radius:3}),jsx(ve,{width:6,height:6,radius:3})]}),jsx(ve,{width:46,height:12,radius:6,style:t.centered}),jsx(View,{style:t.inset,children:jsx(ve,{width:"100%",height:$l,radius:12})}),jsxs(View,{style:[t.inset,t.actions],children:[r("a"),r("b")]})]})}i(uo,"DashboardSkeleton");function po({testID:e}){let t=vn();return jsxs(View,{style:t.request,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:be.loading,testID:e,children:[jsx(View,{children:[0,1,2,3].map(r=>jsxs(View,{style:t.railRow,children:[jsxs(View,{style:t.railColumn,children:[jsx(ve,{width:co,height:co,radius:co/2}),r<3?jsx(ve,{width:2,height:20,radius:1,style:t.connector}):null]}),jsxs(View,{style:t.railBody,children:[jsx(ve,{width:"55%",height:14,radius:7}),jsx(ve,{width:"75%",height:11,radius:6})]})]},r))}),jsxs(View,{style:t.statusCard,children:[jsx(ve,{width:"90%",height:13,radius:6}),jsx(ve,{width:"60%",height:13,radius:6})]}),jsx(ve,{width:"100%",height:50,radius:25})]})}i(po,"RequestSkeleton");function Wl({testID:e}){let t=vn();return jsxs(View,{style:t.timeline,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:ge.loadingTimeline,testID:e,children:[jsx(View,{style:t.timelineDisclaimer,children:jsx(ve,{width:"100%",height:$l,radius:12})}),Array.from({length:Um},(r,o)=>jsxs(View,{children:[o>0?jsx(View,{style:t.timelineSeparator}):null,jsxs(View,{style:t.timelineRow,children:[jsx(ve,{width:Bi,height:Bi,radius:Bi/2}),jsxs(View,{style:t.timelineBody,children:[jsxs(View,{style:t.timelineTop,children:[jsx(ve,{width:44,height:10,radius:5}),jsx(ve,{width:56,height:12,radius:6})]}),jsx(ve,{width:"70%",height:14,radius:7}),o%2===0?jsx(ve,{width:"45%",height:12,radius:6}):null]})]})]},o))]})}i(Wl,"TimelineSkeleton");function Gl({testID:e}){let t=vn();return jsx(View,{style:t.clinics,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:we.loading,testID:e,children:Array.from({length:jm},(r,o)=>jsxs(View,{style:t.clinicRow,children:[jsx(ve,{width:"65%",height:14,radius:7}),jsx(ve,{width:"40%",height:11,radius:6})]},o))})}i(Gl,"ClinicsSkeleton");function Yl({testID:e}){let t=vn();return jsx(View,{style:t.shares,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:ie.loadingLinks,testID:e,children:[0,1].map(r=>jsxs(View,{style:t.shareRow,children:[jsx(ve,{width:"55%",height:13}),jsx(ve,{width:"40%",height:11})]},r))})}i(Yl,"SharesSkeleton");var Hi=62;function vn(){let e=V();return useMemo(()=>$m(e),[e])}i(vn,"useStyles");function $m(e){let{color:t,space:r,radius:o}=e,n=StyleSheet.hairlineWidth;return StyleSheet.create({dashboard:{flex:1,paddingHorizontal:r.sm,paddingTop:r.xs,gap:r.lg,backgroundColor:t.background},inset:{paddingHorizontal:r.sm},summaryCard:{alignItems:"center",borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg+r.xs,gap:r.md+r.xs/2},badges:{flexDirection:"row",gap:r.md},carouselCard:{borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg},dots:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.xs+r.xs/2},centered:{alignSelf:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},request:{paddingHorizontal:r.lg,paddingTop:r.xs,gap:r.lg+r.xs/2,backgroundColor:t.background},railRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md},railColumn:{alignItems:"center",width:co},connector:{marginVertical:r.xs/2},railBody:{flex:1,paddingBottom:r.lg+r.xs/2,gap:r.xs+r.xs/2},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2,gap:r.sm},timeline:{flex:1,backgroundColor:t.background},timelineDisclaimer:{paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBody:{flex:1,gap:r.xs-1},timelineTop:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},timelineSeparator:{height:n,backgroundColor:t.brandBorder,marginLeft:Hi},clinics:{gap:r.md},clinicRow:{borderRadius:o.lg-r.xs/2,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2,gap:r.sm},shares:{gap:r.md,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:n,borderColor:t.brandBorder},shareRow:{gap:r.xs+r.xs/2}})}i($m,"makeStyles");var Xm=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Ui(e){let{userRef:t,scopeEpoch:r}=Se();return jsx(Le,{capability:"recordsClinic",style:e.style,...ze(e.onBack,Ye),children:t===null?jsx(m,{accessibilityRole:"alert",children:pe.sessionRequired}):jsx(Jm,{...Oe(e,["onNavigate","onBack"])},JSON.stringify([t,r,e.petRef]))})}i(Ui,"EverfurClinicPicker");function Jm({petRef:e,controller:t,recordsController:r,location:o,onNavigate:n,onBack:l,style:a}){let c=ue(),s=ey(),d=V(),u=Ut(),p=sl(t??u,o),g=st(r?{petRef:e,controller:r}:{petRef:e}),b=useRef(ar()),[R,v]=useState(false),[w,y]=useState(null),[f,x]=useState(false),[h,_]=useState(""),[S,k]=useState(false),[E,A]=useState(""),[B,z]=useState(false),U=useCallback(C=>{n?.({name:"consent",clinic:Ti(C,null,"",b.current())});},[n]),j=i(()=>{R||(v(true),y(null),g.createRequest(`records-upload-${Date.now().toString(36)}`).then(C=>{if(v(false),!C.ok){y(be.errors.start);return}n?.({name:"request",requestId:C.value.id});}));},"startUpload"),re=S?h:p.query,se=Xm.test(E.trim()),Te=re.trim().length>0&&se,ee=i(C=>{let{layoutMeasurement:L,contentOffset:X,contentSize:fe}=C.nativeEvent;L.height+X.y>=fe.height-L.height*.6&&p.loadMore();},"onEndReached"),I=p.isSearchActive?p.clinics:p.recent,D=p.isSearchActive?p.error?pt(p.error):!p.initialLoading&&p.clinics.length===0?"idle":null:p.recent.length>0||p.recentLoading?null:"idle";return jsxs(View,{style:[c.root,a],children:[jsx(Ke,{title:we.title,onBack:l,testID:"records-clinic-header"}),jsxs(View,{style:s.searchBar,children:[jsx(View,{style:s.searchGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(He,{value:p.query,onChangeText:p.setQuery,placeholder:we.placeholder,placeholderTextColor:d.color.text.muted,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",maxLength:200,accessibilityLabel:we.searchA11y,style:s.searchInput,testID:"records-clinic-search-input"}),p.query.length>0?jsx(Pressable,{onPress:()=>p.setQuery(""),accessibilityRole:"button",accessibilityLabel:we.clearSearch,hitSlop:8,testID:"records-clinic-search-clear",children:jsx(m,{style:s.clearGlyph,children:"\xD7"})}):null]}),n?jsxs(View,{style:s.uploadWrap,children:[w?jsx(View,{style:c.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:c.errorText,children:w})}):null,jsx(J,{label:R?we.uploadOwnStarting:we.uploadOwn,kind:"outline",accessibilityLabel:we.uploadOwnA11y,busy:R,onPress:j,testID:"records-clinic-upload-own"})]}):null,jsxs(ScrollView,{contentContainerStyle:s.list,keyboardShouldPersistTaps:"handled",onScroll:p.isSearchActive?ee:void 0,scrollEventThrottle:200,testID:"records-clinic-results",children:[p.isSearchActive?jsxs(View,{style:s.fallbackCard,testID:"records-clinic-fallback-card",children:[jsxs(Pressable,{onPress:()=>x(C=>!C),accessibilityRole:"button",accessibilityLabel:f?we.fallback.collapseA11y:we.fallback.expandA11y,style:s.fallbackHeader,testID:"records-clinic-fallback",children:[jsxs(View,{style:s.fallbackCopy,children:[jsx(m,{style:s.fallbackTitle,numberOfLines:1,children:we.fallback.title}),jsx(m,{style:s.fallbackSubtitle,numberOfLines:2,children:we.fallback.subtitle})]}),jsx(er,{direction:f?"up":"down"})]}),f?jsxs(View,{style:s.fallbackForm,children:[jsx(m,{style:c.fieldLabel,children:we.fallback.nameLabel}),jsx(He,{accessibilityLabel:we.fallback.nameLabel,style:c.field,value:re,onChangeText:C=>{_(C),k(true);},placeholder:we.fallback.namePlaceholder,placeholderTextColor:d.color.text.placeholder,autoCapitalize:"words",autoCorrect:false,maxLength:200,testID:"records-clinic-fallback-name"}),jsx(m,{style:c.fieldLabel,children:we.fallback.emailLabel}),jsx(He,{accessibilityLabel:we.fallback.emailLabel,style:c.field,value:E,onChangeText:C=>{A(C),z(false);},onBlur:()=>z(true),placeholder:we.fallback.emailPlaceholder,placeholderTextColor:d.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,testID:"records-clinic-fallback-email"}),B&&E.trim().length>0&&!se?jsx(m,{style:c.errorText,accessibilityRole:"alert",children:be.errors.invalidEmail}):null,jsx(m,{style:c.muted,children:we.fallback.reviewNote}),jsx(J,{label:we.fallback.submit,accessibilityLabel:we.fallback.submitA11y,disabled:!Te||!n,onPress:()=>n?.({name:"consent",clinic:Ti(null,re.trim(),E.trim().toLowerCase(),b.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):p.recent.length>0?jsx(m,{style:s.sectionLabel,accessibilityRole:"header",testID:"records-clinic-recent-label",children:we.recentlyUsed}):null,p.isSearchActive&&p.initialLoading?jsx(Gl,{testID:"records-clinic-page-loading"}):null,I.map(C=>jsx(Zm,{clinic:C,onSelect:U,styles:s},C.id)),D&&!p.initialLoading?jsx(Ue,{variant:D,message:p.isSearchActive&&D==="idle"?we.noMatch(p.debouncedQuery):p.error?.displayMessage,onAction:p.error?.retryable===true?p.retry:void 0,testID:"records-clinic-empty"}):null,jsxs(View,{style:s.footer,children:[p.loadingMore?jsxs(View,{style:s.footerLoading,testID:"records-clinic-loading-more",children:[jsx(ActivityIndicator,{color:d.color.brandInk,size:"small"}),jsx(m,{style:c.muted,children:we.loadingMore})]}):null,p.pageError?jsx(Pressable,{onPress:p.loadMore,accessibilityRole:"button",accessibilityLabel:we.loadMoreRetryA11y,style:s.footerRetry,testID:"records-clinic-page-error-retry",children:jsx(m,{style:s.footerRetryLabel,children:we.loadMoreFailed})}):null]})]}),jsx(Ve,{})]})}i(Jm,"PickerBody");function Zm({clinic:e,onSelect:t,styles:r}){let o=Qa(e.emailStatus),n=Xa(e.distanceKm),l=[e.name,e.address,e.phone?`phone ${e.phone}`:null,n?Ja(e.distanceKm):null,o.a11y].filter(Boolean).join(", ");return jsxs(Pressable,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:we.selectA11y(l),hitSlop:8,style:r.item,testID:`records-clinic-${e.id}`,children:[jsxs(View,{style:r.itemHeader,children:[jsx(m,{style:r.itemName,numberOfLines:1,children:e.name}),n?jsx(m,{style:r.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:n}):null]}),e.address?jsx(m,{style:r.itemAddress,numberOfLines:2,children:e.address}):null,e.phone?jsx(m,{style:r.itemPhone,numberOfLines:1,accessibilityElementsHidden:true,importantForAccessibility:"no",children:e.phone}):null,jsx(View,{style:[r.badge,o.tone==="positive"?r.badgePositive:o.tone==="caution"?r.badgeCaution:r.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{style:[r.badgeLabel,o.tone==="positive"?r.badgePositiveText:o.tone==="caution"?r.badgeCautionText:r.badgeNeutralText],children:o.label})})]})}i(Zm,"ClinicRow");function ey(){let e=V();return useMemo(()=>ty(e),[e])}i(ey,"useLocalStyles");function ty(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,a=i((c,s,d,u="regular")=>({...T(e,u),fontSize:c,lineHeight:Math.round(c*s),color:d}),"text");return StyleSheet.create({searchBar:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.md+r.xs/2,height:r.xxl+r.md,marginHorizontal:r.lg,marginBottom:r.sm,borderRadius:o.lg+r.xs/2,backgroundColor:t.surfaceSubtle,borderWidth:l,borderColor:t.borderHairlineGreen},searchGlyph:{width:r.md,height:r.md,borderRadius:o.pill,borderWidth:2,borderColor:t.text.muted},searchInput:{flex:1,...a(n.size.body,n.lineHeight.snug,t.text.primary),paddingVertical:0},clearGlyph:a(n.size.heading,n.lineHeight.tight,t.text.muted),uploadWrap:{paddingHorizontal:r.lg,paddingBottom:r.md,gap:r.sm},list:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.md},sectionLabel:{...a(n.size.caption,n.lineHeight.normal,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:o.lg-r.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.md},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:r.md,minHeight:r.xxl+r.md},fallbackCopy:{flex:1,gap:r.xs/2},fallbackTitle:{...a(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},fallbackSubtitle:a(n.size.caption,n.lineHeight.normal,t.text.muted),fallbackForm:{gap:r.sm},item:{borderRadius:o.lg-r.xs/2,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},itemName:{flex:1,...a(n.size.body,n.lineHeight.snug,t.brandInk,"bold")},itemDistance:{...T(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},itemAddress:a(n.size.caption,n.lineHeight.normal,t.text.primary),itemPhone:a(n.size.caption,n.lineHeight.normal,t.text.muted),badge:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+1,paddingVertical:r.xs},badgePositive:{backgroundColor:t.badgeBgPositive},badgeCaution:{backgroundColor:t.badgeBgCaution},badgeNeutral:{backgroundColor:t.badgeBgNeutral},badgeLabel:{...a(n.size.micro,n.lineHeight.snug,t.text.muted,"bold")},badgePositiveText:{color:t.success},badgeCautionText:{color:t.cautionAccent},badgeNeutralText:{color:t.text.muted},footer:{gap:r.sm,paddingTop:r.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.md},footerRetry:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...a(n.size.bodyTight,n.lineHeight.snug,t.brandInk,"bold")}})}i(ty,"makeLocalStyles");var Ne=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${Gr} clinics`,sendA11y:i(e=>e===1?"Send 1 records request":`Send ${e} records requests`,"sendA11y"),send:i(e=>`Send ${e} ${e===1?"request":"requests"}`,"send"),sending:"Sending\u2026",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:i(e=>`Remove ${e}`,"remove"),emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn\u2019t send any of these requests. See the details below and try again.",partial:i((e,t,r)=>`${e} of ${t} requests sent. ${r} couldn\u2019t be sent.`,"partial"),allSent:i(e=>`${e} ${e===1?"request":"requests"} sent.`,"allSent"),responded:i((e,t)=>`${e} of ${t} ${t===1?"clinic":"clinics"} responded`,"responded")});function wn(e,t,r,o){let n={owner_name:t,pet_name:r,clinic_name:o},l=false,a=e.scopeTemplate.replace(/\{([^{}]+)\}/g,(c,s)=>Object.prototype.hasOwnProperty.call(n,s)?n[s]??"":(l=true,""));return l||/[{}]/.test(a)?null:a}i(wn,"renderClinicScope");function xn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(xn,"clinicNeedsEmail");function Ql(e,t,r){let[o,n]=useState(e.ownerName),[l,a]=useState(""),[c,s]=useState(null),[d,u]=useState(""),[p,g]=useState([]),[b,R]=useState([]),[v,w]=useState(null),[y,f]=useState(null),[x,h]=useState(false),[_,S]=useState(false),[k,E]=useState(null),[A,B]=useState(0),z=useRef(false),U=useRef(false),j=useRef(0),re=useRef(ar()),se=useRef(null),Te=useRef(null),ee=useRef(0);useEffect(()=>(z.current=true,U.current=false,h(false),()=>{z.current=false,ee.current+=1,j.current+=1,se.current=null,Te.current?.abort();}),[t]),useEffect(()=>{let oe=true;return w(null),se.current=null,t.getAuthorizationCopy().then(xe=>{oe&&(xe.ok?(w(xe.value),f(null)):f(xe.error));}).catch(()=>{oe&&f(F("internalError"));}),()=>{oe=false;}},[t,A]),useEffect(()=>{let oe=true;return R([]),t.recentClinics({limit:5}).then(xe=>{oe&&xe.ok&&R(xe.value.clinics);}).catch(()=>{}),()=>{oe=false;}},[t]);let I=i(()=>{se.current=null,f(null);},"invalidate"),D=c?.name??l.trim(),C=v?wn(v,o.trim(),e.petName,D):null,L=xn(c),X=!!(v&&C&&o.trim()&&e.petName.trim()&&D&&(!L||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.trim()))&&r),fe=i(async()=>{if(U.current)return;let oe=++j.current;S(true);try{let xe=await t.searchClinics({query:l.trim(),limit:100});if(!z.current||oe!==j.current)return;xe.ok?(g(xe.value.clinics),f(null)):f(xe.error);}catch{z.current&&oe===j.current&&f(F("internalError"));}finally{z.current&&oe===j.current&&S(false);}},"search"),Be=i(async()=>{if(U.current||k||!X||!v||!C||!r)return;U.current=true;let oe=ee.current,xe=i(()=>z.current&&ee.current===oe,"current");h(true),f(null);try{if(!se.current){Te.current=new AbortController;let tt=await r({petRef:e.petRef,petName:e.petName,ownerName:o.trim(),clinicName:D,authorizationVersion:v.authorizationVersion,scopeText:C,signal:Te.current.signal});if(!xe()||tt===null)return;let Nt=c&&(!L||c.emailStatus==="none")?{clinicId:c.id}:{clinicFreeText:D};se.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:v.authorizationVersion,...Nt,...L?{clinicEmail:d.trim().toLowerCase()}:{},...tt.signatureId!==void 0?{signatureId:tt.signatureId}:{signaturePngBase64:tt.signaturePngBase64},idempotencyKey:re.current()};}if(!xe())return;let xt=await t.createClinicRequest(se.current);if(!xe())return;if(!xt.ok){f(xt.error);return}if(xt.value.petRef!==e.petRef){f(F("internalError"));return}E(xt.value),se.current=null,e.onCreated?.(xt.value);}catch{xe()&&f(F("internalError"));}finally{U.current=false,xe()&&h(false);}},"submit");return {ownerName:o,query:l,clinic:c,email:d,clinics:p,copy:v,scope:C,error:y,busy:x,searching:_,created:k,ready:X,needsEmail:L,recent:p.length===0&&c===null?b:[],setOwnerName(oe){U.current||(I(),n(oe));},setQuery(oe){U.current||(I(),j.current+=1,S(false),g([]),s(null),u(""),a(oe));},setEmail(oe){U.current||(I(),u(oe));},selectClinic(oe){U.current||(I(),j.current+=1,S(false),g([]),s(oe),a(oe.name),u(""));},invalidate:I,search:fe,submit:Be,retryCopy(){f(null),B(oe=>oe+1);}}}i(Ql,"useClinicRequestForm");var ry=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function En(e){return e.clinic?.name??e.freeText??""}i(En,"draftName");function Cn(e){return xn(e.clinic)}i(Cn,"draftNeedsEmail");function Xl(e,t,r,o,n){let[l,a]=useState(e.ownerName),[c,s]=useState(""),[d,u]=useState([]),[p,g]=useState([]),[b,R]=useState([]),[v,w]=useState(null),[y,f]=useState(null),[x,h]=useState(false),[_,S]=useState(false),[k,E]=useState(null),[A,B]=useState(null),[z,U]=useState(0),j=useRef(false),re=useRef(false),se=useRef(0),Te=useRef(0),ee=useRef(ar()),I=useRef(null),D=useRef(null);useEffect(()=>(j.current=true,re.current=false,h(false),()=>{j.current=false,Te.current+=1,se.current+=1,I.current=null,D.current?.abort();}),[t,r]),useEffect(()=>{let N=true;return w(null),I.current=null,t.getAuthorizationCopy().then(Re=>{N&&(Re.ok?(w(Re.value),f(null)):f(Re.error));}).catch(()=>{N&&f(F("internalError"));}),()=>{N=false;}},[t,z]),useEffect(()=>{let N=true;return g([]),t.recentClinics({limit:5}).then(Re=>{N&&Re.ok&&g(Re.value.clinics);}).catch(()=>{}),()=>{N=false;}},[t]);let C=i(()=>{I.current=null,f(null);},"invalidate"),L=b.map(En),X=v?L.map(N=>wn(v,l.trim(),e.petName,N)):[],fe=X.every(N=>N!==null)?X.join(`
|
|
1
|
+
import {createContext,forwardRef,useRef,useMemo,useState,useCallback,useEffect,useReducer,createElement,useContext,useSyncExternalStore,Component}from'react';import {z}from'zod';import {TextInput,View,Pressable,ScrollView,ActivityIndicator,StyleSheet,PanResponder,KeyboardAvoidingView,Image,BackHandler,Text,Modal,AccessibilityInfo,Linking,Share,Platform,RefreshControl}from'react-native';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var du=Object.defineProperty;var i=(e,t)=>du(e,"name",{value:t,configurable:true});var Qo=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(Qo.map(e=>e.wireCode));var uu=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"}),na=Object.freeze(Qo.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:uu[e.wireCode]}))),pu=new Map(na.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),mu=Object.freeze(["http_envelope",...[...new Set(na.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Nn(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let o of [t??"http_envelope",...mu]){let n=pu.get(o+r);if(n)return n}}i(Nn,"contractErrorFor");function yu(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(yu,"contractDocUrl");function oa(e){return null}i(oa,"publishedDocUrl");var fu=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 ia(e){return fu[e]}i(ia,"categoryFor");function sa(e){let t=Nn(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),o=r.replace(/[^A-Z0-9]/g,"");if(o==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(o){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":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(sa,"fromWire");var gu=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function Xo(e){return gu.has(e)}i(Xo,"isAutoRetryable");var bu=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function aa(e){return Xo(e)||bu.has(e)}i(aa,"isRetryableCode");var hu=500,Jo=8e3,la=4;function ca(e,t=Math.random){let r=Math.max(0,e),o=Math.min(hu*2**r,Jo);return Math.floor(t()*o)}i(ca,"backoffDelayMs");var Ru=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 Zo(e){return Ru[e]}i(Zo,"userFacingError");function da(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(da,"defineHidden");var vu=/^[a-z][a-z0-9_]{0,63}$/;function N(e,t){let r=Nn(t?.wireCode,t?.wireEnvelope),o={code:e,category:ia(e),retryable:t?.retryable??aa(e),displayMessage:Zo(e)};if(t?.httpStatus!==void 0&&(o.httpStatus=t.httpStatus),t?.requestId&&(o.requestId=t.requestId),typeof t?.reasonCode=="string"&&vu.test(t.reasonCode)&&(o.reasonCode=t.reasonCode),r);return t?.wireMessage&&da(o,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&da(o,"raw",t.raw),Object.freeze(o)}i(N,"makeEverfurError");function Pe(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(Pe,"ok");function H(e){return Object.freeze({ok:false,error:e})}i(H,"err");var Mn=class Mn extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Mn.prototype);}};i(Mn,"EverfurConfigError");var cn=Mn;var fa=new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),ua=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 wu(e){let t=Object.prototype.hasOwnProperty.call(ua,e)?ua[e]:void 0;if(t!==void 0)return t;let r=e;return fa.has(r)?r:"parsing"}i(wu,"normalizeStatus");function ga(e){return e==="owner_reported"||e==="clinic_document"?e:null}i(ga,"normalizeOrigin");var xu=z.object({request_id:z.string().min(1),pet_ref:z.string().min(1),status:z.string(),simple_status:z.string().nullish(),simple_status_detail:z.string().nullish(),status_label:z.string().optional(),dispatch_status:z.string().nullish(),can_retry_send:z.boolean().optional(),can_revoke:z.boolean().optional(),can_convert_to_upload:z.boolean().optional(),can_update_clinic_email:z.boolean().optional(),reminder_count:z.number().int().nonnegative().optional(),last_reminder_at:z.string().nullish(),waiting_expectation:z.string().nullish(),document_count:z.number().optional(),held_item_count:z.number().optional(),received_at:z.string().nullish(),parsing_started_at:z.string().nullish(),review_started_at:z.string().nullish(),created_at:z.string().optional(),updated_at:z.string().optional(),source:z.string().nullish().catch(null),action_needed_label:z.string().nullish().catch(null),failure_reason:z.string().nullish().catch(null),failure_code:z.string().nullish().catch(null),recovery_stage:z.string().nullish().catch(null),show_clinic_phone:z.boolean().optional().catch(void 0),clinic_name:z.string().nullish().catch(null),clinic_email:z.string().nullish().catch(null),clinic_phone:z.string().nullish().catch(null),converted_to_upload_at:z.string().nullish().catch(null),request_group_id:z.string().nullish().catch(null)}).passthrough();function fr(e){let t=xu.safeParse(e);if(!t.success)return null;let r=t.data,o=Eu(r.simple_status),n=o==="requested"&&(r.status==="awaiting_upload"||r.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":o==="parsing"&&(r.simple_status_detail==="in_review"||r.simple_status_detail==="review_email_failed")?"in_review":o??wu(r.status);return Object.freeze({id:r.request_id,petRef:r.pet_ref,status:n,simpleStatus:o,simpleStatusDetail:r.simple_status_detail??null,statusLabel:r.status_label??"",dispatchStatus:r.dispatch_status??null,canRetrySend:r.can_retry_send===true,canRevoke:r.can_revoke===true,canConvertToUpload:r.can_convert_to_upload===true,canUpdateClinicEmail:r.can_update_clinic_email===true,reminderCount:r.reminder_count??0,lastReminderAt:r.last_reminder_at??null,waitingExpectation:r.waiting_expectation??null,documentCount:ma(r.document_count,0),heldItemCount:ma(r.held_item_count,0),receivedAt:r.received_at??null,parsingStartedAt:r.parsing_started_at??null,reviewStartedAt:r.review_started_at??null,createdAt:r.created_at??"",updatedAt:r.updated_at??"",wireStatus:r.status,source:r.source??null,actionNeededLabel:r.action_needed_label??null,failureReason:r.failure_reason??null,failureCode:r.failure_code??null,recoveryStage:r.recovery_stage??null,showClinicPhone:r.show_clinic_phone===true,clinicName:r.clinic_name??null,clinicEmail:r.clinic_email??null,clinicPhone:r.clinic_phone??null,convertedToUploadAt:r.converted_to_upload_at??null,requestGroupId:r.request_group_id??null})}i(fr,"mapRequestView");var Cu=z.object({request_group_id:z.string().min(1),pet_ref:z.string().min(1),total:z.number().int().nonnegative(),responded:z.number().int().nonnegative(),pending:z.number().int().nonnegative(),members:z.array(z.unknown())});function ba(e){let t=Cu.safeParse(e);if(!t.success)return null;let r=t.data,o=ei(r.members);return o.some(n=>n.petRef!==r.pet_ref)?null:Object.freeze({requestGroupId:r.request_group_id,petRef:r.pet_ref,total:r.total,responded:r.responded,pending:r.pending,members:o})}i(ba,"mapRequestGroup");function Eu(e){return !e||e==="awaiting_upload"||e==="in_review"?null:fa.has(e)?e:null}i(Eu,"normalizeSimpleStatus");function ei(e){let t=Array.isArray(e)?e:[],r=[];for(let o of t){let n=fr(o);n!==null&&r.push(n);}return Object.freeze(r)}i(ei,"mapRequestList");var Su=z.object({source_doc_id:z.string().min(1),request_id:z.string().min(1)});function ha(e){let t=Su.safeParse(e);return t.success?Object.freeze({documentId:t.data.source_doc_id,requestId:t.data.request_id,status:"received"}):null}i(ha,"mapUploadedDocument");var ku=z.object({label:z.string(),value:z.string()}),ti=z.object({key:z.string(),category:z.string().optional(),label:z.string().optional(),value:z.string().nullish(),unit:z.string().nullish(),observed_at:z.string().nullish(),status:z.string().nullish(),origin:z.string().nullish(),canonical_key:z.string().nullish()}),Tu=z.object({at:z.string(),value:z.number().nullish(),display:z.string().nullish(),origin:z.string().nullish()}),_u=z.object({key:z.string(),label:z.string().optional(),points:z.array(Tu).optional()}),Pu=z.object({title:z.string(),detail:z.string().nullish(),due_at:z.string().nullish()}),ri=z.object({doc_id:z.string(),title:z.string().nullish(),page_count:z.number().nullish(),received_at:z.string().nullish()});function ni(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:ga(e.origin),canonicalKey:e.canonical_key??null})}i(ni,"mapEntityRow");function oi(e){return Object.freeze({docId:e.doc_id,title:e.title??null,pageCount:e.page_count??null,receivedAt:e.received_at??null})}i(oi,"mapDocumentRow");var Iu=z.object({identity:z.array(ku).optional(),entities:z.array(ti).optional(),entity_series:z.array(_u).optional(),forward_looking:z.array(Pu).optional(),documents:z.array(ri).optional()});function Ra(e,t){let r=Au(t)?t:{},o=ya(r.schema_version,"epdf/1.0"),n=ya(r.disclaimer,""),a=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return pa(a,o,n);let l=Iu.safeParse(r);if(!l.success)return pa(a,o,n);let c=l.data,s=(c.identity??[]).map(R=>Object.freeze({label:R.label,value:R.value})),d=(c.entities??[]).map(ni),u=(c.entity_series??[]).map(R=>Object.freeze({key:R.key,label:R.label??R.key,points:Object.freeze((R.points??[]).map(v=>Object.freeze({at:v.at,value:v.value??null,display:v.display??null,origin:ga(v.origin)})))})),p=(c.forward_looking??[]).map(R=>Object.freeze({title:R.title,detail:R.detail??null,dueAt:R.due_at??null})),f={};for(let R of c.documents??[])f[R.doc_id]=oi(R);let b=r.is_empty===true||s.length===0&&d.length===0&&u.length===0&&p.length===0&&Object.keys(f).length===0;return Object.freeze({petRef:a,schemaVersion:o,isEmpty:b,withheld:false,generatedAt:Ou(r.generated_at),identity:Object.freeze(s),entities:Object.freeze(d),entitySeries:Object.freeze(u),forwardLooking:Object.freeze(p),documents:Object.freeze(f),disclaimer:n})}i(Ra,"mapRecordView");function pa(e,t,r){return Object.freeze({petRef:e,schemaVersion:t,isEmpty:false,withheld:true,generatedAt:null,identity:Object.freeze([]),entities:Object.freeze([]),entitySeries:Object.freeze([]),forwardLooking:Object.freeze([]),documents:Object.freeze({}),disclaimer:r})}i(pa,"withheldView");var Du=z.object({pet_ref:z.string().optional(),granted:z.boolean().optional(),version:z.string().nullish(),granted_at:z.string().nullish()});function Bn(e,t){let r=Du.safeParse(t),o=r.success?r.data:{};return Object.freeze({petRef:typeof o.pet_ref=="string"&&o.pet_ref.length>0?o.pet_ref:e,granted:o.granted===true,version:o.version??null,grantedAt:o.granted_at??null})}i(Bn,"mapConsent");function Au(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Au,"isObject");function ma(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}i(ma,"numberOr");function ya(e,t){return typeof e=="string"&&e.length>0?e:t}i(ya,"strOr");function Ou(e){return typeof e=="string"&&e.length>0?e:null}i(Ou,"strOrNull");var va=Object.freeze(["published","failed","revoked"]);function gr(e){return va.includes(e)}i(gr,"isTerminalStatus");function br(e){if(e===null)return null;let t=e.recordsReason;return t==="consent_required"||t==="session_required"||t==="entitlement"||t==="pet_not_found"?t:null}i(br,"recordsDenialReasonOf");var Lu="records_consent_required";function Vu(e){let t=e.raw;if(t===null||typeof t!="object")return null;let r=t,o=typeof r.error=="object"&&r.error!==null?r.error.code:r.code;return typeof o=="string"&&o.length>0?o:null}i(Vu,"recordsWireCodeOf");function sr(e){return e===null||e.httpStatus!==409?false:Vu(e)===Lu}i(sr,"isRecordsConsentRequired");var qu=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function Hn(e){return e!==qu}i(Hn,"isUploadTransportAvailable");var wa=Object.freeze({record(){}}),hr=25*1024*1024,xa=64,dn=128,gt=128,un="application/pdf",Ca=9e4;function Sa(e){return new ii(e)}i(Sa,"createRecordsController");var si=class si{constructor(t){this.recordCache=new Map;this.consentEpoch=new Map;this.reportedGaps=new Set;this.repository=t.repository,this.uploads=t.uploads,this.telemetry=t.telemetry??wa,this.newIdempotencyKey=t.newIdempotencyKey??Bu(),this.timers=t.timers??Nu,this.uploadDeadlineMs=t.uploadDeadlineMs??Ca;}async createUploadRequest(t){let r=await this.repository.createRequest({pet_ref:t.petRef,idempotency_key:t.idempotencyKey});if(!r.ok)return this.onRequestError(r.error);let o=fr(r.value);return o===null?H(Un()):(this.observeRequest(o),Pe(o))}async getRequest(t){let r=await this.repository.getRequest(t);if(!r.ok)return this.onRequestError(r.error);let o=fr(r.value);return o===null?H(Un()):(this.observeRequest(o),Pe(o))}async listRequests(){let t=await this.repository.listRequests();if(!t.ok)return this.onRequestError(t.error);let r=ei(t.value);for(let o of r)this.observeRequest(o);return Pe(r)}async uploadDocument(t){let{requestId:r,file:o}=t,n=zu(o);if(n!==null)return this.telemetry.record("records.upload.rejected",{reason:n}),H(Ea(`upload rejected: ${n}`));let a=await this.repository.initiateUpload(r,{content_type:un,file_size:o.sizeBytes});if(!a.ok)return this.onRequestError(a.error);let l=await this.postToS3(a.value,o,t);if(!l.ok)return this.telemetry.record("records.upload.failed",{reason:l.reason}),H(Ea(l.reason));let c=await this.repository.completeUpload(r,{upload_id:a.value.upload_id});if(!c.ok)return c.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:Fu(c.error)??"corrupt"}),this.onRequestError(c.error);let s=ha(c.value);return s===null?H(Un()):Pe(s)}async postToS3(t,r,o){let n=new AbortController,a=Mu(n.signal,o.signal),l=this.timers.setTimeout(()=>n.abort(),this.uploadDeadlineMs);try{let c={signal:a};return o.onProgress&&(c.onProgress=o.onProgress),await this.uploads.postMultipart(t,r,c),{ok:!0}}catch{return {ok:false,reason:n.signal.aborted&&o.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(l);}}async getRecord(t){let r=this.consentEpoch.get(t)??0,o=await this.repository.getRecord(t);if(r!==(this.consentEpoch.get(t)??0))return H(Object.freeze({...N("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!o.ok){let a=br(o.error);return a==="consent_required"?(this.recordCache.delete(t),this.telemetry.record("records.consent.denied",{pet_ref:t})):a==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t}),H(o.error)}let n=Ra(t,o.value);return n.petRef!==t?H(Un()):n.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:t}),this.recordCache.delete(t),Pe(n)):(this.recordCache.set(t,n),Pe(n))}peekCachedRecord(t){return this.recordCache.get(t)??null}async getConsent(t){let r=await this.repository.getConsent(t);return r.ok?Pe(Bn(t,r.value)):H(r.error)}async grantConsent(t){let r=await this.repository.putConsent(t.petRef,{consent_version:t.consentVersion,idempotency_key:t.idempotencyKey});return r.ok?Pe(Bn(t.petRef,r.value)):(br(r.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:t.petRef}),H(r.error))}async revokeConsent(t){let r=await this.repository.deleteConsent(t);return r.ok?(this.consentEpoch.set(t,(this.consentEpoch.get(t)??0)+1),this.recordCache.delete(t),Pe(Bn(t,r.value))):H(r.error)}reportCapabilityDenied(t){this.telemetry.record("records.capability.denied",t?{pet_ref:t}:{});}observeRequest(t){t.reviewStartedAt!==null&&!this.reportedGaps.has(t.id)&&(this.reportedGaps.add(t.id),this.telemetry.record("records.parse.gap",{request_id:t.id}));}onRequestError(t){return br(t)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),H(t)}};i(si,"RecordsControllerImpl");var ii=si;function zu(e){if(e.mimeType!==un)return "unsupported_format";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>hr?"oversize":null}i(zu,"validateFile");function Fu(e){let t=e.wireMessage;return t==="unsupported_format"||t==="oversize"||t==="corrupt"?t:null}i(Fu,"reasonFromWire");function Ea(e){return N("mediaUploadFailed",{retryable:false,wireMessage:e})}i(Ea,"uploadFailed");function Un(){return N("internalError",{retryable:true})}i(Un,"internal");var Nu={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout")};function Mu(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let o=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),r.signal}i(Mu,"mergeSignals");function Bu(){let e=0;return ()=>`records-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(Bu,"defaultIdempotencyFactory");function Rr(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Rr,"assertNever");function ka(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(ka,"errorFrame");function ju(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(ju,"authHeaders");function pn(e,t){return {...e,headers:{...$u(e.headers),...ju(t)}}}i(pn,"withAuthHeaders");function $u(e){if(!e)return {};let t={};for(let[r,o]of Object.entries(e)){let n=r.toLowerCase();n==="authorization"||n==="x-everfur-partner-key"||(t[r]=o);}return t}i($u,"stripAuthHeaders");async function Ta(e,t){if(t.mode==="anonymous")return t.transport.request(pn(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return H(ai())}let o=await t.transport.request(pn(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(o.ok||o.error.httpStatus!==401)return o;let n;try{n=await t.identity.currentToken({forceRefresh:!0});}catch{return H(ai())}let a=await t.transport.request(pn(e,{mode:"personalized",token:n,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !a.ok&&a.error.httpStatus===401?H(ai(a.error.httpStatus)):a}i(Ta,"authedSend");function ai(e){return N("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(ai,"authRejectedError");function _a(e){return N("internalError",{retryable:true,wireMessage:Wu(e)})}i(_a,"networkError");function Wu(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Wu,"describeCause");var Gu=3e4,Yu=Jo*2,Ku="idempotency-key",Qu=new Set(["POST","PUT","PATCH","DELETE"]),Xu=Object.freeze({onEvent(){}}),Ju=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Zu(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(Zu,"seededIdempotencyKey");function vr(e){let t=e.observer??Xu,r=e.timers??Ju,o=e.rng??Math.random,n=e.sleep??((f,b)=>pp(f,r,b)),a=e.maxAttempts??la,l=e.unaryTimeoutMs??Gu,c=e.newIdempotencyKey??ar(),s=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,b,R){let v=R?.maxAttempts,w=Math.max(1,v??a),g=R?.idempotent??Qu.has(b.method),y=R?.idempotencyKey===void 0?null:Zu(R.idempotencyKey),x=g?y??c():null,h=ep(b,x),I=0;for(;;){let S=i(j=>Object.freeze({call:f,method:b.method,path:b.path,attempt:I,...x?{idempotencyKey:x}:{},...j}),"stamp");s(S({phase:"attempt"}));let T=dp(l,r),C=up(T.signal,b.signal),A;try{A=await Ta({...h,signal:C.signal},e.auth);}catch(j){A=H(_a(j));}finally{C.dispose(),T.cancel();}if(A.ok)return s(S({phase:"settled",ok:true,reason:"ok"})),A;let F=A.error,q=rp(F,I,{maxAttempts:w,rng:o,now:r.now(),aborted:b.signal?.aborted===true,...v!==void 0?{perCallMaxAttempts:v}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),U={ok:false,code:F.code,reason:q.reason,...F.httpStatus!==void 0?{httpStatus:F.httpStatus}:{},...F.requestId!==void 0?{requestId:F.requestId}:{}};if(!q.retry)return s(S({phase:"settled",...U})),H(F);if(s(S({phase:"retry",...U,delayMs:q.delayMs})),await n(q.delayMs,b.signal),b.signal?.aborted===true)return s(S({phase:"settled",...U,reason:"aborted"})),H(F);I+=1;}}i(d,"send");async function u(f){return pn(f,await cp(e.auth))}i(u,"authorize");async function*p(f,b,R){s(Object.freeze({call:f,phase:"stream.open",method:b.method,path:b.path,attempt:0}));try{yield*e.auth.transport.stream(b,R);}catch{yield ka({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:u,stream:p})}i(vr,"createRequestFunnel");function ep(e,t){let r={};for(let[o,n]of Object.entries(e.headers??{}))o.toLowerCase()!==Ku&&(r[o]=n);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(ep,"assembleHeaders");function ar(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(ar,"defaultIdempotencyKeyFactory");var tp=10;function rp(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let o=np(e);if(o==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(o!=="burst"&&!Xo(e.code))return {retry:false,reason:"terminal-code"};let n=o==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let l=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(tp,Math.floor(d)))},"policyCeiling"),c=r.perCallMaxAttempts??l()??r.maxAttempts;if(t+1>=c)return {retry:false,reason:"attempts-exhausted"};let s=op(e,r.now);return s!==null?s>Yu?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:n,delayMs:s}:{retry:true,reason:n,delayMs:ca(t,r.rng)}}i(rp,"decideRetry");function np(e){let t=e.code==="unknown"?sa(lp(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(np,"throttleKind");function op(e,t){let r=sp(e.raw);if(r!==null){let n=r-t;return n>0?n:0}let o=ip(e.raw);return o===null?null:Math.round(o*1e3)}i(op,"retryOverrideMs");function ip(e){for(let t of li(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(ip,"findRetryAfterSeconds");function sp(e){for(let t of li(e)){let r=t.resets_at,o=ap(r);if(o!==null)return o}return null}i(sp,"findResetsAt");function li(e){if(!Pa(e))return [];let t=[e];for(let r of ["error","detail"]){let o=e[r];Pa(o)&&t.push(o);}return t}i(li,"candidateScopes");function ap(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(ap,"parseInstantMs");function lp(e){for(let t of li(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(lp,"rawWireCode");function Pa(e){return typeof e=="object"&&e!==null}i(Pa,"isRecord");async function cp(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(cp,"resolveDeviceAuth");function dp(e,t){let r=new AbortController,o=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(o),"cancel")}}i(dp,"boundedSignal");function up(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let o=new AbortController;if(e.aborted||t.aborted)return o.abort(),{signal:o.signal,dispose:r};let n=i(()=>o.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),{signal:o.signal,dispose:i(()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",n);},"dispose")}}i(up,"mergeSignals");function pp(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(o=>{let n=t.setTimeout(()=>{r?.removeEventListener("abort",a),o();},e),a=i(()=>{t.clearTimeout(n),o();},"onAbort");r?.addEventListener("abort",a,{once:true});})}i(pp,"delayAbortable");function wr(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let o=e.charCodeAt(t+1);if(!(o>=56320&&o<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(wr,"hasLoneSurrogate");var lr="/widget/v1/records";function Da(e){let{auth:t}=e,r=t.mode,o=e.funnel??vr({auth:t,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),n=i(async(s,d,u)=>{let p=await o.send(s,d);return p.ok?p:H(fp(p.error,r,u))},"send"),a=i((s,d)=>typeof d!="string"||d.length===0?N("validationFailed",{retryable:false,wireMessage:`${s} is required and must be a non-empty string`}):wr(d)?N("validationFailed",{retryable:false,wireMessage:`${s} contains an unpaired surrogate and cannot be encoded`}):null,"segmentError"),l=i((s,d,u)=>{let p=a(s,d);if(p!==null)return p;let b=[...d].length;return b>u?N("validationFailed",{retryable:false,wireMessage:`${s} is ${b} characters; the server accepts at most ${u}`}):null},"boundsError"),c=i((...s)=>s.find(d=>d!==null)??null,"firstError");return {createRequest:i(s=>{let d=c(l("idempotency_key",s.idempotency_key,dn),l("pet_ref",s.pet_ref,gt));return d?Promise.resolve(H(d)):n("records.createRequest",ci(`${lr}/requests`,s),"request")},"createRequest"),initiateUpload:i((s,d)=>{let u=a("request_id",s);return u?Promise.resolve(H(u)):n("records.initiateUpload",ci(`${lr}/requests/${encodeURIComponent(s)}/uploads/initiate`,d),"request")},"initiateUpload"),completeUpload:i((s,d)=>{let u=a("request_id",s);return u?Promise.resolve(H(u)):n("records.completeUpload",ci(`${lr}/requests/${encodeURIComponent(s)}/uploads/complete`,d),"request")},"completeUpload"),getRequest:i(s=>{let d=a("request_id",s);return d?Promise.resolve(H(d)):n("records.getRequest",jn(`${lr}/requests/${encodeURIComponent(s)}`),"request")},"getRequest"),listRequests:i(async()=>{let s=await n("records.listRequests",jn(`${lr}/requests`),"request");if(!s.ok)return s;let d=s.value;return {ok:true,value:Array.isArray(d)?d:d.items??[]}},"listRequests"),getRecord:i(s=>{let d=l("pet_ref",s,gt);return d?Promise.resolve(H(d)):n("records.getRecord",jn(`${lr}/pets/${encodeURIComponent(s)}/record`),"content")},"getRecord"),getConsent:i(s=>{let d=l("pet_ref",s,gt);return d?Promise.resolve(H(d)):n("records.getConsent",jn(`${lr}/pets/${encodeURIComponent(s)}/consent`),"consent")},"getConsent"),putConsent:i((s,d)=>{let u=c(l("consent_version",d.consent_version,xa),l("idempotency_key",d.idempotency_key,dn),l("pet_ref",s,gt));return u?Promise.resolve(H(u)):n("records.putConsent",gp(`${lr}/pets/${encodeURIComponent(s)}/consent`,d),"consent")},"putConsent"),deleteConsent:i(s=>{let d=l("pet_ref",s,gt);return d?Promise.resolve(H(d)):n("records.deleteConsent",bp(`${lr}/pets/${encodeURIComponent(s)}/consent`),"consent")},"deleteConsent")}}i(Da,"createHttpRecordsRepository");function Ia(e,t){let r={...e,recordsReason:t};for(let o of ["wireMessage","raw"]){let n=Object.getOwnPropertyDescriptor(e,o);n!==void 0&&Object.defineProperty(r,o,n);}return Object.freeze(r)}i(Ia,"withReason");var mp="pet_not_registered";function yp(e){return e.httpStatus!==404?null:e.reasonCode===mp?"pet_not_found":"entitlement"}i(yp,"recordsErrorReasonFor");function fp(e,t,r){let o=yp(e);return o!==null?Ia(e,o):e.code!=="accessDenied"?e:Ia(e,t==="anonymous"?"session_required":r==="content"?"consent_required":"entitlement")}i(fp,"tagReason");function jn(e){return {method:"GET",path:e}}i(jn,"get");function ci(e,t){return {method:"POST",path:e,body:t}}i(ci,"post");function gp(e,t){return {method:"PUT",path:e,body:t}}i(gp,"put");function bp(e){return {method:"DELETE",path:e}}i(bp,"del");var Aa=Symbol.for("@everfur/sdk#EverfurContext@v1"),Oa=globalThis,La=Oa[Aa]??(Oa[Aa]=createContext(null));La.displayName??="EverfurContext";function ke(){let e=useContext(La);if(e===null)throw new cn("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(ke,"useEverfurContext");var di=new Map,ui=new Set;function Va(e){di.set(e,(di.get(e)??0)+1);for(let t of [...ui])t();}i(Va,"notifyRecordsConsentWithdrawn");function xp(e){return di.get(e)??0}i(xp,"recordsConsentEpochOf");function Cp(e){return ui.add(e),()=>{ui.delete(e);}}i(Cp,"subscribe");function $n(e){let t=useCallback(()=>xp(e),[e]);return useSyncExternalStore(Cp,t,t)}i($n,"useRecordsConsentEpoch");var mi={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[]},za=4e3,Sp=30;function st(e){let{petRef:t}=e,r=useRef(e.uploadTransport);r.current=e.uploadTransport;let o=e.uploadTransport!==void 0,{runtime:n,userRef:a,scopeEpoch:l}=ke(),c=useMemo(()=>({}),[n,a,t,l,e.controller]),s=useRef(c),[d,u]=useState({scope:c,controller:e.controller??null}),p=e.controller??(d.scope===c?d.controller:null),[f,b]=useState({scope:c,value:mi}),R=f.scope===c?f.value:mi,v=useCallback(_=>{b(D=>D.scope===c?{scope:c,value:_(D.value)}:D);},[c]),w=useRef(0);useEffect(()=>(s.current=c,b({scope:c,value:mi}),()=>{s.current=null,w.current+=1;}),[c]),useEffect(()=>{if(e.controller)return;let{services:_}=n.registry,D={record:i((L,X)=>_.telemetry.track(L,X),"record")},E=n.registry.acquire("records",`${a??""}|${t}${o?"|own-upload":""}`,()=>Sa({repository:Da({auth:_.authFor(a),..._.errorPolicy?{errorPolicy:_.errorPolicy}:{}}),uploads:o?{postMultipart:i((L,X,fe)=>(r.current??_.uploadTransport).postMultipart(L,X,fe),"postMultipart")}:_.uploadTransport,telemetry:D}),()=>{});return u({scope:c,controller:E}),()=>{n.registry.release(E);}},[n,a,t,e.controller,l,c,o]);let g=useCallback(_=>{v(D=>({...D,..._}));},[v]),y=useCallback(async()=>{if(!p||s.current!==c)return;let _=w.current+=1;S.current=0,A(),g({loading:true,error:null,denialReason:null,withheld:false});let[D,E]=await Promise.all([p.getConsent(t),p.listRequests()]);if(_!==w.current)return;let L=D.ok?D.value:null,X=E.ok?E.value.filter(Be=>Be.petRef===t):[],fe=E.ok?null:E.error;if(L&&L.granted){let Be=await p.getRecord(t);if(_!==w.current)return;if(Be.ok){g({consent:L,requests:X,record:Be.value,withheld:Be.value.withheld,error:Be.value.withheld?Pp():fe,denialReason:null,loading:false});return}g({consent:L,requests:X,record:null,error:Be.error,denialReason:br(Be.error),withheld:false,loading:false});return}g({consent:L,requests:X,record:null,error:D.ok?fe:D.error,denialReason:L?"consent_required":_p(D),withheld:false,loading:false});},[p,t,g,c]);useEffect(()=>(y(),()=>{w.current+=1;}),[y]);let x=useMemo(()=>Tp(R.requests),[R.requests]),h=x?.id??null,I=x?.status??null,S=useRef(0),T=useRef(null),[C,A]=useReducer(_=>_+1,0);useEffect(()=>{if(!p||h===null||I===null||gr(I)||I==="in_review")return;T.current!==String(h)&&(T.current=String(h),S.current=0);let _=false,D=i(async()=>{if(_||S.current>=Sp)return;S.current+=1;let L=await p.getRequest(h);if(!_){if(L.ok&&L.value.petRef===t){if(v(X=>({...X,requests:Gn(X.requests,L.value)})),gr(L.value.status)){L.value.status==="published"&&y();return}if(L.value.status==="in_review")return}E=setTimeout(()=>{D();},za);}},"tick"),E=setTimeout(()=>{D();},za);return ()=>{_=true,clearTimeout(E);}},[p,h,I,y,C,t,v]);let F=useCallback(async _=>{if(!p||s.current!==c)return Yn();let D=await p.createUploadRequest({petRef:t,idempotencyKey:_});return s.current===c&&D.ok&&D.value.petRef===t&&v(E=>({...E,requests:Gn(E.requests,D.value)})),D},[p,t,c,v]),q=useCallback((_,D)=>{v(E=>({...E,uploadQueue:E.uploadQueue.map(L=>L.key===_?D(L):L)}));},[v]),U=useCallback(async(_,D)=>{let E=Date.now().toString(36),L=D.map((fe,Be)=>{let oe=Fa(fe);return {key:`${E}-${Be}`,name:fe.name??null,status:oe===null?"queued":"skipped",progress:0,skipReason:oe,error:null}}),X=[...L];if(!p||s.current!==c)return Object.freeze(X);v(fe=>({...fe,uploadQueue:L,isUploading:true,uploadProgress:0}));for(let[fe,Be]of D.entries()){let oe=L[fe];if(oe.status==="skipped")continue;if(s.current!==c)break;q(oe.key,tt=>({...tt,status:"uploading",progress:0})),g({uploadProgress:0});let Ce=await p.uploadDocument({requestId:_,file:Be,onProgress:i(tt=>{if(s.current!==c)return;let Nt=Math.min(1,Math.max(0,tt));q(oe.key,Mt=>({...Mt,progress:Math.max(Mt.progress,Nt)})),g({uploadProgress:Nt});},"onProgress")});if(s.current!==c)break;let xt=Ce.ok?{...oe,status:"done",progress:1}:{...oe,status:"failed",error:Ce.error};if(X[fe]=xt,q(oe.key,()=>xt),Ce.ok){let tt=await p.getRequest(_);s.current===c&&tt.ok&&tt.value.petRef===t&&v(Nt=>({...Nt,requests:Gn(Nt.requests,tt.value)}));}}return s.current===c&&g({isUploading:false,uploadProgress:null}),Object.freeze(X)},[p,g,q,t,c,v]),j=useCallback(async(_,D)=>{if(!p||s.current!==c)return Yn();let E=`${Date.now().toString(36)}-0`;v(X=>({...X,isUploading:true,uploadProgress:0,uploadQueue:[{key:E,name:D.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let L=await p.uploadDocument({requestId:_,file:D,onProgress:i(X=>{s.current===c&&(g({uploadProgress:X}),q(E,fe=>({...fe,progress:Math.max(fe.progress,Math.min(1,X))})));},"onProgress")});if(s.current!==c)return L;if(g({isUploading:false,uploadProgress:null}),q(E,X=>L.ok?{...X,status:"done",progress:1}:{...X,status:"failed",error:L.error}),L.ok){let X=await p.getRequest(_);s.current===c&&X.ok&&X.value.petRef===t&&v(fe=>({...fe,requests:Gn(fe.requests,X.value)}));}return L},[p,g,q,t,c,v]),ae=useCallback(async(_,D)=>{if(!p||s.current!==c)return Yn();let E=await p.grantConsent({petRef:t,consentVersion:_,idempotencyKey:D});return E.ok&&s.current===c&&y(),E},[p,t,y,c]),ne=useCallback(async()=>{if(!p||s.current!==c)return Yn();let _=await p.revokeConsent(t);return _.ok&&Va(t),_.ok&&s.current===c&&(w.current+=1,g({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:_.value})),_},[p,t,g,c]),Re=useCallback(()=>y(),[y]),te=kp(R,p!==null);return useMemo(()=>({status:te,record:R.record,requests:R.requests,activeRequest:x,consent:R.consent,error:R.error,denialReason:R.denialReason,withheld:R.withheld,isUploading:R.isUploading,uploadProgress:R.uploadProgress,uploadQueue:R.uploadQueue,createRequest:F,uploadDocument:j,uploadDocuments:U,grantConsent:ae,revokeConsent:ne,refresh:Re}),[te,R,x,F,j,U,ae,ne,Re])}i(st,"useEverfurRecords");function Fa(e){if(e.mimeType!==un)return "unsupported";let t=e.sizeBytes;return typeof t!="number"||!Number.isFinite(t)||t<=0||t>hr?"too_large":null}i(Fa,"skipReasonFor");function Na(e){let t=[],r=[];for(let o of e){let n=Fa(o);n===null?t.push(o):r.push({name:o.name??null,reason:n});}return {uploadable:t,skipped:r}}i(Na,"classifyPick");function kp(e,t){return e.loading||!t?"loading":e.withheld||e.denialReason!==null||e.error!==null?"error":e.record!==null&&!e.record.isEmpty||e.requests.length>0?"populated":"empty"}i(kp,"selectStatus");function Tp(e){if(e.length===0)return null;let t=e[0];for(let r of e)r.updatedAt>t.updatedAt&&(t=r);return t}i(Tp,"newestRequest");function Gn(e,t){let r=e.filter(o=>o.id!==t.id);return [t,...r]}i(Gn,"replaceRequest");function _p(e){return e.ok?"consent_required":br(e.error)??"consent_required"}i(_p,"consentDenial");function Pp(){return N("internalError",{retryable:false})}i(Pp,"withheldSentinel");function Yn(){return {ok:false,error:N("internalError",{retryable:true})}}i(Yn,"notReady");function yi(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(yi,"reportHostFailure");function Ip(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(Ip,"isThenable");function Kn(e,...t){if(typeof e=="function")try{let r=e(...t);return Ip(r)&&Promise.resolve(r).then(void 0,yi),r}catch(r){yi(r);return}}i(Kn,"callHost");var Ma=new WeakMap;function yn(e){if(typeof e!="function")return;let t=Ma.get(e);if(t!==void 0)return t;let r=i((...o)=>{Kn(e,...o);},"guarded");return Ma.set(e,r),r}i(yn,"guardHost");function Oe(e,t){let r=null;for(let o of t){let n=e[o];typeof n=="function"&&(r??={...e},r[o]=yn(n));}return r??e}i(Oe,"guardHostProps");function Or(e,...t){let r;try{r=e(...t);}catch(o){return yi(o),Promise.resolve({ok:false,error:o})}return Promise.resolve(r).then(o=>({ok:true,value:o}),o=>({ok:false,error:o}))}i(Or,"callHostAsync");var Ba=Object.freeze({name:"dashboard"});function Qn(e=Ba){return Object.freeze({stack:Object.freeze([e])})}i(Qn,"initialRecordsNav");function Xn(e){return e.stack[e.stack.length-1]??Ba}i(Xn,"currentRecordsScreen");function fi(e,t){return Object.freeze({stack:Object.freeze([...e.stack,t])})}i(fi,"pushRecordsNav");function gi(e,t){return Object.freeze({stack:Object.freeze([...e.stack.slice(0,-1),t])})}i(gi,"replaceRecordsNav");function bi(e){return Qn(e)}i(bi,"resetRecordsNav");function Jn(e){return e.stack.length<=1?{state:e,handled:false}:{state:Object.freeze({stack:Object.freeze(e.stack.slice(0,-1))}),handled:true}}i(Jn,"popRecordsNav");function Ha(e,t){return t.name==="dashboard"?bi(t):Xn(e).name==="upload"&&t.name==="request"?gi(e,t):fi(e,t)}i(Ha,"transitionRecordsNav");function hi(e,t){switch(t.type){case "push":return fi(e,t.screen);case "pop":return Jn(e).state;case "replace":return gi(e,t.screen);case "reset":return bi(t.screen);case "navigate":return Ha(e,t.screen);default:return e}}i(hi,"recordsNavReducer");function wi(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))wi(e[t]);}return e}i(wi,"deepFreeze");var Dp=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),ja={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},$a={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},Ua={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},Ap={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},Op={regular:"400",medium:"500",bold:"700"},Lp={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Vp=0,Zn="System",eo="monospace",qp=["content","heading","control","compact","badge"];function zp(e){let t={};for(let r of qp)t[r]=e;return t}i(zp,"authoredTierSizes");function Wa(){return {family:Zn,mono:eo,fontUrl:null,families:{regular:Zn,medium:Zn,bold:Zn,mono:eo,monoMedium:eo,monoBold:eo},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:Ua,tierSizes:zp(Ua),lineHeight:Ap,weight:Op,letterSpacing:Lp,scale:1,maxScale:Vp,scaleCaps:Dp}}i(Wa,"baseType");var Ga={},Ri=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function vi(e){return `cubic-bezier(${e.join(", ")})`}i(vi,"cssCubicBezier");var Ya={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:vi(Ri.standard),emphasized:vi(Ri.emphasized),exit:vi(Ri.exit)},reducedMotion:false},Fp={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)"},Ka=wi({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Fp,space:ja,radius:$a,type:Wa(),motion:Ya,slots:Ga}),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)"};wi({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Np,space:ja,radius:$a,type:Wa(),motion:Ya,slots:Ga});var Qa=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),Xa=globalThis,xi=Xa[Qa]??(Xa[Qa]=createContext(Ka));xi.displayName??="EverfurThemeContext";function V(){return useContext(xi)}i(V,"useEverfurTheme");function $p(e,t){let r=e.scaleCaps[t];return r>0?r:void 0}i($p,"tierMultiplier");function m({tier:e="content",...t}){let{type:r}=V(),o=$p(r,e);return createElement(Text,o===void 0?t:{maxFontSizeMultiplier:o,...t})}i(m,"Text");var He=forwardRef(i(function(t,r){return createElement(TextInput,{...t,...r===null?{}:{ref:r}})},"TextInput"));var Wp=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function k(e,t){let r=e.type,o=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:o}:{fontFamily:o,fontWeight:r.weight[Wp[t]]}}i(k,"face");var W=Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you\u2019re authorizing",send:"Send request",sending:"Sending\u2026",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can\u2019t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:i(e=>`Typed signature: ${e}`,"typedSignatureA11y"),missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used"});var xe=Object.freeze({title:W.title,placeholder:W.placeholder,searchA11y:W.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:W.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 Za(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(Za,"clinicEmailStatusBadge");function el(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} km`}i(el,"formatClinicDistanceLabel");function tl(e){return e===null||!Number.isFinite(e)?"":`${e.toFixed(1)} ${e===1?"kilometer":"kilometers"} away`}i(tl,"formatClinicDistanceForA11y");var rl=300,Ci=2;var pe=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 nl(e){return !gr(e.status)}i(nl,"isRecordsInProgress");function to(e,t){if(t===null)return null;let r=e.filter(a=>a.petRef===t);if(r.length===0)return null;let o=r.find(a=>a.status==="published");return o!==void 0?o:r.filter(nl).sort((a,l)=>l.updatedAt.localeCompare(a.updatedAt))[0]??null}i(to,"pickPetRecordsRequest");function Ei(e){if(e.hasMarkers)return "published";let t=to(e.requests,e.petRef);return t===null?"none":t.status==="published"||nl(t)?"in_progress":"none"}i(Ei,"deriveRecordsDashboardState");function Gp(e){return e.recordLoading?true:e.hasFullRecord?false:e.markersLoading||!e.hasMarkers&&e.requestsLoading}i(Gp,"selectDashboardLoading");function Si(e){return Gp(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(Si,"selectDashboardView");function pt(e){return e?.httpStatus===429?"rate_limited":e?.httpStatus===502?"service_unavailable":"error"}i(pt,"recordsEmptyVariantForError");var be=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 Yp(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(Yp,"fallbackFailureTitle");function ol(e){let t=e.failureReason?.trim()??"";return t.length>0?t:Yp(e)}i(ol,"failureTitle");var Kp=1440*60*1e3;function ki(e,t){if(!e.createdAt)return 0;let r=Date.parse(e.createdAt);if(Number.isNaN(r))return 0;let o=t-r;return o<=0?0:Math.floor(o/Kp)}i(ki,"requestElapsedDays");var Qp=7;function il(e,t){return e.wireStatus!=="awaiting_response"?false:ki(e,t)>=Qp}i(il,"requestWaitingTooLong");function Ti(e){return e.status==="failed"}i(Ti,"isTerminalFailure");function sl(e){return Ti(e)||e.canUpdateClinicEmail===true||e.canRetrySend===true}i(sl,"shouldOfferRecovery");function cl(e,t){let[r,o]=useState(""),[n,a]=useState(""),[l,c]=useState([]),[s,d]=useState(null),[u,p]=useState([]),[f,b]=useState(true),[R,v]=useState(false),[w,g]=useState(false),[y,x]=useState(null),[h,I]=useState(null),[S,T]=useState(0),C=useRef(0),A=useRef(true),F=t?.latitude,q=t?.longitude,U=useMemo(()=>F!==void 0&&q!==void 0?{latitude:F,longitude:q}:void 0,[F,q]);useEffect(()=>(A.current=true,()=>{A.current=false,C.current+=1;}),[e]),useEffect(()=>{let te=true;return b(true),e.recentClinics({limit:5}).then(_=>{te&&(_.ok&&p(_.value.clinics),b(false));}).catch(()=>{te&&b(false);}),()=>{te=false;}},[e]),useEffect(()=>{let te=r.trim();if(te.length<Ci){a("");return}let _=setTimeout(()=>a(te),rl);return ()=>clearTimeout(_)},[r]);let j=n.length>=Ci;useEffect(()=>{let te=C.current+=1;if(c([]),d(null),x(null),I(null),!j){v(false);return}v(true),e.searchClinics({query:n,limit:25,...U?{location:U}:{}}).then(_=>{!A.current||te!==C.current||(_.ok?(c(_.value.clinics),d(_.value.nextCursor)):x(_.error),v(false));}).catch(()=>{A.current&&te===C.current&&v(false);});},[e,n,j,U,S]);let ae=useCallback(()=>{if(!j||s===null||w)return;let te=C.current;g(true),I(null),e.searchClinics({query:n,limit:25,cursor:s,...U?{location:U}:{}}).then(_=>{!A.current||te!==C.current||(_.ok?(c(D=>[...D,..._.value.clinics]),d(_.value.nextCursor)):I(_.error),g(false));}).catch(()=>{A.current&&te===C.current&&g(false);});},[e,s,n,j,w,U]),ne=useCallback(te=>o(te),[]),Re=useCallback(()=>T(te=>te+1),[]);return useMemo(()=>({query:r,debouncedQuery:n,isSearchActive:j,clinics:l,recent:u,recentLoading:f,initialLoading:R,loadingMore:w,hasNextPage:s!==null,error:y,pageError:h,setQuery:ne,loadMore:ae,retry:Re}),[r,n,j,l,u,f,R,w,s,y,h,ne,ae,Re])}i(cl,"useClinicPicker");function Pi(e,t,r,o){return Object.freeze({key:e?.id??`free:${t??""}`,clinic:e,freeText:t,email:r,idempotencyKey:o})}i(Pi,"clinicDraftFor");var Gr=10,no=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),fn=i((e,t=1)=>z.string().refine(r=>!wr(r)&&[...r].length>=t&&[...r].length<=e),"text"),ul=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),Xp=z.object({clinicId:no.optional(),clinicFreeText:fn(200).refine(e=>e.trim().length>0).optional(),clinicEmail:fn(320,3).refine(e=>!ul(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())).optional(),signatureId:no.optional(),signaturePngBase64:z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0)),Jp=z.object({petRef:fn(128),ownerName:fn(200).refine(e=>e.trim().length>0&&!ul(e)),authorizationVersion:fn(64),clinics:z.array(Xp).min(1).max(Gr)}).strict(),Zp=z.object({request_group_id:no,pet_ref:z.string(),created_count:z.number().int().nonnegative(),failed_count:z.number().int().nonnegative(),results:z.array(z.object({idempotency_key:z.string(),clinic_id:no.nullable().optional(),clinic_free_text:z.string().nullable().optional(),created:z.boolean(),request:z.unknown().optional(),failure_code:z.string().nullable().optional(),failure_reason:z.string().nullable().optional()}))});function pl(e){let t=e.funnel??vr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}});return {async createClinicRequestBatch(r){if(!Jp.safeParse(r).success)return H(N("validationFailed",{retryable:false}));let o=await t.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:r.petRef,owner_name:r.ownerName,authorization_version:r.authorizationVersion,clinics:r.clinics.map(l=>({...l.clinicId!==void 0?{clinic_id:l.clinicId}:{clinic_free_text:l.clinicFreeText},...l.clinicEmail!==void 0?{clinic_email:l.clinicEmail}:{},...l.signatureId!==void 0?{signature_id:l.signatureId}:{signature_png_base64:l.signaturePngBase64},idempotency_key:l.idempotencyKey}))}});if(!o.ok)return o;let n=Zp.safeParse(o.value);if(!n.success||n.data.pet_ref!==r.petRef)return dl();let a=[];for(let l of n.data.results){let c=l.request===void 0||l.request===null?null:fr(l.request);if(l.created!==(c!==null))return dl();a.push(Object.freeze({idempotencyKey:l.idempotency_key,clinicId:l.clinic_id??null,clinicFreeText:l.clinic_free_text??null,created:l.created,request:c,failureCode:l.failure_code??null,failureReason:l.failure_reason??null}));}return Pe(Object.freeze({requestGroupId:n.data.request_group_id,petRef:n.data.pet_ref,results:Object.freeze(a),createdCount:n.data.created_count,failedCount:n.data.failed_count}))}}}i(pl,"createRecordsClinicBatchClient");function dl(){return H(N("internalError",{retryable:false}))}i(dl,"malformed");var ml=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),em=z.object({clinics:z.array(z.object({clinic_id:ml,name:z.string().min(1),address:z.string().nullable(),phone:z.string().nullable(),email_status:z.string(),distance_km:z.number().finite().nonnegative().nullable()})),next_cursor:z.string().nullable().optional()}),tm=z.object({authorization_version:z.string().min(1),scope_template:z.string().min(1),authorization_template:z.string().min(1)}),rm=z.object({upload_id:z.string().min(1),upload_url:z.string().url().refine(e=>e.startsWith("https://")),upload_fields:z.record(z.string())});function yl(e){let{repository:t}=e,r=i(async n=>{let a=await n;if(!a.ok)return a;let l=fr(a.value);return l===null?Lr():Pe(l)},"request"),o=i(async n=>{let a=await n;if(!a.ok)return a;let l=em.safeParse(a.value);return l.success?Pe(Object.freeze({clinics:Object.freeze(l.data.clinics.map(c=>Object.freeze({id:c.clinic_id,name:c.name,address:c.address,phone:c.phone,emailStatus:c.email_status,distanceKm:c.distance_km}))),nextCursor:l.data.next_cursor??null})):Lr()},"page");return {searchClinics:i((n={})=>o(t.searchClinics(n)),"searchClinics"),recentClinics:i((n={})=>o(t.recentClinics(n)),"recentClinics"),async getRequestGroup(n){let a=await t.getRequestGroup(n);if(!a.ok)return a;let l=ba(a.value);return l===null?Lr():Pe(l)},async getAuthorizationCopy(){let n=await t.getAuthorizationCopy();if(!n.ok)return n;let a=tm.safeParse(n.value);return a.success?Pe(Object.freeze({authorizationVersion:a.data.authorization_version,scopeTemplate:a.data.scope_template,authorizationTemplate:a.data.authorization_template})):Lr()},async createClinicRequest(n){let a=await r(t.createClinicRequest(n));return a.ok&&a.value.petRef!==n.petRef?Lr():a},retryRequest:i(n=>r(t.retryRequest(n)),"retryRequest"),revokeRequest:i(n=>r(t.revokeRequest(n)),"revokeRequest"),updateClinicEmail:i((n,a)=>r(t.updateClinicEmail(n,a)),"updateClinicEmail"),convertToUpload:i(n=>r(t.convertToUpload(n)),"convertToUpload"),async initiateSignatureUpload(n){let a=await t.initiateSignatureUpload(n);if(!a.ok)return a;let l=rm.safeParse(a.value);return l.success?Pe(Object.freeze({uploadId:l.data.upload_id,uploadUrl:l.data.upload_url,uploadFields:Object.freeze(l.data.upload_fields)})):Lr()},async completeSignatureUpload(n){let a=await t.completeSignatureUpload(n);if(!a.ok)return a;let l=z.object({signature_id:ml}).safeParse(a.value);return l.success?Pe(l.data.signature_id):Lr()}}}i(yl,"createRecordsClinicController");function Lr(){return H(N("internalError",{retryable:false}))}i(Lr,"malformed");var xr="/widget/v1/records",fl=z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),Er=i((e,t=1)=>z.string().refine(r=>!wr(r)&&[...r].length>=t&&[...r].length<=e),"text"),bl=i(e=>[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127),"hasControl"),hl=Er(320,3).refine(e=>!bl(e)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(e.trim())),gl=Er(64),nm=z.object({limit:z.number().int().min(1).max(25).optional()}).strict(),om=z.object({query:Er(200,0).optional(),location:z.object({latitude:z.number().finite().min(-90).max(90),longitude:z.number().finite().min(-180).max(180)}).strict().optional(),limit:z.number().int().min(1).max(100).optional(),cursor:Er(512,0).optional()}).strict(),im=z.object({petRef:Er(128),ownerName:Er(200).refine(e=>e.trim().length>0&&!bl(e)),authorizationVersion:Er(64),clinicId:fl.optional(),clinicFreeText:Er(200).refine(e=>e.trim().length>0).optional(),clinicEmail:hl.optional(),signatureId:fl.optional(),signaturePngBase64:z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(e=>e.clinicId===void 0!=(e.clinicFreeText===void 0)).refine(e=>e.signatureId===void 0!=(e.signaturePngBase64===void 0));function Rl(e){let t=e.funnel??vr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((n,a,l=false)=>t.send(`records.clinic.${n}`,a,a.method==="GET"||l?void 0:{idempotent:false,maxAttempts:1}),"send"),o=i((n,a,l)=>gl.safeParse(n).success?r(a,{method:"POST",path:`${xr}/requests/${encodeURIComponent(n)}/${a}`,...l?{body:l}:{}}):Cr(),"recover");return {searchClinics(n){return om.safeParse(n).success?r("search",{method:"GET",path:`${xr}/clinics/search`,query:{q:n.query??"",lat:n.location?.latitude,lng:n.location?.longitude,limit:n.limit,cursor:n.cursor}}):Cr()},recentClinics(n){return nm.safeParse(n).success?r("recent",{method:"GET",path:`${xr}/clinics/recent`,query:{limit:n.limit}}):Cr()},getRequestGroup(n){return gl.safeParse(n).success?r("requestGroup",{method:"GET",path:`${xr}/request-groups/${encodeURIComponent(n)}`}):Cr()},getAuthorizationCopy:i(()=>r("authorizationCopy",{method:"GET",path:`${xr}/authorization-copy`}),"getAuthorizationCopy"),createClinicRequest(n){return im.safeParse(n).success?r("create",{method:"POST",path:`${xr}/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):Cr()},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,a){return hl.safeParse(a).success?o(n,"clinic-email",{clinic_email:a}):Cr()},initiateSignatureUpload(n){return !Number.isInteger(n)||n<=0||n>2*1024*1024?Cr():r("signatureInitiate",{method:"POST",path:`${xr}/signatures/initiate`,body:{content_type:"image/png",file_size:n}})},completeSignatureUpload(n){return /^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n)?r("signatureComplete",{method:"POST",path:`${xr}/signatures/complete`,body:{upload_id:n}}):Cr()}}}i(Rl,"createHttpRecordsClinicRepository");function Cr(){return Promise.resolve(H(N("validationFailed",{retryable:false})))}i(Cr,"invalid");function Ut(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=useMemo(()=>{let{services:a}=e.registry;return yl({repository:Rl({auth:a.authFor(t),...a.errorPolicy?{errorPolicy:a.errorPolicy}:{}})})},[e,t,r]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>{let a=i(async l=>{if(t===null||n.current!==o)return H(N("accessDenied"));let c=await l();return n.current===o?c:H(N("accessDenied"))},"run");return {searchClinics:i(l=>a(()=>o.searchClinics(l)),"searchClinics"),recentClinics:i(l=>a(()=>o.recentClinics(l)),"recentClinics"),getRequestGroup:i(l=>a(()=>o.getRequestGroup(l)),"getRequestGroup"),getAuthorizationCopy:i(()=>a(()=>o.getAuthorizationCopy()),"getAuthorizationCopy"),createClinicRequest:i(l=>a(()=>o.createClinicRequest(l)),"createClinicRequest"),retryRequest:i(l=>a(()=>o.retryRequest(l)),"retryRequest"),revokeRequest:i(l=>a(()=>o.revokeRequest(l)),"revokeRequest"),updateClinicEmail:i((l,c)=>a(()=>o.updateClinicEmail(l,c)),"updateClinicEmail"),convertToUpload:i(l=>a(()=>o.convertToUpload(l)),"convertToUpload"),initiateSignatureUpload:i(l=>a(()=>o.initiateSignatureUpload(l)),"initiateSignatureUpload"),completeSignatureUpload:i(l=>a(()=>o.completeSignatureUpload(l)),"completeSignatureUpload")}},[o,t])}i(Ut,"useEverfurRecordsClinic");function Ii(){let{runtime:e,userRef:t,scopeEpoch:r}=ke(),o=useMemo(()=>{let{services:a}=e.registry;return pl({auth:a.authFor(t),...a.errorPolicy?{errorPolicy:a.errorPolicy}:{}})},[e,t,r]),n=useRef(o);return useEffect(()=>(n.current=o,()=>{n.current=null;}),[o]),useMemo(()=>({async createClinicRequestBatch(a){if(t===null||n.current!==o)return H(N("accessDenied"));let l=await o.createClinicRequestBatch(a);return n.current===o?l:H(N("accessDenied"))}}),[o,t])}i(Ii,"useEverfurRecordsClinicBatch");var Oi=class Oi extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,o){return Object.is(r.resetKey,o.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(Oi,"HostRenderBoundary");var Di=Oi;function am({render:e}){return e()}i(am,"RenderHost");function Ai({render:e,fallback:t,resetKey:r}){return createElement(Di,{fallback:t,resetKey:r,children:createElement(am,{render:e})})}i(Ai,"HostRender");var lm=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 cm(e){return lm[e]}i(cm,"requires");function Cl(e,t,r){let o=cm(e),n=new Map;for(let c of t)n.set(c.resource,c);if(r?.isPending===true&&o.some(c=>!n.has(c)))return Li({name:e,enabled:false,isPending:true,limits:{}});let a=dm(o,n);return o.filter(c=>n.get(c)?.granted!==true).length===0?Li({name:e,enabled:true,isPending:false,limits:a}):Li({name:e,enabled:false,isPending:false,limits:a,disabled:um(o,n)})}i(Cl,"decideCapability");function dm(e,t){let r={};for(let o of e){let n=t.get(o)?.limits;if(n)for(let[a,l]of Object.entries(n)){let c=r[a];r[a]=c===void 0?l:Math.min(c,l);}}return r}i(dm,"mergeLimits");function um(e,t){for(let r of e){let o=t.get(r)?.disabled;if(o)return Object.freeze({reason:o.reason,level:o.level,recoverable:o.recoverable})}return Object.freeze({reason:Zo("accessDenied"),level:"user_entitlement",recoverable:false})}i(um,"disabledFor");function Li(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(Li,"freezeDecision");function Vi(e){let{runtime:t}=ke(),r=t.entitlements,o=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>Cl(e,o.decisions,{isPending:o.isPending}),[e,o])}i(Vi,"useCapability");var ym=48;function fm(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(fm,"selectView");function Le(e){let{capability:t,children:r,renderDisabled:o,renderPending:n,style:a}=e,l=Vi(t),c=useMemo(()=>fm(l),[l]);switch(c){case "enabled":return r;case "pending":return n?jsx(Ai,{render:n,fallback:jsx(Sl,{capability:t,style:a})}):jsx(Sl,{capability:t,style:a});case "disabled":return o?jsx(Ai,{render:()=>o(l),fallback:jsx(kl,{decision:l,style:a}),resetKey:l}):jsx(kl,{decision:l,style:a});default:return Rr(c)}}i(Le,"CapabilityGate");function Sl({capability:e,style:t}){let r=V(),o=useMemo(()=>Tl(r),[r]);return jsx(View,{style:[o.offstate,t],accessible:true,accessibilityState:{busy:true},accessibilityLabel:`Loading ${e}`,children:jsx(View,{style:o.skeletonBar})})}i(Sl,"PendingSkeleton");function kl({decision:e,style:t}){let r=V(),o=useMemo(()=>Tl(r),[r]),n=e.disabled?.reason??"";return jsx(View,{style:[o.offstate,t],accessible:true,accessibilityRole:"text",accessibilityLabel:n,children:n.length>0?jsx(m,{style:o.offstateText,children:n}):null})}i(kl,"OffState");function Tl(e){let{color:t,space:r,radius:o,type:n}=e;return StyleSheet.create({offstate:{minHeight:ym,justifyContent:"center",paddingHorizontal:r.lg,paddingVertical:r.md,backgroundColor:t.surfaceCream,borderRadius:o.md,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder},offstateText:{...k(e,"regular"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.normal),color:t.text.muted},skeletonBar:{height:r.md,borderRadius:o.xs,backgroundColor:t.brandSofter}})}i(Tl,"makeStyles");var gn=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 Ve(e){let t=V(),r=useMemo(()=>hm(t),[t]);return jsxs(View,{style:[r.container,e.style],accessible:true,accessibilityRole:"text",accessibilityLabel:`${gn.title}. ${gn.body}`,children:[jsx(m,{style:r.title,children:gn.title}),jsx(m,{style:r.body,children:gn.body})]})}i(Ve,"ClinicalDisclaimer");function hm(e){let{color:t,space:r,type:o}=e;return StyleSheet.create({container:{paddingHorizontal:r.lg,paddingVertical:r.md,borderTopWidth:StyleSheet.hairlineWidth,borderTopColor:t.borderHairlineGreen,backgroundColor:t.surfaceCream,gap:r.xs},title:{...k(e,"bold"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.secondary,letterSpacing:o.letterSpacing.eyebrow},body:{...k(e,"regular"),fontSize:o.size.caption,lineHeight:Math.round(o.size.caption*o.lineHeight.snug),color:t.text.muted}})}i(hm,"makeStyles");function rt(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(rt,"slotBox");function at(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(at,"slotText");var Il=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"})}),Fi=60;function Dl(e){return `Try again in ${e}s`}i(Dl,"coolingActionLabel");var Al="Try again, available shortly";function Ue({variant:e,onAction:t,message:r,testID:o}){let n=Cm(),a=Il[e],[l,c]=useState(e==="rate_limited"?Fi:0);useEffect(()=>{e==="rate_limited"&&c(Fi);},[e]),useEffect(()=>{if(l<=0)return;let u=setTimeout(()=>c(p=>Math.max(0,p-1)),1e3);return ()=>clearTimeout(u)},[l]);let s=e==="rate_limited"&&l>0,d=s?Dl(l):a.action;return jsxs(View,{style:n.container,accessibilityRole:"summary",testID:o,children:[jsx(View,{style:n.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:n.title,children:a.title}),jsx(m,{style:n.body,children:r??a.body}),d!==null&&t?jsx(Pressable,{onPress:t,disabled:s,accessibilityRole:"button",accessibilityLabel:s?Al:d,accessibilityState:{disabled:s},style:[n.action,s?n.actionDisabled:null],testID:o?`${o}-action`:`records-empty-${e}-action`,children:jsx(m,{style:n.actionLabel,children:d})}):null]})}i(Ue,"RecordsEmptyState");function Cm(){let e=V();return useMemo(()=>Em(e),[e])}i(Cm,"useStyles");function Em(e){let{color:t,space:r,radius:o,type:n,slots:a}=e,l=r.lg+r.xs+r.xs/2;return StyleSheet.create({container:{paddingVertical:r.xxl,paddingHorizontal:r.xl,alignItems:"center",gap:r.sm+r.xs/2},glyph:{width:l,height:l,borderRadius:l/2,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{...k(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug)-1,color:t.brandInk,textAlign:"center"},body:{...k(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.normal),color:t.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:r.sm,minHeight:r.xxl+r.sm,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,backgroundColor:t.brand,alignItems:"center",justifyContent:"center",...rt(a.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{...k(e,"bold"),color:t.onPrimary,fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug)-1,...at(a.primaryButton)}})}i(Em,"makeStyles");var Ye="Back";function Ke({title:e,onBack:t,right:r,testID:o,variant:n="brand"}){let a=hn();return jsxs(View,{style:a.row,testID:o,children:[t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:Ye,hitSlop:12,style:a.back,testID:o?`${o}-back`:void 0,children:jsx(View,{style:a.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):jsx(View,{style:a.back}),jsx(m,{style:n==="document"?a.documentTitle:a.title,accessibilityRole:"header",numberOfLines:1,children:e}),jsx(View,{style:a.right,children:r??jsx(View,{style:a.back})})]})}i(Ke,"ScreenHeader");function ql(){let e=hn();return jsxs(View,{style:e.listGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.listBar}),jsx(View,{style:e.listBar}),jsx(View,{style:e.listBar})]})}i(ql,"ListGlyph");function zl(){let e=hn();return jsxs(View,{style:e.shareGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:[e.shareDot,e.shareDotTop]}),jsx(View,{style:[e.shareDot,e.shareDotLeft]}),jsx(View,{style:[e.shareDot,e.shareDotBottom]}),jsx(View,{style:[e.shareStroke,e.shareStrokeUp]}),jsx(View,{style:[e.shareStroke,e.shareStrokeDown]})]})}i(zl,"ShareGlyph");function Fl(){let e=hn();return jsxs(View,{style:e.sendGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.sendBody}),jsx(View,{style:e.sendFold})]})}i(Fl,"SendGlyph");function Nl(){let e=hn();return jsxs(View,{style:e.downloadGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[jsx(View,{style:e.downloadStem}),jsx(View,{style:e.downloadHead}),jsx(View,{style:e.downloadTray})]})}i(Nl,"DownloadGlyph");function hn(){let e=V();return useMemo(()=>Pm(e),[e])}i(hn,"useStyles");function Pm(e){let{color:t,space:r,type:o}=e,n=r.xxl+r.md,a=r.md,l=r.xs/2,c=r.lg+r.xs+r.xs/2;return StyleSheet.create({row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md,gap:r.sm},back:{width:n,height:n,alignItems:"center",justifyContent:"center"},chevron:{width:a,height:a,borderLeftWidth:l,borderBottomWidth:l,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginLeft:r.xs},title:{flex:1,...k(e,"bold"),fontSize:o.size.heading,lineHeight:Math.round(o.size.heading*o.lineHeight.tight)+1,color:t.brandInk},documentTitle:{flex:1,textAlign:"center",...k(e,"bold"),fontSize:o.size.subtitle,lineHeight:Math.round(o.size.subtitle*o.lineHeight.snug),color:t.text.primary},right:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2},listGlyph:{width:c,height:c,justifyContent:"space-evenly"},listBar:{height:l,borderRadius:l,backgroundColor:t.brandInk},shareGlyph:{width:c-r.xs,height:c-r.xs},shareDot:{position:"absolute",width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs,borderWidth:l,borderColor:t.brandInk},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:r.xs+r.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:r.xs,top:r.sm,width:r.sm+r.xs/2,height:l,backgroundColor:t.brandInk},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:c-r.xs,height:c-r.xs},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:l,borderColor:t.brandInk,transform:[{rotate:"45deg"}],borderRadius:l},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:l,backgroundColor:t.brandInk},downloadGlyph:{width:c-r.xs,height:c-r.xs,alignItems:"center"},downloadStem:{width:l,height:r.sm+r.xs/2,backgroundColor:t.brandInk},downloadHead:{width:r.sm,height:r.sm,borderRightWidth:l,borderBottomWidth:l,borderColor:t.brandInk,transform:[{rotate:"45deg"}],marginTop:-r.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:r.xs+r.xs/2,borderLeftWidth:l,borderRightWidth:l,borderBottomWidth:l,borderColor:t.brandInk}})}i(Pm,"makeStyles");var Am=120,Om=44;function Lm({reason:e,onExit:t,exitLabel:r,style:o}){let{color:n,space:a,radius:l,type:c}=V();return jsxs(View,{testID:"records-gate-off",style:[{minHeight:Am,justifyContent:"center",gap:a.md,padding:a.lg,borderRadius:l.md,borderWidth:1,borderColor:n.brandBorder,backgroundColor:n.surfaceCream},o],children:[e.length>0?jsx(m,{style:{fontSize:c.size.bodyTight,color:n.text.muted},children:e}):null,jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:r,testID:"records-gate-off-exit",style:{minHeight:Om,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:a.lg,borderRadius:l.pill,borderWidth:1.5,borderColor:n.brand},children:jsx(m,{style:{fontSize:c.size.body,color:n.brand},children:r})})]})}i(Lm,"RecordsGateOffState");function ze(e,t){return e===void 0?{}:{renderDisabled:i(r=>jsx(Lm,{reason:r.disabled?.reason??"",onExit:e,exitLabel:t}),"renderDisabled")}}i(ze,"recordsGateExit");var qm="your pet";function Fe(e){let t=e?.trim()??"";return t.length>0?t:qm}i(Fe,"petNameOr");var mt=Object.freeze({title:"Health records",openTimeline:"Open timeline",loading:"Loading health records",lead:i(e=>`${Fe(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")}),jt=Object.freeze({title:"Marker Summary",marker:"Marker",markers:"Markers",outOfRange:"OUT OF RANGE",inRange:"IN RANGE",noRange:"NO RANGE",subtitle:"Summary of your pet\u2019s biomarkers",ask:"Ask about these markers",askA11y:"Ask Everfur about these markers",a11y:i((e,t,r,o)=>`Marker summary: ${e} ${e===1?"marker":"markers"}, ${t} in range, ${r} out of range${o>0?`, ${o} without a range`:""}.`,"a11y")}),Ni=Object.freeze({counter:i((e,t)=>`${e+1} of ${t}`,"counter"),a11y:i((e,t,r)=>e!==null?`${e}, marker ${t+1} of ${r}. Swipe left or right to see more markers.`:`Marker ${t+1} of ${r}`,"a11y")}),cr=Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we\u2019ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askA11y:i(e=>`Ask Everfur about ${e}`,"askA11y"),status:i(e=>`Status: ${e}`,"status"),latestA11y:i((e,t,r)=>`Latest reading ${e}, ${t}, collected ${r}`,"latestA11y"),readingsA11y:i(e=>`${e} readings, oldest to newest`,"readingsA11y")}),Et=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"}),Sr=Object.freeze({title:i(e=>`${Fe(e)}\u2019s records request`,"title"),body:i(e=>`We\u2019re requesting ${Fe(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 ${Fe(e)}.`,"a11y"),openA11y:i((e,t)=>`Open ${Fe(e)}\u2019s records request. ${t}`,"openA11y"),ask:"Ask about this request",askA11y:"Ask Everfur about this records request"}),Vr=Object.freeze({title:i(e=>`Add ${Fe(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 ${Fe(e)}\u2019s records from a clinic`,"requestFromClinicA11y"),uploadDocument:"Upload a document",uploadDocumentA11y:i(e=>`Upload one of ${Fe(e)}\u2019s records`,"uploadDocumentA11y")});var so="rgba(0,0,0,0.4)";function ue(){let e=V();return useMemo(()=>Mm(e),[e])}i(ue,"useScreenStyles");function kr({disclaimer:e,style:t}){let r=ue();return e.trim().length===0?null:jsxs(View,{style:[r.band,t],accessible:true,accessibilityRole:"text",accessibilityLabel:mt.important(e),testID:"records-disclaimer-band",children:[jsx(View,{style:r.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{style:r.infoGlyphText,children:"i"})}),jsx(m,{style:r.bandText,children:e})]})}i(kr,"DisclaimerBand");function J({label:e,onPress:t,kind:r="primary",disabled:o=false,busy:n=false,accessibilityLabel:a,testID:l,style:c}){let s=ue(),d=V(),u=r==="primary"?s.pillPrimary:r==="outline"?s.pillOutline:r==="danger"?s.pillDanger:r==="ask"?s.pillAsk:s.pillLink,p=r==="primary"?s.pillPrimaryLabel:r==="danger"?s.pillDangerLabel:r==="ask"?s.pillAskLabel:r==="link"?s.pillLinkLabel:s.pillOutlineLabel;return jsxs(Pressable,{onPress:t,disabled:o||n,accessibilityRole:"button",accessibilityLabel:a??e,accessibilityState:{disabled:o||n,busy:n},style:[s.pill,u,o?s.pillDisabled:null,c],testID:l,children:[n?jsx(ActivityIndicator,{size:"small",color:r==="primary"?d.color.onPrimary:d.color.brandInk}):null,jsx(m,{style:p,children:e})]})}i(J,"Pill");function St({label:e,tone:t="neutral",testID:r}){let o=ue(),{bg:n,fg:a}=o.chipTones[t];return jsx(View,{style:[o.chip,n],testID:r,children:jsx(m,{style:[o.chipText,a],children:e})})}i(St,"Chip");function Dt({title:e,count:t}){let r=ue();return jsxs(View,{style:r.sectionHeader,children:[jsx(m,{style:r.sectionTitle,accessibilityRole:"header",children:e}),t!==void 0?jsx(m,{style:r.sectionCount,children:t}):null]})}i(Dt,"SectionHeader");function tr({direction:e="right"}){let t=ue(),r=e==="right"?"45deg":e==="down"?"135deg":"-45deg";return jsx(View,{style:[t.chevron,{transform:[{rotate:r}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(tr,"Chevron");function Mm(e){let{color:t,space:r,radius:o,type:n,slots:a}=e,{size:l,lineHeight:c}=n,s=i((v,w)=>Math.round(v*w),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl+r.md,p=i((v,w,g,y="regular")=>({...k(e,y),fontSize:v,lineHeight:s(v,w),color:g}),"text"),f=at(a.recordCard),b=e.brightness==="dark"?t.errorRed:t.danger,R=i((v,w)=>({bg:{backgroundColor:v},fg:{color:w}}),"tone");return {chipTones:{neutral:R(t.badgeBgNeutral,t.text.secondary),info:R(t.brandSoft,t.brandInk),warning:R(t.badgeBgCaution,t.warningStrong),critical:R(t.badgeBgCritical,t.danger),positive:R(t.badgeBgPositive,t.success)},...StyleSheet.create({root:{flex:1,backgroundColor:t.background},body:{flex:1},content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg},contentTight:{paddingHorizontal:r.sm,paddingBottom:r.xxl,gap:r.lg},inset:{paddingHorizontal:r.sm},section:{gap:r.sm+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.xs},sectionTitle:{...p(l.body+1,c.snug,t.text.primary,"bold")},sectionCount:{...p(l.bodyTight,c.snug,t.text.muted,"medium")},card:{borderRadius:o.lg-r.xs,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.xs,...rt(a.recordCard,d)},creamCard:{borderRadius:o.lg-r.xs/2,borderWidth:d,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md,...rt(a.recordCard,d)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.md,paddingVertical:r.md},rowDivider:{borderTopWidth:d,borderTopColor:t.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:r.xs+r.xs/2},rowTitle:{...p(l.body,c.snug,t.text.primary,"medium"),...f},rowDetail:{...p(l.caption,c.normal,t.text.secondary),marginTop:r.xs/2,...f},rowValue:{...p(l.body+1,c.snug,t.text.primary,"bold"),marginTop:r.xs/2,...f},rowMuted:{...p(l.caption,c.normal,t.text.muted),...f},chip:{borderRadius:o.pill,paddingHorizontal:r.sm,paddingVertical:r.xs-1,alignSelf:"flex-start"},chipText:{...p(l.tiny,c.snug,t.text.primary,"medium")},pill:{minHeight:u,borderRadius:o.pill,paddingHorizontal:r.lg+r.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm},pillPrimary:{backgroundColor:t.brand,...rt(a.primaryButton)},pillPrimaryLabel:{...p(l.body,c.snug,t.onPrimary,"bold"),...at(a.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:t.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...p(l.body,c.snug,t.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:t.danger,backgroundColor:t.surface},pillDangerLabel:{...p(l.bodyTight,c.snug,t.danger,"bold")},pillAsk:{borderWidth:d,borderColor:t.borderRingCream,backgroundColor:t.surface},pillAskLabel:{...p(l.body,c.snug,t.text.primary,"bold")},pillLink:{backgroundColor:"transparent",paddingHorizontal:r.sm},pillLinkLabel:{...p(l.body,c.snug,t.linkInk,"bold")},pillDisabled:{opacity:.5},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},infoNoteText:{flex:1,...p(l.bodyTight,c.normal,t.text.primary)},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCaution,paddingHorizontal:r.md,paddingVertical:r.sm+r.xs/2},cautionNoteText:{flex:1,...p(l.bodyTight,c.normal,t.warningStrong)},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2},statusText:p(l.bodyTight,c.relaxed,t.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,backgroundColor:t.badgeBgCritical,padding:r.md},errorText:{flex:1,...p(l.bodyTight,c.normal,b)},band:{flexDirection:"row",alignItems:"flex-start",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft},bandText:{flex:1,...p(l.caption,c.normal,t.text.secondary)},infoGlyph:{width:r.md+r.xs/2,height:r.md+r.xs/2,borderRadius:o.pill,borderWidth:1,borderColor:t.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...p(l.small,c.tight,t.text.secondary,"bold")},chevron:{width:r.sm,height:r.sm,borderTopWidth:r.xs/2,borderRightWidth:r.xs/2,borderColor:t.text.muted},lead:{paddingHorizontal:r.sm,...p(l.body+1,c.snug,t.text.primary,"bold")},field:{minHeight:u,paddingHorizontal:r.md,paddingVertical:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,...k(e,"regular"),fontSize:l.body},fieldLabel:{...p(l.bodyTight,c.normal,t.text.secondary,"medium")},muted:p(l.caption,c.normal,t.text.muted),bodyText:p(l.body,c.normal,t.text.primary)})}}i(Mm,"makeScreenStyles");function Yr(e,t){return e===null?"":t?`${e} ${t}`:e}i(Yr,"formatEntityValue");var Bl=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Y(e){if(!e)return "-";let t=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);if(t!==null){let n=Bl[Number(t[2])-1];return n===void 0?"-":`${n} ${Number(t[3])}, ${t[1]}`}let r=Date.parse(e);if(Number.isNaN(r))return "-";let o=new Date(r);return `${Bl[o.getUTCMonth()]} ${o.getUTCDate()}, ${o.getUTCFullYear()}`}i(Y,"formatRecordsDate");var ge=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 rr(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(rr,"markerStatusLabel");function Kr(e,t){return t<2?null:`${e==="flat"?"Holding steady":`Trending ${e==="down"?"down":e==="up"?"up":"steady"}`} over ${t} visits`}i(Kr,"trajectoryLabel");function dr(e){let t=e.replace(/_/g," ").trim();return t.length===0?e:t.charAt(0).toUpperCase()+t.slice(1)}i(dr,"humanize");var Hl=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 qr(e){return Object.prototype.hasOwnProperty.call(Hl,e)?Hl[e]:dr(e)}i(qr,"bodySystemLabel");var Ul=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 Qr(e){return Object.prototype.hasOwnProperty.call(Ul,e)?Ul[e]:dr(e)}i(Qr,"soapSectionLabel");function jl(e){return e===null||!Number.isFinite(e)?"-":`${e.toFixed(3).replace(/\.?0+$/,"")} kg`}i(jl,"formatWeightKg");function kt(e,t,r){if((e===null||!Number.isFinite(e))&&r)return r;if(e===null||!Number.isFinite(e))return "-";let o=e.toFixed(3).replace(/\.?0+$/,"");return t?`${o} ${t}`:o}i(kt,"formatMarkerReading");function Bi(e,t,r){let o=Kr(t,r);return e?`${ge.measured(Y(e))}${o?` \xB7 ${o}`:""}`:o}i(Bi,"labDetailLine");var ie=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 Bm(e,t){if(!e)return false;let r=Date.parse(e);return Number.isNaN(r)?false:r<=t}i(Bm,"isShareExpired");function Hm(e,t){let r=Y(e);return r==="-"?t?"Expired":"No expiry date":t?`Expired ${r}`:`Expires ${r}`}i(Hm,"formatShareExpiry");function $l(e,t,r){let o=e.map(n=>{let a=Bm(n.expiresAt,r),l=Hm(n.expiresAt,a),c=Y(n.createdAt),s=a?"Expired":"Active",d=l.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return {shareId:n.shareId,shareUrl:t[n.shareId]??null,active:!a,statusLabel:s,expiryLabel:l,createdLabel:c==="-"?null:`Created ${c}`,a11yLabel:`Share link. ${s}. ${l}.`,actionContext:d}});return Object.freeze([...o.filter(n=>n.active),...o.filter(n=>!n.active)])}i($l,"buildShareRows");function ao(e,t){let r=e?.httpStatus;if(sr(e)){if(t==="create")return "Records access for this pet is off, so a new link cannot be created.";if(t==="download")return "Records access for this pet is off, so the PDF cannot be downloaded."}if(r===429)return "You are creating links a little too fast. Wait a moment, then try again.";if(t==="revoke"&&(r===404||r===409||r===410))return "That link was already turned off.";if(r===401||r===403)return "You need to be signed in as this pet's owner to do that.";switch(t){case "create":return "Could not create a share link. Please try again.";case "revoke":return "Could not turn off that link. Please try again.";default:return "Could not download the record PDF. Please try again."}}i(ao,"shareErrorMessage");function we({width:e,height:t,radius:r,style:o}){let{color:n,radius:a}=V();return jsx(View,{style:[{width:e,height:t,borderRadius:r??a.xs,backgroundColor:n.skeleton},o],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(we,"SkeletonBlock");var Hi=180,Gl=70,lo=22,jm=300,Yl=44,co=24,Ui=34,$m=6,Wm=5;function uo({testID:e}){let t=wn(),r=i(o=>jsxs(View,{style:t.actionRow,children:[jsxs(View,{style:t.actionLeft,children:[jsx(we,{width:18,height:18,radius:9}),jsx(we,{width:"55%",height:14,radius:7})]}),jsx(we,{width:18,height:18,radius:9})]},o),"action");return jsxs(View,{style:t.dashboard,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:mt.loading,testID:e,children:[jsx(View,{style:t.inset,children:jsxs(View,{style:t.summaryCard,children:[jsx(we,{width:Hi,height:Hi,radius:Hi/2}),jsxs(View,{style:t.badges,children:[jsx(we,{width:Gl,height:lo,radius:lo/2}),jsx(we,{width:Gl,height:lo,radius:lo/2})]})]})}),jsx(we,{width:150,height:16,radius:8,style:t.inset}),jsx(View,{style:t.carouselCard,children:jsx(we,{width:"100%",height:jm,radius:14})}),jsxs(View,{style:t.dots,children:[jsx(we,{width:6,height:6,radius:3}),jsx(we,{width:18,height:6,radius:3}),jsx(we,{width:6,height:6,radius:3})]}),jsx(we,{width:46,height:12,radius:6,style:t.centered}),jsx(View,{style:t.inset,children:jsx(we,{width:"100%",height:Yl,radius:12})}),jsxs(View,{style:[t.inset,t.actions],children:[r("a"),r("b")]})]})}i(uo,"DashboardSkeleton");function po({testID:e}){let t=wn();return jsxs(View,{style:t.request,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:be.loading,testID:e,children:[jsx(View,{children:[0,1,2,3].map(r=>jsxs(View,{style:t.railRow,children:[jsxs(View,{style:t.railColumn,children:[jsx(we,{width:co,height:co,radius:co/2}),r<3?jsx(we,{width:2,height:20,radius:1,style:t.connector}):null]}),jsxs(View,{style:t.railBody,children:[jsx(we,{width:"55%",height:14,radius:7}),jsx(we,{width:"75%",height:11,radius:6})]})]},r))}),jsxs(View,{style:t.statusCard,children:[jsx(we,{width:"90%",height:13,radius:6}),jsx(we,{width:"60%",height:13,radius:6})]}),jsx(we,{width:"100%",height:50,radius:25})]})}i(po,"RequestSkeleton");function Kl({testID:e}){let t=wn();return jsxs(View,{style:t.timeline,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:ge.loadingTimeline,testID:e,children:[jsx(View,{style:t.timelineDisclaimer,children:jsx(we,{width:"100%",height:Yl,radius:12})}),Array.from({length:$m},(r,o)=>jsxs(View,{children:[o>0?jsx(View,{style:t.timelineSeparator}):null,jsxs(View,{style:t.timelineRow,children:[jsx(we,{width:Ui,height:Ui,radius:Ui/2}),jsxs(View,{style:t.timelineBody,children:[jsxs(View,{style:t.timelineTop,children:[jsx(we,{width:44,height:10,radius:5}),jsx(we,{width:56,height:12,radius:6})]}),jsx(we,{width:"70%",height:14,radius:7}),o%2===0?jsx(we,{width:"45%",height:12,radius:6}):null]})]})]},o))]})}i(Kl,"TimelineSkeleton");function Ql({testID:e}){let t=wn();return jsx(View,{style:t.clinics,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:xe.loading,testID:e,children:Array.from({length:Wm},(r,o)=>jsxs(View,{style:t.clinicRow,children:[jsx(we,{width:"65%",height:14,radius:7}),jsx(we,{width:"40%",height:11,radius:6})]},o))})}i(Ql,"ClinicsSkeleton");function Xl({testID:e}){let t=wn();return jsx(View,{style:t.shares,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:ie.loadingLinks,testID:e,children:[0,1].map(r=>jsxs(View,{style:t.shareRow,children:[jsx(we,{width:"55%",height:13}),jsx(we,{width:"40%",height:11})]},r))})}i(Xl,"SharesSkeleton");var ji=62;function wn(){let e=V();return useMemo(()=>Gm(e),[e])}i(wn,"useStyles");function Gm(e){let{color:t,space:r,radius:o}=e,n=StyleSheet.hairlineWidth;return StyleSheet.create({dashboard:{flex:1,paddingHorizontal:r.sm,paddingTop:r.xs,gap:r.lg,backgroundColor:t.background},inset:{paddingHorizontal:r.sm},summaryCard:{alignItems:"center",borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg+r.xs,gap:r.md+r.xs/2},badges:{flexDirection:"row",gap:r.md},carouselCard:{borderRadius:o.lg-r.xs,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg},dots:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.xs+r.xs/2},centered:{alignSelf:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},request:{paddingHorizontal:r.lg,paddingTop:r.xs,gap:r.lg+r.xs/2,backgroundColor:t.background},railRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md},railColumn:{alignItems:"center",width:co},connector:{marginVertical:r.xs/2},railBody:{flex:1,paddingBottom:r.lg+r.xs/2,gap:r.xs+r.xs/2},statusCard:{borderRadius:o.md,backgroundColor:t.brandSoft,padding:r.md+r.xs/2,gap:r.sm},timeline:{flex:1,backgroundColor:t.background},timelineDisclaimer:{paddingHorizontal:r.lg,paddingTop:r.xs,paddingBottom:r.md},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBody:{flex:1,gap:r.xs-1},timelineTop:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},timelineSeparator:{height:n,backgroundColor:t.brandBorder,marginLeft:ji},clinics:{gap:r.md},clinicRow:{borderRadius:o.lg-r.xs/2,borderWidth:n,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2,gap:r.sm},shares:{gap:r.md,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:n,borderColor:t.brandBorder},shareRow:{gap:r.xs+r.xs/2}})}i(Gm,"makeStyles");var Zm=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function $i(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Le,{capability:"recordsClinic",style:e.style,...ze(e.onBack,Ye),children:t===null?jsx(m,{accessibilityRole:"alert",children:pe.sessionRequired}):jsx(ey,{...Oe(e,["onNavigate","onBack"])},JSON.stringify([t,r,e.petRef]))})}i($i,"EverfurClinicPicker");function ey({petRef:e,controller:t,recordsController:r,location:o,onNavigate:n,onBack:a,style:l}){let c=ue(),s=ry(),d=V(),u=Ut(),p=cl(t??u,o),f=st(r?{petRef:e,controller:r}:{petRef:e}),b=useRef(ar()),[R,v]=useState(false),[w,g]=useState(null),[y,x]=useState(false),[h,I]=useState(""),[S,T]=useState(false),[C,A]=useState(""),[F,q]=useState(false),U=useCallback(E=>{n?.({name:"consent",clinic:Pi(E,null,"",b.current())});},[n]),j=i(()=>{R||(v(true),g(null),f.createRequest(`records-upload-${Date.now().toString(36)}`).then(E=>{if(v(false),!E.ok){g(be.errors.start);return}n?.({name:"request",requestId:E.value.id});}));},"startUpload"),ae=S?h:p.query,ne=Zm.test(C.trim()),Re=ae.trim().length>0&&ne,te=i(E=>{let{layoutMeasurement:L,contentOffset:X,contentSize:fe}=E.nativeEvent;L.height+X.y>=fe.height-L.height*.6&&p.loadMore();},"onEndReached"),_=p.isSearchActive?p.clinics:p.recent,D=p.isSearchActive?p.error?pt(p.error):!p.initialLoading&&p.clinics.length===0?"idle":null:p.recent.length>0||p.recentLoading?null:"idle";return jsxs(View,{style:[c.root,l],children:[jsx(Ke,{title:xe.title,onBack:a,testID:"records-clinic-header"}),jsxs(View,{style:s.searchBar,children:[jsx(View,{style:s.searchGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(He,{value:p.query,onChangeText:p.setQuery,placeholder:xe.placeholder,placeholderTextColor:d.color.text.muted,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",maxLength:200,accessibilityLabel:xe.searchA11y,style:s.searchInput,testID:"records-clinic-search-input"}),p.query.length>0?jsx(Pressable,{onPress:()=>p.setQuery(""),accessibilityRole:"button",accessibilityLabel:xe.clearSearch,hitSlop:8,testID:"records-clinic-search-clear",children:jsx(m,{style:s.clearGlyph,children:"\xD7"})}):null]}),n?jsxs(View,{style:s.uploadWrap,children:[w?jsx(View,{style:c.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:c.errorText,children:w})}):null,jsx(J,{label:R?xe.uploadOwnStarting:xe.uploadOwn,kind:"outline",accessibilityLabel:xe.uploadOwnA11y,busy:R,onPress:j,testID:"records-clinic-upload-own"})]}):null,jsxs(ScrollView,{contentContainerStyle:s.list,keyboardShouldPersistTaps:"handled",onScroll:p.isSearchActive?te:void 0,scrollEventThrottle:200,testID:"records-clinic-results",children:[p.isSearchActive?jsxs(View,{style:s.fallbackCard,testID:"records-clinic-fallback-card",children:[jsxs(Pressable,{onPress:()=>x(E=>!E),accessibilityRole:"button",accessibilityLabel:y?xe.fallback.collapseA11y:xe.fallback.expandA11y,style:s.fallbackHeader,testID:"records-clinic-fallback",children:[jsxs(View,{style:s.fallbackCopy,children:[jsx(m,{style:s.fallbackTitle,numberOfLines:1,children:xe.fallback.title}),jsx(m,{style:s.fallbackSubtitle,numberOfLines:2,children:xe.fallback.subtitle})]}),jsx(tr,{direction:y?"up":"down"})]}),y?jsxs(View,{style:s.fallbackForm,children:[jsx(m,{style:c.fieldLabel,children:xe.fallback.nameLabel}),jsx(He,{accessibilityLabel:xe.fallback.nameLabel,style:c.field,value:ae,onChangeText:E=>{I(E),T(true);},placeholder:xe.fallback.namePlaceholder,placeholderTextColor:d.color.text.placeholder,autoCapitalize:"words",autoCorrect:false,maxLength:200,testID:"records-clinic-fallback-name"}),jsx(m,{style:c.fieldLabel,children:xe.fallback.emailLabel}),jsx(He,{accessibilityLabel:xe.fallback.emailLabel,style:c.field,value:C,onChangeText:E=>{A(E),q(false);},onBlur:()=>q(true),placeholder:xe.fallback.emailPlaceholder,placeholderTextColor:d.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,testID:"records-clinic-fallback-email"}),F&&C.trim().length>0&&!ne?jsx(m,{style:c.errorText,accessibilityRole:"alert",children:be.errors.invalidEmail}):null,jsx(m,{style:c.muted,children:xe.fallback.reviewNote}),jsx(J,{label:xe.fallback.submit,accessibilityLabel:xe.fallback.submitA11y,disabled:!Re||!n,onPress:()=>n?.({name:"consent",clinic:Pi(null,ae.trim(),C.trim().toLowerCase(),b.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):p.recent.length>0?jsx(m,{style:s.sectionLabel,accessibilityRole:"header",testID:"records-clinic-recent-label",children:xe.recentlyUsed}):null,p.isSearchActive&&p.initialLoading?jsx(Ql,{testID:"records-clinic-page-loading"}):null,_.map(E=>jsx(ty,{clinic:E,onSelect:U,styles:s},E.id)),D&&!p.initialLoading?jsx(Ue,{variant:D,message:p.isSearchActive&&D==="idle"?xe.noMatch(p.debouncedQuery):p.error?.displayMessage,onAction:p.error?.retryable===true?p.retry:void 0,testID:"records-clinic-empty"}):null,jsxs(View,{style:s.footer,children:[p.loadingMore?jsxs(View,{style:s.footerLoading,testID:"records-clinic-loading-more",children:[jsx(ActivityIndicator,{color:d.color.brandInk,size:"small"}),jsx(m,{style:c.muted,children:xe.loadingMore})]}):null,p.pageError?jsx(Pressable,{onPress:p.loadMore,accessibilityRole:"button",accessibilityLabel:xe.loadMoreRetryA11y,style:s.footerRetry,testID:"records-clinic-page-error-retry",children:jsx(m,{style:s.footerRetryLabel,children:xe.loadMoreFailed})}):null]})]}),jsx(Ve,{})]})}i(ey,"PickerBody");function ty({clinic:e,onSelect:t,styles:r}){let o=Za(e.emailStatus),n=el(e.distanceKm),a=[e.name,e.address,e.phone?`phone ${e.phone}`:null,n?tl(e.distanceKm):null,o.a11y].filter(Boolean).join(", ");return jsxs(Pressable,{onPress:()=>t(e),accessibilityRole:"button",accessibilityLabel:xe.selectA11y(a),hitSlop:8,style:r.item,testID:`records-clinic-${e.id}`,children:[jsxs(View,{style:r.itemHeader,children:[jsx(m,{style:r.itemName,numberOfLines:1,children:e.name}),n?jsx(m,{style:r.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:n}):null]}),e.address?jsx(m,{style:r.itemAddress,numberOfLines:2,children:e.address}):null,e.phone?jsx(m,{style:r.itemPhone,numberOfLines:1,accessibilityElementsHidden:true,importantForAccessibility:"no",children:e.phone}):null,jsx(View,{style:[r.badge,o.tone==="positive"?r.badgePositive:o.tone==="caution"?r.badgeCaution:r.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{style:[r.badgeLabel,o.tone==="positive"?r.badgePositiveText:o.tone==="caution"?r.badgeCautionText:r.badgeNeutralText],children:o.label})})]})}i(ty,"ClinicRow");function ry(){let e=V();return useMemo(()=>ny(e),[e])}i(ry,"useLocalStyles");function ny(e){let{color:t,space:r,radius:o,type:n}=e,a=StyleSheet.hairlineWidth,l=i((c,s,d,u="regular")=>({...k(e,u),fontSize:c,lineHeight:Math.round(c*s),color:d}),"text");return StyleSheet.create({searchBar:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingHorizontal:r.md+r.xs/2,height:r.xxl+r.md,marginHorizontal:r.lg,marginBottom:r.sm,borderRadius:o.lg+r.xs/2,backgroundColor:t.surfaceSubtle,borderWidth:a,borderColor:t.borderHairlineGreen},searchGlyph:{width:r.md,height:r.md,borderRadius:o.pill,borderWidth:2,borderColor:t.text.muted},searchInput:{flex:1,...l(n.size.body,n.lineHeight.snug,t.text.primary),paddingVertical:0},clearGlyph:l(n.size.heading,n.lineHeight.tight,t.text.muted),uploadWrap:{paddingHorizontal:r.lg,paddingBottom:r.md,gap:r.sm},list:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.md},sectionLabel:{...l(n.size.caption,n.lineHeight.normal,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:o.lg-r.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:t.brandBorder,backgroundColor:t.surfaceCream,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.md},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:r.md,minHeight:r.xxl+r.md},fallbackCopy:{flex:1,gap:r.xs/2},fallbackTitle:{...l(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},fallbackSubtitle:l(n.size.caption,n.lineHeight.normal,t.text.muted),fallbackForm:{gap:r.sm},item:{borderRadius:o.lg-r.xs/2,borderWidth:a,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},itemName:{flex:1,...l(n.size.body,n.lineHeight.snug,t.brandInk,"bold")},itemDistance:{...k(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},itemAddress:l(n.size.caption,n.lineHeight.normal,t.text.primary),itemPhone:l(n.size.caption,n.lineHeight.normal,t.text.muted),badge:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+1,paddingVertical:r.xs},badgePositive:{backgroundColor:t.badgeBgPositive},badgeCaution:{backgroundColor:t.badgeBgCaution},badgeNeutral:{backgroundColor:t.badgeBgNeutral},badgeLabel:{...l(n.size.micro,n.lineHeight.snug,t.text.muted,"bold")},badgePositiveText:{color:t.success},badgeCautionText:{color:t.cautionAccent},badgeNeutralText:{color:t.text.muted},footer:{gap:r.sm,paddingTop:r.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.md},footerRetry:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...l(n.size.bodyTight,n.lineHeight.snug,t.brandInk,"bold")}})}i(ny,"makeLocalStyles");var Ne=Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${Gr} clinics`,sendA11y:i(e=>e===1?"Send 1 records request":`Send ${e} records requests`,"sendA11y"),send:i(e=>`Send ${e} ${e===1?"request":"requests"}`,"send"),sending:"Sending\u2026",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:i(e=>`Remove ${e}`,"remove"),emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn\u2019t send any of these requests. See the details below and try again.",partial:i((e,t,r)=>`${e} of ${t} requests sent. ${r} couldn\u2019t be sent.`,"partial"),allSent:i(e=>`${e} ${e===1?"request":"requests"} sent.`,"allSent"),responded:i((e,t)=>`${e} of ${t} ${t===1?"clinic":"clinics"} responded`,"responded")});function xn(e,t,r,o){let n={owner_name:t,pet_name:r,clinic_name:o},a=false,l=e.scopeTemplate.replace(/\{([^{}]+)\}/g,(c,s)=>Object.prototype.hasOwnProperty.call(n,s)?n[s]??"":(a=true,""));return a||/[{}]/.test(l)?null:l}i(xn,"renderClinicScope");function Cn(e){return e===null||e.emailStatus!=="verified"&&e.emailStatus!=="unverified"}i(Cn,"clinicNeedsEmail");function Zl(e,t,r){let[o,n]=useState(e.ownerName),[a,l]=useState(""),[c,s]=useState(null),[d,u]=useState(""),[p,f]=useState([]),[b,R]=useState([]),[v,w]=useState(null),[g,y]=useState(null),[x,h]=useState(false),[I,S]=useState(false),[T,C]=useState(null),[A,F]=useState(0),q=useRef(false),U=useRef(false),j=useRef(0),ae=useRef(ar()),ne=useRef(null),Re=useRef(null),te=useRef(0);useEffect(()=>(q.current=true,U.current=false,h(false),()=>{q.current=false,te.current+=1,j.current+=1,ne.current=null,Re.current?.abort();}),[t]),useEffect(()=>{let oe=true;return w(null),ne.current=null,t.getAuthorizationCopy().then(Ce=>{oe&&(Ce.ok?(w(Ce.value),y(null)):y(Ce.error));}).catch(()=>{oe&&y(N("internalError"));}),()=>{oe=false;}},[t,A]),useEffect(()=>{let oe=true;return R([]),t.recentClinics({limit:5}).then(Ce=>{oe&&Ce.ok&&R(Ce.value.clinics);}).catch(()=>{}),()=>{oe=false;}},[t]);let _=i(()=>{ne.current=null,y(null);},"invalidate"),D=c?.name??a.trim(),E=v?xn(v,o.trim(),e.petName,D):null,L=Cn(c),X=!!(v&&E&&o.trim()&&e.petName.trim()&&D&&(!L||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(d.trim()))&&r),fe=i(async()=>{if(U.current)return;let oe=++j.current;S(true);try{let Ce=await t.searchClinics({query:a.trim(),limit:100});if(!q.current||oe!==j.current)return;Ce.ok?(f(Ce.value.clinics),y(null)):y(Ce.error);}catch{q.current&&oe===j.current&&y(N("internalError"));}finally{q.current&&oe===j.current&&S(false);}},"search"),Be=i(async()=>{if(U.current||T||!X||!v||!E||!r)return;U.current=true;let oe=te.current,Ce=i(()=>q.current&&te.current===oe,"current");h(true),y(null);try{if(!ne.current){Re.current=new AbortController;let tt=await r({petRef:e.petRef,petName:e.petName,ownerName:o.trim(),clinicName:D,authorizationVersion:v.authorizationVersion,scopeText:E,signal:Re.current.signal});if(!Ce()||tt===null)return;let Nt=c&&(!L||c.emailStatus==="none")?{clinicId:c.id}:{clinicFreeText:D};ne.current={petRef:e.petRef,ownerName:o.trim(),authorizationVersion:v.authorizationVersion,...Nt,...L?{clinicEmail:d.trim().toLowerCase()}:{},...tt.signatureId!==void 0?{signatureId:tt.signatureId}:{signaturePngBase64:tt.signaturePngBase64},idempotencyKey:ae.current()};}if(!Ce())return;let xt=await t.createClinicRequest(ne.current);if(!Ce())return;if(!xt.ok){y(xt.error);return}if(xt.value.petRef!==e.petRef){y(N("internalError"));return}C(xt.value),ne.current=null,e.onCreated?.(xt.value);}catch{Ce()&&y(N("internalError"));}finally{U.current=false,Ce()&&h(false);}},"submit");return {ownerName:o,query:a,clinic:c,email:d,clinics:p,copy:v,scope:E,error:g,busy:x,searching:I,created:T,ready:X,needsEmail:L,recent:p.length===0&&c===null?b:[],setOwnerName(oe){U.current||(_(),n(oe));},setQuery(oe){U.current||(_(),j.current+=1,S(false),f([]),s(null),u(""),l(oe));},setEmail(oe){U.current||(_(),u(oe));},selectClinic(oe){U.current||(_(),j.current+=1,S(false),f([]),s(oe),l(oe.name),u(""));},invalidate:_,search:fe,submit:Be,retryCopy(){y(null),F(oe=>oe+1);}}}i(Zl,"useClinicRequestForm");var oy=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Sn(e){return e.clinic?.name??e.freeText??""}i(Sn,"draftName");function En(e){return Cn(e.clinic)}i(En,"draftNeedsEmail");function ec(e,t,r,o,n){let[a,l]=useState(e.ownerName),[c,s]=useState(""),[d,u]=useState([]),[p,f]=useState([]),[b,R]=useState([]),[v,w]=useState(null),[g,y]=useState(null),[x,h]=useState(false),[I,S]=useState(false),[T,C]=useState(null),[A,F]=useState(null),[q,U]=useState(0),j=useRef(false),ae=useRef(false),ne=useRef(0),Re=useRef(0),te=useRef(ar()),_=useRef(null),D=useRef(null);useEffect(()=>(j.current=true,ae.current=false,h(false),()=>{j.current=false,Re.current+=1,ne.current+=1,_.current=null,D.current?.abort();}),[t,r]),useEffect(()=>{let M=true;return w(null),_.current=null,t.getAuthorizationCopy().then(ve=>{M&&(ve.ok?(w(ve.value),y(null)):y(ve.error));}).catch(()=>{M&&y(N("internalError"));}),()=>{M=false;}},[t,q]),useEffect(()=>{let M=true;return f([]),t.recentClinics({limit:5}).then(ve=>{M&&ve.ok&&f(ve.value.clinics);}).catch(()=>{}),()=>{M=false;}},[t]);let E=i(()=>{_.current=null,y(null);},"invalidate"),L=b.map(Sn),X=v?L.map(M=>xn(v,a.trim(),e.petName,M)):[],fe=X.every(M=>M!==null)?X.join(`
|
|
2
2
|
|
|
3
|
-
`):null,Be=b.length>0&&b.every(N=>!Cn(N)||ry.test(N.email.trim())),oe=b.length>=Gr,xe=!!(v&&fe&&l.trim()&&e.petName.trim()&&Be&&o)&&k===null,xt=i(async()=>{if(re.current)return;let N=++se.current;S(true);try{let Re=await t.searchClinics({query:c.trim(),limit:100});if(!j.current||N!==se.current)return;Re.ok?(u(Re.value.clinics),f(null)):f(Re.error);}catch{j.current&&N===se.current&&f(F("internalError"));}finally{j.current&&N===se.current&&S(false);}},"search"),tt=i(N=>{re.current||oe||k!==null||N.clinic!==null&&b.some(Re=>Re.clinic?.id===N.clinic?.id)||(C(),R(Re=>[...Re,{...N,key:ee.current(),idempotencyKey:ee.current()}]),u([]),s(""));},"add"),Nt=i(async()=>{if(re.current||k!==null||!xe||!v||!fe||!o)return;re.current=true;let N=Te.current,Re=i(()=>j.current&&Te.current===N,"current");h(true),f(null);try{if(I.current===null){D.current=new AbortController;let Ct=await o({petRef:e.petRef,petName:e.petName,ownerName:l.trim(),clinicName:L.join(", "),authorizationVersion:v.authorizationVersion,scopeText:fe,signal:D.current.signal});if(!Re()||Ct===null)return;if(I.current=Ct,Ct.signaturePngBase64!==void 0&&n!==void 0){let su=await n(Ct.signaturePngBase64,D.current.signal);if(!Re())return;I.current={signatureId:su.signatureId};}}let Bt=I.current,sn=b.map(Ct=>({...Ct.clinic!==null&&(!Cn(Ct)||Ct.clinic.emailStatus==="none")?{clinicId:Ct.clinic.id}:{clinicFreeText:En(Ct)},...Cn(Ct)?{clinicEmail:Ct.email.trim().toLowerCase()}:{},...Bt.signatureId!==void 0?{signatureId:Bt.signatureId}:{signaturePngBase64:Bt.signaturePngBase64},idempotencyKey:Ct.idempotencyKey})),an=await r.createClinicRequestBatch({petRef:e.petRef,ownerName:l.trim(),authorizationVersion:v.authorizationVersion,clinics:sn});if(!Re())return;if(!an.ok){f(an.error);return}E(an.value),e.onCreated?.(an.value),Mt(an.value.requestGroupId,N);}catch{Re()&&f(F("internalError"));}finally{re.current=false,Re()&&h(false);}},"submit"),Mt=i(async(N,Re)=>{try{let Bt=await t.getRequestGroup(N);if(!j.current||Te.current!==Re)return;Bt.ok&&Bt.value.petRef===e.petRef&&B(Bt.value);}catch{}},"loadGroup"),Ee=i(async()=>{k===null||re.current||await Mt(k.requestGroupId,Te.current);},"refreshGroup");return {ownerName:l,query:c,clinics:d,copy:v,scopeText:fe,error:y,busy:x,searching:_,drafts:b,outcome:k,group:A,ready:xe,atCap:oe,recent:d.length===0?p.filter(N=>!b.some(Re=>Re.clinic?.id===N.id)):[],setOwnerName(N){re.current||(C(),a(N));},setQuery(N){re.current||(se.current+=1,S(false),u([]),s(N));},search:xt,addClinic(N){tt({clinic:N,freeText:null,email:""});},addFreeText(){let N=c.trim();N.length!==0&&tt({clinic:null,freeText:N,email:""});},setDraftEmail(N,Re){re.current||(C(),R(Bt=>Bt.map(sn=>sn.key===N?{...sn,email:Re}:sn)));},removeDraft(N){re.current||k!==null||(C(),R(Re=>Re.filter(Bt=>Bt.key!==N)));},submit:Nt,refreshGroup:Ee,retryCopy(){f(null),U(N=>N+1);}}}i(Xl,"useClinicBatchForm");function Jl(e){try{let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.port&&t.port!=="443")return !1;let r=t.hostname.toLowerCase();return r==="s3.amazonaws.com"||r.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(r)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(r)||r==="s3-accelerate.amazonaws.com"||r.endsWith(".s3-accelerate.amazonaws.com")||r==="s3-accelerate.dualstack.amazonaws.com"||r.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}i(Jl,"trustedSignatureUploadUrl");var ny="Signature upload failed",oy=3e4;function iy(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.floor(e.length*3/4)-t}i(iy,"base64ByteLength");async function Wi(e,t,r,o){let n=i(()=>new Error(ny),"fail"),l=iy(e);if(l<=0||r.aborted)throw n();let a=await t.initiateSignatureUpload(l);if(!a.ok||r.aborted||!Jl(a.value.uploadUrl))throw n();let c=new FormData;for(let[g,b]of Object.entries(a.value.uploadFields))c.append(g,b);c.append("file",{uri:`data:image/png;base64,${e}`,name:"signature.png",type:"image/png"});let s=new AbortController,d=i(()=>s.abort(),"onAbort");r.addEventListener("abort",d,{once:true});let u=setTimeout(d,oy);try{if(!(await(o??fetch)(a.value.uploadUrl,{method:"POST",body:c,credentials:"omit",signal:s.signal})).ok||r.aborted)throw n()}catch{throw n()}finally{clearTimeout(u),r.removeEventListener("abort",d);}let p=await t.completeSignatureUpload(a.value.uploadId);if(!p.ok||r.aborted)throw n();return {signatureId:p.value}}i(Wi,"registerRnSignature");var Xr=Object.freeze({width:360,height:120});function rc(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(rc,"blank");function nc(e,t,r,o){for(let n=-o;n<=o;n+=1)for(let l=-o;l<=o;l+=1){if(l*l+n*n>o*o+o)continue;let a=t+l,c=r+n;a<0||c<0||a>=e.width||c>=e.height||(e.pixels[c*e.width+a]=1);}}i(nc,"stamp");var sy=16384;function ay(e,t){let[r,o]=e;if(!Number.isFinite(r)||!Number.isFinite(o))return null;let n=Math.min(2*t.width,Math.max(-t.width,Math.round(r))),l=Math.min(2*t.height,Math.max(-t.height,Math.round(o)));return [n,l]}i(ay,"padPoint");function ly(e,t,r,o,n){let[l,a]=t,[c,s]=r,d=Math.abs(c-l),u=-Math.abs(s-a),p=l<c?1:-1,g=a<s?1:-1,b=d+u,R=0;for(;R<n&&(nc(e,l,a,o),R+=1,!(l===c&&a===s));){let v=2*b;v>=u&&(b+=u,l+=p),v<=d&&(b+=d,a+=g);}return R}i(ly,"line");function oc(e,t=1){let r=rc(Xr.width,Xr.height);for(let o of e){let n=[];for(let a of o){let c=ay(a,r);c!==null&&n.push(c);}if(n.length===0)continue;if(n.length===1){let[a,c]=n[0];nc(r,a,c,t);continue}let l=sy;for(let a=1;a<n.length&&l>0;a+=1)l-=ly(r,n[a-1],n[a],t,l);}return r}i(oc,"rasterizeStrokes");var cy="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",dy="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",uy="0123456789abcdefghijklmnopqrstuv",Ji=5,Zi=7,Gi=Ji+1;function py(e,t){let r=cy.indexOf(e);return r<0?0:uy.indexOf(dy.charAt(r*Zi+t))}i(py,"glyphRow");function ic(e){let t=rc(Xr.width,Xr.height),r=e.trim();if(r.length===0)return t;let o=[...r],n=4;for(;n>1&&(o.length*Gi-1)*n>t.width-8;)n-=1;let l=(o.length*Gi-1)*n,a=Math.max(0,Math.floor((t.width-l)/2)),c=Math.floor((t.height-Zi*n)/2);return o.forEach((s,d)=>{let u=a+d*Gi*n;for(let p=0;p<Zi;p+=1){let g=py(s,p);for(let b=0;b<Ji;b+=1)if((g>>Ji-1-b&1)!==0)for(let R=0;R<n;R+=1)for(let v=0;v<n;v+=1){let w=u+b*n+v,y=c+p*n+R;w<t.width&&y<t.height&&(t.pixels[y*t.width+w]=1);}}}),t}i(ic,"rasterizeTypedName");var ns=class ns{constructor(){this.bytes=[];this.acc=0;this.count=0;}writeBits(t,r){for(this.acc|=t<<this.count,this.count+=r;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8;}writeCode(t,r){let o=0;for(let n=0;n<r;n+=1)o=o<<1|t>>n&1;this.writeBits(o,r);}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};i(ns,"BitWriter");var es=ns;function ts(e,t){t<144?e.writeCode(48+t,8):t<256?e.writeCode(400+(t-144),9):t<280?e.writeCode(t-256,7):e.writeCode(192+(t-280),8);}i(ts,"writeLiteral");var Yi=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],Zl=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Ki=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],ec=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function my(e,t,r){let o=Yi.length-1;for(;Yi[o]>t;)o-=1;ts(e,257+o),Zl[o]>0&&e.writeBits(t-Yi[o],Zl[o]);let n=Ki.length-1;for(;Ki[n]>r;)n-=1;e.writeCode(n,5),ec[n]>0&&e.writeBits(r-Ki[n],ec[n]);}i(my,"writeMatch");var yy=32768,Qi=3,fy=258,tc=15,gy=64;function by(e){let t=new es;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<tc).fill(-1),o=new Int32Array(e.length).fill(-1),n=i(c=>(e[c]<<10^e[c+1]<<5^e[c+2])&(1<<tc)-1,"hashAt"),l=i(c=>{if(c+Qi>e.length)return;let s=n(c);o[c]=r[s],r[s]=c;},"insert"),a=0;for(;a<e.length;){let c=0,s=0;if(a+Qi<=e.length){let d=r[n(a)],u=0,p=Math.min(fy,e.length-a);for(;d>=0&&u<gy&&a-d<=yy;){let g=0;for(;g<p&&e[d+g]===e[a+g];)g+=1;if(g>c&&(c=g,s=a-d,g===p))break;d=o[d],u+=1;}}if(c>=Qi){my(t,c,s);for(let d=0;d<c;d+=1)l(a+d);a+=c;}else ts(t,e[a]),l(a),a+=1;}return ts(t,256),t.finish()}i(by,"deflate");function hy(e){let t=1,r=0;for(let o of e)t=(t+o)%65521,r=(r+t)%65521;return (r<<16|t)>>>0}i(hy,"adler32");var yo=null;function Ry(e){if(yo===null){yo=new Uint32Array(256);for(let r=0;r<256;r+=1){let o=r;for(let n=0;n<8;n+=1)o=o&1?3988292384^o>>>1:o>>>1;yo[r]=o>>>0;}}let t=4294967295;for(let r of e)t=yo[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(Ry,"crc32");function Sn(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(Sn,"u32");function Xi(e,t){let r=Uint8Array.from([...e].map(n=>n.charCodeAt(0))),o=new Uint8Array(r.length+t.length);return o.set(r,0),o.set(t,r.length),[...Sn(t.length),...o,...Sn(Ry(o))]}i(Xi,"chunk");var fo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function vy(e){let t="";for(let r=0;r<e.length;r+=3){let o=e[r],n=r+1<e.length?e[r+1]:0,l=r+2<e.length?e[r+2]:0,a=o<<16|n<<8|l;t+=fo.charAt(a>>18&63)+fo.charAt(a>>12&63),t+=r+1<e.length?fo.charAt(a>>6&63):"=",t+=r+2<e.length?fo.charAt(a&63):"=";}return t}i(vy,"toBase64");function rs(e){let{width:t,height:r,pixels:o}=e,n=Math.ceil(t/8)+1,l=new Uint8Array(n*r);for(let u=0;u<r;u+=1){let p=u*n;l[p]=0,l.fill(255,p+1,p+n);for(let g=0;g<t;g+=1)if(o[u*t+g]===1){let b=p+1+(g>>3);l[b]=l[b]&~(128>>(g&7));}}let a=by(l),c=new Uint8Array(2+a.length+4);c[0]=120,c[1]=1,c.set(a,2),c.set(Sn(hy(l)),2+a.length);let s=Uint8Array.from([...Sn(t),...Sn(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...Xi("IHDR",s),...Xi("IDAT",c),...Xi("IEND",new Uint8Array(0))]);return vy(d)}i(rs,"encodeSignaturePng");var Ro=2.6,lc="#111111";function Ey(e,t){let r=[];return e.forEach((o,n)=>{let l=i(a=>{let c=o[a];return [c[0]/t,c[1]/t]},"at");if(o.length===1){let[a,c]=l(0);r.push({key:`${n}-0`,cx:a,cy:c,length:0,angle:0});return}for(let a=1;a<o.length;a+=1){let[c,s]=l(a-1),[d,u]=l(a);r.push({key:`${n}-${a}`,cx:(c+d)/2,cy:(s+u)/2,length:Math.hypot(d-c,u-s),angle:Math.atan2(u-s,d-c)});}}),r}i(Ey,"strokeSegments");var Sy=8,cc=2;function Mr({onChange:e,disabled:t=false}){let r=ky(),[o,n]=useState("draw"),[l,a]=useState(""),[c,s]=useState([]),[d,u]=useState(0),p=useRef([]),g=useRef(null),b=d>0?Xr.width/d:1,R=useRef(b);R.current=b;let v=useRef(t);v.current=t,useEffect(()=>{if(o==="type"){Kn(e,l.trim().length>0?rs(ic(l)):null);return}let S=c.reduce((k,E)=>k+E.length,0);Kn(e,S>=Sy?rs(oc(c)):null);},[o,l,c,e]);let w=i(S=>{let{locationX:k,locationY:E}=S.nativeEvent;return [k*R.current,E*R.current]},"point"),y=i(()=>{let S=p.current,k=g.current;p.current=[],g.current=null,s(E=>[...E.filter(A=>A!==k),S]);},"commitStroke"),f=useMemo(()=>PanResponder.create({onStartShouldSetPanResponder:i(()=>!v.current,"onStartShouldSetPanResponder"),onMoveShouldSetPanResponder:i(()=>!v.current,"onMoveShouldSetPanResponder"),onPanResponderTerminationRequest:i(()=>false,"onPanResponderTerminationRequest"),onPanResponderGrant:i(S=>{p.current=[w(S)];},"onPanResponderGrant"),onPanResponderMove:i(S=>{let k=w(S),E=p.current[p.current.length-1];if(E!==void 0&&Math.abs(E[0]-k[0])<cc&&Math.abs(E[1]-k[1])<cc)return;p.current=[...p.current,k];let A=g.current,B=p.current;g.current=B,s(z=>[...z.filter(U=>U!==A),B]);},"onPanResponderMove"),onPanResponderRelease:i(()=>y(),"onPanResponderRelease"),onPanResponderTerminate:i(()=>y(),"onPanResponderTerminate")}),[]),x=useCallback(()=>{v.current||(p.current=[],g.current=null,s([]),a(""));},[]),h=useCallback(()=>{x(),n(S=>S==="draw"?"type":"draw");},[x]),_=i(S=>u(S.nativeEvent.layout.width),"onLayout");return jsxs(View,{style:r.container,testID:"records-signature-pad",children:[jsx(m,{style:r.label,children:o==="draw"?W.draw:W.type}),o==="type"?jsx(He,{accessibilityLabel:W.type,style:r.input,value:l,maxLength:100,editable:!t,autoComplete:"off",autoCorrect:false,onChangeText:S=>{v.current||a(S);}}):null,jsx(View,{onLayout:_,style:[r.canvas,{height:d>0?d/3:120}],accessible:true,accessibilityLabel:W.sign,accessibilityRole:"image",testID:"records-signature-canvas",...o==="draw"?f.panHandlers:{},children:o==="type"?jsx(m,{style:r.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:l.trim()}):Ey(c,b).map(S=>{let k=S.length+Ro;return jsx(View,{pointerEvents:"none",style:[r.segment,{width:k,left:S.cx-k/2,top:S.cy-Ro/2,transform:[{rotate:`${S.angle}rad`}]}]},S.key)})}),jsxs(View,{style:r.actions,children:[jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:W.clear,accessibilityState:{disabled:t},disabled:t,onPress:x,style:r.button,children:jsx(m,{style:r.buttonLabel,children:W.clear})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:o==="draw"?W.toType:W.toDraw,accessibilityState:{disabled:t},disabled:t,onPress:h,style:r.button,children:jsx(m,{style:r.buttonLabel,children:o==="draw"?W.toType:W.toDraw})})]})]})}i(Mr,"SignaturePad");function ky(){let e=V();return useMemo(()=>Ty(e),[e])}i(ky,"useStyles");function Ty(e){let{color:t,space:r,radius:o,type:n}=e;return StyleSheet.create({container:{gap:r.sm},label:{...T(e,"regular"),fontSize:n.size.body,color:t.text.primary},input:{minHeight:44,padding:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,...T(e,"regular"),fontSize:n.size.body},canvas:{width:"100%",backgroundColor:"#ffffff",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,overflow:"hidden",justifyContent:"center"},segment:{position:"absolute",height:Ro,borderRadius:Ro/2,backgroundColor:lc},typedPreview:{textAlign:"center",fontSize:32,fontStyle:"italic",fontWeight:"700",color:lc,paddingHorizontal:r.md},actions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},button:{minHeight:44,paddingHorizontal:r.md,justifyContent:"center",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,backgroundColor:t.surface},buttonLabel:{...T(e,"regular"),fontSize:n.size.body,color:t.text.primary}})}i(Ty,"makeStyles");function is(e){let{userRef:t,scopeEpoch:r}=Se();return jsx(Le,{capability:"recordsClinic",...ze(e.onClose,W.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:pe.sessionRequired}):jsx(Iy,{...Oe(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(is,"EverfurClinicRequestBatch");function Iy(e){let t=Ut(),r=_i(),o=e.controller??t,[n,l]=useState(null),a=useCallback(async()=>n===null?null:{signaturePngBase64:n},[n]),c=useCallback((w,y)=>Wi(w,o,y),[o]),s=Xl(e,o,e.batchClient??r,e.onCaptureSignature??a,e.onCaptureSignature?void 0:c),d=e.onCaptureSignature!==void 0||n!==null,u=V(),p={minHeight:44,padding:u.space.sm,borderWidth:1,borderColor:u.color.borderHairlineGreen,borderRadius:u.radius.sm,color:u.color.text.primary,backgroundColor:u.color.surface},g={color:u.color.text.primary,fontSize:u.type.size.body},b={color:u.color.text.muted,fontSize:u.type.size.bodyTight},R=i((w,y,f=false,x=w)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:x,accessibilityState:{disabled:f},disabled:f,onPress:y,style:[p,{justifyContent:"center",opacity:f?.5:1}],children:jsx(m,{style:g,children:w})}),"button"),v=s.busy?Ne.sending:s.drafts.length===0?Ne.addToContinue:s.error?Ne.tryAgain:Ne.send(s.drafts.length);return jsxs(View,{accessibilityLabel:s.outcome?Ne.resultTitle:Ne.title,style:[{backgroundColor:u.color.surface,padding:u.space.lg,gap:u.space.md,borderRadius:u.radius.lg,minHeight:120},e.style],children:[jsx(m,{accessibilityRole:"header",style:[g,{...T(u,"bold"),fontSize:u.type.size.heading}],children:s.outcome?Ne.resultTitle:Ne.title}),jsx(m,{style:g,children:e.petName}),s.outcome?jsxs(View,{style:{gap:u.space.sm},testID:"records-batch-result",children:[jsx(m,{accessibilityRole:"summary",accessibilityLiveRegion:"polite",style:g,children:s.outcome.createdCount===0?Ne.allFailed:s.outcome.failedCount>0?Ne.partial(s.outcome.createdCount,s.outcome.results.length,s.outcome.failedCount):Ne.allSent(s.outcome.createdCount)}),jsx(m,{accessibilityRole:"header",style:g,children:Ne.perClinic}),s.outcome.results.map((w,y)=>{let f=w.request?.clinicName??s.drafts[y]?.clinic?.name??w.clinicFreeText??"",x=w.created?Ne.sent:Ne.notSent;return jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:[`${f}. ${x}.`,w.created?w.request?.statusLabel:w.failureReason].filter(Boolean).join(" "),testID:`records-batch-row-${w.created?"created":"failed"}`,children:[jsx(m,{style:g,children:f}),jsx(m,{style:b,children:x}),w.created&&w.request?.statusLabel?jsx(m,{style:b,children:w.request.statusLabel}):null,!w.created&&w.failureReason?jsx(m,{style:b,children:w.failureReason}):null]},w.idempotencyKey)}),s.group?jsx(m,{accessibilityLiveRegion:"polite",style:g,children:Ne.responded(s.group.responded,s.group.total)}):null,s.group?.members.map(w=>w.statusLabel?jsx(m,{style:b,children:[w.clinicName,w.statusLabel].filter(Boolean).join(": ")},w.id):null)]}):jsxs(Fragment,{children:[jsx(m,{style:g,children:W.ownerName}),jsx(He,{accessibilityLabel:W.ownerName,style:p,value:s.ownerName,maxLength:200,editable:!s.busy,autoComplete:"name",onChangeText:s.setOwnerName}),s.drafts.map(w=>jsxs(View,{style:{gap:u.space.xs},testID:`records-batch-draft-${w.key}`,children:[jsx(m,{style:g,children:En(w)}),Cn(w)?jsxs(Fragment,{children:[jsx(m,{style:b,children:w.email.trim()?w.email:Ne.emailToAdd}),jsx(He,{accessibilityLabel:W.email,style:p,value:w.email,placeholder:W.emailPlaceholder,placeholderTextColor:u.color.text.placeholder,maxLength:320,editable:!s.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:y=>s.setDraftEmail(w.key,y)})]}):null,R(Ne.remove(En(w)),()=>s.removeDraft(w.key),s.busy)]},w.key)),jsx(m,{style:g,children:s.atCap?Ne.atCap:Ne.addClinic}),!s.atCap&&jsxs(Fragment,{children:[jsx(He,{accessibilityLabel:W.clinic,style:p,value:s.query,placeholder:W.placeholder,placeholderTextColor:u.color.text.placeholder,maxLength:200,editable:!s.busy,onChangeText:s.setQuery}),R(W.search,()=>{s.search();},s.busy||s.searching||s.query.trim().length<2),s.query.trim().length>0&&s.clinics.length===0&&!s.searching&&R(Ne.addClinic,s.addFreeText,s.busy),s.searching&&jsx(m,{accessibilityLiveRegion:"polite",style:g,children:pe.loading}),s.recent.length>0&&jsx(m,{accessibilityRole:"header",style:g,children:W.recentlyUsed}),s.recent.map(w=>jsx(View,{children:R([w.name,w.address,w.phone].filter(Boolean).join(", "),()=>s.addClinic(w),s.busy)},`recent-${w.id}`)),s.clinics.map(w=>jsx(View,{children:R([w.name,w.address,w.phone].filter(Boolean).join(", "),()=>s.addClinic(w),s.busy)},w.id))]}),jsx(m,{accessibilityRole:"header",style:g,children:W.scopeHeading}),s.copy?jsx(m,{style:g,children:s.drafts.length>0&&s.ownerName.trim()?s.scopeText??F("internalError").displayMessage:pe.consentRequired}):!s.error&&jsx(m,{accessibilityLiveRegion:"polite",style:g,children:pe.loading}),!e.onCaptureSignature&&jsx(Mr,{onChange:l,disabled:s.busy}),!d&&jsx(m,{accessibilityRole:"alert",style:g,children:W.missingSignature}),s.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:g,children:s.error.displayMessage}),!s.copy&&s.error&&R(pe.retry,s.retryCopy),R(v,()=>{s.submit();},s.busy||!s.ready||!d,Ne.sendA11y(s.drafts.length))]}),e.onClose&&R(W.cancel,e.onClose,s.busy),jsx(Ve,{})]})}i(Iy,"BatchBody");var ce=Object.freeze({scopeHeading:"What you\u2019re authorizing",scopeBody:"You\u2019re asking your pet\u2019s clinic to release their medical records to Everfur, on your behalf, so we can organize them for you.",whatWeDo:Object.freeze(["We email the clinic a signed copy of this authorization.","When records arrive, our team reviews them before they appear in your app.","You can revoke this request at any time."]),retentionNote:"We keep the records you receive so you always have them. See our Privacy Policy for how records are stored and used.",authorizeLabel:i((e,t)=>`I authorize ${t} to release ${Fe(e)}\u2019s records to Everfur.`,"authorizeLabel"),missingSignatureError:"Please add your signature before submitting.",missingDraftError:"Something went wrong with your selection. Please go back and pick the clinic again.",newClinicDirectSendNote:"We\u2019ll email this clinic directly to request your pet\u2019s medical records. Clinics usually reply within a week.",titleFreeText:"Confirm your request",titleDirectory:"Authorize records release",noEmailNote:i((e,t)=>`We don\u2019t have an email on file for ${t}. Add it so we can request ${Fe(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 Dy="value_text",mc=64,yc=512;function fc(e){return e!==null&&e.httpStatus===409&&!sr(e)}i(fc,"isFactReviewerLocked");var kn=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:Dy}),gc=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,bc=/^\d{4}-\d{2}-\d{2}$/;function hc(e){if(e==null)return "text";let t=e.trim();return gc.test(t)?"num":bc.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(hc,"inferFactValueKind");function ss(e,t){let r=t.trim(),o=hc(e);if(o==="num"&&gc.test(r)){let n=Number(r);if(Number.isFinite(n))return Object.freeze({[kn.num]:n})}return o==="date"&&bc.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[kn.date]:r}):Object.freeze(o==="bool"&&(r==="true"||r==="false")?{[kn.bool]:r==="true"}:{[kn.text]:r})}i(ss,"factCorrectionFor");var De=z.string().nullish(),vo=z.number().nullish(),Ay=z.object({collected_at:De,at:De,value:vo,unit:De,qualitative_result:De,ref_low:vo,ref_high:vo,status:De,source_clinic:De,source_doc_id:De,doc_id:De,reviewed:z.boolean().nullish()}),Oy=z.object({collected_at:De,at:De,value:vo,unit:De,qualitative_result:De,status:De}),Ly=z.object({marker_id:z.string().min(1),canonical_name:De,name:De,loinc_code:De,canonical_unit:De,unit:De,panel_name:De,panel:De,meaning_text:De,meaning:De,latest:Oy.nullish(),trajectory:De,points:z.array(Ay).optional()}),Vy=z.object({total_markers:z.number().int().nonnegative(),in_range_count:z.number().int().nonnegative(),out_of_range_count:z.number().int().nonnegative(),unknown_count:z.number().int().nonnegative()}),qy=z.object({markers:z.array(Ly).optional(),summary:Vy.nullish(),disclaimer:z.string().optional(),featured_marker_id:De});function zy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(zy,"isObject");function Rc(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(Rc,"withheldMarkers");function vc(e,t){let r=zy(t)?t:{},o=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return Rc(o);let n=qy.safeParse(r);if(!n.success)return Rc(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"),c=(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(c),summary:l.summary?Object.freeze({totalMarkers:l.summary.total_markers,inRangeCount:l.summary.in_range_count,outOfRangeCount:l.summary.out_of_range_count,unknownCount:l.summary.unknown_count}):null,disclaimer:l.disclaimer??"",featuredMarkerId:l.featured_marker_id??null})}i(vc,"mapRecordMarkers");var Fy=z.string().min(1).refine(e=>e.startsWith("https://")),Ny=z.object({source_doc_id:z.string().min(1),file_name:z.string().nullish(),doc_format:z.string().nullish(),byte_size:z.number().int().nonnegative().nullish(),received_at:z.string().nullish(),download_url:Fy,expires_in_seconds:z.number().int().nonnegative().nullish()}),My=z.object({items:z.array(z.unknown()).optional()});function wc(e){let t=My.safeParse(e);if(!t.success)return null;let r=[];for(let o of t.data.items??[]){let n=Ny.safeParse(o);n.success&&r.push(Object.freeze({sourceDocId:n.data.source_doc_id,fileName:n.data.file_name??null,docFormat:n.data.doc_format??null,byteSize:n.data.byte_size??null,receivedAt:n.data.received_at??null,downloadUrl:n.data.download_url,expiresInSeconds:n.data.expires_in_seconds??0}));}return Object.freeze(r)}i(wc,"mapRequestDocuments");var By=z.string().min(1).refine(e=>e.startsWith("https://")),Tn=z.string().nullish(),Hy=z.object({share_id:z.string().min(1),share_url:z.string().min(1),expires_at:Tn}),Uy=z.object({shares:z.array(z.object({share_id:z.string().min(1),expires_at:Tn,created_at:Tn,view_count:z.number().int().nonnegative().nullish(),last_viewed_at:Tn})).optional()}),jy=z.object({download_url:By,expires_at:Tn});function $y(e,t){let r=e.trim();if(r.length===0)return null;try{let o=/^[a-z][a-z0-9+.-]*:/i.test(r)?new URL(r):t!==void 0?new URL(r,t):null;return o===null||o.protocol!=="https:"?null:o.toString()}catch{return null}}i($y,"resolveShareUrl");function xc(e,t){let r=Hy.safeParse(e);if(!r.success)return null;let o=$y(r.data.share_url,t);return o===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:o,expiresAt:r.data.expires_at??null})}i(xc,"mapRecordShareLink");function Cc(e){let t=Uy.safeParse(e);return t.success?Object.freeze((t.data.shares??[]).map(r=>Object.freeze({shareId:r.share_id,expiresAt:r.expires_at??null,createdAt:r.created_at??null,viewCount:r.view_count??0,lastViewedAt:r.last_viewed_at??null}))):null}i(Cc,"mapRecordShareList");function Ec(e){let t=jy.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(Ec,"mapRecordPdfLink");var Wy=z.object({signatures:z.array(z.object({signature_id:z.string().min(1),preview_url:z.string().min(1).refine(e=>e.startsWith("https://")),created_at:z.string().nullish()})).optional()});function Sc(e){let t=Wy.safeParse(e);return t.success?Object.freeze((t.data.signatures??[]).map(r=>Object.freeze({signatureId:r.signature_id,previewUrl:r.preview_url,createdAt:r.created_at??null}))):null}i(Sc,"mapSignatureSuggestions");var M=z.string().nullish(),_n=z.number().nullish(),Gy=z.object({at:M,value:_n,unit:M,qualitative_result:M,ref_low:_n,ref_high:_n,status:M,doc_id:M}),Yy=z.object({marker_id:z.string(),name:z.string(),loinc_code:M,unit:M,panel:M,meaning:M,latest:z.object({at:M,value:_n,unit:M,qualitative_result:M,status:M}).nullish(),trajectory:M,points:z.array(Gy).optional()}),Ky=z.object({encounter_id:z.string(),date:M,type:M,clinic_name:M,veterinarian:M,doc_id:M}),Qy=z.object({note_id:z.string(),encounter_id:M,observed_on:M,sections:z.array(z.object({section:z.string(),text:z.string()})).optional()}),Xy=z.object({exam_id:z.string(),encounter_id:M,observed_on:M,doc_id:M,systems:z.record(z.object({finding_status:M,finding:M})).optional()}),Jy=z.object({has_lab_history:z.boolean().optional(),has_vaccination_history:z.boolean().optional(),has_weight_history:z.boolean().optional(),has_vitals_history:z.boolean().optional(),has_physical_exam_history:z.boolean().optional(),has_procedure_history:z.boolean().optional(),has_genetic_history:z.boolean().optional(),has_reproductive_history:z.boolean().optional(),has_parasite_prevention_history:z.boolean().optional(),earliest_record_at:M,latest_record_at:M,documents_ingested:z.number().int().nonnegative().optional(),documents_in_review:z.number().int().nonnegative().optional(),entities_pending_review:z.record(z.number().int().nonnegative()).optional(),held_total:z.number().int().nonnegative().optional()}),Zy=z.object({conflict_id:z.string(),entity_type:z.string(),field:M,severity:M,candidates:z.array(z.object({value:z.string(),source_doc_id:M,doc_id:M,collected_at:M})).optional()}),ef=z.object({lab_results:z.array(Yy).optional(),encounters:z.array(Ky).optional(),clinician_notes:z.array(Qy).optional(),physical_exams:z.array(Xy).optional(),completeness:Jy.nullish(),conflicts:z.array(Zy).optional()}),tf=z.object({visits:z.array(z.object({visit_id:z.string(),visit_date:M,veterinarian:M,summary:M,doc_id:M})),vaccines:z.array(z.object({vaccine_id:z.string(),product:M,lot:M,administered_on:M,expires_on:M,doc_id:M})),weights:z.array(z.object({weight_id:z.string(),observed_on:M,weight_kg:_n,doc_id:M})),medications:z.array(z.object({medication_id:z.string(),drug_name:M,dose:M,route:M,frequency:M,sig:M,rx_number:M,started_on:M,stopped_on:M,doc_id:M})),disclaimer:z.string().optional()}),rf=z.object({document:ei,contributions:z.array(Zo),contribution_count:z.number().int().nonnegative().optional()});function ls(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ls,"isObject");function cs(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(cs,"petOf");function as(e,t){return Object.freeze({petRef:e,available:false,withheld:t,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(as,"emptyDepth");function nf(e,t){let r=ls(t)?t:{},o=cs(r,e);if(r.withheld===true)return as(o,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(s=>s in r))return as(o,false);let l=ef.safeParse(r);if(!l.success)return as(o,true);let a=l.data,c=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(c))}))),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(d=>Object.freeze({section:d.section,text:d.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(([d,u])=>Object.freeze({system:d,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(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(nf,"mapRecordDepth");function kc(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(kc,"withheldTimeline");function of(e,t){let r=ls(t)?t:{},o=cs(r,e);if(r.withheld===true)return kc(o);let n=tf.safeParse(r);if(!n.success)return kc(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})),c=l.vaccines.map(u=>Object.freeze({vaccineId:u.vaccine_id,product:u.product??null,lot:u.lot??null,administeredOn:u.administered_on??null,expiresOn:u.expires_on??null,docId:u.doc_id??null})),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})),d=l.medications.map(u=>Object.freeze({medicationId:u.medication_id,drugName:u.drug_name??null,dose:u.dose??null,route:u.route??null,frequency:u.frequency??null,sig:u.sig??null,rxNumber:u.rx_number??null,startedOn:u.started_on??null,stoppedOn:u.stopped_on??null,docId:u.doc_id??null}));return Object.freeze({petRef:o,withheld:false,isEmpty:a.length===0&&c.length===0&&s.length===0&&d.length===0,visits:Object.freeze(a),vaccines:Object.freeze(c),weights:Object.freeze(s),medications:Object.freeze(d),disclaimer:l.disclaimer??""})}i(of,"mapRecordsTimeline");function sf(e,t){let r=ls(t)?t:{},o=cs(r,e),n=i(()=>Object.freeze({petRef:o,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(r.withheld===true)return n();let l=rf.safeParse(r);if(!l.success)return n();let a=Object.freeze(l.data.contributions.map(ti));return Object.freeze({petRef:o,withheld:false,document:ri(l.data.document),contributions:a,contributionCount:l.data.contribution_count??a.length})}i(sf,"mapDocumentContributions");var af="/widget/v1/records/pets";function Tc(e){let t=e.funnel??vr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((s,d)=>typeof s=="string"&&s.length>0&&!wr(s)&&[...s].length<=d,"segment"),o=i(async(s,d,u,p)=>{if(!r(d,gt))return pr();let g=await t.send(s,{method:"GET",path:u});if(!g.ok)return g;let b=p(g.value);return b.petRef===d?Pe(b):H(F("internalError",{retryable:false}))},"read"),n=i(s=>`${af}/${encodeURIComponent(s)}`,"pet"),l=i(s=>`${n(s)}/everfur_record`,"record"),a=i(async(s,d,u)=>{let p=await t.send(s,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!p.ok)return p;let g=u(p.value);return g===null?H(F("internalError",{retryable:false})):Pe(g)},"parsed"),c=i((s,d)=>!r(s.entityType,mc)||!r(s.canonicalKey,yc)||s.idempotencyKey!==void 0&&!r(s.idempotencyKey,cn)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:s.entityType,canonical_key:s.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...s.idempotencyKey!==void 0?{idempotency_key:s.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(s=>o("records.depth.record",s,`${n(s)}/record`,d=>nf(s,d)),"getRecordDepth"),getTimeline:i(s=>o("records.depth.timeline",s,`${n(s)}/timeline`,d=>of(s,d)),"getTimeline"),getDocumentContributions(s,d){return r(d,64)?o("records.depth.contributions",s,`${n(s)}/documents/${encodeURIComponent(d)}/contributions`,u=>sf(s,u)):pr()},getMarkers:i(s=>o("records.depth.markers",s,`${n(s)}/markers`,d=>vc(s,d)),"getMarkers"),createShare(s){return r(s,gt)?a("records.share.create",{method:"POST",path:`${l(s)}/share`},d=>xc(d,e.apiBaseUrl)):pr()},listShares(s){return r(s,gt)?a("records.share.list",{method:"GET",path:`${l(s)}/shares`},Cc):pr()},async revokeShare(s,d){if(!r(s,gt)||!r(d,64))return pr();let u=await t.send("records.share.revoke",{method:"DELETE",path:`${l(s)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return u.ok?Pe(void 0):u},getPdfLink(s){return r(s,gt)?a("records.pdf.link",{method:"GET",path:`${l(s)}/pdf-link`},Ec):pr()},async editFact(s,d){let u=r(s,gt)?c(d,d.correctedFields):null;if(u===null)return pr();let p=await t.send("records.fact.edit",{method:"POST",path:`${l(s)}/facts/edit`,body:u},{idempotent:false,maxAttempts:1});return p.ok?Pe(void 0):p},async removeFact(s,d){let u=r(s,gt)?c(d):null;if(u===null)return pr();let p=await t.send("records.fact.remove",{method:"POST",path:`${l(s)}/facts/remove`,body:u},{idempotent:false,maxAttempts:1});return p.ok?Pe(void 0):p},listRequestDocuments(s){return r(s,64)?a("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(s)}/documents`},wc):pr()},listAuthorizationSignatures:i(()=>a("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},Sc),"listAuthorizationSignatures")}}i(Tc,"createRecordsDepthClient");function pr(){return Promise.resolve(H(F("validationFailed",{retryable:false})))}i(pr,"invalid");function mr(){let{runtime:e,userRef:t,scopeEpoch:r}=Se();return useMemo(()=>{let{services:o}=e.registry;return Tc({auth:o.authFor(t),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,t,r])}i(mr,"useEverfurRecordsDepthClient");function Gt(e,t,r,o=""){let n=mr(),{userRef:l}=Se(),a=$n(e),c=useMemo(()=>({}),[n,e,o,a]),[s,d]=useState({scope:c,value:null,error:null,loading:true}),u=useRef(0),p=useCallback(async()=>{let y=u.current+=1;if(d({scope:c,value:null,error:null,loading:true}),l===null){d({scope:c,value:null,error:null,loading:false});return}let f=await t(n,e);y===u.current&&(f.ok?d({scope:c,value:f.value,error:null,loading:false}):d({scope:c,value:null,error:f.error,loading:false}));},[n,e,t,c,l]);useEffect(()=>(p(),()=>{u.current+=1;}),[p]);let g=s.scope===c?s:{value:null,error:null,loading:true},b=useCallback(()=>{p();},[p]),R=g.error===null||g.error.httpStatus!==404,v=R?g.error:null,w=g.loading?"loading":v!==null?"error":g.value===null?"empty":g.value.withheld?"populated":r(g.value)?"empty":"populated";return useMemo(()=>({status:w,value:g.value,error:v,available:R,refresh:b}),[w,g.value,v,R,b])}i(Gt,"useRecordsDepthRead");function Tr(e){return e!==null&&e.httpStatus===404}i(Tr,"isDarkRouteError");var pf=i((e,t)=>e.getMarkers(t),"readMarkers"),mf=i(e=>e.markers.length===0,"markersEmpty");function us(e){let t=Gt(e,pf,mf);return useMemo(()=>{let r=t.available&&t.value!==null&&!t.value.withheld?t.value:null;return {status:t.status,markers:r,available:t.available,error:t.error,refresh:t.refresh}},[t])}i(us,"useRecordsMarkers");var yf=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Ic(e){let{clinic:t,controller:r,depthClient:o,capture:n,onCreated:l}=e,a=t.clinic?.name??t.freeText??"",c=t.clinic===null,[s,d]=useState(false),[u,p]=useState(e.ownerName),[g,b]=useState(t.email),[R,v]=useState(false),[w,y]=useState(null),[f,x]=useState(null),[h,_]=useState(0),[S,k]=useState(null),[E,A]=useState(false),[B,z]=useState(null),[U,j]=useState([]),[re,se]=useState(null),[Te,ee]=useState(false),I=useRef(false),D=useRef(true),C=useRef(ar()),L=useRef(null);useEffect(()=>(D.current=true,()=>{D.current=false,L.current=null;}),[r]),useEffect(()=>{let Ee=true;return y(null),L.current=null,r.getAuthorizationCopy().then(N=>{Ee&&(N.ok?(y(N.value),x(null)):x(N.error));}).catch(()=>{Ee&&x(F("internalError"));}),()=>{Ee=false;}},[r,h]),useEffect(()=>{if(o===void 0)return;let Ee=true;return o.listAuthorizationSignatures().then(N=>{Ee&&(N.ok?j(N.value):Tr(N.error)||j([]));}).catch(()=>{}),()=>{Ee=false;}},[o]);let X=xn(t.clinic),fe=g.trim().toLowerCase(),Be=yf.test(fe),oe=X&&(R||fe.length>0)&&!Be?ce.emailRequired:null,xe=w?wn(w,u.trim(),Fe(e.petName),a):null,xt=e.hostCapture===true||Te||re!==null,tt=!!(s&&w&&xe&&u.trim()&&a&&xt&&(!X||Be)),Nt=useCallback(async()=>{if(!(I.current||B!==null||!w||!xe)){if(!a){k(ce.missingDraftError);return}if(X&&!Be){v(true),k(ce.emailRequired);return}if(!(!s||!u.trim())){I.current=true,A(true),k(null);try{if(L.current===null){let N=re!==null?{signatureId:re}:await n();if(!D.current)return;if(N===null){k(ce.missingSignatureError);return}let Re=t.clinic&&(!X||t.clinic.emailStatus==="none")?{clinicId:t.clinic.id}:{clinicFreeText:a};L.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:w.authorizationVersion,...Re,...X?{clinicEmail:fe}:{},...N.signatureId!==void 0?{signatureId:N.signatureId}:{signaturePngBase64:N.signaturePngBase64},idempotencyKey:C.current()};}let Ee=await r.createClinicRequest(L.current);if(!D.current)return;if(!Ee.ok){k(Ee.error.displayMessage);return}if(Ee.value.petRef!==e.petRef){k(F("internalError").displayMessage);return}z(Ee.value),L.current=null,l?.(Ee.value);}catch{D.current&&k(F("internalError").displayMessage);}finally{I.current=false,D.current&&A(false);}}}},[s,n,t.clinic,a,r,w,B,e.petRef,X,fe,l,u,re,xe,Be]),Mt=useCallback(()=>{L.current=null,k(null);},[]);return {title:c?ce.titleFreeText:ce.titleDirectory,clinicName:a,isFreeText:c,authorized:s,ownerName:u,email:g,emailError:oe,needsEmail:X,directoryClinicNoEmail:X&&t.clinic!==null,copy:w,copyError:f,scope:xe,error:S,busy:E,created:B,ready:tt,signatures:U,reuseSignatureId:re,hasSignature:xt,setAuthorized(Ee){I.current||(Mt(),d(Ee));},setOwnerName(Ee){I.current||(Mt(),p(Ee));},setEmail(Ee){I.current||(Mt(),v(false),b(Ee));},setSigned(Ee){I.current||(Mt(),ee(Ee),Ee&&se(null));},pickReuseSignature(Ee){I.current||(Mt(),se(Ee));},retryCopy(){x(null),_(Ee=>Ee+1);},submit:Nt}}i(Ic,"useRecordsConsentForm");function ys(e){let{userRef:t,scopeEpoch:r}=Se();return jsx(Le,{capability:"recordsClinic",style:e.style,...ze(e.onBack,Ye),children:t===null?jsx(m,{accessibilityRole:"alert",children:pe.sessionRequired}):jsx(Rf,{...Oe(e,["onCreated","onNavigate","onBack"])},JSON.stringify([t,r,e.petRef,e.clinic.key]))})}i(ys,"EverfurRecordsConsent");function Rf({petRef:e,petName:t,clinic:r,ownerName:o,onCaptureSignature:n,onCreated:l,controller:a,onNavigate:c,onBack:s,style:d}){let u=ue(),p=vf(),g=V(),b=Ut(),R=mr(),[v,w]=useState(null),[y,f]=useState("draw"),x=useCallback(async()=>v===null?null:{signaturePngBase64:v},[v]),h=Ic({petRef:e,petName:t,ownerName:o??"",clinic:r,controller:a??b,depthClient:R,capture:n?()=>n({petRef:e,petName:Fe(t),ownerName:h.ownerName,clinicName:h.clinicName,authorizationVersion:h.copy?.authorizationVersion??"",scopeText:h.scope??"",signal:new AbortController().signal}):x,hostCapture:n!==void 0,onCreated:i(E=>{l?.(E),c?.({name:"dashboard"});},"onCreated")}),_=useRef(h);_.current=h;let S=useCallback(E=>{w(E),_.current.setSigned(E!==null);},[]),k=h.busy;return jsxs(View,{style:[u.root,d],children:[jsx(Ke,{title:h.title,onBack:s,testID:"records-consent-header"}),jsxs(KeyboardAvoidingView,{behavior:"padding",style:u.body,children:[jsxs(ScrollView,{contentContainerStyle:p.content,keyboardShouldPersistTaps:"handled",testID:"records-consent",children:[jsxs(View,{style:p.scopeCard,accessibilityRole:"summary",children:[jsx(m,{style:p.scopeHeading,accessibilityRole:"header",children:ce.scopeHeading}),jsx(m,{style:p.scopeBody,children:ce.scopeBody}),jsx(View,{style:p.bullets,children:ce.whatWeDo.map(E=>jsxs(View,{style:p.bulletRow,children:[jsx(m,{style:p.check,children:"\u2713"}),jsx(m,{style:p.bulletText,children:E})]},E))}),jsx(View,{style:p.retentionRow,children:jsx(m,{style:p.retentionText,children:ce.retentionNote})}),h.copy&&h.scope?jsx(m,{style:p.serverScope,testID:"records-consent-scope",children:h.scope}):h.copyError?jsxs(Fragment,{children:[jsx(m,{style:u.errorText,accessibilityRole:"alert",children:h.copyError.displayMessage}),jsx(J,{label:pe.retry,kind:"outline",onPress:h.retryCopy,testID:"records-consent-copy-retry"})]}):jsx(m,{style:u.muted,accessibilityLiveRegion:"polite",children:pe.loading})]}),jsxs(Pressable,{onPress:()=>h.setAuthorized(!h.authorized),accessibilityRole:"checkbox",accessibilityState:{checked:h.authorized},accessibilityLabel:ce.authorizeLabel(t,h.clinicName),hitSlop:6,style:[p.toggle,h.authorized?p.toggleChecked:null],testID:"records-authorize-toggle",children:[jsx(View,{style:[p.box,h.authorized?p.boxChecked:null],accessibilityElementsHidden:true,importantForAccessibility:"no",children:h.authorized?jsx(m,{style:p.boxCheck,children:"\u2713"}):null}),jsx(m,{style:p.toggleLabel,children:ce.authorizeLabel(t,h.clinicName)})]}),jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:ce.fullName}),jsx(He,{accessibilityLabel:ce.fullName,style:u.field,value:h.ownerName,placeholder:ce.fullNamePlaceholder,placeholderTextColor:g.color.text.placeholder,maxLength:200,editable:!k,autoComplete:"name",autoCapitalize:"words",onChangeText:h.setOwnerName,testID:"records-consent-owner-name"})]}),h.needsEmail?jsxs(View,{style:p.block,testID:"records-consent-email-block",children:[h.directoryClinicNoEmail?jsx(View,{style:u.cautionNote,testID:"records-consent-no-email-note",children:jsx(m,{style:u.cautionNoteText,children:ce.noEmailNote(t,h.clinicName)})}):null,jsx(m,{style:u.fieldLabel,children:ce.emailLabel}),jsx(He,{accessibilityLabel:ce.emailLabel,style:u.field,value:h.email,placeholder:ce.emailPlaceholder,placeholderTextColor:g.color.text.placeholder,maxLength:320,editable:!k,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:h.setEmail,testID:"records-consent-clinic-email"}),h.emailError?jsx(m,{style:u.errorText,accessibilityRole:"alert",children:h.emailError}):null,jsx(m,{style:u.muted,testID:"records-consent-review-note",children:ce.newClinicDirectSendNote})]}):null,n?null:jsxs(View,{style:p.signatureBlock,children:[h.signatures.length>0?jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:ce.reuseSignature}),jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:p.gallery,children:h.signatures.map(E=>{let A=h.reuseSignatureId===E.signatureId;return jsx(Pressable,{onPress:()=>h.pickReuseSignature(A?null:E.signatureId),accessibilityRole:"button",accessibilityLabel:A?ce.reuseTileSelectedA11y:ce.reuseTileA11y,style:[p.tile,A?p.tileSelected:null],testID:`records-consent-reuse-${E.signatureId}`,children:jsx(Image,{source:{uri:E.previewUrl},style:p.tileImage,resizeMode:"contain",accessibilityIgnoresInvertColors:true})},E.signatureId)})}),jsx(m,{style:u.muted,children:ce.reuseHint})]}):null,jsx(View,{style:p.signatureHeader,children:jsx(m,{style:u.fieldLabel,children:y==="type"?ce.signType:ce.signDraw})}),jsx(Mr,{onChange:S,disabled:k}),jsx(Pressable,{onPress:()=>f(E=>E==="draw"?"type":"draw"),accessibilityRole:"button",accessibilityLabel:y==="draw"?ce.toTypeA11y:ce.toDraw,style:p.modeToggle,testID:"records-consent-sign-mode-toggle",children:jsx(m,{style:p.modeToggleText,children:y==="draw"?ce.toType:ce.toDraw})}),jsx(m,{style:u.muted,children:ce.signatureHint(h.clinicName)})]}),h.error?jsx(View,{style:u.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:jsx(m,{style:u.errorText,children:h.error})}):null,h.created?jsx(m,{accessibilityLiveRegion:"polite",style:u.bodyText,children:h.created.statusLabel||pe.records}):null]}),jsx(View,{style:p.footer,children:jsx(J,{label:k?ce.submitting:ce.submit,accessibilityLabel:ce.submitA11y,disabled:!h.ready,busy:k,onPress:()=>{h.submit();},style:p.submit,testID:"records-consent-submit"})})]}),jsx(Ve,{})]})}i(Rf,"ConsentBody");function vf(){let e=V();return useMemo(()=>wf(e),[e])}i(vf,"useLocalStyles");function wf(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,a=i((c,s,d,u="regular")=>({...T(e,u),fontSize:c,lineHeight:Math.round(c*s),color:d}),"text");return StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xl+r.xs,gap:r.lg+r.xs/2},scopeCard:{borderRadius:o.lg-r.xs/2,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md},scopeHeading:{...a(n.size.body+1,n.lineHeight.snug,t.brandInk,"bold")},scopeBody:a(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),bullets:{gap:r.sm},bulletRow:{flexDirection:"row",alignItems:"flex-start",gap:r.sm},check:{...a(n.size.body,n.lineHeight.normal,t.brandInk,"bold")},bulletText:{flex:1,...a(n.size.bodyTight,n.lineHeight.normal,t.text.primary)},retentionRow:{paddingTop:r.xs,borderTopWidth:1,borderTopColor:t.borderHairlineGreen},retentionText:a(n.size.tiny,n.lineHeight.normal,t.text.muted),serverScope:{...a(n.size.bodyTight,n.lineHeight.relaxed,t.text.secondary),paddingTop:r.xs},toggle:{flexDirection:"row",alignItems:"flex-start",gap:r.md,borderRadius:o.lg-r.xs,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2},toggleChecked:{borderColor:t.brandInk,backgroundColor:t.brandSoft},box:{width:r.xl,height:r.xl,borderRadius:o.xs+1,borderWidth:1.6,borderColor:t.brandInk,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},boxChecked:{backgroundColor:t.brandInk},boxCheck:{...a(n.size.body,n.lineHeight.tight,t.surface,"bold")},toggleLabel:{flex:1,...a(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"bold")},block:{gap:r.sm},signatureBlock:{gap:r.sm},gallery:{gap:r.sm,paddingVertical:r.xs},tile:{width:r.xxl*3+r.lg,height:r.xxl+r.lg+r.sm,borderRadius:o.sm,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,overflow:"hidden"},tileSelected:{borderColor:t.brandInk,borderWidth:2},tileImage:{width:"100%",height:"100%"},signatureHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},modeToggle:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},modeToggleText:{...a(n.size.bodyTight,n.lineHeight.snug,t.linkInk,"bold"),textDecorationLine:"underline"},footer:{paddingHorizontal:r.lg,paddingTop:r.md,paddingBottom:r.xxl,borderTopWidth:l,borderTopColor:t.borderHairlineGreen,backgroundColor:t.background},submit:{minHeight:r.xxl+r.lg+r.xs+r.xs/2}})}i(wf,"makeLocalStyles");function xo(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(xo,"markerStatusTone");function Cf(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(Cf,"markerStatusSpoken");function Ef(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(Ef,"rangePhrase");function Co(e,t){let r=t?` ${t}`:"";return e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}${r}`:e.refLow!==null?`\u2265 ${e.refLow}${r}`:e.refHigh!==null?`\u2264 ${e.refHigh}${r}`:"-"}i(Co,"formatReferenceRange");function Vc(e,t){let r=t.reviewed?", reviewed by our team":"",o=t.sourceClinic?`, from ${t.sourceClinic}`:"";return `${Y(t.at)}: ${kt(t.value,e.unit,t.qualitativeResult)}, ${Cf(t.status)}${Ef(t)}${o}${r}`}i(Vc,"markerPointSpoken");function Xe(e){return e?.trim()||"my pet"}i(Xe,"lead");function qc(e){let t=e.trim();return /[.!?]$/.test(t)?t:`${t}.`}i(qc,"clause");function zc(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`I'm looking at ${Xe(e)}'s ${r}`],n=[t.latestValueText?.trim(),t.statusText?.trim(),t.trajectoryText?.trim()].filter(Boolean).join(", ");return o[0]+=n?`: ${n}.`:".",t.meaningText?.trim()&&o.push(qc(t.meaningText)),o.push(`What does this trend tell me, and should I do anything differently for ${Xe(e)}?`),{prompt:o.join(" "),entityRef:{type:"marker",id:t.markerId,payload:{marker:r,...t.statusText?.trim()?{status:t.statusText.trim()}:{}}}}}i(zc,"buildMarkerAskPrompt");function Fc(e,t,r){let{totalMarkers:o,inRangeCount:n,outOfRangeCount:l,unknownCount:a}=t;if(o===0)return {prompt:`I'm looking at ${Xe(e)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${Xe(e)}?`,entityRef:{type:"marker_summary",id:r,payload:{total:0}}};let c=a>0?`, ${a} without a reference range`:"";return {prompt:`I'm looking at ${Xe(e)}'s lab markers: ${o} total, ${n} in range, ${l} out of range${c}. What should I focus on?`,entityRef:{type:"marker_summary",id:r,payload:{total:o,inRange:n,outOfRange:l,unknown:a}}}}i(Fc,"buildMarkerSummaryAskPrompt");function Nc(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`${r}: ${t.valueText.trim()}`];t.collectedAt?.trim()&&o.push(`collected ${t.collectedAt.trim()}`),t.sourceClinic?.trim()&&o.push(`from ${t.sourceClinic.trim()}`),t.referenceText?.trim()&&o.push(`reference range ${t.referenceText.trim()}`),t.flagged&&o.push(`flagged ${t.flagged}`);let n={marker:r};return t.flagged&&(n.status=t.flagged),t.reviewed!==void 0&&(n.reviewed=t.reviewed),{prompt:`I'm looking at ${Xe(e)}'s ${o.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:t.entityId,payload:n}}}i(Nc,"buildMarkerReadingAskPrompt");function Eo(e,t,r){let o=t.clinicName?.trim(),n=t.heldItemCount??0,l=n>0?`, ${n} fact${n===1?"":"s"} being verified`:"";return {prompt:`I'm looking at ${Xe(e)}'s records request${o?` to ${o}`:""}, status: ${t.statusLabel.trim()}${l}. What does this status mean, and what happens next?`,entityRef:{type:"records_request",id:r,payload:{status:t.status,held:n,...o?{clinic:o}:{}}}}}i(Eo,"buildRecordsRequestAskPrompt");var Sf=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function fs(e,t,r,o){let n=t.entityTypeLabel.trim()||"record",l=t.title.trim()||n,a=t.detail?.trim();return {prompt:`I'm looking at ${Xe(e)}'s ${n.toLowerCase()}: ${l}${a?`, ${a}`:""}. What does this mean, and what should I keep on top of for ${Xe(e)}?`,entityRef:{type:Sf[r]??r,id:o,payload:{kind:n,title:l,...a?{detail:a}:{}}}}}i(fs,"buildEntityRowAskPrompt");function Mc(e,t,r){let o=t.filter(a=>a.label.trim()),n={type:"upcoming_care",id:r};if(o.length===0)return {prompt:`I'm looking at ${Xe(e)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${Xe(e)} be on?`,entityRef:n};let l=[...o].sort((a,c)=>(a.tone==="overdue"?0:1)-(c.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 ${Xe(e)}'s upcoming care: ${l.join(", ")}. What should I prioritize for ${Xe(e)}, and how do I stay on top of these?`,entityRef:n}}i(Mc,"buildUpcomingCareAskPrompt");function Bc(e,t,r){let o=[`I'm looking at ${Xe(e)}'s physical exam${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`],n=t.abnormal.filter(l=>l.system.trim());return n.length>0?(o.push(`Abnormal: ${n.slice(0,6).map(l=>`${l.system.trim()}: ${l.finding.trim()}`).join("; ")}.`),o.push(`What do these findings mean, and what should I follow up on for ${Xe(e)}?`)):o.push(`Everything examined came back normal. What does this tell me about ${Xe(e)}'s health?`),{prompt:o.join(" "),entityRef:{type:"physical_exam",id:r}}}i(Bc,"buildPhysicalExamAskPrompt");function Hc(e,t,r){let o=[`I'm looking at ${Xe(e)}'s visit notes${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`];for(let n of t.sections.filter(l=>l.text.trim()).slice(0,3))o.push(`${n.label.trim()||"Note"}: ${qc(n.text)}`);return o.push(`Can you summarize what happened and what I should follow up on for ${Xe(e)}?`),{prompt:o.join(" "),entityRef:{type:"visit",id:r}}}i(Hc,"buildVisitNoteAskPrompt");function Uc(e,t,r){let o=t.scopeLabel.trim()||"a detail",n=t.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 ${Xe(e)}'s documents disagree on ${o}: ${l}. Which is likely correct, and what should I ask my vet?`,entityRef:{type:"conflict",id:r,payload:{field:o,severity:t.severity,values:n.map(a=>a.value.trim()).join(" | ")}}}}i(Uc,"buildConflictAskPrompt");function Pn(e){return e!==void 0}i(Pn,"canUploadRecords");function gs(e,t){return e??t?.version??""}i(gs,"resolveConsentVersion");function Hr(e,t){return gs(e,t).length>0}i(Hr,"canGrantConsent");function _r(e,t){return e.denialReason==="consent_required"?t?{kind:"consent_required"}:{kind:"consent_unavailable"}:e.denialReason==="pet_not_found"?{kind:"pet_not_found",error:F("petNotFound",{retryable:false})}:e.denialReason==="entitlement"?{kind:"error",error:F("accessDenied")}:e.denialReason==="session_required"?{kind:"session_required"}:e.withheld?{kind:"withheld"}:e.error===null?{kind:"withheld"}:{kind:"error",error:e.error}}i(_r,"selectErrorView");function So(e){let t=e.clinicName?.trim()??"";return t.length>0?t:e.source==="owner_provided"?jc.ownerUpload:jc.clinicRequest}i(So,"selectRequestTitle");var jc=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function bs(e){let t=[...e].sort((r,o)=>r.updatedAt!==o.updatedAt?r.updatedAt>o.updatedAt?-1:1:r.createdAt!==o.createdAt?r.createdAt>o.createdAt?-1:1:0);return Object.freeze(t)}i(bs,"selectRequestList");function Ur(e){let t=e.actionNeededLabel?.trim()??"";return t.length>0?t:e.statusLabel}i(Ur,"selectPrimaryLabel");function ko(e){if(e.showClinicPhone!==true)return null;let t=e.clinicPhone?.trim()??"";return t.length===0?null:{phone:t,dial:`tel:${t.replace(/[^+\d]/g,"")}`,clinicName:e.clinicName?.trim()||null}}i(ko,"selectClinicCall");function $c(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($c,"selectRequestStatusTone");var ht=200,Gc=16;function Tf(e,t){let r=e.inRangeCount+e.outOfRangeCount+e.unknownCount;if(!Number.isFinite(r)||r<=0)return [];let o=[{key:"in_range",color:t.inRange,count:e.inRangeCount},{key:"out_of_range",color:t.outOfRange,count:e.outOfRangeCount},{key:"unknown",color:t.unknown,count:e.unknownCount}],n=0,l=[];for(let a of o){if(!(a.count>0))continue;let c=a.count/r*360;if(!Number.isFinite(c))return null;l.push({key:a.key,color:a.color,startDeg:n,sweepDeg:c}),n+=c;}return l}i(Tf,"buildRingSegments");function Kc({summary:e,onAsk:t,testID:r}){let o=Pf(),n=V(),{totalMarkers:l,inRangeCount:a,outOfRangeCount:c,unknownCount:s}=e,d=useMemo(()=>Tf(e,{inRange:n.color.success,outOfRange:n.color.danger,unknown:n.color.text.muted}),[e,n]),u=d!==null&&d.length>0;return jsxs(View,{style:o.card,accessibilityRole:"summary",testID:r,children:[jsx(m,{style:o.title,children:jt.title}),jsx(View,{style:o.ringRow,accessible:true,accessibilityRole:"image",accessibilityLabel:jt.a11y(l,a,c,s),children:jsxs(View,{style:o.ringWrap,children:[jsx(View,{style:o.track}),d===null?null:d.map(p=>jsx(_f,{segment:p,styles:o},p.key)),jsxs(View,{style:o.center,pointerEvents:"none",children:[jsx(m,{style:o.centerCount,children:l}),jsx(m,{style:o.centerLabel,children:l===1?jt.marker:jt.markers})]})]})}),u||d===null?jsxs(View,{style:o.badges,children:[jsx(hs,{count:c,label:jt.outOfRange,color:n.color.danger,styles:o}),jsx(hs,{count:a,label:jt.inRange,color:n.color.success,styles:o}),s>0?jsx(hs,{count:s,label:jt.noRange,color:n.color.text.muted,styles:o}):null]}):null,jsx(m,{style:o.subtitle,children:jt.subtitle}),t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:jt.askA11y,style:o.ask,testID:"marker-summary-ask",children:jsx(m,{style:o.askLabel,children:jt.ask})}):null]})}i(Kc,"MarkerSummaryCard");function _f({segment:e,styles:t}){return (e.sweepDeg<=180?[{start:e.startDeg,sweep:e.sweepDeg}]:[{start:e.startDeg,sweep:180},{start:e.startDeg+180,sweep:e.sweepDeg-180}]).map((o,n)=>jsx(View,{style:[t.piece,{transform:[{rotate:`${o.start}deg`}]}],pointerEvents:"none",testID:`marker-ring-${e.key}`,children:jsx(View,{style:t.window,children:jsx(View,{style:[t.halfRing,{borderTopColor:e.color,borderRightColor:e.color,transform:[{rotate:`${o.sweep-135}deg`}]}]})})},n))}i(_f,"Arc");function hs({count:e,label:t,color:r,styles:o}){return jsx(View,{style:[o.badge,{borderColor:r}],children:jsx(m,{style:[o.badgeText,{color:r}],children:`${e} ${t}`})})}i(hs,"Badge");function Pf(){let e=V();return useMemo(()=>If(e),[e])}i(Pf,"useStyles");function If(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,a=StyleSheet.hairlineWidth,c=at(l.recordCard);return StyleSheet.create({card:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:a,borderColor:t.brandBorder,padding:r.lg-1,gap:r.sm+r.xs/2,...rt(l.recordCard,a)},title:{...T(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.letterSpacing.headerBrand,...c},ringRow:{alignItems:"center"},ringWrap:{width:ht,height:ht,alignItems:"center",justifyContent:"center"},track:{position:"absolute",width:ht,height:ht,borderRadius:ht/2,borderWidth:Gc,borderColor:t.surfaceSubtle},piece:{position:"absolute",width:ht,height:ht},window:{position:"absolute",left:ht/2,top:0,width:ht/2,height:ht,overflow:"hidden"},halfRing:{position:"absolute",left:-ht/2,top:0,width:ht,height:ht,borderRadius:ht/2,borderWidth:Gc,borderBottomColor:"transparent",borderLeftColor:"transparent"},center:{position:"absolute",alignItems:"center",justifyContent:"center"},centerCount:{...T(e,"medium"),fontSize:n.size.verdict*2,lineHeight:n.size.verdict*2+r.xs,color:t.text.primary,textAlign:"center",...c},centerLabel:{...T(e,"medium"),fontSize:n.size.heading-1,lineHeight:n.size.heading+r.xs/2,color:t.text.primary,textAlign:"center",...c},badges:{flexDirection:"row",flexWrap:"wrap",justifyContent:"center",gap:r.sm},badge:{borderWidth:1,borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs},badgeText:{...T(e,"mono"),fontSize:n.size.nano,lineHeight:n.size.tiny,letterSpacing:n.letterSpacing.headerBrand/2,textTransform:"uppercase"},subtitle:{...T(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.relaxed),color:t.text.primary,...c},ask:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.sm,marginTop:r.xs/2,paddingHorizontal:r.lg,borderRadius:o.pill,borderWidth:a,borderColor:t.borderRingCream,backgroundColor:t.surface},askLabel:{...T(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.primary,letterSpacing:n.letterSpacing.tight}})}i(If,"makeStyles");function Df(e){return e.value!==null&&Number.isFinite(e.value)}i(Df,"numeric");function Qc(e){let t=e.points.filter(Df);if(t.length===0)return null;let r=e.points[e.points.length-1]??null,o=r?.refLow??null,n=r?.refHigh??null,l=t.map(y=>y.value),a=Math.min(...l,...o!==null?[o]:[],...n!==null?[n]:[]),c=Math.max(...l,...o!==null?[o]:[],...n!==null?[n]:[]);a===c&&(a-=1,c+=1);let s=(c-a)*.18,d=a-s,u=c+s,p=u-d,g=i(y=>(u-y)/p*100,"y"),b=6,R=t.length,v=t.map((y,f)=>({index:f,xPct:R<=1?50:b+f/(R-1)*(100-2*b),yPct:g(y.value),status:y.status,point:y})),w=o!==null||n!==null?{topPct:n!==null?g(n):0,bottomPct:o!==null?g(o):100}:null;return {points:v,band:w,firstDate:t[0]?.at??null,lastDate:t[t.length-1]?.at??null}}i(Qc,"buildMarkerChart");var Lf=416,Vf=140;function _o(e){return `${e}%`}i(_o,"pct");function qf({marker:e,width:t,onPointPress:r,onAsk:o}){let n=Rs(),l=ue(),a=tr(e.latest?.status??null),c=xo(e.latest?.status??null),s=Kr(e.trajectory,e.points.length),d=useMemo(()=>Qc(e),[e]),u=e.latest?kt(e.latest.value,e.unit,e.latest.qualitativeResult):null;return jsx(View,{style:[n.page,t!==void 0?{width:t}:null],testID:`marker-card-${e.markerId}`,children:jsxs(View,{style:n.card,children:[jsxs(View,{style:n.headerRow,children:[jsxs(View,{style:n.nameColumn,children:[jsx(m,{style:n.markerName,numberOfLines:2,children:e.name}),e.unit?jsx(m,{style:n.unit,children:e.unit}):null]}),jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:cr.status(a.label),children:jsx(St,{label:a.label,tone:c})})]}),e.latest&&u!==null?jsxs(View,{style:n.latestRow,children:[jsx(m,{style:[n.latestValue,a.outOfRange?n.latestValueDanger:null],accessibilityLabel:cr.latestA11y(u,a.label,Y(e.latest.at)),children:u}),jsx(m,{style:n.latestDate,children:Y(e.latest.at)})]}):null,s?jsx(m,{style:n.trajectory,accessibilityRole:"text",children:s}):null,d!==null?jsxs(View,{style:n.chartWrap,children:[jsxs(View,{style:n.plot,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[d.band?jsx(View,{style:[n.band,{top:_o(d.band.topPct),height:_o(Math.max(0,d.band.bottomPct-d.band.topPct))}]}):null,d.points.map(p=>jsx(Pressable,{onPress:()=>r(e,p.point),hitSlop:12,style:[n.point,p.status==="above"||p.status==="below"?n.pointDanger:null,{left:_o(p.xPct),top:_o(p.yPct)}],testID:`marker-point-${e.markerId}-${p.index}`},p.index))]}),jsx(View,{style:n.a11yTable,accessibilityRole:"summary",accessibilityLabel:cr.readingsA11y(e.name),children:e.points.map((p,g)=>jsx(View,{accessibilityRole:"text",accessibilityLabel:Vc(e,p)},g))}),jsx(m,{style:e.points.length===1?n.singleHint:n.tapHint,children:e.points.length===1?cr.singleHint:cr.tapHint})]}):jsx(View,{style:n.emptyBody,accessibilityRole:"text",children:jsx(m,{style:n.emptyText,children:cr.empty})}),o?jsx(Pressable,{onPress:()=>o(e),accessibilityRole:"button",accessibilityLabel:cr.askA11y(e.name),style:[l.pill,l.pillAsk],testID:`marker-ask-${e.markerId}`,children:jsx(m,{style:l.pillAskLabel,children:cr.ask})}):null]})})}i(qf,"MarkerTrendCard");function ed({markers:e,onPointPress:t,onAsk:r}){let o=Rs(),[n,l]=useState(0),[a,c]=useState(0),s=i(p=>l(p.nativeEvent.layout.width),"onLayout"),d=i(p=>{if(n<=0)return;let g=Math.round(p.nativeEvent.contentOffset.x/n);c(Math.max(0,Math.min(g,e.length-1)));},"onMomentumEnd"),u=e[a]??null;return jsxs(View,{style:o.carousel,onLayout:s,testID:"marker-carousel",children:[jsx(ScrollView,{horizontal:true,pagingEnabled:true,showsHorizontalScrollIndicator:false,onMomentumScrollEnd:d,snapToAlignment:"start",children:e.map(p=>jsx(qf,{marker:p,width:n>0?n:void 0,onPointPress:t,onAsk:r},p.markerId))}),jsxs(View,{style:o.footer,accessible:true,accessibilityRole:"adjustable",accessibilityLabel:zi.a11y(u?.name??null,a,e.length),children:[jsx(View,{style:o.dots,children:e.map((p,g)=>jsx(View,{style:[o.dot,g===a?o.dotActive:null]},p.markerId))}),jsx(m,{style:o.counter,children:zi.counter(a,e.length)})]})]})}i(ed,"MarkerTrendCarousel");function td({marker:e,point:t,onClose:r,onAsk:o}){let n=Rs(),l=ue();if(e===null||t===null)return null;let a=i((c,s)=>jsxs(View,{style:n.detailRow,accessible:true,accessibilityRole:"text",accessibilityLabel:`${c}: ${s}`,children:[jsx(m,{style:n.detailLabel,children:c}),jsx(m,{style:n.detailValue,children:s})]},c),"row");return jsxs(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:r,children:[jsx(Pressable,{style:n.backdrop,onPress:r,accessibilityRole:"button",accessibilityLabel:Et.close}),jsxs(View,{style:n.sheet,accessibilityViewIsModal:true,testID:"marker-provenance-sheet",children:[jsx(View,{style:n.handle}),jsxs(View,{style:n.sheetHeader,children:[jsx(m,{style:n.sheetTitle,accessibilityRole:"header",children:Et.title}),jsx(Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Et.close,hitSlop:10,style:n.closeButton,testID:"marker-provenance-close",children:jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsxs(View,{style:n.sheetBody,children:[jsxs(View,{style:n.valueRow,children:[jsx(m,{style:n.sheetName,children:e.name}),jsx(m,{style:n.sheetValue,children:kt(t.value,e.unit,t.qualitativeResult)})]}),t.reviewed?jsx(View,{style:n.reviewed,accessibilityRole:"text",children:jsx(m,{style:n.reviewedText,children:Et.reviewed})}):null,a(Et.collected,Y(t.at)),t.sourceClinic?a(Et.clinic,t.sourceClinic):null,a(Et.referenceRange,t.refLow!==null||t.refHigh!==null?Co(t,e.unit):Et.noRange),t.docId?a(Et.sourceDocument,t.docId):null,t.reviewed?null:jsx(m,{style:n.unverified,accessibilityRole:"text",children:Et.unverified}),o?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Et.askA11y,style:[l.pill,l.pillAsk],testID:"marker-provenance-ask",children:jsx(m,{style:l.pillAskLabel,children:Et.ask})}):null]})]})]})}i(td,"MarkerProvenanceSheet");function Rs(){let e=V();return useMemo(()=>zf(e),[e])}i(Rs,"useStyles");function zf(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,a=StyleSheet.hairlineWidth,c=r.md,s=i((g,b,R,v="regular")=>({...T(e,v),fontSize:g,lineHeight:Math.round(g*b),color:R}),"text"),d=at(l.recordCard),u=s(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold"),p=s(n.size.verdict+r.xs,n.lineHeight.tight,t.text.primary,"bold");return StyleSheet.create({page:{paddingHorizontal:r.sm},card:{borderRadius:o.lg-r.xs/2,borderWidth:a,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg,gap:r.md,...rt(l.recordCard,a)},headerRow:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm+r.xs/2},nameColumn:{flex:1,gap:r.xs/2},markerName:{...u,...d},sheetName:u,unit:{...T(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted,...d},latestRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},latestValue:{...p,...d},sheetValue:p,latestValueDanger:{color:t.danger},latestDate:{...s(n.size.caption,n.lineHeight.normal,t.text.muted),...d},trajectory:{...s(n.size.bodyTight,n.lineHeight.normal,t.text.muted),...d},chartWrap:{gap:r.sm},plot:{height:Vf,borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:a,borderColor:t.borderHairlineGreen,overflow:"hidden"},band:{position:"absolute",left:0,right:0,backgroundColor:t.badgeBgPositive},point:{position:"absolute",width:c,height:c,borderRadius:c/2,marginLeft:-c/2,marginTop:-c/2,backgroundColor:t.brand,borderWidth:2,borderColor:t.surface},pointDanger:{backgroundColor:t.danger},a11yTable:{width:1,height:1,overflow:"hidden",position:"absolute"},tapHint:{...s(n.size.tiny,n.lineHeight.normal,t.text.placeholder),textAlign:"center",...d},singleHint:{...s(n.size.caption,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},emptyBody:{alignItems:"center",justifyContent:"center",gap:r.sm,paddingVertical:r.xxl+r.xs},emptyText:{...s(n.size.bodyTight,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},carousel:{height:Lf},footer:{alignItems:"center",gap:r.sm,paddingTop:r.md},dots:{flexDirection:"row",gap:r.xs+r.xs/2},dot:{width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs-1,backgroundColor:t.borderHairlineGreen},dotActive:{width:r.lg+r.xs/2,backgroundColor:t.brand},counter:{...T(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,letterSpacing:n.letterSpacing.eyebrow/3,color:t.text.muted},backdrop:{flex:1,backgroundColor:so},sheet:{backgroundColor:t.surfaceCream,borderTopLeftRadius:o.xl-r.xs,borderTopRightRadius:o.xl-r.xs,paddingHorizontal:r.lg+r.xs,paddingTop:r.sm,paddingBottom:r.xxl+r.xs,maxHeight:"80%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},sheetHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},sheetTitle:{flex:1,...s(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},closeButton:{width:r.xxl+r.md,height:r.xxl+r.md,alignItems:"center",justifyContent:"center"},closeGlyph:{...s(n.size.verdict,n.lineHeight.tight,t.text.primary)},sheetBody:{gap:r.md},valueRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},reviewed:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs,backgroundColor:t.badgeBgPositive},reviewedText:{...s(n.size.tiny,n.lineHeight.normal,t.success,"medium")},detailRow:{gap:r.xs/2},detailLabel:{...s(n.size.caption,n.lineHeight.normal,t.text.muted,"medium")},detailValue:s(n.size.body,n.lineHeight.normal,t.text.primary),unverified:s(n.size.caption,n.lineHeight.normal,t.text.muted)})}i(zf,"makeStyles");var K=Object.freeze({title:"Full medical record",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:i(e=>`${e} ${e===1?"document":"documents"} from your vet ${e===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,"inReview"),needsAttention:"Needs your attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:i(e=>`${e} ${e===1?"document":"documents"} on file`,"documentsOnFile"),inReviewChip:i(e=>`${e} in review`,"inReviewChip"),beingVerified:i(e=>`${e} being verified`,"beingVerified"),beingVerifiedA11y:i(e=>`${e} ${e===1?"fact is":"facts are"} being verified`,"beingVerifiedA11y"),pendingReview:"Pending review: ",dateRange:i((e,t)=>`${Y(e)} to ${Y(t)}`,"dateRange"),documents:"Documents",uploadedDocument:ge.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:ge.labResults,visits:ge.visits,physicalExams:ge.physicalExams,visitNotes:ge.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 ${Y(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"})}),rd=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 jr(e){return Object.prototype.hasOwnProperty.call(rd,e)?rd[e]:dr(e)}i(jr,"entityTypeLabel");var nd=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function od(e){let t=nd.filter(o=>e.includes(o)),r=e.filter(o=>!nd.includes(o));return [...t,...r]}i(od,"orderEntityTypes");function Po(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(Po,"conflictSeverityMeta");function Dn(e,t){if(!e)return null;let r=Date.parse(e);if(Number.isNaN(r))return null;let o=r<t-1440*60*1e3;return {label:o?K.overdue:K.due(Y(e)),overdue:o}}i(Dn,"dueBadge");function id(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(id,"formatReferenceBand");var ct=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 sd(e,t){return sr(e)?t==="remove"?"Records access for this pet is off, so this detail cannot be removed.":"Records access for this pet is off, so this detail cannot be changed.":fc(e)?t==="remove"?"A clinician already reviewed this detail, so it can't be removed here.":"A clinician already reviewed this detail, so it can't be changed here.":t==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}i(sd,"factEditErrorMessage");var Ff=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function vs(e,t){if(Object.keys(t.edits).length===0&&t.removed.length===0)return e;let r=[];for(let o of e){let n=o.canonicalKey??null;if(n!==null&&t.removed.includes(n))continue;let l=n!==null?t.edits[n]:void 0;r.push(l===void 0?o:Object.freeze({...o,value:l}));}return Object.freeze(r)}i(vs,"applyFactOverlay");function Do(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(Do,"isFactEditable");function Nf(){return `records-fact-${Date.now().toString(36)}`}i(Nf,"defaultFactKey");function ws(e,t={}){let r=mr(),{userRef:o}=Se(),[n,l]=useState(Ff),[a,c]=useState(false),[s,d]=useState(null),u=useMemo(()=>({}),[r,e,o]),[p,g]=useState(null),b=useCallback(()=>g(u),[u]),R=o!==null&&p!==u,v=useRef(false),w=useRef(t.newIdempotencyKey);w.current=t.newIdempotencyKey;let y=useCallback(()=>(w.current??Nf)(),[]),f=useCallback((S,k,E)=>{if(c(false),!S.ok){if(k(),Tr(S.error)){b();return}d(sd(S.error,E));}},[b]),x=useCallback(async(S,k)=>{let E=S.canonicalKey??"",A=k.trim();if(v.current||E.length===0||A.length===0)return H(F("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let B=n;l(U=>({...U,edits:{...U.edits,[E]:A}}));let z=await r.editFact(e,{entityType:S.category,canonicalKey:E,correctedFields:ss(S.value,A),idempotencyKey:y()});return v.current=false,f(z,()=>l(B),"edit"),z},[r,e,n,f,y]),h=useCallback(async S=>{let k=S.canonicalKey??"";if(v.current||k.length===0)return H(F("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let E=n;l(B=>({...B,removed:[...B.removed,k]}));let A=await r.removeFact(e,{entityType:S.category,canonicalKey:k,idempotencyKey:y()});return v.current=false,f(A,()=>l(E),"remove"),A},[r,e,n,f,y]),_=useCallback(()=>d(null),[]);return useMemo(()=>({overlay:n,busy:a,error:s,available:R,edit:x,remove:h,clearError:_}),[n,a,s,R,x,h,_])}i(ws,"useRecordFactEdit");var xs=Object.freeze(["vaccination","parasite_prevention"]),Ao="Undated",Mf=Object.freeze({given:"Given",prevention:"Prevention",overdue:"Overdue",noDate:"No date"}),cd=Object.freeze({given:"positive",prevention:"neutral",overdue:"critical",noDate:"neutral"});function Oo(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(Oo,"toMillis");function Bf(e){let t=e.status?.toLowerCase()??"";return /overdue|lapsed|expired/.test(t)}i(Bf,"isLapsed");function Hf(e){return e.category==="parasite_prevention"?"prevention":Oo(e.observedAt)===null?"noDate":Bf(e)?"overdue":"given"}i(Hf,"vaccineTone");function Uf(e){let t=Oo(e);return t===null?Ao:String(new Date(t).getUTCFullYear())}i(Uf,"yearOf");function jf(e){let t=Hf(e),r=[e.value!==null&&e.value.length>0?e.value:null,e.observedAt!==null?Y(e.observedAt):null].filter(o=>o!==null&&o.length>0);return {key:e.key,name:e.label,detail:r.length>0?r.join(" \xB7 "):null,statusLabel:Mf[t],tone:t,entity:e}}i(jf,"buildRow");function dd(e){let t=new Map;for(let o of e){if(!xs.includes(o.category))continue;let n=Uf(o.observedAt),l=t.get(n),a={row:jf(o),at:o.observedAt};l===void 0?t.set(n,[a]):l.push(a);}let r=[...t.keys()].sort((o,n)=>o===Ao?1:n===Ao?-1:Number(n)-Number(o));return Object.freeze(r.map(o=>{let n=t.get(o)??[],l=o===Ao?n:[...n].sort((a,c)=>(Oo(c.at)??0)-(Oo(a.at)??0));return Object.freeze({year:o,items:Object.freeze(l.map(a=>a.row))})}))}i(dd,"selectVaccineGroups");function Cs({entity:e,factEdit:t,children:r}){let o=pd(),[n,l]=useState(false),a=e.label.trim()||ct.detail;return jsxs(View,{style:o.row,children:[jsx(View,{style:o.main,children:r}),jsx(Pressable,{onPress:()=>l(true),accessibilityRole:"button",accessibilityLabel:ct.editA11y(a),hitSlop:6,style:o.editButton,testID:`fact-edit-open-${e.canonicalKey??e.key}`,children:jsx(View,{style:o.pencil,accessibilityElementsHidden:true,importantForAccessibility:"no"})}),n?jsx(Kf,{entity:e,title:a,factEdit:t,onClose:()=>l(false)}):null]})}i(Cs,"FactEditAffordance");function Kf({entity:e,title:t,factEdit:r,onClose:o}){let n=pd(),l=ue(),a=V(),[c,s]=useState(e.value??""),[d,u]=useState(null),[p,g]=useState(false);useEffect(()=>{r.clearError();},[r]);let b=c.trim().length>0&&c.trim()!==(e.value??"").trim(),R=d??r.error,v=r.busy,w=i(()=>{if(!b){u(ct.noChange);return}u(null),r.edit(e,c).then(f=>{f.ok&&o();});},"submitEdit"),y=i(()=>{u(null),r.remove(e).then(f=>{f.ok?o():g(false);});},"submitRemove");return jsx(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:o,children:jsxs(KeyboardAvoidingView,{behavior:"padding",style:n.backdrop,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:ct.closeEditorA11y,onPress:o}),jsxs(View,{style:n.sheet,accessibilityViewIsModal:true,testID:"fact-edit-sheet",children:[jsx(View,{style:n.handle}),jsxs(View,{style:n.header,children:[jsxs(View,{style:n.headerText,children:[jsx(m,{style:n.title,accessibilityRole:"header",children:ct.title(t)}),jsx(m,{style:[n.helper,R?n.helperError:null],accessibilityLiveRegion:"polite",children:R??ct.helper})]}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:ct.close,onPress:o,hitSlop:12,style:n.closeButton,testID:"fact-edit-close",children:jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsx(m,{style:l.fieldLabel,children:e.label}),jsx(He,{accessibilityLabel:e.label,style:l.field,value:c,onChangeText:f=>{s(f),u(null);},editable:!v,maxLength:512,placeholderTextColor:a.color.text.placeholder,testID:"fact-edit-field"}),p?jsxs(View,{style:n.confirmBlock,testID:"fact-edit-confirm-remove",children:[jsx(m,{style:n.confirmText,children:ct.confirmRemove}),jsxs(View,{style:n.confirmRow,children:[jsx(J,{label:v?ct.removing:ct.removeConfirm,kind:"danger",busy:v,onPress:y,style:n.confirmButton,testID:"fact-edit-remove-confirm"}),jsx(J,{label:ct.keep,kind:"outline",disabled:v,onPress:()=>g(false),style:n.confirmButton,testID:"fact-edit-remove-cancel"})]})]}):jsxs(View,{style:n.actions,children:[jsx(J,{label:v?ct.saving:ct.save,busy:v,disabled:!b,onPress:w,testID:"fact-edit-save"}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:ct.removeA11y(t),disabled:v,onPress:()=>{u(null),g(true);},style:[n.removeButton,v?n.removeDisabled:null],testID:"fact-edit-remove",children:jsx(m,{style:n.removeText,children:ct.remove})})]})]})]})})}i(Kf,"FactEditSheet");function pd(){let e=V();return useMemo(()=>Qf(e),[e])}i(pd,"useStyles");function Qf(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,a=e.brightness==="dark"?t.errorRed:t.danger,c=i((s,d,u,p="regular")=>({...T(e,p),fontSize:s,lineHeight:Math.round(s*d),color:u}),"text");return StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:r.sm},main:{flex:1},editButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},pencil:{width:r.md+r.xs/2,height:r.xs/2,backgroundColor:t.brandInk,borderRadius:o.pill,transform:[{rotate:"-45deg"}]},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:so},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),helperError:{color:a},closeButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),actions:{gap:r.sm},removeButton:{minHeight:l,alignItems:"center",justifyContent:"center"},removeDisabled:{opacity:.5},removeText:{...c(n.size.bodyTight,n.lineHeight.snug,t.danger,"bold")},confirmBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.badgeBgCritical},confirmText:c(n.size.bodyTight,n.lineHeight.normal,t.text.primary),confirmRow:{flexDirection:"row",gap:r.sm},confirmButton:{flex:1}})}i(Qf,"makeStyles");function zo({record:e,depth:t,petName:r,showLabs:o=true,onNavigate:n,onAsk:l,factEdit:a,nowMs:c}){let s=ue(),d=Xf(),u=c??Date.now(),p=useMemo(()=>a?vs(e.entities,a.overlay):e.entities,[e.entities,a]),g=useMemo(()=>{let y=[],f=new Map;for(let x of p){let h=x.category.trim();if(h.length===0||xs.includes(h))continue;let _=f.get(h);_===void 0?(y.push(h),f.set(h,[x])):_.push(x);}return {order:od(y),groups:f}},[p]),b=useMemo(()=>dd(p),[p]),R=Object.values(e.documents),v=i((y,f,x)=>l?jsx(Pressable,{onPress:()=>{let h=y();l(h.prompt,h.entityRef);},accessibilityRole:"button",accessibilityLabel:f,style:[s.pill,s.pillAsk,d.ask],testID:x,children:jsx(m,{style:s.pillAskLabel,children:f})}):null,"ask"),w=a!==void 0&&a.available;return jsxs(Fragment,{children:[jsxs(View,{style:d.sections,children:[t&&t.conflicts.length>0?jsxs(View,{style:s.section,testID:"record-section-conflicts",children:[jsx(Dt,{title:K.needsAttention,count:t.conflicts.length}),[...t.conflicts].sort((y,f)=>Po(y.severity).rank-Po(f.severity).rank).map(y=>{let f=Po(y.severity),x=dr(y.field??y.entityType);return jsxs(View,{style:[d.conflictCard,{borderColor:s.chipTones[f.tone].fg.color}],accessibilityRole:"summary",children:[jsxs(View,{style:d.conflictHead,children:[jsx(m,{style:d.conflictTitle,children:f.label}),jsx(St,{label:x,tone:f.tone})]}),jsx(m,{style:s.rowDetail,children:K.conflictSub}),y.candidates.map((h,_)=>jsxs(View,{style:d.candidate,children:[jsx(m,{style:s.rowTitle,children:h.value}),jsx(m,{style:s.rowMuted,children:[h.docId?e.documents[h.docId]?.title??K.uploadedDocument:K.uploadedDocument,h.collectedAt?Y(h.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},_)),v(()=>Uc(r,{scopeLabel:x,severity:y.severity,candidates:y.candidates.map(h=>({value:h.value,clinicName:h.docId?e.documents[h.docId]?.title??null:null}))},y.conflictId),K.askConflict,`records-ask-conflict-${y.conflictId}`)]},y.conflictId)})]}):null,t?.completeness?jsxs(View,{style:s.section,testID:"record-section-completeness",children:[jsx(Dt,{title:K.whatsOnFile}),jsxs(View,{style:s.card,children:[jsx(View,{style:d.coverageRow,children:[[K.coverage.labs,t.completeness.hasLabHistory],[K.coverage.vaccines,t.completeness.hasVaccinationHistory],[K.coverage.weight,t.completeness.hasWeightHistory],[K.coverage.vitals,t.completeness.hasVitalsHistory],[K.coverage.exams,t.completeness.hasPhysicalExamHistory],[K.coverage.procedures,t.completeness.hasProcedureHistory],[K.coverage.genetics,t.completeness.hasGeneticHistory],[K.coverage.parasite,t.completeness.hasParasitePreventionHistory],[K.coverage.reproductive,t.completeness.hasReproductiveHistory]].map(([y,f])=>jsx(View,{style:[d.coveragePill,f?s.chipTones.positive.bg:s.chipTones.neutral.bg],accessible:true,accessibilityRole:"text",accessibilityLabel:`${y}: ${f?K.onFile:K.noneOnFile}`,children:jsx(m,{style:[d.coverageText,f?s.chipTones.positive.fg:{color:s.rowMuted.color}],children:y})},y))}),jsxs(View,{style:d.metaRow,children:[jsx(m,{style:d.metaText,children:K.documentsOnFile(t.completeness.documentsIngested)}),t.completeness.documentsInReview>0?jsx(St,{label:K.inReviewChip(t.completeness.documentsInReview),tone:"warning"}):null,Es(t.completeness.heldTotal,t.completeness.entitiesPendingReview)>0?jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:K.beingVerifiedA11y(Es(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),children:jsx(St,{label:K.beingVerified(Es(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),t.completeness.earliestRecordAt||t.completeness.latestRecordAt?jsx(View,{style:d.metaRow,children:jsx(m,{style:d.metaText,children:K.dateRange(t.completeness.earliestRecordAt,t.completeness.latestRecordAt)})}):null,Object.entries(t.completeness.entitiesPendingReview).filter(([,y])=>y>0).length>0?jsxs(m,{style:d.pendingText,children:[K.pendingReview,Object.entries(t.completeness.entitiesPendingReview).filter(([,y])=>y>0).map(([y,f])=>`${jr(y)} (${f})`).join(", ")]}):null]})]}):null,R.length>0?jsxs(View,{style:s.section,testID:"record-section-documents",children:[jsx(Dt,{title:K.documents,count:R.length}),jsx(View,{style:s.card,children:R.map((y,f)=>{let x=y.title?.trim()||K.uploadedDocument,h=y.receivedAt?Y(y.receivedAt):null,_=jsxs(Fragment,{children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:x}),h?jsx(m,{style:s.rowDetail,children:h}):null]}),n?jsx(er,{}):null]});return n?jsx(Pressable,{onPress:()=>n({name:"contributions",docId:y.docId}),accessibilityRole:"button",accessibilityLabel:K.documentRowA11y(x),style:[s.row,f>0?s.rowDivider:null],testID:`records-document-row-${y.docId}`,children:_},y.docId):jsx(View,{style:[s.row,f>0?s.rowDivider:null],children:_},y.docId)})})]}):null,e.identity.length>0?jsxs(View,{style:s.section,testID:"record-section-identity",children:[jsx(Dt,{title:K.identity}),jsx(View,{style:s.card,children:e.identity.map((y,f)=>jsxs(View,{style:[s.row,f>0?s.rowDivider:null],children:[jsx(m,{style:d.identityLabel,children:y.label}),jsx(m,{style:d.identityValue,children:y.value})]},`${f}:${y.label}`))})]}):null,e.forwardLooking.length>0?jsxs(View,{style:s.section,testID:"record-section-upcoming",children:[jsx(Dt,{title:K.upcomingCare,count:e.forwardLooking.length}),jsx(View,{style:s.card,children:e.forwardLooking.map((y,f)=>{let x=Dn(y.dueAt,u);return jsxs(View,{style:[s.row,f>0?s.rowDivider:null],children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:y.title}),y.detail?jsx(m,{style:s.rowDetail,children:y.detail}):null]}),x?jsx(St,{label:x.label,tone:x.overdue?"critical":"info"}):null]},`${y.title}-${f}`)})}),v(()=>Mc(r,e.forwardLooking.map(y=>{let f=Dn(y.dueAt,u);return {label:y.title,relativeText:f?.label??"",tone:f?.overdue?"overdue":"upcoming"}}),e.petRef),K.askUpcomingCare,"records-ask-upcoming-care")]}):null,b.length>0?jsxs(View,{style:s.section,testID:"record-section-vaccination",children:[jsx(Dt,{title:jr("vaccination"),count:b.reduce((y,f)=>y+f.items.length,0)}),b.map(y=>jsxs(View,{style:d.vaccineGroup,testID:`records-vaccine-group-${y.year}`,children:[jsx(m,{style:d.vaccineYear,accessibilityRole:"header",children:y.year.toUpperCase()}),jsx(View,{style:s.card,children:y.items.map((f,x)=>{let h=jsxs(View,{style:[s.row,x>0?s.rowDivider:null],children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:f.name}),f.detail?jsx(m,{style:s.rowDetail,children:f.detail}):null,v(()=>fs(r,{entityTypeLabel:jr(f.entity.category),title:f.name,detail:f.detail},f.entity.category,f.key),K.askEverfur,`records-ask-entity-${f.key}`)]}),jsx(St,{label:f.statusLabel,tone:cd[f.tone]})]});return w&&Do(f.entity)&&a?jsx(Cs,{entity:f.entity,factEdit:a,children:h},f.key):jsx(View,{children:h},f.key)})})]},y.year))]}):null,g.order.map(y=>{let f=g.groups.get(y)??[];if(f.length===0)return null;let x=jr(y);return jsxs(View,{style:s.section,testID:`record-section-${y}`,children:[jsx(Dt,{title:x,count:f.length}),jsx(View,{style:s.card,children:f.map((h,_)=>{let k=[Yr(h.value,h.unit),h.observedAt?Y(h.observedAt):null].filter(A=>A&&A.length>0).join(" \xB7 "),E=jsxs(View,{style:[s.row,_>0?s.rowDivider:null],children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:h.label}),k?jsx(m,{style:s.rowDetail,children:k}):null,v(()=>fs(r,{entityTypeLabel:x,title:h.label,detail:k||null},y,h.key),K.askEverfur,`records-ask-entity-${h.key}`)]}),h.status?jsx(St,{label:dr(h.status)}):null]});return w&&Do(h)&&a?jsx(Cs,{entity:h,factEdit:a,children:E},h.key):jsx(View,{children:E},h.key)})})]},y)}),t&&t.physicalExams.length>0?jsxs(View,{style:s.section,testID:"record-section-exams",children:[jsx(Dt,{title:K.physicalExams,count:t.physicalExams.length}),t.physicalExams.map(y=>jsxs(View,{style:s.card,children:[jsx(m,{style:[s.rowTitle,d.cardTitle],accessibilityRole:"header",children:y.observedOn?Y(y.observedOn):ge.exam}),y.systems.map((f,x)=>{let h=f.findingStatus==="abnormal",_=h?ge.abnormal:f.findingStatus==="not_examined"?ge.notExamined:ge.normal;return jsxs(View,{style:[s.row,x>0?s.rowDivider:null],accessible:true,accessibilityRole:"text",accessibilityLabel:[qr(f.system),_,h?f.finding:null].filter(Boolean).join(", "),children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:qr(f.system)}),h&&f.finding?jsx(m,{style:s.rowDetail,children:f.finding}):null]}),jsx(St,{label:_,tone:h?"warning":f.findingStatus==="not_examined"?"neutral":"positive"})]},f.system)}),v(()=>Bc(r,{observedOn:y.observedOn?Y(y.observedOn):null,abnormal:y.systems.filter(f=>f.findingStatus==="abnormal").map(f=>({system:qr(f.system),finding:f.finding??""}))},y.examId),K.askExam,`records-ask-exam-${y.examId}`)]},y.examId))]}):null,t&&t.clinicianNotes.length>0?jsxs(View,{style:s.section,testID:"record-section-notes",children:[jsx(Dt,{title:K.visitNotes,count:t.clinicianNotes.length}),t.clinicianNotes.map(y=>jsxs(View,{style:s.card,children:[jsx(m,{style:[s.rowTitle,d.cardTitle],accessibilityRole:"header",children:y.observedOn?Y(y.observedOn):ge.visitNote}),y.sections.map((f,x)=>jsxs(View,{style:[d.noteSection,x>0?s.rowDivider:null],children:[jsx(m,{style:d.noteLabel,children:Qr(f.section)}),jsx(m,{style:f.text?d.noteBody:d.noteBodyMuted,children:f.text||ge.notRecorded})]},`${f.section}:${x}`)),v(()=>Hc(r,{observedOn:y.observedOn?Y(y.observedOn):null,sections:y.sections.map(f=>({label:Qr(f.section),text:f.text}))},y.noteId),K.askVisit,`records-ask-note-${y.noteId}`)]},y.noteId))]}):null,o&&t&&t.labResults.length>0?jsxs(View,{style:s.section,testID:"record-section-labs",children:[jsx(Dt,{title:K.labResults,count:t.labResults.length}),jsx(View,{style:s.card,children:t.labResults.map((y,f)=>{let x=tr(y.latest.status),h=Ni(y.latest.at,y.trajectory,y.points.length);return jsxs(View,{style:[s.row,f>0?s.rowDivider:null],children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:y.name}),jsx(m,{style:s.rowValue,children:kt(y.latest.value,y.latest.unit,y.latest.qualitativeResult)}),h?jsx(m,{style:s.rowDetail,children:h}):null]}),jsx(St,{label:x.label,tone:xo(y.latest.status)})]},y.markerId)})})]}):null,t&&t.encounters.length>0?jsxs(View,{style:s.section,testID:"record-section-visits",children:[jsx(Dt,{title:K.visits,count:t.encounters.length}),jsx(View,{style:s.card,children:t.encounters.map((y,f)=>{let x=[y.date?Y(y.date):null,y.clinicName,y.veterinarian].filter(h=>h&&h!=="-").join(" \xB7 ");return jsx(View,{style:[s.row,f>0?s.rowDivider:null],children:jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:y.type?dr(y.type):ge.visit}),x?jsx(m,{style:s.rowDetail,children:x}):null]})},y.encounterId)})})]}):null]}),jsx(kr,{disclaimer:e.disclaimer})]})}i(zo,"RecordSections");function Es(e,t){return e>0?e:Object.values(t).reduce((r,o)=>r+o,0)}i(Es,"heldCount");function Xf(){let e=V();return useMemo(()=>Jf(e),[e])}i(Xf,"useLocalStyles");function Jf(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth;return StyleSheet.create({sections:{gap:r.lg+r.xs},vaccineGroup:{gap:r.xs+1,marginBottom:r.sm},vaccineYear:{...T(e,"monoMedium"),fontSize:n.size.micro,lineHeight:n.size.micro+r.xs,color:t.text.muted,letterSpacing:n.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:r.xs+2},ask:{marginTop:r.lg},conflictCard:{borderRadius:o.md,borderWidth:1,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},conflictHead:{flexDirection:"row",alignItems:"center",gap:r.sm},conflictTitle:{flex:1,...T(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},candidate:{borderTopWidth:l,borderTopColor:t.borderHairlineGreen,paddingTop:r.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,paddingVertical:r.md},coveragePill:{borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs+1},coverageText:{...T(e,"medium"),fontSize:n.size.caption,lineHeight:n.size.caption+r.xs-1},metaRow:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingBottom:r.md},metaText:{flex:1,...T(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},pendingText:{...T(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.normal),color:t.text.muted,paddingBottom:r.md},identityLabel:{...T(e,"medium"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...T(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},cardTitle:{paddingTop:r.sm},noteSection:{paddingVertical:r.md,gap:r.xs},noteLabel:{...T(e,"bold"),fontSize:n.size.bodyTight,color:t.text.secondary,textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},noteBody:{...T(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.primary},noteBodyMuted:{...T(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.muted,fontStyle:"italic"}})}i(Jf,"makeLocalStyles");var An=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 Zf=Math.round(hr/(1024*1024)),ot=Object.freeze({title:i(e=>`Upload ${Fe(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 ${Fe(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 ${Zf} MB each. You can pick several at once. We\u2019ll read them and add the results to your records.`,chooseFiles:"Choose files",chooseFilesA11y:"Choose records to upload",uploading:i((e,t)=>`Uploading ${Math.min(e+1,t)} of ${t}\u2026`,"uploading"),cancel:"Cancel",cancelA11y:"Cancel these uploads",received:i(e=>`${e===1?"Record received.":`${e} records received.`} We\u2019ll read and review ${e===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,"received"),retryFailed:i(e=>`Retry ${e} that didn\u2019t upload`,"retryFailed"),retryFailedA11y:i(e=>`Retry ${e} failed upload${e>1?"s":""}`,"retryFailedA11y"),addMore:"Add more files",addMoreA11y:"Add more records",done:"Done",doneA11y:"Done, view records",errors:Object.freeze({start:"We couldn\u2019t start that upload. Check your connection and try again.",startPlain:"We couldn\u2019t start that upload. Please try again.",upload:"We couldn\u2019t upload that record. Check your connection and try again."})});var gd=Math.round(hr/(1024*1024)),$r=Object.freeze({queued:"Queued",verifying:"Verifying\u2026",done:"Done",failed:"Failed",uploading:i((e,t)=>`Uploading ${Math.min(e+1,t)} of ${t} records`,"uploading"),uploaded:i((e,t)=>`${e} of ${t} records uploaded`,"uploaded")});function bd(e){let t=Math.round(e.progress*100);switch(e.status){case "done":return $r.done;case "failed":return $r.failed;case "uploading":return e.progress>=1?$r.verifying:`${t}%`;case "queued":return $r.queued;default:return null}}i(bd,"uploadItemStatusLabel");function hd(e){if(e.length===0)return null;let t=i(l=>{let a=l.map(c=>c.name??"");return a.length<=3?a.join(", "):`${a.slice(0,3).join(", ")} and ${a.length-3} more`},"nameList"),r=e.filter(l=>l.reason==="too_large"),o=e.filter(l=>l.reason==="unsupported"),n=[];return o.length>0&&n.push(`${t(o)} ${o.length>1?"are not PDFs":"is not a PDF"}`),r.length>0&&n.push(`${t(r)} ${r.length>1?"are":"is"} over ${gd} MB`),`Didn\u2019t upload: ${n.join("; ")}. We can only read PDFs up to ${gd} MB right now.`}i(hd,"skippedFilesMessage");function Rd(e){let t=[];for(let r of e)r.status==="skipped"&&r.skipReason!==null&&t.push({name:r.name,reason:r.skipReason});return t}i(Rd,"skippedOf");var qt=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 vd({request:e,onRecovered:t,canUpload:r=false},o){let[n,l]=useState(""),[a,c]=useState(false),[s,d]=useState(null),[u,p]=useState(false),[g,b]=useState(null),R=useRef(false),v=useRef(false),w=useRef(0);useEffect(()=>(v.current=true,()=>{v.current=false,w.current+=1;}),[o]);let y=g!==null&&g.before===e.updatedAt?{...g.value,canRetrySend:e.canRetrySend===true&&g.value.canRetrySend===true,canUpdateClinicEmail:e.canUpdateClinicEmail===true&&g.value.canUpdateClinicEmail===true,canRevoke:e.canRevoke===true&&g.value.canRevoke===true,canConvertToUpload:e.canConvertToUpload===true&&g.value.canConvertToUpload===true}:e,f=n.trim(),x=f.length<=320&&!Array.from(f).some(A=>A.charCodeAt(0)<=32||A.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f),h=y.canUpdateClinicEmail===true&&f.length>0,_=y.canRetrySend===true&&!a&&!h,S=y.canUpdateClinicEmail===true&&!a&&x,k=y.canConvertToUpload===true&&r,E=i(async A=>{let B={retry:_,email:S,revoke:y.canRevoke===true&&u,convert:k};if(R.current||!v.current||!B[A])return;R.current=true,c(true),d(null);let z=w.current,U=i(()=>v.current&&z===w.current,"live");try{let j=A==="retry"?await o.retryRequest(e.id):A==="email"?await o.updateClinicEmail(e.id,f):A==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!U())return;if(!j.ok){d(j.error);return}if(j.value.id!==e.id||j.value.petRef!==e.petRef){d(F("internalError"));return}b({before:e.updatedAt,value:j.value}),l(""),p(!1),t();}catch{U()&&d(F("internalError"));}finally{R.current=false,U()&&c(false);}},"run");return {request:y,email:n,busy:a,error:s,canRetry:_,canUpdateEmail:S,canConvert:k,hasEmailEdit:h,confirmingRevoke:u&&y.canRevoke===true,emailInvalid:f.length>0&&!x,setEmail(A){R.current||(l(A),d(null));},retry:i(()=>E("retry"),"retry"),updateEmail:i(()=>E("email"),"updateEmail"),revoke:i(()=>E("revoke"),"revoke"),convert:i(()=>E("convert"),"convert"),askRevoke(){!R.current&&y.canRevoke===true&&p(true);},keepRequest(){R.current||p(false);}}}i(vd,"useRecordsRecovery");var tg=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],rg=["requested","awaiting_upload","records_received","processing","ready"],ng=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],Ln=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"}),_t=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"}),og=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"}),ig=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 sg(e){return e.wireStatus??ig[e.status]??"sent"}i(sg,"wireStatusOf");function ag(e,t){return e!=="awaiting_response"||t<=0?null:`${t} ${t===1?"reminder":"reminders"} sent`}i(ag,"reminderProgressLabel");function lg(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(lg,"reachedRailIndex");function cg(e){switch(e.dispatchStatus){case "sent":return _t.delivered;case "preparing":case "queued":case "sending":return _t.emailing;case "failed":return _t.bounced;default:return null}}i(cg,"deliveryDetail");function dg(e,t){return ag(t,e.reminderCount??0)??_t.waiting}i(dg,"awaitingDetail");function ug(e){return e.source==="owner_provided"||!!e.convertedToUploadAt}i(ug,"isOwnerSourcedRequest");function pg(e,t,r){let o=ug(t);switch(e){case "sent_to_clinic":return cg(t);case "awaiting_clinic":return dg(t,r);case "awaiting_upload":return _t.upload;case "records_received":return o?_t.ownerAdded:_t.clinicSent;case "processing":return _t.preparing;case "ready":return _t.ready;default:return null}}i(pg,"railDetail");function mg(e,t){return !!e.reviewStartedAt||t==="parsing_failed"||t==="review_email_failed"}i(mg,"tookReviewBranch");function yg(e,t,r){if(e.key!=="processing"||!mg(t,r))return [e];let o=r==="parsing_failed",n=r==="published",l=n?"done":o?"current":"done",a=n?"done":o?"upcoming":"current";return [{key:"parsing_failed",title:Ln.parsing_failed,detail:_t.parsingFailed,at:null,state:l},{key:"manual_review",title:Ln.manual_review,detail:_t.manualReview,at:t.reviewStartedAt??null,state:a}]}i(yg,"expandProcessingPhase");function fg(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(fg,"convertedReachedIndex");function wd(e){return {key:"awaiting_clinic",title:_t.switchedTitle,detail:_t.switched,at:e.convertedToUploadAt??null,state:"done"}}i(wd,"convertedClinicSwitchEvent");function gg(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(gg,"ownerReachedIndex");function bg(e,t,r){switch(e){case "requested":return t.createdAt||null;case "awaiting_clinic":return t.lastReminderAt??null;case "processing":return t.parsingStartedAt??t.reviewStartedAt??null;case "ready":return r==="published"&&t.updatedAt||null;default:return null}}i(bg,"railTimestamp");function xd(e,t,r,o){return {key:e,title:Ln[e],detail:pg(e,t,r),at:bg(e,t,r),state:o}}i(xd,"railEvent");function yr(e,t){return {key:e,title:Ln[e],detail:og[e]??null,at:t.updatedAt||null,state:"failed"}}i(yr,"terminalEvent");function ks(e,t,r,o,n){return e.map((l,a)=>{let c=n?.(l)??null;if(c!==null)return c;let s=o==="published"||a<t?"done":a===t?"current":"upcoming";return xd(l,r,o,s)}).flatMap(l=>yg(l,r,o))}i(ks,"walkRail");function Ts(e){let t=sg(e),r=i(n=>xd(n,e,t,"done"),"done");if(t==="revoked")return [r("requested"),yr("revoked",e)];if(e.convertedToUploadAt)return t==="failed"?[r("requested"),r("sent_to_clinic"),wd(e),r("awaiting_upload"),r("records_received"),yr("processing_failed",e)]:ks(ng,fg(t),e,t,n=>n==="awaiting_clinic"?wd(e):null);if(e.source==="owner_provided"){if(t==="failed"||t==="clinic_declined")return [r("requested"),r("awaiting_upload"),r("records_received"),yr("processing_failed",e)];let n=gg(t);return ks(rg,n<0?1:n,e,t)}if(t==="clinic_declined")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),yr("clinic_declined",e)];if(t==="clinic_responded_no_records")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),yr("clinic_no_records",e)];if(t==="failed"){let n=e.failureCode??null;return n==="no_response"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),yr("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[r("requested"),yr("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),r("records_received"),yr("processing_failed",e)]:[r("requested"),yr("delivery_failed",e)]}let o=lg(t);return ks(tg,o<0?1:o,e,t)}i(Ts,"buildRequestTimeline");var vg=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),Fo=24,_s=10;function Mo({request:e}){let t=Cg(),r=Ts(e);return jsx(View,{style:t.container,accessibilityRole:"summary",children:r.map((o,n)=>jsx(wg,{event:o,isLast:n===r.length-1,styles:t},o.key))})}i(Mo,"RequestTimeline");function wg({event:e,isLast:t,styles:r}){let o=e.at?Y(e.at):null,n=[e.title,e.detail,o,vg[e.state]].filter(Boolean);return jsxs(View,{style:r.row,accessible:true,accessibilityRole:"text",accessibilityLabel:n.join(", "),testID:`records-timeline-${e.key}`,children:[jsxs(View,{style:r.railColumn,children:[jsx(xg,{state:e.state,styles:r}),t?null:jsx(View,{style:[r.connector,e.state==="done"&&r.connectorDone],accessibilityElementsHidden:true,importantForAccessibility:"no"})]}),jsxs(View,{style:r.body,children:[jsxs(View,{style:r.titleRow,children:[jsx(m,{style:[r.title,e.state==="current"&&r.titleCurrent,e.state==="failed"&&r.titleFailed,e.state==="upcoming"&&r.titleUpcoming],children:e.title}),o?jsx(m,{style:r.date,children:o}):null]}),e.detail?jsx(m,{style:[r.detail,e.state==="upcoming"&&r.detailUpcoming],children:e.detail}):null]})]})}i(wg,"TimelineRow");function xg({state:e,styles:t}){return e==="done"?jsx(View,{style:[t.dot,t.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{tier:"badge",style:[t.glyph,t.glyphOnBrand],children:"\u2713"})}):e==="failed"?jsx(View,{style:[t.dot,t.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{tier:"badge",style:t.glyph,children:"!"})}):e==="current"?jsx(View,{style:[t.dot,t.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(View,{style:t.dotCurrentCore})}):jsx(View,{style:[t.dot,t.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(xg,"TimelineDot");function Cg(){let e=V();return useMemo(()=>Eg(e),[e])}i(Cg,"useStyles");function Eg(e){let{color:t,type:r}=e,{size:o}=r;return StyleSheet.create({container:{gap:0},row:{flexDirection:"row",alignItems:"flex-start",gap:12},railColumn:{alignItems:"center",width:Fo},body:{flex:1,paddingBottom:18,gap:2},titleRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:8},dot:{width:Fo,height:Fo,borderRadius:Fo/2,alignItems:"center",justifyContent:"center"},dotDone:{backgroundColor:t.brand},dotFailed:{backgroundColor:t.danger},dotCurrent:{borderWidth:2,borderColor:t.brand,backgroundColor:t.surface},dotCurrentCore:{width:_s,height:_s,borderRadius:_s/2,backgroundColor:t.brand},dotUpcoming:{borderWidth:2,borderColor:t.borderHairlineGreen,backgroundColor:t.surface},glyph:{...T(e,"bold"),fontSize:o.caption,lineHeight:o.caption+2,color:t.surface},glyphOnBrand:{color:t.onPrimary},connector:{width:2,flex:1,minHeight:22,backgroundColor:t.borderHairlineGreen,marginVertical:2},connectorDone:{backgroundColor:t.brand},title:{flex:1,...T(e,"bold"),fontSize:o.body,lineHeight:o.body+4,color:t.text.primary},titleCurrent:{color:t.brandInk},titleFailed:{color:t.danger},titleUpcoming:{color:t.text.muted,...T(e,"regular")},date:{...T(e,"regular"),fontSize:o.caption,lineHeight:o.caption+4,color:t.text.muted},detail:{...T(e,"regular"),fontSize:o.bodyTight,lineHeight:o.bodyTight+4,color:t.text.muted},detailUpcoming:{color:t.text.muted,opacity:.7}})}i(Eg,"makeStyles");function tn(e,t,r){let o=_r(e,r);switch(o.kind){case "consent_required":return jsx(Tg,{onGrant:t});case "consent_unavailable":return jsx(_g,{});case "session_required":return jsx(Pg,{});case "withheld":return jsx(Ig,{});case "pet_not_found":case "error":return jsx(Dg,{error:o.error,onRetry:e.refresh});default:return Rr(o)}}i(tn,"renderErrorFamily");function rn(e,t){return ()=>{let r=gs(t,e.consent);if(r.length===0)return;let o=`records-consent-${Date.now().toString(36)}`;e.grantConsent(r,o);}}i(rn,"makeGrantHandler");function Sd({records:e}){let t=qn(),r=e.uploadQueue;if(r.length===0)return null;let o=r.filter(a=>a.status!=="skipped"),n=o.filter(a=>a.status==="done").length,l=hd(Rd(r));return jsxs(View,{style:t.timeline,testID:"records-upload-queue",children:[l!==null?jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"polite",style:t.errorText,children:l}):null,o.length>0?jsx(View,{accessibilityLiveRegion:"polite",accessibilityLabel:e.isUploading?$r.uploading(n,o.length):$r.uploaded(n,o.length),children:o.map(a=>{let c=Math.round(a.progress*100);return jsxs(View,{style:t.row,testID:`records-upload-file-${a.status}`,children:[jsx(m,{style:t.rowLabel,children:a.name??""}),jsx(m,{style:t.rowValue,children:bd(a)}),a.status==="uploading"?jsx(View,{style:t.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:c},children:jsx(View,{style:[t.progressFill,{width:`${c}%`}]})}):null,a.status==="failed"&&a.error?jsx(m,{style:t.timelineMeta,children:a.error.displayMessage}):null]},a.key)})}):null]})}i(Sd,"UploadQueue");function Tg({onGrant:e}){let t=qn();return jsx(View,{style:t.centered,accessible:true,accessibilityRole:"alert",accessibilityLabel:pe.consentRequired,children:jsx(Pressable,{onPress:e,accessibilityRole:"button",accessibilityLabel:pe.allow,style:t.primaryButton,children:jsx(m,{style:t.primaryLabel,children:pe.allow})})})}i(Tg,"ConsentRequiredState");function Ds({label:e,glyph:t}){let r=qn();return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(e);},[e]),jsxs(View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",accessibilityLabel:e,children:[jsx(View,{style:t==="withheld"?r.withheldGlyph:r.emptyGlyph}),jsx(m,{style:r.errorText,children:e})]})}i(Ds,"AlertState");function _g(){return jsx(Ds,{label:pe.consentRequired,glyph:"empty"})}i(_g,"ConsentUnavailableState");function Pg(){return jsx(Ds,{label:pe.sessionRequired,glyph:"empty"})}i(Pg,"SessionRequiredState");function Ig(){return jsx(Ds,{label:pe.recordUnavailable,glyph:"withheld"})}i(Ig,"WithheldState");function Dg({error:e,onRetry:t}){let r=qn();return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(e.displayMessage);},[e.displayMessage]),jsxs(View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:[jsx(m,{style:r.errorText,children:e.displayMessage}),e.retryable?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:pe.retry,style:r.primaryButton,children:jsx(m,{style:r.primaryLabel,children:pe.retry})}):null]})}i(Dg,"ErrorState");function kd({call:e,prompt:t}){let r=qn(),o=t.trim().length>0?t:An.fallbackPrompt;return jsxs(View,{style:r.callCard,accessibilityRole:"summary",children:[jsx(m,{style:r.timelineLabel,children:An.heading}),jsx(m,{style:r.timelineMeta,children:o}),jsx(Pressable,{onPress:()=>{Linking?.openURL?.(e.dial);},accessibilityRole:"button",accessibilityLabel:An.callAt(e.phone),style:r.linkButton,testID:"records-call-clinic",children:jsx(m,{style:r.linkLabel,children:An.call})})]})}i(kd,"ClinicCallCard");function qn(){let e=V();return useMemo(()=>Ag(e),[e])}i(qn,"useStyles");function Ag(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:a,lineHeight:c,letterSpacing:s}=n,d=rt(l.recordCard,StyleSheet.hairlineWidth),u=at(l.recordCard),p=i((f,x)=>Math.round(f*x),"lh"),g=StyleSheet.hairlineWidth,b=r.xxl*3+r.xl,R=r.xxl+r.md,v=r.xxl+r.sm,w=e.brightness==="dark"?t.errorRed:t.danger,y={shadowColor:t.brand,shadowOffset:{width:0,height:r.xs},shadowRadius:r.sm,shadowOpacity:.08,elevation:r.xs};return StyleSheet.create({container:{flex:1,minHeight:b,backgroundColor:t.background},body:{flex:1},centered:{minHeight:b,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:v,height:v,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:g,borderColor:t.brandBorder},withheldGlyph:{width:v,height:v,borderRadius:o.sm,backgroundColor:t.badgeBgCaution,borderWidth:g,borderColor:t.cautionAccent},errorText:{...T(e,"regular"),fontSize:a.subtitle,lineHeight:p(a.subtitle,c.snug),color:w,textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...y,...rt(l.primaryButton)},primaryLabel:{...T(e,"bold"),color:t.onPrimary,fontSize:a.body,letterSpacing:s.tight,...at(l.primaryButton)},linkButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...y,...rt(l.primaryButton)},linkLabel:{...T(e,"bold"),color:t.onPrimary,fontSize:a.body,letterSpacing:s.tight,...at(l.primaryButton)},disabledButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.surfaceSubtle,borderWidth:g,borderColor:t.brandBorder},disabledLabel:{...T(e,"bold"),color:t.text.muted,fontSize:a.body,letterSpacing:s.tight},list:{flex:1},listContent:{padding:r.lg,gap:r.md},timeline:{paddingVertical:r.md,paddingHorizontal:r.lg,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:g,borderColor:t.brandBorder,gap:r.xs,...y,...d},timelineTitle:{...T(e,"bold"),fontSize:a.heading,lineHeight:p(a.heading,c.snug),color:t.text.primary,letterSpacing:s.tight,...u},timelineLabel:{...T(e,"bold"),fontSize:a.subtitle,lineHeight:p(a.subtitle,c.snug),color:t.text.secondary,letterSpacing:s.tight,...u},callCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:g,borderColor:t.brandBorder,...d},timelineMeta:{...T(e,"regular"),fontSize:a.bodyTight,lineHeight:p(a.bodyTight,c.normal),color:t.text.muted,...u},recordBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:g,borderColor:t.brandBorder,...y,...d},row:{flexDirection:"row",justifyContent:"space-between",gap:r.md,paddingVertical:r.xs,borderBottomWidth:g,borderBottomColor:t.borderHairlineGreen},rowLabel:{...T(e,"regular"),fontSize:a.body,lineHeight:p(a.body,c.normal),color:t.text.muted,flexShrink:1,...u},rowValue:{...T(e,"medium"),fontSize:a.body,lineHeight:p(a.body,c.normal),color:t.text.primary,textAlign:"right",flexShrink:1,...u},disclaimer:{...T(e,"regular"),fontSize:a.caption,lineHeight:p(a.caption,c.normal),color:t.text.muted,marginTop:r.md},progressTrack:{height:r.xs,borderRadius:o.pill,backgroundColor:t.brandSofter,overflow:"hidden",width:"100%"},progressFill:{height:"100%",backgroundColor:t.brand}})}i(Ag,"makeStyles");var zt=Object.freeze({title:"Medical records",subtitle:i(e=>{let t=e?.trim()??"";return t.length>0?`${t}\u2019s uploads and clinic requests`:"Every upload and clinic request"},"subtitle"),requestRecords:"Request records",requestRecordsA11y:"Request records from a clinic",uploadOwn:"I already have the records",uploadOwnA11y:"Upload records you already have",ownerUpload:"Records you uploaded",clinicRequest:"Clinic request",meta:i((e,t)=>`${e?"Uploaded":"Requested"} ${Y(t)}`,"meta"),rowA11y:i((e,t,r)=>`${e}, ${t}, status ${r}`,"rowA11y"),askA11y:i(e=>`Ask Everfur about ${e}`,"askA11y")}),Bo=Object.freeze({preparing:"Preparing",sent:"Sent",processing:"Processing",done:"Ready"});function Og(e){switch(e){case "awaiting_clinic":return Bo.sent;case "received":case "parsing":case "in_review":return Bo.processing;case "published":return Bo.done;default:return Bo.preparing}}i(Og,"stepLabel");function Td(e){let t=e.source==="owner_provided",r=e.clinicName?.trim()||(t?zt.ownerUpload:zt.clinicRequest),o=e.statusLabel.trim()||Og(e.status),n=zt.meta(t,e.createdAt);return Object.freeze({source:r,meta:n,status:o,ownerUpload:t,a11yLabel:zt.rowA11y(r,n,o)})}i(Td,"requestRowView");var Lg=new Set(["records_received","parsing","parsing_failed","in_review","review_email_failed"]),Vg=new Set(["received","parsing","in_review"]);function qg(e){return e.wireStatus!==void 0?Lg.has(e.wireStatus):Vg.has(e.status)}i(qg,"isProcessing");function _d(e,t,r={}){let o=e.filter(c=>!gr(c.status));if(e.length===0||r.activeOnly===true&&o.length===0)return null;let n=e.filter(qg).length,l=n>0?`${n} document${n===1?"":"s"} being read`:o.length>0?`${o.length} active record request${o.length===1?"":"s"}`:"Your record requests",a=n>0?`We\u2019ll add ${n===1?"it":"them"} to ${t}\u2019s records once ready.`:o.length>0?"See each clinic\u2019s status and what happens next.":"See the status of every upload and clinic request.";return Object.freeze({title:l,subtitle:a,processing:n>0,a11yLabel:`${l}. ${a}`})}i(_d,"requestsStatusCardView");function As(e){let{style:t,renderPending:r,...o}=Oe(e,["onNavigate","onBack","onAsk"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(Ng,{...o,style:t})})}i(As,"EverfurRecordsRequests");function Ng({petRef:e,petName:t,controller:r,onNavigate:o,onBack:n,onAsk:l,style:a}){let c=ue(),s=Os(),d=st(r?{petRef:e,controller:r}:{petRef:e}),u=useMemo(()=>bs(d.requests.filter(b=>b.petRef===e)),[d.requests,e]),p=l?b=>{let R=Eo(t,{clinicName:b.clinicName??null,statusLabel:Ur(b),status:b.status,heldItemCount:b.heldItemCount},b.id);l(R.prompt,R.entityRef);}:void 0,g;return d.status==="loading"&&u.length===0?g=jsx(po,{testID:"records-list-loading"}):d.status==="error"&&u.length===0?g=jsx(Ue,{variant:pt(d.error),message:d.error?.displayMessage,onAction:d.error?.retryable?d.refresh:void 0,testID:"records-list-error"}):u.length===0?g=jsx(Ue,{variant:"no_requests",testID:"records-list-empty"}):g=jsx(ScrollView,{contentContainerStyle:s.list,testID:"records-list-results",children:u.map(b=>jsx(Mg,{request:b,onOpen:o?()=>o({name:"request",requestId:b.id}):void 0,onAsk:p?()=>p(b):void 0},b.id))}),jsxs(View,{style:[c.root,a],children:[jsx(Ke,{title:zt.title,onBack:n,testID:"records-list-header"}),u.length>0?jsx(m,{style:s.subtitle,testID:"records-list-subtitle",children:zt.subtitle(t)}):null,jsx(View,{style:c.body,children:g}),o?jsxs(View,{style:s.footer,children:[jsx(J,{label:zt.requestRecords,accessibilityLabel:zt.requestRecordsA11y,onPress:()=>o({name:"clinicPicker"}),testID:"records-list-new"}),jsx(J,{label:zt.uploadOwn,kind:"outline",accessibilityLabel:zt.uploadOwnA11y,onPress:()=>o({name:"upload"}),testID:"records-list-upload-own"})]}):null,jsx(Ve,{})]})}i(Ng,"RequestsBody");function Mg({request:e,onOpen:t,onAsk:r}){let o=ue(),n=Os(),l=Td(e),a=$c(e),c=jsxs(Fragment,{children:[jsx(View,{style:[n.bubble,o.chipTones[a].bg],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxs(View,{style:n.copy,children:[jsx(m,{style:n.source,numberOfLines:1,children:l.source}),jsx(m,{style:n.meta,numberOfLines:1,children:l.meta}),jsx(View,{accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(St,{label:l.status,tone:a})})]}),t?jsx(er,{}):null]});return jsxs(View,{style:n.row,testID:`records-request-row-${e.id}`,children:[t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:l.a11yLabel,style:n.rowInner,testID:`records-request-open-${e.id}`,children:c}):jsx(View,{style:n.rowInner,accessible:true,accessibilityLabel:l.a11yLabel,children:c}),r?jsx(J,{label:Sr.ask,kind:"ask",accessibilityLabel:zt.askA11y(l.source),onPress:r,testID:`records-request-ask-${e.id}`}):null]})}i(Mg,"RequestRow");function zn({requests:e,petName:t,activeOnly:r=false,onOpen:o}){let n=Os(),l=_d(e,Fe(t),{activeOnly:r});return l===null||o===void 0?null:jsxs(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:l.a11yLabel,style:n.card,testID:"records-requests-status",children:[jsx(View,{style:[n.cardBubble,l.processing?n.cardBubbleProcessing:null],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxs(View,{style:n.cardText,children:[jsx(m,{style:n.cardTitle,children:l.title}),jsx(m,{style:n.cardSubtitle,children:l.subtitle})]}),jsx(er,{})]})}i(zn,"RecordsRequestsStatusCard");function Os(){let e=V();return useMemo(()=>Bg(e),[e])}i(Os,"useLocalStyles");function Bg(e){let{color:t,space:r,radius:o,type:n}=e,l=i((c,s)=>Math.round(c*s),"lh"),a=r.xxl+r.xs/2;return StyleSheet.create({subtitle:{...T(e,"regular"),fontSize:n.size.caption,lineHeight:l(n.size.caption,n.lineHeight.normal),color:t.text.muted,paddingHorizontal:r.lg,paddingBottom:r.md},list:{paddingHorizontal:r.lg,paddingBottom:r.xl,gap:r.md},row:{borderRadius:o.lg,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},rowInner:{flexDirection:"row",alignItems:"center",gap:r.md},bubble:{width:a,height:a,borderRadius:a/2},copy:{flex:1,gap:r.xs+1},source:{...T(e,"bold"),fontSize:n.size.body,lineHeight:l(n.size.body,n.lineHeight.snug),color:t.text.primary},meta:{...T(e,"regular"),fontSize:n.size.tiny,lineHeight:l(n.size.tiny,n.lineHeight.normal),color:t.text.muted},footer:{paddingHorizontal:r.lg,paddingTop:r.sm+r.xs/2,paddingBottom:r.lg,gap:r.sm+r.xs/2,borderTopWidth:1,borderTopColor:t.borderHairlineGreen},card:{flexDirection:"row",alignItems:"center",gap:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,paddingHorizontal:r.md+r.xs,paddingVertical:r.md},cardBubble:{width:r.xl+r.xs/2,height:r.xl+r.xs/2,borderRadius:o.pill,borderWidth:2,borderColor:t.brandInk},cardBubbleProcessing:{borderColor:t.warningStrong,backgroundColor:t.badgeBgCaution},cardText:{flex:1,gap:2},cardTitle:{...T(e,"bold"),fontSize:n.size.bodyTight,lineHeight:l(n.size.bodyTight,n.lineHeight.snug),color:t.brandInk},cardSubtitle:{...T(e,"regular"),fontSize:n.size.caption,lineHeight:l(n.size.caption,n.lineHeight.normal),color:t.text.muted}})}i(Bg,"makeLocalStyles");var $g=i((e,t)=>e.getRecordDepth(t),"readDepth"),Wg=i(e=>!e.available,"depthEmpty");function zs(e){let{style:t,renderPending:r,...o}=Oe(e,["onNavigate","onBack","onAsk"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(Gg,{...o,style:t})})}i(zs,"EverfurRecordsDashboard");function Gg({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:a,style:c}){let s=ue(),d=Fs(),u=st(r?{petRef:e,controller:r}:{petRef:e}),p=us(e),g=Gt(e,$g,Wg),[b,R]=useState(null),v=useCallback((C,L)=>R({marker:C,point:L}),[]),w=useMemo(()=>Hr(o,u.consent),[o,u.consent]),y=useMemo(()=>rn(u,o),[u,o]),f=p.markers?.markers??[],x=f.length>0,h=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,_=to(u.requests,e),S=u.requests.filter(C=>C.petRef===e),k=n?()=>n({name:"requests"}):void 0,E=xi({hasMarkers:x,requests:u.requests,petRef:e}),A=Ci({recordLoading:u.status==="loading",hasFullRecord:h,recordError:u.status==="error",markersLoading:p.status==="loading",markersError:p.status==="error",hasMarkers:x,requestsLoading:u.status==="loading",dashboardState:E,drivingRequest:_}),B=p.markers?.disclaimer??u.record?.disclaimer??"",z=i(()=>{u.refresh(),p.refresh(),g.refresh();},"retryAll"),U=g.value!==null&&!g.value.withheld&&g.value.available?g.value:null,j=Fe(t),re=a&&p.markers?.summary?()=>{let C=Fc(t,p.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);a(C.prompt,C.entityRef);}:void 0,se=a?C=>{let L=zc(t,{canonicalName:C.name,markerId:C.markerId,latestValueText:C.latest?kt(C.latest.value,C.unit,C.latest.qualitativeResult):null,statusText:C.latest?tr(C.latest.status).label:null,trajectoryText:Kr(C.trajectory,C.points.length),meaningText:C.meaning});a(L.prompt,L.entityRef);}:void 0,Te=a&&b?()=>{let{marker:C,point:L}=b,X=Nc(t,{canonicalName:C.name,valueText:kt(L.value,C.unit,L.qualitativeResult),collectedAt:Y(L.at),sourceClinic:L.sourceClinic,referenceText:L.refLow!==null||L.refHigh!==null?Co(L,C.unit):null,flagged:L.status==="above"?"above":L.status==="below"?"below":null,reviewed:L.reviewed,entityId:L.docId??C.markerId});R(null),a(X.prompt,X.entityRef);}:void 0,ee=jsxs(Fragment,{children:[p.markers?.summary?jsx(View,{style:s.inset,children:jsx(Kc,{summary:p.markers.summary,onAsk:re,testID:"dashboard-marker-summary"})}):null,jsx(m,{style:s.lead,children:mt.lead(t)}),jsx(ed,{markers:f,onPointPress:v,onAsk:se})]}),I=i(C=>n?jsxs(View,{style:[s.inset,d.actions],children:[C?jsx(Ls,{label:mt.viewFullRecord,onPress:()=>n({name:"record"}),testID:"dashboard-full-record-action"}):null,jsx(Ls,{label:mt.viewTimeline,onPress:()=>n({name:"timeline"}),testID:"dashboard-timeline-action"})]}):null,"actions"),D;if(u.status==="error"){let C=_r(u,w);D=C.kind==="error"||C.kind==="pet_not_found"?jsx(Ue,{variant:pt(C.error),message:C.error.displayMessage,onAction:C.error.retryable?z:void 0,testID:"dashboard-error"}):tn(u,y,w);}else switch(A){case "loading":D=jsx(uo,{testID:"dashboard-loading"});break;case "record":D=jsxs(ScrollView,{contentContainerStyle:s.contentTight,testID:"dashboard-record",children:[x?ee:p.status==="error"?jsx(View,{style:[s.inset,d.actions],children:jsx(Ls,{label:mt.retryMarkers,onPress:z,testID:"dashboard-markers-retry"})}):null,jsx(View,{style:s.inset,children:u.record?jsx(zo,{record:u.record,depth:U,petName:t,showLabs:!x,onNavigate:n,onAsk:a}):null}),jsx(View,{style:s.inset,children:jsx(zn,{requests:S,petName:t,activeOnly:true,onOpen:k})}),I(true)]});break;case "error":D=jsx(Ue,{variant:pt(p.error??u.error),message:(p.error??u.error)?.displayMessage,onAction:(p.error??u.error)?.retryable?z:void 0,testID:"dashboard-error"});break;case "in_progress":D=jsxs(ScrollView,{contentContainerStyle:s.content,testID:"dashboard-in-progress",children:[_?jsx(Yg,{request:_,petName:j,onOpen:n?()=>n({name:"request",requestId:_.id}):void 0,onAsk:a?()=>{let C=Eo(t,{clinicName:_.clinicName??null,statusLabel:Ur(_),status:_.status,heldItemCount:_.heldItemCount},_.id);a(C.prompt,C.entityRef);}:void 0}):null,jsx(zn,{requests:S,petName:t,onOpen:k}),jsx(kr,{disclaimer:B})]});break;case "none":D=jsxs(ScrollView,{contentContainerStyle:s.content,testID:"dashboard-request-prompt",children:[jsxs(View,{style:d.promptCard,children:[jsxs(View,{style:d.promptHeader,children:[jsx(View,{style:d.promptGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:d.promptTitle,children:Vr.title(t)})]}),jsx(m,{style:d.promptBody,children:Vr.body}),n?jsxs(Fragment,{children:[jsx(J,{label:Vr.requestFromClinic,accessibilityLabel:Vr.requestFromClinicA11y(t),onPress:()=>n({name:"clinicPicker"}),style:d.promptCta,testID:"dashboard-request-prompt-clinic"}),jsx(J,{label:Vr.uploadDocument,kind:"outline",accessibilityLabel:Vr.uploadDocumentA11y(t),onPress:()=>n({name:"upload"}),style:d.promptCtaSecondary,testID:"dashboard-request-prompt-upload"})]}):null]}),jsx(zn,{requests:S,petName:t,onOpen:k}),jsx(kr,{disclaimer:B})]});break;case "labs_only":D=jsxs(ScrollView,{contentContainerStyle:s.contentTight,testID:"dashboard-labs-only",children:[ee,jsx(View,{style:s.inset,children:jsx(zn,{requests:S,petName:t,activeOnly:true,onOpen:k})}),jsx(View,{style:s.inset,children:jsx(kr,{disclaimer:B})}),I(false)]});break;default:D=Rr(A);}return jsxs(View,{style:[s.root,c],children:[jsx(Ke,{title:mt.title,onBack:l,testID:"dashboard-header",right:n?jsx(Pressable,{onPress:()=>n({name:"timeline"}),accessibilityRole:"button",accessibilityLabel:mt.openTimeline,hitSlop:12,style:d.headerButton,testID:"dashboard-timeline-link",children:jsx(Ol,{})}):void 0}),jsx(View,{style:s.body,children:D}),jsx(td,{marker:b?.marker??null,point:b?.point??null,onClose:()=>R(null),onAsk:Te}),jsx(Ve,{})]})}i(Gg,"DashboardBody");function Ls({label:e,onPress:t,testID:r}){let o=Fs();return jsxs(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:e,style:o.actionRow,testID:r,children:[jsxs(View,{style:o.actionLeft,children:[jsx(View,{style:o.actionIcon,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:o.actionLabel,children:e})]}),jsx(er,{})]})}i(Ls,"ActionRow");function Yg({request:e,petName:t,onOpen:r,onAsk:o}){let n=ue(),l=Fs(),a=e.clinicName?.trim()||Sr.title(t),c=Ur(e),s=jsxs(View,{style:l.inProgressInner,children:[jsxs(View,{style:l.inProgressHead,children:[jsx(m,{style:l.inProgressTitle,children:a}),r?jsx(er,{}):null]}),jsx(Mo,{request:e}),c.length>0?jsx(View,{style:n.statusCard,children:jsx(m,{style:n.statusText,children:c})}):null]});return jsxs(View,{style:l.inProgressCard,testID:"dashboard-in-progress-card",accessibilityRole:"summary",accessible:r?false:void 0,accessibilityLabel:r?void 0:Sr.a11y(t),children:[r?jsx(Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Sr.openA11y(t,c),testID:"dashboard-in-progress-open",children:s}):s,o?jsx(J,{label:Sr.ask,kind:"ask",accessibilityLabel:Sr.askA11y,onPress:o,testID:"dashboard-in-progress-ask"}):null]})}i(Yg,"InProgressCard");function Fs(){let e=V();return useMemo(()=>Kg(e),[e])}i(Fs,"useLocalStyles");function Kg(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,a=r.xxl+r.md;return StyleSheet.create({headerButton:{width:a,height:a,alignItems:"center",justifyContent:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},actionIcon:{width:r.lg+r.xs/2,height:r.lg+r.xs/2,borderRadius:o.xs,backgroundColor:t.brandSoft,borderWidth:l,borderColor:t.brandBorder},actionLabel:{flex:1,...T(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},inProgressCard:{borderRadius:o.lg-r.xs/2,backgroundColor:t.surface,borderWidth:l,borderColor:t.brandBorder,padding:r.lg+r.xs/2,gap:r.lg},inProgressInner:{gap:r.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},inProgressTitle:{flex:1,...T(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),color:t.text.primary},promptCard:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:l,borderColor:t.borderRingCream,paddingHorizontal:r.lg+r.xs,paddingVertical:r.lg+r.xs/2},promptHeader:{flexDirection:"row",alignItems:"center",gap:r.xs+1},promptGlyph:{width:r.xl+1,height:r.xl+1,borderRadius:o.xs,borderWidth:2,borderColor:t.warningStrong},promptTitle:{flex:1,...T(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),letterSpacing:n.letterSpacing.headerBrand,color:t.brandInk},promptBody:{marginTop:r.sm-1,...T(e,"regular"),fontSize:n.size.bodyTight,lineHeight:r.lg+r.xs,color:t.text.primary},promptCta:{marginTop:r.sm-1,minHeight:r.xxl+r.sm},promptCtaSecondary:{marginTop:r.sm,minHeight:r.xxl+r.sm}})}i(Kg,"makeLocalStyles");var Uo=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function Od(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(Od,"toMillis");function Ld(e){let t=[...e.visits.map((r,o)=>({key:`visit-${o}-${r.visitId}`,kind:"visit",kindLabel:ge.kind.visit,at:r.visitDate,date:Y(r.visitDate),title:r.summary??ge.clinicVisit,detail:r.veterinarian?ge.doctor(r.veterinarian):null,docId:r.docId})),...e.vaccines.map((r,o)=>{let n=[];return r.lot&&n.push(ge.lot(r.lot)),r.expiresOn&&n.push(ge.expires(Y(r.expiresOn))),{key:`vaccine-${o}-${r.vaccineId}`,kind:"vaccine",kindLabel:ge.kind.vaccine,at:r.administeredOn,date:Y(r.administeredOn),title:r.product||ge.kind.vaccine,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}}),...e.weights.map((r,o)=>({key:`weight-${o}-${r.weightId}`,kind:"weight",kindLabel:ge.kind.weight,at:r.observedOn,date:Y(r.observedOn),title:Bl(r.weightKg),detail:null,docId:r.docId})),...e.medications.map((r,o)=>{let n=[r.dose,r.route,r.frequency].filter(l=>!!l);return {key:`medication-${o}-${r.medicationId}`,kind:"medication",kindLabel:ge.kind.medication,at:r.startedOn,date:Y(r.startedOn),title:r.drugName||ge.kind.medication,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}})];return Object.freeze(t.sort((r,o)=>{let n=Od(r.at),l=Od(o.at);return n===null&&l===null?Uo[r.kind]-Uo[o.kind]:n===null?1:l===null?-1:l!==n?l-n:Uo[r.kind]-Uo[o.kind]}))}i(Ld,"buildTimelineRows");var tb=300,rb=i((e,t)=>e.getTimeline(t),"readTimeline"),nb=i(e=>e.isEmpty,"timelineEmpty");var ob=i(e=>e.contributions.length===0,"contributionsEmpty");function zd({petRef:e,style:t,onBack:r}){let o=Gt(e,rb,nb);return jsx(Nd,{state:o,style:t,onBack:r,header:jsx(Ke,{title:ge.timeline,onBack:mn(r),testID:"timeline-header"}),loading:jsx(Wl,{testID:"timeline-loading"}),empty:jsx(Ue,{variant:"no_records",testID:"timeline-empty"}),render:n=>jsx(ab,{timeline:n})})}i(zd,"EverfurRecordsTimeline");function Fd({petRef:e,docId:t,style:r,onBack:o}){let n=useCallback((c,s)=>c.getDocumentContributions(s,t),[t]),l=Gt(e,n,ob,t),a=l.value?.document?.title?.trim()||ge.uploadedDocument;return jsx(Nd,{state:l,style:r,onBack:o,header:jsx(Ke,{title:a,onBack:mn(o),testID:"contributions-header"}),empty:jsx(Ue,{variant:"no_records",testID:"contributions-empty"}),render:c=>jsx(lb,{view:c})})}i(Fd,"EverfurDocumentContributions");function Nd({state:e,style:t,header:r,loading:o,empty:n,render:l,onBack:a}){let c=Ns();return jsx(Le,{capability:"records",style:t,...ze(mn(a),Ye),children:jsxs(View,{style:[c.container,t],children:[r??null,jsx(View,{style:c.body,children:ib(e,l,c,o,n)}),jsx(Ve,{})]})})}i(Nd,"DepthSurface");function ib(e,t,r,o,n){switch(e.status){case "loading":return o??jsx(sb,{styles:r});case "empty":return n??jsx(View,{style:r.centered,accessible:true,accessibilityRole:"summary",accessibilityLabel:pe.empty,children:jsx(View,{style:r.emptyGlyph})});case "error":return e.error?jsx(Ue,{variant:pt(e.error),message:e.error.displayMessage,onAction:e.error.retryable?e.refresh:void 0,testID:"depth-error"}):null;case "populated":return e.value===null||e.value.withheld?null:t(e.value);default:return null}}i(ib,"renderState");function sb({styles:e}){let[t,r]=useState(false);return useEffect(()=>{let o=setTimeout(()=>r(true),tb);return ()=>clearTimeout(o)},[]),jsx(View,{style:e.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:pe.loading,children:t?jsx(ActivityIndicator,{}):null})}i(sb,"LoadingState");function ab({timeline:e}){let t=Ns(),r=Ld(e);return jsxs(ScrollView,{style:t.list,contentContainerStyle:t.timelineContent,accessibilityLabel:ge.timeline,children:[e.disclaimer.length>0?jsx(View,{style:t.timelineBand,accessible:true,accessibilityRole:"text",accessibilityLabel:mt.important(e.disclaimer),children:jsx(m,{style:t.timelineBandText,children:e.disclaimer})}):null,r.map((o,n)=>jsxs(View,{children:[n>0?jsx(View,{style:t.timelineSeparator}):null,jsxs(View,{style:t.timelineRow,accessible:true,accessibilityRole:"text",accessibilityLabel:[o.kindLabel,o.date,o.title,o.detail].filter(Boolean).join(", "),testID:`records-timeline-row-${o.kind}`,children:[jsx(View,{style:t.timelineBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxs(View,{style:t.timelineBody,children:[jsxs(View,{style:t.topLine,children:[jsx(m,{style:t.timelineKind,children:o.kindLabel}),jsx(m,{style:t.date,children:o.date})]}),jsx(m,{style:t.timelineTitle,children:o.title}),o.detail?jsx(m,{style:t.rowDetail,children:o.detail}):null]})]})]},o.key))]})}i(ab,"TimelineBody");function lb({view:e}){let t=Ns();return jsxs(ScrollView,{style:t.list,contentContainerStyle:t.listContent,accessibilityLabel:pe.records,children:[e.document?.receivedAt?jsx(m,{style:t.rowDetail,children:Y(e.document.receivedAt)}):null,jsx(View,{style:t.card,children:e.contributions.map(r=>jsxs(View,{style:t.row,accessible:true,accessibilityRole:"text",children:[jsx(m,{style:t.rowTitle,children:r.label}),jsx(m,{style:t.rowValue,children:Yr(r.value,r.unit)}),r.observedAt?jsx(m,{style:t.rowDetail,children:Y(r.observedAt)}):null]},r.key))})]})}i(lb,"ContributionsBody");function Ns(){let e=V();return useMemo(()=>cb(e),[e])}i(Ns,"useStyles");function cb(e){let{color:t,space:r,radius:o,type:n,slots:l}=e,{size:a,lineHeight:c}=n,s=i((w,y)=>Math.round(w*y),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl*3+r.xl,p=r.xxl+r.md,g=e.brightness==="dark"?t.errorRed:t.danger,b=at(l.recordCard),R=i((w,y,f,x="regular")=>({...T(e,x),fontSize:w,lineHeight:s(w,y),color:f}),"text"),v=i((w,y,f,x="regular")=>({...R(w,y,f,x),...b}),"inCard");return StyleSheet.create({container:{flex:1,minHeight:u,backgroundColor:t.background},body:{flex:1},centered:{minHeight:u,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:r.xxl+r.sm,height:r.xxl+r.sm,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},errorText:{...R(a.subtitle,c.snug,g),textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:p,minWidth:p,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...rt(l.primaryButton)},primaryLabel:{...T(e,"bold"),color:t.onPrimary,fontSize:a.body,...at(l.primaryButton)},list:{flex:1},listContent:{padding:r.lg,gap:r.md},section:{gap:r.sm},heading:{...R(a.heading,c.snug,t.text.primary,"bold")},card:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:d,borderColor:t.brandBorder,...rt(l.recordCard,d)},row:{gap:r.xs,paddingVertical:r.xs,borderBottomWidth:d,borderBottomColor:t.borderHairlineGreen},topLine:{flexDirection:"row",justifyContent:"space-between",gap:r.md},kindLabel:{...v(a.caption,c.normal,t.text.muted,"medium")},date:v(a.caption,c.normal,t.text.muted),rowTitle:{...v(a.body,c.normal,t.text.primary,"bold")},rowValue:{...v(a.body,c.normal,t.text.primary,"medium")},rowDetail:v(a.bodyTight,c.normal,t.text.muted),rowMuted:{...v(a.bodyTight,c.normal,t.text.muted),opacity:.7},chip:{...R(a.caption,c.normal,t.text.primary),alignSelf:"flex-start",paddingHorizontal:r.sm,paddingVertical:r.xs,borderRadius:o.pill},chipNeutral:{backgroundColor:t.badgeBgNeutral},chipCaution:{backgroundColor:t.badgeBgCaution},chipCritical:{backgroundColor:t.badgeBgCritical},disclaimer:{...R(a.caption,c.normal,t.text.muted),marginTop:r.md},timelineContent:{paddingBottom:r.xxl},timelineBand:{flexDirection:"row",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft,marginHorizontal:r.lg,marginTop:r.xs,marginBottom:r.md},timelineBandText:{flex:1,...R(a.caption,c.normal,t.text.secondary)},timelineSeparator:{height:d,backgroundColor:t.brandBorder,marginLeft:Hi},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBubble:{width:r.xxl+r.xs/2,height:r.xxl+r.xs/2,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},timelineBody:{flex:1,gap:r.xs-1},timelineKind:{...T(e,"mono"),fontSize:a.micro,lineHeight:a.bodyTight,letterSpacing:n.letterSpacing.eyebrow/3,textTransform:"uppercase",color:t.text.secondary},timelineTitle:{...R(a.body,c.normal,t.text.primary,"medium")}})}i(cb,"makeStyles");function Ms(e,t={}){let r=mr(),{userRef:o}=Se(),n=t.now??Date.now,[l,a]=useState(null),[c,s]=useState(true),[d,u]=useState(null),[p,g]=useState(null),b=p===true,[R,v]=useState({}),[w,y]=useState(false),[f,x]=useState(null),[h,_]=useState(false),[S,k]=useState(false),E=$n(e),A=useRef(0),B=useRef(true),z=useCallback(async()=>{let D=A.current+=1;if(s(true),u(null),o===null){a(null),s(false);return}let C=await r.listShares(e);D!==A.current||!B.current||(C.ok?(a(C.value),g(true)):Tr(C.error)?(a(null),g(false)):(a(null),u(C.error),Md(C)&&g(true)),s(false));},[r,e,o]);useEffect(()=>(B.current=true,z(),()=>{B.current=false,A.current+=1;}),[z]);let U=useRef(E);useEffect(()=>{U.current!==E&&(U.current=E,v({}),k(true),z());},[E,z]);let j=useCallback(async()=>{y(true);let D=await r.createShare(e);return B.current&&(y(false),D.ok?(v(C=>({...C,[D.value.shareId]:D.value.shareUrl})),z()):Tr(D.error)?g(false):sr(D.error)&&k(true)),D},[r,e,z]),re=useCallback(async D=>{x(D);let C=await r.revokeShare(e,D);return B.current&&(x(null),z()),C},[r,e,z]),se=useCallback(async()=>{_(true);let D=await r.getPdfLink(e);return B.current&&(_(false),!D.ok&&sr(D.error)&&k(true)),D},[r,e]),Te=useCallback(()=>{k(false),z();},[z]),ee=useMemo(()=>Hl(l??[],R,n()),[l,R,n]),I=c?"loading":d!==null?"error":ee.length===0?"empty":"populated";return useMemo(()=>({status:I,rows:ee,available:b,consentRequired:S,error:d,creating:w,revokingId:f,preparingPdf:h,createLink:j,revoke:re,pdfLink:se,refresh:Te}),[I,ee,b,S,d,w,f,h,j,re,se,Te])}i(Ms,"useRecordShares");function Md(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(Md,"answeredBehindGate");function Bd(e){return e.available||e.status!=="empty"}i(Bd,"sharesListShown");function Bs(e){let t=mr(),{userRef:r}=Se(),o=useMemo(()=>({}),[t,e,r]),[n,l]=useState({scope:o,lit:null});useEffect(()=>{if(r===null)return;let c=true;return t.listShares(e).then(s=>{c&&(!s.ok&&Tr(s.error)?l({scope:o,lit:false}):Md(s)&&l({scope:o,lit:true}));},()=>{}),()=>{c=false;}},[t,e,r,o]);let a=n.scope===o?n.lit:null;return useMemo(()=>({lit:a}),[a])}i(Bs,"useRecordsDepthProbe");function Hs(e){let t=mr(),o=Bs(e).lit===true,[n,l]=useState(false),[a,c]=useState(null),s=useRef(true);useEffect(()=>(s.current=true,()=>{s.current=false;}),[]);let d=useCallback(async()=>{l(true),c(null);let u=await t.getPdfLink(e);return s.current&&(l(false),u.ok||c(u.error)),u},[t,e]);return useMemo(()=>({preparing:n,available:o,error:a,pdfLink:d}),[n,o,a,d])}i(Hs,"useRecordPdfLink");async function Ud(e){await Share.share({message:ie.shareMessage(e),url:e});}i(Ud,"shareLinkViaOs");async function Wo(e){await Share.share(Platform.OS==="ios"?{url:e}:{message:e});}i(Wo,"shareFileLinkViaOs");var Pt=K.document,Wd=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),yb=i((e,t)=>e.getRecordDepth(t),"readDepth"),fb=i(e=>!e.available,"depthEmpty");function Us(e){let{style:t,renderPending:r,...o}=Oe(e,["onBack"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(bb,{...o,style:t})})}i(Us,"EverfurRecordDocument");function gb(e,t){return e.identity.length===0&&e.entities.length===0&&e.forwardLooking.length===0&&(t===null||t.labResults.length===0&&t.physicalExams.length===0&&t.clinicianNotes.length===0)}i(gb,"documentIsEmpty");function bb({petRef:e,petName:t,controller:r,consentVersion:o,onBack:n,onOpenUrl:l,style:a}){let c=ue(),s=Gd(),d=V(),u=st(r?{petRef:e,controller:r}:{petRef:e}),p=Gt(e,yb,fb),g=Hs(e),b=useMemo(()=>Hr(o,u.consent),[o,u.consent]),R=useMemo(()=>rn(u,o),[u,o]),v=p.value!==null&&!p.value.withheld&&p.value.available?p.value:null,w=u.record,[y,f]=useState(false),x=i(()=>{f(false),g.pdfLink().then(S=>{if(!S.ok)return;Or(l??(E=>Wo(E)),S.value.downloadUrl,"record_pdf").then(E=>{!E.ok&&!l&&f(true);});});},"download"),h,_=false;if(u.status==="loading"||p.status==="loading"&&w!==null)h=jsx(View,{style:s.centered,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:mt.loading,testID:"record-document-loading",children:jsx(ActivityIndicator,{color:d.color.brandInk})});else if(u.status==="error"){let S=_r(u,b);h=S.kind==="error"||S.kind==="pet_not_found"?jsx(Ue,{variant:pt(S.error),message:S.error.displayMessage,onAction:S.error.retryable?()=>{u.refresh(),p.refresh();}:void 0,testID:"record-document-error"}):tn(u,R,b);}else w===null||gb(w,v)?h=jsx(View,{style:s.centered,testID:"record-document-empty",children:jsx(m,{style:s.emptyText,children:Pt.empty})}):(_=true,h=jsx(hb,{record:w,depth:v,petName:t,wordmark:d.meta.displayName}));return jsxs(View,{style:[c.root,s.root,a],children:[jsx(Ke,{title:Pt.title,variant:"document",onBack:n,testID:"record-document-header",right:g.available&&_?jsx(Pressable,{onPress:x,disabled:g.preparing,accessibilityRole:"button",accessibilityLabel:Pt.download,accessibilityState:{disabled:g.preparing,busy:g.preparing},hitSlop:8,style:s.download,testID:"record-document-download",children:g.preparing?jsx(ActivityIndicator,{size:"small",color:d.color.brandInk}):jsx(ql,{})}):void 0}),g.error?jsx(m,{style:[c.errorText,s.inset],accessibilityRole:"alert",children:g.error.displayMessage}):y?jsx(m,{style:[c.errorText,s.inset],accessibilityRole:"alert",testID:"record-document-share-failed",children:ie.toasts.pdfShareSheet}):null,jsx(View,{style:c.body,children:h}),jsx(Ve,{})]})}i(bb,"DocumentBody");function hb({record:e,depth:t,petName:r,wordmark:o}){let n=Gd(),l=useMemo(()=>{let s=[],d=new Map;for(let g of e.entities){let b=g.category.trim();if(b.length===0)continue;let R=d.get(b);R===void 0?(s.push(b),d.set(b,[g])):R.push(g);}let u=Wd.filter(g=>s.includes(g)),p=s.filter(g=>!Wd.includes(g));return [...u,...p].map(g=>({type:g,rows:d.get(g)??[]}))},[e.entities]),a=Date.now(),c=i((s,d,u)=>jsxs(View,{style:n.section,testID:u,children:[jsxs(View,{style:n.sectionHeader,children:[jsx(m,{style:n.sectionTitle,accessibilityRole:"header",children:s}),jsx(View,{style:n.rule})]}),jsx(View,{children:d})]},u),"section");return jsxs(ScrollView,{contentContainerStyle:n.page,showsVerticalScrollIndicator:false,testID:"record-document",children:[jsxs(View,{style:n.letterhead,children:[jsx(m,{style:n.wordmark,children:o}),jsx(m,{style:n.docTitle,children:Pt.docTitle}),jsx(m,{style:n.petName,children:r?.trim()||Pt.namelessPet}),jsx(m,{style:n.generated,children:Pt.generated(e.generatedAt)})]}),e.identity.length>0?c(Pt.identity,e.identity.map((s,d)=>jsxs(View,{style:[n.row,d>0?n.rowDivider:null],children:[jsx(m,{style:n.rowLabel,children:s.label}),jsx(m,{style:n.rowValue,children:s.value})]},`${d}:${s.label}`)),"record-document-identity"):null,t&&t.labResults.length>0?c(Pt.labs,t.labResults.map((s,d)=>{let u=tr(s.latest.status),p=id(s.points[s.points.length-1]??null),g=kt(s.latest.value,s.latest.unit??s.unit,s.latest.qualitativeResult);return jsxs(View,{style:[n.row,u.outOfRange?n.rowFlag:null,d>0?n.rowDivider:null],children:[jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:s.name}),jsxs(m,{style:n.rowMeta,children:[p?Pt.ref(p):Pt.noRange,s.latest.at?` \xB7 ${Y(s.latest.at)}`:""]})]}),jsxs(View,{style:n.rowRight,children:[g!=="-"?jsx(m,{style:[n.rowValue,u.outOfRange?n.rowValueAlert:null],children:g}):null,jsx(m,{style:[n.markerStatus,u.outOfRange?n.rowValueAlert:null],children:u.label})]})]},s.markerId)}),"record-document-labs"):null,l.map(({type:s,rows:d})=>c(jr(s),d.map((u,p)=>{let g=[Yr(u.value,u.unit),u.observedAt?Y(u.observedAt):null].filter(b=>b&&b.length>0).join(" \xB7 ");return jsx(View,{style:[n.row,p>0?n.rowDivider:null],children:jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:u.label}),g?jsx(m,{style:n.rowMeta,children:g}):null]})},u.key)}),`record-document-${s}`)),e.forwardLooking.length>0?c(Pt.upcomingCare,e.forwardLooking.map((s,d)=>{let u=Dn(s.dueAt,a);return jsxs(View,{style:[n.row,d>0?n.rowDivider:null],children:[jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:s.title}),s.detail?jsx(m,{style:n.rowMeta,children:s.detail}):null]}),u?jsx(m,{style:[n.rowValue,u.overdue?n.rowValueAlert:null],children:u.label}):null]},`${s.title}-${d}`)}),"record-document-upcoming"):null,t&&t.physicalExams.length>0?c(Pt.physicalExams,t.physicalExams.map((s,d)=>jsxs(View,{style:[n.block,d>0?n.rowDivider:null],children:[s.observedOn?jsx(m,{style:n.blockDate,children:Y(s.observedOn)}):null,s.systems.filter(u=>u.finding).map(u=>jsxs(View,{style:n.fieldRow,children:[jsx(m,{style:n.fieldLabel,children:qr(u.system)}),jsx(m,{style:n.fieldValue,children:u.finding})]},u.system))]},s.examId)),"record-document-exams"):null,t&&t.clinicianNotes.length>0?c(Pt.clinicianNotes,t.clinicianNotes.map((s,d)=>jsxs(View,{style:[n.block,d>0?n.rowDivider:null],children:[s.observedOn?jsx(m,{style:n.blockDate,children:Y(s.observedOn)}):null,s.sections.filter(u=>u.text).map((u,p)=>jsxs(View,{style:n.noteSection,children:[jsx(m,{style:n.noteLabel,children:Qr(u.section)}),jsx(m,{style:n.noteBody,children:u.text})]},`${u.section}-${p}`))]},s.noteId)),"record-document-notes"):null,e.disclaimer.length>0?jsx(View,{style:n.disclaimer,children:jsx(m,{style:n.disclaimerText,children:e.disclaimer})}):null]})}i(hb,"RecordDocument");function Gd(){let e=V();return useMemo(()=>Rb(e),[e])}i(Gd,"useLocalStyles");function Rb(e){let{color:t,space:r,radius:o,type:n}=e,l=StyleSheet.hairlineWidth,a=i((s,d,u,p="regular")=>({...T(e,p),fontSize:s,lineHeight:Math.round(s*d),color:u}),"text"),c=i((s,d)=>({...T(e,"mono"),fontSize:s,lineHeight:s+r.xs-1,color:d,letterSpacing:n.letterSpacing.eyebrow/2,textTransform:"uppercase"}),"mono");return StyleSheet.create({root:{backgroundColor:t.surface},inset:{paddingHorizontal:r.lg},download:{width:r.xxl+r.xs+r.xs/2,height:r.xxl+r.xs+r.xs/2,borderRadius:o.pill,alignItems:"center",justifyContent:"center"},centered:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xxl,minHeight:r.xxl*3+r.xl},emptyText:{...a(n.size.body,n.lineHeight.normal,t.text.muted,"medium"),textAlign:"center"},page:{paddingHorizontal:r.lg+r.xs,paddingBottom:r.xxl+r.lg},letterhead:{alignItems:"center",paddingTop:r.md,paddingBottom:r.lg+r.xs+r.xs/2,borderBottomWidth:2,borderBottomColor:t.brand,gap:r.xs+r.xs/2,marginBottom:r.sm},wordmark:{...a(n.size.heading,n.lineHeight.snug,t.brandInk,"bold"),letterSpacing:n.letterSpacing.headerBrand},docTitle:{...c(n.size.caption,t.brandInk),marginTop:r.sm+r.xs/2,letterSpacing:n.letterSpacing.eyebrow+.4},petName:a(n.size.verdict+r.xs/2,n.lineHeight.tight,t.text.primary),generated:{...c(n.size.tiny,t.text.muted),textTransform:"none"},section:{marginTop:r.lg+r.xs+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2,marginBottom:r.sm},sectionTitle:c(n.size.tiny,t.brandInk),rule:{flex:1,height:l,backgroundColor:t.borderHairlineGreen},row:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.md+r.xs/2,paddingVertical:r.sm+1},rowDivider:{borderTopWidth:l,borderTopColor:t.borderHairlineGreen},rowFlag:{backgroundColor:t.badgeBgCritical,marginHorizontal:-r.sm,paddingHorizontal:r.sm,borderRadius:o.xs},rowMain:{flexShrink:1},rowRight:{alignItems:"flex-end",gap:r.xs/2},rowLabel:{flexShrink:1,...a(n.size.body,n.lineHeight.normal,t.text.primary,"medium")},rowValue:{...a(n.size.body,n.lineHeight.normal,t.text.primary,"bold"),textAlign:"right"},rowValueAlert:{color:t.danger},rowMeta:{marginTop:r.xs/2,...T(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},markerStatus:c(n.size.micro,t.text.muted),block:{paddingVertical:r.sm+r.xs/2},blockDate:{...c(n.size.tiny,t.text.muted),marginBottom:r.xs+r.xs/2},fieldRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md+r.xs/2,paddingVertical:r.xs-1},fieldLabel:{width:120,...a(n.size.bodyTight,n.lineHeight.normal,t.text.muted,"medium")},fieldValue:{flex:1,...a(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")},noteSection:{marginTop:r.sm},noteLabel:{...c(n.size.tiny,t.brandInk),marginBottom:r.xs/2},noteBody:a(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),disclaimer:{marginTop:o.xl,paddingTop:r.md+r.xs/2,borderTopWidth:l,borderTopColor:t.borderHairlineGreen},disclaimerText:a(n.size.tiny,n.lineHeight.relaxed,t.text.muted)})}i(Rb,"makeLocalStyles");function Qd({petRef:e,onClose:t,onNavigate:r,onOpenUrl:o,onCopy:n}){let l=Cb(),a=ue(),c=Ms(e),[s,d]=useState(null),[u,p]=useState(null),g=c.available&&!c.consentRequired,b=i((f,x)=>{let h=o??((S,k)=>k==="share_link"?Ud(S):Wo(S)),_=x==="share_link"?ie.toasts.shareSheet:ie.toasts.pdfShareSheet;Or(h,f,x).then(S=>{S.ok||d(_);});},"open"),R=i(()=>{d(null),c.createLink().then(f=>{f.ok?b(f.value.shareUrl,"share_link"):d(ao(f.error,"create"));});},"onCreateLink"),v=i(()=>{d(null),c.pdfLink().then(f=>{f.ok?b(f.value.downloadUrl,"record_pdf"):d(ao(f.error,"download"));});},"onDownload"),w=i(f=>{!n||f.shareUrl===null||Or(n,f.shareUrl).then(x=>d(x.ok?ie.toasts.copied:ie.toasts.copyFailed));},"onCopyRow"),y=i(f=>{c.revoke(f).then(x=>{p(null),d(x.ok?ie.toasts.turnedOff:ao(x.error,"revoke"));});},"onConfirmRevoke");return jsx(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:t,children:jsxs(View,{style:l.backdrop,children:[jsx(Pressable,{style:StyleSheet.absoluteFill,accessibilityRole:"button",accessibilityLabel:ie.closeSheetA11y,onPress:t}),jsxs(View,{style:l.sheet,accessibilityViewIsModal:true,testID:"share-record-sheet",children:[jsx(View,{style:l.handle}),jsxs(View,{style:l.header,children:[jsxs(View,{style:l.headerText,children:[jsx(m,{style:l.title,accessibilityRole:"header",children:ie.title}),jsx(m,{style:l.helper,children:ie.helper})]}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:ie.close,onPress:t,hitSlop:12,style:l.closeButton,testID:"share-record-close",children:jsx(m,{style:l.closeGlyph,children:"\xD7"})})]}),jsxs(ScrollView,{style:l.scroll,contentContainerStyle:l.body,showsVerticalScrollIndicator:false,children:[jsxs(View,{style:l.actions,children:[r?jsx(J,{label:ie.viewDocument,onPress:()=>{t(),r({name:"document"});},testID:"share-view-document"}):null,g?jsx(J,{label:c.creating?ie.creatingLink:ie.createLink,kind:"outline",busy:c.creating,onPress:R,testID:"share-create-link"}):null,g?jsx(J,{label:c.preparingPdf?ie.preparingPdf:ie.downloadPdf,kind:"outline",busy:c.preparingPdf,onPress:v,testID:"share-download-pdf"}):null]}),c.consentRequired?jsxs(View,{style:l.stateCard,testID:"share-consent-off",children:[jsx(m,{style:l.stateTitle,accessibilityRole:"header",children:ie.consentOffTitle}),jsx(m,{style:l.stateBody,children:ie.consentOffBody}),jsx(J,{label:ie.retry,kind:"outline",onPress:c.refresh,testID:"share-consent-retry"})]}):null,s?jsx(m,{style:l.notice,accessibilityRole:"alert",accessibilityLiveRegion:"polite",testID:"share-notice",children:s}):null,Bd(c)?jsxs(View,{style:l.section,children:[jsx(m,{style:l.sectionLabel,accessibilityRole:"header",children:ie.activeLinks}),c.status==="loading"?jsx(Yl,{testID:"share-record-loading"}):c.status==="error"?jsxs(View,{style:l.stateCard,testID:"share-record-error",children:[jsx(m,{style:l.stateTitle,children:ie.errorTitle}),jsx(m,{style:l.stateBody,children:ie.errorBody}),jsx(J,{label:ie.retry,kind:"outline",onPress:c.refresh,testID:"share-record-retry"})]}):c.rows.length===0?jsxs(View,{style:l.stateCard,testID:"share-record-empty",children:[jsx(m,{style:l.stateTitle,children:ie.emptyTitle}),jsx(m,{style:l.stateBody,children:ie.emptyBody})]}):jsx(View,{style:l.list,children:c.rows.map(f=>jsxs(View,{style:l.row,testID:`share-row-${f.shareId}`,children:[jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:f.a11yLabel,children:[jsxs(View,{style:l.statusLine,children:[jsx(View,{style:[l.statusDot,{backgroundColor:f.active?l.active.color:l.inactive.color}],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:l.status,children:f.statusLabel}),jsx(m,{style:l.expiry,children:f.expiryLabel})]}),f.createdLabel?jsx(m,{style:l.created,children:f.createdLabel}):null]}),f.shareUrl!==null&&!n?jsx(m,{selectable:true,style:l.url,testID:`share-url-${f.shareId}`,children:f.shareUrl}):null,u===f.shareId?jsxs(View,{style:l.confirm,testID:`share-revoke-confirm-${f.shareId}`,children:[jsx(m,{style:l.confirmText,children:ie.confirmTurnOff}),jsxs(View,{style:l.rowActions,children:[jsx(J,{label:c.revokingId===f.shareId?ie.turningOff:ie.turnOff,kind:"danger",busy:c.revokingId===f.shareId,onPress:()=>y(f.shareId),testID:`share-revoke-do-${f.shareId}`}),jsx(J,{label:ie.keep,kind:"outline",disabled:c.revokingId===f.shareId,onPress:()=>p(null),testID:`share-revoke-cancel-${f.shareId}`})]})]}):jsxs(View,{style:l.rowActions,children:[n?jsx(J,{label:ie.copyLink,kind:"outline",disabled:f.shareUrl===null,accessibilityLabel:ie.copyLinkA11y(f.actionContext),onPress:()=>w(f),testID:`share-copy-${f.shareId}`}):null,jsx(J,{label:ie.turnOff,kind:"danger",accessibilityLabel:ie.turnOffA11y(f.actionContext),onPress:()=>p(f.shareId),testID:`share-ask-revoke-${f.shareId}`})]})]},f.shareId))})]}):null]}),jsx(View,{style:a.inset})]})]})})}i(Qd,"ShareSheet");function Cb(){let e=V();return useMemo(()=>Eb(e),[e])}i(Cb,"useStyles");function Eb(e){let{color:t,space:r,radius:o,type:n}=e,l=r.xxl+r.md,a=StyleSheet.hairlineWidth,c=i((s,d,u,p="regular")=>({...T(e,p),fontSize:s,lineHeight:Math.round(s*d),color:u}),"text");return StyleSheet.create({active:{color:t.success},inactive:{color:t.text.muted},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:"rgba(0,0,0,0.4)"},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),closeButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),scroll:{flexGrow:0},body:{gap:r.lg,paddingBottom:r.sm},actions:{gap:r.sm},notice:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.secondary),padding:r.md,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft},section:{gap:r.sm},sectionLabel:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},stateCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:a,borderColor:t.brandBorder},stateTitle:{...c(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},stateBody:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),list:{gap:r.md},row:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:a,borderColor:t.brandBorder},statusLine:{flexDirection:"row",alignItems:"center",gap:r.sm},statusDot:{width:r.sm,height:r.sm,borderRadius:r.xs},status:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.primary,"bold")},expiry:{...c(n.size.caption,n.lineHeight.normal,t.text.muted)},created:c(n.size.tiny,n.lineHeight.normal,t.text.muted),url:{...c(n.size.caption,n.lineHeight.normal,t.text.secondary,"mono")},rowActions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},confirm:{gap:r.sm},confirmText:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")}})}i(Eb,"makeStyles");var Tb=i((e,t)=>e.getRecordDepth(t),"readDepth"),_b=i(e=>!e.available,"depthEmpty");function Gs(e){let{style:t,renderPending:r,...o}=Oe(e,["onNavigate","onBack","onAsk"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(Pb,{...o,style:t})})}i(Gs,"EverfurRecordDetail");function Pb({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:l,onAsk:a,onOpenUrl:c,onCopy:s,style:d}){let u=ue(),p=Ib(),g=st(r?{petRef:e,controller:r}:{petRef:e}),b=Gt(e,Tb,_b),R=ws(e),v=Bs(e),[w,y]=useState(false),f=useMemo(()=>Hr(o,g.consent),[o,g.consent]),x=useMemo(()=>rn(g,o),[g,o]),h=b.value!==null&&!b.value.withheld&&b.value.available?b.value:null,_=g.record,S=i(()=>{g.refresh(),b.refresh();},"retry"),k=n!==void 0||v.lit===true,E;if(g.status==="loading"||b.status==="loading"&&_!==null&&!_.isEmpty)E=jsx(uo,{testID:"everfur-record-loading"});else if(g.status==="error"){let A=_r(g,f);E=A.kind==="error"||A.kind==="pet_not_found"?jsx(Ue,{variant:pt(A.error),message:A.error.displayMessage,onAction:A.error.retryable?S:void 0,testID:"everfur-record-error"}):tn(g,x,f);}else if(_===null||_.isEmpty){let A=h?.completeness?.documentsInReview??0;E=jsxs(ScrollView,{contentContainerStyle:u.content,testID:"everfur-record-empty",children:[jsx(Ue,{variant:"no_records",message:A>0?K.inReview(A):void 0}),jsx(kr,{disclaimer:_?.disclaimer??""})]});}else E=jsx(ScrollView,{contentContainerStyle:p.content,testID:"everfur-record",children:jsx(zo,{record:_,depth:h,petName:t,onNavigate:n,onAsk:a,factEdit:R})});return jsxs(View,{style:[u.root,d],children:[jsx(Ke,{title:K.title,onBack:l,testID:"everfur-record-header",right:k||n?jsxs(Fragment,{children:[n?jsx(Pressable,{onPress:()=>n({name:"clinicBatch"}),accessibilityRole:"button",accessibilityLabel:K.requestClinicsA11y,hitSlop:8,style:p.share,testID:"everfur-record-request-clinics",children:jsx(Vl,{})}):null,k?jsx(Pressable,{onPress:()=>y(true),accessibilityRole:"button",accessibilityLabel:K.shareA11y,hitSlop:8,style:p.share,testID:"everfur-record-share",children:jsx(Ll,{})}):null]}):void 0}),jsx(View,{style:u.body,children:E}),w?jsx(Qd,{petRef:e,onClose:()=>y(false),onNavigate:n,...c?{onOpenUrl:c}:{},...s?{onCopy:s}:{}}):null,jsx(Ve,{})]})}i(Pb,"RecordBody");function Ib(){let e=V();return useMemo(()=>Db(e),[e])}i(Ib,"useLocalStyles");function Db(e){let{space:t,radius:r}=e;return StyleSheet.create({content:{paddingHorizontal:t.lg,paddingBottom:t.xxl+t.sm,gap:t.lg+t.xs},share:{width:t.xxl+t.sm,height:t.xxl+t.sm,borderRadius:r.pill,alignItems:"center",justifyContent:"center"}})}i(Db,"makeLocalStyles");function Ks(e){let{style:t,renderPending:r,...o}=Oe(e,["onNavigate","onBack"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(Vb,{...o,style:t})})}i(Ks,"EverfurRecordsUpload");function Vb({petRef:e,petName:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:l,onBack:a,style:c}){let s=ue(),d=nu(),{runtime:u}=Se(),p=st(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),g=Pn(o)&&(r!==void 0||n!==void 0||Hn(u.registry.services.uploadTransport));return jsxs(View,{style:[s.root,c],children:[jsx(Ke,{title:"",onBack:a,testID:"upload-header"}),jsxs(ScrollView,{contentContainerStyle:d.content,testID:"upload-screen",children:[jsxs(View,{style:d.header,children:[jsx(View,{style:d.iconBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:d.title,accessibilityRole:"header",children:ot.title(t)}),jsx(m,{style:d.subtitle,children:ot.subtitle(t)})]}),jsx(Qs,{records:p,requestId:null,onPickDocument:o,canUpload:g,onDone:l?b=>l({name:"request",requestId:b}):void 0})]}),jsx(Ve,{})]})}i(Vb,"UploadBody");function Qs({records:e,requestId:t,onPickDocument:r,canUpload:o,onDone:n}){let l=ue(),a=nu(),[c,s]=useState(null),[d,u]=useState(0),p=useRef(t),g=useRef([]),b=e.uploadQueue.filter(h=>h.status!=="skipped"),R=b.filter(h=>h.status==="done").length,v=b.filter(h=>h.status==="failed").length,w=!e.isUploading&&d>0,y=useCallback(async h=>{if(h.length===0)return;s(null);let _=p.current;if(_===null){let k=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!k.ok){s(ot.errors.start);return}_=k.value.id,p.current=_;}u(k=>k+1);let S=await e.uploadDocuments(_,h);g.current=S.flatMap((k,E)=>k.status==="failed"&&h[E]!==void 0?[h[E]]:[]);},[e]),f=useCallback(()=>{!r||!o||Or(r).then(h=>{if(!h.ok){s(ot.errors.startPlain);return}let _=h.value;_!==null&&y(Array.isArray(_)?_:[_]);});},[r,o,y]),x=useCallback(()=>{y(g.current);},[y]);return jsxs(View,{style:a.card,testID:"records-upload-card",children:[jsx(m,{style:a.cardTitle,accessibilityRole:"header",children:ot.cardTitle}),jsx(m,{style:a.cardSubtitle,children:ot.cardSubtitle}),c?jsx(View,{style:l.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:l.errorText,children:c})}):null,jsx(Sd,{records:e}),e.isUploading?jsx(View,{style:a.uploadingRow,children:jsx(m,{style:a.progressText,children:ot.uploading(R,b.length)})}):w?jsxs(View,{style:a.settled,children:[R>0?jsx(m,{style:a.success,accessibilityRole:"alert",children:ot.received(R)}):null,v>0?jsx(J,{label:ot.retryFailed(v),kind:"link",accessibilityLabel:ot.retryFailedA11y(v),onPress:x,testID:"records-upload-retry-failed"}):null,jsxs(View,{style:a.settledActions,children:[jsx(J,{label:ot.addMore,kind:"link",accessibilityLabel:ot.addMoreA11y,disabled:!o,onPress:f,testID:"records-upload-another"}),n&&p.current!==null&&R>0?jsx(J,{label:ot.done,accessibilityLabel:ot.doneA11y,onPress:()=>n(p.current),testID:"records-upload-done"}):null]})]}):jsx(J,{label:ot.chooseFiles,accessibilityLabel:ot.chooseFilesA11y,disabled:!o,onPress:f,testID:"records-upload-choose"})]})}i(Qs,"UploadRecordCard");function nu(){let e=V();return useMemo(()=>qb(e),[e])}i(nu,"useLocalStyles");function qb(e){let{color:t,space:r,radius:o,type:n}=e,l=i((a,c,s,d="regular")=>({...T(e,d),fontSize:a,lineHeight:Math.round(a*c),color:s}),"text");return StyleSheet.create({content:{padding:r.lg+r.xs,gap:r.lg+r.xs},header:{gap:r.sm,alignItems:"center"},iconBubble:{width:r.xxl+r.lg+r.xs,height:r.xxl+r.lg+r.xs,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{...l(n.size.heading+r.xs/2,n.lineHeight.snug,t.brandInk,"bold"),textAlign:"center"},subtitle:{...l(n.size.body,n.lineHeight.normal,t.text.muted),textAlign:"center",maxWidth:340},card:{borderRadius:o.md,backgroundColor:t.surface,borderWidth:1,borderColor:t.brandSoft,padding:r.lg,gap:r.md},cardTitle:{...l(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},cardSubtitle:l(n.size.bodyTight,n.lineHeight.normal,t.text.muted),uploadingRow:{flexDirection:"row",alignItems:"center",gap:r.sm},progressText:{flex:1,...l(n.size.bodyTight,n.lineHeight.normal,t.text.secondary)},settled:{gap:r.sm},success:l(n.size.bodyTight,n.lineHeight.normal,t.text.primary),settledActions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:r.sm}})}i(qb,"makeLocalStyles");function Js(e){let{style:t,renderPending:r,...o}=Oe(e,["onNavigate","onBack"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(Ub,{...o,style:t})})}i(Js,"EverfurRecordsRequest");function Ub({petRef:e,requestId:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:l,onBack:a,style:c,nowMs:s}){let d=ue(),{runtime:u,userRef:p,scopeEpoch:g}=Se(),b=st(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),R=b.requests.find(f=>f.id===t)??null,v=Pn(o)&&(r!==void 0||n!==void 0||Hn(u.registry.services.uploadTransport)),w=R?So(R):"",y;return b.status==="loading"?y=jsx(po,{testID:"records-request-loading"}):b.status==="error"&&b.error?y=jsx(Ue,{variant:pt(b.error),message:b.error.displayMessage,onAction:b.error.retryable?b.refresh:void 0,testID:"records-request-error"}):R===null?y=jsx(Ue,{variant:"no_requests",testID:"records-request-missing"}):p===null?y=jsx(Ue,{variant:"error",testID:"records-request-error"}):y=jsx(jb,{request:R,records:b,canUpload:v,onPickDocument:o,onNavigate:l,nowMs:s},JSON.stringify([p,g,R.id])),jsxs(View,{style:[d.root,c],children:[jsx(Ke,{title:w,onBack:a,testID:"records-request-header"}),jsx(KeyboardAvoidingView,{behavior:"padding",style:d.body,children:y}),jsx(Ve,{})]})}i(Ub,"RequestBody");function jb({request:e,records:t,canUpload:r,onPickDocument:o,onNavigate:n,nowMs:l}){let a=ue(),c=$b(),s=V(),d=vd({request:e,onRecovered:t.refresh,canUpload:r},Ut()),[u,p]=useState(null),[g,b]=useState(false),[R,v]=useState(null),w=useRef(true);useEffect(()=>(w.current=true,()=>{w.current=false;}),[]);let y=d.request,f=l??Date.now(),x=y.status==="published",h=y.status==="published"||y.status==="failed"||y.status==="revoked",_=Si(y),S=y.wireStatus==="clinic_responded_no_records",k=rl(y,f),E=Ei(y,f),A=h?null:y.waitingExpectation?.trim()||null,B=ko(y),z=nl(y),U=d.canConvert,j=h&&!x,re=d.error!==null&&u!==null&&u!=="start"?u==="revoke"?be.errors.cancel:be.errors[u]:null,se=i((ee,I)=>{p(ee),I();},"run"),Te=i(()=>{g||(b(true),v(null),t.createRequest(`records-upload-${Date.now().toString(36)}`).then(ee=>{if(w.current){if(b(false),!ee.ok){v(be.errors.start);return}n?.({name:"request",requestId:ee.value.id});}}));},"startFresh");return jsxs(ScrollView,{contentContainerStyle:c.content,keyboardShouldPersistTaps:"handled",testID:`records-request-${y.id}`,children:[jsx(Mo,{request:y}),y.status==="awaiting_upload"?jsx(Qs,{records:t,requestId:y.id,onPickDocument:o,canUpload:r}):null,y.statusLabel.length>0?jsx(View,{style:a.statusCard,accessibilityRole:"summary",children:jsx(m,{style:a.statusText,children:y.statusLabel})}):null,A&&!k?jsx(View,{style:a.infoNote,accessibilityRole:"summary",children:jsx(m,{style:a.infoNoteText,children:A})}):y.wireStatus==="awaiting_response"&&!k?jsx(View,{style:a.infoNote,accessibilityRole:"summary",children:jsx(m,{style:a.infoNoteText,children:be.awaitingNote})}):null,k?jsx(View,{style:a.cautionNote,accessibilityRole:"summary",testID:"records-request-waiting-banner",children:jsx(m,{style:a.cautionNoteText,children:be.waitingBanner(E)})}):null,x&&n?jsx(J,{label:be.viewRecords,onPress:()=>n({name:"dashboard"}),style:c.readyCta,testID:"records-request-view-dashboard"}):null,z?jsxs(View,{style:[c.failureCard,_?c.failureCritical:c.failureCaution],accessibilityRole:"summary",testID:"records-failure-card",children:[jsx(m,{style:[c.failureTitle,_?c.failureTitleCritical:c.failureTitleCaution],children:tl(y)}),y.canUpdateClinicEmail!==true&&y.canRetrySend!==true?jsx(m,{style:a.rowDetail,children:be.nextStep}):null,y.canUpdateClinicEmail===true?jsxs(View,{style:c.emailBlock,children:[jsx(m,{style:a.fieldLabel,children:qt.email}),jsx(He,{style:a.field,accessibilityLabel:qt.email,placeholder:qt.emailPlaceholder,placeholderTextColor:s.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,value:d.email,editable:!d.busy,onChangeText:d.setEmail,testID:"records-failure-clinic-email"}),d.emailInvalid?jsx(m,{style:a.errorText,accessibilityRole:"alert",children:be.errors.invalidEmail}):null,jsx(J,{label:qt.updateEmail,accessibilityLabel:qt.updateEmailA11y,disabled:!d.canUpdateEmail,busy:d.busy&&u==="email",onPress:()=>se("email",d.updateEmail),testID:"records-failure-update-email"})]}):null,y.canRetrySend===true?jsx(J,{label:qt.retry,kind:"outline",accessibilityLabel:qt.retryA11y,disabled:!d.canRetry,busy:d.busy&&u==="retry",onPress:()=>se("retry",d.retry),testID:"records-failure-retry-send"}):null,y.canRetrySend===true&&d.hasEmailEdit?jsx(m,{style:a.rowDetail,children:qt.retryHint}):null,re&&(u==="email"||u==="retry")?jsx(View,{style:a.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:a.errorText,children:re})}):null]}):null,(_||S)&&n?jsx(J,{label:be.tryAnotherClinic,kind:"outline",accessibilityLabel:be.tryAnotherClinicA11y,onPress:()=>n({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,B!==null?jsxs(View,{style:c.callBlock,children:[jsx(kd,{call:B,prompt:y.statusLabel}),y.canRetrySend===true?jsx(J,{label:d.busy&&u==="retry"?be.resending:be.resend,kind:"outline",accessibilityLabel:d.busy&&u==="retry"?be.resendingA11y:be.resendA11y,disabled:!d.canRetry,onPress:()=>se("retry",d.retry),testID:"records-resend-authorization"}):null]}):null,U?jsxs(View,{style:c.block,children:[jsx(J,{label:d.busy&&u==="convert"?be.converting:be.convert,busy:d.busy&&u==="convert",onPress:()=>se("convert",d.convert),testID:"records-convert-upload"}),jsx(m,{style:a.muted,children:be.convertHint}),re&&u==="convert"?jsx(View,{style:a.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:a.errorText,children:re})}):null]}):null,j?jsxs(View,{style:c.block,children:[jsx(J,{label:g?be.freshUploadStarting:be.freshUpload,kind:_||S?"outline":"primary",busy:g,onPress:Te,testID:"records-upload-own-fresh"}),R?jsx(View,{style:a.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:a.errorText,children:R})}):null]}):null,re&&u==="revoke"?jsx(View,{style:a.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:a.errorText,children:re})}):null,y.canRevoke===true?d.confirmingRevoke?jsxs(View,{style:c.block,testID:"records-revoke-confirm",children:[jsx(m,{style:c.confirmTitle,accessibilityRole:"header",children:qt.cancelQuestion}),jsx(m,{style:a.bodyText,children:qt.cancelConsequence}),jsx(J,{label:d.busy&&u==="revoke"?be.cancelling:be.cancel,kind:"danger",accessibilityLabel:d.busy&&u==="revoke"?be.cancellingA11y:be.cancelA11y,busy:d.busy&&u==="revoke",onPress:()=>se("revoke",d.revoke),testID:"records-revoke-do"}),jsx(J,{label:qt.keepRequest,kind:"outline",disabled:d.busy,onPress:d.keepRequest,testID:"records-revoke-keep"})]}):jsx(J,{label:be.cancel,kind:"danger",accessibilityLabel:be.cancelA11y,disabled:d.busy,onPress:d.askRevoke,testID:"records-revoke"}):null]})}i(jb,"RequestDetail");function $b(){let e=V();return useMemo(()=>Wb(e),[e])}i($b,"useLocalStyles");function Wb(e){let{color:t,space:r,radius:o,type:n}=e,l=i((a,c,s,d="regular")=>({...T(e,d),fontSize:a,lineHeight:Math.round(a*c),color:s}),"text");return StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg+r.xs/2},readyCta:{minHeight:r.xxl+r.lg+r.xs/2},failureCard:{borderRadius:o.lg-r.xs,borderWidth:1,padding:r.md+r.xs/2,gap:r.md},failureCritical:{borderColor:t.badgeBgCritical,backgroundColor:t.badgeBgCritical},failureCaution:{borderColor:t.badgeBgCaution,backgroundColor:t.badgeBgCaution},failureTitle:{...l(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},failureTitleCritical:{color:t.danger},failureTitleCaution:{color:t.warningStrong},emailBlock:{gap:r.sm},callBlock:{gap:r.sm},block:{gap:r.sm},confirmTitle:{...l(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")}})}i(Wb,"makeLocalStyles");function ou(e){let{petRef:t,petName:r,controller:o,clinicController:n,onPickDocument:l,uploadTransport:a,consentVersion:c,ownerName:s,onCaptureSignature:d,initialScreen:u,onExit:p,style:g,renderPending:b,onOpenUrl:R,onCopy:v,onAsk:w,location:y}=Oe(e,["onExit"]),[f,x]=useReducer(gi,u,Qn),h=Xn(f),_=f.stack.length;useEffect(()=>{let U=i(()=>_<=1?false:(x({type:"pop"}),true),"onBackPress"),j=BackHandler.addEventListener("hardwareBackPress",U);return ()=>{j.remove();}},[_]);let S=useCallback(U=>x({type:"navigate",screen:U}),[]),k=useMemo(()=>Jn(f).handled?()=>x({type:"pop"}):p,[f,p]),E={onNavigate:S,...k?{onBack:k}:{},...r!==void 0?{petName:r}:{},...R?{onOpenUrl:R}:{},...v?{onCopy:v}:{},...w?{onAsk:w}:{},...y?{location:y}:{}},A={...o?{controller:o}:{},...c!==void 0?{consentVersion:c}:{}},B={...l?{onPickDocument:l}:{},...a?{uploadTransport:a}:{}},z=b?{renderPending:b}:{};switch(h.name){case "dashboard":return jsx(zs,{petRef:t,...E,...A,...z,style:g});case "request":return jsx(Js,{petRef:t,requestId:h.requestId,...E,...A,...B,...z,style:g});case "timeline":return jsx(zd,{petRef:t,...E,style:g});case "record":return jsx(Gs,{petRef:t,...E,...A,...z,style:g});case "document":return jsx(Us,{petRef:t,...E,...A,...z,style:g});case "contributions":return jsx(Fd,{petRef:t,docId:h.docId,...E,style:g});case "clinicPicker":return jsx(Ui,{petRef:t,...E,...n?{controller:n}:{},...o?{recordsController:o}:{},style:g});case "clinicBatch":return jsx(is,{petRef:t,petName:r??"",ownerName:s??"",...k?{onClose:k}:{},onCreated:()=>x({type:"navigate",screen:{name:"dashboard"}}),...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:g});case "consent":return jsx(ys,{petRef:t,clinic:h.clinic,...E,...s!==void 0?{ownerName:s}:{},...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:g});case "upload":return jsx(Ks,{petRef:t,...E,...o?{controller:o}:{},...B,...z,style:g});case "requests":return jsx(As,{petRef:t,...E,...o?{controller:o}:{},...z,style:g});default:return Rr(h)}}i(ou,"EverfurRecordsFlow");var Jb=ou;function rh(e){let{userRef:t,scopeEpoch:r}=Se();return jsx(Le,{capability:"recordsClinic",...ze(e.onClose,W.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:pe.sessionRequired}):jsx(nh,{...Oe(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(rh,"EverfurClinicRequest");function nh(e){let t=Ut(),[r,o]=useState(null),n=useCallback(async()=>r===null?null:{signaturePngBase64:r},[r]),l=Ql(e,e.controller??t,e.onCaptureSignature??n),a=e.onCaptureSignature!==void 0||r!==null,c=V(),s={minHeight:44,padding:c.space.sm,borderWidth:1,borderColor:c.color.borderHairlineGreen,borderRadius:c.radius.sm,color:c.color.text.primary,backgroundColor:c.color.surface},d={color:c.color.text.primary,fontSize:c.type.size.body},u=i((p,g,b=false)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:p,accessibilityState:{disabled:b},disabled:b,onPress:g,style:[s,{justifyContent:"center",opacity:b?.5:1}],children:jsx(m,{style:d,children:p})}),"button");return jsxs(View,{accessibilityLabel:W.title,style:[{backgroundColor:c.color.surface,padding:c.space.lg,gap:c.space.md,borderRadius:c.radius.lg,minHeight:120},e.style],children:[jsx(m,{accessibilityRole:"header",style:[d,{...T(c,"bold"),fontSize:c.type.size.heading}],children:W.title}),jsx(m,{style:d,children:e.petName}),l.created?jsx(m,{accessibilityLiveRegion:"polite",style:d,children:l.created.statusLabel||pe.records}):jsxs(Fragment,{children:[jsx(m,{style:d,children:W.ownerName}),jsx(He,{accessibilityLabel:W.ownerName,style:s,value:l.ownerName,maxLength:200,editable:!l.busy,autoComplete:"name",onChangeText:l.setOwnerName}),jsx(m,{style:d,children:W.clinic}),jsx(He,{accessibilityLabel:W.clinic,style:s,value:l.query,placeholder:W.placeholder,placeholderTextColor:c.color.text.placeholder,maxLength:200,editable:!l.busy,onChangeText:l.setQuery}),u(W.search,()=>{l.search();},l.busy||l.searching||l.query.trim().length<2),l.searching&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:pe.loading}),l.recent.length>0&&jsx(m,{accessibilityRole:"header",style:d,testID:"records-clinic-recent-label",children:W.recentlyUsed}),l.recent.map(p=>jsx(View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>l.selectClinic(p),l.busy)},`recent-${p.id}`)),l.clinics.map(p=>jsx(View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>l.selectClinic(p),l.busy)},p.id)),l.needsEmail&&jsxs(Fragment,{children:[jsx(m,{style:d,children:W.email}),jsx(He,{accessibilityLabel:W.email,style:s,value:l.email,placeholder:W.emailPlaceholder,placeholderTextColor:c.color.text.placeholder,maxLength:320,editable:!l.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:l.setEmail})]}),jsx(m,{accessibilityRole:"header",style:d,children:W.scopeHeading}),l.copy?jsx(m,{style:d,children:l.query.trim()&&l.ownerName.trim()?l.scope??F("internalError").displayMessage:pe.consentRequired}):!l.error&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:pe.loading}),!e.onCaptureSignature&&jsx(Mr,{onChange:o,disabled:l.busy}),!a&&jsx(m,{accessibilityRole:"alert",style:d,children:W.missingSignature}),l.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:d,children:l.error.displayMessage}),!l.copy&&l.error&&u(pe.retry,l.retryCopy),u(l.busy?W.sending:W.send,()=>{l.submit();},l.busy||!l.ready||!a)]}),e.onClose&&u(W.cancel,e.onClose,l.busy),jsx(Ve,{})]})}i(nh,"ClinicRequestBody");
|
|
4
|
-
export{
|
|
3
|
+
`):null,Be=b.length>0&&b.every(M=>!En(M)||oy.test(M.email.trim())),oe=b.length>=Gr,Ce=!!(v&&fe&&a.trim()&&e.petName.trim()&&Be&&o)&&T===null,xt=i(async()=>{if(ae.current)return;let M=++ne.current;S(true);try{let ve=await t.searchClinics({query:c.trim(),limit:100});if(!j.current||M!==ne.current)return;ve.ok?(u(ve.value.clinics),y(null)):y(ve.error);}catch{j.current&&M===ne.current&&y(N("internalError"));}finally{j.current&&M===ne.current&&S(false);}},"search"),tt=i(M=>{ae.current||oe||T!==null||M.clinic!==null&&b.some(ve=>ve.clinic?.id===M.clinic?.id)||(E(),R(ve=>[...ve,{...M,key:te.current(),idempotencyKey:te.current()}]),u([]),s(""));},"add"),Nt=i(async()=>{if(ae.current||T!==null||!Ce||!v||!fe||!o)return;ae.current=true;let M=Re.current,ve=i(()=>j.current&&Re.current===M,"current");h(true),y(null);try{if(_.current===null){D.current=new AbortController;let Ct=await o({petRef:e.petRef,petName:e.petName,ownerName:a.trim(),clinicName:L.join(", "),authorizationVersion:v.authorizationVersion,scopeText:fe,signal:D.current.signal});if(!ve()||Ct===null)return;if(_.current=Ct,Ct.signaturePngBase64!==void 0&&n!==void 0){let cu=await n(Ct.signaturePngBase64,D.current.signal);if(!ve())return;_.current={signatureId:cu.signatureId};}}let Bt=_.current,an=b.map(Ct=>({...Ct.clinic!==null&&(!En(Ct)||Ct.clinic.emailStatus==="none")?{clinicId:Ct.clinic.id}:{clinicFreeText:Sn(Ct)},...En(Ct)?{clinicEmail:Ct.email.trim().toLowerCase()}:{},...Bt.signatureId!==void 0?{signatureId:Bt.signatureId}:{signaturePngBase64:Bt.signaturePngBase64},idempotencyKey:Ct.idempotencyKey})),ln=await r.createClinicRequestBatch({petRef:e.petRef,ownerName:a.trim(),authorizationVersion:v.authorizationVersion,clinics:an});if(!ve())return;if(!ln.ok){y(ln.error);return}C(ln.value),e.onCreated?.(ln.value),Mt(ln.value.requestGroupId,M);}catch{ve()&&y(N("internalError"));}finally{ae.current=false,ve()&&h(false);}},"submit"),Mt=i(async(M,ve)=>{try{let Bt=await t.getRequestGroup(M);if(!j.current||Re.current!==ve)return;Bt.ok&&Bt.value.petRef===e.petRef&&F(Bt.value);}catch{}},"loadGroup"),Se=i(async()=>{T===null||ae.current||await Mt(T.requestGroupId,Re.current);},"refreshGroup");return {ownerName:a,query:c,clinics:d,copy:v,scopeText:fe,error:g,busy:x,searching:I,drafts:b,outcome:T,group:A,ready:Ce,atCap:oe,recent:d.length===0?p.filter(M=>!b.some(ve=>ve.clinic?.id===M.id)):[],setOwnerName(M){ae.current||(E(),l(M));},setQuery(M){ae.current||(ne.current+=1,S(false),u([]),s(M));},search:xt,addClinic(M){tt({clinic:M,freeText:null,email:""});},addFreeText(){let M=c.trim();M.length!==0&&tt({clinic:null,freeText:M,email:""});},setDraftEmail(M,ve){ae.current||(E(),R(Bt=>Bt.map(an=>an.key===M?{...an,email:ve}:an)));},removeDraft(M){ae.current||T!==null||(E(),R(ve=>ve.filter(Bt=>Bt.key!==M)));},submit:Nt,refreshGroup:Se,retryCopy(){y(null),U(M=>M+1);}}}i(ec,"useClinicBatchForm");function tc(e){try{let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.port&&t.port!=="443")return !1;let r=t.hostname.toLowerCase();return r==="s3.amazonaws.com"||r.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(r)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(r)||r==="s3-accelerate.amazonaws.com"||r.endsWith(".s3-accelerate.amazonaws.com")||r==="s3-accelerate.dualstack.amazonaws.com"||r.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}i(tc,"trustedSignatureUploadUrl");var iy="Signature upload failed",sy=3e4;function ay(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.floor(e.length*3/4)-t}i(ay,"base64ByteLength");async function Yi(e,t,r,o){let n=i(()=>new Error(iy),"fail"),a=ay(e);if(a<=0||r.aborted)throw n();let l=await t.initiateSignatureUpload(a);if(!l.ok||r.aborted||!tc(l.value.uploadUrl))throw n();let c=new FormData;for(let[f,b]of Object.entries(l.value.uploadFields))c.append(f,b);c.append("file",{uri:`data:image/png;base64,${e}`,name:"signature.png",type:"image/png"});let s=new AbortController,d=i(()=>s.abort(),"onAbort");r.addEventListener("abort",d,{once:true});let u=setTimeout(d,sy);try{if(!(await(o??fetch)(l.value.uploadUrl,{method:"POST",body:c,credentials:"omit",signal:s.signal})).ok||r.aborted)throw n()}catch{throw n()}finally{clearTimeout(u),r.removeEventListener("abort",d);}let p=await t.completeSignatureUpload(l.value.uploadId);if(!p.ok||r.aborted)throw n();return {signatureId:p.value}}i(Yi,"registerRnSignature");var Xr=Object.freeze({width:360,height:120});function ic(e,t){return {width:e,height:t,pixels:new Uint8Array(e*t)}}i(ic,"blank");function sc(e,t,r,o){for(let n=-o;n<=o;n+=1)for(let a=-o;a<=o;a+=1){if(a*a+n*n>o*o+o)continue;let l=t+a,c=r+n;l<0||c<0||l>=e.width||c>=e.height||(e.pixels[c*e.width+l]=1);}}i(sc,"stamp");var ly=16384;function cy(e,t){let[r,o]=e;if(!Number.isFinite(r)||!Number.isFinite(o))return null;let n=Math.min(2*t.width,Math.max(-t.width,Math.round(r))),a=Math.min(2*t.height,Math.max(-t.height,Math.round(o)));return [n,a]}i(cy,"padPoint");function dy(e,t,r,o,n){let[a,l]=t,[c,s]=r,d=Math.abs(c-a),u=-Math.abs(s-l),p=a<c?1:-1,f=l<s?1:-1,b=d+u,R=0;for(;R<n&&(sc(e,a,l,o),R+=1,!(a===c&&l===s));){let v=2*b;v>=u&&(b+=u,a+=p),v<=d&&(b+=d,l+=f);}return R}i(dy,"line");function ac(e,t=1){let r=ic(Xr.width,Xr.height);for(let o of e){let n=[];for(let l of o){let c=cy(l,r);c!==null&&n.push(c);}if(n.length===0)continue;if(n.length===1){let[l,c]=n[0];sc(r,l,c,t);continue}let a=ly;for(let l=1;l<n.length&&a>0;l+=1)a-=dy(r,n[l-1],n[l],t,a);}return r}i(ac,"rasterizeStrokes");var uy="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",py="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",my="0123456789abcdefghijklmnopqrstuv",es=5,ts=7,Ki=es+1;function yy(e,t){let r=uy.indexOf(e);return r<0?0:my.indexOf(py.charAt(r*ts+t))}i(yy,"glyphRow");function lc(e){let t=ic(Xr.width,Xr.height),r=e.trim();if(r.length===0)return t;let o=[...r],n=4;for(;n>1&&(o.length*Ki-1)*n>t.width-8;)n-=1;let a=(o.length*Ki-1)*n,l=Math.max(0,Math.floor((t.width-a)/2)),c=Math.floor((t.height-ts*n)/2);return o.forEach((s,d)=>{let u=l+d*Ki*n;for(let p=0;p<ts;p+=1){let f=yy(s,p);for(let b=0;b<es;b+=1)if((f>>es-1-b&1)!==0)for(let R=0;R<n;R+=1)for(let v=0;v<n;v+=1){let w=u+b*n+v,g=c+p*n+R;w<t.width&&g<t.height&&(t.pixels[g*t.width+w]=1);}}}),t}i(lc,"rasterizeTypedName");var is=class is{constructor(){this.bytes=[];this.acc=0;this.count=0;}writeBits(t,r){for(this.acc|=t<<this.count,this.count+=r;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8;}writeCode(t,r){let o=0;for(let n=0;n<r;n+=1)o=o<<1|t>>n&1;this.writeBits(o,r);}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};i(is,"BitWriter");var rs=is;function ns(e,t){t<144?e.writeCode(48+t,8):t<256?e.writeCode(400+(t-144),9):t<280?e.writeCode(t-256,7):e.writeCode(192+(t-280),8);}i(ns,"writeLiteral");var Qi=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],rc=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Xi=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],nc=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function fy(e,t,r){let o=Qi.length-1;for(;Qi[o]>t;)o-=1;ns(e,257+o),rc[o]>0&&e.writeBits(t-Qi[o],rc[o]);let n=Xi.length-1;for(;Xi[n]>r;)n-=1;e.writeCode(n,5),nc[n]>0&&e.writeBits(r-Xi[n],nc[n]);}i(fy,"writeMatch");var gy=32768,Ji=3,by=258,oc=15,hy=64;function Ry(e){let t=new rs;t.writeBits(1,1),t.writeBits(1,2);let r=new Int32Array(1<<oc).fill(-1),o=new Int32Array(e.length).fill(-1),n=i(c=>(e[c]<<10^e[c+1]<<5^e[c+2])&(1<<oc)-1,"hashAt"),a=i(c=>{if(c+Ji>e.length)return;let s=n(c);o[c]=r[s],r[s]=c;},"insert"),l=0;for(;l<e.length;){let c=0,s=0;if(l+Ji<=e.length){let d=r[n(l)],u=0,p=Math.min(by,e.length-l);for(;d>=0&&u<hy&&l-d<=gy;){let f=0;for(;f<p&&e[d+f]===e[l+f];)f+=1;if(f>c&&(c=f,s=l-d,f===p))break;d=o[d],u+=1;}}if(c>=Ji){fy(t,c,s);for(let d=0;d<c;d+=1)a(l+d);l+=c;}else ns(t,e[l]),a(l),l+=1;}return ns(t,256),t.finish()}i(Ry,"deflate");function vy(e){let t=1,r=0;for(let o of e)t=(t+o)%65521,r=(r+t)%65521;return (r<<16|t)>>>0}i(vy,"adler32");var yo=null;function wy(e){if(yo===null){yo=new Uint32Array(256);for(let r=0;r<256;r+=1){let o=r;for(let n=0;n<8;n+=1)o=o&1?3988292384^o>>>1:o>>>1;yo[r]=o>>>0;}}let t=4294967295;for(let r of e)t=yo[(t^r)&255]^t>>>8;return (t^4294967295)>>>0}i(wy,"crc32");function kn(e){return [e>>>24&255,e>>>16&255,e>>>8&255,e&255]}i(kn,"u32");function Zi(e,t){let r=Uint8Array.from([...e].map(n=>n.charCodeAt(0))),o=new Uint8Array(r.length+t.length);return o.set(r,0),o.set(t,r.length),[...kn(t.length),...o,...kn(wy(o))]}i(Zi,"chunk");var fo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function xy(e){let t="";for(let r=0;r<e.length;r+=3){let o=e[r],n=r+1<e.length?e[r+1]:0,a=r+2<e.length?e[r+2]:0,l=o<<16|n<<8|a;t+=fo.charAt(l>>18&63)+fo.charAt(l>>12&63),t+=r+1<e.length?fo.charAt(l>>6&63):"=",t+=r+2<e.length?fo.charAt(l&63):"=";}return t}i(xy,"toBase64");function os(e){let{width:t,height:r,pixels:o}=e,n=Math.ceil(t/8)+1,a=new Uint8Array(n*r);for(let u=0;u<r;u+=1){let p=u*n;a[p]=0,a.fill(255,p+1,p+n);for(let f=0;f<t;f+=1)if(o[u*t+f]===1){let b=p+1+(f>>3);a[b]=a[b]&~(128>>(f&7));}}let l=Ry(a),c=new Uint8Array(2+l.length+4);c[0]=120,c[1]=1,c.set(l,2),c.set(kn(vy(a)),2+l.length);let s=Uint8Array.from([...kn(t),...kn(r),1,0,0,0,0]),d=Uint8Array.from([137,80,78,71,13,10,26,10,...Zi("IHDR",s),...Zi("IDAT",c),...Zi("IEND",new Uint8Array(0))]);return xy(d)}i(os,"encodeSignaturePng");var Ro=2.6,uc="#111111";function ky(e,t){let r=[];return e.forEach((o,n)=>{let a=i(l=>{let c=o[l];return [c[0]/t,c[1]/t]},"at");if(o.length===1){let[l,c]=a(0);r.push({key:`${n}-0`,cx:l,cy:c,length:0,angle:0});return}for(let l=1;l<o.length;l+=1){let[c,s]=a(l-1),[d,u]=a(l);r.push({key:`${n}-${l}`,cx:(c+d)/2,cy:(s+u)/2,length:Math.hypot(d-c,u-s),angle:Math.atan2(u-s,d-c)});}}),r}i(ky,"strokeSegments");var Ty=8,pc=2;function Mr({onChange:e,disabled:t=false}){let r=_y(),[o,n]=useState("draw"),[a,l]=useState(""),[c,s]=useState([]),[d,u]=useState(0),p=useRef([]),f=useRef(null),b=d>0?Xr.width/d:1,R=useRef(b);R.current=b;let v=useRef(t);v.current=t,useEffect(()=>{if(o==="type"){Kn(e,a.trim().length>0?os(lc(a)):null);return}let S=c.reduce((T,C)=>T+C.length,0);Kn(e,S>=Ty?os(ac(c)):null);},[o,a,c,e]);let w=i(S=>{let{locationX:T,locationY:C}=S.nativeEvent;return [T*R.current,C*R.current]},"point"),g=i(()=>{let S=p.current,T=f.current;p.current=[],f.current=null,s(C=>[...C.filter(A=>A!==T),S]);},"commitStroke"),y=useMemo(()=>PanResponder.create({onStartShouldSetPanResponder:i(()=>!v.current,"onStartShouldSetPanResponder"),onMoveShouldSetPanResponder:i(()=>!v.current,"onMoveShouldSetPanResponder"),onPanResponderTerminationRequest:i(()=>false,"onPanResponderTerminationRequest"),onPanResponderGrant:i(S=>{p.current=[w(S)];},"onPanResponderGrant"),onPanResponderMove:i(S=>{let T=w(S),C=p.current[p.current.length-1];if(C!==void 0&&Math.abs(C[0]-T[0])<pc&&Math.abs(C[1]-T[1])<pc)return;p.current=[...p.current,T];let A=f.current,F=p.current;f.current=F,s(q=>[...q.filter(U=>U!==A),F]);},"onPanResponderMove"),onPanResponderRelease:i(()=>g(),"onPanResponderRelease"),onPanResponderTerminate:i(()=>g(),"onPanResponderTerminate")}),[]),x=useCallback(()=>{v.current||(p.current=[],f.current=null,s([]),l(""));},[]),h=useCallback(()=>{x(),n(S=>S==="draw"?"type":"draw");},[x]),I=i(S=>u(S.nativeEvent.layout.width),"onLayout");return jsxs(View,{style:r.container,testID:"records-signature-pad",children:[jsx(m,{style:r.label,children:o==="draw"?W.draw:W.type}),o==="type"?jsx(He,{accessibilityLabel:W.type,style:r.input,value:a,maxLength:100,editable:!t,autoComplete:"off",autoCorrect:false,onChangeText:S=>{v.current||l(S);}}):null,jsx(View,{onLayout:I,style:[r.canvas,{height:d>0?d/3:120}],accessible:true,accessibilityLabel:W.sign,accessibilityRole:"image",testID:"records-signature-canvas",...o==="draw"?y.panHandlers:{},children:o==="type"?jsx(m,{style:r.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:a.trim()}):ky(c,b).map(S=>{let T=S.length+Ro;return jsx(View,{pointerEvents:"none",style:[r.segment,{width:T,left:S.cx-T/2,top:S.cy-Ro/2,transform:[{rotate:`${S.angle}rad`}]}]},S.key)})}),jsxs(View,{style:r.actions,children:[jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:W.clear,accessibilityState:{disabled:t},disabled:t,onPress:x,style:r.button,children:jsx(m,{style:r.buttonLabel,children:W.clear})}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:o==="draw"?W.toType:W.toDraw,accessibilityState:{disabled:t},disabled:t,onPress:h,style:r.button,children:jsx(m,{style:r.buttonLabel,children:o==="draw"?W.toType:W.toDraw})})]})]})}i(Mr,"SignaturePad");function _y(){let e=V();return useMemo(()=>Py(e),[e])}i(_y,"useStyles");function Py(e){let{color:t,space:r,radius:o,type:n}=e;return StyleSheet.create({container:{gap:r.sm},label:{...k(e,"regular"),fontSize:n.size.body,color:t.text.primary},input:{minHeight:44,padding:r.sm,borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,color:t.text.primary,backgroundColor:t.surface,...k(e,"regular"),fontSize:n.size.body},canvas:{width:"100%",backgroundColor:"#ffffff",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,overflow:"hidden",justifyContent:"center"},segment:{position:"absolute",height:Ro,borderRadius:Ro/2,backgroundColor:uc},typedPreview:{textAlign:"center",fontSize:32,fontStyle:"italic",fontWeight:"700",color:uc,paddingHorizontal:r.md},actions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},button:{minHeight:44,paddingHorizontal:r.md,justifyContent:"center",borderWidth:1,borderColor:t.borderHairlineGreen,borderRadius:o.sm,backgroundColor:t.surface},buttonLabel:{...k(e,"regular"),fontSize:n.size.body,color:t.text.primary}})}i(Py,"makeStyles");function as(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Le,{capability:"recordsClinic",...ze(e.onClose,W.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:pe.sessionRequired}):jsx(Ay,{...Oe(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(as,"EverfurClinicRequestBatch");function Ay(e){let t=Ut(),r=Ii(),o=e.controller??t,[n,a]=useState(null),l=useCallback(async()=>n===null?null:{signaturePngBase64:n},[n]),c=useCallback((w,g)=>Yi(w,o,g),[o]),s=ec(e,o,e.batchClient??r,e.onCaptureSignature??l,e.onCaptureSignature?void 0:c),d=e.onCaptureSignature!==void 0||n!==null,u=V(),p={minHeight:44,padding:u.space.sm,borderWidth:1,borderColor:u.color.borderHairlineGreen,borderRadius:u.radius.sm,color:u.color.text.primary,backgroundColor:u.color.surface},f={color:u.color.text.primary,fontSize:u.type.size.body},b={color:u.color.text.muted,fontSize:u.type.size.bodyTight},R=i((w,g,y=false,x=w)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:x,accessibilityState:{disabled:y},disabled:y,onPress:g,style:[p,{justifyContent:"center",opacity:y?.5:1}],children:jsx(m,{style:f,children:w})}),"button"),v=s.busy?Ne.sending:s.drafts.length===0?Ne.addToContinue:s.error?Ne.tryAgain:Ne.send(s.drafts.length);return jsxs(View,{accessibilityLabel:s.outcome?Ne.resultTitle:Ne.title,style:[{backgroundColor:u.color.surface,padding:u.space.lg,gap:u.space.md,borderRadius:u.radius.lg,minHeight:120},e.style],children:[jsx(m,{accessibilityRole:"header",style:[f,{...k(u,"bold"),fontSize:u.type.size.heading}],children:s.outcome?Ne.resultTitle:Ne.title}),jsx(m,{style:f,children:e.petName}),s.outcome?jsxs(View,{style:{gap:u.space.sm},testID:"records-batch-result",children:[jsx(m,{accessibilityRole:"summary",accessibilityLiveRegion:"polite",style:f,children:s.outcome.createdCount===0?Ne.allFailed:s.outcome.failedCount>0?Ne.partial(s.outcome.createdCount,s.outcome.results.length,s.outcome.failedCount):Ne.allSent(s.outcome.createdCount)}),jsx(m,{accessibilityRole:"header",style:f,children:Ne.perClinic}),s.outcome.results.map((w,g)=>{let y=w.request?.clinicName??s.drafts[g]?.clinic?.name??w.clinicFreeText??"",x=w.created?Ne.sent:Ne.notSent;return jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:[`${y}. ${x}.`,w.created?w.request?.statusLabel:w.failureReason].filter(Boolean).join(" "),testID:`records-batch-row-${w.created?"created":"failed"}`,children:[jsx(m,{style:f,children:y}),jsx(m,{style:b,children:x}),w.created&&w.request?.statusLabel?jsx(m,{style:b,children:w.request.statusLabel}):null,!w.created&&w.failureReason?jsx(m,{style:b,children:w.failureReason}):null]},w.idempotencyKey)}),s.group?jsx(m,{accessibilityLiveRegion:"polite",style:f,children:Ne.responded(s.group.responded,s.group.total)}):null,s.group?.members.map(w=>w.statusLabel?jsx(m,{style:b,children:[w.clinicName,w.statusLabel].filter(Boolean).join(": ")},w.id):null)]}):jsxs(Fragment,{children:[jsx(m,{style:f,children:W.ownerName}),jsx(He,{accessibilityLabel:W.ownerName,style:p,value:s.ownerName,maxLength:200,editable:!s.busy,autoComplete:"name",onChangeText:s.setOwnerName}),s.drafts.map(w=>jsxs(View,{style:{gap:u.space.xs},testID:`records-batch-draft-${w.key}`,children:[jsx(m,{style:f,children:Sn(w)}),En(w)?jsxs(Fragment,{children:[jsx(m,{style:b,children:w.email.trim()?w.email:Ne.emailToAdd}),jsx(He,{accessibilityLabel:W.email,style:p,value:w.email,placeholder:W.emailPlaceholder,placeholderTextColor:u.color.text.placeholder,maxLength:320,editable:!s.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:g=>s.setDraftEmail(w.key,g)})]}):null,R(Ne.remove(Sn(w)),()=>s.removeDraft(w.key),s.busy)]},w.key)),jsx(m,{style:f,children:s.atCap?Ne.atCap:Ne.addClinic}),!s.atCap&&jsxs(Fragment,{children:[jsx(He,{accessibilityLabel:W.clinic,style:p,value:s.query,placeholder:W.placeholder,placeholderTextColor:u.color.text.placeholder,maxLength:200,editable:!s.busy,onChangeText:s.setQuery}),R(W.search,()=>{s.search();},s.busy||s.searching||s.query.trim().length<2),s.query.trim().length>0&&s.clinics.length===0&&!s.searching&&R(Ne.addClinic,s.addFreeText,s.busy),s.searching&&jsx(m,{accessibilityLiveRegion:"polite",style:f,children:pe.loading}),s.recent.length>0&&jsx(m,{accessibilityRole:"header",style:f,children:W.recentlyUsed}),s.recent.map(w=>jsx(View,{children:R([w.name,w.address,w.phone].filter(Boolean).join(", "),()=>s.addClinic(w),s.busy)},`recent-${w.id}`)),s.clinics.map(w=>jsx(View,{children:R([w.name,w.address,w.phone].filter(Boolean).join(", "),()=>s.addClinic(w),s.busy)},w.id))]}),jsx(m,{accessibilityRole:"header",style:f,children:W.scopeHeading}),s.copy?jsx(m,{style:f,children:s.drafts.length>0&&s.ownerName.trim()?s.scopeText??N("internalError").displayMessage:pe.consentRequired}):!s.error&&jsx(m,{accessibilityLiveRegion:"polite",style:f,children:pe.loading}),!e.onCaptureSignature&&jsx(Mr,{onChange:a,disabled:s.busy}),!d&&jsx(m,{accessibilityRole:"alert",style:f,children:W.missingSignature}),s.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:f,children:s.error.displayMessage}),!s.copy&&s.error&&R(pe.retry,s.retryCopy),R(v,()=>{s.submit();},s.busy||!s.ready||!d,Ne.sendA11y(s.drafts.length))]}),e.onClose&&R(W.cancel,e.onClose,s.busy),jsx(Ve,{})]})}i(Ay,"BatchBody");var ce=Object.freeze({scopeHeading:"What you\u2019re authorizing",scopeBody:"You\u2019re asking your pet\u2019s clinic to release their medical records to Everfur, on your behalf, so we can organize them for you.",whatWeDo:Object.freeze(["We email the clinic a signed copy of this authorization.","When records arrive, our team reviews them before they appear in your app.","You can revoke this request at any time."]),retentionNote:"We keep the records you receive so you always have them. See our Privacy Policy for how records are stored and used.",authorizeLabel:i((e,t)=>`I authorize ${t} to release ${Fe(e)}\u2019s records to Everfur.`,"authorizeLabel"),missingSignatureError:"Please add your signature before submitting.",missingDraftError:"Something went wrong with your selection. Please go back and pick the clinic again.",newClinicDirectSendNote:"We\u2019ll email this clinic directly to request your pet\u2019s medical records. Clinics usually reply within a week.",titleFreeText:"Confirm your request",titleDirectory:"Authorize records release",noEmailNote:i((e,t)=>`We don\u2019t have an email on file for ${t}. Add it so we can request ${Fe(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 Oy="value_text",gc=64,bc=512;function hc(e){return e!==null&&e.httpStatus===409&&!sr(e)}i(hc,"isFactReviewerLocked");var Tn=Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:Oy}),Rc=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,vc=/^\d{4}-\d{2}-\d{2}$/;function wc(e){if(e==null)return "text";let t=e.trim();return Rc.test(t)?"num":vc.test(t)&&!Number.isNaN(Date.parse(t))?"date":t==="true"||t==="false"?"bool":"text"}i(wc,"inferFactValueKind");function ls(e,t){let r=t.trim(),o=wc(e);if(o==="num"&&Rc.test(r)){let n=Number(r);if(Number.isFinite(n))return Object.freeze({[Tn.num]:n})}return o==="date"&&vc.test(r)&&!Number.isNaN(Date.parse(r))?Object.freeze({[Tn.date]:r}):Object.freeze(o==="bool"&&(r==="true"||r==="false")?{[Tn.bool]:r==="true"}:{[Tn.text]:r})}i(ls,"factCorrectionFor");var De=z.string().nullish(),vo=z.number().nullish(),Ly=z.object({collected_at:De,at:De,value:vo,unit:De,qualitative_result:De,ref_low:vo,ref_high:vo,status:De,source_clinic:De,source_doc_id:De,doc_id:De,reviewed:z.boolean().nullish()}),Vy=z.object({collected_at:De,at:De,value:vo,unit:De,qualitative_result:De,status:De}),qy=z.object({marker_id:z.string().min(1),canonical_name:De,name:De,loinc_code:De,canonical_unit:De,unit:De,panel_name:De,panel:De,meaning_text:De,meaning:De,latest:Vy.nullish(),trajectory:De,points:z.array(Ly).optional()}),zy=z.object({total_markers:z.number().int().nonnegative(),in_range_count:z.number().int().nonnegative(),out_of_range_count:z.number().int().nonnegative(),unknown_count:z.number().int().nonnegative()}),Fy=z.object({markers:z.array(qy).optional(),summary:zy.nullish(),disclaimer:z.string().optional(),featured_marker_id:De});function Ny(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Ny,"isObject");function xc(e){return Object.freeze({petRef:e,withheld:true,markers:Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}i(xc,"withheldMarkers");function Cc(e,t){let r=Ny(t)?t:{},o=typeof r.pet_ref=="string"&&r.pet_ref.length>0?r.pet_ref:e;if(r.withheld===true)return xc(o);let n=Fy.safeParse(r);if(!n.success)return xc(o);let a=n.data,l=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"),c=(a.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(l))}));return Object.freeze({petRef:o,withheld:false,markers:Object.freeze(c),summary:a.summary?Object.freeze({totalMarkers:a.summary.total_markers,inRangeCount:a.summary.in_range_count,outOfRangeCount:a.summary.out_of_range_count,unknownCount:a.summary.unknown_count}):null,disclaimer:a.disclaimer??"",featuredMarkerId:a.featured_marker_id??null})}i(Cc,"mapRecordMarkers");var My=z.string().min(1).refine(e=>e.startsWith("https://")),By=z.object({source_doc_id:z.string().min(1),file_name:z.string().nullish(),doc_format:z.string().nullish(),byte_size:z.number().int().nonnegative().nullish(),received_at:z.string().nullish(),download_url:My,expires_in_seconds:z.number().int().nonnegative().nullish()}),Hy=z.object({items:z.array(z.unknown()).optional()});function Ec(e){let t=Hy.safeParse(e);if(!t.success)return null;let r=[];for(let o of t.data.items??[]){let n=By.safeParse(o);n.success&&r.push(Object.freeze({sourceDocId:n.data.source_doc_id,fileName:n.data.file_name??null,docFormat:n.data.doc_format??null,byteSize:n.data.byte_size??null,receivedAt:n.data.received_at??null,downloadUrl:n.data.download_url,expiresInSeconds:n.data.expires_in_seconds??0}));}return Object.freeze(r)}i(Ec,"mapRequestDocuments");var Uy=z.string().min(1).refine(e=>e.startsWith("https://")),_n=z.string().nullish(),jy=z.object({share_id:z.string().min(1),share_url:z.string().min(1),expires_at:_n}),$y=z.object({shares:z.array(z.object({share_id:z.string().min(1),expires_at:_n,created_at:_n,view_count:z.number().int().nonnegative().nullish(),last_viewed_at:_n})).optional()}),Wy=z.object({download_url:Uy,expires_at:_n});function Gy(e,t){let r=e.trim();if(r.length===0)return null;try{let o=/^[a-z][a-z0-9+.-]*:/i.test(r)?new URL(r):t!==void 0?new URL(r,t):null;return o===null||o.protocol!=="https:"?null:o.toString()}catch{return null}}i(Gy,"resolveShareUrl");function Sc(e,t){let r=jy.safeParse(e);if(!r.success)return null;let o=Gy(r.data.share_url,t);return o===null?null:Object.freeze({shareId:r.data.share_id,shareUrl:o,expiresAt:r.data.expires_at??null})}i(Sc,"mapRecordShareLink");function kc(e){let t=$y.safeParse(e);return t.success?Object.freeze((t.data.shares??[]).map(r=>Object.freeze({shareId:r.share_id,expiresAt:r.expires_at??null,createdAt:r.created_at??null,viewCount:r.view_count??0,lastViewedAt:r.last_viewed_at??null}))):null}i(kc,"mapRecordShareList");function Tc(e){let t=Wy.safeParse(e);return t.success?Object.freeze({downloadUrl:t.data.download_url,expiresAt:t.data.expires_at??null}):null}i(Tc,"mapRecordPdfLink");var Yy=z.object({signatures:z.array(z.object({signature_id:z.string().min(1),preview_url:z.string().min(1).refine(e=>e.startsWith("https://")),created_at:z.string().nullish()})).optional()});function _c(e){let t=Yy.safeParse(e);return t.success?Object.freeze((t.data.signatures??[]).map(r=>Object.freeze({signatureId:r.signature_id,previewUrl:r.preview_url,createdAt:r.created_at??null}))):null}i(_c,"mapSignatureSuggestions");var B=z.string().nullish(),Pn=z.number().nullish(),Ky=z.object({at:B,value:Pn,unit:B,qualitative_result:B,ref_low:Pn,ref_high:Pn,status:B,doc_id:B}),Qy=z.object({marker_id:z.string(),name:z.string(),loinc_code:B,unit:B,panel:B,meaning:B,latest:z.object({at:B,value:Pn,unit:B,qualitative_result:B,status:B}).nullish(),trajectory:B,points:z.array(Ky).optional()}),Xy=z.object({encounter_id:z.string(),date:B,type:B,clinic_name:B,veterinarian:B,doc_id:B}),Jy=z.object({note_id:z.string(),encounter_id:B,observed_on:B,sections:z.array(z.object({section:z.string(),text:z.string()})).optional()}),Zy=z.object({exam_id:z.string(),encounter_id:B,observed_on:B,doc_id:B,systems:z.record(z.object({finding_status:B,finding:B})).optional()}),ef=z.object({has_lab_history:z.boolean().optional(),has_vaccination_history:z.boolean().optional(),has_weight_history:z.boolean().optional(),has_vitals_history:z.boolean().optional(),has_physical_exam_history:z.boolean().optional(),has_procedure_history:z.boolean().optional(),has_genetic_history:z.boolean().optional(),has_reproductive_history:z.boolean().optional(),has_parasite_prevention_history:z.boolean().optional(),earliest_record_at:B,latest_record_at:B,documents_ingested:z.number().int().nonnegative().optional(),documents_in_review:z.number().int().nonnegative().optional(),entities_pending_review:z.record(z.number().int().nonnegative()).optional(),held_total:z.number().int().nonnegative().optional()}),tf=z.object({conflict_id:z.string(),entity_type:z.string(),field:B,severity:B,candidates:z.array(z.object({value:z.string(),source_doc_id:B,doc_id:B,collected_at:B})).optional()}),rf=z.object({lab_results:z.array(Qy).optional(),encounters:z.array(Xy).optional(),clinician_notes:z.array(Jy).optional(),physical_exams:z.array(Zy).optional(),completeness:ef.nullish(),conflicts:z.array(tf).optional()}),nf=z.object({visits:z.array(z.object({visit_id:z.string(),visit_date:B,veterinarian:B,summary:B,doc_id:B})),vaccines:z.array(z.object({vaccine_id:z.string(),product:B,lot:B,administered_on:B,expires_on:B,doc_id:B})),weights:z.array(z.object({weight_id:z.string(),observed_on:B,weight_kg:Pn,doc_id:B})),medications:z.array(z.object({medication_id:z.string(),drug_name:B,dose:B,route:B,frequency:B,sig:B,rx_number:B,started_on:B,stopped_on:B,doc_id:B})),disclaimer:z.string().optional()}),of=z.object({document:ri,contributions:z.array(ti),contribution_count:z.number().int().nonnegative().optional()});function ds(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ds,"isObject");function us(e,t){return typeof e.pet_ref=="string"&&e.pet_ref.length>0?e.pet_ref:t}i(us,"petOf");function cs(e,t){return Object.freeze({petRef:e,available:false,withheld:t,labResults:Object.freeze([]),encounters:Object.freeze([]),clinicianNotes:Object.freeze([]),physicalExams:Object.freeze([]),completeness:null,conflicts:Object.freeze([])})}i(cs,"emptyDepth");function sf(e,t){let r=ds(t)?t:{},o=us(r,e);if(r.withheld===true)return cs(o,true);if(!["lab_results","encounters","clinician_notes","physical_exams","completeness","conflicts"].some(s=>s in r))return cs(o,false);let a=rf.safeParse(r);if(!a.success)return cs(o,true);let l=a.data,c=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((l.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(c))}))),encounters:Object.freeze((l.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((l.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(d=>Object.freeze({section:d.section,text:d.text})))}))),physicalExams:Object.freeze((l.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(([d,u])=>Object.freeze({system:d,findingStatus:u.finding_status??null,finding:u.finding??null})))}))),completeness:l.completeness?Object.freeze({hasLabHistory:l.completeness.has_lab_history===true,hasVaccinationHistory:l.completeness.has_vaccination_history===true,hasWeightHistory:l.completeness.has_weight_history===true,hasVitalsHistory:l.completeness.has_vitals_history===true,hasPhysicalExamHistory:l.completeness.has_physical_exam_history===true,hasProcedureHistory:l.completeness.has_procedure_history===true,hasGeneticHistory:l.completeness.has_genetic_history===true,hasReproductiveHistory:l.completeness.has_reproductive_history===true,hasParasitePreventionHistory:l.completeness.has_parasite_prevention_history===true,earliestRecordAt:l.completeness.earliest_record_at??null,latestRecordAt:l.completeness.latest_record_at??null,documentsIngested:l.completeness.documents_ingested??0,documentsInReview:l.completeness.documents_in_review??0,entitiesPendingReview:Object.freeze({...l.completeness.entities_pending_review??{}}),heldTotal:l.completeness.held_total??0}):null,conflicts:Object.freeze((l.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(d=>Object.freeze({value:d.value,docId:d.source_doc_id??d.doc_id??null,collectedAt:d.collected_at??null})))})))})}i(sf,"mapRecordDepth");function Pc(e){return Object.freeze({petRef:e,withheld:true,isEmpty:false,visits:Object.freeze([]),vaccines:Object.freeze([]),weights:Object.freeze([]),medications:Object.freeze([]),disclaimer:""})}i(Pc,"withheldTimeline");function af(e,t){let r=ds(t)?t:{},o=us(r,e);if(r.withheld===true)return Pc(o);let n=nf.safeParse(r);if(!n.success)return Pc(o);let a=n.data,l=a.visits.map(u=>Object.freeze({visitId:u.visit_id,visitDate:u.visit_date??null,veterinarian:u.veterinarian??null,summary:u.summary??null,docId:u.doc_id??null})),c=a.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=a.weights.map(u=>Object.freeze({weightId:u.weight_id,observedOn:u.observed_on??null,weightKg:u.weight_kg??null,docId:u.doc_id??null})),d=a.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:l.length===0&&c.length===0&&s.length===0&&d.length===0,visits:Object.freeze(l),vaccines:Object.freeze(c),weights:Object.freeze(s),medications:Object.freeze(d),disclaimer:a.disclaimer??""})}i(af,"mapRecordsTimeline");function lf(e,t){let r=ds(t)?t:{},o=us(r,e),n=i(()=>Object.freeze({petRef:o,withheld:true,document:null,contributions:Object.freeze([]),contributionCount:0}),"withheld");if(r.withheld===true)return n();let a=of.safeParse(r);if(!a.success)return n();let l=Object.freeze(a.data.contributions.map(ni));return Object.freeze({petRef:o,withheld:false,document:oi(a.data.document),contributions:l,contributionCount:a.data.contribution_count??l.length})}i(lf,"mapDocumentContributions");var cf="/widget/v1/records/pets";function Ic(e){let t=e.funnel??vr({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=i((s,d)=>typeof s=="string"&&s.length>0&&!wr(s)&&[...s].length<=d,"segment"),o=i(async(s,d,u,p)=>{if(!r(d,gt))return pr();let f=await t.send(s,{method:"GET",path:u});if(!f.ok)return f;let b=p(f.value);return b.petRef===d?Pe(b):H(N("internalError",{retryable:false}))},"read"),n=i(s=>`${cf}/${encodeURIComponent(s)}`,"pet"),a=i(s=>`${n(s)}/everfur_record`,"record"),l=i(async(s,d,u)=>{let p=await t.send(s,d,d.method==="POST"?{idempotent:false,maxAttempts:1}:void 0);if(!p.ok)return p;let f=u(p.value);return f===null?H(N("internalError",{retryable:false})):Pe(f)},"parsed"),c=i((s,d)=>!r(s.entityType,gc)||!r(s.canonicalKey,bc)||s.idempotencyKey!==void 0&&!r(s.idempotencyKey,dn)||d!==void 0&&Object.keys(d).length===0?null:{entity_type:s.entityType,canonical_key:s.canonicalKey,...d!==void 0?{corrected_fields:d}:{},...s.idempotencyKey!==void 0?{idempotency_key:s.idempotencyKey}:{}},"factBody");return {getRecordDepth:i(s=>o("records.depth.record",s,`${n(s)}/record`,d=>sf(s,d)),"getRecordDepth"),getTimeline:i(s=>o("records.depth.timeline",s,`${n(s)}/timeline`,d=>af(s,d)),"getTimeline"),getDocumentContributions(s,d){return r(d,64)?o("records.depth.contributions",s,`${n(s)}/documents/${encodeURIComponent(d)}/contributions`,u=>lf(s,u)):pr()},getMarkers:i(s=>o("records.depth.markers",s,`${n(s)}/markers`,d=>Cc(s,d)),"getMarkers"),createShare(s){return r(s,gt)?l("records.share.create",{method:"POST",path:`${a(s)}/share`},d=>Sc(d,e.apiBaseUrl)):pr()},listShares(s){return r(s,gt)?l("records.share.list",{method:"GET",path:`${a(s)}/shares`},kc):pr()},async revokeShare(s,d){if(!r(s,gt)||!r(d,64))return pr();let u=await t.send("records.share.revoke",{method:"DELETE",path:`${a(s)}/shares/${encodeURIComponent(d)}`},{idempotent:false,maxAttempts:1});return u.ok?Pe(void 0):u},getPdfLink(s){return r(s,gt)?l("records.pdf.link",{method:"GET",path:`${a(s)}/pdf-link`},Tc):pr()},async editFact(s,d){let u=r(s,gt)?c(d,d.correctedFields):null;if(u===null)return pr();let p=await t.send("records.fact.edit",{method:"POST",path:`${a(s)}/facts/edit`,body:u},{idempotent:false,maxAttempts:1});return p.ok?Pe(void 0):p},async removeFact(s,d){let u=r(s,gt)?c(d):null;if(u===null)return pr();let p=await t.send("records.fact.remove",{method:"POST",path:`${a(s)}/facts/remove`,body:u},{idempotent:false,maxAttempts:1});return p.ok?Pe(void 0):p},listRequestDocuments(s){return r(s,64)?l("records.request.documents",{method:"GET",path:`/widget/v1/records/requests/${encodeURIComponent(s)}/documents`},Ec):pr()},listAuthorizationSignatures:i(()=>l("records.signatures.list",{method:"GET",path:"/widget/v1/records/authorization-signatures"},_c),"listAuthorizationSignatures")}}i(Ic,"createRecordsDepthClient");function pr(){return Promise.resolve(H(N("validationFailed",{retryable:false})))}i(pr,"invalid");function mr(){let{runtime:e,userRef:t,scopeEpoch:r}=ke();return useMemo(()=>{let{services:o}=e.registry;return Ic({auth:o.authFor(t),...o.errorPolicy?{errorPolicy:o.errorPolicy}:{},...typeof o.apiBaseUrl=="string"?{apiBaseUrl:o.apiBaseUrl}:{}})},[e,t,r])}i(mr,"useEverfurRecordsDepthClient");function Gt(e,t,r,o=""){let n=mr(),{userRef:a}=ke(),l=$n(e),c=useMemo(()=>({}),[n,e,o,l]),[s,d]=useState({scope:c,value:null,error:null,loading:true}),u=useRef(0),p=useCallback(async()=>{let g=u.current+=1;if(d({scope:c,value:null,error:null,loading:true}),a===null){d({scope:c,value:null,error:null,loading:false});return}let y=await t(n,e);g===u.current&&(y.ok?d({scope:c,value:y.value,error:null,loading:false}):d({scope:c,value:null,error:y.error,loading:false}));},[n,e,t,c,a]);useEffect(()=>(p(),()=>{u.current+=1;}),[p]);let f=s.scope===c?s:{value:null,error:null,loading:true},b=useCallback(()=>{p();},[p]),R=f.error===null||f.error.httpStatus!==404,v=R?f.error:null,w=f.loading?"loading":v!==null?"error":f.value===null?"empty":f.value.withheld?"populated":r(f.value)?"empty":"populated";return useMemo(()=>({status:w,value:f.value,error:v,available:R,refresh:b}),[w,f.value,v,R,b])}i(Gt,"useRecordsDepthRead");function Tr(e){return e!==null&&e.httpStatus===404}i(Tr,"isDarkRouteError");var yf=i((e,t)=>e.getMarkers(t),"readMarkers"),ff=i(e=>e.markers.length===0,"markersEmpty");function ms(e){let t=Gt(e,yf,ff);return useMemo(()=>{let r=t.available&&t.value!==null&&!t.value.withheld?t.value:null;return {status:t.status,markers:r,available:t.available,error:t.error,refresh:t.refresh}},[t])}i(ms,"useRecordsMarkers");var gf=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function Oc(e){let{clinic:t,controller:r,depthClient:o,capture:n,onCreated:a}=e,l=t.clinic?.name??t.freeText??"",c=t.clinic===null,[s,d]=useState(false),[u,p]=useState(e.ownerName),[f,b]=useState(t.email),[R,v]=useState(false),[w,g]=useState(null),[y,x]=useState(null),[h,I]=useState(0),[S,T]=useState(null),[C,A]=useState(false),[F,q]=useState(null),[U,j]=useState([]),[ae,ne]=useState(null),[Re,te]=useState(false),_=useRef(false),D=useRef(true),E=useRef(ar()),L=useRef(null);useEffect(()=>(D.current=true,()=>{D.current=false,L.current=null;}),[r]),useEffect(()=>{let Se=true;return g(null),L.current=null,r.getAuthorizationCopy().then(M=>{Se&&(M.ok?(g(M.value),x(null)):x(M.error));}).catch(()=>{Se&&x(N("internalError"));}),()=>{Se=false;}},[r,h]),useEffect(()=>{if(o===void 0)return;let Se=true;return o.listAuthorizationSignatures().then(M=>{Se&&(M.ok?j(M.value):Tr(M.error)||j([]));}).catch(()=>{}),()=>{Se=false;}},[o]);let X=Cn(t.clinic),fe=f.trim().toLowerCase(),Be=gf.test(fe),oe=X&&(R||fe.length>0)&&!Be?ce.emailRequired:null,Ce=w?xn(w,u.trim(),Fe(e.petName),l):null,xt=e.hostCapture===true||Re||ae!==null,tt=!!(s&&w&&Ce&&u.trim()&&l&&xt&&(!X||Be)),Nt=useCallback(async()=>{if(!(_.current||F!==null||!w||!Ce)){if(!l){T(ce.missingDraftError);return}if(X&&!Be){v(true),T(ce.emailRequired);return}if(!(!s||!u.trim())){_.current=true,A(true),T(null);try{if(L.current===null){let M=ae!==null?{signatureId:ae}:await n();if(!D.current)return;if(M===null){T(ce.missingSignatureError);return}let ve=t.clinic&&(!X||t.clinic.emailStatus==="none")?{clinicId:t.clinic.id}:{clinicFreeText:l};L.current={petRef:e.petRef,ownerName:u.trim(),authorizationVersion:w.authorizationVersion,...ve,...X?{clinicEmail:fe}:{},...M.signatureId!==void 0?{signatureId:M.signatureId}:{signaturePngBase64:M.signaturePngBase64},idempotencyKey:E.current()};}let Se=await r.createClinicRequest(L.current);if(!D.current)return;if(!Se.ok){T(Se.error.displayMessage);return}if(Se.value.petRef!==e.petRef){T(N("internalError").displayMessage);return}q(Se.value),L.current=null,a?.(Se.value);}catch{D.current&&T(N("internalError").displayMessage);}finally{_.current=false,D.current&&A(false);}}}},[s,n,t.clinic,l,r,w,F,e.petRef,X,fe,a,u,ae,Ce,Be]),Mt=useCallback(()=>{L.current=null,T(null);},[]);return {title:c?ce.titleFreeText:ce.titleDirectory,clinicName:l,isFreeText:c,authorized:s,ownerName:u,email:f,emailError:oe,needsEmail:X,directoryClinicNoEmail:X&&t.clinic!==null,copy:w,copyError:y,scope:Ce,error:S,busy:C,created:F,ready:tt,signatures:U,reuseSignatureId:ae,hasSignature:xt,setAuthorized(Se){_.current||(Mt(),d(Se));},setOwnerName(Se){_.current||(Mt(),p(Se));},setEmail(Se){_.current||(Mt(),v(false),b(Se));},setSigned(Se){_.current||(Mt(),te(Se),Se&&ne(null));},pickReuseSignature(Se){_.current||(Mt(),ne(Se));},retryCopy(){x(null),I(Se=>Se+1);},submit:Nt}}i(Oc,"useRecordsConsentForm");function gs(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Le,{capability:"recordsClinic",style:e.style,...ze(e.onBack,Ye),children:t===null?jsx(m,{accessibilityRole:"alert",children:pe.sessionRequired}):jsx(wf,{...Oe(e,["onCreated","onNavigate","onBack"])},JSON.stringify([t,r,e.petRef,e.clinic.key]))})}i(gs,"EverfurRecordsConsent");function wf({petRef:e,petName:t,clinic:r,ownerName:o,onCaptureSignature:n,onCreated:a,controller:l,onNavigate:c,onBack:s,style:d}){let u=ue(),p=xf(),f=V(),b=Ut(),R=mr(),[v,w]=useState(null),[g,y]=useState("draw"),x=useCallback(async()=>v===null?null:{signaturePngBase64:v},[v]),h=Oc({petRef:e,petName:t,ownerName:o??"",clinic:r,controller:l??b,depthClient:R,capture:n?()=>n({petRef:e,petName:Fe(t),ownerName:h.ownerName,clinicName:h.clinicName,authorizationVersion:h.copy?.authorizationVersion??"",scopeText:h.scope??"",signal:new AbortController().signal}):x,hostCapture:n!==void 0,onCreated:i(C=>{a?.(C),c?.({name:"dashboard"});},"onCreated")}),I=useRef(h);I.current=h;let S=useCallback(C=>{w(C),I.current.setSigned(C!==null);},[]),T=h.busy;return jsxs(View,{style:[u.root,d],children:[jsx(Ke,{title:h.title,onBack:s,testID:"records-consent-header"}),jsxs(KeyboardAvoidingView,{behavior:"padding",style:u.body,children:[jsxs(ScrollView,{contentContainerStyle:p.content,keyboardShouldPersistTaps:"handled",testID:"records-consent",children:[jsxs(View,{style:p.scopeCard,accessibilityRole:"summary",children:[jsx(m,{style:p.scopeHeading,accessibilityRole:"header",children:ce.scopeHeading}),jsx(m,{style:p.scopeBody,children:ce.scopeBody}),jsx(View,{style:p.bullets,children:ce.whatWeDo.map(C=>jsxs(View,{style:p.bulletRow,children:[jsx(m,{style:p.check,children:"\u2713"}),jsx(m,{style:p.bulletText,children:C})]},C))}),jsx(View,{style:p.retentionRow,children:jsx(m,{style:p.retentionText,children:ce.retentionNote})}),h.copy&&h.scope?jsx(m,{style:p.serverScope,testID:"records-consent-scope",children:h.scope}):h.copyError?jsxs(Fragment,{children:[jsx(m,{style:u.errorText,accessibilityRole:"alert",children:h.copyError.displayMessage}),jsx(J,{label:pe.retry,kind:"outline",onPress:h.retryCopy,testID:"records-consent-copy-retry"})]}):jsx(m,{style:u.muted,accessibilityLiveRegion:"polite",children:pe.loading})]}),jsxs(Pressable,{onPress:()=>h.setAuthorized(!h.authorized),accessibilityRole:"checkbox",accessibilityState:{checked:h.authorized},accessibilityLabel:ce.authorizeLabel(t,h.clinicName),hitSlop:6,style:[p.toggle,h.authorized?p.toggleChecked:null],testID:"records-authorize-toggle",children:[jsx(View,{style:[p.box,h.authorized?p.boxChecked:null],accessibilityElementsHidden:true,importantForAccessibility:"no",children:h.authorized?jsx(m,{style:p.boxCheck,children:"\u2713"}):null}),jsx(m,{style:p.toggleLabel,children:ce.authorizeLabel(t,h.clinicName)})]}),jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:ce.fullName}),jsx(He,{accessibilityLabel:ce.fullName,style:u.field,value:h.ownerName,placeholder:ce.fullNamePlaceholder,placeholderTextColor:f.color.text.placeholder,maxLength:200,editable:!T,autoComplete:"name",autoCapitalize:"words",onChangeText:h.setOwnerName,testID:"records-consent-owner-name"})]}),h.needsEmail?jsxs(View,{style:p.block,testID:"records-consent-email-block",children:[h.directoryClinicNoEmail?jsx(View,{style:u.cautionNote,testID:"records-consent-no-email-note",children:jsx(m,{style:u.cautionNoteText,children:ce.noEmailNote(t,h.clinicName)})}):null,jsx(m,{style:u.fieldLabel,children:ce.emailLabel}),jsx(He,{accessibilityLabel:ce.emailLabel,style:u.field,value:h.email,placeholder:ce.emailPlaceholder,placeholderTextColor:f.color.text.placeholder,maxLength:320,editable:!T,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:h.setEmail,testID:"records-consent-clinic-email"}),h.emailError?jsx(m,{style:u.errorText,accessibilityRole:"alert",children:h.emailError}):null,jsx(m,{style:u.muted,testID:"records-consent-review-note",children:ce.newClinicDirectSendNote})]}):null,n?null:jsxs(View,{style:p.signatureBlock,children:[h.signatures.length>0?jsxs(View,{style:p.block,children:[jsx(m,{style:u.fieldLabel,children:ce.reuseSignature}),jsx(ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:p.gallery,children:h.signatures.map(C=>{let A=h.reuseSignatureId===C.signatureId;return jsx(Pressable,{onPress:()=>h.pickReuseSignature(A?null:C.signatureId),accessibilityRole:"button",accessibilityLabel:A?ce.reuseTileSelectedA11y:ce.reuseTileA11y,style:[p.tile,A?p.tileSelected:null],testID:`records-consent-reuse-${C.signatureId}`,children:jsx(Image,{source:{uri:C.previewUrl},style:p.tileImage,resizeMode:"contain",accessibilityIgnoresInvertColors:true})},C.signatureId)})}),jsx(m,{style:u.muted,children:ce.reuseHint})]}):null,jsx(View,{style:p.signatureHeader,children:jsx(m,{style:u.fieldLabel,children:g==="type"?ce.signType:ce.signDraw})}),jsx(Mr,{onChange:S,disabled:T}),jsx(Pressable,{onPress:()=>y(C=>C==="draw"?"type":"draw"),accessibilityRole:"button",accessibilityLabel:g==="draw"?ce.toTypeA11y:ce.toDraw,style:p.modeToggle,testID:"records-consent-sign-mode-toggle",children:jsx(m,{style:p.modeToggleText,children:g==="draw"?ce.toType:ce.toDraw})}),jsx(m,{style:u.muted,children:ce.signatureHint(h.clinicName)})]}),h.error?jsx(View,{style:u.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:jsx(m,{style:u.errorText,children:h.error})}):null,h.created?jsx(m,{accessibilityLiveRegion:"polite",style:u.bodyText,children:h.created.statusLabel||pe.records}):null]}),jsx(View,{style:p.footer,children:jsx(J,{label:T?ce.submitting:ce.submit,accessibilityLabel:ce.submitA11y,disabled:!h.ready,busy:T,onPress:()=>{h.submit();},style:p.submit,testID:"records-consent-submit"})})]}),jsx(Ve,{})]})}i(wf,"ConsentBody");function xf(){let e=V();return useMemo(()=>Cf(e),[e])}i(xf,"useLocalStyles");function Cf(e){let{color:t,space:r,radius:o,type:n}=e,a=StyleSheet.hairlineWidth,l=i((c,s,d,u="regular")=>({...k(e,u),fontSize:c,lineHeight:Math.round(c*s),color:d}),"text");return StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xl+r.xs,gap:r.lg+r.xs/2},scopeCard:{borderRadius:o.lg-r.xs/2,borderWidth:a,borderColor:t.brandBorder,backgroundColor:t.surfaceCream,padding:r.lg,gap:r.md},scopeHeading:{...l(n.size.body+1,n.lineHeight.snug,t.brandInk,"bold")},scopeBody:l(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),bullets:{gap:r.sm},bulletRow:{flexDirection:"row",alignItems:"flex-start",gap:r.sm},check:{...l(n.size.body,n.lineHeight.normal,t.brandInk,"bold")},bulletText:{flex:1,...l(n.size.bodyTight,n.lineHeight.normal,t.text.primary)},retentionRow:{paddingTop:r.xs,borderTopWidth:1,borderTopColor:t.borderHairlineGreen},retentionText:l(n.size.tiny,n.lineHeight.normal,t.text.muted),serverScope:{...l(n.size.bodyTight,n.lineHeight.relaxed,t.text.secondary),paddingTop:r.xs},toggle:{flexDirection:"row",alignItems:"flex-start",gap:r.md,borderRadius:o.lg-r.xs,borderWidth:a,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md+r.xs/2},toggleChecked:{borderColor:t.brandInk,backgroundColor:t.brandSoft},box:{width:r.xl,height:r.xl,borderRadius:o.xs+1,borderWidth:1.6,borderColor:t.brandInk,alignItems:"center",justifyContent:"center",backgroundColor:t.surface},boxChecked:{backgroundColor:t.brandInk},boxCheck:{...l(n.size.body,n.lineHeight.tight,t.surface,"bold")},toggleLabel:{flex:1,...l(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"bold")},block:{gap:r.sm},signatureBlock:{gap:r.sm},gallery:{gap:r.sm,paddingVertical:r.xs},tile:{width:r.xxl*3+r.lg,height:r.xxl+r.lg+r.sm,borderRadius:o.sm,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,overflow:"hidden"},tileSelected:{borderColor:t.brandInk,borderWidth:2},tileImage:{width:"100%",height:"100%"},signatureHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},modeToggle:{minHeight:r.xxl+r.md,alignItems:"center",justifyContent:"center"},modeToggleText:{...l(n.size.bodyTight,n.lineHeight.snug,t.linkInk,"bold"),textDecorationLine:"underline"},footer:{paddingHorizontal:r.lg,paddingTop:r.md,paddingBottom:r.xxl,borderTopWidth:a,borderTopColor:t.borderHairlineGreen,backgroundColor:t.background},submit:{minHeight:r.xxl+r.lg+r.xs+r.xs/2}})}i(Cf,"makeLocalStyles");function xo(e){return e==="above"||e==="below"?"critical":e==="in_range"?"positive":"neutral"}i(xo,"markerStatusTone");function Sf(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(Sf,"markerStatusSpoken");function kf(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(kf,"rangePhrase");function Co(e,t){let r=t?` ${t}`:"";return e.refLow!==null&&e.refHigh!==null?`${e.refLow}-${e.refHigh}${r}`:e.refLow!==null?`\u2265 ${e.refLow}${r}`:e.refHigh!==null?`\u2264 ${e.refHigh}${r}`:"-"}i(Co,"formatReferenceRange");function Fc(e,t){let r=t.reviewed?", reviewed by our team":"",o=t.sourceClinic?`, from ${t.sourceClinic}`:"";return `${Y(t.at)}: ${kt(t.value,e.unit,t.qualitativeResult)}, ${Sf(t.status)}${kf(t)}${o}${r}`}i(Fc,"markerPointSpoken");function Xe(e){return e?.trim()||"my pet"}i(Xe,"lead");function Nc(e){let t=e.trim();return /[.!?]$/.test(t)?t:`${t}.`}i(Nc,"clause");function Mc(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`I'm looking at ${Xe(e)}'s ${r}`],n=[t.latestValueText?.trim(),t.statusText?.trim(),t.trajectoryText?.trim()].filter(Boolean).join(", ");return o[0]+=n?`: ${n}.`:".",t.meaningText?.trim()&&o.push(Nc(t.meaningText)),o.push(`What does this trend tell me, and should I do anything differently for ${Xe(e)}?`),{prompt:o.join(" "),entityRef:{type:"marker",id:t.markerId,payload:{marker:r,...t.statusText?.trim()?{status:t.statusText.trim()}:{}}}}}i(Mc,"buildMarkerAskPrompt");function Bc(e,t,r){let{totalMarkers:o,inRangeCount:n,outOfRangeCount:a,unknownCount:l}=t;if(o===0)return {prompt:`I'm looking at ${Xe(e)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${Xe(e)}?`,entityRef:{type:"marker_summary",id:r,payload:{total:0}}};let c=l>0?`, ${l} without a reference range`:"";return {prompt:`I'm looking at ${Xe(e)}'s lab markers: ${o} total, ${n} in range, ${a} out of range${c}. What should I focus on?`,entityRef:{type:"marker_summary",id:r,payload:{total:o,inRange:n,outOfRange:a,unknown:l}}}}i(Bc,"buildMarkerSummaryAskPrompt");function Hc(e,t){let r=t.canonicalName.trim()||"a lab marker",o=[`${r}: ${t.valueText.trim()}`];t.collectedAt?.trim()&&o.push(`collected ${t.collectedAt.trim()}`),t.sourceClinic?.trim()&&o.push(`from ${t.sourceClinic.trim()}`),t.referenceText?.trim()&&o.push(`reference range ${t.referenceText.trim()}`),t.flagged&&o.push(`flagged ${t.flagged}`);let n={marker:r};return t.flagged&&(n.status=t.flagged),t.reviewed!==void 0&&(n.reviewed=t.reviewed),{prompt:`I'm looking at ${Xe(e)}'s ${o.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:t.entityId,payload:n}}}i(Hc,"buildMarkerReadingAskPrompt");function Eo(e,t,r){let o=t.clinicName?.trim(),n=t.heldItemCount??0,a=n>0?`, ${n} fact${n===1?"":"s"} being verified`:"";return {prompt:`I'm looking at ${Xe(e)}'s records request${o?` to ${o}`:""}, status: ${t.statusLabel.trim()}${a}. What does this status mean, and what happens next?`,entityRef:{type:"records_request",id:r,payload:{status:t.status,held:n,...o?{clinic:o}:{}}}}}i(Eo,"buildRecordsRequestAskPrompt");var Tf=Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function bs(e,t,r,o){let n=t.entityTypeLabel.trim()||"record",a=t.title.trim()||n,l=t.detail?.trim();return {prompt:`I'm looking at ${Xe(e)}'s ${n.toLowerCase()}: ${a}${l?`, ${l}`:""}. What does this mean, and what should I keep on top of for ${Xe(e)}?`,entityRef:{type:Tf[r]??r,id:o,payload:{kind:n,title:a,...l?{detail:l}:{}}}}}i(bs,"buildEntityRowAskPrompt");function Uc(e,t,r){let o=t.filter(l=>l.label.trim()),n={type:"upcoming_care",id:r};if(o.length===0)return {prompt:`I'm looking at ${Xe(e)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${Xe(e)} be on?`,entityRef:n};let a=[...o].sort((l,c)=>(l.tone==="overdue"?0:1)-(c.tone==="overdue"?0:1)).slice(0,4).map(l=>l.relativeText.trim()?`${l.label.trim()} (${l.relativeText.trim().toLowerCase()})`:l.label.trim());return {prompt:`I'm looking at ${Xe(e)}'s upcoming care: ${a.join(", ")}. What should I prioritize for ${Xe(e)}, and how do I stay on top of these?`,entityRef:n}}i(Uc,"buildUpcomingCareAskPrompt");function jc(e,t,r){let o=[`I'm looking at ${Xe(e)}'s physical exam${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`],n=t.abnormal.filter(a=>a.system.trim());return n.length>0?(o.push(`Abnormal: ${n.slice(0,6).map(a=>`${a.system.trim()}: ${a.finding.trim()}`).join("; ")}.`),o.push(`What do these findings mean, and what should I follow up on for ${Xe(e)}?`)):o.push(`Everything examined came back normal. What does this tell me about ${Xe(e)}'s health?`),{prompt:o.join(" "),entityRef:{type:"physical_exam",id:r}}}i(jc,"buildPhysicalExamAskPrompt");function $c(e,t,r){let o=[`I'm looking at ${Xe(e)}'s visit notes${t.observedOn?.trim()?` from ${t.observedOn.trim()}`:""}.`];for(let n of t.sections.filter(a=>a.text.trim()).slice(0,3))o.push(`${n.label.trim()||"Note"}: ${Nc(n.text)}`);return o.push(`Can you summarize what happened and what I should follow up on for ${Xe(e)}?`),{prompt:o.join(" "),entityRef:{type:"visit",id:r}}}i($c,"buildVisitNoteAskPrompt");function Wc(e,t,r){let o=t.scopeLabel.trim()||"a detail",n=t.candidates.filter(l=>l.value.trim()),a=n.slice(0,3).map(l=>`"${l.value.trim()}"${l.clinicName?.trim()?` (${l.clinicName.trim()})`:""}`).join(" vs ");return {prompt:`Two of ${Xe(e)}'s documents disagree on ${o}: ${a}. Which is likely correct, and what should I ask my vet?`,entityRef:{type:"conflict",id:r,payload:{field:o,severity:t.severity,values:n.map(l=>l.value.trim()).join(" | ")}}}}i(Wc,"buildConflictAskPrompt");function In(e){return e!==void 0}i(In,"canUploadRecords");function hs(e,t){return e??t?.version??""}i(hs,"resolveConsentVersion");function Hr(e,t){return hs(e,t).length>0}i(Hr,"canGrantConsent");function _r(e,t){return e.denialReason==="consent_required"?t?{kind:"consent_required"}:{kind:"consent_unavailable"}:e.denialReason==="pet_not_found"?{kind:"pet_not_found",error:N("petNotFound",{retryable:false})}:e.denialReason==="entitlement"?{kind:"error",error:N("accessDenied")}:e.denialReason==="session_required"?{kind:"session_required"}:e.withheld?{kind:"withheld"}:e.error===null?{kind:"withheld"}:{kind:"error",error:e.error}}i(_r,"selectErrorView");function So(e){let t=e.clinicName?.trim()??"";return t.length>0?t:e.source==="owner_provided"?Gc.ownerUpload:Gc.clinicRequest}i(So,"selectRequestTitle");var Gc=Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function Rs(e){let t=[...e].sort((r,o)=>r.updatedAt!==o.updatedAt?r.updatedAt>o.updatedAt?-1:1:r.createdAt!==o.createdAt?r.createdAt>o.createdAt?-1:1:0);return Object.freeze(t)}i(Rs,"selectRequestList");function Ur(e){let t=e.actionNeededLabel?.trim()??"";return t.length>0?t:e.statusLabel}i(Ur,"selectPrimaryLabel");function ko(e){if(e.showClinicPhone!==true)return null;let t=e.clinicPhone?.trim()??"";return t.length===0?null:{phone:t,dial:`tel:${t.replace(/[^+\d]/g,"")}`,clinicName:e.clinicName?.trim()||null}}i(ko,"selectClinicCall");function Yc(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(Yc,"selectRequestStatusTone");var ht=200,Qc=16;function Pf(e,t){let r=e.inRangeCount+e.outOfRangeCount+e.unknownCount;if(!Number.isFinite(r)||r<=0)return [];let o=[{key:"in_range",color:t.inRange,count:e.inRangeCount},{key:"out_of_range",color:t.outOfRange,count:e.outOfRangeCount},{key:"unknown",color:t.unknown,count:e.unknownCount}],n=0,a=[];for(let l of o){if(!(l.count>0))continue;let c=l.count/r*360;if(!Number.isFinite(c))return null;a.push({key:l.key,color:l.color,startDeg:n,sweepDeg:c}),n+=c;}return a}i(Pf,"buildRingSegments");function Jc({summary:e,onAsk:t,testID:r}){let o=Df(),n=V(),{totalMarkers:a,inRangeCount:l,outOfRangeCount:c,unknownCount:s}=e,d=useMemo(()=>Pf(e,{inRange:n.color.success,outOfRange:n.color.danger,unknown:n.color.text.muted}),[e,n]),u=d!==null&&d.length>0;return jsxs(View,{style:o.card,accessibilityRole:"summary",testID:r,children:[jsx(m,{style:o.title,children:jt.title}),jsx(View,{style:o.ringRow,accessible:true,accessibilityRole:"image",accessibilityLabel:jt.a11y(a,l,c,s),children:jsxs(View,{style:o.ringWrap,children:[jsx(View,{style:o.track}),d===null?null:d.map(p=>jsx(If,{segment:p,styles:o},p.key)),jsxs(View,{style:o.center,pointerEvents:"none",children:[jsx(m,{style:o.centerCount,children:a}),jsx(m,{style:o.centerLabel,children:a===1?jt.marker:jt.markers})]})]})}),u||d===null?jsxs(View,{style:o.badges,children:[jsx(vs,{count:c,label:jt.outOfRange,color:n.color.danger,styles:o}),jsx(vs,{count:l,label:jt.inRange,color:n.color.success,styles:o}),s>0?jsx(vs,{count:s,label:jt.noRange,color:n.color.text.muted,styles:o}):null]}):null,jsx(m,{style:o.subtitle,children:jt.subtitle}),t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:jt.askA11y,style:o.ask,testID:"marker-summary-ask",children:jsx(m,{style:o.askLabel,children:jt.ask})}):null]})}i(Jc,"MarkerSummaryCard");function If({segment:e,styles:t}){return (e.sweepDeg<=180?[{start:e.startDeg,sweep:e.sweepDeg}]:[{start:e.startDeg,sweep:180},{start:e.startDeg+180,sweep:e.sweepDeg-180}]).map((o,n)=>jsx(View,{style:[t.piece,{transform:[{rotate:`${o.start}deg`}]}],pointerEvents:"none",testID:`marker-ring-${e.key}`,children:jsx(View,{style:t.window,children:jsx(View,{style:[t.halfRing,{borderTopColor:e.color,borderRightColor:e.color,transform:[{rotate:`${o.sweep-135}deg`}]}]})})},n))}i(If,"Arc");function vs({count:e,label:t,color:r,styles:o}){return jsx(View,{style:[o.badge,{borderColor:r}],children:jsx(m,{style:[o.badgeText,{color:r}],children:`${e} ${t}`})})}i(vs,"Badge");function Df(){let e=V();return useMemo(()=>Af(e),[e])}i(Df,"useStyles");function Af(e){let{color:t,space:r,radius:o,type:n,slots:a}=e,l=StyleSheet.hairlineWidth,c=at(a.recordCard);return StyleSheet.create({card:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:l,borderColor:t.brandBorder,padding:r.lg-1,gap:r.sm+r.xs/2,...rt(a.recordCard,l)},title:{...k(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.brandInk,letterSpacing:n.letterSpacing.headerBrand,...c},ringRow:{alignItems:"center"},ringWrap:{width:ht,height:ht,alignItems:"center",justifyContent:"center"},track:{position:"absolute",width:ht,height:ht,borderRadius:ht/2,borderWidth:Qc,borderColor:t.surfaceSubtle},piece:{position:"absolute",width:ht,height:ht},window:{position:"absolute",left:ht/2,top:0,width:ht/2,height:ht,overflow:"hidden"},halfRing:{position:"absolute",left:-ht/2,top:0,width:ht,height:ht,borderRadius:ht/2,borderWidth:Qc,borderBottomColor:"transparent",borderLeftColor:"transparent"},center:{position:"absolute",alignItems:"center",justifyContent:"center"},centerCount:{...k(e,"medium"),fontSize:n.size.verdict*2,lineHeight:n.size.verdict*2+r.xs,color:t.text.primary,textAlign:"center",...c},centerLabel:{...k(e,"medium"),fontSize:n.size.heading-1,lineHeight:n.size.heading+r.xs/2,color:t.text.primary,textAlign:"center",...c},badges:{flexDirection:"row",flexWrap:"wrap",justifyContent:"center",gap:r.sm},badge:{borderWidth:1,borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs},badgeText:{...k(e,"mono"),fontSize:n.size.nano,lineHeight:n.size.tiny,letterSpacing:n.letterSpacing.headerBrand/2,textTransform:"uppercase"},subtitle:{...k(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.relaxed),color:t.text.primary,...c},ask:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:r.sm,minHeight:r.xxl+r.sm,marginTop:r.xs/2,paddingHorizontal:r.lg,borderRadius:o.pill,borderWidth:l,borderColor:t.borderRingCream,backgroundColor:t.surface},askLabel:{...k(e,"bold"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.primary,letterSpacing:n.letterSpacing.tight}})}i(Af,"makeStyles");function Of(e){return e.value!==null&&Number.isFinite(e.value)}i(Of,"numeric");function Zc(e){let t=e.points.filter(Of);if(t.length===0)return null;let r=e.points[e.points.length-1]??null,o=r?.refLow??null,n=r?.refHigh??null,a=t.map(g=>g.value),l=Math.min(...a,...o!==null?[o]:[],...n!==null?[n]:[]),c=Math.max(...a,...o!==null?[o]:[],...n!==null?[n]:[]);l===c&&(l-=1,c+=1);let s=(c-l)*.18,d=l-s,u=c+s,p=u-d,f=i(g=>(u-g)/p*100,"y"),b=6,R=t.length,v=t.map((g,y)=>({index:y,xPct:R<=1?50:b+y/(R-1)*(100-2*b),yPct:f(g.value),status:g.status,point:g})),w=o!==null||n!==null?{topPct:n!==null?f(n):0,bottomPct:o!==null?f(o):100}:null;return {points:v,band:w,firstDate:t[0]?.at??null,lastDate:t[t.length-1]?.at??null}}i(Zc,"buildMarkerChart");var qf=416,zf=140;function _o(e){return `${e}%`}i(_o,"pct");function Ff({marker:e,width:t,onPointPress:r,onAsk:o}){let n=ws(),a=ue(),l=rr(e.latest?.status??null),c=xo(e.latest?.status??null),s=Kr(e.trajectory,e.points.length),d=useMemo(()=>Zc(e),[e]),u=e.latest?kt(e.latest.value,e.unit,e.latest.qualitativeResult):null;return jsx(View,{style:[n.page,t!==void 0?{width:t}:null],testID:`marker-card-${e.markerId}`,children:jsxs(View,{style:n.card,children:[jsxs(View,{style:n.headerRow,children:[jsxs(View,{style:n.nameColumn,children:[jsx(m,{style:n.markerName,numberOfLines:2,children:e.name}),e.unit?jsx(m,{style:n.unit,children:e.unit}):null]}),jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:cr.status(l.label),children:jsx(St,{label:l.label,tone:c})})]}),e.latest&&u!==null?jsxs(View,{style:n.latestRow,children:[jsx(m,{style:[n.latestValue,l.outOfRange?n.latestValueDanger:null],accessibilityLabel:cr.latestA11y(u,l.label,Y(e.latest.at)),children:u}),jsx(m,{style:n.latestDate,children:Y(e.latest.at)})]}):null,s?jsx(m,{style:n.trajectory,accessibilityRole:"text",children:s}):null,d!==null?jsxs(View,{style:n.chartWrap,children:[jsxs(View,{style:n.plot,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[d.band?jsx(View,{style:[n.band,{top:_o(d.band.topPct),height:_o(Math.max(0,d.band.bottomPct-d.band.topPct))}]}):null,d.points.map(p=>jsx(Pressable,{onPress:()=>r(e,p.point),hitSlop:12,style:[n.point,p.status==="above"||p.status==="below"?n.pointDanger:null,{left:_o(p.xPct),top:_o(p.yPct)}],testID:`marker-point-${e.markerId}-${p.index}`},p.index))]}),jsx(View,{style:n.a11yTable,accessibilityRole:"summary",accessibilityLabel:cr.readingsA11y(e.name),children:e.points.map((p,f)=>jsx(View,{accessibilityRole:"text",accessibilityLabel:Fc(e,p)},f))}),jsx(m,{style:e.points.length===1?n.singleHint:n.tapHint,children:e.points.length===1?cr.singleHint:cr.tapHint})]}):jsx(View,{style:n.emptyBody,accessibilityRole:"text",children:jsx(m,{style:n.emptyText,children:cr.empty})}),o?jsx(Pressable,{onPress:()=>o(e),accessibilityRole:"button",accessibilityLabel:cr.askA11y(e.name),style:[a.pill,a.pillAsk],testID:`marker-ask-${e.markerId}`,children:jsx(m,{style:a.pillAskLabel,children:cr.ask})}):null]})})}i(Ff,"MarkerTrendCard");function nd({markers:e,onPointPress:t,onAsk:r}){let o=ws(),[n,a]=useState(0),[l,c]=useState(0),s=i(p=>a(p.nativeEvent.layout.width),"onLayout"),d=i(p=>{if(n<=0)return;let f=Math.round(p.nativeEvent.contentOffset.x/n);c(Math.max(0,Math.min(f,e.length-1)));},"onMomentumEnd"),u=e[l]??null;return jsxs(View,{style:o.carousel,onLayout:s,testID:"marker-carousel",children:[jsx(ScrollView,{horizontal:true,pagingEnabled:true,showsHorizontalScrollIndicator:false,onMomentumScrollEnd:d,snapToAlignment:"start",children:e.map(p=>jsx(Ff,{marker:p,width:n>0?n:void 0,onPointPress:t,onAsk:r},p.markerId))}),jsxs(View,{style:o.footer,accessible:true,accessibilityRole:"adjustable",accessibilityLabel:Ni.a11y(u?.name??null,l,e.length),children:[jsx(View,{style:o.dots,children:e.map((p,f)=>jsx(View,{style:[o.dot,f===l?o.dotActive:null]},p.markerId))}),jsx(m,{style:o.counter,children:Ni.counter(l,e.length)})]})]})}i(nd,"MarkerTrendCarousel");function od({marker:e,point:t,onClose:r,onAsk:o}){let n=ws(),a=ue();if(e===null||t===null)return null;let l=i((c,s)=>jsxs(View,{style:n.detailRow,accessible:true,accessibilityRole:"text",accessibilityLabel:`${c}: ${s}`,children:[jsx(m,{style:n.detailLabel,children:c}),jsx(m,{style:n.detailValue,children:s})]},c),"row");return jsxs(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:r,children:[jsx(Pressable,{style:n.backdrop,onPress:r,accessibilityRole:"button",accessibilityLabel:Et.close}),jsxs(View,{style:n.sheet,accessibilityViewIsModal:true,testID:"marker-provenance-sheet",children:[jsx(View,{style:n.handle}),jsxs(View,{style:n.sheetHeader,children:[jsx(m,{style:n.sheetTitle,accessibilityRole:"header",children:Et.title}),jsx(Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Et.close,hitSlop:10,style:n.closeButton,testID:"marker-provenance-close",children:jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsxs(View,{style:n.sheetBody,children:[jsxs(View,{style:n.valueRow,children:[jsx(m,{style:n.sheetName,children:e.name}),jsx(m,{style:n.sheetValue,children:kt(t.value,e.unit,t.qualitativeResult)})]}),t.reviewed?jsx(View,{style:n.reviewed,accessibilityRole:"text",children:jsx(m,{style:n.reviewedText,children:Et.reviewed})}):null,l(Et.collected,Y(t.at)),t.sourceClinic?l(Et.clinic,t.sourceClinic):null,l(Et.referenceRange,t.refLow!==null||t.refHigh!==null?Co(t,e.unit):Et.noRange),t.docId?l(Et.sourceDocument,t.docId):null,t.reviewed?null:jsx(m,{style:n.unverified,accessibilityRole:"text",children:Et.unverified}),o?jsx(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:Et.askA11y,style:[a.pill,a.pillAsk],testID:"marker-provenance-ask",children:jsx(m,{style:a.pillAskLabel,children:Et.ask})}):null]})]})]})}i(od,"MarkerProvenanceSheet");function ws(){let e=V();return useMemo(()=>Nf(e),[e])}i(ws,"useStyles");function Nf(e){let{color:t,space:r,radius:o,type:n,slots:a}=e,l=StyleSheet.hairlineWidth,c=r.md,s=i((f,b,R,v="regular")=>({...k(e,v),fontSize:f,lineHeight:Math.round(f*b),color:R}),"text"),d=at(a.recordCard),u=s(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold"),p=s(n.size.verdict+r.xs,n.lineHeight.tight,t.text.primary,"bold");return StyleSheet.create({page:{paddingHorizontal:r.sm},card:{borderRadius:o.lg-r.xs/2,borderWidth:l,borderColor:t.brandBorder,backgroundColor:t.surface,padding:r.lg,gap:r.md,...rt(a.recordCard,l)},headerRow:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm+r.xs/2},nameColumn:{flex:1,gap:r.xs/2},markerName:{...u,...d},sheetName:u,unit:{...k(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted,...d},latestRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},latestValue:{...p,...d},sheetValue:p,latestValueDanger:{color:t.danger},latestDate:{...s(n.size.caption,n.lineHeight.normal,t.text.muted),...d},trajectory:{...s(n.size.bodyTight,n.lineHeight.normal,t.text.muted),...d},chartWrap:{gap:r.sm},plot:{height:zf,borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:l,borderColor:t.borderHairlineGreen,overflow:"hidden"},band:{position:"absolute",left:0,right:0,backgroundColor:t.badgeBgPositive},point:{position:"absolute",width:c,height:c,borderRadius:c/2,marginLeft:-c/2,marginTop:-c/2,backgroundColor:t.brand,borderWidth:2,borderColor:t.surface},pointDanger:{backgroundColor:t.danger},a11yTable:{width:1,height:1,overflow:"hidden",position:"absolute"},tapHint:{...s(n.size.tiny,n.lineHeight.normal,t.text.placeholder),textAlign:"center",...d},singleHint:{...s(n.size.caption,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},emptyBody:{alignItems:"center",justifyContent:"center",gap:r.sm,paddingVertical:r.xxl+r.xs},emptyText:{...s(n.size.bodyTight,n.lineHeight.normal,t.text.muted),textAlign:"center",...d},carousel:{height:qf},footer:{alignItems:"center",gap:r.sm,paddingTop:r.md},dots:{flexDirection:"row",gap:r.xs+r.xs/2},dot:{width:r.xs+r.xs/2,height:r.xs+r.xs/2,borderRadius:r.xs-1,backgroundColor:t.borderHairlineGreen},dotActive:{width:r.lg+r.xs/2,backgroundColor:t.brand},counter:{...k(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,letterSpacing:n.letterSpacing.eyebrow/3,color:t.text.muted},backdrop:{flex:1,backgroundColor:so},sheet:{backgroundColor:t.surfaceCream,borderTopLeftRadius:o.xl-r.xs,borderTopRightRadius:o.xl-r.xs,paddingHorizontal:r.lg+r.xs,paddingTop:r.sm,paddingBottom:r.xxl+r.xs,maxHeight:"80%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},sheetHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},sheetTitle:{flex:1,...s(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},closeButton:{width:r.xxl+r.md,height:r.xxl+r.md,alignItems:"center",justifyContent:"center"},closeGlyph:{...s(n.size.verdict,n.lineHeight.tight,t.text.primary)},sheetBody:{gap:r.md},valueRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:r.md},reviewed:{alignSelf:"flex-start",borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs,backgroundColor:t.badgeBgPositive},reviewedText:{...s(n.size.tiny,n.lineHeight.normal,t.success,"medium")},detailRow:{gap:r.xs/2},detailLabel:{...s(n.size.caption,n.lineHeight.normal,t.text.muted,"medium")},detailValue:s(n.size.body,n.lineHeight.normal,t.text.primary),unverified:s(n.size.caption,n.lineHeight.normal,t.text.muted)})}i(Nf,"makeStyles");var K=Object.freeze({title:"Full medical record",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:i(e=>`${e} ${e===1?"document":"documents"} from your vet ${e===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,"inReview"),needsAttention:"Needs your attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:i(e=>`${e} ${e===1?"document":"documents"} on file`,"documentsOnFile"),inReviewChip:i(e=>`${e} in review`,"inReviewChip"),beingVerified:i(e=>`${e} being verified`,"beingVerified"),beingVerifiedA11y:i(e=>`${e} ${e===1?"fact is":"facts are"} being verified`,"beingVerifiedA11y"),pendingReview:"Pending review: ",dateRange:i((e,t)=>`${Y(e)} to ${Y(t)}`,"dateRange"),documents:"Documents",uploadedDocument:ge.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:ge.labResults,visits:ge.visits,physicalExams:ge.physicalExams,visitNotes:ge.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 ${Y(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"})}),id=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 jr(e){return Object.prototype.hasOwnProperty.call(id,e)?id[e]:dr(e)}i(jr,"entityTypeLabel");var sd=Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function ad(e){let t=sd.filter(o=>e.includes(o)),r=e.filter(o=>!sd.includes(o));return [...t,...r]}i(ad,"orderEntityTypes");function Po(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(Po,"conflictSeverityMeta");function An(e,t){if(!e)return null;let r=Date.parse(e);if(Number.isNaN(r))return null;let o=r<t-1440*60*1e3;return {label:o?K.overdue:K.due(Y(e)),overdue:o}}i(An,"dueBadge");function ld(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(ld,"formatReferenceBand");var ct=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 cd(e,t){return sr(e)?t==="remove"?"Records access for this pet is off, so this detail cannot be removed.":"Records access for this pet is off, so this detail cannot be changed.":hc(e)?t==="remove"?"A clinician already reviewed this detail, so it can't be removed here.":"A clinician already reviewed this detail, so it can't be changed here.":t==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}i(cd,"factEditErrorMessage");var Mf=Object.freeze({edits:Object.freeze({}),removed:Object.freeze([])});function xs(e,t){if(Object.keys(t.edits).length===0&&t.removed.length===0)return e;let r=[];for(let o of e){let n=o.canonicalKey??null;if(n!==null&&t.removed.includes(n))continue;let a=n!==null?t.edits[n]:void 0;r.push(a===void 0?o:Object.freeze({...o,value:a}));}return Object.freeze(r)}i(xs,"applyFactOverlay");function Do(e){return typeof e.canonicalKey=="string"&&e.canonicalKey.length>0}i(Do,"isFactEditable");function Bf(){return `records-fact-${Date.now().toString(36)}`}i(Bf,"defaultFactKey");function Cs(e,t={}){let r=mr(),{userRef:o}=ke(),[n,a]=useState(Mf),[l,c]=useState(false),[s,d]=useState(null),u=useMemo(()=>({}),[r,e,o]),[p,f]=useState(null),b=useCallback(()=>f(u),[u]),R=o!==null&&p!==u,v=useRef(false),w=useRef(t.newIdempotencyKey);w.current=t.newIdempotencyKey;let g=useCallback(()=>(w.current??Bf)(),[]),y=useCallback((S,T,C)=>{if(c(false),!S.ok){if(T(),Tr(S.error)){b();return}d(cd(S.error,C));}},[b]),x=useCallback(async(S,T)=>{let C=S.canonicalKey??"",A=T.trim();if(v.current||C.length===0||A.length===0)return H(N("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let F=n;a(U=>({...U,edits:{...U.edits,[C]:A}}));let q=await r.editFact(e,{entityType:S.category,canonicalKey:C,correctedFields:ls(S.value,A),idempotencyKey:g()});return v.current=false,y(q,()=>a(F),"edit"),q},[r,e,n,y,g]),h=useCallback(async S=>{let T=S.canonicalKey??"";if(v.current||T.length===0)return H(N("validationFailed",{retryable:false}));v.current=true,c(true),d(null);let C=n;a(F=>({...F,removed:[...F.removed,T]}));let A=await r.removeFact(e,{entityType:S.category,canonicalKey:T,idempotencyKey:g()});return v.current=false,y(A,()=>a(C),"remove"),A},[r,e,n,y,g]),I=useCallback(()=>d(null),[]);return useMemo(()=>({overlay:n,busy:l,error:s,available:R,edit:x,remove:h,clearError:I}),[n,l,s,R,x,h,I])}i(Cs,"useRecordFactEdit");var Es=Object.freeze(["vaccination","parasite_prevention"]),Ao="Undated",Hf=Object.freeze({given:"Given",prevention:"Prevention",overdue:"Overdue",noDate:"No date"}),pd=Object.freeze({given:"positive",prevention:"neutral",overdue:"critical",noDate:"neutral"});function Oo(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(Oo,"toMillis");function Uf(e){let t=e.status?.toLowerCase()??"";return /overdue|lapsed|expired/.test(t)}i(Uf,"isLapsed");function jf(e){return e.category==="parasite_prevention"?"prevention":Oo(e.observedAt)===null?"noDate":Uf(e)?"overdue":"given"}i(jf,"vaccineTone");function $f(e){let t=Oo(e);return t===null?Ao:String(new Date(t).getUTCFullYear())}i($f,"yearOf");function Wf(e){let t=jf(e),r=[e.value!==null&&e.value.length>0?e.value:null,e.observedAt!==null?Y(e.observedAt):null].filter(o=>o!==null&&o.length>0);return {key:e.key,name:e.label,detail:r.length>0?r.join(" \xB7 "):null,statusLabel:Hf[t],tone:t,entity:e}}i(Wf,"buildRow");function md(e){let t=new Map;for(let o of e){if(!Es.includes(o.category))continue;let n=$f(o.observedAt),a=t.get(n),l={row:Wf(o),at:o.observedAt};a===void 0?t.set(n,[l]):a.push(l);}let r=[...t.keys()].sort((o,n)=>o===Ao?1:n===Ao?-1:Number(n)-Number(o));return Object.freeze(r.map(o=>{let n=t.get(o)??[],a=o===Ao?n:[...n].sort((l,c)=>(Oo(c.at)??0)-(Oo(l.at)??0));return Object.freeze({year:o,items:Object.freeze(a.map(l=>l.row))})}))}i(md,"selectVaccineGroups");var Lo=Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});function Ss({entity:e,factEdit:t,children:r}){let o=yd(),[n,a]=useState(false),l=e.label.trim()||ct.detail;return jsxs(View,{style:o.row,children:[jsx(View,{style:o.main,children:r}),jsx(Pressable,{onPress:()=>a(true),accessibilityRole:"button",accessibilityLabel:ct.editA11y(l),hitSlop:6,style:o.editButton,testID:`fact-edit-open-${e.canonicalKey??e.key}`,children:jsx(View,{style:o.pencil,accessibilityElementsHidden:true,importantForAccessibility:"no"})}),n?jsx(Jf,{entity:e,title:l,factEdit:t,onClose:()=>a(false)}):null]})}i(Ss,"FactEditAffordance");function Jf({entity:e,title:t,factEdit:r,onClose:o}){let n=yd(),a=ue(),l=V(),[c,s]=useState(e.value??""),[d,u]=useState(null),[p,f]=useState(false);useEffect(()=>{r.clearError();},[r]);let b=c.trim().length>0&&c.trim()!==(e.value??"").trim(),R=d??r.error,v=r.busy,w=i(()=>{if(!b){u(ct.noChange);return}u(null),r.edit(e,c).then(y=>{y.ok&&o();});},"submitEdit"),g=i(()=>{u(null),r.remove(e).then(y=>{y.ok?o():f(false);});},"submitRemove");return jsx(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:o,children:jsxs(KeyboardAvoidingView,{behavior:"padding",style:n.backdrop,children:[jsx(Pressable,{style:Lo,accessibilityRole:"button",accessibilityLabel:ct.closeEditorA11y,onPress:o}),jsxs(View,{style:n.sheet,accessibilityViewIsModal:true,testID:"fact-edit-sheet",children:[jsx(View,{style:n.handle}),jsxs(View,{style:n.header,children:[jsxs(View,{style:n.headerText,children:[jsx(m,{style:n.title,accessibilityRole:"header",children:ct.title(t)}),jsx(m,{style:[n.helper,R?n.helperError:null],accessibilityLiveRegion:"polite",children:R??ct.helper})]}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:ct.close,onPress:o,hitSlop:12,style:n.closeButton,testID:"fact-edit-close",children:jsx(m,{style:n.closeGlyph,children:"\xD7"})})]}),jsx(m,{style:a.fieldLabel,children:e.label}),jsx(He,{accessibilityLabel:e.label,style:a.field,value:c,onChangeText:y=>{s(y),u(null);},editable:!v,maxLength:512,placeholderTextColor:l.color.text.placeholder,testID:"fact-edit-field"}),p?jsxs(View,{style:n.confirmBlock,testID:"fact-edit-confirm-remove",children:[jsx(m,{style:n.confirmText,children:ct.confirmRemove}),jsxs(View,{style:n.confirmRow,children:[jsx(J,{label:v?ct.removing:ct.removeConfirm,kind:"danger",busy:v,onPress:g,style:n.confirmButton,testID:"fact-edit-remove-confirm"}),jsx(J,{label:ct.keep,kind:"outline",disabled:v,onPress:()=>f(false),style:n.confirmButton,testID:"fact-edit-remove-cancel"})]})]}):jsxs(View,{style:n.actions,children:[jsx(J,{label:v?ct.saving:ct.save,busy:v,disabled:!b,onPress:w,testID:"fact-edit-save"}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:ct.removeA11y(t),disabled:v,onPress:()=>{u(null),f(true);},style:[n.removeButton,v?n.removeDisabled:null],testID:"fact-edit-remove",children:jsx(m,{style:n.removeText,children:ct.remove})})]})]})]})})}i(Jf,"FactEditSheet");function yd(){let e=V();return useMemo(()=>Zf(e),[e])}i(yd,"useStyles");function Zf(e){let{color:t,space:r,radius:o,type:n}=e,a=r.xxl+r.md,l=e.brightness==="dark"?t.errorRed:t.danger,c=i((s,d,u,p="regular")=>({...k(e,p),fontSize:s,lineHeight:Math.round(s*d),color:u}),"text");return StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:r.sm},main:{flex:1},editButton:{width:a,height:a,alignItems:"center",justifyContent:"center"},pencil:{width:r.md+r.xs/2,height:r.xs/2,backgroundColor:t.brandInk,borderRadius:o.pill,transform:[{rotate:"-45deg"}]},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:so},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),helperError:{color:l},closeButton:{width:a,height:a,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),actions:{gap:r.sm},removeButton:{minHeight:a,alignItems:"center",justifyContent:"center"},removeDisabled:{opacity:.5},removeText:{...c(n.size.bodyTight,n.lineHeight.snug,t.danger,"bold")},confirmBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.badgeBgCritical},confirmText:c(n.size.bodyTight,n.lineHeight.normal,t.text.primary),confirmRow:{flexDirection:"row",gap:r.sm},confirmButton:{flex:1}})}i(Zf,"makeStyles");function Fo({record:e,depth:t,petName:r,showLabs:o=true,onNavigate:n,onAsk:a,factEdit:l,nowMs:c}){let s=ue(),d=eg(),u=c??Date.now(),p=useMemo(()=>l?xs(e.entities,l.overlay):e.entities,[e.entities,l]),f=useMemo(()=>{let g=[],y=new Map;for(let x of p){let h=x.category.trim();if(h.length===0||Es.includes(h))continue;let I=y.get(h);I===void 0?(g.push(h),y.set(h,[x])):I.push(x);}return {order:ad(g),groups:y}},[p]),b=useMemo(()=>md(p),[p]),R=Object.values(e.documents),v=i((g,y,x)=>a?jsx(Pressable,{onPress:()=>{let h=g();a(h.prompt,h.entityRef);},accessibilityRole:"button",accessibilityLabel:y,style:[s.pill,s.pillAsk,d.ask],testID:x,children:jsx(m,{style:s.pillAskLabel,children:y})}):null,"ask"),w=l!==void 0&&l.available;return jsxs(Fragment,{children:[jsxs(View,{style:d.sections,children:[t&&t.conflicts.length>0?jsxs(View,{style:s.section,testID:"record-section-conflicts",children:[jsx(Dt,{title:K.needsAttention,count:t.conflicts.length}),[...t.conflicts].sort((g,y)=>Po(g.severity).rank-Po(y.severity).rank).map(g=>{let y=Po(g.severity),x=dr(g.field??g.entityType);return jsxs(View,{style:[d.conflictCard,{borderColor:s.chipTones[y.tone].fg.color}],accessibilityRole:"summary",children:[jsxs(View,{style:d.conflictHead,children:[jsx(m,{style:d.conflictTitle,children:y.label}),jsx(St,{label:x,tone:y.tone})]}),jsx(m,{style:s.rowDetail,children:K.conflictSub}),g.candidates.map((h,I)=>jsxs(View,{style:d.candidate,children:[jsx(m,{style:s.rowTitle,children:h.value}),jsx(m,{style:s.rowMuted,children:[h.docId?e.documents[h.docId]?.title??K.uploadedDocument:K.uploadedDocument,h.collectedAt?Y(h.collectedAt):null].filter(Boolean).join(" \xB7 ")})]},I)),v(()=>Wc(r,{scopeLabel:x,severity:g.severity,candidates:g.candidates.map(h=>({value:h.value,clinicName:h.docId?e.documents[h.docId]?.title??null:null}))},g.conflictId),K.askConflict,`records-ask-conflict-${g.conflictId}`)]},g.conflictId)})]}):null,t?.completeness?jsxs(View,{style:s.section,testID:"record-section-completeness",children:[jsx(Dt,{title:K.whatsOnFile}),jsxs(View,{style:s.card,children:[jsx(View,{style:d.coverageRow,children:[[K.coverage.labs,t.completeness.hasLabHistory],[K.coverage.vaccines,t.completeness.hasVaccinationHistory],[K.coverage.weight,t.completeness.hasWeightHistory],[K.coverage.vitals,t.completeness.hasVitalsHistory],[K.coverage.exams,t.completeness.hasPhysicalExamHistory],[K.coverage.procedures,t.completeness.hasProcedureHistory],[K.coverage.genetics,t.completeness.hasGeneticHistory],[K.coverage.parasite,t.completeness.hasParasitePreventionHistory],[K.coverage.reproductive,t.completeness.hasReproductiveHistory]].map(([g,y])=>jsx(View,{style:[d.coveragePill,y?s.chipTones.positive.bg:s.chipTones.neutral.bg],accessible:true,accessibilityRole:"text",accessibilityLabel:`${g}: ${y?K.onFile:K.noneOnFile}`,children:jsx(m,{style:[d.coverageText,y?s.chipTones.positive.fg:{color:s.rowMuted.color}],children:g})},g))}),jsxs(View,{style:d.metaRow,children:[jsx(m,{style:d.metaText,children:K.documentsOnFile(t.completeness.documentsIngested)}),t.completeness.documentsInReview>0?jsx(St,{label:K.inReviewChip(t.completeness.documentsInReview),tone:"warning"}):null,ks(t.completeness.heldTotal,t.completeness.entitiesPendingReview)>0?jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:K.beingVerifiedA11y(ks(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),children:jsx(St,{label:K.beingVerified(ks(t.completeness.heldTotal,t.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),t.completeness.earliestRecordAt||t.completeness.latestRecordAt?jsx(View,{style:d.metaRow,children:jsx(m,{style:d.metaText,children:K.dateRange(t.completeness.earliestRecordAt,t.completeness.latestRecordAt)})}):null,Object.entries(t.completeness.entitiesPendingReview).filter(([,g])=>g>0).length>0?jsxs(m,{style:d.pendingText,children:[K.pendingReview,Object.entries(t.completeness.entitiesPendingReview).filter(([,g])=>g>0).map(([g,y])=>`${jr(g)} (${y})`).join(", ")]}):null]})]}):null,R.length>0?jsxs(View,{style:s.section,testID:"record-section-documents",children:[jsx(Dt,{title:K.documents,count:R.length}),jsx(View,{style:s.card,children:R.map((g,y)=>{let x=g.title?.trim()||K.uploadedDocument,h=g.receivedAt?Y(g.receivedAt):null,I=jsxs(Fragment,{children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:x}),h?jsx(m,{style:s.rowDetail,children:h}):null]}),n?jsx(tr,{}):null]});return n?jsx(Pressable,{onPress:()=>n({name:"contributions",docId:g.docId}),accessibilityRole:"button",accessibilityLabel:K.documentRowA11y(x),style:[s.row,y>0?s.rowDivider:null],testID:`records-document-row-${g.docId}`,children:I},g.docId):jsx(View,{style:[s.row,y>0?s.rowDivider:null],children:I},g.docId)})})]}):null,e.identity.length>0?jsxs(View,{style:s.section,testID:"record-section-identity",children:[jsx(Dt,{title:K.identity}),jsx(View,{style:s.card,children:e.identity.map((g,y)=>jsxs(View,{style:[s.row,y>0?s.rowDivider:null],children:[jsx(m,{style:d.identityLabel,children:g.label}),jsx(m,{style:d.identityValue,children:g.value})]},`${y}:${g.label}`))})]}):null,e.forwardLooking.length>0?jsxs(View,{style:s.section,testID:"record-section-upcoming",children:[jsx(Dt,{title:K.upcomingCare,count:e.forwardLooking.length}),jsx(View,{style:s.card,children:e.forwardLooking.map((g,y)=>{let x=An(g.dueAt,u);return jsxs(View,{style:[s.row,y>0?s.rowDivider:null],children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:g.title}),g.detail?jsx(m,{style:s.rowDetail,children:g.detail}):null]}),x?jsx(St,{label:x.label,tone:x.overdue?"critical":"info"}):null]},`${g.title}-${y}`)})}),v(()=>Uc(r,e.forwardLooking.map(g=>{let y=An(g.dueAt,u);return {label:g.title,relativeText:y?.label??"",tone:y?.overdue?"overdue":"upcoming"}}),e.petRef),K.askUpcomingCare,"records-ask-upcoming-care")]}):null,b.length>0?jsxs(View,{style:s.section,testID:"record-section-vaccination",children:[jsx(Dt,{title:jr("vaccination"),count:b.reduce((g,y)=>g+y.items.length,0)}),b.map(g=>jsxs(View,{style:d.vaccineGroup,testID:`records-vaccine-group-${g.year}`,children:[jsx(m,{style:d.vaccineYear,accessibilityRole:"header",children:g.year.toUpperCase()}),jsx(View,{style:s.card,children:g.items.map((y,x)=>{let h=jsxs(View,{style:[s.row,x>0?s.rowDivider:null],children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:y.name}),y.detail?jsx(m,{style:s.rowDetail,children:y.detail}):null,v(()=>bs(r,{entityTypeLabel:jr(y.entity.category),title:y.name,detail:y.detail},y.entity.category,y.key),K.askEverfur,`records-ask-entity-${y.key}`)]}),jsx(St,{label:y.statusLabel,tone:pd[y.tone]})]});return w&&Do(y.entity)&&l?jsx(Ss,{entity:y.entity,factEdit:l,children:h},y.key):jsx(View,{children:h},y.key)})})]},g.year))]}):null,f.order.map(g=>{let y=f.groups.get(g)??[];if(y.length===0)return null;let x=jr(g);return jsxs(View,{style:s.section,testID:`record-section-${g}`,children:[jsx(Dt,{title:x,count:y.length}),jsx(View,{style:s.card,children:y.map((h,I)=>{let T=[Yr(h.value,h.unit),h.observedAt?Y(h.observedAt):null].filter(A=>A&&A.length>0).join(" \xB7 "),C=jsxs(View,{style:[s.row,I>0?s.rowDivider:null],children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:h.label}),T?jsx(m,{style:s.rowDetail,children:T}):null,v(()=>bs(r,{entityTypeLabel:x,title:h.label,detail:T||null},g,h.key),K.askEverfur,`records-ask-entity-${h.key}`)]}),h.status?jsx(St,{label:dr(h.status)}):null]});return w&&Do(h)&&l?jsx(Ss,{entity:h,factEdit:l,children:C},h.key):jsx(View,{children:C},h.key)})})]},g)}),t&&t.physicalExams.length>0?jsxs(View,{style:s.section,testID:"record-section-exams",children:[jsx(Dt,{title:K.physicalExams,count:t.physicalExams.length}),t.physicalExams.map(g=>jsxs(View,{style:s.card,children:[jsx(m,{style:[s.rowTitle,d.cardTitle],accessibilityRole:"header",children:g.observedOn?Y(g.observedOn):ge.exam}),g.systems.map((y,x)=>{let h=y.findingStatus==="abnormal",I=h?ge.abnormal:y.findingStatus==="not_examined"?ge.notExamined:ge.normal;return jsxs(View,{style:[s.row,x>0?s.rowDivider:null],accessible:true,accessibilityRole:"text",accessibilityLabel:[qr(y.system),I,h?y.finding:null].filter(Boolean).join(", "),children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:qr(y.system)}),h&&y.finding?jsx(m,{style:s.rowDetail,children:y.finding}):null]}),jsx(St,{label:I,tone:h?"warning":y.findingStatus==="not_examined"?"neutral":"positive"})]},y.system)}),v(()=>jc(r,{observedOn:g.observedOn?Y(g.observedOn):null,abnormal:g.systems.filter(y=>y.findingStatus==="abnormal").map(y=>({system:qr(y.system),finding:y.finding??""}))},g.examId),K.askExam,`records-ask-exam-${g.examId}`)]},g.examId))]}):null,t&&t.clinicianNotes.length>0?jsxs(View,{style:s.section,testID:"record-section-notes",children:[jsx(Dt,{title:K.visitNotes,count:t.clinicianNotes.length}),t.clinicianNotes.map(g=>jsxs(View,{style:s.card,children:[jsx(m,{style:[s.rowTitle,d.cardTitle],accessibilityRole:"header",children:g.observedOn?Y(g.observedOn):ge.visitNote}),g.sections.map((y,x)=>jsxs(View,{style:[d.noteSection,x>0?s.rowDivider:null],children:[jsx(m,{style:d.noteLabel,children:Qr(y.section)}),jsx(m,{style:y.text?d.noteBody:d.noteBodyMuted,children:y.text||ge.notRecorded})]},`${y.section}:${x}`)),v(()=>$c(r,{observedOn:g.observedOn?Y(g.observedOn):null,sections:g.sections.map(y=>({label:Qr(y.section),text:y.text}))},g.noteId),K.askVisit,`records-ask-note-${g.noteId}`)]},g.noteId))]}):null,o&&t&&t.labResults.length>0?jsxs(View,{style:s.section,testID:"record-section-labs",children:[jsx(Dt,{title:K.labResults,count:t.labResults.length}),jsx(View,{style:s.card,children:t.labResults.map((g,y)=>{let x=rr(g.latest.status),h=Bi(g.latest.at,g.trajectory,g.points.length);return jsxs(View,{style:[s.row,y>0?s.rowDivider:null],children:[jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:g.name}),jsx(m,{style:s.rowValue,children:kt(g.latest.value,g.latest.unit,g.latest.qualitativeResult)}),h?jsx(m,{style:s.rowDetail,children:h}):null]}),jsx(St,{label:x.label,tone:xo(g.latest.status)})]},g.markerId)})})]}):null,t&&t.encounters.length>0?jsxs(View,{style:s.section,testID:"record-section-visits",children:[jsx(Dt,{title:K.visits,count:t.encounters.length}),jsx(View,{style:s.card,children:t.encounters.map((g,y)=>{let x=[g.date?Y(g.date):null,g.clinicName,g.veterinarian].filter(h=>h&&h!=="-").join(" \xB7 ");return jsx(View,{style:[s.row,y>0?s.rowDivider:null],children:jsxs(View,{style:s.rowMain,children:[jsx(m,{style:s.rowTitle,children:g.type?dr(g.type):ge.visit}),x?jsx(m,{style:s.rowDetail,children:x}):null]})},g.encounterId)})})]}):null]}),jsx(kr,{disclaimer:e.disclaimer})]})}i(Fo,"RecordSections");function ks(e,t){return e>0?e:Object.values(t).reduce((r,o)=>r+o,0)}i(ks,"heldCount");function eg(){let e=V();return useMemo(()=>tg(e),[e])}i(eg,"useLocalStyles");function tg(e){let{color:t,space:r,radius:o,type:n}=e,a=StyleSheet.hairlineWidth;return StyleSheet.create({sections:{gap:r.lg+r.xs},vaccineGroup:{gap:r.xs+1,marginBottom:r.sm},vaccineYear:{...k(e,"monoMedium"),fontSize:n.size.micro,lineHeight:n.size.micro+r.xs,color:t.text.muted,letterSpacing:n.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:r.xs+2},ask:{marginTop:r.lg},conflictCard:{borderRadius:o.md,borderWidth:1,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},conflictHead:{flexDirection:"row",alignItems:"center",gap:r.sm},conflictTitle:{flex:1,...k(e,"bold"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},candidate:{borderTopWidth:a,borderTopColor:t.borderHairlineGreen,paddingTop:r.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:r.sm,paddingVertical:r.md},coveragePill:{borderRadius:o.pill,paddingHorizontal:r.sm+r.xs/2,paddingVertical:r.xs+1},coverageText:{...k(e,"medium"),fontSize:n.size.caption,lineHeight:n.size.caption+r.xs-1},metaRow:{flexDirection:"row",alignItems:"center",gap:r.sm,paddingBottom:r.md},metaText:{flex:1,...k(e,"regular"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},pendingText:{...k(e,"regular"),fontSize:n.size.caption,lineHeight:Math.round(n.size.caption*n.lineHeight.normal),color:t.text.muted,paddingBottom:r.md},identityLabel:{...k(e,"medium"),fontSize:n.size.bodyTight,lineHeight:Math.round(n.size.bodyTight*n.lineHeight.snug),color:t.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...k(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},cardTitle:{paddingTop:r.sm},noteSection:{paddingVertical:r.md,gap:r.xs},noteLabel:{...k(e,"bold"),fontSize:n.size.bodyTight,color:t.text.secondary,textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},noteBody:{...k(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.primary},noteBodyMuted:{...k(e,"regular"),fontSize:n.size.body+1,lineHeight:Math.round((n.size.body+1)*n.lineHeight.relaxed),color:t.text.muted,fontStyle:"italic"}})}i(tg,"makeLocalStyles");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 rg=Math.round(hr/(1024*1024)),ot=Object.freeze({title:i(e=>`Upload ${Fe(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 ${Fe(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 ${rg} MB each. You can pick several at once. We\u2019ll read them and add the results to your records.`,chooseFiles:"Choose files",chooseFilesA11y:"Choose records to upload",uploading:i((e,t)=>`Uploading ${Math.min(e+1,t)} of ${t}\u2026`,"uploading"),cancel:"Cancel",cancelA11y:"Cancel these uploads",received:i(e=>`${e===1?"Record received.":`${e} records received.`} We\u2019ll read and review ${e===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,"received"),retryFailed:i(e=>`Retry ${e} that didn\u2019t upload`,"retryFailed"),retryFailedA11y:i(e=>`Retry ${e} failed upload${e>1?"s":""}`,"retryFailedA11y"),addMore:"Add more files",addMoreA11y:"Add more records",done:"Done",doneA11y:"Done, view records",errors:Object.freeze({start:"We couldn\u2019t start that upload. Check your connection and try again.",startPlain:"We couldn\u2019t start that upload. Please try again.",upload:"We couldn\u2019t upload that record. Check your connection and try again."})});var hd=Math.round(hr/(1024*1024)),$r=Object.freeze({queued:"Queued",verifying:"Verifying\u2026",done:"Done",failed:"Failed",uploading:i((e,t)=>`Uploading ${Math.min(e+1,t)} of ${t} records`,"uploading"),uploaded:i((e,t)=>`${e} of ${t} records uploaded`,"uploaded")});function Rd(e){let t=Math.round(e.progress*100);switch(e.status){case "done":return $r.done;case "failed":return $r.failed;case "uploading":return e.progress>=1?$r.verifying:`${t}%`;case "queued":return $r.queued;default:return null}}i(Rd,"uploadItemStatusLabel");function No(e){if(e.length===0)return null;let t=i(a=>{let l=a.map(c=>c.name??"");return l.length<=3?l.join(", "):`${l.slice(0,3).join(", ")} and ${l.length-3} more`},"nameList"),r=e.filter(a=>a.reason==="too_large"),o=e.filter(a=>a.reason==="unsupported"),n=[];return o.length>0&&n.push(`${t(o)} ${o.length>1?"are not PDFs":"is not a PDF"}`),r.length>0&&n.push(`${t(r)} ${r.length>1?"are":"is"} over ${hd} MB`),`Didn\u2019t upload: ${n.join("; ")}. We can only read PDFs up to ${hd} MB right now.`}i(No,"skippedFilesMessage");function vd(e){let t=[];for(let r of e)r.status==="skipped"&&r.skipReason!==null&&t.push({name:r.name,reason:r.skipReason});return t}i(vd,"skippedOf");var qt=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 wd({request:e,onRecovered:t,canUpload:r=false},o){let[n,a]=useState(""),[l,c]=useState(false),[s,d]=useState(null),[u,p]=useState(false),[f,b]=useState(null),R=useRef(false),v=useRef(false),w=useRef(0);useEffect(()=>(v.current=true,()=>{v.current=false,w.current+=1;}),[o]);let g=f!==null&&f.before===e.updatedAt?{...f.value,canRetrySend:e.canRetrySend===true&&f.value.canRetrySend===true,canUpdateClinicEmail:e.canUpdateClinicEmail===true&&f.value.canUpdateClinicEmail===true,canRevoke:e.canRevoke===true&&f.value.canRevoke===true,canConvertToUpload:e.canConvertToUpload===true&&f.value.canConvertToUpload===true}:e,y=n.trim(),x=y.length<=320&&!Array.from(y).some(A=>A.charCodeAt(0)<=32||A.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(y),h=g.canUpdateClinicEmail===true&&y.length>0,I=g.canRetrySend===true&&!l&&!h,S=g.canUpdateClinicEmail===true&&!l&&x,T=g.canConvertToUpload===true&&r,C=i(async A=>{let F={retry:I,email:S,revoke:g.canRevoke===true&&u,convert:T};if(R.current||!v.current||!F[A])return;R.current=true,c(true),d(null);let q=w.current,U=i(()=>v.current&&q===w.current,"live");try{let j=A==="retry"?await o.retryRequest(e.id):A==="email"?await o.updateClinicEmail(e.id,y):A==="revoke"?await o.revokeRequest(e.id):await o.convertToUpload(e.id);if(!U())return;if(!j.ok){d(j.error);return}if(j.value.id!==e.id||j.value.petRef!==e.petRef){d(N("internalError"));return}b({before:e.updatedAt,value:j.value}),a(""),p(!1),t();}catch{U()&&d(N("internalError"));}finally{R.current=false,U()&&c(false);}},"run");return {request:g,email:n,busy:l,error:s,canRetry:I,canUpdateEmail:S,canConvert:T,hasEmailEdit:h,confirmingRevoke:u&&g.canRevoke===true,emailInvalid:y.length>0&&!x,setEmail(A){R.current||(a(A),d(null));},retry:i(()=>C("retry"),"retry"),updateEmail:i(()=>C("email"),"updateEmail"),revoke:i(()=>C("revoke"),"revoke"),convert:i(()=>C("convert"),"convert"),askRevoke(){!R.current&&g.canRevoke===true&&p(true);},keepRequest(){R.current||p(false);}}}i(wd,"useRecordsRecovery");var og=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],ig=["requested","awaiting_upload","records_received","processing","ready"],sg=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],Vn=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"}),_t=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"}),ag=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"}),lg=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 cg(e){return e.wireStatus??lg[e.status]??"sent"}i(cg,"wireStatusOf");function dg(e,t){return e!=="awaiting_response"||t<=0?null:`${t} ${t===1?"reminder":"reminders"} sent`}i(dg,"reminderProgressLabel");function ug(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(ug,"reachedRailIndex");function pg(e){switch(e.dispatchStatus){case "sent":return _t.delivered;case "preparing":case "queued":case "sending":return _t.emailing;case "failed":return _t.bounced;default:return null}}i(pg,"deliveryDetail");function mg(e,t){return dg(t,e.reminderCount??0)??_t.waiting}i(mg,"awaitingDetail");function yg(e){return e.source==="owner_provided"||!!e.convertedToUploadAt}i(yg,"isOwnerSourcedRequest");function fg(e,t,r){let o=yg(t);switch(e){case "sent_to_clinic":return pg(t);case "awaiting_clinic":return mg(t,r);case "awaiting_upload":return _t.upload;case "records_received":return o?_t.ownerAdded:_t.clinicSent;case "processing":return _t.preparing;case "ready":return _t.ready;default:return null}}i(fg,"railDetail");function gg(e,t){return !!e.reviewStartedAt||t==="parsing_failed"||t==="review_email_failed"}i(gg,"tookReviewBranch");function bg(e,t,r){if(e.key!=="processing"||!gg(t,r))return [e];let o=r==="parsing_failed",n=r==="published",a=n?"done":o?"current":"done",l=n?"done":o?"upcoming":"current";return [{key:"parsing_failed",title:Vn.parsing_failed,detail:_t.parsingFailed,at:null,state:a},{key:"manual_review",title:Vn.manual_review,detail:_t.manualReview,at:t.reviewStartedAt??null,state:l}]}i(bg,"expandProcessingPhase");function hg(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(hg,"convertedReachedIndex");function xd(e){return {key:"awaiting_clinic",title:_t.switchedTitle,detail:_t.switched,at:e.convertedToUploadAt??null,state:"done"}}i(xd,"convertedClinicSwitchEvent");function Rg(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(Rg,"ownerReachedIndex");function vg(e,t,r){switch(e){case "requested":return t.createdAt||null;case "awaiting_clinic":return t.lastReminderAt??null;case "processing":return t.parsingStartedAt??t.reviewStartedAt??null;case "ready":return r==="published"&&t.updatedAt||null;default:return null}}i(vg,"railTimestamp");function Cd(e,t,r,o){return {key:e,title:Vn[e],detail:fg(e,t,r),at:vg(e,t,r),state:o}}i(Cd,"railEvent");function yr(e,t){return {key:e,title:Vn[e],detail:ag[e]??null,at:t.updatedAt||null,state:"failed"}}i(yr,"terminalEvent");function _s(e,t,r,o,n){return e.map((a,l)=>{let c=n?.(a)??null;if(c!==null)return c;let s=o==="published"||l<t?"done":l===t?"current":"upcoming";return Cd(a,r,o,s)}).flatMap(a=>bg(a,r,o))}i(_s,"walkRail");function Ps(e){let t=cg(e),r=i(n=>Cd(n,e,t,"done"),"done");if(t==="revoked")return [r("requested"),yr("revoked",e)];if(e.convertedToUploadAt)return t==="failed"?[r("requested"),r("sent_to_clinic"),xd(e),r("awaiting_upload"),r("records_received"),yr("processing_failed",e)]:_s(sg,hg(t),e,t,n=>n==="awaiting_clinic"?xd(e):null);if(e.source==="owner_provided"){if(t==="failed"||t==="clinic_declined")return [r("requested"),r("awaiting_upload"),r("records_received"),yr("processing_failed",e)];let n=Rg(t);return _s(ig,n<0?1:n,e,t)}if(t==="clinic_declined")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),yr("clinic_declined",e)];if(t==="clinic_responded_no_records")return [r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),yr("clinic_no_records",e)];if(t==="failed"){let n=e.failureCode??null;return n==="no_response"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),yr("no_response",e)]:n==="hard_bounce"||n==="dispatch_failed"?[r("requested"),yr("delivery_failed",e)]:n==="parse_timeout"||n==="parse_error"||e.dispatchStatus==="sent"?[r("requested"),r("sent_to_clinic"),r("awaiting_clinic"),r("records_received"),yr("processing_failed",e)]:[r("requested"),yr("delivery_failed",e)]}let o=ug(t);return _s(og,o<0?1:o,e,t)}i(Ps,"buildRequestTimeline");var Cg=Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),Mo=24,Is=10;function Ho({request:e}){let t=kg(),r=Ps(e);return jsx(View,{style:t.container,accessibilityRole:"summary",children:r.map((o,n)=>jsx(Eg,{event:o,isLast:n===r.length-1,styles:t},o.key))})}i(Ho,"RequestTimeline");function Eg({event:e,isLast:t,styles:r}){let o=e.at?Y(e.at):null,n=[e.title,e.detail,o,Cg[e.state]].filter(Boolean);return jsxs(View,{style:r.row,accessible:true,accessibilityRole:"text",accessibilityLabel:n.join(", "),testID:`records-timeline-${e.key}`,children:[jsxs(View,{style:r.railColumn,children:[jsx(Sg,{state:e.state,styles:r}),t?null:jsx(View,{style:[r.connector,e.state==="done"&&r.connectorDone],accessibilityElementsHidden:true,importantForAccessibility:"no"})]}),jsxs(View,{style:r.body,children:[jsxs(View,{style:r.titleRow,children:[jsx(m,{style:[r.title,e.state==="current"&&r.titleCurrent,e.state==="failed"&&r.titleFailed,e.state==="upcoming"&&r.titleUpcoming],children:e.title}),o?jsx(m,{style:r.date,children:o}):null]}),e.detail?jsx(m,{style:[r.detail,e.state==="upcoming"&&r.detailUpcoming],children:e.detail}):null]})]})}i(Eg,"TimelineRow");function Sg({state:e,styles:t}){return e==="done"?jsx(View,{style:[t.dot,t.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{tier:"badge",style:[t.glyph,t.glyphOnBrand],children:"\u2713"})}):e==="failed"?jsx(View,{style:[t.dot,t.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(m,{tier:"badge",style:t.glyph,children:"!"})}):e==="current"?jsx(View,{style:[t.dot,t.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(View,{style:t.dotCurrentCore})}):jsx(View,{style:[t.dot,t.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}i(Sg,"TimelineDot");function kg(){let e=V();return useMemo(()=>Tg(e),[e])}i(kg,"useStyles");function Tg(e){let{color:t,type:r}=e,{size:o}=r;return StyleSheet.create({container:{gap:0},row:{flexDirection:"row",alignItems:"flex-start",gap:12},railColumn:{alignItems:"center",width:Mo},body:{flex:1,paddingBottom:18,gap:2},titleRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:8},dot:{width:Mo,height:Mo,borderRadius:Mo/2,alignItems:"center",justifyContent:"center"},dotDone:{backgroundColor:t.brand},dotFailed:{backgroundColor:t.danger},dotCurrent:{borderWidth:2,borderColor:t.brand,backgroundColor:t.surface},dotCurrentCore:{width:Is,height:Is,borderRadius:Is/2,backgroundColor:t.brand},dotUpcoming:{borderWidth:2,borderColor:t.borderHairlineGreen,backgroundColor:t.surface},glyph:{...k(e,"bold"),fontSize:o.caption,lineHeight:o.caption+2,color:t.surface},glyphOnBrand:{color:t.onPrimary},connector:{width:2,flex:1,minHeight:22,backgroundColor:t.borderHairlineGreen,marginVertical:2},connectorDone:{backgroundColor:t.brand},title:{flex:1,...k(e,"bold"),fontSize:o.body,lineHeight:o.body+4,color:t.text.primary},titleCurrent:{color:t.brandInk},titleFailed:{color:t.danger},titleUpcoming:{color:t.text.muted,...k(e,"regular")},date:{...k(e,"regular"),fontSize:o.caption,lineHeight:o.caption+4,color:t.text.muted},detail:{...k(e,"regular"),fontSize:o.bodyTight,lineHeight:o.bodyTight+4,color:t.text.muted},detailUpcoming:{color:t.text.muted,opacity:.7}})}i(Tg,"makeStyles");function rn(e,t,r){let o=_r(e,r);switch(o.kind){case "consent_required":return jsx(Ig,{onGrant:t});case "consent_unavailable":return jsx(Dg,{});case "session_required":return jsx(Ag,{});case "withheld":return jsx(Og,{});case "pet_not_found":case "error":return jsx(Lg,{error:o.error,onRetry:e.refresh});default:return Rr(o)}}i(rn,"renderErrorFamily");function nn(e,t){return ()=>{let r=hs(t,e.consent);if(r.length===0)return;let o=`records-consent-${Date.now().toString(36)}`;e.grantConsent(r,o);}}i(nn,"makeGrantHandler");function kd({records:e}){let t=qn(),r=e.uploadQueue;if(r.length===0)return null;let o=r.filter(l=>l.status!=="skipped"),n=o.filter(l=>l.status==="done").length,a=No(vd(r));return jsxs(View,{style:t.timeline,testID:"records-upload-queue",children:[a!==null?jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"polite",style:t.errorText,children:a}):null,o.length>0?jsx(View,{accessibilityLiveRegion:"polite",accessibilityLabel:e.isUploading?$r.uploading(n,o.length):$r.uploaded(n,o.length),children:o.map(l=>{let c=Math.round(l.progress*100);return jsxs(View,{style:t.uploadRow,testID:`records-upload-file-${l.status}`,children:[jsxs(View,{style:t.uploadRowHead,children:[jsx(m,{style:t.rowLabel,children:l.name??""}),jsx(m,{style:t.rowValue,children:Rd(l)})]}),l.status==="uploading"?jsx(View,{style:t.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:c},children:jsx(View,{style:[t.progressFill,{width:`${c}%`}]})}):null,l.status==="failed"&&l.error?jsx(m,{style:t.timelineMeta,children:l.error.displayMessage}):null]},l.key)})}):null]})}i(kd,"UploadQueue");function Ig({onGrant:e}){let t=qn();return jsx(View,{style:t.centered,accessible:true,accessibilityRole:"alert",accessibilityLabel:pe.consentRequired,children:jsx(Pressable,{onPress:e,accessibilityRole:"button",accessibilityLabel:pe.allow,style:t.primaryButton,children:jsx(m,{style:t.primaryLabel,children:pe.allow})})})}i(Ig,"ConsentRequiredState");function Os({label:e,glyph:t}){let r=qn();return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(e);},[e]),jsxs(View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",accessibilityLabel:e,children:[jsx(View,{style:t==="withheld"?r.withheldGlyph:r.emptyGlyph}),jsx(m,{style:r.errorText,children:e})]})}i(Os,"AlertState");function Dg(){return jsx(Os,{label:pe.consentRequired,glyph:"empty"})}i(Dg,"ConsentUnavailableState");function Ag(){return jsx(Os,{label:pe.sessionRequired,glyph:"empty"})}i(Ag,"SessionRequiredState");function Og(){return jsx(Os,{label:pe.recordUnavailable,glyph:"withheld"})}i(Og,"WithheldState");function Lg({error:e,onRetry:t}){let r=qn();return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(e.displayMessage);},[e.displayMessage]),jsxs(View,{style:r.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:[jsx(m,{style:r.errorText,children:e.displayMessage}),e.retryable?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:pe.retry,style:r.primaryButton,children:jsx(m,{style:r.primaryLabel,children:pe.retry})}):null]})}i(Lg,"ErrorState");function Td({call:e,prompt:t}){let r=qn(),o=t.trim().length>0?t:On.fallbackPrompt;return jsxs(View,{style:r.callCard,accessibilityRole:"summary",children:[jsx(m,{style:r.timelineLabel,children:On.heading}),jsx(m,{style:r.timelineMeta,children:o}),jsx(Pressable,{onPress:()=>{Linking?.openURL?.(e.dial);},accessibilityRole:"button",accessibilityLabel:On.callAt(e.phone),style:r.linkButton,testID:"records-call-clinic",children:jsx(m,{style:r.linkLabel,children:On.call})})]})}i(Td,"ClinicCallCard");function qn(){let e=V();return useMemo(()=>Vg(e),[e])}i(qn,"useStyles");function Vg(e){let{color:t,space:r,radius:o,type:n,slots:a}=e,{size:l,lineHeight:c,letterSpacing:s}=n,d=rt(a.recordCard,StyleSheet.hairlineWidth),u=at(a.recordCard),p=i((y,x)=>Math.round(y*x),"lh"),f=StyleSheet.hairlineWidth,b=r.xxl*3+r.xl,R=r.xxl+r.md,v=r.xxl+r.sm,w=e.brightness==="dark"?t.errorRed:t.danger,g={shadowColor:t.brand,shadowOffset:{width:0,height:r.xs},shadowRadius:r.sm,shadowOpacity:.08,elevation:r.xs};return StyleSheet.create({container:{flex:1,minHeight:b,backgroundColor:t.background},body:{flex:1},centered:{minHeight:b,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:v,height:v,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:f,borderColor:t.brandBorder},withheldGlyph:{width:v,height:v,borderRadius:o.sm,backgroundColor:t.badgeBgCaution,borderWidth:f,borderColor:t.cautionAccent},errorText:{...k(e,"regular"),fontSize:l.subtitle,lineHeight:p(l.subtitle,c.snug),color:w,textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...g,...rt(a.primaryButton)},primaryLabel:{...k(e,"bold"),color:t.onPrimary,fontSize:l.body,letterSpacing:s.tight,...at(a.primaryButton)},linkButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...g,...rt(a.primaryButton)},linkLabel:{...k(e,"bold"),color:t.onPrimary,fontSize:l.body,letterSpacing:s.tight,...at(a.primaryButton)},disabledButton:{minHeight:R,minWidth:R,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.surfaceSubtle,borderWidth:f,borderColor:t.brandBorder},disabledLabel:{...k(e,"bold"),color:t.text.muted,fontSize:l.body,letterSpacing:s.tight},list:{flex:1},listContent:{padding:r.lg,gap:r.md},timeline:{paddingVertical:r.md,paddingHorizontal:r.lg,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:f,borderColor:t.brandBorder,gap:r.xs,...g,...d},timelineTitle:{...k(e,"bold"),fontSize:l.heading,lineHeight:p(l.heading,c.snug),color:t.text.primary,letterSpacing:s.tight,...u},timelineLabel:{...k(e,"bold"),fontSize:l.subtitle,lineHeight:p(l.subtitle,c.snug),color:t.text.secondary,letterSpacing:s.tight,...u},callCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:f,borderColor:t.brandBorder,...d},timelineMeta:{...k(e,"regular"),fontSize:l.bodyTight,lineHeight:p(l.bodyTight,c.normal),color:t.text.muted,...u},recordBlock:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:f,borderColor:t.brandBorder,...g,...d},row:{flexDirection:"row",justifyContent:"space-between",gap:r.md,paddingVertical:r.xs,borderBottomWidth:f,borderBottomColor:t.borderHairlineGreen},rowLabel:{...k(e,"regular"),fontSize:l.body,lineHeight:p(l.body,c.normal),color:t.text.muted,flexShrink:1,...u},rowValue:{...k(e,"medium"),fontSize:l.body,lineHeight:p(l.body,c.normal),color:t.text.primary,textAlign:"right",flexShrink:1,...u},disclaimer:{...k(e,"regular"),fontSize:l.caption,lineHeight:p(l.caption,c.normal),color:t.text.muted,marginTop:r.md},uploadRow:{gap:r.xs,paddingVertical:r.xs,borderBottomWidth:f,borderBottomColor:t.borderHairlineGreen},uploadRowHead:{flexDirection:"row",justifyContent:"space-between",gap:r.md},progressTrack:{height:r.xs,borderRadius:o.pill,backgroundColor:t.brandSofter,overflow:"hidden",width:"100%"},progressFill:{height:"100%",backgroundColor:t.brand}})}i(Vg,"makeStyles");var zt=Object.freeze({title:"Medical records",subtitle:i(e=>{let t=e?.trim()??"";return t.length>0?`${t}\u2019s uploads and clinic requests`:"Every upload and clinic request"},"subtitle"),requestRecords:"Request records",requestRecordsA11y:"Request records from a clinic",uploadOwn:"I already have the records",uploadOwnA11y:"Upload records you already have",ownerUpload:"Records you uploaded",clinicRequest:"Clinic request",meta:i((e,t)=>`${e?"Uploaded":"Requested"} ${Y(t)}`,"meta"),rowA11y:i((e,t,r)=>`${e}, ${t}, status ${r}`,"rowA11y"),askA11y:i(e=>`Ask Everfur about ${e}`,"askA11y")}),Uo=Object.freeze({preparing:"Preparing",sent:"Sent",processing:"Processing",done:"Ready"});function qg(e){switch(e){case "awaiting_clinic":return Uo.sent;case "received":case "parsing":case "in_review":return Uo.processing;case "published":return Uo.done;default:return Uo.preparing}}i(qg,"stepLabel");function _d(e){let t=e.source==="owner_provided",r=e.clinicName?.trim()||(t?zt.ownerUpload:zt.clinicRequest),o=e.statusLabel.trim()||qg(e.status),n=zt.meta(t,e.createdAt);return Object.freeze({source:r,meta:n,status:o,ownerUpload:t,a11yLabel:zt.rowA11y(r,n,o)})}i(_d,"requestRowView");var zg=new Set(["records_received","parsing","parsing_failed","in_review","review_email_failed"]),Fg=new Set(["received","parsing","in_review"]);function Ng(e){return e.wireStatus!==void 0?zg.has(e.wireStatus):Fg.has(e.status)}i(Ng,"isProcessing");function Pd(e,t,r={}){let o=e.filter(c=>!gr(c.status));if(e.length===0||r.activeOnly===true&&o.length===0)return null;let n=e.filter(Ng).length,a=n>0?`${n} document${n===1?"":"s"} being read`:o.length>0?`${o.length} active record request${o.length===1?"":"s"}`:"Your record requests",l=n>0?`We\u2019ll add ${n===1?"it":"them"} to ${t}\u2019s records once ready.`:o.length>0?"See each clinic\u2019s status and what happens next.":"See the status of every upload and clinic request.";return Object.freeze({title:a,subtitle:l,processing:n>0,a11yLabel:`${a}. ${l}`})}i(Pd,"requestsStatusCardView");function Ls(e){let{style:t,renderPending:r,...o}=Oe(e,["onNavigate","onBack","onAsk"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(Hg,{...o,style:t})})}i(Ls,"EverfurRecordsRequests");function Hg({petRef:e,petName:t,controller:r,onNavigate:o,onBack:n,onAsk:a,style:l}){let c=ue(),s=Vs(),d=st(r?{petRef:e,controller:r}:{petRef:e}),u=useMemo(()=>Rs(d.requests.filter(b=>b.petRef===e)),[d.requests,e]),p=a?b=>{let R=Eo(t,{clinicName:b.clinicName??null,statusLabel:Ur(b),status:b.status,heldItemCount:b.heldItemCount},b.id);a(R.prompt,R.entityRef);}:void 0,f;return d.status==="loading"&&u.length===0?f=jsx(po,{testID:"records-list-loading"}):d.status==="error"&&u.length===0?f=jsx(Ue,{variant:pt(d.error),message:d.error?.displayMessage,onAction:d.error?.retryable?d.refresh:void 0,testID:"records-list-error"}):u.length===0?f=jsx(Ue,{variant:"no_requests",testID:"records-list-empty"}):f=jsx(ScrollView,{contentContainerStyle:s.list,testID:"records-list-results",children:u.map(b=>jsx(Ug,{request:b,onOpen:o?()=>o({name:"request",requestId:b.id}):void 0,onAsk:p?()=>p(b):void 0},b.id))}),jsxs(View,{style:[c.root,l],children:[jsx(Ke,{title:zt.title,onBack:n,testID:"records-list-header"}),u.length>0?jsx(m,{style:s.subtitle,testID:"records-list-subtitle",children:zt.subtitle(t)}):null,jsx(View,{style:c.body,children:f}),o?jsxs(View,{style:s.footer,children:[jsx(J,{label:zt.requestRecords,accessibilityLabel:zt.requestRecordsA11y,onPress:()=>o({name:"clinicPicker"}),testID:"records-list-new"}),jsx(J,{label:zt.uploadOwn,kind:"outline",accessibilityLabel:zt.uploadOwnA11y,onPress:()=>o({name:"upload"}),testID:"records-list-upload-own"})]}):null,jsx(Ve,{})]})}i(Hg,"RequestsBody");function Ug({request:e,onOpen:t,onAsk:r}){let o=ue(),n=Vs(),a=_d(e),l=Yc(e),c=jsxs(Fragment,{children:[jsx(View,{style:[n.bubble,o.chipTones[l].bg],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxs(View,{style:n.copy,children:[jsx(m,{style:n.source,numberOfLines:1,children:a.source}),jsx(m,{style:n.meta,numberOfLines:1,children:a.meta}),jsx(View,{accessibilityElementsHidden:true,importantForAccessibility:"no",children:jsx(St,{label:a.status,tone:l})})]}),t?jsx(tr,{}):null]});return jsxs(View,{style:n.row,testID:`records-request-row-${e.id}`,children:[t?jsx(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:a.a11yLabel,style:n.rowInner,testID:`records-request-open-${e.id}`,children:c}):jsx(View,{style:n.rowInner,accessible:true,accessibilityLabel:a.a11yLabel,children:c}),r?jsx(J,{label:Sr.ask,kind:"ask",accessibilityLabel:zt.askA11y(a.source),onPress:r,testID:`records-request-ask-${e.id}`}):null]})}i(Ug,"RequestRow");function zn({requests:e,petName:t,activeOnly:r=false,onOpen:o}){let n=Vs(),a=Pd(e,Fe(t),{activeOnly:r});return a===null||o===void 0?null:jsxs(Pressable,{onPress:o,accessibilityRole:"button",accessibilityLabel:a.a11yLabel,style:n.card,testID:"records-requests-status",children:[jsx(View,{style:[n.cardBubble,a.processing?n.cardBubbleProcessing:null],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxs(View,{style:n.cardText,children:[jsx(m,{style:n.cardTitle,children:a.title}),jsx(m,{style:n.cardSubtitle,children:a.subtitle})]}),jsx(tr,{})]})}i(zn,"RecordsRequestsStatusCard");function Vs(){let e=V();return useMemo(()=>jg(e),[e])}i(Vs,"useLocalStyles");function jg(e){let{color:t,space:r,radius:o,type:n}=e,a=i((c,s)=>Math.round(c*s),"lh"),l=r.xxl+r.xs/2;return StyleSheet.create({subtitle:{...k(e,"regular"),fontSize:n.size.caption,lineHeight:a(n.size.caption,n.lineHeight.normal),color:t.text.muted,paddingHorizontal:r.lg,paddingBottom:r.md},list:{paddingHorizontal:r.lg,paddingBottom:r.xl,gap:r.md},row:{borderRadius:o.lg,borderWidth:1,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.md+r.xs/2,paddingVertical:r.md,gap:r.sm},rowInner:{flexDirection:"row",alignItems:"center",gap:r.md},bubble:{width:l,height:l,borderRadius:l/2},copy:{flex:1,gap:r.xs+1},source:{...k(e,"bold"),fontSize:n.size.body,lineHeight:a(n.size.body,n.lineHeight.snug),color:t.text.primary},meta:{...k(e,"regular"),fontSize:n.size.tiny,lineHeight:a(n.size.tiny,n.lineHeight.normal),color:t.text.muted},footer:{paddingHorizontal:r.lg,paddingTop:r.sm+r.xs/2,paddingBottom:r.lg,gap:r.sm+r.xs/2,borderTopWidth:1,borderTopColor:t.borderHairlineGreen},card:{flexDirection:"row",alignItems:"center",gap:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,paddingHorizontal:r.md+r.xs,paddingVertical:r.md},cardBubble:{width:r.xl+r.xs/2,height:r.xl+r.xs/2,borderRadius:o.pill,borderWidth:2,borderColor:t.brandInk},cardBubbleProcessing:{borderColor:t.warningStrong,backgroundColor:t.badgeBgCaution},cardText:{flex:1,gap:2},cardTitle:{...k(e,"bold"),fontSize:n.size.bodyTight,lineHeight:a(n.size.bodyTight,n.lineHeight.snug),color:t.brandInk},cardSubtitle:{...k(e,"regular"),fontSize:n.size.caption,lineHeight:a(n.size.caption,n.lineHeight.normal),color:t.text.muted}})}i(jg,"makeLocalStyles");var Yg=i((e,t)=>e.getRecordDepth(t),"readDepth"),Kg=i(e=>!e.available,"depthEmpty");function Ns(e){let{style:t,renderPending:r,...o}=Oe(e,["onNavigate","onBack","onAsk"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(Qg,{...o,style:t})})}i(Ns,"EverfurRecordsDashboard");function Qg({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:a,onAsk:l,style:c}){let s=ue(),d=Ms(),u=st(r?{petRef:e,controller:r}:{petRef:e}),p=ms(e),f=Gt(e,Yg,Kg),[b,R]=useState(null),v=useCallback((E,L)=>R({marker:E,point:L}),[]),w=useMemo(()=>Hr(o,u.consent),[o,u.consent]),g=useMemo(()=>nn(u,o),[u,o]),y=p.markers?.markers??[],x=y.length>0,h=u.record!==null&&!u.record.isEmpty&&!u.record.withheld,I=to(u.requests,e),S=u.requests.filter(E=>E.petRef===e),T=n?()=>n({name:"requests"}):void 0,C=Ei({hasMarkers:x,requests:u.requests,petRef:e}),A=Si({recordLoading:u.status==="loading",hasFullRecord:h,recordError:u.status==="error",markersLoading:p.status==="loading",markersError:p.status==="error",hasMarkers:x,requestsLoading:u.status==="loading",dashboardState:C,drivingRequest:I}),F=p.markers?.disclaimer??u.record?.disclaimer??"",q=i(()=>{u.refresh(),p.refresh(),f.refresh();},"retryAll"),U=f.value!==null&&!f.value.withheld&&f.value.available?f.value:null,j=Fe(t),ae=l&&p.markers?.summary?()=>{let E=Bc(t,p.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},e);l(E.prompt,E.entityRef);}:void 0,ne=l?E=>{let L=Mc(t,{canonicalName:E.name,markerId:E.markerId,latestValueText:E.latest?kt(E.latest.value,E.unit,E.latest.qualitativeResult):null,statusText:E.latest?rr(E.latest.status).label:null,trajectoryText:Kr(E.trajectory,E.points.length),meaningText:E.meaning});l(L.prompt,L.entityRef);}:void 0,Re=l&&b?()=>{let{marker:E,point:L}=b,X=Hc(t,{canonicalName:E.name,valueText:kt(L.value,E.unit,L.qualitativeResult),collectedAt:Y(L.at),sourceClinic:L.sourceClinic,referenceText:L.refLow!==null||L.refHigh!==null?Co(L,E.unit):null,flagged:L.status==="above"?"above":L.status==="below"?"below":null,reviewed:L.reviewed,entityId:L.docId??E.markerId});R(null),l(X.prompt,X.entityRef);}:void 0,te=jsxs(Fragment,{children:[p.markers?.summary?jsx(View,{style:s.inset,children:jsx(Jc,{summary:p.markers.summary,onAsk:ae,testID:"dashboard-marker-summary"})}):null,jsx(m,{style:s.lead,children:mt.lead(t)}),jsx(nd,{markers:y,onPointPress:v,onAsk:ne})]}),_=i(E=>n?jsxs(View,{style:[s.inset,d.actions],children:[E?jsx(qs,{label:mt.viewFullRecord,onPress:()=>n({name:"record"}),testID:"dashboard-full-record-action"}):null,jsx(qs,{label:mt.viewTimeline,onPress:()=>n({name:"timeline"}),testID:"dashboard-timeline-action"})]}):null,"actions"),D;if(u.status==="error"){let E=_r(u,w);D=E.kind==="error"||E.kind==="pet_not_found"?jsx(Ue,{variant:pt(E.error),message:E.error.displayMessage,onAction:E.error.retryable?q:void 0,testID:"dashboard-error"}):rn(u,g,w);}else switch(A){case "loading":D=jsx(uo,{testID:"dashboard-loading"});break;case "record":D=jsxs(ScrollView,{contentContainerStyle:s.contentTight,testID:"dashboard-record",children:[x?te:p.status==="error"?jsx(View,{style:[s.inset,d.actions],children:jsx(qs,{label:mt.retryMarkers,onPress:q,testID:"dashboard-markers-retry"})}):null,jsx(View,{style:s.inset,children:u.record?jsx(Fo,{record:u.record,depth:U,petName:t,showLabs:!x,onNavigate:n,onAsk:l}):null}),jsx(View,{style:s.inset,children:jsx(zn,{requests:S,petName:t,activeOnly:true,onOpen:T})}),_(true)]});break;case "error":D=jsx(Ue,{variant:pt(p.error??u.error),message:(p.error??u.error)?.displayMessage,onAction:(p.error??u.error)?.retryable?q:void 0,testID:"dashboard-error"});break;case "in_progress":D=jsxs(ScrollView,{contentContainerStyle:s.content,testID:"dashboard-in-progress",children:[I?jsx(Xg,{request:I,petName:j,onOpen:n?()=>n({name:"request",requestId:I.id}):void 0,onAsk:l?()=>{let E=Eo(t,{clinicName:I.clinicName??null,statusLabel:Ur(I),status:I.status,heldItemCount:I.heldItemCount},I.id);l(E.prompt,E.entityRef);}:void 0}):null,jsx(zn,{requests:S,petName:t,onOpen:T}),jsx(kr,{disclaimer:F})]});break;case "none":D=jsxs(ScrollView,{contentContainerStyle:s.content,testID:"dashboard-request-prompt",children:[jsxs(View,{style:d.promptCard,children:[jsxs(View,{style:d.promptHeader,children:[jsx(View,{style:d.promptGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:d.promptTitle,children:Vr.title(t)})]}),jsx(m,{style:d.promptBody,children:Vr.body}),n?jsxs(Fragment,{children:[jsx(J,{label:Vr.requestFromClinic,accessibilityLabel:Vr.requestFromClinicA11y(t),onPress:()=>n({name:"clinicPicker"}),style:d.promptCta,testID:"dashboard-request-prompt-clinic"}),jsx(J,{label:Vr.uploadDocument,kind:"outline",accessibilityLabel:Vr.uploadDocumentA11y(t),onPress:()=>n({name:"upload"}),style:d.promptCtaSecondary,testID:"dashboard-request-prompt-upload"})]}):null]}),jsx(zn,{requests:S,petName:t,onOpen:T}),jsx(kr,{disclaimer:F})]});break;case "labs_only":D=jsxs(ScrollView,{contentContainerStyle:s.contentTight,testID:"dashboard-labs-only",children:[te,jsx(View,{style:s.inset,children:jsx(zn,{requests:S,petName:t,activeOnly:true,onOpen:T})}),jsx(View,{style:s.inset,children:jsx(kr,{disclaimer:F})}),_(false)]});break;default:D=Rr(A);}return jsxs(View,{style:[s.root,c],children:[jsx(Ke,{title:mt.title,onBack:a,testID:"dashboard-header",right:n?jsx(Pressable,{onPress:()=>n({name:"timeline"}),accessibilityRole:"button",accessibilityLabel:mt.openTimeline,hitSlop:12,style:d.headerButton,testID:"dashboard-timeline-link",children:jsx(ql,{})}):void 0}),jsx(View,{style:s.body,children:D}),jsx(od,{marker:b?.marker??null,point:b?.point??null,onClose:()=>R(null),onAsk:Re}),jsx(Ve,{})]})}i(Qg,"DashboardBody");function qs({label:e,onPress:t,testID:r}){let o=Ms();return jsxs(Pressable,{onPress:t,accessibilityRole:"button",accessibilityLabel:e,style:o.actionRow,testID:r,children:[jsxs(View,{style:o.actionLeft,children:[jsx(View,{style:o.actionIcon,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:o.actionLabel,children:e})]}),jsx(tr,{})]})}i(qs,"ActionRow");function Xg({request:e,petName:t,onOpen:r,onAsk:o}){let n=ue(),a=Ms(),l=e.clinicName?.trim()||Sr.title(t),c=Ur(e),s=jsxs(View,{style:a.inProgressInner,children:[jsxs(View,{style:a.inProgressHead,children:[jsx(m,{style:a.inProgressTitle,children:l}),r?jsx(tr,{}):null]}),jsx(Ho,{request:e}),c.length>0?jsx(View,{style:n.statusCard,children:jsx(m,{style:n.statusText,children:c})}):null]});return jsxs(View,{style:a.inProgressCard,testID:"dashboard-in-progress-card",accessibilityRole:"summary",accessible:r?false:void 0,accessibilityLabel:r?void 0:Sr.a11y(t),children:[r?jsx(Pressable,{onPress:r,accessibilityRole:"button",accessibilityLabel:Sr.openA11y(t,c),testID:"dashboard-in-progress-open",children:s}):s,o?jsx(J,{label:Sr.ask,kind:"ask",accessibilityLabel:Sr.askA11y,onPress:o,testID:"dashboard-in-progress-ask"}):null]})}i(Xg,"InProgressCard");function Ms(){let e=V();return useMemo(()=>Jg(e),[e])}i(Ms,"useLocalStyles");function Jg(e){let{color:t,space:r,radius:o,type:n}=e,a=StyleSheet.hairlineWidth,l=r.xxl+r.md;return StyleSheet.create({headerButton:{width:l,height:l,alignItems:"center",justifyContent:"center"},actions:{gap:r.sm+r.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:o.md,borderWidth:a,borderColor:t.brandBorder,backgroundColor:t.surface,paddingHorizontal:r.lg,paddingVertical:r.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:r.md},actionIcon:{width:r.lg+r.xs/2,height:r.lg+r.xs/2,borderRadius:o.xs,backgroundColor:t.brandSoft,borderWidth:a,borderColor:t.brandBorder},actionLabel:{flex:1,...k(e,"medium"),fontSize:n.size.body,lineHeight:Math.round(n.size.body*n.lineHeight.snug),color:t.text.primary},inProgressCard:{borderRadius:o.lg-r.xs/2,backgroundColor:t.surface,borderWidth:a,borderColor:t.brandBorder,padding:r.lg+r.xs/2,gap:r.lg},inProgressInner:{gap:r.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm},inProgressTitle:{flex:1,...k(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),color:t.text.primary},promptCard:{borderRadius:o.sm,backgroundColor:t.surfaceCream,borderWidth:a,borderColor:t.borderRingCream,paddingHorizontal:r.lg+r.xs,paddingVertical:r.lg+r.xs/2},promptHeader:{flexDirection:"row",alignItems:"center",gap:r.xs+1},promptGlyph:{width:r.xl+1,height:r.xl+1,borderRadius:o.xs,borderWidth:2,borderColor:t.warningStrong},promptTitle:{flex:1,...k(e,"bold"),fontSize:n.size.subtitle,lineHeight:Math.round(n.size.subtitle*n.lineHeight.snug),letterSpacing:n.letterSpacing.headerBrand,color:t.brandInk},promptBody:{marginTop:r.sm-1,...k(e,"regular"),fontSize:n.size.bodyTight,lineHeight:r.lg+r.xs,color:t.text.primary},promptCta:{marginTop:r.sm-1,minHeight:r.xxl+r.sm},promptCtaSecondary:{marginTop:r.sm,minHeight:r.xxl+r.sm}})}i(Jg,"makeLocalStyles");var $o=Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function Ld(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}i(Ld,"toMillis");function Vd(e){let t=[...e.visits.map((r,o)=>({key:`visit-${o}-${r.visitId}`,kind:"visit",kindLabel:ge.kind.visit,at:r.visitDate,date:Y(r.visitDate),title:r.summary??ge.clinicVisit,detail:r.veterinarian?ge.doctor(r.veterinarian):null,docId:r.docId})),...e.vaccines.map((r,o)=>{let n=[];return r.lot&&n.push(ge.lot(r.lot)),r.expiresOn&&n.push(ge.expires(Y(r.expiresOn))),{key:`vaccine-${o}-${r.vaccineId}`,kind:"vaccine",kindLabel:ge.kind.vaccine,at:r.administeredOn,date:Y(r.administeredOn),title:r.product||ge.kind.vaccine,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}}),...e.weights.map((r,o)=>({key:`weight-${o}-${r.weightId}`,kind:"weight",kindLabel:ge.kind.weight,at:r.observedOn,date:Y(r.observedOn),title:jl(r.weightKg),detail:null,docId:r.docId})),...e.medications.map((r,o)=>{let n=[r.dose,r.route,r.frequency].filter(a=>!!a);return {key:`medication-${o}-${r.medicationId}`,kind:"medication",kindLabel:ge.kind.medication,at:r.startedOn,date:Y(r.startedOn),title:r.drugName||ge.kind.medication,detail:n.length?n.join(" \xB7 "):null,docId:r.docId}})];return Object.freeze(t.sort((r,o)=>{let n=Ld(r.at),a=Ld(o.at);return n===null&&a===null?$o[r.kind]-$o[o.kind]:n===null?1:a===null?-1:a!==n?a-n:$o[r.kind]-$o[o.kind]}))}i(Vd,"buildTimelineRows");var ob=300,ib=i((e,t)=>e.getTimeline(t),"readTimeline"),sb=i(e=>e.isEmpty,"timelineEmpty");var ab=i(e=>e.contributions.length===0,"contributionsEmpty");function Fd({petRef:e,style:t,onBack:r}){let o=Gt(e,ib,sb);return jsx(Md,{state:o,style:t,onBack:r,header:jsx(Ke,{title:ge.timeline,onBack:yn(r),testID:"timeline-header"}),loading:jsx(Kl,{testID:"timeline-loading"}),empty:jsx(Ue,{variant:"no_records",testID:"timeline-empty"}),render:n=>jsx(db,{timeline:n})})}i(Fd,"EverfurRecordsTimeline");function Nd({petRef:e,docId:t,style:r,onBack:o}){let n=useCallback((c,s)=>c.getDocumentContributions(s,t),[t]),a=Gt(e,n,ab,t),l=a.value?.document?.title?.trim()||ge.uploadedDocument;return jsx(Md,{state:a,style:r,onBack:o,header:jsx(Ke,{title:l,onBack:yn(o),testID:"contributions-header"}),empty:jsx(Ue,{variant:"no_records",testID:"contributions-empty"}),render:c=>jsx(ub,{view:c})})}i(Nd,"EverfurDocumentContributions");function Md({state:e,style:t,header:r,loading:o,empty:n,render:a,onBack:l}){let c=Bs();return jsx(Le,{capability:"records",style:t,...ze(yn(l),Ye),children:jsxs(View,{style:[c.container,t],children:[r??null,jsx(View,{style:c.body,children:lb(e,a,c,o,n)}),jsx(Ve,{})]})})}i(Md,"DepthSurface");function lb(e,t,r,o,n){switch(e.status){case "loading":return o??jsx(cb,{styles:r});case "empty":return n??jsx(View,{style:r.centered,accessible:true,accessibilityRole:"summary",accessibilityLabel:pe.empty,children:jsx(View,{style:r.emptyGlyph})});case "error":return e.error?jsx(Ue,{variant:pt(e.error),message:e.error.displayMessage,onAction:e.error.retryable?e.refresh:void 0,testID:"depth-error"}):null;case "populated":return e.value===null||e.value.withheld?null:t(e.value);default:return null}}i(lb,"renderState");function cb({styles:e}){let[t,r]=useState(false);return useEffect(()=>{let o=setTimeout(()=>r(true),ob);return ()=>clearTimeout(o)},[]),jsx(View,{style:e.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:pe.loading,children:t?jsx(ActivityIndicator,{}):null})}i(cb,"LoadingState");function db({timeline:e}){let t=Bs(),r=Vd(e);return jsxs(ScrollView,{style:t.list,contentContainerStyle:t.timelineContent,accessibilityLabel:ge.timeline,children:[e.disclaimer.length>0?jsx(View,{style:t.timelineBand,accessible:true,accessibilityRole:"text",accessibilityLabel:mt.important(e.disclaimer),children:jsx(m,{style:t.timelineBandText,children:e.disclaimer})}):null,r.map((o,n)=>jsxs(View,{children:[n>0?jsx(View,{style:t.timelineSeparator}):null,jsxs(View,{style:t.timelineRow,accessible:true,accessibilityRole:"text",accessibilityLabel:[o.kindLabel,o.date,o.title,o.detail].filter(Boolean).join(", "),testID:`records-timeline-row-${o.kind}`,children:[jsx(View,{style:t.timelineBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsxs(View,{style:t.timelineBody,children:[jsxs(View,{style:t.topLine,children:[jsx(m,{style:t.timelineKind,children:o.kindLabel}),jsx(m,{style:t.date,children:o.date})]}),jsx(m,{style:t.timelineTitle,children:o.title}),o.detail?jsx(m,{style:t.rowDetail,children:o.detail}):null]})]})]},o.key))]})}i(db,"TimelineBody");function ub({view:e}){let t=Bs();return jsxs(ScrollView,{style:t.list,contentContainerStyle:t.listContent,accessibilityLabel:pe.records,children:[e.document?.receivedAt?jsx(m,{style:t.rowDetail,children:Y(e.document.receivedAt)}):null,jsx(View,{style:t.card,children:e.contributions.map(r=>jsxs(View,{style:t.row,accessible:true,accessibilityRole:"text",children:[jsx(m,{style:t.rowTitle,children:r.label}),jsx(m,{style:t.rowValue,children:Yr(r.value,r.unit)}),r.observedAt?jsx(m,{style:t.rowDetail,children:Y(r.observedAt)}):null]},r.key))})]})}i(ub,"ContributionsBody");function Bs(){let e=V();return useMemo(()=>pb(e),[e])}i(Bs,"useStyles");function pb(e){let{color:t,space:r,radius:o,type:n,slots:a}=e,{size:l,lineHeight:c}=n,s=i((w,g)=>Math.round(w*g),"lh"),d=StyleSheet.hairlineWidth,u=r.xxl*3+r.xl,p=r.xxl+r.md,f=e.brightness==="dark"?t.errorRed:t.danger,b=at(a.recordCard),R=i((w,g,y,x="regular")=>({...k(e,x),fontSize:w,lineHeight:s(w,g),color:y}),"text"),v=i((w,g,y,x="regular")=>({...R(w,g,y,x),...b}),"inCard");return StyleSheet.create({container:{flex:1,minHeight:u,backgroundColor:t.background},body:{flex:1},centered:{minHeight:u,flexGrow:1,alignItems:"center",justifyContent:"center",padding:r.xl,gap:r.lg},emptyGlyph:{width:r.xxl+r.sm,height:r.xxl+r.sm,borderRadius:o.lg,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},errorText:{...R(l.subtitle,c.snug,f),textAlign:"center",marginBottom:r.md},primaryButton:{minHeight:p,minWidth:p,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xl,paddingVertical:r.md,borderRadius:o.pill,backgroundColor:t.primary,...rt(a.primaryButton)},primaryLabel:{...k(e,"bold"),color:t.onPrimary,fontSize:l.body,...at(a.primaryButton)},list:{flex:1},listContent:{padding:r.lg,gap:r.md},section:{gap:r.sm},heading:{...R(l.heading,c.snug,t.text.primary,"bold")},card:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:d,borderColor:t.brandBorder,...rt(a.recordCard,d)},row:{gap:r.xs,paddingVertical:r.xs,borderBottomWidth:d,borderBottomColor:t.borderHairlineGreen},topLine:{flexDirection:"row",justifyContent:"space-between",gap:r.md},kindLabel:{...v(l.caption,c.normal,t.text.muted,"medium")},date:v(l.caption,c.normal,t.text.muted),rowTitle:{...v(l.body,c.normal,t.text.primary,"bold")},rowValue:{...v(l.body,c.normal,t.text.primary,"medium")},rowDetail:v(l.bodyTight,c.normal,t.text.muted),rowMuted:{...v(l.bodyTight,c.normal,t.text.muted),opacity:.7},chip:{...R(l.caption,c.normal,t.text.primary),alignSelf:"flex-start",paddingHorizontal:r.sm,paddingVertical:r.xs,borderRadius:o.pill},chipNeutral:{backgroundColor:t.badgeBgNeutral},chipCaution:{backgroundColor:t.badgeBgCaution},chipCritical:{backgroundColor:t.badgeBgCritical},disclaimer:{...R(l.caption,c.normal,t.text.muted),marginTop:r.md},timelineContent:{paddingBottom:r.xxl},timelineBand:{flexDirection:"row",gap:r.sm,borderRadius:o.md-r.xs/2,padding:r.md,backgroundColor:t.brandSoft,marginHorizontal:r.lg,marginTop:r.xs,marginBottom:r.md},timelineBandText:{flex:1,...R(l.caption,c.normal,t.text.secondary)},timelineSeparator:{height:d,backgroundColor:t.brandBorder,marginLeft:ji},timelineRow:{flexDirection:"row",gap:r.md,paddingHorizontal:r.lg,paddingVertical:r.md+r.xs/2},timelineBubble:{width:r.xxl+r.xs/2,height:r.xxl+r.xs/2,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:d,borderColor:t.brandBorder},timelineBody:{flex:1,gap:r.xs-1},timelineKind:{...k(e,"mono"),fontSize:l.micro,lineHeight:l.bodyTight,letterSpacing:n.letterSpacing.eyebrow/3,textTransform:"uppercase",color:t.text.secondary},timelineTitle:{...R(l.body,c.normal,t.text.primary,"medium")}})}i(pb,"makeStyles");function Hs(e,t={}){let r=mr(),{userRef:o}=ke(),n=t.now??Date.now,[a,l]=useState(null),[c,s]=useState(true),[d,u]=useState(null),[p,f]=useState(null),b=p===true,[R,v]=useState({}),[w,g]=useState(false),[y,x]=useState(null),[h,I]=useState(false),[S,T]=useState(false),C=$n(e),A=useRef(0),F=useRef(true),q=useCallback(async()=>{let D=A.current+=1;if(s(true),u(null),o===null){l(null),s(false);return}let E=await r.listShares(e);D!==A.current||!F.current||(E.ok?(l(E.value),f(true)):Tr(E.error)?(l(null),f(false)):(l(null),u(E.error),Bd(E)&&f(true)),s(false));},[r,e,o]);useEffect(()=>(F.current=true,q(),()=>{F.current=false,A.current+=1;}),[q]);let U=useRef(C);useEffect(()=>{U.current!==C&&(U.current=C,v({}),T(true),q());},[C,q]);let j=useCallback(async()=>{g(true);let D=await r.createShare(e);return F.current&&(g(false),D.ok?(v(E=>({...E,[D.value.shareId]:D.value.shareUrl})),q()):Tr(D.error)?f(false):sr(D.error)&&T(true)),D},[r,e,q]),ae=useCallback(async D=>{x(D);let E=await r.revokeShare(e,D);return F.current&&(x(null),q()),E},[r,e,q]),ne=useCallback(async()=>{I(true);let D=await r.getPdfLink(e);return F.current&&(I(false),!D.ok&&sr(D.error)&&T(true)),D},[r,e]),Re=useCallback(()=>{T(false),q();},[q]),te=useMemo(()=>$l(a??[],R,n()),[a,R,n]),_=c?"loading":d!==null?"error":te.length===0?"empty":"populated";return useMemo(()=>({status:_,rows:te,available:b,consentRequired:S,error:d,creating:w,revokingId:y,preparingPdf:h,createLink:j,revoke:ae,pdfLink:ne,refresh:Re}),[_,te,b,S,d,w,y,h,j,ae,ne,Re])}i(Hs,"useRecordShares");function Bd(e){return e.ok||e.error.httpStatus!==void 0&&e.error.httpStatus!==404}i(Bd,"answeredBehindGate");function Hd(e){return e.available||e.status!=="empty"}i(Hd,"sharesListShown");function Us(e){let t=mr(),{userRef:r}=ke(),o=useMemo(()=>({}),[t,e,r]),[n,a]=useState({scope:o,lit:null});useEffect(()=>{if(r===null)return;let c=true;return t.listShares(e).then(s=>{c&&(!s.ok&&Tr(s.error)?a({scope:o,lit:false}):Bd(s)&&a({scope:o,lit:true}));},()=>{}),()=>{c=false;}},[t,e,r,o]);let l=n.scope===o?n.lit:null;return useMemo(()=>({lit:l}),[l])}i(Us,"useRecordsDepthProbe");function js(e){let t=mr(),o=Us(e).lit===true,[n,a]=useState(false),[l,c]=useState(null),s=useRef(true);useEffect(()=>(s.current=true,()=>{s.current=false;}),[]);let d=useCallback(async()=>{a(true),c(null);let u=await t.getPdfLink(e);return s.current&&(a(false),u.ok||c(u.error)),u},[t,e]);return useMemo(()=>({preparing:n,available:o,error:l,pdfLink:d}),[n,o,l,d])}i(js,"useRecordPdfLink");async function jd(e){await Share.share({message:ie.shareMessage(e),url:e});}i(jd,"shareLinkViaOs");async function Yo(e){await Share.share(Platform.OS==="ios"?{url:e}:{message:e});}i(Yo,"shareFileLinkViaOs");var Pt=K.document,Gd=Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),bb=i((e,t)=>e.getRecordDepth(t),"readDepth"),hb=i(e=>!e.available,"depthEmpty");function $s(e){let{style:t,renderPending:r,...o}=Oe(e,["onBack"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(vb,{...o,style:t})})}i($s,"EverfurRecordDocument");function Rb(e,t){return e.identity.length===0&&e.entities.length===0&&e.forwardLooking.length===0&&(t===null||t.labResults.length===0&&t.physicalExams.length===0&&t.clinicianNotes.length===0)}i(Rb,"documentIsEmpty");function vb({petRef:e,petName:t,controller:r,consentVersion:o,onBack:n,onOpenUrl:a,style:l}){let c=ue(),s=Yd(),d=V(),u=st(r?{petRef:e,controller:r}:{petRef:e}),p=Gt(e,bb,hb),f=js(e),b=useMemo(()=>Hr(o,u.consent),[o,u.consent]),R=useMemo(()=>nn(u,o),[u,o]),v=p.value!==null&&!p.value.withheld&&p.value.available?p.value:null,w=u.record,[g,y]=useState(false),x=i(()=>{y(false),f.pdfLink().then(S=>{if(!S.ok)return;Or(a??(C=>Yo(C)),S.value.downloadUrl,"record_pdf").then(C=>{!C.ok&&!a&&y(true);});});},"download"),h,I=false;if(u.status==="loading"||p.status==="loading"&&w!==null)h=jsx(View,{style:s.centered,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:mt.loading,testID:"record-document-loading",children:jsx(ActivityIndicator,{color:d.color.brandInk})});else if(u.status==="error"){let S=_r(u,b);h=S.kind==="error"||S.kind==="pet_not_found"?jsx(Ue,{variant:pt(S.error),message:S.error.displayMessage,onAction:S.error.retryable?()=>{u.refresh(),p.refresh();}:void 0,testID:"record-document-error"}):rn(u,R,b);}else w===null||Rb(w,v)?h=jsx(View,{style:s.centered,testID:"record-document-empty",children:jsx(m,{style:s.emptyText,children:Pt.empty})}):(I=true,h=jsx(wb,{record:w,depth:v,petName:t,wordmark:d.meta.displayName}));return jsxs(View,{style:[c.root,s.root,l],children:[jsx(Ke,{title:Pt.title,variant:"document",onBack:n,testID:"record-document-header",right:f.available&&I?jsx(Pressable,{onPress:x,disabled:f.preparing,accessibilityRole:"button",accessibilityLabel:Pt.download,accessibilityState:{disabled:f.preparing,busy:f.preparing},hitSlop:8,style:s.download,testID:"record-document-download",children:f.preparing?jsx(ActivityIndicator,{size:"small",color:d.color.brandInk}):jsx(Nl,{})}):void 0}),f.error?jsx(m,{style:[c.errorText,s.inset],accessibilityRole:"alert",children:f.error.displayMessage}):g?jsx(m,{style:[c.errorText,s.inset],accessibilityRole:"alert",testID:"record-document-share-failed",children:ie.toasts.pdfShareSheet}):null,jsx(View,{style:c.body,children:h}),jsx(Ve,{})]})}i(vb,"DocumentBody");function wb({record:e,depth:t,petName:r,wordmark:o}){let n=Yd(),a=useMemo(()=>{let s=[],d=new Map;for(let f of e.entities){let b=f.category.trim();if(b.length===0)continue;let R=d.get(b);R===void 0?(s.push(b),d.set(b,[f])):R.push(f);}let u=Gd.filter(f=>s.includes(f)),p=s.filter(f=>!Gd.includes(f));return [...u,...p].map(f=>({type:f,rows:d.get(f)??[]}))},[e.entities]),l=Date.now(),c=i((s,d,u)=>jsxs(View,{style:n.section,testID:u,children:[jsxs(View,{style:n.sectionHeader,children:[jsx(m,{style:n.sectionTitle,accessibilityRole:"header",children:s}),jsx(View,{style:n.rule})]}),jsx(View,{children:d})]},u),"section");return jsxs(ScrollView,{contentContainerStyle:n.page,showsVerticalScrollIndicator:false,testID:"record-document",children:[jsxs(View,{style:n.letterhead,children:[jsx(m,{style:n.wordmark,children:o}),jsx(m,{style:n.docTitle,children:Pt.docTitle}),jsx(m,{style:n.petName,children:r?.trim()||Pt.namelessPet}),jsx(m,{style:n.generated,children:Pt.generated(e.generatedAt)})]}),e.identity.length>0?c(Pt.identity,e.identity.map((s,d)=>jsxs(View,{style:[n.row,d>0?n.rowDivider:null],children:[jsx(m,{style:n.rowLabel,children:s.label}),jsx(m,{style:n.rowValue,children:s.value})]},`${d}:${s.label}`)),"record-document-identity"):null,t&&t.labResults.length>0?c(Pt.labs,t.labResults.map((s,d)=>{let u=rr(s.latest.status),p=ld(s.points[s.points.length-1]??null),f=kt(s.latest.value,s.latest.unit??s.unit,s.latest.qualitativeResult);return jsxs(View,{style:[n.row,u.outOfRange?n.rowFlag:null,d>0?n.rowDivider:null],children:[jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:s.name}),jsxs(m,{style:n.rowMeta,children:[p?Pt.ref(p):Pt.noRange,s.latest.at?` \xB7 ${Y(s.latest.at)}`:""]})]}),jsxs(View,{style:n.rowRight,children:[f!=="-"?jsx(m,{style:[n.rowValue,u.outOfRange?n.rowValueAlert:null],children:f}):null,jsx(m,{style:[n.markerStatus,u.outOfRange?n.rowValueAlert:null],children:u.label})]})]},s.markerId)}),"record-document-labs"):null,a.map(({type:s,rows:d})=>c(jr(s),d.map((u,p)=>{let f=[Yr(u.value,u.unit),u.observedAt?Y(u.observedAt):null].filter(b=>b&&b.length>0).join(" \xB7 ");return jsx(View,{style:[n.row,p>0?n.rowDivider:null],children:jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:u.label}),f?jsx(m,{style:n.rowMeta,children:f}):null]})},u.key)}),`record-document-${s}`)),e.forwardLooking.length>0?c(Pt.upcomingCare,e.forwardLooking.map((s,d)=>{let u=An(s.dueAt,l);return jsxs(View,{style:[n.row,d>0?n.rowDivider:null],children:[jsxs(View,{style:n.rowMain,children:[jsx(m,{style:n.rowLabel,children:s.title}),s.detail?jsx(m,{style:n.rowMeta,children:s.detail}):null]}),u?jsx(m,{style:[n.rowValue,u.overdue?n.rowValueAlert:null],children:u.label}):null]},`${s.title}-${d}`)}),"record-document-upcoming"):null,t&&t.physicalExams.length>0?c(Pt.physicalExams,t.physicalExams.map((s,d)=>jsxs(View,{style:[n.block,d>0?n.rowDivider:null],children:[s.observedOn?jsx(m,{style:n.blockDate,children:Y(s.observedOn)}):null,s.systems.filter(u=>u.finding).map(u=>jsxs(View,{style:n.fieldRow,children:[jsx(m,{style:n.fieldLabel,children:qr(u.system)}),jsx(m,{style:n.fieldValue,children:u.finding})]},u.system))]},s.examId)),"record-document-exams"):null,t&&t.clinicianNotes.length>0?c(Pt.clinicianNotes,t.clinicianNotes.map((s,d)=>jsxs(View,{style:[n.block,d>0?n.rowDivider:null],children:[s.observedOn?jsx(m,{style:n.blockDate,children:Y(s.observedOn)}):null,s.sections.filter(u=>u.text).map((u,p)=>jsxs(View,{style:n.noteSection,children:[jsx(m,{style:n.noteLabel,children:Qr(u.section)}),jsx(m,{style:n.noteBody,children:u.text})]},`${u.section}-${p}`))]},s.noteId)),"record-document-notes"):null,e.disclaimer.length>0?jsx(View,{style:n.disclaimer,children:jsx(m,{style:n.disclaimerText,children:e.disclaimer})}):null]})}i(wb,"RecordDocument");function Yd(){let e=V();return useMemo(()=>xb(e),[e])}i(Yd,"useLocalStyles");function xb(e){let{color:t,space:r,radius:o,type:n}=e,a=StyleSheet.hairlineWidth,l=i((s,d,u,p="regular")=>({...k(e,p),fontSize:s,lineHeight:Math.round(s*d),color:u}),"text"),c=i((s,d)=>({...k(e,"mono"),fontSize:s,lineHeight:s+r.xs-1,color:d,letterSpacing:n.letterSpacing.eyebrow/2,textTransform:"uppercase"}),"mono");return StyleSheet.create({root:{backgroundColor:t.surface},inset:{paddingHorizontal:r.lg},download:{width:r.xxl+r.xs+r.xs/2,height:r.xxl+r.xs+r.xs/2,borderRadius:o.pill,alignItems:"center",justifyContent:"center"},centered:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:r.xxl,minHeight:r.xxl*3+r.xl},emptyText:{...l(n.size.body,n.lineHeight.normal,t.text.muted,"medium"),textAlign:"center"},page:{paddingHorizontal:r.lg+r.xs,paddingBottom:r.xxl+r.lg},letterhead:{alignItems:"center",paddingTop:r.md,paddingBottom:r.lg+r.xs+r.xs/2,borderBottomWidth:2,borderBottomColor:t.brand,gap:r.xs+r.xs/2,marginBottom:r.sm},wordmark:{...l(n.size.heading,n.lineHeight.snug,t.brandInk,"bold"),letterSpacing:n.letterSpacing.headerBrand},docTitle:{...c(n.size.caption,t.brandInk),marginTop:r.sm+r.xs/2,letterSpacing:n.letterSpacing.eyebrow+.4},petName:l(n.size.verdict+r.xs/2,n.lineHeight.tight,t.text.primary),generated:{...c(n.size.tiny,t.text.muted),textTransform:"none"},section:{marginTop:r.lg+r.xs+r.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:r.sm+r.xs/2,marginBottom:r.sm},sectionTitle:c(n.size.tiny,t.brandInk),rule:{flex:1,height:a,backgroundColor:t.borderHairlineGreen},row:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.md+r.xs/2,paddingVertical:r.sm+1},rowDivider:{borderTopWidth:a,borderTopColor:t.borderHairlineGreen},rowFlag:{backgroundColor:t.badgeBgCritical,marginHorizontal:-r.sm,paddingHorizontal:r.sm,borderRadius:o.xs},rowMain:{flexShrink:1},rowRight:{alignItems:"flex-end",gap:r.xs/2},rowLabel:{flexShrink:1,...l(n.size.body,n.lineHeight.normal,t.text.primary,"medium")},rowValue:{...l(n.size.body,n.lineHeight.normal,t.text.primary,"bold"),textAlign:"right"},rowValueAlert:{color:t.danger},rowMeta:{marginTop:r.xs/2,...k(e,"mono"),fontSize:n.size.tiny,lineHeight:n.size.body,color:t.text.muted},markerStatus:c(n.size.micro,t.text.muted),block:{paddingVertical:r.sm+r.xs/2},blockDate:{...c(n.size.tiny,t.text.muted),marginBottom:r.xs+r.xs/2},fieldRow:{flexDirection:"row",alignItems:"flex-start",gap:r.md+r.xs/2,paddingVertical:r.xs-1},fieldLabel:{width:120,...l(n.size.bodyTight,n.lineHeight.normal,t.text.muted,"medium")},fieldValue:{flex:1,...l(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")},noteSection:{marginTop:r.sm},noteLabel:{...c(n.size.tiny,t.brandInk),marginBottom:r.xs/2},noteBody:l(n.size.bodyTight,n.lineHeight.relaxed,t.text.primary),disclaimer:{marginTop:o.xl,paddingTop:r.md+r.xs/2,borderTopWidth:a,borderTopColor:t.borderHairlineGreen},disclaimerText:l(n.size.tiny,n.lineHeight.relaxed,t.text.muted)})}i(xb,"makeLocalStyles");function Jd({petRef:e,onClose:t,onNavigate:r,onOpenUrl:o,onCopy:n}){let a=kb(),l=ue(),c=Hs(e),[s,d]=useState(null),[u,p]=useState(null),f=c.available&&!c.consentRequired,b=i((y,x)=>{let h=o??((S,T)=>T==="share_link"?jd(S):Yo(S)),I=x==="share_link"?ie.toasts.shareSheet:ie.toasts.pdfShareSheet;Or(h,y,x).then(S=>{S.ok||d(I);});},"open"),R=i(()=>{d(null),c.createLink().then(y=>{y.ok?b(y.value.shareUrl,"share_link"):d(ao(y.error,"create"));});},"onCreateLink"),v=i(()=>{d(null),c.pdfLink().then(y=>{y.ok?b(y.value.downloadUrl,"record_pdf"):d(ao(y.error,"download"));});},"onDownload"),w=i(y=>{!n||y.shareUrl===null||Or(n,y.shareUrl).then(x=>d(x.ok?ie.toasts.copied:ie.toasts.copyFailed));},"onCopyRow"),g=i(y=>{c.revoke(y).then(x=>{p(null),d(x.ok?ie.toasts.turnedOff:ao(x.error,"revoke"));});},"onConfirmRevoke");return jsx(Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:t,children:jsxs(View,{style:a.backdrop,children:[jsx(Pressable,{style:Lo,accessibilityRole:"button",accessibilityLabel:ie.closeSheetA11y,onPress:t}),jsxs(View,{style:a.sheet,accessibilityViewIsModal:true,testID:"share-record-sheet",children:[jsx(View,{style:a.handle}),jsxs(View,{style:a.header,children:[jsxs(View,{style:a.headerText,children:[jsx(m,{style:a.title,accessibilityRole:"header",children:ie.title}),jsx(m,{style:a.helper,children:ie.helper})]}),jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:ie.close,onPress:t,hitSlop:12,style:a.closeButton,testID:"share-record-close",children:jsx(m,{style:a.closeGlyph,children:"\xD7"})})]}),jsxs(ScrollView,{style:a.scroll,contentContainerStyle:a.body,showsVerticalScrollIndicator:false,children:[jsxs(View,{style:a.actions,children:[r?jsx(J,{label:ie.viewDocument,onPress:()=>{t(),r({name:"document"});},testID:"share-view-document"}):null,f?jsx(J,{label:c.creating?ie.creatingLink:ie.createLink,kind:"outline",busy:c.creating,onPress:R,testID:"share-create-link"}):null,f?jsx(J,{label:c.preparingPdf?ie.preparingPdf:ie.downloadPdf,kind:"outline",busy:c.preparingPdf,onPress:v,testID:"share-download-pdf"}):null]}),c.consentRequired?jsxs(View,{style:a.stateCard,testID:"share-consent-off",children:[jsx(m,{style:a.stateTitle,accessibilityRole:"header",children:ie.consentOffTitle}),jsx(m,{style:a.stateBody,children:ie.consentOffBody}),jsx(J,{label:ie.retry,kind:"outline",onPress:c.refresh,testID:"share-consent-retry"})]}):null,s?jsx(m,{style:a.notice,accessibilityRole:"alert",accessibilityLiveRegion:"polite",testID:"share-notice",children:s}):null,Hd(c)?jsxs(View,{style:a.section,children:[jsx(m,{style:a.sectionLabel,accessibilityRole:"header",children:ie.activeLinks}),c.status==="loading"?jsx(Xl,{testID:"share-record-loading"}):c.status==="error"?jsxs(View,{style:a.stateCard,testID:"share-record-error",children:[jsx(m,{style:a.stateTitle,children:ie.errorTitle}),jsx(m,{style:a.stateBody,children:ie.errorBody}),jsx(J,{label:ie.retry,kind:"outline",onPress:c.refresh,testID:"share-record-retry"})]}):c.rows.length===0?jsxs(View,{style:a.stateCard,testID:"share-record-empty",children:[jsx(m,{style:a.stateTitle,children:ie.emptyTitle}),jsx(m,{style:a.stateBody,children:ie.emptyBody})]}):jsx(View,{style:a.list,children:c.rows.map(y=>jsxs(View,{style:a.row,testID:`share-row-${y.shareId}`,children:[jsxs(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:y.a11yLabel,children:[jsxs(View,{style:a.statusLine,children:[jsx(View,{style:[a.statusDot,{backgroundColor:y.active?a.active.color:a.inactive.color}],accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:a.status,children:y.statusLabel}),jsx(m,{style:a.expiry,children:y.expiryLabel})]}),y.createdLabel?jsx(m,{style:a.created,children:y.createdLabel}):null]}),y.shareUrl!==null&&!n?jsx(m,{selectable:true,style:a.url,testID:`share-url-${y.shareId}`,children:y.shareUrl}):null,u===y.shareId?jsxs(View,{style:a.confirm,testID:`share-revoke-confirm-${y.shareId}`,children:[jsx(m,{style:a.confirmText,children:ie.confirmTurnOff}),jsxs(View,{style:a.rowActions,children:[jsx(J,{label:c.revokingId===y.shareId?ie.turningOff:ie.turnOff,kind:"danger",busy:c.revokingId===y.shareId,onPress:()=>g(y.shareId),testID:`share-revoke-do-${y.shareId}`}),jsx(J,{label:ie.keep,kind:"outline",disabled:c.revokingId===y.shareId,onPress:()=>p(null),testID:`share-revoke-cancel-${y.shareId}`})]})]}):jsxs(View,{style:a.rowActions,children:[n?jsx(J,{label:ie.copyLink,kind:"outline",disabled:y.shareUrl===null,accessibilityLabel:ie.copyLinkA11y(y.actionContext),onPress:()=>w(y),testID:`share-copy-${y.shareId}`}):null,jsx(J,{label:ie.turnOff,kind:"danger",accessibilityLabel:ie.turnOffA11y(y.actionContext),onPress:()=>p(y.shareId),testID:`share-ask-revoke-${y.shareId}`})]})]},y.shareId))})]}):null]}),jsx(View,{style:l.inset})]})]})})}i(Jd,"ShareSheet");function kb(){let e=V();return useMemo(()=>Tb(e),[e])}i(kb,"useStyles");function Tb(e){let{color:t,space:r,radius:o,type:n}=e,a=r.xxl+r.md,l=StyleSheet.hairlineWidth,c=i((s,d,u,p="regular")=>({...k(e,p),fontSize:s,lineHeight:Math.round(s*d),color:u}),"text");return StyleSheet.create({active:{color:t.success},inactive:{color:t.text.muted},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:"rgba(0,0,0,0.4)"},sheet:{backgroundColor:t.surface,borderTopLeftRadius:o.xl-1,borderTopRightRadius:o.xl-1,paddingHorizontal:r.lg+r.xs+r.xs/2,paddingTop:r.md,paddingBottom:o.xl,maxHeight:"88%",gap:r.md},handle:{alignSelf:"center",width:r.xxl+r.xs,height:r.xs,borderRadius:o.pill,backgroundColor:t.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:r.sm},headerText:{flex:1,gap:r.xs},title:{...c(n.size.heading,n.lineHeight.snug,t.text.primary,"bold")},helper:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),closeButton:{width:a,height:a,alignItems:"center",justifyContent:"center"},closeGlyph:c(n.size.verdict,n.lineHeight.tight,t.text.primary),scroll:{flexGrow:0},body:{gap:r.lg,paddingBottom:r.sm},actions:{gap:r.sm},notice:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.secondary),padding:r.md,borderRadius:o.md-r.xs/2,backgroundColor:t.brandSoft},section:{gap:r.sm},sectionLabel:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:n.letterSpacing.eyebrow/2},stateCard:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:l,borderColor:t.brandBorder},stateTitle:{...c(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},stateBody:c(n.size.bodyTight,n.lineHeight.normal,t.text.muted),list:{gap:r.md},row:{gap:r.sm,padding:r.md,borderRadius:o.md,backgroundColor:t.surfaceCream,borderWidth:l,borderColor:t.brandBorder},statusLine:{flexDirection:"row",alignItems:"center",gap:r.sm},statusDot:{width:r.sm,height:r.sm,borderRadius:r.xs},status:{...c(n.size.bodyTight,n.lineHeight.snug,t.text.primary,"bold")},expiry:{...c(n.size.caption,n.lineHeight.normal,t.text.muted)},created:c(n.size.tiny,n.lineHeight.normal,t.text.muted),url:{...c(n.size.caption,n.lineHeight.normal,t.text.secondary,"mono")},rowActions:{flexDirection:"row",flexWrap:"wrap",gap:r.sm},confirm:{gap:r.sm},confirmText:{...c(n.size.bodyTight,n.lineHeight.normal,t.text.primary,"medium")}})}i(Tb,"makeStyles");var Ib=i((e,t)=>e.getRecordDepth(t),"readDepth"),Db=i(e=>!e.available,"depthEmpty");function Ys(e){let{style:t,renderPending:r,...o}=Oe(e,["onNavigate","onBack","onAsk"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(Ab,{...o,style:t})})}i(Ys,"EverfurRecordDetail");function Ab({petRef:e,petName:t,controller:r,consentVersion:o,onNavigate:n,onBack:a,onAsk:l,onOpenUrl:c,onCopy:s,style:d}){let u=ue(),p=Ob(),f=st(r?{petRef:e,controller:r}:{petRef:e}),b=Gt(e,Ib,Db),R=Cs(e),v=Us(e),[w,g]=useState(false),y=useMemo(()=>Hr(o,f.consent),[o,f.consent]),x=useMemo(()=>nn(f,o),[f,o]),h=b.value!==null&&!b.value.withheld&&b.value.available?b.value:null,I=f.record,S=i(()=>{f.refresh(),b.refresh();},"retry"),T=n!==void 0||v.lit===true,C;if(f.status==="loading"||b.status==="loading"&&I!==null&&!I.isEmpty)C=jsx(uo,{testID:"everfur-record-loading"});else if(f.status==="error"){let A=_r(f,y);C=A.kind==="error"||A.kind==="pet_not_found"?jsx(Ue,{variant:pt(A.error),message:A.error.displayMessage,onAction:A.error.retryable?S:void 0,testID:"everfur-record-error"}):rn(f,x,y);}else if(I===null||I.isEmpty){let A=h?.completeness?.documentsInReview??0;C=jsxs(ScrollView,{contentContainerStyle:u.content,testID:"everfur-record-empty",children:[jsx(Ue,{variant:"no_records",message:A>0?K.inReview(A):void 0}),jsx(kr,{disclaimer:I?.disclaimer??""})]});}else C=jsx(ScrollView,{contentContainerStyle:p.content,testID:"everfur-record",children:jsx(Fo,{record:I,depth:h,petName:t,onNavigate:n,onAsk:l,factEdit:R})});return jsxs(View,{style:[u.root,d],children:[jsx(Ke,{title:K.title,onBack:a,testID:"everfur-record-header",right:T||n?jsxs(Fragment,{children:[n?jsx(Pressable,{onPress:()=>n({name:"clinicBatch"}),accessibilityRole:"button",accessibilityLabel:K.requestClinicsA11y,hitSlop:8,style:p.share,testID:"everfur-record-request-clinics",children:jsx(Fl,{})}):null,T?jsx(Pressable,{onPress:()=>g(true),accessibilityRole:"button",accessibilityLabel:K.shareA11y,hitSlop:8,style:p.share,testID:"everfur-record-share",children:jsx(zl,{})}):null]}):void 0}),jsx(View,{style:u.body,children:C}),w?jsx(Jd,{petRef:e,onClose:()=>g(false),onNavigate:n,...c?{onOpenUrl:c}:{},...s?{onCopy:s}:{}}):null,jsx(Ve,{})]})}i(Ab,"RecordBody");function Ob(){let e=V();return useMemo(()=>Lb(e),[e])}i(Ob,"useLocalStyles");function Lb(e){let{space:t,radius:r}=e;return StyleSheet.create({content:{paddingHorizontal:t.lg,paddingBottom:t.xxl+t.sm,gap:t.lg+t.xs},share:{width:t.xxl+t.sm,height:t.xxl+t.sm,borderRadius:r.pill,alignItems:"center",justifyContent:"center"}})}i(Lb,"makeLocalStyles");function ru(e,t){let r=V(),[o,n]=useState(false),a=useCallback(()=>{n(true),e().finally(()=>n(false));},[e]);return jsx(RefreshControl,{refreshing:o,onRefresh:a,tintColor:r.color.brandInk,colors:[r.color.brandInk],testID:t})}i(ru,"useRecordsPullToRefresh");function Qs(e){let{style:t,renderPending:r,...o}=Oe(e,["onNavigate","onBack"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(Hb,{...o,style:t})})}i(Qs,"EverfurRecordsUpload");function Hb({petRef:e,petName:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:a,onBack:l,style:c}){let s=ue(),d=su(),{runtime:u}=ke(),p=st(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),f=In(o)&&(r!==void 0||n!==void 0||Hn(u.registry.services.uploadTransport));return jsxs(View,{style:[s.root,c],children:[jsx(Ke,{title:"",onBack:l,testID:"upload-header"}),jsxs(ScrollView,{contentContainerStyle:d.content,testID:"upload-screen",children:[jsxs(View,{style:d.header,children:[jsx(View,{style:d.iconBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),jsx(m,{style:d.title,accessibilityRole:"header",children:ot.title(t)}),jsx(m,{style:d.subtitle,children:ot.subtitle(t)})]}),jsx(Xs,{records:p,requestId:null,onPickDocument:o,canUpload:f,onDone:a?b=>a({name:"request",requestId:b}):void 0})]}),jsx(Ve,{})]})}i(Hb,"UploadBody");function Xs({records:e,requestId:t,onPickDocument:r,canUpload:o,onDone:n}){let a=ue(),l=su(),[c,s]=useState(null),[d,u]=useState(0),p=useRef(t),f=useRef([]),b=e.uploadQueue.filter(h=>h.status!=="skipped"),R=b.filter(h=>h.status==="done").length,v=b.filter(h=>h.status==="failed").length,w=!e.isUploading&&d>0,g=useCallback(async h=>{let{uploadable:I,skipped:S}=Na(h),T=No(S);if(I.length===0){T!==null&&s(T);return}s(T);let C=p.current;if(C===null){let F=await e.createRequest(`records-upload-${Date.now().toString(36)}`);if(!F.ok){s(ot.errors.start);return}C=F.value.id,p.current=C;}u(F=>F+1);let A=await e.uploadDocuments(C,I);f.current=A.flatMap((F,q)=>F.status==="failed"&&I[q]!==void 0?[I[q]]:[]);},[e]),y=useCallback(()=>{!r||!o||Or(r).then(h=>{if(!h.ok){s(ot.errors.startPlain);return}let I=h.value;I!==null&&g(Array.isArray(I)?I:[I]);});},[r,o,g]),x=useCallback(()=>{g(f.current);},[g]);return jsxs(View,{style:l.card,testID:"records-upload-card",children:[jsx(m,{style:l.cardTitle,accessibilityRole:"header",children:ot.cardTitle}),jsx(m,{style:l.cardSubtitle,children:ot.cardSubtitle}),c?jsx(View,{style:a.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:a.errorText,children:c})}):null,jsx(kd,{records:e}),e.isUploading?jsx(View,{style:l.uploadingRow,children:jsx(m,{style:l.progressText,children:ot.uploading(R,b.length)})}):w?jsxs(View,{style:l.settled,children:[R>0?jsx(m,{style:l.success,accessibilityRole:"alert",children:ot.received(R)}):null,v>0?jsx(J,{label:ot.retryFailed(v),kind:"link",accessibilityLabel:ot.retryFailedA11y(v),onPress:x,testID:"records-upload-retry-failed"}):null,jsxs(View,{style:l.settledActions,children:[jsx(J,{label:ot.addMore,kind:"link",accessibilityLabel:ot.addMoreA11y,disabled:!o,onPress:y,testID:"records-upload-another"}),n&&p.current!==null&&R>0?jsx(J,{label:ot.done,accessibilityLabel:ot.doneA11y,onPress:()=>n(p.current),testID:"records-upload-done"}):null]})]}):jsx(J,{label:ot.chooseFiles,accessibilityLabel:ot.chooseFilesA11y,disabled:!o,onPress:y,testID:"records-upload-choose"})]})}i(Xs,"UploadRecordCard");function su(){let e=V();return useMemo(()=>Ub(e),[e])}i(su,"useLocalStyles");function Ub(e){let{color:t,space:r,radius:o,type:n}=e,a=i((l,c,s,d="regular")=>({...k(e,d),fontSize:l,lineHeight:Math.round(l*c),color:s}),"text");return StyleSheet.create({content:{padding:r.lg+r.xs,gap:r.lg+r.xs},header:{gap:r.sm,alignItems:"center"},iconBubble:{width:r.xxl+r.lg+r.xs,height:r.xxl+r.lg+r.xs,borderRadius:o.pill,backgroundColor:t.brandSoft,borderWidth:StyleSheet.hairlineWidth,borderColor:t.brandBorder,marginBottom:r.xs},title:{...a(n.size.heading+r.xs/2,n.lineHeight.snug,t.brandInk,"bold"),textAlign:"center"},subtitle:{...a(n.size.body,n.lineHeight.normal,t.text.muted),textAlign:"center",maxWidth:340},card:{borderRadius:o.md,backgroundColor:t.surface,borderWidth:1,borderColor:t.brandSoft,padding:r.lg,gap:r.md},cardTitle:{...a(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")},cardSubtitle:a(n.size.bodyTight,n.lineHeight.normal,t.text.muted),uploadingRow:{flexDirection:"row",alignItems:"center",gap:r.sm},progressText:{flex:1,...a(n.size.bodyTight,n.lineHeight.normal,t.text.secondary)},settled:{gap:r.sm},success:a(n.size.bodyTight,n.lineHeight.normal,t.text.primary),settledActions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:r.sm}})}i(Ub,"makeLocalStyles");function Zs(e){let{style:t,renderPending:r,...o}=Oe(e,["onNavigate","onBack"]);return jsx(Le,{capability:"records",style:t,...r?{renderPending:r}:{},...ze(o.onBack,Ye),children:jsx(Qb,{...o,style:t})})}i(Zs,"EverfurRecordsRequest");function Qb({petRef:e,requestId:t,controller:r,onPickDocument:o,uploadTransport:n,onNavigate:a,onBack:l,style:c,nowMs:s}){let d=ue(),{runtime:u,userRef:p,scopeEpoch:f}=ke(),b=st(r?{petRef:e,controller:r}:n?{petRef:e,uploadTransport:n}:{petRef:e}),R=b.requests.find(x=>x.id===t)??null,v=In(o)&&(r!==void 0||n!==void 0||Hn(u.registry.services.uploadTransport)),w=R?So(R):"",g=ru(b.refresh,"records-request-refresh"),y;return b.status==="loading"&&R===null?y=jsx(po,{testID:"records-request-loading"}):b.status==="error"&&b.error?y=jsx(Ue,{variant:pt(b.error),message:b.error.displayMessage,onAction:b.error.retryable?b.refresh:void 0,testID:"records-request-error"}):R===null?y=jsx(Ue,{variant:"no_requests",testID:"records-request-missing"}):p===null?y=jsx(Ue,{variant:"error",testID:"records-request-error"}):y=jsx(Xb,{request:R,records:b,canUpload:v,onPickDocument:o,onNavigate:a,nowMs:s,refreshControl:g},JSON.stringify([p,f,R.id])),jsxs(View,{style:[d.root,c],children:[jsx(Ke,{title:w,onBack:l,testID:"records-request-header"}),jsx(KeyboardAvoidingView,{behavior:"padding",style:d.body,children:y}),jsx(Ve,{})]})}i(Qb,"RequestBody");function Xb({request:e,records:t,canUpload:r,onPickDocument:o,onNavigate:n,nowMs:a,refreshControl:l}){let c=ue(),s=Jb(),d=V(),u=wd({request:e,onRecovered:t.refresh,canUpload:r},Ut()),[p,f]=useState(null),[b,R]=useState(false),[v,w]=useState(null),g=useRef(true);useEffect(()=>(g.current=true,()=>{g.current=false;}),[]);let y=u.request,x=a??Date.now(),h=y.status==="published",I=y.status==="published"||y.status==="failed"||y.status==="revoked",S=Ti(y),T=y.wireStatus==="clinic_responded_no_records",C=il(y,x),A=ki(y,x),F=I?null:y.waitingExpectation?.trim()||null,q=ko(y),U=sl(y),j=u.canConvert,ae=I&&!h,ne=u.error!==null&&p!==null&&p!=="start"?p==="revoke"?be.errors.cancel:be.errors[p]:null,Re=i((_,D)=>{f(_),D();},"run"),te=i(()=>{b||(R(true),w(null),t.createRequest(`records-upload-${Date.now().toString(36)}`).then(_=>{if(g.current){if(R(false),!_.ok){w(be.errors.start);return}n?.({name:"request",requestId:_.value.id});}}));},"startFresh");return jsxs(ScrollView,{contentContainerStyle:s.content,keyboardShouldPersistTaps:"handled",refreshControl:l,testID:`records-request-${y.id}`,children:[jsx(Ho,{request:y}),y.status==="awaiting_upload"?jsx(Xs,{records:t,requestId:y.id,onPickDocument:o,canUpload:r}):null,y.statusLabel.length>0?jsx(View,{style:c.statusCard,accessibilityRole:"summary",children:jsx(m,{style:c.statusText,children:y.statusLabel})}):null,F&&!C?jsx(View,{style:c.infoNote,accessibilityRole:"summary",children:jsx(m,{style:c.infoNoteText,children:F})}):y.wireStatus==="awaiting_response"&&!C?jsx(View,{style:c.infoNote,accessibilityRole:"summary",children:jsx(m,{style:c.infoNoteText,children:be.awaitingNote})}):null,C?jsx(View,{style:c.cautionNote,accessibilityRole:"summary",testID:"records-request-waiting-banner",children:jsx(m,{style:c.cautionNoteText,children:be.waitingBanner(A)})}):null,h&&n?jsx(J,{label:be.viewRecords,onPress:()=>n({name:"dashboard"}),style:s.readyCta,testID:"records-request-view-dashboard"}):null,U?jsxs(View,{style:[s.failureCard,S?s.failureCritical:s.failureCaution],accessibilityRole:"summary",testID:"records-failure-card",children:[jsx(m,{style:[s.failureTitle,S?s.failureTitleCritical:s.failureTitleCaution],children:ol(y)}),y.canUpdateClinicEmail!==true&&y.canRetrySend!==true?jsx(m,{style:c.rowDetail,children:be.nextStep}):null,y.canUpdateClinicEmail===true?jsxs(View,{style:s.emailBlock,children:[jsx(m,{style:c.fieldLabel,children:qt.email}),jsx(He,{style:c.field,accessibilityLabel:qt.email,placeholder:qt.emailPlaceholder,placeholderTextColor:d.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,value:u.email,editable:!u.busy,onChangeText:u.setEmail,testID:"records-failure-clinic-email"}),u.emailInvalid?jsx(m,{style:c.errorText,accessibilityRole:"alert",children:be.errors.invalidEmail}):null,jsx(J,{label:qt.updateEmail,accessibilityLabel:qt.updateEmailA11y,disabled:!u.canUpdateEmail,busy:u.busy&&p==="email",onPress:()=>Re("email",u.updateEmail),testID:"records-failure-update-email"})]}):null,y.canRetrySend===true?jsx(J,{label:qt.retry,kind:"outline",accessibilityLabel:qt.retryA11y,disabled:!u.canRetry,busy:u.busy&&p==="retry",onPress:()=>Re("retry",u.retry),testID:"records-failure-retry-send"}):null,y.canRetrySend===true&&u.hasEmailEdit?jsx(m,{style:c.rowDetail,children:qt.retryHint}):null,ne&&(p==="email"||p==="retry")?jsx(View,{style:c.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:c.errorText,children:ne})}):null]}):null,(S||T)&&n?jsx(J,{label:be.tryAnotherClinic,kind:"outline",accessibilityLabel:be.tryAnotherClinicA11y,onPress:()=>n({name:"clinicPicker"}),testID:"records-request-try-another-clinic"}):null,q!==null?jsxs(View,{style:s.callBlock,children:[jsx(Td,{call:q,prompt:y.statusLabel}),y.canRetrySend===true?jsx(J,{label:u.busy&&p==="retry"?be.resending:be.resend,kind:"outline",accessibilityLabel:u.busy&&p==="retry"?be.resendingA11y:be.resendA11y,disabled:!u.canRetry,onPress:()=>Re("retry",u.retry),testID:"records-resend-authorization"}):null]}):null,j?jsxs(View,{style:s.block,children:[jsx(J,{label:u.busy&&p==="convert"?be.converting:be.convert,busy:u.busy&&p==="convert",onPress:()=>Re("convert",u.convert),testID:"records-convert-upload"}),jsx(m,{style:c.muted,children:be.convertHint}),ne&&p==="convert"?jsx(View,{style:c.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:c.errorText,children:ne})}):null]}):null,ae?jsxs(View,{style:s.block,children:[jsx(J,{label:b?be.freshUploadStarting:be.freshUpload,kind:S||T?"outline":"primary",busy:b,onPress:te,testID:"records-upload-own-fresh"}),v?jsx(View,{style:c.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:c.errorText,children:v})}):null]}):null,ne&&p==="revoke"?jsx(View,{style:c.errorBanner,accessibilityRole:"alert",children:jsx(m,{style:c.errorText,children:ne})}):null,y.canRevoke===true?u.confirmingRevoke?jsxs(View,{style:s.block,testID:"records-revoke-confirm",children:[jsx(m,{style:s.confirmTitle,accessibilityRole:"header",children:qt.cancelQuestion}),jsx(m,{style:c.bodyText,children:qt.cancelConsequence}),jsx(J,{label:u.busy&&p==="revoke"?be.cancelling:be.cancel,kind:"danger",accessibilityLabel:u.busy&&p==="revoke"?be.cancellingA11y:be.cancelA11y,busy:u.busy&&p==="revoke",onPress:()=>Re("revoke",u.revoke),testID:"records-revoke-do"}),jsx(J,{label:qt.keepRequest,kind:"outline",disabled:u.busy,onPress:u.keepRequest,testID:"records-revoke-keep"})]}):jsx(J,{label:be.cancel,kind:"danger",accessibilityLabel:be.cancelA11y,disabled:u.busy,onPress:u.askRevoke,testID:"records-revoke"}):null]})}i(Xb,"RequestDetail");function Jb(){let e=V();return useMemo(()=>Zb(e),[e])}i(Jb,"useLocalStyles");function Zb(e){let{color:t,space:r,radius:o,type:n}=e,a=i((l,c,s,d="regular")=>({...k(e,d),fontSize:l,lineHeight:Math.round(l*c),color:s}),"text");return StyleSheet.create({content:{paddingHorizontal:r.lg,paddingBottom:r.xxl,gap:r.lg+r.xs/2},readyCta:{minHeight:r.xxl+r.lg+r.xs/2},failureCard:{borderRadius:o.lg-r.xs,borderWidth:1,padding:r.md+r.xs/2,gap:r.md},failureCritical:{borderColor:t.badgeBgCritical,backgroundColor:t.badgeBgCritical},failureCaution:{borderColor:t.badgeBgCaution,backgroundColor:t.badgeBgCaution},failureTitle:{...a(n.size.body,n.lineHeight.snug,t.text.primary,"bold")},failureTitleCritical:{color:t.danger},failureTitleCaution:{color:t.warningStrong},emailBlock:{gap:r.sm},callBlock:{gap:r.sm},block:{gap:r.sm},confirmTitle:{...a(n.size.subtitle,n.lineHeight.snug,t.text.primary,"bold")}})}i(Zb,"makeLocalStyles");function au(e){let{petRef:t,petName:r,controller:o,clinicController:n,onPickDocument:a,uploadTransport:l,consentVersion:c,ownerName:s,onCaptureSignature:d,initialScreen:u,onExit:p,style:f,renderPending:b,onOpenUrl:R,onCopy:v,onAsk:w,location:g}=Oe(e,["onExit"]),[y,x]=useReducer(hi,u,Qn),h=Xn(y),I=y.stack.length;useEffect(()=>{let U=i(()=>I<=1?false:(x({type:"pop"}),true),"onBackPress"),j=BackHandler.addEventListener("hardwareBackPress",U);return ()=>{j.remove();}},[I]);let S=useCallback(U=>x({type:"navigate",screen:U}),[]),T=useMemo(()=>Jn(y).handled?()=>x({type:"pop"}):p,[y,p]),C={onNavigate:S,...T?{onBack:T}:{},...r!==void 0?{petName:r}:{},...R?{onOpenUrl:R}:{},...v?{onCopy:v}:{},...w?{onAsk:w}:{},...g?{location:g}:{}},A={...o?{controller:o}:{},...c!==void 0?{consentVersion:c}:{}},F={...a?{onPickDocument:a}:{},...l?{uploadTransport:l}:{}},q=b?{renderPending:b}:{};switch(h.name){case "dashboard":return jsx(Ns,{petRef:t,...C,...A,...q,style:f});case "request":return jsx(Zs,{petRef:t,requestId:h.requestId,...C,...A,...F,...q,style:f});case "timeline":return jsx(Fd,{petRef:t,...C,style:f});case "record":return jsx(Ys,{petRef:t,...C,...A,...q,style:f});case "document":return jsx($s,{petRef:t,...C,...A,...q,style:f});case "contributions":return jsx(Nd,{petRef:t,docId:h.docId,...C,style:f});case "clinicPicker":return jsx($i,{petRef:t,...C,...n?{controller:n}:{},...o?{recordsController:o}:{},style:f});case "clinicBatch":return jsx(as,{petRef:t,petName:r??"",ownerName:s??"",...T?{onClose:T}:{},onCreated:()=>x({type:"navigate",screen:{name:"dashboard"}}),...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:f});case "consent":return jsx(gs,{petRef:t,clinic:h.clinic,...C,...s!==void 0?{ownerName:s}:{},...d?{onCaptureSignature:d}:{},...n?{controller:n}:{},style:f});case "upload":return jsx(Qs,{petRef:t,...C,...o?{controller:o}:{},...F,...q,style:f});case "requests":return jsx(Ls,{petRef:t,...C,...o?{controller:o}:{},...q,style:f});default:return Rr(h)}}i(au,"EverfurRecordsFlow");var ih=au;function ch(e){let{userRef:t,scopeEpoch:r}=ke();return jsx(Le,{capability:"recordsClinic",...ze(e.onClose,W.cancel),children:t===null?jsx(m,{accessibilityRole:"alert",children:pe.sessionRequired}):jsx(dh,{...Oe(e,["onClose","onCreated"])},JSON.stringify([t,r,e.petRef,e.petName]))})}i(ch,"EverfurClinicRequest");function dh(e){let t=Ut(),[r,o]=useState(null),n=useCallback(async()=>r===null?null:{signaturePngBase64:r},[r]),a=Zl(e,e.controller??t,e.onCaptureSignature??n),l=e.onCaptureSignature!==void 0||r!==null,c=V(),s={minHeight:44,padding:c.space.sm,borderWidth:1,borderColor:c.color.borderHairlineGreen,borderRadius:c.radius.sm,color:c.color.text.primary,backgroundColor:c.color.surface},d={color:c.color.text.primary,fontSize:c.type.size.body},u=i((p,f,b=false)=>jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:p,accessibilityState:{disabled:b},disabled:b,onPress:f,style:[s,{justifyContent:"center",opacity:b?.5:1}],children:jsx(m,{style:d,children:p})}),"button");return jsxs(View,{accessibilityLabel:W.title,style:[{backgroundColor:c.color.surface,padding:c.space.lg,gap:c.space.md,borderRadius:c.radius.lg,minHeight:120},e.style],children:[jsx(m,{accessibilityRole:"header",style:[d,{...k(c,"bold"),fontSize:c.type.size.heading}],children:W.title}),jsx(m,{style:d,children:e.petName}),a.created?jsx(m,{accessibilityLiveRegion:"polite",style:d,children:a.created.statusLabel||pe.records}):jsxs(Fragment,{children:[jsx(m,{style:d,children:W.ownerName}),jsx(He,{accessibilityLabel:W.ownerName,style:s,value:a.ownerName,maxLength:200,editable:!a.busy,autoComplete:"name",onChangeText:a.setOwnerName}),jsx(m,{style:d,children:W.clinic}),jsx(He,{accessibilityLabel:W.clinic,style:s,value:a.query,placeholder:W.placeholder,placeholderTextColor:c.color.text.placeholder,maxLength:200,editable:!a.busy,onChangeText:a.setQuery}),u(W.search,()=>{a.search();},a.busy||a.searching||a.query.trim().length<2),a.searching&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:pe.loading}),a.recent.length>0&&jsx(m,{accessibilityRole:"header",style:d,testID:"records-clinic-recent-label",children:W.recentlyUsed}),a.recent.map(p=>jsx(View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>a.selectClinic(p),a.busy)},`recent-${p.id}`)),a.clinics.map(p=>jsx(View,{children:u([p.name,p.address,p.phone].filter(Boolean).join(", "),()=>a.selectClinic(p),a.busy)},p.id)),a.needsEmail&&jsxs(Fragment,{children:[jsx(m,{style:d,children:W.email}),jsx(He,{accessibilityLabel:W.email,style:s,value:a.email,placeholder:W.emailPlaceholder,placeholderTextColor:c.color.text.placeholder,maxLength:320,editable:!a.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:a.setEmail})]}),jsx(m,{accessibilityRole:"header",style:d,children:W.scopeHeading}),a.copy?jsx(m,{style:d,children:a.query.trim()&&a.ownerName.trim()?a.scope??N("internalError").displayMessage:pe.consentRequired}):!a.error&&jsx(m,{accessibilityLiveRegion:"polite",style:d,children:pe.loading}),!e.onCaptureSignature&&jsx(Mr,{onChange:o,disabled:a.busy}),!l&&jsx(m,{accessibilityRole:"alert",style:d,children:W.missingSignature}),a.error&&jsx(m,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:d,children:a.error.displayMessage}),!a.copy&&a.error&&u(pe.retry,a.retryCopy),u(a.busy?W.sending:W.send,()=>{a.submit();},a.busy||!a.ready||!l)]}),e.onClose&&u(W.cancel,e.onClose,a.busy),jsx(Ve,{})]})}i(dh,"ClinicRequestBody");
|
|
4
|
+
export{$i as EverfurClinicPicker,ch as EverfurClinicRequest,as as EverfurClinicRequestBatch,Ys as EverfurRecordDetail,$s as EverfurRecordDocument,ih as EverfurRecords,gs as EverfurRecordsConsent,Ns as EverfurRecordsDashboard,au as EverfurRecordsFlow,Zs as EverfurRecordsRequest,Ls as EverfurRecordsRequests,Qs as EverfurRecordsUpload,Gr as RECORDS_CLINIC_BATCH_MAX,va as RECORDS_TERMINAL,Vn as REQUEST_TIMELINE_TITLES,Mr as SignaturePad,xs as applyFactOverlay,Ps as buildRequestTimeline,Xn as currentRecordsScreen,Ei as deriveRecordsDashboardState,Qn as initialRecordsNav,Do as isFactEditable,gr as isTerminalStatus,to as pickPetRecordsRequest,Jn as popRecordsNav,fi as pushRecordsNav,br as recordsDenialReasonOf,hi as recordsNavReducer,Yi as registerRnSignature,gi as replaceRecordsNav,bi as resetRecordsNav,ko as selectClinicCall,Si as selectDashboardView,Ur as selectPrimaryLabel,Rs as selectRequestList,So as selectRequestTitle,Ha as transitionRecordsNav,st as useEverfurRecords,Ut as useEverfurRecordsClinic,Ii as useEverfurRecordsClinicBatch,Cs as useRecordFactEdit,js as useRecordPdfLink,Hs as useRecordShares,ms as useRecordsMarkers};
|