const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BoostCompanion-v2C1aUhc.js","assets/BoostPanel-iDGPsrCS.js","assets/useAssistantChat-CJu97qJH.js","assets/useSmartQueue-DkRk-RtO.js","assets/useBoostGift-DjEx8jw6.js","assets/rotate-ccw-BfFIsI8J.js","assets/sun-1qB5g-30.js","assets/announcements-CHWMrHjI.js","assets/pause-Cv02nx3E.js","assets/bell-off-C9_BgQeb.js","assets/LeadSiteHome-WrkmA9p1.js","assets/useLeadSiteSearchSuggestions-LiRQSyEY.js","assets/map-mmG3cAUs.js","assets/hash-OAkrCuNT.js","assets/AgentReviewsSection-_wc6UtVV.js","assets/credits-PIR_bev7.js","assets/ExchangeListingsSection-BaSOBZRl.js","assets/leadSiteAgent--GbV6IdE.js","assets/ScrollLivingHero-D0_mac17.js","assets/LeadSiteLuxuryHome-BUsnB4ee.js","assets/RecentSalesSnapshot-DQnVn6tQ.js","assets/LeadSiteExchangeListings-aktFQ31K.js","assets/truck-B83GmnOF.js","assets/LeadSiteLuxuryHome-DKt_VWIz.css","assets/LeadSiteLandRanchHome-DKjZvLWe.js","assets/mountain-DlsbiMfP.js","assets/tree-pine-B5IsRgEw.js","assets/use-in-view-CG5sMzMr.js","assets/LeadSiteSearch-Bj8VZbDN.js","assets/ListingCardExtras-17w1GmQq.js","assets/bell-ring-llgv4tcd.js","assets/useInfiniteQuery-COFNQSiW.js","assets/LeadSiteMap-6_KGrWEd.js","assets/LeadSiteLuxurySearch-BKNyJtXL.js","assets/LeadSiteListingDetail-B7GS2mDf.js","assets/ListingVideoTour-H_Qcs6cd.js","assets/expand-C47vabjc.js","assets/car-M8KV3llx.js","assets/thermometer-BbPJmchU.js","assets/snowflake-DGgw7AfE.js","assets/waves-BsPWA-gx.js","assets/useListingVideos-DyF0Herx.js","assets/LeadSiteLuxuryListingDetail-DRfpB3Os.js","assets/LeadSiteAbout-DCzpqlQp.js","assets/LeadSiteLuxuryAbout-C7YGm-HM.js","assets/ExpReadySpotlight-CWSyuwaB.js","assets/LeadSiteBlog-5jS8fhrc.js","assets/renderPostContent-C6mq4hf6.js","assets/purify.es-CAi2OJFm.js","assets/LeadSiteCommunity-BC3_POQo.js","assets/wine-CDgkrifn.js","assets/trees-Fis93jyO.js","assets/plane-CIai6n3T.js","assets/music-BdyotIyA.js","assets/LeadSiteSellers-C1qj2iXX.js","assets/LeadSiteCityPage-D4E5PyQE.js","assets/CityFaqSection-C7w32P1I.js","assets/LeadSiteFocusPage-DN20shAh.js","assets/LeadSiteExpReady-Cp9_Cqya.js","assets/paintbrush-HJHKgLsJ.js","assets/OrgSiteLayout-CZ71csk6.js","assets/orgSiteBrand-DKMUe12O.js","assets/OrgSiteHome-DNpitldw.js","assets/OrgSiteAgents-BGj-L8yA.js","assets/OrgSitePages-DfD1aOvQ.js","assets/OrgSiteListings-Do0qw5I3.js","assets/CanvaSupport-DY0aaxOk.js","assets/unplug-Dk6vO8E9.js","assets/SmsOptIn-BLCfMWhh.js","assets/signpost-CcWDvIFr.js","assets/ConnectChatGPT-BtQ1jJ_n.js","assets/circle-check-big-dxXK1Ucx.js","assets/SubscriptionSuccess-BboNQaIM.js","assets/SetupBrokerage-ChdFRNkf.js","assets/InviteSignup-DIdDtZWx.js","assets/eye-off-CDu7LPDA.js","assets/CoachingHub-CQnICbKP.js","assets/useCoaching-HG3rzTqg.js","assets/CoachAgentWorkspace-DZxAgK0t.js","assets/CoachingFiles-sFGV2XNP.js","assets/folder-open-BTraZSJ3.js","assets/save-Bg1XERVj.js","assets/MyCoach-BdBvapH6.js","assets/CoachReviews-dLKzL2fD.js","assets/circle-x-4Nbtb9u6.js","assets/AdminCoaching-DWfSJPMi.js","assets/arrow-left-right-BCXHto3W.js","assets/user-minus-DEydRvpj.js","assets/inbox-CMKlE9TG.js","assets/CoachBilling-BnuqRqK9.js","assets/credit-card-CR5HhkxK.js","assets/CoachSettings-E37VG34v.js","assets/GoogleCalendarCard-MiY6V7kv.js","assets/calendar-off-BuUsvr8q.js","assets/useCoachGoogleCalendar-Dkfofoc5.js","assets/link-D6jNEUCK.js","assets/Microsoft365Return-olagGOdA.js","assets/useMicrosoft365-DzHdjBrI.js","assets/freshAccessToken-BYbuwwC8.js","assets/CoachWaitlist-Ddz6Bq9r.js","assets/mail-check-DwEUiVRn.js","assets/CoachProfile-EBBZ2u3v.js","assets/Trial-DwJz4JIC.js","assets/testimonial-avatar-5-DBoTqx4u.js","assets/TrialSuccess-C4A8fQ-5.js","assets/party-popper-QXVPrs5z.js","assets/LaborDaySale-BbMTCdcT.js","assets/OpenHouseInviteModal-Cw5J51jA.js","assets/workflow-BwtOHlfI.js","assets/infinity-D2l5w7mB.js","assets/BrokerageLaborDaySale-DUMaZ8Yx.js","assets/BrokerageSolutions-Dqf2Er1N.js","assets/receipt-CLttG0Sh.js","assets/scale-CXlf9Gh1.js","assets/pencil-line-C85SnXkr.js","assets/Upgrade-DrT21Rsu.js","assets/log-in-DBu12StR.js","assets/InstagramGift-B-HAVkrq.js","assets/VideoShare-CAMH0Y3G.js","assets/VideoPageTemplates-DINgy4hN.js","assets/message-circle-heart-gLlIe0Ia.js","assets/flag-DDqy-GpZ.js","assets/door-open-By3_w3We.js","assets/brain-Bt9qAW0x.js","assets/coffee-DWsqrHYs.js","assets/CommercialWizard-Dk6MDsOp.js","assets/useListingExchange-CAHZ_veu.js","assets/useTeamListingAccess-D4GtHXTC.js","assets/CommercialWorkspace-Da2oQIwr.js","assets/ListingSocialDialog-Cltt0uNT.js","assets/useAgentBrand-2IkpRqWU.js","assets/listingGraphic-jesxFSmt.js","assets/ListingPhotoGrid-NELnFQ_o.js","assets/sortable.esm-Bklih1i6.js","assets/grip-vertical-D62kVM1E.js","assets/ShareListingDialog-Bdr51etV.js","assets/EmailListingToSphereDialog-BLYu0ai1.js","assets/index-CGZ5kfZL.js","assets/separator-CmFvjnic.js","assets/GmailComposeDialog-Dcs_iDMT.js","assets/useMassEmailReady-CdyRdtX1.js","assets/useSenderIdentity-B-TXL0dT.js","assets/useVerifiedSenderCheck-CRRZzhX8.js","assets/VerifySenderRequiredDialog-Cy_mXx43.js","assets/useContactIntakePage-EQYVc6du.js","assets/ToContactAutocomplete-Bo6dfhMZ.js","assets/outlookSend-7RGncvDb.js","assets/paperclip-Be7x5u_Z.js","assets/file-search-CyNBiLxW.js","assets/qr-code-DPz2jCtu.js","assets/CommercialPitchPreview-kbuDD0Qv.js","assets/PublicLiveEvent-CuWSsDJX.js","assets/pin-CsMbH7vl.js","assets/arrow-up-ZZy3M6Cp.js","assets/useLiveEngagement-RBL5vzmm.js","assets/sparkle-8g1CP-KU.js","assets/LiveEvents-D4VyL-Tx.js","assets/AdminPageHeader-DbWKKsxk.js","assets/useLiveEvents-BPDmt7VV.js","assets/image-plus-CK_rwBSL.js","assets/LiveEventConsole-BYsh0RBU.js","assets/mouse-pointer-click-Dax7yNfA.js","assets/ban-fXKO1Brd.js","assets/Dashboard-BHQxf4QZ.js","assets/useContentEngagement-BGfODeOB.js","assets/usePrograms-Dp9Mk62F.js","assets/timezone-BQmfqhtz.js","assets/addMilliseconds-zuivi7v0.js","assets/isWithinInterval-sljoTHCi.js","assets/useGmailIntegration-Bn5yVNcx.js","assets/GoalTargetsDialog-Cdks2Uou.js","assets/useBrokerageContent-HZ1rMeyu.js","assets/beta-badge-BH0TecOj.js","assets/useEventGamification-UxnoAu40.js","assets/RelationshipHealthWidget-BhS2A12D.js","assets/useRelationshipScore-C_sSdLXe.js","assets/file-image-UKfXdTph.js","assets/Profile-CVdKh0IU.js","assets/RichTextEditor-DKUsnHx0.js","assets/index-wGqyHmDC.js","assets/index-zRw8hkpK.js","assets/index-wnopZthl.js","assets/heading-1-DrHv8YB7.js","assets/heading-2-BQNi5II-.js","assets/undo-D5VlHyfP.js","assets/list-ordered-CTG9JQKb.js","assets/align-left-B_06XVpB.js","assets/align-right-CtqHY-Ko.js","assets/ImageCropper-DZ7vCwxk.js","assets/zoom-out-MUpHYNw6.js","assets/rotate-cw-BCb53plb.js","assets/ImageCropper-BgW1nI8X.css","assets/useBrandKit-z3kNVMxK.js","assets/useStagingStudio-RBRg68oI.js","assets/checkoutTab-DsuQ3Oiw.js","assets/BrokerageLogoUpload-DZ8GcUeL.js","assets/user-round-BKpkMx8F.js","assets/mail-x-CPQnWPWP.js","assets/Events-D59zC4lX.js","assets/EventLeaderboard-B-nnTmKy.js","assets/medal-CGsHK0wi.js","assets/MainStageSchedule-8yMgj1lo.js","assets/history-CLjdiSpR.js","assets/EventDetail-DLZoUD3P.js","assets/ShareButton-DqqcZMsK.js","assets/user-cog-B72zVddw.js","assets/Apps-DbZVQbC0.js","assets/monitor-play-DM-NQAH4.js","assets/skip-forward-BS3Wsoln.js","assets/Templates-euCBPcNt.js","assets/TemplateDetail-BMEB7sGK.js","assets/Programs-C82Sg6bm.js","assets/ProgramDetail-hg7UKgbq.js","assets/accordion-Dtsozolo.js","assets/index-Bf0wVheO.js","assets/ProgramEnroll-CWzOIJzK.js","assets/tag-Cmx-rBCd.js","assets/ProgramWorkspace-DeOiAup1.js","assets/layout-template-CbkuPt-Y.js","assets/file-spreadsheet-D2cVYDZV.js","assets/Programs-BN0PCtVg.js","assets/route-CXPPl8cT.js","assets/collapsible-CyPr_JB-.js","assets/AcademyVideoDetail-BXJKJ-xg.js","assets/LinkedTemplatePills-t6D4SFw_.js","assets/ToolboxDetail-27j59Gba.js","assets/SocialSwag-C6fok9rj.js","assets/SocialStudio-CTqW-IDT.js","assets/CanvaImportDialog-DyqQsxkz.js","assets/useCanvaMailStudio-CLoEsb6y.js","assets/unlink-Bi_vswc9.js","assets/platforms-Cb-tBXDB.js","assets/music-2-RtyUC_ao.js","assets/jpegConvert-Rgz8SYSg.js","assets/repeat-2-950w22pV.js","assets/type-Cu-zxBGi.js","assets/settings-2-B6Aikz8s.js","assets/scheduleTz-sV91p5EC.js","assets/calendarTz-JHe45SGp.js","assets/YouTubePublishing-BUFbtgSC.js","assets/useCalendarTimezone-CfL1Z3ve.js","assets/CalendarSettingsDialog-JC1uefx3.js","assets/earth-D6spZ6l_.js","assets/tiktokCallbackError-HhZqZSBp.js","assets/edgeError-D7v3Opwd.js","assets/jszip.min-B54FtA63.js","assets/MarketingStudio-CvorF0VN.js","assets/message-square-quote-BunPocA4.js","assets/BrandKit-CtlDSrFy.js","assets/useBrandPresets-D8hhVBIH.js","assets/BrandingBarEditor-Chk1PK1Q.js","assets/ReactKonvaCore-Dx4SVMj-.js","assets/index-Cd2KakmS.js","assets/ListingTemplates-B_MEmRHa.js","assets/index-xVp0PEHv.js","assets/EditorialTemplate-BSRNtbSH.js","assets/PersonalBranding-BYmdJ9qP.js","assets/toggle-group-WP63Zpob.js","assets/SocialSwagDetail-W7WeSiip.js","assets/Community-B_bIEsZg.js","assets/MentionTextarea-BgWs0F9u.js","assets/reply-3CzZxd6F.js","assets/pin-off-CrNXsjYf.js","assets/Support-NLM8Bfsq.js","assets/SupportAttachmentList-iHKplRfK.js","assets/file-video-BaOPd6Ky.js","assets/BrokerageResources-BDp3vdb5.js","assets/AdminDashboard-mu2fBi7-.js","assets/database-CgUtz5-S.js","assets/flask-conical-DMgA76oj.js","assets/shopping-bag-CKWJiuED.js","assets/coins--s_fbJnZ.js","assets/MemberManagement-9arZTSdm.js","assets/SendCelebrationDialog-ClpNyz6y.js","assets/sortable-table-head-DckxPyul.js","assets/arrow-down-B3S1-bOw.js","assets/useTeams-CSXZk_po.js","assets/CreateTeamDialog-DNq_PTKV.js","assets/TeamSharedAssetsView-GcJyDb1Z.js","assets/LeadPondView-mwpKau5c.js","assets/arrow-right-left-DRoGv-rT.js","assets/sticky-note-BmauldkR.js","assets/droplets-ChQmUgUi.js","assets/hand-pwxWaAq1.js","assets/contact-BOlukra9.js","assets/crown-BnpcT0Di.js","assets/calendar-heart-XSWIMzk9.js","assets/UnassignedMembers-DVMXjJNJ.js","assets/InviteCodes-yEDnAH1y.js","assets/Events-D2sBFklc.js","assets/useNotifications-3FWdb0xz.js","assets/repeat-5dQs355N.js","assets/MCPAuditLog-cnAGqY3P.js","assets/shield-alert-BKSLxyIp.js","assets/Templates-BXM68Iv5.js","assets/Academy-BzmJfV7w.js","assets/LinkedTemplatePicker-D3xus_7s.js","assets/Toolbox-DUuVEqgq.js","assets/SocialSwag-DnIEWROM.js","assets/SocialSwag2-CschF9rq.js","assets/Community-C3DJc_3_.js","assets/Analytics-CPHqc0WL.js","assets/ShareAnalytics-DWRu4RJG.js","assets/mouse-pointer-ZWwG5sEH.js","assets/panels-top-left-CbUR7T-F.js","assets/LineChart-DWSErB8Z.js","assets/chrome-D4rvcGIo.js","assets/BrokerageResources-t4B0ng5t.js","assets/DashboardManagement-Boz9ZKkC.js","assets/SupportTickets-BesKFGHH.js","assets/EmailTemplates-fousVngN.js","assets/index-CLwf3nz3.js","assets/code-BQSdJowh.js","assets/variable-CgAmigiX.js","assets/monitor-oG_K334_.js","assets/AgentEmailTemplates-DIZZt809.js","assets/BrokerageDashboard-pJm3zCfI.js","assets/MyBrokerage-F6oHdBqF.js","assets/useBrokerageOnboarding-D7NuGzWN.js","assets/OnboardingChecklist-CdintpxG.js","assets/BrokerageContent-D6ui10cK.js","assets/BrokerageHelpBoard-c3YmW9Ep.js","assets/useBrokerageHelpBoard-GX93xNOk.js","assets/BrokerageHelpBoardNew-DGg_bO33.js","assets/BrokerageHelpBoardDetail-DHllJyuH.js","assets/Newsletters-CCVrsknn.js","assets/useMailingAddressGate-C6OqLbD3.js","assets/NewsletterGraphicsPicker-tqygLMkI.js","assets/underline-Ci9qt1bH.js","assets/SenderAddressDialog-k4PdA8RT.js","assets/uploadBase64Images-D6FbU3TO.js","assets/SendNewsletterDialog-CMid6m3k.js","assets/undo-2-CUOHNsmf.js","assets/useContactCustomTags-LAr-fhCn.js","assets/useSmartLists-BS8d-US7.js","assets/code-xml-BJVMDgfN.js","assets/list-filter-COukUfzC.js","assets/NewsletterDetail-vK4LjMsi.js","assets/Newsletters-Bb6Ktpf5.js","assets/library-BMcqznwf.js","assets/MemberBroadcasts-gZqs_8xs.js","assets/bookmark-plus-q3tBPA2G.js","assets/BoostAnnouncements-CJah-sH2.js","assets/NewsletterGraphics-DAomMW91.js","assets/Wishlist-CLwnnaks.js","assets/WishlistDetail-KMoVz0Gg.js","assets/LevelUpBrief-BBNRzGCA.js","assets/AdditionalServices-DCuJULjJ.js","assets/Discounts-CxhuTzR6.js","assets/Subscriptions-C2-VjwNY.js","assets/instagramEmailReview-DK4Cq88H.js","assets/InstagramGiftEmails-BuMhFKmo.js","assets/Referrals-zKNVXSaR.js","assets/AgentOSControlCenter-BDCsVpuT.js","assets/AskAI-vuii8J0t.js","assets/InnerCircleHome-D7tQYLU9.js","assets/SnoozeContactDialog-D4ALiHQj.js","assets/pen-tool-OioaAvPj.js","assets/milestoneMail-volIAJ1Q.js","assets/handoff-B7AOa2Ye.js","assets/milestones-Uak6QeIS.js","assets/stamp-C3uDP4UK.js","assets/mail-open-CRV4EfK_.js","assets/InnerCircleContacts-D4BgutrB.js","assets/mailingAddress-BJ5Zh-Ye.js","assets/SyncDirectionSelector-C4FR8gb4.js","assets/refresh-ccw-BrsX5Ugr.js","assets/merge-BMTS-UwW.js","assets/ContactCriteriaForm-Cu7YQjQL.js","assets/usePopbys-B_6fzPf_.js","assets/ContactTagChip-B2qVBZaM.js","assets/info-DKAco9ne.js","assets/RelationshipScoreBadge-_ioWAPnt.js","assets/MailStudioHandoffButton-BJJQiwdX.js","assets/useVideoShareTracking-B5W4kzQP.js","assets/EnrollContactsDialog-CaDNphOx.js","assets/useDripCampaigns-DfkODvHn.js","assets/CampaignBuilderDialog-BSv7Qmjp.js","assets/quill.snow-BB_HOWK1.js","assets/quill-BzY4kI8E.css","assets/braces-Cd7RqmCn.js","assets/VideoLibraryPicker-uOheK-_R.js","assets/VideoUploadDialog--fX6qoKU.js","assets/useVideoTouch-B3ITEzTW.js","assets/NeighborhoodFilter-Bo_0QkhQ.js","assets/useNeighborhoods-suRN9Ptv.js","assets/sphereMap-DH23JP4j.js","assets/sprout-CymsJVCc.js","assets/ContactAvatar-BhiUHcV1.js","assets/user-x-CSJ4Po8J.js","assets/map-pinned-DMfR-icc.js","assets/InnerCircleContactDetail-DCnaKTvB.js","assets/useCMA-BI2-2d6p.js","assets/useClientPortal-BzuLsXy9.js","assets/futureSeller-zvCkkJRV.js","assets/useSentEmails-C6WDN9Dj.js","assets/propertyService-Cm9U676_.js","assets/building-4N_5Jqg9.js","assets/archive-Xu5bQ_py.js","assets/useContactFinder-DoIlWokE.js","assets/SentEmails-C-rEhys7.js","assets/InnerCirclePlans-D08xEo7Z.js","assets/pen-CkGxnLSn.js","assets/CMAList-B5noKSUF.js","assets/SendCMADialog-BDO0vGVy.js","assets/UpgradeLockedCard-C8cSxmw7.js","assets/CMABuilder-HIxM0-OU.js","assets/VideoRecorder-CR5qM7Sa.js","assets/flip-horizontal-JRJ6a_pA.js","assets/videoSegmentation-CqOVlWAo.js","assets/monitor-up-Br57x7HL.js","assets/mic-D0F3EZK9.js","assets/ListingPresentations-Ch8sWXVT.js","assets/session-BLQXDUj2.js","assets/jspdf.es.min-CC3fmQwS.js","assets/SendPresentationDialog-DPfQ3sgJ.js","assets/ListingPresentationBuilder-pPulDnNL.js","assets/PdfCanvasPreview-BjYszl_2.js","assets/pdf.worker.min-CXH_Kl7N.js","assets/ImageUploadField-DC3h8o2j.js","assets/move-iheCejwD.js","assets/InnerCirclePopbys-DukCoC7m.js","assets/locate-Q492wGa5.js","assets/navigation-DgMOL1rT.js","assets/ListingExchange-COtAkBa7.js","assets/ListingLaunchKitModal-CCEqSMbS.js","assets/ListingSelectionBar-DEVUapL7.js","assets/musicVideoHandoff-Bs6IOG8F.js","assets/ListingDetail-wi-PG1Mh.js","assets/ListingForm-DBlS6Oqk.js","assets/CustomizeListingPage-C6GIUysY.js","assets/box-B2SF8A_A.js","assets/VideoStudio-1FWiGqRf.js","assets/wifi-C1qOEWLv.js","assets/VideoShareWithTemplate-B2MgpgHk.js","assets/stageInvite-D0yI5SXb.js","assets/interactive-h6Bhda0v.js","assets/browser-CjSdxGTc.js","assets/tv-CZoxMNeV.js","assets/video-off-CKBMoVuj.js","assets/guestRoom-AaCAeUt8.js","assets/kits-Dnbdw2nv.js","assets/BackdropPanel-CkZgdb3O.js","assets/ListingPhotoImport-CInpAd6I.js","assets/images-B-Ya_khV.js","assets/panel-right-close-0wyYF68k.js","assets/clapperboard-i62r6BtK.js","assets/scissors-DDZaXrKp.js","assets/switch-camera-BC-yo6qM.js","assets/MainStageGate-B9sXMs7W.js","assets/survey-D78-hbGw.js","assets/phone-off-DyazEXuK.js","assets/eraser-ElsuIloT.js","assets/theater-Ct5Gqx2k.js","assets/MainStageAdmin-WnYC5H_R.js","assets/StudioKitsAdmin-Dzg6W-8w.js","assets/StudioGuestJoin-BMo39j8B.js","assets/VideoLibrary-Bn2xgkeO.js","assets/tags-DmFf6saI.js","assets/hard-drive-CeR9BGfQ.js","assets/DealPipeline-DoP6FUt1.js","assets/lucide-react-C-V76oon.js","assets/archive-restore-BD-i4_m7.js","assets/arrow-down-right-D1-e4iOB.js","assets/badge-check-DJzxfMPn.js","assets/circle-user-Jnl1zxo1.js","assets/beaker-Bkv-oE9c.js","assets/brain-circuit-Di3kI169.js","assets/calendar-x-DMVaw1z8.js","assets/file-code-Bzzf87Cy.js","assets/table-CTtWlzCJ.js","assets/circle-dollar-sign-D1Ig_jYu.js","assets/clock-3-DM_-yZlt.js","assets/sunset-Dw0I1DV3.js","assets/cloud-upload-ByV_H-T0.js","assets/corner-down-right-3WkF0m_n.js","assets/file-check-2-5UGDEdCP.js","assets/hammer-iEULw4P2.js","assets/file-down-D52X8C6X.js","assets/file-plus-2-CjPfUPlG.js","assets/piggy-bank-Cq5ghIXS.js","assets/folder-plus-fnZ95306.js","assets/folder-DS6Lcgd3.js","assets/footprints-BHrNSdcr.js","assets/gem-CCE_aczS.js","assets/hand-heart-5pdZwXWq.js","assets/heading-3-yauhvvE_.js","assets/heart-handshake-3mvmPg7n.js","assets/id-card-XXY_us0H.js","assets/locate-fixed-DQMCIOjQ.js","assets/list-plus-BgWzv3LP.js","assets/lock-keyhole-BLUyCrre.js","assets/mail-warning-CtTFcZAM.js","assets/message-square-more-DDhCMpcE.js","assets/message-square-plus-f2Gh1L1G.js","assets/message-square-reply-aYcxAGZX.js","assets/messages-square-DbT6Hr_I.js","assets/mouse-pointer-2-CphsHUcC.js","assets/skip-back-gLc9H94L.js","assets/octagon-alert-BSB0BL3D.js","assets/power-off-CbC5puGs.js","assets/power-CexAIi-y.js","assets/printer-CdK9tyCf.js","assets/rectangle-vertical-DxzPsv0S.js","assets/scroll-text-BYosDsWG.js","assets/shield-off-B0WZxIYi.js","assets/shield-question-Bn7sdEev.js","assets/shuffle-BR0210D0.js","assets/table-2-CQH-QJPL.js","assets/text-cursor-input-lROraDrA.js","assets/thumbs-down-BU55nBHZ.js","assets/twitter-BnbFXLCe.js","assets/user-round-check-BPAeqKeV.js","assets/user-round-search-DQMm6ZeV.js","assets/users-round-C2m-IszL.js","assets/useCommissionPlans-CkLS9Oav.js","assets/ComplianceMessageThread-D4PqmfZC.js","assets/SendForSignatureDialog-C10qr_4F.js","assets/useFormEnvelopes-DXwgFD7R.js","assets/PortalInviteDialog-B71ijb6w.js","assets/CardVideoRecorderDialog-I913EbzU.js","assets/PlaybookLibraryDialog-CtZT7To0.js","assets/PortalListView-u2Ko_Sa0.js","assets/complianceMetrics-Ce83UgLe.js","assets/FormsLibrary---hOgZl7.js","assets/FormPlacementEditor-DTUZwNlZ.js","assets/TransactionCoordinator-CF2MDIbJ.js","assets/PortalReferrals-ukHbHG3N.js","assets/usePortalReferrals-FSXb7uyk.js","assets/AgentVendors-C9tnUY4y.js","assets/VendorFormDialog-sfGjHCM-.js","assets/BrokerageForms-ByROiw2Y.js","assets/BrokerageVendors-1e6XlKKq.js","assets/ClientPortalsHub-DuAgP3nC.js","assets/PortalMessagesPanel-D690FjNX.js","assets/ClientPortalDetail-DTSgeguy.js","assets/MyCardEditor-B_5CjIP9.js","assets/CardBlocksEditor-CctQoG8k.js","assets/Integrations-kivBccYz.js","assets/SesIntegrationCard-B38TA4Qs.js","assets/RecruitVerifiedSenders-Bfcpxj-M.js","assets/Microsoft365Card-CcUCmpm2.js","assets/BrowserExtension-DWHTaUcL.js","assets/IntegrationsGmailCallback-CyMsuWwE.js","assets/IntegrationsMetaCallback-Dh8zPY7L.js","assets/AgentActivation-CQPVfkas.js","assets/MembershipReviews-DC4acSVN.js","assets/LeadNotifications-CwHxqUS9.js","assets/WeeklyDigest-BgFsbNL0.js","assets/AgentPoints-By1fPR8W.js","assets/AgentCards-BQaPS_uG.js","assets/Marketplace-B34eN3jX.js","assets/RewardStore-Ah5PizEM.js","assets/usePointRewardSettings-wifOVYWc.js","assets/Integrations-CjbN4ufT.js","assets/SocialConnections-CGT_xYwm.js","assets/SocialAutopilot-Wso-Y4kH.js","assets/McpUpdates-qn8ET3m6.js","assets/NotificationSettings-BKhdFktC.js","assets/PresentationAnalytics-CgyGdhIu.js","assets/ListingPresentationStudioAdmin-6HEAf4P-.js","assets/ListingRevivalAdmin-DQao4QVZ.js","assets/useListingRevivalAccess-tap8GubN.js","assets/GuestBookAnalytics-B1k9CuqR.js","assets/IntegrationsCallback-B5XCRG4q.js","assets/AdminRecruiting-Bunkfz6q.js","assets/RecruitPipelineStageEditor-CZyrw_Q1.js","assets/index-Cezw4mjC.js","assets/BrokerageRecruiting-DFyW-Aes.js","assets/600-BSKZD_mM.css","assets/BrokerageOnboarding-DYR8llq1.js","assets/BrokerageTransactions-Cdrn6Siq.js","assets/useDealEscrow-D6TWjrdd.js","assets/BrokerageOperations-1NraUHGM.js","assets/renewals-CTiRO4iB.js","assets/WebsitesHub-BsYZyBnq.js","assets/useMyWebsites-C9RD8g3q.js","assets/TeamWebsite-DDqP1CYY.js","assets/OrgSiteBuilder-DDMnoRBz.js","assets/SiteSwitcher-D4xO53-4.js","assets/BrokerageWebsite-BfzpDu4R.js","assets/BrokerageCommissionPlans-G_V-Fjzc.js","assets/BrokerageContentActivity-CZJeyOn5.js","assets/BetaSocialPostGenerator-KkvEvrmR.js","assets/AdminLMS-tQGP8OtX.js","assets/useLMS-DNX8m9Qe.js","assets/AdminCourseDetail-DC-0LCjH.js","assets/LevelUpU-CzWjLDdY.js","assets/LevelUpUCourse-faA7Ft31.js","assets/MobileAgentApp-Mu8lcksh.js","assets/StagingStudio-BAbo_VtG.js","assets/presets-Q-fy2QBn.js","assets/download-BqCckdNk.js","assets/BeforeAfterSlider-BkkH9pyB.js","assets/BuyCreditsDialog-D-rcL4EJ.js","assets/StagingLibrary-sFToGAPE.js","assets/StagingCredits-CkLucpBS.js","assets/AgentWallet-J1H0t4iX.js","assets/useHomeReel-C5G6yObO.js","assets/StagingSharePage-Cr9L4AJY.js","assets/StagingStudioAdmin-DR2U-x4j.js","assets/ContactFinderAdmin-DjCXQthe.js","assets/PostcardManager-CDLTMxlO.js","assets/PostcardZoneEditor-CYOESf-l.js","assets/usePostcardZones-CsnwM-7l.js","assets/MailStudioTemplates-BfMP041K.js","assets/HomeReelManager-BexcC4RN.js","assets/videoRenderSink-DBE5COLu.js","assets/AdminMusicVideos-D8F1X-ua.js","assets/AdminVideoLab-Clvdr7Kh.js","assets/BoostPreview-BjfcEAPb.js","assets/AdminCredits-CyHDTGtk.js","assets/MailStudio-Bzky2hS4.js","assets/farmToCrm-BSmCLYUo.js","assets/artwork-Y-3q8EOM.js","assets/MailStudio-D-BotKHo.css","assets/InnerCirclePopbyMap-DJDdYXeK.js","assets/SphereMap-q9F77Nyu.js","assets/PropertyIntelligenceDashboard-B1U86liQ.js","assets/LiveVisitorFeed-nTmfxRL9.js","assets/LeadSites-CH81xXqb.js","assets/LeadSiteEditor-wzUPUOAQ.js","assets/ImageUrlField-Cr9Rdqdd.js","assets/HomepageModuleManager-72SVJYt8.js","assets/VideoUrlField-CnsXpYmZ.js","assets/AdminLeadSiteThemes-D3T5qIiA.js","assets/AdminFreeWebsiteOfferStudio-hbjWCEdm.js","assets/AdminMlsFeeds-C56tI4Zt.js","assets/AdminWebsiteRequests-CwJm3TSm.js","assets/NeedAWebsite-DPIlgTWQ.js","assets/MLSListings-B1L8ZRF-.js","assets/MLSListingDetail-DIBbaQMR.js","assets/WebsiteActivityPage-DEydijSR.js","assets/PublicRecruitForm-Dn4lfz-9.js","assets/PublicEventInviteUnsubscribe-Ba6GHSzZ.js","assets/SocialConnections-EXatQGNu.js","assets/SocialConnectionsCallback-CeBII7gb.js","assets/LinkedInCallback-CrQMZW8g.js","assets/TikTokCallback-B3BxKr_H.js","assets/MarketplaceCart-CYAtZwOO.js","assets/MarketplaceOrderDetail-E_v2lmLW.js","assets/RewardStore-BuRvCYtt.js","assets/ReferFriends-BfRTdvNg.js","assets/SmartPresentations-BJb3CMbJ.js","assets/useSmartPresentations-DUJjpmQ8.js","assets/SmartPresentationCreate-BrOwa9hw.js","assets/TeleprompterOverlay-Dnn6WgKX.js","assets/GuestBook-CVNv0yn-.js","assets/SignDocument-CsZE8iUT.js","assets/Blog-BHbUBSGk.js","assets/TrialCTA-mDdeJiNr.js","assets/BlogPost-C0wYx33u.js","assets/AdminBlog-sNJITOlN.js","assets/ReviewLanding-BsCHQDTs.js","assets/ReviewIntake-Dzjcf7-M.js","assets/PublicReviewsPage-iIvGW0il.js","assets/PublicReviewSubmit-D2p5uwzE.js","assets/Reviews-qNwm4k-W.js","assets/CardStudio-Bo74Gk0x.js","assets/ListingStudio-CMJreyfz.js","assets/SmartDrips-DzNnNUKX.js","assets/WeeklyReels-Dii1kP-5.js","assets/ReelCard-DFtr8Blf.js","assets/useWeeklyReels-CAEXRF_x.js","assets/WeeklyReelsOnboarding-BAALcN-4.js","assets/WeeklyReelsAdmin-BTelLZnv.js","assets/AttractLayout-Di0bGL3X.js","assets/useAttractSettings-CKb0H_pg.js","assets/useAttractIntelligence-DqdOTCT9.js","assets/HealthScoreBadge-DT1oi4IQ.js","assets/AttractToday-Dug4e5hS.js","assets/useAttractIntelSync-BIiHVW8B.js","assets/useAttractAgents-DP0nchjP.js","assets/useAttractFollowUps-njpoNyJA.js","assets/useAttractActivities-DcoN-DEL.js","assets/RecommendationCard-VbIyM4zj.js","assets/QuickAddRelationship-Cp13dEcY.js","assets/relationshipStages-Buh5_cBI.js","assets/useAttractEvents-8_HQk7LS.js","assets/AttractRelationships-BoniQF0c.js","assets/AttractPageHeader-BkGLkp6a.js","assets/AgentEditSheet-Be_y_u7L.js","assets/AttractFollowUp-BJe1Eiom.js","assets/AttractTemplates-Dld2vPyK.js","assets/AttractReports-BqKZlFDq.js","assets/AttractSettings-RKe4_xZK.js","assets/AttractToolkit-a2k0xAP5.js","assets/Objections-CtuN1WlY.js","assets/AttractCalculator-DY_kAWOZ.js","assets/attractionPageTemplate-C9AaZMgq.js","assets/AttractEventList-BSedPwyH.js","assets/AttractEventBuilder-DbodBmUT.js","assets/useAttractKits-DfNoIJkC.js","assets/AttractEventDetail-83VrXEc3.js","assets/AttractEventCheckIn-DYnyKdLo.js","assets/AttractOnboarding-CcszfYP1.js","assets/ContentStudio-I8QMQl42.js","assets/KitList-FHoF5H2f.js","assets/KitBuilder-CcMcn_ht.js","assets/KitPreview-R56Cd7U2.js","assets/KitAnalytics-BQPo9o79.js","assets/KitTemplates-Cx8Ab3mZ.js","assets/AttractAgentDetail-DyMC07tE.js","assets/AttractOpportunities-tTVv6yOm.js","assets/AttractIntelligenceDebug-D3kEMvjh.js","assets/PublicAttractKit-B2YWU8zw.js","assets/PublicAttractEvent-CeNkd0tq.js","assets/PublicAttractionPage-DAvSC1fL.js","assets/AttractionPageView-BXiw8EaL.js","assets/RevivalLanding-DrwwSK-f.js","assets/types-Bbp_6W6m.js","assets/RevivalPlan-CxwN2Xjz.js","assets/revivalPdf-DN3ftKJU.js","assets/ListingRevival-2VovfzHb.js","assets/useListingRevival-Dp9_gdhg.js","assets/AreaChart-nns9ZLAs.js","assets/RevivalCampaignWizard-Bk7GzWbP.js","assets/campaignMail-C2LhuLOX.js","assets/RevivalCampaignDetail-fATNK7sB.js","assets/LetterEditor-s0N5UU9U.js","assets/FsboBreakthrough-BzE0K6u9.js","assets/useFsboBreakthrough-1NjtVuYX.js","assets/types-CK1tolb7.js","assets/FsboPropertyDialog-y7-pKpJm.js","assets/FsboCampaignWizard-BYhmJH2A.js","assets/FsboCampaignDetail-DQtejuBo.js","assets/FsboLanding-oiQwhlWr.js","assets/publicApi-BEaFpcRg.js","assets/FsboGuide-LahaKusA.js","assets/FsboBreakthroughAdmin-XQUSCWYr.js","assets/AttractLandingPageBuilder-CYGXtN2h.js","assets/AttractAccess-CnFvnJLm.js","assets/Teams-Buz_43KK.js","assets/MyTeam-ChWU9ckD.js","assets/TeamLeaderSettings-CqFIus2S.js","assets/TeamHub--zKbayz1.js","assets/SchedulerSettings-Ci7fQSlb.js","assets/MyCalendar-5fkOJLwt.js","assets/BookingManagePage-ChG4-iyk.js","assets/LandingPages-BAHsy_IW.js","assets/BuyerMatch-YVzQ2krP.js","assets/SendBuyerMatchEmailDialog-CZczKwWE.js","assets/BuyerMatchEditor-S85RHDKV.js","assets/matching-BdEgbJjD.js","assets/PublicBuyerMatch-BR4-1ktI.js","assets/LandingPageEditor-n3Z3Wx3i.js","assets/LandingPageDefaults-p1iYS32S.js","assets/WebsiteAppsHub-Bp0C2gsc.js","assets/ClaimFreeLeadSiteCard-BEdQ9rTI.js","assets/useWebsiteApps-ravr4RrT.js","assets/ClaimWebsite-CoOO_Fhn.js","assets/VideoGreeterEditor-4EFPW7BY.js","assets/ExitIntentEditor-Cpvt5Zqu.js","assets/widgetTemplates-keLygp7O.js","assets/LeadMagnetEditor-BeKAF0Sz.js","assets/RelationshipScorecard-BgpB5NHk.js","assets/SphereGaps-BNIwgzVL.js","assets/ConnectPageSettings-CwuHkfNa.js","assets/EmailCampaigns-Bxcls9O1.js","assets/sesRequest-6FtMnUsO.js","assets/EmailCompliance-1a2Lv5LS.js","assets/EmailCampaignComposer-VfJRhOkr.js","assets/EditorModeSelector-D21TUQfY.js","assets/EmailCampaignDetail-C5ipFBO6.js","assets/SharedCampaignTemplates-hB9oG-R5.js","assets/TemplateEditorDialog-0AoPUgcT.js","assets/AgentTemplates-B4GDC38U.js","assets/TheLocalMoveHome-Br4A1xnl.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-CS4nOL7Q.js","assets/TheLocalMoveCheckout-CEjH_ZXX.js","assets/AdminWebsiteOrders-CLfJ4HZF.js"])))=>i.map(i=>d[i]); var rOe=Object.defineProperty;var xie=t=>{throw TypeError(t)};var nOe=(t,e,r)=>e in t?rOe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var jn=(t,e,r)=>nOe(t,typeof e!="symbol"?e+"":e,r),h6=(t,e,r)=>e.has(t)||xie("Cannot "+r);var Nt=(t,e,r)=>(h6(t,e,"read from private field"),r?r.call(t):e.get(t)),hi=(t,e,r)=>e.has(t)?xie("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),In=(t,e,r,n)=>(h6(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),is=(t,e,r)=>(h6(t,e,"access private method"),r);var VL=(t,e,r,n)=>({set _(i){In(t,e,i,r)},get _(){return Nt(t,e,n)}});function iOe(t,e){for(var r=0;rn[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const c of a.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(i){if(i.ep)return;i.ep=!0;const a=r(i);fetch(i.href,a)}})();var Ou=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ea(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function sOe(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var r=function n(){return this instanceof n?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var Kge={exports:{}},s4={},Yge={exports:{}},Ms={};/** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var EP=Symbol.for("react.element"),aOe=Symbol.for("react.portal"),oOe=Symbol.for("react.fragment"),lOe=Symbol.for("react.strict_mode"),cOe=Symbol.for("react.profiler"),uOe=Symbol.for("react.provider"),dOe=Symbol.for("react.context"),hOe=Symbol.for("react.forward_ref"),fOe=Symbol.for("react.suspense"),mOe=Symbol.for("react.memo"),pOe=Symbol.for("react.lazy"),_ie=Symbol.iterator;function gOe(t){return t===null||typeof t!="object"?null:(t=_ie&&t[_ie]||t["@@iterator"],typeof t=="function"?t:null)}var Zge={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Xge=Object.assign,Qge={};function KT(t,e,r){this.props=t,this.context=e,this.refs=Qge,this.updater=r||Zge}KT.prototype.isReactComponent={};KT.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};KT.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Jge(){}Jge.prototype=KT.prototype;function qH(t,e,r){this.props=t,this.context=e,this.refs=Qge,this.updater=r||Zge}var GH=qH.prototype=new Jge;GH.constructor=qH;Xge(GH,KT.prototype);GH.isPureReactComponent=!0;var vie=Array.isArray,eye=Object.prototype.hasOwnProperty,HH={current:null},tye={key:!0,ref:!0,__self:!0,__source:!0};function rye(t,e,r){var n,i={},a=null,c=null;if(e!=null)for(n in e.ref!==void 0&&(c=e.ref),e.key!==void 0&&(a=""+e.key),e)eye.call(e,n)&&!tye.hasOwnProperty(n)&&(i[n]=e[n]);var d=arguments.length-2;if(d===1)i.children=r;else if(1>>1,Ae=ge[ke];if(0>>1;kei(nt,we))tti(vt,nt)?(ge[ke]=vt,ge[tt]=we,ke=tt):(ge[ke]=nt,ge[ot]=we,ke=ot);else if(tti(vt,we))ge[ke]=vt,ge[tt]=we,ke=tt;else break e}}return $e}function i(ge,$e){var we=ge.sortIndex-$e.sortIndex;return we!==0?we:ge.id-$e.id}if(typeof performance=="object"&&typeof performance.now=="function"){var a=performance;t.unstable_now=function(){return a.now()}}else{var c=Date,d=c.now();t.unstable_now=function(){return c.now()-d}}var p=[],l=[],g=1,v=null,E=3,T=!1,j=!1,P=!1,C=typeof setTimeout=="function"?setTimeout:null,L=typeof clearTimeout=="function"?clearTimeout:null,O=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function F(ge){for(var $e=r(l);$e!==null;){if($e.callback===null)n(l);else if($e.startTime<=ge)n(l),$e.sortIndex=$e.expirationTime,e(p,$e);else break;$e=r(l)}}function $(ge){if(P=!1,F(ge),!j)if(r(p)!==null)j=!0,Ie(G);else{var $e=r(l);$e!==null&&Te($,$e.startTime-ge)}}function G(ge,$e){j=!1,P&&(P=!1,L(Q),Q=-1),T=!0;var we=E;try{for(F($e),v=r(p);v!==null&&(!(v.expirationTime>$e)||ge&&!oe());){var ke=v.callback;if(typeof ke=="function"){v.callback=null,E=v.priorityLevel;var Ae=ke(v.expirationTime<=$e);$e=t.unstable_now(),typeof Ae=="function"?v.callback=Ae:v===r(p)&&n(p),F($e)}else n(p);v=r(p)}if(v!==null)var He=!0;else{var ot=r(l);ot!==null&&Te($,ot.startTime-$e),He=!1}return He}finally{v=null,E=we,T=!1}}var W=!1,Z=null,Q=-1,ee=5,ie=-1;function oe(){return!(t.unstable_now()-iege||125ke?(ge.sortIndex=we,e(l,ge),r(p)===null&&ge===r(l)&&(P?(L(Q),Q=-1):P=!0,Te($,we-ke))):(ge.sortIndex=Ae,e(p,ge),j||T||(j=!0,Ie(G))),ge},t.unstable_shouldYield=oe,t.unstable_wrapCallback=function(ge){var $e=E;return function(){var we=E;E=$e;try{return ge.apply(this,arguments)}finally{E=we}}}})(oye);aye.exports=oye;var kOe=aye.exports;/** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var IOe=N,Jh=kOe;function fn(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),I8=Object.prototype.hasOwnProperty,jOe=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,wie={},Sie={};function COe(t){return I8.call(Sie,t)?!0:I8.call(wie,t)?!1:jOe.test(t)?Sie[t]=!0:(wie[t]=!0,!1)}function POe(t,e,r,n){if(r!==null&&r.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function NOe(t,e,r,n){if(e===null||typeof e>"u"||POe(t,e,r,n))return!0;if(n)return!1;if(r!==null)switch(r.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function $d(t,e,r,n,i,a,c){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=t,this.type=e,this.sanitizeURL=a,this.removeEmptyString=c}var Uu={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){Uu[t]=new $d(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];Uu[e]=new $d(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){Uu[t]=new $d(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){Uu[t]=new $d(t,2,!1,t,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(t){Uu[t]=new $d(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){Uu[t]=new $d(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){Uu[t]=new $d(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){Uu[t]=new $d(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){Uu[t]=new $d(t,5,!1,t.toLowerCase(),null,!1,!1)});var KH=/[\-:]([a-z])/g;function YH(t){return t[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(t){var e=t.replace(KH,YH);Uu[e]=new $d(e,1,!1,t,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(t){var e=t.replace(KH,YH);Uu[e]=new $d(e,1,!1,t,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(t){var e=t.replace(KH,YH);Uu[e]=new $d(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){Uu[t]=new $d(t,1,!1,t.toLowerCase(),null,!1,!1)});Uu.xlinkHref=new $d("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){Uu[t]=new $d(t,1,!1,t.toLowerCase(),null,!0,!0)});function ZH(t,e,r,n){var i=Uu.hasOwnProperty(e)?Uu[e]:null;(i!==null?i.type!==0:n||!(2d||i[c]!==a[d]){var p=` `+i[c].replace(" at new "," at ");return t.displayName&&p.includes("")&&(p=p.replace("",t.displayName)),p}while(1<=c&&0<=d);break}}}finally{p6=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?jI(t):""}function ROe(t){switch(t.tag){case 5:return jI(t.type);case 16:return jI("Lazy");case 13:return jI("Suspense");case 19:return jI("SuspenseList");case 0:case 2:case 15:return t=g6(t.type,!1),t;case 11:return t=g6(t.type.render,!1),t;case 1:return t=g6(t.type,!0),t;default:return""}}function N8(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case HS:return"Fragment";case GS:return"Portal";case j8:return"Profiler";case XH:return"StrictMode";case C8:return"Suspense";case P8:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case uye:return(t.displayName||"Context")+".Consumer";case cye:return(t._context.displayName||"Context")+".Provider";case QH:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case JH:return e=t.displayName||null,e!==null?e:N8(t.type)||"Memo";case k_:e=t._payload,t=t._init;try{return N8(t(e))}catch{}}return null}function LOe(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return N8(e);case 8:return e===XH?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function pv(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function hye(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function DOe(t){var e=hye(t)?"checked":"value",r=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),n=""+t[e];if(!t.hasOwnProperty(e)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var i=r.get,a=r.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return i.call(this)},set:function(c){n=""+c,a.call(this,c)}}),Object.defineProperty(t,e,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(c){n=""+c},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function HL(t){t._valueTracker||(t._valueTracker=DOe(t))}function fye(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=hye(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function CO(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function R8(t,e){var r=e.checked;return pl({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function Tie(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=pv(e.value!=null?e.value:r),t._wrapperState={initialChecked:n,initialValue:r,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function mye(t,e){e=e.checked,e!=null&&ZH(t,"checked",e,!1)}function L8(t,e){mye(t,e);var r=pv(e.value),n=e.type;if(r!=null)n==="number"?(r===0&&t.value===""||t.value!=r)&&(t.value=""+r):t.value!==""+r&&(t.value=""+r);else if(n==="submit"||n==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?D8(t,e.type,r):e.hasOwnProperty("defaultValue")&&D8(t,e.type,pv(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function Aie(t,e,r){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var n=e.type;if(!(n!=="submit"&&n!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,r||e===t.value||(t.value=e),t.defaultValue=e}r=t.name,r!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,r!==""&&(t.name=r)}function D8(t,e,r){(e!=="number"||CO(t.ownerDocument)!==t)&&(r==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+r&&(t.defaultValue=""+r))}var CI=Array.isArray;function fE(t,e,r,n){if(t=t.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=WL.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function jj(t,e){if(e){var r=t.firstChild;if(r&&r===t.lastChild&&r.nodeType===3){r.nodeValue=e;return}}t.textContent=e}var HI={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},MOe=["Webkit","ms","Moz","O"];Object.keys(HI).forEach(function(t){MOe.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),HI[e]=HI[t]})});function xye(t,e,r){return e==null||typeof e=="boolean"||e===""?"":r||typeof e!="number"||e===0||HI.hasOwnProperty(t)&&HI[t]?(""+e).trim():e+"px"}function _ye(t,e){t=t.style;for(var r in e)if(e.hasOwnProperty(r)){var n=r.indexOf("--")===0,i=xye(r,e[r],n);r==="float"&&(r="cssFloat"),n?t.setProperty(r,i):t[r]=i}}var OOe=pl({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function F8(t,e){if(e){if(OOe[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(fn(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(fn(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(fn(61))}if(e.style!=null&&typeof e.style!="object")throw Error(fn(62))}}function B8(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var z8=null;function eW(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var $8=null,mE=null,pE=null;function jie(t){if(t=kP(t)){if(typeof $8!="function")throw Error(fn(280));var e=t.stateNode;e&&(e=u4(e),$8(t.stateNode,t.type,e))}}function vye(t){mE?pE?pE.push(t):pE=[t]:mE=t}function bye(){if(mE){var t=mE,e=pE;if(pE=mE=null,jie(t),e)for(t=0;t>>=0,t===0?32:31-(KOe(t)/YOe|0)|0}var KL=64,YL=4194304;function PI(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function LO(t,e){var r=t.pendingLanes;if(r===0)return 0;var n=0,i=t.suspendedLanes,a=t.pingedLanes,c=r&268435455;if(c!==0){var d=c&~i;d!==0?n=PI(d):(a&=c,a!==0&&(n=PI(a)))}else c=r&~i,c!==0?n=PI(c):a!==0&&(n=PI(a));if(n===0)return 0;if(e!==0&&e!==n&&!(e&i)&&(i=n&-n,a=e&-e,i>=a||i===16&&(a&4194240)!==0))return e;if(n&4&&(n|=r&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=n;0r;r++)e.push(t);return e}function TP(t,e,r){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-Xm(e),t[e]=r}function JOe(t,e){var r=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var n=t.eventTimes;for(t=t.expirationTimes;0=KI),Fie=" ",Bie=!1;function $ye(t,e){switch(t){case"keyup":return kFe.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Uye(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var WS=!1;function jFe(t,e){switch(t){case"compositionend":return Uye(e);case"keypress":return e.which!==32?null:(Bie=!0,Fie);case"textInput":return t=e.data,t===Fie&&Bie?null:t;default:return null}}function CFe(t,e){if(WS)return t==="compositionend"||!lW&&$ye(t,e)?(t=Bye(),NM=sW=K_=null,WS=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1=e)return{node:r,offset:e-t};t=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Vie(r)}}function Hye(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?Hye(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Wye(){for(var t=window,e=CO();e instanceof t.HTMLIFrameElement;){try{var r=typeof e.contentWindow.location.href=="string"}catch{r=!1}if(r)t=e.contentWindow;else break;e=CO(t.document)}return e}function cW(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function BFe(t){var e=Wye(),r=t.focusedElem,n=t.selectionRange;if(e!==r&&r&&r.ownerDocument&&Hye(r.ownerDocument.documentElement,r)){if(n!==null&&cW(r)){if(e=n.start,t=n.end,t===void 0&&(t=e),"selectionStart"in r)r.selectionStart=e,r.selectionEnd=Math.min(t,r.value.length);else if(t=(e=r.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var i=r.textContent.length,a=Math.min(n.start,i);n=n.end===void 0?a:Math.min(n.end,i),!t.extend&&a>n&&(i=n,n=a,a=i),i=qie(r,a);var c=qie(r,n);i&&c&&(t.rangeCount!==1||t.anchorNode!==i.node||t.anchorOffset!==i.offset||t.focusNode!==c.node||t.focusOffset!==c.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),t.removeAllRanges(),a>n?(t.addRange(e),t.extend(c.node,c.offset)):(e.setEnd(c.node,c.offset),t.addRange(e)))}}for(e=[],t=r;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,KS=null,W8=null,ZI=null,K8=!1;function Gie(t,e,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;K8||KS==null||KS!==CO(n)||(n=KS,"selectionStart"in n&&cW(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),ZI&&Dj(ZI,n)||(ZI=n,n=OO(W8,"onSelect"),0XS||(t.current=eq[XS],eq[XS]=null,XS--)}function Eo(t,e){XS++,eq[XS]=t.current,t.current=e}var gv={},sd=Mv(gv),dh=Mv(!1),Jb=gv;function KE(t,e){var r=t.type.contextTypes;if(!r)return gv;var n=t.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===e)return n.__reactInternalMemoizedMaskedChildContext;var i={},a;for(a in r)i[a]=e[a];return n&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=i),i}function hh(t){return t=t.childContextTypes,t!=null}function BO(){Lo(dh),Lo(sd)}function Qie(t,e,r){if(sd.current!==gv)throw Error(fn(168));Eo(sd,e),Eo(dh,r)}function rxe(t,e,r){var n=t.stateNode;if(e=e.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var i in n)if(!(i in e))throw Error(fn(108,LOe(t)||"Unknown",i));return pl({},r,n)}function zO(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||gv,Jb=sd.current,Eo(sd,t),Eo(dh,dh.current),!0}function Jie(t,e,r){var n=t.stateNode;if(!n)throw Error(fn(169));r?(t=rxe(t,e,Jb),n.__reactInternalMemoizedMergedChildContext=t,Lo(dh),Lo(sd),Eo(sd,t)):Lo(dh),Eo(dh,r)}var _y=null,d4=!1,C6=!1;function nxe(t){_y===null?_y=[t]:_y.push(t)}function XFe(t){d4=!0,nxe(t)}function Ov(){if(!C6&&_y!==null){C6=!0;var t=0,e=Ua;try{var r=_y;for(Ua=1;t>=c,i-=c,Sy=1<<32-Xm(e)+i|r<Q?(ee=Z,Z=null):ee=Z.sibling;var ie=E(L,Z,F[Q],$);if(ie===null){Z===null&&(Z=ee);break}t&&Z&&ie.alternate===null&&e(L,Z),O=a(ie,O,Q),W===null?G=ie:W.sibling=ie,W=ie,Z=ee}if(Q===F.length)return r(L,Z),Wo&&hb(L,Q),G;if(Z===null){for(;QQ?(ee=Z,Z=null):ee=Z.sibling;var oe=E(L,Z,ie.value,$);if(oe===null){Z===null&&(Z=ee);break}t&&Z&&oe.alternate===null&&e(L,Z),O=a(oe,O,Q),W===null?G=oe:W.sibling=oe,W=oe,Z=ee}if(ie.done)return r(L,Z),Wo&&hb(L,Q),G;if(Z===null){for(;!ie.done;Q++,ie=F.next())ie=v(L,ie.value,$),ie!==null&&(O=a(ie,O,Q),W===null?G=ie:W.sibling=ie,W=ie);return Wo&&hb(L,Q),G}for(Z=n(L,Z);!ie.done;Q++,ie=F.next())ie=T(Z,L,Q,ie.value,$),ie!==null&&(t&&ie.alternate!==null&&Z.delete(ie.key===null?Q:ie.key),O=a(ie,O,Q),W===null?G=ie:W.sibling=ie,W=ie);return t&&Z.forEach(function(pe){return e(L,pe)}),Wo&&hb(L,Q),G}function C(L,O,F,$){if(typeof F=="object"&&F!==null&&F.type===HS&&F.key===null&&(F=F.props.children),typeof F=="object"&&F!==null){switch(F.$$typeof){case GL:e:{for(var G=F.key,W=O;W!==null;){if(W.key===G){if(G=F.type,G===HS){if(W.tag===7){r(L,W.sibling),O=i(W,F.props.children),O.return=L,L=O;break e}}else if(W.elementType===G||typeof G=="object"&&G!==null&&G.$$typeof===k_&&rse(G)===W.type){r(L,W.sibling),O=i(W,F.props),O.ref=Kk(L,W,F),O.return=L,L=O;break e}r(L,W);break}else e(L,W);W=W.sibling}F.type===HS?(O=Hb(F.props.children,L.mode,$,F.key),O.return=L,L=O):($=zM(F.type,F.key,F.props,null,L.mode,$),$.ref=Kk(L,O,F),$.return=L,L=$)}return c(L);case GS:e:{for(W=F.key;O!==null;){if(O.key===W)if(O.tag===4&&O.stateNode.containerInfo===F.containerInfo&&O.stateNode.implementation===F.implementation){r(L,O.sibling),O=i(O,F.children||[]),O.return=L,L=O;break e}else{r(L,O);break}else e(L,O);O=O.sibling}O=F6(F,L.mode,$),O.return=L,L=O}return c(L);case k_:return W=F._init,C(L,O,W(F._payload),$)}if(CI(F))return j(L,O,F,$);if(Vk(F))return P(L,O,F,$);rD(L,F)}return typeof F=="string"&&F!==""||typeof F=="number"?(F=""+F,O!==null&&O.tag===6?(r(L,O.sibling),O=i(O,F),O.return=L,L=O):(r(L,O),O=O6(F,L.mode,$),O.return=L,L=O),c(L)):r(L,O)}return C}var ZE=oxe(!0),lxe=oxe(!1),VO=Mv(null),qO=null,eE=null,fW=null;function mW(){fW=eE=qO=null}function pW(t){var e=VO.current;Lo(VO),t._currentValue=e}function nq(t,e,r){for(;t!==null;){var n=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,n!==null&&(n.childLanes|=e)):n!==null&&(n.childLanes&e)!==e&&(n.childLanes|=e),t===r)break;t=t.return}}function yE(t,e){qO=t,fW=eE=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(ch=!0),t.firstContext=null)}function Gf(t){var e=t._currentValue;if(fW!==t)if(t={context:t,memoizedValue:e,next:null},eE===null){if(qO===null)throw Error(fn(308));eE=t,qO.dependencies={lanes:0,firstContext:t}}else eE=eE.next=t;return e}var Eb=null;function gW(t){Eb===null?Eb=[t]:Eb.push(t)}function cxe(t,e,r,n){var i=e.interleaved;return i===null?(r.next=r,gW(e)):(r.next=i.next,i.next=r),e.interleaved=r,Uy(t,n)}function Uy(t,e){t.lanes|=e;var r=t.alternate;for(r!==null&&(r.lanes|=e),r=t,t=t.return;t!==null;)t.childLanes|=e,r=t.alternate,r!==null&&(r.childLanes|=e),r=t,t=t.return;return r.tag===3?r.stateNode:null}var I_=!1;function yW(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function uxe(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function jy(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function iv(t,e,r){var n=t.updateQueue;if(n===null)return null;if(n=n.shared,oa&2){var i=n.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),n.pending=e,Uy(t,r)}return i=n.interleaved,i===null?(e.next=e,gW(n)):(e.next=i.next,i.next=e),n.interleaved=e,Uy(t,r)}function LM(t,e,r){if(e=e.updateQueue,e!==null&&(e=e.shared,(r&4194240)!==0)){var n=e.lanes;n&=t.pendingLanes,r|=n,e.lanes=r,rW(t,r)}}function nse(t,e){var r=t.updateQueue,n=t.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var i=null,a=null;if(r=r.firstBaseUpdate,r!==null){do{var c={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};a===null?i=a=c:a=a.next=c,r=r.next}while(r!==null);a===null?i=a=e:a=a.next=e}else i=a=e;r={baseState:n.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:n.shared,effects:n.effects},t.updateQueue=r;return}t=r.lastBaseUpdate,t===null?r.firstBaseUpdate=e:t.next=e,r.lastBaseUpdate=e}function GO(t,e,r,n){var i=t.updateQueue;I_=!1;var a=i.firstBaseUpdate,c=i.lastBaseUpdate,d=i.shared.pending;if(d!==null){i.shared.pending=null;var p=d,l=p.next;p.next=null,c===null?a=l:c.next=l,c=p;var g=t.alternate;g!==null&&(g=g.updateQueue,d=g.lastBaseUpdate,d!==c&&(d===null?g.firstBaseUpdate=l:d.next=l,g.lastBaseUpdate=p))}if(a!==null){var v=i.baseState;c=0,g=l=p=null,d=a;do{var E=d.lane,T=d.eventTime;if((n&E)===E){g!==null&&(g=g.next={eventTime:T,lane:0,tag:d.tag,payload:d.payload,callback:d.callback,next:null});e:{var j=t,P=d;switch(E=e,T=r,P.tag){case 1:if(j=P.payload,typeof j=="function"){v=j.call(T,v,E);break e}v=j;break e;case 3:j.flags=j.flags&-65537|128;case 0:if(j=P.payload,E=typeof j=="function"?j.call(T,v,E):j,E==null)break e;v=pl({},v,E);break e;case 2:I_=!0}}d.callback!==null&&d.lane!==0&&(t.flags|=64,E=i.effects,E===null?i.effects=[d]:E.push(d))}else T={eventTime:T,lane:E,tag:d.tag,payload:d.payload,callback:d.callback,next:null},g===null?(l=g=T,p=v):g=g.next=T,c|=E;if(d=d.next,d===null){if(d=i.shared.pending,d===null)break;E=d,d=E.next,E.next=null,i.lastBaseUpdate=E,i.shared.pending=null}}while(!0);if(g===null&&(p=v),i.baseState=p,i.firstBaseUpdate=l,i.lastBaseUpdate=g,e=i.shared.interleaved,e!==null){i=e;do c|=i.lane,i=i.next;while(i!==e)}else a===null&&(i.shared.lanes=0);rw|=c,t.lanes=c,t.memoizedState=v}}function ise(t,e,r){if(t=e.effects,e.effects=null,t!==null)for(e=0;er?r:4,t(!0);var n=N6.transition;N6.transition={};try{t(!1),e()}finally{Ua=r,N6.transition=n}}function kxe(){return Hf().memoizedState}function t3e(t,e,r){var n=av(t);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},Ixe(t))jxe(e,r);else if(r=cxe(t,e,r,n),r!==null){var i=Od();Qm(r,t,n,i),Cxe(r,e,n)}}function r3e(t,e,r){var n=av(t),i={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(Ixe(t))jxe(e,i);else{var a=t.alternate;if(t.lanes===0&&(a===null||a.lanes===0)&&(a=e.lastRenderedReducer,a!==null))try{var c=e.lastRenderedState,d=a(c,r);if(i.hasEagerState=!0,i.eagerState=d,ip(d,c)){var p=e.interleaved;p===null?(i.next=i,gW(e)):(i.next=p.next,p.next=i),e.interleaved=i;return}}catch{}finally{}r=cxe(t,e,i,n),r!==null&&(i=Od(),Qm(r,t,n,i),Cxe(r,e,n))}}function Ixe(t){var e=t.alternate;return t===fl||e!==null&&e===fl}function jxe(t,e){XI=WO=!0;var r=t.pending;r===null?e.next=e:(e.next=r.next,r.next=e),t.pending=e}function Cxe(t,e,r){if(r&4194240){var n=e.lanes;n&=t.pendingLanes,r|=n,e.lanes=r,rW(t,r)}}var KO={readContext:Gf,useCallback:Zu,useContext:Zu,useEffect:Zu,useImperativeHandle:Zu,useInsertionEffect:Zu,useLayoutEffect:Zu,useMemo:Zu,useReducer:Zu,useRef:Zu,useState:Zu,useDebugValue:Zu,useDeferredValue:Zu,useTransition:Zu,useMutableSource:Zu,useSyncExternalStore:Zu,useId:Zu,unstable_isNewReconciler:!1},n3e={readContext:Gf,useCallback:function(t,e){return Op().memoizedState=[t,e===void 0?null:e],t},useContext:Gf,useEffect:ase,useImperativeHandle:function(t,e,r){return r=r!=null?r.concat([t]):null,MM(4194308,4,wxe.bind(null,e,t),r)},useLayoutEffect:function(t,e){return MM(4194308,4,t,e)},useInsertionEffect:function(t,e){return MM(4,2,t,e)},useMemo:function(t,e){var r=Op();return e=e===void 0?null:e,t=t(),r.memoizedState=[t,e],t},useReducer:function(t,e,r){var n=Op();return e=r!==void 0?r(e):e,n.memoizedState=n.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},n.queue=t,t=t.dispatch=t3e.bind(null,fl,t),[n.memoizedState,t]},useRef:function(t){var e=Op();return t={current:t},e.memoizedState=t},useState:sse,useDebugValue:TW,useDeferredValue:function(t){return Op().memoizedState=t},useTransition:function(){var t=sse(!1),e=t[0];return t=e3e.bind(null,t[1]),Op().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,r){var n=fl,i=Op();if(Wo){if(r===void 0)throw Error(fn(407));r=r()}else{if(r=e(),ou===null)throw Error(fn(349));tw&30||mxe(n,e,r)}i.memoizedState=r;var a={value:r,getSnapshot:e};return i.queue=a,ase(gxe.bind(null,n,a,t),[t]),n.flags|=2048,Vj(9,pxe.bind(null,n,a,r,e),void 0,null),r},useId:function(){var t=Op(),e=ou.identifierPrefix;if(Wo){var r=Ey,n=Sy;r=(n&~(1<<32-Xm(n)-1)).toString(32)+r,e=":"+e+"R"+r,r=$j++,0<\/script>",t=t.removeChild(t.firstChild)):typeof n.is=="string"?t=c.createElement(r,{is:n.is}):(t=c.createElement(r),r==="select"&&(c=t,n.multiple?c.multiple=!0:n.size&&(c.size=n.size))):t=c.createElementNS(t,r),t[Wp]=e,t[Fj]=n,zxe(t,e,!1,!1),e.stateNode=t;e:{switch(c=B8(r,n),r){case"dialog":Po("cancel",t),Po("close",t),i=n;break;case"iframe":case"object":case"embed":Po("load",t),i=n;break;case"video":case"audio":for(i=0;iJE&&(e.flags|=128,n=!0,Yk(a,!1),e.lanes=4194304)}else{if(!n)if(t=HO(c),t!==null){if(e.flags|=128,n=!0,r=t.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),Yk(a,!0),a.tail===null&&a.tailMode==="hidden"&&!c.alternate&&!Wo)return Xu(e),null}else 2*Vl()-a.renderingStartTime>JE&&r!==1073741824&&(e.flags|=128,n=!0,Yk(a,!1),e.lanes=4194304);a.isBackwards?(c.sibling=e.child,e.child=c):(r=a.last,r!==null?r.sibling=c:e.child=c,a.last=c)}return a.tail!==null?(e=a.tail,a.rendering=e,a.tail=e.sibling,a.renderingStartTime=Vl(),e.sibling=null,r=dl.current,Eo(dl,n?r&1|2:r&1),e):(Xu(e),null);case 22:case 23:return PW(),n=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?$h&1073741824&&(Xu(e),e.subtreeFlags&6&&(e.flags|=8192)):Xu(e),null;case 24:return null;case 25:return null}throw Error(fn(156,e.tag))}function d3e(t,e){switch(dW(e),e.tag){case 1:return hh(e.type)&&BO(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return XE(),Lo(dh),Lo(sd),vW(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return _W(e),null;case 13:if(Lo(dl),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(fn(340));YE()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Lo(dl),null;case 4:return XE(),null;case 10:return pW(e.type._context),null;case 22:case 23:return PW(),null;case 24:return null;default:return null}}var iD=!1,td=!1,h3e=typeof WeakSet=="function"?WeakSet:Set,Wn=null;function tE(t,e){var r=t.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){kl(t,e,n)}else r.current=null}function hq(t,e,r){try{r()}catch(n){kl(t,e,n)}}var yse=!1;function f3e(t,e){if(Y8=DO,t=Wye(),cW(t)){if("selectionStart"in t)var r={start:t.selectionStart,end:t.selectionEnd};else e:{r=(r=t.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var i=n.anchorOffset,a=n.focusNode;n=n.focusOffset;try{r.nodeType,a.nodeType}catch{r=null;break e}var c=0,d=-1,p=-1,l=0,g=0,v=t,E=null;t:for(;;){for(var T;v!==r||i!==0&&v.nodeType!==3||(d=c+i),v!==a||n!==0&&v.nodeType!==3||(p=c+n),v.nodeType===3&&(c+=v.nodeValue.length),(T=v.firstChild)!==null;)E=v,v=T;for(;;){if(v===t)break t;if(E===r&&++l===i&&(d=c),E===a&&++g===n&&(p=c),(T=v.nextSibling)!==null)break;v=E,E=v.parentNode}v=T}r=d===-1||p===-1?null:{start:d,end:p}}else r=null}r=r||{start:0,end:0}}else r=null;for(Z8={focusedElem:t,selectionRange:r},DO=!1,Wn=e;Wn!==null;)if(e=Wn,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,Wn=t;else for(;Wn!==null;){e=Wn;try{var j=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(j!==null){var P=j.memoizedProps,C=j.memoizedState,L=e.stateNode,O=L.getSnapshotBeforeUpdate(e.elementType===e.type?P:Dm(e.type,P),C);L.__reactInternalSnapshotBeforeUpdate=O}break;case 3:var F=e.stateNode.containerInfo;F.nodeType===1?F.textContent="":F.nodeType===9&&F.documentElement&&F.removeChild(F.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(fn(163))}}catch($){kl(e,e.return,$)}if(t=e.sibling,t!==null){t.return=e.return,Wn=t;break}Wn=e.return}return j=yse,yse=!1,j}function QI(t,e,r){var n=e.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var i=n=n.next;do{if((i.tag&t)===t){var a=i.destroy;i.destroy=void 0,a!==void 0&&hq(e,r,a)}i=i.next}while(i!==n)}}function m4(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var r=e=e.next;do{if((r.tag&t)===t){var n=r.create;r.destroy=n()}r=r.next}while(r!==e)}}function fq(t){var e=t.ref;if(e!==null){var r=t.stateNode;switch(t.tag){case 5:t=r;break;default:t=r}typeof e=="function"?e(t):e.current=t}}function Vxe(t){var e=t.alternate;e!==null&&(t.alternate=null,Vxe(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[Wp],delete e[Fj],delete e[J8],delete e[YFe],delete e[ZFe])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function qxe(t){return t.tag===5||t.tag===3||t.tag===4}function xse(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||qxe(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function mq(t,e,r){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?r.nodeType===8?r.parentNode.insertBefore(t,e):r.insertBefore(t,e):(r.nodeType===8?(e=r.parentNode,e.insertBefore(t,r)):(e=r,e.appendChild(t)),r=r._reactRootContainer,r!=null||e.onclick!==null||(e.onclick=FO));else if(n!==4&&(t=t.child,t!==null))for(mq(t,e,r),t=t.sibling;t!==null;)mq(t,e,r),t=t.sibling}function pq(t,e,r){var n=t.tag;if(n===5||n===6)t=t.stateNode,e?r.insertBefore(t,e):r.appendChild(t);else if(n!==4&&(t=t.child,t!==null))for(pq(t,e,r),t=t.sibling;t!==null;)pq(t,e,r),t=t.sibling}var Au=null,Fm=!1;function h_(t,e,r){for(r=r.child;r!==null;)Gxe(t,e,r),r=r.sibling}function Gxe(t,e,r){if(rg&&typeof rg.onCommitFiberUnmount=="function")try{rg.onCommitFiberUnmount(a4,r)}catch{}switch(r.tag){case 5:td||tE(r,e);case 6:var n=Au,i=Fm;Au=null,h_(t,e,r),Au=n,Fm=i,Au!==null&&(Fm?(t=Au,r=r.stateNode,t.nodeType===8?t.parentNode.removeChild(r):t.removeChild(r)):Au.removeChild(r.stateNode));break;case 18:Au!==null&&(Fm?(t=Au,r=r.stateNode,t.nodeType===8?j6(t.parentNode,r):t.nodeType===1&&j6(t,r),Rj(t)):j6(Au,r.stateNode));break;case 4:n=Au,i=Fm,Au=r.stateNode.containerInfo,Fm=!0,h_(t,e,r),Au=n,Fm=i;break;case 0:case 11:case 14:case 15:if(!td&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){i=n=n.next;do{var a=i,c=a.destroy;a=a.tag,c!==void 0&&(a&2||a&4)&&hq(r,e,c),i=i.next}while(i!==n)}h_(t,e,r);break;case 1:if(!td&&(tE(r,e),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(d){kl(r,e,d)}h_(t,e,r);break;case 21:h_(t,e,r);break;case 22:r.mode&1?(td=(n=td)||r.memoizedState!==null,h_(t,e,r),td=n):h_(t,e,r);break;default:h_(t,e,r)}}function _se(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var r=t.stateNode;r===null&&(r=t.stateNode=new h3e),e.forEach(function(n){var i=w3e.bind(null,t,n);r.has(n)||(r.add(n),n.then(i,i))})}}function Sm(t,e){var r=e.deletions;if(r!==null)for(var n=0;ni&&(i=c),n&=~a}if(n=i,n=Vl()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*p3e(n/1960))-n,10t?16:t,Y_===null)var n=!1;else{if(t=Y_,Y_=null,XO=0,oa&6)throw Error(fn(331));var i=oa;for(oa|=4,Wn=t.current;Wn!==null;){var a=Wn,c=a.child;if(Wn.flags&16){var d=a.deletions;if(d!==null){for(var p=0;pVl()-jW?Gb(t,0):IW|=r),fh(t,e)}function Jxe(t,e){e===0&&(t.mode&1?(e=YL,YL<<=1,!(YL&130023424)&&(YL=4194304)):e=1);var r=Od();t=Uy(t,e),t!==null&&(TP(t,e,r),fh(t,r))}function b3e(t){var e=t.memoizedState,r=0;e!==null&&(r=e.retryLane),Jxe(t,r)}function w3e(t,e){var r=0;switch(t.tag){case 13:var n=t.stateNode,i=t.memoizedState;i!==null&&(r=i.retryLane);break;case 19:n=t.stateNode;break;default:throw Error(fn(314))}n!==null&&n.delete(e),Jxe(t,r)}var e_e;e_e=function(t,e,r){if(t!==null)if(t.memoizedProps!==e.pendingProps||dh.current)ch=!0;else{if(!(t.lanes&r)&&!(e.flags&128))return ch=!1,c3e(t,e,r);ch=!!(t.flags&131072)}else ch=!1,Wo&&e.flags&1048576&&ixe(e,UO,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;OM(t,e),t=e.pendingProps;var i=KE(e,sd.current);yE(e,r),i=wW(null,e,n,t,i,r);var a=SW();return e.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,hh(n)?(a=!0,zO(e)):a=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,yW(e),i.updater=f4,e.stateNode=i,i._reactInternals=e,sq(e,n,t,r),e=lq(null,e,n,!0,a,r)):(e.tag=0,Wo&&a&&uW(e),kd(null,e,i,r),e=e.child),e;case 16:n=e.elementType;e:{switch(OM(t,e),t=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=E3e(n),t=Dm(n,t),i){case 0:e=oq(null,e,n,t,r);break e;case 1:e=mse(null,e,n,t,r);break e;case 11:e=hse(null,e,n,t,r);break e;case 14:e=fse(null,e,n,Dm(n.type,t),r);break e}throw Error(fn(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Dm(n,i),oq(t,e,n,i,r);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Dm(n,i),mse(t,e,n,i,r);case 3:e:{if(Oxe(e),t===null)throw Error(fn(387));n=e.pendingProps,a=e.memoizedState,i=a.element,uxe(t,e),GO(e,n,null,r);var c=e.memoizedState;if(n=c.element,a.isDehydrated)if(a={element:n,isDehydrated:!1,cache:c.cache,pendingSuspenseBoundaries:c.pendingSuspenseBoundaries,transitions:c.transitions},e.updateQueue.baseState=a,e.memoizedState=a,e.flags&256){i=QE(Error(fn(423)),e),e=pse(t,e,n,r,i);break e}else if(n!==i){i=QE(Error(fn(424)),e),e=pse(t,e,n,r,i);break e}else for(Hh=nv(e.stateNode.containerInfo.firstChild),Yh=e,Wo=!0,Um=null,r=lxe(e,null,n,r),e.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(YE(),n===i){e=Vy(t,e,r);break e}kd(t,e,n,r)}e=e.child}return e;case 5:return dxe(e),t===null&&rq(e),n=e.type,i=e.pendingProps,a=t!==null?t.memoizedProps:null,c=i.children,X8(n,i)?c=null:a!==null&&X8(n,a)&&(e.flags|=32),Mxe(t,e),kd(t,e,c,r),e.child;case 6:return t===null&&rq(e),null;case 13:return Fxe(t,e,r);case 4:return xW(e,e.stateNode.containerInfo),n=e.pendingProps,t===null?e.child=ZE(e,null,n,r):kd(t,e,n,r),e.child;case 11:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Dm(n,i),hse(t,e,n,i,r);case 7:return kd(t,e,e.pendingProps,r),e.child;case 8:return kd(t,e,e.pendingProps.children,r),e.child;case 12:return kd(t,e,e.pendingProps.children,r),e.child;case 10:e:{if(n=e.type._context,i=e.pendingProps,a=e.memoizedProps,c=i.value,Eo(VO,n._currentValue),n._currentValue=c,a!==null)if(ip(a.value,c)){if(a.children===i.children&&!dh.current){e=Vy(t,e,r);break e}}else for(a=e.child,a!==null&&(a.return=e);a!==null;){var d=a.dependencies;if(d!==null){c=a.child;for(var p=d.firstContext;p!==null;){if(p.context===n){if(a.tag===1){p=jy(-1,r&-r),p.tag=2;var l=a.updateQueue;if(l!==null){l=l.shared;var g=l.pending;g===null?p.next=p:(p.next=g.next,g.next=p),l.pending=p}}a.lanes|=r,p=a.alternate,p!==null&&(p.lanes|=r),nq(a.return,r,e),d.lanes|=r;break}p=p.next}}else if(a.tag===10)c=a.type===e.type?null:a.child;else if(a.tag===18){if(c=a.return,c===null)throw Error(fn(341));c.lanes|=r,d=c.alternate,d!==null&&(d.lanes|=r),nq(c,r,e),c=a.sibling}else c=a.child;if(c!==null)c.return=a;else for(c=a;c!==null;){if(c===e){c=null;break}if(a=c.sibling,a!==null){a.return=c.return,c=a;break}c=c.return}a=c}kd(t,e,i.children,r),e=e.child}return e;case 9:return i=e.type,n=e.pendingProps.children,yE(e,r),i=Gf(i),n=n(i),e.flags|=1,kd(t,e,n,r),e.child;case 14:return n=e.type,i=Dm(n,e.pendingProps),i=Dm(n.type,i),fse(t,e,n,i,r);case 15:return Lxe(t,e,e.type,e.pendingProps,r);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Dm(n,i),OM(t,e),e.tag=1,hh(n)?(t=!0,zO(e)):t=!1,yE(e,r),Pxe(e,n,i),sq(e,n,i,r),lq(null,e,n,!0,t,r);case 19:return Bxe(t,e,r);case 22:return Dxe(t,e,r)}throw Error(fn(156,e.tag))};function t_e(t,e){return Iye(t,e)}function S3e(t,e,r,n){this.tag=t,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ff(t,e,r,n){return new S3e(t,e,r,n)}function RW(t){return t=t.prototype,!(!t||!t.isReactComponent)}function E3e(t){if(typeof t=="function")return RW(t)?1:0;if(t!=null){if(t=t.$$typeof,t===QH)return 11;if(t===JH)return 14}return 2}function ov(t,e){var r=t.alternate;return r===null?(r=Ff(t.tag,e,t.key,t.mode),r.elementType=t.elementType,r.type=t.type,r.stateNode=t.stateNode,r.alternate=t,t.alternate=r):(r.pendingProps=e,r.type=t.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=t.flags&14680064,r.childLanes=t.childLanes,r.lanes=t.lanes,r.child=t.child,r.memoizedProps=t.memoizedProps,r.memoizedState=t.memoizedState,r.updateQueue=t.updateQueue,e=t.dependencies,r.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},r.sibling=t.sibling,r.index=t.index,r.ref=t.ref,r}function zM(t,e,r,n,i,a){var c=2;if(n=t,typeof t=="function")RW(t)&&(c=1);else if(typeof t=="string")c=5;else e:switch(t){case HS:return Hb(r.children,i,a,e);case XH:c=8,i|=8;break;case j8:return t=Ff(12,r,e,i|2),t.elementType=j8,t.lanes=a,t;case C8:return t=Ff(13,r,e,i),t.elementType=C8,t.lanes=a,t;case P8:return t=Ff(19,r,e,i),t.elementType=P8,t.lanes=a,t;case dye:return g4(r,i,a,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case cye:c=10;break e;case uye:c=9;break e;case QH:c=11;break e;case JH:c=14;break e;case k_:c=16,n=null;break e}throw Error(fn(130,t==null?t:typeof t,""))}return e=Ff(c,r,e,i),e.elementType=t,e.type=n,e.lanes=a,e}function Hb(t,e,r,n){return t=Ff(7,t,n,e),t.lanes=r,t}function g4(t,e,r,n){return t=Ff(22,t,n,e),t.elementType=dye,t.lanes=r,t.stateNode={isHidden:!1},t}function O6(t,e,r){return t=Ff(6,t,null,e),t.lanes=r,t}function F6(t,e,r){return e=Ff(4,t.children!==null?t.children:[],t.key,e),e.lanes=r,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function T3e(t,e,r,n,i){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=x6(0),this.expirationTimes=x6(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=x6(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function LW(t,e,r,n,i,a,c,d,p){return t=new T3e(t,e,r,d,p),e===1?(e=1,a===!0&&(e|=8)):e=0,a=Ff(3,null,null,e),t.current=a,a.stateNode=t,a.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},yW(a),t}function A3e(t,e,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s_e)}catch(t){console.error(t)}}s_e(),sye.exports=of;var vg=sye.exports;const P3e=ea(vg);var a_e,kse=vg;a_e=kse.createRoot,kse.hydrateRoot;const N3e="modulepreload",R3e=function(t){return"/"+t},Ise={},Ge=function(e,r,n){let i=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));i=Promise.allSettled(r.map(p=>{if(p=R3e(p),p in Ise)return;Ise[p]=!0;const l=p.endsWith(".css"),g=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${g}`))return;const v=document.createElement("link");if(v.rel=l?"stylesheet":N3e,l||(v.as="script"),v.crossOrigin="",v.href=p,d&&v.setAttribute("nonce",d),document.head.appendChild(v),l)return new Promise((E,T)=>{v.addEventListener("load",E),v.addEventListener("error",()=>T(new Error(`Unable to preload CSS for ${p}`)))})}))}function a(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return i.then(c=>{for(const d of c||[])d.status==="rejected"&&a(d.reason);return e().catch(a)})},L3e=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),D3e=t=>t.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function M3e(t){return!!(t==="localhost"||t.endsWith(".localhost")||/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.endsWith(".lovable.app")||t.endsWith(".lovableproject.com")||t.endsWith(".lovable.dev")||t.endsWith(".vercel.app")||t==="relevelup.com"||t.endsWith(".relevelup.com")||t==="thelocalmove.com"||t.endsWith(".thelocalmove.com")||L3e.has(t))}function o_e(t){return l_e(t)!==null}function l_e(t){const e=D3e(t);return M3e(e)?null:e}const O3e=1,F3e=1e6;let B6=0;function B3e(){return B6=(B6+1)%Number.MAX_SAFE_INTEGER,B6.toString()}const z6=new Map,jse=t=>{if(z6.has(t))return;const e=setTimeout(()=>{z6.delete(t),tj({type:"REMOVE_TOAST",toastId:t})},F3e);z6.set(t,e)},z3e=(t,e)=>{switch(e.type){case"ADD_TOAST":return{...t,toasts:[e.toast,...t.toasts].slice(0,O3e)};case"UPDATE_TOAST":return{...t,toasts:t.toasts.map(r=>r.id===e.toast.id?{...r,...e.toast}:r)};case"DISMISS_TOAST":{const{toastId:r}=e;return r?jse(r):t.toasts.forEach(n=>{jse(n.id)}),{...t,toasts:t.toasts.map(n=>n.id===r||r===void 0?{...n,open:!1}:n)}}case"REMOVE_TOAST":return e.toastId===void 0?{...t,toasts:[]}:{...t,toasts:t.toasts.filter(r=>r.id!==e.toastId)}}},$M=[];let UM={toasts:[]};function tj(t){UM=z3e(UM,t),$M.forEach(e=>{e(UM)})}function ba({...t}){const e=B3e(),r=i=>tj({type:"UPDATE_TOAST",toast:{...i,id:e}}),n=()=>tj({type:"DISMISS_TOAST",toastId:e});return tj({type:"ADD_TOAST",toast:{...t,id:e,open:!0,onOpenChange:i=>{i||n()}}}),{id:e,dismiss:n,update:r}}function c_e(){const[t,e]=N.useState(UM);return N.useEffect(()=>($M.push(e),()=>{const r=$M.indexOf(e);r>-1&&$M.splice(r,1)}),[t]),{...t,toast:ba,dismiss:r=>tj({type:"DISMISS_TOAST",toastId:r})}}var $3e=Object.defineProperty,XT=(t,e)=>$3e(t,"name",{value:e,configurable:!0}),u_e=!!(typeof window<"u"&&window.document&&window.document.createElement);function Qr(t,e,{checkForDefaultPrevented:r=!0}={}){return XT(function(i){if(t==null||t(i),r===!1||!i||!i.defaultPrevented)return e==null?void 0:e(i)},"handleEvent")}XT(Qr,"composeEventHandlers");function U3e(t){var e;if(!u_e)throw new Error("Cannot access window outside of the DOM");return((e=t==null?void 0:t.ownerDocument)==null?void 0:e.defaultView)??window}XT(U3e,"getOwnerWindow");function vq(t){if(!u_e)throw new Error("Cannot access document outside of the DOM");return(t==null?void 0:t.ownerDocument)??document}XT(vq,"getOwnerDocument");function d_e(t,e=!1){const{activeElement:r}=vq(t);if(!(r!=null&&r.nodeName))return null;if(h_e(r)&&r.contentDocument)return d_e(r.contentDocument.body,e);if(e){const n=r.getAttribute("aria-activedescendant");if(n){const i=vq(r).getElementById(n);if(i)return i}}return r}XT(d_e,"getActiveElement");function h_e(t){return t.tagName==="IFRAME"}XT(h_e,"isFrame");var V3e=Object.defineProperty,FW=(t,e)=>V3e(t,"name",{value:e,configurable:!0});function bq(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}FW(bq,"setRef");function iw(...t){return e=>{let r=!1;const n=t.map(i=>{const a=bq(i,e);return!r&&typeof a=="function"&&(r=!0),a});if(r)return()=>{for(let i=0;iq3e(t,"name",{value:e,configurable:!0});function G3e(t,e){const r=N.createContext(e);r.displayName=t+"Context";const n=Lf(a=>{const{children:c,...d}=a,p=N.useMemo(()=>d,Object.values(d));return s.jsx(r.Provider,{value:p,children:c})},"Provider");n.displayName=t+"Provider";function i(a,c={}){const{optional:d=!1}=c,p=N.useContext(r);if(p)return p;if(e!==void 0)return e;if(!d)throw new Error(`\`${a}\` must be used within \`${t}\``)}return Lf(i,"useContext"),[n,i]}Lf(G3e,"createContext");function Nl(t,e=[]){let r=[];function n(a,c){const d=N.createContext(c);d.displayName=a+"Context";const p=r.length;r=[...r,c];const l=Lf(v=>{var L;const{scope:E,children:T,...j}=v,P=((L=E==null?void 0:E[t])==null?void 0:L[p])||d,C=N.useMemo(()=>j,Object.values(j));return s.jsx(P.Provider,{value:C,children:T})},"Provider");l.displayName=a+"Provider";function g(v,E,T={}){var L;const{optional:j=!1}=T,P=((L=E==null?void 0:E[t])==null?void 0:L[p])||d,C=N.useContext(P);if(C)return C;if(c!==void 0)return c;if(!j)throw new Error(`\`${v}\` must be used within \`${a}\``)}return Lf(g,"useContext"),[l,g]}Lf(n,"createContext");const i=Lf(()=>{const a=r.map(c=>N.createContext(c));return Lf(function(d){const p=(d==null?void 0:d[t])||a;return N.useMemo(()=>({[`__scope${t}`]:{...d,[t]:p}}),[d,p])},"useScope")},"createScope");return i.scopeName=t,[n,f_e(i,...e)]}Lf(Nl,"createContextScope");function f_e(...t){const e=t[0];if(t.length===1)return e;const r=Lf(()=>{const n=t.map(i=>({useScope:i(),scopeName:i.scopeName}));return Lf(function(a){const c=n.reduce((d,{useScope:p,scopeName:l})=>{const v=p(a)[`__scope${l}`];return{...d,...v}},{});return N.useMemo(()=>({[`__scope${e.scopeName}`]:c}),[c])},"useComposedScopes")},"createScope");return r.scopeName=e.scopeName,r}Lf(f_e,"composeContextScopes");var H3e=Object.defineProperty,cf=(t,e)=>H3e(t,"name",{value:e,configurable:!0});function sp(t){const e=N.forwardRef((r,n)=>{let{children:i,...a}=r,c=null,d=!1;const p=[];i=v_e(i),N.Children.forEach(i,E=>{var T;if(x_e(E)){d=!0;const j=E;let P="child"in j.props?j.props.child:j.props.children;for(;zW(P)&&typeof eF=="function";)P=eF(P._payload);c=W3e(j,P),p.push((T=c==null?void 0:c.props)==null?void 0:T.children)}else p.push(E)}),c?c=N.cloneElement(c,void 0,p):!d&&N.Children.count(i)===1&&N.isValidElement(i)&&(c=i);const l=c?y_e(c):void 0,g=Jn(n,l);if(!c){if(i||i===0)throw new Error(d?Z3e(t):Y3e(t));return i}const v=g_e(a,c.props??{});return c.type!==N.Fragment&&(v.ref=n?g:l),N.cloneElement(c,v)});return e.displayName=`${t}.Slot`,e}cf(sp,"createSlot");var m_e=sp("Slot"),p_e=Symbol.for("radix.slottable");function BW(t){const e=cf(r=>"child"in r?r.children(r.child):r.children,"Slottable");return e.displayName=`${t}.Slottable`,e.__radixId=p_e,e}cf(BW,"createSlottable");var W3e=cf((t,e)=>"child"in t.props?N.isValidElement(e)?N.cloneElement(e,void 0,t.props.children(e.props.children)):null:N.isValidElement(e)?e:null,"getSlottableElementFromSlottable");function g_e(t,e){const r={...e};for(const n in e){const i=t[n],a=e[n];/^on[A-Z]/.test(n)?i&&a?r[n]=(...d)=>{const p=a(...d);return i(...d),p}:i&&(r[n]=i):n==="style"?r[n]={...i,...a}:n==="className"?r[n]=[i,a].filter(Boolean).join(" "):n==="aria-describedby"&&(r[n]=b_e(a,i))}return{...t,...r}}cf(g_e,"mergeProps");function y_e(t){var n,i;let e=(n=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:n.get,r=e&&"isReactWarning"in e&&e.isReactWarning;return r?t.ref:(e=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=e&&"isReactWarning"in e&&e.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}cf(y_e,"getElementRef");function x_e(t){return N.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===p_e}cf(x_e,"isSlottable");var K3e=Symbol.for("react.lazy");function zW(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===K3e&&"_payload"in t&&__e(t._payload)}cf(zW,"isLazyComponent");function __e(t){return typeof t=="object"&&t!==null&&"then"in t}cf(__e,"isPromiseLike");function v_e(t){let e=t;for(;zW(e)&&typeof eF=="function";)e=eF(e._payload);return e}cf(v_e,"useUnwrappedLazy");function b_e(...t){const e=new Set;for(const r of t)if(typeof r=="string")for(const n of String(r).trim().split(/\s+/))n&&e.add(n);return e.size>0?Array.from(e).join(" "):void 0}cf(b_e,"concatAriaDescribedby");var Y3e=cf(t=>`${t} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),Z3e=cf(t=>`${t} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),eF=ex[" use ".trim().toString()],no=globalThis!=null&&globalThis.document?N.useLayoutEffect:()=>{},X3e=Object.defineProperty,Rc=(t,e)=>X3e(t,"name",{value:e,configurable:!0});function QT(t){const e=t+"CollectionProvider",[r,n]=Nl(e),[i,a]=r(e,{collectionRef:{current:null},itemMap:new Map}),c=Rc(P=>{const{scope:C,children:L}=P,O=N.useRef(null),F=N.useRef(new Map).current;return s.jsx(i,{scope:C,itemMap:F,collectionRef:O,children:L})},"CollectionProvider");c.displayName=e;const d=t+"CollectionSlot",p=sp(d),l=N.forwardRef((P,C)=>{const{scope:L,children:O}=P,F=a(d,L),$=Jn(C,F.collectionRef);return s.jsx(p,{ref:$,children:O})});l.displayName=d;const g=t+"CollectionItemSlot",v="data-radix-collection-item",E=sp(g),T=N.forwardRef((P,C)=>{const{scope:L,children:O,...F}=P,$=N.useRef(null),G=Jn(C,$),W=a(g,L);return N.useEffect(()=>(W.itemMap.set($,{ref:$,...F}),()=>void W.itemMap.delete($))),s.jsx(E,{[v]:"",ref:G,children:O})});T.displayName=g;function j(P){const C=a(t+"CollectionConsumer",P);return N.useCallback(()=>{const O=C.collectionRef.current;if(!O)return[];const F=Array.from(O.querySelectorAll(`[${v}]`));return Array.from(C.itemMap.values()).sort((W,Z)=>F.indexOf(W.ref.current)-F.indexOf(Z.ref.current))},[C.collectionRef,C.itemMap])}return Rc(j,"useCollection"),[{Provider:c,Slot:l,ItemSlot:T},j,n]}Rc(QT,"createCollection");var Cse=new WeakMap,$l,Vh,oD=(Vh=class extends Map{constructor(r){super(r);hi(this,$l);In(this,$l,[...super.keys()]),Cse.set(this,!0)}set(r,n){return Cse.get(this)&&!this.has(r)&&Nt(this,$l).push(r),super.set(r,n),this}insert(r,n,i){const a=this.has(n),c=a?this.size:this.size+1,d=$W(r),p=d>=0?Math.min(d,c-1):Math.max(c+d,0);if(a?Nt(this,$l).indexOf(n)===p:p===this.size)return this.set(n,i),this;const l=Nt(this,$l).filter(v=>v!==n);l.splice(p,0,n);const g=l.map(v=>[v,v===n?i:this.get(v)]);this.clear();for(const[v,E]of g)this.set(v,E);return this}with(r,n,i){const a=new Vh(this);return a.insert(r,n,i),a}before(r){const n=Nt(this,$l).indexOf(r)-1;if(!(n<0))return this.entryAt(n)}setBefore(r,n,i){const a=Nt(this,$l).indexOf(r);if(a===-1)return this;const c=Nt(this,$l).indexOf(n),d=c!==-1&&c=this.size&&(a=this.size-1),this.at(a)}keyFrom(r,n){const i=this.indexOf(r);if(i===-1)return;let a=i+n;return a<0&&(a=0),a>=this.size&&(a=this.size-1),this.keyAt(a)}find(r,n){let i=0;for(const a of this){if(Reflect.apply(r,n,[a,i,this]))return a;i++}}findIndex(r,n){let i=0;for(const a of this){if(Reflect.apply(r,n,[a,i,this]))return i;i++}return-1}filter(r,n){const i=[];let a=0;for(const c of this)Reflect.apply(r,n,[c,a,this])&&i.push(c),a++;return new Vh(i)}map(r,n){const i=[];let a=0;for(const c of this)i.push([c[0],Reflect.apply(r,n,[c,a,this])]),a++;return new Vh(i)}reduce(...r){const[n,i]=r,a=r.length>1;if(!a&&this.size===0)throw new TypeError("Reduce of empty OrderedDict with no initial value");let c=0,d=i;for(const p of this)c===0&&!a?d=p:d=Reflect.apply(n,this,[d,p,c,this]),c++;return d}reduceRight(...r){const[n,i]=r,a=r.length>1;if(!a&&this.size===0)throw new TypeError("Reduce of empty OrderedDict with no initial value");let c=i;for(let d=this.size-1;d>=0;d--){const p=this.entryAt(d);d===this.size-1&&!a?c=p:c=Reflect.apply(n,this,[c,p,d,this])}return c}sort(r){if(typeof r!="function")throw new TypeError("OrderedDict.sort requires a compare function");const n=[...this.entries()].sort(r);this.clear();for(const[i,a]of n)this.set(i,a);return this}toSorted(r){if(typeof r!="function")throw new TypeError("OrderedDict.toSorted requires a compare function");const n=[...this.entries()].sort(r);return new Vh(n)}toReversed(){const r=new Vh;for(let n=this.size-1;n>=0;n--){const i=this.keyAt(n),a=this.get(i);r.set(i,a)}return r}toSpliced(...r){const n=[...this.entries()];return n.splice(...r),new Vh(n)}slice(r,n){const i=new Vh;for(const a of Nt(this,$l).slice(r,n))i.set(a,this.get(a));return i}every(r,n){let i=0;for(const a of this){if(!Reflect.apply(r,n,[a,i,this]))return!1;i++}return!0}some(r,n){let i=0;for(const a of this){if(Reflect.apply(r,n,[a,i,this]))return!0;i++}return!1}},$l=new WeakMap,Rc(Vh,"OrderedDict"),Vh);function VM(t,e){if("at"in Array.prototype)return Array.prototype.at.call(t,e);const r=w_e(t,e);return r===-1?void 0:t[r]}Rc(VM,"at");function w_e(t,e){const r=t.length,n=$W(e),i=n>=0?n:r+n;return i<0||i>=r?-1:i}Rc(w_e,"toSafeIndex");function $W(t){return t!==t||t===0?0:Math.trunc(t)}Rc($W,"toSafeInteger");function Q3e(t){const e=t+"CollectionProvider",[r,n]=Nl(e),[i,a]=r(e);i.displayName=t+"CollectionStableContextProvider";const[c,d]=r(e);c.displayName=t+"CollectionStatefulContextProvider";const p=Rc(({state:W,...Z})=>W?s.jsx(g,{...Z,state:W}):s.jsx(l,{...Z}),"CollectionProvider");p.displayName=e;const l=Rc(W=>{const Z=O();return s.jsx(g,{...W,state:Z})},"CollectionInit");l.displayName=t+"CollectionInit";const g=Rc(W=>{const{scope:Z,children:Q,state:ee}=W,ie=N.useRef(null),[oe,pe]=N.useState(null),Le=Jn(ie,pe),[be,Re]=ee,Ie=N.useRef(new oD),Te=N.useCallback(()=>{const ge=Ie.current;return T_e(ge)||ge.sort(qM),ge},[]);return N.useEffect(()=>{if(!oe)return;const ge=A_e(()=>{Re($e=>{const we=$e.toSorted(qM);return we.some(([Ae],He)=>$e.keyAt(He)!==Ae)?we:$e})});return ge.observe(oe,{childList:!0,subtree:!0}),()=>{ge.disconnect()}},[oe,Re]),s.jsx(i,{scope:Z,collectionElementRef:Le,collectionElementRefObject:ie,getCollection:Te,setCollection:Re,registryRef:Ie,children:s.jsx(c,{scope:Z,collectionElement:oe,collection:be,children:Q})})},"CollectionProviderImpl");g.displayName=t+"CollectionProviderImpl";const v=t+"CollectionSlot",E=sp(v),T=N.forwardRef((W,Z)=>{const{scope:Q,children:ee}=W,ie=a(v,Q),oe=Jn(Z,ie.collectionElementRef);return s.jsx(E,{ref:oe,children:ee})});T.displayName=v;const j=t+"CollectionItemSlot",P="data-radix-collection-item",C=sp(j),L=N.forwardRef((W,Z)=>{const{scope:Q,children:ee,...ie}=W,oe=N.useRef(null),pe=a(j,Q),{setCollection:Le,registryRef:be}=pe,Re=N.useRef(ie);S_e(Re.current,ie)||(Re.current=ie);const Ie=Re.current,Te=N.useCallback(we=>{const ke=be.current;we?ke.set(we,{...Re.current,element:we}):oe.current&&ke.delete(oe.current)},[be]),ge=Jn(Z,Te,oe);no(()=>{const we=oe.current,ke=be.current;we&&ke.has(we)&&ke.set(we,{...Ie,element:we})},[Ie,be]);const $e=N.useRef(null);return N.useEffect(()=>{const we=oe.current,ke=$e.current;((ke==null?void 0:ke.element)??null)===we&&(!we||(ke==null?void 0:ke.itemData)===Ie)||($e.current=we?{element:we,itemData:Ie}:null,Le(Ae=>{const He=new oD(Ae);return ke&&ke.element!==we&&He.delete(ke.element),we&&He.set(we,{...Ie,element:we}),He.sort(qM)}))}),N.useEffect(()=>()=>{const we=$e.current;$e.current=null,we&&Le(ke=>{if(!ke.has(we.element))return ke;const Ae=new oD(ke);return Ae.delete(we.element),Ae})},[Le]),s.jsx(C,{[P]:"",ref:ge,children:ee})});L.displayName=j;function O(){return N.useState(new oD)}Rc(O,"useInitCollection");function F(W){const{collection:Z}=d(t+"CollectionConsumer",W);return Z}Rc(F,"useCollection");function $(W){const{getCollection:Z}=a(t+"CollectionConsumer",W);return Z}return Rc($,"useGetCollection"),[{Provider:p,Slot:T,ItemSlot:L},{createCollectionScope:n,useCollection:F,useGetCollection:$,useInitCollection:O}]}Rc(Q3e,"createCollection");function S_e(t,e){if(t===e)return!0;if(typeof t!="object"||typeof e!="object"||t==null||e==null)return!1;const r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(const i of r)if(!Object.prototype.hasOwnProperty.call(e,i)||t[i]!==e[i])return!1;return!0}Rc(S_e,"shallowEqual");function E_e(t,e){return!!(e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_PRECEDING)}Rc(E_e,"isElementPreceding");function T_e(t){let e;for(const r of t.keys()){if(e){const n=e.compareDocumentPosition(r);if(!(n&Node.DOCUMENT_POSITION_DISCONNECTED)&&n&Node.DOCUMENT_POSITION_PRECEDING)return!1}e=r}return!0}Rc(T_e,"isInDocumentOrder");function qM(t,e){return!t[1].element||!e[1].element?0:E_e(t[1].element,e[1].element)?-1:1}Rc(qM,"sortByDocumentPosition");function A_e(t){return new MutationObserver(r=>{for(const n of r)if(n.type==="childList"){t();return}})}Rc(A_e,"getChildListObserver");var J3e=Object.defineProperty,e4e=(t,e)=>J3e(t,"name",{value:e,configurable:!0}),t4e=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],An=t4e.reduce((t,e)=>{const r=sp(`Primitive.${e}`),n=N.forwardRef((i,a)=>{const{asChild:c,...d}=i,p=c?r:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(p,{...d,ref:a})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{});function b4(t,e){t&&vg.flushSync(()=>t.dispatchEvent(e))}e4e(b4,"dispatchDiscreteCustomEvent");var r4e=Object.defineProperty,n4e=(t,e)=>r4e(t,"name",{value:e,configurable:!0}),Pse=ex[" useInsertionEffect ".trim().toString()];function Yo(t){const e=N.useRef(t);return typeof Pse=="function"?Pse(()=>{e.current=t}):no(()=>{e.current=t}),N.useMemo(()=>(...r)=>{var n;return(n=e.current)==null?void 0:n.call(e,...r)},[])}n4e(Yo,"useCallbackRef");var i4e=Object.defineProperty,Nc=(t,e)=>i4e(t,"name",{value:e,configurable:!0}),wq="dismissableLayer.update",s4e="dismissableLayer.pointerDownOutside",a4e="dismissableLayer.focusOutside",Nse,UW=N.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),JT=N.forwardRef(Nc(function(e,r){const{disableOutsidePointerEvents:n=!1,deferPointerDownOutside:i=!1,onEscapeKeyDown:a,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:p,onDismiss:l,...g}=e,v=N.useContext(UW),[E,T]=N.useState(null),j=(E==null?void 0:E.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,P]=N.useState({}),C=Jn(r,T),L=Array.from(v.layers),[O]=[...v.layersWithOutsidePointerEventsDisabled].slice(-1),F=O?L.indexOf(O):-1,$=E?L.indexOf(E):-1,G=v.layersWithOutsidePointerEventsDisabled.size>0,W=$>=F,Z=N.useRef(!1),Q=I_e(pe=>{c==null||c(pe),p==null||p(pe),pe.defaultPrevented||l==null||l()},{ownerDocument:j,deferPointerDownOutside:i,isDeferredPointerDownOutsideRef:Z,dismissableSurfaces:v.dismissableSurfaces,shouldHandlePointerDownOutside:N.useCallback(pe=>{if(!(pe instanceof Node))return!1;const Le=[...v.branches].some(be=>be.contains(pe));return W&&!Le},[v.branches,W])}),ee=j_e(pe=>{if(i&&Z.current)return;const Le=pe.target;[...v.branches].some(Re=>Re.contains(Le))||(d==null||d(pe),p==null||p(pe),pe.defaultPrevented||l==null||l())},j),ie=E?$===L.length-1:!1,oe=Yo(pe=>{pe.key==="Escape"&&(a==null||a(pe),!pe.defaultPrevented&&l&&(pe.preventDefault(),l()))});return N.useEffect(()=>{if(ie)return j.addEventListener("keydown",oe,{capture:!0}),()=>j.removeEventListener("keydown",oe,{capture:!0})},[j,ie,oe]),N.useEffect(()=>{if(E)return n&&(v.layersWithOutsidePointerEventsDisabled.size===0&&(Nse=j.body.style.pointerEvents,j.body.style.pointerEvents="none"),v.layersWithOutsidePointerEventsDisabled.add(E)),v.layers.add(E),Sq(),()=>{n&&(v.layersWithOutsidePointerEventsDisabled.delete(E),v.layersWithOutsidePointerEventsDisabled.size===0&&(j.body.style.pointerEvents=Nse))}},[E,j,n,v]),N.useEffect(()=>()=>{E&&(v.layers.delete(E),v.layersWithOutsidePointerEventsDisabled.delete(E),Sq())},[E,v]),N.useEffect(()=>{const pe=Nc(()=>P({}),"handleUpdate");return document.addEventListener(wq,pe),()=>document.removeEventListener(wq,pe)},[]),s.jsx(An.div,{...g,ref:C,style:{pointerEvents:G?W?"auto":"none":void 0,...e.style},onFocusCapture:Qr(e.onFocusCapture,ee.onFocusCapture),onBlurCapture:Qr(e.onBlurCapture,ee.onBlurCapture),onPointerDownCapture:Qr(e.onPointerDownCapture,Q.onPointerDownCapture)})},"DismissableLayer")),o4e=N.forwardRef(Nc(function(e,r){const n=N.useContext(UW),i=N.useRef(null),a=Jn(r,i);return N.useEffect(()=>{const c=i.current;if(c)return n.branches.add(c),()=>{n.branches.delete(c)}},[n.branches]),s.jsx(An.div,{...e,ref:a})},"DismissableLayerBranch"));function k_e(){const t=N.useContext(UW),[e,r]=N.useState(null);return N.useEffect(()=>{if(e)return t.dismissableSurfaces.add(e),()=>{t.dismissableSurfaces.delete(e)}},[e,t.dismissableSurfaces]),r}Nc(k_e,"useDismissableLayerSurface");var l4e=Nc(()=>!0,"IS_TRUE");function I_e(t,e){const{ownerDocument:r=globalThis==null?void 0:globalThis.document,deferPointerDownOutside:n=!1,isDeferredPointerDownOutsideRef:i,dismissableSurfaces:a,shouldHandlePointerDownOutside:c=l4e}=e,d=Yo(t),p=N.useRef(!1),l=N.useRef(!1),g=N.useRef(new Map),v=N.useRef(()=>{});return N.useEffect(()=>{function E(){l.current=!1,i.current=!1,g.current.clear()}Nc(E,"resetOutsideInteraction");function T(){return Array.from(g.current.values()).some(Boolean)}Nc(T,"isOutsideInteractionIntercepted");function j(F){if(!l.current)return;const $=F.target;$ instanceof Node&&[...a].some(W=>W.contains($))||g.current.set(F.type,!0),F.type==="click"&&window.setTimeout(()=>{l.current&&v.current()},0)}Nc(j,"handleInteractionCapture");function P(F){l.current&&g.current.set(F.type,!1)}Nc(P,"handleInteractionBubble");const C=Nc(F=>{if(F.target&&!p.current){let $=function(){r.removeEventListener("click",v.current);const W=T();E(),W||VW(s4e,d,G,{discrete:!0})};if(Nc($,"handleAndDispatchPointerDownOutsideEvent"),!c(F.target)){r.removeEventListener("click",v.current),E(),p.current=!1;return}const G={originalEvent:F};l.current=!0,i.current=n&&F.button===0,g.current.clear(),!n||F.button!==0?$():(r.removeEventListener("click",v.current),v.current=$,r.addEventListener("click",v.current,{once:!0}))}else r.removeEventListener("click",v.current),E();p.current=!1},"handlePointerDown"),L=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const F of L)r.addEventListener(F,j,!0),r.addEventListener(F,P);const O=window.setTimeout(()=>{r.addEventListener("pointerdown",C)},0);return()=>{window.clearTimeout(O),r.removeEventListener("pointerdown",C),r.removeEventListener("click",v.current);for(const F of L)r.removeEventListener(F,j,!0),r.removeEventListener(F,P)}},[r,d,n,i,a,c]),{onPointerDownCapture:Nc(()=>p.current=!0,"onPointerDownCapture")}}Nc(I_e,"usePointerDownOutside");function j_e(t,e=globalThis==null?void 0:globalThis.document){const r=Yo(t),n=N.useRef(!1);return N.useEffect(()=>{const i=Nc(a=>{a.target&&!n.current&&VW(a4e,r,{originalEvent:a},{discrete:!1})},"handleFocus");return e.addEventListener("focusin",i),()=>e.removeEventListener("focusin",i)},[e,r]),{onFocusCapture:Nc(()=>n.current=!0,"onFocusCapture"),onBlurCapture:Nc(()=>n.current=!1,"onBlurCapture")}}Nc(j_e,"useFocusOutside");function Sq(){const t=new CustomEvent(wq);document.dispatchEvent(t)}Nc(Sq,"dispatchUpdate");function VW(t,e,r,{discrete:n}){const i=r.originalEvent.target,a=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:r});e&&i.addEventListener(t,e,{once:!0}),n?b4(i,a):i.dispatchEvent(a)}Nc(VW,"handleAndDispatchCustomEvent");var c4e=Object.defineProperty,u4e=(t,e)=>c4e(t,"name",{value:e,configurable:!0}),jP=N.forwardRef(u4e(function(e,r){var p;const{container:n,...i}=e,[a,c]=N.useState(!1);no(()=>c(!0),[]);const d=n||a&&((p=globalThis==null?void 0:globalThis.document)==null?void 0:p.body);return d?vg.createPortal(s.jsx(An.div,{...i,ref:r}),d):null},"Portal")),d4e=Object.defineProperty,qy=(t,e)=>d4e(t,"name",{value:e,configurable:!0});function C_e(t,e){return N.useReducer((r,n)=>e[r][n]??r,t)}qy(C_e,"useStateMachine");var zc=qy(t=>{const{present:e,children:r}=t,n=P_e(e),i=typeof r=="function"?r({present:n.isPresent}):N.Children.only(r),a=N_e(n.ref,R_e(i));return typeof r=="function"||n.isPresent?N.cloneElement(i,{ref:a}):null},"Presence");function P_e(t){const[e,r]=N.useState(),n=N.useRef(null),i=N.useRef(t),a=N.useRef("none"),c=N.useRef(void 0),d=t?"mounted":"unmounted",[p,l]=C_e(d,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return N.useEffect(()=>{p==="mounted"?(a.current=c.current??FS(n.current),c.current=void 0):a.current="none"},[p]),no(()=>{const g=n.current,v=i.current;if(v!==t){const T=a.current,j=FS(g);t?(c.current=j,l("MOUNT")):j==="none"||(g==null?void 0:g.display)==="none"?l("UNMOUNT"):l(v&&T!==j?"ANIMATION_OUT":"UNMOUNT"),i.current=t}},[t,l]),no(()=>{if(e){let g;const v=e.ownerDocument.defaultView??window,E=qy(j=>{const C=FS(n.current).includes(CSS.escape(j.animationName));if(j.target===e&&C&&(l("ANIMATION_END"),!i.current)){const L=e.style.animationFillMode;e.style.animationFillMode="forwards",g=v.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=L)})}},"handleAnimationEnd"),T=qy(j=>{j.target===e&&(a.current=FS(n.current))},"handleAnimationStart");return e.addEventListener("animationstart",T),e.addEventListener("animationcancel",E),e.addEventListener("animationend",E),()=>{v.clearTimeout(g),e.removeEventListener("animationstart",T),e.removeEventListener("animationcancel",E),e.removeEventListener("animationend",E)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(p),ref:N.useCallback(g=>{if(g){const v=getComputedStyle(g);n.current=v,c.current=FS(v)}else n.current=null;r(g)},[])}}qy(P_e,"usePresence");function Eq(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}qy(Eq,"setRef");function N_e(...t){const e=N.useRef(t);return e.current=t,N.useCallback(r=>{const n=e.current;let i=!1;const a=n.map(c=>{const d=Eq(c,r);return!i&&typeof d=="function"&&(i=!0),d});if(i)return()=>{for(let c=0;ch4e(t,"name",{value:e,configurable:!0}),Rse=ex[" useEffectEvent ".trim().toString()],Lse=ex[" useInsertionEffect ".trim().toString()];function L_e(t){if(typeof Rse=="function")return Rse(t);const e=N.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof Lse=="function"?Lse(()=>{e.current=t}):no(()=>{e.current=t}),N.useMemo(()=>(...r)=>{var n;return(n=e.current)==null?void 0:n.call(e,...r)},[])}f4e(L_e,"useEffectEvent");var m4e=Object.defineProperty,CP=(t,e)=>m4e(t,"name",{value:e,configurable:!0}),p4e=ex[" useInsertionEffect ".trim().toString()]||no;function ph({prop:t,defaultProp:e,onChange:r=CP(()=>{},"onChange"),caller:n}){const[i,a,c]=D_e({defaultProp:e,onChange:r}),d=t!==void 0,p=d?t:i,l=N.useCallback(g=>{var v;if(d){const E=M_e(g)?g(t):g;E!==t&&((v=c.current)==null||v.call(c,E))}else a(g)},[d,t,a,c]);return[p,l]}CP(ph,"useControllableState");function D_e({defaultProp:t,onChange:e}){const[r,n]=N.useState(t),i=N.useRef(r),a=N.useRef(e);return p4e(()=>{a.current=e},[e]),N.useEffect(()=>{var c;i.current!==r&&((c=a.current)==null||c.call(a,r),i.current=r)},[r,i]),[r,n,a]}CP(D_e,"useUncontrolledState");function M_e(t){return typeof t=="function"}CP(M_e,"isFunction");var Dse=Symbol("RADIX:SYNC_STATE");function g4e(t,e,r,n){const{prop:i,defaultProp:a,onChange:c,caller:d}=e,p=i!==void 0,l=L_e(c),g=[{...r,state:a}];n&&g.push(n);const[v,E]=N.useReducer((C,L)=>{if(L.type===Dse)return{...C,state:L.state};const O=t(C,L);return p&&!Object.is(O.state,C.state)&&l(O.state),O},...g),T=v.state,j=N.useRef(T);N.useEffect(()=>{j.current!==T&&(j.current=T,p||l(T))},[T,j,p]);const P=N.useMemo(()=>i!==void 0?{...v,state:i}:v,[v,i]);return N.useEffect(()=>{p&&!Object.is(i,v.state)&&E({type:Dse,state:i})},[i,v.state,p]),[P,E]}CP(g4e,"useControllableStateReducer");var y4e=Object.defineProperty,x4e=(t,e)=>y4e(t,"name",{value:e,configurable:!0}),O_e=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),qW=N.forwardRef(x4e(function(e,r){return s.jsx(An.span,{...e,ref:r,style:{...O_e,...e.style}})},"VisuallyHidden")),_4e=Object.defineProperty,eo=(t,e)=>_4e(t,"name",{value:e,configurable:!0}),Mse=ex[" startTransition ".trim().toString()]||(()=>{}),F_e="ToastProvider",[GW,B_e,v4e]=QT("Toast"),Tq={Left:"left",Right:"right"},Ose={Foreground:"foreground"},[z_e,MWt]=Nl("Toast",[v4e]),[b4e,w4]=z_e(F_e);function GM(t){typeof Mse=="function"?Mse(t):t()}eo(GM,"scheduleUpdate");var w4e=eo(t=>{const{__scopeToast:e,label:r="Notification",duration:n=5e3,swipeDirection:i=Tq.Right,swipeThreshold:a=50,announcerContainer:c,children:d}=t,[p,l]=N.useState(null),[g,v]=N.useState(0),E=N.useRef(!1),T=N.useCallback(C=>{GM(()=>l(C))},[]),j=N.useCallback(()=>{GM(()=>v(C=>C+1))},[]),P=N.useCallback(()=>{GM(()=>v(C=>C-1))},[]);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${F_e}\`. Expected non-empty \`string\`.`),s.jsx(GW.Provider,{scope:e,children:s.jsx(b4e,{scope:e,label:r,duration:n,swipeDirection:i,swipeThreshold:a,toastCount:g,viewport:p,onViewportChange:T,onToastAdd:j,onToastRemove:P,isClosePausedRef:E,announcerContainer:c,children:d})})},"ToastProvider"),S4e="ToastViewport",E4e=["F8"],Aq="toast.viewportPause",kq="toast.viewportResume",$_e=N.forwardRef(eo(function(e,r){const{__scopeToast:n,hotkey:i=E4e,label:a="Notifications ({hotkey})",...c}=e,d=w4(S4e,n),p=B_e(n),l=N.useRef(null),g=N.useRef(null),v=N.useRef(null),E=N.useRef(null),T=Jn(r,E,d.onViewportChange),j=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),P=d.toastCount>0;N.useEffect(()=>{const L=eo(O=>{var $;i.length!==0&&i.every(G=>O[G]||O.code===G)&&(($=E.current)==null||$.focus())},"handleKeyDown");return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[i]),N.useEffect(()=>{const L=l.current,O=E.current;if(P&&L&&O){const F=eo(()=>{if(!d.isClosePausedRef.current){const Z=new CustomEvent(Aq);O.dispatchEvent(Z),d.isClosePausedRef.current=!0}},"handlePause"),$=eo(()=>{if(d.isClosePausedRef.current){const Z=new CustomEvent(kq);O.dispatchEvent(Z),d.isClosePausedRef.current=!1}},"handleResume"),G=eo(Z=>{!L.contains(Z.relatedTarget)&&$()},"handleFocusOutResume"),W=eo(()=>{L.contains(document.activeElement)||$()},"handlePointerLeaveResume");return L.addEventListener("focusin",F),L.addEventListener("focusout",G),L.addEventListener("pointermove",F),L.addEventListener("pointerleave",W),window.addEventListener("blur",F),window.addEventListener("focus",$),()=>{L.removeEventListener("focusin",F),L.removeEventListener("focusout",G),L.removeEventListener("pointermove",F),L.removeEventListener("pointerleave",W),window.removeEventListener("blur",F),window.removeEventListener("focus",$)}}},[P,d.isClosePausedRef]);const C=N.useCallback(({tabbingDirection:L})=>{const F=p().map($=>{const G=$.ref.current,W=[G,...Y_e(G)];return L==="forwards"?W:W.reverse()});return(L==="forwards"?F.reverse():F).flat()},[p]);return N.useEffect(()=>{const L=E.current;if(L){const O=eo(F=>{var W,Z,Q;const $=F.altKey||F.ctrlKey||F.metaKey;if(F.key==="Tab"&&!$){const ee=document.activeElement,ie=F.shiftKey;if(F.target===L&&ie){(W=g.current)==null||W.focus();return}const Le=C({tabbingDirection:ie?"backwards":"forwards"}),be=Le.findIndex(Re=>Re===ee);HM(Le.slice(be+1))?F.preventDefault():ie?(Z=g.current)==null||Z.focus():(Q=v.current)==null||Q.focus()}},"handleKeyDown");return L.addEventListener("keydown",O),()=>L.removeEventListener("keydown",O)}},[p,C]),s.jsxs(o4e,{ref:l,role:"region","aria-label":a.replace("{hotkey}",j),tabIndex:-1,style:{pointerEvents:P?void 0:"none"},children:[P&&s.jsx(Fse,{ref:g,onFocusFromOutsideViewport:()=>{const L=C({tabbingDirection:"forwards"});HM(L)}}),s.jsx(GW.Slot,{scope:n,children:s.jsx(An.ol,{tabIndex:-1,...c,ref:T})}),P&&s.jsx(Fse,{ref:v,onFocusFromOutsideViewport:()=>{const L=C({tabbingDirection:"backwards"});HM(L)}})]})},"ToastViewport")),T4e="ToastFocusProxy",Fse=N.forwardRef(eo(function(e,r){const{__scopeToast:n,onFocusFromOutsideViewport:i,...a}=e,c=w4(T4e,n);return s.jsx(qW,{tabIndex:0,...a,ref:r,style:{position:"fixed"},onFocus:d=>{var g;const p=d.relatedTarget;!((g=c.viewport)!=null&&g.contains(p))&&i()}})},"ToastFocusProxy")),S4="Toast",A4e="toast.swipeStart",k4e="toast.swipeMove",I4e="toast.swipeCancel",j4e="toast.swipeEnd",U_e=N.forwardRef(eo(function(e,r){const{forceMount:n,open:i,defaultOpen:a,onOpenChange:c,...d}=e,[p,l]=ph({prop:i,defaultProp:a??!0,onChange:c,caller:S4});return s.jsx(zc,{present:n||p,children:s.jsx(N4e,{open:p,...d,ref:r,onClose:()=>l(!1),onPause:Yo(e.onPause),onResume:Yo(e.onResume),onSwipeStart:Qr(e.onSwipeStart,g=>{g.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Qr(e.onSwipeMove,g=>{const{x:v,y:E}=g.detail.delta;g.currentTarget.setAttribute("data-swipe","move"),g.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${v}px`),g.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${E}px`)}),onSwipeCancel:Qr(e.onSwipeCancel,g=>{g.currentTarget.setAttribute("data-swipe","cancel"),g.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),g.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),g.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),g.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:Qr(e.onSwipeEnd,g=>{const{x:v,y:E}=g.detail.delta;g.currentTarget.setAttribute("data-swipe","end"),g.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),g.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),g.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${v}px`),g.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${E}px`),l(!1)})})})},"Toast")),[C4e,P4e]=z_e(S4,{onClose(){}}),N4e=N.forwardRef(eo(function(e,r){const{__scopeToast:n,type:i=Ose.Foreground,duration:a,open:c,onClose:d,onEscapeKeyDown:p,onPause:l,onResume:g,onSwipeStart:v,onSwipeMove:E,onSwipeCancel:T,onSwipeEnd:j,...P}=e,C=w4(S4,n),L=B_e(n),[O,F]=N.useState(null),$=Jn(r,F),G=N.useRef(null),W=N.useRef(null),Z=a||C.duration,Q=N.useRef(0),ee=N.useRef(Z),ie=N.useRef(0),{onToastAdd:oe,onToastRemove:pe}=C,Le=Yo(()=>{var Te;(O==null?void 0:O.contains(document.activeElement))&&((Te=C.viewport)==null||Te.focus()),d()}),be=N.useCallback(Ie=>{!Ie||Ie===1/0||(window.clearTimeout(ie.current),Q.current=new Date().getTime(),ie.current=window.setTimeout(Le,Ie))},[Le]);N.useEffect(()=>{const Ie=C.viewport;if(Ie){const Te=eo(()=>{be(ee.current),g==null||g()},"handleResume"),ge=eo(()=>{const $e=new Date().getTime()-Q.current;ee.current=ee.current-$e,window.clearTimeout(ie.current),l==null||l()},"handlePause");return Ie.addEventListener(Aq,ge),Ie.addEventListener(kq,Te),()=>{Ie.removeEventListener(Aq,ge),Ie.removeEventListener(kq,Te)}}},[C.viewport,Z,l,g,be]),N.useEffect(()=>{ee.current=Z,c&&!C.isClosePausedRef.current&&be(Z)},[c,Z,C.isClosePausedRef,be]),N.useEffect(()=>()=>{window.clearTimeout(ie.current)},[]),N.useEffect(()=>(oe(),()=>pe()),[oe,pe]);const Re=N.useMemo(()=>O?WW(O):null,[O]);return C.viewport?s.jsxs(s.Fragment,{children:[Re&&s.jsx(R4e,{__scopeToast:n,role:"status","aria-live":i===Ose.Foreground?"assertive":"polite",children:Re}),s.jsx(C4e,{scope:n,onClose:Le,children:vg.createPortal(s.jsx(GW.ItemSlot,{scope:n,children:s.jsx(JT,{asChild:!0,onEscapeKeyDown:Qr(p,Ie=>{L().some(ge=>{var $e;return($e=ge.ref.current)==null?void 0:$e.contains(Ie.target)})||Le()}),children:s.jsx(An.li,{tabIndex:0,"data-state":c?"open":"closed","data-swipe-direction":C.swipeDirection,...P,ref:$,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:Qr(e.onKeyDown,Ie=>{Ie.key==="Escape"&&(p==null||p(Ie.nativeEvent),Ie.nativeEvent.defaultPrevented||Le())}),onPointerDown:Qr(e.onPointerDown,Ie=>{Ie.button===0&&(G.current={x:Ie.clientX,y:Ie.clientY})}),onPointerMove:Qr(e.onPointerMove,Ie=>{if(!G.current)return;const Te=Ie.clientX-G.current.x,ge=Ie.clientY-G.current.y,$e=!!W.current,we=["left","right"].includes(C.swipeDirection),ke=["left","up"].includes(C.swipeDirection)?Math.min:Math.max,Ae=we?ke(0,Te):0,He=we?0:ke(0,ge),ot=Ie.pointerType==="touch"?10:2,nt={x:Ae,y:He},tt={originalEvent:Ie,delta:nt};$e?(W.current=nt,RI(k4e,E,tt,{discrete:!1})):Bse(nt,C.swipeDirection,ot)?(W.current=nt,RI(A4e,v,tt,{discrete:!1}),Ie.target.setPointerCapture(Ie.pointerId)):(Math.abs(Te)>ot||Math.abs(ge)>ot)&&(G.current=null)}),onPointerUp:Qr(e.onPointerUp,Ie=>{const Te=W.current,ge=Ie.target;if(ge.hasPointerCapture(Ie.pointerId)&&ge.releasePointerCapture(Ie.pointerId),W.current=null,G.current=null,Te){const $e=Ie.currentTarget,we={originalEvent:Ie,delta:Te};Bse(Te,C.swipeDirection,C.swipeThreshold)?RI(j4e,j,we,{discrete:!0}):RI(I4e,T,we,{discrete:!0}),$e.addEventListener("click",ke=>ke.preventDefault(),{once:!0})}})})})}),C.viewport)})]}):null},"ToastImpl")),R4e=eo(t=>{const{__scopeToast:e,children:r,...n}=t,i=w4(S4,e),[a,c]=N.useState(!1),[d,p]=N.useState(!1);return W_e(()=>c(!0)),N.useEffect(()=>{const l=window.setTimeout(()=>p(!0),1e3);return()=>window.clearTimeout(l)},[]),d?null:s.jsx(jP,{asChild:!0,container:i.announcerContainer||void 0,children:s.jsx(qW,{...n,children:a&&s.jsxs(s.Fragment,{children:[i.label," ",r]})})})},"ToastAnnounce"),V_e=N.forwardRef(eo(function(e,r){const{__scopeToast:n,...i}=e;return s.jsx(An.div,{...i,ref:r})},"ToastTitle")),q_e=N.forwardRef(eo(function(e,r){const{__scopeToast:n,...i}=e;return s.jsx(An.div,{...i,ref:r})},"ToastDescription")),L4e="ToastAction",G_e=N.forwardRef(eo(function(e,r){const{altText:n,...i}=e;return n.trim()?s.jsx(H_e,{altText:n,asChild:!0,children:s.jsx(HW,{...i,ref:r})}):(console.error(`Invalid prop \`altText\` supplied to \`${L4e}\`. Expected non-empty \`string\`.`),null)},"ToastAction")),D4e="ToastClose",HW=N.forwardRef(eo(function(e,r){const{__scopeToast:n,...i}=e,a=P4e(D4e,n);return s.jsx(H_e,{asChild:!0,children:s.jsx(An.button,{type:"button",...i,ref:r,onClick:Qr(e.onClick,a.onClose)})})},"ToastClose")),H_e=N.forwardRef(eo(function(e,r){const{__scopeToast:n,altText:i,...a}=e;return s.jsx(An.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":i||void 0,...a,ref:r})},"ToastAnnounceExclude"));function WW(t){const e=[];return Array.from(t.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&e.push(n.textContent),K_e(n)){const i=n.ariaHidden||n.hidden||n.style.display==="none",a=n.dataset.radixToastAnnounceExclude==="";if(!i)if(a){const c=n.dataset.radixToastAnnounceAlt;c&&e.push(c)}else e.push(...WW(n))}}),e}eo(WW,"getAnnounceTextContent");function RI(t,e,r,{discrete:n}){const i=r.originalEvent.currentTarget,a=new CustomEvent(t,{bubbles:!0,cancelable:!0,detail:r});e&&i.addEventListener(t,e,{once:!0}),n?b4(i,a):i.dispatchEvent(a)}eo(RI,"handleAndDispatchCustomEvent");var Bse=eo((t,e,r=0)=>{const n=Math.abs(t.x),i=Math.abs(t.y),a=n>i;return e===Tq.Left||e===Tq.Right?a&&n>r:!a&&i>r},"isDeltaInDirection");function W_e(t=()=>{}){const e=Yo(t);no(()=>{let r=0,n=0;return r=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(n)}},[e])}eo(W_e,"useNextFrame");function K_e(t){return t.nodeType===t.ELEMENT_NODE}eo(K_e,"isHTMLElement");function Y_e(t){const e=[],r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:eo(n=>{const i=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||i?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;r.nextNode();)e.push(r.currentNode);return e}eo(Y_e,"getTabbableCandidates");function HM(t){const e=document.activeElement;return t.some(r=>r===e?!0:(r.focus(),document.activeElement!==e))}eo(HM,"focusFirst");function Z_e(t){var e,r,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(e=0;etypeof t=="boolean"?`${t}`:t===0?"0":t,$se=hs,eA=(t,e)=>r=>{var n;if((e==null?void 0:e.variants)==null)return $se(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:a}=e,c=Object.keys(i).map(l=>{const g=r==null?void 0:r[l],v=a==null?void 0:a[l];if(g===null)return null;const E=zse(g)||zse(v);return i[l][E]}),d=r&&Object.entries(r).reduce((l,g)=>{let[v,E]=g;return E===void 0||(l[v]=E),l},{}),p=e==null||(n=e.compoundVariants)===null||n===void 0?void 0:n.reduce((l,g)=>{let{class:v,className:E,...T}=g;return Object.entries(T).every(j=>{let[P,C]=j;return Array.isArray(C)?C.includes({...a,...d}[P]):{...a,...d}[P]===C})?[...l,v,E]:l},[]);return $se(t,c,p,r==null?void 0:r.class,r==null?void 0:r.className)};/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M4e=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),X_e=(...t)=>t.filter((e,r,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===r).join(" ").trim();/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */var O4e={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const F4e=N.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:i="",children:a,iconNode:c,...d},p)=>N.createElement("svg",{ref:p,...O4e,width:e,height:e,stroke:t,strokeWidth:n?Number(r)*24/Number(e):r,className:X_e("lucide",i),...d},[...c.map(([l,g])=>N.createElement(l,g)),...Array.isArray(a)?a:[a]]));/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xr=(t,e)=>{const r=N.forwardRef(({className:n,...i},a)=>N.createElement(F4e,{ref:a,iconNode:e,className:X_e(`lucide-${M4e(t)}`,n),...i}));return r.displayName=`${t}`,r};/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Use=xr("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yv=xr("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lo=xr("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const B4e=xr("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q_e=xr("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _E=xr("Award",[["path",{d:"m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526",key:"1yiouv"}],["circle",{cx:"12",cy:"8",r:"6",key:"1vp47v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ww=xr("Bath",[["path",{d:"M10 4 8 6",key:"1rru8s"}],["path",{d:"M17 19v2",key:"ts1sot"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M7 19v2",key:"12npes"}],["path",{d:"M9 5 7.621 3.621A2.121 2.121 0 0 0 4 5v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5",key:"14ym8i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const z4e=xr("BedDouble",[["path",{d:"M2 20v-8a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v8",key:"1k78r4"}],["path",{d:"M4 10V6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4",key:"fb3tl2"}],["path",{d:"M12 4v6",key:"1dcgq2"}],["path",{d:"M2 18h20",key:"ajqnye"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tA=xr("Bed",[["path",{d:"M2 4v16",key:"vw9hq8"}],["path",{d:"M2 8h18a2 2 0 0 1 2 2v10",key:"1dgv2r"}],["path",{d:"M2 17h20",key:"18nfp3"}],["path",{d:"M6 8v9",key:"1yriud"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PP=xr("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eT=xr("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tF=xr("Bookmark",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $4e=xr("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J_e=xr("Briefcase",[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jl=xr("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const U4e=xr("Cake",[["path",{d:"M20 21v-8a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8",key:"1w3rig"}],["path",{d:"M4 16s.5-1 2-1 2.5 2 4 2 2.5-2 4-2 2.5 2 4 2 2-1 2-1",key:"n2jgmb"}],["path",{d:"M2 21h20",key:"1nyx9w"}],["path",{d:"M7 8v3",key:"1qtyvj"}],["path",{d:"M12 8v3",key:"hwp4zt"}],["path",{d:"M17 8v3",key:"1i6e5u"}],["path",{d:"M7 4h.01",key:"1bh4kh"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M17 4h.01",key:"1upcoc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eve=xr("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KW=xr("CalendarCheck",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m9 16 2 2 4-4",key:"19s6y9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tve=xr("CalendarClock",[["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M17.5 17.5 16 16.3V14",key:"akvzfd"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ig=xr("CalendarDays",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rve=xr("CalendarPlus",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 13V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8",key:"3spt84"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M19 16v6",key:"tddt3s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cl=xr("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vse=xr("Camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gj=xr("ChartColumn",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ql=xr("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ad=xr("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bg=xr("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uf=xr("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V4e=xr("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Iq=xr("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nve=xr("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const od=xr("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q4e=xr("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YW=xr("CirclePlay",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polygon",{points:"10 8 16 12 10 16 10 8",key:"1cimsy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tT=xr("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jq=xr("ClipboardCheck",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"m9 14 2 2 4-4",key:"df797q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $6=xr("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const su=xr("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qse=xr("Compass",[["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cq=xr("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cy=xr("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $u=xr("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const G4e=xr("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H4e=xr("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rA=xr("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E4=xr("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ive=xr("Facebook",[["path",{d:"M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z",key:"1jg4f8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W4e=xr("FilePenLine",[["path",{d:"m18 5-2.414-2.414A2 2 0 0 0 14.172 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2",key:"142zxg"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}],["path",{d:"M8 18h1",key:"13wk12"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K4e=xr("FileStack",[["path",{d:"M21 7h-3a2 2 0 0 1-2-2V2",key:"9rb54x"}],["path",{d:"M21 6v6.5c0 .8-.7 1.5-1.5 1.5h-7c-.8 0-1.5-.7-1.5-1.5v-9c0-.8.7-1.5 1.5-1.5H17Z",key:"1059l0"}],["path",{d:"M7 8v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H15",key:"16874u"}],["path",{d:"M3 12v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H11",key:"k2ox98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lg=xr("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gse=xr("Film",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y4e=xr("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sve=xr("Flame",[["path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z",key:"96xj49"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jm=xr("Gift",[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rT=xr("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hj=xr("GraduationCap",[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z4e=xr("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const X4e=xr("HandHelping",[["path",{d:"M11 12h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 14",key:"1j4xps"}],["path",{d:"m7 18 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"uospg8"}],["path",{d:"m2 13 6 6",key:"16e5sb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pq=xr("Handshake",[["path",{d:"m11 17 2 2a1 1 0 1 0 3-3",key:"efffak"}],["path",{d:"m14 14 2.5 2.5a1 1 0 1 0 3-3l-3.88-3.88a3 3 0 0 0-4.24 0l-.88.88a1 1 0 1 1-3-3l2.81-2.81a5.79 5.79 0 0 1 7.06-.87l.47.28a2 2 0 0 0 1.42.25L21 4",key:"9pr0kb"}],["path",{d:"m21 3 1 11h-2",key:"1tisrp"}],["path",{d:"M3 3 2 14l6.5 6.5a1 1 0 1 0 3-3",key:"1uvwmv"}],["path",{d:"M3 4h8",key:"1ep09j"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cg=xr("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Do=xr("House",[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"1d0kgt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hse=xr("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ave=xr("Instagram",[["rect",{width:"20",height:"20",x:"2",y:"2",rx:"5",ry:"5",key:"2e1cvw"}],["path",{d:"M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z",key:"9exkf1"}],["line",{x1:"17.5",x2:"17.51",y1:"6.5",y2:"6.5",key:"r4j83e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZW=xr("Kanban",[["path",{d:"M6 5v11",key:"mdvv1e"}],["path",{d:"M12 5v6",key:"14ar3b"}],["path",{d:"M18 5v14",key:"7ji314"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q4e=xr("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ove=xr("Key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lve=xr("Landmark",[["line",{x1:"3",x2:"21",y1:"22",y2:"22",key:"j8o0r"}],["line",{x1:"6",x2:"6",y1:"18",y2:"11",key:"10tf0k"}],["line",{x1:"10",x2:"10",y1:"18",y2:"11",key:"54lgf6"}],["line",{x1:"14",x2:"14",y1:"18",y2:"11",key:"380y"}],["line",{x1:"18",x2:"18",y1:"18",y2:"11",key:"1kevvc"}],["polygon",{points:"12 2 20 7 4 7",key:"jkujk7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J4e=xr("Layers",[["path",{d:"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z",key:"8b97xw"}],["path",{d:"m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65",key:"dd6zsq"}],["path",{d:"m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65",key:"ep9fru"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cve=xr("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const e5e=xr("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const t5e=xr("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const r5e=xr("Lightbulb",[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wse=xr("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uve=xr("Linkedin",[["path",{d:"M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z",key:"c2jq9f"}],["rect",{width:"4",height:"12",x:"2",y:"9",key:"mk3on5"}],["circle",{cx:"4",cy:"4",r:"2",key:"bt5ra8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const n5e=xr("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nq=xr("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gh=xr("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xv=xr("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const T4=xr("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rs=xr("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Va=xr("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const i5e=xr("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const s5e=xr("Maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NP=xr("Megaphone",[["path",{d:"m3 11 18-5v12L3 14v-3z",key:"n962bs"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nA=xr("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a5e=xr("MessageCircleQuestion",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nT=xr("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ug=xr("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const o5e=xr("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dve=xr("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kse=xr("Package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"m3.3 7 7.703 4.734a2 2 0 0 0 1.994 0L20.7 7",key:"yx3hmr"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A4=xr("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const l5e=xr("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const c5e=xr("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const u5e=xr("Percent",[["line",{x1:"19",x2:"5",y1:"5",y2:"19",key:"1x9vlm"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5",key:"4mh3h7"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5",key:"1mdrzq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const d5e=xr("PhoneCall",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}],["path",{d:"M14.05 2a9 9 0 0 1 8 7.94",key:"vmijpz"}],["path",{d:"M14.05 6A5 5 0 0 1 18 10",key:"13nbpp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ui=xr("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const h5e=xr("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rF=xr("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Py=xr("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const f5e=xr("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const m5e=xr("Quote",[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const p5e=xr("Radar",[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hve=xr("Radio",[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const g5e=xr("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yse=xr("Rocket",[["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z",key:"m3kijz"}],["path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z",key:"1fmvmk"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0",key:"1f8sc4"}],["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k4=xr("Ruler",[["path",{d:"M21.3 15.3a2.4 2.4 0 0 1 0 3.4l-2.6 2.6a2.4 2.4 0 0 1-3.4 0L2.7 8.7a2.41 2.41 0 0 1 0-3.4l2.6-2.6a2.41 2.41 0 0 1 3.4 0Z",key:"icamh8"}],["path",{d:"m14.5 12.5 2-2",key:"inckbg"}],["path",{d:"m11.5 9.5 2-2",key:"fmmyf7"}],["path",{d:"m8.5 6.5 2-2",key:"vc6u1g"}],["path",{d:"m17.5 15.5 2-2",key:"wo5hmg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const y5e=xr("SearchX",[["path",{d:"m13.5 8.5-5 5",key:"1cs55j"}],["path",{d:"m8.5 8.5 5 5",key:"a8mexj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ef=xr("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nF=xr("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XW=xr("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RP=xr("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const x5e=xr("Share",[["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["polyline",{points:"16 6 12 2 8 6",key:"m901s6"}],["line",{x1:"12",x2:"12",y1:"2",y2:"15",key:"1p0rca"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QW=xr("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wj=xr("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fve=xr("ShoppingCart",[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _5e=xr("SlidersHorizontal",[["line",{x1:"21",x2:"14",y1:"4",y2:"4",key:"obuewd"}],["line",{x1:"10",x2:"3",y1:"4",y2:"4",key:"1q6298"}],["line",{x1:"21",x2:"12",y1:"12",y2:"12",key:"1iu8h1"}],["line",{x1:"8",x2:"3",y1:"12",y2:"12",key:"ntss68"}],["line",{x1:"21",x2:"16",y1:"20",y2:"20",key:"14d8ph"}],["line",{x1:"12",x2:"3",y1:"20",y2:"20",key:"m0wm8r"}],["line",{x1:"14",x2:"14",y1:"2",y2:"6",key:"14e1ph"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"16",x2:"16",y1:"18",y2:"22",key:"1lctlv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const U6=xr("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const v5e=xr("Sofa",[["path",{d:"M20 9V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v3",key:"1dgpiv"}],["path",{d:"M2 16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5a2 2 0 0 0-4 0v1.5a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5V11a2 2 0 0 0-4 0z",key:"xacw8m"}],["path",{d:"M4 18v2",key:"jwo5n2"}],["path",{d:"M20 18v2",key:"1ar1qi"}],["path",{d:"M12 4v9",key:"oqhhn3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const va=xr("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const b5e=xr("SquareCheckBig",[["path",{d:"M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.5",key:"1uzm8b"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rq=xr("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JW=xr("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bd=xr("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mve=xr("Store",[["path",{d:"m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7",key:"ztvudi"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["path",{d:"M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4",key:"2ebpfo"}],["path",{d:"M2 7h20",key:"1fcdvo"}],["path",{d:"M22 7v3a2 2 0 0 1-2 2a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 16 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 12 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 8 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 4 12a2 2 0 0 1-2-2V7",key:"6c3vgh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w5e=xr("Tablet",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["line",{x1:"12",x2:"12.01",y1:"18",y2:"18",key:"1dp563"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eK=xr("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S5e=xr("ThumbsUp",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pve=xr("Ticket",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M13 5v2",key:"dyzc3o"}],["path",{d:"M13 17v2",key:"1ont0d"}],["path",{d:"M13 11v2",key:"1wjjxi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iF=xr("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gve=xr("TrendingDown",[["polyline",{points:"22 17 13.5 8.5 8.5 13.5 2 7",key:"1r2t7k"}],["polyline",{points:"16 17 22 17 22 11",key:"11uiuu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iA=xr("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LP=xr("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sF=xr("Trophy",[["path",{d:"M6 9H4.5a2.5 2.5 0 0 1 0-5H6",key:"17hqa7"}],["path",{d:"M18 9h1.5a2.5 2.5 0 0 0 0-5H18",key:"lmptdp"}],["path",{d:"M4 22h16",key:"57wxv0"}],["path",{d:"M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22",key:"1nw9bq"}],["path",{d:"M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22",key:"1np0yb"}],["path",{d:"M18 2H6v7a6 6 0 0 0 12 0V2Z",key:"u46fv3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lq=xr("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E5e=xr("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I4=xr("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nd=xr("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dc=xr("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rj=xr("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const T5e=xr("Volume2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A5e=xr("VolumeX",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tK=xr("Wallet",[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k5e=xr("WandSparkles",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rK=xr("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ra=xr("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I5e=xr("Youtube",[["path",{d:"M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17",key:"1q2vi4"}],["path",{d:"m10 15 5-3-5-3z",key:"1jp15x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aF=xr("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zse=xr("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),nK="-",j5e=t=>{const e=P5e(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:c=>{const d=c.split(nK);return d[0]===""&&d.length!==1&&d.shift(),yve(d,e)||C5e(c)},getConflictingClassGroupIds:(c,d)=>{const p=r[c]||[];return d&&n[c]?[...p,...n[c]]:p}}},yve=(t,e)=>{var c;if(t.length===0)return e.classGroupId;const r=t[0],n=e.nextPart.get(r),i=n?yve(t.slice(1),n):void 0;if(i)return i;if(e.validators.length===0)return;const a=t.join(nK);return(c=e.validators.find(({validator:d})=>d(a)))==null?void 0:c.classGroupId},Xse=/^\[(.+)\]$/,C5e=t=>{if(Xse.test(t)){const e=Xse.exec(t)[1],r=e==null?void 0:e.substring(0,e.indexOf(":"));if(r)return"arbitrary.."+r}},P5e=t=>{const{theme:e,prefix:r}=t,n={nextPart:new Map,validators:[]};return R5e(Object.entries(t.classGroups),r).forEach(([a,c])=>{Dq(c,n,a,e)}),n},Dq=(t,e,r,n)=>{t.forEach(i=>{if(typeof i=="string"){const a=i===""?e:Qse(e,i);a.classGroupId=r;return}if(typeof i=="function"){if(N5e(i)){Dq(i(n),e,r,n);return}e.validators.push({validator:i,classGroupId:r});return}Object.entries(i).forEach(([a,c])=>{Dq(c,Qse(e,a),r,n)})})},Qse=(t,e)=>{let r=t;return e.split(nK).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},N5e=t=>t.isThemeGetter,R5e=(t,e)=>e?t.map(([r,n])=>{const i=n.map(a=>typeof a=="string"?e+a:typeof a=="object"?Object.fromEntries(Object.entries(a).map(([c,d])=>[e+c,d])):a);return[r,i]}):t,L5e=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,r=new Map,n=new Map;const i=(a,c)=>{r.set(a,c),e++,e>t&&(e=0,n=r,r=new Map)};return{get(a){let c=r.get(a);if(c!==void 0)return c;if((c=n.get(a))!==void 0)return i(a,c),c},set(a,c){r.has(a)?r.set(a,c):i(a,c)}}},xve="!",D5e=t=>{const{separator:e,experimentalParseClassName:r}=t,n=e.length===1,i=e[0],a=e.length,c=d=>{const p=[];let l=0,g=0,v;for(let C=0;Cg?v-g:void 0;return{modifiers:p,hasImportantModifier:T,baseClassName:j,maybePostfixModifierPosition:P}};return r?d=>r({className:d,parseClassName:c}):c},M5e=t=>{if(t.length<=1)return t;const e=[];let r=[];return t.forEach(n=>{n[0]==="["?(e.push(...r.sort(),n),r=[]):r.push(n)}),e.push(...r.sort()),e},O5e=t=>({cache:L5e(t.cacheSize),parseClassName:D5e(t),...j5e(t)}),F5e=/\s+/,B5e=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:i}=e,a=[],c=t.trim().split(F5e);let d="";for(let p=c.length-1;p>=0;p-=1){const l=c[p],{modifiers:g,hasImportantModifier:v,baseClassName:E,maybePostfixModifierPosition:T}=r(l);let j=!!T,P=n(j?E.substring(0,T):E);if(!P){if(!j){d=l+(d.length>0?" "+d:d);continue}if(P=n(E),!P){d=l+(d.length>0?" "+d:d);continue}j=!1}const C=M5e(g).join(":"),L=v?C+xve:C,O=L+P;if(a.includes(O))continue;a.push(O);const F=i(P,j);for(let $=0;$0?" "+d:d)}return d};function z5e(){let t=0,e,r,n="";for(;t{if(typeof t=="string")return t;let e,r="";for(let n=0;nv(g),t());return r=O5e(l),n=r.cache.get,i=r.cache.set,a=d,d(p)}function d(p){const l=n(p);if(l)return l;const g=B5e(p,r);return i(p,g),g}return function(){return a(z5e.apply(null,arguments))}}const Co=t=>{const e=r=>r[t]||[];return e.isThemeGetter=!0,e},vve=/^\[(?:([a-z-]+):)?(.+)\]$/i,U5e=/^\d+\/\d+$/,V5e=new Set(["px","full","screen"]),q5e=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,G5e=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,H5e=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,W5e=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,K5e=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ay=t=>vE(t)||V5e.has(t)||U5e.test(t),f_=t=>sA(t,"length",rBe),vE=t=>!!t&&!Number.isNaN(Number(t)),V6=t=>sA(t,"number",vE),Xk=t=>!!t&&Number.isInteger(Number(t)),Y5e=t=>t.endsWith("%")&&vE(t.slice(0,-1)),cs=t=>vve.test(t),m_=t=>q5e.test(t),Z5e=new Set(["length","size","percentage"]),X5e=t=>sA(t,Z5e,bve),Q5e=t=>sA(t,"position",bve),J5e=new Set(["image","url"]),eBe=t=>sA(t,J5e,iBe),tBe=t=>sA(t,"",nBe),Qk=()=>!0,sA=(t,e,r)=>{const n=vve.exec(t);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):r(n[2]):!1},rBe=t=>G5e.test(t)&&!H5e.test(t),bve=()=>!1,nBe=t=>W5e.test(t),iBe=t=>K5e.test(t),sBe=()=>{const t=Co("colors"),e=Co("spacing"),r=Co("blur"),n=Co("brightness"),i=Co("borderColor"),a=Co("borderRadius"),c=Co("borderSpacing"),d=Co("borderWidth"),p=Co("contrast"),l=Co("grayscale"),g=Co("hueRotate"),v=Co("invert"),E=Co("gap"),T=Co("gradientColorStops"),j=Co("gradientColorStopPositions"),P=Co("inset"),C=Co("margin"),L=Co("opacity"),O=Co("padding"),F=Co("saturate"),$=Co("scale"),G=Co("sepia"),W=Co("skew"),Z=Co("space"),Q=Co("translate"),ee=()=>["auto","contain","none"],ie=()=>["auto","hidden","clip","visible","scroll"],oe=()=>["auto",cs,e],pe=()=>[cs,e],Le=()=>["",ay,f_],be=()=>["auto",vE,cs],Re=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Ie=()=>["solid","dashed","dotted","double","none"],Te=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ge=()=>["start","end","center","between","around","evenly","stretch"],$e=()=>["","0",cs],we=()=>["auto","avoid","all","avoid-page","page","left","right","column"],ke=()=>[vE,cs];return{cacheSize:500,separator:":",theme:{colors:[Qk],spacing:[ay,f_],blur:["none","",m_,cs],brightness:ke(),borderColor:[t],borderRadius:["none","","full",m_,cs],borderSpacing:pe(),borderWidth:Le(),contrast:ke(),grayscale:$e(),hueRotate:ke(),invert:$e(),gap:pe(),gradientColorStops:[t],gradientColorStopPositions:[Y5e,f_],inset:oe(),margin:oe(),opacity:ke(),padding:pe(),saturate:ke(),scale:ke(),sepia:$e(),skew:ke(),space:pe(),translate:pe()},classGroups:{aspect:[{aspect:["auto","square","video",cs]}],container:["container"],columns:[{columns:[m_]}],"break-after":[{"break-after":we()}],"break-before":[{"break-before":we()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...Re(),cs]}],overflow:[{overflow:ie()}],"overflow-x":[{"overflow-x":ie()}],"overflow-y":[{"overflow-y":ie()}],overscroll:[{overscroll:ee()}],"overscroll-x":[{"overscroll-x":ee()}],"overscroll-y":[{"overscroll-y":ee()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[P]}],"inset-x":[{"inset-x":[P]}],"inset-y":[{"inset-y":[P]}],start:[{start:[P]}],end:[{end:[P]}],top:[{top:[P]}],right:[{right:[P]}],bottom:[{bottom:[P]}],left:[{left:[P]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Xk,cs]}],basis:[{basis:oe()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",cs]}],grow:[{grow:$e()}],shrink:[{shrink:$e()}],order:[{order:["first","last","none",Xk,cs]}],"grid-cols":[{"grid-cols":[Qk]}],"col-start-end":[{col:["auto",{span:["full",Xk,cs]},cs]}],"col-start":[{"col-start":be()}],"col-end":[{"col-end":be()}],"grid-rows":[{"grid-rows":[Qk]}],"row-start-end":[{row:["auto",{span:[Xk,cs]},cs]}],"row-start":[{"row-start":be()}],"row-end":[{"row-end":be()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",cs]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",cs]}],gap:[{gap:[E]}],"gap-x":[{"gap-x":[E]}],"gap-y":[{"gap-y":[E]}],"justify-content":[{justify:["normal",...ge()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...ge(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...ge(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[O]}],px:[{px:[O]}],py:[{py:[O]}],ps:[{ps:[O]}],pe:[{pe:[O]}],pt:[{pt:[O]}],pr:[{pr:[O]}],pb:[{pb:[O]}],pl:[{pl:[O]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[Z]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[Z]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",cs,e]}],"min-w":[{"min-w":[cs,e,"min","max","fit"]}],"max-w":[{"max-w":[cs,e,"none","full","min","max","fit","prose",{screen:[m_]},m_]}],h:[{h:[cs,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[cs,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[cs,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[cs,e,"auto","min","max","fit"]}],"font-size":[{text:["base",m_,f_]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",V6]}],"font-family":[{font:[Qk]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",cs]}],"line-clamp":[{"line-clamp":["none",vE,V6]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",ay,cs]}],"list-image":[{"list-image":["none",cs]}],"list-style-type":[{list:["none","disc","decimal",cs]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[L]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[L]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Ie(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",ay,f_]}],"underline-offset":[{"underline-offset":["auto",ay,cs]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:pe()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",cs]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",cs]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[L]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...Re(),Q5e]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",X5e]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eBe]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[j]}],"gradient-via-pos":[{via:[j]}],"gradient-to-pos":[{to:[j]}],"gradient-from":[{from:[T]}],"gradient-via":[{via:[T]}],"gradient-to":[{to:[T]}],rounded:[{rounded:[a]}],"rounded-s":[{"rounded-s":[a]}],"rounded-e":[{"rounded-e":[a]}],"rounded-t":[{"rounded-t":[a]}],"rounded-r":[{"rounded-r":[a]}],"rounded-b":[{"rounded-b":[a]}],"rounded-l":[{"rounded-l":[a]}],"rounded-ss":[{"rounded-ss":[a]}],"rounded-se":[{"rounded-se":[a]}],"rounded-ee":[{"rounded-ee":[a]}],"rounded-es":[{"rounded-es":[a]}],"rounded-tl":[{"rounded-tl":[a]}],"rounded-tr":[{"rounded-tr":[a]}],"rounded-br":[{"rounded-br":[a]}],"rounded-bl":[{"rounded-bl":[a]}],"border-w":[{border:[d]}],"border-w-x":[{"border-x":[d]}],"border-w-y":[{"border-y":[d]}],"border-w-s":[{"border-s":[d]}],"border-w-e":[{"border-e":[d]}],"border-w-t":[{"border-t":[d]}],"border-w-r":[{"border-r":[d]}],"border-w-b":[{"border-b":[d]}],"border-w-l":[{"border-l":[d]}],"border-opacity":[{"border-opacity":[L]}],"border-style":[{border:[...Ie(),"hidden"]}],"divide-x":[{"divide-x":[d]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[d]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[L]}],"divide-style":[{divide:Ie()}],"border-color":[{border:[i]}],"border-color-x":[{"border-x":[i]}],"border-color-y":[{"border-y":[i]}],"border-color-s":[{"border-s":[i]}],"border-color-e":[{"border-e":[i]}],"border-color-t":[{"border-t":[i]}],"border-color-r":[{"border-r":[i]}],"border-color-b":[{"border-b":[i]}],"border-color-l":[{"border-l":[i]}],"divide-color":[{divide:[i]}],"outline-style":[{outline:["",...Ie()]}],"outline-offset":[{"outline-offset":[ay,cs]}],"outline-w":[{outline:[ay,f_]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:Le()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[L]}],"ring-offset-w":[{"ring-offset":[ay,f_]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",m_,tBe]}],"shadow-color":[{shadow:[Qk]}],opacity:[{opacity:[L]}],"mix-blend":[{"mix-blend":[...Te(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":Te()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[p]}],"drop-shadow":[{"drop-shadow":["","none",m_,cs]}],grayscale:[{grayscale:[l]}],"hue-rotate":[{"hue-rotate":[g]}],invert:[{invert:[v]}],saturate:[{saturate:[F]}],sepia:[{sepia:[G]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[p]}],"backdrop-grayscale":[{"backdrop-grayscale":[l]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[g]}],"backdrop-invert":[{"backdrop-invert":[v]}],"backdrop-opacity":[{"backdrop-opacity":[L]}],"backdrop-saturate":[{"backdrop-saturate":[F]}],"backdrop-sepia":[{"backdrop-sepia":[G]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[c]}],"border-spacing-x":[{"border-spacing-x":[c]}],"border-spacing-y":[{"border-spacing-y":[c]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",cs]}],duration:[{duration:ke()}],ease:[{ease:["linear","in","out","in-out",cs]}],delay:[{delay:ke()}],animate:[{animate:["none","spin","ping","pulse","bounce",cs]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[$]}],"scale-x":[{"scale-x":[$]}],"scale-y":[{"scale-y":[$]}],rotate:[{rotate:[Xk,cs]}],"translate-x":[{"translate-x":[Q]}],"translate-y":[{"translate-y":[Q]}],"skew-x":[{"skew-x":[W]}],"skew-y":[{"skew-y":[W]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",cs]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",cs]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":pe()}],"scroll-mx":[{"scroll-mx":pe()}],"scroll-my":[{"scroll-my":pe()}],"scroll-ms":[{"scroll-ms":pe()}],"scroll-me":[{"scroll-me":pe()}],"scroll-mt":[{"scroll-mt":pe()}],"scroll-mr":[{"scroll-mr":pe()}],"scroll-mb":[{"scroll-mb":pe()}],"scroll-ml":[{"scroll-ml":pe()}],"scroll-p":[{"scroll-p":pe()}],"scroll-px":[{"scroll-px":pe()}],"scroll-py":[{"scroll-py":pe()}],"scroll-ps":[{"scroll-ps":pe()}],"scroll-pe":[{"scroll-pe":pe()}],"scroll-pt":[{"scroll-pt":pe()}],"scroll-pr":[{"scroll-pr":pe()}],"scroll-pb":[{"scroll-pb":pe()}],"scroll-pl":[{"scroll-pl":pe()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",cs]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[ay,f_,V6]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},aBe=$5e(sBe);function hr(...t){return aBe(hs(t))}function Ho(t,e=!1){return e&&t>=1e6?`$${(t/1e6).toFixed(1)}M`:e&&t>=1e3?`$${(t/1e3).toFixed(0)}K`:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(t)}function Jse(t){const e=new Date(t);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(e)}function OWt(t){return t?t.replace(/<[^>]*>/g,""):""}const oBe=w4e,wve=N.forwardRef(({className:t,...e},r)=>s.jsx($_e,{ref:r,className:hr("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",t),...e}));wve.displayName=$_e.displayName;const lBe=eA("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),Sve=N.forwardRef(({className:t,variant:e,...r},n)=>s.jsx(U_e,{ref:n,className:hr(lBe({variant:e}),t),...r}));Sve.displayName=U_e.displayName;const cBe=N.forwardRef(({className:t,...e},r)=>s.jsx(G_e,{ref:r,className:hr("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors group-[.destructive]:border-muted/40 hover:bg-secondary group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 group-[.destructive]:focus:ring-destructive disabled:pointer-events-none disabled:opacity-50",t),...e}));cBe.displayName=G_e.displayName;const Eve=N.forwardRef(({className:t,...e},r)=>s.jsx(HW,{ref:r,className:hr("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity group-hover:opacity-100 group-[.destructive]:text-red-300 hover:text-foreground group-[.destructive]:hover:text-red-50 focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",t),"toast-close":"",...e,children:s.jsx(Ra,{className:"h-4 w-4"})}));Eve.displayName=HW.displayName;const Tve=N.forwardRef(({className:t,...e},r)=>s.jsx(V_e,{ref:r,className:hr("text-sm font-semibold",t),...e}));Tve.displayName=V_e.displayName;const Ave=N.forwardRef(({className:t,...e},r)=>s.jsx(q_e,{ref:r,className:hr("text-sm opacity-90",t),...e}));Ave.displayName=q_e.displayName;function uBe(){const{toasts:t}=c_e();return s.jsxs(oBe,{children:[t.map(function({id:e,title:r,description:n,action:i,...a}){return s.jsxs(Sve,{...a,children:[s.jsxs("div",{className:"grid gap-1",children:[r&&s.jsx(Tve,{children:r}),n&&s.jsx(Ave,{children:n})]}),i,s.jsx(Eve,{})]},e)}),s.jsx(wve,{})]})}var eae=["light","dark"],dBe="(prefers-color-scheme: dark)",hBe=N.createContext(void 0),fBe={setTheme:t=>{},themes:[]},mBe=()=>{var t;return(t=N.useContext(hBe))!=null?t:fBe};N.memo(({forcedTheme:t,storageKey:e,attribute:r,enableSystem:n,enableColorScheme:i,defaultTheme:a,value:c,attrs:d,nonce:p})=>{let l=a==="system",g=r==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${d.map(j=>`'${j}'`).join(",")})`};`:`var d=document.documentElement,n='${r}',s='setAttribute';`,v=i?eae.includes(a)&&a?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${a}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",E=(j,P=!1,C=!0)=>{let L=c?c[j]:j,O=P?j+"|| ''":`'${L}'`,F="";return i&&C&&!P&&eae.includes(j)&&(F+=`d.style.colorScheme = '${j}';`),r==="class"?P||L?F+=`c.add(${O})`:F+="null":L&&(F+=`d[s](n,${O})`),F},T=t?`!function(){${g}${E(t)}}()`:n?`!function(){try{${g}var e=localStorage.getItem('${e}');if('system'===e||(!e&&${l})){var t='${dBe}',m=window.matchMedia(t);if(m.media!==t||m.matches){${E("dark")}}else{${E("light")}}}else if(e){${c?`var x=${JSON.stringify(c)};`:""}${E(c?"x[e]":"e",!0)}}${l?"":"else{"+E(a,!1,!1)+"}"}${v}}catch(e){}}()`:`!function(){try{${g}var e=localStorage.getItem('${e}');if(e){${c?`var x=${JSON.stringify(c)};`:""}${E(c?"x[e]":"e",!0)}}else{${E(a,!1,!1)};}${v}}catch(t){}}();`;return N.createElement("script",{nonce:p,dangerouslySetInnerHTML:{__html:T}})});var pBe=t=>{switch(t){case"success":return xBe;case"info":return vBe;case"warning":return _Be;case"error":return bBe;default:return null}},gBe=Array(12).fill(0),yBe=({visible:t,className:e})=>et.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":t},et.createElement("div",{className:"sonner-spinner"},gBe.map((r,n)=>et.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),xBe=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},et.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),_Be=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},et.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),vBe=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},et.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),bBe=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},et.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),wBe=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},et.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),et.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),SBe=()=>{let[t,e]=et.useState(document.hidden);return et.useEffect(()=>{let r=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),t},Mq=1,EBe=class{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{let e=this.subscribers.indexOf(t);this.subscribers.splice(e,1)}),this.publish=t=>{this.subscribers.forEach(e=>e(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var e;let{message:r,...n}=t,i=typeof(t==null?void 0:t.id)=="number"||((e=t.id)==null?void 0:e.length)>0?t.id:Mq++,a=this.toasts.find(d=>d.id===i),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),a?this.toasts=this.toasts.map(d=>d.id===i?(this.publish({...d,...t,id:i,title:r}),{...d,...t,id:i,dismissible:c,title:r}):d):this.addToast({title:r,...n,dismissible:c,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(e=>{this.subscribers.forEach(r=>r({id:e.id,dismiss:!0}))}),this.subscribers.forEach(e=>e({id:t,dismiss:!0})),t),this.message=(t,e)=>this.create({...e,message:t}),this.error=(t,e)=>this.create({...e,message:t,type:"error"}),this.success=(t,e)=>this.create({...e,type:"success",message:t}),this.info=(t,e)=>this.create({...e,type:"info",message:t}),this.warning=(t,e)=>this.create({...e,type:"warning",message:t}),this.loading=(t,e)=>this.create({...e,type:"loading",message:t}),this.promise=(t,e)=>{if(!e)return;let r;e.loading!==void 0&&(r=this.create({...e,promise:t,type:"loading",message:e.loading,description:typeof e.description!="function"?e.description:void 0}));let n=t instanceof Promise?t:t(),i=r!==void 0,a,c=n.then(async p=>{if(a=["resolve",p],et.isValidElement(p))i=!1,this.create({id:r,type:"default",message:p});else if(ABe(p)&&!p.ok){i=!1;let l=typeof e.error=="function"?await e.error(`HTTP error! status: ${p.status}`):e.error,g=typeof e.description=="function"?await e.description(`HTTP error! status: ${p.status}`):e.description;this.create({id:r,type:"error",message:l,description:g})}else if(e.success!==void 0){i=!1;let l=typeof e.success=="function"?await e.success(p):e.success,g=typeof e.description=="function"?await e.description(p):e.description;this.create({id:r,type:"success",message:l,description:g})}}).catch(async p=>{if(a=["reject",p],e.error!==void 0){i=!1;let l=typeof e.error=="function"?await e.error(p):e.error,g=typeof e.description=="function"?await e.description(p):e.description;this.create({id:r,type:"error",message:l,description:g})}}).finally(()=>{var p;i&&(this.dismiss(r),r=void 0),(p=e.finally)==null||p.call(e)}),d=()=>new Promise((p,l)=>c.then(()=>a[0]==="reject"?l(a[1]):p(a[1])).catch(l));return typeof r!="string"&&typeof r!="number"?{unwrap:d}:Object.assign(r,{unwrap:d})},this.custom=(t,e)=>{let r=(e==null?void 0:e.id)||Mq++;return this.create({jsx:t(r),id:r,...e}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},ih=new EBe,TBe=(t,e)=>{let r=(e==null?void 0:e.id)||Mq++;return ih.addToast({title:t,...e,id:r}),r},ABe=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",kBe=TBe,IBe=()=>ih.toasts,jBe=()=>ih.getActiveToasts(),lr=Object.assign(kBe,{success:ih.success,info:ih.info,warning:ih.warning,error:ih.error,custom:ih.custom,message:ih.message,promise:ih.promise,dismiss:ih.dismiss,loading:ih.loading},{getHistory:IBe,getToasts:jBe});function CBe(t,{insertAt:e}={}){if(typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",e==="top"&&r.firstChild?r.insertBefore(n,r.firstChild):r.appendChild(n),n.styleSheet?n.styleSheet.cssText=t:n.appendChild(document.createTextNode(t))}CBe(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)} `);function lD(t){return t.label!==void 0}var PBe=3,NBe="32px",RBe="16px",tae=4e3,LBe=356,DBe=14,MBe=20,OBe=200;function Em(...t){return t.filter(Boolean).join(" ")}function FBe(t){let[e,r]=t.split("-"),n=[];return e&&n.push(e),r&&n.push(r),n}var BBe=t=>{var e,r,n,i,a,c,d,p,l,g,v;let{invert:E,toast:T,unstyled:j,interacting:P,setHeights:C,visibleToasts:L,heights:O,index:F,toasts:$,expanded:G,removeToast:W,defaultRichColors:Z,closeButton:Q,style:ee,cancelButtonStyle:ie,actionButtonStyle:oe,className:pe="",descriptionClassName:Le="",duration:be,position:Re,gap:Ie,loadingIcon:Te,expandByDefault:ge,classNames:$e,icons:we,closeButtonAriaLabel:ke="Close toast",pauseWhenPageIsHidden:Ae}=t,[He,ot]=et.useState(null),[nt,tt]=et.useState(null),[vt,Vt]=et.useState(!1),[Ct,Bt]=et.useState(!1),[cr,ft]=et.useState(!1),[Kt,ir]=et.useState(!1),[Gr,tr]=et.useState(!1),[Qt,zt]=et.useState(0),[Vr,Jr]=et.useState(0),Fn=et.useRef(T.duration||be||tae),Ar=et.useRef(null),Tn=et.useRef(null),mn=F===0,li=F+1<=L,Lr=T.type,Or=T.dismissible!==!1,si=T.className||"",ss=T.descriptionClassName||"",ps=et.useMemo(()=>O.findIndex(at=>at.toastId===T.id)||0,[O,T.id]),Mi=et.useMemo(()=>{var at;return(at=T.closeButton)!=null?at:Q},[T.closeButton,Q]),gs=et.useMemo(()=>T.duration||be||tae,[T.duration,be]),ma=et.useRef(0),Ki=et.useRef(0),Hr=et.useRef(0),ci=et.useRef(null),[mo,_r]=Re.split("-"),Da=et.useMemo(()=>O.reduce((at,yt,rr)=>rr>=ps?at:at+yt.height,0),[O,ps]),pn=SBe(),Vi=T.invert||E,Yi=Lr==="loading";Ki.current=et.useMemo(()=>ps*Ie+Da,[ps,Da]),et.useEffect(()=>{Fn.current=gs},[gs]),et.useEffect(()=>{Vt(!0)},[]),et.useEffect(()=>{let at=Tn.current;if(at){let yt=at.getBoundingClientRect().height;return Jr(yt),C(rr=>[{toastId:T.id,height:yt,position:T.position},...rr]),()=>C(rr=>rr.filter(Er=>Er.toastId!==T.id))}},[C,T.id]),et.useLayoutEffect(()=>{if(!vt)return;let at=Tn.current,yt=at.style.height;at.style.height="auto";let rr=at.getBoundingClientRect().height;at.style.height=yt,Jr(rr),C(Er=>Er.find(Wr=>Wr.toastId===T.id)?Er.map(Wr=>Wr.toastId===T.id?{...Wr,height:rr}:Wr):[{toastId:T.id,height:rr,position:T.position},...Er])},[vt,T.title,T.description,C,T.id]);let nn=et.useCallback(()=>{Bt(!0),zt(Ki.current),C(at=>at.filter(yt=>yt.toastId!==T.id)),setTimeout(()=>{W(T)},OBe)},[T,W,C,Ki]);et.useEffect(()=>{if(T.promise&&Lr==="loading"||T.duration===1/0||T.type==="loading")return;let at;return G||P||Ae&&pn?(()=>{if(Hr.current{var yt;(yt=T.onAutoClose)==null||yt.call(T,T),nn()},Fn.current)),()=>clearTimeout(at)},[G,P,T,Lr,Ae,pn,nn]),et.useEffect(()=>{T.delete&&nn()},[nn,T.delete]);function Ke(){var at,yt,rr;return we!=null&&we.loading?et.createElement("div",{className:Em($e==null?void 0:$e.loader,(at=T==null?void 0:T.classNames)==null?void 0:at.loader,"sonner-loader"),"data-visible":Lr==="loading"},we.loading):Te?et.createElement("div",{className:Em($e==null?void 0:$e.loader,(yt=T==null?void 0:T.classNames)==null?void 0:yt.loader,"sonner-loader"),"data-visible":Lr==="loading"},Te):et.createElement(yBe,{className:Em($e==null?void 0:$e.loader,(rr=T==null?void 0:T.classNames)==null?void 0:rr.loader),visible:Lr==="loading"})}return et.createElement("li",{tabIndex:0,ref:Tn,className:Em(pe,si,$e==null?void 0:$e.toast,(e=T==null?void 0:T.classNames)==null?void 0:e.toast,$e==null?void 0:$e.default,$e==null?void 0:$e[Lr],(r=T==null?void 0:T.classNames)==null?void 0:r[Lr]),"data-sonner-toast":"","data-rich-colors":(n=T.richColors)!=null?n:Z,"data-styled":!(T.jsx||T.unstyled||j),"data-mounted":vt,"data-promise":!!T.promise,"data-swiped":Gr,"data-removed":Ct,"data-visible":li,"data-y-position":mo,"data-x-position":_r,"data-index":F,"data-front":mn,"data-swiping":cr,"data-dismissible":Or,"data-type":Lr,"data-invert":Vi,"data-swipe-out":Kt,"data-swipe-direction":nt,"data-expanded":!!(G||ge&&vt),style:{"--index":F,"--toasts-before":F,"--z-index":$.length-F,"--offset":`${Ct?Qt:Ki.current}px`,"--initial-height":ge?"auto":`${Vr}px`,...ee,...T.style},onDragEnd:()=>{ft(!1),ot(null),ci.current=null},onPointerDown:at=>{Yi||!Or||(Ar.current=new Date,zt(Ki.current),at.target.setPointerCapture(at.pointerId),at.target.tagName!=="BUTTON"&&(ft(!0),ci.current={x:at.clientX,y:at.clientY}))},onPointerUp:()=>{var at,yt,rr,Er;if(Kt||!Or)return;ci.current=null;let Wr=Number(((at=Tn.current)==null?void 0:at.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Nr=Number(((yt=Tn.current)==null?void 0:yt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Zr=new Date().getTime()-((rr=Ar.current)==null?void 0:rr.getTime()),$r=He==="x"?Wr:Nr,qn=Math.abs($r)/Zr;if(Math.abs($r)>=MBe||qn>.11){zt(Ki.current),(Er=T.onDismiss)==null||Er.call(T,T),tt(He==="x"?Wr>0?"right":"left":Nr>0?"down":"up"),nn(),ir(!0),tr(!1);return}ft(!1),ot(null)},onPointerMove:at=>{var yt,rr,Er,Wr;if(!ci.current||!Or||((yt=window.getSelection())==null?void 0:yt.toString().length)>0)return;let Nr=at.clientY-ci.current.y,Zr=at.clientX-ci.current.x,$r=(rr=t.swipeDirections)!=null?rr:FBe(Re);!He&&(Math.abs(Zr)>1||Math.abs(Nr)>1)&&ot(Math.abs(Zr)>Math.abs(Nr)?"x":"y");let qn={x:0,y:0};He==="y"?($r.includes("top")||$r.includes("bottom"))&&($r.includes("top")&&Nr<0||$r.includes("bottom")&&Nr>0)&&(qn.y=Nr):He==="x"&&($r.includes("left")||$r.includes("right"))&&($r.includes("left")&&Zr<0||$r.includes("right")&&Zr>0)&&(qn.x=Zr),(Math.abs(qn.x)>0||Math.abs(qn.y)>0)&&tr(!0),(Er=Tn.current)==null||Er.style.setProperty("--swipe-amount-x",`${qn.x}px`),(Wr=Tn.current)==null||Wr.style.setProperty("--swipe-amount-y",`${qn.y}px`)}},Mi&&!T.jsx?et.createElement("button",{"aria-label":ke,"data-disabled":Yi,"data-close-button":!0,onClick:Yi||!Or?()=>{}:()=>{var at;nn(),(at=T.onDismiss)==null||at.call(T,T)},className:Em($e==null?void 0:$e.closeButton,(i=T==null?void 0:T.classNames)==null?void 0:i.closeButton)},(a=we==null?void 0:we.close)!=null?a:wBe):null,T.jsx||N.isValidElement(T.title)?T.jsx?T.jsx:typeof T.title=="function"?T.title():T.title:et.createElement(et.Fragment,null,Lr||T.icon||T.promise?et.createElement("div",{"data-icon":"",className:Em($e==null?void 0:$e.icon,(c=T==null?void 0:T.classNames)==null?void 0:c.icon)},T.promise||T.type==="loading"&&!T.icon?T.icon||Ke():null,T.type!=="loading"?T.icon||(we==null?void 0:we[Lr])||pBe(Lr):null):null,et.createElement("div",{"data-content":"",className:Em($e==null?void 0:$e.content,(d=T==null?void 0:T.classNames)==null?void 0:d.content)},et.createElement("div",{"data-title":"",className:Em($e==null?void 0:$e.title,(p=T==null?void 0:T.classNames)==null?void 0:p.title)},typeof T.title=="function"?T.title():T.title),T.description?et.createElement("div",{"data-description":"",className:Em(Le,ss,$e==null?void 0:$e.description,(l=T==null?void 0:T.classNames)==null?void 0:l.description)},typeof T.description=="function"?T.description():T.description):null),N.isValidElement(T.cancel)?T.cancel:T.cancel&&lD(T.cancel)?et.createElement("button",{"data-button":!0,"data-cancel":!0,style:T.cancelButtonStyle||ie,onClick:at=>{var yt,rr;lD(T.cancel)&&Or&&((rr=(yt=T.cancel).onClick)==null||rr.call(yt,at),nn())},className:Em($e==null?void 0:$e.cancelButton,(g=T==null?void 0:T.classNames)==null?void 0:g.cancelButton)},T.cancel.label):null,N.isValidElement(T.action)?T.action:T.action&&lD(T.action)?et.createElement("button",{"data-button":!0,"data-action":!0,style:T.actionButtonStyle||oe,onClick:at=>{var yt,rr;lD(T.action)&&((rr=(yt=T.action).onClick)==null||rr.call(yt,at),!at.defaultPrevented&&nn())},className:Em($e==null?void 0:$e.actionButton,(v=T==null?void 0:T.classNames)==null?void 0:v.actionButton)},T.action.label):null))};function rae(){if(typeof window>"u"||typeof document>"u")return"ltr";let t=document.documentElement.getAttribute("dir");return t==="auto"||!t?window.getComputedStyle(document.documentElement).direction:t}function zBe(t,e){let r={};return[t,e].forEach((n,i)=>{let a=i===1,c=a?"--mobile-offset":"--offset",d=a?RBe:NBe;function p(l){["top","right","bottom","left"].forEach(g=>{r[`${c}-${g}`]=typeof l=="number"?`${l}px`:l})}typeof n=="number"||typeof n=="string"?p(n):typeof n=="object"?["top","right","bottom","left"].forEach(l=>{n[l]===void 0?r[`${c}-${l}`]=d:r[`${c}-${l}`]=typeof n[l]=="number"?`${n[l]}px`:n[l]}):p(d)}),r}var $Be=N.forwardRef(function(t,e){let{invert:r,position:n="bottom-right",hotkey:i=["altKey","KeyT"],expand:a,closeButton:c,className:d,offset:p,mobileOffset:l,theme:g="light",richColors:v,duration:E,style:T,visibleToasts:j=PBe,toastOptions:P,dir:C=rae(),gap:L=DBe,loadingIcon:O,icons:F,containerAriaLabel:$="Notifications",pauseWhenPageIsHidden:G}=t,[W,Z]=et.useState([]),Q=et.useMemo(()=>Array.from(new Set([n].concat(W.filter(Ae=>Ae.position).map(Ae=>Ae.position)))),[W,n]),[ee,ie]=et.useState([]),[oe,pe]=et.useState(!1),[Le,be]=et.useState(!1),[Re,Ie]=et.useState(g!=="system"?g:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Te=et.useRef(null),ge=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),$e=et.useRef(null),we=et.useRef(!1),ke=et.useCallback(Ae=>{Z(He=>{var ot;return(ot=He.find(nt=>nt.id===Ae.id))!=null&&ot.delete||ih.dismiss(Ae.id),He.filter(({id:nt})=>nt!==Ae.id)})},[]);return et.useEffect(()=>ih.subscribe(Ae=>{if(Ae.dismiss){Z(He=>He.map(ot=>ot.id===Ae.id?{...ot,delete:!0}:ot));return}setTimeout(()=>{P3e.flushSync(()=>{Z(He=>{let ot=He.findIndex(nt=>nt.id===Ae.id);return ot!==-1?[...He.slice(0,ot),{...He[ot],...Ae},...He.slice(ot+1)]:[Ae,...He]})})})}),[]),et.useEffect(()=>{if(g!=="system"){Ie(g);return}if(g==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Ie("dark"):Ie("light")),typeof window>"u")return;let Ae=window.matchMedia("(prefers-color-scheme: dark)");try{Ae.addEventListener("change",({matches:He})=>{Ie(He?"dark":"light")})}catch{Ae.addListener(({matches:ot})=>{try{Ie(ot?"dark":"light")}catch(nt){console.error(nt)}})}},[g]),et.useEffect(()=>{W.length<=1&&pe(!1)},[W]),et.useEffect(()=>{let Ae=He=>{var ot,nt;i.every(tt=>He[tt]||He.code===tt)&&(pe(!0),(ot=Te.current)==null||ot.focus()),He.code==="Escape"&&(document.activeElement===Te.current||(nt=Te.current)!=null&&nt.contains(document.activeElement))&&pe(!1)};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[i]),et.useEffect(()=>{if(Te.current)return()=>{$e.current&&($e.current.focus({preventScroll:!0}),$e.current=null,we.current=!1)}},[Te.current]),et.createElement("section",{ref:e,"aria-label":`${$} ${ge}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},Q.map((Ae,He)=>{var ot;let[nt,tt]=Ae.split("-");return W.length?et.createElement("ol",{key:Ae,dir:C==="auto"?rae():C,tabIndex:-1,ref:Te,className:d,"data-sonner-toaster":!0,"data-theme":Re,"data-y-position":nt,"data-lifted":oe&&W.length>1&&!a,"data-x-position":tt,style:{"--front-toast-height":`${((ot=ee[0])==null?void 0:ot.height)||0}px`,"--width":`${LBe}px`,"--gap":`${L}px`,...T,...zBe(p,l)},onBlur:vt=>{we.current&&!vt.currentTarget.contains(vt.relatedTarget)&&(we.current=!1,$e.current&&($e.current.focus({preventScroll:!0}),$e.current=null))},onFocus:vt=>{vt.target instanceof HTMLElement&&vt.target.dataset.dismissible==="false"||we.current||(we.current=!0,$e.current=vt.relatedTarget)},onMouseEnter:()=>pe(!0),onMouseMove:()=>pe(!0),onMouseLeave:()=>{Le||pe(!1)},onDragEnd:()=>pe(!1),onPointerDown:vt=>{vt.target instanceof HTMLElement&&vt.target.dataset.dismissible==="false"||be(!0)},onPointerUp:()=>be(!1)},W.filter(vt=>!vt.position&&He===0||vt.position===Ae).map((vt,Vt)=>{var Ct,Bt;return et.createElement(BBe,{key:vt.id,icons:F,index:Vt,toast:vt,defaultRichColors:v,duration:(Ct=P==null?void 0:P.duration)!=null?Ct:E,className:P==null?void 0:P.className,descriptionClassName:P==null?void 0:P.descriptionClassName,invert:r,visibleToasts:j,closeButton:(Bt=P==null?void 0:P.closeButton)!=null?Bt:c,interacting:Le,position:Ae,style:P==null?void 0:P.style,unstyled:P==null?void 0:P.unstyled,classNames:P==null?void 0:P.classNames,cancelButtonStyle:P==null?void 0:P.cancelButtonStyle,actionButtonStyle:P==null?void 0:P.actionButtonStyle,removeToast:ke,toasts:W.filter(cr=>cr.position==vt.position),heights:ee.filter(cr=>cr.position==vt.position),setHeights:ie,expandByDefault:a,gap:L,loadingIcon:O,expanded:oe,pauseWhenPageIsHidden:G,swipeDirections:t.swipeDirections})})):null}))});const UBe=({...t})=>{const{theme:e="system"}=mBe();return s.jsx($Be,{theme:e,position:"top-center",className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...t})};var VBe=Object.defineProperty,qBe=(t,e)=>VBe(t,"name",{value:e,configurable:!0}),GBe=ex[" useId ".trim().toString()]||(()=>{}),HBe=0;function Wl(t){const[e,r]=N.useState(GBe());return no(()=>{t||r(n=>n??String(HBe++))},[t]),t||(e?`radix-${e}`:"")}qBe(Wl,"useId");var WBe=Object.defineProperty,dc=(t,e)=>WBe(t,"name",{value:e,configurable:!0}),q6="focusScope.autoFocusOnMount",G6="focusScope.autoFocusOnUnmount",nae={bubbles:!1,cancelable:!0},j4=N.forwardRef(dc(function(e,r){const{loop:n=!1,trapped:i=!1,branches:a,onMountAutoFocus:c,onUnmountAutoFocus:d,...p}=e,[l,g]=N.useState(null),v=Yo(c),E=Yo(d),T=N.useRef(null),j=Jn(r,g),P=N.useRef(a);N.useEffect(()=>{P.current=a});const C=N.useCallback(F=>{var $;return F?l!=null&&l.contains(F)?!0:!!(($=P.current)!=null&&$.some(G=>G.contains(F))):!1},[l]),L=N.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;N.useEffect(()=>{if(i){let F=function(Z){if(L.paused||!l)return;const Q=Z.target;C(Q)?T.current=Q:gy(T.current,{select:!0})},$=function(Z){if(L.paused||!l)return;const Q=Z.relatedTarget;Q!==null&&(C(Q)||gy(T.current,{select:!0}))},G=function(Z){if(document.activeElement===document.body)for(const ee of Z)ee.removedNodes.length>0&&gy(l)};dc(F,"handleFocusIn"),dc($,"handleFocusOut"),dc(G,"handleMutations"),document.addEventListener("focusin",F),document.addEventListener("focusout",$);const W=new MutationObserver(G);return l&&W.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",F),document.removeEventListener("focusout",$),W.disconnect()}}},[i,l,L.paused,C]),N.useEffect(()=>{if(l){iae.add(L);const F=document.activeElement;if(!l.contains(F)){const G=new CustomEvent(q6,nae);l.addEventListener(q6,v),l.dispatchEvent(G),G.defaultPrevented||(Ive(Rve(iK(l)),{select:!0}),document.activeElement===F&&gy(l))}return()=>{l.removeEventListener(q6,v);const G=l.ownerDocument,W=CustomEvent;setTimeout(()=>{const Z=new W(G6,nae);l.addEventListener(G6,E),l.dispatchEvent(Z),Z.defaultPrevented||gy(F??G.body,{select:!0}),l.removeEventListener(G6,E),iae.remove(L)},0)}}},[l,v,E,L]);const O=N.useCallback(F=>{if(!n&&!i||L.paused)return;const $=F.key==="Tab"&&!F.altKey&&!F.ctrlKey&&!F.metaKey,G=document.activeElement;if($&&G){const W=F.currentTarget,[Z,Q]=jve(W);Z&&Q?!F.shiftKey&&G===Q?(F.preventDefault(),n&&gy(Z,{select:!0})):F.shiftKey&&G===Z&&(F.preventDefault(),n&&gy(Q,{select:!0})):G===W&&F.preventDefault()}},[n,i,L.paused]);return s.jsx(An.div,{tabIndex:-1,...p,ref:j,onKeyDown:O})},"FocusScope")),kve=N.createContext(null);function C4({registry:t,children:e}){return t?s.jsx(kve.Provider,{value:t,children:e}):e}dc(C4,"FocusScopeBranchProvider");function P4(){const[t,e]=N.useState([]),r=N.useMemo(()=>({add:dc(n=>e(i=>i.includes(n)?i:[...i,n]),"add"),remove:dc(n=>e(i=>i.filter(a=>a!==n)),"remove")}),[]);return{nodes:t,registry:r}}dc(P4,"useFocusScopeBranchRegistry");function N4(t){const e=N.useContext(kve);N.useEffect(()=>{if(!(!t||!e))return e.add(t),()=>e.remove(t)},[t,e])}dc(N4,"useFocusScopeBranch");function Ive(t,{select:e=!1}={}){const r=document.activeElement;for(const n of t)if(gy(n,{select:e}),document.activeElement!==r)return}dc(Ive,"focusFirst");function jve(t){const e=iK(t),r=Oq(e,t),n=Oq(e.reverse(),t);return[r,n]}dc(jve,"getTabbableEdges");function iK(t){const e=[],n=t.ownerDocument.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:dc(i=>{const a=i.tagName==="INPUT"&&i.type==="hidden";return i.disabled||i.hidden||a?NodeFilter.FILTER_SKIP:i.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)e.push(n.currentNode);return e}dc(iK,"getTabbableCandidates");function Oq(t,e){const r=typeof e.checkVisibility=="function"&&e.checkVisibility({checkVisibilityCSS:!0});for(const n of t)if(!(r?!n.checkVisibility({checkVisibilityCSS:!0}):Cve(n,{upTo:e})))return n}dc(Oq,"findVisible");function Cve(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}dc(Cve,"isHidden");function Pve(t){return t.tagName==="INPUT"&&typeof t.select=="function"}dc(Pve,"isSelectableInput");function gy(t,{select:e=!1}={}){if(t&&t.focus){const n=(t.ownerDocument??document).activeElement;t.focus({preventScroll:!0}),t!==n&&Pve(t)&&e&&t.select()}}dc(gy,"focus");var iae=Nve();function Nve(){let t=[];return{add(e){const r=t[0];e!==r&&(r==null||r.pause()),t=Fq(t,e),t.unshift(e)},remove(e){var r;t=Fq(t,e),(r=t[0])==null||r.resume()}}}dc(Nve,"createFocusScopesStack");function Fq(t,e){const r=[...t],n=r.indexOf(e);return n!==-1&&r.splice(n,1),r}dc(Fq,"arrayRemove");function Rve(t){return t.filter(e=>e.tagName!=="A")}dc(Rve,"removeLinks");var KBe=Object.defineProperty,sK=(t,e)=>KBe(t,"name",{value:e,configurable:!0}),cD=0,Rp=null;function YBe(t){return aA(),t.children}sK(YBe,"FocusGuards");function aA(){N.useEffect(()=>{Rp||(Rp={start:Bq(),end:Bq()});const{start:t,end:e}=Rp;return document.body.firstElementChild!==t&&document.body.insertAdjacentElement("afterbegin",t),document.body.lastElementChild!==e&&document.body.insertAdjacentElement("beforeend",e),cD++,()=>{cD===1&&(Rp==null||Rp.start.remove(),Rp==null||Rp.end.remove(),Rp=null),cD=Math.max(0,cD-1)}},[])}sK(aA,"useFocusGuards");function Bq(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}sK(Bq,"createFocusGuard");var Kp=function(){return Kp=Object.assign||function(e){for(var r,n=1,i=arguments.length;n"u")return hze;var e=fze(t),r=document.documentElement.clientWidth,n=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,n-r+e[2]-e[0])}},pze=Ove(),bE="data-scroll-locked",gze=function(t,e,r,n){var i=t.left,a=t.top,c=t.right,d=t.gap;return r===void 0&&(r="margin"),` .`.concat(XBe,` { overflow: hidden `).concat(n,`; padding-right: `).concat(d,"px ").concat(n,`; } body[`).concat(bE,`] { overflow: hidden `).concat(n,`; overscroll-behavior: contain; `).concat([e&&"position: relative ".concat(n,";"),r==="margin"&&` padding-left: `.concat(i,`px; padding-top: `).concat(a,`px; padding-right: `).concat(c,`px; margin-left:0; margin-top:0; margin-right: `).concat(d,"px ").concat(n,`; `),r==="padding"&&"padding-right: ".concat(d,"px ").concat(n,";")].filter(Boolean).join(""),` } .`).concat(WM,` { right: `).concat(d,"px ").concat(n,`; } .`).concat(KM,` { margin-right: `).concat(d,"px ").concat(n,`; } .`).concat(WM," .").concat(WM,` { right: 0 `).concat(n,`; } .`).concat(KM," .").concat(KM,` { margin-right: 0 `).concat(n,`; } body[`).concat(bE,`] { `).concat(QBe,": ").concat(d,`px; } `)},aae=function(){var t=parseInt(document.body.getAttribute(bE)||"0",10);return isFinite(t)?t:0},yze=function(){N.useEffect(function(){return document.body.setAttribute(bE,(aae()+1).toString()),function(){var t=aae()-1;t<=0?document.body.removeAttribute(bE):document.body.setAttribute(bE,t.toString())}},[])},xze=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,i=n===void 0?"margin":n;yze();var a=N.useMemo(function(){return mze(i)},[i]);return N.createElement(pze,{styles:gze(a,!e,i,r?"":"!important")})},zq=!1;if(typeof window<"u")try{var uD=Object.defineProperty({},"passive",{get:function(){return zq=!0,!0}});window.addEventListener("test",uD,uD),window.removeEventListener("test",uD,uD)}catch{zq=!1}var yS=zq?{passive:!1}:!1,_ze=function(t){return t.tagName==="TEXTAREA"},Fve=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!_ze(t)&&r[e]==="visible")},vze=function(t){return Fve(t,"overflowY")},bze=function(t){return Fve(t,"overflowX")},oae=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var i=Bve(t,n);if(i){var a=zve(t,n),c=a[1],d=a[2];if(c>d)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},wze=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},Sze=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},Bve=function(t,e){return t==="v"?vze(e):bze(e)},zve=function(t,e){return t==="v"?wze(e):Sze(e)},Eze=function(t,e){return t==="h"&&e==="rtl"?-1:1},Tze=function(t,e,r,n,i){var a=Eze(t,window.getComputedStyle(e).direction),c=a*n,d=r.target,p=e.contains(d),l=!1,g=c>0,v=0,E=0;do{if(!d)break;var T=zve(t,d),j=T[0],P=T[1],C=T[2],L=P-C-a*j;(j||L)&&Bve(t,d)&&(v+=L,E+=j);var O=d.parentNode;d=O&&O.nodeType===Node.DOCUMENT_FRAGMENT_NODE?O.host:O}while(!p&&d!==document.body||p&&(e.contains(d)||e===d));return(g&&Math.abs(v)<1||!g&&Math.abs(E)<1)&&(l=!0),l},dD=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},lae=function(t){return[t.deltaX,t.deltaY]},cae=function(t){return t&&"current"in t?t.current:t},Aze=function(t,e){return t[0]===e[0]&&t[1]===e[1]},kze=function(t){return` .block-interactivity-`.concat(t,` {pointer-events: none;} .allow-interactivity-`).concat(t,` {pointer-events: all;} `)},Ize=0,xS=[];function jze(t){var e=N.useRef([]),r=N.useRef([0,0]),n=N.useRef(),i=N.useState(Ize++)[0],a=N.useState(Ove)[0],c=N.useRef(t);N.useEffect(function(){c.current=t},[t]),N.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(i));var P=ZBe([t.lockRef.current],(t.shards||[]).map(cae),!0).filter(Boolean);return P.forEach(function(C){return C.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),P.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var d=N.useCallback(function(P,C){if("touches"in P&&P.touches.length===2||P.type==="wheel"&&P.ctrlKey)return!c.current.allowPinchZoom;var L=dD(P),O=r.current,F="deltaX"in P?P.deltaX:O[0]-L[0],$="deltaY"in P?P.deltaY:O[1]-L[1],G,W=P.target,Z=Math.abs(F)>Math.abs($)?"h":"v";if("touches"in P&&Z==="h"&&W.type==="range")return!1;var Q=window.getSelection(),ee=Q&&Q.anchorNode,ie=ee?ee===W||ee.contains(W):!1;if(ie)return!1;var oe=oae(Z,W);if(!oe)return!0;if(oe?G=Z:(G=Z==="v"?"h":"v",oe=oae(Z,W)),!oe)return!1;if(!n.current&&"changedTouches"in P&&(F||$)&&(n.current=G),!G)return!0;var pe=n.current||G;return Tze(pe,C,P,pe==="h"?F:$)},[]),p=N.useCallback(function(P){var C=P;if(!(!xS.length||xS[xS.length-1]!==a)){var L="deltaY"in C?lae(C):dD(C),O=e.current.filter(function(G){return G.name===C.type&&(G.target===C.target||C.target===G.shadowParent)&&Aze(G.delta,L)})[0];if(O&&O.should){C.cancelable&&C.preventDefault();return}if(!O){var F=(c.current.shards||[]).map(cae).filter(Boolean).filter(function(G){return G.contains(C.target)}),$=F.length>0?d(C,F[0]):!c.current.noIsolation;$&&C.cancelable&&C.preventDefault()}}},[]),l=N.useCallback(function(P,C,L,O){var F={name:P,delta:C,target:L,should:O,shadowParent:Cze(L)};e.current.push(F),setTimeout(function(){e.current=e.current.filter(function($){return $!==F})},1)},[]),g=N.useCallback(function(P){r.current=dD(P),n.current=void 0},[]),v=N.useCallback(function(P){l(P.type,lae(P),P.target,d(P,t.lockRef.current))},[]),E=N.useCallback(function(P){l(P.type,dD(P),P.target,d(P,t.lockRef.current))},[]);N.useEffect(function(){return xS.push(a),t.setCallbacks({onScrollCapture:v,onWheelCapture:v,onTouchMoveCapture:E}),document.addEventListener("wheel",p,yS),document.addEventListener("touchmove",p,yS),document.addEventListener("touchstart",g,yS),function(){xS=xS.filter(function(P){return P!==a}),document.removeEventListener("wheel",p,yS),document.removeEventListener("touchmove",p,yS),document.removeEventListener("touchstart",g,yS)}},[]);var T=t.removeScrollBar,j=t.inert;return N.createElement(N.Fragment,null,j?N.createElement(a,{styles:kze(i)}):null,T?N.createElement(xze,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function Cze(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const Pze=sze(Mve,jze);var DP=N.forwardRef(function(t,e){return N.createElement(R4,Kp({},t,{ref:e,sideCar:Pze}))});DP.classNames=R4.classNames;var Nze=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},_S=new WeakMap,hD=new WeakMap,fD={},Y6=0,$ve=function(t){return t&&(t.host||$ve(t.parentNode))},Rze=function(t,e){return e.map(function(r){if(t.contains(r))return r;var n=$ve(r);return n&&t.contains(n)?n:(console.error("aria-hidden",r,"in not contained inside",t,". Doing nothing"),null)}).filter(function(r){return!!r})},Lze=function(t,e,r,n){var i=Rze(e,Array.isArray(t)?t:[t]);fD[r]||(fD[r]=new WeakMap);var a=fD[r],c=[],d=new Set,p=new Set(i),l=function(v){!v||d.has(v)||(d.add(v),l(v.parentNode))};i.forEach(l);var g=function(v){!v||p.has(v)||Array.prototype.forEach.call(v.children,function(E){if(d.has(E))g(E);else try{var T=E.getAttribute(n),j=T!==null&&T!=="false",P=(_S.get(E)||0)+1,C=(a.get(E)||0)+1;_S.set(E,P),a.set(E,C),c.push(E),P===1&&j&&hD.set(E,!0),C===1&&E.setAttribute(r,"true"),j||E.setAttribute(n,"true")}catch(L){console.error("aria-hidden: cannot operate on ",E,L)}})};return g(e),d.clear(),Y6++,function(){c.forEach(function(v){var E=_S.get(v)-1,T=a.get(v)-1;_S.set(v,E),a.set(v,T),E||(hD.has(v)||v.removeAttribute(n),hD.delete(v)),T||v.removeAttribute(r)}),Y6--,Y6||(_S=new WeakMap,_S=new WeakMap,hD=new WeakMap,fD={})}},L4=function(t,e,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(t)?t:[t]),i=Nze(t);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live], script"))),Lze(n,i,r,"aria-hidden")):function(){return null}},Dze=Object.defineProperty,xh=(t,e)=>Dze(t,"name",{value:e,configurable:!0}),aK="Dialog",[Uve,Vve]=Nl(aK),[Mze,lp]=Uve(aK),D4=xh(t=>{const{__scopeDialog:e,children:r,open:n,defaultOpen:i,onOpenChange:a,modal:c=!0}=t,d=N.useRef(null),p=N.useRef(null),{nodes:l,registry:g}=P4(),[v,E]=ph({prop:n,defaultProp:i??!1,onChange:a,caller:aK}),[T,j]=N.useState(0),[P,C]=N.useState(0);return s.jsx(Mze,{scope:e,triggerRef:d,contentRef:p,contentId:Wl(),titleId:Wl(),descriptionId:Wl(),titlePresent:T>0,descriptionPresent:P>0,setTitleCount:j,setDescriptionCount:C,open:v,onOpenChange:E,onOpenToggle:N.useCallback(()=>E(L=>!L),[E]),modal:c,branchNodes:l,branchRegistry:g,children:r})},"Dialog"),Oze="DialogTrigger",oK=N.forwardRef(xh(function(e,r){const{__scopeDialog:n,...i}=e,a=lp(Oze,n),c=Jn(r,a.triggerRef);return s.jsx(An.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":O4(a.open),...i,ref:c,onClick:Qr(e.onClick,a.onOpenToggle)})},"DialogTrigger")),qve="DialogPortal",[Fze,Gve]=Uve(qve,{forceMount:void 0}),M4=xh(t=>{const{__scopeDialog:e,forceMount:r,children:n,container:i}=t,a=lp(qve,e);return s.jsx(Fze,{scope:e,forceMount:r,children:N.Children.map(n,c=>s.jsx(zc,{present:r||a.open,children:s.jsx(jP,{asChild:!0,container:i,children:c})}))})},"DialogPortal"),$q="DialogOverlay",oA=N.forwardRef(xh(function(e,r){const n=Gve($q,e.__scopeDialog),{forceMount:i=n.forceMount,...a}=e,c=lp($q,e.__scopeDialog);return c.modal?s.jsx(zc,{present:i||c.open,children:s.jsx(zze,{...a,ref:r})}):null},"DialogOverlay")),Bze=sp("DialogOverlay.RemoveScroll"),zze=N.forwardRef(xh(function(e,r){const{__scopeDialog:n,...i}=e,a=lp($q,n),c=k_e(),d=Jn(r,c);return s.jsx(DP,{as:Bze,allowPinchZoom:!0,shards:N.useMemo(()=>[a.contentRef,...a.branchNodes.map(p=>({current:p}))],[a.contentRef,a.branchNodes]),children:s.jsx(An.div,{"data-state":O4(a.open),...i,ref:d,style:{pointerEvents:"auto",...i.style}})})},"DialogOverlayImpl")),Kj="DialogContent",lA=N.forwardRef(xh(function(e,r){const n=Gve(Kj,e.__scopeDialog),{forceMount:i=n.forceMount,...a}=e,c=lp(Kj,e.__scopeDialog);return s.jsx(zc,{present:i||c.open,children:c.modal?s.jsx($ze,{...a,ref:r}):s.jsx(Uze,{...a,ref:r})})},"DialogContent")),$ze=N.forwardRef(xh(function(e,r){const n=lp(Kj,e.__scopeDialog),i=N.useRef(null),a=Jn(r,n.contentRef,i);return N.useEffect(()=>{const c=i.current;if(c)return L4(c)},[]),s.jsx(Hve,{...e,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,onCloseAutoFocus:Qr(e.onCloseAutoFocus,c=>{var d;c.preventDefault(),(d=n.triggerRef.current)==null||d.focus()}),onPointerDownOutside:Qr(e.onPointerDownOutside,c=>{const d=c.detail.originalEvent,p=d.button===0&&d.ctrlKey===!0;(d.button===2||p)&&c.preventDefault()}),onFocusOutside:Qr(e.onFocusOutside,c=>c.preventDefault())})},"DialogContentModal")),Uze=N.forwardRef(xh(function(e,r){const n=lp(Kj,e.__scopeDialog),i=N.useRef(!1),a=N.useRef(!1);return s.jsx(Hve,{...e,ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:c=>{var d,p;(d=e.onCloseAutoFocus)==null||d.call(e,c),c.defaultPrevented||(i.current||(p=n.triggerRef.current)==null||p.focus(),c.preventDefault()),i.current=!1,a.current=!1},onInteractOutside:c=>{var l,g;(l=e.onInteractOutside)==null||l.call(e,c),c.defaultPrevented||(i.current=!0,c.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const d=c.target;((g=n.triggerRef.current)==null?void 0:g.contains(d))&&c.preventDefault(),c.detail.originalEvent.type==="focusin"&&a.current&&c.preventDefault()}})},"DialogContentNonModal")),Hve=N.forwardRef(xh(function(e,r){const{__scopeDialog:n,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:c,"aria-describedby":d,children:p,...l}=e,g=lp(Kj,n);return aA(),s.jsx(C4,{registry:g.branchRegistry,children:s.jsx(j4,{asChild:!0,loop:!0,trapped:i,branches:g.branchNodes,onMountAutoFocus:a,onUnmountAutoFocus:c,children:s.jsx(JT,{role:"dialog",id:g.contentId,"aria-labelledby":g.titlePresent?g.titleId:void 0,"aria-describedby":g.descriptionPresent?Wve(d,g.descriptionId):d,"data-state":O4(g.open),...l,ref:r,deferPointerDownOutside:!0,onDismiss:()=>g.onOpenChange(!1),children:p})})})},"DialogContentImpl")),MP=N.forwardRef(xh(function(e,r){const{__scopeDialog:n,...i}=e,a=lp("DialogTitle",n),{setTitleCount:c}=a;return no(()=>(c(d=>d+1),()=>c(d=>d-1)),[c]),s.jsx(An.h2,{id:a.titleId,...i,ref:r})},"DialogTitle")),OP=N.forwardRef(xh(function(e,r){const{__scopeDialog:n,...i}=e,a=lp("DialogDescription",n),{setDescriptionCount:c}=a;return no(()=>(c(d=>d+1),()=>c(d=>d-1)),[c]),s.jsx(An.p,{id:a.descriptionId,...i,ref:r})},"DialogDescription")),Vze="DialogClose",FP=N.forwardRef(xh(function(e,r){const{__scopeDialog:n,...i}=e,a=lp(Vze,n);return s.jsx(An.button,{type:"button",...i,ref:r,onClick:Qr(e.onClick,()=>a.onOpenChange(!1))})},"DialogClose"));function Wve(...t){const e=new Set;for(const r of t)if(typeof r=="string")for(const n of String(r).trim().split(/\s+/))n&&e.add(n);return e.size>0?Array.from(e).join(" "):void 0}xh(Wve,"concatAriaDescribedby");function O4(t){return t?"open":"closed"}xh(O4,"getState");var qze=Object.defineProperty,rx=(t,e)=>qze(t,"name",{value:e,configurable:!0}),Gze="AlertDialog",[Hze,FWt]=Nl(Gze,[Vve]),nx=Vve(),Wze=rx(t=>{const{__scopeAlertDialog:e,...r}=t,n=nx(e);return s.jsx(D4,{...n,...r,modal:!0})},"AlertDialog"),Kze=N.forwardRef(rx(function(e,r){const{__scopeAlertDialog:n,...i}=e,a=nx(n);return s.jsx(oK,{...a,...i,ref:r})},"AlertDialogTrigger")),Yze=rx(t=>{const{__scopeAlertDialog:e,...r}=t,n=nx(e);return s.jsx(M4,{...n,...r})},"AlertDialogPortal"),Kve=N.forwardRef(rx(function(e,r){const{__scopeAlertDialog:n,...i}=e,a=nx(n);return s.jsx(oA,{...a,...i,ref:r})},"AlertDialogOverlay")),Zze="AlertDialogContent",[Xze,Qze]=Hze(Zze),Yve=N.forwardRef(rx(function(e,r){const{__scopeAlertDialog:n,children:i,...a}=e,c=nx(n),d=N.useRef(null),p=Jn(r,d),l=N.useRef(null);return s.jsx(Xze,{scope:n,cancelRef:l,children:s.jsx(lA,{role:"alertdialog",...c,...a,ref:p,onOpenAutoFocus:Qr(a.onOpenAutoFocus,g=>{var v;g.preventDefault(),(v=l.current)==null||v.focus({preventScroll:!0})}),onPointerDownOutside:g=>g.preventDefault(),onInteractOutside:g=>g.preventDefault(),children:i})})},"AlertDialogContent")),Zve=N.forwardRef(rx(function(e,r){const{__scopeAlertDialog:n,...i}=e,a=nx(n);return s.jsx(MP,{...a,...i,ref:r})},"AlertDialogTitle")),Xve=N.forwardRef(rx(function(e,r){const{__scopeAlertDialog:n,...i}=e,a=nx(n);return s.jsx(OP,{...a,...i,ref:r})},"AlertDialogDescription")),Qve=N.forwardRef(rx(function(e,r){const{__scopeAlertDialog:n,...i}=e,a=nx(n);return s.jsx(FP,{...a,...i,ref:r})},"AlertDialogAction")),Jze="AlertDialogCancel",Jve=N.forwardRef(rx(function(e,r){const{__scopeAlertDialog:n,...i}=e,{cancelRef:a}=Qze(Jze,n),c=nx(n),d=Jn(r,a);return s.jsx(FP,{...c,...i,ref:d})},"AlertDialogCancel"));const Yj=eA("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-full px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),Jt=N.forwardRef(({className:t,variant:e,size:r,asChild:n=!1,...i},a)=>{const c=n?m_e:"button";return s.jsx(c,{className:hr(Yj({variant:e,size:r,className:t})),ref:a,...i})});Jt.displayName="Button";const e0e=Wze,BWt=Kze,e$e=Yze,t0e=N.forwardRef(({className:t,...e},r)=>s.jsx(Kve,{className:hr("fixed inset-0 z-50 bg-foreground/45 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...e,ref:r}));t0e.displayName=Kve.displayName;const lK=N.forwardRef(({className:t,...e},r)=>s.jsxs(e$e,{children:[s.jsx(t0e,{}),s.jsx(Yve,{ref:r,className:hr("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...e})]}));lK.displayName=Yve.displayName;const cK=({className:t,...e})=>s.jsx("div",{className:hr("flex flex-col space-y-2 text-center sm:text-left",t),...e});cK.displayName="AlertDialogHeader";const uK=({className:t,...e})=>s.jsx("div",{className:hr("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});uK.displayName="AlertDialogFooter";const dK=N.forwardRef(({className:t,...e},r)=>s.jsx(Zve,{ref:r,className:hr("text-lg font-semibold",t),...e}));dK.displayName=Zve.displayName;const hK=N.forwardRef(({className:t,...e},r)=>s.jsx(Xve,{ref:r,className:hr("text-sm text-muted-foreground",t),...e}));hK.displayName=Xve.displayName;const fK=N.forwardRef(({className:t,...e},r)=>s.jsx(Qve,{ref:r,className:hr(Yj(),t),...e}));fK.displayName=Qve.displayName;const mK=N.forwardRef(({className:t,...e},r)=>s.jsx(Jve,{ref:r,className:hr(Yj({variant:"outline"}),"mt-2 sm:mt-0",t),...e}));mK.displayName=Jve.displayName;let oF=null;const t$e=["delete","remove","revoke","cannot be undone","permanently"];function zWt(t,e={}){const r=typeof t=="string"?{description:t,...e}:t,n=`${r.title??""} ${r.description??""}`.toLowerCase(),i=r.destructive??t$e.some(a=>n.includes(a));return new Promise(a=>{if(!oF){a(window.confirm(r.description??r.title??"Are you sure?"));return}oF({...r,destructive:i,resolve:a})})}function r$e(){const[t,e]=N.useState(null);N.useEffect(()=>(oF=i=>e(i),()=>{oF=null}),[]);const r=i=>{t==null||t.resolve(i),e(null)},n=!!(t!=null&&t.destructive);return s.jsx(e0e,{open:!!t,onOpenChange:i=>!i&&r(!1),children:s.jsxs(lK,{className:"sm:max-w-md",children:[s.jsx(cK,{children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:hr("mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-full",n?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"),children:s.jsx(LP,{className:"h-5 w-5"})}),s.jsxs("div",{className:"space-y-1.5 text-left",children:[s.jsx(dK,{children:(t==null?void 0:t.title)??(n?"Are you sure?":"Please confirm")}),(t==null?void 0:t.description)&&s.jsx(hK,{className:"leading-relaxed",children:t.description})]})]})}),s.jsxs(uK,{className:"gap-2 sm:gap-2",children:[s.jsx(mK,{onClick:()=>r(!1),children:(t==null?void 0:t.cancelText)??"Cancel"}),s.jsx(fK,{onClick:()=>r(!0),className:hr(n&&"bg-destructive text-destructive-foreground hover:bg-destructive/90"),children:(t==null?void 0:t.confirmText)??(n?"Delete":"Continue")})]})]})})}const n$e=["top","right","bottom","left"],_v=Math.min,Ny=Math.max,lF=Math.round,mD=Math.floor,Ry=t=>({x:t,y:t}),i$e={left:"right",right:"left",bottom:"top",top:"bottom"};function r0e(t,e,r){return Ny(t,_v(e,r))}function Gy(t,e){return typeof t=="function"?t(e):t}function vv(t){return t.split("-")[0]}function cA(t){return t.split("-")[1]}function pK(t){return t==="x"?"y":"x"}function gK(t){return t==="y"?"height":"width"}function Xp(t){const e=t[0];return e==="t"||e==="b"?"y":"x"}function yK(t){return pK(Xp(t))}function s$e(t,e,r){r===void 0&&(r=!1);const n=cA(t),i=yK(t),a=gK(i);let c=i==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[a]>e.floating[a]&&(c=cF(c)),[c,cF(c)]}function a$e(t){const e=cF(t);return[Uq(t),e,Uq(e)]}function Uq(t){return t.includes("start")?t.replace("start","end"):t.replace("end","start")}const uae=["left","right"],dae=["right","left"],o$e=["top","bottom"],l$e=["bottom","top"];function c$e(t,e,r){switch(t){case"top":case"bottom":return r?e?dae:uae:e?uae:dae;case"left":case"right":return e?o$e:l$e;default:return[]}}function u$e(t,e,r,n){const i=cA(t);let a=c$e(vv(t),r==="start",n);return i&&(a=a.map(c=>c+"-"+i),e&&(a=a.concat(a.map(Uq)))),a}function cF(t){const e=vv(t);return i$e[e]+t.slice(e.length)}function d$e(t){var e,r,n,i;return{top:(e=t.top)!=null?e:0,right:(r=t.right)!=null?r:0,bottom:(n=t.bottom)!=null?n:0,left:(i=t.left)!=null?i:0}}function n0e(t){return typeof t!="number"?d$e(t):{top:t,right:t,bottom:t,left:t}}function uF(t){const{x:e,y:r,width:n,height:i}=t;return{width:n,height:i,top:r,left:e,right:e+n,bottom:r+i,x:e,y:r}}function hae(t,e,r){let{reference:n,floating:i}=t;const a=Xp(e),c=yK(e),d=gK(c),p=vv(e),l=a==="y",g=n.x+n.width/2-i.width/2,v=n.y+n.height/2-i.height/2,E=n[d]/2-i[d]/2;let T;switch(p){case"top":T={x:g,y:n.y-i.height};break;case"bottom":T={x:g,y:n.y+n.height};break;case"right":T={x:n.x+n.width,y:v};break;case"left":T={x:n.x-i.width,y:v};break;default:T={x:n.x,y:n.y}}const j=cA(e);return j&&(T[c]+=E*(j==="end"?1:-1)*(r&&l?-1:1)),T}async function h$e(t,e){var r;e===void 0&&(e={});const{x:n,y:i,platform:a,rects:c,elements:d,strategy:p}=t,{boundary:l="clippingAncestors",rootBoundary:g="viewport",elementContext:v="floating",altBoundary:E=!1,padding:T=0}=Gy(e,t),j=n0e(T),C=d[E?v==="floating"?"reference":"floating":v],L=uF(await a.getClippingRect({element:(r=await(a.isElement==null?void 0:a.isElement(C)))==null||r?C:C.contextElement||await(a.getDocumentElement==null?void 0:a.getDocumentElement(d.floating)),boundary:l,rootBoundary:g,strategy:p})),O=v==="floating"?{x:n,y:i,width:c.floating.width,height:c.floating.height}:c.reference,F=await(a.getOffsetParent==null?void 0:a.getOffsetParent(d.floating)),$=await(a.isElement==null?void 0:a.isElement(F))&&await(a.getScale==null?void 0:a.getScale(F))||{x:1,y:1},G=uF(a.convertOffsetParentRelativeRectToViewportRelativeRect?await a.convertOffsetParentRelativeRectToViewportRelativeRect({elements:d,rect:O,offsetParent:F,strategy:p}):O);return{top:(L.top-G.top+j.top)/$.y,bottom:(G.bottom-L.bottom+j.bottom)/$.y,left:(L.left-G.left+j.left)/$.x,right:(G.right-L.right+j.right)/$.x}}const f$e=50,m$e=async(t,e,r)=>{const{placement:n="bottom",strategy:i="absolute",middleware:a=[],platform:c}=r,d=c.detectOverflow?c:{...c,detectOverflow:h$e},p=await(c.isRTL==null?void 0:c.isRTL(e));let l=await c.getElementRects({reference:t,floating:e,strategy:i}),{x:g,y:v}=hae(l,n,p),E=n,T=0;const j={};for(let P=0;P({name:"arrow",options:t,async fn(e){const{x:r,y:n,placement:i,rects:a,platform:c,elements:d,middlewareData:p}=e,{element:l,padding:g=0}=Gy(t,e)||{};if(l==null)return{};const v=n0e(g),E={x:r,y:n},T=yK(i),j=gK(T),P=await c.getDimensions(l),C=T==="y",L=C?"top":"left",O=C?"bottom":"right",F=C?"clientHeight":"clientWidth",$=a.reference[j]+a.reference[T]-E[T]-a.floating[j],G=E[T]-a.reference[T],W=await(c.getOffsetParent==null?void 0:c.getOffsetParent(l));let Z=W?W[F]:0;(!Z||!await(c.isElement==null?void 0:c.isElement(W)))&&(Z=d.floating[F]||a.floating[j]);const Q=$/2-G/2,ee=Z/2-P[j]/2-1,ie=_v(v[L],ee),oe=_v(v[O],ee),pe=Z-P[j]-oe,Le=Z/2-P[j]/2+Q,be=r0e(ie,Le,pe),Re=!p.arrow&&cA(i)!=null&&Le!==be&&a.reference[j]/2-(Lebe<=0)){var oe,pe;const be=(((oe=a.flip)==null?void 0:oe.index)||0)+1,Re=Z[be];if(Re&&(!(v==="alignment"?O!==Xp(Re):!1)||ie.every(ge=>Xp(ge.placement)===O?ge.overflows[0]>0:!0)))return{data:{index:be,overflows:ie},reset:{placement:Re}};let Ie=(pe=ie.filter(Te=>Te.overflows[0]<=0).sort((Te,ge)=>Te.overflows[1]-ge.overflows[1])[0])==null?void 0:pe.placement;if(!Ie)switch(T){case"bestFit":{var Le;const Te=(Le=ie.filter(ge=>{if(W){const $e=Xp(ge.placement);return $e===O||$e==="y"}return!0}).map(ge=>[ge.placement,ge.overflows.filter($e=>$e>0).reduce(($e,we)=>$e+we,0)]).sort((ge,$e)=>ge[1]-$e[1])[0])==null?void 0:Le[0];Te&&(Ie=Te);break}case"initialPlacement":Ie=d;break}if(i!==Ie)return{reset:{placement:Ie}}}return{}}}};function fae(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function mae(t){return n$e.some(e=>t[e]>=0)}const y$e=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:r,platform:n}=e,{strategy:i="referenceHidden",...a}=Gy(t,e);switch(i){case"referenceHidden":{const c=await n.detectOverflow(e,{...a,elementContext:"reference"}),d=fae(c,r.reference);return{data:{referenceHiddenOffsets:d,referenceHidden:mae(d)}}}case"escaped":{const c=await n.detectOverflow(e,{...a,altBoundary:!0}),d=fae(c,r.floating);return{data:{escapedOffsets:d,escaped:mae(d)}}}default:return{}}}}},i0e=new Set(["left","top"]);async function x$e(t,e){const{placement:r,platform:n,elements:i}=t,a=await(n.isRTL==null?void 0:n.isRTL(i.floating)),c=vv(r),d=cA(r),p=Xp(r)==="y",l=i0e.has(c)?-1:1,g=a&&p?-1:1,v=Gy(e,t);let{mainAxis:E,crossAxis:T,alignmentAxis:j}=typeof v=="number"?{mainAxis:v,crossAxis:0,alignmentAxis:null}:{mainAxis:v.mainAxis||0,crossAxis:v.crossAxis||0,alignmentAxis:v.alignmentAxis};return d&&typeof j=="number"&&(T=d==="end"?j*-1:j),p?{x:T*g,y:E*l}:{x:E*l,y:T*g}}const _$e=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var r,n;const{x:i,y:a,placement:c,middlewareData:d}=e,p=await x$e(e,t);return c===((r=d.offset)==null?void 0:r.placement)&&(n=d.arrow)!=null&&n.alignmentOffset?{}:{x:i+p.x,y:a+p.y,data:{...p,placement:c}}}}},v$e=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:r,y:n,placement:i,platform:a}=e,{mainAxis:c=!0,crossAxis:d=!1,limiter:p={fn:O=>{let{x:F,y:$}=O;return{x:F,y:$}}},...l}=Gy(t,e),g={x:r,y:n},v=await a.detectOverflow(e,l),E=Xp(i),T=pK(E);let j=g[T],P=g[E];const C=(O,F)=>r0e(F+v[O==="y"?"top":"left"],F,F-v[O==="y"?"bottom":"right"]);c&&(j=C(T,j)),d&&(P=C(E,P));const L=p.fn({...e,[T]:j,[E]:P});return{...L,data:{x:L.x-r,y:L.y-n,enabled:{[T]:c,[E]:d}}}}}},b$e=function(t){return t===void 0&&(t={}),{options:t,fn(e){var r,n;const{x:i,y:a,placement:c,rects:d,middlewareData:p}=e,{offset:l=0,mainAxis:g=!0,crossAxis:v=!0}=Gy(t,e),E={x:i,y:a},T=Xp(c),j=pK(T);let P=E[j],C=E[T];const L=Gy(l,e),O=typeof L=="number"?{mainAxis:L,crossAxis:0}:{mainAxis:(r=L.mainAxis)!=null?r:0,crossAxis:(n=L.crossAxis)!=null?n:0};if(g){const G=j==="y"?"height":"width",W=d.reference[j]-d.floating[G]+O.mainAxis,Z=d.reference[j]+d.reference[G]-O.mainAxis;PZ&&(P=Z)}if(v){var F,$;const G=j==="y"?"width":"height",W=i0e.has(vv(c)),Z=d.reference[T]-d.floating[G]+(W&&((F=p.offset)==null?void 0:F[T])||0)+(W?0:O.crossAxis),Q=d.reference[T]+d.reference[G]+(W?0:(($=p.offset)==null?void 0:$[T])||0)-(W?O.crossAxis:0);CQ&&(C=Q)}return{[j]:P,[T]:C}}}},w$e=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){const{placement:r,rects:n,platform:i,elements:a}=e,{apply:c=()=>{},...d}=Gy(t,e),p=await i.detectOverflow(e,d),l=vv(r),g=cA(r),v=Xp(r)==="y",{width:E,height:T}=n.floating;let j,P;l==="top"||l==="bottom"?(j=l,P=g===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(P=l,j=g==="end"?"top":"bottom");const C=T-p.top-p.bottom,L=E-p.left-p.right,O=_v(T-p[j],C),F=_v(E-p[P],L),$=e.middlewareData.shift,G=!$;let W=O,Z=F;$!=null&&$.enabled.x&&(Z=L),$!=null&&$.enabled.y&&(W=C),G&&!g&&(v?Z=E-2*Ny(p.left,p.right):W=T-2*Ny(p.top,p.bottom)),await c({...e,availableWidth:Z,availableHeight:W});const Q=await i.getDimensions(a.floating);return E!==Q.width||T!==Q.height?{reset:{rects:!0}}:{}}}};function F4(){return typeof window<"u"}function uA(t){return s0e(t)?(t.nodeName||"").toLowerCase():"#document"}function mh(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function ix(t){var e;return(e=(s0e(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function s0e(t){return F4()?t instanceof Node||t instanceof mh(t).Node:!1}function dg(t){return F4()?t instanceof Element||t instanceof mh(t).Element:!1}function Fv(t){return F4()?t instanceof HTMLElement||t instanceof mh(t).HTMLElement:!1}function pae(t){return!F4()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof mh(t).ShadowRoot}function B4(t){const{overflow:e,overflowX:r,overflowY:n,display:i}=hg(t);return/auto|scroll|overlay|hidden|clip/.test(e+n+r)&&i!=="inline"&&i!=="contents"}function S$e(t){return/^(table|td|th)$/.test(uA(t))}function z4(t){try{if(t.matches(":popover-open"))return!0}catch{}try{return t.matches(":modal")}catch{return!1}}const E$e=/transform|translate|scale|rotate|perspective|filter/,T$e=/paint|layout|strict|content/,tb=t=>!!t&&t!=="none";let Z6;function xK(t){const e=dg(t)?hg(t):t;return tb(e.transform)||tb(e.translate)||tb(e.scale)||tb(e.rotate)||tb(e.perspective)||!_K()&&(tb(e.backdropFilter)||tb(e.filter))||E$e.test(e.willChange||"")||T$e.test(e.contain||"")}function A$e(t){let e=sw(t);for(;Fv(e)&&!Zj(e);){if(xK(e))return e;if(z4(e))return null;e=sw(e)}return null}function _K(){return Z6==null&&(Z6=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Z6}function Zj(t){return/^(html|body|#document)$/.test(uA(t))}function hg(t){return mh(t).getComputedStyle(t)}function $4(t){return dg(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function sw(t){if(uA(t)==="html")return t;const e=t.assignedSlot||t.parentNode||pae(t)&&t.host||ix(t);return pae(e)?e.host:e}function a0e(t){const e=sw(t);return Zj(e)?(t.ownerDocument||t).body:Fv(e)&&B4(e)?e:a0e(e)}function Xj(t,e,r){var n;e===void 0&&(e=[]),r===void 0&&(r=!0);const i=a0e(t),a=i===((n=t.ownerDocument)==null?void 0:n.body),c=mh(i);if(a){const d=Vq(c);return e.concat(c,c.visualViewport||[],B4(i)?i:[],d&&r?Xj(d):[])}else return e.concat(i,Xj(i,[],r))}function Vq(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function o0e(t){const e=hg(t);let r=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const i=Fv(t),a=i?t.offsetWidth:r,c=i?t.offsetHeight:n,d=lF(r)!==a||lF(n)!==c;return d&&(r=a,n=c),{width:r,height:n,$:d}}function vK(t){return dg(t)?t:t.contextElement}function wE(t){const e=vK(t);if(!Fv(e))return Ry(1);const r=e.getBoundingClientRect(),{width:n,height:i,$:a}=o0e(e);let c=(a?lF(r.width):r.width)/n,d=(a?lF(r.height):r.height)/i;return(!c||!Number.isFinite(c))&&(c=1),(!d||!Number.isFinite(d))&&(d=1),{x:c,y:d}}const k$e=Ry(0);function l0e(t){const e=mh(t);return!_K()||!e.visualViewport?k$e:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function I$e(t,e,r){return e===void 0&&(e=!1),!!r&&e&&r===mh(t)}function aw(t,e,r,n){e===void 0&&(e=!1),r===void 0&&(r=!1);const i=t.getBoundingClientRect(),a=vK(t);let c=Ry(1);e&&(n?dg(n)&&(c=wE(n)):c=wE(t));const d=I$e(a,r,n)?l0e(a):Ry(0);let p=(i.left+d.x)/c.x,l=(i.top+d.y)/c.y,g=i.width/c.x,v=i.height/c.y;if(a&&n){const E=mh(a),T=dg(n)?mh(n):n;let j=E,P=Vq(j);for(;P&&T!==j;){const C=wE(P),L=P.getBoundingClientRect(),O=hg(P),F=L.left+(P.clientLeft+parseFloat(O.paddingLeft))*C.x,$=L.top+(P.clientTop+parseFloat(O.paddingTop))*C.y;p*=C.x,l*=C.y,g*=C.x,v*=C.y,p+=F,l+=$,j=mh(P),P=Vq(j)}}return uF({width:g,height:v,x:p,y:l})}function U4(t,e){const r=$4(t).scrollLeft;return e?e.left+r:aw(ix(t)).left+r}function c0e(t,e){const r=t.getBoundingClientRect(),n=r.left+e.scrollLeft-U4(t,r),i=r.top+e.scrollTop;return{x:n,y:i}}function j$e(t){let{elements:e,rect:r,offsetParent:n,strategy:i}=t;const a=i==="fixed",c=ix(n),d=e?z4(e.floating):!1;if(n===c||d&&a)return r;let p={scrollLeft:0,scrollTop:0},l=Ry(1);const g=Ry(0),v=Fv(n);if((v||!a)&&((uA(n)!=="body"||B4(c))&&(p=$4(n)),v)){const T=aw(n);l=wE(n),g.x=T.x+n.clientLeft,g.y=T.y+n.clientTop}const E=c&&!v&&!a?c0e(c,p):Ry(0);return{width:r.width*l.x,height:r.height*l.y,x:r.x*l.x-p.scrollLeft*l.x+g.x+E.x,y:r.y*l.y-p.scrollTop*l.y+g.y+E.y}}function C$e(t){return t.getClientRects?Array.from(t.getClientRects()):[]}function P$e(t){const e=$4(t),r=t.ownerDocument.body,n=Ny(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=Ny(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let a=-e.scrollLeft+U4(t);const c=-e.scrollTop;return hg(r).direction==="rtl"&&(a+=Ny(t.clientWidth,r.clientWidth)-n),{width:n,height:i,x:a,y:c}}const N$e=25;function R$e(t,e,r){r===void 0&&(r="viewport");const n=r==="layoutViewport",i=mh(t),a=ix(t),c=i.visualViewport;let d=a.clientWidth,p=a.clientHeight,l=0,g=0;if(c){const E=!_K()||e==="fixed";n?E||(l=-c.offsetLeft,g=-c.offsetTop):(d=c.width,p=c.height,E&&(l=c.offsetLeft,g=c.offsetTop))}if(U4(a)<=0){const E=a.ownerDocument,T=E.body,j=getComputedStyle(T),P=E.compatMode==="CSS1Compat"&&parseFloat(j.marginLeft)+parseFloat(j.marginRight)||0,C=Math.abs(a.clientWidth-T.clientWidth-P),L=getComputedStyle(a).scrollbarGutter==="stable both-edges"?C/2:C;L<=N$e&&(d-=L)}return{width:d,height:p,x:l,y:g}}function L$e(t,e){const r=aw(t,!0,e==="fixed"),n=r.top+t.clientTop,i=r.left+t.clientLeft,a=wE(t),c=t.clientWidth*a.x,d=t.clientHeight*a.y,p=i*a.x,l=n*a.y;return{width:c,height:d,x:p,y:l}}function gae(t,e,r){let n;if(e==="viewport"||e==="layoutViewport")n=R$e(t,r,e);else if(e==="document")n=P$e(ix(t));else if(dg(e))n=L$e(e,r);else{const i=l0e(t);n={x:e.x-i.x,y:e.y-i.y,width:e.width,height:e.height}}return uF(n)}function D$e(t,e){const r=e.get(t);if(r)return r;let n=Xj(t,[],!1).filter(d=>dg(d)&&uA(d)!=="body"),i=null;const a=hg(t).position==="fixed";let c=a?sw(t):t;for(;dg(c)&&!Zj(c);){const d=hg(c),p=xK(c),l=i?i.position:a?"fixed":"";!p&&(l==="fixed"||l==="absolute"&&d.position==="static")?n=n.filter(v=>v!==c):i=d,c=sw(c)}return e.set(t,n),n}function M$e(t){let{element:e,boundary:r,rootBoundary:n,strategy:i}=t;const c=[...r==="clippingAncestors"?z4(e)?[]:D$e(e,this._c):[].concat(r),n],d=gae(e,c[0],i);let p=d.top,l=d.right,g=d.bottom,v=d.left;for(let E=1;E{d(!1,1e-7)},1e3)}Z=!1}try{n=new IntersectionObserver(Q,{...W,root:a.ownerDocument})}catch{n=new IntersectionObserver(Q,W)}n.observe(t)}const p=mh(t),l=()=>d(r);return p.addEventListener("resize",l),d(!0),()=>{p.removeEventListener("resize",l),c()}}function V$e(t,e,r,n){n===void 0&&(n={});const{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:c=typeof ResizeObserver=="function",layoutShift:d=typeof IntersectionObserver=="function",animationFrame:p=!1}=n,l=vK(t),g=i||a?[...l?Xj(l):[],...e?Xj(e):[]]:[];g.forEach(L=>{i&&L.addEventListener("scroll",r),a&&L.addEventListener("resize",r)});const v=l&&d?U$e(l,r,a):null;let E=-1,T=null;c&&(T=new ResizeObserver(L=>{let[O]=L;O&&O.target===l&&T&&e&&(T.unobserve(e),cancelAnimationFrame(E),E=requestAnimationFrame(()=>{var F;(F=T)==null||F.observe(e)})),r()}),l&&!p&&T.observe(l),e&&T.observe(e));let j,P=p?aw(t):null;p&&C();function C(){const L=aw(t);P&&!d0e(P,L)&&r(),P=L,j=requestAnimationFrame(C)}return r(),()=>{var L;g.forEach(O=>{i&&O.removeEventListener("scroll",r),a&&O.removeEventListener("resize",r)}),v==null||v(),(L=T)==null||L.disconnect(),T=null,p&&cancelAnimationFrame(j)}}const q$e=_$e,G$e=v$e,H$e=g$e,W$e=w$e,K$e=y$e,xae=p$e,Y$e=b$e,Z$e=(t,e,r)=>{const n=new Map,i=r??{},a={...$$e,...i.platform,_c:n};return m$e(t,e,{...i,platform:a})};var X$e=typeof document<"u",Q$e=function(){},YM=X$e?N.useLayoutEffect:Q$e;function dF(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let r,n,i;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(r=t.length,r!==e.length)return!1;for(n=r;n--!==0;)if(!dF(t[n],e[n]))return!1;return!0}if(i=Object.keys(t),r=i.length,r!==Object.keys(e).length)return!1;for(n=r;n--!==0;)if(!{}.hasOwnProperty.call(e,i[n]))return!1;for(n=r;n--!==0;){const a=i[n];if(!(a==="_owner"&&t.$$typeof)&&!dF(t[a],e[a]))return!1}return!0}return t!==t&&e!==e}function h0e(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function _ae(t,e){const r=h0e(t);return Math.round(e*r)/r}function Q6(t){const e=N.useRef(t);return YM(()=>{e.current=t}),e}function J$e(t){t===void 0&&(t={});const{placement:e="bottom",strategy:r="absolute",middleware:n=[],platform:i,elements:{reference:a,floating:c}={},transform:d=!0,whileElementsMounted:p,open:l}=t,[g,v]=N.useState({x:0,y:0,strategy:r,placement:e,middlewareData:{},isPositioned:!1}),[E,T]=N.useState(n);dF(E,n)||T(n);const[j,P]=N.useState(null),[C,L]=N.useState(null),O=N.useCallback(ge=>{ge!==W.current&&(W.current=ge,P(ge))},[]),F=N.useCallback(ge=>{ge!==Z.current&&(Z.current=ge,L(ge))},[]),$=a||j,G=c||C,W=N.useRef(null),Z=N.useRef(null),Q=N.useRef(g),ee=p!=null,ie=Q6(p),oe=Q6(i),pe=Q6(l),Le=N.useCallback(()=>{if(!W.current||!Z.current)return;const ge={placement:e,strategy:r,middleware:E};oe.current&&(ge.platform=oe.current),Z$e(W.current,Z.current,ge).then($e=>{const we={...$e,isPositioned:pe.current!==!1};be.current&&!dF(Q.current,we)&&(Q.current=we,vg.flushSync(()=>{v(we)}))})},[E,e,r,oe,pe]);YM(()=>{l===!1&&Q.current.isPositioned&&(Q.current.isPositioned=!1,v(ge=>({...ge,isPositioned:!1})))},[l]);const be=N.useRef(!1);YM(()=>(be.current=!0,()=>{be.current=!1}),[]),YM(()=>{if($&&(W.current=$),G&&(Z.current=G),$&&G){if(ie.current)return ie.current($,G,Le);Le()}},[$,G,Le,ie,ee]);const Re=N.useMemo(()=>({reference:W,floating:Z,setReference:O,setFloating:F}),[O,F]),Ie=N.useMemo(()=>({reference:$,floating:G}),[$,G]),Te=N.useMemo(()=>{const ge={position:r,left:0,top:0};if(!Ie.floating)return ge;const $e=_ae(Ie.floating,g.x),we=_ae(Ie.floating,g.y);return d?{...ge,transform:"translate("+$e+"px, "+we+"px)",...h0e(Ie.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:$e,top:we}},[r,d,Ie.floating,g.x,g.y]);return N.useMemo(()=>({...g,update:Le,refs:Re,elements:Ie,floatingStyles:Te}),[g,Le,Re,Ie,Te])}const e6e=t=>{function e(r){return{}.hasOwnProperty.call(r,"current")}return{name:"arrow",options:t,fn(r){const{element:n,padding:i}=typeof t=="function"?t(r):t;return n&&e(n)?n.current!=null?xae({element:n.current,padding:i}).fn(r):{}:n?xae({element:n,padding:i}).fn(r):{}}}},t6e=(t,e)=>{const r=q$e(t);return{name:r.name,fn:r.fn,options:[t,e]}},r6e=(t,e)=>{const r=G$e(t);return{name:r.name,fn:r.fn,options:[t,e]}},n6e=(t,e)=>({fn:Y$e(t).fn,options:[t,e]}),i6e=(t,e)=>{const r=H$e(t);return{name:r.name,fn:r.fn,options:[t,e]}},s6e=(t,e)=>{const r=W$e(t);return{name:r.name,fn:r.fn,options:[t,e]}},a6e=(t,e)=>{const r=K$e(t);return{name:r.name,fn:r.fn,options:[t,e]}},o6e=(t,e)=>{const r=e6e(t);return{name:r.name,fn:r.fn,options:[t,e]}};var l6e=Object.defineProperty,c6e=(t,e)=>l6e(t,"name",{value:e,configurable:!0});function dA(t){const[e,r]=N.useState(void 0);return no(()=>{if(t){r({width:t.offsetWidth,height:t.offsetHeight});let n=0;const i=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const c=a[0];window.cancelAnimationFrame(n),n=window.requestAnimationFrame(()=>{let d,p;if("borderBoxSize"in c){const l=c.borderBoxSize,g=Array.isArray(l)?l[0]:l;d=g.inlineSize,p=g.blockSize}else d=t.offsetWidth,p=t.offsetHeight;r({width:d,height:p})})});return i.observe(t,{box:"border-box"}),()=>{window.cancelAnimationFrame(n),i.unobserve(t)}}else r(void 0)},[t]),e}c6e(dA,"useSize");var u6e=Object.defineProperty,lv=(t,e)=>u6e(t,"name",{value:e,configurable:!0}),vae={Partial:"partial"},bae={Optimized:"optimized",Always:"always"},f0e="Popper",[m0e,Bv]=Nl(f0e),[d6e,p0e]=m0e(f0e),V4=lv(t=>{const{__scopePopper:e,children:r}=t,[n,i]=N.useState(null),[a,c]=N.useState(void 0);return s.jsx(d6e,{scope:e,anchor:n,onAnchorChange:i,placementState:a,setPlacementState:c,children:r})},"Popper"),h6e="PopperAnchor",q4=N.forwardRef(lv(function(e,r){const{__scopePopper:n,virtualRef:i,...a}=e,c=p0e(h6e,n),d=N.useRef(null),p=c.onAnchorChange,l=N.useCallback(P=>{d.current=P,P&&p(P)},[p]),g=Jn(r,l),v=N.useRef(null);N.useEffect(()=>{if(!i)return;const P=v.current;v.current=i.current,P!==v.current&&p(v.current)});const E=c.placementState&&H4(c.placementState),T=E==null?void 0:E[0],j=E==null?void 0:E[1];return i?null:s.jsx(An.div,{"data-radix-popper-side":T,"data-radix-popper-align":j,...a,ref:g})},"PopperAnchor")),g0e="PopperContent",[f6e,$Wt]=m0e(g0e),G4=N.forwardRef(lv(function(e,r){var Ct,Bt,cr,ft,Kt,ir,Gr;const{__scopePopper:n,side:i="bottom",sideOffset:a=0,align:c="center",alignOffset:d=0,arrowPadding:p=0,avoidCollisions:l=!0,collisionBoundary:g=[],collisionPadding:v=0,sticky:E=vae.Partial,hideWhenDetached:T=!1,updatePositionStrategy:j=bae.Optimized,onPlaced:P,...C}=e,L=p0e(g0e,n),[O,F]=N.useState(null),$=Jn(r,F),[G,W]=N.useState(null),Z=dA(G),Q=(Z==null?void 0:Z.width)??0,ee=(Z==null?void 0:Z.height)??0,ie=i+(c!=="center"?"-"+c:""),oe=typeof v=="number"?v:{top:0,right:0,bottom:0,left:0,...v},pe=Array.isArray(g)?g:[g],Le=pe.length>0,be={padding:oe,boundary:pe.filter(y0e),altBoundary:Le},{refs:Re,floatingStyles:Ie,placement:Te,isPositioned:ge,middlewareData:$e}=J$e({strategy:"fixed",placement:ie,whileElementsMounted:lv((...tr)=>V$e(...tr,{animationFrame:j===bae.Always}),"whileElementsMounted"),elements:{reference:L.anchor},middleware:[t6e({mainAxis:a+ee,alignmentAxis:d}),l&&r6e({mainAxis:!0,crossAxis:!1,...E===vae.Partial?{limiter:n6e()}:{},...be}),l&&i6e({...be}),s6e({...be,apply:lv(({elements:tr,rects:Qt,availableWidth:zt,availableHeight:Vr})=>{const{width:Jr,height:Fn}=Qt.reference,Ar=tr.floating.style;Ar.setProperty("--radix-popper-available-width",`${zt}px`),Ar.setProperty("--radix-popper-available-height",`${Vr}px`),Ar.setProperty("--radix-popper-anchor-width",`${Jr}px`),Ar.setProperty("--radix-popper-anchor-height",`${Fn}px`)},"apply")}),G&&o6e({element:G,padding:p}),m6e({arrowWidth:Q,arrowHeight:ee}),T&&a6e(Le?{strategy:"referenceHidden",...be}:{strategy:"referenceHidden",padding:be.padding,altBoundary:be.altBoundary})]}),we=L.setPlacementState;no(()=>(we(Te),()=>{we(void 0)}),[Te,we]);const[ke,Ae]=H4(Te),He=Yo(P);no(()=>{ge&&(He==null||He())},[ge,He]);const ot=(Ct=$e.arrow)==null?void 0:Ct.x,nt=(Bt=$e.arrow)==null?void 0:Bt.y,tt=((cr=$e.arrow)==null?void 0:cr.centerOffset)!==0,[vt,Vt]=N.useState();return no(()=>{O&&Vt(window.getComputedStyle(O).zIndex)},[O]),s.jsx("div",{ref:Re.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ie,transform:ge?Ie.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:vt,"--radix-popper-transform-origin":[(ft=$e.transformOrigin)==null?void 0:ft.x,(Kt=$e.transformOrigin)==null?void 0:Kt.y].join(" "),...((ir=$e.hide)==null?void 0:ir.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:s.jsx(f6e,{scope:n,placedSide:ke,placedAlign:Ae,onArrowChange:W,arrowX:ot,arrowY:nt,shouldHideArrow:tt,children:s.jsx(An.div,{"data-side":ke,"data-align":Ae,...C,ref:$,style:{...C.style,animation:ge?(Gr=C.style)==null?void 0:Gr.animation:"none"}})})})},"PopperContent"));function y0e(t){return t!==null}lv(y0e,"isNotNull");var m6e=lv(t=>({name:"transformOrigin",options:t,fn(e){var C,L,O;const{placement:r,rects:n,middlewareData:i}=e,c=((C=i.arrow)==null?void 0:C.centerOffset)!==0,d=c?0:t.arrowWidth,p=c?0:t.arrowHeight,[l,g]=H4(r),v={start:"0%",center:"50%",end:"100%"}[g],E=(((L=i.arrow)==null?void 0:L.x)??0)+d/2,T=(((O=i.arrow)==null?void 0:O.y)??0)+p/2;let j="",P="";return l==="bottom"?(j=c?v:`${E}px`,P=`${-p}px`):l==="top"?(j=c?v:`${E}px`,P=`${n.floating.height+p}px`):l==="right"?(j=`${-p}px`,P=c?v:`${T}px`):l==="left"&&(j=`${n.floating.width+p}px`,P=c?v:`${T}px`),{data:{x:j,y:P}}}}),"transformOrigin");function H4(t){const[e,r="center"]=t.split("-");return[e,r]}lv(H4,"getSideAndAlignFromPlacement");var p6e=Object.defineProperty,au=(t,e)=>p6e(t,"name",{value:e,configurable:!0}),[bK,UWt]=Nl("Tooltip",[Bv]),wK=Bv(),g6e="TooltipProvider",y6e=700,qq="tooltip.open",[x6e,SK]=bK(g6e),_6e=au(t=>{const{__scopeTooltip:e,delayDuration:r=y6e,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:a}=t,c=N.useRef(!0),d=N.useRef(!1),p=N.useRef(0);return N.useEffect(()=>{const l=p.current;return()=>window.clearTimeout(l)},[]),s.jsx(x6e,{scope:e,isOpenDelayedRef:c,delayDuration:r,onOpen:N.useCallback(()=>{n<=0||(window.clearTimeout(p.current),c.current=!1)},[n]),onClose:N.useCallback(()=>{n<=0||(window.clearTimeout(p.current),p.current=window.setTimeout(()=>c.current=!0,n))},[n]),isPointerInTransitRef:d,onPointerInTransitChange:N.useCallback(l=>{d.current=l},[]),disableHoverableContent:i,children:a})},"TooltipProvider"),Gq="Tooltip",[v6e,W4]=bK(Gq),b6e=au(t=>{const{__scopeTooltip:e,children:r,open:n,defaultOpen:i,onOpenChange:a,disableHoverableContent:c,delayDuration:d}=t,p=SK(Gq,t.__scopeTooltip),l=wK(e),[g,v]=N.useState(null),[E,T]=N.useState(void 0),j=Wl(),P=N.useRef(0),C=c??p.disableHoverableContent,L=d??p.delayDuration,O=N.useRef(!1),[F,$]=ph({prop:n,defaultProp:i??!1,onChange:au(ie=>{ie?(p.onOpen(),document.dispatchEvent(new CustomEvent(qq))):p.onClose(),a==null||a(ie)},"onChange"),caller:Gq}),G=N.useMemo(()=>F?O.current?"delayed-open":"instant-open":"closed",[F]),W=N.useCallback(()=>{window.clearTimeout(P.current),P.current=0,O.current=!1,$(!0)},[$]),Z=N.useCallback(()=>{window.clearTimeout(P.current),P.current=0,$(!1)},[$]),Q=N.useCallback(()=>{window.clearTimeout(P.current),P.current=window.setTimeout(()=>{O.current=!0,$(!0),P.current=0},L)},[L,$]);N.useEffect(()=>()=>{P.current&&(window.clearTimeout(P.current),P.current=0)},[]);const ee=E??j;return s.jsx(V4,{...l,children:s.jsx(v6e,{scope:e,contentId:ee,setContentId:T,open:F,stateAttribute:G,trigger:g,onTriggerChange:v,onTriggerEnter:N.useCallback(()=>{p.isOpenDelayedRef.current?Q():W()},[p.isOpenDelayedRef,Q,W]),onTriggerLeave:N.useCallback(()=>{C?Z():(window.clearTimeout(P.current),P.current=0)},[Z,C]),onOpen:W,onClose:Z,disableHoverableContent:C,children:r})})},"Tooltip"),wae="TooltipTrigger",w6e=N.forwardRef(au(function(e,r){const{__scopeTooltip:n,"aria-describedby":i,...a}=e,c=W4(wae,n),d=SK(wae,n),p=wK(n),l=N.useRef(null),g=Jn(r,l,c.onTriggerChange),v=N.useRef(!1),E=N.useRef(!1),T=N.useCallback(()=>v.current=!1,[]);return N.useEffect(()=>()=>document.removeEventListener("pointerup",T),[T]),s.jsx(q4,{asChild:!0,...p,children:s.jsx(An.button,{"aria-describedby":c.open?A0e(i,c.contentId):i,"data-state":c.stateAttribute,...a,ref:g,onPointerMove:Qr(e.onPointerMove,j=>{j.pointerType!=="touch"&&!E.current&&!d.isPointerInTransitRef.current&&(c.onTriggerEnter(),E.current=!0)}),onPointerLeave:Qr(e.onPointerLeave,()=>{c.onTriggerLeave(),E.current=!1}),onPointerDown:Qr(e.onPointerDown,()=>{c.open&&c.onClose(),v.current=!0,document.addEventListener("pointerup",T,{once:!0})}),onFocus:Qr(e.onFocus,()=>{v.current||c.onOpen()}),onBlur:Qr(e.onBlur,c.onClose),onClick:Qr(e.onClick,c.onClose)})})},"TooltipTrigger")),S6e="TooltipPortal",[VWt,E6e]=bK(S6e,{forceMount:void 0}),Qj="TooltipContent",x0e=N.forwardRef(au(function(e,r){const n=E6e(Qj,e.__scopeTooltip),{forceMount:i=n.forceMount,side:a="top",...c}=e,d=W4(Qj,e.__scopeTooltip);return s.jsx(zc,{present:i||d.open,children:d.disableHoverableContent?s.jsx(_0e,{side:a,...c,ref:r}):s.jsx(T6e,{side:a,...c,ref:r})})},"TooltipContent")),T6e=N.forwardRef(au(function(e,r){const n=W4(Qj,e.__scopeTooltip),i=SK(Qj,e.__scopeTooltip),a=N.useRef(null),c=Jn(r,a),[d,p]=N.useState(null),{trigger:l,onClose:g}=n,v=a.current,{onPointerInTransitChange:E}=i,T=N.useCallback(()=>{p(null),E(!1)},[E]),j=N.useCallback((P,C)=>{const L=P.currentTarget,O={x:P.clientX,y:P.clientY},F=v0e(O,L.getBoundingClientRect()),$=b0e(O,F),G=w0e(C.getBoundingClientRect()),W=E0e([...$,...G]);p(W),E(!0)},[E]);return N.useEffect(()=>()=>T(),[T]),N.useEffect(()=>{if(l&&v){const P=au(L=>j(L,v),"handleTriggerLeave"),C=au(L=>j(L,l),"handleContentLeave");return l.addEventListener("pointerleave",P),v.addEventListener("pointerleave",C),()=>{l.removeEventListener("pointerleave",P),v.removeEventListener("pointerleave",C)}}},[l,v,j,T]),N.useEffect(()=>{if(d){const P=au(C=>{const L=C.target,O={x:C.clientX,y:C.clientY},F=(l==null?void 0:l.contains(L))||(v==null?void 0:v.contains(L)),$=!S0e(O,d);F?T():$&&(T(),g())},"handleTrackPointerGrace");return document.addEventListener("pointermove",P),()=>document.removeEventListener("pointermove",P)}},[l,v,d,g,T]),s.jsx(_0e,{...e,ref:c})},"TooltipContentHoverable")),A6e=BW("TooltipContent"),_0e=N.forwardRef(au(function(e,r){const{__scopeTooltip:n,children:i,"aria-label":a,id:c,onEscapeKeyDown:d,onPointerDownOutside:p,...l}=e,g=W4(Qj,n),v=wK(n),{onClose:E}=g,[T,j]=N.useState(null),P=Jn(r,j);N4(T),N.useEffect(()=>(document.addEventListener(qq,E),()=>document.removeEventListener(qq,E)),[E]),N.useEffect(()=>{if(g.trigger){const L=au(O=>{O.target instanceof Node&&O.target.contains(g.trigger)&&E()},"handleScroll");return window.addEventListener("scroll",L,{capture:!0}),()=>window.removeEventListener("scroll",L,{capture:!0})}},[g.trigger,E]);const{setContentId:C}=g;return no(()=>(C(c),()=>{C(void 0)}),[c,C]),s.jsx(JT,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:d,onPointerDownOutside:p,onFocusOutside:L=>L.preventDefault(),onDismiss:E,children:s.jsxs(G4,{"data-state":g.stateAttribute,role:a?void 0:"tooltip",id:a?void 0:g.contentId,...v,...l,ref:P,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[s.jsx(A6e,{children:i}),a?s.jsx(qW,{id:g.contentId,role:"tooltip",children:a}):null]})})},"TooltipContentImpl"));function v0e(t,e){const r=Math.abs(e.top-t.y),n=Math.abs(e.bottom-t.y),i=Math.abs(e.right-t.x),a=Math.abs(e.left-t.x);switch(Math.min(r,n,i,a)){case a:return"left";case i:return"right";case r:return"top";case n:return"bottom";default:throw new Error("unreachable")}}au(v0e,"getExitSideFromRect");function b0e(t,e,r=5){const n=[];switch(e){case"top":n.push({x:t.x-r,y:t.y+r},{x:t.x+r,y:t.y+r});break;case"bottom":n.push({x:t.x-r,y:t.y-r},{x:t.x+r,y:t.y-r});break;case"left":n.push({x:t.x+r,y:t.y-r},{x:t.x+r,y:t.y+r});break;case"right":n.push({x:t.x-r,y:t.y-r},{x:t.x-r,y:t.y+r});break}return n}au(b0e,"getPaddedExitPoints");function w0e(t){const{top:e,right:r,bottom:n,left:i}=t;return[{x:i,y:e},{x:r,y:e},{x:r,y:n},{x:i,y:n}]}au(w0e,"getPointsFromRect");function S0e(t,e){const{x:r,y:n}=t;let i=!1;for(let a=0,c=e.length-1;an!=E>n&&r<(v-l)*(n-g)/(E-g)+l&&(i=!i)}return i}au(S0e,"isPointInPolygon");function E0e(t){const e=t.slice();return e.sort((r,n)=>r.xn.x?1:r.yn.y?1:0),T0e(e)}au(E0e,"getHull");function T0e(t){if(t.length<=1)return t.slice();const e=[];for(let n=0;n=2;){const a=e[e.length-1],c=e[e.length-2];if((a.x-c.x)*(i.y-c.y)>=(a.y-c.y)*(i.x-c.x))e.pop();else break}e.push(i)}e.pop();const r=[];for(let n=t.length-1;n>=0;n--){const i=t[n];for(;r.length>=2;){const a=r[r.length-1],c=r[r.length-2];if((a.x-c.x)*(i.y-c.y)>=(a.y-c.y)*(i.x-c.x))r.pop();else break}r.push(i)}return r.pop(),e.length===1&&r.length===1&&e[0].x===r[0].x&&e[0].y===r[0].y?e:e.concat(r)}au(T0e,"getHullPresorted");function A0e(...t){const e=new Set;for(const r of t)if(typeof r=="string")for(const n of String(r).trim().split(/\s+/))n&&e.add(n);return e.size>0?Array.from(e).join(" "):void 0}au(A0e,"concatAriaDescribedby");const k0e=_6e,k6e=b6e,I6e=w6e,I0e=N.forwardRef(({className:t,sideOffset:e=4,...r},n)=>s.jsx(x0e,{ref:n,sideOffset:e,className:hr("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r}));I0e.displayName=x0e.displayName;const j0e=N.createContext(void 0),Ur=t=>{const e=N.useContext(j0e);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},j6e=({client:t,children:e})=>(N.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),s.jsx(j0e.Provider,{value:t,children:e})),C6e={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t),setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)};var B_,VH,Oge,P6e=(Oge=class{constructor(){hi(this,B_,C6e);hi(this,VH,!1)}setTimeoutProvider(t){In(this,B_,t)}setTimeout(t,e){return Nt(this,B_).setTimeout(t,e)}clearTimeout(t){Nt(this,B_).clearTimeout(t)}setInterval(t,e){return Nt(this,B_).setInterval(t,e)}clearInterval(t){Nt(this,B_).clearInterval(t)}},B_=new WeakMap,VH=new WeakMap,Oge);const Ab=new P6e;function N6e(t){setTimeout(t,0)}const R6e=typeof window>"u"||"Deno"in globalThis;function Id(){}function L6e(t,e){return typeof t=="function"?t(e):t}function C0e(t){return typeof t=="number"&&t>=0&&t!==1/0}function P0e(t,e){return Math.max(t+(e||0)-Date.now(),0)}function qo(t,e){return typeof t=="function"?t(e):t}function Sae(t,e){const{type:r="all",exact:n,fetchStatus:i,predicate:a,queryKey:c,stale:d}=t;if(c){if(n){if(e.queryHash!==EK(c,e.options))return!1}else if(!iT(e.queryKey,c))return!1}if(r!=="all"){const p=e.isActive();if(r==="active"&&!p||r==="inactive"&&p)return!1}return!(typeof d=="boolean"&&e.isStale()!==d||i&&i!==e.state.fetchStatus||a&&!a(e))}function Eae(t,e){const{exact:r,status:n,predicate:i,mutationKey:a}=t;if(a){if(!e.options.mutationKey)return!1;if(r){if(ow(e.options.mutationKey)!==ow(a))return!1}else if(!iT(e.options.mutationKey,a))return!1}return!(n&&e.state.status!==n||i&&!i(e))}function EK(t,e){return((e==null?void 0:e.queryKeyHashFn)||ow)(t)}function ow(t){return JSON.stringify(t,(e,r)=>Hq(r)?Object.keys(r).sort().reduce((n,i)=>(n[i]=r[i],n),{}):r)}function iT(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){if(e.length>t.length)return!1;for(let n=0;n500)return e;const n=Tae(t)&&Tae(e);if(!n&&!(Hq(t)&&Hq(e)))return e;const i=(n?t:Object.keys(t)).length,a=n?e:Object.keys(e),c=a.length,d=n?new Array(c):{};let p=0;for(let l=0;l{Ab.setTimeout(e,t)})}function Wq(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?N0e(t,e):e}function O6e(t,e,r=0){const n=[...t,e];return r&&n.length>r?n.slice(1):n}function F6e(t,e,r=0){const n=[e,...t];return r&&n.length>r?n.slice(0,-1):n}const TK=Symbol();function R0e(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===TK?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function AK(t,e){return typeof t=="function"?t(...e):!!t}function B6e(t,e,r){let n=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:()=>(i??(i=e()),n||(n=!0,i.aborted?r():i.addEventListener("abort",r,{once:!0})),i)}),t}let z6e=()=>R6e;const kK=()=>z6e();var hA=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Db,z_,LE,Fge,$6e=(Fge=class extends hA{constructor(){super();hi(this,Db);hi(this,z_);hi(this,LE);In(this,LE,e=>{if(typeof window<"u"&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Nt(this,z_)||this.setEventListener(Nt(this,LE))}onUnsubscribe(){var e;this.hasListeners()||((e=Nt(this,z_))==null||e.call(this),In(this,z_,void 0))}setEventListener(e){var r;In(this,LE,e),(r=Nt(this,z_))==null||r.call(this),In(this,z_,e(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(e){Nt(this,Db)!==e&&(In(this,Db,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof Nt(this,Db)=="boolean"?Nt(this,Db):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},Db=new WeakMap,z_=new WeakMap,LE=new WeakMap,Fge);const IK=new $6e,U6e=N6e;function V6e(){let t=[],e=0,r=d=>{d()},n=d=>{d()},i=U6e;const a=d=>{e?t.push(d):i(()=>{r(d)})},c=()=>{const d=t;t=[],d.length&&i(()=>{n(()=>{d.forEach(p=>{r(p)})})})};return{batch:d=>{let p;e++;try{p=d()}finally{e--,e||c()}return p},batchCalls:d=>(...p)=>{a(()=>{d(...p)})},schedule:a,setNotifyFunction:d=>{r=d},setBatchNotifyFunction:d=>{n=d},setScheduler:d=>{i=d}}}const Lc=V6e();var DE,$_,ME,Bge,q6e=(Bge=class extends hA{constructor(){super();hi(this,DE,!0);hi(this,$_);hi(this,ME);In(this,ME,e=>{if(typeof window<"u"&&window.addEventListener){const r=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",r,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",r),window.removeEventListener("offline",n)}}})}onSubscribe(){Nt(this,$_)||this.setEventListener(Nt(this,ME))}onUnsubscribe(){var e;this.hasListeners()||((e=Nt(this,$_))==null||e.call(this),In(this,$_,void 0))}setEventListener(e){var r;In(this,ME,e),(r=Nt(this,$_))==null||r.call(this),In(this,$_,e(this.setOnline.bind(this)))}setOnline(e){Nt(this,DE)!==e&&(In(this,DE,e),this.listeners.forEach(r=>{r(e)}))}isOnline(){return Nt(this,DE)}},DE=new WeakMap,$_=new WeakMap,ME=new WeakMap,Bge);const hF=new q6e;function G6e(t){return Math.min(1e3*2**t,3e4)}function L0e(t){return(t??"online")==="online"?hF.isOnline():!0}var Kq=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function D0e(t){let e=!1,r=0,n,i="pending",a,c;const d=new Promise((O,F)=>{a=O,c=F});d.catch(Id);const p=()=>i!=="pending",l=O=>{var F;if(!p()){const $=new Kq(O);P($),(F=t.onCancel)==null||F.call(t,$)}},g=()=>{e=!0},v=()=>{e=!1},E=()=>IK.isFocused()&&(t.networkMode==="always"||hF.isOnline())&&t.canRun(),T=()=>L0e(t.networkMode)&&t.canRun(),j=O=>{p()||(n==null||n(),i="resolved",a(O))},P=O=>{p()||(n==null||n(),i="rejected",c(O))},C=O=>new Promise(F=>{var $;n=G=>{(p()||O())&&F(G)},($=t.onPause)==null||$.call(t)}).then(()=>{var F;n=void 0,p()||(F=t.onContinue)==null||F.call(t)}),L=()=>{if(p())return;let O;const F=r===0?t.initialPromise:void 0;try{O=F??t.fn()}catch($){O=Promise.reject($)}Promise.resolve(O).then(j).catch($=>{var ee;if(p())return;const G=t.retry??(kK()?0:3),W=t.retryDelay??G6e,Z=typeof W=="function"?W(r,$):W,Q=G===!0||typeof G=="number"&&rE()?void 0:C(E)).then(()=>{e?P($):L()})})};return{promise:d,status:()=>i,cancel:l,continue:()=>(n==null||n(),d),cancelRetry:g,continueRetry:v,canStart:T,start:()=>(T()?L():C(T).then(L),d)}}var Mb,zge,M0e=(zge=class{constructor(){hi(this,Mb)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),C0e(this.gcTime)&&In(this,Mb,Ab.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(kK()?1/0:3e5))}clearGcTimeout(){Nt(this,Mb)!==void 0&&(Ab.clearTimeout(Nt(this,Mb)),In(this,Mb,void 0))}},Mb=new WeakMap,zge);function H6e(t){return{onFetch:(e,r)=>{var g,v,E,T,j;const n=e.options,i=(E=(v=(g=e.fetchOptions)==null?void 0:g.meta)==null?void 0:v.fetchMore)==null?void 0:E.direction,a=((T=e.state.data)==null?void 0:T.pages)||[],c=((j=e.state.data)==null?void 0:j.pageParams)||[];let d={pages:[],pageParams:[]},p=0;const l=async()=>{let P=!1;const C=F=>{B6e(F,()=>e.signal,()=>P=!0)},L=R0e(e.options,e.fetchOptions),O=async(F,$,G)=>{if(P)return Promise.reject(e.signal.reason);if($==null&&F.pages.length)return Promise.resolve(F);const Z=(()=>{const oe={client:e.client,queryKey:e.queryKey,pageParam:$,direction:G?"backward":"forward",meta:e.options.meta};return C(oe),oe})(),Q=await L(Z),{maxPages:ee}=e.options,ie=G?F6e:O6e;return{pages:ie(F.pages,Q,ee),pageParams:ie(F.pageParams,$,ee)}};if(i&&a.length){const F=i==="backward",$=F?O0e:Yq,G={pages:a,pageParams:c};d=await O(G,$(n,G),F)}else{const F=t??a.length;do{const $=p===0?c[0]===void 0?n.initialPageParam:c[0]:Yq(n,d);if(p>0&&$==null)break;d=await O(d,$),p++}while(p{var P,C;return(C=(P=e.options).persister)==null?void 0:C.call(P,l,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=l}}}function Yq(t,{pages:e,pageParams:r}){const n=e.length-1;return e.length>0?t.getNextPageParam(e[n],e,r[n],r):void 0}function O0e(t,{pages:e,pageParams:r}){var n;return e.length>0?(n=t.getPreviousPageParam)==null?void 0:n.call(t,e[0],e,r[0],r):void 0}function qWt(t,e){return e?Yq(t,e)!=null:!1}function GWt(t,e){return!e||!t.getPreviousPageParam?!1:O0e(t,e)!=null}var OE,Ob,FE,Cf,Fb,Ic,xP,Bb,Mm,hy,$ge,W6e=($ge=class extends M0e{constructor(e){super();hi(this,Mm);hi(this,OE);hi(this,Ob);hi(this,FE);hi(this,Cf);hi(this,Fb);hi(this,Ic);hi(this,xP);hi(this,Bb);In(this,Bb,!1),In(this,xP,e.defaultOptions),this.setOptions(e.options),this.observers=[],In(this,Fb,e.client),In(this,Cf,Nt(this,Fb).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,In(this,Ob,Iae(this.options)),this.state=e.state??Nt(this,Ob),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return Nt(this,OE)}get promise(){var e;return(e=Nt(this,Ic))==null?void 0:e.promise}setOptions(e){if(this.options={...Nt(this,xP),...e},e!=null&&e._type&&In(this,OE,e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const r=Iae(this.options);r.data!==void 0&&(this.setState(kae(r.data,r.dataUpdatedAt)),In(this,Ob,r))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Nt(this,Cf).remove(this)}setData(e,r){const n=Wq(this.state.data,e,this.options);return is(this,Mm,hy).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(e){is(this,Mm,hy).call(this,{type:"setState",state:e})}cancel(e){var n,i;const r=(n=Nt(this,Ic))==null?void 0:n.promise;return(i=Nt(this,Ic))==null||i.cancel(e),r?r.then(Id).catch(Id):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return Nt(this,Ob)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>qo(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===TK||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>qo(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!P0e(this.state.dataUpdatedAt,e)}onFocus(){var e,r;(e=this.observers.find(n=>n.shouldFetchOnWindowFocus()))==null||e.refetch({cancelRefetch:!1}),(r=Nt(this,Ic))==null||r.continue()}onOnline(){var e,r;(e=this.observers.find(n=>n.shouldFetchOnReconnect()))==null||e.refetch({cancelRefetch:!1}),(r=Nt(this,Ic))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),Nt(this,Cf).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){const r=this.observers.indexOf(e);r!==-1&&(this.observers.splice(r,1),this.observers.length||(Nt(this,Ic)&&(Nt(this,Bb)||this.state.fetchStatus==="paused"&&this.state.status==="pending"?Nt(this,Ic).cancel({revert:!0}):Nt(this,Ic).cancelRetry()),this.scheduleGc()),Nt(this,Cf).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||is(this,Mm,hy).call(this,{type:"invalidate"})}async fetch(e,r){var l,g,v,E,T,j,P,C,L,O,F,$;if(this.state.fetchStatus!=="idle"&&((l=Nt(this,Ic))==null?void 0:l.status())!=="rejected"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Nt(this,Ic))return Nt(this,Ic).continueRetry(),Nt(this,Ic).promise}if(e&&this.setOptions(e),!this.options.queryFn){const G=this.observers.find(W=>W.options.queryFn);G&&this.setOptions(G.options)}const n=new AbortController,i=G=>{Object.defineProperty(G,"signal",{enumerable:!0,get:()=>(In(this,Bb,!0),n.signal)})},a=()=>{const G=R0e(this.options,r),Z=(()=>{const Q={client:Nt(this,Fb),queryKey:this.queryKey,meta:this.meta};return i(Q),Q})();return In(this,Bb,!1),this.options.persister?this.options.persister(G,Z,this):G(Z)},d=(()=>{const G={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Nt(this,Fb),state:this.state,fetchFn:a};return i(G),G})();(g=Nt(this,OE)==="infinite"?H6e(this.options.pages):this.options.behavior)==null||g.onFetch(d,this),In(this,FE,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((v=d.fetchOptions)==null?void 0:v.meta))&&is(this,Mm,hy).call(this,{type:"fetch",meta:(E=d.fetchOptions)==null?void 0:E.meta});const p=In(this,Ic,D0e({initialPromise:r==null?void 0:r.initialPromise,fn:d.fetchFn,onCancel:G=>{G instanceof Kq&&G.revert&&this.setState({...Nt(this,FE),fetchStatus:"idle"}),n.abort()},onFail:(G,W)=>{is(this,Mm,hy).call(this,{type:"failed",failureCount:G,error:W})},onPause:()=>{is(this,Mm,hy).call(this,{type:"pause"})},onContinue:()=>{is(this,Mm,hy).call(this,{type:"continue"})},retry:d.options.retry,retryDelay:d.options.retryDelay,networkMode:d.options.networkMode,canRun:()=>!0}));try{const G=await p.start();if(G===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(G),(j=(T=Nt(this,Cf).config).onSuccess)==null||j.call(T,G,this),(C=(P=Nt(this,Cf).config).onSettled)==null||C.call(P,G,this.state.error,this),G}catch(G){if(G instanceof Kq){if(G.silent)return Nt(this,Ic).promise;if(G.revert){if(this.state.data===void 0)throw G;return this.state.data}}throw is(this,Mm,hy).call(this,{type:"error",error:G}),(O=(L=Nt(this,Cf).config).onError)==null||O.call(L,G,this),($=(F=Nt(this,Cf).config).onSettled)==null||$.call(F,this.state.data,G,this),G}finally{Nt(this,Ic)===p&&In(this,Ic,void 0),this.scheduleGc()}}},OE=new WeakMap,Ob=new WeakMap,FE=new WeakMap,Cf=new WeakMap,Fb=new WeakMap,Ic=new WeakMap,xP=new WeakMap,Bb=new WeakMap,Mm=new WeakSet,hy=function(e){const r=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...F0e(n.data,this.options),fetchMeta:e.meta??null};case"success":const i={...n,...kae(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return In(this,FE,e.manual?i:void 0),i;case"error":const a=e.error;return{...n,error:a,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=r(this.state),Lc.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),Nt(this,Cf).notify({query:this,type:"updated",action:e})})},$ge);function F0e(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:L0e(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function kae(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Iae(t){const e=typeof t.initialData=="function"?t.initialData():t.initialData,r=e!==void 0,n=r?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:r?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var Td,Ys,_P,Ad,zb,BE,by,vP,zE,$E,$b,Ub,U_,UE,wa,LI,Zq,Xq,Qq,Jq,eG,tG,rG,nG,Uge,K6e=(Uge=class extends hA{constructor(e,r){super();hi(this,wa);hi(this,Td);hi(this,Ys);hi(this,_P);hi(this,Ad);hi(this,zb);hi(this,BE);hi(this,by);hi(this,vP);hi(this,zE);hi(this,$E);hi(this,$b);hi(this,Ub);hi(this,U_);hi(this,UE,new Set);this.options=r,In(this,Td,e),In(this,by,null),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Nt(this,Ys).addObserver(this),jae(Nt(this,Ys),this.options)?is(this,wa,LI).call(this):this.updateResult(),is(this,wa,eG).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return iG(Nt(this,Ys),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return iG(Nt(this,Ys),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,is(this,wa,tG).call(this),is(this,wa,rG).call(this),Nt(this,Ys).removeObserver(this)}setOptions(e){const r=this.options,n=Nt(this,Ys);if(this.options=Nt(this,Td).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof qo(this.options.enabled,Nt(this,Ys))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");is(this,wa,nG).call(this),Nt(this,Ys).setOptions(this.options),r._defaulted&&!ZM(this.options,r)&&Nt(this,Td).getQueryCache().notify({type:"observerOptionsUpdated",query:Nt(this,Ys),observer:this});const i=this.hasListeners();i&&Cae(Nt(this,Ys),n,this.options,r)&&is(this,wa,LI).call(this),this.updateResult(),i&&(Nt(this,Ys)!==n||qo(this.options.enabled,Nt(this,Ys))!==qo(r.enabled,Nt(this,Ys))||qo(this.options.staleTime,Nt(this,Ys))!==qo(r.staleTime,Nt(this,Ys)))&&is(this,wa,Xq).call(this);const a=is(this,wa,Qq).call(this);i&&(Nt(this,Ys)!==n||qo(this.options.enabled,Nt(this,Ys))!==qo(r.enabled,Nt(this,Ys))||a!==Nt(this,U_))&&is(this,wa,Jq).call(this,a)}getOptimisticResult(e){const r=Nt(this,Td).getQueryCache().build(Nt(this,Td),e),n=this.createResult(r,e);return ZM(this.getCurrentResult(),n)||(In(this,Ad,n),In(this,BE,this.options),In(this,zb,Nt(this,Ys).state)),n}getCurrentResult(){return Nt(this,Ad)}trackResult(e,r){return new Proxy(e,{get:(n,i)=>(this.trackProp(i),r==null||r(i),Reflect.get(n,i))})}trackProp(e){Nt(this,UE).add(e)}getCurrentQuery(){return Nt(this,Ys)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=Nt(this,Td).defaultQueryOptions(e),n=Nt(this,Td).getQueryCache().build(Nt(this,Td),r);let i=()=>{},a;const c=new Promise(d=>{a=d,i=Nt(this,Td).getQueryCache().subscribe(p=>{p.type==="updated"&&p.query.queryHash===n.queryHash&&n.state.data!==void 0&&(i(),d(this.createResult(n,r)))})});return Promise.race([n.fetch(r).then(()=>{const d=this.createResult(n,r);return a==null||a(d),d}).finally(()=>{i()}),c])}fetch(e){return is(this,wa,LI).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),Nt(this,Ad)))}createResult(e,r){var W;const n=Nt(this,Ys),i=this.options,a=Nt(this,Ad),c=Nt(this,zb),d=Nt(this,BE),p=e!==n?e.state:Nt(this,_P),{state:l}=e;let g={...l},v=!1,E;if(r._optimisticResults){const Z=this.hasListeners(),Q=!Z&&jae(e,r),ee=Z&&Cae(e,n,r,i);(Q||ee)&&(g={...g,...F0e(l.data,e.options)}),r._optimisticResults==="isRestoring"&&(g.fetchStatus="idle")}let{error:T,errorUpdatedAt:j,status:P}=g;E=g.data;let C=!1;if(r.placeholderData!==void 0&&E===void 0&&P==="pending"){let Z;a!=null&&a.isPlaceholderData&&r.placeholderData===(d==null?void 0:d.placeholderData)?(Z=a.data,C=!0):Z=typeof r.placeholderData=="function"?r.placeholderData((W=Nt(this,$E))==null?void 0:W.state.data,Nt(this,$E)):r.placeholderData,Z!==void 0&&(P="success",E=Wq(a==null?void 0:a.data,Z,r),v=!0)}if(r.select&&E!==void 0&&!C)if(a&&E===(c==null?void 0:c.data)&&r.select===Nt(this,vP))E=Nt(this,zE);else try{In(this,vP,r.select),E=r.select(E),E=Wq(a==null?void 0:a.data,E,r),In(this,zE,E),In(this,by,null)}catch(Z){In(this,by,Z)}else E===void 0&&In(this,by,null);Nt(this,by)&&(T=Nt(this,by),E=Nt(this,zE),j=Date.now(),P="error",v=!1);const L=g.fetchStatus==="fetching",O=P==="pending",F=P==="error",$=O&&L,G=E!==void 0;return{status:P,fetchStatus:g.fetchStatus,isPending:O,isSuccess:P==="success",isError:F,isInitialLoading:$,isLoading:$,data:E,dataUpdatedAt:g.dataUpdatedAt,error:T,errorUpdatedAt:j,failureCount:g.fetchFailureCount,failureReason:g.fetchFailureReason,errorUpdateCount:g.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:g.dataUpdateCount>p.dataUpdateCount||g.errorUpdateCount>p.errorUpdateCount,isFetching:L,isRefetching:L&&!O,isLoadingError:F&&!G,isPaused:g.fetchStatus==="paused",isPlaceholderData:v,isRefetchError:F&&G,isStale:jK(e,r),refetch:this.refetch,isEnabled:qo(r.enabled,e)!==!1}}updateResult(){const e=Nt(this,Ad),r=this.createResult(Nt(this,Ys),this.options);if(In(this,zb,Nt(this,Ys).state),In(this,BE,this.options),Nt(this,zb).data!==void 0&&In(this,$E,Nt(this,Ys)),ZM(r,e))return;In(this,Ad,r);const i=(()=>{if(!e)return!0;const{notifyOnChangeProps:a}=this.options,c=typeof a=="function"?a():a;if(c==="all"||!c&&!Nt(this,UE).size)return!0;const d=new Set(c??Nt(this,UE));return this.options.throwOnError&&d.add("error"),Object.keys(Nt(this,Ad)).some(p=>{const l=p;return Nt(this,Ad)[l]!==e[l]&&d.has(l)})})();Lc.batch(()=>{i&&this.listeners.forEach(a=>{a(Nt(this,Ad))}),Nt(this,Td).getQueryCache().notify({query:Nt(this,Ys),type:"observerResultsUpdated"})})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&is(this,wa,eG).call(this)}},Td=new WeakMap,Ys=new WeakMap,_P=new WeakMap,Ad=new WeakMap,zb=new WeakMap,BE=new WeakMap,by=new WeakMap,vP=new WeakMap,zE=new WeakMap,$E=new WeakMap,$b=new WeakMap,Ub=new WeakMap,U_=new WeakMap,UE=new WeakMap,wa=new WeakSet,LI=function(e){is(this,wa,nG).call(this);let r=Nt(this,Ys).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(Id)),r},Zq=function(e){return!kK()&&qo(this.options.enabled,Nt(this,Ys))!==!1&&C0e(e)},Xq=function(){is(this,wa,tG).call(this);const e=qo(this.options.staleTime,Nt(this,Ys));if(Nt(this,Ad).isStale||!is(this,wa,Zq).call(this,e))return;const r=P0e(Nt(this,Ad).dataUpdatedAt,e)+1;In(this,$b,Ab.setTimeout(()=>{Nt(this,Ad).isStale||this.updateResult()},r))},Qq=function(){return qo(this.options.refetchInterval,Nt(this,Ys))??!1},Jq=function(e){is(this,wa,rG).call(this),In(this,U_,e),!(Nt(this,U_)===0||!is(this,wa,Zq).call(this,Nt(this,U_)))&&In(this,Ub,Ab.setInterval(()=>{(this.options.refetchIntervalInBackground||IK.isFocused())&&is(this,wa,LI).call(this)},Nt(this,U_)))},eG=function(){is(this,wa,Xq).call(this),is(this,wa,Jq).call(this,is(this,wa,Qq).call(this))},tG=function(){Nt(this,$b)!==void 0&&(Ab.clearTimeout(Nt(this,$b)),In(this,$b,void 0))},rG=function(){Nt(this,Ub)!==void 0&&(Ab.clearInterval(Nt(this,Ub)),In(this,Ub,void 0))},nG=function(){const e=Nt(this,Td).getQueryCache().build(Nt(this,Td),this.options);if(e===Nt(this,Ys))return;const r=Nt(this,Ys);In(this,Ys,e),In(this,_P,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},Uge);function Y6e(t,e){return qo(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&qo(e.retryOnMount,t)===!1)}function jae(t,e){return Y6e(t,e)||t.state.data!==void 0&&iG(t,e,e.refetchOnMount)}function iG(t,e,r){if(qo(e.enabled,t)!==!1&&qo(e.staleTime,t)!=="static"){const n=qo(r,t);return n==="always"||n!==!1&&jK(t,e)}return!1}function Cae(t,e,r,n){return(t!==e||qo(n.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&jK(t,r)}function jK(t,e){return qo(e.enabled,t)!==!1&&t.isStaleByTime(qo(e.staleTime,t))}var bP,Up,Qu,Vb,Vp,w_,Vge,Z6e=(Vge=class extends M0e{constructor(e){super();hi(this,Vp);hi(this,bP);hi(this,Up);hi(this,Qu);hi(this,Vb);In(this,bP,e.client),this.mutationId=e.mutationId,In(this,Qu,e.mutationCache),In(this,Up,[]),this.state=e.state||B0e(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){Nt(this,Up).includes(e)||(Nt(this,Up).push(e),this.clearGcTimeout(),Nt(this,Qu).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){In(this,Up,Nt(this,Up).filter(r=>r!==e)),this.scheduleGc(),Nt(this,Qu).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){Nt(this,Up).length||(this.state.status==="pending"?this.scheduleGc():Nt(this,Qu).remove(this))}continue(){var e;return((e=Nt(this,Vb))==null?void 0:e.continue())??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(e){var d,p,l,g,v,E,T,j,P,C,L,O,F,$,G,W,Z,Q;const r=()=>{is(this,Vp,w_).call(this,{type:"continue"})},n={client:Nt(this,bP),meta:this.options.meta,mutationKey:this.options.mutationKey},i=In(this,Vb,D0e({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(ee,ie)=>{is(this,Vp,w_).call(this,{type:"failed",failureCount:ee,error:ie})},onPause:()=>{is(this,Vp,w_).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Nt(this,Qu).canRun(this)})),a=this.state.status==="pending",c=!i.canStart();try{if(a)r();else{is(this,Vp,w_).call(this,{type:"pending",variables:e,isPaused:c}),Nt(this,Qu).config.onMutate&&await Nt(this,Qu).config.onMutate(e,this,n);const ie=await((p=(d=this.options).onMutate)==null?void 0:p.call(d,e,n));ie!==this.state.context&&is(this,Vp,w_).call(this,{type:"pending",context:ie,variables:e,isPaused:c})}const ee=await i.start();return await((g=(l=Nt(this,Qu).config).onSuccess)==null?void 0:g.call(l,ee,e,this.state.context,this,n)),await((E=(v=this.options).onSuccess)==null?void 0:E.call(v,ee,e,this.state.context,n)),await((j=(T=Nt(this,Qu).config).onSettled)==null?void 0:j.call(T,ee,null,this.state.variables,this.state.context,this,n)),await((C=(P=this.options).onSettled)==null?void 0:C.call(P,ee,null,e,this.state.context,n)),is(this,Vp,w_).call(this,{type:"success",data:ee}),ee}catch(ee){try{await((O=(L=Nt(this,Qu).config).onError)==null?void 0:O.call(L,ee,e,this.state.context,this,n))}catch(ie){Promise.reject(ie)}try{await(($=(F=this.options).onError)==null?void 0:$.call(F,ee,e,this.state.context,n))}catch(ie){Promise.reject(ie)}try{await((W=(G=Nt(this,Qu).config).onSettled)==null?void 0:W.call(G,void 0,ee,this.state.variables,this.state.context,this,n))}catch(ie){Promise.reject(ie)}try{await((Q=(Z=this.options).onSettled)==null?void 0:Q.call(Z,void 0,ee,e,this.state.context,n))}catch(ie){Promise.reject(ie)}throw is(this,Vp,w_).call(this,{type:"error",error:ee}),ee}finally{Nt(this,Vb)===i&&In(this,Vb,void 0),Nt(this,Qu).runNext(this)}}},bP=new WeakMap,Up=new WeakMap,Qu=new WeakMap,Vb=new WeakMap,Vp=new WeakSet,w_=function(e){const r=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=r(this.state),Lc.batch(()=>{Nt(this,Up).forEach(n=>{n.onMutationUpdate(e)}),Nt(this,Qu).notify({mutation:this,type:"updated",action:e})})},Vge);function B0e(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var V_,Om,wP,qge,X6e=(qge=class extends hA{constructor(e={}){super();hi(this,V_);hi(this,Om);hi(this,wP);this.config=e,In(this,V_,new Set),In(this,Om,new Map),In(this,wP,0)}build(e,r,n){const i=new Z6e({client:e,mutationCache:this,mutationId:++VL(this,wP)._,options:e.defaultMutationOptions(r),state:n});return this.add(i),i}add(e){Nt(this,V_).add(e);const r=pD(e);if(typeof r=="string"){const n=Nt(this,Om).get(r);n?n.push(e):Nt(this,Om).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(Nt(this,V_).delete(e)){const r=pD(e);if(typeof r=="string"){const n=Nt(this,Om).get(r);if(n)if(n.length>1){const i=n.indexOf(e);i!==-1&&n.splice(i,1)}else n[0]===e&&Nt(this,Om).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){var n;const r=pD(e);if(typeof r=="string"){const i=(n=Nt(this,Om).get(r))==null?void 0:n.find(a=>a.state.status==="pending");return!i||i===e}else return!0}runNext(e){var n,i;const r=pD(e);return typeof r=="string"?((i=(n=Nt(this,Om).get(r))==null?void 0:n.find(a=>a!==e&&a.state.isPaused))==null?void 0:i.continue())??Promise.resolve():Promise.resolve()}clear(){Lc.batch(()=>{const e=this.getAll();Nt(this,V_).clear(),Nt(this,Om).clear(),e.forEach(r=>{this.notify({type:"removed",mutation:r})})})}getAll(){return Array.from(Nt(this,V_))}find(e){const r={exact:!0,...e};return this.getAll().find(n=>Eae(r,n))}findAll(e={}){return this.getAll().filter(r=>Eae(e,r))}notify(e){Lc.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return Lc.batch(()=>Promise.all(e.map(r=>r.continue().catch(Id))))}},V_=new WeakMap,Om=new WeakMap,wP=new WeakMap,qge);function pD(t){var e;return(e=t.options.scope)==null?void 0:e.id}var wy,q_,Ju,SP,tg,DI,sG,Gge,Q6e=(Gge=class extends hA{constructor(r,n){super();hi(this,tg);hi(this,wy);hi(this,q_);hi(this,Ju);hi(this,SP);In(this,wy,r),this.setOptions(n),this.bindMethods(),is(this,tg,DI).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(r){var i;const n=this.options;this.options=Nt(this,wy).defaultMutationOptions(r),ZM(this.options,n)||Nt(this,wy).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Nt(this,Ju),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&ow(n.mutationKey)!==ow(this.options.mutationKey)?this.reset():((i=Nt(this,Ju))==null?void 0:i.state.status)==="pending"&&Nt(this,Ju).setOptions(this.options)}onSubscribe(){this.listeners.size===1&&Nt(this,Ju)&&(Nt(this,Ju).addObserver(this),is(this,tg,DI).call(this))}onUnsubscribe(){var r;this.hasListeners()||(r=Nt(this,Ju))==null||r.removeObserver(this)}onMutationUpdate(r){is(this,tg,DI).call(this),is(this,tg,sG).call(this,r)}getCurrentResult(){return Nt(this,q_)}reset(){var r;(r=Nt(this,Ju))==null||r.removeObserver(this),In(this,Ju,void 0),is(this,tg,DI).call(this),is(this,tg,sG).call(this)}mutate(r,n){var i;return In(this,SP,n),(i=Nt(this,Ju))==null||i.removeObserver(this),In(this,Ju,Nt(this,wy).getMutationCache().build(Nt(this,wy),this.options)),Nt(this,Ju).addObserver(this),Nt(this,Ju).execute(r)}},wy=new WeakMap,q_=new WeakMap,Ju=new WeakMap,SP=new WeakMap,tg=new WeakSet,DI=function(){var n;const r=((n=Nt(this,Ju))==null?void 0:n.state)??B0e();In(this,q_,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},sG=function(r){Lc.batch(()=>{var i,a,c,d;const n=Nt(this,SP);if(n&&this.hasListeners()){const p=Nt(this,q_).variables,l=Nt(this,q_).context,g={client:Nt(this,wy),meta:this.options.meta,mutationKey:this.options.mutationKey};if((r==null?void 0:r.type)==="success"){try{(i=n.onSuccess)==null||i.call(n,r.data,p,l,g)}catch(v){Promise.reject(v)}try{(a=n.onSettled)==null||a.call(n,r.data,null,p,l,g)}catch(v){Promise.reject(v)}}else if((r==null?void 0:r.type)==="error"){try{(c=n.onError)==null||c.call(n,r.error,p,l,g)}catch(v){Promise.reject(v)}try{(d=n.onSettled)==null||d.call(n,void 0,r.error,p,l,g)}catch(v){Promise.reject(v)}}}this.listeners.forEach(p=>{p(Nt(this,q_))})})},Gge),qp,Hge,J6e=(Hge=class extends hA{constructor(e={}){super();hi(this,qp);this.config=e,In(this,qp,new Map)}build(e,r,n){const i=r.queryKey,a=r.queryHash??EK(i,r);let c=this.get(a);return c||(c=new W6e({client:e,queryKey:i,queryHash:a,options:e.defaultQueryOptions(r),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(c)),c}add(e){Nt(this,qp).has(e.queryHash)||(Nt(this,qp).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){Nt(this,qp).get(e.queryHash)===e&&(e.destroy(),Nt(this,qp).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Lc.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return Nt(this,qp).get(e)}getAll(){return[...Nt(this,qp).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(n=>Sae(r,n))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(n=>Sae(e,n)):r}notify(e){Lc.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){Lc.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Lc.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},qp=new WeakMap,Hge),ul,G_,H_,VE,qE,W_,GE,HE,Wge,eUe=(Wge=class{constructor(t={}){hi(this,ul);hi(this,G_);hi(this,H_);hi(this,VE);hi(this,qE);hi(this,W_);hi(this,GE);hi(this,HE);In(this,ul,t.queryCache||new J6e),In(this,G_,t.mutationCache||new X6e),In(this,H_,t.defaultOptions||{}),In(this,VE,new Map),In(this,qE,new Map),In(this,W_,0)}mount(){VL(this,W_)._++,Nt(this,W_)===1&&(In(this,GE,IK.subscribe(async t=>{t&&(await this.resumePausedMutations(),Nt(this,ul).onFocus())})),In(this,HE,hF.subscribe(async t=>{t&&(await this.resumePausedMutations(),Nt(this,ul).onOnline())})))}unmount(){var t,e;VL(this,W_)._--,Nt(this,W_)===0&&((t=Nt(this,GE))==null||t.call(this),In(this,GE,void 0),(e=Nt(this,HE))==null||e.call(this),In(this,HE,void 0))}isFetching(t){return Nt(this,ul).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return Nt(this,G_).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=Nt(this,ul).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=Nt(this,ul).build(this,e),n=r.state.data;return n===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(qo(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(n))}getQueriesData(t){return Nt(this,ul).findAll(t).map(({queryKey:e,state:r})=>[e,r.data])}setQueryData(t,e,r){var c;const n=this.defaultQueryOptions({queryKey:t}),i=(c=Nt(this,ul).get(n.queryHash))==null?void 0:c.state.data,a=L6e(e,i);if(a!==void 0)return Nt(this,ul).build(this,n).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return Lc.batch(()=>Nt(this,ul).findAll(t).map(({queryKey:n})=>[n,this.setQueryData(n,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=Nt(this,ul).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=Nt(this,ul);Lc.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=Nt(this,ul);return Lc.batch(()=>{const n=r.findAll(t),i=new Set(n);return n.forEach(a=>{a.reset()}),this.refetchQueries({type:"active",predicate:a=>i.has(a)},e)})}cancelQueries(t,e={}){const r={revert:!0,...e},n=Lc.batch(()=>Nt(this,ul).findAll(t).map(i=>i.cancel(r)));return Promise.all(n).then(Id).catch(Id)}invalidateQueries(t,e={}){return Lc.batch(()=>(Nt(this,ul).findAll(t).forEach(r=>{r.invalidate()}),(t==null?void 0:t.refetchType)==="none"?Promise.resolve():this.refetchQueries({...t,type:(t==null?void 0:t.refetchType)??(t==null?void 0:t.type)??"active"},e)))}refetchQueries(t,e={}){const r={...e,cancelRefetch:e.cancelRefetch??!0},n=Lc.batch(()=>Nt(this,ul).findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,r);return r.throwOnError||(a=a.catch(Id)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(n).then(Id)}async query(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=Nt(this,ul).build(this,e),n=r.isStaleByTime(qo(e.staleTime,r))?await r.fetch(e):r.state.data,i=e.select;return i?i(n):n}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=Nt(this,ul).build(this,e);return r.isStaleByTime(qo(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(Id).catch(Id)}infiniteQuery(t){return t._type="infinite",this.query(t)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(Id).catch(Id)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return hF.isOnline()?Nt(this,G_).resumePausedMutations():Promise.resolve()}getQueryCache(){return Nt(this,ul)}getMutationCache(){return Nt(this,G_)}getDefaultOptions(){return Nt(this,H_)}setDefaultOptions(t){In(this,H_,t)}setQueryDefaults(t,e){Nt(this,VE).set(ow(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...Nt(this,VE).values()],r={};return e.forEach(n=>{iT(t,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(t,e){Nt(this,qE).set(ow(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...Nt(this,qE).values()],r={};return e.forEach(n=>{iT(t,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...Nt(this,H_).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=EK(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===TK&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...Nt(this,H_).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){Nt(this,ul).clear(),Nt(this,G_).clear()}},ul=new WeakMap,G_=new WeakMap,H_=new WeakMap,VE=new WeakMap,qE=new WeakMap,W_=new WeakMap,GE=new WeakMap,HE=new WeakMap,Wge);const z0e=N.createContext(!1),tUe=()=>N.useContext(z0e);z0e.Provider;function rUe(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}const nUe=N.createContext(rUe()),iUe=()=>N.useContext(nUe),sUe=(t,e,r)=>{const n=(r==null?void 0:r.state.status)==="error"&&typeof t.throwOnError=="function"?AK(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||n)&&(e.isReset()||(t.retryOnMount=!1))},aUe=t=>{N.useEffect(()=>{t.clearReset()},[t])},oUe=({result:t,errorResetBoundary:e,throwOnError:r,query:n,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&n&&(i&&t.data===void 0||AK(r,[t.error,n])),lUe=t=>{if(t.suspense){const r=i=>i==="static"?i:Math.max(i??1e3,1e3),n=t.staleTime;t.staleTime=typeof n=="function"?(...i)=>r(n(...i)):r(n),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},cUe=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,uUe=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function dUe(t,e,r){const n=tUe(),i=iUe(),a=Ur(),c=a.defaultQueryOptions(t),d=a.getQueryCache().get(c.queryHash),p=t.subscribed!==!1;c._optimisticResults=n?"isRestoring":p?"optimistic":void 0,lUe(c),sUe(c,i,d),aUe(i);const[l]=N.useState(()=>new e(a,c)),g=l.getOptimisticResult(c),v=!n&&p;if(N.useSyncExternalStore(N.useCallback(E=>{const T=v?l.subscribe(Lc.batchCalls(E)):Id;return l.updateResult(),T},[l,v]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),N.useEffect(()=>{l.setOptions(c)},[c,l]),cUe(c,g))throw uUe(c,l,i);if(oUe({result:g,errorResetBoundary:i,throwOnError:c.throwOnError,query:d,suspense:c.suspense}))throw g.error;return c.notifyOnChangeProps?g:l.trackResult(g)}function jr(t,e){return dUe(t,K6e)}function zr(t,e){const r=Ur(),[n]=N.useState(()=>new Q6e(r,t));N.useEffect(()=>{n.setOptions(t)},[n,t]);const i=N.useSyncExternalStore(N.useCallback(c=>n.subscribe(Lc.batchCalls(c)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),a=N.useCallback((...c)=>{n.mutate(c[0],c[1]).catch(Id)},[n]);if(i.error&&AK(n.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}/** * @remix-run/router v1.23.4 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function Jj(){return Jj=Object.assign?Object.assign.bind():function(t){for(var e=1;e"u")throw new Error(e)}function $0e(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function fUe(){return Math.random().toString(36).substr(2,8)}function Nae(t,e){return{usr:t.state,key:t.key,idx:e}}function aG(t,e,r,n){return r===void 0&&(r=null),Jj({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?fA(e):e,{state:r,key:e&&e.key||n||fUe()})}function fF(t){let{pathname:e="/",search:r="",hash:n=""}=t;return r&&r!=="?"&&(e+=r.charAt(0)==="?"?r:"?"+r),n&&n!=="#"&&(e+=n.charAt(0)==="#"?n:"#"+n),e}function fA(t){let e={};if(t){let r=t.indexOf("#");r>=0&&(e.hash=t.substr(r),t=t.substr(0,r));let n=t.indexOf("?");n>=0&&(e.search=t.substr(n),t=t.substr(0,n)),t&&(e.pathname=t)}return e}function mUe(t,e,r,n){n===void 0&&(n={});let{window:i=document.defaultView,v5Compat:a=!1}=n,c=i.history,d=Z_.Pop,p=null,l=g();l==null&&(l=0,c.replaceState(Jj({},c.state,{idx:l}),""));function g(){return(c.state||{idx:null}).idx}function v(){d=Z_.Pop;let C=g(),L=C==null?null:C-l;l=C,p&&p({action:d,location:P.location,delta:L})}function E(C,L){d=Z_.Push;let O=aG(P.location,C,L);l=g()+1;let F=Nae(O,l),$=P.createHref(O);try{c.pushState(F,"",$)}catch(G){if(G instanceof DOMException&&G.name==="DataCloneError")throw G;i.location.assign($)}a&&p&&p({action:d,location:P.location,delta:1})}function T(C,L){d=Z_.Replace;let O=aG(P.location,C,L);l=g();let F=Nae(O,l),$=P.createHref(O);c.replaceState(F,"",$),a&&p&&p({action:d,location:P.location,delta:0})}function j(C){let L=i.location.origin!=="null"?i.location.origin:i.location.href,O=typeof C=="string"?C:fF(C);return O=O.replace(/ $/,"%20"),ml(L,"No window.location.(origin|href) available to create URL for href: "+O),new URL(O,L)}let P={get action(){return d},get location(){return t(i,c)},listen(C){if(p)throw new Error("A history only accepts one active listener");return i.addEventListener(Pae,v),p=C,()=>{i.removeEventListener(Pae,v),p=null}},createHref(C){return e(i,C)},createURL:j,encodeLocation(C){let L=j(C);return{pathname:L.pathname,search:L.search,hash:L.hash}},push:E,replace:T,go(C){return c.go(C)}};return P}var Rae;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(Rae||(Rae={}));function pUe(t,e,r){return r===void 0&&(r="/"),gUe(t,e,r)}function gUe(t,e,r,n){let i=typeof e=="string"?fA(e):e,a=sT(i.pathname||"/",r);if(a==null)return null;let c=U0e(t);yUe(c);let d=null,p=IUe(a);for(let l=0;d==null&&l{let p={relativePath:d===void 0?a.path||"":d,caseSensitive:a.caseSensitive===!0,childrenIndex:c,route:a};p.relativePath.startsWith("/")&&(ml(p.relativePath.startsWith(n),'Absolute route path "'+p.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),p.relativePath=p.relativePath.slice(n.length));let l=cv([n,p.relativePath]),g=r.concat(p);a.children&&a.children.length>0&&(ml(a.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+l+'".')),U0e(a.children,e,g,l)),!(a.path==null&&!a.index)&&e.push({path:l,score:EUe(l,a.index),routesMeta:g})};return t.forEach((a,c)=>{var d;if(a.path===""||!((d=a.path)!=null&&d.includes("?")))i(a,c);else for(let p of V0e(a.path))i(a,c,p)}),e}function V0e(t){let e=t.split("/");if(e.length===0)return[];let[r,...n]=e,i=r.endsWith("?"),a=r.replace(/\?$/,"");if(n.length===0)return i?[a,""]:[a];let c=V0e(n.join("/")),d=[];return d.push(...c.map(p=>p===""?a:[a,p].join("/"))),i&&d.push(...c),d.map(p=>t.startsWith("/")&&p===""?"/":p)}function yUe(t){t.sort((e,r)=>e.score!==r.score?r.score-e.score:TUe(e.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const xUe=/^:[\w-]+$/,_Ue=3,vUe=2,bUe=1,wUe=10,SUe=-2,Lae=t=>t==="*";function EUe(t,e){let r=t.split("/"),n=r.length;return r.some(Lae)&&(n+=SUe),e&&(n+=vUe),r.filter(i=>!Lae(i)).reduce((i,a)=>i+(xUe.test(a)?_Ue:a===""?bUe:wUe),n)}function TUe(t,e){return t.length===e.length&&t.slice(0,-1).every((n,i)=>n===e[i])?t[t.length-1]-e[e.length-1]:0}function AUe(t,e,r){let{routesMeta:n}=t,i={},a="/",c=[];for(let d=0;d{let{paramName:E,isOptional:T}=g;if(E==="*"){let P=d[v]||"";c=a.slice(0,a.length-P.length).replace(/(.)\/+$/,"$1")}const j=d[v];return T&&!j?l[E]=void 0:l[E]=(j||"").replace(/%2F/g,"/"),l},{}),pathname:a,pathnameBase:c,pattern:t}}function kUe(t,e,r){e===void 0&&(e=!1),r===void 0&&(r=!0),$0e(t==="*"||!t.endsWith("*")||t.endsWith("/*"),'Route path "'+t+'" will be treated as if it were '+('"'+t.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+t.replace(/\*$/,"/*")+'".'));let n=[],i="^"+t.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(c,d,p)=>(n.push({paramName:d,isOptional:p!=null}),p?"/?([^\\/]+)?":"/([^\\/]+)"));return t.endsWith("*")?(n.push({paramName:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),n]}function IUe(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return $0e(!1,'The URL path "'+t+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+e+").")),t}}function sT(t,e){if(e==="/")return t;if(!t.toLowerCase().startsWith(e.toLowerCase()))return null;let r=e.endsWith("/")?e.length-1:e.length,n=t.charAt(r);return n&&n!=="/"?null:t.slice(r)||"/"}function jUe(t,e){e===void 0&&(e="/");let{pathname:r,search:n="",hash:i=""}=typeof t=="string"?fA(t):t,a;return r?(r=q0e(r),r.startsWith("/")?a=Dae(r.substring(1),"/"):a=Dae(r,e)):a=e,{pathname:a,search:NUe(n),hash:RUe(i)}}function Dae(t,e){let r=e.replace(/\/+$/,"").split("/");return t.split("/").forEach(i=>{i===".."?r.length>1&&r.pop():i!=="."&&r.push(i)}),r.length>1?r.join("/"):"/"}function J6(t,e,r,n){return"Cannot include a '"+t+"' character in a manually specified "+("`to."+e+"` field ["+JSON.stringify(n)+"]. Please separate it out to the ")+("`to."+r+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function CUe(t){return t.filter((e,r)=>r===0||e.route.path&&e.route.path.length>0)}function CK(t,e){let r=CUe(t);return e?r.map((n,i)=>i===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function PK(t,e,r,n){n===void 0&&(n=!1);let i;typeof t=="string"?i=fA(t):(i=Jj({},t),ml(!i.pathname||!i.pathname.includes("?"),J6("?","pathname","search",i)),ml(!i.pathname||!i.pathname.includes("#"),J6("#","pathname","hash",i)),ml(!i.search||!i.search.includes("#"),J6("#","search","hash",i)));let a=t===""||i.pathname==="",c=a?"/":i.pathname,d;if(c==null)d=r;else{let v=e.length-1;if(!n&&c.startsWith("..")){let E=c.split("/");for(;E[0]==="..";)E.shift(),v-=1;i.pathname=E.join("/")}d=v>=0?e[v]:"/"}let p=jUe(i,d),l=c&&c!=="/"&&c.endsWith("/"),g=(a||c===".")&&r.endsWith("/");return!p.pathname.endsWith("/")&&(l||g)&&(p.pathname+="/"),p}const q0e=t=>t.replace(/\/\/+/g,"/"),cv=t=>q0e(t.join("/")),PUe=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),NUe=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,RUe=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function LUe(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const G0e=["post","put","patch","delete"];new Set(G0e);const DUe=["get",...G0e];new Set(DUe);/** * React Router v6.30.6 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function eC(){return eC=Object.assign?Object.assign.bind():function(t){for(var e=1;e{d.current=!0}),N.useCallback(function(l,g){if(g===void 0&&(g={}),!d.current)return;if(typeof l=="number"){n.go(l);return}let v=PK(l,JSON.parse(c),a,g.relative==="path");t==null&&e!=="/"&&(v.pathname=v.pathname==="/"?e:cv([e,v.pathname])),(g.replace?n.replace:n.push)(v,g.state,g)},[e,n,c,a,t])}const FUe=N.createContext(null);function BUe(t){let e=N.useContext(wg).outlet;return e&&N.createElement(FUe.Provider,{value:t},e)}function Sg(){let{matches:t}=N.useContext(wg),e=t[t.length-1];return e?e.params:{}}function Z4(t,e){let{relative:r}=e===void 0?{}:e,{future:n}=N.useContext(sx),{matches:i}=N.useContext(wg),{pathname:a}=ms(),c=JSON.stringify(CK(i,n.v7_relativeSplatPath));return N.useMemo(()=>PK(t,JSON.parse(c),a,r==="path"),[t,c,a,r])}function zUe(t,e){return $Ue(t,e)}function $Ue(t,e,r,n){mA()||ml(!1);let{navigator:i}=N.useContext(sx),{matches:a}=N.useContext(wg),c=a[a.length-1],d=c?c.params:{};c&&c.pathname;let p=c?c.pathnameBase:"/";c&&c.route;let l=ms(),g;if(e){var v;let C=typeof e=="string"?fA(e):e;p==="/"||(v=C.pathname)!=null&&v.startsWith(p)||ml(!1),g=C}else g=l;let E=g.pathname||"/",T=E;if(p!=="/"){let C=p.replace(/^\//,"").split("/");T="/"+E.replace(/^\//,"").split("/").slice(C.length).join("/")}let j=pUe(t,{pathname:T}),P=HUe(j&&j.map(C=>Object.assign({},C,{params:Object.assign({},d,C.params),pathname:cv([p,i.encodeLocation?i.encodeLocation(C.pathname).pathname:C.pathname]),pathnameBase:C.pathnameBase==="/"?p:cv([p,i.encodeLocation?i.encodeLocation(C.pathnameBase).pathname:C.pathnameBase])})),a,r,n);return e&&P?N.createElement(Y4.Provider,{value:{location:eC({pathname:"/",search:"",hash:"",state:null,key:"default"},g),navigationType:Z_.Pop}},P):P}function UUe(){let t=ZUe(),e=LUe(t)?t.status+" "+t.statusText:t instanceof Error?t.message:JSON.stringify(t),r=t instanceof Error?t.stack:null,i={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return N.createElement(N.Fragment,null,N.createElement("h2",null,"Unexpected Application Error!"),N.createElement("h3",{style:{fontStyle:"italic"}},e),r?N.createElement("pre",{style:i},r):null,null)}const VUe=N.createElement(UUe,null);class qUe extends N.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,r){return r.location!==e.location||r.revalidation!=="idle"&&e.revalidation==="idle"?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error!==void 0?e.error:r.error,location:r.location,revalidation:e.revalidation||r.revalidation}}componentDidCatch(e,r){console.error("React Router caught the following error during render",e,r)}render(){return this.state.error!==void 0?N.createElement(wg.Provider,{value:this.props.routeContext},N.createElement(W0e.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function GUe(t){let{routeContext:e,match:r,children:n}=t,i=N.useContext(K4);return i&&i.static&&i.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=r.route.id),N.createElement(wg.Provider,{value:e},n)}function HUe(t,e,r,n){var i;if(e===void 0&&(e=[]),r===void 0&&(r=null),n===void 0&&(n=null),t==null){var a;if(!r)return null;if(r.errors)t=r.matches;else if((a=n)!=null&&a.v7_partialHydration&&e.length===0&&!r.initialized&&r.matches.length>0)t=r.matches;else return null}let c=t,d=(i=r)==null?void 0:i.errors;if(d!=null){let g=c.findIndex(v=>v.route.id&&(d==null?void 0:d[v.route.id])!==void 0);g>=0||ml(!1),c=c.slice(0,Math.min(c.length,g+1))}let p=!1,l=-1;if(r&&n&&n.v7_partialHydration)for(let g=0;g=0?c=c.slice(0,l+1):c=[c[0]];break}}}return c.reduceRight((g,v,E)=>{let T,j=!1,P=null,C=null;r&&(T=d&&v.route.id?d[v.route.id]:void 0,P=v.route.errorElement||VUe,p&&(l<0&&E===0?(QUe("route-fallback"),j=!0,C=null):l===E&&(j=!0,C=v.route.hydrateFallbackElement||null)));let L=e.concat(c.slice(0,E+1)),O=()=>{let F;return T?F=P:j?F=C:v.route.Component?F=N.createElement(v.route.Component,null):v.route.element?F=v.route.element:F=g,N.createElement(GUe,{match:v,routeContext:{outlet:g,matches:L,isDataRoute:r!=null},children:F})};return r&&(v.route.ErrorBoundary||v.route.errorElement||E===0)?N.createElement(qUe,{location:r.location,revalidation:r.revalidation,component:P,error:T,children:O(),routeContext:{outlet:null,matches:L,isDataRoute:!0}}):O()},null)}var Y0e=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(Y0e||{}),Z0e=function(t){return t.UseBlocker="useBlocker",t.UseLoaderData="useLoaderData",t.UseActionData="useActionData",t.UseRouteError="useRouteError",t.UseNavigation="useNavigation",t.UseRouteLoaderData="useRouteLoaderData",t.UseMatches="useMatches",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t.UseRouteId="useRouteId",t}(Z0e||{});function WUe(t){let e=N.useContext(K4);return e||ml(!1),e}function KUe(t){let e=N.useContext(H0e);return e||ml(!1),e}function YUe(t){let e=N.useContext(wg);return e||ml(!1),e}function X0e(t){let e=YUe(),r=e.matches[e.matches.length-1];return r.route.id||ml(!1),r.route.id}function ZUe(){var t;let e=N.useContext(W0e),r=KUe(),n=X0e();return e!==void 0?e:(t=r.errors)==null?void 0:t[n]}function XUe(){let{router:t}=WUe(Y0e.UseNavigateStable),e=X0e(Z0e.UseNavigateStable),r=N.useRef(!1);return K0e(()=>{r.current=!0}),N.useCallback(function(i,a){a===void 0&&(a={}),r.current&&(typeof i=="number"?t.navigate(i):t.navigate(i,eC({fromRouteId:e},a)))},[t,e])}const Mae={};function QUe(t,e,r){Mae[t]||(Mae[t]=!0)}function JUe(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function Oi(t){let{to:e,replace:r,state:n,relative:i}=t;mA()||ml(!1);let{future:a,static:c}=N.useContext(sx),{matches:d}=N.useContext(wg),{pathname:p}=ms(),l=qa(),g=PK(e,CK(d,a.v7_relativeSplatPath),p,i==="path"),v=JSON.stringify(g);return N.useEffect(()=>l(JSON.parse(v),{replace:r,state:n,relative:i}),[l,v,i,r,n]),null}function WWt(t){return BUe(t.context)}function Ce(t){ml(!1)}function eVe(t){let{basename:e="/",children:r=null,location:n,navigationType:i=Z_.Pop,navigator:a,static:c=!1,future:d}=t;mA()&&ml(!1);let p=e.replace(/^\/*/,"/"),l=N.useMemo(()=>({basename:p,navigator:a,static:c,future:eC({v7_relativeSplatPath:!1},d)}),[p,d,a,c]);typeof n=="string"&&(n=fA(n));let{pathname:g="/",search:v="",hash:E="",state:T=null,key:j="default"}=n,P=N.useMemo(()=>{let C=sT(g,p);return C==null?null:{location:{pathname:C,search:v,hash:E,state:T,key:j},navigationType:i}},[p,g,v,E,T,j,i]);return P==null?null:N.createElement(sx.Provider,{value:l},N.createElement(Y4.Provider,{children:r,value:P}))}function kb(t){let{children:e,location:r}=t;return zUe(lG(e),r)}new Promise(()=>{});function lG(t,e){e===void 0&&(e=[]);let r=[];return N.Children.forEach(t,(n,i)=>{if(!N.isValidElement(n))return;let a=[...e,i];if(n.type===N.Fragment){r.push.apply(r,lG(n.props.children,a));return}n.type!==Ce&&ml(!1),!n.props.index||!n.props.children||ml(!1);let c={id:n.props.id||a.join("-"),caseSensitive:n.props.caseSensitive,element:n.props.element,Component:n.props.Component,index:n.props.index,path:n.props.path,loader:n.props.loader,action:n.props.action,errorElement:n.props.errorElement,ErrorBoundary:n.props.ErrorBoundary,hasErrorBoundary:n.props.ErrorBoundary!=null||n.props.errorElement!=null,shouldRevalidate:n.props.shouldRevalidate,handle:n.props.handle,lazy:n.props.lazy};n.props.children&&(c.children=lG(n.props.children,a)),r.push(c)}),r}/** * React Router DOM v6.30.6 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function mF(){return mF=Object.assign?Object.assign.bind():function(t){for(var e=1;e{let n=t[r];return e.concat(Array.isArray(n)?n.map(i=>[r,i]):[[r,n]])},[]))}function nVe(t,e){let r=cG(t);return e&&e.forEach((n,i)=>{r.has(i)||e.getAll(i).forEach(a=>{r.append(i,a)})}),r}const iVe=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],sVe=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],aVe="6";try{window.__reactRouterVersion=aVe}catch{}const oVe=N.createContext({isTransitioning:!1}),lVe="startTransition",Oae=ex[lVe];function cVe(t){let{basename:e,children:r,future:n,window:i}=t,a=N.useRef();a.current==null&&(a.current=hUe({window:i,v5Compat:!0}));let c=a.current,[d,p]=N.useState({action:c.action,location:c.location}),{v7_startTransition:l}=n||{},g=N.useCallback(v=>{l&&Oae?Oae(()=>p(v)):p(v)},[p,l]);return N.useLayoutEffect(()=>c.listen(g),[c,g]),N.useEffect(()=>JUe(n),[n]),N.createElement(eVe,{basename:e,children:r,location:d.location,navigationType:d.action,navigator:c,future:n})}const uVe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",dVe=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Nn=N.forwardRef(function(e,r){let{onClick:n,relative:i,reloadDocument:a,replace:c,state:d,target:p,to:l,preventScrollReset:g,viewTransition:v}=e,E=Q0e(e,iVe),{basename:T}=N.useContext(sx),j,P=!1;if(typeof l=="string"&&dVe.test(l)&&(j=l,uVe))try{let F=new URL(window.location.href),$=l.startsWith("//")?new URL(F.protocol+l):new URL(l),G=sT($.pathname,T);$.origin===F.origin&&G!=null?l=G+$.search+$.hash:P=!0}catch{}let C=MUe(l,{relative:i}),L=fVe(l,{replace:c,state:d,target:p,preventScrollReset:g,relative:i,viewTransition:v});function O(F){n&&n(F),F.defaultPrevented||L(F)}return N.createElement("a",mF({},E,{href:j||C,onClick:P||a?n:O,ref:r,target:p}))}),KWt=N.forwardRef(function(e,r){let{"aria-current":n="page",caseSensitive:i=!1,className:a="",end:c=!1,style:d,to:p,viewTransition:l,children:g}=e,v=Q0e(e,sVe),E=Z4(p,{relative:v.relative}),T=ms(),j=N.useContext(H0e),{navigator:P,basename:C}=N.useContext(sx),L=j!=null&&mVe(E)&&l===!0,O=P.encodeLocation?P.encodeLocation(E).pathname:E.pathname,F=T.pathname,$=j&&j.navigation&&j.navigation.location?j.navigation.location.pathname:null;i||(F=F.toLowerCase(),$=$?$.toLowerCase():null,O=O.toLowerCase()),$&&C&&($=sT($,C)||$);const G=O!=="/"&&O.endsWith("/")?O.length-1:O.length;let W=F===O||!c&&F.startsWith(O)&&F.charAt(G)==="/",Z=$!=null&&($===O||!c&&$.startsWith(O)&&$.charAt(O.length)==="/"),Q={isActive:W,isPending:Z,isTransitioning:L},ee=W?n:void 0,ie;typeof a=="function"?ie=a(Q):ie=[a,W?"active":null,Z?"pending":null,L?"transitioning":null].filter(Boolean).join(" ");let oe=typeof d=="function"?d(Q):d;return N.createElement(Nn,mF({},v,{"aria-current":ee,className:ie,ref:r,style:oe,to:p,viewTransition:l}),typeof g=="function"?g(Q):g)});var uG;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(uG||(uG={}));var Fae;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(Fae||(Fae={}));function hVe(t){let e=N.useContext(K4);return e||ml(!1),e}function fVe(t,e){let{target:r,replace:n,state:i,preventScrollReset:a,relative:c,viewTransition:d}=e===void 0?{}:e,p=qa(),l=ms(),g=Z4(t,{relative:c});return N.useCallback(v=>{if(rVe(v,r)){v.preventDefault();let E=n!==void 0?n:fF(l)===fF(g);p(t,{replace:E,state:i,preventScrollReset:a,relative:c,viewTransition:d})}},[l,p,g,n,i,r,t,a,c,d])}function zv(t){let e=N.useRef(cG(t)),r=N.useRef(!1),n=ms(),i=N.useMemo(()=>nVe(n.search,r.current?null:e.current),[n.search]),a=qa(),c=N.useCallback((d,p)=>{const l=cG(typeof d=="function"?d(i):d);r.current=!0,a("?"+l,p)},[a,i]);return[i,c]}function mVe(t,e){e===void 0&&(e={});let r=N.useContext(oVe);r==null&&ml(!1);let{basename:n}=hVe(uG.useViewTransitionState),i=Z4(t,{relative:e.relative});if(!r.isTransitioning)return!1;let a=sT(r.currentLocation.pathname,n)||r.currentLocation.pathname,c=sT(r.nextLocation.pathname,n)||r.nextLocation.pathname;return oG(i.pathname,c)!=null||oG(i.pathname,a)!=null}var pVe=typeof Element<"u",gVe=typeof Map=="function",yVe=typeof Set=="function",xVe=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function XM(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(t.constructor!==e.constructor)return!1;var r,n,i;if(Array.isArray(t)){if(r=t.length,r!=e.length)return!1;for(n=r;n--!==0;)if(!XM(t[n],e[n]))return!1;return!0}var a;if(gVe&&t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(a=t.entries();!(n=a.next()).done;)if(!e.has(n.value[0]))return!1;for(a=t.entries();!(n=a.next()).done;)if(!XM(n.value[1],e.get(n.value[0])))return!1;return!0}if(yVe&&t instanceof Set&&e instanceof Set){if(t.size!==e.size)return!1;for(a=t.entries();!(n=a.next()).done;)if(!e.has(n.value[0]))return!1;return!0}if(xVe&&ArrayBuffer.isView(t)&&ArrayBuffer.isView(e)){if(r=t.length,r!=e.length)return!1;for(n=r;n--!==0;)if(t[n]!==e[n])return!1;return!0}if(t.constructor===RegExp)return t.source===e.source&&t.flags===e.flags;if(t.valueOf!==Object.prototype.valueOf&&typeof t.valueOf=="function"&&typeof e.valueOf=="function")return t.valueOf()===e.valueOf();if(t.toString!==Object.prototype.toString&&typeof t.toString=="function"&&typeof e.toString=="function")return t.toString()===e.toString();if(i=Object.keys(t),r=i.length,r!==Object.keys(e).length)return!1;for(n=r;n--!==0;)if(!Object.prototype.hasOwnProperty.call(e,i[n]))return!1;if(pVe&&t instanceof Element)return!1;for(n=r;n--!==0;)if(!((i[n]==="_owner"||i[n]==="__v"||i[n]==="__o")&&t.$$typeof)&&!XM(t[i[n]],e[i[n]]))return!1;return!0}return t!==t&&e!==e}var _Ve=function(e,r){try{return XM(e,r)}catch(n){if((n.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw n}};const vVe=ea(_Ve);var bVe=function(t,e,r,n,i,a,c,d){if(!t){var p;if(e===void 0)p=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[r,n,i,a,c,d],g=0;p=new Error(e.replace(/%s/g,function(){return l[g++]})),p.name="Invariant Violation"}throw p.framesToPop=1,p}},wVe=bVe;const Bae=ea(wVe);var SVe=function(e,r,n,i){var a=n?n.call(i,e,r):void 0;if(a!==void 0)return!!a;if(e===r)return!0;if(typeof e!="object"||!e||typeof r!="object"||!r)return!1;var c=Object.keys(e),d=Object.keys(r);if(c.length!==d.length)return!1;for(var p=Object.prototype.hasOwnProperty.bind(r),l=0;l(t.BASE="base",t.BODY="body",t.HEAD="head",t.HTML="html",t.LINK="link",t.META="meta",t.NOSCRIPT="noscript",t.SCRIPT="script",t.STYLE="style",t.TITLE="title",t.FRAGMENT="Symbol(react.fragment)",t))(J0e||{}),eU={link:{rel:["amphtml","canonical","alternate"]},script:{type:["application/ld+json"]},meta:{charset:"",name:["generator","robots","description"],property:["og:type","og:title","og:url","og:image","og:image:alt","og:description","twitter:url","twitter:title","twitter:description","twitter:image","twitter:image:alt","twitter:card","twitter:site"]}},zae=Object.values(J0e),NK={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},TVe=Object.entries(NK).reduce((t,[e,r])=>(t[r]=e,t),{}),Wm="data-rh",SE={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},EE=(t,e)=>{for(let r=t.length-1;r>=0;r-=1){const n=t[r];if(Object.prototype.hasOwnProperty.call(n,e))return n[e]}return null},AVe=t=>{let e=EE(t,"title");const r=EE(t,SE.TITLE_TEMPLATE);if(Array.isArray(e)&&(e=e.join("")),r&&e)return r.replace(/%s/g,()=>e);const n=EE(t,SE.DEFAULT_TITLE);return e||n||void 0},kVe=t=>EE(t,SE.ON_CHANGE_CLIENT_STATE)||(()=>{}),tU=(t,e)=>e.filter(r=>typeof r[t]<"u").map(r=>r[t]).reduce((r,n)=>({...r,...n}),{}),IVe=(t,e)=>e.filter(r=>typeof r.base<"u").map(r=>r.base).reverse().reduce((r,n)=>{if(!r.length){const i=Object.keys(n);for(let a=0;aconsole&&typeof console.warn=="function"&&console.warn(t),Jk=(t,e,r)=>{const n={};return r.filter(i=>Array.isArray(i[t])?!0:(typeof i[t]<"u"&&jVe(`Helmet: ${t} should be of type "Array". Instead found type "${typeof i[t]}"`),!1)).map(i=>i[t]).reverse().reduce((i,a)=>{const c={};a.filter(p=>{let l;const g=Object.keys(p);for(let E=0;Ei.push(p));const d=Object.keys(c);for(let p=0;p{if(Array.isArray(t)&&t.length){for(let r=0;r({baseTag:IVe(["href"],t),bodyAttributes:tU("bodyAttributes",t),defer:EE(t,SE.DEFER),encode:EE(t,SE.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:tU("htmlAttributes",t),linkTags:Jk("link",["rel","href"],t),metaTags:Jk("meta",["name","charset","http-equiv","property","itemprop"],t),noscriptTags:Jk("noscript",["innerHTML"],t),onChangeClientState:kVe(t),scriptTags:Jk("script",["src","innerHTML"],t),styleTags:Jk("style",["cssText"],t),title:AVe(t),titleAttributes:tU("titleAttributes",t),prioritizeSeoTags:CVe(t,SE.PRIORITIZE_SEO_TAGS)}),ebe=t=>Array.isArray(t)?t.join(""):t,NVe=(t,e)=>{const r=Object.keys(t);for(let n=0;nArray.isArray(t)?t.reduce((r,n)=>(NVe(n,e)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:t,priority:[]},$ae=(t,e)=>({...t,[e]:void 0}),RVe=["noscript","script","style"],dG=(t,e=!0)=>e===!1?String(t):String(t).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),tbe=t=>Object.keys(t).reduce((e,r)=>{const n=typeof t[r]<"u"?`${r}="${t[r]}"`:`${r}`;return e?`${e} ${n}`:n},""),LVe=(t,e,r,n)=>{const i=tbe(r),a=ebe(e);return i?`<${t} ${Wm}="true" ${i}>${dG(a,n)}`:`<${t} ${Wm}="true">${dG(a,n)}`},DVe=(t,e,r=!0)=>e.reduce((n,i)=>{const a=i,c=Object.keys(a).filter(l=>!(l==="innerHTML"||l==="cssText")).reduce((l,g)=>{const v=typeof a[g]>"u"?g:`${g}="${dG(a[g],r)}"`;return l?`${l} ${v}`:v},""),d=a.innerHTML||a.cssText||"",p=RVe.indexOf(t)===-1;return`${n}<${t} ${Wm}="true" ${c}${p?"/>":`>${d}`}`},""),rbe=(t,e={})=>Object.keys(t).reduce((r,n)=>{const i=NK[n];return r[i||n]=t[n],r},e),MVe=(t,e,r)=>{const n={key:e,[Wm]:!0},i=rbe(r,n);return[et.createElement("title",i,e)]},QM=(t,e)=>e.map((r,n)=>{const i={key:n,[Wm]:!0};return Object.keys(r).forEach(a=>{const d=NK[a]||a;if(d==="innerHTML"||d==="cssText"){const p=r.innerHTML||r.cssText;i.dangerouslySetInnerHTML={__html:p}}else i[d]=r[a]}),et.createElement(t,i)}),jf=(t,e,r=!0)=>{switch(t){case"title":return{toComponent:()=>MVe(t,e.title,e.titleAttributes),toString:()=>LVe(t,e.title,e.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>rbe(e),toString:()=>tbe(e)};default:return{toComponent:()=>QM(t,e),toString:()=>DVe(t,e,r)}}},OVe=({metaTags:t,linkTags:e,scriptTags:r,encode:n})=>{const i=rU(t,eU.meta),a=rU(e,eU.link),c=rU(r,eU.script);return{priorityMethods:{toComponent:()=>[...QM("meta",i.priority),...QM("link",a.priority),...QM("script",c.priority)],toString:()=>`${jf("meta",i.priority,n)} ${jf("link",a.priority,n)} ${jf("script",c.priority,n)}`},metaTags:i.default,linkTags:a.default,scriptTags:c.default}},FVe=t=>{const{baseTag:e,bodyAttributes:r,encode:n=!0,htmlAttributes:i,noscriptTags:a,styleTags:c,title:d="",titleAttributes:p,prioritizeSeoTags:l}=t;let{linkTags:g,metaTags:v,scriptTags:E}=t,T={toComponent:()=>{},toString:()=>""};return l&&({priorityMethods:T,linkTags:g,metaTags:v,scriptTags:E}=OVe(t)),{priority:T,base:jf("base",e,n),bodyAttributes:jf("bodyAttributes",r,n),htmlAttributes:jf("htmlAttributes",i,n),link:jf("link",g,n),meta:jf("meta",v,n),noscript:jf("noscript",a,n),script:jf("script",E,n),style:jf("style",c,n),title:jf("title",{title:d,titleAttributes:p},n)}},hG=FVe,gD=[],nbe=!!(typeof window<"u"&&window.document&&window.document.createElement),fG=class{constructor(t,e){jn(this,"instances",[]);jn(this,"canUseDOM",nbe);jn(this,"context");jn(this,"value",{setHelmet:t=>{this.context.helmet=t},helmetInstances:{get:()=>this.canUseDOM?gD:this.instances,add:t=>{(this.canUseDOM?gD:this.instances).push(t)},remove:t=>{const e=(this.canUseDOM?gD:this.instances).indexOf(t);(this.canUseDOM?gD:this.instances).splice(e,1)}}});this.context=t,this.canUseDOM=e||!1,e||(t.helmet=hG({baseTag:[],bodyAttributes:{},htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},BVe={},ibe=et.createContext(BVe),qb,sbe=(qb=class extends N.Component{constructor(r){super(r);jn(this,"helmetData");this.helmetData=new fG(this.props.context||{},qb.canUseDOM)}render(){return et.createElement(ibe.Provider,{value:this.helmetData.value},this.props.children)}},jn(qb,"canUseDOM",nbe),qb),vS=(t,e)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${t}[${Wm}]`),i=[].slice.call(n),a=[];let c;return e&&e.length&&e.forEach(d=>{const p=document.createElement(t);for(const l in d)if(Object.prototype.hasOwnProperty.call(d,l))if(l==="innerHTML")p.innerHTML=d.innerHTML;else if(l==="cssText")p.styleSheet?p.styleSheet.cssText=d.cssText:p.appendChild(document.createTextNode(d.cssText));else{const g=l,v=typeof d[g]>"u"?"":d[g];p.setAttribute(l,v)}p.setAttribute(Wm,"true"),i.some((l,g)=>(c=g,p.isEqualNode(l)))?i.splice(c,1):a.push(p)}),i.forEach(d=>{var p;return(p=d.parentNode)==null?void 0:p.removeChild(d)}),a.forEach(d=>r.appendChild(d)),{oldTags:i,newTags:a}},mG=(t,e)=>{const r=document.getElementsByTagName(t)[0];if(!r)return;const n=r.getAttribute(Wm),i=n?n.split(","):[],a=[...i],c=Object.keys(e);for(const d of c){const p=e[d]||"";r.getAttribute(d)!==p&&r.setAttribute(d,p),i.indexOf(d)===-1&&i.push(d);const l=a.indexOf(d);l!==-1&&a.splice(l,1)}for(let d=a.length-1;d>=0;d-=1)r.removeAttribute(a[d]);i.length===a.length?r.removeAttribute(Wm):r.getAttribute(Wm)!==c.join(",")&&r.setAttribute(Wm,c.join(","))},zVe=(t,e)=>{typeof t<"u"&&document.title!==t&&(document.title=ebe(t)),mG("title",e)},Uae=(t,e)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:i,linkTags:a,metaTags:c,noscriptTags:d,onChangeClientState:p,scriptTags:l,styleTags:g,title:v,titleAttributes:E}=t;mG("body",n),mG("html",i),zVe(v,E);const T={baseTag:vS("base",r),linkTags:vS("link",a),metaTags:vS("meta",c),noscriptTags:vS("noscript",d),scriptTags:vS("script",l),styleTags:vS("style",g)},j={},P={};Object.keys(T).forEach(C=>{const{newTags:L,oldTags:O}=T[C];L.length&&(j[C]=L),O.length&&(P[C]=T[C].oldTags)}),e&&e(),p(t,j,P)},eI=null,$Ve=t=>{eI&&cancelAnimationFrame(eI),t.defer?eI=requestAnimationFrame(()=>{Uae(t,()=>{eI=null})}):(Uae(t),eI=null)},UVe=$Ve,Vae=class extends N.Component{constructor(){super(...arguments);jn(this,"rendered",!1)}shouldComponentUpdate(e){return!EVe(e,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:e}=this.props.context;e.remove(this),this.emitChange()}emitChange(){const{helmetInstances:e,setHelmet:r}=this.props.context;let n=null;const i=PVe(e.get().map(a=>{const c={...a.props};return delete c.context,c}));sbe.canUseDOM?UVe(i):hG&&(n=hG(i)),r(n)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:e}=this.props.context;e.add(this),this.emitChange()}render(){return this.init(),null}},k8,mc=(k8=class extends N.Component{shouldComponentUpdate(t){return!vVe($ae(this.props,"helmetData"),$ae(t,"helmetData"))}mapNestedChildrenToProps(t,e){if(!e)return null;switch(t.type){case"script":case"noscript":return{innerHTML:e};case"style":return{cssText:e};default:throw new Error(`<${t.type} /> elements are self-closing and can not contain children. Refer to our API for more information.`)}}flattenArrayTypeChildren(t,e,r,n){return{...e,[t.type]:[...e[t.type]||[],{...r,...this.mapNestedChildrenToProps(t,n)}]}}mapObjectTypeChildren(t,e,r,n){switch(t.type){case"title":return{...e,[t.type]:n,titleAttributes:{...r}};case"body":return{...e,bodyAttributes:{...r}};case"html":return{...e,htmlAttributes:{...r}};default:return{...e,[t.type]:{...r}}}}mapArrayTypeChildrenToProps(t,e){let r={...e};return Object.keys(t).forEach(n=>{r={...r,[n]:t[n]}}),r}warnOnInvalidChildren(t,e){return Bae(zae.some(r=>t.type===r),typeof t.type=="function"?"You may be attempting to nest components within each other, which is not allowed. Refer to our API for more information.":`Only elements types ${zae.join(", ")} are allowed. Helmet does not support rendering <${t.type}> elements. Refer to our API for more information.`),Bae(!e||typeof e=="string"||Array.isArray(e)&&!e.some(r=>typeof r!="string"),`Helmet expects a string as a child of <${t.type}>. Did you forget to wrap your children in braces? ( <${t.type}>{\`\`} ) Refer to our API for more information.`),!0}mapChildrenToProps(t,e){let r={};return et.Children.forEach(t,n=>{if(!n||!n.props)return;const{children:i,...a}=n.props,c=Object.keys(a).reduce((p,l)=>(p[TVe[l]||l]=a[l],p),{});let{type:d}=n;switch(typeof d=="symbol"?d=d.toString():this.warnOnInvalidChildren(n,i),d){case"Symbol(react.fragment)":e=this.mapChildrenToProps(i,e);break;case"link":case"meta":case"noscript":case"script":case"style":r=this.flattenArrayTypeChildren(n,r,c,i);break;default:e=this.mapObjectTypeChildren(n,e,c,i);break}}),this.mapArrayTypeChildrenToProps(r,e)}render(){const{children:t,...e}=this.props;let r={...e},{helmetData:n}=e;if(t&&(r=this.mapChildrenToProps(t,r)),n&&!(n instanceof fG)){const i=n;n=new fG(i.context,!0),delete r.helmetData}return n?et.createElement(Vae,{...r,context:n.value}):et.createElement(ibe.Consumer,null,i=>et.createElement(Vae,{...r,context:i}))}},jn(k8,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),k8);const VVe=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Ge(async()=>{const{default:n}=await Promise.resolve().then(()=>pA);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)};class RK extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}}class qVe extends RK{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class GVe extends RK{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class HVe extends RK{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var pG;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(pG||(pG={}));var WVe=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(c){c(a)})}return new(r||(r=Promise))(function(a,c){function d(g){try{l(n.next(g))}catch(v){c(v)}}function p(g){try{l(n.throw(g))}catch(v){c(v)}}function l(g){g.done?a(g.value):i(g.value).then(d,p)}l((n=n.apply(t,e||[])).next())})};class KVe{constructor(e,{headers:r={},customFetch:n,region:i=pG.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=VVe(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,r={}){var n;return WVe(this,void 0,void 0,function*(){try{const{headers:i,method:a,body:c}=r;let d={},{region:p}=r;p||(p=this.region),p&&p!=="any"&&(d["x-region"]=p);let l;c&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(d["Content-Type"]="application/octet-stream",l=c):typeof c=="string"?(d["Content-Type"]="text/plain",l=c):typeof FormData<"u"&&c instanceof FormData?l=c:(d["Content-Type"]="application/json",l=JSON.stringify(c)));const g=yield this.fetch(`${this.url}/${e}`,{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},d),this.headers),i),body:l}).catch(j=>{throw new qVe(j)}),v=g.headers.get("x-relay-error");if(v&&v==="true")throw new GVe(g);if(!g.ok)throw new HVe(g);let E=((n=g.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),T;return E==="application/json"?T=yield g.json():E==="application/octet-stream"?T=yield g.blob():E==="text/event-stream"?T=g:E==="multipart/form-data"?T=yield g.formData():T=yield g.text(),{data:T,error:null}}catch(i){return{data:null,error:i}}})}}var oh={},LK={},X4={},BP={},Q4={},J4={},YVe=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("unable to locate global object")},aT=YVe();const ZVe=aT.fetch,abe=aT.fetch.bind(aT),obe=aT.Headers,XVe=aT.Request,QVe=aT.Response,pA=Object.freeze(Object.defineProperty({__proto__:null,Headers:obe,Request:XVe,Response:QVe,default:abe,fetch:ZVe},Symbol.toStringTag,{value:"Module"})),JVe=sOe(pA);var e5={};Object.defineProperty(e5,"__esModule",{value:!0});let e8e=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};e5.default=e8e;var lbe=Ou&&Ou.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(J4,"__esModule",{value:!0});const t8e=lbe(JVe),r8e=lbe(e5);let n8e=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=t8e.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,r){return this.headers=Object.assign({},this.headers),this.headers[e]=r,this}then(e,r){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const n=this.fetch;let i=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async a=>{var c,d,p;let l=null,g=null,v=null,E=a.status,T=a.statusText;if(a.ok){if(this.method!=="HEAD"){const L=await a.text();L===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?g=L:g=JSON.parse(L))}const P=(c=this.headers.Prefer)===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),C=(d=a.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");P&&C&&C.length>1&&(v=parseInt(C[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(g)&&(g.length>1?(l={code:"PGRST116",details:`Results contain ${g.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},g=null,v=null,E=406,T="Not Acceptable"):g.length===1?g=g[0]:g=null)}else{const P=await a.text();try{l=JSON.parse(P),Array.isArray(l)&&a.status===404&&(g=[],l=null,E=200,T="OK")}catch{a.status===404&&P===""?(E=204,T="No Content"):l={message:P}}if(l&&this.isMaybeSingle&&(!((p=l==null?void 0:l.details)===null||p===void 0)&&p.includes("0 rows"))&&(l=null,E=200,T="OK"),l&&this.shouldThrowOnError)throw new r8e.default(l)}return{error:l,data:g,count:v,status:E,statusText:T}});return this.shouldThrowOnError||(i=i.catch(a=>{var c,d,p;return{error:{message:`${(c=a==null?void 0:a.name)!==null&&c!==void 0?c:"FetchError"}: ${a==null?void 0:a.message}`,details:`${(d=a==null?void 0:a.stack)!==null&&d!==void 0?d:""}`,hint:"",code:`${(p=a==null?void 0:a.code)!==null&&p!==void 0?p:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,r)}returns(){return this}overrideTypes(){return this}};J4.default=n8e;var i8e=Ou&&Ou.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Q4,"__esModule",{value:!0});const s8e=i8e(J4);let a8e=class extends s8e.default{select(e){let r=!1;const n=(e??"*").split("").map(i=>/\s/.test(i)&&!r?"":(i==='"'&&(r=!r),i)).join("");return this.url.searchParams.set("select",n),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:r=!0,nullsFirst:n,foreignTable:i,referencedTable:a=i}={}){const c=a?`${a}.order`:"order",d=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${d?`${d},`:""}${e}.${r?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:r,referencedTable:n=r}={}){const i=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${e}`),this}range(e,r,{foreignTable:n,referencedTable:i=n}={}){const a=typeof i>"u"?"offset":`${i}.offset`,c=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(a,`${e}`),this.url.searchParams.set(c,`${r-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:r=!1,settings:n=!1,buffers:i=!1,wal:a=!1,format:c="text"}={}){var d;const p=[e?"analyze":null,r?"verbose":null,n?"settings":null,i?"buffers":null,a?"wal":null].filter(Boolean).join("|"),l=(d=this.headers.Accept)!==null&&d!==void 0?d:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${c}; for="${l}"; options=${p};`,c==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};Q4.default=a8e;var o8e=Ou&&Ou.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(BP,"__esModule",{value:!0});const l8e=o8e(Q4);let c8e=class extends l8e.default{eq(e,r){return this.url.searchParams.append(e,`eq.${r}`),this}neq(e,r){return this.url.searchParams.append(e,`neq.${r}`),this}gt(e,r){return this.url.searchParams.append(e,`gt.${r}`),this}gte(e,r){return this.url.searchParams.append(e,`gte.${r}`),this}lt(e,r){return this.url.searchParams.append(e,`lt.${r}`),this}lte(e,r){return this.url.searchParams.append(e,`lte.${r}`),this}like(e,r){return this.url.searchParams.append(e,`like.${r}`),this}likeAllOf(e,r){return this.url.searchParams.append(e,`like(all).{${r.join(",")}}`),this}likeAnyOf(e,r){return this.url.searchParams.append(e,`like(any).{${r.join(",")}}`),this}ilike(e,r){return this.url.searchParams.append(e,`ilike.${r}`),this}ilikeAllOf(e,r){return this.url.searchParams.append(e,`ilike(all).{${r.join(",")}}`),this}ilikeAnyOf(e,r){return this.url.searchParams.append(e,`ilike(any).{${r.join(",")}}`),this}is(e,r){return this.url.searchParams.append(e,`is.${r}`),this}in(e,r){const n=Array.from(new Set(r)).map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${n})`),this}contains(e,r){return typeof r=="string"?this.url.searchParams.append(e,`cs.${r}`):Array.isArray(r)?this.url.searchParams.append(e,`cs.{${r.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(r)}`),this}containedBy(e,r){return typeof r=="string"?this.url.searchParams.append(e,`cd.${r}`):Array.isArray(r)?this.url.searchParams.append(e,`cd.{${r.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(r)}`),this}rangeGt(e,r){return this.url.searchParams.append(e,`sr.${r}`),this}rangeGte(e,r){return this.url.searchParams.append(e,`nxl.${r}`),this}rangeLt(e,r){return this.url.searchParams.append(e,`sl.${r}`),this}rangeLte(e,r){return this.url.searchParams.append(e,`nxr.${r}`),this}rangeAdjacent(e,r){return this.url.searchParams.append(e,`adj.${r}`),this}overlaps(e,r){return typeof r=="string"?this.url.searchParams.append(e,`ov.${r}`):this.url.searchParams.append(e,`ov.{${r.join(",")}}`),this}textSearch(e,r,{config:n,type:i}={}){let a="";i==="plain"?a="pl":i==="phrase"?a="ph":i==="websearch"&&(a="w");const c=n===void 0?"":`(${n})`;return this.url.searchParams.append(e,`${a}fts${c}.${r}`),this}match(e){return Object.entries(e).forEach(([r,n])=>{this.url.searchParams.append(r,`eq.${n}`)}),this}not(e,r,n){return this.url.searchParams.append(e,`not.${r}.${n}`),this}or(e,{foreignTable:r,referencedTable:n=r}={}){const i=n?`${n}.or`:"or";return this.url.searchParams.append(i,`(${e})`),this}filter(e,r,n){return this.url.searchParams.append(e,`${r}.${n}`),this}};BP.default=c8e;var u8e=Ou&&Ou.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(X4,"__esModule",{value:!0});const tI=u8e(BP);let d8e=class{constructor(e,{headers:r={},schema:n,fetch:i}){this.url=e,this.headers=r,this.schema=n,this.fetch=i}select(e,{head:r=!1,count:n}={}){const i=r?"HEAD":"GET";let a=!1;const c=(e??"*").split("").map(d=>/\s/.test(d)&&!a?"":(d==='"'&&(a=!a),d)).join("");return this.url.searchParams.set("select",c),n&&(this.headers.Prefer=`count=${n}`),new tI.default({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:r,defaultToNull:n=!0}={}){const i="POST",a=[];if(this.headers.Prefer&&a.push(this.headers.Prefer),r&&a.push(`count=${r}`),n||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){const c=e.reduce((d,p)=>d.concat(Object.keys(p)),[]);if(c.length>0){const d=[...new Set(c)].map(p=>`"${p}"`);this.url.searchParams.set("columns",d.join(","))}}return new tI.default({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:r,ignoreDuplicates:n=!1,count:i,defaultToNull:a=!0}={}){const c="POST",d=[`resolution=${n?"ignore":"merge"}-duplicates`];if(r!==void 0&&this.url.searchParams.set("on_conflict",r),this.headers.Prefer&&d.push(this.headers.Prefer),i&&d.push(`count=${i}`),a||d.push("missing=default"),this.headers.Prefer=d.join(","),Array.isArray(e)){const p=e.reduce((l,g)=>l.concat(Object.keys(g)),[]);if(p.length>0){const l=[...new Set(p)].map(g=>`"${g}"`);this.url.searchParams.set("columns",l.join(","))}}return new tI.default({method:c,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:r}={}){const n="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),r&&i.push(`count=${r}`),this.headers.Prefer=i.join(","),new tI.default({method:n,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const r="DELETE",n=[];return e&&n.push(`count=${e}`),this.headers.Prefer&&n.unshift(this.headers.Prefer),this.headers.Prefer=n.join(","),new tI.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};X4.default=d8e;var t5={},r5={};Object.defineProperty(r5,"__esModule",{value:!0});r5.version=void 0;r5.version="0.0.0-automated";Object.defineProperty(t5,"__esModule",{value:!0});t5.DEFAULT_HEADERS=void 0;const h8e=r5;t5.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${h8e.version}`};var cbe=Ou&&Ou.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(LK,"__esModule",{value:!0});const f8e=cbe(X4),m8e=cbe(BP),p8e=t5;let g8e=class ube{constructor(e,{headers:r={},schema:n,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},p8e.DEFAULT_HEADERS),r),this.schemaName=n,this.fetch=i}from(e){const r=new URL(`${this.url}/${e}`);return new f8e.default(r,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new ube(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,r={},{head:n=!1,get:i=!1,count:a}={}){let c;const d=new URL(`${this.url}/rpc/${e}`);let p;n||i?(c=n?"HEAD":"GET",Object.entries(r).filter(([g,v])=>v!==void 0).map(([g,v])=>[g,Array.isArray(v)?`{${v.join(",")}}`:`${v}`]).forEach(([g,v])=>{d.searchParams.append(g,v)})):(c="POST",p=r);const l=Object.assign({},this.headers);return a&&(l.Prefer=`count=${a}`),new m8e.default({method:c,url:d,headers:l,schema:this.schemaName,body:p,fetch:this.fetch,allowEmpty:!1})}};LK.default=g8e;var gA=Ou&&Ou.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(oh,"__esModule",{value:!0});oh.PostgrestError=oh.PostgrestBuilder=oh.PostgrestTransformBuilder=oh.PostgrestFilterBuilder=oh.PostgrestQueryBuilder=oh.PostgrestClient=void 0;const dbe=gA(LK);oh.PostgrestClient=dbe.default;const hbe=gA(X4);oh.PostgrestQueryBuilder=hbe.default;const fbe=gA(BP);oh.PostgrestFilterBuilder=fbe.default;const mbe=gA(Q4);oh.PostgrestTransformBuilder=mbe.default;const pbe=gA(J4);oh.PostgrestBuilder=pbe.default;const gbe=gA(e5);oh.PostgrestError=gbe.default;var y8e=oh.default={PostgrestClient:dbe.default,PostgrestQueryBuilder:hbe.default,PostgrestFilterBuilder:fbe.default,PostgrestTransformBuilder:mbe.default,PostgrestBuilder:pbe.default,PostgrestError:gbe.default};const{PostgrestClient:x8e,PostgrestQueryBuilder:eKt,PostgrestFilterBuilder:tKt,PostgrestTransformBuilder:rKt,PostgrestBuilder:nKt,PostgrestError:iKt}=y8e;let gG;typeof window>"u"?gG=require("ws"):gG=window.WebSocket;const _8e="2.11.10",v8e={"X-Client-Info":`realtime-js/${_8e}`},b8e="1.0.0",ybe=1e4,w8e=1e3;var TE;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(TE||(TE={}));var Ed;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(Ed||(Ed={}));var Bm;(function(t){t.close="phx_close",t.error="phx_error",t.join="phx_join",t.reply="phx_reply",t.leave="phx_leave",t.access_token="access_token"})(Bm||(Bm={}));var yG;(function(t){t.websocket="websocket"})(yG||(yG={}));var bb;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(bb||(bb={}));class S8e{constructor(){this.HEADER_LENGTH=1}decode(e,r){return e.constructor===ArrayBuffer?r(this._binaryDecode(e)):r(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const r=new DataView(e),n=new TextDecoder;return this._decodeBroadcast(e,r,n)}_decodeBroadcast(e,r,n){const i=r.getUint8(1),a=r.getUint8(2);let c=this.HEADER_LENGTH+2;const d=n.decode(e.slice(c,c+i));c=c+i;const p=n.decode(e.slice(c,c+a));c=c+a;const l=JSON.parse(n.decode(e.slice(c,e.byteLength)));return{ref:null,topic:d,event:p,payload:l}}}class xbe{constructor(e,r){this.callback=e,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var _o;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(_o||(_o={}));const qae=(t,e,r={})=>{var n;const i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((a,c)=>(a[c]=E8e(c,t,e,i),a),{})},E8e=(t,e,r,n)=>{const i=e.find(d=>d.name===t),a=i==null?void 0:i.type,c=r[t];return a&&!n.includes(a)?_be(a,c):xG(c)},_be=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return I8e(e,r)}switch(t){case _o.bool:return T8e(e);case _o.float4:case _o.float8:case _o.int2:case _o.int4:case _o.int8:case _o.numeric:case _o.oid:return A8e(e);case _o.json:case _o.jsonb:return k8e(e);case _o.timestamp:return j8e(e);case _o.abstime:case _o.date:case _o.daterange:case _o.int4range:case _o.int8range:case _o.money:case _o.reltime:case _o.text:case _o.time:case _o.timestamptz:case _o.timetz:case _o.tsrange:case _o.tstzrange:return xG(e);default:return xG(e)}},xG=t=>t,T8e=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},A8e=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},k8e=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch(e){return console.log(`JSON parse error: ${e}`),t}return t},I8e=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let a;const c=t.slice(1,r);try{a=JSON.parse("["+c+"]")}catch{a=c?c.split(","):[]}return a.map(d=>_be(e,d))}return t},j8e=t=>typeof t=="string"?t.replace(" ","T"):t,vbe=t=>{let e=t;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class nU{constructor(e,r,n={},i=ybe){this.channel=e,this.event=r,this.payload=n,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var n;return this._hasReceived(e)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:r}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var Gae;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Gae||(Gae={}));class nj{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(r==null?void 0:r.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},i=>{const{onJoin:a,onLeave:c,onSync:d}=this.caller;this.joinRef=this.channel._joinRef(),this.state=nj.syncState(this.state,i,a,c),this.pendingDiffs.forEach(p=>{this.state=nj.syncDiff(this.state,p,a,c)}),this.pendingDiffs=[],d()}),this.channel._on(n.diff,{},i=>{const{onJoin:a,onLeave:c,onSync:d}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=nj.syncDiff(this.state,i,a,c),d())}),this.onJoin((i,a,c)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:a,newPresences:c})}),this.onLeave((i,a,c)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:a,leftPresences:c})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,n,i){const a=this.cloneDeep(e),c=this.transformState(r),d={},p={};return this.map(a,(l,g)=>{c[l]||(p[l]=g)}),this.map(c,(l,g)=>{const v=a[l];if(v){const E=g.map(C=>C.presence_ref),T=v.map(C=>C.presence_ref),j=g.filter(C=>T.indexOf(C.presence_ref)<0),P=v.filter(C=>E.indexOf(C.presence_ref)<0);j.length>0&&(d[l]=j),P.length>0&&(p[l]=P)}else d[l]=g}),this.syncDiff(a,{joins:d,leaves:p},n,i)}static syncDiff(e,r,n,i){const{joins:a,leaves:c}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),i||(i=()=>{}),this.map(a,(d,p)=>{var l;const g=(l=e[d])!==null&&l!==void 0?l:[];if(e[d]=this.cloneDeep(p),g.length>0){const v=e[d].map(T=>T.presence_ref),E=g.filter(T=>v.indexOf(T.presence_ref)<0);e[d].unshift(...E)}n(d,g,p)}),this.map(c,(d,p)=>{let l=e[d];if(!l)return;const g=p.map(v=>v.presence_ref);l=l.filter(v=>g.indexOf(v.presence_ref)<0),e[d]=l,i(d,l,p),l.length===0&&delete e[d]}),e}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{const i=e[n];return"metas"in i?r[n]=i.metas.map(a=>(a.presence_ref=a.phx_ref,delete a.phx_ref,delete a.phx_ref_prev,a)):r[n]=i,r},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var Hae;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Hae||(Hae={}));var Wae;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Wae||(Wae={}));var yy;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(yy||(yy={}));class DK{constructor(e,r={config:{}},n){this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=Ed.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},r.config),this.timeout=this.socket.timeout,this.joinPush=new nU(this,Bm.join,this.params,this.timeout),this.rejoinTimer=new xbe(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Ed.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=Ed.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=Ed.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Ed.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Bm.reply,{},(i,a)=>{this._trigger(this._replyEventName(a),i)}),this.presence=new nj(this),this.broadcastEndpointURL=vbe(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(e,r=this.timeout){var n,i;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:a,presence:c,private:d}}=this.params;this._onError(g=>e==null?void 0:e(yy.CHANNEL_ERROR,g)),this._onClose(()=>e==null?void 0:e(yy.CLOSED));const p={},l={broadcast:a,presence:c,postgres_changes:(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(g=>g.filter))!==null&&i!==void 0?i:[],private:d};this.socket.accessTokenValue&&(p.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:l},p)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:g})=>{var v;if(this.socket.setAuth(),g===void 0){e==null||e(yy.SUBSCRIBED);return}else{const E=this.bindings.postgres_changes,T=(v=E==null?void 0:E.length)!==null&&v!==void 0?v:0,j=[];for(let P=0;P{this.state=Ed.errored,e==null||e(yy.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(g).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(yy.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){return this._on(e,r,n)}async send(e,r={}){var n,i;if(!this._canPush()&&e.type==="broadcast"){const{event:a,payload:c}=e,p={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:c,private:this.private}]})};try{const l=await this._fetchWithTimeout(this.broadcastEndpointURL,p,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=l.body)===null||i===void 0?void 0:i.cancel()),l.ok?"ok":"error"}catch(l){return l.name==="AbortError"?"timed out":"error"}}else return new Promise(a=>{var c,d,p;const l=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((p=(d=(c=this.params)===null||c===void 0?void 0:c.config)===null||d===void 0?void 0:d.broadcast)===null||p===void 0)&&p.ack)&&a("ok"),l.receive("ok",()=>a("ok")),l.receive("error",()=>a("error")),l.receive("timeout",()=>a("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=Ed.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Bm.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(n=>{const i=new nU(this,Bm.leave,{},e);i.receive("ok",()=>{r(),n("ok")}).receive("timeout",()=>{r(),n("timed out")}).receive("error",()=>{n("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.rejoinTimer&&clearTimeout(this.rejoinTimer.timer),this.joinPush.destroy()}async _fetchWithTimeout(e,r,n){const i=new AbortController,a=setTimeout(()=>i.abort(),n),c=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(a),c}_push(e,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new nU(this,e,r,n);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,r,n){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,n){var i,a;const c=e.toLocaleLowerCase(),{close:d,error:p,leave:l,join:g}=Bm;if(n&&[d,p,l,g].indexOf(c)>=0&&n!==this._joinRef())return;let E=this._onMessage(c,r,n);if(r&&!E)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(c)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(T=>{var j,P,C;return((j=T.filter)===null||j===void 0?void 0:j.event)==="*"||((C=(P=T.filter)===null||P===void 0?void 0:P.event)===null||C===void 0?void 0:C.toLocaleLowerCase())===c}).map(T=>T.callback(E,n)):(a=this.bindings[c])===null||a===void 0||a.filter(T=>{var j,P,C,L,O,F;if(["broadcast","presence","postgres_changes"].includes(c))if("id"in T){const $=T.id,G=(j=T.filter)===null||j===void 0?void 0:j.event;return $&&((P=r.ids)===null||P===void 0?void 0:P.includes($))&&(G==="*"||(G==null?void 0:G.toLocaleLowerCase())===((C=r.data)===null||C===void 0?void 0:C.type.toLocaleLowerCase()))}else{const $=(O=(L=T==null?void 0:T.filter)===null||L===void 0?void 0:L.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return $==="*"||$===((F=r==null?void 0:r.event)===null||F===void 0?void 0:F.toLocaleLowerCase())}else return T.type.toLocaleLowerCase()===c}).map(T=>{if(typeof E=="object"&&"ids"in E){const j=E.data,{schema:P,table:C,commit_timestamp:L,type:O,errors:F}=j;E=Object.assign(Object.assign({},{schema:P,table:C,commit_timestamp:L,eventType:O,new:{},old:{},errors:F}),this._getPayloadRecords(j))}T.callback(E,n)})}_isClosed(){return this.state===Ed.closed}_isJoined(){return this.state===Ed.joined}_isJoining(){return this.state===Ed.joining}_isLeaving(){return this.state===Ed.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,n){const i=e.toLocaleLowerCase(),a={type:i,filter:r,callback:n};return this.bindings[i]?this.bindings[i].push(a):this.bindings[i]=[a],this}_off(e,r){const n=e.toLocaleLowerCase();return this.bindings[n]=this.bindings[n].filter(i=>{var a;return!(((a=i.type)===null||a===void 0?void 0:a.toLocaleLowerCase())===n&&DK.isEqual(i.filter,r))}),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(const n in e)if(e[n]!==r[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Bm.close,{},e)}_onError(e){this._on(Bm.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Ed.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=qae(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=qae(e.columns,e.old_record)),r}}const Kae=()=>{},C8e=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class P8e{constructor(e,r){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=v8e,this.params={},this.timeout=ybe,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Kae,this.ref=0,this.logger=Kae,this.conn=null,this.sendBuffer=[],this.serializer=new S8e,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=a=>{let c;return a?c=a:typeof fetch>"u"?c=(...d)=>Ge(async()=>{const{default:p}=await Promise.resolve().then(()=>pA);return{default:p}},void 0).then(({default:p})=>p(...d)):c=fetch,(...d)=>c(...d)},this.endPoint=`${e}/${yG.websocket}`,this.httpEndpoint=vbe(e),r!=null&&r.transport?this.transport=r.transport:this.transport=null,r!=null&&r.params&&(this.params=r.params),r!=null&&r.headers&&(this.headers=Object.assign(Object.assign({},this.headers),r.headers)),r!=null&&r.timeout&&(this.timeout=r.timeout),r!=null&&r.logger&&(this.logger=r.logger),(r!=null&&r.logLevel||r!=null&&r.log_level)&&(this.logLevel=r.logLevel||r.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),r!=null&&r.heartbeatIntervalMs&&(this.heartbeatIntervalMs=r.heartbeatIntervalMs);const i=(n=r==null?void 0:r.params)===null||n===void 0?void 0:n.apikey;if(i&&(this.accessTokenValue=i,this.apiKey=i),this.reconnectAfterMs=r!=null&&r.reconnectAfterMs?r.reconnectAfterMs:a=>[1e3,2e3,5e3,1e4][a-1]||1e4,this.encode=r!=null&&r.encode?r.encode:(a,c)=>c(JSON.stringify(a)),this.decode=r!=null&&r.decode?r.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new xbe(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(r==null?void 0:r.fetch),r!=null&&r.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(r==null?void 0:r.worker)||!1,this.workerUrl=r==null?void 0:r.workerUrl}this.accessToken=(r==null?void 0:r.accessToken)||null}connect(){if(!this.conn){if(this.transport||(this.transport=gG),this.transport){typeof window<"u"&&this.transport===window.WebSocket?this.conn=new this.transport(this.endpointURL()):this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection();return}this.conn=new N8e(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:b8e}))}disconnect(e,r){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,r??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset(),this.channels.forEach(n=>n.teardown()))}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return this.channels=this.channels.filter(n=>n._joinRef!==e._joinRef),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const e=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,r,n){this.logger(e,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case TE.connecting:return bb.Connecting;case TE.open:return bb.Open;case TE.closing:return bb.Closing;default:return bb.Closed}}isConnected(){return this.connectionState()===bb.Open}channel(e,r={config:{}}){const n=`realtime:${e}`,i=this.getChannels().find(a=>a.topic===n);if(i)return i;{const a=new DK(`realtime:${e}`,r,this);return this.channels.push(a),a}}push(e){const{topic:r,event:n,payload:i,ref:a}=e,c=()=>{this.encode(e,d=>{var p;(p=this.conn)===null||p===void 0||p.send(d)})};this.log("push",`${r} ${n} (${a})`,i),this.isConnected()?c():this.sendBuffer.push(c)}async setAuth(e=null){let r=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{r&&n.updateJoinPayload({access_token:r,version:this.headers&&this.headers["X-Client-Info"]}),n.joinedOnce&&n._isJoined()&&n._push(Bm.access_token,{access_token:r})}))}async sendHeartbeat(){var e;if(!this.isConnected()){this.heartbeatCallback("disconnected");return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.heartbeatCallback("timeout"),(e=this.conn)===null||e===void 0||e.close(w8e,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatCallback("sent"),await this.setAuth()}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let r=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${e}"`),r.unsubscribe())}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_onConnMessage(e){this.decode(e.data,r=>{let{topic:n,event:i,payload:a,ref:c}=r;n==="phoenix"&&i==="phx_reply"&&this.heartbeatCallback(r.payload.status=="ok"?"ok":"error"),c&&c===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${a.status||""} ${n} ${i} ${c&&"("+c+")"||""}`,a),Array.from(this.channels).filter(d=>d._isMember(n)).forEach(d=>d._trigger(i,a,c)),this.stateChangeCallbacks.message.forEach(d=>d(r))})}_onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else{this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this.workerRef.terminate()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(r=>r(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(r=>r(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(Bm.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;const n=e.match(/\?/)?"&":"?",i=new URLSearchParams(r);return`${e}${n}${i}`}_workerObjectUrl(e){let r;if(e)r=e;else{const n=new Blob([C8e],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}}class N8e{constructor(e,r,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=TE.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}}class MK extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function Xc(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}class R8e extends MK{constructor(e,r){super(e),this.name="StorageApiError",this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class _G extends MK{constructor(e,r){super(e),this.name="StorageUnknownError",this.originalError=r}}var L8e=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(c){c(a)})}return new(r||(r=Promise))(function(a,c){function d(g){try{l(n.next(g))}catch(v){c(v)}}function p(g){try{l(n.throw(g))}catch(v){c(v)}}function l(g){g.done?a(g.value):i(g.value).then(d,p)}l((n=n.apply(t,e||[])).next())})};const bbe=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Ge(async()=>{const{default:n}=await Promise.resolve().then(()=>pA);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},D8e=()=>L8e(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Ge(()=>Promise.resolve().then(()=>pA),void 0)).Response:Response}),vG=t=>{if(Array.isArray(t))return t.map(r=>vG(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,n])=>{const i=r.replace(/([-_][a-z])/gi,a=>a.toUpperCase().replace(/[-_]/g,""));e[i]=vG(n)}),e};var Sw=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(c){c(a)})}return new(r||(r=Promise))(function(a,c){function d(g){try{l(n.next(g))}catch(v){c(v)}}function p(g){try{l(n.throw(g))}catch(v){c(v)}}function l(g){g.done?a(g.value):i(g.value).then(d,p)}l((n=n.apply(t,e||[])).next())})};const iU=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),M8e=(t,e,r)=>Sw(void 0,void 0,void 0,function*(){const n=yield D8e();t instanceof n&&!(r!=null&&r.noResolveJson)?t.json().then(i=>{e(new R8e(iU(i),t.status||500))}).catch(i=>{e(new _G(iU(i),i))}):e(new _G(iU(t),t))}),O8e=(t,e,r,n)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),n&&(i.body=JSON.stringify(n)),Object.assign(Object.assign({},i),r))};function zP(t,e,r,n,i,a){return Sw(this,void 0,void 0,function*(){return new Promise((c,d)=>{t(r,O8e(e,n,i,a)).then(p=>{if(!p.ok)throw p;return n!=null&&n.noResolveJson?p:p.json()}).then(p=>c(p)).catch(p=>M8e(p,d,n))})})}function pF(t,e,r,n){return Sw(this,void 0,void 0,function*(){return zP(t,"GET",e,r,n)})}function j_(t,e,r,n,i){return Sw(this,void 0,void 0,function*(){return zP(t,"POST",e,n,i,r)})}function F8e(t,e,r,n,i){return Sw(this,void 0,void 0,function*(){return zP(t,"PUT",e,n,i,r)})}function B8e(t,e,r,n){return Sw(this,void 0,void 0,function*(){return zP(t,"HEAD",e,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function wbe(t,e,r,n,i){return Sw(this,void 0,void 0,function*(){return zP(t,"DELETE",e,n,i,r)})}var th=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(c){c(a)})}return new(r||(r=Promise))(function(a,c){function d(g){try{l(n.next(g))}catch(v){c(v)}}function p(g){try{l(n.throw(g))}catch(v){c(v)}}function l(g){g.done?a(g.value):i(g.value).then(d,p)}l((n=n.apply(t,e||[])).next())})};const z8e={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Yae={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class $8e{constructor(e,r={},n,i){this.url=e,this.headers=r,this.bucketId=n,this.fetch=bbe(i)}uploadOrUpdate(e,r,n,i){return th(this,void 0,void 0,function*(){try{let a;const c=Object.assign(Object.assign({},Yae),i);let d=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(c.upsert)});const p=c.metadata;typeof Blob<"u"&&n instanceof Blob?(a=new FormData,a.append("cacheControl",c.cacheControl),p&&a.append("metadata",this.encodeMetadata(p)),a.append("",n)):typeof FormData<"u"&&n instanceof FormData?(a=n,a.append("cacheControl",c.cacheControl),p&&a.append("metadata",this.encodeMetadata(p))):(a=n,d["cache-control"]=`max-age=${c.cacheControl}`,d["content-type"]=c.contentType,p&&(d["x-metadata"]=this.toBase64(this.encodeMetadata(p)))),i!=null&&i.headers&&(d=Object.assign(Object.assign({},d),i.headers));const l=this._removeEmptyFolders(r),g=this._getFinalPath(l),v=yield this.fetch(`${this.url}/object/${g}`,Object.assign({method:e,body:a,headers:d},c!=null&&c.duplex?{duplex:c.duplex}:{})),E=yield v.json();return v.ok?{data:{path:l,id:E.Id,fullPath:E.Key},error:null}:{data:null,error:E}}catch(a){if(Xc(a))return{data:null,error:a};throw a}})}upload(e,r,n){return th(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,r,n)})}uploadToSignedUrl(e,r,n,i){return th(this,void 0,void 0,function*(){const a=this._removeEmptyFolders(e),c=this._getFinalPath(a),d=new URL(this.url+`/object/upload/sign/${c}`);d.searchParams.set("token",r);try{let p;const l=Object.assign({upsert:Yae.upsert},i),g=Object.assign(Object.assign({},this.headers),{"x-upsert":String(l.upsert)});typeof Blob<"u"&&n instanceof Blob?(p=new FormData,p.append("cacheControl",l.cacheControl),p.append("",n)):typeof FormData<"u"&&n instanceof FormData?(p=n,p.append("cacheControl",l.cacheControl)):(p=n,g["cache-control"]=`max-age=${l.cacheControl}`,g["content-type"]=l.contentType);const v=yield this.fetch(d.toString(),{method:"PUT",body:p,headers:g}),E=yield v.json();return v.ok?{data:{path:a,fullPath:E.Key},error:null}:{data:null,error:E}}catch(p){if(Xc(p))return{data:null,error:p};throw p}})}createSignedUploadUrl(e,r){return th(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e);const i=Object.assign({},this.headers);r!=null&&r.upsert&&(i["x-upsert"]="true");const a=yield j_(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:i}),c=new URL(this.url+a.url),d=c.searchParams.get("token");if(!d)throw new MK("No token returned by API");return{data:{signedUrl:c.toString(),path:e,token:d},error:null}}catch(n){if(Xc(n))return{data:null,error:n};throw n}})}update(e,r,n){return th(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,r,n)})}move(e,r,n){return th(this,void 0,void 0,function*(){try{return{data:yield j_(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(i){if(Xc(i))return{data:null,error:i};throw i}})}copy(e,r,n){return th(this,void 0,void 0,function*(){try{return{data:{path:(yield j_(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:r,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(i){if(Xc(i))return{data:null,error:i};throw i}})}createSignedUrl(e,r,n){return th(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),a=yield j_(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:r},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers});const c=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return a={signedUrl:encodeURI(`${this.url}${a.signedURL}${c}`)},{data:a,error:null}}catch(i){if(Xc(i))return{data:null,error:i};throw i}})}createSignedUrls(e,r,n){return th(this,void 0,void 0,function*(){try{const i=yield j_(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:r,paths:e},{headers:this.headers}),a=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:i.map(c=>Object.assign(Object.assign({},c),{signedUrl:c.signedURL?encodeURI(`${this.url}${c.signedURL}${a}`):null})),error:null}}catch(i){if(Xc(i))return{data:null,error:i};throw i}})}download(e,r){return th(this,void 0,void 0,function*(){const i=typeof(r==null?void 0:r.transform)<"u"?"render/image/authenticated":"object",a=this.transformOptsToQueryString((r==null?void 0:r.transform)||{}),c=a?`?${a}`:"";try{const d=this._getFinalPath(e);return{data:yield(yield pF(this.fetch,`${this.url}/${i}/${d}${c}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(d){if(Xc(d))return{data:null,error:d};throw d}})}info(e){return th(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{const n=yield pF(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:vG(n),error:null}}catch(n){if(Xc(n))return{data:null,error:n};throw n}})}exists(e){return th(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{return yield B8e(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(Xc(n)&&n instanceof _G){const i=n.originalError;if([400,404].includes(i==null?void 0:i.status))return{data:!1,error:n}}throw n}})}getPublicUrl(e,r){const n=this._getFinalPath(e),i=[],a=r!=null&&r.download?`download=${r.download===!0?"":r.download}`:"";a!==""&&i.push(a);const d=typeof(r==null?void 0:r.transform)<"u"?"render/image":"object",p=this.transformOptsToQueryString((r==null?void 0:r.transform)||{});p!==""&&i.push(p);let l=i.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${d}/public/${n}${l}`)}}}remove(e){return th(this,void 0,void 0,function*(){try{return{data:yield wbe(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(r){if(Xc(r))return{data:null,error:r};throw r}})}list(e,r,n){return th(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},z8e),r),{prefix:e||""});return{data:yield j_(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},n),error:null}}catch(i){if(Xc(i))return{data:null,error:i};throw i}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const r=[];return e.width&&r.push(`width=${e.width}`),e.height&&r.push(`height=${e.height}`),e.resize&&r.push(`resize=${e.resize}`),e.format&&r.push(`format=${e.format}`),e.quality&&r.push(`quality=${e.quality}`),r.join("&")}}const U8e="2.7.1",V8e={"X-Client-Info":`storage-js/${U8e}`};var bS=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(c){c(a)})}return new(r||(r=Promise))(function(a,c){function d(g){try{l(n.next(g))}catch(v){c(v)}}function p(g){try{l(n.throw(g))}catch(v){c(v)}}function l(g){g.done?a(g.value):i(g.value).then(d,p)}l((n=n.apply(t,e||[])).next())})};class q8e{constructor(e,r={},n){this.url=e,this.headers=Object.assign(Object.assign({},V8e),r),this.fetch=bbe(n)}listBuckets(){return bS(this,void 0,void 0,function*(){try{return{data:yield pF(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(Xc(e))return{data:null,error:e};throw e}})}getBucket(e){return bS(this,void 0,void 0,function*(){try{return{data:yield pF(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(r){if(Xc(r))return{data:null,error:r};throw r}})}createBucket(e,r={public:!1}){return bS(this,void 0,void 0,function*(){try{return{data:yield j_(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(Xc(n))return{data:null,error:n};throw n}})}updateBucket(e,r){return bS(this,void 0,void 0,function*(){try{return{data:yield F8e(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(Xc(n))return{data:null,error:n};throw n}})}emptyBucket(e){return bS(this,void 0,void 0,function*(){try{return{data:yield j_(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(Xc(r))return{data:null,error:r};throw r}})}deleteBucket(e){return bS(this,void 0,void 0,function*(){try{return{data:yield wbe(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(r){if(Xc(r))return{data:null,error:r};throw r}})}}class G8e extends q8e{constructor(e,r={},n){super(e,r,n)}from(e){return new $8e(this.url,this.headers,e,this.fetch)}}const H8e="2.49.10";let MI="";typeof Deno<"u"?MI="deno":typeof document<"u"?MI="web":typeof navigator<"u"&&navigator.product==="ReactNative"?MI="react-native":MI="node";const W8e={"X-Client-Info":`supabase-js-${MI}/${H8e}`},K8e={headers:W8e},Y8e={schema:"public"},Z8e={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},X8e={};var Q8e=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(c){c(a)})}return new(r||(r=Promise))(function(a,c){function d(g){try{l(n.next(g))}catch(v){c(v)}}function p(g){try{l(n.throw(g))}catch(v){c(v)}}function l(g){g.done?a(g.value):i(g.value).then(d,p)}l((n=n.apply(t,e||[])).next())})};const J8e=t=>{let e;return t?e=t:typeof fetch>"u"?e=abe:e=fetch,(...r)=>e(...r)},eqe=()=>typeof Headers>"u"?obe:Headers,tqe=(t,e,r)=>{const n=J8e(r),i=eqe();return(a,c)=>Q8e(void 0,void 0,void 0,function*(){var d;const p=(d=yield e())!==null&&d!==void 0?d:t;let l=new i(c==null?void 0:c.headers);return l.has("apikey")||l.set("apikey",t),l.has("Authorization")||l.set("Authorization",`Bearer ${p}`),n(a,Object.assign(Object.assign({},c),{headers:l}))})};var rqe=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(c){c(a)})}return new(r||(r=Promise))(function(a,c){function d(g){try{l(n.next(g))}catch(v){c(v)}}function p(g){try{l(n.throw(g))}catch(v){c(v)}}function l(g){g.done?a(g.value):i(g.value).then(d,p)}l((n=n.apply(t,e||[])).next())})};function nqe(t){return t.endsWith("/")?t:t+"/"}function iqe(t,e){var r,n;const{db:i,auth:a,realtime:c,global:d}=t,{db:p,auth:l,realtime:g,global:v}=e,E={db:Object.assign(Object.assign({},p),i),auth:Object.assign(Object.assign({},l),a),realtime:Object.assign(Object.assign({},g),c),global:Object.assign(Object.assign(Object.assign({},v),d),{headers:Object.assign(Object.assign({},(r=v==null?void 0:v.headers)!==null&&r!==void 0?r:{}),(n=d==null?void 0:d.headers)!==null&&n!==void 0?n:{})}),accessToken:()=>rqe(this,void 0,void 0,function*(){return""})};return t.accessToken?E.accessToken=t.accessToken:delete E.accessToken,E}const Sbe="2.69.1",BS=30*1e3,bG=3,sU=bG*BS,sqe="http://localhost:9999",aqe="supabase.auth.token",oqe={"X-Client-Info":`gotrue-js/${Sbe}`},wG="X-Supabase-Api-Version",Ebe={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},lqe=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,cqe=6e5;class OK extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function us(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class uqe extends OK{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function dqe(t){return us(t)&&t.name==="AuthApiError"}class Tbe extends OK{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class $v extends OK{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n}}class S_ extends $v{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function hqe(t){return us(t)&&t.name==="AuthSessionMissingError"}class aU extends $v{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class yD extends $v{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class xD extends $v{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function fqe(t){return us(t)&&t.name==="AuthImplicitGrantRedirectError"}class Zae extends $v{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class SG extends $v{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function oU(t){return us(t)&&t.name==="AuthRetryableFetchError"}class Xae extends $v{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class ij extends $v{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Qae="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Jae=` \r=`.split(""),mqe=(()=>{const t=new Array(128);for(let e=0;e-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function eoe(t){const e=[],r=c=>{e.push(String.fromCodePoint(c))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},a=c=>{yqe(c,n,r)};for(let c=0;c>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function gqe(t,e){for(let r=0;r55295&&n<=56319){const i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}pqe(n,e)}}function yqe(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if(!(t>>7-n&1)){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function xqe(t){const e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};for(let i=0;ie.push(r)),new Uint8Array(e)}function vqe(t){return Math.round(Date.now()/1e3)+t}function bqe(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=Math.random()*16|0;return(t=="x"?e:e&3|8).toString(16)})}const Mp=()=>typeof window<"u"&&typeof document<"u",rb={tested:!1,writable:!1},sj=()=>{if(!Mp())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(rb.tested)return rb.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),rb.tested=!0,rb.writable=!0}catch{rb.tested=!0,rb.writable=!1}return rb.writable};function wqe(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,a)=>{e[a]=i})}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n}),e}const kbe=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Ge(async()=>{const{default:n}=await Promise.resolve().then(()=>pA);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},Sqe=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Ibe=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},_D=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},vD=async(t,e)=>{await t.removeItem(e)};class n5{constructor(){this.promise=new n5.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}n5.promiseConstructor=Promise;function lU(t){const e=t.split(".");if(e.length!==3)throw new ij("Invalid JWT structure");for(let n=0;n{setTimeout(()=>e(null),t)})}function Tqe(t,e){return new Promise((n,i)=>{(async()=>{for(let a=0;a<1/0;a++)try{const c=await t(a);if(!e(a,null,c)){n(c);return}}catch(c){if(!e(a,c)){i(c);return}}})()})}function Aqe(t){return("0"+t.toString(16)).substr(-2)}function kqe(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length;let i="";for(let a=0;a<56;a++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,Aqe).join("")}async function Iqe(t){const r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(a=>String.fromCharCode(a)).join("")}async function jqe(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const r=await Iqe(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function wS(t,e,r=!1){const n=kqe();let i=n;r&&(i+="/PASSWORD_RECOVERY"),await Ibe(t,`${e}-code-verifier`,i);const a=await jqe(n);return[a,n===a?"plain":"s256"]}const Cqe=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Pqe(t){const e=t.headers.get(wG);if(!e||!e.match(Cqe))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Nqe(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Rqe(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Lqe=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);it.msg||t.message||t.error_description||t.error||JSON.stringify(t),Dqe=[502,503,504];async function toe(t){var e;if(!Sqe(t))throw new SG(mb(t),0);if(Dqe.includes(t.status))throw new SG(mb(t),t.status);let r;try{r=await t.json()}catch(a){throw new Tbe(mb(a),a)}let n;const i=Pqe(t);if(i&&i.getTime()>=Ebe["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Xae(mb(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new S_}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((a,c)=>a&&typeof c=="string",!0))throw new Xae(mb(r),t.status,r.weak_password.reasons);throw new uqe(mb(r),t.status||500,n)}const Mqe=(t,e,r,n)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r))};async function $s(t,e,r,n){var i;const a=Object.assign({},n==null?void 0:n.headers);a[wG]||(a[wG]=Ebe["2024-01-01"].name),n!=null&&n.jwt&&(a.Authorization=`Bearer ${n.jwt}`);const c=(i=n==null?void 0:n.query)!==null&&i!==void 0?i:{};n!=null&&n.redirectTo&&(c.redirect_to=n.redirectTo);const d=Object.keys(c).length?"?"+new URLSearchParams(c).toString():"",p=await Oqe(t,e,r+d,{headers:a,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(p):{data:Object.assign({},p),error:null}}async function Oqe(t,e,r,n,i,a){const c=Mqe(e,n,i,a);let d;try{d=await t(r,Object.assign({},c))}catch(p){throw console.error(p),new SG(mb(p),0)}if(d.ok||await toe(d),n!=null&&n.noResolveJson)return d;try{return await d.json()}catch(p){await toe(p)}}function E_(t){var e;let r=null;$qe(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=vqe(t.expires_in)));const n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function roe(t){const e=E_(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function O_(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Fqe(t){return{data:t,error:null}}function Bqe(t){const{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:a}=t,c=Lqe(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),d={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:a},p=Object.assign({},c);return{data:{properties:d,user:p},error:null}}function zqe(t){return t}function $qe(t){return t.access_token&&t.refresh_token&&t.expires_in}var Uqe=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i0&&(T.forEach(j=>{const P=parseInt(j.split(";")[0].split("=")[1].substring(0,1)),C=JSON.parse(j.split(";")[1].split("=")[1]);l[`${C}Page`]=P}),l.total=parseInt(E)),{data:Object.assign(Object.assign({},v),l),error:null}}catch(l){if(us(l))return{data:{users:[]},error:l};throw l}}async getUserById(e){try{return await $s(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:O_})}catch(r){if(us(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){try{return await $s(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:O_})}catch(n){if(us(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){try{return await $s(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:O_})}catch(n){if(us(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{const{data:r,error:n}=await $s(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:r,error:n}}catch(r){if(us(r))return{data:null,error:r};throw r}}async _deleteFactor(e){try{return{data:await $s(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(us(r))return{data:null,error:r};throw r}}}const qqe={getItem:t=>sj()?globalThis.localStorage.getItem(t):null,setItem:(t,e)=>{sj()&&globalThis.localStorage.setItem(t,e)},removeItem:t=>{sj()&&globalThis.localStorage.removeItem(t)}};function noe(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}function Gqe(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}const SS={debug:!!(globalThis&&sj()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class jbe extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Hqe extends jbe{}async function Wqe(t,e,r){SS.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),SS.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async i=>{if(i){SS.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{SS.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw SS.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Hqe(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(SS.debug)try{const a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}}))}Gqe();const Kqe={url:sqe,storageKey:aqe,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:oqe,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function ioe(t,e,r){return await r()}class tC{constructor(e){var r,n;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=tC.nextInstanceID,tC.nextInstanceID+=1,this.instanceID>0&&Mp()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const i=Object.assign(Object.assign({},Kqe),e);if(this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.persistSession=i.persistSession,this.storageKey=i.storageKey,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Vqe({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=kbe(i.fetch),this.lock=i.lock||ioe,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:Mp()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=Wqe:this.lock=ioe,this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?i.storage?this.storage=i.storage:sj()?this.storage=qqe:(this.memoryStorage={},this.storage=noe(this.memoryStorage)):(this.memoryStorage={},this.storage=noe(this.memoryStorage)),Mp()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a),await this._notifyAllSubscribers(a.data.event,a.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Sbe}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{const r=wqe(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),Mp()&&this.detectSessionInUrl&&n!=="none"){const{data:i,error:a}=await this._getSessionFromURL(r,n);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),fqe(a)){const p=(e=a.details)===null||e===void 0?void 0:e.code;if(p==="identity_already_exists"||p==="identity_not_found"||p==="single_identity_not_deletable")return{error:a}}return await this._removeSession(),{error:a}}const{session:c,redirectType:d}=i;return this._debug("#_initialize()","detected session in URL",c,"redirect type",d),await this._saveSession(c),setTimeout(async()=>{d==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",c):await this._notifyAllSubscribers("SIGNED_IN",c)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return us(r)?{error:r}:{error:new Tbe("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{const a=await $s(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}},xform:E_}),{data:c,error:d}=a;if(d||!c)return{data:{user:null,session:null},error:d};const p=c.session,l=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",p)),{data:{user:l,session:p},error:null}}catch(a){if(us(a))return{data:{user:null,session:null},error:a};throw a}}async signUp(e){var r,n,i;try{let a;if("email"in e){const{email:g,password:v,options:E}=e;let T=null,j=null;this.flowType==="pkce"&&([T,j]=await wS(this.storage,this.storageKey)),a=await $s(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:E==null?void 0:E.emailRedirectTo,body:{email:g,password:v,data:(r=E==null?void 0:E.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:E==null?void 0:E.captchaToken},code_challenge:T,code_challenge_method:j},xform:E_})}else if("phone"in e){const{phone:g,password:v,options:E}=e;a=await $s(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:g,password:v,data:(n=E==null?void 0:E.data)!==null&&n!==void 0?n:{},channel:(i=E==null?void 0:E.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:E==null?void 0:E.captchaToken}},xform:E_})}else throw new yD("You must provide either an email or phone number and a password");const{data:c,error:d}=a;if(d||!c)return{data:{user:null,session:null},error:d};const p=c.session,l=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",p)),{data:{user:l,session:p},error:null}}catch(a){if(us(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithPassword(e){try{let r;if("email"in e){const{email:a,password:c,options:d}=e;r=await $s(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:c,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:roe})}else if("phone"in e){const{phone:a,password:c,options:d}=e;r=await $s(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:c,gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:roe})}else throw new yD("You must provide either an email or phone number and a password");const{data:n,error:i}=r;return i?{data:{user:null,session:null},error:i}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new aU}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(us(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOAuth(e){var r,n,i,a;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){const r=await _D(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{const{data:a,error:c}=await $s(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:E_});if(await vD(this.storage,`${this.storageKey}-code-verifier`),c)throw c;return!a||!a.session||!a.user?{data:{user:null,session:null,redirectType:null},error:new aU}:(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:Object.assign(Object.assign({},a),{redirectType:i??null}),error:c})}catch(a){if(us(a))return{data:{user:null,session:null,redirectType:null},error:a};throw a}}async signInWithIdToken(e){try{const{options:r,provider:n,token:i,access_token:a,nonce:c}=e,d=await $s(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:a,nonce:c,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:E_}),{data:p,error:l}=d;return l?{data:{user:null,session:null},error:l}:!p||!p.session||!p.user?{data:{user:null,session:null},error:new aU}:(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("SIGNED_IN",p.session)),{data:p,error:l})}catch(r){if(us(r))return{data:{user:null,session:null},error:r};throw r}}async signInWithOtp(e){var r,n,i,a,c;try{if("email"in e){const{email:d,options:p}=e;let l=null,g=null;this.flowType==="pkce"&&([l,g]=await wS(this.storage,this.storageKey));const{error:v}=await $s(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:d,data:(r=p==null?void 0:p.data)!==null&&r!==void 0?r:{},create_user:(n=p==null?void 0:p.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken},code_challenge:l,code_challenge_method:g},redirectTo:p==null?void 0:p.emailRedirectTo});return{data:{user:null,session:null},error:v}}if("phone"in e){const{phone:d,options:p}=e,{data:l,error:g}=await $s(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:d,data:(i=p==null?void 0:p.data)!==null&&i!==void 0?i:{},create_user:(a=p==null?void 0:p.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken},channel:(c=p==null?void 0:p.channel)!==null&&c!==void 0?c:"sms"}});return{data:{user:null,session:null,messageId:l==null?void 0:l.message_id},error:g}}throw new yD("You must provide either an email or phone number.")}catch(d){if(us(d))return{data:{user:null,session:null},error:d};throw d}}async verifyOtp(e){var r,n;try{let i,a;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,a=(n=e.options)===null||n===void 0?void 0:n.captchaToken);const{data:c,error:d}=await $s(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:i,xform:E_});if(d)throw d;if(!c)throw new Error("An error occurred on token verification.");const p=c.session,l=c.user;return p!=null&&p.access_token&&(await this._saveSession(p),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",p)),{data:{user:l,session:p},error:null}}catch(i){if(us(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var r,n,i;try{let a=null,c=null;return this.flowType==="pkce"&&([a,c]=await wS(this.storage,this.storageKey)),await $s(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:c}),headers:this.headers,xform:Fqe})}catch(a){if(us(a))return{data:null,error:a};throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new S_;const{error:i}=await $s(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(us(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:n,type:i,options:a}=e,{error:c}=await $s(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},redirectTo:a==null?void 0:a.emailRedirectTo});return{data:{user:null,session:null},error:c}}else if("phone"in e){const{phone:n,type:i,options:a}=e,{data:c,error:d}=await $s(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:d}}throw new yD("You must provide either an email or phone number and a type")}catch(r){if(us(r))return{data:{user:null,session:null},error:r};throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await _D(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=e.expires_at?e.expires_at*1e3-Date.now()(!c&&l==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),c=!0,this.suppressGetSessionWarning=!0),Reflect.get(p,l,g))})}return{data:{session:e},error:null}}const{session:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?{data:{session:null},error:a}:{data:{session:i},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await $s(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:O_}):await this._useSession(async r=>{var n,i,a;const{data:c,error:d}=r;if(d)throw d;return!(!((n=c.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new S_}:await $s(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(i=c.session)===null||i===void 0?void 0:i.access_token)!==null&&a!==void 0?a:void 0,xform:O_})})}catch(r){if(us(r))return hqe(r)&&(await this._removeSession(),await vD(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:r};throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{const{data:i,error:a}=n;if(a)throw a;if(!i.session)throw new S_;const c=i.session;let d=null,p=null;this.flowType==="pkce"&&e.email!=null&&([d,p]=await wS(this.storage,this.storageKey));const{data:l,error:g}=await $s(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:d,code_challenge_method:p}),jwt:c.access_token,xform:O_});if(g)throw g;return c.user=l.user,await this._saveSession(c),await this._notifyAllSubscribers("USER_UPDATED",c),{data:{user:c.user},error:null}})}catch(n){if(us(n))return{data:{user:null},error:n};throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new S_;const r=Date.now()/1e3;let n=r,i=!0,a=null;const{payload:c}=lU(e.access_token);if(c.exp&&(n=c.exp,i=n<=r),i){const{session:d,error:p}=await this._callRefreshToken(e.refresh_token);if(p)return{data:{user:null,session:null},error:p};if(!d)return{data:{user:null,session:null},error:null};a=d}else{const{data:d,error:p}=await this._getUser(e.access_token);if(p)throw p;a={access_token:e.access_token,refresh_token:e.refresh_token,user:d.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return{data:{user:a.user,session:a},error:null}}catch(r){if(us(r))return{data:{session:null,user:null},error:r};throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){const{data:c,error:d}=r;if(d)throw d;e=(n=c.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new S_;const{session:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?{data:{user:null,session:null},error:a}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(r){if(us(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(e,r){try{if(!Mp())throw new xD("No browser detected.");if(e.error||e.error_description||e.error_code)throw new xD(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new Zae("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new xD("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Zae("No code detected.");const{data:O,error:F}=await this._exchangeCodeForSession(e.code);if(F)throw F;const $=new URL(window.location.href);return $.searchParams.delete("code"),window.history.replaceState(window.history.state,"",$.toString()),{data:{session:O.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:a,refresh_token:c,expires_in:d,expires_at:p,token_type:l}=e;if(!a||!d||!c||!l)throw new xD("No session defined in URL");const g=Math.round(Date.now()/1e3),v=parseInt(d);let E=g+v;p&&(E=parseInt(p));const T=E-g;T*1e3<=BS&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${T}s, should have been closer to ${v}s`);const j=E-v;g-j>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",j,E,g):g-j<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",j,E,g);const{data:P,error:C}=await this._getUser(a);if(C)throw C;const L={provider_token:n,provider_refresh_token:i,access_token:a,expires_in:v,expires_at:E,refresh_token:c,token_type:l,user:P.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:L,redirectType:e.type},error:null}}catch(n){if(us(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await _D(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a)return{error:a};const c=(n=i.session)===null||n===void 0?void 0:n.access_token;if(c){const{error:d}=await this.admin.signOut(c,e);if(d&&!(dqe(d)&&(d.status===404||d.status===401||d.status===403)))return{error:d}}return e!=="others"&&(await this._removeSession(),await vD(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const r=bqe(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{const{data:{session:a},error:c}=r;if(c)throw c;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",a),console.error(a)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await wS(this.storage,this.storageKey,!0));try{return await $s(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(a){if(us(a))return{data:null,error:a};throw a}}async getUserIdentities(){var e;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(r){if(us(r))return{data:null,error:r};throw r}}async linkIdentity(e){var r;try{const{data:n,error:i}=await this._useSession(async a=>{var c,d,p,l,g;const{data:v,error:E}=a;if(E)throw E;const T=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(c=e.options)===null||c===void 0?void 0:c.redirectTo,scopes:(d=e.options)===null||d===void 0?void 0:d.scopes,queryParams:(p=e.options)===null||p===void 0?void 0:p.queryParams,skipBrowserRedirect:!0});return await $s(this.fetch,"GET",T,{headers:this.headers,jwt:(g=(l=v.session)===null||l===void 0?void 0:l.access_token)!==null&&g!==void 0?g:void 0})});if(i)throw i;return Mp()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),{data:{provider:e.provider,url:n==null?void 0:n.url},error:null}}catch(n){if(us(n))return{data:{provider:e.provider,url:null},error:n};throw n}}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;const{data:a,error:c}=r;if(c)throw c;return await $s(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(us(r))return{data:null,error:r};throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await Tqe(async i=>(i>0&&await Eqe(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await $s(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:E_})),(i,a)=>{const c=200*Math.pow(2,i);return a&&oU(a)&&Date.now()+c-n{try{await d.callback(e,r)}catch(p){a.push(p)}});if(await Promise.all(c),a.length>0){for(let d=0;dthis._autoRefreshTokenTick(),BS);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((n.expires_at*1e3-e)/BS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${BS}ms, refresh threshold is ${bG} ticks`),i<=bG&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof jbe)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Mp()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){const i=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[a,c]=await wS(this.storage,this.storageKey),d=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(c)}`});i.push(d.toString())}if(n!=null&&n.queryParams){const a=new URLSearchParams(n.queryParams);i.push(a.toString())}return n!=null&&n.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;return a?{data:null,error:a}:await $s(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(us(r))return{data:null,error:r};throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;const{data:a,error:c}=r;if(c)return{data:null,error:c};const d=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:p,error:l}=await $s(this.fetch,"POST",`${this.url}/factors`,{body:d,headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return l?{data:null,error:l}:(e.factorType==="totp"&&(!((i=p==null?void 0:p.totp)===null||i===void 0)&&i.qr_code)&&(p.totp.qr_code=`data:image/svg+xml;utf-8,${p.totp.qr_code}`),{data:p,error:null})})}catch(r){if(us(r))return{data:null,error:r};throw r}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a)return{data:null,error:a};const{data:c,error:d}=await $s(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return d?{data:null,error:d}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),{data:c,error:d})})}catch(r){if(us(r))return{data:null,error:r};throw r}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;return a?{data:null,error:a}:await $s(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(us(r))return{data:null,error:r};throw r}})}async _challengeAndVerify(e){const{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?{data:null,error:n}:await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){const{data:{user:e},error:r}=await this.getUser();if(r)return{data:null,error:r};const n=(e==null?void 0:e.factors)||[],i=n.filter(c=>c.factor_type==="totp"&&c.status==="verified"),a=n.filter(c=>c.factor_type==="phone"&&c.status==="verified");return{data:{all:n,totp:i,phone:a},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var r,n;const{data:{session:i},error:a}=e;if(a)return{data:null,error:a};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=lU(i.access_token);let d=null;c.aal&&(d=c.aal);let p=d;((n=(r=i.user.factors)===null||r===void 0?void 0:r.filter(v=>v.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(p="aal2");const g=c.amr||[];return{data:{currentLevel:d,nextLevel:p,currentAuthenticationMethods:g},error:null}}))}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(c=>c.kid===e);if(n||(n=this.jwks.keys.find(c=>c.kid===e),n&&this.jwks_cached_at+cqe>Date.now()))return n;const{data:i,error:a}=await $s(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;if(!i.keys||i.keys.length===0)throw new ij("JWKS is empty");if(this.jwks=i,this.jwks_cached_at=Date.now(),n=i.keys.find(c=>c.kid===e),!n)throw new ij("No matching signing key found in JWKS");return n}async getClaims(e,r={keys:[]}){try{let n=e;if(!n){const{data:T,error:j}=await this.getSession();if(j||!T.session)return{data:null,error:j};n=T.session.access_token}const{header:i,payload:a,signature:c,raw:{header:d,payload:p}}=lU(n);if(Nqe(a.exp),!i.kid||i.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:T}=await this.getUser(n);if(T)throw T;return{data:{claims:a,header:i,signature:c},error:null}}const l=Rqe(i.alg),g=await this.fetchJwk(i.kid,r),v=await crypto.subtle.importKey("jwk",g,l,!0,["verify"]);if(!await crypto.subtle.verify(l,v,c,_qe(`${d}.${p}`)))throw new ij("Invalid JWT signature");return{data:{claims:a,header:i,signature:c},error:null}}catch(n){if(us(n))return{data:null,error:n};throw n}}}tC.nextInstanceID=0;const Yqe=tC;class Zqe extends Yqe{constructor(e){super(e)}}var Xqe=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(c){c(a)})}return new(r||(r=Promise))(function(a,c){function d(g){try{l(n.next(g))}catch(v){c(v)}}function p(g){try{l(n.throw(g))}catch(v){c(v)}}function l(g){g.done?a(g.value):i(g.value).then(d,p)}l((n=n.apply(t,e||[])).next())})};class Qqe{constructor(e,r,n){var i,a,c;if(this.supabaseUrl=e,this.supabaseKey=r,!e)throw new Error("supabaseUrl is required.");if(!r)throw new Error("supabaseKey is required.");const d=nqe(e),p=new URL(d);this.realtimeUrl=new URL("realtime/v1",p),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",p),this.storageUrl=new URL("storage/v1",p),this.functionsUrl=new URL("functions/v1",p);const l=`sb-${p.hostname.split(".")[0]}-auth-token`,g={db:Y8e,realtime:X8e,auth:Object.assign(Object.assign({},Z8e),{storageKey:l}),global:K8e},v=iqe(n??{},g);this.storageKey=(i=v.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(a=v.global.headers)!==null&&a!==void 0?a:{},v.accessToken?(this.accessToken=v.accessToken,this.auth=new Proxy({},{get:(E,T)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(T)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((c=v.auth)!==null&&c!==void 0?c:{},this.headers,v.global.fetch),this.fetch=tqe(r,this._getAccessToken.bind(this),v.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},v.realtime)),this.rest=new x8e(new URL("rest/v1",p).href,{headers:this.headers,schema:v.db.schema,fetch:this.fetch}),v.accessToken||this._listenForAuthEvents()}get functions(){return new KVe(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new G8e(this.storageUrl.href,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,r={},n={}){return this.rest.rpc(e,r,n)}channel(e,r={config:{}}){return this.realtime.channel(e,r)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,r;return Xqe(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:n}=yield this.auth.getSession();return(r=(e=n.session)===null||e===void 0?void 0:e.access_token)!==null&&r!==void 0?r:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:r,detectSessionInUrl:n,storage:i,storageKey:a,flowType:c,lock:d,debug:p},l,g){const v={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Zqe({url:this.authUrl.href,headers:Object.assign(Object.assign({},v),l),storageKey:a,autoRefreshToken:e,persistSession:r,detectSessionInUrl:n,storage:i,flowType:c,lock:d,debug:p,fetch:g,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new P8e(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,n)=>{this._handleTokenChanged(r,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(e,r,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?this.changedAccessToken=n:e==="SIGNED_OUT"&&(this.realtime.setAuth(),r=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Jqe=(t,e,r)=>new Qqe(t,e,r),eGe="lovable-preview-auth:result";function tGe(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!==eGe||!("requestId"in t)||t.requestId!==e?null:{ok:"ok"in t&&!!t.ok,value:"value"in t&&typeof t.value=="string"?t.value:null}}function rGe(){var O,F;if(typeof window>"u")return;const t=location.hostname,r=["lovableproject.com","lovableproject-dev.com","lovable.app","gpt-eng.com","gptengineer.run"].some($=>t===$||t.endsWith("."+$)),n="[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",i=r?((O=new RegExp("^(?:id-preview(?:-[a-z0-9]+)?|project)--("+n+")(?:-dev)?(?=\\.|$)","i").exec(t))==null?void 0:O[1])??((F=new RegExp("^("+n+")(?=[.-])","i").exec(t))==null?void 0:F[1]):void 0,a=window.parent;if(!i||!(a!==null&&a!==window))return localStorage;const d=t.endsWith(".lovableproject-dev.com")||t.endsWith(".gpt-eng.com"),p=d?/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$|^http:\/\/localhost:3000$/:/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$/,l=location.ancestorOrigins,g=(l==null?void 0:l[0])??(document.referrer?new URL(document.referrer).origin:""),v=g&&p.test(g)?[g]:d?["https://lovable.dev","http://localhost:3000"]:["https://lovable.dev"],E=2e3,T=()=>Math.random().toString(36).slice(2)+Date.now().toString(36),j=($,G,W)=>new Promise(Z=>{const Q=T();let ee=!1;const ie=be=>{ee||(ee=!0,clearTimeout(pe),window.removeEventListener("message",oe),Z(be))},oe=be=>{if(!v.includes(be.origin))return;const Re=tGe(be.data,Q);Re&&ie(Re)};window.addEventListener("message",oe);const pe=setTimeout(()=>{ie(null)},E),Le={type:$,requestId:Q,projectId:i,key:G};W!==void 0&&(Le.value=W);for(const be of v)window.parent.postMessage(Le,be)});let P=!0;const C=250,L=$=>{try{return localStorage.getItem($)}catch{return}};return{getItem:async $=>{const G=L($);let W=await j("lovable-preview-auth:get",$,G??void 0);if(!W&&P&&(await new Promise(Z=>setTimeout(Z,C)),W=await j("lovable-preview-auth:get",$,G??void 0)),P=!1,W!=null&&W.ok&&W.value!==null){if(W.value==="")return G!==void 0&&L($)===G&&localStorage.removeItem($),null;if(G===null&&L($)===null)try{localStorage.setItem($,W.value)}catch{}return W.value}return localStorage.getItem($)},setItem:($,G)=>(localStorage.setItem($,G),j("lovable-preview-auth:set",$,G).then(W=>{W!=null&&W.ok&&W.value!==null&&localStorage.getItem($)===G&&(W.value===""?localStorage.removeItem($):localStorage.setItem($,W.value))})),removeItem:$=>{const G=L($);return localStorage.removeItem($),j("lovable-preview-auth:remove",$,G??void 0).then(()=>{})}}}const nGe="https://relzejiswnotikjgvjhz.supabase.co",iGe="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",Be=Jqe(nGe,iGe,{auth:{storage:rGe(),persistSession:!0,autoRefreshToken:!0}}),sKt=Object.freeze(Object.defineProperty({__proto__:null,supabase:Be},Symbol.toStringTag,{value:"Module"})),Cbe=N.createContext(void 0),sGe=({children:t})=>{const[e,r]=N.useState(null),[n,i]=N.useState(null),[a,c]=N.useState(!0),[d,p]=N.useState(!0),[l,g]=N.useState(!1),[v,E]=N.useState(!1),[T,j]=N.useState(!1),[P,C]=N.useState(null),[L,O]=N.useState([]),[F,$]=N.useState(null),G=N.useRef(null),W=N.useRef(!1),Z=N.useRef(!1),Q=qa(),ee=()=>{g(!1),E(!1),j(!1),C(null),O([]),$(null),G.current=null,W.current=!1},ie=async be=>{if(W.current&&G.current===be||Z.current)return;Z.current=!0,p(!0);const Re=window.setTimeout(()=>{console.warn("Role check timeout reached — unblocking UI."),Z.current=!1,p(!1)},8e3);try{console.log("Checking roles via RPC for user:",be);const[{data:Ie,error:Te},{data:ge,error:$e},{data:we,error:ke}]=await Promise.all([Be.rpc("has_role",{_user_id:be,_role:"admin"}),Be.rpc("has_role",{_user_id:be,_role:"brokerage_manager"}),Be.rpc("has_role",{_user_id:be,_role:"coach"})]);if(Te||$e)console.error("Role RPC errors:",{isAdminError:Te,isBrokerError:$e,isCoachError:ke}),g(!1),E(!1),j(!1);else{const ot=!!Ie,nt=!!ge,tt=!!we;console.log("RPC roles result:",{adminValue:ot,brokerValue:nt,coachValue:tt}),g(ot),E(nt),j(tt)}G.current=be,W.current=!0,window.clearTimeout(Re),p(!1);const{data:Ae,error:He}=await Be.from("profiles").select("brokerage_id, is_paused, paused_reason").eq("id",be).single();if(!He&&(Ae!=null&&Ae.is_paused)){const ot=Ae.paused_reason;try{sessionStorage.setItem("accountPausedReason",ot||"")}catch{}await Be.auth.signOut(),ee(),Q("/auth?paused=1",{replace:!0});return}if(C(!He&&Ae?Ae.brokerage_id:null),ge){console.log("Fetching managed brokerages for user:",be);const{data:ot,error:nt}=await Be.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",be);if(console.log("Managed brokerage assignments result:",{assignments:ot,assignmentsError:nt}),nt||!ot){console.error("Error fetching managed brokerage assignments:",nt),O([]);return}const tt=Array.from(new Set(ot.map(Bt=>Bt.brokerage_id).filter(Boolean)));if(tt.length===0){O([]);return}const{data:vt,error:Vt}=await Be.from("brokerages").select("id, name").in("id",tt);if(console.log("Managed brokerages details result:",{brokeragesData:vt,brokeragesError:Vt}),Vt||!vt){console.error("Error fetching managed brokerages details:",Vt),O([]);return}const Ct=vt.map(Bt=>({id:Bt.id,name:Bt.name})).sort((Bt,cr)=>tt.indexOf(Bt.id)-tt.indexOf(cr.id));console.log("Parsed managed brokerages:",Ct),O(Ct),Ct.length>0&&$(Bt=>Bt??Ct[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),O([]);G.current=be,W.current=!0}catch(Ie){console.error("Unexpected error in checkRoles:",Ie),ee()}finally{window.clearTimeout(Re),Z.current=!1,p(!1)}};N.useEffect(()=>{let be=!0,Re=!1;const Ie=()=>{!be||Re||(Re=!0,c(!1))},{data:{subscription:Te}}=Be.auth.onAuthStateChange(($e,we)=>{console.log("Auth event:",$e),be&&(i(we),r((we==null?void 0:we.user)??null),Ie(),$e==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{Q("/profile?reset=true")},100)),we!=null&&we.user?(!W.current||G.current!==we.user.id)&&setTimeout(()=>{ie(we.user.id)},0):(ee(),p(!1)))}),ge=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),Ie()},8e3);return()=>{be=!1,window.clearTimeout(ge),Te.unsubscribe()}},[]);const oe=async(be,Re)=>{var $e;const Ie=(be||"").trim().toLowerCase(),{data:Te,error:ge}=await Be.auth.signInWithPassword({email:Ie,password:Re});if(ge)throw lr.error(/invalid login credentials/i.test(ge.message)?`That email and password don't match an account. Check the email address, or use "Forgot password" to set a new password.`:ge.message),ge;if(($e=Te.user)!=null&&$e.id){const{data:we}=await Be.from("profiles").select("is_paused, paused_reason").eq("id",Te.user.id).maybeSingle();if(we!=null&&we.is_paused){const ke=we.paused_reason||"";try{sessionStorage.setItem("accountPausedReason",ke)}catch{}await Be.auth.signOut(),ee(),r(null),i(null);const Ae=new Error(ke?`Your account is paused. ${ke}`:"Your account is paused. Please contact LevelUp support to reactivate it.");throw Ae.name="AccountPaused",lr.error(Ae.message),Ae}}lr.success("Welcome back!")},pe=async(be,Re,Ie)=>{var ke;const Te="https://dashboard.relevelup.com/dashboard",ge=localStorage.getItem("levelup_referral_code")||null,{data:$e,error:we}=await Be.auth.signUp({email:be,password:Re,options:{emailRedirectTo:Te,data:{name:Ie,referred_by_code:ge}}});if(we)throw lr.error(we.message),we;if(ge&&((ke=$e.user)!=null&&ke.id))try{await Be.from("profiles").update({referred_by_code:ge}).eq("id",$e.user.id),localStorage.removeItem("levelup_referral_code")}catch(Ae){console.warn("Failed to attach referral code to profile",Ae)}lr.success("Account created! Welcome to LevelUp."),Q("/dashboard")},Le=async()=>{try{const{data:{session:be}}=await Be.auth.getSession();if(be){const{error:Re}=await Be.auth.signOut();Re?Re.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",Re.message):(console.error("Sign out error:",Re),lr.error(Re.message)):lr.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");r(null),i(null),g(!1),E(!1),C(null),O([]),$(null),Q("/auth")}catch(be){console.error("Unexpected sign out error:",be),Q("/auth")}};return s.jsx(Cbe.Provider,{value:{user:e,session:n,loading:a,rolesLoading:d,signIn:oe,signUp:pe,signOut:Le,isAdmin:l,isBrokerageManager:v,isCoach:T,brokerageId:P,managedBrokerages:L,selectedBrokerageId:F,setSelectedBrokerageId:$},children:t})},_i=()=>{const t=N.useContext(Cbe);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t},Pbe=N.createContext({onlineUsers:[],totalOnline:0}),aGe=3*60*1e3,oGe=45*1e3,lGe=30*1e3,cGe=({children:t})=>{const{user:e,brokerageId:r,isAdmin:n}=_i(),[i,a]=N.useState([]),c=N.useRef(new Date().toISOString()),d=N.useCallback(async()=>{e&&await Be.from("user_presence").upsert({user_id:e.id,last_seen_at:new Date().toISOString(),online_since:c.current,current_path:window.location.pathname},{onConflict:"user_id"})},[e==null?void 0:e.id]),p=N.useCallback(async()=>{if(!e)return;const g=new Date(Date.now()-aGe).toISOString(),{data:v}=await Be.from("user_presence").select("user_id, last_seen_at, online_since").gte("last_seen_at",g).order("last_seen_at",{ascending:!1}).limit(200);if(!(v!=null&&v.length)){a([]);return}const E=v.map(P=>P.user_id),{data:T}=await Be.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",E),j=new Map((T||[]).map(P=>[P.id,P]));a(v.map(P=>{var L;const C=j.get(P.user_id);return{id:P.user_id,name:(C==null?void 0:C.name)||((L=C==null?void 0:C.email)==null?void 0:L.split("@")[0])||"Member",avatarUrl:(C==null?void 0:C.avatar_url)||void 0,brokerageId:(C==null?void 0:C.brokerage_id)||void 0,onlineSince:P.online_since||P.last_seen_at}}))},[e==null?void 0:e.id]);N.useEffect(()=>{if(!e){a([]);return}c.current=new Date().toISOString();let g=!1;const v=async()=>{g||(await d(),await p())};v();const E=window.setInterval(()=>{d()},oGe),T=window.setInterval(()=>{p()},lGe),j=()=>{document.visibilityState==="visible"&&v()};return document.addEventListener("visibilitychange",j),()=>{g=!0,window.clearInterval(E),window.clearInterval(T),document.removeEventListener("visibilitychange",j)}},[e==null?void 0:e.id,d,p]);const l=i.filter(g=>!!(g.id===(e==null?void 0:e.id)||n||r&&g.brokerageId===r||!r&&!g.brokerageId));return s.jsx(Pbe.Provider,{value:{onlineUsers:l,totalOnline:l.length},children:t})},aKt=()=>N.useContext(Pbe),Nbe=N.createContext(void 0),nb="levelup_admin_session",p_="levelup_impersonation",cU="levelup_impersonation_return",uGe=({children:t})=>{const[e,r]=N.useState(!1),[n,i]=N.useState(null),[a,c]=N.useState(!1);N.useEffect(()=>{const l=sessionStorage.getItem(p_);if(l)try{const g=JSON.parse(l);r(!0),i(g)}catch{sessionStorage.removeItem(p_)}},[]);const d=async(l,g)=>{c(!0);try{const{data:{session:v}}=await Be.auth.getSession();if(!v)return lr.error("No active session found"),!1;const E={access_token:v.access_token,refresh_token:v.refresh_token};sessionStorage.setItem(nb,JSON.stringify(E)),g&&sessionStorage.setItem(cU,g);const T=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v.access_token}`},body:JSON.stringify({targetUserId:l})}),j=await T.json();if(!T.ok)throw new Error(j.error||"Failed to impersonate user");const P={id:j.targetUser.id,name:j.targetUser.name,email:j.targetUser.email};if(sessionStorage.setItem(p_,JSON.stringify(P)),j.method==="session"){const{error:C}=await Be.auth.setSession({access_token:j.access_token,refresh_token:j.refresh_token});if(C)throw console.error("Set session error:",C),sessionStorage.removeItem(nb),sessionStorage.removeItem(p_),new Error("Failed to establish impersonation session")}else{const C=j.type||"recovery",{error:L}=await Be.auth.verifyOtp({token_hash:j.token_hash,type:C});if(L)throw console.error("Verify OTP error:",L),sessionStorage.removeItem(nb),sessionStorage.removeItem(p_),new Error("Failed to establish impersonation session")}return r(!0),i(P),lr.success(`Now viewing as ${P.name}`),window.location.href="/dashboard",!0}catch(v){return console.error("Impersonation error:",v),lr.error(v.message||"Failed to impersonate user"),sessionStorage.removeItem(nb),sessionStorage.removeItem(p_),!1}finally{c(!1)}},p=async()=>{c(!0);try{const l=sessionStorage.getItem(nb);if(!l){await Be.auth.signOut(),window.location.href="/auth";return}const g=JSON.parse(l);await Be.auth.signOut();const{error:v}=await Be.auth.setSession({access_token:g.access_token,refresh_token:g.refresh_token});if(sessionStorage.removeItem(nb),sessionStorage.removeItem(p_),v){console.error("Failed to restore admin session:",v),lr.error("Admin session expired, please sign in again"),window.location.href="/auth";return}r(!1),i(null),lr.success("Returned to your account");const E=sessionStorage.getItem(cU)||"/admin/members";sessionStorage.removeItem(cU),window.location.href=E}catch(l){console.error("Stop impersonation error:",l),lr.error("Failed to restore admin session"),sessionStorage.removeItem(nb),sessionStorage.removeItem(p_),window.location.href="/auth"}finally{c(!1)}};return s.jsx(Nbe.Provider,{value:{isImpersonating:e,impersonatedUser:n,startImpersonation:d,stopImpersonation:p,isLoading:a},children:t})},Rbe=()=>{const t=N.useContext(Nbe);if(t===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return t},dGe=()=>{const{isImpersonating:t,impersonatedUser:e,stopImpersonation:r,isLoading:n}=Rbe();return!t||!e?null:s.jsx("div",{className:"fixed top-0 left-0 right-0 z-[100] bg-amber-500 text-amber-950 px-4 py-2 shadow-lg",children:s.jsxs("div",{className:"container mx-auto flex items-center justify-between gap-4",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(LP,{className:"h-5 w-5 flex-shrink-0"}),s.jsxs("span",{className:"font-medium text-sm md:text-base",children:[s.jsx("span",{className:"hidden sm:inline",children:"You are viewing as "}),s.jsx("strong",{children:e.name}),s.jsxs("span",{className:"hidden md:inline text-amber-800",children:[" (",e.email,")"]})]})]}),s.jsx(Jt,{size:"sm",variant:"secondary",onClick:r,disabled:n,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:n?s.jsx(gh,{className:"h-4 w-4 animate-spin"}):s.jsxs(s.Fragment,{children:[s.jsx(Ra,{className:"h-4 w-4 mr-1"}),s.jsx("span",{className:"hidden sm:inline",children:"Exit Impersonation"}),s.jsx("span",{className:"sm:hidden",children:"Exit"})]})})]})})},Lbe=N.createContext(void 0),ES="levelup_acting_as",bD="levelup_acting_as_self",hGe=({children:t})=>{const{user:e}=_i(),[r,n]=N.useState(!1),[i,a]=N.useState([]),[c,d]=N.useState(null),[p,l]=N.useState({}),[g,v]=N.useState(!0),[E,T]=N.useState(()=>sessionStorage.getItem(bD)==="true");N.useEffect(()=>{if(!(e!=null&&e.id)){n(!1),a([]),d(null),l({}),v(!1);return}(async()=>{v(!0);try{const{data:F}=await Be.rpc("has_role",{_user_id:e.id,_role:"assistant"});if(!F){n(!1),a([]),d(null),l({}),v(!1);return}n(!0);const{data:$,error:G}=await Be.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",e.id);if(G||!$||$.length===0){a([]),v(!1);return}const W=$.map(ee=>ee.agent_id),{data:Z}=await Be.from("profiles").select("id, name, email, avatar_url").in("id",W),Q=(Z||[]).map(ee=>({id:ee.id,name:ee.name||ee.email||"Unknown",email:ee.email||"",avatar_url:ee.avatar_url}));if(a(Q),sessionStorage.getItem(bD)==="true")T(!0),d(null),l({});else{const ee=sessionStorage.getItem(ES);if(ee){const ie=Q.find(oe=>oe.id===ee);if(ie){d(ie);const oe=$.find(pe=>pe.agent_id===ee);l((oe==null?void 0:oe.permissions)||{})}else if(Q.length>0){d(Q[0]);const oe=$.find(pe=>pe.agent_id===Q[0].id);l((oe==null?void 0:oe.permissions)||{}),sessionStorage.setItem(ES,Q[0].id)}}else if(Q.length>0){d(Q[0]);const ie=$.find(oe=>oe.agent_id===Q[0].id);l((ie==null?void 0:ie.permissions)||{}),sessionStorage.setItem(ES,Q[0].id)}}}catch(F){console.error("Error loading assistant data:",F)}finally{v(!1)}})()},[e==null?void 0:e.id]);const j=O=>{d(O),T(!1),sessionStorage.removeItem(bD),O?(sessionStorage.setItem(ES,O.id),Be.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(e==null?void 0:e.id)||"").eq("agent_id",O.id).single().then(({data:F})=>{l((F==null?void 0:F.permissions)||{})})):(sessionStorage.removeItem(ES),l({}))},P=()=>{T(!0),d(null),l({}),sessionStorage.setItem(bD,"true"),sessionStorage.removeItem(ES)},C=O=>!r||E?!0:p[O]===!0,L=r&&c&&!E?c.id:(e==null?void 0:e.id)||null;return s.jsx(Lbe.Provider,{value:{isAssistant:r,assignedAgents:i,actingAsAgent:c,setActingAsAgent:j,effectiveUserId:L,permissions:p,hasPermission:C,isLoading:g,isActingAsSelf:E,setActingAsSelf:P},children:t})},i5=()=>{const t=N.useContext(Lbe);if(t===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return t},qs=()=>{const{effectiveUserId:t}=i5();return t};var fGe=Object.defineProperty,Hy=(t,e)=>fGe(t,"name",{value:e,configurable:!0}),Dbe="Avatar",[mGe,oKt]=Nl(Dbe),Ly={Idle:"idle",Loading:"loading",Loaded:"loaded",Error:"error"},pGe=[0,()=>{}],[gGe,Mbe]=mGe(Dbe),Obe=N.forwardRef(Hy(function(e,r){const{__scopeAvatar:n,...i}=e,[a,c]=N.useState(Ly.Idle),[d,p]=$be();return s.jsx(gGe,{scope:n,imageLoadingStatus:a,setImageLoadingStatus:c,imageCount:d,setImageCount:p,children:s.jsx(An.span,{...i,ref:r})})},"Avatar")),yGe="AvatarImage",Fbe=N.forwardRef(Hy(function(e,r){const{__scopeAvatar:n,src:i,onLoadingStatusChange:a,...c}=e,d=Mbe(yGe,n);d.setImageCount;const p=zbe(i,{referrerPolicy:c.referrerPolicy,crossOrigin:c.crossOrigin,loadingStatus:d.imageLoadingStatus,setLoadingStatus:d.setImageLoadingStatus}),l=Yo(v=>{a==null||a(v)}),g=N.useRef(p);return no(()=>{const v=g.current;g.current=p,p!==v&&l(p)},[p,l]),p===Ly.Loaded?s.jsx(An.img,{...c,ref:r,src:i}):null},"AvatarImage")),xGe="AvatarFallback",Bbe=N.forwardRef(Hy(function(e,r){const{__scopeAvatar:n,delayMs:i,...a}=e,c=Mbe(xGe,n),[d,p]=N.useState(i===void 0);return N.useEffect(()=>{if(i!==void 0){const l=window.setTimeout(()=>p(!0),i);return()=>window.clearTimeout(l)}},[i]),d&&c.imageLoadingStatus!==Ly.Loaded?s.jsx(An.span,{...a,ref:r}):null},"AvatarFallback"));function zbe(t,{loadingStatus:e,setLoadingStatus:r,referrerPolicy:n,crossOrigin:i}){return no(()=>{if(!t){r(Ly.Error);return}const a=new window.Image,c=Hy(p=>{const l=p.currentTarget;r(EG(l))},"handleLoad"),d=Hy(()=>r(Ly.Error),"handleError");return a.addEventListener("load",c),a.addEventListener("error",d),n&&(a.referrerPolicy=n),a.crossOrigin=i??null,a.src=t,r(EG(a)),()=>{a.removeEventListener("load",c),a.removeEventListener("error",d),r(Ly.Idle)}},[t,i,n,r]),e}Hy(zbe,"useImageLoadingStatus");function EG(t){return t.complete?t.naturalWidth>0?Ly.Loaded:Ly.Error:Ly.Loading}Hy(EG,"getImageLoadingStatus");function $be(){return pGe}Hy($be,"useImageCount");function _Ge(t){}Hy(_Ge,"useUpdateImageCount");const tf=N.forwardRef(({className:t,...e},r)=>s.jsx(Obe,{ref:r,className:hr("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...e}));tf.displayName=Obe.displayName;const rf=N.forwardRef(({className:t,...e},r)=>s.jsx(Fbe,{ref:r,className:hr("aspect-square h-full w-full",t),...e}));rf.displayName=Fbe.displayName;const nf=N.forwardRef(({className:t,...e},r)=>s.jsx(Bbe,{ref:r,className:hr("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...e}));nf.displayName=Bbe.displayName;const vGe=eA("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Js({className:t,variant:e,...r}){return s.jsx("div",{className:hr(vGe({variant:e}),t),...r})}var bGe=Object.defineProperty,wGe=(t,e)=>bGe(t,"name",{value:e,configurable:!0}),SGe={LTR:"ltr"},EGe=N.createContext(void 0);function Uv(t){const e=N.useContext(EGe);return t||e||SGe.LTR}wGe(Uv,"useDirection");var TGe=Object.defineProperty,FK=(t,e)=>TGe(t,"name",{value:e,configurable:!0}),uU=!1;function Ube(){const[t,e]=N.useState(uU);return N.useEffect(()=>{uU||(uU=!0,e(!0))},[]),t}FK(Ube,"useIsHydrated");var Vbe=ex[" useSyncExternalStore ".trim().toString()];function qbe(){return()=>{}}FK(qbe,"subscribe");function Gbe(){return Vbe(qbe,()=>!0,()=>!1)}FK(Gbe,"useIsHydratedModern");var AGe=typeof Vbe=="function"?Gbe:Ube,kGe=Object.defineProperty,Ew=(t,e)=>kGe(t,"name",{value:e,configurable:!0}),dU="rovingFocusGroup.onEntryFocus",IGe={bubbles:!1,cancelable:!0},s5="RovingFocusGroup",[TG,Hbe,jGe]=QT(s5),[CGe,yA]=Nl(s5,[jGe]),soe={Vertical:"vertical",Horizontal:"horizontal"},PGe={RTL:"rtl"},[NGe,RGe]=CGe(s5),BK=N.forwardRef(Ew(function(e,r){return s.jsx(TG.Provider,{scope:e.__scopeRovingFocusGroup,children:s.jsx(TG.Slot,{scope:e.__scopeRovingFocusGroup,children:s.jsx(LGe,{...e,ref:r})})})},"RovingFocusGroup")),LGe=N.forwardRef(Ew(function(e,r){const{__scopeRovingFocusGroup:n,orientation:i,loop:a=!1,dir:c,currentTabStopId:d,defaultCurrentTabStopId:p,onCurrentTabStopIdChange:l,onEntryFocus:g,preventScrollOnEntryFocus:v=!1,...E}=e,T=N.useRef(null),j=Jn(r,T),P=Uv(c),[C,L]=ph({prop:d,defaultProp:p??null,onChange:l,caller:s5}),[O,F]=N.useState(!1),$=Yo(g),G=Hbe(n),W=N.useRef(!1),[Z,Q]=N.useState(0);return N.useEffect(()=>{const ee=T.current;if(ee)return ee.addEventListener(dU,$),()=>ee.removeEventListener(dU,$)},[$]),s.jsx(NGe,{scope:n,orientation:i,dir:P,loop:a,currentTabStopId:C,onItemFocus:N.useCallback(ee=>L(ee),[L]),onItemShiftTab:N.useCallback(()=>F(!0),[]),onFocusableItemAdd:N.useCallback(()=>Q(ee=>ee+1),[]),onFocusableItemRemove:N.useCallback(()=>Q(ee=>ee-1),[]),children:s.jsx(An.div,{tabIndex:O||Z===0?-1:0,"data-orientation":i,...E,ref:j,style:{outline:"none",...e.style},onMouseDown:Qr(e.onMouseDown,()=>{W.current=!0}),onFocus:Qr(e.onFocus,ee=>{const ie=!W.current;if(ee.target===ee.currentTarget&&ie&&!O){const oe=new CustomEvent(dU,IGe);if(ee.currentTarget.dispatchEvent(oe),!oe.defaultPrevented){const pe=G().filter(Te=>Te.focusable),Le=pe.find(Te=>Te.active),be=pe.find(Te=>Te.id===C),Ie=[Le,be,...pe].filter(Boolean).map(Te=>Te.ref.current);$K(Ie,v)}}W.current=!1}),onBlur:Qr(e.onBlur,()=>F(!1))})})},"RovingFocusGroupImpl")),DGe="RovingFocusGroupItem",zK=N.forwardRef(Ew(function(e,r){const{__scopeRovingFocusGroup:n,focusable:i=!0,active:a=!1,tabStopId:c,children:d,...p}=e,l=Wl(),g=c||l,v=RGe(DGe,n),E=v.currentTabStopId===g,T=Hbe(n),{onFocusableItemAdd:j,onFocusableItemRemove:P,currentTabStopId:C}=v,L=AGe();return no(()=>{if(!(!L||!i))return j(),()=>P()},[L,i,j,P]),N.useEffect(()=>{if(!(L||!i))return j(),()=>P()},[L,i,j,P]),s.jsx(TG.ItemSlot,{scope:n,id:g,focusable:i,active:a,children:s.jsx(An.span,{tabIndex:E?0:-1,"data-orientation":v.orientation,...p,ref:r,onMouseDown:Qr(e.onMouseDown,O=>{i?v.onItemFocus(g):O.preventDefault()}),onFocus:Qr(e.onFocus,()=>v.onItemFocus(g)),onKeyDown:Qr(e.onKeyDown,O=>{if(O.key==="Tab"&&O.shiftKey){v.onItemShiftTab();return}if(O.target!==O.currentTarget)return;const F=Kbe(O,v.orientation,v.dir);if(F!==void 0){if(O.metaKey||O.ctrlKey||O.altKey||O.shiftKey)return;O.preventDefault();let G=T().filter(W=>W.focusable).map(W=>W.ref.current);if(F==="last")G.reverse();else if(F==="prev"||F==="next"){F==="prev"&&G.reverse();const W=G.indexOf(O.currentTarget);G=v.loop?Ybe(G,W+1):G.slice(W+1)}setTimeout(()=>$K(G))}}),children:typeof d=="function"?d({isCurrentTabStop:E,hasTabStop:C!=null}):d})})},"RovingFocusGroupItem")),MGe={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Wbe(t,e){return e!==PGe.RTL?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}Ew(Wbe,"getDirectionAwareKey");function Kbe(t,e,r){const n=Wbe(t.key,r);if(!(e===soe.Vertical&&["ArrowLeft","ArrowRight"].includes(n))&&!(e===soe.Horizontal&&["ArrowUp","ArrowDown"].includes(n)))return MGe[n]}Ew(Kbe,"getFocusIntent");function $K(t,e=!1){const r=document.activeElement;for(const n of t)if(n===r||(n.focus({preventScroll:e}),document.activeElement!==r))return}Ew($K,"focusFirst");function Ybe(t,e){return t.map((r,n)=>t[(e+n)%t.length])}Ew(Ybe,"wrapArray");var OGe=Object.defineProperty,ha=(t,e)=>OGe(t,"name",{value:e,configurable:!0}),FGe={RTL:"rtl"},AG=["Enter"," "],BGe=["ArrowDown","PageUp","Home"],Zbe=["ArrowUp","PageDown","End"],zGe=[...BGe,...Zbe],$Ge={ltr:[...AG,"ArrowRight"],rtl:[...AG,"ArrowLeft"]},UGe={ltr:["ArrowLeft"],rtl:["ArrowRight"]},a5="Menu",[rC,VGe,qGe]=QT(a5),[Tw,Xbe]=Nl(a5,[qGe,Bv,yA]),UK=Bv(),Qbe=yA(),[GGe,Aw]=Tw(a5),[HGe,$P]=Tw(a5),WGe=ha(t=>{const{__scopeMenu:e,open:r=!1,children:n,dir:i,onOpenChange:a,modal:c=!0}=t,d=UK(e),[p,l]=N.useState(null),g=N.useRef(!1),v=Yo(a),E=Uv(i);return N.useEffect(()=>{const T=ha(()=>{g.current=!0,document.addEventListener("pointerdown",j,{capture:!0,once:!0}),document.addEventListener("pointermove",j,{capture:!0,once:!0})},"handleKeyDown"),j=ha(()=>g.current=!1,"handlePointer");return document.addEventListener("keydown",T,{capture:!0}),()=>{document.removeEventListener("keydown",T,{capture:!0}),document.removeEventListener("pointerdown",j,{capture:!0}),document.removeEventListener("pointermove",j,{capture:!0})}},[]),N.useEffect(()=>{if(!r)return;const T=ha(()=>v(!1),"handleBlur");return window.addEventListener("blur",T),()=>window.removeEventListener("blur",T)},[r,v]),s.jsx(V4,{...d,children:s.jsx(GGe,{scope:e,open:r,onOpenChange:v,content:p,onContentChange:l,children:s.jsx(HGe,{scope:e,onClose:N.useCallback(()=>v(!1),[v]),isUsingKeyboardRef:g,dir:E,modal:c,children:n})})})},"Menu"),Jbe=N.forwardRef(ha(function(e,r){const{__scopeMenu:n,...i}=e,a=UK(n);return s.jsx(q4,{...a,...i,ref:r})},"MenuAnchor")),ewe="MenuPortal",[KGe,twe]=Tw(ewe,{forceMount:void 0}),YGe=ha(t=>{const{__scopeMenu:e,forceMount:r,children:n,container:i}=t,a=Aw(ewe,e);return s.jsx(KGe,{scope:e,forceMount:r,children:s.jsx(zc,{present:r||a.open,children:s.jsx(jP,{asChild:!0,container:i,children:n})})})},"MenuPortal"),ep="MenuContent",[ZGe,VK]=Tw(ep),XGe=N.forwardRef(ha(function(e,r){const n=twe(ep,e.__scopeMenu),{forceMount:i=n.forceMount,...a}=e,c=Aw(ep,e.__scopeMenu),d=$P(ep,e.__scopeMenu);return s.jsx(rC.Provider,{scope:e.__scopeMenu,children:s.jsx(zc,{present:i||c.open,children:s.jsx(rC.Slot,{scope:e.__scopeMenu,children:d.modal?s.jsx(QGe,{...a,ref:r}):s.jsx(JGe,{...a,ref:r})})})})},"MenuContent")),QGe=N.forwardRef(ha(function(e,r){const n=Aw(ep,e.__scopeMenu),i=N.useRef(null),a=Jn(r,i);return N.useEffect(()=>{const c=i.current;if(c)return L4(c)},[]),s.jsx(qK,{...e,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Qr(e.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})},"MenuRootContentModal")),JGe=N.forwardRef(ha(function(e,r){const n=Aw(ep,e.__scopeMenu);return s.jsx(qK,{...e,ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})},"MenuRootContentNonModal")),e9e=sp("MenuContent.ScrollLock"),qK=N.forwardRef(ha(function(e,r){const{__scopeMenu:n,loop:i=!1,trapFocus:a,onOpenAutoFocus:c,onCloseAutoFocus:d,disableOutsidePointerEvents:p,onEntryFocus:l,onEscapeKeyDown:g,onPointerDownOutside:v,onFocusOutside:E,onInteractOutside:T,onDismiss:j,disableOutsideScroll:P,...C}=e,L=Aw(ep,n),O=$P(ep,n),F=UK(n),$=Qbe(n),G=VGe(n),[W,Z]=N.useState(null),Q=N.useRef(null),[ee,ie]=N.useState(null);N4(ee);const{nodes:oe,registry:pe}=P4(),Le=!!(a||P),be=Jn(r,Q,L.onContentChange,ie),Re=N.useRef(0),Ie=N.useRef(""),Te=N.useRef(0),ge=N.useRef(null),$e=N.useRef("right"),we=N.useRef(0),ke=N.useMemo(()=>P?[Q,...oe.map(tt=>({current:tt}))]:[],[Q,oe,P]),Ae=P?DP:N.Fragment,He=P?{as:e9e,allowPinchZoom:!0,shards:ke}:void 0,ot=ha(tt=>{var Gr,tr;const vt=Ie.current+tt,Vt=G().filter(Qt=>!Qt.disabled),Ct=document.activeElement,Bt=(Gr=Vt.find(Qt=>Qt.ref.current===Ct))==null?void 0:Gr.textValue,cr=Vt.map(Qt=>Qt.textValue),ft=lwe(cr,vt,Bt),Kt=(tr=Vt.find(Qt=>Qt.textValue===ft))==null?void 0:tr.ref.current;function ir(Qt){Ie.current=Qt,window.clearTimeout(Re.current),Qt!==""&&(Re.current=window.setTimeout(()=>ir(""),1e3))}ha(ir,"updateSearch"),ir(vt),Kt&&setTimeout(()=>Kt.focus())},"handleTypeaheadSearch");N.useEffect(()=>()=>window.clearTimeout(Re.current),[]),aA();const nt=N.useCallback(tt=>{var Vt,Ct;return $e.current===((Vt=ge.current)==null?void 0:Vt.side)&&uwe(tt,(Ct=ge.current)==null?void 0:Ct.area)},[]);return s.jsx(ZGe,{scope:n,searchRef:Ie,onItemEnter:N.useCallback(tt=>{nt(tt)&&tt.preventDefault()},[nt]),onItemLeave:N.useCallback(tt=>{var vt;nt(tt)||((vt=Q.current)==null||vt.focus(),Z(null))},[nt]),onTriggerLeave:N.useCallback(tt=>{nt(tt)&&tt.preventDefault()},[nt]),pointerGraceTimerRef:Te,onPointerGraceIntentChange:N.useCallback(tt=>{ge.current=tt},[]),children:s.jsx(C4,{registry:Le?pe:null,children:s.jsx(Ae,{...He,children:s.jsx(j4,{asChild:!0,trapped:a,branches:oe,onMountAutoFocus:Qr(c,tt=>{var vt;tt.preventDefault(),(vt=Q.current)==null||vt.focus({preventScroll:!0})}),onUnmountAutoFocus:d,children:s.jsx(JT,{asChild:!0,disableOutsidePointerEvents:p,onEscapeKeyDown:g,onPointerDownOutside:v,onFocusOutside:E,onInteractOutside:T,onDismiss:j,children:s.jsx(BK,{asChild:!0,...$,dir:O.dir,orientation:"vertical",loop:i,currentTabStopId:W,onCurrentTabStopIdChange:Z,onEntryFocus:Qr(l,tt=>{O.isUsingKeyboardRef.current||tt.preventDefault()}),preventScrollOnEntryFocus:!0,children:s.jsx(G4,{role:"menu","aria-orientation":"vertical","data-state":HK(L.open),"data-radix-menu-content":"",dir:O.dir,...F,...C,ref:be,style:{outline:"none",...C.style},onKeyDown:Qr(C.onKeyDown,tt=>{const Vt=tt.target.closest("[data-radix-menu-content]")===tt.currentTarget,Ct=tt.ctrlKey||tt.altKey||tt.metaKey,Bt=tt.key.length===1;Vt&&(tt.key==="Tab"&&tt.preventDefault(),!Ct&&Bt&&ot(tt.key));const cr=Q.current;if(tt.target!==cr||!zGe.includes(tt.key))return;tt.preventDefault();const Kt=G().filter(ir=>!ir.disabled).map(ir=>ir.ref.current);Zbe.includes(tt.key)&&Kt.reverse(),awe(Kt)}),onBlur:Qr(e.onBlur,tt=>{tt.currentTarget.contains(tt.target)||(window.clearTimeout(Re.current),Ie.current="")}),onPointerMove:Qr(e.onPointerMove,oT(tt=>{const vt=tt.target,Vt=we.current!==tt.clientX;if(tt.currentTarget.contains(vt)&&Vt){const Ct=tt.clientX>we.current?"right":"left";$e.current=Ct,we.current=tt.clientX}}))})})})})})})})},"MenuContentImpl")),t9e=N.forwardRef(ha(function(e,r){const{__scopeMenu:n,...i}=e;return s.jsx(An.div,{...i,ref:r})},"MenuLabel")),kG="MenuItem",aoe="menu.itemSelect",GK=N.forwardRef(ha(function(e,r){const{disabled:n=!1,onSelect:i,...a}=e,c=N.useRef(null),d=$P(kG,e.__scopeMenu),p=VK(kG,e.__scopeMenu),l=Jn(r,c),g=N.useRef(!1),v=ha(()=>{const E=c.current;if(!n&&E){const T=new CustomEvent(aoe,{bubbles:!0,cancelable:!0});E.addEventListener(aoe,j=>i==null?void 0:i(j),{once:!0}),b4(E,T),T.defaultPrevented?g.current=!1:d.onClose()}},"handleSelect");return s.jsx(rwe,{...a,ref:l,disabled:n,onClick:Qr(e.onClick,v),onPointerDown:E=>{var T;(T=e.onPointerDown)==null||T.call(e,E),g.current=!0},onPointerUp:Qr(e.onPointerUp,E=>{var T;g.current||(T=E.currentTarget)==null||T.click()}),onKeyDown:Qr(e.onKeyDown,E=>{n||E.target!==E.currentTarget||p.searchRef.current!==""&&E.key===" "||AG.includes(E.key)&&(E.currentTarget.click(),E.preventDefault())})})},"MenuItem")),rwe=N.forwardRef(ha(function(e,r){const{__scopeMenu:n,disabled:i=!1,textValue:a,...c}=e,d=VK(kG,n),p=Qbe(n),l=N.useRef(null),g=Jn(r,l),[v,E]=N.useState(!1),[T,j]=N.useState("");return N.useEffect(()=>{const P=l.current;P&&j((P.textContent??"").trim())},[c.children]),s.jsx(rC.ItemSlot,{scope:n,disabled:i,textValue:a??T,children:s.jsx(zK,{asChild:!0,...p,focusable:!i,children:s.jsx(An.div,{role:"menuitem","data-highlighted":v?"":void 0,"aria-disabled":i||void 0,"data-disabled":i?"":void 0,...c,ref:g,onPointerMove:Qr(e.onPointerMove,oT(P=>{i?d.onItemLeave(P):(d.onItemEnter(P),P.defaultPrevented||P.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Qr(e.onPointerLeave,oT(P=>d.onItemLeave(P))),onFocus:Qr(e.onFocus,()=>E(!0)),onBlur:Qr(e.onBlur,()=>E(!1))})})})},"MenuItemImpl")),r9e=N.forwardRef(ha(function(e,r){const{checked:n=!1,onCheckedChange:i,...a}=e;return s.jsx(iwe,{scope:e.__scopeMenu,checked:n,children:s.jsx(GK,{role:"menuitemcheckbox","aria-checked":nC(n)?"mixed":n,...a,ref:r,"data-state":o5(n),onSelect:Qr(a.onSelect,()=>i==null?void 0:i(nC(n)?!0:!n),{checkForDefaultPrevented:!1})})})},"MenuCheckboxItem")),n9e="MenuRadioGroup",[lKt,i9e]=Tw(n9e,{value:void 0,onValueChange:ha(()=>{},"onValueChange")}),s9e="MenuRadioItem",a9e=N.forwardRef(ha(function(e,r){const{value:n,...i}=e,a=i9e(s9e,e.__scopeMenu),c=n===a.value;return s.jsx(iwe,{scope:e.__scopeMenu,checked:c,children:s.jsx(GK,{role:"menuitemradio","aria-checked":c,...i,ref:r,"data-state":o5(c),onSelect:Qr(i.onSelect,()=>{var d;return(d=a.onValueChange)==null?void 0:d.call(a,n)},{checkForDefaultPrevented:!1})})})},"MenuRadioItem")),nwe="MenuItemIndicator",[iwe,o9e]=Tw(nwe,{checked:!1}),l9e=N.forwardRef(ha(function(e,r){const{__scopeMenu:n,forceMount:i,...a}=e,c=o9e(nwe,n);return s.jsx(zc,{present:i||nC(c.checked)||c.checked===!0,children:s.jsx(An.span,{...a,ref:r,"data-state":o5(c.checked)})})},"MenuItemIndicator")),c9e=N.forwardRef(ha(function(e,r){const{__scopeMenu:n,...i}=e;return s.jsx(An.div,{role:"separator","aria-orientation":"horizontal",...i,ref:r})},"MenuSeparator")),u9e="MenuSub",[cKt,swe]=Tw(u9e),wD="MenuSubTrigger",d9e=N.forwardRef(ha(function(e,r){const n=Aw(wD,e.__scopeMenu),i=$P(wD,e.__scopeMenu),a=swe(wD,e.__scopeMenu),c=VK(wD,e.__scopeMenu),d=N.useRef(null),{pointerGraceTimerRef:p,onPointerGraceIntentChange:l}=c,g={__scopeMenu:e.__scopeMenu},v=N.useCallback(()=>{d.current&&window.clearTimeout(d.current),d.current=null},[]);N.useEffect(()=>v,[v]),N.useEffect(()=>{const T=p.current;return()=>{window.clearTimeout(T),l(null)}},[p,l]);const E=Jn(r,a.onTriggerChange);return s.jsx(Jbe,{asChild:!0,...g,children:s.jsx(rwe,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":n.open?a.contentId:void 0,"data-state":HK(n.open),...e,ref:E,onClick:T=>{var j;(j=e.onClick)==null||j.call(e,T),!(e.disabled||T.defaultPrevented)&&(T.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Qr(e.onPointerMove,oT(T=>{c.onItemEnter(T),!T.defaultPrevented&&!e.disabled&&!n.open&&!d.current&&(c.onPointerGraceIntentChange(null),d.current=window.setTimeout(()=>{n.onOpenChange(!0),v()},100))})),onPointerLeave:Qr(e.onPointerLeave,oT(T=>{var P,C;v();const j=(P=n.content)==null?void 0:P.getBoundingClientRect();if(j){const L=(C=n.content)==null?void 0:C.dataset.side,O=L==="right",F=O?-5:5,$=j[O?"left":"right"],G=j[O?"right":"left"];c.onPointerGraceIntentChange({area:[{x:T.clientX+F,y:T.clientY},{x:$,y:j.top},{x:G,y:j.top},{x:G,y:j.bottom},{x:$,y:j.bottom}],side:L}),window.clearTimeout(p.current),p.current=window.setTimeout(()=>c.onPointerGraceIntentChange(null),300)}else{if(c.onTriggerLeave(T),T.defaultPrevented)return;c.onPointerGraceIntentChange(null)}})),onKeyDown:Qr(e.onKeyDown,T=>{var P;e.disabled||T.target!==T.currentTarget||c.searchRef.current!==""&&T.key===" "||$Ge[i.dir].includes(T.key)&&(n.onOpenChange(!0),(P=n.content)==null||P.focus(),T.preventDefault())})})})},"MenuSubTrigger")),h9e="MenuSubContent",f9e=N.forwardRef(ha(function(e,r){const n=twe(ep,e.__scopeMenu),{forceMount:i=n.forceMount,align:a="start",...c}=e,d=Aw(ep,e.__scopeMenu),p=$P(ep,e.__scopeMenu),l=swe(h9e,e.__scopeMenu),g=N.useRef(null),v=Jn(r,g);return s.jsx(rC.Provider,{scope:e.__scopeMenu,children:s.jsx(zc,{present:i||d.open,children:s.jsx(rC.Slot,{scope:e.__scopeMenu,children:s.jsx(qK,{id:l.contentId,"aria-labelledby":l.triggerId,...c,ref:v,align:a,side:p.dir===FGe.RTL?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:E=>{var T;p.isUsingKeyboardRef.current&&((T=g.current)==null||T.focus()),E.preventDefault()},onCloseAutoFocus:E=>E.preventDefault(),onFocusOutside:Qr(e.onFocusOutside,E=>{E.target!==l.trigger&&d.onOpenChange(!1)}),onEscapeKeyDown:Qr(e.onEscapeKeyDown,E=>{p.onClose(),E.preventDefault()}),onKeyDown:Qr(e.onKeyDown,E=>{var P;const T=E.currentTarget.contains(E.target),j=UGe[p.dir].includes(E.key);T&&j&&(d.onOpenChange(!1),(P=l.trigger)==null||P.focus(),E.preventDefault())})})})})})},"MenuSubContent"));function HK(t){return t?"open":"closed"}ha(HK,"getOpenState");function nC(t){return t==="indeterminate"}ha(nC,"isIndeterminate");function o5(t){return nC(t)?"indeterminate":t?"checked":"unchecked"}ha(o5,"getCheckedState");function awe(t){const e=document.activeElement;for(const r of t)if(r===e||(r.focus(),document.activeElement!==e))return}ha(awe,"focusFirst");function owe(t,e){return t.map((r,n)=>t[(e+n)%t.length])}ha(owe,"wrapArray");function lwe(t,e,r){const i=e.length>1&&Array.from(e).every(l=>l===e[0])?e[0]:e,a=r?t.indexOf(r):-1;let c=owe(t,Math.max(a,0));i.length===1&&(c=c.filter(l=>l!==r));const p=c.find(l=>l.toLowerCase().startsWith(i.toLowerCase()));return p!==r?p:void 0}ha(lwe,"getNextMatch");function cwe(t,e){const{x:r,y:n}=t;let i=!1;for(let a=0,c=e.length-1;an!=E>n&&r<(v-l)*(n-g)/(E-g)+l&&(i=!i)}return i}ha(cwe,"isPointInPolygon");function uwe(t,e){if(!e)return!1;const r={x:t.clientX,y:t.clientY};return cwe(r,e)}ha(uwe,"isPointerInGraceArea");function oT(t){return e=>e.pointerType==="mouse"?t(e):void 0}ha(oT,"whenMouse");var m9e=Object.defineProperty,Yf=(t,e)=>m9e(t,"name",{value:e,configurable:!0}),WK="DropdownMenu",[p9e,uKt]=Nl(WK,[Xbe]),Zf=Xbe(),[g9e,dwe]=p9e(WK),y9e=Yf(t=>{const{__scopeDropdownMenu:e,children:r,dir:n,open:i,defaultOpen:a,onOpenChange:c,modal:d=!0}=t,p=Zf(e),l=N.useRef(null),[g,v]=ph({prop:i,defaultProp:a??!1,onChange:c,caller:WK});return s.jsx(g9e,{scope:e,triggerId:Wl(),triggerRef:l,contentId:Wl(),open:g,onOpenChange:v,onOpenToggle:N.useCallback(()=>v(E=>!E),[v]),modal:d,children:s.jsx(WGe,{...p,open:g,onOpenChange:v,dir:n,modal:d,children:r})})},"DropdownMenu"),x9e="DropdownMenuTrigger",_9e=N.forwardRef(Yf(function(e,r){const{__scopeDropdownMenu:n,disabled:i=!1,...a}=e,c=dwe(x9e,n),d=Zf(n),p=Jn(r,c.triggerRef);return s.jsx(Jbe,{asChild:!0,...d,children:s.jsx(An.button,{type:"button",id:c.triggerId,"aria-haspopup":"menu","aria-expanded":c.open,"aria-controls":c.open?c.contentId:void 0,"data-state":c.open?"open":"closed","data-disabled":i?"":void 0,disabled:i,...a,ref:p,onPointerDown:Qr(e.onPointerDown,l=>{!i&&l.button===0&&l.ctrlKey===!1&&(c.onOpenToggle(),c.open||l.preventDefault())}),onKeyDown:Qr(e.onKeyDown,l=>{i||(["Enter"," "].includes(l.key)&&c.onOpenToggle(),l.key==="ArrowDown"&&c.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})},"DropdownMenuTrigger")),v9e=Yf(t=>{const{__scopeDropdownMenu:e,...r}=t,n=Zf(e);return s.jsx(YGe,{...n,...r})},"DropdownMenuPortal"),b9e="DropdownMenuContent",hwe=N.forwardRef(Yf(function(e,r){const{__scopeDropdownMenu:n,...i}=e,a=dwe(b9e,n),c=Zf(n),d=N.useRef(!1);return s.jsx(XGe,{id:a.contentId,"aria-labelledby":a.triggerId,...c,...i,ref:r,onCloseAutoFocus:Qr(e.onCloseAutoFocus,p=>{var l;d.current||(l=a.triggerRef.current)==null||l.focus(),d.current=!1,p.preventDefault()}),onInteractOutside:Qr(e.onInteractOutside,p=>{const l=p.detail.originalEvent,g=l.button===0&&l.ctrlKey===!0,v=l.button===2||g;(!a.modal||v)&&(d.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})},"DropdownMenuContent")),fwe=N.forwardRef(Yf(function(e,r){const{__scopeDropdownMenu:n,...i}=e,a=Zf(n);return s.jsx(t9e,{...a,...i,ref:r})},"DropdownMenuLabel")),mwe=N.forwardRef(Yf(function(e,r){const{__scopeDropdownMenu:n,...i}=e,a=Zf(n);return s.jsx(GK,{...a,...i,ref:r})},"DropdownMenuItem")),pwe=N.forwardRef(Yf(function(e,r){const{__scopeDropdownMenu:n,...i}=e,a=Zf(n);return s.jsx(r9e,{...a,...i,ref:r})},"DropdownMenuCheckboxItem")),gwe=N.forwardRef(Yf(function(e,r){const{__scopeDropdownMenu:n,...i}=e,a=Zf(n);return s.jsx(a9e,{...a,...i,ref:r})},"DropdownMenuRadioItem")),ywe=N.forwardRef(Yf(function(e,r){const{__scopeDropdownMenu:n,...i}=e,a=Zf(n);return s.jsx(l9e,{...a,...i,ref:r})},"DropdownMenuItemIndicator")),xwe=N.forwardRef(Yf(function(e,r){const{__scopeDropdownMenu:n,...i}=e,a=Zf(n);return s.jsx(c9e,{...a,...i,ref:r})},"DropdownMenuSeparator")),_we=N.forwardRef(Yf(function(e,r){const{__scopeDropdownMenu:n,...i}=e,a=Zf(n);return s.jsx(d9e,{...a,...i,ref:r})},"DropdownMenuSubTrigger")),vwe=N.forwardRef(Yf(function(e,r){const{__scopeDropdownMenu:n,...i}=e,a=Zf(n);return s.jsx(f9e,{...a,...i,ref:r,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})},"DropdownMenuSubContent"));const UP=y9e,VP=_9e,w9e=N.forwardRef(({className:t,inset:e,children:r,...n},i)=>s.jsxs(_we,{ref:i,className:hr("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent focus:bg-accent",e&&"pl-8",t),...n,children:[r,s.jsx(uf,{className:"ml-auto h-4 w-4"})]}));w9e.displayName=_we.displayName;const S9e=N.forwardRef(({className:t,...e},r)=>s.jsx(vwe,{ref:r,className:hr("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...e}));S9e.displayName=vwe.displayName;const xA=N.forwardRef(({className:t,sideOffset:e=4,...r},n)=>s.jsx(v9e,{children:s.jsx(hwe,{ref:n,sideOffset:e,className:hr("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...r})}));xA.displayName=hwe.displayName;const lh=N.forwardRef(({className:t,inset:e,...r},n)=>s.jsx(mwe,{ref:n,className:hr("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",e&&"pl-8",t),...r}));lh.displayName=mwe.displayName;const E9e=N.forwardRef(({className:t,children:e,checked:r,...n},i)=>s.jsxs(pwe,{ref:i,className:hr("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t),checked:r,...n,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(ywe,{children:s.jsx(ql,{className:"h-4 w-4"})})}),e]}));E9e.displayName=pwe.displayName;const T9e=N.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(gwe,{ref:n,className:hr("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t),...r,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(ywe,{children:s.jsx(tT,{className:"h-2 w-2 fill-current"})})}),e]}));T9e.displayName=gwe.displayName;const bwe=N.forwardRef(({className:t,inset:e,...r},n)=>s.jsx(fwe,{ref:n,className:hr("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",t),...r}));bwe.displayName=fwe.displayName;const iC=N.forwardRef(({className:t,...e},r)=>s.jsx(xwe,{ref:r,className:hr("-mx-1 my-1 h-px bg-muted",t),...e}));iC.displayName=xwe.displayName;const A9e=()=>{const{isAssistant:t,actingAsAgent:e,assignedAgents:r,setActingAsAgent:n,isActingAsSelf:i,setActingAsSelf:a}=i5();if(!t)return null;const c=d=>d.split(" ").map(p=>p[0]).join("").toUpperCase().slice(0,2);return s.jsx("div",{className:"fixed top-0 left-0 right-0 z-[2147483647] bg-primary text-primary-foreground px-4 py-1.5 shadow-lg",style:{height:"40px"},children:s.jsxs("div",{className:"container mx-auto flex items-center justify-between gap-4 h-full",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[i?s.jsxs(s.Fragment,{children:[s.jsx(nd,{className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{className:"font-medium text-sm",children:"My Account"})]}):s.jsxs(s.Fragment,{children:[s.jsx(Dc,{className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),s.jsxs(UP,{children:[s.jsx(VP,{asChild:!0,children:s.jsxs(Jt,{variant:"secondary",size:"sm",className:"gap-2 bg-primary-foreground/20 hover:bg-primary-foreground/30 text-primary-foreground border-0",children:[i?s.jsxs(s.Fragment,{children:[s.jsx(nd,{className:"h-4 w-4"}),s.jsx("strong",{children:"My Account"})]}):e?s.jsxs(s.Fragment,{children:[s.jsxs(tf,{className:"h-5 w-5",children:[s.jsx(rf,{src:e.avatar_url||void 0}),s.jsx(nf,{className:"text-[10px] bg-primary-foreground/30",children:c(e.name)})]}),s.jsx("strong",{children:e.name})]}):s.jsx("strong",{children:"Select..."}),s.jsx(ad,{className:"h-3 w-3"})]})}),s.jsxs(xA,{align:"start",className:"z-[2147483647]",children:[s.jsxs(lh,{onClick:a,className:"gap-2",children:[s.jsx(nd,{className:"h-4 w-4"}),s.jsx("span",{children:"My Account"}),i&&s.jsx(Js,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),s.jsx(iC,{}),r.map(d=>s.jsxs(lh,{onClick:()=>n(d),className:"gap-2",children:[s.jsxs(tf,{className:"h-6 w-6",children:[s.jsx(rf,{src:d.avatar_url||void 0}),s.jsx(nf,{className:"text-[10px]",children:c(d.name)})]}),s.jsx("span",{children:d.name}),!i&&d.id===(e==null?void 0:e.id)&&s.jsx(Js,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},d.id))]})]})]}),s.jsx(Js,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:i?"Personal Mode":"Assistant Mode"})]})})};function wwe(){var p,l;const{user:t,isAdmin:e}=_i(),{data:r,isLoading:n}=jr({queryKey:["partnership-membership",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:g}=await Be.from("partnership_memberships").select("id, status, package_id, program_id").eq("user_id",t.id).eq("status","active").maybeSingle();if(!g)return null;const[{data:v},{data:E}]=await Promise.all([Be.from("partnership_packages").select("*").eq("id",g.package_id).maybeSingle(),Be.from("partnership_programs").select("id, name, enabled, brokerage_id").eq("id",g.program_id).maybeSingle()]);return!v||!(E!=null&&E.enabled)?null:{membership:g,pkg:v,program:E}}}),i=N.useMemo(()=>{var g;return new Set(((g=r==null?void 0:r.pkg)==null?void 0:g.included_features)||[])},[r]),a=!!r,c=g=>e||!a?!0:i.has(g),d=g=>{var T,j;const v=((T=r==null?void 0:r.pkg)==null?void 0:T.feature_limits)||{},E=(j=v==null?void 0:v[g])==null?void 0:j.monthly_limit;return typeof E=="number"?E:null};return{isLoading:n,isMember:a,membership:(r==null?void 0:r.membership)??null,pkg:(r==null?void 0:r.pkg)??null,program:(r==null?void 0:r.program)??null,packageKey:((p=r==null?void 0:r.pkg)==null?void 0:p.key)??null,packageName:((l=r==null?void 0:r.pkg)==null?void 0:l.name)??null,features:i,hasFeature:c,limitFor:d,isRestricted:a&&!e}}const KK={crm:"Contacts & CRM",mass_email:"Mass Email",website:"Agent Website",deals:"Deal Pipeline",listing_exchange:"Listing Exchange",smart_card:"Smart Card",guest_book:"Guest Book",landing_pages:"Landing Pages",learn:"Learn & Academy",community:"Community",quickvid:"QuickVid",reelflow:"ReelFlow",direct_mail:"Direct Mail",levelup_attract:"LevelUp Attract",listing_revival:"Listing Revival",fsbo_breakthrough:"By-Owner Breakthrough",weekly_reels:"Weekly Reels",coaching_access:"Coaching",marketing_studio:"Marketing Studio",video_library:"Video Library",presentations:"Presentations",card_studio:"Card Studio",newsletter:"Newsletters",scheduler:"Scheduler",client_portals:"Client Portals",social:"Social Swag"},dKt=Object.keys(KK),k9e={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},ooe={"mission-control":"crm",contacts:"crm","sphere-gaps":"crm","mass-emails":"mass_email","bulk-email":"mass_email",newsletters:"newsletter","my-card":"smart_card","guest-book":"guest_book","landing-pages":"landing_pages","card-studio":"card_studio","direct-mail":"direct_mail",quickvid:"quickvid","video-library":"video_library",reelflow:"reelflow",scheduler:"scheduler",community:"community",coaching:"coaching_access","my-coach":"coaching_access","client-portals":"client_portals",presentations:"presentations","social-swag":"social",attract:"levelup_attract","listing-revival":"listing_revival",fsbo:"fsbo_breakthrough","weekly-reels":"weekly_reels"},I9e={quickvid:"quickvid","smart-card":"smart_card","smart-presentations":"presentations","listing-presentation-studio":"presentations","landing-pages":"landing_pages","guest-book":"guest_book","card-studio":"card_studio","direct-mail":"direct_mail",reelflow:"reelflow","mass-emails":"mass_email","newsletter-pro":"newsletter","listing-studio":"listing_exchange","listing-revival":"listing_revival","fsbo-breakthrough":"fsbo_breakthrough",attract:"levelup_attract",scheduler:"scheduler","client-portals":"client_portals","social-swag":"social","weekly-reels":"weekly_reels"};function j9e(t){return t.id in ooe?ooe[t.id]:k9e[t.primaryCategory]??null}function hKt(t){return I9e[t]??null}const C9e=[["/mission-control/pipeline","deals"],["/mission-control/transactions","deals"],["/mission-control/tasks","deals"],["/mission-control/client-portals","client_portals"],["/mission-control/scheduler","scheduler"],["/mission-control/guest-book","guest_book"],["/mission-control/landing-pages","landing_pages"],["/mission-control/card-studio","card_studio"],["/mission-control/direct-mail","direct_mail"],["/mission-control/video-library","video_library"],["/mission-control/video","quickvid"],["/mission-control/my-card","smart_card"],["/mission-control/listing-presentations","presentations"],["/mission-control/sent-emails","mass_email"],["/mission-control/listings","listing_exchange"],["/mission-control/listing-studio","listing_exchange"],["/mission-control/cma","listing_exchange"],["/apps/listing-presentation-studio","presentations"],["/apps/listing-revival","listing_revival"],["/apps/fsbo-breakthrough","fsbo_breakthrough"],["/marketing-studio","marketing_studio"],["/social-swag","social"],["/weekly-reels","weekly_reels"],["/newsletters","newsletter"],["/email-campaigns","mass_email"],["/templates","marketing_studio"],["/reelflow","reelflow"],["/attract","levelup_attract"],["/community","community"],["/coaching","coaching_access"],["/my-coach","coaching_access"],["/events","learn"],["/academy","learn"],["/levelup-u","learn"],["/toolbox","learn"],["/programs","learn"]];function P9e(t){let e=null;for(const r of C9e){const[n]=r;(t===n||t.startsWith(n+"/")||t.startsWith(n+"?"))&&(!e||n.length>e[0].length)&&(e=r)}return e?e[1]:null}const wi=N.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:hr("rounded-lg border bg-card text-card-foreground shadow-sm",t),...e}));wi.displayName="Card";const Wh=N.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:hr("flex flex-col space-y-1.5 p-6",t),...e}));Wh.displayName="CardHeader";const Kh=N.forwardRef(({className:t,...e},r)=>s.jsx("h3",{ref:r,className:hr("text-2xl font-semibold leading-none tracking-tight",t),...e}));Kh.displayName="CardTitle";const sC=N.forwardRef(({className:t,...e},r)=>s.jsx("p",{ref:r,className:hr("text-sm text-muted-foreground",t),...e}));sC.displayName="CardDescription";const Di=N.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:hr("p-6 pt-0",t),...e}));Di.displayName="CardContent";const IG=N.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:hr("flex items-center p-6 pt-0",t),...e}));IG.displayName="CardFooter";const df=N.forwardRef(({className:t,...e},r)=>s.jsx("textarea",{className:hr("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),ref:r,...e}));df.displayName="Textarea";const gl=D4,Swe=oK,N9e=M4,fKt=FP,Ewe=N.forwardRef(({className:t,...e},r)=>s.jsx(oA,{ref:r,className:hr("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...e}));Ewe.displayName=oA.displayName;const Jo=N.forwardRef(({className:t,children:e,overlayClassName:r,...n},i)=>s.jsxs(N9e,{children:[s.jsx(Ewe,{className:r}),s.jsxs(lA,{ref:i,className:hr("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...n,children:[e,s.jsxs(FP,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[s.jsx(Ra,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Jo.displayName=lA.displayName;const Bc=({className:t,...e})=>s.jsx("div",{className:hr("flex flex-col space-y-1.5 text-center sm:text-left",t),...e});Bc.displayName="DialogHeader";const Twe=({className:t,...e})=>s.jsx("div",{className:hr("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});Twe.displayName="DialogFooter";const pc=N.forwardRef(({className:t,...e},r)=>s.jsx(MP,{ref:r,className:hr("text-lg font-semibold leading-none tracking-tight",t),...e}));pc.displayName=MP.displayName;const sf=N.forwardRef(({className:t,...e},r)=>s.jsx(OP,{ref:r,className:hr("text-sm text-muted-foreground",t),...e}));sf.displayName=OP.displayName;function R9e({featureKey:t,open:e,onOpenChange:r}){const{user:n}=_i(),i=Ur(),[a,c]=N.useState(""),{data:d}=jr({queryKey:["partnership-upgrade-requests",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&e,queryFn:async()=>{const{data:v}=await Be.from("lead_site_upgrade_requests").select("id, feature_key, status").eq("user_id",n.id);return v||[]}}),p=!!(d!=null&&d.some(v=>v.feature_key===t&&v.status!=="declined")),l=zr({mutationFn:async()=>{const{error:v}=await Be.from("lead_site_upgrade_requests").insert({user_id:n.id,feature_key:t,notes:a||null});if(v)throw v},onSuccess:()=>{i.invalidateQueries({queryKey:["partnership-upgrade-requests"]}),lr.success("Request sent — we'll be in touch shortly."),c(""),r(!1)},onError:v=>lr.error((v==null?void 0:v.message)||"Could not send your request")}),g=KK[t]||t;return s.jsx(gl,{open:e,onOpenChange:r,children:s.jsxs(Jo,{className:"sm:max-w-md",children:[s.jsxs(Bc,{children:[s.jsxs(pc,{className:"flex items-center gap-2",children:[s.jsx(va,{className:"h-5 w-5 text-primary"}),"Request ",g]}),s.jsxs(sf,{children:[g," is included with the Signature package. Send a request and we'll get you set up."]})]}),p?s.jsxs("div",{className:"rounded-lg border border-border bg-muted/40 p-4 text-sm flex items-start gap-2",children:[s.jsx(ql,{className:"h-4 w-4 mt-0.5 text-primary"}),s.jsx("span",{children:"You've already requested this. We'll follow up soon."})]}):s.jsx(df,{placeholder:"Anything we should know? (optional)",value:a,onChange:v=>c(v.target.value),rows:4}),s.jsxs(Twe,{children:[s.jsx(Jt,{variant:"outline",onClick:()=>r(!1),children:"Close"}),!p&&s.jsx(Jt,{onClick:()=>l.mutate(),disabled:l.isPending,children:l.isPending?"Sending…":"Send request"})]})]})})}function L9e({featureKey:t}){const[e,r]=N.useState(!1),n=KK[t]||t;return s.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[s.jsx(wi,{className:"max-w-lg w-full border-border/60",children:s.jsxs(Di,{className:"p-8 text-center space-y-4",children:[s.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:s.jsx(xv,{className:"h-6 w-6 text-primary"})}),s.jsxs("h2",{className:"text-2xl font-semibold",children:[n," is a Signature feature"]}),s.jsxs("p",{className:"text-muted-foreground",children:["Your current package doesn't include ",n,". Request access and our team will upgrade your account."]}),s.jsxs(Jt,{onClick:()=>r(!0),className:"gap-2",children:[s.jsx(va,{className:"h-4 w-4"})," Request access"]})]})}),s.jsx(R9e,{featureKey:t,open:e,onOpenChange:r})]})}const D9e=t=>{const[e,r]=N.useState(null),[n,i]=N.useState(!0);return N.useEffect(()=>{if(!t){i(!1);return}(async()=>{try{const{data:d}=await Be.storage.from("avatars").list(`${t}`);if(d&&d.length>0){const{data:p}=Be.storage.from("avatars").getPublicUrl(`${t}/${d[0].name}`);r(`${p.publicUrl}?t=${Date.now()}`)}else r(null)}catch(d){console.error("Error fetching avatar:",d),r(null)}finally{i(!1)}})()},[t]),{avatarUrl:e,loading:n,refreshAvatar:async()=>{if(t)try{const{data:c}=await Be.storage.from("avatars").list(`${t}`);if(c&&c.length>0){const{data:d}=Be.storage.from("avatars").getPublicUrl(`${t}/${c[0].name}`);r(`${d.publicUrl}?t=${Date.now()}`)}}catch(c){console.error("Error refreshing avatar:",c)}}}},mKt=async t=>{const e=new Map;return await Promise.all(t.map(async r=>{try{const{data:n}=await Be.storage.from("avatars").list(`${r}`);if(n&&n.length>0){const{data:i}=Be.storage.from("avatars").getPublicUrl(`${r}/${n[0].name}`);e.set(r,i.publicUrl)}}catch{}})),e},M9e=t=>{const[e,r]=N.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return N.useEffect(()=>{if(!t){r(i=>({...i,loading:!1}));return}(async()=>{try{const{data:i,error:a}=await Be.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",t).single();if(a){console.error("Error fetching trial status:",a),r(v=>({...v,loading:!1}));return}const c=(i==null?void 0:i.subscription_status)==="trialing",d=!!(i!=null&&i.is_trial),p=!!(i!=null&&i.trial_expires_at)&&new Date(i.trial_expires_at).getTime()>Date.now()&&(i==null?void 0:i.subscription_status)!=="active",l=c&&(i==null?void 0:i.subscription_end_date)||(i==null?void 0:i.trial_expires_at)||(i==null?void 0:i.subscription_end_date)||null;if((c||d||p)&&!!l&&l){const v=new Date().getTime(),E=new Date(l).getTime(),T=Math.ceil((E-v)/(1e3*60*60*24)),j=T<=0;r({isTrial:!0,isExpired:j,expiresAt:l,daysLeft:j?0:T,loading:!1})}else r({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(i){console.error("Error in useTrialStatus:",i),r(a=>({...a,loading:!1}))}})()},[t]),e},l5=()=>{const{data:t,isLoading:e}=jr({queryKey:["feature-flags"],queryFn:async()=>{const{data:n,error:i}=await Be.from("feature_flags").select("*");if(i)throw i;return n}}),r=n=>{if(!t)return!1;const i=t.find(a=>a.key===n);return(i==null?void 0:i.enabled)??!1};return{flags:t,isLoading:e,isFeatureEnabled:r,isAgentOSEnabled:r("agent_os_enabled"),isInnerCircleEnabled:r("innercircle_enabled"),isMarketplaceEnabled:r("marketplace")}},loe="community_last_seen_post_at";function O9e(){const{user:t}=_i(),e=ms(),[r,n]=N.useState(0),[i,a]=N.useState(null);N.useEffect(()=>{if(!t)return;const d=localStorage.getItem(`${loe}_${t.id}`);a(d)},[t]),N.useEffect(()=>{if(!t)return;const d=`community_unread_count_${t.id}`,p=2*60*1e3;(async()=>{try{const T=sessionStorage.getItem(d);if(T){const j=JSON.parse(T);if(j.ts&&Date.now()-j.ts{if(!t)return;const d=Be.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async p=>{const l=p.new;if(l.user_id===t.id)return;const g=e.pathname==="/community";g||n(P=>P+1);const{data:v}=await Be.from("profiles").select("name").eq("id",l.user_id).single(),E=(v==null?void 0:v.name)||"Someone",T=l.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),j=T.length>50?T.substring(0,50)+"...":T;g||lr("New Community Post",{description:`${E}: ${j}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{Be.removeChannel(d)}},[t,e.pathname]);const c=N.useCallback(()=>{if(!t)return;const d=new Date().toISOString();localStorage.setItem(`${loe}_${t.id}`,d),a(d),n(0)},[t]);return N.useEffect(()=>{e.pathname==="/community"&&r>0&&c()},[e.pathname,r,c]),{unreadCount:r,markAsRead:c}}function F9e(){const{isAdmin:t}=_i(),{data:e=0}=jr({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:r,error:n}=await Be.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(n)throw n;return r||0},enabled:t,staleTime:6e4});return{openCount:t?e:0}}const hU=t=>`levelup:activeTeam:${t}`,B9e=()=>{const t=qs();return jr({queryKey:["user-teams",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("team_members").select("id, team_id, role").eq("user_id",t);if(r)throw r;if(!(e!=null&&e.length))return[];const{data:n,error:i}=await Be.from("teams").select("*").in("id",e.map(c=>c.team_id));if(i)throw i;const a=new Map((n||[]).map(c=>[c.id,c]));return e.filter(c=>a.has(c.team_id)).map(c=>({membershipId:c.id,teamId:c.team_id,role:c.role,team:a.get(c.team_id)})).sort((c,d)=>{var p,l;return c.role!==d.role?c.role==="team_leader"?-1:1:(((p=c.team)==null?void 0:p.name)||"").localeCompare(((l=d.team)==null?void 0:l.name)||"")})},enabled:!!t,staleTime:5*60*1e3})},_A=()=>{const t=qs(),e=B9e(),r=N.useMemo(()=>e.data||[],[e.data]),[n,i]=N.useState(()=>!t||typeof window>"u"?null:window.localStorage.getItem(hU(t)));N.useEffect(()=>{!t||typeof window>"u"||i(window.localStorage.getItem(hU(t)))},[t]);const a=N.useCallback(d=>{i(d),t&&typeof window<"u"&&window.localStorage.setItem(hU(t),d)},[t]),c=N.useMemo(()=>r.length?r.find(d=>d.teamId===n)||r[0]:null,[r,n]);return{...e,data:c,teams:r,activeTeamId:(c==null?void 0:c.teamId)??null,setActiveTeamId:a}},coe="weekly_reels";function YK(){const{user:t,loading:e,isAdmin:r}=_i(),{data:n,isLoading:i}=jr({queryKey:["feature-entitlement",coe,t==null?void 0:t.id],enabled:!!t&&!r,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:c}=await Be.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",t.id).eq("feature_key",coe).maybeSingle();if(c)throw c;return a?{hasAccess:a.enabled&&(!a.expires_at||new Date(a.expires_at).getTime()>Date.now()),tier:a.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:r||!!(n!=null&&n.hasAccess),tier:r?"admin":(n==null?void 0:n.tier)??null,isLoading:e||!r&&!!t&&i}}const Awe=D4,z9e=oK,$9e=M4,kwe=N.forwardRef(({className:t,...e},r)=>s.jsx(oA,{className:hr("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...e,ref:r}));kwe.displayName=oA.displayName;const U9e=eA("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),ZK=N.forwardRef(({side:t="right",className:e,children:r,...n},i)=>s.jsxs($9e,{children:[s.jsx(kwe,{}),s.jsxs(lA,{ref:i,className:hr(U9e({side:t}),e),...n,children:[r,s.jsxs(FP,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[s.jsx(Ra,{className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));ZK.displayName=lA.displayName;const Iwe=({className:t,...e})=>s.jsx("div",{className:hr("flex flex-col space-y-2 text-center sm:text-left",t),...e});Iwe.displayName="SheetHeader";const V9e=({className:t,...e})=>s.jsx("div",{className:hr("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});V9e.displayName="SheetFooter";const jwe=N.forwardRef(({className:t,...e},r)=>s.jsx(MP,{ref:r,className:hr("text-lg font-semibold text-foreground",t),...e}));jwe.displayName=MP.displayName;const Cwe=N.forwardRef(({className:t,...e},r)=>s.jsx(OP,{ref:r,className:hr("text-sm text-muted-foreground",t),...e}));Cwe.displayName=OP.displayName;var q9e=Object.defineProperty,G9e=(t,e)=>q9e(t,"name",{value:e,configurable:!0});function lw(t,[e,r]){return Math.min(r,Math.max(e,t))}G9e(lw,"clamp");var H9e=Object.defineProperty,Ps=(t,e)=>H9e(t,"name",{value:e,configurable:!0});function Pwe(t,e){return N.useReducer((r,n)=>e[r][n]??r,t)}Ps(Pwe,"useStateMachine");var nE={Auto:"auto",Always:"always",Scroll:"scroll",Hover:"hover"},AE={Vertical:"vertical",Horizontal:"horizontal"},fg={LTR:"ltr",RTL:"rtl"},Nwe="ScrollArea",[Rwe,pKt]=Nl(Nwe),[W9e,hf]=Rwe(Nwe),Lwe=N.forwardRef(Ps(function(e,r){const{__scopeScrollArea:n,type:i=nE.Hover,dir:a,scrollHideDelay:c=600,...d}=e,[p,l]=N.useState(null),[g,v]=N.useState(null),[E,T]=N.useState(null),[j,P]=N.useState(null),[C,L]=N.useState(null),[O,F]=N.useState(0),[$,G]=N.useState(0),[W,Z]=N.useState(!1),[Q,ee]=N.useState(!1),ie=Jn(r,l),oe=Uv(a);return s.jsx(W9e,{scope:n,type:i,dir:oe,scrollHideDelay:c,scrollArea:p,viewport:g,onViewportChange:v,content:E,onContentChange:T,scrollbarX:j,onScrollbarXChange:P,scrollbarXEnabled:W,onScrollbarXEnabledChange:Z,scrollbarY:C,onScrollbarYChange:L,scrollbarYEnabled:Q,onScrollbarYEnabledChange:ee,onCornerWidthChange:F,onCornerHeightChange:G,children:s.jsx(An.div,{dir:oe,...d,ref:ie,style:{position:"relative","--radix-scroll-area-corner-width":O+"px","--radix-scroll-area-corner-height":$+"px",...e.style}})})},"ScrollArea")),Dwe="ScrollAreaViewport",uoe=BW(Dwe),K9e=N.forwardRef(Ps(function(e,r){const{__scopeScrollArea:n,children:i,nonce:a,disableImplicitContentElement:c,...d}=e,p=hf(Dwe,n),l=N.useRef(null),g=Jn(r,l,p.onViewportChange),v=N.isValidElement(i);return s.jsxs(s.Fragment,{children:[s.jsx(Y9e,{nonce:a}),s.jsx(An.div,{"data-radix-scroll-area-viewport":"",...d,ref:g,style:{overflowX:p.scrollbarXEnabled?"scroll":"hidden",overflowY:p.scrollbarYEnabled?"scroll":"hidden",...e.style},children:c?i:v?s.jsx(uoe,{child:i,children:E=>s.jsx(doe,{__scopeScrollArea:n,children:E})}):s.jsx(uoe,{children:s.jsx(doe,{__scopeScrollArea:n,children:i})})})]})},"ScrollAreaViewport")),Y9e=N.memo(Ps(function({nonce:e}){return s.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:e})},"ScrollAreaViewportStyle"),(t,e)=>t.nonce===e.nonce),Z9e="ScrollAreaContent",doe=N.forwardRef(Ps(function(e,r){const{__scopeScrollArea:n,children:i,...a}=e,c=hf(Z9e,n),d=Jn(r,c.onContentChange);return s.jsx(An.div,{...a,ref:d,style:{minWidth:"100%",display:"table",...e.style},children:i})},"ScrollAreaContent")),ax="ScrollAreaScrollbar",Mwe=N.forwardRef(Ps(function(e,r){const{forceMount:n,...i}=e,a=hf(ax,e.__scopeScrollArea),{onScrollbarXEnabledChange:c,onScrollbarYEnabledChange:d}=a,p=e.orientation===AE.Horizontal;return N.useEffect(()=>(p?c(!0):d(!0),()=>{p?c(!1):d(!1)}),[p,c,d]),a.type===nE.Hover?s.jsx(X9e,{...i,ref:r,forceMount:n}):a.type===nE.Scroll?s.jsx(Q9e,{...i,ref:r,forceMount:n}):a.type===nE.Auto?s.jsx(Owe,{...i,ref:r,forceMount:n}):a.type===nE.Always?s.jsx(XK,{...i,ref:r,"data-state":"visible"}):null},"ScrollAreaScrollbar")),X9e=N.forwardRef(Ps(function(e,r){const{forceMount:n,...i}=e,a=hf(ax,e.__scopeScrollArea),[c,d]=N.useState(!1);return N.useEffect(()=>{const p=a.scrollArea;let l=0;if(p){const g=Ps(()=>{window.clearTimeout(l),d(!0)},"handlePointerEnter"),v=Ps(()=>{l=window.setTimeout(()=>d(!1),a.scrollHideDelay)},"handlePointerLeave");return p.addEventListener("pointerenter",g),p.addEventListener("pointerleave",v),()=>{window.clearTimeout(l),p.removeEventListener("pointerenter",g),p.removeEventListener("pointerleave",v)}}},[a.scrollArea,a.scrollHideDelay]),s.jsx(zc,{present:n||c,children:s.jsx(Owe,{"data-state":c?"visible":"hidden",...i,ref:r})})},"ScrollAreaScrollbarHover")),Q9e=N.forwardRef(Ps(function(e,r){const{forceMount:n,...i}=e,a=hf(ax,e.__scopeScrollArea),c=e.orientation===AE.Horizontal,d=GP(()=>l("SCROLL_END"),100),[p,l]=Pwe("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return N.useEffect(()=>{if(p==="idle"){const g=window.setTimeout(()=>l("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(g)}},[p,a.scrollHideDelay,l]),N.useEffect(()=>{const g=a.viewport,v=c?"scrollLeft":"scrollTop";if(g){let E=g[v];const T=Ps(()=>{const j=g[v];E!==j&&(l("SCROLL"),d()),E=j},"handleScroll");return g.addEventListener("scroll",T),()=>g.removeEventListener("scroll",T)}},[a.viewport,c,l,d]),s.jsx(zc,{present:n||p!=="hidden",children:s.jsx(XK,{"data-state":p==="hidden"?"hidden":"visible",...i,ref:r,onPointerEnter:Qr(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:Qr(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})},"ScrollAreaScrollbarScroll")),Owe=N.forwardRef(Ps(function(e,r){const n=hf(ax,e.__scopeScrollArea),{forceMount:i,...a}=e,[c,d]=N.useState(!1),p=e.orientation===AE.Horizontal,l=GP(()=>{if(n.viewport){const g=n.viewport.offsetWidth0&&g<1,onThumbChange:Ps(T=>c.current=T,"onThumbChange"),onThumbPointerUp:Ps(()=>d.current=0,"onThumbPointerUp"),onThumbPointerDown:Ps(T=>d.current=T,"onThumbPointerDown")};function E(T,j){return $we(T,d.current,p,j)}return Ps(E,"getScrollPosition"),n===AE.Horizontal?s.jsx(J9e,{...v,ref:r,onThumbPositionChange:()=>{if(a.viewport&&c.current){const T=a.viewport.scrollLeft,j=CG(T,p,a.dir);c.current.style.transform=`translate3d(${j}px, 0, 0)`}},onWheelScroll:T=>{a.viewport&&(a.viewport.scrollLeft=T)},onDragScroll:T=>{a.viewport&&(a.viewport.scrollLeft=E(T,a.dir))}}):n===AE.Vertical?s.jsx(e7e,{...v,ref:r,onThumbPositionChange:()=>{if(a.viewport&&c.current){const T=a.viewport.scrollTop,j=CG(T,p);c.current.style.transform=`translate3d(0, ${j}px, 0)`}},onWheelScroll:T=>{a.viewport&&(a.viewport.scrollTop=T)},onDragScroll:T=>{a.viewport&&(a.viewport.scrollTop=E(T))}}):null},"ScrollAreaScrollbarVisible")),J9e=N.forwardRef(Ps(function(e,r){const{sizes:n,onSizesChange:i,...a}=e,c=hf(ax,e.__scopeScrollArea),[d,p]=N.useState(),l=N.useRef(null),g=Jn(r,l,c.onScrollbarXChange);return N.useEffect(()=>{l.current&&p(getComputedStyle(l.current))},[l]),s.jsx(Bwe,{"data-orientation":"horizontal",...a,ref:g,sizes:n,style:{bottom:0,left:c.dir===fg.RTL?"var(--radix-scroll-area-corner-width)":0,right:c.dir===fg.LTR?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":qP(n)+"px",...e.style},onThumbPointerDown:v=>e.onThumbPointerDown(v.x),onDragScroll:v=>e.onDragScroll(v.x),onWheelScroll:(v,E)=>{if(c.viewport){const T=c.viewport.scrollLeft+v.deltaX;e.onWheelScroll(T),eY(T,E)&&v.preventDefault()}},onResize:()=>{l.current&&c.viewport&&d&&i({content:c.viewport.scrollWidth,viewport:c.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:aC(d.paddingLeft),paddingEnd:aC(d.paddingRight)}})}})},"ScrollAreaScrollbarX")),e7e=N.forwardRef(Ps(function(e,r){const{sizes:n,onSizesChange:i,...a}=e,c=hf(ax,e.__scopeScrollArea),[d,p]=N.useState(),l=N.useRef(null),g=Jn(r,l,c.onScrollbarYChange);return N.useEffect(()=>{l.current&&p(getComputedStyle(l.current))},[l]),s.jsx(Bwe,{"data-orientation":"vertical",...a,ref:g,sizes:n,style:{top:0,right:c.dir===fg.LTR?0:void 0,left:c.dir===fg.RTL?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":qP(n)+"px",...e.style},onThumbPointerDown:v=>e.onThumbPointerDown(v.y),onDragScroll:v=>e.onDragScroll(v.y),onWheelScroll:(v,E)=>{if(c.viewport){const T=c.viewport.scrollTop+v.deltaY;e.onWheelScroll(T),eY(T,E)&&v.preventDefault()}},onResize:()=>{l.current&&c.viewport&&d&&i({content:c.viewport.scrollHeight,viewport:c.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:aC(d.paddingTop),paddingEnd:aC(d.paddingBottom)}})}})},"ScrollAreaScrollbarY")),[t7e,Fwe]=Rwe(ax),Bwe=N.forwardRef(Ps(function(e,r){const{__scopeScrollArea:n,sizes:i,hasThumb:a,onThumbChange:c,onThumbPointerUp:d,onThumbPointerDown:p,onThumbPositionChange:l,onDragScroll:g,onWheelScroll:v,onResize:E,...T}=e,j=hf(ax,n),[P,C]=N.useState(null),L=Jn(r,C),O=N.useRef(null),F=N.useRef(""),$=j.viewport,G=i.content-i.viewport,W=Yo(v),Z=Yo(l),Q=GP(E,10);function ee(ie){if(O.current){const oe=ie.clientX-O.current.left,pe=ie.clientY-O.current.top;g({x:oe,y:pe})}}return Ps(ee,"handleDragScroll"),N.useEffect(()=>{const ie=Ps(oe=>{const pe=oe.target;(P==null?void 0:P.contains(pe))&&W(oe,G)},"handleWheel");return document.addEventListener("wheel",ie,{passive:!1}),()=>document.removeEventListener("wheel",ie,{passive:!1})},[$,P,G,W]),N.useEffect(Z,[i,Z]),cw(P,Q),cw(j.content,Q),s.jsx(t7e,{scope:n,scrollbar:P,hasThumb:a,onThumbChange:Yo(c),onThumbPointerUp:Yo(d),onThumbPositionChange:Z,onThumbPointerDown:Yo(p),children:s.jsx(An.div,{...T,ref:L,style:{position:"absolute",...T.style},onPointerDown:Qr(e.onPointerDown,ie=>{ie.button===0&&(ie.target.setPointerCapture(ie.pointerId),O.current=P.getBoundingClientRect(),F.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",j.viewport&&(j.viewport.style.scrollBehavior="auto"),ee(ie))}),onPointerMove:Qr(e.onPointerMove,ee),onPointerUp:Qr(e.onPointerUp,ie=>{const oe=ie.target;oe.hasPointerCapture(ie.pointerId)&&oe.releasePointerCapture(ie.pointerId),document.body.style.webkitUserSelect=F.current,j.viewport&&(j.viewport.style.scrollBehavior=""),O.current=null})})})},"ScrollAreaScrollbarImpl")),jG="ScrollAreaThumb",r7e=N.forwardRef(Ps(function(e,r){const{forceMount:n,...i}=e,a=Fwe(jG,e.__scopeScrollArea);return s.jsx(zc,{present:n||a.hasThumb,children:s.jsx(n7e,{ref:r,...i})})},"ScrollAreaThumb")),n7e=N.forwardRef(Ps(function(e,r){const{__scopeScrollArea:n,style:i,...a}=e,c=hf(jG,n),d=Fwe(jG,n),{onThumbPositionChange:p}=d,l=Jn(r,d.onThumbChange),g=N.useRef(void 0),v=GP(()=>{g.current&&(g.current(),g.current=void 0)},100);return N.useEffect(()=>{const E=c.viewport;if(E){const T=Ps(()=>{if(v(),!g.current){const j=a7e(E,p);g.current=j,p()}},"handleScroll");return p(),E.addEventListener("scroll",T),()=>E.removeEventListener("scroll",T)}},[c.viewport,v,p]),s.jsx(An.div,{"data-state":d.hasThumb?"visible":"hidden",...a,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...i},onPointerDownCapture:Qr(e.onPointerDownCapture,E=>{const j=E.target.getBoundingClientRect(),P=E.clientX-j.left,C=E.clientY-j.top;d.onThumbPointerDown({x:P,y:C})}),onPointerUp:Qr(e.onPointerUp,d.onThumbPointerUp)})},"ScrollAreaThumbImpl")),zwe="ScrollAreaCorner",i7e=N.forwardRef(Ps(function(e,r){const n=hf(zwe,e.__scopeScrollArea),i=!!(n.scrollbarX&&n.scrollbarY);return n.type!==nE.Scroll&&i?s.jsx(s7e,{...e,ref:r}):null},"ScrollAreaCorner")),s7e=N.forwardRef(Ps(function(e,r){const{__scopeScrollArea:n,...i}=e,a=hf(zwe,n),[c,d]=N.useState(0),[p,l]=N.useState(0),g=!!(c&&p),{onCornerWidthChange:v,onCornerHeightChange:E}=a;return cw(a.scrollbarX,()=>{var j;const T=((j=a.scrollbarX)==null?void 0:j.offsetHeight)||0;a.onCornerHeightChange(T),l(T)}),cw(a.scrollbarY,()=>{var j;const T=((j=a.scrollbarY)==null?void 0:j.offsetWidth)||0;a.onCornerWidthChange(T),d(T)}),N.useEffect(()=>()=>{v(0),E(0)},[v,E]),g?s.jsx(An.div,{...i,ref:r,style:{width:c,height:p,position:"absolute",right:a.dir===fg.LTR?0:void 0,left:a.dir===fg.RTL?0:void 0,bottom:0,...e.style}}):null},"ScrollAreaCornerImpl"));function aC(t){return t?parseInt(t,10):0}Ps(aC,"toInt");function QK(t,e){const r=t/e;return isNaN(r)?0:r}Ps(QK,"getThumbRatio");function qP(t){const e=QK(t.viewport,t.content),r=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,n=(t.scrollbar.size-r)*e;return Math.max(n,18)}Ps(qP,"getThumbSize");function $we(t,e,r,n=fg.LTR){const i=qP(r),a=i/2,c=e||a,d=i-c,p=r.scrollbar.paddingStart+c,l=r.scrollbar.size-r.scrollbar.paddingEnd-d,g=r.content-r.viewport,v=n===fg.LTR?[0,g]:[g*-1,0];return JK([p,l],v)(t)}Ps($we,"getScrollPositionFromPointer");function CG(t,e,r=fg.LTR){const n=qP(e),i=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,a=e.scrollbar.size-i,c=e.content-e.viewport,d=a-n,p=r===fg.LTR?[0,c]:[c*-1,0],l=lw(t,p);return JK([0,c],[0,d])(l)}Ps(CG,"getThumbOffsetFromScroll");function JK(t,e){return r=>{if(t[0]===t[1]||e[0]===e[1])return e[0];const n=(e[1]-e[0])/(t[1]-t[0]);return e[0]+n*(r-t[0])}}Ps(JK,"linearScale");function eY(t,e){return t>0&&t{})=>{let r={left:t.scrollLeft,top:t.scrollTop},n=0;function i(){const a={left:t.scrollLeft,top:t.scrollTop},c=r.left!==a.left,d=r.top!==a.top;(c||d)&&e(),r=a,n=window.requestAnimationFrame(i)}return Ps(i,"loop"),i(),()=>window.cancelAnimationFrame(n)},"addUnlinkedScrollListener");function GP(t,e){const r=Yo(t),n=N.useRef(0);return N.useEffect(()=>()=>window.clearTimeout(n.current),[]),N.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,e)},[r,e])}Ps(GP,"useDebounceCallback");function cw(t,e){const r=Yo(e);no(()=>{let n=0;if(t){const i=new ResizeObserver(()=>{cancelAnimationFrame(n),n=window.requestAnimationFrame(r)});return i.observe(t),()=>{window.cancelAnimationFrame(n),i.unobserve(t)}}},[t,r])}Ps(cw,"useResizeObserver");const Eg=N.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(Lwe,{ref:n,className:hr("relative overflow-hidden",t),...r,children:[s.jsx(K9e,{className:"h-full w-full rounded-[inherit]",children:e}),s.jsx(Uwe,{}),s.jsx(i7e,{})]}));Eg.displayName=Lwe.displayName;const Uwe=N.forwardRef(({className:t,orientation:e="vertical",...r},n)=>s.jsx(Mwe,{ref:n,orientation:e,className:hr("flex touch-none select-none transition-colors",e==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",e==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",t),...r,children:s.jsx(r7e,{className:"relative flex-1 rounded-full bg-border"})}));Uwe.displayName=Mwe.displayName;const o7e="/assets/levelup-logo-Eif24dqY.png",l7e="/assets/levelup-logo-icon-C-7iromj.png",c7e="/assets/levelup-logo-mobile-B9skSjUG.png";var vA=t=>t.type==="checkbox",c5=t=>t.type==="file",Ib=t=>t instanceof Date,Tl=t=>t==null;const tY=t=>typeof t=="object";var Go=t=>!Tl(t)&&!Array.isArray(t)&&tY(t)&&!Ib(t),PG=t=>Go(t)&&t.target?vA(t.target)?t.target.checked:c5(t.target)?t.target.files:t.target.value:t;const u7e=/[.[\]'"]/;var bA=t=>t.split(u7e).filter(Boolean);function d7e(t,e){const r=bA(e);let n=t._formValues,i=t._defaultValues;for(let a=0;ae.split(".").some((r,n,i)=>!isNaN(Number(r))&&t.has(i.slice(0,n).join("."))),u5=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Pa(t){if(t===null||typeof t!="object")return t;if(t instanceof Date)return new Date(t);const e=typeof Blob<"u"&&t instanceof Blob,r=typeof FileList<"u"&&t instanceof FileList;if(u5&&(e||r))return t;const n=Array.isArray(t),i=Object.getPrototypeOf(t);if(!n&&i&&i.constructor!==Object)return t;const a=n?new Array(t.length):Object.create(i);for(const c in t)Object.prototype.hasOwnProperty.call(t,c)&&(a[c]=Pa(t[c]));return a}const C_={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},Df={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Qc={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},h7e=[Qc.required,Qc.min,Qc.max,Qc.minLength,Qc.maxLength,Qc.pattern,Qc.validate],OI="form",qwe="root",rY=["__proto__","constructor","prototype"],f7e=/^\w*$/;var HP=t=>f7e.test(t),Cs=t=>t===void 0,ln=(t,e,r)=>{if(!e||!Go(t))return r;const n=HP(e)?[e]:bA(e);if(n.some(a=>rY.includes(a)))return r;const i=n.reduce((a,c)=>Tl(a)?void 0:a[c],t);return Cs(i)||i===t?Cs(t[e])?r:t[e]:i},sh=t=>typeof t=="boolean",Nu=t=>typeof t=="function",sa=(t,e,r)=>{let n=-1;const i=HP(e)?[e]:bA(e),a=i.length,c=a-1;for(;++net.useContext(nY);var Gwe=(t,e,r,n=!0)=>{const i={};for(const a in t)Object.defineProperty(i,a,{get:()=>{const c=a;return e._proxyFormState[c]!==Df.all&&(e._proxyFormState[c]=!n||Df.all),r&&(r[c]=!0),t[c]}});return i};const sY=u5?et.useLayoutEffect:et.useEffect;var m7e=t=>{const e=t.constructor&&t.constructor.prototype;return Go(e)&&e.hasOwnProperty("isPrototypeOf")},NG=t=>Tl(t)||!tY(t);const hoe=(t,e)=>e.length===0&&!Array.isArray(t)&&Object.getPrototypeOf(t)!==null&&!m7e(t);function Iu(t,e,r=!1,n=new WeakMap){if(t===e)return!0;if(NG(t)||NG(e))return Object.is(t,e);if(Ib(t)&&Ib(e))return Object.is(t.getTime(),e.getTime());if(Array.isArray(t)&&Array.isArray(e)&&t.length!==e.length)return!1;const i=Object.keys(t),a=Object.keys(e);if(i.length!==a.length)return!1;if(hoe(t,i)||hoe(e,a))return Object.is(t,e);if(!i.length&&Array.isArray(t)!==Array.isArray(e))return!1;const c=n.get(t);if(c&&c.has(e))return!0;if(c)c.add(e);else{const d=new WeakSet;d.add(e),n.set(t,d)}for(const d of i){const p=t[d];if(!Object.prototype.hasOwnProperty.call(e,d))return!1;if(!r||d!=="ref"){const l=e[d];if(Ib(p)&&Ib(l)||(Go(p)||Array.isArray(p))&&(Go(l)||Array.isArray(l))?!Iu(p,l,r,n):!Object.is(p,l))return!1}}return!0}function aY(t){const e=et.useRef(!1),r=et.useRef(!1),n=et.useRef(void 0),i=et.useRef(0);i.current++,!r.current&&t&&(r.current=!0,n.current=Pa(t()));const a=et.useCallback((d,p,l)=>{if(d&&(e.current||r.current&&i.current>1)){const g=p();Iu(n.current,g)||l(g)}e.current=!0},[]),c=et.useCallback((d,p)=>{d&&(n.current=Pa(p()))},[]);return{resyncIfNeeded:a,snapshot:c}}function p7e(t){const e=iY(),{control:r=e,disabled:n,name:i,exact:a}=t||{},c=()=>({...r._formState,defaultValues:r._defaultValues}),[d,p]=et.useState(c),l=et.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),{resyncIfNeeded:g,snapshot:v}=aY(c);return sY(()=>{g(!n,c,p);const E=r._subscribe({name:i,formState:l.current,exact:a,callback:T=>{!n&&p({...r._formState,...T,defaultValues:r._defaultValues})}});return()=>{E(),v(!n,c)}},[r,i,n,a,g,v]),et.useEffect(()=>{l.current.isValid&&r._setValid(!0)},[r]),et.useMemo(()=>Gwe(d,r,l.current,!1),[d,r])}var Ru=t=>typeof t=="string",RG=(t,e,r,n,i)=>Ru(t)?(n&&e.watch.add(t),ln(r,t,i)):Array.isArray(t)?t.map(a=>(n&&e.watch.add(a),ln(r,a,ln(i,a)))):(n&&(e.watchAll=!0),r);function g7e(t){const e=iY(),{control:r=e,name:n,defaultValue:i,disabled:a,exact:c,compute:d}=t||{},p=et.useRef(i),l=et.useRef(d),g=et.useRef(r),v=et.useRef(n);l.current=d;const E=()=>{const ie=r._getWatch(n,p.current);return l.current?l.current(ie):ie},[T,j]=et.useState(E),P=et.useRef(T),C=et.useCallback(ie=>{const oe=RG(n,r._names,ie||r._formValues,!1,p.current);return l.current?l.current(oe):oe},[r._formValues,r._names,n]),L=et.useCallback(ie=>{if(!a){const oe=RG(n,r._names,ie||r._formValues,!1,p.current);if(l.current){const pe=l.current(oe);Iu(pe,P.current)||(j(pe),P.current=pe)}else j(oe)}},[r._formValues,r._names,a,n]),{resyncIfNeeded:O,snapshot:F}=aY(E),$=et.useRef(L);$.current=L;const G=et.useRef(C);G.current=C,sY(()=>{g.current!==r||!Iu(v.current,n)?(g.current=r,v.current=n,$.current()):O(!a,()=>G.current(),oe=>{const pe=Pa(oe);j(pe),P.current=pe});const ie=r._subscribe({name:n,formState:{values:!0},exact:c,callback:oe=>{$.current(oe.values)}});return()=>{ie(),F(!a,()=>G.current())}},[r,c,n,a,O,F]),et.useEffect(()=>r._removeUnmounted());const W=g.current!==r,Z=v.current,Q=et.useMemo(()=>!W&&!Iu(Z,n),[W,n,Z]);return(W||Q)&&(p.current=i),!a&&(W||Q)?C():T}function y7e(t){const e=iY(),{name:r,disabled:n,control:i=e,shouldUnregister:a,defaultValue:c,exact:d=!0}=t,p=Vwe(i._names.array,r),l=et.useMemo(()=>{const $=ln(i._formValues,r,ln(i._defaultValues,r,c));return Cs($)?d7e(i,r):$},[i,r,c]),g=g7e({control:i,name:r,defaultValue:l,exact:d}),v=p7e({control:i,name:r,exact:d}),E=et.useRef(t),T=et.useRef(null),j=et.useRef(i.register(r,{...t.rules,value:g,...sh(t.disabled)?{disabled:t.disabled}:{}}));E.current=t;const P=et.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ln(v.errors,r)},isDirty:{enumerable:!0,get:()=>!!ln(v.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!ln(v.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!ln(v.validatingFields,r)},error:{enumerable:!0,get:()=>ln(v.errors,r)}}),[v,r]),C=et.useCallback($=>{const G=PG($);return ln(i._fields,r)||(j.current=i.register(r,{...E.current.rules,value:G})),j.current.onChange({target:{value:PG($),name:r},type:C_.CHANGE})},[r,i]),L=et.useCallback(()=>{const $=ln(i._formValues,r);return ln(i._fields,r)||(j.current=i.register(r,{...E.current.rules,value:$})),j.current.onBlur({target:{value:$,name:r},type:C_.BLUR})},[r,i]),O=et.useCallback($=>{$&&(T.current={focus:()=>Nu($.focus)&&$.focus(),select:()=>Nu($.select)&&$.select(),setCustomValidity:W=>Nu($.setCustomValidity)&&$.setCustomValidity(W),reportValidity:()=>Nu($.reportValidity)&&$.reportValidity()});const G=ln(i._fields,r);G&&G._f&&$&&(G._f.ref=T.current,G._f._c=!0)},[i._fields,r]),F=et.useMemo(()=>({name:r,value:g,...sh(n)||v.disabled?{disabled:v.disabled||n}:{},onChange:C,onBlur:L,ref:O}),[r,n,v.disabled,C,L,O,g]);return et.useEffect(()=>{const $=i._options.shouldUnregister||a;j.current=i.register(r,{...E.current.rules,...sh(E.current.disabled)?{disabled:E.current.disabled}:{}});const G=(W,Z)=>{const Q=ln(i._fields,W);Q&&Q._f&&(Q._f.mount=Z,Q._f._c=Z)};if(G(r,!0),$){const W=Pa(ln(a?i._defaultValues:i._options.values||i._defaultValues,r,ln(i._options.defaultValues,r,E.current.defaultValue)));sa(i._defaultValues,r,W),Cs(ln(i._formValues,r))&&sa(i._formValues,r,W)}if(!p&&i.register(r,{...E.current.rules,...sh(E.current.disabled)?{disabled:E.current.disabled}:{}}),T.current){const W=ln(i._fields,r);W&&W._f&&(W._f.ref=T.current)}return()=>{(p?$&&!i._state.action:$)?i.unregister(r):G(r,!1)}},[r,i,p,a]),et.useEffect(()=>{i._setDisabledField({disabled:n,name:r})},[n,r,i]),et.useMemo(()=>({field:F,formState:v,fieldState:P}),[F,v,P])}const x7e=t=>t.render(y7e(t));var SD=t=>({isOnSubmit:!t||t===Df.onSubmit,isOnBlur:t===Df.onBlur,isOnChange:t===Df.onChange,isOnAll:t===Df.all,isOnTouch:t===Df.onTouched}),fU=(t,e,r)=>{if(r)return!1;if(e.watchAll||e.watch.has(t))return!0;for(const n of e.watch)if(t.startsWith(n)&&t.charAt(n.length)===".")return!0;return!1};const aj=(t,e,r)=>{for(const n of r||Object.keys(t)){if(n==="_f")continue;const i=r?ln(t,n):t[n];if(i){const{_f:a}=i;if(a){if(a.refs&&a.refs[0]&&e(a.refs[0],a.name))return!0;if(a.ref&&e(a.ref,a.name))return!0;if(aj(i,e))return!0}else if((Go(i)||Array.isArray(i))&&aj(i,e))return!0}}};var foe=(t,e,r)=>{const n=ln(t,r),i=Array.isArray(n)?n:[];return sa(i,qwe,e[r]),sa(t,r,i),t},zl=t=>Go(t)&&!Object.keys(t).length,gF=t=>{if(!u5)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},d5=t=>t.type==="radio",yF=t=>t instanceof RegExp,Hwe=(t,e,r,n,i)=>e?{...r[t],types:{...r[t]&&r[t].types?r[t].types:{},[n]:i||!0}}:{};const moe={value:!1,isValid:!1},poe={value:!0,isValid:!0};var Wwe=t=>{if(!Array.isArray(t))return moe;if(t.length>1){const r=t.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:r,isValid:!!r.length}}const e=t[0];return!e||!e.checked||e.disabled?moe:!e.attributes||!("value"in e.attributes)||Cs(e.value)||e.value===""?poe:{value:e.value,isValid:!0}};const goe={isValid:!1,value:null};var Kwe=t=>Array.isArray(t)?t.reduce((e,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:e,goe):goe;function yoe(t,e,r="validate"){if(Ru(t)||Array.isArray(t)&&t.length&&t.every(Ru)||sh(t)&&!t)return{type:r,message:Ru(t)?t:"",ref:e}}var TS=t=>Go(t)&&!yF(t)?t:{value:t,message:""},xoe=async(t,e,r,n,i,a)=>{const{ref:c,refs:d,required:p,maxLength:l,minLength:g,min:v,max:E,pattern:T,validate:j,name:P,valueAsNumber:C,mount:L,_c:O}=t._f,F=ln(r,P);if(!L||e.has(P))return{};const $=d?d[0]:c,G=be=>{if(i&&$.reportValidity){const Re=sh(be)?"":be||"";d?d.forEach(Ie=>Nu(Ie.setCustomValidity)&&Ie.setCustomValidity(Re)):$.setCustomValidity(Re),$.reportValidity()}},W={},Z=!O&&d5(c),Q=!O&&vA(c),ee=Z||Q,ie=(C||c5(c))&&Cs(c.value)&&Cs(F)||gF(c)&&c.value===""&&!O||F===""||Array.isArray(F)&&!F.length,oe=Hwe.bind(null,P,n,W),pe=(be,Re,Ie,Te=Qc.maxLength,ge=Qc.minLength)=>{const $e=be?Re:Ie;W[P]={type:be?Te:ge,message:$e,ref:c,...oe(be?Te:ge,$e)}};if(a?!Array.isArray(F)||!F.length:p&&(!ee&&(ie||Tl(F))||sh(F)&&!F||Q&&!Wwe(d).isValid||Z&&!Kwe(d).isValid)){const{value:be,message:Re}=Ru(p)?{value:!!p,message:p}:TS(p);if(be&&(W[P]={type:Qc.required,message:Re,ref:$,...oe(Qc.required,Re)},!n))return G(Re),W}if(!ie&&(!Tl(v)||!Tl(E))){let be,Re;const Ie=TS(E),Te=TS(v);if(!Tl(F)&&!Ib(F)&&!isNaN(F)){const ge=!O&&c.valueAsNumber||F&&+F;Tl(Ie.value)||(be=ge>Ie.value),Tl(Te.value)||(Re=genew Date(new Date().toDateString()+" "+Ae),we=c.type=="time",ke=c.type=="week";Ru(Ie.value)&&F&&(be=we?$e(F)>$e(Ie.value):ke?F>Ie.value:ge>new Date(Ie.value)),Ru(Te.value)&&F&&(Re=we?$e(F)<$e(Te.value):ke?F+be.value,Te=!Tl(Re.value)&&F.length<+Re.value;if((Ie||Te)&&(pe(Ie,be.message,Re.message),!n))return G(W[P].message),W}if(T&&!ie&&Ru(F)){const{value:be,message:Re}=TS(T);if(yF(be)&&!F.match(be)&&(W[P]={type:Qc.pattern,message:Re,ref:c,...oe(Qc.pattern,Re)},!n))return G(Re),W}if(j){if(Nu(j)){const be=await j(F,r),Re=yoe(be,$);if(Re&&(W[P]={...Re,...oe(Qc.validate,Re.message)},!n))return G(Re.message),W}else if(Go(j)){let be={};for(const Re in j){if(!zl(be)&&!n)break;const Ie=yoe(await j[Re](F,r),$,Re);Ie&&(be={...Ie,...oe(Re,Ie.message)},n||G(Ie.message),n&&(W[P]=be))}if(!zl(be)&&(W[P]={ref:$,...be},!n))return W}}const Le=W[P];return G(Le?Le.message:!0),W},mU=t=>Array.isArray(t)?t:[t],Ywe=t=>Array.isArray(t)?t.filter(Boolean):[];function _7e(t,e){const r=e.length-1;let n=0;for(;nrY.includes(String(c))))return t;const n=r.length===1?t:_7e(t,r),i=r.length-1,a=r[i];return n&&delete n[a],i!==0&&(Go(n)&&zl(n)||Array.isArray(n)&&v7e(n))&&Bl(t,r.slice(0,-1)),t}var _oe=()=>{let t=new Set,e=0;return{get observers(){return Array.from(t)},next:a=>{const c=t;e++;for(const d of c)d.next&&d.next(a);c===t&&e--},subscribe:a=>(t.add(a),{unsubscribe:()=>{e&&(t=new Set(t),e=0),t.delete(a)}}),unsubscribe:()=>{t=new Set,e=0}}};function Zwe(t,e){const r=Array.isArray(t)?[]:{};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const i=t[n],a=e[n];i&&(Go(i)||Array.isArray(i))&&a?r[n]=Zwe(i,a):t[n]&&(r[n]=a)}return r}const voe=(t,e)=>t!==null&&tY(t)&&Object.prototype.hasOwnProperty.call(t,e);var pU=(t,e)=>{if(!e)return!1;let r=t;for(const n of HP(e)?[e]:bA(e)){if(!voe(r,n))return voe(t,e);r=r[n]}return!0},oY=t=>t.type==="select-multiple";const b7e=t=>{const e=[...t.options];return!t.multiple&&t.size<2&&!e.some(r=>r.defaultSelected)?t.selectedIndex!==e.findIndex(r=>!r.disabled):e.some(r=>r.selected!==r.defaultSelected)};var w7e=t=>vA(t)?t.checked!==t.defaultChecked:t.type==="select-one"||oY(t)?b7e(t):!d5(t)&&"defaultValue"in t&&t.value!==t.defaultValue,S7e=t=>d5(t)||vA(t),gU=t=>gF(t)&&t.isConnected;function boe(t){return Array.isArray(t)||Go(t)}function Xwe(t,e,r="",n=[]){for(const i in t){const a=r?`${r}.${i}`:i,c=t[i];boe(c)&&boe(ln(e,a))?Xwe(c,e,a,n):n.push(a)}return n}var E7e=t=>{for(const e in t)if(Nu(t[e]))return!0;return!1};function Qwe(t){return Array.isArray(t)||Go(t)&&!E7e(t)}function Jwe(t){return!!(t&&"_f"in t)}function e1e(t){return Array.isArray(t)?!t.some(e=>!Cs(e)):!Object.keys(t).length}function LG(t,e){Array.isArray(t)?t[e]=void 0:delete t[e]}function DG(t,e={},r){for(const n in t){const i=t[n],a=r&&r[n];Qwe(i)&&(!Array.isArray(i)||!Jwe(a))?(e[n]=Array.isArray(i)?[]:{},DG(i,e[n],a),e1e(e[n])&&LG(e,n)):Cs(i)||(e[n]=!0)}return e}function fy(t,e,r,n){r||(r=DG(e,Array.isArray(Tl(e)?t:e)?[]:{},n));for(const i in t){const a=t[i],c=n&&n[i];Qwe(a)&&(!Array.isArray(a)||!Jwe(c))?(Cs(e)||NG(r[i])?r[i]=DG(a,Array.isArray(a)?[]:{},c):fy(a,Tl(e)?{}:e[i],r[i],c),e1e(r[i])&&LG(r,i)):Iu(a,Tl(e)?void 0:e[i])?LG(r,i):r[i]=!0}return r}var T7e=(t,e)=>{const r=e.split("."),n=[];let i=r[0];for(let a=1;aCs(t)?t:e?t===""?NaN:t&&+t:r&&Ru(t)?new Date(t):n?n(t):t;function woe(t){const e=t.ref;return c5(e)?e.files:d5(e)?Kwe(t.refs).value:oY(e)?[...e.selectedOptions].map(({value:r})=>r):vA(e)?Wwe(t.refs).value:MG(e.value,t)}var A7e=(t,e,r,n)=>{const i={};for(const a of t){const c=ln(e,a);c&&sa(i,a,c._f)}return{criteriaMode:r,names:[...t],fields:i,shouldUseNativeValidation:n}},AS=t=>Cs(t)?t:yF(t)?t.source:Go(t)?yF(t.value)?t.value.source:t.value:t;const Soe="AsyncFunction";var k7e=t=>{if(!t||!t.validate)return!1;if(Nu(t.validate))return t.validate.constructor.name===Soe;if(Go(t.validate)){for(const e in t.validate)if(t.validate[e].constructor.name===Soe)return!0}return!1},I7e=t=>t.mount&&(t.required||!Cs(t.required)&&t.required!==!1||!Cs(t.min)||!Cs(t.max)||!Cs(t.maxLength)||!Cs(t.minLength)||t.pattern||t.validate);function Eoe(t,e,r){const n=ln(t,r);if(n&&(n.type||n.message)||Array.isArray(n))return{error:n,name:r};const i=r.split(".");for(;i.length;){const a=i.join("."),c=ln(e,a),d=ln(t,a);if(c&&!Array.isArray(c)&&r!==a)return{name:r};if(d&&d.type)return{name:a,error:d};if(d&&d.root&&d.root.type)return{name:`${a}.root`,error:d.root};i.pop()}return{name:r}}var j7e=(t,e,r)=>{const n=Object.keys(t).filter(i=>i!=="name");return!n.length||r&&n.length>=Object.keys(e).length||n.find(i=>e[i]===(!r||Df.all))};const Toe=(t,e,r)=>r?t===e||t.startsWith(e+"."):t.startsWith(e)||e.startsWith(t);var Aoe=(t,e,r)=>{if(!t||!e||t===e)return!0;if(!Array.isArray(t))return Toe(t,e,r);for(const n of t)if(n&&Toe(n,e,r))return!0;return!1},C7e=(t,e,r,n,i)=>i.isOnAll?!1:!r&&i.isOnTouch?!(e||t):(r?n.isOnBlur:i.isOnBlur)?!t:(r?n.isOnChange:i.isOnChange)?t:!0,P7e=(t,e)=>{const r=ln(t,e);!Ywe(r).length&&!(r&&r.root)&&Bl(t,e)};const JM={mode:Df.onSubmit,reValidateMode:Df.onChange,shouldFocusError:!0},N7e=(t,e)=>{for(const r in t)delete t[r];Object.assign(t,e)},t1e={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function R7e(t={}){let e={...JM,...t},r={...Pa(t1e),isLoading:Nu(e.defaultValues),errors:Pa(e.errors)||{},disabled:e.disabled||!1},n={},i=Go(e.defaultValues)||Go(e.values)?Pa(e.defaultValues||e.values)||{}:{},a=e.shouldUnregister?{}:Pa(i),c={action:!1,actionArrayLengths:new Map,mount:!1,watch:!1,keepIsValid:!1},d=!1,p={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set,registerName:new Set};const l={},g={},v=new Set;let E=SD(e.mode),T=SD(e.reValidateMode);const j={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},P={...j},C={},L=(...Ke)=>Ke.some(at=>P[at]||C[at]),O=Ke=>{for(const at of v)if(Aoe(at.name,Ke,at.exact))return!0;return!1},F={array:_oe(),state:_oe()};let $=0,G=0,W=0;const Z={};let Q=e.criteriaMode===Df.all;const ee=(Ke,at)=>yt=>{clearTimeout(g[Ke]),g[Ke]=setTimeout(at,yt)},ie=Ke=>{clearTimeout(g[Ke]),delete g[Ke],delete l[Ke]},oe=Ke=>{ie(Ke);const at=`${Ke}.`;for(const yt of Object.keys(l))yt.startsWith(at)&&ie(yt)},pe=async Ke=>{if(!c.keepIsValid&&!e.disabled&&(L("isValid")||Ke)){const at=++$;let yt;e.resolver?(yt=zl((await tt()).errors),at===$&&be()):yt=await Ct({fields:n,onlyCheckValid:!0,eventType:C_.VALID}),at===$&&yt!==r.isValid&&F.state.next({isValid:yt})}},Le=(Ke,at)=>{const yt=[...Ke];if(!yt.some(Er=>Er&&(at?ln(r.validatingFields,Er)!==!0:pU(r.validatingFields,Er))))return;const rr=Pa(r.validatingFields);for(const Er of yt)Er&&(at?sa(rr,Er,!0):Bl(rr,Er));Iu(r.validatingFields,rr)||(r.validatingFields=rr)},be=(Ke,at)=>{!e.disabled&&L("isValidating","validatingFields")&&(Le(Ke||p.mount,at),F.state.next({validatingFields:r.validatingFields,isValidating:!zl(r.validatingFields)}))},Re=()=>{r.dirtyFields=fy(i,a,void 0,n)},Ie=(Ke,at=[],yt,rr,Er=!0,Wr=!0)=>{if(rr&&yt&&!e.disabled){c.action=!0,c.keepIsValid=!1;const Nr=ln(n,Ke),Zr=Nr&&Nr._f,$r=Zr?Object.assign([],Nr):Nr;if(c.actionArrayLengths.has(Ke)||c.actionArrayLengths.set(Ke,Array.isArray($r)?$r.length:0),Wr&&Array.isArray($r)){const jt=yt($r,rr.argA,rr.argB)||$r;Zr?sa(n,Ke,{...jt,_f:Zr}):Er&&sa(n,Ke,jt)}const qn=ln(r.errors,Ke);if(Wr&&Array.isArray(qn)){const jt=qn.root,Ha=yt(qn,rr.argA,rr.argB)||qn;jt&&(Ha.root=jt),Er&&sa(r.errors,Ke,Ha),P7e(r.errors,Ke),r.errors={...r.errors}}const ki=ln(r.touchedFields,Ke),xs=Wr&&Array.isArray(ki);if(xs){const jt=yt(ki,rr.argA,rr.argB);Er&&sa(r.touchedFields,Ke,jt)}const Ea=ln(r.dirtyFields,Ke);if(Wr&&Array.isArray(Ea)){const jt=yt(Ea,rr.argA,rr.argB)||Ea;Er&&sa(r.dirtyFields,Ke,jt)}L("dirtyFields")?Re():d=!0,F.state.next({name:Ke,isDirty:cr(Ke,at),dirtyFields:r.dirtyFields,...xs&&{touchedFields:r.touchedFields},errors:r.errors,isValid:r.isValid})}else sa(a,Ke,at)},Te=(Ke,at)=>{sa(r.errors,Ke,at),r.errors={...r.errors},F.state.next({errors:r.errors})},ge=Ke=>{Object.keys(l).forEach(ie);const at=!zl(Ke);r.errors=Pa(Ke),F.state.next({errors:r.errors,...at?{isValid:!1}:{}}),!at&&c.mount&&pe()},$e=Ke=>HP(Ke)?[Ke]:bA(Ke),we=Ke=>{const at=$e(Ke);let yt=a,rr=i;for(let Er=0;Er{if(!c.actionArrayLengths.size)return!1;const at=$e(Ke);let yt=a,rr="",Er=-1,Wr=0;for(let Nr=0;Nr=yt.length)return Er===-1?!1:Nr===Er?+ZrEr&&+at[Er]{let at=a;for(const yt of $e(Ke)){if(Array.isArray(at)&&+yt>=at.length)return!0;at=at&&at[yt]}return!1},He=(Ke,at,yt,rr)=>{const Er=ln(n,Ke);if(Er){if(we(Ke)||ke(Ke))return;const Wr=Cs(ln(a,Ke)),Nr=ln(a,Ke,Cs(yt)?ln(i,Ke):yt),Zr=!!rr&&!r.isReady&&w7e(rr);if(Cs(Nr)||rr&&rr.defaultChecked||Zr||at){const $r=at?Nr:woe(Er._f);(!Cs($r)||!Ae(Ke))&&(L("dirtyFields")&&!Iu(ln(a,Ke),$r)&&(d=!0),sa(a,Ke,$r),Zr&&ot(Ke,$r))}else ir(Ke,Nr);c.mount&&!c.action&&(e.resolver&&L("isValidating","validatingFields")?Promise.resolve().then(()=>pe()):pe(),Wr&&r.isDirty&&L("isDirty")&&(cr()||(r.isDirty=!1,F.state.next({...r}))),e.shouldUnregister&&Wr&&!Cs(ln(a,Ke))&&fU(Ke,p)&&(c.watch=!0))}},ot=(Ke,at,yt,rr,Er)=>{let Wr=!1,Nr=!1;const Zr={name:Ke};if(!e.disabled||rr===!0){if(!yt||rr){const $r=Iu(ln(i,Ke),at);if(L("isDirty")&&(Nr=r.isDirty,r.isDirty=Zr.isDirty=!$r||cr(),Wr=Nr!==Zr.isDirty),Nr=!!ln(r.dirtyFields,Ke),$r)Bl(r.dirtyFields,Ke);else{const ki=ln(i,Ke),xs=ln(n,Ke),Ea=!(xs&&xs._f)&&(Go(ki)||Array.isArray(ki))?fy(ki,at,void 0,xs):!0;sa(r.dirtyFields,Ke,Ea)}let qn=!1;if(d||$r&&(L("isDirty")?r.isDirty:cr())){d=!1;const ki=fy(i,a,void 0,n);Iu(r.dirtyFields,ki)||(qn=!0,N7e(r.dirtyFields,ki))}Zr.dirtyFields=r.dirtyFields,Wr=Wr||L("dirtyFields")&&(qn||Nr!==!$r)}if(yt){const $r=pU(r.touchedFields,Ke)?ln(r.touchedFields,Ke):void 0;$r||(sa(r.touchedFields,Ke,yt),Zr.touchedFields=r.touchedFields,Wr=Wr||L("touchedFields")&&$r!==yt)}Wr&&Er&&F.state.next(Zr)}return Wr?Zr:{}},nt=(Ke,at,yt,rr)=>{const Er=ln(r.errors,Ke),Wr=L("isValid")&&sh(at)&&r.isValid!==at;if(e.delayError&&yt?(l[Ke]=ee(Ke,()=>Te(Ke,yt)),l[Ke](e.delayError)):(ie(Ke),yt?sa(r.errors,Ke,yt):Bl(r.errors,Ke),r.errors={...r.errors}),(yt?!Iu(Er,yt,!0):Er)||!zl(rr)||Wr){const Nr={...rr,...Wr&&sh(at)?{isValid:at}:{},errors:r.errors,name:Ke};F.state.next(Nr)}},tt=async Ke=>(be(Ke,!0),await e.resolver(a,e.context,A7e(Ke||p.mount,n,e.criteriaMode,e.shouldUseNativeValidation))),vt=async Ke=>{const at=G,yt=W,rr=Ke?Ke.filter(Wr=>ln(n,Wr)):[],{errors:Er}=await tt(Ke);if(at!==G)return Er;if(be(Ke),Ke){for(const Wr of Ke){if(rr.includes(Wr)&&(!ln(n,Wr)||Z[Wr]>yt)){Bl(Er,Wr);continue}const Nr=ln(Er,Wr);oe(Wr);const Zr=p.array.has(Wr)&&Go(Nr)&&!Object.keys(Nr).some(ki=>!Number.isNaN(Number(ki))),$r=ln(n,Wr),qn=Go($r)&&Object.keys($r).some(ki=>ki!=="_f");Zr?foe(r.errors,{[Wr]:Nr},Wr):Nr&&(Nr.type||Nr.message)||Array.isArray(Nr)||Go(Nr)&&qn?sa(r.errors,Wr,Nr):Bl(r.errors,Wr)}r.errors={...r.errors}}else Object.keys(l).forEach(ie),r.errors=Er;return Er},Vt=async({name:Ke,eventType:at})=>{if(e.validate){const yt=G,rr=await e.validate({formValues:a,formState:r,name:Ke,eventType:at});if(yt!==G)return!0;if(Go(rr)){let Er=!0;li(OI);for(const Wr in rr){const Nr=rr[Wr];Nr&&(Er=!1,Lr(`${OI}.${Wr}`,{message:Ru(Nr.message)?Nr.message:"",type:Nr.type||Qc.validate}))}return Er}else return Ru(rr)||!rr?(Lr(OI,{message:rr||"",type:Qc.validate}),!1):(li(OI),!0)}return!0},Ct=async({fields:Ke,onlyCheckValid:at,name:yt,eventType:rr,context:Er={valid:!0,runRootValidation:!1}})=>{const Wr=G;if(e.validate&&!Er.runRootValidation&&(Er.runRootValidation=!0,!await Vt({name:yt,eventType:rr})&&(Er.valid=!1,at)))return Er.valid;for(const Nr in Ke){const Zr=Ke[Nr];if(Zr){const{_f:$r,...qn}=Zr;if($r){const ki=p.array.has($r.name),xs=Zr._f&&k7e(Zr._f),Ea=L("isValidating","validatingFields");xs&&Ea&&be([$r.name],!0);const jt=W,Ha=await xoe(Zr,p.disabled,a,Q,e.shouldUseNativeValidation&&!at,ki);if(Wr!==G)return Er.valid;if(xs&&Ea&&be([$r.name]),!ln(n,$r.name)||Z[$r.name]>jt)continue;if(Ha[$r.name]&&(Er.valid=!1,at)||(at||(ie($r.name),ln(Ha,$r.name)?ki?foe(r.errors,Ha,$r.name):sa(r.errors,$r.name,Ha[$r.name]):Bl(r.errors,$r.name)),e.shouldUseNativeValidation&&Ha[$r.name]))break}!zl(qn)&&await Ct({context:Er,onlyCheckValid:at,fields:qn,name:Nr,eventType:rr})}}return Er.valid},Bt=()=>{for(const Ke of p.unMount){const at=ln(n,Ke);at&&(at._f.refs?at._f.refs.every(yt=>!gU(yt)):!gU(at._f.ref))&&ps(Ke)}p.unMount=new Set},cr=(Ke,at)=>(Ke&&!Cs(at)&&sa(a,Ke,at),!Iu(c.mount?a:i,i)),ft=(Ke,at,yt)=>{const rr=c.mount?a:Cs(at)||!Cs(Ke)?i:at;return RG(Ke,p,Cs(Ke)?{...rr}:rr,yt,at)},Kt=Ke=>Ywe(ln(c.mount?a:i,Ke,e.shouldUnregister?ln(i,Ke,[]):[])),ir=(Ke,at,yt={},rr=!1,Er=!1,Wr=!1)=>{const Nr=ln(n,Ke);let Zr=at;if(Nr){const $r=Nr._f;$r&&(!$r.disabled&&sa(a,Ke,MG(at,$r)),Zr=gF($r.ref)&&Tl(at)?"":at,oY($r.ref)?[...$r.ref.options].forEach(qn=>qn.selected=Zr.includes(qn.value)):$r.refs?vA($r.ref)?$r.refs.forEach(qn=>{(!qn.defaultChecked||!qn.disabled)&&(Array.isArray(Zr)?qn.checked=!!Zr.find(ki=>ki===qn.value):qn.checked=Zr===qn.value||!!Zr)}):$r.refs.forEach(qn=>qn.checked=qn.value===Zr):c5($r.ref)?$r.ref.value="":($r.ref.value=Zr,!$r.ref.type&&!Er&&!Wr&&F.state.next({name:Ke,values:rr?a:O(Ke)?Pa(a):void 0})))}(yt.shouldDirty||yt.shouldTouch)&&ot(Ke,Nr&&Nr._f&&!Nr._f.disabled&&(Nr._f.valueAsNumber||Nr._f.valueAsDate||Nr._f.setValueAs)?MG(at,Nr._f):Zr,yt.shouldTouch,yt.shouldDirty,!Er),yt.shouldValidate&&Fn(Ke,{delayError:yt.delayError}),yt.shouldValidate&&Nr&&Nr._f&&Nr._f.deps&&(!Array.isArray(Nr._f.deps)||Nr._f.deps.length>0)&&Fn(Nr._f.deps)},Gr=(Ke,at,yt,rr=!1,Er=!1,Wr=!1)=>{for(const Nr in at){if(!Object.prototype.hasOwnProperty.call(at,Nr))continue;const Zr=at[Nr],$r=Ke+"."+Nr,qn=ln(n,$r);p.array.has($r)&&F.array.next({name:$r,values:rr?a:Pa(a)}),(p.array.has(Ke)||Go(Zr)||qn&&!qn._f)&&!Ib(Zr)?Gr($r,Zr,yt,rr,Er,Wr):ir($r,Zr,yt,rr,Er,Wr)}},tr=(Ke,at,yt,rr,Er=!1)=>{const Wr=ln(n,Ke),Nr=p.array.has(Ke),Zr=rr?at:Pa(at),$r=ln(a,Ke),qn=Iu($r,Zr);if(qn||sa(a,Ke,Zr),Nr)F.array.next({name:Ke,values:rr?a:Pa(a)}),L("isDirty","dirtyFields")&&yt.shouldDirty&&(Re(),r.isDirty=cr(Ke,Zr),Er||F.state.next({name:Ke,dirtyFields:r.dirtyFields,isDirty:r.isDirty})),yt.shouldValidate&&Fn(Ke,{delayError:yt.delayError});else{const ki=Array.isArray(Zr)&&!Zr.length||zl(Zr),xs=!qn&&!Er;!Wr||Wr._f||Tl(Zr)||ki?ir(Ke,Zr,yt,rr,Er,xs):Gr(Ke,Zr,yt,rr,Er,xs)}if(!qn&&!Er){const ki=fU(Ke,p),xs=c.mount||ki?Ke:void 0,Ea=Nr?[]:T7e(p.array,Ke),jt=rr?a:O(xs)||Ea.some(O)?Pa(a):void 0;F.state.next({...ki&&r,name:xs,values:jt});for(const Ha of Ea)F.state.next({name:Ha,values:jt})}},Qt=(Ke,at,yt={})=>tr(Ke,at,yt,!1),zt=(Ke,at={})=>{const yt=Nu(Ke)?Ke(a):Ke;if(!Iu(a,yt)){a={...a,...yt};for(const rr of new Set([...p.mount,...p.array]))pU(yt,rr)&&tr(rr,ln(yt,rr),at,!0,!0);F.state.next({...r,name:void 0,type:void 0,...v.size?{values:a}:{}}),at.shouldValidate&&pe()}},Vr=async Ke=>{c.mount=!0;const at=Ke.target;let yt=at.name,rr=!0;const Er=ln(n,yt),Wr=W,Nr=Zr=>{rr=!!ln(n,yt)&&!(Z[yt]>Wr)&&Iu(Zr,ln(a,yt,Zr))};if(Er){c.keepIsValid=!1;let Zr,$r,qn=!1;const ki=at.type?woe(Er._f):PG(Ke),xs=Ke.type===C_.BLUR||Ke.type===C_.FOCUS_OUT,Ea=!I7e(Er._f)&&!e.validate&&!e.resolver&&!ln(r.errors,yt)&&!Er._f.deps,jt=Ea||C7e(xs,ln(r.touchedFields,yt),r.isSubmitted,T,E),Ha=fU(yt,p,xs);sa(a,yt,Pa(ki)),xs?(!at||!at.readOnly)&&(Er._f.onBlur&&Er._f.onBlur(Ke),Object.prototype.hasOwnProperty.call(l,yt)&&(qn=!0,l[yt](0))):Er._f.onChange&&Er._f.onChange(Ke);const wh=ot(yt,ki,xs),Ud=!zl(wh)||Ha;if(!xs&&F.state.next({name:yt,type:Ke.type,...O(yt)?{values:Pa(a)}:{}}),jt)return(!Ea||!r.isValid)&&L("isValid")&&(e.mode==="onBlur"?xs&&pe():xs||pe()),Ud&&F.state.next({name:yt,...Ha?{}:wh});if(!e.resolver&&e.validate&&await Vt({name:yt,eventType:Ke.type}),!xs&&Ha&&F.state.next({...r}),e.resolver){const mf=G,{errors:Sh}=await tt([yt]);if(mf!==G)return;if(be([yt]),Nr(ki),!rr){!zl(wh)&&F.state.next(wh);return}const cu=Eoe(r.errors,n,yt),Ig=Eoe(Sh,n,cu.name||yt);Zr=Ig.error,yt=Ig.name,$r=zl(Sh)}else{const mf=G,Sh=++$;if(be([yt],!0),Zr=(await xoe(Er,p.disabled,a,Q,e.shouldUseNativeValidation))[yt],mf!==G)return;if(be([yt]),Nr(ki),rr){if(Zr)$r=!1;else if(L("isValid")){if($r=await Ct({fields:n,onlyCheckValid:!0,name:yt,eventType:Ke.type}),mf!==G)return;Nr(ki),Sh!==$&&($r=void 0)}}}rr&&(Er._f.deps&&(!Array.isArray(Er._f.deps)||Er._f.deps.length>0)&&Fn(Er._f.deps),nt(yt,$r,Zr,wh),qn&&Object.prototype.hasOwnProperty.call(l,yt)&&l[yt](0))}},Jr=(Ke,at)=>{if(ln(r.errors,at)&&Ke.focus)return Ke.focus(),1},Fn=async(Ke,at={})=>{c.keepIsValid=!1;let yt,rr;const Er=mU(Ke),Wr=G;if(e.resolver){const Nr=await vt(Cs(Ke)?Ke:Er);yt=zl(Nr),rr=Ke?!Er.some(Zr=>ln(Nr,Zr)):yt}else Ke?(rr=(await Promise.all(Er.map(async Nr=>{const Zr=ln(n,Nr);return await Ct({fields:Zr&&Zr._f?{[Nr]:Zr}:Zr,eventType:C_.TRIGGER})}))).every(Boolean),!(!rr&&!r.isValid)&&pe()):rr=yt=await Ct({fields:n,name:Ke,eventType:C_.TRIGGER});if(Wr!==G)return rr;if(at.delayError&&e.delayError&&Ru(Ke)){const Nr=ln(r.errors,Ke);Nr?(Bl(r.errors,Ke),l[Ke]=ee(Ke,()=>Te(Ke,Nr)),l[Ke](e.delayError)):ie(Ke)}if(at.shouldTouch)for(const Nr of Ke?Er:p.mount)!p.array.has(Nr)&&sa(r.touchedFields,Nr,!0);return r.errors={...r.errors},F.state.next({...!Ru(Ke)||L("isValid")&&yt!==r.isValid?{}:{name:Ke},...e.resolver||!Ke?{isValid:yt}:{},...at.shouldTouch&&L("touchedFields")?{touchedFields:r.touchedFields}:{},errors:r.errors}),at.shouldFocus&&!rr&&aj(n,Jr,Ke?Er:p.mount),rr},Ar=(Ke,at)=>{let yt=Cs(Ke)&&!at?{...c.mount?a:i}:c.mount?a:i;return at&&(yt=Zwe(at.dirtyFields?r.dirtyFields:r.touchedFields,yt)),Cs(Ke)?yt:Ru(Ke)?ln(yt,Ke):Ke.map(rr=>ln(yt,rr))},Tn=Ke=>Cs(Ke)?{...r.errors}:Ru(Ke)?ln(r.errors,Ke):Ke.map(at=>ln(r.errors,at)),mn=(Ke,at)=>{const yt=at||r,rr=ln(yt.errors,Ke);return{invalid:!!rr,isDirty:!!ln(yt.dirtyFields,Ke),error:rr,isValidating:!!ln(yt.validatingFields,Ke),isTouched:!!ln(yt.touchedFields,Ke)}},li=Ke=>{const at=Ke?mU(Ke):void 0;at?at.forEach(yt=>{oe(yt),Bl(r.errors,yt),r.errors={...r.errors},F.state.next({name:yt,errors:r.errors})}):(Object.keys(l).forEach(ie),r.errors={},F.state.next({errors:r.errors}))},Lr=(Ke,at,yt)=>{oe(Ke);const rr=ln(n,Ke,{_f:{}}),Er=rr._f&&rr._f.ref,Wr=ln(r.errors,Ke)||{},{ref:Nr,message:Zr,type:$r,types:qn,...ki}=Wr;sa(r.errors,Ke,{...ki,...at,ref:Er}),r.errors={...r.errors},F.state.next({name:Ke,errors:r.errors,isValid:!1}),yt&&yt.shouldFocus&&Er&&Er.focus&&Er.focus()},Or=(Ke,at)=>{if(Nu(Ke)){const yt={};v.add(yt);const{unsubscribe:rr}=F.state.subscribe({next:Er=>"values"in Er&&Ke(Er.values||ft(void 0,at),Er)});return{unsubscribe:()=>{v.delete(yt),rr()}}}return ft(Ke,at,!0)},si=Ke=>{const at={name:Ke.name,exact:Ke.exact};Ke.formState&&Ke.formState.values&&v.add(at);const{unsubscribe:yt}=F.state.subscribe({next:rr=>{if(Aoe(Ke.name,rr.name,Ke.exact)&&j7e(rr,Ke.formState||P,Ke.reRenderRoot)){const Er=rr.values||{...a};Ke.callback({...r,...rr,validatingFields:r.validatingFields,isValidating:r.isValidating,values:Er,defaultValues:i})}}});return()=>{v.delete(at),yt()}},ss=Ke=>{c.mount=!0;const at=Object.keys(Ke.formState||{}).filter(rr=>Ke.formState&&Ke.formState[rr]);for(const rr of at)C[rr]=(C[rr]||0)+1;const yt=si({...Ke,formState:{...j,...Ke.formState}});return()=>{for(const rr of at.splice(0))C[rr]--;yt()}},ps=(Ke,at={})=>{const yt=Ke?mU(Ke):p.mount;at.keepIsValidating||Le(yt);for(const rr of yt)p.mount.delete(rr),p.array.delete(rr),p.disabled.delete(rr),Bl(n,rr),!at.keepValue&&Bl(a,rr),at.keepError||(oe(rr),Bl(r.errors,rr)),!at.keepDirty&&Bl(r.dirtyFields,rr),!at.keepTouched&&Bl(r.touchedFields,rr),!e.shouldUnregister&&!at.keepDefaultValue&&Bl(i,rr);at.keepError||(r.errors={...r.errors}),v.size&&F.state.next({values:Pa(a)}),F.state.next({...r,...at.keepDirty?{}:{isDirty:cr()},...at.keepIsValidating?{}:{isValidating:!zl(r.validatingFields)}}),!at.keepIsValid&&pe()},Mi=({disabled:Ke,name:at})=>{if(sh(Ke)&&c.mount||Ke||p.disabled.has(at)){const Er=p.disabled.has(at)!==!!Ke;Ke?p.disabled.add(at):p.disabled.delete(at),Er&&c.mount&&!c.action&&pe()}},gs=(Ke,at={})=>{let yt=ln(n,Ke);const rr=sh(at.disabled)||sh(e.disabled),Er=!p.registerName.has(Ke)&&yt&&yt._f&&!yt._f.mount;if((!yt||!yt._f)&&(Z[Ke]=++W),sa(n,Ke,{...yt||{},_f:{...yt&&yt._f?yt._f:{ref:{name:Ke}},name:Ke,mount:!0,...at}}),p.mount.add(Ke),yt&&yt._f){const Wr=ln(n,Ke);for(const Nr of h7e)Nr in at||delete Wr._f[Nr]}return yt&&!Er?Mi({disabled:sh(at.disabled)?at.disabled:e.disabled,name:Ke}):He(Ke,!0,at.value),{...rr?{disabled:at.disabled||e.disabled}:{},...e.progressive?{required:!!AS(at.required),min:AS(at.min),max:AS(at.max),minLength:AS(at.minLength),maxLength:AS(at.maxLength),pattern:AS(at.pattern)}:{},name:Ke,onChange:Vr,onBlur:Vr,ref:Wr=>{if(Wr){p.registerName.add(Ke),gs(Ke,at),p.registerName.delete(Ke),yt=ln(n,Ke);const Nr=Cs(Wr.value)&&Wr.querySelectorAll&&Wr.querySelectorAll("input,select,textarea")[0]||Wr,Zr=S7e(Nr),$r=yt._f.refs||[];if(Zr?$r.find(ki=>ki===Nr):Nr===yt._f.ref)return;const qn={...yt._f};Zr?(qn.refs=[...$r.filter(gU),Nr,...Array.isArray(ln(i,Ke))?[{}]:[]],qn.ref={type:Nr.type,name:Ke}):(qn.ref=Nr,delete qn.refs),sa(n,Ke,{_f:qn}),He(Ke,!1,void 0,Nr)}else yt=ln(n,Ke,{}),yt._f&&(yt._f.mount=!1),(e.shouldUnregister||at.shouldUnregister)&&!(Vwe(p.array,Ke)&&c.action)&&p.unMount.add(Ke)}}},ma=()=>e.shouldFocusError&&!e.shouldUseNativeValidation&&aj(n,Jr,p.mount),Ki=Ke=>{sh(Ke)&&(F.state.next({disabled:Ke}),aj(n,(at,yt)=>{const rr=ln(n,yt);rr&&(at.disabled=rr._f.disabled||Ke,Array.isArray(rr._f.refs)&&rr._f.refs.forEach(Er=>{Er.disabled=rr._f.disabled||Ke}))},0))},Hr=(Ke,at)=>async yt=>{let rr,Er;yt&&(yt.preventDefault&&yt.preventDefault(),yt.persist&&yt.persist());let Wr=Pa(a);F.state.next({isSubmitting:!0});const Nr=G,Zr=$r=>{throw Nr===G&&F.state.next({isSubmitting:!1}),$r};if(e.resolver){let $r;try{$r=await tt()}catch(xs){Zr(xs)}const{errors:qn,values:ki}=$r;if(Nr!==G)return;be(),Object.keys(l).forEach(ie),r.errors=qn,Wr=Pa(ki)}else{try{await Ct({fields:n,eventType:C_.SUBMIT})}catch($r){Zr($r)}if(Nr!==G)return;Bl(r.errors,qwe),r.errors={...r.errors}}if(p.disabled.size)for(const $r of p.disabled)Bl(Wr,$r);if(zl(r.errors)){F.state.next({errors:{}});try{rr=await Ke(Wr,yt)}catch($r){Er=$r}}else{if(at)try{await at({...r.errors},yt)}catch($r){Zr($r)}ma(),setTimeout(ma)}if(F.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:zl(r.errors)&&!Er,submitCount:r.submitCount+1,errors:r.errors}),Er)throw Er;return rr},ci=(Ke,at={})=>{ln(n,Ke)&&(Le([Ke]),Cs(at.defaultValue)?Qt(Ke,Pa(ln(i,Ke))):(Qt(Ke,at.defaultValue),sa(i,Ke,Pa(at.defaultValue))),at.keepTouched||Bl(r.touchedFields,Ke),at.keepDirty||(Bl(r.dirtyFields,Ke),r.isDirty=Cs(at.defaultValue)?cr():cr(Ke,Pa(ln(i,Ke)))),at.keepError||(oe(Ke),Bl(r.errors,Ke),r.errors={...r.errors},pe()),F.state.next({...r,isValidating:!zl(r.validatingFields)}))},mo=(Ke,at={})=>{G++,$++;const yt=Ke?Pa(Ke):i,rr=Pa(yt),Er=zl(Ke),Wr=rr,Nr=n;if(Object.keys(l).forEach(ie),at.keepDefaultValues||(i=yt),!at.keepValues){if(at.keepDirtyValues){const Zr=new Set([...p.mount,...Xwe(fy(i,a,void 0,Nr),r.dirtyFields)]);for(const $r of Zr){const qn=ln(r.dirtyFields,$r),ki=ln(a,$r),xs=ln(Wr,$r);qn&&!Cs(ki)?sa(Wr,$r,ki):!qn&&!Cs(xs)&&Qt($r,xs)}}else{if(u5&&Cs(Ke))for(const Zr of p.mount){const $r=ln(n,Zr);if($r&&$r._f){const qn=Array.isArray($r._f.refs)?$r._f.refs[0]:$r._f.ref;if(gF(qn)){const ki=qn.closest("form");if(ki){ki.reset();break}}}}if(at.keepFieldsRef)for(const Zr of p.mount)Qt(Zr,ln(Wr,Zr));else n={}}if(e.shouldUnregister){if(a=at.keepDefaultValues?Pa(i):{},at.keepFieldsRef)for(const Zr of p.mount)sa(a,Zr,ln(Wr,Zr))}else a=Pa(Wr);F.array.next({values:{...Wr}}),F.state.next({name:void 0,type:void 0,values:{...Wr}})}p={mount:at.keepDirtyValues?p.mount:new Set,unMount:new Set,array:new Set,registerName:new Set,disabled:at.keepValues||at.keepDirtyValues||at.keepFieldsRef?new Set([...p.disabled].filter(Zr=>ln(n,Zr))):new Set,watch:new Set,watchAll:!1,focus:""},c.mount=!P.isValid||!!at.keepIsValid||!!at.keepDirtyValues||!e.shouldUnregister&&!zl(Wr),c.watch=!!e.shouldUnregister,c.keepIsValid=!!at.keepIsValid,c.action=!1,c.actionArrayLengths.clear(),d=!1,at.keepErrors||(r.errors={}),F.state.next({submitCount:at.keepSubmitCount?r.submitCount:0,isDirty:Er?!1:at.keepDirty?r.isDirty:at.keepValues?cr():!!(at.keepDefaultValues&&Ke&&!Iu(Ke,i)),isSubmitted:at.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Er?{}:at.keepDirtyValues?at.keepDefaultValues&&a?fy(i,a,void 0,Nr):r.dirtyFields:at.keepDefaultValues&&Ke?fy(i,Ke,void 0,Nr):at.keepDirty?r.dirtyFields:at.keepValues?fy(i,a,void 0,Nr):{},touchedFields:at.keepTouched?r.touchedFields:{},...!at.keepIsValidating&&(r.isValidating||!zl(r.validatingFields))?{validatingFields:{},isValidating:!1}:null,errors:at.keepErrors?r.errors:{},isSubmitSuccessful:at.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:i})},_r=(Ke,at)=>mo(Nu(Ke)?Ke(a):Ke,{...e.resetOptions,...at}),Da=(Ke,at={})=>{const yt=ln(n,Ke),rr=yt&&yt._f;if(rr){const Er=rr.refs?rr.refs[0]:rr.ref;Er.focus&&setTimeout(()=>{Er.focus(),at.shouldSelect&&Nu(Er.select)&&Er.select()})}},pn=Ke=>{const{name:at,type:yt,values:rr,...Er}=Ke;Object.keys(Er).length&&(r={...r,...Er})};F.state.subscribe({next:pn});const nn={control:{register:gs,unregister:ps,getFieldState:mn,handleSubmit:Hr,setError:Lr,_subscribe:si,_runSchema:tt,_updateIsValidating:be,_focusError:ma,_getWatch:ft,_getDirty:cr,_setValid:pe,_setFieldArray:Ie,_setDisabledField:Mi,_setErrors:ge,_getFieldArray:Kt,_reset:mo,_resetDefaultValues:()=>Nu(e.defaultValues)&&e.defaultValues().then(Ke=>{_r(Ke,e.resetOptions),F.state.next({isLoading:!1})}),_removeUnmounted:Bt,_disableForm:Ki,_subjects:F,_proxyFormState:P,get _fields(){return n},get _formValues(){return a},get _state(){return c},set _state(Ke){c=Ke},get _defaultValues(){return i},get _names(){return p},set _names(Ke){p=Ke},get _formState(){return r},get _options(){return e},set _options(Ke){e={...e,...Ke},E=SD(e.mode),T=SD(e.reValidateMode),Q=e.criteriaMode===Df.all}},subscribe:ss,trigger:Fn,register:gs,handleSubmit:Hr,watch:Or,setValue:Qt,setValues:zt,getValues:Ar,getErrors:Tn,reset:_r,resetField:ci,resetDefaultValues:(Ke,at={})=>{if(i=Pa(Ke),!at.keepDirty){const yt=fy(i,a,void 0,n);r.dirtyFields=yt,r.isDirty=!zl(yt)}at.keepIsValid||pe(),F.state.next({...r,defaultValues:i})},clearErrors:li,unregister:ps,setError:Lr,setFocus:Da,getFieldState:mn};return{...nn,formControl:nn}}const koe={mode:JM.mode,reValidateMode:JM.reValidateMode,shouldFocusError:JM.shouldFocusError,resolver:void 0,criteriaMode:void 0,delayError:void 0,shouldUnregister:void 0,shouldUseNativeValidation:void 0,context:void 0,progressive:void 0,resetOptions:void 0};function lY(t={}){const e=et.useRef(void 0),r=et.useRef(void 0),n=et.useRef(t.formControl),i=et.useRef(!1),a=et.useRef(!!t.validate),c=et.useRef(!!t.errors),d=et.useRef(!1),[p,l]=et.useState(()=>({...Pa(t1e),isLoading:Nu(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1,defaultValues:Nu(t.defaultValues)?void 0:t.defaultValues}));if(!e.current||t.formControl&&n.current!==t.formControl)if(n.current=t.formControl,i.current=!1,t.formControl)e.current={...t.formControl,formState:p},t.defaultValues&&!Nu(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions);else{const{formControl:C,...L}=R7e(t);e.current={...L,formState:p}}const g=e.current.control,v=g._options,E={};for(const C in koe)C in v&&!(C in t)&&(E[C]=koe[C]);i.current&&!t.disabled&&(E.disabled=!1),g._options={...E,...t,validate:t.validate};const T=()=>({...g._formState,defaultValues:g._defaultValues}),{resyncIfNeeded:j,snapshot:P}=aY(T);return sY(()=>{j(!0,T,l);const C=g._subscribe({formState:g._proxyFormState,callback:()=>l({...g._formState,defaultValues:g._defaultValues}),reRenderRoot:!0});return l(L=>({...L,isReady:!0})),g._formState.isReady=!0,g._subjects.state.next({isReady:!0}),()=>{C(),P(!0,T)}},[g,j,P]),et.useEffect(()=>{g._disableForm(i.current&&!t.disabled?!1:t.disabled),i.current=!!t.disabled},[g,t.disabled]),et.useEffect(()=>{t.mode&&(g._options.mode=t.mode),t.reValidateMode&&(g._options.reValidateMode=t.reValidateMode)},[g,t.mode,t.reValidateMode]),et.useEffect(()=>{t.errors?(g._setErrors(t.errors),g._focusError()):c.current&&g._setErrors({}),c.current=!!t.errors},[g,t.errors]),et.useEffect(()=>{a.current&&!t.validate&&e.current&&e.current.clearErrors(OI),a.current=!!t.validate},[t.validate]),et.useEffect(()=>{t.shouldUnregister&&g._subjects.state.next({values:g._getWatch()})},[g,t.shouldUnregister]),et.useEffect(()=>{if(g._proxyFormState.isDirty){const C=g._getDirty();C!==p.isDirty&&g._subjects.state.next({isDirty:C})}},[g,p.isDirty]),et.useEffect(()=>{t.values&&!Iu(t.values,r.current)?(g._reset(t.values,{keepFieldsRef:!0,...g._options.resetOptions}),g._options.resetOptions&&g._options.resetOptions.keepIsValid||g._setValid(),r.current=t.values,l(C=>({...C}))):g._resetDefaultValues()},[g,t.values]),et.useEffect(()=>{(!g._state.mount||!d.current&&!t.values)&&(g._setValid(),g._state.mount=!0),d.current=!0,g._state.watch&&(g._state.watch=!1,g._subjects.state.next({...g._formState})),g._removeUnmounted()}),e.current.formState=et.useMemo(()=>Gwe(p,g),[g,p]),e.current}const cY=et.createContext(null);cY.displayName="HookFormContext";const L7e=()=>et.useContext(cY),D7e=({children:t,watch:e,getValues:r,getErrors:n,getFieldState:i,setError:a,clearErrors:c,setValue:d,setValues:p,trigger:l,formState:g,resetField:v,reset:E,resetDefaultValues:T,handleSubmit:j,unregister:P,control:C,register:L,setFocus:O,subscribe:F})=>{const $=et.useMemo(()=>({watch:e,getValues:r,getErrors:n,getFieldState:i,setError:a,clearErrors:c,setValue:d,setValues:p,trigger:l,formState:g,resetField:v,reset:E,resetDefaultValues:T,handleSubmit:j,unregister:P,control:C,register:L,setFocus:O,subscribe:F}),[c,C,g,n,i,r,j,L,E,T,v,a,O,d,p,F,l,P,e]);return et.createElement(cY.Provider,{value:$},et.createElement(nY.Provider,{value:$.control},t))},Ioe=(t,e,r)=>{if(t&&"reportValidity"in t){const n=ln(r,e);t.setCustomValidity(n&&n.message||""),t.reportValidity()}},r1e=(t,e)=>{for(const r in e.fields){const n=e.fields[r];n&&n.ref&&"reportValidity"in n.ref?Ioe(n.ref,r,t):n.refs&&n.refs.forEach(i=>Ioe(i,r,t))}},M7e=(t,e)=>{e.shouldUseNativeValidation&&r1e(t,e);const r={};for(const n in t){const i=ln(e.fields,n),a=Object.assign(t[n]||{},{ref:i&&i.ref});if(O7e(e.names||Object.keys(t),n)){const c=Object.assign({},ln(r,n));sa(c,"root",a),sa(r,n,c)}else sa(r,n,a)}return r},O7e=(t,e)=>t.some(r=>r.startsWith(e+"."));var F7e=function(t,e){for(var r={};t.length;){var n=t[0],i=n.code,a=n.message,c=n.path.join(".");if(!r[c])if("unionErrors"in n){var d=n.unionErrors[0].errors[0];r[c]={message:d.message,type:d.code}}else r[c]={message:a,type:i};if("unionErrors"in n&&n.unionErrors.forEach(function(g){return g.errors.forEach(function(v){return t.push(v)})}),e){var p=r[c].types,l=p&&p[n.code];r[c]=Hwe(c,e,r,i,l?[].concat(l,n.message):n.message)}t.shift()}return r},uY=function(t,e,r){return r===void 0&&(r={}),function(n,i,a){try{return Promise.resolve(function(c,d){try{var p=Promise.resolve(t[r.mode==="sync"?"parse":"parseAsync"](n,e)).then(function(l){return a.shouldUseNativeValidation&&r1e({},a),{errors:{},values:r.raw?n:l}})}catch(l){return d(l)}return p&&p.then?p.then(void 0,d):p}(0,function(c){if(function(d){return Array.isArray(d==null?void 0:d.errors)}(c))return{values:{},errors:M7e(F7e(c.errors,!a.shouldUseNativeValidation&&a.criteriaMode==="all"),a)};throw c}))}catch(c){return Promise.reject(c)}}};function OG(t){const e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,i])=>e.indexOf(+n)===-1).map(([n,i])=>i)}function joe(t,e="|"){return t.map(r=>l1e(r)).join(e)}function FG(t,e){return typeof e=="bigint"?e.toString():e}class B7e{constructor(e){this._getter=e,this._value=void 0}get value(){const e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}}function dY(t){return new B7e(t)}function z7e(t){return t==null}function hY(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function $7e(t,e){const r=t/e,n=Math.round(r),i=4*Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n){const d=e._zod.def.shape[a];return n?n(d,a):d}):s1e(t,a,n?n(c.value,a):c.value))}}function U7e(t,e){for(const r of Reflect.ownKeys(e)){const n=Object.getOwnPropertyDescriptor(e,r);n.enumerable&&(n.get?i1e(t,r,()=>e[r]):s1e(t,r,n.value))}}function qh(...t){const e={};for(const r of t){const n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function V7e(t){return JSON.stringify(t)}function q7e(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const a1e="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function xF(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const G7e=dY(()=>{var t;if(ap.jitless||typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function lT(t){if(xF(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const r=e.prototype;return!(xF(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function o1e(t){return lT(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}const H7e=new Set(["string","number","symbol"]);function cT(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qv(t,e,r){const n=new t._zod.constr(e??t._zod.def);return(!e||r!=null&&r.parent)&&(n._zod.parent=t),n}function fi(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function l1e(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function W7e(t){return Object.keys(t).filter(e=>t[e]._zod.optin!==void 0&&t[e]._zod.optout==="optional")}const c1e={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},K7e={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Y7e(t,e){const r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const a={};return uw(a,t,h5(t,e)),qv(t,qh(r,{shape:a,checks:[]}))}function h5(t,e){var i;const r=Wy(t),n=[];for(const a of Reflect.ownKeys(e)){if(!((i=Object.getOwnPropertyDescriptor(r,a))!=null&&i.enumerable))throw new Error(`Unrecognized key: "${String(a)}"`);e[a]&&n.push(a)}return n}function Z7e(t,e){const r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=new Set(h5(t,e)),c={};return uw(c,t,Reflect.ownKeys(Wy(t)).filter(d=>!a.has(d))),qv(t,qh(r,{shape:c,checks:[]}))}function X7e(t,e){if(!lT(e))throw new Error("Invalid input to extend: expected a plain object");const r=t._zod.def.checks;if(r&&r.length>0){const i=Wy(t);for(const a of Reflect.ownKeys(e))if(Object.getOwnPropertyDescriptor(i,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return qv(t,qh(t._zod.def,{shape:u1e(t,e)}))}function u1e(t,e){const r={};return uw(r,t,Reflect.ownKeys(Wy(t))),U7e(r,e),r}function Q7e(t,e){if(!lT(e))throw new Error("Invalid input to safeExtend: expected a plain object");return qv(t,qh(t._zod.def,{shape:u1e(t,e)}))}function J7e(t,e){var i,a;if(!((i=e==null?void 0:e._zod)!=null&&i.def))throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if((a=t._zod.def.checks)!=null&&a.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const r={};uw(r,t,Reflect.ownKeys(Wy(t))),uw(r,e,Reflect.ownKeys(Wy(e)));const n=qh(t._zod.def,{shape:r,get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return qv(t,n)}function Coe(t,e,r,n="partial"){const a=e._zod.def.checks;if(a&&a.length>0)throw new Error(`.${n}() cannot be used on object schemas containing refinements`);const d=r?new Set(h5(e,r)):void 0,p={};return uw(p,e,Reflect.ownKeys(Wy(e)),t&&((l,g)=>d&&!d.has(g)?l:new t({type:"optional",innerType:l}))),qv(e,qh(e._zod.def,{shape:p,checks:[]}))}function eHe(t,e,r){const n=r?new Set(h5(e,r)):void 0,i={};return uw(i,e,Reflect.ownKeys(Wy(e)),(a,c)=>n&&!n.has(c)?a:new t({type:"nonoptional",innerType:a})),qv(e,qh(e._zod.def,{shape:i}))}function Ty(t,e=0){var r;if(t.aborted===!0)return!0;for(let n=e;n{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function rI(t){return typeof t=="string"?t:t==null?void 0:t.message}function Poe(t){const e=[];for(const r of t??[]){const n=r._zod.def;if(!/_(length|size)$|_equals$/.test(n.check))break;const i=n.maximum??n.length??n.size;i>=0&&e.push([i,r])}return e}function BG(t,e,r){var n;for(let i=e;it;return e[cHe]=!0,e}var Noe;const xU={value:void 0,enumerable:!1};let Roe="captureStackTrace"in Error?Error:null;function dHe(t){const e=Roe;if(e){const r=e.stackTraceLimit;if(typeof r=="number"){try{e.stackTraceLimit=0}catch{return Roe=null,new t}try{return new t}finally{e.stackTraceLimit=r}}}return new t}function Mr(t,e,r,n){const i={};function a(E){this.def=E,this.constr=v,this.traits=new Set}a.prototype=i;const c=r,d=c&&new WeakSet;function p(E,T){if(E._zod){if(E._zod.traits.has(t))return}else{xU.value=new a(T);try{Object.defineProperty(E,"_zod",xU)}finally{xU.value=void 0}}if(E._zod.traits.add(t),e(E,T),d){const P=Object.getPrototypeOf(E),C=E._zod.constr.prototype;let L=P;for(;L&&L!==C;)L=Object.getPrototypeOf(L);const O=L??P;d.has(O)||(d.add(O),iHe(O,c))}const j=v.prototype;for(const P in j)Object.prototype.hasOwnProperty.call(j,P)&&(P in E||(E[P]=j[P].bind(E)))}const l=(n==null?void 0:n.Parent)??Object;class g extends l{}Object.defineProperty(g,"name",{value:t});function v(E){var C;const T=n!=null&&n.Parent?dHe(g):this;p(T,E);const j=T._zod.deferred;if(j){for(const L of j)L();T._zod.deferred=void 0}const P=(C=globalThis.__zod_globalConfig)==null?void 0:C.postProcessor;return P&&P(T),T}return Object.defineProperty(v,"init",{value:p}),Object.defineProperty(v,Symbol.hasInstance,{value:E=>{var T,j;return n!=null&&n.Parent&&E instanceof n.Parent?!0:(j=(T=E==null?void 0:E._zod)==null?void 0:T.traits)==null?void 0:j.has(t)}}),Object.defineProperty(v,"name",{value:t}),v}class Wb extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class f1e extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(Noe=globalThis).__zod_globalConfig??(Noe.__zod_globalConfig={});const ap=globalThis.__zod_globalConfig;function mg(t){return t&&Object.assign(ap,t),ap}function hHe(){const t=this._zod;return t.message??(t.message=JSON.stringify(t.def,FG,2)),t.message}function fHe(t){this._zod.message=t}const mHe={get:hHe,set:fHe,enumerable:!0,configurable:!0},_U={value:void 0,enumerable:!1},Loe=new WeakSet([Object.prototype,Error.prototype]),pHe=(t,e)=>{t.name="$ZodError",_U.value=e,Object.defineProperty(t,"issues",_U),_U.value=void 0,Object.defineProperty(t,"message",mHe);const r=Object.getPrototypeOf(t);Loe.has(r)||(Loe.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){const n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}}))},gHe=Mr("$ZodError",pHe);function yHe(t,e,r){return Object.prototype.hasOwnProperty.call(t,e)||(e==="__proto__"?Object.defineProperty(t,e,{value:r(),writable:!0,enumerable:!0,configurable:!0}):t[e]=r()),t[e]}function xHe(t,e=r=>r.message){const r={},n=[];for(const i of t.issues)i.path.length>0?yHe(r,i.path[0],()=>[]).push(e(i)):n.push(e(i));return{formErrors:n,fieldErrors:r}}function _He(t,e=r=>r.message){const r={_errors:[]},n=(i,a=[])=>{for(const c of i.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(d=>n({issues:d},[...a,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...a,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...a,...c.path]);else{const d=[...a,...c.path];if(d.length===0)r._errors.push(e(c));else{let p=r,l=0;for(;l{const e=(r,n,i,a)=>{const c=i?{...i,async:!1}:{async:!1},d=r._zod.run({value:n,issues:[]},c);if(d instanceof Promise)throw new Wb;if(d.issues.length){const p=new((a==null?void 0:a.Err)??t)(d.issues.map(l=>bv(l,c,mg())));throw a1e(p,(a==null?void 0:a.callee)??e),p}return d.value};return e},gY=t=>{const e=async(r,n,i,a)=>{const c=i?{...i,async:!0}:{async:!0};let d=r._zod.run({value:n,issues:[]},c);if(d instanceof Promise&&(d=await d),d.issues.length){const p=new((a==null?void 0:a.Err)??t)(d.issues.map(l=>bv(l,c,mg())));throw a1e(p,(a==null?void 0:a.callee)??e),p}return d.value};return e},yY=t=>(e,r,n)=>{const i=n?{...n,async:!1}:{async:!1},a=e._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new Wb;return a.issues.length?m1e(t,a.issues,i):{success:!0,data:a.value}};function m1e(t,e,r){let n;return{success:!1,get error(){return n||(n=new t(e.map(i=>bv(i,r,mg()))),e=void 0,r=void 0),n},set error(i){n=i,e=void 0,r=void 0}}}const xY=t=>async(e,r,n)=>{const i=n?{...n,async:!0}:{async:!0};let a=e._zod.run({value:r,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?m1e(t,a.issues,i):{success:!0,data:a.value}},vHe=Symbol.for("zod.compile.invalid"),bHe=Symbol.for("zod.compile.fallback"),wHe=(t,e,r)=>{const n=t._zod.bag.validator;if(n!==void 0){if(n(e)!==vHe)return!0;if(n.definite===!0&&r===void 0)return!1}return SHe(t,e,r)};function SHe(t,e,r){const n=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=t._zod.bag.fallbackRun;let a;if(i?(n[bHe]=!0,a=i({value:e,issues:[]},n)):a=t._zod.run({value:e,issues:[]},n),a instanceof Promise)throw new Wb;return a.issues.length===0}const EHe=async(t,e,r)=>{const n=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0};let i=t._zod.run({value:e,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length===0},THe=t=>{const e=pY(t),r=(n,i,a,c)=>{const d=a?{...a,direction:"backward"}:{direction:"backward"};return e(n,i,d,f5(r,c))};return r},AHe=t=>{const e=pY(t),r=(n,i,a,c)=>e(n,i,a,f5(r,c));return r},kHe=t=>{const e=gY(t),r=async(n,i,a,c)=>{const d=a?{...a,direction:"backward"}:{direction:"backward"};return await e(n,i,d,f5(r,c))};return r},IHe=t=>{const e=gY(t),r=async(n,i,a,c)=>await e(n,i,a,f5(r,c));return r},jHe=t=>(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return yY(t)(e,r,i)},CHe=t=>(e,r,n)=>yY(t)(e,r,n),PHe=t=>async(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return xY(t)(e,r,i)},NHe=t=>async(e,r,n)=>xY(t)(e,r,n),RHe=/^[cC][0-9a-z]{6,}$/,LHe=/^[0-9a-z]+$/,DHe=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,MHe=/^[0-9a-vA-V]{20}$/,OHe=/^[A-Za-z0-9]{27}$/,FHe=/^[a-zA-Z0-9_-]{21}$/;function BHe(t){return new RegExp(`^[a-zA-Z0-9_-]{${t}}$`)}const zHe=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,$He=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Doe=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,UHe=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,VHe="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function qHe(){return new RegExp(VHe,"u")}const GHe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,HHe=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,WHe=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,KHe=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,YHe=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ZHe=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,XHe=/^https?$/,QHe=/^\+[1-9]\d{6,14}$/,p1e="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function JHe(t){return new RegExp(`^${t}$`)}const eWe=JHe(p1e);function zG(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:t.seconds?`${e}:[0-5]\\d(?:\\.\\d+)?`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function tWe(t){return new RegExp(`^${zG(t)}$`)}function rWe(t){const e=["Z"];t.offset&&e.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${zG({precision:t.precision,seconds:!0})}(?:${e.join("|")})`,n=t.local?`${r}|${zG({precision:t.precision})}`:r;return new RegExp(`^${p1e}T(?:${n})$`)}const nWe=/^[\s\S]{0,}$/,iWe=/^-?\d+$/,_Y=/^-?\d+(?:\.\d+)?$/,sWe=/^(?:true|false)$/i,aWe=/^[^A-Z]*$/,oWe=/^[^a-z]*$/,_h=Mr("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),vY=t=>{const e=t.value;return!z7e(e)&&e.length!==void 0},_F={number:"number",bigint:"bigint",object:"date"},g1e=Mr("$ZodCheckLessThan",(t,e)=>{_h.init(t,e);const r=_F[typeof e.value];t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value{_h.init(t,e);const r=_F[typeof e.value];t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:_F[typeof n.value]??r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),lWe=Mr("$ZodCheckMultipleOf",(t,e)=>{_h.init(t,e),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?e.value!==BigInt(0)&&r.value%e.value===BigInt(0):$7e(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),cWe=Mr("$ZodCheckNumberFormat",(t,e)=>{var c;_h.init(t,e),e.format=e.format||"float64";const r=(c=e.format)==null?void 0:c.includes("int"),n=r?"int":"number",[i,a]=c1e[e.format];t._zod.check=d=>{const p=d.value;if(r){if(!Number.isInteger(p)){d.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:p,inst:t});return}if(!Number.isSafeInteger(p)){p>0?d.issues.push({input:p,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort}):d.issues.push({input:p,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort});return}}pa&&d.issues.push({origin:"number",input:p,code:"too_big",maximum:a,inclusive:!0,inst:t,continue:!e.abort})}}),uWe=Mr("$ZodCheckMaxLength",(t,e)=>{var r;_h.init(t,e),(r=t._zod.def).when??(r.when=vY),t._zod.check=n=>{const i=n.value,a=i.length;if((typeof i=="string"&&a>e.maximum?fY(i):a)<=e.maximum)return;const d=mY(i);n.issues.push({origin:d,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),dWe=Mr("$ZodCheckMinLength",(t,e)=>{var r;_h.init(t,e),(r=t._zod.def).when??(r.when=vY),t._zod.check=n=>{const i=n.value,a=i.length;if((typeof i=="string"&&a>=e.minimum&&a=e.minimum)return;const d=mY(i);n.issues.push({origin:d,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),hWe=Mr("$ZodCheckLengthEquals",(t,e)=>{var r;_h.init(t,e),(r=t._zod.def).when??(r.when=vY),t._zod.check=n=>{const i=n.value,a=i.length,c=typeof i=="string"&&a>=e.length&&a<=e.length*2?fY(i):a;if(c===e.length)return;const d=mY(i),p=c>e.length;n.issues.push({origin:d,...p?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),m5=Mr("$ZodCheckStringFormat",(t,e)=>{var r,n;_h.init(t,e),e.pattern?(r=t._zod).check??(r.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),fWe=Mr("$ZodCheckRegex",(t,e)=>{m5.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),mWe=Mr("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=aWe),m5.init(t,e)}),pWe=Mr("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=oWe),m5.init(t,e)}),gWe=Mr("$ZodCheckIncludes",(t,e)=>{_h.init(t,e);const r=cT(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position},}${r}`:r);e.pattern=n,t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}}),yWe=Mr("$ZodCheckStartsWith",(t,e)=>{_h.init(t,e);const r=new RegExp(`^${cT(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),xWe=Mr("$ZodCheckEndsWith",(t,e)=>{_h.init(t,e);const r=new RegExp(`.*${cT(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),_We=Mr("$ZodCheckOverwrite",(t,e)=>{_h.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class vWe{constructor(e=[],r={}){this.content=[],this.indent=0,this.args=e,this.closed=r}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const n=e.split(` `).filter(c=>c),i=Math.min(...n.map(c=>c.length-c.trimStart().length)),a=n.map(c=>c.slice(i)).map(c=>" ".repeat(this.indent*2)+c);for(const c of a)this.content.push(c)}compile(){const e=Function,r=(this==null?void 0:this.content)??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) { ${r.join(` `)} };`)(...Object.values(this.closed))}}const bWe={major:4,minor:6,patch:7},yl=Mr("$ZodType",(t,e)=>{var a;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=bWe;const n=t._zod.def.checks,i=t._zod.traits.has("$ZodCheck")?[t,...n??[]]:n!=null&&n.length?[...n]:[];for(const c of i)for(const d of c._zod.onattach)d(t);if(i.length===0)(r=t._zod).deferred??(r.deferred=[]),(a=t._zod.deferred)==null||a.push(()=>{t._zod.run=t._zod.parse});else{const c=(p,l,g)=>{if(p.memo)return p;let v=Ty(p),E;for(const T of l){if(T._zod.def.when){if(tHe(p)||!T._zod.def.when(p))continue}else if(v)continue;const j=p.issues.length,P=T._zod.check(p);if(P instanceof Promise&&(g==null?void 0:g.async)===!1)throw new Wb;if(E||P instanceof Promise)E=(E??Promise.resolve()).then(async()=>{await P,p.issues.length!==j&&(BG(p.issues,j,t),v||(v=Ty(p,j)))});else{if(p.issues.length===j)continue;BG(p.issues,j,t),v||(v=Ty(p,j))}}return E?E.then(()=>p):p},d=(p,l,g)=>{if(Ty(p))return p.aborted=!0,p;const v=c(l,i,g);if(v instanceof Promise){if(g.async===!1)throw new Wb;return v.then(E=>t._zod.parse(E,g))}return t._zod.parse(v,g)};t._zod.run=(p,l)=>{if(l.skipChecks)return t._zod.parse(p,l);if(l.direction==="backward"){const v=t._zod.parse({value:p.value,issues:[]},{...l,skipChecks:!0});return v instanceof Promise?v.then(E=>d(E,p,l)):d(v,p,l)}const g=t._zod.parse(p,l);if(g instanceof Promise){if(l.async===!1)throw new Wb;return g.then(v=>c(v,i,l))}return c(g,i,l)}}},{get"~standard"(){return d1e(this,"~standard",_1e(this))},set"~standard"(t){wv(this,"~standard",t)}}),x1e=(t,e)=>t.issues.length?{issues:t.issues.map(r=>bv(r,e,mg()))}:{value:t.value};async function wWe(t,e){const r={async:!0};return x1e(await t._zod.run({value:e,issues:[]},r),r)}function _1e(t){return{validate:e=>{const r={async:!1};try{const n=t._zod.run({value:e,issues:[]},r);if(!(n instanceof Promise))return x1e(n,r)}catch{}return wWe(t,e)},vendor:"zod",version:1}}const bY=Mr("$ZodString",(t,e)=>{yl.init(t,e),t._zod.pattern=e.pattern??nWe,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),el=Mr("$ZodStringFormat",(t,e)=>{m5.init(t,e),bY.init(t,e)}),SWe=Mr("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=$He),el.init(t,e)}),EWe=Mr("$ZodUUID",(t,e)=>{if(e.version){const n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Doe(n))}else e.pattern??(e.pattern=Doe());el.init(t,e)}),TWe=Mr("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=UHe),el.init(t,e)}),v1e=1,vF=2;function b1e(t){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(t):(new URL(t),!0)}catch{return!1}}function AWe(t,e){return!("normalize"in e)&&!("hostname"in e)&&!("protocol"in e)?b1e(t)||vF:kWe(t,e)}function kWe(t,e){var r;if(!e.normalize&&((r=e.protocol)==null?void 0:r.source)===XHe.source&&!/^https?:\/\//i.test(t))return v1e;try{if(typeof URL<"u"){const n=URL;if(typeof n.parse=="function")return n.parse(t)??vF}return new URL(t)}catch{return vF}}const IWe=/[\t\n\r]/g;function Moe(t){return t.replace(IWe,"")}function jWe(t,e){return e.lastIndex=0,e.test(t.hostname)}function CWe(t,e){return e.lastIndex=0,e.test(t.protocol.endsWith(":")?t.protocol.slice(0,-1):t.protocol)}const PWe=Mr("$ZodURL",(t,e)=>{el.init(t,e),t._zod.check=r=>{try{const n=r.value.trim(),i=AWe(n,e);if(i===v1e){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}if(i===vF){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort});return}if(i===!0){r.value=Moe(n);return}e.hostname&&!jWe(i,e.hostname)&&r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort}),e.protocol&&!CWe(i,e.protocol)&&r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort}),r.value=e.normalize?i.href:Moe(n);return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),NWe=Mr("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=qHe()),el.init(t,e)}),RWe=Mr("$ZodNanoID",(t,e)=>{if(e.length!==void 0&&(!Number.isInteger(e.length)||e.length<1))throw new Error(`Invalid nanoid length: ${e.length}`);e.pattern??(e.pattern=e.length===void 0?FHe:BHe(e.length)),el.init(t,e)}),LWe=Mr("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=RHe),el.init(t,e)}),DWe=Mr("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=LHe),el.init(t,e)}),MWe=Mr("$ZodULID",(t,e)=>{e.pattern??(e.pattern=DHe),el.init(t,e)}),OWe=Mr("$ZodXID",(t,e)=>{e.pattern??(e.pattern=MHe),el.init(t,e)}),FWe=Mr("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=OHe),el.init(t,e)}),BWe=Mr("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=rWe(e)),el.init(t,e)}),zWe=Mr("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=eWe),el.init(t,e)}),$We=Mr("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=tWe(e)),el.init(t,e)}),UWe=Mr("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=zHe),el.init(t,e)}),VWe=Mr("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=GHe),el.init(t,e)}),qWe=/^[0-9a-fA-F:.]+$/;function w1e(t){return qWe.test(t)?b1e(`http://[${t}]`):!1}const GWe=Mr("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=HHe),el.init(t,e),t._zod.check=r=>{w1e(r.value)||r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}),HWe=Mr("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=WHe),el.init(t,e)});function WWe(t){const e=t.split("/");if(e.length!==2)return!1;const[r,n]=e;if(!n)return!1;const i=Number(n);return`${i}`!==n||i<0||i>128?!1:w1e(r)}const KWe=Mr("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=KHe),el.init(t,e),t._zod.check=r=>{WWe(r.value)||r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}});function S1e(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const E1e=/^[0-9a-zA-Z+/]*={0,2}$/,YWe=Mr("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=E1e),el.init(t,e),t._zod.check=r=>{S1e(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}}),wY=/^[A-Za-z0-9_-]*$/;function ZWe(t){if(!wY.test(t))return!1;const e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return S1e(r)}const XWe=Mr("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=wY),el.init(t,e),t._zod.check=r=>{ZWe(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),QWe=Mr("$ZodE164",(t,e)=>{e.pattern??(e.pattern=QHe),el.init(t,e)});function JWe(t,e=null){try{const r=t.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const i=JSON.parse(atob(n));return!("typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}const eKe=Mr("$ZodJWT",(t,e)=>{el.init(t,e),t._zod.check=r=>{JWe(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),T1e=Mr("$ZodNumber",(t,e)=>{yl.init(t,e),t._zod.pattern=_Y,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}const i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;const a=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:String(i):void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...a?{received:a}:{}}),r}}),tKe=Mr("$ZodNumberFormat",(t,e)=>{cWe.init(t,e),T1e.init(t,e)}),rKe=Mr("$ZodBoolean",(t,e)=>{yl.init(t,e),t._zod.pattern=sWe,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}const i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:t}),r}}),nKe=Mr("$ZodUnknown",(t,e)=>{yl.init(t,e),t._zod.parse=r=>r}),iKe=Mr("$ZodNever",(t,e)=>{yl.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function sKe(t,e){const r=Poe(t._zod.def.checks);if(!r.length)return;const n=Math.min(...r.map(a=>a[0])),i=t._zod.parse;t._zod.parse=(a,c)=>{const d=e(a.value);if(d>n&&!(c!=null&&c.skipChecks)&&(c==null?void 0:c.direction)!=="backward"){for(const[p,l]of Poe(t._zod.def.checks))if(d>p&&l._zod.def.when(a)){const g=a.issues.length;return l._zod.check(a),a.issues[g].continue=!1,BG(a.issues,g,t),a}}return i(a,c)}}const aKe=t=>Array.isArray(t)?t.length:-1;function Ooe(t,e,r){t.issues.length&&e.issues.push(...iE(r,t.issues)),e.value[r]=t.value}const oKe=Mr("$ZodArray",(t,e)=>{yl.init(t,e);const r=ap.memoizer;r==null||r.attach(t),t._zod.parse=(n,i)=>{const a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:t}),n;n.value=r?r.alloc(t,n,Array(a.length),i):Array(a.length);const c=[],d=i==null?void 0:i.abortEarly;for(let p=0;pOoe(v,n,p)));else if(Ooe(g,n,p),d&&g.issues.length!==0&&Ty(g))break}return c.length?Promise.all(c).then(()=>n):n},sKe(t,aKe)});function bF(t,e,r,n,i,a){const c=r in n,d=a==="optional";if(!(!c&&d&&i==="optional")){if(t.issues.length){if(i!==void 0&&d&&!c)return;e.issues.push(...iE(r,t.issues))}if(!c&&i===void 0){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?(c||i==="defaulted"&&!d)&&(e.value[r]=void 0):e.value[r]=t.value}}const lKe=[];function A1e(t){var c,d,p,l;const e=Object.keys(t.shape),r=Object.getOwnPropertySymbols(t.shape),n=r.length?r:lKe,i=n.length?[...e,...n]:e;for(const g of i)if(!((l=(p=(d=(c=t.shape)==null?void 0:c[g])==null?void 0:d._zod)==null?void 0:p.traits)!=null&&l.has("$ZodType")))throw new Error(`Invalid element at key "${String(g)}": expected a Zod schema`);const a=W7e(t.shape);return{...t,allKeys:i,symbolKeys:n,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(a)}}function k1e(t,e,r,n,i,a,c){const d=[],p=i.keySet,l=i.catchall._zod,g=l.def.type,v=l.optin,E=l.optout;let T=0;for(const j in e){if(c&&r.issues.length!==T){if(Ty(r,T))break;T=r.issues.length}if(p.has(j))continue;if(j==="__proto__"){g==="never"&&d.push(j);continue}if(g==="never"){d.push(j);continue}const P=l.run({value:e[j],issues:[]},n);P instanceof Promise?t.push(P.then(C=>bF(C,r,j,e,v,E))):bF(P,r,j,e,v,E)}return d.length&&r.issues.push({code:"unrecognized_keys",keys:d,input:e,inst:a,continue:!0}),t.length?Promise.all(t).then(()=>r):r}const cKe=Mr("$ZodObject",(t,e)=>{yl.init(t,e);const r=Object.getOwnPropertyDescriptor(e,"shape"),n=r!=null&&r.get?r.get.raw:e.shape??{};if(n){const l=()=>{const g={...n};return Object.defineProperty(e,"shape",{value:g}),l.raw=g,g};l.raw=n,Object.defineProperty(e,"shape",{get:l})}const i=dY(()=>A1e(e));Na(t,"propValues",l=>{const g=l.def.shape,v={};for(const E in g){const T=g[E]._zod;if(T.values){Object.prototype.hasOwnProperty.call(v,E)||Vv(v,E,new Set);for(const j of T.values)v[E].add(j);T.optin!==void 0&&v[E].add(void 0)}}return v});const a=xF,c=e.catchall;let d;const p=ap.memoizer;p==null||p.attach(t),t._zod.parse=(l,g)=>{d??(d=i.value);const v=l.value;if(!a(v))return l.issues.push({expected:"object",code:"invalid_type",input:v,inst:t}),l;l.value=p?p.alloc(t,l,{},g):{};const E=[],T=d.shape,j=g==null?void 0:g.abortEarly;let P=l.issues.length;for(const C of d.allKeys){if(j&&l.issues.length!==P){if(Ty(l,P))break;P=l.issues.length}if(C==="__proto__")continue;const L=T[C],O=L._zod.optin,F=L._zod.optout,$=L._zod.run({value:v[C],issues:[]},g);$ instanceof Promise?E.push($.then(G=>bF(G,l,C,v,O,F))):bF($,l,C,v,O,F)}return c?k1e(E,v,l,g,i.value,t,j===!0):E.length?Promise.all(E).then(()=>l):l}}),uKe=Mr("$ZodObjectJIT",(t,e)=>{cKe.init(t,e);const r=t._zod.parse,n=dY(()=>A1e(e)),i=ap.memoizer,a=T=>{var G,W;const j=n.value,P=j.symbolKeys,C=new vWe(["payload","ctx"],{shape:T,inst:t,memo:i,syms:P}),L=Z=>`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`,O=(Z,Q)=>` let ${Z}_ab = false; for (let i = 0; i < ${Z}.issues.length; i++) { const iss = ${Z}.issues[i]; iss.path = iss.path ? [${Q}, ...iss.path] : [${Q}]; payload.issues.push(iss); if (iss.continue !== true) ${Z}_ab = true; } if (${Z}_ab && ctx && ctx.abortEarly) { payload.value = newResult; return payload; }`;C.write("const input = payload.value;");const F=Object.create(null);let $=0;for(const Z of j.allKeys)F[Z]=`key_${$++}`;C.write(i?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(const Z of j.allKeys){if(Z==="__proto__")continue;const Q=F[Z],ee=typeof Z=="symbol"?`syms[${P.indexOf(Z)}]`:V7e(Z),ie=`${ee} in input`,oe=T[Z],pe=(G=oe==null?void 0:oe._zod)==null?void 0:G.optin,Le=pe!==void 0,be=((W=oe==null?void 0:oe._zod)==null?void 0:W.optout)==="optional";if(C.write(`const ${Q} = ${L(ee)};`),Le&&be){const Re=pe==="optional"?`${Q}_present`:`${Q}.value !== undefined || ${Q}_present`;C.write(` const ${Q}_present = ${ie}; if (!${Q}.issues.length || ${Q}_present) { if (${Q}.issues.length) {${O(Q,ee)} } if (${Re}) { newResult[${ee}] = ${Q}.value; } } `)}else Le?(C.write(` if (${Q}.issues.length) {${O(Q,ee)} } `),pe==="defaulted"?C.write(`newResult[${ee}] = ${Q}.value;`):C.write(` if (${Q}.value !== undefined || ${ie}) { newResult[${ee}] = ${Q}.value; } `)):C.write(` const ${Q}_present = ${ie}; if (${Q}.issues.length) {${O(Q,ee)} } if (!${Q}_present && !${Q}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${ee}] }); if (ctx && ctx.abortEarly) { payload.value = newResult; return payload; } } if (${Q}_present) { newResult[${ee}] = ${Q}.value; } `)}return C.write("payload.value = newResult;"),C.write("return payload;"),C.compile()};let c;const d=xF,p=!ap.jitless,g=p&&G7e.value,v=e.catchall;let E;t._zod.parse=(T,j)=>{E??(E=n.value);const P=T.value;return d(P)?p&&g&&(j==null?void 0:j.async)===!1&&j.jitless!==!0?(c||(c=a(e.shape)),T=c(T,j),v?k1e([],P,T,j,E,t,(j==null?void 0:j.abortEarly)===!0):T):r(T,j):(T.issues.push({expected:"object",code:"invalid_type",input:P,inst:t}),T)}});function Foe(t,e,r,n){for(const a of t)if(a.issues.length===0)return e.value=a.value,e;const i=t.filter(a=>!Ty(a));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(a=>a.issues.map(c=>bv(c,n,mg())))}),e)}const dKe=Mr("$ZodUnion",(t,e)=>{yl.init(t,e),Na(t,"optin",n=>n.def.options.some(i=>i._zod.optin==="defaulted")?"defaulted":n.def.options.some(i=>i._zod.optin!==void 0)?"optional":void 0),Na(t,"optout",n=>n.def.options.some(i=>i._zod.optout==="optional")?"optional":void 0),Na(t,"values",n=>{if(n.def.options.every(i=>i._zod.values))return new Set(n.def.options.flatMap(i=>Array.from(i._zod.values)))}),Na(t,"pattern",n=>{if(n.def.options.every(i=>i._zod.pattern)){const i=n.def.options.map(a=>a._zod.pattern);return new RegExp(`^(${i.map(a=>hY(a.source)).join("|")})$`)}});const r=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(n,i)=>{if(r)return r(n,i);let a=!1;const c=[];for(const d of e.options){const p=d._zod.run({value:n.value,issues:[]},i);if(p instanceof Promise)c.push(p),a=!0;else{if(p.issues.length===0)return p;c.push(p)}}return a?Promise.all(c).then(d=>Foe(d,n,t,i)):Foe(c,n,t,i)}}),hKe=Mr("$ZodIntersection",(t,e)=>{yl.init(t,e),t._zod.parse=(r,n)=>{const i=r.value,a=e.left._zod.run({value:i,issues:[]},n),c=e.right._zod.run({value:i,issues:[]},n);return a instanceof Promise||c instanceof Promise?Promise.all([a,c]).then(([p,l])=>Boe(r,p,l)):Boe(r,a,c)}});function $G(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(lT(t)&&lT(e)){const r=Object.keys(e),n=Object.keys(t).filter(a=>r.indexOf(a)!==-1),i={...t,...e};Object.prototype.hasOwnProperty.call(i,"__proto__")&&delete i.__proto__;for(const a of n){if(a==="__proto__")continue;const c=$G(t[a],e[a]);if(!c.valid)return{valid:!1,mergeErrorPath:[a,...c.mergeErrorPath]};i[a]=c.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n{var E,T;let v;if(l.code==="unrecognized_keys"&&!((E=l.path)!=null&&E.length))i??(i=l),v=l.keys;else if(l.code==="invalid_key"&&l.origin==="record"&&((T=l.path)==null?void 0:T.length)===1){const j=String(l.path[0]);a.has(j)||a.set(j,l),v=[j]}else return!1;for(const j of v)n.has(j)||n.set(j,{}),n.get(j)[g]=!0;return!0};for(const l of e.issues)c(l,"l")||t.issues.push(l);for(const l of r.issues)c(l,"r")||t.issues.push(l);const d=[...n].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(d.length){const l=i?d.filter(g=>i.keys.includes(g)):[];l.length&&t.issues.push({...i,keys:l});for(const g of d)!l.includes(g)&&a.has(g)&&t.issues.push(a.get(g))}const p=$G(e.value,r.value);if(!p.valid){if(Ty(t))return t;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(p.mergeErrorPath)}`)}return t.value=p.data,t}const fKe=Mr("$ZodRecord",(t,e)=>{yl.init(t,e);const r=ap.memoizer;r==null||r.attach(t),t._zod.parse=(n,i)=>{const a=n.value;if(!lT(a))return n.issues.push({expected:"record",code:"invalid_type",input:a,inst:t}),n;const c=[],d=e.keyType._zod.values;if(d&&!e.partial){n.value=r?r.alloc(t,n,{},i):{};const p=new Set;for(const g of d)if(typeof g=="string"||typeof g=="number"||typeof g=="symbol"){if(p.add(typeof g=="number"?g.toString():g),g==="__proto__")continue;const v=e.keyType._zod.run({value:g,issues:[]},i);if(v instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(v.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:v.issues.map(j=>bv(j,i,mg())),input:g,path:[g],inst:t});continue}const E=v.value;if(E==="__proto__")continue;const T=e.valueType._zod.run({value:a[g],issues:[]},i);T instanceof Promise?c.push(T.then(j=>{j.issues.length&&n.issues.push(...iE(g,j.issues)),n.value[E]=j.value})):(T.issues.length&&n.issues.push(...iE(g,T.issues)),n.value[E]=T.value)}let l;for(const g in a)if(!p.has(g))if(e.mode==="loose"){if(g==="__proto__")continue;n.value[g]=a[g]}else l=l??[],l.push(g);l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:a,inst:t,keys:l,continue:!0})}else{n.value=r?r.alloc(t,n,{},i):{};let p;for(const l of Reflect.ownKeys(a)){if(l==="__proto__"||!Object.prototype.propertyIsEnumerable.call(a,l))continue;let g=e.keyType._zod.run({value:l,issues:[]},i);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&_Y.test(l)&&g.issues.length){const j=e.keyType._zod.run({value:Number(l),issues:[]},i);if(j instanceof Promise)throw new Error("Async schemas not supported in object keys currently");j.issues.length===0&&(g=j)}if(g.issues.length){e.mode==="loose"?n.value[l]=a[l]:d?(p=p??[],p.push(l)):n.issues.push({code:"invalid_key",origin:"record",issues:g.issues.map(j=>bv(j,i,mg())),input:l,path:[l],inst:t});continue}const E=g.value;if(E==="__proto__")continue;const T=e.valueType._zod.run({value:a[l],issues:[]},i);T instanceof Promise?c.push(T.then(j=>{j.issues.length&&n.issues.push(...iE(l,j.issues)),n.value[E]=j.value})):(T.issues.length&&n.issues.push(...iE(l,T.issues)),n.value[E]=T.value)}p&&p.length>0&&n.issues.push({code:"unrecognized_keys",input:a,inst:t,keys:p,continue:!0})}return c.length?Promise.all(c).then(()=>n):n}}),mKe=Mr("$ZodEnum",(t,e)=>{yl.init(t,e);const r=OG(e.entries),n=new Set(r);t._zod.values=n,Na(t,"pattern",i=>{const a=OG(i.def.entries).filter(c=>H7e.has(typeof c));return new RegExp(a.length?`^(${a.map(c=>cT(c.toString())).join("|")})$`:"^[^\\s\\S]$")}),t._zod.parse=(i,a)=>{const c=i.value;return n.has(c)||i.issues.push({code:"invalid_value",values:r,input:c,inst:t}),i}}),pKe=Mr("$ZodLiteral",(t,e)=>{yl.init(t,e);const r=new Set(e.values);t._zod.values=r,Na(t,"pattern",n=>{const i=n.def.values;return new RegExp(i.length?`^(${i.map(a=>typeof a=="string"?cT(a):a?cT(a.toString()):String(a)).join("|")})$`:"^[^\\s\\S]$")}),t._zod.parse=(n,i)=>{const a=n.value;return r.has(a)||n.issues.push({code:"invalid_value",values:e.values,input:a,inst:t}),n}}),gKe=Mr("$ZodTransform",(t,e)=>{var r;yl.init(t,e),t._zod.optin="optional",(r=ap.memoizer)==null||r.guard(t),t._zod.parse=(n,i)=>{if(i.direction==="backward")throw new f1e(t.constructor.name);const a=e.transform(n.value,n);if(i.async)return(a instanceof Promise?a:Promise.resolve(a)).then(d=>(n.value=d,n));if(a instanceof Promise)throw new Wb;return n.value=a,n}});function zoe(t,e){return t.value=e.issues.length?void 0:e.value,t}const I1e=Mr("$ZodOptional",(t,e)=>{yl.init(t,e),Na(t,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),t._zod.optout="optional",Na(t,"values",r=>{const n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),Na(t,"pattern",r=>{const n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${hY(n.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(r.value===void 0){if(e.innerType._zod.optin!=="defaulted")return r;const i=e.innerType._zod.run({value:r.value,issues:[]},n);return i instanceof Promise?i.then(a=>zoe(r,a)):zoe(r,i)}return e.innerType._zod.run(r,n)}}),yKe=Mr("$ZodExactOptional",(t,e)=>{I1e.init(t,e),Na(t,"values",r=>r.def.innerType._zod.values),Na(t,"pattern",r=>r.def.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),xKe=Mr("$ZodNullable",(t,e)=>{yl.init(t,e),Na(t,"optin",r=>r.def.innerType._zod.optin),Na(t,"optout",r=>r.def.innerType._zod.optout),Na(t,"pattern",r=>{const n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${hY(n.source)}|null)$`):void 0}),Na(t,"values",r=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),_Ke=Mr("$ZodDefault",(t,e)=>{yl.init(t,e),t._zod.optin="defaulted",Na(t,"values",r=>r.def.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;const i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(a=>$oe(a,e)):$oe(i,e)}});function $oe(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const vKe=Mr("$ZodPrefault",(t,e)=>{yl.init(t,e),t._zod.optin="defaulted",Na(t,"values",r=>r.def.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),bKe=Mr("$ZodNonOptional",(t,e)=>{yl.init(t,e),Na(t,"values",r=>{const n=r.def.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),t._zod.parse=(r,n)=>{const i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(a=>Uoe(a,t)):Uoe(i,t)}});function Uoe(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function Voe(t,e,r,n){return e.issues.length?(t.value=r.catchValue({...e,value:t.value,error:{issues:e.issues.map(i=>bv(i,n,mg()))},input:t.value}),t):(t.value=e.value,e.memo&&(t.memo=!0),t)}const wKe=Mr("$ZodCatch",(t,e)=>{yl.init(t,e),Na(t,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),Na(t,"optout",r=>r.def.innerType._zod.optout),Na(t,"values",r=>r.def.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);const i=e.innerType._zod.run({value:r.value,issues:[]},n);return i instanceof Promise?i.then(a=>Voe(r,a,e,n)):Voe(r,i,e,n)}}),SKe=Mr("$ZodPipe",(t,e)=>{yl.init(t,e),Na(t,"values",r=>r.def.in._zod.values),Na(t,"optin",r=>r.def.in._zod.optin),Na(t,"optout",r=>r.def.out._zod.optout),Na(t,"propValues",r=>r.def.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){const a=e.out._zod.run(r,n);return a instanceof Promise?a.then(c=>ED(c,e.in,n)):ED(a,e.in,n)}const i=e.in._zod.run(r,n);return i instanceof Promise?i.then(a=>ED(a,e.out,n)):ED(i,e.out,n)}});function ED(t,e,r){return t.issues.some(n=>n.code!=="unrecognized_keys")?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},r)}const EKe=Mr("$ZodReadonly",(t,e)=>{yl.init(t,e),Na(t,"propValues",r=>r.def.innerType._zod.propValues),Na(t,"values",r=>r.def.innerType._zod.values),Na(t,"optin",r=>{var n,i;return(i=(n=r.def.innerType)==null?void 0:n._zod)==null?void 0:i.optin}),Na(t,"optout",r=>{var n,i;return(i=(n=r.def.innerType)==null?void 0:n._zod)==null?void 0:i.optout}),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);const i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(qoe):qoe(i)}});function qoe(t){return t.memo||(t.value=Object.freeze(t.value)),t}const TKe=Mr("$ZodCustom",(t,e)=>{_h.init(t,e),yl.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{const n=r.value,i=e.fn(n);if(i instanceof Promise)return i.then(a=>Goe(a,r,n,t));Goe(i,r,n,t)}});function Goe(t,e,r,n){if(!t){const i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),e.issues.push(oC(i))}}class AKe extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}const UG="~memo",Hoe=[];function j1e(t){return t!==null&&typeof t=="object"}function vU(t){return t.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const C1e=new WeakMap,FI=0,eO=1,oj=2;function tO(t,e,r){const n=C1e.get(t);if(n!==void 0)return n?oj:FI;if(e.has(t))return oj;e.add(t);let i=FI;const a=g=>{if(i!==oj&&(g!=null&&g._zod)){const v=tO(g,e);v>i&&(i=v)}},c=(g,v)=>{var T;let E=FI;for(const j of Reflect.ownKeys(g)){const P=Object.getOwnPropertyDescriptor(g,j);if(!P.enumerable)continue;const C=P.get?eO:(T=P.value)!=null&&T._zod?tO(P.value,e):FI;C>E&&(E=C)}return E},d=g=>{g>i&&(i=g)},p=t._zod.def;switch(p.type){case"object":{const g=n1e(p);d(g?c(g):eO),a(p.catchall);break}case"array":a(p.element);break;case"tuple":for(const g of p.items)a(g);a(p.rest);break;case"record":case"map":a(p.keyType),a(p.valueType);break;case"set":a(p.valueType);break;case"union":for(const g of p.options)a(g);break;case"intersection":a(p.left),a(p.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":a(p.innerType);break;case"pipe":a(p.in),a(p.out);break;case"function":a(p.input),a(p.output);break;case"lazy":{const g=p._cachedInner??void 0;d(g?tO(g,e):eO);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(const g in p){const v=Object.getOwnPropertyDescriptor(p,g);if(!v||v.get)continue;const E=v.value;if(!(!E||typeof E!="object")){if(E._zod)a(E);else if(Array.isArray(E))for(const T of E)a(T)}}}return e.delete(t),kKe(t,i)}function kKe(t,e){return e!==eO&&C1e.set(t,e===oj),e}function IKe(t,e){let r=t.buckets.get(e);return r||(r=new WeakMap,t.buckets.set(e,r)),r}let TD;const AD=[],jKe={alloc(t,e,r){const n=TD;if(!n)return r;TD=void 0;const i={value:r,issues:null};return n.set(e.value,i),AD.push(i),r},guard(t){var e;(e=t._zod).deferred??(e.deferred=[]),t._zod.deferred.push(()=>{const r=t._zod.parse,n=(i,a)=>{if(a.direction!=="backward"&&PKe(a,i.value))throw new AKe;return r(i,a)};t._zod.parse=n,t._zod.run===r&&(t._zod.run=n)})},attach(t){var e;let r,n=!1,i,a;(e=t._zod).deferred??(e.deferred=[]),t._zod.deferred.push(()=>{const c=t._zod.parse,d=(p,l)=>{if(r===void 0){const L=tO(t,new Set);if(L===FI)return t._zod.parse=c,t._zod.run===d&&(t._zod.run=c),c(p,l);L===oj||n?r=!0:n=!0}const g=p.value;if(!j1e(g))return c(p,l);let v=l[UG];v||(v={buckets:new WeakMap,backEdges:void 0},l[UG]=v);let E;i===l?E=a:(E=IKe(v,t),i=l,a=E);const T=E.get(g);if(T)return p.value=T.value,T.issues?T.issues.length&&p.issues.push(...vU(T.issues)):(p.memo=!0,v.backEdges??(v.backEdges=new WeakSet),v.backEdges.add(T.value)),p;TD=E;const j=AD.length,P=c(p,l);TD=void 0;const C=AD.length>j?AD.pop():void 0;return P instanceof Promise?P.then(L=>(C&&(C.issues=L.issues.length?vU(L.issues):Hoe),L)):(C&&(C.issues=P.issues.length?vU(P.issues):Hoe),P)};t._zod.parse=d,t._zod.run===c&&(t._zod.run=d)})}};function CKe(){return jKe}function PKe(t,e){var n;const r=(n=t[UG])==null?void 0:n.backEdges;return r!==void 0&&j1e(e)&&r.has(e)}const NKe=()=>{const t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(a){return t[a]??null}const r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};function i(a,c){return a==="number"&&typeof c=="number"&&!Number.isFinite(c)?String(c):n[a]??a}return a=>{switch(a.code){case"invalid_type":{const c=i(a.expected),d=nHe(a.input),p=i(d,a.input);return`Invalid input: expected ${c}, received ${p}`}case"invalid_value":return a.values.length===1?`Invalid input: expected ${l1e(a.values[0])}`:`Invalid option: expected one of ${joe(a.values,"|")}`;case"too_big":{const c=a.exact?"exactly ":a.inclusive?"<=":"<",d=e(a.origin);return d?`Too big: expected ${a.origin??"value"} to have ${c}${a.maximum.toString()} ${d.unit??"elements"}`:`Too big: expected ${a.origin??"value"} to be ${c}${a.maximum.toString()}`}case"too_small":{const c=a.exact?"exactly ":a.inclusive?">=":">",d=e(a.origin);return d?`Too small: expected ${a.origin} to have ${c}${a.minimum.toString()} ${d.unit}`:`Too small: expected ${a.origin} to be ${c}${a.minimum.toString()}`}case"invalid_format":{const c=a;return c.format==="starts_with"?`Invalid string: must start with "${c.prefix}"`:c.format==="ends_with"?`Invalid string: must end with "${c.suffix}"`:c.format==="includes"?`Invalid string: must include "${c.includes}"`:c.format==="regex"?`Invalid string: must match pattern ${c.pattern}`:`Invalid ${r[c.format]??a.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${a.divisor}`;case"unrecognized_keys":return`Unrecognized key${a.keys.length>1?"s":""}: ${joe(a.keys,", ")}`;case"invalid_key":return`Invalid key in ${a.origin}`;case"invalid_union":return a.options&&Array.isArray(a.options)&&a.options.length>0?`Invalid discriminator value. Expected ${a.options.map(d=>`'${d}'`).join(" | ")}`:a.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${a.origin}`;default:return"Invalid input"}}};function RKe(){return{localeError:NKe()}}var Woe;class LKe{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){const n=r[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){const r=e._zod.parent;if(r){const n={...this.get(r)??{}};delete n.id;const i={...n,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function DKe(){return new LKe}(Woe=globalThis).__zod_globalRegistry??(Woe.__zod_globalRegistry=DKe());const BI=globalThis.__zod_globalRegistry;function P1e(t){return t.checks&&(t.checks=[...t.checks]),t}function MKe(t,e){return new t(P1e({type:"string",...fi(e)}))}function OKe(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...fi(e)})}function FKe(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...fi(e)})}function BKe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...fi(e)})}function zKe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...fi(e)})}function $Ke(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...fi(e)})}function UKe(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...fi(e)})}function VKe(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...fi(e)})}function qKe(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...fi(e)})}function GKe(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...fi(e)})}function HKe(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...fi(e)})}function WKe(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...fi(e)})}function KKe(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...fi(e)})}function YKe(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...fi(e)})}function ZKe(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...fi(e)})}function XKe(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...fi(e)})}function QKe(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...fi(e)})}function JKe(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...fi(e)})}function eYe(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...fi(e)})}function tYe(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...fi(e)})}function rYe(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...fi(e)})}function nYe(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...fi(e)})}function iYe(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...fi(e)})}function sYe(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...fi(e)})}function aYe(t,e){return new t({type:"string",format:"date",check:"string_format",...fi(e)})}function oYe(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...fi(e)})}function lYe(t,e){return new t({type:"string",format:"duration",check:"string_format",...fi(e)})}function cYe(t,e){return new t(P1e({type:"number",checks:[],...fi(e)}))}function uYe(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...fi(e)})}function dYe(t,e){return new t({type:"boolean",...fi(e)})}function hYe(t){return new t({type:"unknown"})}function fYe(t,e){return new t({type:"never",...fi(e)})}function Koe(t,e){return new g1e({check:"less_than",...fi(e),value:t,inclusive:!1})}function bU(t,e){return new g1e({check:"less_than",...fi(e),value:t,inclusive:!0})}function Yoe(t,e){return new y1e({check:"greater_than",...fi(e),value:t,inclusive:!1})}function wU(t,e){return new y1e({check:"greater_than",...fi(e),value:t,inclusive:!0})}function Zoe(t,e){return new lWe({check:"multiple_of",...fi(e),value:t})}function N1e(t,e){return new uWe({check:"max_length",...fi(e),maximum:t})}function wF(t,e){return new dWe({check:"min_length",...fi(e),minimum:t})}function R1e(t,e){return new hWe({check:"length_equals",...fi(e),length:t})}function mYe(t,e){return new fWe({check:"string_format",format:"regex",...fi(e),pattern:t})}function pYe(t){return new mWe({check:"string_format",format:"lowercase",...fi(t)})}function gYe(t){return new pWe({check:"string_format",format:"uppercase",...fi(t)})}function yYe(t,e){return new gWe({check:"string_format",format:"includes",...fi(e),includes:t})}function xYe(t,e){return new yWe({check:"string_format",format:"starts_with",...fi(e),prefix:t})}function _Ye(t,e){return new xWe({check:"string_format",format:"ends_with",...fi(e),suffix:t})}function wA(t){return new _We({check:"overwrite",tx:t})}function vYe(t){return wA(e=>e.normalize(t))}function bYe(){return wA(t=>t.trim())}function wYe(){return wA(t=>t.toLowerCase())}function SYe(){return wA(t=>t.toUpperCase())}function EYe(){return wA(t=>q7e(t))}function TYe(t,e,r){return new t({type:"array",element:e,...fi(r)})}function AYe(t,e,r){return new t({type:"custom",check:"custom",fn:e,...fi(r)})}function kYe(t,e){const r=IYe(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(oC(i,n.value,r._zod.def));else{const a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),"input"in a||(a.input=n.value),a.inst??(a.inst=r),a.continue??(a.continue=!r._zod.def.abort),n.issues.push(oC(a))}},t(n.value,n)),e);return r}function IYe(t,e){const r=new _h({check:"custom",...fi(e)});return r._zod.check=t,r}function lj(t,...e){for(const r of e)for(const n of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,n)&&Vv(t,n,r[n]);return t}function L1e(t){let e=(t==null?void 0:t.target)??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:(t==null?void 0:t.metadata)??BI,target:e,unrepresentable:(t==null?void 0:t.unrepresentable)??"throw",override:(t==null?void 0:t.override)??(()=>{}),io:(t==null?void 0:t.io)??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:(t==null?void 0:t.cycles)??"ref",reused:(t==null?void 0:t.reused)??"inline",intersections:[],deferred:[],external:(t==null?void 0:t.external)??void 0}}function Sv(t,e,r,n,i){const a=typeof e.unrepresentable=="function"?e.unrepresentable({zodSchema:t,path:n.path,message:i}):e.unrepresentable;if(a==="any")return!1;if(a===void 0||a==="throw")throw new Error(i);return Object.assign(r,a),!0}function hc(t,e,r={path:[],schemaPath:[]}){var g,v;var n;const i=t._zod.def,a=e.seen.get(t);if(a)return a.count++,r.schemaPath.includes(t)&&(a.cycle=r.path),a.schema;const c={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,c),e.sharedDefsExtractedFor=void 0,e.sharedEmitDoneFor=void 0;const d=(v=(g=t._zod).toJSONSchema)==null?void 0:v.call(g);if(d)c.schema=d;else{const E={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,c.schema,E);else{const j=c.schema,P=e.processors[i.type];if(!P)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);P(t,e,j,E)}const T=t._zod.parent;T&&(c.ref||(c.ref=T),hc(T,e,E),e.seen.get(T).isParent=!0)}const p=e.metadataRegistry.get(t);return p&&lj(c.schema,p),e.io==="input"&&Sd(t)&&(delete c.schema.examples,delete c.schema.default),e.io==="input"&&"_prefault"in c.schema&&((n=c.schema).default??(n.default=c.schema._prefault)),delete c.schema._prefault,e.seen.get(t).schema}function Xoe(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function D1e(t,e){var c,d,p,l;const r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(t.external&&t.sharedDefsExtractedFor===t.external)return;const n=new Map;for(const g of t.seen.entries()){const v=(c=t.metadataRegistry.get(g[0]))==null?void 0:c.id;if(v){const E=n.get(v);if(E&&E!==g[0])throw new Error(`Duplicate schema id "${v}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(v,g[0])}}const i=g=>{var P;const v=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const C=(P=t.external.registry.get(g[0]))==null?void 0:P.id,L=t.external.uri??(F=>F);if(C)return{ref:L(C)};const O=g[1].defId??g[1].schema.id??`schema${t.counter++}`;return g[1].defId=O,{defId:O,ref:`${L("__shared")}#/${v}/${Xoe(O)}`}}const E="#",T=`${E}/${v}/`;if(g[1]===r&&!g[1].schema.id)return{ref:E};const j=g[1].schema.id??`__schema${t.counter++}`;return{defId:j,ref:T+Xoe(j)}},a=g=>{if(g[1].schema.$ref)return;const v=g[1],{ref:E,defId:T}=i(g);v.def={...v.schema},T&&(v.defId=T);const j=v.schema;for(const P in j)delete j[P];j.$ref=E};if(t.cycles==="throw")for(const g of t.seen.entries()){const v=g[1];if(v.cycle)throw new Error(`Cycle detected: #/${(d=v.cycle)==null?void 0:d.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const g of t.seen.entries()){const v=g[1];if(e===g[0]){a(g);continue}if(t.external){const T=(p=t.external.registry.get(g[0]))==null?void 0:p.id;if(e!==g[0]&&T){a(g);continue}}if((l=t.metadataRegistry.get(g[0]))==null?void 0:l.id){a(g);continue}if(v.cycle){a(g);continue}v.count>1&&t.reused==="ref"&&a(g)}t.external&&(t.sharedDefsExtractedFor=t.external)}function M1e(t){const e=t.anyOf;if(!Array.isArray(e)||e.length===0||t.type!==void 0)return;const r=[];for(const n of e){if(!n||typeof n!="object")return;M1e(n);const i=Object.keys(n);if(i.length!==1||i[0]!=="type")return;const a=n.type;for(const c of Array.isArray(a)?a:[a]){if(typeof c!="string")return;r.includes(c)||r.push(c)}}delete t.anyOf,t.type=r.length===1?r[0]:r}const O1e=new Set(["type","properties","required","additionalProperties"]),Qoe=["oneOf","anyOf"];function Joe(t){const e=t.additionalProperties;return e===void 0||e===!1||typeof e!="object"||e===null?null:Object.keys(e).length?e:null}function VG(t){var a;const e=[];for(const c of t){if(typeof c!="object"||c.type!=="object")return null;for(const d in c)if(!O1e.has(d))return null;e.push(c)}const r={},n=new Set;for(const c of e){for(const d in c.properties){if(Object.prototype.hasOwnProperty.call(r,d))continue;const p=[];for(const g of e){const v=((a=g.properties)==null?void 0:a[d])??Joe(g);v!=null&&(p.some(E=>JSON.stringify(E)===JSON.stringify(v))||p.push(v))}const l=p.length===1?p[0]:VG(p)??{allOf:p};Vv(r,d,l)}for(const d of c.required??[])n.add(d)}const i={type:"object",properties:r};if(n.size&&(i.required=[...n]),e.every(c=>c.additionalProperties===!1))i.additionalProperties=!1;else{const c=[];for(const d of e){const p=Joe(d);p&&!c.some(l=>JSON.stringify(l)===JSON.stringify(p))&&c.push(p)}c.length===1?i.additionalProperties=c[0]:c.length>1&&(i.additionalProperties={allOf:c})}return i}function jYe(t){const e=t.allOf;if(!Array.isArray(e)||e.length<2)return;for(const i of O1e)if(i in t)return;const r=e.filter(i=>Qoe.some(a=>Array.isArray(i[a])));let n=null;if(!r.length)n=VG(e);else{const i=r[0],a=Qoe.find(p=>Array.isArray(i[p]));if(Object.keys(i).length!==1)return;const c=e.filter(p=>p!==i),d=i[a].map(p=>VG([...c,p]));if(d.some(p=>!p))return;n={[a]:d}}n&&(delete t.allOf,lj(t,n))}function F1e(t,e){var d,p,l,g;const r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=v=>{const E=t.seen.get(v);if(E.ref===null)return;const T=E.def??E.schema,j={...T},P=E.ref;if(E.ref=null,P){n(P);const L=t.seen.get(P),O=L.schema;if(O.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(T.allOf=T.allOf??[],T.allOf.push(O)):lj(T,O),lj(T,j),v._zod.parent===P)for(const $ in T)$==="$ref"||$==="allOf"||$ in j||delete T[$];if(O.$ref&&L.def)for(const $ in T)$==="$ref"||$==="allOf"||$ in L.def&&JSON.stringify(T[$])===JSON.stringify(L.def[$])&&delete T[$]}const C=v._zod.parent;if(C&&C!==P){n(C);const L=t.seen.get(C);if(L!=null&&L.schema.$ref&&(T.$ref=L.schema.$ref,L.def))for(const O in T)O==="$ref"||O==="allOf"||O in L.def&&JSON.stringify(T[O])===JSON.stringify(L.def[O])&&delete T[O]}t.override({zodSchema:v,jsonSchema:T,path:E.path??[]})};if(!t.external||t.sharedEmitDoneFor!==t.external){for(const v of[...t.seen.entries()].reverse())n(v[0]);if(t.target!=="openapi-3.0")for(const v of t.seen.entries())M1e(v[1].def??v[1].schema);for(const v of t.deferred)v();if(t.intersections.length){const v=new Map;for(const E of t.seen.values())for(const T of[E.schema,E.def]){const j=T==null?void 0:T.allOf;if(!Array.isArray(j))continue;const P=v.get(j);P?P.push(T):v.set(j,[T])}for(const E of t.intersections)for(const T of v.get(E)??[])jYe(T)}}const i={};if(t.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":t.target,(d=t.external)!=null&&d.uri){const v=(p=t.external.registry.get(e))==null?void 0:p.id;if(!v)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(v)}lj(i,r.defId?r.schema:r.def??r.schema);const a=(l=t.metadataRegistry.get(e))==null?void 0:l.id;a!==void 0&&i.id===a&&delete i.id;const c=((g=t.external)==null?void 0:g.defs)??{};if(!t.external||t.sharedEmitDoneFor!==t.external)for(const v of t.seen.entries()){const E=v[1];E.def&&E.defId&&(E.def.id===E.defId&&delete E.def.id,Vv(c,E.defId,E.def))}t.external&&(t.sharedEmitDoneFor=t.external),t.external||Object.keys(c).length>0&&(t.target==="draft-2020-12"?i.$defs=c:i.definitions=c);try{const v=JSON.parse(JSON.stringify(i));return Object.defineProperty(v,"~standard",{value:{...e["~standard"],jsonSchema:{input:SF(e,"input",t.processors),output:SF(e,"output",t.processors)}},enumerable:!1,writable:!1}),v}catch{throw new Error("Error converting schema to JSON.")}}function Sd(t,e){const r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);const n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Sd(n.element,r);if(n.type==="set")return Sd(n.valueType,r);if(n.type==="lazy")return Sd(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return Sd(n.innerType,r);if(n.type==="intersection")return Sd(n.left,r)||Sd(n.right,r);if(n.type==="record"||n.type==="map")return Sd(n.keyType,r)||Sd(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Sd(n.in,r)||Sd(n.out,r);if(n.type==="object"){for(const i in n.shape)if(Sd(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(const i of n.options)if(Sd(i,r))return!0;return!1}if(n.type==="tuple"){for(const i of n.items)if(Sd(i,r))return!0;return!!(n.rest&&Sd(n.rest,r))}return!1}const CYe=(t,e={})=>r=>{const n=L1e({...r,processors:e});return hc(t,n),D1e(n,t),F1e(n,t)},SF=(t,e,r={})=>n=>{const{libraryOptions:i,target:a}=n??{},c=L1e({...i??{},target:a,io:e,processors:r});return hc(t,c),D1e(c,t),F1e(c,t)},uT=(t,e,r)=>{(t[e]===void 0||r>t[e])&&(t[e]=r)},dT=(t,e,r)=>{(t[e]===void 0||r{uT(t,"minimum",e),dT(t,"maximum",e)},B1e=(t,e)=>{t.multipleOf??(t.multipleOf=[]),t.multipleOf.includes(e)||t.multipleOf.push(e)},z1e=(t,e)=>{t.patterns??(t.patterns=new Set),t.patterns.add(e)},$1e=(t,e)=>{t.mime=t.mime?t.mime.filter(r=>e.includes(r)):[...e]},U1e=(t,e)=>{t.format=e,e.includes("int")&&(t.isInt=!0)},tle=(t,e)=>uT(t,"minimum",e.minimum),rle=(t,e)=>dT(t,"maximum",e.maximum),nle=t=>(e,r)=>{U1e(e,r.format);const[n,i]=t[r.format];uT(e,"minimum",n),dT(e,"maximum",i)},SU={greater_than:(t,e)=>uT(t,e.inclusive?"minimum":"exclusiveMinimum",e.value),less_than:(t,e)=>dT(t,e.inclusive?"maximum":"exclusiveMaximum",e.value),multiple_of:(t,e)=>B1e(t,e.value),number_format:nle(c1e),bigint_format:nle(K7e),min_length:tle,max_length:rle,length_equals:(t,e)=>ele(t,e.length),min_size:tle,max_size:rle,size_equals:(t,e)=>ele(t,e.size),string_format:(t,e)=>{U1e(t,e.format),e.pattern&&z1e(t,e.pattern),(e.format==="base64"||e.format==="base64url")&&(t.contentEncoding=e.format),(e.local||e.precision===-1)&&(t.laxFormat=!0)},mime_type:(t,e)=>$1e(t,e.mime)};function Km(t){var a;const e={},r=t._zod.def,n=t._zod.traits.has("$ZodCheck")?[t,...r.checks??[]]:r.checks??[];for(const c of n)(a=SU[c._zod.def.check])==null||a.call(SU,e,c._zod.def);const i=t._zod.bag;i.minimum!==void 0&&uT(e,"minimum",i.minimum),i.exclusiveMinimum!==void 0&&uT(e,"exclusiveMinimum",i.exclusiveMinimum),i.maximum!==void 0&&dT(e,"maximum",i.maximum),i.exclusiveMaximum!==void 0&&dT(e,"exclusiveMaximum",i.exclusiveMaximum),i.multipleOf!==void 0&&B1e(e,i.multipleOf),i.format!==void 0&&(e.format??(e.format=i.format),i.format.includes("int")&&(e.isInt=!0)),i.mime&&$1e(e,i.mime);for(const c of i.patterns??[])z1e(e,c);return e}const PYe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},NYe=new Map([[E1e,YHe],[wY,ZHe]]),V1e=t=>NYe.get(t)??t,RYe=(t,e,r,n)=>{const i=r;i.type="string";const{minimum:a,maximum:c,format:d,patterns:p,contentEncoding:l,laxFormat:g}=Km(t);if(typeof a=="number"&&(i.minLength=a),typeof c=="number"&&(i.maxLength=c),d&&(i.format=PYe[d]??d,i.format===""&&delete i.format,(d==="time"||g)&&delete i.format),l&&(i.contentEncoding=l),p&&p.size>0){const v=[...p].map(V1e);v.length===1?i.pattern=v[0].source:v.length>1&&(i.allOf=[...v.map(E=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:E.source}))])}},LYe=(t,e,r,n)=>{const i=r,{minimum:a,maximum:c,multipleOf:d,exclusiveMaximum:p,exclusiveMinimum:l,isInt:g}=Km(t);i.type=g?"integer":"number";const v=typeof l=="number"&&l>=(a??Number.NEGATIVE_INFINITY),E=typeof p=="number"&&p<=(c??Number.POSITIVE_INFINITY),T=e.target==="draft-04"||e.target==="openapi-3.0";if(v?T?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a=="number"&&(i.minimum=a),E?T?(i.maximum=p,i.exclusiveMaximum=!0):i.exclusiveMaximum=p:typeof c=="number"&&(i.maximum=c),d){const j=new Set;for(const L of d)Number.isFinite(L)&&L!==0?j.add(Math.abs(L)):Sv(t,e,i,n,`A multipleOf divisor of ${L} cannot be represented in JSON Schema`);const[P,...C]=j;P!==void 0&&(i.multipleOf=P),C.length&&(i.allOf=[...i.allOf??[],...C.map(L=>({multipleOf:L}))])}},DYe=(t,e,r,n)=>{r.type="boolean"},MYe=(t,e,r,n)=>{r.not={}},OYe=(t,e,r,n)=>{},FYe=(t,e,r,n)=>{const i=t._zod.def,a=OG(i.entries);if(a.length===0){r.not={};return}a.every(c=>typeof c=="number")&&(r.type="number"),a.every(c=>typeof c=="string")&&(r.type="string"),r.enum=a},BYe=(t,e,r,n)=>{const i=t._zod.def;if(i.values.length===0){r.not={};return}const a=[];for(const c of i.values)if(c===void 0){if(Sv(t,e,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof c=="bigint"){if(Sv(t,e,r,n,"BigInt literals cannot be represented in JSON Schema"))return;a.push(Number(c))}else a.push(c);if(a.length!==0)if(a.length===1){const c=a[0];r.type=c===null?"null":typeof c,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[c]:r.const=c}else a.every(c=>typeof c=="number")&&(r.type="number"),a.every(c=>typeof c=="string")&&(r.type="string"),a.every(c=>typeof c=="boolean")&&(r.type="boolean"),a.every(c=>c===null)&&(r.type="null"),r.enum=a},zYe=(t,e,r,n)=>{Sv(t,e,r,n,"Custom types cannot be represented in JSON Schema")},$Ye=(t,e,r,n)=>{Sv(t,e,r,n,"Transforms cannot be represented in JSON Schema")},UYe=(t,e,r,n)=>{const i=r,a=t._zod.def,{minimum:c,maximum:d}=Km(t);typeof c=="number"&&(i.minItems=c),typeof d=="number"&&(i.maxItems=d),i.type="array",i.items=hc(a.element,e,{...n,path:[...n.path,"items"]})};function EF(t){const e=t._zod.def;return e.type==="pipe"&&e.in._zod.traits.has("$ZodTransform")?EF(e.out):e.type==="catch"?EF(e.innerType):t._zod.optin}const VYe=(t,e,r,n)=>{var l;const i=r,a=t._zod.def,c=a.shape;if(Object.getOwnPropertySymbols(c).length&&Sv(t,e,i,n,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(const g in c)Vv(i.properties,g,hc(c[g],e,{...n,path:[...n.path,"properties",g]}));const p=[];for(const g of Object.keys(c)){const v=a.shape[g];(e.io==="input"?EF(v)===void 0:v._zod.optout===void 0)&&p.push(g)}p.length>0&&(i.required=p),((l=a.catchall)==null?void 0:l._zod.def.type)==="never"?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=hc(a.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},qYe=(t,e,r,n)=>{const i=t._zod.def,a=i.inclusive===!1,c=i.options.map((d,p)=>hc(d,e,{...n,path:[...n.path,a?"oneOf":"anyOf",p]}));a?r.oneOf=c:r.anyOf=c},GYe=(t,e,r,n)=>{const i=t._zod.def,a=hc(i.left,e,{...n,path:[...n.path,"allOf",0]}),c=hc(i.right,e,{...n,path:[...n.path,"allOf",1]}),d=l=>"allOf"in l&&Object.keys(l).length===1,p=[...d(a)?a.allOf:[a],...d(c)?c.allOf:[c]];r.allOf=p,e.intersections.push(p)};function qG(t,e,r){var j;if(e.$ref){if(r.has(e))return e;r.add(e);const P=(j=t.get(e))==null?void 0:j.def;if(!P)return e;const C=qG(t,P,r);return C===P?e:C}for(const P of["anyOf","oneOf"]){const C=e[P];if(!Array.isArray(C))continue;const L=C.map(O=>qG(t,O,r));L.some((O,F)=>O!==C[F])&&(e={...e,[P]:L})}const n=Array.isArray(e.type)?e.type:[e.type],i=!n.includes("string")&&n.some(P=>P==="number"||P==="integer"),a=e.enum??(e.const!==void 0?[e.const]:void 0);if(!i&&!(a!=null&&a.some(P=>typeof P=="number")))return e;const{minimum:c,maximum:d,exclusiveMinimum:p,exclusiveMaximum:l,multipleOf:g,format:v,id:E,...T}=e;return T.enum?T.enum=T.enum.map(P=>typeof P=="number"?String(P):P):typeof T.const=="number"&&(T.const=String(T.const)),i&&(T.type="string",a||(T.pattern=(n.includes("number")?_Y:iWe).source)),T}const GG=new WeakMap;function HYe(t){var n;const e=new Map;for(const i of t.seen.values())i.def&&!e.has(i.schema)&&e.set(i.schema,i);const r=new Map;for(const i of GG.get(t)??[]){const a=t.seen.get(i),c=(n=(a==null?void 0:a.def)??(a==null?void 0:a.schema))==null?void 0:n.propertyNames;if(!c||c===!0||r.has(c))continue;const d=qG(e,c,new Set);d!==c&&r.set(c,d)}if(r.size)for(const i of t.seen.values())for(const a of[i.schema,i.def]){const c=a&&r.get(a.propertyNames);c&&(a.propertyNames=c)}}const WYe=(t,e,r,n)=>{const i=r,a=t._zod.def;i.type="object";const c=a.keyType,d=Km(c).patterns;if(a.mode==="loose"&&d&&d.size>0){const g=hc(a.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(const v of d)Vv(i.patternProperties,V1e(v).source,g)}else{if(e.target==="draft-07"||e.target==="draft-2020-12"){i.propertyNames=hc(a.keyType,e,{...n,path:[...n.path,"propertyNames"]});let g=GG.get(e);g||(g=[],GG.set(e,g),e.deferred.push(()=>HYe(e))),g.push(t)}i.additionalProperties=hc(a.valueType,e,{...n,path:[...n.path,"additionalProperties"]})}const p=c._zod.values,l=e.io==="input"&&EF(a.valueType)!==void 0;if(p&&!a.partial&&!l){const g=[...p].filter(v=>typeof v=="string"||typeof v=="number");g.length>0&&(i.required=g.map(String))}},KYe=(t,e,r,n)=>{const i=t._zod.def,a=hc(i.innerType,e,n),c=e.seen.get(t);e.target==="openapi-3.0"?(c.ref=i.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}]},YYe=(t,e,r,n)=>{const i=t._zod.def;hc(i.innerType,e,n);const a=e.seen.get(t);a.ref=i.innerType},SY=Symbol();function q1e(t,e,r,n,i){let a=!1;const c=JSON.stringify(t,(d,p)=>typeof p!="bigint"?p:(a=!0,null));return a?(Sv(e,r,n,i,"BigInt defaults cannot be represented in JSON Schema"),SY):JSON.parse(c)}const ZYe=(t,e,r,n)=>{const i=t._zod.def;hc(i.innerType,e,n);const a=e.seen.get(t);a.ref=i.innerType;const c=q1e(i.defaultValue,t,e,r,n);c!==SY&&(r.default=c)},XYe=(t,e,r,n)=>{const i=t._zod.def;hc(i.innerType,e,n);const a=e.seen.get(t);if(a.ref=i.innerType,e.io!=="input")return;const c=q1e(i.defaultValue,t,e,r,n);c!==SY&&(r._prefault=c)},QYe=(t,e,r,n)=>{const i=t._zod.def;hc(i.innerType,e,n);const a=e.seen.get(t);a.ref=i.innerType;let c;try{c=i.catchValue(void 0)}catch{Sv(t,e,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=c},JYe=(t,e,r,n)=>{const i=t._zod.def,a=i.in._zod.traits.has("$ZodTransform"),c=e.io==="input"?a?i.out:i.in:i.out;hc(c,e,n);const d=e.seen.get(t);d.ref=c},eZe=(t,e,r,n)=>{const i=t._zod.def;hc(i.innerType,e,n);const a=e.seen.get(t);a.ref=i.innerType,r.readOnly=!0},G1e=(t,e,r,n)=>{const i=t._zod.def;hc(i.innerType,e,n);const a=e.seen.get(t);a.ref=i.innerType},ile=new WeakSet([Object.prototype,Error.prototype]);function kD(t,e,r){Object.defineProperty(t,e,{configurable:!0,enumerable:!1,get(){const n=r(this);return Object.defineProperty(this,e,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,e,{value:n,configurable:!0,writable:!0})}})}const H1e=(t,e)=>{gHe.init(t,e),t.name="ZodError";const r=Object.getPrototypeOf(t);ile.has(r)||(ile.add(r),kD(r,"format",n=>i=>_He(n,i)),kD(r,"flatten",n=>i=>xHe(n,i)),kD(r,"addIssue",n=>i=>{n.issues.push(i),n.message=JSON.stringify(n.issues,FG,2)}),kD(r,"addIssues",n=>i=>{n.issues.push(...i),n.message=JSON.stringify(n.issues,FG,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},tZe=Mr("ZodError",H1e),Xf=Mr("ZodError",H1e,void 0,{Parent:Error}),rZe=pY(Xf),nZe=gY(Xf),iZe=yY(Xf),sZe=xY(Xf),aZe=THe(Xf),oZe=AHe(Xf),lZe=kHe(Xf),cZe=IHe(Xf),uZe=jHe(Xf),dZe=CHe(Xf),hZe=PHe(Xf),fZe=NHe(Xf);function mZe(){ap.localeError||mg(RKe())}function p5(){ap.memoizer||mg({memoizer:CKe()})}const xl=Mr("ZodType",(t,e)=>(mZe(),yl.init(t,e),t.def=e,t.type=e.type,t),{check(...t){const e=this.def;return this.clone(qh(e,{checks:[...e.checks??[],...t.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...t){return this.check(...t)},clone(t,e){return qv(this,t,e)},brand(){return this},register(t,e){return t.add(this,e),this},refine(t,e){return this.check(mXe(t,e))},superRefine(t,e){return this.check(pXe(t,e))},overwrite(t){return this.check(wA(t))},optional(){return ole(this)},exactOptional(){return tXe(this)},nullable(){return lle(this)},nullish(){return ole(lle(this))},nonoptional(t){return oXe(this,t)},array(){return GZe(this)},or(t){return KZe([this,t])},and(t){return ZZe(this,t)},transform(t){return cle(this,eXe(t))},default(t){return iXe(this,t)},prefault(t){return aXe(this,t)},catch(t){return cXe(this,t)},pipe(t){return cle(this,t)},readonly(){return hXe(this)},describe(t){const e=this.clone();return BI.add(e,{description:t}),e},meta(...t){if(t.length===0)return BI.get(this);const e=this.clone();return BI.add(e,t[0]),e},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(t,...e){return e.length===0?t(this):t(this,...e)},get"~standard"(){return d1e(this,"~standard",{..._1e(this),jsonSchema:{input:SF(this,"input"),output:SF(this,"output")}})},set"~standard"(t){wv(this,"~standard",t)},parse:function t(e,r){return rZe(this,e,r,{callee:t})},parseAsync:async function t(e,r){return await nZe(this,e,r,{callee:t})},safeParse(t,e){return iZe(this,t,e)},async safeParseAsync(t,e){return sZe(this,t,e)},get spa(){return this==null?void 0:this.safeParseAsync},set spa(t){wv(this,"spa",t)},validate(t,e){return wHe(this,t,e)},validateAsync(t,e){return EHe(this,t,e)},encode:function t(e,r){return aZe(this,e,r,{callee:t})},decode:function t(e,r){return oZe(this,e,r,{callee:t})},encodeAsync:async function t(e,r){return await lZe(this,e,r,{callee:t})},decodeAsync:async function t(e,r){return await cZe(this,e,r,{callee:t})},safeEncode(t,e){return uZe(this,t,e)},safeDecode(t,e){return dZe(this,t,e)},async safeEncodeAsync(t,e){return hZe(this,t,e)},async safeDecodeAsync(t,e){return fZe(this,t,e)},toJSONSchema(t){return CYe(this,{})(t)},get description(){var t;return(t=BI.get(this))==null?void 0:t.description},get _def(){return this._zod.def}}),W1e=Mr("_ZodString",(t,e)=>{bY.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>RYe(t,r,n)},h1e({format:t=>Km(t).format??null,minLength:t=>Km(t).minimum??null,maxLength:t=>Km(t).maximum??null},{regex(...t){return this.check(mYe(...t))},includes(...t){return this.check(yYe(...t))},startsWith(...t){return this.check(xYe(...t))},endsWith(...t){return this.check(_Ye(...t))},min(...t){return this.check(wF(...t))},max(...t){return this.check(N1e(...t))},length(...t){return this.check(R1e(...t))},nonempty(...t){return this.check(wF(1,...t))},lowercase(t){return this.check(pYe(t))},uppercase(t){return this.check(gYe(t))},trim(){return this.check(bYe())},normalize(...t){return this.check(vYe(...t))},toLowerCase(){return this.check(wYe())},toUpperCase(){return this.check(SYe())},slugify(){return this.check(EYe())}})),pZe=Mr("ZodString",(t,e)=>{bY.init(t,e),W1e.init(t,e)},{email(t){return this.check(OKe(vZe,t))},url(t){return this.check(VKe(wZe,t))},jwt(t){return this.check(iYe(OZe,t))},emoji(t){return this.check(qKe(SZe,t))},guid(t){return this.check(FKe(bZe,t))},uuid(t){return this.check(BKe(ID,t))},uuidv4(t){return this.check(zKe(ID,t))},uuidv6(t){return this.check($Ke(ID,t))},uuidv7(t){return this.check(UKe(ID,t))},nanoid(t){return this.check(GKe(EZe,t))},cuid(t){return this.check(HKe(TZe,t))},cuid2(t){return this.check(WKe(AZe,t))},ulid(t){return this.check(KKe(kZe,t))},base64(t){return this.check(tYe(LZe,t))},base64url(t){return this.check(rYe(DZe,t))},xid(t){return this.check(YKe(IZe,t))},ksuid(t){return this.check(ZKe(jZe,t))},ipv4(t){return this.check(XKe(CZe,t))},ipv6(t){return this.check(QKe(PZe,t))},cidrv4(t){return this.check(JKe(NZe,t))},cidrv6(t){return this.check(eYe(RZe,t))},e164(t){return this.check(nYe(MZe,t))},datetime(t){return this.check(sYe(gZe,t))},date(t){return this.check(aYe(yZe,t))},time(t){return this.check(oYe(xZe,t))},duration(t){return this.check(lYe(_Ze,t))}});function Us(t){return MKe(pZe,t)}const _l=Mr("ZodStringFormat",(t,e)=>{el.init(t,e),W1e.init(t,e)}),gZe=Mr("ZodISODateTime",(t,e)=>{BWe.init(t,e),_l.init(t,e)}),yZe=Mr("ZodISODate",(t,e)=>{zWe.init(t,e),_l.init(t,e)}),xZe=Mr("ZodISOTime",(t,e)=>{$We.init(t,e),_l.init(t,e)}),_Ze=Mr("ZodISODuration",(t,e)=>{UWe.init(t,e),_l.init(t,e)}),vZe=Mr("ZodEmail",(t,e)=>{TWe.init(t,e),_l.init(t,e)}),bZe=Mr("ZodGUID",(t,e)=>{SWe.init(t,e),_l.init(t,e)}),ID=Mr("ZodUUID",(t,e)=>{EWe.init(t,e),_l.init(t,e)}),wZe=Mr("ZodURL",(t,e)=>{PWe.init(t,e),_l.init(t,e)}),SZe=Mr("ZodEmoji",(t,e)=>{NWe.init(t,e),_l.init(t,e)}),EZe=Mr("ZodNanoID",(t,e)=>{RWe.init(t,e),_l.init(t,e)}),TZe=Mr("ZodCUID",(t,e)=>{LWe.init(t,e),_l.init(t,e)}),AZe=Mr("ZodCUID2",(t,e)=>{DWe.init(t,e),_l.init(t,e)}),kZe=Mr("ZodULID",(t,e)=>{MWe.init(t,e),_l.init(t,e)}),IZe=Mr("ZodXID",(t,e)=>{OWe.init(t,e),_l.init(t,e)}),jZe=Mr("ZodKSUID",(t,e)=>{FWe.init(t,e),_l.init(t,e)}),CZe=Mr("ZodIPv4",(t,e)=>{VWe.init(t,e),_l.init(t,e)}),PZe=Mr("ZodIPv6",(t,e)=>{GWe.init(t,e),_l.init(t,e)}),NZe=Mr("ZodCIDRv4",(t,e)=>{HWe.init(t,e),_l.init(t,e)}),RZe=Mr("ZodCIDRv6",(t,e)=>{KWe.init(t,e),_l.init(t,e)}),LZe=Mr("ZodBase64",(t,e)=>{YWe.init(t,e),_l.init(t,e)}),DZe=Mr("ZodBase64URL",(t,e)=>{XWe.init(t,e),_l.init(t,e)}),MZe=Mr("ZodE164",(t,e)=>{QWe.init(t,e),_l.init(t,e)}),OZe=Mr("ZodJWT",(t,e)=>{eKe.init(t,e),_l.init(t,e)}),K1e=Mr("ZodNumber",(t,e)=>{T1e.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>LYe(t,r,n,i),t.isFinite=!0},h1e({minValue:t=>{const{minimum:e,exclusiveMinimum:r}=Km(t);return Math.max(e??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:t=>{const{maximum:e,exclusiveMaximum:r}=Km(t);return Math.min(e??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:t=>{const{isInt:e,multipleOf:r}=Km(t);return!!e||!!(r!=null&&r.some(Number.isSafeInteger))},format:t=>Km(t).format??null},{gt(t,e){return this.check(Yoe(t,e))},gte(t,e){return this.check(wU(t,e))},min(t,e){return this.check(wU(t,e))},lt(t,e){return this.check(Koe(t,e))},lte(t,e){return this.check(bU(t,e))},max(t,e){return this.check(bU(t,e))},int(t){return this.check(sle(t))},safe(t){return this.check(sle(t))},positive(t){return this.check(Yoe(0,t))},nonnegative(t){return this.check(wU(0,t))},negative(t){return this.check(Koe(0,t))},nonpositive(t){return this.check(bU(0,t))},multipleOf(t,e){return this.check(Zoe(t,e))},step(t,e){return this.check(Zoe(t,e))},finite(){return this}}));function cj(t){return cYe(K1e,t)}const FZe=Mr("ZodNumberFormat",(t,e)=>{tKe.init(t,e),K1e.init(t,e)});function sle(t){return uYe(FZe,t)}const BZe=Mr("ZodBoolean",(t,e)=>{rKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>DYe(t,r,n)});function zZe(t){return dYe(BZe,t)}const $Ze=Mr("ZodUnknown",(t,e)=>{nKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>OYe()});function HG(){return hYe($Ze)}const UZe=Mr("ZodNever",(t,e)=>{iKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>MYe(t,r,n)});function VZe(t){return fYe(UZe,t)}const qZe=Mr("ZodArray",(t,e)=>{p5(),oKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>UYe(t,r,n,i),t.element=e.element},{min(t,e){return this.check(wF(t,e))},nonempty(t){return this.check(wF(1,t))},max(t,e){return this.check(N1e(t,e))},length(t,e){return this.check(R1e(t,e))},unwrap(){return this.element}});function GZe(t,e){return TYe(qZe,t,e)}const HZe=Mr("ZodObject",(t,e)=>{p5(),uKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>VYe(t,r,n,i),lHe(t,"shape",r=>r._zod.def.shape,!1)},{keyof(){return g5(Object.keys(this._zod.def.shape))},catchall(t){return this.clone(qh(this._zod.def,{catchall:t}))},passthrough(){return this.clone(qh(this._zod.def,{catchall:HG()}))},loose(){return this.clone(qh(this._zod.def,{catchall:HG()}))},strict(){return this.clone(qh(this._zod.def,{catchall:VZe()}))},strip(){return this.clone(qh(this._zod.def,{catchall:void 0}))},extend(t){return X7e(this,t)},safeExtend(t){return Q7e(this,t)},merge(t){return J7e(this,t)},pick(t){return Y7e(this,t)},omit(t){return Z7e(this,t)},partial(...t){return Coe(Y1e,this,t[0])},exactPartial(...t){return Coe(Z1e,this,t[0],"exactPartial")},required(...t){return eHe(X1e,this,t[0])}});function Gv(t,e){const r={type:"object",shape:t??{},...fi(e)};return new HZe(r)}const WZe=Mr("ZodUnion",(t,e)=>{dKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>qYe(t,r,n,i),t.options=e.options});function KZe(t,e){return new WZe({type:"union",options:t,...fi(e)})}const YZe=Mr("ZodIntersection",(t,e)=>{hKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>GYe(t,r,n,i)});function ZZe(t,e){return new YZe({type:"intersection",left:t,right:e})}const ale=Mr("ZodRecord",(t,e)=>{p5(),fKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>WYe(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function XZe(t,e,r){return!e||!e._zod?new ale({type:"record",keyType:Us(),valueType:t,...fi(e)}):new ale({type:"record",keyType:t,valueType:e,...fi(r)})}const WG=Mr("ZodEnum",(t,e)=>{mKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(n,i,a)=>FYe(t,n,i),t.enum=e.entries,t.options=[...t._zod.values];const r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{const a={};for(const c of n)if(r.has(c))a[c]=e.entries[c];else throw new Error(`Key ${c} not found in enum`);return new WG({...e,checks:[],...fi(i),entries:a})},t.exclude=(n,i)=>{const a={...e.entries};for(const c of n)if(r.has(c))delete a[c];else throw new Error(`Key ${c} not found in enum`);return new WG({...e,checks:[],...fi(i),entries:a})}});function g5(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new WG({type:"enum",entries:r,...fi(e)})}const QZe=Mr("ZodLiteral",(t,e)=>{pKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>BYe(t,r,n,i),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function TF(t,e){return new QZe({type:"literal",values:Array.isArray(t)?t:[t],...fi(e)})}const JZe=Mr("ZodTransform",(t,e)=>{p5(),gKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>$Ye(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new f1e(t.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(oC(a,r.value,e));else{const c=a;c.fatal&&(c.continue=!1),c.code??(c.code="custom"),"input"in c||(c.input=r.value),c.inst??(c.inst=t),r.issues.push(oC(c))}};const i=e.transform(r.value,r);return i instanceof Promise?i.then(a=>(r.value=a,r)):(r.value=i,r)}});function eXe(t){return new JZe({type:"transform",transform:t})}const Y1e=Mr("ZodOptional",(t,e)=>{I1e.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>G1e(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function ole(t){return new Y1e({type:"optional",innerType:t})}const Z1e=Mr("ZodExactOptional",(t,e)=>{yKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>G1e(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function tXe(t){return new Z1e({type:"optional",innerType:t})}const rXe=Mr("ZodNullable",(t,e)=>{xKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>KYe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function lle(t){return new rXe({type:"nullable",innerType:t})}const nXe=Mr("ZodDefault",(t,e)=>{_Ke.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>ZYe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function iXe(t,e){return new nXe({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():o1e(e)}})}const sXe=Mr("ZodPrefault",(t,e)=>{vKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>XYe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function aXe(t,e){return new sXe({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():o1e(e)}})}const X1e=Mr("ZodNonOptional",(t,e)=>{bKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>YYe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function oXe(t,e){return new X1e({type:"nonoptional",innerType:t,...fi(e)})}const lXe=Mr("ZodCatch",(t,e)=>{wKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>QYe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function cXe(t,e){return new lXe({type:"catch",innerType:t,catchValue:typeof e=="function"?e:uHe(e)})}const uXe=Mr("ZodPipe",(t,e)=>{SKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>JYe(t,r,n,i),t.in=e.in,t.out=e.out});function cle(t,e){return new uXe({type:"pipe",in:t,out:e})}const dXe=Mr("ZodReadonly",(t,e)=>{EKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>eZe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function hXe(t){return new dXe({type:"readonly",innerType:t})}const fXe=Mr("ZodCustom",(t,e)=>{TKe.init(t,e),xl.init(t,e),t._zod.processJSONSchema=(r,n,i)=>zYe(t,r,n,i)});function mXe(t,e={}){return AYe(fXe,t,e)}function pXe(t,e){return kYe(t,e)}var gXe=Object.defineProperty,yXe=(t,e)=>gXe(t,"name",{value:e,configurable:!0}),Q1e=N.forwardRef(yXe(function(e,r){return s.jsx(An.label,{...e,ref:r,onMouseDown:n=>{var a;n.target.closest("button, input, select, textarea")||((a=e.onMouseDown)==null||a.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}})},"Label"));const xXe=eA("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),sn=N.forwardRef(({className:t,...e},r)=>s.jsx(Q1e,{ref:r,className:hr(xXe(),t),...e}));sn.displayName=Q1e.displayName;const EY=D7e,J1e=N.createContext({}),Cc=({...t})=>s.jsx(J1e.Provider,{value:{name:t.name},children:s.jsx(x7e,{...t})}),y5=()=>{const t=N.useContext(J1e),e=N.useContext(eSe),{getFieldState:r,formState:n}=L7e(),i=r(t.name,n);if(!t)throw new Error("useFormField should be used within ");const{id:a}=e;return{id:a,name:t.name,formItemId:`${a}-form-item`,formDescriptionId:`${a}-form-item-description`,formMessageId:`${a}-form-item-message`,...i}},eSe=N.createContext({}),sc=N.forwardRef(({className:t,...e},r)=>{const n=N.useId();return s.jsx(eSe.Provider,{value:{id:n},children:s.jsx("div",{ref:r,className:hr("space-y-2",t),...e})})});sc.displayName="FormItem";const ac=N.forwardRef(({className:t,...e},r)=>{const{error:n,formItemId:i}=y5();return s.jsx(sn,{ref:r,className:hr(n&&"text-destructive",t),htmlFor:i,...e})});ac.displayName="FormLabel";const oc=N.forwardRef(({...t},e)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:a}=y5();return s.jsx(m_e,{ref:e,id:n,"aria-describedby":r?`${i} ${a}`:`${i}`,"aria-invalid":!!r,...t})});oc.displayName="FormControl";const rO=N.forwardRef(({className:t,...e},r)=>{const{formDescriptionId:n}=y5();return s.jsx("p",{ref:r,id:n,className:hr("text-sm text-muted-foreground",t),...e})});rO.displayName="FormDescription";const Ym=N.forwardRef(({className:t,children:e,...r},n)=>{const{error:i,formMessageId:a}=y5(),c=i?String(i==null?void 0:i.message):e;return c?s.jsx("p",{ref:n,id:a,className:hr("text-sm font-medium text-destructive",t),...r,children:c}):null});Ym.displayName="FormMessage";const hn=N.forwardRef(({className:t,type:e,...r},n)=>s.jsx("input",{type:e,className:hr("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),ref:n,...r}));hn.displayName="Input";var _Xe=Object.defineProperty,Ds=(t,e)=>_Xe(t,"name",{value:e,configurable:!0}),ule={ItemAligned:"item-aligned",Popper:"popper"},vXe={RTL:"rtl"},bXe=[" ","Enter","ArrowUp","ArrowDown"],wXe=[" ","Enter"],hT="Select",[x5,_5,SXe]=QT(hT),[kw,gKt]=Nl(hT,[SXe,Bv]),TY=Bv(),[EXe,Hv]=kw(hT),[TXe,AXe]=kw(hT);function tSe(t){const{__scopeSelect:e,children:r,open:n,defaultOpen:i,onOpenChange:a,value:c,defaultValue:d,onValueChange:p,dir:l,name:g,autoComplete:v,disabled:E,required:T,form:j,internal_do_not_use_render:P}=t,C=TY(e),[L,O]=N.useState(null),[F,$]=N.useState(null),[G,W]=N.useState(!1),Z=Uv(l),[Q,ee]=ph({prop:n,defaultProp:i??!1,onChange:a,caller:hT}),[ie,oe]=ph({prop:c,defaultProp:d,onChange:p,caller:hT}),pe=N.useRef(null),Le=N.useRef(!1),[be,Re]=N.useState(null),Ie=Ds(tt=>{Re({value:tt,hasConsumerStoppedPropagation:Le.current}),oe(tt)},"handleUserSelect"),Te=N.useRef(ie);N.useEffect(()=>{const tt=j?L==null?void 0:L.ownerDocument.getElementById(j):L==null?void 0:L.form;if(tt instanceof HTMLFormElement){const vt=Ds(()=>oe(Te.current),"reset");return tt.addEventListener("reset",vt),()=>tt.removeEventListener("reset",vt)}},[j,L,oe]);const ge=L?!!j||!!L.closest("form"):!0,[$e,we]=N.useState(new Set),ke=Wl(),Ae=Array.from($e).map(tt=>tt.props.value).join(";"),He=N.useCallback(tt=>{we(vt=>new Set(vt).add(tt))},[]),ot=N.useCallback(tt=>{we(vt=>{const Vt=new Set(vt);return Vt.delete(tt),Vt})},[]),nt={required:T,trigger:L,onTriggerChange:O,valueNode:F,onValueNodeChange:$,valueNodeHasChildren:G,onValueNodeHasChildrenChange:W,contentId:ke,value:ie,onValueChange:oe,hasConsumerStoppedPropagationRef:Le,userSelection:be,onUserSelect:Ie,open:Q,onOpenChange:ee,dir:Z,triggerPointerDownPosRef:pe,disabled:E,name:g,autoComplete:v,form:j,nativeOptions:$e,nativeSelectKey:Ae,isFormControl:ge};return s.jsx(V4,{...C,children:s.jsx(EXe,{scope:e,...nt,children:s.jsx(x5.Provider,{scope:e,children:s.jsx(TXe,{scope:e,onNativeOptionAdd:He,onNativeOptionRemove:ot,children:hSe(P)?P(nt):r})})})})}Ds(tSe,"SelectProvider");var kXe=Ds(t=>{const{__scopeSelect:e,children:r,...n}=t;return s.jsx(tSe,{__scopeSelect:e,...n,internal_do_not_use_render:({isFormControl:i})=>s.jsxs(s.Fragment,{children:[r,i?s.jsx(QXe,{__scopeSelect:e}):null]})})},"Select"),IXe="SelectTrigger",rSe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,disabled:i=!1,...a}=e,c=TY(n),d=Hv(IXe,n),p=d.disabled||i,l=Jn(r,d.onTriggerChange),g=_5(n),v=N.useRef("touch"),[E,T,j]=kY(C=>{const L=g().filter($=>!$.disabled),O=L.find($=>$.value===d.value),F=IY(L,C,O);F!==void 0&&d.onUserSelect(F.value)}),P=Ds(C=>{p||(d.onOpenChange(!0),j()),C&&(d.triggerPointerDownPosRef.current={x:Math.round(C.pageX),y:Math.round(C.pageY)})},"handleOpen");return s.jsx(q4,{asChild:!0,...c,children:s.jsx(An.button,{type:"button",role:"combobox","aria-controls":d.open?d.contentId:void 0,"aria-expanded":d.open,"aria-required":d.required,"aria-autocomplete":"none",dir:d.dir,"data-state":d.open?"open":"closed",disabled:p,"data-disabled":p?"":void 0,"data-placeholder":WP(d.value)?"":void 0,...a,ref:l,onClick:Qr(a.onClick,C=>{C.currentTarget.focus(),v.current!=="mouse"&&P(C)}),onPointerDown:Qr(a.onPointerDown,C=>{v.current=C.pointerType;const L=C.target;L.hasPointerCapture(C.pointerId)&&L.releasePointerCapture(C.pointerId),C.button===0&&C.ctrlKey===!1&&C.pointerType==="mouse"&&(P(C),C.preventDefault())}),onKeyDown:Qr(a.onKeyDown,C=>{const L=E.current!=="";!(C.ctrlKey||C.altKey||C.metaKey)&&C.key.length===1&&(d.hasConsumerStoppedPropagationRef.current=C.isPropagationStopped(),T(C.key)),!(L&&C.key===" ")&&bXe.includes(C.key)&&(P(),C.preventDefault())})})})},"SelectTrigger")),jXe="SelectValue",CXe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,className:i,style:a,children:c,placeholder:d="",...p}=e,l=Hv(jXe,n),{onValueNodeHasChildrenChange:g}=l,v=c!==void 0,E=Jn(r,l.onValueNodeChange);no(()=>{g(v)},[g,v]);const T=WP(l.value);return s.jsx(An.span,{...p,asChild:T?!1:p.asChild,ref:E,style:{pointerEvents:"none"},children:s.jsx(N.Fragment,{children:T?d:c},T?"placeholder":"value")})},"SelectValue")),PXe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,children:i,...a}=e;return s.jsx(An.span,{"aria-hidden":!0,...a,ref:r,children:i||"▼"})},"SelectIcon")),NXe="SelectPortal",[RXe,LXe]=kw(NXe,{forceMount:void 0}),DXe=Ds(t=>{const{__scopeSelect:e,forceMount:r,...n}=t;return s.jsx(RXe,{scope:t.__scopeSelect,forceMount:r,children:s.jsx(jP,{asChild:!0,...n})})},"SelectPortal"),dw="SelectContent",nSe=N.forwardRef(Ds(function(e,r){const n=LXe(dw,e.__scopeSelect),{forceMount:i=n.forceMount,...a}=e,c=Hv(dw,e.__scopeSelect),[d,p]=N.useState();return no(()=>{p(new DocumentFragment)},[]),s.jsx(zc,{present:i||c.open,children:({present:l})=>l?s.jsx(FXe,{...a,ref:r}):s.jsx(MXe,{...a,fragment:d})})},"SelectContent")),MXe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,children:i,fragment:a}=e;return a?vg.createPortal(s.jsx(iSe,{scope:n,children:s.jsx(x5.Slot,{scope:n,children:s.jsx("div",{ref:r,children:i})})}),a):null},"SelectContentFragment")),Nm=10,[iSe,Iw]=kw(dw),OXe=sp("SelectContent.RemoveScroll"),FXe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n}=e,{position:i=ule.ItemAligned,onCloseAutoFocus:a,onEscapeKeyDown:c,onPointerDownOutside:d,side:p,sideOffset:l,align:g,alignOffset:v,arrowPadding:E,collisionBoundary:T,collisionPadding:j,sticky:P,hideWhenDetached:C,avoidCollisions:L,...O}=e,F=Hv(dw,n),[$,G]=N.useState(null),[W,Z]=N.useState(null),Q=Jn(r,G),[ee,ie]=N.useState(null),[oe,pe]=N.useState(null),Le=_5(n),[be,Re]=N.useState(!1),Ie=N.useRef(!1),Te=N.useRef(!1),ge=N.useRef(!1);N.useEffect(()=>{if($)return L4($)},[$]),aA();const $e=N.useCallback(Bt=>{const[cr,...ft]=Le().map(Gr=>Gr.ref.current),[Kt]=ft.slice(-1),ir=document.activeElement;for(const Gr of Bt)if(Gr===ir||(Gr==null||Gr.scrollIntoView({block:"nearest"}),Gr===cr&&W&&(W.scrollTop=0),Gr===Kt&&W&&(W.scrollTop=W.scrollHeight),Gr==null||Gr.focus(),document.activeElement!==ir))return},[Le,W]),we=N.useCallback(()=>$e([ee,$]),[$e,ee,$]);N.useEffect(()=>{be&&we()},[be,we]);const{onOpenChange:ke,triggerPointerDownPosRef:Ae}=F;N.useEffect(()=>{if($){let Bt={x:0,y:0};const cr=Ds(Kt=>{var ir,Gr;Bt={x:Math.abs(Math.round(Kt.pageX)-(((ir=Ae.current)==null?void 0:ir.x)??0)),y:Math.abs(Math.round(Kt.pageY)-(((Gr=Ae.current)==null?void 0:Gr.y)??0))}},"handlePointerMove"),ft=Ds(Kt=>{Bt.x<=10&&Bt.y<=10?Kt.preventDefault():Kt.composedPath().includes($)||ke(!1),document.removeEventListener("pointermove",cr),Ae.current=null},"handlePointerUp");return Ae.current!==null&&(document.addEventListener("pointermove",cr),document.addEventListener("pointerup",ft,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",cr),document.removeEventListener("pointerup",ft,{capture:!0})}}},[$,ke,Ae]),N.useEffect(()=>{const Bt=Ds(()=>ke(!1),"close");return window.addEventListener("blur",Bt),window.addEventListener("resize",Bt),()=>{window.removeEventListener("blur",Bt),window.removeEventListener("resize",Bt)}},[ke]);const[He,ot]=kY(Bt=>{const cr=Le().filter(ir=>!ir.disabled),ft=cr.find(ir=>ir.ref.current===document.activeElement),Kt=IY(cr,Bt,ft);Kt&&setTimeout(()=>{var ir;return(ir=Kt.ref.current)==null?void 0:ir.focus()})}),nt=N.useCallback((Bt,cr,ft)=>{const Kt=!Te.current;Kt&&(Te.current=!0);const ir=!Ie.current&&!ft;F.value!==void 0&&F.value===cr||ir?(ie(Bt),ir&&(Ie.current=!0)):Kt&&ie(Bt)},[F.value]),tt=N.useCallback(()=>$==null?void 0:$.focus(),[$]),vt=N.useCallback((Bt,cr,ft)=>{if(!Bt)return;const Kt=!ge.current;Kt&&(ge.current=!0);const ir=!Ie.current&&!ft;(F.value!==void 0&&F.value===cr||ir||Kt)&&pe(Bt)},[F.value]),Vt=i===ule.Popper?dle:BXe,Ct=Vt===dle?{side:p,sideOffset:l,align:g,alignOffset:v,arrowPadding:E,collisionBoundary:T,collisionPadding:j,sticky:P,hideWhenDetached:C,avoidCollisions:L}:{};return s.jsx(iSe,{scope:n,content:$,viewport:W,onViewportChange:Z,itemRefCallback:nt,selectedItem:ee,onItemLeave:tt,itemTextRefCallback:vt,focusSelectedItem:we,selectedItemText:oe,position:i,isPositioned:be,searchRef:He,children:s.jsx(DP,{as:OXe,allowPinchZoom:!0,children:s.jsx(j4,{asChild:!0,trapped:F.open,onMountAutoFocus:Bt=>{Bt.preventDefault()},onUnmountAutoFocus:Qr(a,Bt=>{var cr;(cr=F.trigger)==null||cr.focus({preventScroll:!0}),Bt.preventDefault()}),children:s.jsx(JT,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:Bt=>Bt.preventDefault(),onDismiss:()=>F.onOpenChange(!1),children:s.jsx(Vt,{role:"listbox",id:F.contentId,"data-state":F.open?"open":"closed",dir:F.dir,onContextMenu:Bt=>Bt.preventDefault(),...O,...Ct,onPlaced:()=>Re(!0),ref:Q,style:{display:"flex",flexDirection:"column",outline:"none",...O.style},onKeyDown:Qr(O.onKeyDown,Bt=>{const cr=Bt.ctrlKey||Bt.altKey||Bt.metaKey;if(Bt.key==="Tab"&&Bt.preventDefault(),!cr&&Bt.key.length===1&&ot(Bt.key),["ArrowUp","ArrowDown","Home","End"].includes(Bt.key)){let Kt=Le().filter(ir=>!ir.disabled).map(ir=>ir.ref.current);if(["ArrowUp","End"].includes(Bt.key)&&(Kt=Kt.slice().reverse()),["ArrowUp","ArrowDown"].includes(Bt.key)){const ir=Bt.target,Gr=Kt.indexOf(ir);Kt=Kt.slice(Gr+1)}setTimeout(()=>$e(Kt)),Bt.preventDefault()}})})})})})})},"SelectContentImpl")),BXe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,onPlaced:i,...a}=e,c=Hv(dw,n),d=Iw(dw,n),[p,l]=N.useState(null),[g,v]=N.useState(null),E=Jn(r,v),T=_5(n),j=N.useRef(!1),P=N.useRef(!0),{viewport:C,selectedItem:L,selectedItemText:O,focusSelectedItem:F}=d,$=N.useCallback(()=>{if(c.trigger&&c.valueNode&&p&&g&&C&&L&&O){const Q=c.trigger.getBoundingClientRect(),ee=g.getBoundingClientRect(),ie=c.valueNode.getBoundingClientRect(),oe=O.getBoundingClientRect();if(c.dir!==vXe.RTL){const ft=oe.left-ee.left,Kt=ie.left-ft,ir=Q.left-Kt,Gr=Q.width+ir,tr=Math.max(Gr,ee.width),Qt=window.innerWidth-Nm,zt=lw(Kt,[Nm,Math.max(Nm,Qt-tr)]);p.style.minWidth=Gr+"px",p.style.left=zt+"px"}else{const ft=ee.right-oe.right,Kt=window.innerWidth-ie.right-ft,ir=window.innerWidth-Q.right-Kt,Gr=Q.width+ir,tr=Math.max(Gr,ee.width),Qt=window.innerWidth-Nm,zt=lw(Kt,[Nm,Math.max(Nm,Qt-tr)]);p.style.minWidth=Gr+"px",p.style.right=zt+"px"}const pe=T(),Le=window.innerHeight-Nm*2,be=C.scrollHeight,Re=window.getComputedStyle(g),Ie=parseInt(Re.borderTopWidth,10),Te=parseInt(Re.paddingTop,10),ge=parseInt(Re.borderBottomWidth,10),$e=parseInt(Re.paddingBottom,10),we=Ie+Te+be+$e+ge,ke=Math.min(L.offsetHeight*5,we),Ae=window.getComputedStyle(C),He=parseInt(Ae.paddingTop,10),ot=parseInt(Ae.paddingBottom,10),nt=Q.top+Q.height/2-Nm,tt=Le-nt,vt=L.offsetHeight/2,Vt=L.offsetTop+vt,Ct=Ie+Te+Vt,Bt=we-Ct;if(Ct<=nt){const ft=pe.length>0&&L===pe[pe.length-1].ref.current;p.style.bottom="0px";const Kt=g.clientHeight-C.offsetTop-C.offsetHeight,ir=Math.max(tt,vt+(ft?ot:0)+Kt+ge),Gr=Ct+ir;p.style.height=Gr+"px"}else{const ft=pe.length>0&&L===pe[0].ref.current;p.style.top="0px";const ir=Math.max(nt,Ie+C.offsetTop+(ft?He:0)+vt)+Bt;p.style.height=ir+"px",C.scrollTop=Ct-nt+C.offsetTop}p.style.margin=`${Nm}px 0`,p.style.minHeight=ke+"px",p.style.maxHeight=Le+"px",i==null||i(),requestAnimationFrame(()=>j.current=!0)}},[T,c.trigger,c.valueNode,p,g,C,L,O,c.dir,i]);no(()=>$(),[$]);const[G,W]=N.useState();no(()=>{g&&W(window.getComputedStyle(g).zIndex)},[g]);const Z=N.useCallback(Q=>{Q&&P.current===!0&&($(),F==null||F(),P.current=!1)},[$,F]);return s.jsx(zXe,{scope:n,contentWrapper:p,shouldExpandOnScrollRef:j,onScrollButtonChange:Z,children:s.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:G},children:s.jsx(An.div,{...a,ref:E,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})},"SelectItemAlignedPosition")),dle=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,align:i="start",collisionPadding:a=Nm,...c}=e,d=TY(n);return s.jsx(G4,{...d,...c,ref:r,align:i,collisionPadding:a,style:{boxSizing:"border-box",...c.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})},"SelectPopperPosition")),[zXe,AY]=kw(dw,{}),hle="SelectViewport",$Xe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,nonce:i,...a}=e,c=Iw(hle,n),d=AY(hle,n),p=Jn(r,c.onViewportChange),l=N.useRef(0);return s.jsxs(s.Fragment,{children:[s.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:i}),s.jsx(x5.Slot,{scope:n,children:s.jsx(An.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:p,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:Qr(a.onScroll,g=>{const v=g.currentTarget,{contentWrapper:E,shouldExpandOnScrollRef:T}=d;if(T!=null&&T.current&&E){const j=Math.abs(l.current-v.scrollTop);if(j>0){const P=window.innerHeight-Nm*2,C=parseFloat(E.style.minHeight),L=parseFloat(E.style.height),O=Math.max(C,L);if(O0?G:0,E.style.justifyContent="flex-end")}}}l.current=v.scrollTop})})})]})},"SelectViewport")),UXe="SelectGroup",[VXe,qXe]=kw(UXe),GXe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,...i}=e,a=Wl();return s.jsx(VXe,{scope:n,id:a,children:s.jsx(An.div,{role:"group","aria-labelledby":a,...i,ref:r})})},"SelectGroup")),HXe="SelectLabel",sSe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,...i}=e,a=qXe(HXe,n);return s.jsx(An.div,{id:a.id,...i,ref:r})},"SelectLabel")),KG="SelectItem",[WXe,aSe]=kw(KG),oSe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,value:i,disabled:a=!1,textValue:c,...d}=e,p=Hv(KG,n),l=Iw(KG,n),g=p.value===i,[v,E]=N.useState(c??""),[T,j]=N.useState(!1),P=Yo($=>{var G;return(G=l.itemRefCallback)==null?void 0:G.call(l,$,i,a)}),C=Jn(r,P),L=Wl(),O=N.useRef("touch");function F($){p.hasConsumerStoppedPropagationRef.current=$.isPropagationStopped(),p.onUserSelect(i),p.onOpenChange(!1)}return Ds(F,"handleSelect"),s.jsx(WXe,{scope:n,value:i,disabled:a,textId:L,isSelected:g,onItemTextChange:N.useCallback($=>{E(G=>G||(($==null?void 0:$.textContent)??"").trim())},[]),children:s.jsx(x5.ItemSlot,{scope:n,value:i,disabled:a,textValue:v,children:s.jsx(An.div,{role:"option","aria-labelledby":L,"data-highlighted":T?"":void 0,"aria-selected":g&&T,"data-state":g?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...d,ref:C,onFocus:Qr(d.onFocus,()=>j(!0)),onBlur:Qr(d.onBlur,()=>j(!1)),onClick:Qr(d.onClick,$=>{a||O.current!=="mouse"&&F($)}),onPointerUp:Qr(d.onPointerUp,$=>{a||O.current==="mouse"&&F($)}),onPointerDown:Qr(d.onPointerDown,$=>{O.current=$.pointerType}),onPointerMove:Qr(d.onPointerMove,$=>{var G;O.current=$.pointerType,a?(G=l.onItemLeave)==null||G.call(l):O.current==="mouse"&&$.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Qr(d.onPointerLeave,$=>{var G;$.currentTarget===document.activeElement&&((G=l.onItemLeave)==null||G.call(l))}),onKeyDown:Qr(d.onKeyDown,$=>{var W;a||$.target!==$.currentTarget||((W=l.searchRef)==null?void 0:W.current)!==""&&$.key===" "||(wXe.includes($.key)&&F($),$.key===" "&&$.preventDefault())})})})})},"SelectItem")),jD="SelectItemText",KXe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,className:i,style:a,...c}=e,d=Hv(jD,n),p=Iw(jD,n),l=aSe(jD,n),g=AXe(jD,n),[v,E]=N.useState(null),T=Yo(F=>{var $;return($=p.itemTextRefCallback)==null?void 0:$.call(p,F,l.value,l.disabled)}),j=Jn(r,E,l.onItemTextChange,T),P=v==null?void 0:v.textContent,C=N.useMemo(()=>s.jsx("option",{value:l.value,disabled:l.disabled,children:P},l.value),[l.disabled,l.value,P]),{onNativeOptionAdd:L,onNativeOptionRemove:O}=g;return no(()=>(L(C),()=>O(C)),[L,O,C]),s.jsxs(s.Fragment,{children:[s.jsx(An.span,{id:l.textId,...c,ref:j}),l.isSelected&&d.valueNode&&!d.valueNodeHasChildren&&!WP(d.value)?vg.createPortal(c.children,d.valueNode):null]})},"SelectItemText")),YXe="SelectItemIndicator",ZXe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,...i}=e;return aSe(YXe,n).isSelected?s.jsx(An.span,{"aria-hidden":!0,...i,ref:r}):null},"SelectItemIndicator")),fle="SelectScrollUpButton",lSe=N.forwardRef(Ds(function(e,r){const n=Iw(fle,e.__scopeSelect),i=AY(fle,e.__scopeSelect),[a,c]=N.useState(!1),d=Jn(r,i.onScrollButtonChange);return no(()=>{if(n.viewport&&n.isPositioned){let p=function(){const g=l.scrollTop>0;c(g)};Ds(p,"handleScroll");const l=n.viewport;return p(),l.addEventListener("scroll",p),()=>l.removeEventListener("scroll",p)}},[n.viewport,n.isPositioned]),a?s.jsx(uSe,{...e,ref:d,onAutoScroll:()=>{const{viewport:p,selectedItem:l}=n;p&&l&&(p.scrollTop=p.scrollTop-l.offsetHeight)}}):null},"SelectScrollUpButton")),mle="SelectScrollDownButton",cSe=N.forwardRef(Ds(function(e,r){const n=Iw(mle,e.__scopeSelect),i=AY(mle,e.__scopeSelect),[a,c]=N.useState(!1),d=Jn(r,i.onScrollButtonChange);return no(()=>{if(n.viewport&&n.isPositioned){let p=function(){const g=l.scrollHeight-l.clientHeight,v=Math.ceil(l.scrollTop)l.removeEventListener("scroll",p)}},[n.viewport,n.isPositioned]),a?s.jsx(uSe,{...e,ref:d,onAutoScroll:()=>{const{viewport:p,selectedItem:l}=n;p&&l&&(p.scrollTop=p.scrollTop+l.offsetHeight)}}):null},"SelectScrollDownButton")),uSe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,onAutoScroll:i,...a}=e,c=Iw("SelectScrollButton",n),d=N.useRef(null),p=_5(n),l=N.useCallback(()=>{d.current!==null&&(window.clearInterval(d.current),d.current=null)},[]);return N.useEffect(()=>()=>l(),[l]),no(()=>{var v;const g=p().find(E=>E.ref.current===document.activeElement);(v=g==null?void 0:g.ref.current)==null||v.scrollIntoView({block:"nearest"})},[p]),s.jsx(An.div,{"aria-hidden":!0,...a,ref:r,style:{flexShrink:0,...a.style},onPointerDown:Qr(a.onPointerDown,()=>{d.current===null&&(d.current=window.setInterval(i,50))}),onPointerMove:Qr(a.onPointerMove,()=>{var g;(g=c.onItemLeave)==null||g.call(c),d.current===null&&(d.current=window.setInterval(i,50))}),onPointerLeave:Qr(a.onPointerLeave,()=>{l()})})},"SelectScrollButtonImpl")),dSe=N.forwardRef(Ds(function(e,r){const{__scopeSelect:n,...i}=e;return s.jsx(An.div,{"aria-hidden":!0,...i,ref:r})},"SelectSeparator")),XXe="SelectBubbleInput",QXe=N.forwardRef(Ds(function({__scopeSelect:e,...r},n){const i=Hv(XXe,e),{value:a,onValueChange:c,required:d,disabled:p,name:l,autoComplete:g,form:v,userSelection:E}=i,{nativeOptions:T,nativeSelectKey:j}=i,P=N.useRef(null),C=Jn(n,P),L=a??"",O=N.useRef(L),F=N.useRef(E),$=N.useRef(!1),G=Array.from(T).some(W=>(W.props.value??"")==="");return N.useEffect(()=>{const W=P.current;if(!W)return;const Z=window.HTMLSelectElement.prototype,ee=Object.getOwnPropertyDescriptor(Z,"value").set,ie=E!==null&&E!==F.current;F.current=E;const oe=O.current!==L;O.current=L;const pe=ie&&oe;if(ie&&!oe&&E.value!==L&&!E.hasConsumerStoppedPropagation&&ee){$.current=!0;try{ee.call(W,E.value),W.dispatchEvent(new Event("change",{bubbles:!0}))}finally{$.current=!1,ee.call(W,L)}return}const Le=pe&&!E.hasConsumerStoppedPropagation;if(oe&&ee){const be=new Event("change",{bubbles:Le});ee.call(W,L),W.dispatchEvent(be)}},[L,E]),s.jsxs(An.select,{"aria-hidden":!0,required:d,tabIndex:-1,name:l,autoComplete:g,disabled:p,form:v,onChange:W=>{$.current||c(W.target.value)},...r,style:{...O_e,...r.style},ref:C,defaultValue:L,children:[WP(a)&&!G?s.jsx("option",{value:""}):null,Array.from(T)]},j)},"SelectBubbleInput"));function hSe(t){return typeof t=="function"}Ds(hSe,"isFunction");function WP(t){return t===""||t===void 0}Ds(WP,"shouldShowPlaceholder");function kY(t){const e=Yo(t),r=N.useRef(""),n=N.useRef(0),i=N.useCallback(c=>{const d=r.current+c;e(d);function p(l){r.current=l,window.clearTimeout(n.current),l!==""&&(n.current=window.setTimeout(()=>p(""),1e3))}Ds(p,"updateSearch"),p(d)},[e]),a=N.useCallback(()=>{r.current="",window.clearTimeout(n.current)},[]);return N.useEffect(()=>()=>window.clearTimeout(n.current),[]),[r,i,a]}Ds(kY,"useTypeaheadSearch");function IY(t,e,r){const i=e.length>1&&Array.from(e).every(l=>l===e[0])?e[0]:e,a=r?t.indexOf(r):-1;let c=fSe(t,Math.max(a,0));i.length===1&&(c=c.filter(l=>l!==r));const p=c.find(l=>l.textValue.toLowerCase().startsWith(i.toLowerCase()));return p!==r?p:void 0}Ds(IY,"findNextItem");function fSe(t,e){return t.map((r,n)=>t[(e+n)%t.length])}Ds(fSe,"wrapArray");const Xo=kXe,yKt=GXe,Qo=CXe,Mo=N.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(rSe,{ref:n,className:hr("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...r,children:[e,s.jsx(PXe,{asChild:!0,children:s.jsx(ad,{className:"h-4 w-4 opacity-50"})})]}));Mo.displayName=rSe.displayName;const mSe=N.forwardRef(({className:t,...e},r)=>s.jsx(lSe,{ref:r,className:hr("flex cursor-default items-center justify-center py-1",t),...e,children:s.jsx(V4e,{className:"h-4 w-4"})}));mSe.displayName=lSe.displayName;const pSe=N.forwardRef(({className:t,...e},r)=>s.jsx(cSe,{ref:r,className:hr("flex cursor-default items-center justify-center py-1",t),...e,children:s.jsx(ad,{className:"h-4 w-4"})}));pSe.displayName=cSe.displayName;const Oo=N.forwardRef(({className:t,children:e,position:r="popper",...n},i)=>s.jsx(DXe,{children:s.jsxs(nSe,{ref:i,className:hr("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:r,...n,children:[s.jsx(mSe,{}),s.jsx($Xe,{className:hr("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),s.jsx(pSe,{})]})}));Oo.displayName=nSe.displayName;const JXe=N.forwardRef(({className:t,...e},r)=>s.jsx(sSe,{ref:r,className:hr("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...e}));JXe.displayName=sSe.displayName;const $n=N.forwardRef(({className:t,children:e,...r},n)=>s.jsxs(oSe,{ref:n,className:hr("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t),...r,children:[s.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:s.jsx(ZXe,{children:s.jsx(ql,{className:"h-4 w-4"})})}),s.jsx(KXe,{children:e})]}));$n.displayName=oSe.displayName;const eQe=N.forwardRef(({className:t,...e},r)=>s.jsx(dSe,{ref:r,className:hr("-mx-1 my-1 h-px bg-muted",t),...e}));eQe.displayName=dSe.displayName;const tQe=Gv({category:g5(["general","technology","crm","marketing"]),subject:Us().min(5,"Subject must be at least 5 characters").max(200),description:Us().min(20,"Please provide more details (at least 20 characters)").max(1e4,"Please keep the description under 10,000 characters")}),rQe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function nQe({trigger:t}){const[e,r]=N.useState(!1),[n,i]=N.useState(!1),{user:a}=_i(),c=lY({resolver:uY(tQe),defaultValues:{category:"general",subject:"",description:""}}),d=async p=>{if(!a){lr.error("You must be logged in to submit a ticket");return}i(!0);try{const{error:l}=await Be.from("support_tickets").insert({user_id:a.id,category:p.category,subject:p.subject,description:p.description});if(l)throw l;try{await Be.functions.invoke("support-ticket-notify",{body:{category:rQe[p.category],subject:p.subject}})}catch(g){console.log("Notification send attempted:",g)}lr.success("Support ticket submitted successfully!"),c.reset(),r(!1)}catch(l){console.error("Error submitting ticket:",l),lr.error("Failed to submit ticket. Please try again.")}finally{i(!1)}};return s.jsxs(gl,{open:e,onOpenChange:r,children:[s.jsx(Swe,{asChild:!0,children:t||s.jsxs(Jt,{variant:"ghost",size:"icon",className:"relative",children:[s.jsx(a5e,{className:"h-5 w-5"}),s.jsx("span",{className:"sr-only",children:"Support"})]})}),s.jsxs(Jo,{className:"sm:max-w-[500px]",children:[s.jsxs(Bc,{children:[s.jsx(pc,{children:"Need Help?"}),s.jsx(sf,{children:"Submit a support ticket and we'll get back to you as soon as possible."})]}),s.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted rounded-lg mb-4",children:[s.jsx(Ui,{className:"h-4 w-4 text-muted-foreground"}),s.jsxs("span",{className:"text-sm text-muted-foreground",children:["You can also text us at: ",s.jsx("span",{className:"font-medium text-foreground",children:"1-866-527-8668"})]})]}),s.jsx(EY,{...c,children:s.jsxs("form",{onSubmit:c.handleSubmit(d),className:"space-y-4",children:[s.jsx(Cc,{control:c.control,name:"category",render:({field:p})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Category"}),s.jsxs(Xo,{onValueChange:p.onChange,defaultValue:p.value,children:[s.jsx(oc,{children:s.jsx(Mo,{children:s.jsx(Qo,{placeholder:"Select a category"})})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"general",children:"General Support"}),s.jsx($n,{value:"technology",children:"Technology Support"}),s.jsx($n,{value:"crm",children:"CRM Support"}),s.jsx($n,{value:"marketing",children:"Marketing Support"})]})]}),s.jsx(Ym,{})]})}),s.jsx(Cc,{control:c.control,name:"subject",render:({field:p})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Subject"}),s.jsx(oc,{children:s.jsx(hn,{placeholder:"Brief description of your issue",...p})}),s.jsx(Ym,{})]})}),s.jsx(Cc,{control:c.control,name:"description",render:({field:p})=>{var l;return s.jsxs(sc,{children:[s.jsx(ac,{children:"Description"}),s.jsx(oc,{children:s.jsx(df,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...p})}),s.jsxs("p",{className:"text-right text-xs text-muted-foreground",children:[(((l=p.value)==null?void 0:l.length)??0).toLocaleString()," / 10,000"]}),s.jsx(Ym,{})]})}}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(Jt,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),s.jsx(Jt,{type:"submit",disabled:n,children:n?"Submitting...":"Submit Ticket"})]})]})})]})]})}function oi(t){const e=Object.prototype.toString.call(t);return t instanceof Date||typeof t=="object"&&e==="[object Date]"?new t.constructor(+t):typeof t=="number"||e==="[object Number]"||typeof t=="string"||e==="[object String]"?new Date(t):new Date(NaN)}function to(t,e){return t instanceof Date?new t.constructor(e):new Date(e)}function tu(t,e){const r=oi(t);return isNaN(e)?to(t,NaN):(e&&r.setDate(r.getDate()+e),r)}function af(t,e){const r=oi(t);if(isNaN(e))return to(t,NaN);if(!e)return r;const n=r.getDate(),i=to(t,r.getTime());i.setMonth(r.getMonth()+e+1,0);const a=i.getDate();return n>=a?i:(r.setFullYear(i.getFullYear(),i.getMonth(),n),r)}const jY=6048e5,iQe=864e5,CY=6e4,PY=36e5,sQe=1e3,CD=43200,ple=1440;let aQe={};function Wv(){return aQe}function ld(t,e){var d,p,l,g;const r=Wv(),n=(e==null?void 0:e.weekStartsOn)??((p=(d=e==null?void 0:e.locale)==null?void 0:d.options)==null?void 0:p.weekStartsOn)??r.weekStartsOn??((g=(l=r.locale)==null?void 0:l.options)==null?void 0:g.weekStartsOn)??0,i=oi(t),a=i.getDay(),c=(a=i.getTime()?r+1:e.getTime()>=c.getTime()?r:r-1}function Ev(t){const e=oi(t);return e.setHours(0,0,0,0),e}function Tv(t){const e=oi(t),r=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return r.setUTCFullYear(e.getFullYear()),+t-+r}function Zm(t,e){const r=Ev(t),n=Ev(e),i=+r-Tv(r),a=+n-Tv(n);return Math.round((i-a)/iQe)}function oQe(t){const e=gSe(t),r=to(t,0);return r.setFullYear(e,0,4),r.setHours(0,0,0,0),Ky(r)}function YG(t,e){const r=e*7;return tu(t,r)}function lQe(t,e){return af(t,e*12)}function cQe(t){let e;return t.forEach(function(r){const n=oi(r);(e===void 0||e{const n=oi(r);(!e||e>n||isNaN(+n))&&(e=n)}),e||new Date(NaN)}function nO(t,e){const r=oi(t),n=oi(e),i=r.getTime()-n.getTime();return i<0?-1:i>0?1:i}function NY(t){return to(t,Date.now())}function Fu(t,e){const r=Ev(t),n=Ev(e);return+r==+n}function RY(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function ZG(t){if(!RY(t)&&typeof t!="number")return!1;const e=oi(t);return!isNaN(Number(e))}function fT(t,e){const r=oi(t),n=oi(e),i=r.getFullYear()-n.getFullYear(),a=r.getMonth()-n.getMonth();return i*12+a}function dQe(t,e,r){const n=ld(t,r),i=ld(e,r),a=+n-Tv(n),c=+i-Tv(i);return Math.round((a-c)/jY)}function hQe(t,e){const r=oi(t),n=oi(e),i=gle(r,n),a=Math.abs(Zm(r,n));r.setDate(r.getDate()-i*a);const c=+(gle(r,n)===-i),d=i*(a-c);return d===0?0:d}function gle(t,e){const r=t.getFullYear()-e.getFullYear()||t.getMonth()-e.getMonth()||t.getDate()-e.getDate()||t.getHours()-e.getHours()||t.getMinutes()-e.getMinutes()||t.getSeconds()-e.getSeconds()||t.getMilliseconds()-e.getMilliseconds();return r<0?-1:r>0?1:r}function fQe(t){return e=>{const n=(t?Math[t]:Math.trunc)(e);return n===0?0:n}}function mQe(t,e){return+oi(t)-+oi(e)}function pQe(t){const e=oi(t);return e.setHours(23,59,59,999),e}function KP(t){const e=oi(t),r=e.getMonth();return e.setFullYear(e.getFullYear(),r+1,0),e.setHours(23,59,59,999),e}function gQe(t){const e=oi(t);return+pQe(e)==+KP(e)}function yQe(t,e){const r=oi(t),n=oi(e),i=nO(r,n),a=Math.abs(fT(r,n));let c;if(a<1)c=0;else{r.getMonth()===1&&r.getDate()>27&&r.setDate(30),r.setMonth(r.getMonth()-i*a);let d=nO(r,n)===-i;gQe(oi(t))&&a===1&&nO(t,n)===1&&(d=!1),c=i*(a-Number(d))}return c===0?0:c}function xQe(t,e,r){const n=mQe(t,e)/1e3;return fQe(r==null?void 0:r.roundingMethod)(n)}function _Qe(t,e){const r=oi(t.start),n=oi(t.end);let i=+r>+n;const a=i?+r:+n,c=i?n:r;c.setHours(0,0,0,0);let d=1;const p=[];for(;+c<=a;)p.push(oi(c)),c.setDate(c.getDate()+d),c.setHours(0,0,0,0);return i?p.reverse():p}function Fd(t){const e=oi(t);return e.setDate(1),e.setHours(0,0,0,0),e}function ySe(t){const e=oi(t),r=to(t,0);return r.setFullYear(e.getFullYear(),0,1),r.setHours(0,0,0,0),r}function v5(t,e){var d,p,l,g;const r=Wv(),n=(e==null?void 0:e.weekStartsOn)??((p=(d=e==null?void 0:e.locale)==null?void 0:d.options)==null?void 0:p.weekStartsOn)??r.weekStartsOn??((g=(l=r.locale)==null?void 0:l.options)==null?void 0:g.weekStartsOn)??0,i=oi(t),a=i.getDay(),c=(a{let n;const i=vQe[t];return typeof i=="string"?n=i:e===1?n=i.one:n=i.other.replace("{{count}}",e.toString()),r!=null&&r.addSuffix?r.comparison&&r.comparison>0?"in "+n:n+" ago":n};function EU(t){return(e={})=>{const r=e.width?String(e.width):t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}const wQe={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},SQe={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},EQe={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},TQe={date:EU({formats:wQe,defaultWidth:"full"}),time:EU({formats:SQe,defaultWidth:"full"}),dateTime:EU({formats:EQe,defaultWidth:"full"})},AQe={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},kQe=(t,e,r,n)=>AQe[t];function nI(t){return(e,r)=>{const n=r!=null&&r.context?String(r.context):"standalone";let i;if(n==="formatting"&&t.formattingValues){const c=t.defaultFormattingWidth||t.defaultWidth,d=r!=null&&r.width?String(r.width):c;i=t.formattingValues[d]||t.formattingValues[c]}else{const c=t.defaultWidth,d=r!=null&&r.width?String(r.width):t.defaultWidth;i=t.values[d]||t.values[c]}const a=t.argumentCallback?t.argumentCallback(e):e;return i[a]}}const IQe={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},jQe={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},CQe={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},PQe={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},NQe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},RQe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},LQe=(t,e)=>{const r=Number(t),n=r%100;if(n>20||n<10)switch(n%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},DQe={ordinalNumber:LQe,era:nI({values:IQe,defaultWidth:"wide"}),quarter:nI({values:jQe,defaultWidth:"wide",argumentCallback:t=>t-1}),month:nI({values:CQe,defaultWidth:"wide"}),day:nI({values:PQe,defaultWidth:"wide"}),dayPeriod:nI({values:NQe,defaultWidth:"wide",formattingValues:RQe,defaultFormattingWidth:"wide"})};function iI(t){return(e,r={})=>{const n=r.width,i=n&&t.matchPatterns[n]||t.matchPatterns[t.defaultMatchWidth],a=e.match(i);if(!a)return null;const c=a[0],d=n&&t.parsePatterns[n]||t.parsePatterns[t.defaultParseWidth],p=Array.isArray(d)?OQe(d,v=>v.test(c)):MQe(d,v=>v.test(c));let l;l=t.valueCallback?t.valueCallback(p):p,l=r.valueCallback?r.valueCallback(l):l;const g=e.slice(c.length);return{value:l,rest:g}}}function MQe(t,e){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return r}function OQe(t,e){for(let r=0;r{const n=e.match(t.matchPattern);if(!n)return null;const i=n[0],a=e.match(t.parsePattern);if(!a)return null;let c=t.valueCallback?t.valueCallback(a[0]):a[0];c=r.valueCallback?r.valueCallback(c):c;const d=e.slice(i.length);return{value:c,rest:d}}}const BQe=/^(\d+)(th|st|nd|rd)?/i,zQe=/\d+/i,$Qe={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},UQe={any:[/^b/i,/^(a|c)/i]},VQe={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},qQe={any:[/1/i,/2/i,/3/i,/4/i]},GQe={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},HQe={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},WQe={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},KQe={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},YQe={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},ZQe={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},XQe={ordinalNumber:FQe({matchPattern:BQe,parsePattern:zQe,valueCallback:t=>parseInt(t,10)}),era:iI({matchPatterns:$Qe,defaultMatchWidth:"wide",parsePatterns:UQe,defaultParseWidth:"any"}),quarter:iI({matchPatterns:VQe,defaultMatchWidth:"wide",parsePatterns:qQe,defaultParseWidth:"any",valueCallback:t=>t+1}),month:iI({matchPatterns:GQe,defaultMatchWidth:"wide",parsePatterns:HQe,defaultParseWidth:"any"}),day:iI({matchPatterns:WQe,defaultMatchWidth:"wide",parsePatterns:KQe,defaultParseWidth:"any"}),dayPeriod:iI({matchPatterns:YQe,defaultMatchWidth:"any",parsePatterns:ZQe,defaultParseWidth:"any"})},b5={code:"en-US",formatDistance:bQe,formatLong:TQe,formatRelative:kQe,localize:DQe,match:XQe,options:{weekStartsOn:0,firstWeekContainsDate:1}};function QQe(t){const e=oi(t);return Zm(e,ySe(e))+1}function LY(t){const e=oi(t),r=+Ky(e)-+oQe(e);return Math.round(r/jY)+1}function DY(t,e){var g,v,E,T;const r=oi(t),n=r.getFullYear(),i=Wv(),a=(e==null?void 0:e.firstWeekContainsDate)??((v=(g=e==null?void 0:e.locale)==null?void 0:g.options)==null?void 0:v.firstWeekContainsDate)??i.firstWeekContainsDate??((T=(E=i.locale)==null?void 0:E.options)==null?void 0:T.firstWeekContainsDate)??1,c=to(t,0);c.setFullYear(n+1,0,a),c.setHours(0,0,0,0);const d=ld(c,e),p=to(t,0);p.setFullYear(n,0,a),p.setHours(0,0,0,0);const l=ld(p,e);return r.getTime()>=d.getTime()?n+1:r.getTime()>=l.getTime()?n:n-1}function JQe(t,e){var d,p,l,g;const r=Wv(),n=(e==null?void 0:e.firstWeekContainsDate)??((p=(d=e==null?void 0:e.locale)==null?void 0:d.options)==null?void 0:p.firstWeekContainsDate)??r.firstWeekContainsDate??((g=(l=r.locale)==null?void 0:l.options)==null?void 0:g.firstWeekContainsDate)??1,i=DY(t,e),a=to(t,0);return a.setFullYear(i,0,n),a.setHours(0,0,0,0),ld(a,e)}function MY(t,e){const r=oi(t),n=+ld(r,e)-+JQe(r,e);return Math.round(n/jY)+1}function za(t,e){const r=t<0?"-":"",n=Math.abs(t).toString().padStart(e,"0");return r+n}const g_={y(t,e){const r=t.getFullYear(),n=r>0?r:1-r;return za(e==="yy"?n%100:n,e.length)},M(t,e){const r=t.getMonth();return e==="M"?String(r+1):za(r+1,2)},d(t,e){return za(t.getDate(),e.length)},a(t,e){const r=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];case"aaaa":default:return r==="am"?"a.m.":"p.m."}},h(t,e){return za(t.getHours()%12||12,e.length)},H(t,e){return za(t.getHours(),e.length)},m(t,e){return za(t.getMinutes(),e.length)},s(t,e){return za(t.getSeconds(),e.length)},S(t,e){const r=e.length,n=t.getMilliseconds(),i=Math.trunc(n*Math.pow(10,r-3));return za(i,e.length)}},kS={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},yle={G:function(t,e,r){const n=t.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return r.era(n,{width:"abbreviated"});case"GGGGG":return r.era(n,{width:"narrow"});case"GGGG":default:return r.era(n,{width:"wide"})}},y:function(t,e,r){if(e==="yo"){const n=t.getFullYear(),i=n>0?n:1-n;return r.ordinalNumber(i,{unit:"year"})}return g_.y(t,e)},Y:function(t,e,r,n){const i=DY(t,n),a=i>0?i:1-i;if(e==="YY"){const c=a%100;return za(c,2)}return e==="Yo"?r.ordinalNumber(a,{unit:"year"}):za(a,e.length)},R:function(t,e){const r=gSe(t);return za(r,e.length)},u:function(t,e){const r=t.getFullYear();return za(r,e.length)},Q:function(t,e,r){const n=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(n);case"QQ":return za(n,2);case"Qo":return r.ordinalNumber(n,{unit:"quarter"});case"QQQ":return r.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return r.quarter(n,{width:"wide",context:"formatting"})}},q:function(t,e,r){const n=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(n);case"qq":return za(n,2);case"qo":return r.ordinalNumber(n,{unit:"quarter"});case"qqq":return r.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return r.quarter(n,{width:"wide",context:"standalone"})}},M:function(t,e,r){const n=t.getMonth();switch(e){case"M":case"MM":return g_.M(t,e);case"Mo":return r.ordinalNumber(n+1,{unit:"month"});case"MMM":return r.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return r.month(n,{width:"wide",context:"formatting"})}},L:function(t,e,r){const n=t.getMonth();switch(e){case"L":return String(n+1);case"LL":return za(n+1,2);case"Lo":return r.ordinalNumber(n+1,{unit:"month"});case"LLL":return r.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return r.month(n,{width:"wide",context:"standalone"})}},w:function(t,e,r,n){const i=MY(t,n);return e==="wo"?r.ordinalNumber(i,{unit:"week"}):za(i,e.length)},I:function(t,e,r){const n=LY(t);return e==="Io"?r.ordinalNumber(n,{unit:"week"}):za(n,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):g_.d(t,e)},D:function(t,e,r){const n=QQe(t);return e==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):za(n,e.length)},E:function(t,e,r){const n=t.getDay();switch(e){case"E":case"EE":case"EEE":return r.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(n,{width:"short",context:"formatting"});case"EEEE":default:return r.day(n,{width:"wide",context:"formatting"})}},e:function(t,e,r,n){const i=t.getDay(),a=(i-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(a);case"ee":return za(a,2);case"eo":return r.ordinalNumber(a,{unit:"day"});case"eee":return r.day(i,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(i,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(i,{width:"short",context:"formatting"});case"eeee":default:return r.day(i,{width:"wide",context:"formatting"})}},c:function(t,e,r,n){const i=t.getDay(),a=(i-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(a);case"cc":return za(a,e.length);case"co":return r.ordinalNumber(a,{unit:"day"});case"ccc":return r.day(i,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(i,{width:"narrow",context:"standalone"});case"cccccc":return r.day(i,{width:"short",context:"standalone"});case"cccc":default:return r.day(i,{width:"wide",context:"standalone"})}},i:function(t,e,r){const n=t.getDay(),i=n===0?7:n;switch(e){case"i":return String(i);case"ii":return za(i,e.length);case"io":return r.ordinalNumber(i,{unit:"day"});case"iii":return r.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(n,{width:"short",context:"formatting"});case"iiii":default:return r.day(n,{width:"wide",context:"formatting"})}},a:function(t,e,r){const i=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(i,{width:"narrow",context:"formatting"});case"aaaa":default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},b:function(t,e,r){const n=t.getHours();let i;switch(n===12?i=kS.noon:n===0?i=kS.midnight:i=n/12>=1?"pm":"am",e){case"b":case"bb":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(i,{width:"narrow",context:"formatting"});case"bbbb":default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},B:function(t,e,r){const n=t.getHours();let i;switch(n>=17?i=kS.evening:n>=12?i=kS.afternoon:n>=4?i=kS.morning:i=kS.night,e){case"B":case"BB":case"BBB":return r.dayPeriod(i,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(i,{width:"narrow",context:"formatting"});case"BBBB":default:return r.dayPeriod(i,{width:"wide",context:"formatting"})}},h:function(t,e,r){if(e==="ho"){let n=t.getHours()%12;return n===0&&(n=12),r.ordinalNumber(n,{unit:"hour"})}return g_.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):g_.H(t,e)},K:function(t,e,r){const n=t.getHours()%12;return e==="Ko"?r.ordinalNumber(n,{unit:"hour"}):za(n,e.length)},k:function(t,e,r){let n=t.getHours();return n===0&&(n=24),e==="ko"?r.ordinalNumber(n,{unit:"hour"}):za(n,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):g_.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):g_.s(t,e)},S:function(t,e){return g_.S(t,e)},X:function(t,e,r){const n=t.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return _le(n);case"XXXX":case"XX":return pb(n);case"XXXXX":case"XXX":default:return pb(n,":")}},x:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"x":return _le(n);case"xxxx":case"xx":return pb(n);case"xxxxx":case"xxx":default:return pb(n,":")}},O:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+xle(n,":");case"OOOO":default:return"GMT"+pb(n,":")}},z:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+xle(n,":");case"zzzz":default:return"GMT"+pb(n,":")}},t:function(t,e,r){const n=Math.trunc(t.getTime()/1e3);return za(n,e.length)},T:function(t,e,r){const n=t.getTime();return za(n,e.length)}};function xle(t,e=""){const r=t>0?"-":"+",n=Math.abs(t),i=Math.trunc(n/60),a=n%60;return a===0?r+String(i):r+String(i)+e+za(a,2)}function _le(t,e){return t%60===0?(t>0?"-":"+")+za(Math.abs(t)/60,2):pb(t,e)}function pb(t,e=""){const r=t>0?"-":"+",n=Math.abs(t),i=za(Math.trunc(n/60),2),a=za(n%60,2);return r+i+e+a}const vle=(t,e)=>{switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},_Se=(t,e)=>{switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},eJe=(t,e)=>{const r=t.match(/(P+)(p+)?/)||[],n=r[1],i=r[2];if(!i)return vle(t,e);let a;switch(n){case"P":a=e.dateTime({width:"short"});break;case"PP":a=e.dateTime({width:"medium"});break;case"PPP":a=e.dateTime({width:"long"});break;case"PPPP":default:a=e.dateTime({width:"full"});break}return a.replace("{{date}}",vle(n,e)).replace("{{time}}",_Se(i,e))},XG={p:_Se,P:eJe},tJe=/^D+$/,rJe=/^Y+$/,nJe=["D","DD","YY","YYYY"];function vSe(t){return tJe.test(t)}function bSe(t){return rJe.test(t)}function QG(t,e,r){const n=iJe(t,e,r);if(console.warn(n),nJe.includes(t))throw new RangeError(n)}function iJe(t,e,r){const n=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${n} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const sJe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,aJe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,oJe=/^'([^]*?)'?$/,lJe=/''/g,cJe=/[a-zA-Z]/;function ds(t,e,r){var g,v,E,T,j,P,C,L;const n=Wv(),i=(r==null?void 0:r.locale)??n.locale??b5,a=(r==null?void 0:r.firstWeekContainsDate)??((v=(g=r==null?void 0:r.locale)==null?void 0:g.options)==null?void 0:v.firstWeekContainsDate)??n.firstWeekContainsDate??((T=(E=n.locale)==null?void 0:E.options)==null?void 0:T.firstWeekContainsDate)??1,c=(r==null?void 0:r.weekStartsOn)??((P=(j=r==null?void 0:r.locale)==null?void 0:j.options)==null?void 0:P.weekStartsOn)??n.weekStartsOn??((L=(C=n.locale)==null?void 0:C.options)==null?void 0:L.weekStartsOn)??0,d=oi(t);if(!ZG(d))throw new RangeError("Invalid time value");let p=e.match(aJe).map(O=>{const F=O[0];if(F==="p"||F==="P"){const $=XG[F];return $(O,i.formatLong)}return O}).join("").match(sJe).map(O=>{if(O==="''")return{isToken:!1,value:"'"};const F=O[0];if(F==="'")return{isToken:!1,value:uJe(O)};if(yle[F])return{isToken:!0,value:O};if(F.match(cJe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+F+"`");return{isToken:!1,value:O}});i.localize.preprocessor&&(p=i.localize.preprocessor(d,p));const l={firstWeekContainsDate:a,weekStartsOn:c,locale:i};return p.map(O=>{if(!O.isToken)return O.value;const F=O.value;(!(r!=null&&r.useAdditionalWeekYearTokens)&&bSe(F)||!(r!=null&&r.useAdditionalDayOfYearTokens)&&vSe(F))&&QG(F,e,String(t));const $=yle[F[0]];return $(d,F,i.localize,l)}).join("")}function uJe(t){const e=t.match(oJe);return e?e[1].replace(lJe,"'"):t}function dJe(t,e,r){const n=Wv(),i=(r==null?void 0:r.locale)??n.locale??b5,a=2520,c=nO(t,e);if(isNaN(c))throw new RangeError("Invalid time value");const d=Object.assign({},r,{addSuffix:r==null?void 0:r.addSuffix,comparison:c});let p,l;c>0?(p=oi(e),l=oi(t)):(p=oi(t),l=oi(e));const g=xQe(l,p),v=(Tv(l)-Tv(p))/1e3,E=Math.round((g-v)/60);let T;if(E<2)return r!=null&&r.includeSeconds?g<5?i.formatDistance("lessThanXSeconds",5,d):g<10?i.formatDistance("lessThanXSeconds",10,d):g<20?i.formatDistance("lessThanXSeconds",20,d):g<40?i.formatDistance("halfAMinute",0,d):g<60?i.formatDistance("lessThanXMinutes",1,d):i.formatDistance("xMinutes",1,d):E===0?i.formatDistance("lessThanXMinutes",1,d):i.formatDistance("xMinutes",E,d);if(E<45)return i.formatDistance("xMinutes",E,d);if(E<90)return i.formatDistance("aboutXHours",1,d);if(En.getTime()}function OY(t,e){const r=oi(t),n=oi(e);return+r<+n}function xJe(t,e){const r=e instanceof Date?to(e,0):new e(0);return r.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),r.setHours(t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()),r}const _Je=10;class SSe{constructor(){jn(this,"subPriority",0)}validate(e,r){return!0}}class vJe extends SSe{constructor(e,r,n,i,a){super(),this.value=e,this.validateValue=r,this.setValue=n,this.priority=i,a&&(this.subPriority=a)}validate(e,r){return this.validateValue(e,this.value,r)}set(e,r,n){return this.setValue(e,r,this.value,n)}}class bJe extends SSe{constructor(){super(...arguments);jn(this,"priority",_Je);jn(this,"subPriority",-1)}set(r,n){return n.timestampIsSet?r:to(r,xJe(r,Date))}}class Sa{run(e,r,n,i){const a=this.parse(e,r,n,i);return a?{setter:new vJe(a.value,this.validate,this.set,this.priority,this.subPriority),rest:a.rest}:null}validate(e,r,n){return!0}}class wJe extends Sa{constructor(){super(...arguments);jn(this,"priority",140);jn(this,"incompatibleTokens",["R","u","t","T"])}parse(r,n,i){switch(n){case"G":case"GG":case"GGG":return i.era(r,{width:"abbreviated"})||i.era(r,{width:"narrow"});case"GGGGG":return i.era(r,{width:"narrow"});case"GGGG":default:return i.era(r,{width:"wide"})||i.era(r,{width:"abbreviated"})||i.era(r,{width:"narrow"})}}set(r,n,i){return n.era=i,r.setFullYear(i,0,1),r.setHours(0,0,0,0),r}}const Gl={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},Yp={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function Hl(t,e){return t&&{value:e(t.value),rest:t.rest}}function hl(t,e){const r=e.match(t);return r?{value:parseInt(r[0],10),rest:e.slice(r[0].length)}:null}function Zp(t,e){const r=e.match(t);if(!r)return null;if(r[0]==="Z")return{value:0,rest:e.slice(1)};const n=r[1]==="+"?1:-1,i=r[2]?parseInt(r[2],10):0,a=r[3]?parseInt(r[3],10):0,c=r[5]?parseInt(r[5],10):0;return{value:n*(i*PY+a*CY+c*sQe),rest:e.slice(r[0].length)}}function ESe(t){return hl(Gl.anyDigitsSigned,t)}function Pl(t,e){switch(t){case 1:return hl(Gl.singleDigit,e);case 2:return hl(Gl.twoDigits,e);case 3:return hl(Gl.threeDigits,e);case 4:return hl(Gl.fourDigits,e);default:return hl(new RegExp("^\\d{1,"+t+"}"),e)}}function AF(t,e){switch(t){case 1:return hl(Gl.singleDigitSigned,e);case 2:return hl(Gl.twoDigitsSigned,e);case 3:return hl(Gl.threeDigitsSigned,e);case 4:return hl(Gl.fourDigitsSigned,e);default:return hl(new RegExp("^-?\\d{1,"+t+"}"),e)}}function FY(t){switch(t){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;case"am":case"midnight":case"night":default:return 0}}function TSe(t,e){const r=e>0,n=r?e:1-e;let i;if(n<=50)i=t||100;else{const a=n+50,c=Math.trunc(a/100)*100,d=t>=a%100;i=t+c-(d?100:0)}return r?i:1-i}function ASe(t){return t%400===0||t%4===0&&t%100!==0}class SJe extends Sa{constructor(){super(...arguments);jn(this,"priority",130);jn(this,"incompatibleTokens",["Y","R","u","w","I","i","e","c","t","T"])}parse(r,n,i){const a=c=>({year:c,isTwoDigitYear:n==="yy"});switch(n){case"y":return Hl(Pl(4,r),a);case"yo":return Hl(i.ordinalNumber(r,{unit:"year"}),a);default:return Hl(Pl(n.length,r),a)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,i){const a=r.getFullYear();if(i.isTwoDigitYear){const d=TSe(i.year,a);return r.setFullYear(d,0,1),r.setHours(0,0,0,0),r}const c=!("era"in n)||n.era===1?i.year:1-i.year;return r.setFullYear(c,0,1),r.setHours(0,0,0,0),r}}class EJe extends Sa{constructor(){super(...arguments);jn(this,"priority",130);jn(this,"incompatibleTokens",["y","R","u","Q","q","M","L","I","d","D","i","t","T"])}parse(r,n,i){const a=c=>({year:c,isTwoDigitYear:n==="YY"});switch(n){case"Y":return Hl(Pl(4,r),a);case"Yo":return Hl(i.ordinalNumber(r,{unit:"year"}),a);default:return Hl(Pl(n.length,r),a)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,i,a){const c=DY(r,a);if(i.isTwoDigitYear){const p=TSe(i.year,c);return r.setFullYear(p,0,a.firstWeekContainsDate),r.setHours(0,0,0,0),ld(r,a)}const d=!("era"in n)||n.era===1?i.year:1-i.year;return r.setFullYear(d,0,a.firstWeekContainsDate),r.setHours(0,0,0,0),ld(r,a)}}class TJe extends Sa{constructor(){super(...arguments);jn(this,"priority",130);jn(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(r,n){return AF(n==="R"?4:n.length,r)}set(r,n,i){const a=to(r,0);return a.setFullYear(i,0,4),a.setHours(0,0,0,0),Ky(a)}}class AJe extends Sa{constructor(){super(...arguments);jn(this,"priority",130);jn(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(r,n){return AF(n==="u"?4:n.length,r)}set(r,n,i){return r.setFullYear(i,0,1),r.setHours(0,0,0,0),r}}class kJe extends Sa{constructor(){super(...arguments);jn(this,"priority",120);jn(this,"incompatibleTokens",["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"])}parse(r,n,i){switch(n){case"Q":case"QQ":return Pl(n.length,r);case"Qo":return i.ordinalNumber(r,{unit:"quarter"});case"QQQ":return i.quarter(r,{width:"abbreviated",context:"formatting"})||i.quarter(r,{width:"narrow",context:"formatting"});case"QQQQQ":return i.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return i.quarter(r,{width:"wide",context:"formatting"})||i.quarter(r,{width:"abbreviated",context:"formatting"})||i.quarter(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=1&&n<=4}set(r,n,i){return r.setMonth((i-1)*3,1),r.setHours(0,0,0,0),r}}class IJe extends Sa{constructor(){super(...arguments);jn(this,"priority",120);jn(this,"incompatibleTokens",["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"])}parse(r,n,i){switch(n){case"q":case"qq":return Pl(n.length,r);case"qo":return i.ordinalNumber(r,{unit:"quarter"});case"qqq":return i.quarter(r,{width:"abbreviated",context:"standalone"})||i.quarter(r,{width:"narrow",context:"standalone"});case"qqqqq":return i.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return i.quarter(r,{width:"wide",context:"standalone"})||i.quarter(r,{width:"abbreviated",context:"standalone"})||i.quarter(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=1&&n<=4}set(r,n,i){return r.setMonth((i-1)*3,1),r.setHours(0,0,0,0),r}}class jJe extends Sa{constructor(){super(...arguments);jn(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);jn(this,"priority",110)}parse(r,n,i){const a=c=>c-1;switch(n){case"M":return Hl(hl(Gl.month,r),a);case"MM":return Hl(Pl(2,r),a);case"Mo":return Hl(i.ordinalNumber(r,{unit:"month"}),a);case"MMM":return i.month(r,{width:"abbreviated",context:"formatting"})||i.month(r,{width:"narrow",context:"formatting"});case"MMMMM":return i.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return i.month(r,{width:"wide",context:"formatting"})||i.month(r,{width:"abbreviated",context:"formatting"})||i.month(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=11}set(r,n,i){return r.setMonth(i,1),r.setHours(0,0,0,0),r}}class CJe extends Sa{constructor(){super(...arguments);jn(this,"priority",110);jn(this,"incompatibleTokens",["Y","R","q","Q","M","w","I","D","i","e","c","t","T"])}parse(r,n,i){const a=c=>c-1;switch(n){case"L":return Hl(hl(Gl.month,r),a);case"LL":return Hl(Pl(2,r),a);case"Lo":return Hl(i.ordinalNumber(r,{unit:"month"}),a);case"LLL":return i.month(r,{width:"abbreviated",context:"standalone"})||i.month(r,{width:"narrow",context:"standalone"});case"LLLLL":return i.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return i.month(r,{width:"wide",context:"standalone"})||i.month(r,{width:"abbreviated",context:"standalone"})||i.month(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=0&&n<=11}set(r,n,i){return r.setMonth(i,1),r.setHours(0,0,0,0),r}}function PJe(t,e,r){const n=oi(t),i=MY(n,r)-e;return n.setDate(n.getDate()-i*7),n}class NJe extends Sa{constructor(){super(...arguments);jn(this,"priority",100);jn(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(r,n,i){switch(n){case"w":return hl(Gl.week,r);case"wo":return i.ordinalNumber(r,{unit:"week"});default:return Pl(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,i,a){return ld(PJe(r,i,a),a)}}function RJe(t,e){const r=oi(t),n=LY(r)-e;return r.setDate(r.getDate()-n*7),r}class LJe extends Sa{constructor(){super(...arguments);jn(this,"priority",100);jn(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"])}parse(r,n,i){switch(n){case"I":return hl(Gl.week,r);case"Io":return i.ordinalNumber(r,{unit:"week"});default:return Pl(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,i){return Ky(RJe(r,i))}}const DJe=[31,28,31,30,31,30,31,31,30,31,30,31],MJe=[31,29,31,30,31,30,31,31,30,31,30,31];class OJe extends Sa{constructor(){super(...arguments);jn(this,"priority",90);jn(this,"subPriority",1);jn(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(r,n,i){switch(n){case"d":return hl(Gl.date,r);case"do":return i.ordinalNumber(r,{unit:"date"});default:return Pl(n.length,r)}}validate(r,n){const i=r.getFullYear(),a=ASe(i),c=r.getMonth();return a?n>=1&&n<=MJe[c]:n>=1&&n<=DJe[c]}set(r,n,i){return r.setDate(i),r.setHours(0,0,0,0),r}}class FJe extends Sa{constructor(){super(...arguments);jn(this,"priority",90);jn(this,"subpriority",1);jn(this,"incompatibleTokens",["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"])}parse(r,n,i){switch(n){case"D":case"DD":return hl(Gl.dayOfYear,r);case"Do":return i.ordinalNumber(r,{unit:"date"});default:return Pl(n.length,r)}}validate(r,n){const i=r.getFullYear();return ASe(i)?n>=1&&n<=366:n>=1&&n<=365}set(r,n,i){return r.setMonth(0,i),r.setHours(0,0,0,0),r}}function BY(t,e,r){var v,E,T,j;const n=Wv(),i=(r==null?void 0:r.weekStartsOn)??((E=(v=r==null?void 0:r.locale)==null?void 0:v.options)==null?void 0:E.weekStartsOn)??n.weekStartsOn??((j=(T=n.locale)==null?void 0:T.options)==null?void 0:j.weekStartsOn)??0,a=oi(t),c=a.getDay(),p=(e%7+7)%7,l=7-i,g=e<0||e>6?e-(c+l)%7:(p+l)%7-(c+l)%7;return tu(a,g)}class BJe extends Sa{constructor(){super(...arguments);jn(this,"priority",90);jn(this,"incompatibleTokens",["D","i","e","c","t","T"])}parse(r,n,i){switch(n){case"E":case"EE":case"EEE":return i.day(r,{width:"abbreviated",context:"formatting"})||i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"});case"EEEEE":return i.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"});case"EEEE":default:return i.day(r,{width:"wide",context:"formatting"})||i.day(r,{width:"abbreviated",context:"formatting"})||i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=6}set(r,n,i,a){return r=BY(r,i,a),r.setHours(0,0,0,0),r}}class zJe extends Sa{constructor(){super(...arguments);jn(this,"priority",90);jn(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(r,n,i,a){const c=d=>{const p=Math.floor((d-1)/7)*7;return(d+a.weekStartsOn+6)%7+p};switch(n){case"e":case"ee":return Hl(Pl(n.length,r),c);case"eo":return Hl(i.ordinalNumber(r,{unit:"day"}),c);case"eee":return i.day(r,{width:"abbreviated",context:"formatting"})||i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"});case"eeeee":return i.day(r,{width:"narrow",context:"formatting"});case"eeeeee":return i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"});case"eeee":default:return i.day(r,{width:"wide",context:"formatting"})||i.day(r,{width:"abbreviated",context:"formatting"})||i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"})}}validate(r,n){return n>=0&&n<=6}set(r,n,i,a){return r=BY(r,i,a),r.setHours(0,0,0,0),r}}class $Je extends Sa{constructor(){super(...arguments);jn(this,"priority",90);jn(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(r,n,i,a){const c=d=>{const p=Math.floor((d-1)/7)*7;return(d+a.weekStartsOn+6)%7+p};switch(n){case"c":case"cc":return Hl(Pl(n.length,r),c);case"co":return Hl(i.ordinalNumber(r,{unit:"day"}),c);case"ccc":return i.day(r,{width:"abbreviated",context:"standalone"})||i.day(r,{width:"short",context:"standalone"})||i.day(r,{width:"narrow",context:"standalone"});case"ccccc":return i.day(r,{width:"narrow",context:"standalone"});case"cccccc":return i.day(r,{width:"short",context:"standalone"})||i.day(r,{width:"narrow",context:"standalone"});case"cccc":default:return i.day(r,{width:"wide",context:"standalone"})||i.day(r,{width:"abbreviated",context:"standalone"})||i.day(r,{width:"short",context:"standalone"})||i.day(r,{width:"narrow",context:"standalone"})}}validate(r,n){return n>=0&&n<=6}set(r,n,i,a){return r=BY(r,i,a),r.setHours(0,0,0,0),r}}function UJe(t,e){const r=oi(t),n=mJe(r),i=e-n;return tu(r,i)}class VJe extends Sa{constructor(){super(...arguments);jn(this,"priority",90);jn(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"])}parse(r,n,i){const a=c=>c===0?7:c;switch(n){case"i":case"ii":return Pl(n.length,r);case"io":return i.ordinalNumber(r,{unit:"day"});case"iii":return Hl(i.day(r,{width:"abbreviated",context:"formatting"})||i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"}),a);case"iiiii":return Hl(i.day(r,{width:"narrow",context:"formatting"}),a);case"iiiiii":return Hl(i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"}),a);case"iiii":default:return Hl(i.day(r,{width:"wide",context:"formatting"})||i.day(r,{width:"abbreviated",context:"formatting"})||i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"}),a)}}validate(r,n){return n>=1&&n<=7}set(r,n,i){return r=UJe(r,i),r.setHours(0,0,0,0),r}}class qJe extends Sa{constructor(){super(...arguments);jn(this,"priority",80);jn(this,"incompatibleTokens",["b","B","H","k","t","T"])}parse(r,n,i){switch(n){case"a":case"aa":case"aaa":return i.dayPeriod(r,{width:"abbreviated",context:"formatting"})||i.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaaa":return i.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaa":default:return i.dayPeriod(r,{width:"wide",context:"formatting"})||i.dayPeriod(r,{width:"abbreviated",context:"formatting"})||i.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,i){return r.setHours(FY(i),0,0,0),r}}class GJe extends Sa{constructor(){super(...arguments);jn(this,"priority",80);jn(this,"incompatibleTokens",["a","B","H","k","t","T"])}parse(r,n,i){switch(n){case"b":case"bb":case"bbb":return i.dayPeriod(r,{width:"abbreviated",context:"formatting"})||i.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbbb":return i.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbb":default:return i.dayPeriod(r,{width:"wide",context:"formatting"})||i.dayPeriod(r,{width:"abbreviated",context:"formatting"})||i.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,i){return r.setHours(FY(i),0,0,0),r}}class HJe extends Sa{constructor(){super(...arguments);jn(this,"priority",80);jn(this,"incompatibleTokens",["a","b","t","T"])}parse(r,n,i){switch(n){case"B":case"BB":case"BBB":return i.dayPeriod(r,{width:"abbreviated",context:"formatting"})||i.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBBB":return i.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBB":default:return i.dayPeriod(r,{width:"wide",context:"formatting"})||i.dayPeriod(r,{width:"abbreviated",context:"formatting"})||i.dayPeriod(r,{width:"narrow",context:"formatting"})}}set(r,n,i){return r.setHours(FY(i),0,0,0),r}}class WJe extends Sa{constructor(){super(...arguments);jn(this,"priority",70);jn(this,"incompatibleTokens",["H","K","k","t","T"])}parse(r,n,i){switch(n){case"h":return hl(Gl.hour12h,r);case"ho":return i.ordinalNumber(r,{unit:"hour"});default:return Pl(n.length,r)}}validate(r,n){return n>=1&&n<=12}set(r,n,i){const a=r.getHours()>=12;return a&&i<12?r.setHours(i+12,0,0,0):!a&&i===12?r.setHours(0,0,0,0):r.setHours(i,0,0,0),r}}class KJe extends Sa{constructor(){super(...arguments);jn(this,"priority",70);jn(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(r,n,i){switch(n){case"H":return hl(Gl.hour23h,r);case"Ho":return i.ordinalNumber(r,{unit:"hour"});default:return Pl(n.length,r)}}validate(r,n){return n>=0&&n<=23}set(r,n,i){return r.setHours(i,0,0,0),r}}class YJe extends Sa{constructor(){super(...arguments);jn(this,"priority",70);jn(this,"incompatibleTokens",["h","H","k","t","T"])}parse(r,n,i){switch(n){case"K":return hl(Gl.hour11h,r);case"Ko":return i.ordinalNumber(r,{unit:"hour"});default:return Pl(n.length,r)}}validate(r,n){return n>=0&&n<=11}set(r,n,i){return r.getHours()>=12&&i<12?r.setHours(i+12,0,0,0):r.setHours(i,0,0,0),r}}class ZJe extends Sa{constructor(){super(...arguments);jn(this,"priority",70);jn(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(r,n,i){switch(n){case"k":return hl(Gl.hour24h,r);case"ko":return i.ordinalNumber(r,{unit:"hour"});default:return Pl(n.length,r)}}validate(r,n){return n>=1&&n<=24}set(r,n,i){const a=i<=24?i%24:i;return r.setHours(a,0,0,0),r}}class XJe extends Sa{constructor(){super(...arguments);jn(this,"priority",60);jn(this,"incompatibleTokens",["t","T"])}parse(r,n,i){switch(n){case"m":return hl(Gl.minute,r);case"mo":return i.ordinalNumber(r,{unit:"minute"});default:return Pl(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,i){return r.setMinutes(i,0,0),r}}class QJe extends Sa{constructor(){super(...arguments);jn(this,"priority",50);jn(this,"incompatibleTokens",["t","T"])}parse(r,n,i){switch(n){case"s":return hl(Gl.second,r);case"so":return i.ordinalNumber(r,{unit:"second"});default:return Pl(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,i){return r.setSeconds(i,0),r}}class JJe extends Sa{constructor(){super(...arguments);jn(this,"priority",30);jn(this,"incompatibleTokens",["t","T"])}parse(r,n){const i=a=>Math.trunc(a*Math.pow(10,-n.length+3));return Hl(Pl(n.length,r),i)}set(r,n,i){return r.setMilliseconds(i),r}}class eet extends Sa{constructor(){super(...arguments);jn(this,"priority",10);jn(this,"incompatibleTokens",["t","T","x"])}parse(r,n){switch(n){case"X":return Zp(Yp.basicOptionalMinutes,r);case"XX":return Zp(Yp.basic,r);case"XXXX":return Zp(Yp.basicOptionalSeconds,r);case"XXXXX":return Zp(Yp.extendedOptionalSeconds,r);case"XXX":default:return Zp(Yp.extended,r)}}set(r,n,i){return n.timestampIsSet?r:to(r,r.getTime()-Tv(r)-i)}}class tet extends Sa{constructor(){super(...arguments);jn(this,"priority",10);jn(this,"incompatibleTokens",["t","T","X"])}parse(r,n){switch(n){case"x":return Zp(Yp.basicOptionalMinutes,r);case"xx":return Zp(Yp.basic,r);case"xxxx":return Zp(Yp.basicOptionalSeconds,r);case"xxxxx":return Zp(Yp.extendedOptionalSeconds,r);case"xxx":default:return Zp(Yp.extended,r)}}set(r,n,i){return n.timestampIsSet?r:to(r,r.getTime()-Tv(r)-i)}}class ret extends Sa{constructor(){super(...arguments);jn(this,"priority",40);jn(this,"incompatibleTokens","*")}parse(r){return ESe(r)}set(r,n,i){return[to(r,i*1e3),{timestampIsSet:!0}]}}class net extends Sa{constructor(){super(...arguments);jn(this,"priority",20);jn(this,"incompatibleTokens","*")}parse(r){return ESe(r)}set(r,n,i){return[to(r,i),{timestampIsSet:!0}]}}const iet={G:new wJe,y:new SJe,Y:new EJe,R:new TJe,u:new AJe,Q:new kJe,q:new IJe,M:new jJe,L:new CJe,w:new NJe,I:new LJe,d:new OJe,D:new FJe,E:new BJe,e:new zJe,c:new $Je,i:new VJe,a:new qJe,b:new GJe,B:new HJe,h:new WJe,H:new KJe,K:new YJe,k:new ZJe,m:new XJe,s:new QJe,S:new JJe,X:new eet,x:new tet,t:new ret,T:new net},set=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,aet=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,oet=/^'([^]*?)'?$/,cet=/''/g,uet=/\S/,det=/[a-zA-Z]/;function het(t,e,r,n){var P,C,L,O;const i=fJe(),a=i.locale??b5,c=i.firstWeekContainsDate??((C=(P=i.locale)==null?void 0:P.options)==null?void 0:C.firstWeekContainsDate)??1,d=i.weekStartsOn??((O=(L=i.locale)==null?void 0:L.options)==null?void 0:O.weekStartsOn)??0;if(e==="")return t===""?oi(r):to(r,NaN);const p={firstWeekContainsDate:c,weekStartsOn:d,locale:a},l=[new bJe],g=e.match(aet).map(F=>{const $=F[0];if($ in XG){const G=XG[$];return G(F,a.formatLong)}return F}).join("").match(set),v=[];for(let F of g){bSe(F)&&QG(F,e,t),vSe(F)&&QG(F,e,t);const $=F[0],G=iet[$];if(G){const{incompatibleTokens:W}=G;if(Array.isArray(W)){const Q=v.find(ee=>W.includes(ee.token)||ee.token===$);if(Q)throw new RangeError(`The format string mustn't contain \`${Q.fullToken}\` and \`${F}\` at the same time`)}else if(G.incompatibleTokens==="*"&&v.length>0)throw new RangeError(`The format string mustn't contain \`${F}\` and any other token at the same time`);v.push({token:$,fullToken:F});const Z=G.run(t,F,a.match,p);if(!Z)return to(r,NaN);l.push(Z.setter),t=Z.rest}else{if($.match(det))throw new RangeError("Format string contains an unescaped latin alphabet character `"+$+"`");if(F==="''"?F="'":$==="'"&&(F=fet(F)),t.indexOf(F)===0)t=t.slice(F.length);else return to(r,NaN)}}if(t.length>0&&uet.test(t))return to(r,NaN);const E=l.map(F=>F.priority).sort((F,$)=>$-F).filter((F,$,G)=>G.indexOf(F)===$).map(F=>l.filter($=>$.priority===F).sort(($,G)=>G.subPriority-$.subPriority)).map(F=>F[0]);let T=oi(r);if(isNaN(T.getTime()))return to(r,NaN);const j={};for(const F of E){if(!F.validate(T,p))return to(r,NaN);const $=F.set(T,j,p);Array.isArray($)?(T=$[0],Object.assign(j,$[1])):T=$}return to(r,T)}function fet(t){return t.match(oet)[1].replace(cet,"'")}function mT(t){return+oi(t)2)return e;if(/:/.test(r[0])?n=r[0]:(e.date=r[0],n=r[1],PD.timeZoneDelimiter.test(e.date)&&(e.date=t.split(PD.timeZoneDelimiter)[0],n=t.substr(e.date.length,t.length))),n){const i=PD.timezone.exec(n);i?(e.time=n.replace(i[1],""),e.timezone=i[1]):e.time=n}return e}function bet(t,e){const r=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+e)+"})|(\\d{2}|[+-]\\d{"+(2+e)+"})$)"),n=t.match(r);if(!n)return{year:NaN,restDateString:""};const i=n[1]?parseInt(n[1]):null,a=n[2]?parseInt(n[2]):null;return{year:a===null?i:a*100,restDateString:t.slice((n[1]||n[2]).length)}}function wet(t,e){if(e===null)return new Date(NaN);const r=t.match(yet);if(!r)return new Date(NaN);const n=!!r[4],i=sI(r[1]),a=sI(r[2])-1,c=sI(r[3]),d=sI(r[4]),p=sI(r[5])-1;if(n)return Cet(e,d,p)?Aet(e,d,p):new Date(NaN);{const l=new Date(0);return!Iet(e,a,c)||!jet(e,i)?new Date(NaN):(l.setUTCFullYear(e,a,Math.max(i,c)),l)}}function sI(t){return t?parseInt(t):1}function Eet(t){const e=t.match(xet);if(!e)return NaN;const r=AU(e[1]),n=AU(e[2]),i=AU(e[3]);return Pet(r,n,i)?r*PY+n*CY+i*1e3:NaN}function AU(t){return t&&parseFloat(t.replace(",","."))||0}function Tet(t){if(t==="Z")return 0;const e=t.match(_et);if(!e)return 0;const r=e[1]==="+"?-1:1,n=parseInt(e[2]),i=e[3]&&parseInt(e[3])||0;return Net(n,i)?r*(n*PY+i*CY):NaN}function Aet(t,e,r){const n=new Date(0);n.setUTCFullYear(t,0,4);const i=n.getUTCDay()||7,a=(e-1)*7+r+1-i;return n.setUTCDate(n.getUTCDate()+a),n}const ket=[31,null,31,30,31,30,31,31,30,31,30,31];function kSe(t){return t%400===0||t%4===0&&t%100!==0}function Iet(t,e,r){return e>=0&&e<=11&&r>=1&&r<=(ket[e]||(kSe(t)?29:28))}function jet(t,e){return e>=1&&e<=(kSe(t)?366:365)}function Cet(t,e,r){return e>=1&&e<=53&&r>=0&&r<=6}function Pet(t,e,r){return t===24?e===0&&r===0:r>=0&&r<60&&e>=0&&e<60&&t>=0&&t<25}function Net(t,e){return e>=0&&e<=59}function kU(t,e){const r=oi(t),n=r.getFullYear(),i=r.getDate(),a=to(t,0);a.setFullYear(n,e,15),a.setHours(0,0,0,0);const c=hJe(a);return r.setMonth(e,Math.min(i,c)),r}function ble(t,e){const r=oi(t);return isNaN(+r)?to(t,NaN):(r.setFullYear(e),r)}function Ret(t,e){return af(t,-e)}const Let=()=>{const{user:t}=_i(),e=qa(),[r,n]=N.useState([]),[i,a]=N.useState(0),[c,d]=N.useState(!1),[p,l]=N.useState(null),g=N.useRef(null);N.useEffect(()=>{g.current=p},[p]),N.useEffect(()=>{if(!t)return;const P=`notification_last_read_${t.id}`,C=localStorage.getItem(P);C&&!g.current&&(g.current=C,l(C));const L=`nb_cache_${t.id}`,O=60*1e3,F=async()=>{try{const Q=sessionStorage.getItem(L);if(Q){const ee=JSON.parse(Q);if(ee.ts&&Date.now()-ee.ts{n(W);const Z=g.current?new Date(g.current):null,Q=W.filter(ee=>Z?new Date(ee.created_at)>Z:!0);a(Q.length)};F();const G=Be.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},W=>{const Z=W.new;n(ee=>{const ie=[Z,...ee].slice(0,20);try{sessionStorage.setItem(L,JSON.stringify({ts:Date.now(),data:ie}))}catch{}return ie});const Q=g.current?new Date(g.current):null;(!Q||new Date(Z.created_at)>Q)&&a(ee=>ee+1),Notification.permission==="granted"&&new Notification(Z.title,{body:Z.body,icon:"/favicon.ico"})}).subscribe();return()=>{Be.removeChannel(G)}},[t]);const v=P=>{const C=P.toLowerCase();return C.includes("community")||C.includes("post")?ug:C.includes("academy")||C.includes("video")?rj:C.includes("template")?A4:C.includes("event")?Cl:C.includes("newsletter")?dve:C.includes("brokerage")?J_e:C.includes("swag")||C.includes("social")?Jm:C.includes("toolbox")||C.includes("tool")?rK:C.includes("brief")?va:ug},E=P=>{d(!1),P.url&&P.url!=="/"&&e(P.url)},T=()=>{if(!t)return;const P=new Date().toISOString(),C=`notification_last_read_${t.id}`;localStorage.setItem(C,P),l(P),a(0)},j=P=>{d(P),P&&i>0&&T()};return s.jsxs(UP,{open:c,onOpenChange:j,children:[s.jsx(VP,{asChild:!0,children:s.jsxs(Jt,{variant:"ghost",size:"icon",className:"relative",children:[s.jsx(PP,{className:"h-5 w-5"}),i>0&&s.jsx(Js,{variant:"destructive",className:"absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 text-xs",children:i>9?"9+":i})]})}),s.jsxs(xA,{align:"end",className:"w-80",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[s.jsx("span",{className:"font-semibold",children:"Notifications"}),r.length>0&&s.jsx(Jt,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:T,children:"Mark all read"})]}),s.jsx(Eg,{className:"h-[300px]",children:r.length===0?s.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):r.map(P=>{const C=v(P.title);return s.jsxs(lh,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>E(P),children:[s.jsx("div",{className:"flex-shrink-0 mt-0.5",children:s.jsx(C,{className:"h-4 w-4 text-primary"})}),s.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[s.jsx("span",{className:"font-medium text-sm",children:P.title}),s.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:P.body}),s.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:wSe(new Date(P.created_at),{addSuffix:!0})})]})]},P.id)})})]})]})};function Det(t){return t!=null&&t.length?t.find(e=>e.is_active&&e.mls_provider_id&&!e.no_mls_mode)||t[0]:null}function ISe(){const{user:t}=_i(),{data:e,isLoading:r}=jr({queryKey:["agent-lead-site",t==null?void 0:t.id],queryFn:async()=>{const{data:n,error:i}=await Be.from("lead_sites").select("id, subdomain_slug, custom_domain, site_title, is_active, plan_tier, mls_provider_id, no_mls_mode, mls_agent_id, mls_agent_key, mls_office_id, mls_service_cities, mls_disclaimer_text, brokerage_legal_name").eq("agent_id",t.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(10);if(i)throw i;return Det(n)},enabled:!!t,staleTime:5*60*1e3});return{leadSite:e??null,hasLeadSite:!!e,isFreePlan:(e==null?void 0:e.plan_tier)==="free_luxury",hasIdx:!!(e!=null&&e.mls_provider_id)&&!(e!=null&&e.no_mls_mode),isLoading:r,siteUrl:e?e.custom_domain?`https://${e.custom_domain}`:`https://${e.subdomain_slug}.thelocalmove.com`:null}}function jSe(t=!0){const{user:e}=_i(),{data:r,isLoading:n}=jr({queryKey:["free-lead-site-offer",e==null?void 0:e.id],enabled:!!e&&t,staleTime:5*60*1e3,queryFn:async()=>{const{data:i}=await Be.from("profiles").select("brokerage_id").eq("id",e.id).maybeSingle();if(!(i!=null&&i.brokerage_id))return null;const{data:a}=await Be.from("lead_site_brokerage_offers").select("*").eq("brokerage_id",i.brokerage_id).eq("enabled",!0).maybeSingle();return a??null}});return{offer:r??null,hasOffer:!!r,isLoading:n}}const Met="coaching_access";function Oet(){const{user:t,loading:e,isAdmin:r,isCoach:n}=_i(),{data:i,isLoading:a}=jr({queryKey:["coaching-access",t==null?void 0:t.id],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const[c,d]=await Promise.all([Be.from("coaching_assignments").select("id").eq("agent_id",t.id).eq("status","active").limit(1),Be.from("feature_entitlements").select("enabled, expires_at").eq("user_id",t.id).eq("feature_key",Met).maybeSingle()]),p=(c.data||[]).length>0,l=d.data,g=!!(l!=null&&l.enabled)&&(!l.expires_at||new Date(l.expires_at).getTime()>Date.now());return{hasAssignment:p,entitled:g}}});return{hasAccess:!!(r||n||i!=null&&i.hasAssignment||i!=null&&i.entitled),hasAssignment:!!(i!=null&&i.hasAssignment),isLoading:e||a}}const Ns=Be,xKt=[{value:"contract",label:"Under contract"},{value:"inspection",label:"Inspection / due diligence"},{value:"closing",label:"Closing"},{value:"closed",label:"Closed"}];function _Kt(t){return t.total_items===0?"not_started":t.rejected_items>0?"changes_requested":t.approved_items>=t.total_items?"compliant":"in_review"}const vKt={not_started:"Not started",in_review:"In review",changes_requested:"Changes requested",compliant:"Compliant"};function Fet(){return jr({queryKey:["transaction-admin-seats"],queryFn:async()=>{const{data:t}=await Be.auth.getUser();if(!t.user)return[];const{data:e,error:r}=await Ns.from("brokerage_transaction_admins").select("brokerage_id").eq("user_id",t.user.id);if(r)throw r;return e||[]}})}function bKt(t){return jr({queryKey:["transaction-admins",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ns.from("brokerage_transaction_admins").select("id, user_id, created_at").eq("brokerage_id",t);if(r)throw r;const n=e||[];if(n.length===0)return[];const{data:i}=await Ns.from("profiles").select("id, name, email").in("id",n.map(c=>c.user_id)),a=new Map((i||[]).map(c=>[c.id,{name:c.name??null,email:c.email??null}]));return n.map(c=>{var d,p;return{...c,name:((d=a.get(c.user_id))==null?void 0:d.name)??null,email:((p=a.get(c.user_id))==null?void 0:p.email)??null}})}})}function wKt(){const t=Ur();return zr({mutationFn:async({brokerageId:e,userId:r})=>{const{error:n}=await Ns.from("brokerage_transaction_admins").insert({brokerage_id:e,user_id:r});if(n)throw n},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["transaction-admins",r.brokerageId]})})}function SKt(){const t=Ur();return zr({mutationFn:async({id:e})=>{const{error:r}=await Ns.from("brokerage_transaction_admins").delete().eq("id",e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["transaction-admins",r.brokerageId]})})}function EKt(t){return jr({queryKey:["compliance-settings",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ns.from("brokerage_compliance_settings").select("*").eq("brokerage_id",t).maybeSingle();if(r)throw r;return e}})}function TKt(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Ns.from("brokerage_compliance_settings").upsert(e,{onConflict:"brokerage_id"});if(r)throw r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["compliance-settings",r.brokerage_id]}),t.invalidateQueries({queryKey:["compliance-deals"]})}})}function AKt(t){return jr({queryKey:["compliance-templates",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ns.from("brokerage_checklist_templates").select("*").eq("brokerage_id",t).order("created_at",{ascending:!0});if(r)throw r;return e||[]}})}function kKt(t){return jr({queryKey:["compliance-template-items",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ns.from("brokerage_checklist_template_items").select("*").eq("template_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]}})}function IKt(){const t=Ur();return zr({mutationFn:async e=>{if(e.id){const{error:i}=await Ns.from("brokerage_checklist_templates").update(e).eq("id",e.id);if(i)throw i;return e.id}const{data:r,error:n}=await Ns.from("brokerage_checklist_templates").insert(e).select("id").single();if(n)throw n;return r.id},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-templates",r.brokerage_id]})})}function jKt(){const t=Ur();return zr({mutationFn:async({id:e})=>{const{error:r}=await Ns.from("brokerage_checklist_templates").delete().eq("id",e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-templates",r.brokerageId]})})}function CKt(){const t=Ur();return zr({mutationFn:async e=>{if(e.id){const{error:n}=await Ns.from("brokerage_checklist_template_items").update(e).eq("id",e.id);if(n)throw n;return}const{error:r}=await Ns.from("brokerage_checklist_template_items").insert(e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-template-items",r.template_id]})})}function PKt(){const t=Ur();return zr({mutationFn:async({id:e})=>{const{error:r}=await Ns.from("brokerage_checklist_template_items").delete().eq("id",e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-template-items",r.templateId]})})}function NKt(t){return jr({queryKey:["compliance-deals",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ns.rpc("get_brokerage_compliance_deals",{_brokerage_id:t});if(r)throw r;return e||[]}})}function RKt(t){return jr({queryKey:["deal-compliance-items",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ns.from("deal_compliance_items").select("*").eq("deal_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]}})}function LKt(t){return jr({queryKey:["deal-compliance-events",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ns.from("deal_compliance_events").select("*").eq("deal_id",t).order("created_at",{ascending:!1}).limit(200);if(r)throw r;return e||[]}})}async function YP(t){var r;const{data:e}=await Be.auth.getUser();await Ns.from("deal_compliance_events").insert({deal_id:t.dealId,brokerage_id:t.brokerageId??null,item_id:t.itemId??null,actor_user_id:((r=e.user)==null?void 0:r.id)??null,event_type:t.eventType,detail:t.detail??null})}function DKt(){const t=Ur();return zr({mutationFn:async({item:e,status:r,note:n})=>{var c;const{data:i}=await Be.auth.getUser(),{error:a}=await Ns.from("deal_compliance_items").update({status:r,review_note:n??null,reviewed_by:((c=i.user)==null?void 0:c.id)??null,reviewed_at:new Date().toISOString()}).eq("id",e.id);if(a)throw a;await YP({dealId:e.deal_id,brokerageId:e.brokerage_id,itemId:e.id,eventType:r==="approved"?"item_approved":r==="rejected"?"item_rejected":"item_updated",detail:n?`${e.title}: ${n}`:e.title})},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-compliance-items",r.item.deal_id]}),t.invalidateQueries({queryKey:["deal-compliance-events",r.item.deal_id]}),t.invalidateQueries({queryKey:["compliance-deals"]})}})}function MKt(){const t=Ur();return zr({mutationFn:async({dealId:e,brokerageId:r,templateId:n,deal:i})=>{const{data:a,error:c}=await Ns.from("brokerage_checklist_template_items").select("*").eq("template_id",n).order("sort_order",{ascending:!0});if(c)throw c;const d=(g,v)=>{if(!g)return null;const[E,T,j]=g.split(/[-/T]/).map(Number);return new Date(Date.UTC(E,T-1,j+(v||0))).toISOString().slice(0,10)},p=(a||[]).map(g=>({deal_id:e,brokerage_id:r,template_item_id:g.id,title:g.title,description:g.description,phase:g.phase,requires_document:g.requires_document,required_for_closing:g.required_for_closing,due_date:g.due_anchor==="contract_date"?d(i==null?void 0:i.contract_date,g.due_offset_days):g.due_anchor==="target_close_date"?d(i==null?void 0:i.target_close_date,g.due_offset_days):null,sort_order:g.sort_order}));if(p.length===0)return;const{error:l}=await Ns.from("deal_compliance_items").insert(p);if(l)throw l;await YP({dealId:e,brokerageId:r,eventType:"checklist_applied",detail:`${p.length} items added`})},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-compliance-items",r.dealId]}),t.invalidateQueries({queryKey:["deal-compliance-events",r.dealId]}),t.invalidateQueries({queryKey:["compliance-deals"]})}})}function OKt(t){return jr({queryKey:["deal-compliance-files",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ns.from("deal_files").select("id, deal_id, compliance_item_id, file_name, file_size, storage_path, version_no, is_current, created_at, owner_user_id").eq("deal_id",t).not("compliance_item_id","is",null).order("version_no",{ascending:!1});if(r)throw r;return e||[]}})}function FKt(){const t=Ur();return zr({mutationFn:async({item:e,file:r})=>{var v,E;const{data:n}=await Be.auth.getUser(),i=(v=n.user)==null?void 0:v.id;if(!i)throw new Error("Not signed in");const{data:a}=await Ns.from("deal_files").select("id, version_no").eq("compliance_item_id",e.id).order("version_no",{ascending:!1}).limit(1),c=(((E=a==null?void 0:a[0])==null?void 0:E.version_no)||0)+1,d=r.name.split(".").pop(),p=`${i}/${e.deal_id}/${crypto.randomUUID()}.${d}`,{error:l}=await Be.storage.from("deal-files").upload(p,r);if(l)throw l;a!=null&&a.length&&await Ns.from("deal_files").update({is_current:!1}).eq("compliance_item_id",e.id);const{error:g}=await Ns.from("deal_files").insert({deal_id:e.deal_id,owner_user_id:i,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:p,compliance_item_id:e.id,version_no:c,is_current:!0});if(g)throw g;await Ns.from("deal_compliance_items").update({status:"submitted",review_note:null,reviewed_at:null,reviewed_by:null}).eq("id",e.id),await YP({dealId:e.deal_id,brokerageId:e.brokerage_id,itemId:e.id,eventType:"document_uploaded",detail:`${e.title} — ${r.name} (v${c})`})},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-compliance-files",r.item.deal_id]}),t.invalidateQueries({queryKey:["deal-compliance-items",r.item.deal_id]}),t.invalidateQueries({queryKey:["deal-compliance-events",r.item.deal_id]}),t.invalidateQueries({queryKey:["deal-files",r.item.deal_id]}),t.invalidateQueries({queryKey:["compliance-deals"]})}})}async function BKt(t){const{data:e,error:r}=await Be.storage.from("deal-files").createSignedUrl(t,3600);if(r)throw r;window.open(e.signedUrl,"_blank","noopener,noreferrer")}function zKt(t){return jr({queryKey:["deal-compliance-messages",t],enabled:!!t,refetchInterval:3e4,queryFn:async()=>{const{data:e,error:r}=await Ns.from("deal_compliance_messages").select("*").eq("deal_id",t).order("created_at",{ascending:!0});if(r)throw r;const n=e||[],i=Array.from(new Set(n.map(d=>d.sender_user_id)));if(i.length===0)return n;const{data:a}=await Ns.from("profiles").select("id, name").in("id",i),c=new Map((a||[]).map(d=>[d.id,d.name??null]));return n.map(d=>({...d,sender_name:c.get(d.sender_user_id)??null}))}})}function $Kt(){const t=Ur();return zr({mutationFn:async({dealId:e,brokerageId:r,body:n,senderRole:i,itemId:a})=>{var g;const{data:c}=await Be.auth.getUser(),d=(g=c.user)==null?void 0:g.id;if(!d)throw new Error("Not signed in");const{data:p,error:l}=await Ns.from("deal_compliance_messages").insert({deal_id:e,brokerage_id:r,sender_user_id:d,sender_role:i,item_id:a??null,body:n.trim()}).select("id").single();if(l)throw l;try{await Be.functions.invoke("compliance-message-notify",{body:{messageId:p.id}})}catch(v){console.error("compliance message notify failed",v)}return p.id},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["deal-compliance-messages",r.dealId]})})}function UKt(){const t=Ur();return zr({mutationFn:async({dealId:e,senderRole:r})=>{const{error:n}=await Ns.from("deal_compliance_messages").update({read_at:new Date().toISOString()}).eq("deal_id",e).neq("sender_role",r).is("read_at",null);if(n)throw n},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["deal-compliance-messages",r.dealId]})})}function VKt(t){return jr({queryKey:["brokerage-agent-roster",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ns.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",t).order("name",{ascending:!0});if(r)throw r;return e||[]}})}function qKt(t){return jr({queryKey:["agent-pipeline-stages",t],enabled:!!t,queryFn:async()=>{const e=async()=>{const{data:n,error:i}=await Ns.from("deal_pipeline_stages").select("id, name, sort_order, default_probability").eq("owner_user_id",t).order("sort_order",{ascending:!0});if(i)throw i;return n||[]};let r=await e();if(r.length===0){const{error:n}=await Ns.rpc("initialize_deal_pipeline_stages",{p_user_id:t});n||(r=await e())}return r}})}function GKt(){const t=Ur();return zr({mutationFn:async e=>{const r=e.price!=null&&e.commissionPercentage!=null?Math.round(e.price*(e.commissionPercentage/100)*100)/100:null,{data:n,error:i}=await Ns.from("deal_pipeline").insert({owner_user_id:e.ownerUserId,deal_name:e.dealName.trim(),deal_type:e.dealType,stage_id:e.stageId,property_address:e.propertyAddress||null,city:e.city||null,state:e.state||null,zip_code:e.zipCode||null,contract_date:e.contractDate||null,target_close_date:e.targetCloseDate||null,actual_close_date:e.actualCloseDate||null,expected_price:e.price??null,sale_price:e.actualCloseDate?e.price??null:null,commission_percentage:e.commissionPercentage??null,expected_commission:r,notes:e.notes||null}).select("id").single();if(i)throw i;const a=n.id;try{await Ns.rpc("ensure_deal_compliance",{_deal_id:a})}catch(c){console.error("ensure_deal_compliance failed",c)}return await YP({dealId:a,brokerageId:e.brokerageId,eventType:"deal_added_by_staff",detail:"Deal added by brokerage staff for the agent's pipeline"}),a},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["compliance-deals",r.brokerageId]}),t.invalidateQueries({queryKey:["deal-pipeline"]})}})}function HKt(t){return jr({queryKey:["staff-deal-detail",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await Ns.from("deal_pipeline").select("id, owner_user_id, deal_name, deal_type, stage_id, property_address, city, state, zip_code, contract_date, target_close_date, actual_close_date, expected_price, sale_price, commission_percentage, notes").eq("id",t).maybeSingle();if(r)throw r;return e||null}})}function WKt(){const t=Ur();return zr({mutationFn:async e=>{const r=e.price!=null&&e.commissionPercentage!=null?Math.round(e.price*(e.commissionPercentage/100)*100)/100:null,{error:n}=await Ns.from("deal_pipeline").update({deal_name:e.dealName.trim(),deal_type:e.dealType,stage_id:e.stageId,property_address:e.propertyAddress||null,city:e.city||null,state:e.state||null,zip_code:e.zipCode||null,contract_date:e.contractDate||null,target_close_date:e.targetCloseDate||null,actual_close_date:e.actualCloseDate||null,expected_price:e.price??null,sale_price:e.actualCloseDate?e.price??null:null,commission_percentage:e.commissionPercentage??null,expected_commission:r,notes:e.notes||null}).eq("id",e.dealId);if(n)throw n;return await YP({dealId:e.dealId,brokerageId:e.brokerageId,eventType:"deal_updated_by_staff",detail:"Deal details updated by brokerage staff"}),e.dealId},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["compliance-deals",r.brokerageId]}),t.invalidateQueries({queryKey:["staff-deal-detail",r.dealId]}),t.invalidateQueries({queryKey:["deal-pipeline"]}),t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-compliance-events",r.dealId]})}})}const S5=[{id:"home",label:"Home",icon:cve,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:cg,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:ZW,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:jl,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:NP,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:rT,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:Hj,description:"Training, programs and coaching",accent:"nav-academy"},{id:"mainstage",label:"Main Stage",icon:hve,route:"/main-stage",accent:"nav-mainstage"},{id:"events",label:"Events",icon:pve,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:Z4e,route:"/apps",accent:"nav-apps"},{id:"team",label:"Team",icon:Dc,route:"/team",description:"Your team hub — production, pond and resources",accent:"nav-team",visible:t=>t.isOnTeam&&!t.isAdmin&&!t.isBrokerageManager},{id:"brokerage",label:"Brokerage",icon:lve,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:t=>!t.isAdmin&&(!!t.brokerageId||t.isBrokerageManager||t.isOnTeam)},{id:"more",label:"More",icon:H4e,description:"Community, marketplace and help",accent:"nav-more"}],Su=t=>e=>e.hasPermission(t),Bet=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:$4e,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:Su("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:va,description:"Private portals for buyers and sellers",primaryCategory:"crm",section:"Overview",searchKeywords:["portal","client portal"],displayOrder:20},{id:"contacts",label:"All Contacts",route:"/mission-control/contacts",icon:Dc,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:Su("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"contact-map",label:"Contact Map",route:"/mission-control/sphere-map",icon:Va,iconTone:"red",description:"See your sphere on a map — boundaries, farms and prospects",primaryCategory:"crm",section:"Contacts",visible:Su("contacts"),searchKeywords:["contact map","sphere map","map","boundaries","property lines","farm","neighborhood","prospects"],displayOrder:35},{id:"relationship-report",label:"Relationship Report",route:"/mission-control/relationship-scorecard",icon:Use,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:Su("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:y5e,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:Su("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:nF,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:Su("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:Wse,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:Su("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"property-intelligence",label:"Property Intelligence",route:"/mission-control/property-intelligence",icon:jl,description:"Enrich property data for your contacts",primaryCategory:"crm",section:"Contacts",visible:t=>t.isAdmin,searchKeywords:["property","zillow","enrichment","intelligence","home value"],displayOrder:75},{id:"touchplans",label:"TouchPlans",route:"/mission-control/plans",icon:ig,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:Su("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:aF,description:"Automated drip campaigns that pause when they reply",primaryCategory:"crm",section:"Follow-Up",badge:"beta",searchKeywords:["drip","automation","campaign"],displayOrder:90},{id:"email-templates",label:"Email Templates",route:"/email-campaigns/templates",icon:rs,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:p5e,description:"Buying and selling signals from your database",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["signals","intent","hot leads"],displayOrder:110},{id:"popbys",label:"Popbys",route:"/mission-control/popbys",icon:Jm,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:Su("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:ZW,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:Su("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:jq,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:Su("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"forms",label:"Forms Library",route:"/mission-control/forms",icon:W4e,description:"Your PDF form templates, filled from any deal",primaryCategory:"deals",section:"Pipeline",visible:Su("pipeline"),searchKeywords:["forms","pdf","templates","contracts","documents"],displayOrder:145},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:b5e,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:Su("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:Gj,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:Su("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"my-calendar",label:"My Calendar",route:"/mission-control/calendar",icon:ig,description:"Every appointment, deadline and task in one view",primaryCategory:"crm",section:"Overview",visible:()=>!0,searchKeywords:["calendar","schedule","agenda","google calendar","my calendar"],displayOrder:24},{id:"scheduler",label:"LevelUp Scheduler",route:"/mission-control/scheduler",icon:ig,description:"Share your booking link and sync your calendar",primaryCategory:"crm",section:"Overview",toolId:"scheduler",visible:()=>!0,searchKeywords:["scheduler","booking","calendar","appointments"],displayOrder:25},{id:"listing-exchange",label:"Listing Exchange",route:"/mission-control/listings",icon:jl,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:Su("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:f5e,description:"Build a polished listing presentation PDF",primaryCategory:"listings",section:"Win the Listing",toolId:"listing-presentation-studio",searchKeywords:["listing presentation","pdf","pitch"],displayOrder:20},{id:"listing-revival",label:"Listing Revival",route:"/apps/listing-revival",icon:sve,description:"Win expired and withdrawn listings",primaryCategory:"listings",section:"Win the Listing",toolId:"listing-revival",searchKeywords:["expired","revival","withdrawn"],displayOrder:30},{id:"fsbo-breakthrough",label:"By-Owner Breakthrough",route:"/apps/fsbo-breakthrough",icon:Do,description:"Convert for-sale-by-owner sellers",primaryCategory:"listings",section:"Win the Listing",toolId:"fsbo-breakthrough",searchKeywords:["fsbo","by owner"],displayOrder:40},{id:"cma",label:"CMA Reports",route:"/mission-control/cma",icon:eve,description:"Comparative market analysis for sellers",primaryCategory:"listings",section:"Win the Listing",toolId:"cma",visible:t=>t.hasLeadSiteMLS,searchKeywords:["cma","market analysis","pricing"],displayOrder:50},{id:"guest-book",label:"Guest Book",route:"/mission-control/guest-book",icon:jq,description:"Digital open house sign-in",primaryCategory:"listings",section:"Open Houses",toolId:"guest-book",searchKeywords:["open house","sign in","guest book"],displayOrder:60},{id:"listing-studio",label:"Listing Studio",route:"/mission-control/listing-studio",icon:Hse,description:"Marketing assets for a listing",primaryCategory:"listings",section:"Market the Listing",toolId:"listing-studio",searchKeywords:["listing marketing","flyer","just listed"],displayOrder:70},{id:"templates",label:"Templates",route:"/templates",icon:A4,description:"Ready-to-edit Canva templates",primaryCategory:"marketing",section:"Create",searchKeywords:["templates","canva","graphics"],displayOrder:10},{id:"staging-studio",label:"Staging Studio",route:"/apps/staging-studio",icon:v5e,description:"Virtually stage, declutter and brighten listing photos",primaryCategory:"marketing",section:"Create",toolId:"staging-studio",visible:t=>t.isAdmin||t.stagingStudioEnabled,searchKeywords:["staging","virtual staging","twilight","declutter","sky replacement","photo"],displayOrder:11},{id:"reviews",label:"Reviews",route:"/apps/reviews",icon:Bd,description:"Collect, showcase and reply to client reviews",primaryCategory:"marketing",section:"Create",searchKeywords:["reviews","agent reviews","google reviews","testimonials","reputation","review link","review page","ratings","video review"],displayOrder:12},{id:"marketing-studio",label:"Marketing Studio",route:"/marketing-studio",icon:Hse,description:"Create branded marketing assets",primaryCategory:"marketing",section:"Create",searchKeywords:["marketing studio","design","brand kit"],displayOrder:20},{id:"social-studio",label:"Social Studio",route:"/social-studio",icon:U6,description:"Post to all your social accounts from one composer",primaryCategory:"marketing",section:"Social & Content",searchKeywords:["social","posts","instagram","facebook","linkedin","google business","schedule","swag"],displayOrder:29},{id:"social-swag",label:"Social Swag",route:"/social-studio?tab=gallery",icon:U6,description:"Daily social posts you can publish in a tap",primaryCategory:"marketing",section:"Social & Content",searchKeywords:["social","posts","instagram","facebook"],displayOrder:30},{id:"weekly-reels",label:"Weekly Reels",route:"/weekly-reels",icon:Gse,description:"A fresh reel script every Monday",primaryCategory:"marketing",section:"Social & Content",toolId:"weekly-reels",visible:t=>t.hasWeeklyReels,searchKeywords:["reels","video script","instagram"],displayOrder:40},{id:"newsletter-pro",label:"Newsletter Pro",route:"/newsletters",icon:dve,description:"Send a branded monthly newsletter",primaryCategory:"marketing",section:"Email & Mail",badge:"new",toolId:"newsletter-pro",searchKeywords:["newsletter","email marketing"],displayOrder:50},{id:"mass-emails",label:"Mass Emails",route:"/admin/email-campaigns",icon:rs,description:"Email your whole database at once",primaryCategory:"marketing",section:"Email & Mail",toolId:"mass-emails",searchKeywords:["mass email","campaign","blast"],displayOrder:60},{id:"direct-mail",label:"Mail Studio",route:"/mission-control/direct-mail",icon:nF,description:"Postcards & letters via your thanks.io account",primaryCategory:"marketing",section:"Email & Mail",toolId:"direct-mail",searchKeywords:["postcard","direct mail","farming","letter","thanks.io","mail studio"],displayOrder:70},{id:"card-studio",label:"Card Studio",route:"/mission-control/card-studio",icon:Jm,description:"Send digital celebration cards",primaryCategory:"marketing",section:"Email & Mail",toolId:"card-studio",searchKeywords:["cards","birthday","anniversary"],displayOrder:80},{id:"video-library",label:"Video Library",route:"/mission-control/video-library",icon:rj,description:"All of your recorded videos",primaryCategory:"marketing",section:"Video",visible:Su("videos"),searchKeywords:["videos","library"],displayOrder:90},{id:"video-studio",label:"Video Studio",route:"/video-studio",icon:rj,description:"Record vertical or horizontal videos with a scrolling teleprompter",primaryCategory:"marketing",section:"Video",visible:Su("videos"),searchKeywords:["teleprompter","studio","reels","record video","social video"],displayOrder:95},{id:"quickvid",label:"Video Messages",route:"/video-studio",icon:rj,description:"Record a personal video and email or text it with a template",primaryCategory:"marketing",section:"Video",toolId:"quickvid",searchKeywords:["record video","video email","screen record"],displayOrder:100},{id:"reelflow",label:"ReelFlow",route:"/admin/beta/homereel",icon:Gse,description:"AI-assisted short-form video creation",primaryCategory:"marketing",section:"Video",toolId:"reelflow",searchKeywords:["reelflow","ai video","reels"],displayOrder:110},{id:"landing-pages",label:"Landing Pages",route:"/mission-control/landing-pages",icon:Yse,description:"Capture leads with focused landing pages",primaryCategory:"marketing",section:"Lead Capture",toolId:"landing-pages",searchKeywords:["landing page","lead capture","funnel"],displayOrder:120},{id:"buyer-match",label:"Buyer Match",route:"/mission-control/buyer-match",icon:Pq,description:"Turn a buyer's wish list into seller conversations",primaryCategory:"marketing",section:"Lead Capture",searchKeywords:["buyer match","buyer needs","seller leads","wish list"],displayOrder:125},{id:"smart-card",label:"Smart Card",route:"/mission-control/my-card",icon:Wse,description:"Your digital business card",primaryCategory:"marketing",section:"Lead Capture",toolId:"smart-card",searchKeywords:["digital card","business card","qr"],displayOrder:130},{id:"my-websites",label:"My Websites",route:"/websites",icon:e5e,description:"Every site you can edit: yours, your company and your team",primaryCategory:"websites",section:"My Website",visible:t=>t.hasLeadSite||t.isBrokerageManager||t.isTeamLeader||t.isAdmin,searchKeywords:["websites","my sites","edit website","company site","team site"],displayOrder:1},{id:"get-my-website",label:"Get My Website",route:"/get-my-website",icon:rT,description:"Claim the free site your brokerage offers",primaryCategory:"websites",section:"My Website",visible:t=>!t.hasLeadSite&&t.hasFreeSiteOffer,searchKeywords:["website","claim site","free site"],displayOrder:5},{id:"need-a-website",label:"Need a Website",route:"/need-a-website",icon:rT,description:"Request your free beta agent website",primaryCategory:"websites",section:"My Website",badge:"beta",visible:t=>!t.hasLeadSite&&!t.hasFreeSiteOffer,searchKeywords:["website","need a website","beta site","free website"],displayOrder:6},{id:"view-site",label:"View Site",route:t=>t.siteUrl||"#",icon:E4,description:"Open your live website",primaryCategory:"websites",section:"My Website",external:!0,openInNewTab:!0,visible:t=>t.hasLeadSite&&!!t.siteUrl,searchKeywords:["view site","live site"],displayOrder:10},{id:"edit-website",label:"Edit My Site",route:t=>`/my-website/${t.leadSiteId}/edit`,icon:c5e,description:"Site builder for pages, branding and content",primaryCategory:"websites",section:"My Website",visible:t=>t.hasLeadSite&&!!t.leadSiteId,searchKeywords:["edit website","site builder","pages"],displayOrder:20},{id:"brokerage-website",label:"Edit Company Site",route:"/brokerage/website",icon:jl,description:"Your company site: agents, listings, recruiting and leads",primaryCategory:"websites",section:"My Website",badge:"new",visible:t=>t.isBrokerageManager||t.isAdmin,searchKeywords:["website","company site","brokerage site","agents","roster"],displayOrder:24},{id:"team-website",label:"Edit Team Site",route:"/team/website",icon:Dc,description:"Your team site: members, listings and leads",primaryCategory:"websites",section:"My Website",badge:"new",visible:t=>t.isTeamLeader||t.isAdmin,searchKeywords:["team website","team site","team page"],displayOrder:26},{id:"mls-listings",label:"MLS Listings",route:"/my-website/mls-listings",icon:Do,description:"Control which listings appear on your site",primaryCategory:"websites",section:"My Website",visible:t=>t.hasLeadSite,searchKeywords:["mls","idx","listings on site"],displayOrder:30},{id:"market-reports",label:"Market Reports",route:"/my-website/market-report",icon:Gj,description:"Monthly market reports for your areas",primaryCategory:"websites",section:"My Website",visible:t=>t.hasLeadSite&&t.hasLeadSiteMLS,searchKeywords:["market report","stats"],displayOrder:40},{id:"website-activity",label:"Website Activity",route:"/mission-control/website-activity",icon:Use,description:"See who is browsing your site",primaryCategory:"websites",section:"My Website",visible:t=>t.hasLeadSite,searchKeywords:["website activity","visitors","analytics"],displayOrder:50},{id:"mobile-command",label:"Mobile Command",route:"/m",icon:U6,description:"The mobile-first agent console",primaryCategory:"websites",section:"My Website",visible:t=>t.hasLeadSite,searchKeywords:["mobile","command"],displayOrder:60},{id:"website-apps",label:"Website Apps",route:"/website-apps",icon:va,description:"Lead magnets, video greeter and more",primaryCategory:"websites",section:"Website Add-Ons",toolId:"website-apps",searchKeywords:["widgets","lead magnet","video greeter"],displayOrder:70},{id:"levelup-u",label:"LevelUp U",route:"/levelup-u",icon:Hj,description:"Structured courses and certifications",primaryCategory:"academy",section:"Learn",badge:"new",searchKeywords:["levelup u","courses","training"],displayOrder:10},{id:"academy",label:"Academy",route:"/academy",icon:eT,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:rK,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:pve,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:Yse,description:"Cohort programs like Reel Estate 90",primaryCategory:"academy",section:"Programs & Coaching",searchKeywords:["programs","reel estate 90","cohort"],displayOrder:50},{id:"coaching",label:"Coaching",route:"/coaching",icon:Hj,description:"Your coaching hub and calendar",primaryCategory:"academy",section:"Programs & Coaching",visible:t=>t.isCoach,searchKeywords:["coaching","coach hub"],displayOrder:60},{id:"my-coach",label:"Coaching",route:"/my-coach",icon:cg,description:"Sessions, goals and notes with your coach",primaryCategory:"academy",section:"Programs & Coaching",visible:t=>!t.isCoach&&(t.hasCoach||t.hasCoachingAccess),searchKeywords:["my coach","coaching","sessions","book session"],displayOrder:70},{id:"community",label:"Community",route:"/community",icon:ug,description:"Talk shop with other LevelUp members",primaryCategory:"more",section:"Community",badgeKey:"community",searchKeywords:["community","forum","posts"],displayOrder:10},{id:"wishlist",label:"Wishlist",route:"/wishlist",icon:r5e,description:"Request and vote on new features",primaryCategory:"more",section:"Community",badgeKey:"wishlist",searchKeywords:["wishlist","feature request"],displayOrder:20},{id:"facebook-group",label:"Facebook Group",route:"https://www.facebook.com/share/g/1CC6thti2V/",icon:rA,description:"Our private Facebook community",primaryCategory:"more",section:"Community",external:!0,openInNewTab:!0,searchKeywords:["facebook group"],displayOrder:30},{id:"marketplace",label:"Marketplace",route:"/marketplace",icon:mve,description:"Print and promo products",primaryCategory:"more",section:"The Goods",badge:"new",visible:t=>t.isMarketplaceEnabled,searchKeywords:["marketplace","shop","print"],displayOrder:40},{id:"reward-store",label:"Reward Store",route:"/reward-store",icon:sF,description:"Spend the points you have earned",primaryCategory:"more",section:"The Goods",searchKeywords:["rewards","points","store"],displayOrder:50},{id:"refer-friends",label:"Refer & Earn",route:"/refer-friends",icon:Jm,description:"Invite agents and earn rewards",primaryCategory:"more",section:"The Goods",searchKeywords:["referral","refer a friend"],displayOrder:60},{id:"support",label:"Support",route:"/support",icon:t5e,description:"Get help from the LevelUp team",primaryCategory:"more",section:"Help & Services",searchKeywords:["support","help","ticket"],displayOrder:70},{id:"additional-services",label:"Additional Services",route:"/additional-services",icon:va,description:"Done-for-you services from LevelUp",primaryCategory:"more",section:"Help & Services",searchKeywords:["services","done for you"],displayOrder:80},{id:"integrations",label:"Integrations",route:"/mission-control/integrations",icon:rF,description:"Connect your CRM, calendar and socials",primaryCategory:"more",section:"Help & Services",searchKeywords:["integrations","connect","crm sync"],displayOrder:90},{id:"browser-extension",label:"Browser Extension",route:"/mission-control/browser-extension",icon:rF,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:va,description:"Relationship-first attraction coach",primaryCategory:"more",section:"Help & Services",badge:"beta",visible:t=>t.email==="jeremy@relevelup.com",searchKeywords:["attract","recruiting"],displayOrder:110},{id:"admin-dashboard",label:"Admin Dashboard",route:"/admin",icon:xv,description:"Manage members, content and settings",primaryCategory:"more",section:"Admin",visible:t=>t.isAdmin,searchKeywords:["admin"],displayOrder:120},{id:"agent-activation",label:"Agent Activation",route:"/admin/agent-activation",icon:aF,description:"Wake up dormant agents with branded email sequences",primaryCategory:"more",section:"Admin",visible:t=>t.isAdmin,searchKeywords:["activation","dormant","adoption","agents"],displayOrder:121},{id:"my-brokerage",label:"My Brokerage",route:"/my-brokerage",icon:jl,description:"Your brokerage hub",primaryCategory:"brokerage",section:"My Brokerage",visible:t=>!!t.brokerageId&&!t.isAdmin,searchKeywords:["brokerage"],displayOrder:130},{id:"help-board",label:"Help Board",route:"/brokerage/help-board",icon:X4e,description:"Ask for showing and open house coverage",primaryCategory:"brokerage",section:"My Brokerage",visible:t=>!!t.brokerageId&&!t.isAdmin,searchKeywords:["help board","coverage"],displayOrder:140},{id:"brokerage-content",label:"Brokerage Content",route:"/brokerage-content",icon:eT,description:"Content shared by your brokerage",primaryCategory:"brokerage",section:"My Brokerage",visible:t=>!!t.brokerageId&&!t.isAdmin,searchKeywords:["brokerage content"],displayOrder:150},{id:"team-hub",label:"Team Hub",route:"/team",icon:Dc,description:"Production, leaderboard, pond and resources for your team",primaryCategory:"team",section:"My Team",searchKeywords:["team","leaderboard","production","team hub","standing"],displayOrder:155},{id:"my-team",label:"My Team",route:"/my-team",icon:Dc,description:"Your team roster and lead pond",primaryCategory:"brokerage",section:"My Team",visible:t=>t.isOnTeam&&!t.isBrokerageManager&&!t.isAdmin,searchKeywords:["team","lead pond"],displayOrder:160},{id:"manage-brokerages",label:"Manage Brokerages",route:"/brokerage/dashboard",icon:XW,description:"Brokerage manager dashboard",primaryCategory:"brokerage",section:"Manage Brokerage",visible:t=>t.isBrokerageManager&&!t.isAdmin,searchKeywords:["manage brokerage"],displayOrder:170},{id:"brokerage-teams",label:"Teams",route:"/brokerage/teams",icon:Dc,description:"Teams, rosters and lead ponds",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:t=>t.isBrokerageManager&&!t.isAdmin,searchKeywords:["teams","pond"],displayOrder:180},{id:"brokerage-recruiting",label:"Recruiting",route:"/brokerage/recruiting",icon:NP,description:"Recruit and nurture agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:t=>t.isBrokerageManager&&!t.isAdmin,searchKeywords:["recruiting"],displayOrder:190},{id:"brokerage-onboarding",label:"Agent Onboarding",route:"/brokerage/onboarding",icon:$6,description:"Onboarding checklists, documents and agent notes",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:t=>t.isBrokerageManager&&!t.isAdmin,searchKeywords:["onboarding","checklist","documents","new agent"],displayOrder:195},{id:"brokerage-operations",label:"Operations",route:"/brokerage/operations",icon:cve,description:"Daily action feed, office task board and brokerage calendar",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:t=>(t.isBrokerageManager||t.isTransactionAdmin)&&!t.isAdmin,searchKeywords:["operations","tasks","today","calendar","action items"],displayOrder:188},{id:"brokerage-commission-plans",label:"Financials",route:"/brokerage/commission-plans",icon:u5e,description:"Commission plans, company dollar and fee statements",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:t=>(t.isBrokerageManager||t.isTransactionAdmin)&&!t.isAdmin,searchKeywords:["commission","split","cap","fees","agent plans"],displayOrder:195},{id:"brokerage-transactions",label:"Transactions & Compliance",route:"/brokerage/transactions",icon:$6,description:"Review agent files, required documents and closing compliance",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:t=>(t.isBrokerageManager||t.isTransactionAdmin)&&!t.isAdmin,searchKeywords:["compliance","transactions","documents","closing","paperless"],displayOrder:196},{id:"brokerage-vendors",label:"Vendors",route:"/brokerage/vendors",icon:Pq,description:"Preferred vendor directory",primaryCategory:"brokerage",section:"Manage Brokerage",visible:t=>t.isBrokerageManager&&!t.isAdmin,searchKeywords:["vendors"],displayOrder:200},{id:"brokerage-forms",label:"Brokerage Forms",route:"/brokerage/forms",icon:lg,description:"Official forms your agents can use",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:t=>t.isBrokerageManager&&!t.isAdmin,searchKeywords:["forms","pdf","documents"],displayOrder:205},{id:"brokerage-resources",label:"Brokerage Resources",route:"/brokerage-resources",icon:J_e,description:"Documents and links for your agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:t=>t.isBrokerageManager&&!t.isAdmin,searchKeywords:["resources"],displayOrder:210},{id:"my-partnership",label:"My Package",route:"/my-partnership",icon:va,description:"What is included in your partnership package",primaryCategory:"more",section:"Account",visible:t=>t.isPartnershipMember,searchKeywords:["partnership","package","upgrade","exp luxury"],displayOrder:5},{id:"coaching-onboarding",label:"Coaching Onboarding",route:"/coaching/onboarding",icon:$6,description:"Tell your coach about your business before session one",primaryCategory:"academy",section:"Coaching",visible:t=>t.hasCoachingOnboarding,searchKeywords:["coaching","onboarding","intake"],displayOrder:45}];function CSe(t,e){return typeof t.route=="function"?t.route(e):t.route}function PSe(){const{user:t,isAdmin:e,isBrokerageManager:r,isCoach:n,brokerageId:i}=_i(),{hasPermission:a}=i5(),{isInnerCircleEnabled:c,isMarketplaceEnabled:d,isFeatureEnabled:p}=l5(),{hasAccess:l}=YK(),{data:g,teams:v}=_A(),{leadSite:E,hasLeadSite:T,siteUrl:j}=ISe(),{hasOffer:P}=jSe(!T),C=wwe(),{hasAccess:L}=Oet(),{data:O}=Fet(),F=Ur(),{data:$}=jr({queryKey:["my-coach-nav",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:Te}=await Be.from("coaching_assignments").select("id").eq("agent_id",t.id).eq("status","active").limit(1);return(Te||[]).length>0}}),{data:G}=jr({queryKey:["user-tool-favorites",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:60*1e3,queryFn:async()=>{const{data:Te}=await Be.from("user_tool_favorites").select("tool_id").eq("user_id",t.id);return(Te||[]).map(ge=>ge.tool_id)}}),W=N.useMemo(()=>new Set(G||[]),[G]),Z=zr({mutationFn:async Te=>{t!=null&&t.id&&(W.has(Te)?await Be.from("user_tool_favorites").delete().eq("user_id",t.id).eq("tool_id",Te):await Be.from("user_tool_favorites").insert({user_id:t.id,tool_id:Te}))},onSuccess:()=>{F.invalidateQueries({queryKey:["user-tool-favorites"]}),F.invalidateQueries({queryKey:["app-catalog"]})}}),Q=N.useMemo(()=>{var Te,ge;return{isAdmin:!!e,isBrokerageManager:!!r,isTransactionAdmin:((O==null?void 0:O.length)||0)>0,isCoach:!!n,isOnTeam:!!g,isTeamLeader:(v||[]).some($e=>$e.role==="team_leader"),hasCoach:!!$,brokerageId:i??null,hasPermission:a,isInnerCircleEnabled:!!c,stagingStudioEnabled:p("staging_studio_enabled"),isMarketplaceEnabled:!!d,hasWeeklyReels:!!l,hasLeadSite:!!T,hasLeadSiteMLS:!!(E!=null&&E.mls_provider_id),hasFreeSiteOffer:!!P,leadSiteId:(E==null?void 0:E.id)??null,siteUrl:j??null,email:(t==null?void 0:t.email)??null,isPartnershipMember:C.isMember,hasCoachingOnboarding:C.isMember&&!!((Te=C.pkg)!=null&&Te.includes_coaching),hasCoachingAccess:!!L||C.isMember&&!!((ge=C.pkg)!=null&&ge.includes_coaching)}},[e,r,O,n,g,v,$,i,a,c,d,p,l,T,E,P,j,t==null?void 0:t.email,C.isMember,C.pkg,L]),ee=N.useMemo(()=>Bet.filter(Te=>Te.visible?Te.visible(Q):!0).map(Te=>{if(!C.isRestricted)return Te;const ge=j9e(Te);return!ge||C.hasFeature(ge)?Te:{...Te,locked:!0,route:`/upgrade/${ge}`}}).sort((Te,ge)=>Te.displayOrder-ge.displayOrder),[Q,C.isRestricted,C.features]),ie=N.useMemo(()=>S5.filter(Te=>Te.visible?Te.visible(Q):!0),[Q]),oe=N.useMemo(()=>ie.filter(Te=>!Te.route).map(Te=>{const ge=ee.filter(ke=>ke.primaryCategory===Te.id),$e=[],we=new Map;for(const ke of ge)we.has(ke.section)||(we.set(ke.section,[]),$e.push(ke.section)),we.get(ke.section).push(ke);return{id:Te.id,label:Te.label,sections:$e.map(ke=>({title:ke,items:we.get(ke)}))}}),[ee,ie]),pe=N.useMemo(()=>new Map(oe.map(Te=>[Te.id,Te])),[oe]),Le=Te=>Te.toolId||`nav:${Te.id}`,be=Te=>W.has(Le(Te));return{ctx:Q,categories:oe,railCategories:ie,categoryMap:pe,destinations:ee,favorites:W,isFavorite:be,favoritesFor:Te=>ee.filter(ge=>ge.primaryCategory===Te&&be(ge)),favoriteKey:Le,toggleFavorite:Te=>Z.mutate(Te),searchDestinations:Te=>{const ge=Te.trim().toLowerCase();return ge?ee.map(we=>{const ke=we.label.toLowerCase(),Ae=(we.description||"").toLowerCase(),He=(we.searchKeywords||[]).join(" ").toLowerCase();let ot=0;return ke===ge?ot=100:ke.startsWith(ge)?ot=80:ke.includes(ge)?ot=60:He.includes(ge)?ot=40:Ae.includes(ge)?ot=20:we.section.toLowerCase().includes(ge)&&(ot=10),ot&&be(we)&&(ot+=5),{d:we,score:ot}}).filter(we=>we.score>0).sort((we,ke)=>ke.score-we.score).map(we=>we.d):[]},routeFor:Te=>CSe(Te,Q)}}var wle=1,zet=.9,$et=.8,Uet=.17,IU=.1,jU=.999,Vet=.9999,qet=.99,Get=/[\\\/_+.#"@\[\(\{&]/,Het=/[\\\/_+.#"@\[\(\{&]/g,Wet=/[\s-]/,NSe=/[\s-]/g;function JG(t,e,r,n,i,a,c){if(a===e.length)return i===t.length?wle:qet;var d=`${i},${a}`;if(c[d]!==void 0)return c[d];for(var p=n.charAt(a),l=r.indexOf(p,i),g=0,v,E,T,j;l>=0;)v=JG(t,e,r,n,l+1,a+1,c),v>g&&(l===i?v*=wle:Get.test(t.charAt(l-1))?(v*=$et,T=t.slice(i,l-1).match(Het),T&&i>0&&(v*=Math.pow(jU,T.length))):Wet.test(t.charAt(l-1))?(v*=zet,j=t.slice(i,l-1).match(NSe),j&&i>0&&(v*=Math.pow(jU,j.length))):(v*=Uet,i>0&&(v*=Math.pow(jU,l-i))),t.charAt(l)!==e.charAt(a)&&(v*=Vet)),(vv&&(v=E*IU)),v>g&&(g=v),l=r.indexOf(p,l+1);return c[d]=g,g}function Sle(t){return t.toLowerCase().replace(NSe," ")}function Ket(t,e,r){return t=r&&r.length>0?`${t+" "+r.join(" ")}`:t,JG(t,e,Sle(t),Sle(e),0,0,{})}var aI='[cmdk-group=""]',CU='[cmdk-group-items=""]',Yet='[cmdk-group-heading=""]',RSe='[cmdk-item=""]',Ele=`${RSe}:not([aria-disabled="true"])`,e9="cmdk-item-select",zS="data-value",Zet=(t,e,r)=>Ket(t,e,r),LSe=N.createContext(void 0),ZP=()=>N.useContext(LSe),DSe=N.createContext(void 0),zY=()=>N.useContext(DSe),MSe=N.createContext(void 0),OSe=N.forwardRef((t,e)=>{let r=$S(()=>{var Ae,He;return{search:"",value:(He=(Ae=t.value)!=null?Ae:t.defaultValue)!=null?He:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=$S(()=>new Set),i=$S(()=>new Map),a=$S(()=>new Map),c=$S(()=>new Set),d=FSe(t),{label:p,children:l,value:g,onValueChange:v,filter:E,shouldFilter:T,loop:j,disablePointerSelection:P=!1,vimBindings:C=!0,...L}=t,O=Wl(),F=Wl(),$=Wl(),G=N.useRef(null),W=ott();hw(()=>{if(g!==void 0){let Ae=g.trim();r.current.value=Ae,Z.emit()}},[g]),hw(()=>{W(6,Le)},[]);let Z=N.useMemo(()=>({subscribe:Ae=>(c.current.add(Ae),()=>c.current.delete(Ae)),snapshot:()=>r.current,setState:(Ae,He,ot)=>{var nt,tt,vt,Vt;if(!Object.is(r.current[Ae],He)){if(r.current[Ae]=He,Ae==="search")pe(),ie(),W(1,oe);else if(Ae==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Ct=document.getElementById($);Ct?Ct.focus():(nt=document.getElementById(O))==null||nt.focus()}if(W(7,()=>{var Ct;r.current.selectedItemId=(Ct=be())==null?void 0:Ct.id,Z.emit()}),ot||W(5,Le),((tt=d.current)==null?void 0:tt.value)!==void 0){let Ct=He??"";(Vt=(vt=d.current).onValueChange)==null||Vt.call(vt,Ct);return}}Z.emit()}},emit:()=>{c.current.forEach(Ae=>Ae())}}),[]),Q=N.useMemo(()=>({value:(Ae,He,ot)=>{var nt;He!==((nt=a.current.get(Ae))==null?void 0:nt.value)&&(a.current.set(Ae,{value:He,keywords:ot}),r.current.filtered.items.set(Ae,ee(He,ot)),W(2,()=>{ie(),Z.emit()}))},item:(Ae,He)=>(n.current.add(Ae),He&&(i.current.has(He)?i.current.get(He).add(Ae):i.current.set(He,new Set([Ae]))),W(3,()=>{pe(),ie(),r.current.value||oe(),Z.emit()}),()=>{a.current.delete(Ae),n.current.delete(Ae),r.current.filtered.items.delete(Ae);let ot=be();W(4,()=>{pe(),(ot==null?void 0:ot.getAttribute("id"))===Ae&&oe(),Z.emit()})}),group:Ae=>(i.current.has(Ae)||i.current.set(Ae,new Set),()=>{a.current.delete(Ae),i.current.delete(Ae)}),filter:()=>d.current.shouldFilter,label:p||t["aria-label"],getDisablePointerSelection:()=>d.current.disablePointerSelection,listId:O,inputId:$,labelId:F,listInnerRef:G}),[]);function ee(Ae,He){var ot,nt;let tt=(nt=(ot=d.current)==null?void 0:ot.filter)!=null?nt:Zet;return Ae?tt(Ae,r.current.search,He):0}function ie(){if(!r.current.search||d.current.shouldFilter===!1)return;let Ae=r.current.filtered.items,He=[];r.current.filtered.groups.forEach(nt=>{let tt=i.current.get(nt),vt=0;tt.forEach(Vt=>{let Ct=Ae.get(Vt);vt=Math.max(Ct,vt)}),He.push([nt,vt])});let ot=G.current;Re().sort((nt,tt)=>{var vt,Vt;let Ct=nt.getAttribute("id"),Bt=tt.getAttribute("id");return((vt=Ae.get(Bt))!=null?vt:0)-((Vt=Ae.get(Ct))!=null?Vt:0)}).forEach(nt=>{let tt=nt.closest(CU);tt?tt.appendChild(nt.parentElement===tt?nt:nt.closest(`${CU} > *`)):ot.appendChild(nt.parentElement===ot?nt:nt.closest(`${CU} > *`))}),He.sort((nt,tt)=>tt[1]-nt[1]).forEach(nt=>{var tt;let vt=(tt=G.current)==null?void 0:tt.querySelector(`${aI}[${zS}="${encodeURIComponent(nt[0])}"]`);vt==null||vt.parentElement.appendChild(vt)})}function oe(){let Ae=Re().find(ot=>ot.getAttribute("aria-disabled")!=="true"),He=Ae==null?void 0:Ae.getAttribute(zS);Z.setState("value",He||void 0)}function pe(){var Ae,He,ot,nt;if(!r.current.search||d.current.shouldFilter===!1){r.current.filtered.count=n.current.size;return}r.current.filtered.groups=new Set;let tt=0;for(let vt of n.current){let Vt=(He=(Ae=a.current.get(vt))==null?void 0:Ae.value)!=null?He:"",Ct=(nt=(ot=a.current.get(vt))==null?void 0:ot.keywords)!=null?nt:[],Bt=ee(Vt,Ct);r.current.filtered.items.set(vt,Bt),Bt>0&&tt++}for(let[vt,Vt]of i.current)for(let Ct of Vt)if(r.current.filtered.items.get(Ct)>0){r.current.filtered.groups.add(vt);break}r.current.filtered.count=tt}function Le(){var Ae,He,ot;let nt=be();nt&&(((Ae=nt.parentElement)==null?void 0:Ae.firstChild)===nt&&((ot=(He=nt.closest(aI))==null?void 0:He.querySelector(Yet))==null||ot.scrollIntoView({block:"nearest"})),nt.scrollIntoView({block:"nearest"}))}function be(){var Ae;return(Ae=G.current)==null?void 0:Ae.querySelector(`${RSe}[aria-selected="true"]`)}function Re(){var Ae;return Array.from(((Ae=G.current)==null?void 0:Ae.querySelectorAll(Ele))||[])}function Ie(Ae){let He=Re()[Ae];He&&Z.setState("value",He.getAttribute(zS))}function Te(Ae){var He;let ot=be(),nt=Re(),tt=nt.findIndex(Vt=>Vt===ot),vt=nt[tt+Ae];(He=d.current)!=null&&He.loop&&(vt=tt+Ae<0?nt[nt.length-1]:tt+Ae===nt.length?nt[0]:nt[tt+Ae]),vt&&Z.setState("value",vt.getAttribute(zS))}function ge(Ae){let He=be(),ot=He==null?void 0:He.closest(aI),nt;for(;ot&&!nt;)ot=Ae>0?stt(ot,aI):att(ot,aI),nt=ot==null?void 0:ot.querySelector(Ele);nt?Z.setState("value",nt.getAttribute(zS)):Te(Ae)}let $e=()=>Ie(Re().length-1),we=Ae=>{Ae.preventDefault(),Ae.metaKey?$e():Ae.altKey?ge(1):Te(1)},ke=Ae=>{Ae.preventDefault(),Ae.metaKey?Ie(0):Ae.altKey?ge(-1):Te(-1)};return N.createElement(An.div,{ref:e,tabIndex:-1,...L,"cmdk-root":"",onKeyDown:Ae=>{var He;(He=L.onKeyDown)==null||He.call(L,Ae);let ot=Ae.nativeEvent.isComposing||Ae.keyCode===229;if(!(Ae.defaultPrevented||ot))switch(Ae.key){case"n":case"j":{C&&Ae.ctrlKey&&we(Ae);break}case"ArrowDown":{we(Ae);break}case"p":case"k":{C&&Ae.ctrlKey&&ke(Ae);break}case"ArrowUp":{ke(Ae);break}case"Home":{Ae.preventDefault(),Ie(0);break}case"End":{Ae.preventDefault(),$e();break}case"Enter":{Ae.preventDefault();let nt=be();if(nt){let tt=new Event(e9);nt.dispatchEvent(tt)}}}}},N.createElement("label",{"cmdk-label":"",htmlFor:Q.inputId,id:Q.labelId,style:ctt},p),E5(t,Ae=>N.createElement(DSe.Provider,{value:Z},N.createElement(LSe.Provider,{value:Q},Ae))))}),Xet=N.forwardRef((t,e)=>{var r,n;let i=Wl(),a=N.useRef(null),c=N.useContext(MSe),d=ZP(),p=FSe(t),l=(n=(r=p.current)==null?void 0:r.forceMount)!=null?n:c==null?void 0:c.forceMount;hw(()=>{if(!l)return d.item(i,c==null?void 0:c.id)},[l]);let g=BSe(i,a,[t.value,t.children,a],t.keywords),v=zY(),E=Av(W=>W.value&&W.value===g.current),T=Av(W=>l||d.filter()===!1?!0:W.search?W.filtered.items.get(i)>0:!0);N.useEffect(()=>{let W=a.current;if(!(!W||t.disabled))return W.addEventListener(e9,j),()=>W.removeEventListener(e9,j)},[T,t.onSelect,t.disabled]);function j(){var W,Z;P(),(Z=(W=p.current).onSelect)==null||Z.call(W,g.current)}function P(){v.setState("value",g.current,!0)}if(!T)return null;let{disabled:C,value:L,onSelect:O,forceMount:F,keywords:$,...G}=t;return N.createElement(An.div,{ref:iw(a,e),...G,id:i,"cmdk-item":"",role:"option","aria-disabled":!!C,"aria-selected":!!E,"data-disabled":!!C,"data-selected":!!E,onPointerMove:C||d.getDisablePointerSelection()?void 0:P,onClick:C?void 0:j},t.children)}),Qet=N.forwardRef((t,e)=>{let{heading:r,children:n,forceMount:i,...a}=t,c=Wl(),d=N.useRef(null),p=N.useRef(null),l=Wl(),g=ZP(),v=Av(T=>i||g.filter()===!1?!0:T.search?T.filtered.groups.has(c):!0);hw(()=>g.group(c),[]),BSe(c,d,[t.value,t.heading,p]);let E=N.useMemo(()=>({id:c,forceMount:i}),[i]);return N.createElement(An.div,{ref:iw(d,e),...a,"cmdk-group":"",role:"presentation",hidden:v?void 0:!0},r&&N.createElement("div",{ref:p,"cmdk-group-heading":"","aria-hidden":!0,id:l},r),E5(t,T=>N.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?l:void 0},N.createElement(MSe.Provider,{value:E},T))))}),Jet=N.forwardRef((t,e)=>{let{alwaysRender:r,...n}=t,i=N.useRef(null),a=Av(c=>!c.search);return!r&&!a?null:N.createElement(An.div,{ref:iw(i,e),...n,"cmdk-separator":"",role:"separator"})}),ett=N.forwardRef((t,e)=>{let{onValueChange:r,...n}=t,i=t.value!=null,a=zY(),c=Av(l=>l.search),d=Av(l=>l.selectedItemId),p=ZP();return N.useEffect(()=>{t.value!=null&&a.setState("search",t.value)},[t.value]),N.createElement(An.input,{ref:e,...n,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":p.listId,"aria-labelledby":p.labelId,"aria-activedescendant":d,id:p.inputId,type:"text",value:i?t.value:c,onChange:l=>{i||a.setState("search",l.target.value),r==null||r(l.target.value)}})}),ttt=N.forwardRef((t,e)=>{let{children:r,label:n="Suggestions",...i}=t,a=N.useRef(null),c=N.useRef(null),d=Av(l=>l.selectedItemId),p=ZP();return N.useEffect(()=>{if(c.current&&a.current){let l=c.current,g=a.current,v,E=new ResizeObserver(()=>{v=requestAnimationFrame(()=>{let T=l.offsetHeight;g.style.setProperty("--cmdk-list-height",T.toFixed(1)+"px")})});return E.observe(l),()=>{cancelAnimationFrame(v),E.unobserve(l)}}},[]),N.createElement(An.div,{ref:iw(a,e),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":d,"aria-label":n,id:p.listId},E5(t,l=>N.createElement("div",{ref:iw(c,p.listInnerRef),"cmdk-list-sizer":""},l)))}),rtt=N.forwardRef((t,e)=>{let{open:r,onOpenChange:n,overlayClassName:i,contentClassName:a,container:c,...d}=t;return N.createElement(D4,{open:r,onOpenChange:n},N.createElement(M4,{container:c},N.createElement(oA,{"cmdk-overlay":"",className:i}),N.createElement(lA,{"aria-label":t.label,"cmdk-dialog":"",className:a},N.createElement(OSe,{ref:e,...d}))))}),ntt=N.forwardRef((t,e)=>Av(r=>r.filtered.count===0)?N.createElement(An.div,{ref:e,...t,"cmdk-empty":"",role:"presentation"}):null),itt=N.forwardRef((t,e)=>{let{progress:r,children:n,label:i="Loading...",...a}=t;return N.createElement(An.div,{ref:e,...a,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},E5(t,c=>N.createElement("div",{"aria-hidden":!0},c)))}),vh=Object.assign(OSe,{List:ttt,Item:Xet,Input:ett,Group:Qet,Separator:Jet,Dialog:rtt,Empty:ntt,Loading:itt});function stt(t,e){let r=t.nextElementSibling;for(;r;){if(r.matches(e))return r;r=r.nextElementSibling}}function att(t,e){let r=t.previousElementSibling;for(;r;){if(r.matches(e))return r;r=r.previousElementSibling}}function FSe(t){let e=N.useRef(t);return hw(()=>{e.current=t}),e}var hw=typeof window>"u"?N.useEffect:N.useLayoutEffect;function $S(t){let e=N.useRef();return e.current===void 0&&(e.current=t()),e}function Av(t){let e=zY(),r=()=>t(e.snapshot());return N.useSyncExternalStore(e.subscribe,r,r)}function BSe(t,e,r,n=[]){let i=N.useRef(),a=ZP();return hw(()=>{var c;let d=(()=>{var l;for(let g of r){if(typeof g=="string")return g.trim();if(typeof g=="object"&&"current"in g)return g.current?(l=g.current.textContent)==null?void 0:l.trim():i.current}})(),p=n.map(l=>l.trim());a.value(t,d,p),(c=e.current)==null||c.setAttribute(zS,d),i.current=d}),i}var ott=()=>{let[t,e]=N.useState(),r=$S(()=>new Map);return hw(()=>{r.current.forEach(n=>n()),r.current=new Map},[t]),(n,i)=>{r.current.set(n,i),e({})}};function ltt(t){let e=t.type;return typeof e=="function"?e(t.props):"render"in e?e.render(t.props):t}function E5({asChild:t,children:e},r){return t&&N.isValidElement(e)?N.cloneElement(ltt(e),{ref:e.ref},r(e.props.children)):r(e)}var ctt={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const cC=N.forwardRef(({className:t,...e},r)=>s.jsx(vh,{ref:r,className:hr("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...e}));cC.displayName=vh.displayName;const utt=({children:t,...e})=>s.jsx(gl,{...e,children:s.jsx(Jo,{className:"overflow-hidden p-0 shadow-lg",children:s.jsx(cC,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5",children:t})})}),uC=N.forwardRef(({className:t,...e},r)=>s.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[s.jsx(ef,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),s.jsx(vh.Input,{ref:r,className:hr("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",t),...e})]}));uC.displayName=vh.Input.displayName;const dC=N.forwardRef(({className:t,...e},r)=>s.jsx(vh.List,{ref:r,className:hr("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...e}));dC.displayName=vh.List.displayName;const hC=N.forwardRef((t,e)=>s.jsx(vh.Empty,{ref:e,className:"py-6 text-center text-sm",...t}));hC.displayName=vh.Empty.displayName;const pT=N.forwardRef(({className:t,...e},r)=>s.jsx(vh.Group,{ref:r,className:hr("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",t),...e}));pT.displayName=vh.Group.displayName;const dtt=N.forwardRef(({className:t,...e},r)=>s.jsx(vh.Separator,{ref:r,className:hr("-mx-1 h-px bg-border",t),...e}));dtt.displayName=vh.Separator.displayName;const X_=N.forwardRef(({className:t,...e},r)=>s.jsx(vh.Item,{ref:r,className:hr("group relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-primary/80 data-[selected=true]:text-primary-foreground data-[disabled=true]:opacity-50",t),...e}));X_.displayName=vh.Item.displayName;const htt={event:{label:"Events",icon:ig,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:A4,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:Hj,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:rK,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:va,color:"bg-fuchsia-500/10 text-fuchsia-600"}},Tle=()=>{const[t,e]=N.useState(!1),[r,n]=N.useState(""),[i,a]=N.useState([]),[c,d]=N.useState(!1),p=qa(),{searchDestinations:l,isFavorite:g,routeFor:v}=PSe(),E=r.trim()?l(r).slice(0,6):[];N.useEffect(()=>{const C=L=>{L.key==="k"&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),e(O=>!O))};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[]);const T=N.useCallback(async C=>{if(!C.trim()){a([]);return}d(!0);const L=`%${C}%`;try{const[O,F,$,G,W]=await Promise.all([Be.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${L},description.ilike.${L}`).limit(5),Be.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${L},description.ilike.${L}`).limit(5),Be.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${L},description.ilike.${L}`).limit(5),Be.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${L},description.ilike.${L}`).limit(5),Be.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${L},description.ilike.${L}`).limit(5)]),Z=[];O.data&&O.data.forEach(Q=>{Z.push({id:Q.id,title:Q.title,description:Q.description,type:"event",date:Q.event_date,path:`/event/${Q.id}`})}),F.data&&F.data.forEach(Q=>{Z.push({id:Q.id,title:Q.name,description:Q.description,type:"template",date:Q.publish_date,path:`/templates/${Q.id}`})}),$.data&&$.data.forEach(Q=>{Z.push({id:Q.id,title:Q.title,description:Q.description,type:"academy",date:Q.publish_date,path:`/academy/${Q.id}`})}),G.data&&G.data.forEach(Q=>{Z.push({id:Q.id,title:Q.name,description:Q.description,type:"toolbox",date:Q.publish_date,path:`/toolbox/${Q.id}`})}),W.data&&W.data.forEach(Q=>{Z.push({id:Q.id,title:Q.title,description:Q.description,type:"social-swag",date:Q.publish_date,path:`/social-swag/${Q.id}`})}),a(Z)}catch(O){console.error("Search error:",O)}finally{d(!1)}},[]);N.useEffect(()=>{const C=setTimeout(()=>{T(r)},300);return()=>clearTimeout(C)},[r,T]);const j=C=>{e(!1),n(""),p(C)},P=i.reduce((C,L)=>(C[L.type]||(C[L.type]=[]),C[L.type].push(L),C),{});return s.jsxs(s.Fragment,{children:[s.jsxs(Jt,{variant:"outline",className:"relative h-9 w-9 p-0 xl:h-9 xl:w-60 xl:justify-start xl:px-3 xl:py-2",onClick:()=>e(!0),children:[s.jsx(ef,{className:"h-4 w-4 xl:mr-2"}),s.jsx("span",{className:"hidden xl:inline-flex text-muted-foreground text-sm",children:"Search..."}),s.jsxs("kbd",{className:"pointer-events-none absolute right-1.5 top-1.5 hidden h-6 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 xl:flex",children:[s.jsx("span",{className:"text-xs",children:"⌘"}),"K"]})]}),s.jsxs(utt,{open:t,onOpenChange:e,children:[s.jsx(uC,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:r,onValueChange:n}),s.jsxs(dC,{children:[E.length>0&&s.jsx(pT,{heading:"Go to",children:E.map(C=>{const L=C.icon;return s.jsxs(X_,{value:`nav-${C.id}-${C.label}`,onSelect:()=>{const O=v(C);C.external||C.openInNewTab?(e(!1),n(""),window.open(O,"_blank","noopener,noreferrer")):j(O)},className:"flex items-start gap-3 py-3 cursor-pointer",children:[s.jsx("div",{className:"p-2 rounded-md bg-primary/10 text-primary",children:s.jsx(L,{className:"h-4 w-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"font-medium truncate flex items-center gap-1.5",children:[C.label,g(C)&&s.jsx(tF,{className:"h-3 w-3 fill-current text-primary"})]}),C.description&&s.jsx("div",{className:"text-sm text-muted-foreground truncate",children:C.description})]}),s.jsx(Js,{variant:"secondary",className:"text-xs shrink-0",children:C.section})]},`nav-${C.id}`)})}),c&&s.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!c&&r&&i.length===0&&E.length===0&&s.jsxs(hC,{children:['No results found for "',r,'"']}),!c&&!r&&s.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search pages, apps and content..."}),Object.entries(P).map(([C,L])=>{const O=htt[C],F=O.icon;return s.jsx(pT,{heading:O.label,children:L.map($=>s.jsxs(X_,{value:`${$.type}-${$.id}-${$.title}`,onSelect:()=>j($.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[s.jsx("div",{className:`p-2 rounded-md ${O.color}`,children:s.jsx(F,{className:"h-4 w-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"font-medium truncate",children:$.title}),$.description&&s.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:$.description})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[s.jsx(Js,{variant:"secondary",className:"text-xs",children:O.label}),s.jsx("span",{className:"text-xs text-muted-foreground",children:wSe(new Date($.date),{addSuffix:!0})})]})]},`${$.type}-${$.id}`))},C)})]})]})]})},ftt=({expiresAt:t,className:e,showUpgradeButton:r=!0})=>{const[n,i]=N.useState(null),a=qa();if(N.useEffect(()=>{const l=()=>{const v=new Date().getTime(),T=new Date(t).getTime()-v;if(T<=0){i({days:0,hours:0,minutes:0});return}const j=Math.floor(T/(1e3*60*60*24)),P=Math.floor(T%(1e3*60*60*24)/(1e3*60*60)),C=Math.floor(T%(1e3*60*60)/(1e3*60));i({days:j,hours:P,minutes:C})};l();const g=setInterval(l,6e4);return()=>clearInterval(g)},[t]),!n)return null;const c=n.days===0&&n.hours===0&&n.minutes===0,d=n.days<=1,p=n.days<=3&&!d;return c?s.jsxs("div",{className:hr("flex items-center justify-between gap-3 px-4 py-2 rounded-lg bg-destructive/10 border border-destructive/20",e),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(LP,{className:"h-4 w-4 text-destructive"}),s.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),r&&s.jsxs(Jt,{size:"sm",onClick:()=>a("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[s.jsx(va,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):s.jsxs("div",{className:hr("flex items-center justify-between gap-3 px-4 py-2 rounded-lg border transition-colors",d?"bg-destructive/10 border-destructive/20":p?"bg-amber-500/10 border-amber-500/20":"bg-primary/10 border-primary/20",e),children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(su,{className:hr("h-4 w-4",d?"text-destructive":p?"text-amber-500":"text-primary")}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:hr("text-sm font-medium",d?"text-destructive":p?"text-amber-600":"text-primary"),children:"Free Trial:"}),s.jsxs("div",{className:"flex items-center gap-1",children:[n.days>0&&s.jsxs("span",{className:hr("text-sm font-bold",d?"text-destructive":p?"text-amber-600":"text-primary"),children:[n.days,"d"]}),s.jsxs("span",{className:hr("text-sm font-bold",d?"text-destructive":p?"text-amber-600":"text-primary"),children:[n.hours,"h"]}),s.jsxs("span",{className:hr("text-sm font-bold",d?"text-destructive":p?"text-amber-600":"text-primary"),children:[n.minutes,"m"]}),s.jsx("span",{className:hr("text-xs",d?"text-destructive/70":p?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),r&&s.jsxs(Jt,{size:"sm",onClick:()=>a("/subscription"),variant:d?"destructive":p?"default":"outline",className:hr("text-xs h-7 px-3",p&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[s.jsx(va,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},mtt=()=>{const t=qa();return s.jsx("div",{className:"fixed inset-0 bg-background/95 backdrop-blur-sm z-50 flex items-center justify-center p-4 overflow-y-auto",children:s.jsxs(wi,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[s.jsxs(Wh,{className:"text-center pb-2",children:[s.jsx("div",{className:"mx-auto mb-4 h-16 w-16 rounded-full bg-destructive/10 flex items-center justify-center",children:s.jsx(LP,{className:"h-8 w-8 text-destructive"})}),s.jsx(Kh,{className:"text-2xl",children:"Your Free Trial Has Ended"}),s.jsx(sC,{className:"text-base",children:"Your 7-day free trial has expired. Upgrade now to continue accessing all the powerful tools and resources LevelUp has to offer!"})]}),s.jsxs(Di,{className:"space-y-6",children:[s.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[s.jsx(wi,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>t("/subscription"),children:s.jsxs(Di,{className:"p-5 text-center",children:[s.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:s.jsx(Dc,{className:"h-6 w-6 text-primary"})}),s.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),s.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",s.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),s.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),s.jsxs(Jt,{className:"w-full",onClick:e=>{e.stopPropagation(),t("/subscription")},children:[s.jsx(va,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),s.jsx(wi,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>t("/subscription"),children:s.jsxs(Di,{className:"p-5 text-center",children:[s.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-amber-500/10 flex items-center justify-center",children:s.jsx(jl,{className:"h-6 w-6 text-amber-600"})}),s.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Brokerage"}),s.jsxs("p",{className:"text-2xl font-bold text-amber-600 mb-2",children:["$299",s.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),s.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"For teams and brokerages"}),s.jsxs(Jt,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:e=>{e.stopPropagation(),t("/subscription")},children:[s.jsx(jl,{className:"h-4 w-4 mr-2"}),"Choose Brokerage"]})]})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"With a full membership, you'll get:"}),s.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground grid sm:grid-cols-2 gap-x-4",children:[s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Unlimited access to all marketing templates"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Complete Academy training library"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," AI-powered tools and resources"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Community forums and support"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Exclusive member events and workshops"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"✓"})," Deal pipeline & scorecard tracking"]})]})]}),s.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3",children:[s.jsx("p",{className:"text-sm font-medium text-center",children:"Questions? Contact us:"}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[s.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[s.jsx(Ui,{className:"h-4 w-4"}),s.jsx("span",{children:"1-866-527-8668"})]}),s.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[s.jsx(rs,{className:"h-4 w-4"}),s.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},ptt=({hasUnseenBrief:t,onClick:e,className:r})=>s.jsxs(k6e,{children:[s.jsx(I6e,{asChild:!0,children:s.jsxs(Jt,{variant:"ghost",size:"icon",onClick:e,className:hr("relative transition-colors",t&&"text-primary hover:text-primary",r),children:[s.jsx(NP,{className:"h-5 w-5"}),t&&s.jsx("span",{className:"absolute top-1 right-1 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),s.jsx(I0e,{children:s.jsx("p",{children:"The LevelUp Brief"})})]});var gtt=Object.defineProperty,Yy=(t,e)=>gtt(t,"name",{value:e,configurable:!0}),$Y="Checkbox",[ytt,KKt]=Nl($Y),[xtt,UY]=ytt($Y);function zSe(t){const{__scopeCheckbox:e,checked:r,children:n,defaultChecked:i,disabled:a,form:c,name:d,onCheckedChange:p,required:l,value:g="on",internal_do_not_use_render:v}=t,[E,T]=ph({prop:r,defaultProp:i??!1,onChange:p,caller:$Y}),[j,P]=N.useState(null),[C,L]=N.useState(null),[O,F]=N.useState(null),$=j?!!c||!!j.closest("form"):!0,G={checked:E,disabled:a,setChecked:T,control:j,setControl:P,name:d,form:c,value:g,userClick:O,onUserClick:F,required:l,defaultChecked:Mf(i)?!1:i,isFormControl:$,bubbleInput:C,setBubbleInput:L};return s.jsx(xtt,{scope:e,...G,children:USe(v)?v(G):n})}Yy(zSe,"CheckboxProvider");var _tt="CheckboxTrigger",vtt=N.forwardRef(Yy(function({__scopeCheckbox:e,onKeyDown:r,onClick:n,...i},a){const{control:c,value:d,disabled:p,checked:l,required:g,setControl:v,setChecked:E,onUserClick:T,isFormControl:j,bubbleInput:P}=UY(_tt,e),C=Jn(a,v),L=N.useRef(l);return N.useEffect(()=>{const O=c==null?void 0:c.form;if(O){const F=Yy(()=>E(L.current),"reset");return O.addEventListener("reset",F),()=>O.removeEventListener("reset",F)}},[c,E]),s.jsx(An.button,{type:"button",role:"checkbox","aria-checked":Mf(l)?"mixed":l,"aria-required":g,"data-state":VY(l),"data-disabled":p?"":void 0,disabled:p,value:d,...i,ref:C,onKeyDown:Qr(r,O=>{O.key==="Enter"&&O.preventDefault()}),onClick:Qr(n,O=>{const F=O.isPropagationStopped();T({requestedChecked:Mf(l)?!0:!l,hasConsumerStoppedPropagation:F}),E($=>Mf($)?!0:!$),P&&j&&(F||O.stopPropagation())})})},"CheckboxTrigger")),$Se=N.forwardRef(Yy(function(e,r){const{__scopeCheckbox:n,name:i,checked:a,defaultChecked:c,required:d,disabled:p,value:l,onCheckedChange:g,form:v,...E}=e;return s.jsx(zSe,{__scopeCheckbox:n,checked:a,defaultChecked:c,disabled:p,required:d,onCheckedChange:g,name:i,form:v,value:l,internal_do_not_use_render:({isFormControl:T})=>s.jsxs(s.Fragment,{children:[s.jsx(vtt,{...E,ref:r,__scopeCheckbox:n}),T&&s.jsx(Ett,{__scopeCheckbox:n})]})})},"Checkbox")),btt="CheckboxIndicator",wtt=N.forwardRef(Yy(function(e,r){const{__scopeCheckbox:n,forceMount:i,...a}=e,c=UY(btt,n);return s.jsx(zc,{present:i||Mf(c.checked)||c.checked===!0,children:s.jsx(An.span,{"data-state":VY(c.checked),"data-disabled":c.disabled?"":void 0,...a,ref:r,style:{pointerEvents:"none",...e.style}})})},"CheckboxIndicator")),Stt="CheckboxBubbleInput",Ett=N.forwardRef(Yy(function({__scopeCheckbox:e,onClick:r,...n},i){const{control:a,userClick:c,checked:d,defaultChecked:p,required:l,disabled:g,name:v,value:E,form:T,bubbleInput:j,setBubbleInput:P}=UY(Stt,e),C=Jn(i,P),L=dA(a),O=N.useRef(!1),F=N.useRef(d),$=N.useRef(c),G=N.useRef(null);N.useEffect(()=>{const Z=j;if(!Z)return;const Q=window.HTMLInputElement.prototype,ie=Object.getOwnPropertyDescriptor(Q,"checked").set;if(!ie)return;const oe=F.current!==d;F.current=d;const pe=c!==null&&c!==$.current;if($.current=c,pe)G.current=oe?null:c,oe&&(Z.indeterminate=Mf(d),ie.call(Z,Mf(d)?!1:d)),Z.dispatchEvent(new Event("click",{bubbles:!c.hasConsumerStoppedPropagation}));else if(oe){const Le=G.current;G.current=null;const be=(Le==null?void 0:Le.requestedChecked)===d;O.current=!0,Z.indeterminate=Mf(d),ie.call(Z,Mf(d)?!1:d),Z.dispatchEvent(new Event("click",{bubbles:!(be&&Le.hasConsumerStoppedPropagation)})),O.current=!1}},[j,d,c]);const W=N.useRef(Mf(d)?!1:d);return s.jsx(An.input,{type:"checkbox","aria-hidden":!0,defaultChecked:p??W.current,required:l,disabled:g,name:v,value:E,form:T,...n,tabIndex:-1,ref:C,onClick:Qr(r,Z=>{O.current&&Z.stopPropagation()}),style:{...n.style,...L,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"CheckboxBubbleInput"));function USe(t){return typeof t=="function"}Yy(USe,"isFunction");function Mf(t){return t==="indeterminate"}Yy(Mf,"isIndeterminate");function VY(t){return Mf(t)?"indeterminate":t?"checked":"unchecked"}Yy(VY,"getState");const XP=N.forwardRef(({className:t,...e},r)=>s.jsx($Se,{ref:r,className:hr("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...e,children:s.jsx(wtt,{className:hr("flex items-center justify-center text-current"),children:s.jsx(ql,{className:"h-4 w-4"})})}));XP.displayName=$Se.displayName;var Ttt=Object.defineProperty,id=(t,e)=>Ttt(t,"name",{value:e,configurable:!0}),VSe="Radio",[Att,qSe]=Nl(VSe),[ktt,T5]=Att(VSe);function GSe(t){const{__scopeRadio:e,checked:r=!1,children:n,disabled:i,form:a,name:c,onCheck:d,required:p,value:l="on",internal_do_not_use_render:g}=t,[v,E]=N.useState(null),[T,j]=N.useState(null),[P,C]=N.useState(null),L=v?!!a||!!v.closest("form"):!0,O={checked:r,disabled:i,required:p,name:c,form:a,value:l,control:v,setControl:E,userClick:P,onUserClick:C,isFormControl:L,bubbleInput:T,setBubbleInput:j,onCheck:id(()=>d==null?void 0:d(),"onCheck")};return s.jsx(ktt,{scope:e,...O,children:HSe(g)?g(O):n})}id(GSe,"RadioProvider");var Itt="RadioTrigger",jtt=N.forwardRef(id(function({__scopeRadio:e,onClick:r,...n},i){const{checked:a,disabled:c,value:d,setControl:p,onCheck:l,onUserClick:g,isFormControl:v,bubbleInput:E}=T5(Itt,e),T=Jn(i,p);return s.jsx(An.button,{type:"button",role:"radio","aria-checked":a,"data-state":qY(a),"data-disabled":c?"":void 0,disabled:c,value:d,...n,ref:T,onClick:Qr(r,j=>{const P=j.isPropagationStopped();a||(g({hasConsumerStoppedPropagation:P}),l()),E&&v&&(P||j.stopPropagation())})})},"RadioTrigger")),Ctt="RadioIndicator",Ptt=N.forwardRef(id(function(e,r){const{__scopeRadio:n,forceMount:i,...a}=e,c=T5(Ctt,n);return s.jsx(zc,{present:i||c.checked,children:s.jsx(An.span,{"data-state":qY(c.checked),"data-disabled":c.disabled?"":void 0,...a,ref:r})})},"RadioIndicator")),Ntt="RadioBubbleInput",Rtt=N.forwardRef(id(function({__scopeRadio:e,onClick:r,...n},i){const{control:a,checked:c,required:d,disabled:p,name:l,value:g,form:v,bubbleInput:E,setBubbleInput:T,userClick:j}=T5(Ntt,e),P=Jn(i,T),C=dA(a),L=N.useRef(!1),O=N.useRef(c),F=N.useRef(j),$=N.useRef(null);N.useEffect(()=>{const W=E;if(!W)return;const Z=window.HTMLInputElement.prototype,ee=Object.getOwnPropertyDescriptor(Z,"checked").set;if(!ee)return;const ie=O.current!==c;O.current=c;const oe=j!==null&&j!==F.current;if(F.current=j,oe)$.current=ie?null:j,ie&&ee.call(W,c),W.dispatchEvent(new Event("click",{bubbles:!j.hasConsumerStoppedPropagation}));else if(ie){const pe=$.current;$.current=null;const Le=c&&pe!==null;L.current=!0,ee.call(W,c),W.dispatchEvent(new Event("click",{bubbles:!(Le&&pe.hasConsumerStoppedPropagation)})),L.current=!1}},[E,c,j]);const G=N.useRef(c);return s.jsx(An.input,{type:"radio","aria-hidden":!0,defaultChecked:G.current,required:d,disabled:p,name:l,value:g,form:v,...n,tabIndex:-1,ref:P,onClick:Qr(r,W=>{L.current&&W.stopPropagation()}),style:{...n.style,...C,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"RadioBubbleInput"));function HSe(t){return typeof t=="function"}id(HSe,"isFunction");function qY(t){return t?"checked":"unchecked"}id(qY,"getState");var Ltt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],GY="RadioGroup",[Dtt,YKt]=Nl(GY,[yA,qSe]),WSe=yA(),A5=qSe(),[Mtt,Ott]=Dtt(GY),KSe=N.forwardRef(id(function(e,r){const{__scopeRadioGroup:n,name:i,form:a,defaultValue:c,value:d,required:p=!1,disabled:l=!1,orientation:g,dir:v,loop:E=!0,onValueChange:T,...j}=e,P=WSe(n),C=Uv(v),[L,O]=ph({prop:d,defaultProp:c??null,onChange:T,caller:GY}),[F,$]=N.useState(null),G=Jn(r,$),W=N.useRef(L);return N.useEffect(()=>{const Z=a?F==null?void 0:F.ownerDocument.getElementById(a):F==null?void 0:F.closest("form");if(Z instanceof HTMLFormElement){const Q=id(()=>O(W.current),"reset");return Z.addEventListener("reset",Q),()=>Z.removeEventListener("reset",Q)}},[F,a,O]),s.jsx(Mtt,{scope:n,name:i,form:a,required:p,disabled:l,value:L,onValueChange:O,children:s.jsx(BK,{asChild:!0,...P,orientation:g,dir:C,loop:E,children:s.jsx(An.div,{role:"radiogroup","aria-required":p,"aria-orientation":g,"data-disabled":l?"":void 0,dir:C,...j,ref:G})})})},"RadioGroup")),Ftt="RadioGroupItemProvider",Btt="RadioGroupItemTrigger";function YSe(t){const{__scopeRadioGroup:e,value:r,disabled:n,children:i,internal_do_not_use_render:a}=t,c=Ott(Ftt,e),d=A5(e),p=c.disabled||n;return s.jsx(GSe,{...d,checked:c.value===r,disabled:p,required:c.required,name:c.name,form:c.form,value:r,onCheck:()=>c.onValueChange(r),internal_do_not_use_render:a,children:i})}id(YSe,"RadioGroupItemProvider");var ztt=N.forwardRef(id(function(e,r){const{__scopeRadioGroup:n,...i}=e,a=WSe(n),c=A5(n),{checked:d,disabled:p}=T5(Btt,c.__scopeRadio),l=N.useRef(null),g=Jn(r,l),v=N.useRef(!1);return N.useEffect(()=>{const E=id(j=>{Ltt.includes(j.key)&&(v.current=!0)},"handleKeyDown"),T=id(()=>v.current=!1,"handleKeyUp");return document.addEventListener("keydown",E),document.addEventListener("keyup",T),()=>{document.removeEventListener("keydown",E),document.removeEventListener("keyup",T)}},[]),s.jsx(zK,{asChild:!0,...a,focusable:!p,active:d,children:s.jsx(jtt,{...c,...i,ref:g,onKeyDown:Qr(i.onKeyDown,E=>{E.key==="Enter"&&E.preventDefault()}),onFocus:Qr(i.onFocus,()=>{var E;v.current&&((E=l.current)==null||E.click())})})})},"RadioGroupItemTrigger")),ZSe=N.forwardRef(id(function(e,r){const{__scopeRadioGroup:n,value:i,disabled:a,...c}=e;return s.jsx(YSe,{__scopeRadioGroup:n,value:i,disabled:a,internal_do_not_use_render:({isFormControl:d})=>s.jsxs(s.Fragment,{children:[s.jsx(ztt,{...c,ref:r,__scopeRadioGroup:n}),d&&s.jsx($tt,{__scopeRadioGroup:n})]})})},"RadioGroupItem")),$tt=N.forwardRef(id(function(e,r){const{__scopeRadioGroup:n,...i}=e,a=A5(n);return s.jsx(Rtt,{...a,...i,ref:r})},"RadioGroupItemBubbleInput")),Utt=N.forwardRef(id(function(e,r){const{__scopeRadioGroup:n,...i}=e,a=A5(n);return s.jsx(Ptt,{...a,...i,ref:r})},"RadioGroupIndicator"));const XSe=N.forwardRef(({className:t,...e},r)=>s.jsx(KSe,{className:hr("grid gap-2",t),...e,ref:r}));XSe.displayName=KSe.displayName;const QSe=N.forwardRef(({className:t,...e},r)=>s.jsx(ZSe,{ref:r,className:hr("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...e,children:s.jsx(Utt,{className:"flex items-center justify-center",children:s.jsx(tT,{className:"h-2.5 w-2.5 fill-current text-current"})})}));QSe.displayName=ZSe.displayName;const Vtt=({brief:t,open:e,onClose:r,onDismiss:n})=>{const{user:i}=_i(),[a,c]=N.useState({}),[d,p]=N.useState({}),[l,g]=N.useState([]);N.useEffect(()=>{e&&i&&t.polls.length>0&&v()},[e,i,t.polls]);const v=async()=>{if(!i)return;const C=t.polls.map(O=>O.id),{data:L}=await Be.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",i.id).in("poll_id",C);if(L){const O={};L.forEach(F=>{O[F.poll_id]||(O[F.poll_id]=[]),O[F.poll_id].push(F.option_id)}),p(O)}},E=(C,L)=>{c(O=>({...O,[C]:L}))},T=(C,L,O)=>{c(F=>{const $=F[C]||[];return O?{...F,[C]:[...$,L]}:{...F,[C]:$.filter(G=>G!==L)}})},j=async C=>{if(!i)return;const L=a[C];if(!L||Array.isArray(L)&&L.length===0){lr.error("Please select an option");return}g(O=>[...O,C]);try{await Be.from("levelup_brief_poll_responses").delete().eq("poll_id",C).eq("user_id",i.id);const O=Array.isArray(L)?L:[L],F=O.map(G=>({poll_id:C,option_id:G,user_id:i.id})),{error:$}=await Be.from("levelup_brief_poll_responses").insert(F);if($)throw $;p(G=>({...G,[C]:O})),lr.success("Response submitted!")}catch(O){console.error("Error submitting poll response:",O),lr.error("Failed to submit response")}finally{g(O=>O.filter(F=>F!==C))}},P=C=>(C.includes("mediadelivery.net")||C.includes("bunny"),C);return s.jsx(gl,{open:e,onOpenChange:C=>!C&&r(),children:s.jsxs(Jo,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[s.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[s.jsx("button",{onClick:r,className:"absolute top-3 right-3 p-1.5 rounded-full bg-white/30 hover:bg-white/50 transition-colors","aria-label":"Close",children:s.jsx(Ra,{className:"h-5 w-5 text-white"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-white/20 rounded-lg",children:s.jsx(NP,{className:"h-6 w-6"})}),s.jsxs("div",{children:[s.jsx(Js,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),s.jsx(pc,{className:"text-xl font-bold text-white",children:t.brief.title})]})]})]}),s.jsx(Eg,{className:"max-h-[calc(90vh-240px)]",children:s.jsxs("div",{className:"p-6 space-y-6",children:[t.brief.description&&s.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:t.brief.description}}),t.brief.video_url&&s.jsx("div",{className:"relative w-full aspect-video rounded-lg overflow-hidden bg-muted",children:s.jsx("iframe",{src:P(t.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),t.brief.graphic_url&&!t.brief.video_url&&s.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:t.brief.graphic_link_url?s.jsx("a",{href:t.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:s.jsx("img",{src:t.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):s.jsx("img",{src:t.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),t.links.length>0&&s.jsxs("div",{className:"space-y-3",children:[s.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:t.links.map(C=>s.jsxs(Jt,{variant:"outline",size:"sm",onClick:()=>window.open(C.url,"_blank"),className:"gap-2",children:[s.jsx(rA,{className:"h-4 w-4"}),C.title]},C.id))})]}),t.polls.map(C=>{var F,$;const L=((F=d[C.id])==null?void 0:F.length)>0,O=l.includes(C.id);return s.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("h4",{className:"font-semibold text-foreground",children:C.question}),L&&s.jsxs(Js,{variant:"secondary",className:"gap-1",children:[s.jsx(od,{className:"h-3 w-3"}),"Responded"]})]}),C.poll_type==="single"?s.jsx(XSe,{value:a[C.id]||(($=d[C.id])==null?void 0:$[0])||"",onValueChange:G=>E(C.id,G),className:"space-y-2",children:C.options.map(G=>s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(QSe,{value:G.id,id:G.id}),s.jsx(sn,{htmlFor:G.id,className:"cursor-pointer",children:G.option_text})]},G.id))}):s.jsx("div",{className:"space-y-2",children:C.options.map(G=>{const Z=(a[C.id]||d[C.id]||[]).includes(G.id);return s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx(XP,{id:G.id,checked:Z,onCheckedChange:Q=>T(C.id,G.id,Q)}),s.jsx(sn,{htmlFor:G.id,className:"cursor-pointer",children:G.option_text})]},G.id)})}),s.jsx(Jt,{size:"sm",onClick:()=>j(C.id),disabled:O,children:O?"Submitting...":L?"Update Response":"Submit"})]},C.id)})]})}),s.jsxs("div",{className:"p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] border-t bg-muted/30 flex flex-col items-center gap-2 sticky bottom-0 z-10",children:[s.jsx(Jt,{onClick:r,className:"w-full max-w-xs",children:"Got it!"}),s.jsx(Jt,{variant:"ghost",size:"sm",onClick:n,children:"Don't show again"})]})]})})},qtt=()=>{const{user:t}=_i(),[e,r]=N.useState(null),[n,i]=N.useState(!1),[a,c]=N.useState(!0),[d,p]=N.useState(!1),l=N.useCallback(async()=>{if(!t){c(!1);return}try{const{data:j,error:P}=await Be.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(P||!j){c(!1);return}const{data:C}=await Be.from("levelup_brief_views").select("*").eq("brief_id",j.id).eq("user_id",t.id).maybeSingle(),[L,O]=await Promise.all([Be.from("levelup_brief_links").select("*").eq("brief_id",j.id).order("sort_order"),Be.from("levelup_brief_polls").select("*").eq("brief_id",j.id).order("sort_order")]),F=[];if(O.data)for(const Q of O.data){const{data:ee}=await Be.from("levelup_brief_poll_options").select("*").eq("poll_id",Q.id).order("sort_order");F.push({...Q,options:ee||[]})}const $={brief:j,links:L.data||[],polls:F};r($);const G=!!C,W=(C==null?void 0:C.dismissed_at)!=null,Z=localStorage.getItem(`brief-dismissed-${j.id}`)==="true";if(W||Z)p(!1),i(!1);else if(!G)i(!0),p(!0);else if(j.show_frequency==="every_login")i(!0),p(!0);else if(j.show_frequency==="daily"){const Q=new Date(C.viewed_at);(new Date().getTime()-Q.getTime())/(1e3*60*60)>=24&&(i(!0),p(!0))}else p(!1)}catch(j){console.error("Error fetching brief:",j)}finally{c(!1)}},[t]);N.useEffect(()=>{l()},[l]);const g=async()=>{if(!(!t||!e))try{const{data:j}=await Be.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();j?await Be.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",j.id):await Be.from("levelup_brief_views").insert({brief_id:e.brief.id,user_id:t.id})}catch(j){console.error("Error marking brief as viewed:",j)}};return{currentBrief:e,shouldShowPopup:n,hasUnseenBrief:d,loading:a,openBrief:()=>{i(!0)},closeBrief:()=>{i(!1),g()},dismissBrief:async()=>{if(!(!t||!e)){i(!1),p(!1);try{const{data:j,error:P}=await Be.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();if(P&&console.error("Error checking existing brief view:",P),j){const{error:C}=await Be.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",j.id).eq("user_id",t.id);C&&console.error("Error updating brief dismiss:",C)}else{const{error:C}=await Be.from("levelup_brief_views").insert({brief_id:e.brief.id,user_id:t.id,dismissed_at:new Date().toISOString()});C&&console.error("Error inserting brief dismiss:",C)}localStorage.setItem(`brief-dismissed-${e.brief.id}`,"true")}catch(j){console.error("Error dismissing brief:",j),e&&localStorage.setItem(`brief-dismissed-${e.brief.id}`,"true")}}},refetch:l}};function Gtt(){const[t,e]=N.useState(!1),[r,n]=N.useState(!1),[i,a]=N.useState(null);N.useEffect(()=>{const p=localStorage.getItem("install-banner-dismissed"),l=localStorage.getItem("install-banner-shown");if(p||l)return;if(window.matchMedia("(display-mode: standalone)").matches||window.matchMedia("(display-mode: fullscreen)").matches||window.matchMedia("(display-mode: minimal-ui)").matches||window.navigator.standalone===!0||document.referrer.startsWith("android-app://")){localStorage.setItem("install-banner-dismissed","true");return}if(!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const E=/iPhone|iPad|iPod/i.test(navigator.userAgent);n(E),e(!0),localStorage.setItem("install-banner-shown","true");const T=j=>{j.preventDefault(),a(j)};return window.addEventListener("beforeinstallprompt",T),()=>{window.removeEventListener("beforeinstallprompt",T)}},[]);const c=()=>{localStorage.setItem("install-banner-dismissed","true"),localStorage.setItem("install-banner-shown","true"),e(!1)},d=async()=>{if(i){await i.prompt();const{outcome:p}=await i.userChoice;p==="accepted"&&c(),a(null)}};return t?s.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-50 p-4 bg-primary text-primary-foreground shadow-lg animate-in slide-in-from-bottom duration-300",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[s.jsx("div",{className:"flex-shrink-0 p-2 bg-primary-foreground/10 rounded-full",children:s.jsx($u,{className:"h-5 w-5"})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"font-medium text-sm",children:"Add LevelUp to your home screen"}),r?s.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",s.jsx(x5e,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):s.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!r&&i&&s.jsx(Jt,{size:"sm",variant:"secondary",onClick:d,className:"text-xs",children:"Install"}),s.jsx(Jt,{size:"sm",variant:"secondary",onClick:c,className:"text-xs",children:"Got it"}),s.jsx("button",{onClick:c,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:s.jsx(Ra,{className:"h-4 w-4"})})]})]})}):null}const Htt=({children:t,onRefresh:e})=>{const[r,n]=N.useState(!1),[i,a]=N.useState(0),[c,d]=N.useState(!1),p=N.useRef(null),l=N.useRef(0),g=Ur(),v=80,E=120,T=N.useCallback(O=>{const F=p.current;F&&F.scrollTop<=0&&(l.current=O.touches[0].clientY,n(!0))},[]),j=N.useCallback(O=>{if(!r||c)return;const F=p.current;if(!F||F.scrollTop>0){n(!1),a(0);return}const G=O.touches[0].clientY-l.current;if(G>0){const Z=Math.min(G*.5,E);a(Z),Z>10&&O.preventDefault()}},[r,c]),P=N.useCallback(async()=>{if(r)if(n(!1),i>=v&&!c){d(!0),a(v);try{e?await e():await g.invalidateQueries()}catch(O){console.error("Refresh failed:",O)}finally{d(!1),a(0)}}else a(0)},[r,i,c,e,g]),C=Math.min(i/v,1),L=C*180;return s.jsxs("div",{ref:p,className:"h-full overflow-auto",onTouchStart:T,onTouchMove:j,onTouchEnd:P,children:[s.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:i>0?i:0,opacity:C},children:s.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${c?"animate-spin":""}`,style:{transform:c?void 0:`rotate(${L}deg)`,transition:c?void 0:"transform 0.1s ease-out"},children:s.jsx(g5e,{className:"h-5 w-5 text-primary"})})}),s.jsx("div",{style:{transform:i>0?`translateY(${Math.max(0,i-60)}px)`:void 0,transition:r?void 0:"transform 0.2s ease-out"},children:t})]})},Wtt=()=>{const{user:t}=_i(),[e,r]=N.useState(!1),[n,i]=N.useState(!1),[a,c]=N.useState(0),[d,p]=N.useState(!0);N.useEffect(()=>{(async()=>{if(!t){p(!1);return}try{const{data:T}=await Be.from("membership_reviews").select("id").eq("user_id",t.id).maybeSingle();if(T){i(!0),r(!1),p(!1);return}const{data:j}=await Be.from("profiles").select("login_count").eq("id",t.id).single(),P=(j==null?void 0:j.login_count)||0;c(P);const C=sessionStorage.getItem("review-prompt-dismissed");r(P>=4&&!C)}catch(T){console.error("Error checking review eligibility:",T)}finally{p(!1)}})()},[t]);const l=N.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),r(!1)},[]),g=N.useCallback(async(E,T)=>{if(!t)return{success:!1,error:"Not authenticated"};try{const{error:j}=await Be.from("membership_reviews").insert({user_id:t.id,rating:E,review_text:T});if(j)throw j;return i(!0),r(!1),{success:!0,pointsAwarded:25}}catch(j){return console.error("Error submitting review:",j),{success:!1,error:j.message}}},[t]),v=N.useCallback(async()=>{if(t)try{await Be.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",t.id)}catch(E){console.error("Error updating Google review status:",E)}},[t]);return{shouldShowPrompt:e,hasSubmittedReview:n,loginCount:a,isLoading:d,dismissPrompt:l,submitReview:g,markPostedToGoogle:v}},Ktt="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",Ytt=()=>{const{shouldShowPrompt:t,isLoading:e,dismissPrompt:r,submitReview:n,markPostedToGoogle:i}=Wtt(),[a,c]=N.useState(!1),[d,p]=N.useState("review"),[l,g]=N.useState(0),[v,E]=N.useState(0),[T,j]=N.useState(""),[P,C]=N.useState(!1),[L,O]=N.useState(!1);if(e||!t&&!L)return null;const F=async()=>{if(l===0){ba({title:"Please select a rating",variant:"destructive"});return}C(!0);const W=await n(l,T);C(!1),W.success?(O(!0),ba({title:"Thank you for your feedback!",description:"Your review helps us improve."}),p("google")):ba({title:"Error submitting review",description:W.error,variant:"destructive"})},$=async W=>{W&&(await navigator.clipboard.writeText(T||`${l} star rating for LevelUp!`),ba({title:"Review copied!",description:"Paste it on Google Reviews."}),await i(),window.open(Ktt,"_blank")),c(!1),r()},G=()=>{c(!1),r()};return s.jsxs(s.Fragment,{children:[s.jsxs("button",{onClick:()=>c(!0),className:"fixed bottom-20 left-1/2 -translate-x-1/2 z-40 flex items-center gap-2 rounded-full bg-primary/90 px-3 py-2 text-xs text-primary-foreground shadow-lg backdrop-blur-sm transition-all hover:bg-primary hover:scale-105 md:bottom-6",children:[s.jsx(Bd,{className:"h-3.5 w-3.5 fill-current"}),s.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),s.jsx(gl,{open:a,onOpenChange:G,children:s.jsx(Jo,{className:"sm:max-w-md",children:d==="review"?s.jsxs(s.Fragment,{children:[s.jsxs(Bc,{children:[s.jsx(pc,{className:"text-center",children:"How are you enjoying LevelUp?"}),s.jsx(sf,{className:"text-center",children:"Your feedback helps us improve the experience for all members."})]}),s.jsxs("div",{className:"space-y-6 py-4",children:[s.jsx("div",{className:"flex justify-center gap-1",children:[1,2,3,4,5].map(W=>s.jsx("button",{type:"button",onClick:()=>g(W),onMouseEnter:()=>E(W),onMouseLeave:()=>E(0),className:"p-1 transition-transform hover:scale-110",children:s.jsx(Bd,{className:hr("h-8 w-8 transition-colors",(v||l)>=W?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},W))}),s.jsx(df,{placeholder:"Tell us about your experience (optional)",value:T,onChange:W=>j(W.target.value),rows:4,className:"resize-none"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Jt,{variant:"outline",onClick:G,className:"flex-1",children:"Maybe Later"}),s.jsx(Jt,{onClick:F,disabled:P||l===0,className:"flex-1",children:P?"Submitting...":"Submit Review"})]})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs(Bc,{children:[s.jsx(pc,{className:"text-center",children:"🎉 Thank you!"}),s.jsx(sf,{className:"text-center",children:"Would you mind sharing your review on Google? It really helps other agents discover LevelUp!"})]}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"We'll copy your review so you can easily paste it."}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Jt,{variant:"outline",onClick:()=>$(!1),className:"flex-1",children:"No Thanks"}),s.jsx(Jt,{onClick:()=>$(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function Ztt(t){const e="=".repeat((4-t.length%4)%4),r=(t+e).replace(/-/g,"+").replace(/_/g,"/"),n=window.atob(r),i=new Uint8Array(n.length);for(let a=0;a{if(!v){c(!1);return}(async()=>{try{const P="vapid_public_key";let C=localStorage.getItem(P);if(!C){const{data:F,error:$}=await Be.functions.invoke("get-vapid-public-key",{body:{}});if($)throw $;if(C=(F==null?void 0:F.vapidPublicKey)??null,!C)throw new Error("Missing VAPID public key");localStorage.setItem(P,C)}g(C);const L=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});p(L),r(Notification.permission);const O=await L.pushManager.getSubscription();i(!!O)}catch(P){console.error("Error initializing push notifications:",P)}finally{c(!1)}})()},[v]);const E=N.useCallback(async()=>{if(!v||!d||!t)return console.error("Push notifications not supported or user not logged in"),!1;if(!l)return lr.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{c(!0);const j=await d.pushManager.getSubscription();if(j){try{await j.unsubscribe()}catch($){console.warn("Failed to unsubscribe existing push subscription:",$)}const{error:F}=await Be.from("push_subscriptions").delete().eq("user_id",t.id);F&&console.warn("Failed to cleanup push_subscriptions rows:",F)}if(Notification.permission!=="granted"){const F=await Notification.requestPermission();if(r(F),F!=="granted")return F==="denied"?lr.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):lr.error("Notification permission was dismissed. Please try again."),!1}const P=Ztt(l);let C;try{C=await d.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:P})}catch(F){console.error("PushManager.subscribe() failed:",F);const $=(F==null?void 0:F.message)||String(F);return $.includes("permission")?lr.error("Push permission denied. Check your browser notification settings."):$.includes("key")||$.includes("VAPID")?lr.error("Push configuration error. Please contact support."):$.includes("AbortError")?lr.error("Push subscription was cancelled. Please try again."):lr.error(`Failed to subscribe: ${$}`),!1}const L=C.toJSON(),{error:O}=await Be.from("push_subscriptions").upsert({user_id:t.id,endpoint:L.endpoint,p256dh_key:L.keys.p256dh,auth_key:L.keys.auth},{onConflict:"user_id,endpoint"});if(O)throw console.error("Error saving subscription:",O),lr.error("Failed to save notification preferences. Please try again."),O;return i(!0),lr.success("Push notifications enabled!"),!0}catch(j){if(console.error("Error subscribing to push notifications:",j),!(j instanceof Error&&j.message.includes("toast"))){const P=j instanceof Error?j.message:"Unknown error";lr.error("Failed to enable push notifications: "+P)}return!1}finally{c(!1)}},[v,d,t,l]),T=N.useCallback(async()=>{if(!d||!t)return!1;try{c(!0);const j=await d.pushManager.getSubscription();return j&&await j.unsubscribe(),await Be.from("push_subscriptions").delete().eq("user_id",t.id),i(!1),lr.success("Push notifications disabled"),!0}catch(j){console.error("Error unsubscribing:",j);const P=j instanceof Error?j.message:"Unknown error";return lr.error("Failed to disable push notifications: "+P),!1}finally{c(!1)}},[d,t]);return{isSupported:v,permission:e,isSubscribed:n,isLoading:a,vapidPublicKey:l,subscribe:E,unsubscribe:T}}const PU="push_notification_prompt_dismissed",Qtt=["/dashboard","/admin"],Jtt=()=>{const{user:t}=_i(),{isSupported:e,isSubscribed:r,isLoading:n,subscribe:i}=Xtt(),a=ms(),[c,d]=N.useState(!1),[p,l]=N.useState(!1),g=Qtt.some(T=>a.pathname===T||a.pathname.startsWith(`${T}/`));N.useEffect(()=>{if(g){d(!1);return}if(!t||!e||r||n||localStorage.getItem(`${PU}_${t.id}`))return;const j=setTimeout(()=>{d(!0)},2e3);return()=>clearTimeout(j)},[t,e,r,n,g]);const v=async()=>{l(!0);const T=await i();l(!1),T&&(t&&localStorage.setItem(`${PU}_${t.id}`,"true"),d(!1))},E=()=>{t&&localStorage.setItem(`${PU}_${t.id}`,"true"),d(!1)};return!e||r||g?null:s.jsx(gl,{open:c,onOpenChange:T=>!T&&E(),children:s.jsxs(Jo,{className:"sm:max-w-md",children:[s.jsxs(Bc,{children:[s.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:s.jsx(PP,{className:"h-6 w-6 text-primary"})}),s.jsx(pc,{className:"text-center",children:"Stay in the Loop!"}),s.jsx(sf,{className:"text-center",children:"Enable push notifications to get alerted when:"})]}),s.jsxs("ul",{className:"my-4 space-y-2 text-sm text-muted-foreground",children:[s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," New events go live"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," Fresh templates are added"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," New toolbox resources drop"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," Social swag updates"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," New newsletters arrive"]}),s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-primary",children:"•"})," Posts in your community groups"]})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Jt,{onClick:v,disabled:p,className:"w-full",children:p?"Enabling...":"Enable Notifications"}),s.jsx(Jt,{variant:"ghost",onClick:E,className:"w-full",children:"Not Now"})]}),s.jsx("p",{className:"text-center text-xs text-muted-foreground",children:"You can always change this in your Profile settings."})]})})},Ale=t=>{let e;const r=new Set,n=(l,g)=>{const v=typeof l=="function"?l(e):l;if(!Object.is(v,e)){const E=e;e=g??(typeof v!="object"||v===null)?v:Object.assign({},e,v),r.forEach(T=>T(e,E))}},i=()=>e,d={setState:n,getState:i,getInitialState:()=>p,subscribe:l=>(r.add(l),()=>r.delete(l))},p=e=t(n,i,d);return d},ert=t=>t?Ale(t):Ale,trt=t=>t;function rrt(t,e=trt){const r=et.useSyncExternalStore(t.subscribe,et.useCallback(()=>e(t.getState()),[t,e]),()=>e(t.getInitialState()));return et.useDebugValue(r),r}const kle=t=>{const e=ert(t),r=n=>rrt(e,n);return Object.assign(r,e),r},nrt=t=>t?kle(t):kle;function irt(t,e){let r;try{r=t()}catch{return}return{getItem:i=>{var a;const c=p=>p===null?null:JSON.parse(p,void 0),d=(a=r.getItem(i))!=null?a:null;return d instanceof Promise?d.then(c):c(d)},setItem:(i,a)=>r.setItem(i,JSON.stringify(a,void 0)),removeItem:i=>r.removeItem(i)}}const t9=t=>e=>{try{const r=t(e);return r instanceof Promise?r:{then(n){return t9(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return t9(n)(r)}}}},srt=(t,e)=>(r,n,i)=>{let a={storage:irt(()=>window.localStorage),partialize:C=>C,version:0,merge:(C,L)=>({...L,...C}),...e},c=!1,d=0;const p=new Set,l=new Set;let g=a.storage;if(!g)return t((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...C)},n,i);const v=()=>{const C=a.partialize({...n()});return g.setItem(a.name,{state:C,version:a.version})},E=i.setState;i.setState=(...C)=>(E(...C),v());const T=t((...C)=>(r(...C),v()),n,i);i.getInitialState=()=>T;let j;const P=()=>{var C,L;if(!g)return;const O=++d;c=!1,p.forEach($=>{var G;return $((G=n())!=null?G:T)});const F=((L=a.onRehydrateStorage)==null?void 0:L.call(a,(C=n())!=null?C:T))||void 0;return t9(g.getItem.bind(g))(a.name).then($=>{if($)if(typeof $.version=="number"&&$.version!==a.version){if(a.migrate){const G=a.migrate($.state,$.version);return G instanceof Promise?G.then(W=>[!0,W]):[!0,G]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,$.state];return[!1,void 0]}).then($=>{var G;if(O!==d)return;const[W,Z]=$;if(j=a.merge(Z,(G=n())!=null?G:T),r(j,!0),W)return v()}).then(()=>{O===d&&(F==null||F(n(),void 0),j=n(),c=!0,l.forEach($=>$(j)))}).catch($=>{O===d&&(F==null||F(void 0,$))})};return i.persist={setOptions:C=>{a={...a,...C},C.storage&&(g=C.storage)},clearStorage:()=>{++d,g==null||g.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>P(),hasHydrated:()=>c,onHydrate:C=>(p.add(C),()=>{p.delete(C)}),onFinishHydration:C=>(l.add(C),()=>{l.delete(C)})},a.skipHydration||P(),j||T},art=srt,JSe=nrt()(art((t,e)=>({cartItems:[],addToCart:(r,n,i=1,a)=>{t(c=>{const d=c.cartItems.findIndex(p=>{var l;return p.product.id===r.id&&((l=p.variant)==null?void 0:l.id)===(n==null?void 0:n.id)});if(d>=0){const p=[...c.cartItems];return p[d].quantity+=i,a&&(p[d].artworkUrl=a),{cartItems:p}}return{cartItems:[...c.cartItems,{product:r,variant:n,quantity:i,artworkUrl:a}]}})},removeFromCart:(r,n)=>{t(i=>({cartItems:i.cartItems.filter(a=>{var c;return!(a.product.id===r&&((c=a.variant)==null?void 0:c.id)===n)})}))},updateQuantity:(r,n,i)=>{t(a=>({cartItems:a.cartItems.map(c=>{var d;return c.product.id===r&&((d=c.variant)==null?void 0:d.id)===n?{...c,quantity:Math.max(1,i)}:c})}))},updateArtwork:(r,n,i)=>{t(a=>({cartItems:a.cartItems.map(c=>{var d;return c.product.id===r&&((d=c.variant)==null?void 0:d.id)===n?{...c,artworkUrl:i}:c})}))},clearCart:()=>t({cartItems:[]}),getItemPrice:r=>{const n=Number(r.product.base_price),i=r.variant?Number(r.variant.price_adjustment):0;return n+i},getSubtotal:()=>{const{cartItems:r,getItemPrice:n}=e();return r.reduce((i,a)=>i+n(a)*a.quantity,0)},getShippingTotal:()=>{const{cartItems:r}=e();return r.reduce((n,i)=>n+Number(i.product.shipping_fee)*i.quantity,0)},getTotal:()=>{const{getSubtotal:r,getShippingTotal:n}=e();return r()+n()}}),{name:"marketplace-cart",partialize:t=>({cartItems:t.cartItems})})),ort="/admin/beta/boost",lrt=N.lazy(()=>Ge(()=>import("./BoostCompanion-v2C1aUhc.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])));function crt(){const{user:t,isAdmin:e}=_i(),{isFeatureEnabled:r}=l5(),{pathname:n}=ms(),i=n==="/main-stage"||n.startsWith("/main-stage/");return!(!!t&&(e||r("boost_mascot"))&&n!==ort&&!i)||!t?null:s.jsx(N.Suspense,{fallback:null,children:s.jsx(lrt,{userId:t.id})})}async function urt(t){const{data:e,error:r}=await Be.rpc("main_stage_list_events",t?{_event_id:t}:{});if(r)throw r;return(e||[]).map(n=>({...n,speakers:Array.isArray(n.speakers)?n.speakers:[],registered_count:Number(n.registered_count)}))}async function ZKt(t){const{data:e,error:r}=await Be.functions.invoke("main-stage-events",{body:t});if(e!=null&&e.error)throw new Error(e.error);if(r)throw new Error(r.message);return e}const eEe="America/New_York",XKt=t=>new Intl.DateTimeFormat("en-US",{timeZone:eEe,weekday:"short",month:"short",day:"numeric"}).format(new Date(t)),QKt=t=>new Intl.DateTimeFormat("en-US",{timeZone:eEe,hour:"numeric",minute:"2-digit",timeZoneName:"short"}).format(new Date(t)),JKt=t=>t.trim().toUpperCase().replace(/\s+/g,"");function eYt(t,e="https://dashboard.relevelup.com"){const r=d=>d.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),n=new Date(t.starts_at),i=new Date(n.getTime()+t.duration_min*6e4),a=`${e}/main-stage?event=${t.id}`;return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:`The Main Stage: ${t.title}`,dates:`${r(n)}/${r(i)}`,details:`Join here: ${a}`,location:a})}`}function tYt(t,e="https://dashboard.relevelup.com"){const r=d=>d.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),n=new Date(t.starts_at),i=new Date(n.getTime()+t.duration_min*6e4),a=`${e}/main-stage?event=${t.id}`,c=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp//Main Stage//EN","BEGIN:VEVENT",`UID:main-stage-${t.id}@relevelup.com`,`DTSTAMP:${r(new Date)}`,`DTSTART:${r(n)}`,`DTEND:${r(i)}`,`SUMMARY:The Main Stage: ${t.title.replace(/[,;]/g," ")}`,`URL:${a}`,`LOCATION:${a}`,"END:VEVENT","END:VCALENDAR"].join(`\r `);return URL.createObjectURL(new Blob([c],{type:"text/calendar"}))}const rYt=t=>{const e=Math.floor(t/1e3);return{d:Math.floor(e/86400),h:Math.floor(e%86400/3600),m:Math.floor(e%3600/60),s:e%60}};function tEe(){const{data:t}=jr({queryKey:["main-stage-live-nav"],queryFn:async()=>(await urt()).some(e=>e.status==="live"),refetchInterval:6e4,staleTime:3e4});return!!t}function drt({activeCategory:t,currentCategory:e,onSelect:r,onHover:n,badgeCounts:i,categories:a=S5}){const c=tEe();return s.jsx("nav",{"aria-label":"Primary",className:"flex flex-col gap-1 p-2",children:a.map(d=>{const p=d.icon,l=t===d.id,g=e===d.id,v=(i==null?void 0:i[d.id])??0,E=`hsl(var(--${d.accent}))`,T=l||g;return s.jsxs("button",{type:"button",onClick:()=>r(d.id),onMouseEnter:()=>n==null?void 0:n(d.id),"aria-expanded":d.route?void 0:l,"aria-controls":d.route?void 0:"primary-nav-flyout","aria-current":g?"page":void 0,style:{color:T?E:void 0,backgroundColor:T?`hsl(var(--${d.accent}) / 0.12)`:void 0},className:hr("group relative flex flex-col items-center gap-1 rounded-xl px-1 py-2.5 text-[11px] font-medium transition-colors","text-sidebar-foreground/70 hover:bg-sidebar-accent/10","focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[g&&s.jsx("span",{className:"absolute left-0 top-1/2 h-6 w-1 -translate-y-1/2 rounded-r",style:{backgroundColor:E}}),s.jsxs("span",{className:"relative",children:[s.jsx(p,{className:"h-5 w-5 transition-colors",style:{color:E}}),d.id==="mainstage"&&c&&s.jsxs("span",{className:"absolute -right-1 -top-1 flex h-3 w-3",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-destructive opacity-75"}),s.jsx("span",{className:"relative inline-flex h-3 w-3 rounded-full bg-destructive"})]}),v>0&&s.jsx("span",{className:"absolute -right-1.5 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[9px] font-bold text-primary-foreground",style:{backgroundColor:E},children:v>9?"9+":v})]}),d.id==="mainstage"&&c?s.jsx("span",{className:"rounded bg-destructive px-1 text-[9px] font-bold uppercase tracking-wider leading-tight text-destructive-foreground",children:"Live"}):s.jsx("span",{className:"leading-tight",children:d.label})]},d.id)})})}function hrt({category:t,top:e,left:r,onClose:n,onNavigate:i,isFavorite:a,favorites:c,onToggleFavorite:d,isCurrent:p,badgeCounts:l}){const g=N.useRef(null);N.useEffect(()=>{const E=j=>{j.key==="Escape"&&n()},T=j=>{var C;if(!g.current)return;const P=j.target;!g.current.contains(P)&&!((C=P==null?void 0:P.closest)!=null&&C.call(P,"[data-nav-rail]"))&&n()};return document.addEventListener("keydown",E),document.addEventListener("mousedown",T),()=>{document.removeEventListener("keydown",E),document.removeEventListener("mousedown",T)}},[n]);const v=E=>{const T=E.icon,j=E.badgeKey?(l==null?void 0:l[E.badgeKey])??0:0;return s.jsxs("div",{className:hr("group flex items-start gap-3 rounded-lg border border-transparent p-2 transition-colors hover:bg-muted/60",p(E)&&"border-primary/30 bg-primary/5"),children:[s.jsxs("button",{type:"button",onClick:()=>i(E),className:"flex flex-1 items-start gap-3 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md",children:[s.jsx("span",{className:hr("mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",E.iconTone==="red"?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"),children:s.jsx(T,{className:hr("h-4 w-4",E.iconTone==="red"&&"fill-destructive/20")})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-sm font-medium text-foreground",children:E.label}),E.badge==="new"&&s.jsx("span",{className:"rounded bg-primary px-1 py-px text-[9px] font-bold uppercase tracking-wide text-primary-foreground",children:"New"}),E.badge==="beta"&&s.jsx("span",{className:"rounded border border-amber-500 bg-amber-500/10 px-1 py-px text-[9px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:"Beta"}),E.locked&&s.jsx(xv,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),j>0&&s.jsx("span",{className:"flex h-4 min-w-4 items-center justify-center rounded-full bg-muted-foreground/15 px-1 text-[10px] font-medium text-muted-foreground",children:j>9?"9+":j})]}),E.description&&s.jsx("span",{className:"mt-0.5 block text-xs leading-snug text-muted-foreground line-clamp-2",children:E.description})]})]}),s.jsx("button",{type:"button","aria-label":a(E)?`Remove ${E.label} from favorites`:`Add ${E.label} to favorites`,onClick:P=>{P.stopPropagation(),d(E)},className:hr("mt-1 rounded p-1 opacity-0 transition-opacity focus:outline-none focus-visible:ring-2 focus-visible:ring-primary group-hover:opacity-100",a(E)&&"opacity-100 text-primary",!a(E)&&"text-muted-foreground/60 hover:text-primary"),children:s.jsx(tF,{className:hr("h-4 w-4",a(E)&&"fill-current")})})]},E.id)};return s.jsxs("div",{id:"primary-nav-flyout",ref:g,role:"dialog","aria-label":`${t.label} navigation`,style:{top:e,left:r,maxHeight:`calc(100vh - ${e+16}px)`},className:"fixed z-40 hidden w-[min(720px,calc(100vw-8rem))] animate-in fade-in-0 slide-in-from-left-2 duration-200 motion-reduce:animate-none overflow-hidden rounded-2xl border border-border bg-card shadow-2xl md:block",children:[s.jsx("div",{className:"flex items-center justify-between border-b border-border px-5 py-3",children:s.jsx("h2",{className:"text-sm font-semibold text-foreground",children:t.label})}),s.jsxs("div",{className:"max-h-[70vh] overflow-y-auto p-4",children:[c.length>0&&s.jsxs("section",{className:"mb-4",children:[s.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[s.jsx(tF,{className:"h-3 w-3 fill-current text-primary"})," My Favorites"]}),s.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:c.map(v)})]}),t.sections.map(E=>s.jsxs("section",{className:"mb-4 last:mb-0",children:[s.jsx("h3",{className:"mb-2 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:E.title}),s.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:E.items.map(v)})]},E.title)),t.sections.length===0&&s.jsx("p",{className:"px-2 py-6 text-sm text-muted-foreground",children:"Nothing here yet."})]})]})}function frt({categories:t,railCategories:e=S5,currentCategory:r,onNavigate:n,onNavigateRoute:i,isCurrent:a,badgeCounts:c,isFavorite:d,onToggleFavorite:p}){const[l,g]=N.useState(r),v=tEe();return s.jsx("nav",{"aria-label":"Primary",className:"p-2",children:e.map(E=>{const T=E.icon;if(E.route)return s.jsxs("button",{type:"button",onClick:()=>i(E.route),className:hr("flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent",r===E.id&&"bg-sidebar-accent"),children:[s.jsx(T,{className:"h-4 w-4",style:{color:`hsl(var(--${E.accent}))`}}),E.label,E.id==="mainstage"&&v&&s.jsxs("span",{className:"ml-auto flex items-center gap-1 rounded-full bg-destructive px-2 py-0.5 text-[10px] font-bold uppercase text-destructive-foreground",children:[s.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-destructive-foreground"}),"Live"]})]},E.id);const j=t.find(C=>C.id===E.id),P=l===E.id;return s.jsxs("div",{children:[s.jsxs("button",{type:"button","aria-expanded":P,onClick:()=>g(P?null:E.id),className:hr("flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent",r===E.id&&"text-primary"),children:[s.jsx(T,{className:"h-4 w-4",style:{color:`hsl(var(--${E.accent}))`}}),E.label,s.jsx(ad,{className:hr("ml-auto h-4 w-4 transition-transform",P&&"rotate-180")})]}),P&&j&&s.jsx("div",{className:"space-y-3 pb-3 pl-4 pr-1",children:j.sections.map(C=>s.jsxs("div",{children:[s.jsx("p",{className:"px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:C.title}),C.items.map(L=>{const O=L.icon,F=L.badgeKey?(c==null?void 0:c[L.badgeKey])??0:0,$=(d==null?void 0:d(L))??!1;return s.jsxs("div",{className:hr("flex w-full items-center gap-2 rounded-md pr-1 hover:bg-sidebar-accent",a(L)&&"bg-sidebar-accent"),children:[s.jsxs("button",{type:"button",onClick:()=>n(L),className:"flex flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-sidebar-foreground",children:[s.jsx(O,{className:hr("h-4 w-4 shrink-0",L.iconTone==="red"&&"text-destructive")}),s.jsx("span",{className:"truncate",children:L.label}),F>0&&s.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-xs text-muted-foreground",children:F>9?"9+":F})]}),p&&s.jsx("button",{type:"button","aria-label":$?`Remove ${L.label} from favorites`:`Add ${L.label} to favorites`,onClick:()=>p(L),className:hr("rounded p-2",$?"text-primary":"text-muted-foreground/60"),children:s.jsx(tF,{className:hr("h-4 w-4",$&&"fill-current")})})]},L.id)})]},C.title))})]},E.id)})})}function rEe(){const t=qa(),e=ms(),r=PSe(),n=N.useCallback(d=>CSe(d,r.ctx),[r.ctx]),i=N.useMemo(()=>{if(e.pathname.startsWith("/apps"))return"apps";if(e.pathname==="/dashboard")return"home";let d=null;for(const p of r.destinations){if(p.external)continue;const l=n(p);l!=="/"&&e.pathname.startsWith(l)&&(!d||l.length>d.len)&&(d={id:p.primaryCategory,len:l.length})}return(d==null?void 0:d.id)??null},[e.pathname,r.destinations,n]),a=N.useCallback(d=>!d.external&&e.pathname===n(d),[e.pathname,n]),c=N.useCallback(d=>{const p=n(d);if(d.external||d.openInNewTab){window.open(p,"_blank","noopener,noreferrer");return}t(p)},[t,n]);return{nav:r,navigate:t,currentCategory:i,isCurrent:a,go:c}}function mrt({communityUnreadCount:t=0,wishlistOpenCount:e=0,flyoutTop:r=64,flyoutLeft:n=80}){const{nav:i,navigate:a,currentCategory:c,isCurrent:d,go:p}=rEe(),[l,g]=N.useState(null),v=N.useRef(null),E=P=>{const C=S5.find(L=>L.id===P);if(C!=null&&C.route){g(null),a(C.route);return}g(L=>L===P?null:P)},T=l?i.categoryMap.get(l):void 0,j={more:t+e};return s.jsxs("div",{"data-nav-rail":!0,className:"flex h-full flex-col",onMouseLeave:()=>{v.current&&window.clearTimeout(v.current),v.current=window.setTimeout(()=>g(null),250)},onMouseEnter:()=>{v.current&&window.clearTimeout(v.current)},children:[s.jsx(drt,{activeCategory:l,currentCategory:c,onSelect:E,categories:i.railCategories,badgeCounts:j}),T&&s.jsx(hrt,{category:T,top:r,left:n,onClose:()=>g(null),onNavigate:P=>{g(null),p(P)},isFavorite:i.isFavorite,favorites:i.favoritesFor(T.id),onToggleFavorite:P=>i.toggleFavorite(i.favoriteKey(P)),isCurrent:d,badgeCounts:{community:t,wishlist:e}})]})}function prt({communityUnreadCount:t=0,wishlistOpenCount:e=0,onNavigated:r}){const{nav:n,navigate:i,currentCategory:a,isCurrent:c,go:d}=rEe();return s.jsx(frt,{categories:n.categories,railCategories:n.railCategories,currentCategory:a,isCurrent:c,isFavorite:n.isFavorite,onToggleFavorite:p=>n.toggleFavorite(n.favoriteKey(p)),badgeCounts:{community:t,wishlist:e},onNavigate:p=>{d(p),r==null||r()},onNavigateRoute:p=>{i(p),r==null||r()}})}const grt=({bannerHeight:t,communityUnreadCount:e,wishlistOpenCount:r,isTrial:n,isExpired:i})=>{const a=qa();return s.jsxs("div",{className:"flex h-full flex-col",children:[s.jsx("div",{className:"flex h-16 shrink-0 items-center justify-center border-b border-sidebar-border",children:s.jsx("button",{type:"button",onClick:()=>a("/dashboard"),"aria-label":"LevelUp home",children:s.jsx("img",{src:l7e,alt:"LevelUp",className:"h-8 w-auto"})})}),s.jsxs(Eg,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[s.jsx(mrt,{communityUnreadCount:e,wishlistOpenCount:r,flyoutTop:t+64,flyoutLeft:80}),n&&!i&&s.jsx("div",{className:"p-2",children:s.jsxs("button",{type:"button",onClick:()=>a("/subscription"),className:"flex w-full flex-col items-center gap-1 rounded-xl border border-amber-500/30 bg-amber-500/10 px-1 py-2 text-[10px] font-semibold text-amber-600 dark:text-amber-400",children:[s.jsx(va,{className:"h-4 w-4"}),"Upgrade"]})})]})]})},yrt=({isTrial:t,isExpired:e,expiresAt:r,communityUnreadCount:n,wishlistOpenCount:i,pathname:a,onSignOut:c,onNavigated:d})=>{const p=qa();return s.jsxs("div",{className:"flex h-full flex-col",children:[s.jsx("div",{className:"flex items-center gap-2 border-b border-sidebar-border p-3",children:s.jsx("img",{src:o7e,alt:"LevelUp",className:"h-8 w-auto"})}),s.jsxs(Eg,{className:"flex-1",children:[t&&!e&&s.jsx("div",{className:"p-2",children:s.jsx("button",{type:"button",onClick:()=>{p("/subscription"),d==null||d()},className:hr("relative mb-1 w-full overflow-hidden rounded-md p-[1.5px]","bg-[linear-gradient(120deg,#f59e0b,#ef4444,#a855f7,#f59e0b)] bg-[length:200%_200%]","animate-gradient-x shadow-lg shadow-amber-500/20"),children:s.jsxs("span",{className:"flex items-center gap-2 rounded-[5px] bg-sidebar px-3 py-2 text-sm font-semibold text-sidebar-foreground",children:[s.jsx(va,{className:"h-4 w-4 text-amber-500"}),s.jsx("span",{className:"flex-1 text-left",children:"Ready to Upgrade?"}),r&&s.jsxs("span",{className:"rounded border border-amber-500/30 bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:[Math.max(0,Math.ceil((Date.parse(r)-Date.now())/864e5)),"d left"]})]})})}),s.jsx(prt,{communityUnreadCount:n,wishlistOpenCount:i,onNavigated:d})]}),s.jsxs("div",{className:"border-t border-sidebar-border p-3",children:[s.jsxs(Jt,{variant:"ghost",size:"sm",className:hr("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",a==="/profile"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>{p("/profile"),d==null||d()},children:[s.jsx(nd,{className:"h-4 w-4"}),"Profile"]}),s.jsxs(Jt,{variant:"ghost",size:"sm",className:hr("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",a==="/credits"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>{p("/credits"),d==null||d()},children:[s.jsx(tK,{className:"h-4 w-4"}),"Credits & Wallet"]}),s.jsxs(Jt,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:c,children:[s.jsx(T4,{className:"h-4 w-4"}),"Sign Out"]})]})]})},gT=({children:t,title:e})=>{var Ae;const{user:r,signOut:n,isAdmin:i,isBrokerageManager:a,isCoach:c,brokerageId:d}=_i(),{isAssistant:p,actingAsAgent:l,hasPermission:g}=i5();YK();const{isImpersonating:v}=Rbe(),T=(p&&!!l?40:0)+(v?40:0),{avatarUrl:j}=D9e(r==null?void 0:r.id),{isTrial:P,isExpired:C,expiresAt:L}=M9e(r==null?void 0:r.id),{isMarketplaceEnabled:O}=l5(),{currentBrief:F,shouldShowPopup:$,hasUnseenBrief:G,openBrief:W,closeBrief:Z,dismissBrief:Q}=qtt(),{unreadCount:ee}=O9e(),{openCount:ie}=F9e();_A();const pe=JSe(He=>He.cartItems).reduce((He,ot)=>He+ot.quantity,0),{hasLeadSite:Le}=ISe();jSe(!Le);const be=qa(),Re=ms(),[Ie,Te]=N.useState(null);N.useEffect(()=>{r!=null&&r.id&&Be.from("profiles").select("name").eq("id",r.id).single().then(({data:He})=>{He!=null&&He.name&&Te(He.name)})},[r==null?void 0:r.id]);const ge=Ie||((Ae=r==null?void 0:r.user_metadata)==null?void 0:Ae.name)||(r==null?void 0:r.email)||"User",[$e,we]=N.useState(!1),ke=He=>He.split(" ").map(ot=>ot[0]).join("").toUpperCase().slice(0,2);return s.jsx(k0e,{children:s.jsxs("div",{className:"min-h-screen bg-background flex",children:[P&&C&&Re.pathname!=="/subscription"&&s.jsx(mtt,{}),typeof document<"u"&&vg.createPortal(s.jsx("aside",{className:"hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto w-20",style:{top:`${T}px`,height:`calc(100vh - ${T}px)`},children:s.jsx(grt,{bannerHeight:T,communityUnreadCount:ee,wishlistOpenCount:ie,isTrial:P,isExpired:C})}),document.body),s.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden md:ml-20",style:{height:`calc(100vh - ${T}px)`,marginTop:`${T}px`},children:[s.jsx("header",{className:"sticky top-0 z-40 bg-card border-b border-border flex-shrink-0",children:s.jsxs("div",{className:"flex items-center justify-between px-6 py-3",children:[s.jsxs(Awe,{open:$e,onOpenChange:we,children:[s.jsx(z9e,{asChild:!0,children:s.jsx(Jt,{variant:"ghost",size:"icon",className:"md:hidden",children:s.jsx(nA,{className:"h-5 w-5"})})}),s.jsx(ZK,{side:"left",className:"w-72 p-0 bg-card",children:s.jsx(yrt,{isTrial:P,isExpired:C,expiresAt:L,communityUnreadCount:ee,wishlistOpenCount:ie,pathname:Re.pathname,onSignOut:n,onNavigated:()=>we(!1)})})]}),s.jsx("div",{className:"flex-1 md:hidden",children:s.jsx("img",{src:c7e,alt:"LevelUp",className:"h-8 w-auto"})}),s.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:s.jsx(Tle,{})}),s.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[P&&!C&&L&&s.jsx(ftt,{expiresAt:L,className:"hidden lg:flex"}),s.jsx("div",{className:"md:hidden",children:s.jsx(Tle,{})}),F&&s.jsx(ptt,{hasUnseenBrief:G,onClick:W}),O&&s.jsxs(Jt,{variant:"ghost",size:"icon",className:"relative",onClick:()=>be("/marketplace/cart"),children:[s.jsx(fve,{className:"h-5 w-5"}),pe>0&&s.jsx("span",{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-primary text-primary-foreground text-xs font-medium flex items-center justify-center",children:pe>99?"99+":pe})]}),s.jsx(Jt,{variant:"ghost",size:"icon","aria-label":"My Calendar",title:"My Calendar",onClick:()=>be("/mission-control/calendar"),children:s.jsx(ig,{className:"h-5 w-5"})}),s.jsx(Let,{}),s.jsx(nQe,{}),s.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",ge.split(" ")[0],"!"]}),s.jsxs(UP,{children:[s.jsx(VP,{asChild:!0,children:s.jsx("button",{className:"focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-full",children:s.jsxs(tf,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[s.jsx(rf,{src:j||void 0}),s.jsx(nf,{className:"bg-primary text-primary-foreground font-medium text-sm",children:ke(ge)})]})})}),s.jsxs(xA,{align:"end",className:"w-48",children:[s.jsxs(lh,{onClick:()=>be("/profile"),className:"cursor-pointer",children:[s.jsx(nd,{className:"h-4 w-4 mr-2"}),"Profile"]}),s.jsxs(lh,{onClick:()=>be("/credits"),className:"cursor-pointer",children:[s.jsx(tK,{className:"h-4 w-4 mr-2"}),"Credits & Wallet"]}),s.jsxs(lh,{onClick:()=>be("/mission-control/integrations"),className:"cursor-pointer",children:[s.jsx(rF,{className:"h-4 w-4 mr-2"}),"Integrations"]}),s.jsxs(lh,{onClick:()=>be("/mission-control/browser-extension"),className:"cursor-pointer",children:[s.jsx(rF,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),s.jsx(iC,{}),s.jsxs(lh,{onClick:n,className:"cursor-pointer text-destructive focus:text-destructive",children:[s.jsx(T4,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),s.jsx(Htt,{children:s.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:t})}),F&&s.jsx(Vtt,{brief:F,open:$,onClose:Z,onDismiss:Q}),s.jsx(Gtt,{}),s.jsx(Ytt,{}),s.jsx(Jtt,{}),s.jsx(crt,{})]})]})})},gt=({children:t,requireAdmin:e=!1,requireBrokerageManager:r=!1})=>{const{user:n,loading:i,rolesLoading:a,isAdmin:c,isBrokerageManager:d}=_i(),p=ms(),l=wwe();if(i||(e||r)&&a)return s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),s.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})});if(!n){const g=p.pathname+p.search+p.hash;return g&&g!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",g),s.jsx(Oi,{to:"/auth",replace:!0})}if(e&&!c)return s.jsx(Oi,{to:"/dashboard",replace:!0});if(r&&!d&&!c)return s.jsx(Oi,{to:"/dashboard",replace:!0});if(l.isRestricted&&!l.isLoading){const g=P9e(p.pathname);if(g&&!l.hasFeature(g))return s.jsx(gT,{title:"Upgrade required",children:s.jsx(L9e,{featureKey:g})})}return s.jsx(s.Fragment,{children:t})};function NU({children:t}){const{isAdmin:e,loading:r,rolesLoading:n}=_i(),{isFeatureEnabled:i,isLoading:a}=l5();return r||n||a?s.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):!e&&!i("staging_studio_enabled")?s.jsx(Oi,{to:"/apps",replace:!0}):s.jsx(gT,{title:"Staging Studio",children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:t})})}var HY={};(function t(e,r,n,i){var a=!!(e.Worker&&e.Blob&&e.Promise&&e.OffscreenCanvas&&e.OffscreenCanvasRenderingContext2D&&e.HTMLCanvasElement&&e.HTMLCanvasElement.prototype.transferControlToOffscreen&&e.URL&&e.URL.createObjectURL),c=typeof Path2D=="function"&&typeof DOMMatrix=="function",d=function(){if(!e.OffscreenCanvas)return!1;try{var we=new OffscreenCanvas(1,1),ke=we.getContext("2d");ke.fillRect(0,0,1,1);var Ae=we.transferToImageBitmap();ke.createPattern(Ae,"no-repeat")}catch{return!1}return!0}();function p(){}function l(we){var ke=r.exports.Promise,Ae=ke!==void 0?ke:e.Promise;return typeof Ae=="function"?new Ae(we):(we(p,p),null)}var g=function(we,ke){return{transform:function(Ae){if(we)return Ae;if(ke.has(Ae))return ke.get(Ae);var He=new OffscreenCanvas(Ae.width,Ae.height),ot=He.getContext("2d");return ot.drawImage(Ae,0,0),ke.set(Ae,He),He},clear:function(){ke.clear()}}}(d,new Map),v=function(){var we=Math.floor(16.666666666666668),ke,Ae,He={},ot=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(ke=function(nt){var tt=Math.random();return He[tt]=requestAnimationFrame(function vt(Vt){ot===Vt||ot+we-1{const{data:e,error:r}=await Be.from("celebration_queue").select("*").eq("user_id",t.id).is("seen_at",null).order("created_at",{ascending:!0});if(r)throw r;return e},enabled:!!(t!=null&&t.id),refetchOnWindowFocus:!0,staleTime:0})}function _rt(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["celebrations"]})}})}function nYt(){const t=Ur(),{user:e}=_i();return zr({mutationFn:async r=>{const{error:n}=await Be.from("celebration_queue").insert({user_id:r.user_id,celebration_type:r.celebration_type,title:r.title,message:r.message||null,points_amount:r.points_amount||null,created_by:e==null?void 0:e.id});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["celebrations"]})}})}const vrt={points_earned:sF,listing_created:Do,deal_closed:Cy,custom:Bd},jle={points_earned:"from-amber-500 to-orange-500",listing_created:"from-emerald-500 to-teal-500",deal_closed:"from-green-500 to-emerald-500",custom:"from-purple-500 to-pink-500"},Cle=()=>{const t=window.location.hostname;return t.startsWith("cards.")||t.startsWith("cardstudio.")||t.startsWith("listings.")||t.startsWith("presentations.")||t.startsWith("guestbook.")||t.startsWith("clients.")||t.startsWith("booking.")||t.startsWith("contacts.")};function brt(){const{user:t}=_i(),e=Ur(),{data:r}=xrt(),n=_rt(),[i,a]=N.useState(null),[c,d]=N.useState(!1),p=N.useCallback(()=>{const T=Date.now()+3e3,j={startVelocity:30,spread:360,ticks:60,zIndex:9999},P=(L,O)=>Math.random()*(O-L)+L,C=setInterval(()=>{const L=T-Date.now();if(L<=0){clearInterval(C);return}const O=50*(L/3e3);Ile({...j,particleCount:O,origin:{x:P(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),Ile({...j,particleCount:O,origin:{x:P(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);N.useEffect(()=>{Cle()||r&&r.length>0&&!i&&(a(r[0]),d(!0),setTimeout(p,100))},[r,i,p]);const l=async()=>{if(i){const E=i.id;d(!1),a(null),e.setQueryData(["celebrations","pending",t==null?void 0:t.id],T=>(T==null?void 0:T.filter(j=>j.id!==E))??[]),await n.mutateAsync(E)}};if(Cle()||!i)return null;const g=vrt[i.celebration_type]||Bd,v=jle[i.celebration_type]||jle.custom;return s.jsx(gl,{open:c,onOpenChange:E=>!E&&l(),children:s.jsxs(Jo,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[s.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${v} opacity-10`}),s.jsxs("div",{className:"relative z-10 py-6",children:[s.jsx("div",{className:"flex justify-center mb-4",children:s.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${v} flex items-center justify-center animate-bounce`,children:s.jsx(g,{className:"w-10 h-10 text-white"})})}),s.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[s.jsx(va,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),s.jsx(va,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),s.jsx(va,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),s.jsxs("h2",{className:"text-2xl font-bold mb-2 bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent",children:["🎉 ",i.title]}),i.points_amount&&i.points_amount>0&&s.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",i.points_amount," points!"]}),i.message&&s.jsx("p",{className:"text-muted-foreground mb-6",children:i.message}),s.jsx(Jt,{onClick:l,className:"w-full",size:"lg",children:"Awesome! 🙌"}),r&&r.length>1&&s.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",r.length-1," more celebration",r.length>2?"s":""," waiting"]})]})]})})}function Mc({className:t,...e}){return s.jsx("div",{className:hr("animate-pulse rounded-md bg-muted",t),...e})}var wrt=Object.defineProperty,SA=(t,e)=>wrt(t,"name",{value:e,configurable:!0}),nEe={Automatic:"automatic",Manual:"manual"},WY="Tabs",[Srt,iYt]=Nl(WY,[yA]),iEe=yA(),[Ert,KY]=Srt(WY),Trt=N.forwardRef(SA(function(e,r){const{__scopeTabs:n,value:i,onValueChange:a,defaultValue:c,orientation:d="horizontal",dir:p,activationMode:l=nEe.Automatic,...g}=e,v=Uv(p),[E,T]=ph({prop:i,onChange:a,defaultProp:c??"",caller:WY});return s.jsx(Ert,{scope:n,baseId:Wl(),value:E,onValueChange:T,orientation:d,dir:v,activationMode:l,children:s.jsx(An.div,{dir:v,"data-orientation":d,...g,ref:r})})},"Tabs")),Art="TabsList",sEe=N.forwardRef(SA(function(e,r){const{__scopeTabs:n,loop:i=!0,...a}=e,c=KY(Art,n),d=iEe(n);return s.jsx(BK,{asChild:!0,...d,orientation:c.orientation,dir:c.dir,loop:i,children:s.jsx(An.div,{role:"tablist","aria-orientation":c.orientation,...a,ref:r})})},"TabsList")),krt="TabsTrigger",aEe=N.forwardRef(SA(function(e,r){const{__scopeTabs:n,value:i,disabled:a=!1,...c}=e,d=KY(krt,n),p=iEe(n),l=YY(d.baseId,i),g=ZY(d.baseId,i),v=i===d.value;return s.jsx(zK,{asChild:!0,...p,focusable:!a,active:v,children:s.jsx(An.button,{type:"button",role:"tab","aria-selected":v,"aria-controls":g,"data-state":v?"active":"inactive","data-disabled":a?"":void 0,disabled:a,id:l,...c,ref:r,onMouseDown:Qr(e.onMouseDown,E=>{!a&&E.button===0&&E.ctrlKey===!1?(E.currentTarget.focus(),d.onValueChange(i)):E.preventDefault()}),onKeyDown:Qr(e.onKeyDown,E=>{a||E.target!==E.currentTarget||[" ","Enter"].includes(E.key)&&d.onValueChange(i)}),onFocus:Qr(e.onFocus,()=>{const E=d.activationMode!==nEe.Manual;!v&&!a&&E&&d.onValueChange(i)})})})},"TabsTrigger")),Irt="TabsContent",oEe=N.forwardRef(SA(function(e,r){const{__scopeTabs:n,value:i,forceMount:a,children:c,...d}=e,p=KY(Irt,n),l=YY(p.baseId,i),g=ZY(p.baseId,i),v=i===p.value,E=N.useRef(v);return N.useEffect(()=>{const T=requestAnimationFrame(()=>E.current=!1);return()=>cancelAnimationFrame(T)},[]),s.jsx(zc,{present:a||v,children:({present:T})=>s.jsx(An.div,{"data-state":v?"active":"inactive","data-orientation":p.orientation,role:"tabpanel","aria-labelledby":l,hidden:!T,id:g,tabIndex:0,...d,ref:r,style:{...e.style,animationDuration:E.current?"0s":void 0},children:T&&c})})},"TabsContent"));function YY(t,e){return`${t}-trigger-${e}`}SA(YY,"makeTriggerId");function ZY(t,e){return`${t}-content-${e}`}SA(ZY,"makeContentId");const XY=Trt,k5=N.forwardRef(({className:t,...e},r)=>s.jsx(sEe,{ref:r,className:hr("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...e}));k5.displayName=sEe.displayName;const Dy=N.forwardRef(({className:t,...e},r)=>s.jsx(aEe,{ref:r,className:hr("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",t),...e}));Dy.displayName=aEe.displayName;const uv=N.forwardRef(({className:t,...e},r)=>s.jsx(oEe,{ref:r,className:hr("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...e}));uv.displayName=oEe.displayName;const fC="#0d0d0d",kF="#1a1a1a",Du="#c9a84c",QP="#f0d78c",pg={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function I5(t){const e={...t,source_page:typeof window<"u"?window.location.pathname:null,user_agent:typeof navigator<"u"?navigator.userAgent:null,referrer:typeof document<"u"?document.referrer:null},{data:r,error:n}=await Be.functions.invoke("public-site-lead",{body:e});if(n)throw n;try{localStorage.setItem(pg.captured,JSON.stringify({email:t.email,ts:Date.now()}))}catch{}return r}function QY(){try{return!!localStorage.getItem(pg.captured)}catch{return!1}}function jrt(){try{const t=localStorage.getItem(pg.captured);return t?JSON.parse(t).email??null:null}catch{return null}}function JY({open:t,onClose:e,children:r}){return N.useEffect(()=>{if(!t)return;const n=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=n}},[t]),t?vg.createPortal(s.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4 animate-in fade-in",style:{background:"rgba(0,0,0,0.82)",backdropFilter:"blur(6px)"},onClick:e,children:s.jsxs("div",{onClick:n=>n.stopPropagation(),className:"relative w-full max-w-md rounded-2xl overflow-hidden animate-in zoom-in-95",style:{background:`linear-gradient(180deg, ${kF} 0%, ${fC} 100%)`,border:`1px solid ${Du}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${Du}22 inset`},children:[s.jsx("button",{onClick:e,className:"absolute right-4 top-4 z-10 rounded-full p-2 text-white/60 hover:text-white hover:bg-white/10 transition","aria-label":"Close",children:s.jsx(Ra,{className:"h-4 w-4"})}),r]})}),document.body):null}function eZ(){const[t,e]=N.useState({first_name:"",email:"",phone:"",area:""}),[r,n]=N.useState(!1),[i,a]=N.useState("");return{values:t,setValues:e,loading:r,setLoading:n,honeypot:i,setHoneypot:a}}function tZ({values:t,setValues:e,honeypot:r,setHoneypot:n,showPhone:i=!0,showArea:a=!0,areaPlaceholder:c="City, ZIP, or neighborhood"}){const d="w-full rounded-lg px-11 py-3 text-sm text-white placeholder:text-white/40 border transition focus:outline-none",p={background:"rgba(255,255,255,0.04)",borderColor:"rgba(255,255,255,0.12)"};return s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"relative",children:[s.jsx(nd,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),s.jsx("input",{type:"text",placeholder:"First name",value:t.first_name,onChange:l=>e({...t,first_name:l.target.value}),className:d,style:p})]}),s.jsxs("div",{className:"relative",children:[s.jsx(rs,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),s.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:t.email,onChange:l=>e({...t,email:l.target.value}),className:d,style:p})]}),i&&s.jsxs("div",{className:"relative",children:[s.jsx(Ui,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),s.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:t.phone,onChange:l=>e({...t,phone:l.target.value}),className:d,style:p})]}),a&&s.jsxs("div",{className:"relative",children:[s.jsx(Va,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),s.jsx("input",{type:"text",placeholder:c,value:t.area,onChange:l=>e({...t,area:l.target.value}),className:d,style:p})]}),s.jsx("input",{type:"text",value:r,onChange:l=>n(l.target.value),tabIndex:-1,autoComplete:"off",className:"absolute -left-[9999px] w-0 h-0 opacity-0","aria-hidden":"true"})]})}function rZ({children:t,disabled:e,onClick:r,type:n="button"}){return s.jsx("button",{type:n,disabled:e,onClick:r,className:"w-full rounded-lg py-3 text-sm font-semibold uppercase tracking-widest transition disabled:opacity-60 disabled:cursor-not-allowed",style:{background:`linear-gradient(180deg, ${QP} 0%, ${Du} 100%)`,color:fC,boxShadow:`0 8px 24px ${Du}55`},children:t})}function Ple({open:t,onClose:e,initialCriteria:r}){const{values:n,setValues:i,loading:a,setLoading:c,honeypot:d,setHoneypot:p}=eZ(),[l,g]=N.useState(!1),v=async E=>{if(E.preventDefault(),!!n.email){c(!0);try{await I5({lead_type:"new_listing_alerts",email:n.email.trim().toLowerCase(),first_name:n.first_name.trim()||void 0,phone:n.phone.trim()||void 0,criteria:{...r||{},...n.area.trim()?{area:n.area.trim()}:{}}}),g(!0);try{localStorage.setItem(pg.stickyDismissed,"1")}catch{}setTimeout(e,2200)}catch{lr.error("Something went wrong. Please try again.")}finally{c(!1)}}};return s.jsx(JY,{open:t,onClose:e,children:s.jsxs("div",{className:"p-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(PP,{className:"h-4 w-4",style:{color:Du}}),s.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:QP},children:"New Listing Alerts"})]}),s.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"Be the first to know."}),s.jsx("p",{className:"text-sm text-white/60 mb-6 leading-relaxed",children:"The best homes go before they hit the market. Get instant alerts the moment new listings match your search."}),l?s.jsxs("div",{className:"py-6 text-center",children:[s.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full flex items-center justify-center",style:{background:`${Du}22`,border:`1px solid ${Du}55`},children:s.jsx(va,{className:"h-5 w-5",style:{color:Du}})}),s.jsx("div",{className:"text-white font-medium",children:"You're on the list."}),s.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Check your inbox for confirmation."})]}):s.jsxs("form",{onSubmit:v,className:"space-y-4",children:[s.jsx(tZ,{values:n,setValues:i,honeypot:d,setHoneypot:p}),s.jsx(rZ,{type:"submit",disabled:a||!n.email,children:a?"Activating…":"Activate Alerts"}),s.jsx("p",{className:"text-[10px] text-white/40 text-center leading-relaxed",children:"We respect your inbox. Unsubscribe any time."})]})]})})}function Crt(){const[t,e]=N.useState(!0),[r,n]=N.useState(!1);N.useEffect(()=>{try{const a=!!localStorage.getItem(pg.stickyDismissed)||QY();e(a)}catch{e(!1)}},[]);const i=()=>{e(!0);try{localStorage.setItem(pg.stickyDismissed,"1")}catch{}};return t?s.jsx(Ple,{open:r,onClose:()=>n(!1)}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-40 animate-in slide-in-from-bottom",style:{background:`linear-gradient(180deg, ${kF} 0%, ${fC} 100%)`,borderTop:`1px solid ${Du}44`,boxShadow:"0 -8px 30px rgba(0,0,0,0.5)"},children:s.jsxs("div",{className:"max-w-6xl mx-auto px-4 sm:px-6 py-3 flex items-center gap-3",children:[s.jsx("div",{className:"hidden sm:flex h-9 w-9 rounded-full items-center justify-center flex-shrink-0",style:{background:`${Du}22`,border:`1px solid ${Du}55`},children:s.jsx(PP,{className:"h-4 w-4",style:{color:Du}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-white text-sm font-medium truncate",children:"Be the first to know when new homes hit the market"}),s.jsx("div",{className:"text-white/50 text-xs hidden sm:block",children:"Instant alerts. No spam. Unsubscribe anytime."})]}),s.jsx("button",{onClick:()=>n(!0),className:"rounded-lg px-4 py-2 text-xs font-semibold uppercase tracking-wider whitespace-nowrap transition hover:brightness-110",style:{background:`linear-gradient(180deg, ${QP} 0%, ${Du} 100%)`,color:fC},children:"Get Alerts"}),s.jsx("button",{onClick:i,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:s.jsx(Ra,{className:"h-4 w-4"})})]})}),s.jsx(Ple,{open:r,onClose:()=>n(!1)})]})}function Prt(){const[t,e]=N.useState(!1),r=N.useRef(!1);N.useEffect(()=>{try{if(sessionStorage.getItem(pg.exitShown)||QY())return}catch{}const E=setTimeout(()=>{r.current=!0},8e3),T=j=>{if(r.current&&!(j.clientY>0)){e(!0);try{sessionStorage.setItem(pg.exitShown,"1")}catch{}window.removeEventListener("mouseleave",T),document.removeEventListener("mouseleave",T)}};return document.addEventListener("mouseleave",T),()=>{clearTimeout(E),document.removeEventListener("mouseleave",T)}},[]);const{values:n,setValues:i,loading:a,setLoading:c,honeypot:d,setHoneypot:p}=eZ(),[l,g]=N.useState(!1),v=async E=>{if(E.preventDefault(),!!n.email){c(!0);try{await I5({lead_type:"exit_intent",email:n.email.trim().toLowerCase(),first_name:n.first_name.trim()||void 0,phone:n.phone.trim()||void 0,criteria:n.area.trim()?{area:n.area.trim()}:void 0}),g(!0),setTimeout(()=>e(!1),2200)}catch{lr.error("Something went wrong. Please try again.")}finally{c(!1)}}};return s.jsx(JY,{open:t,onClose:()=>e(!1),children:s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"h-32 w-full",style:{background:`linear-gradient(135deg, ${fC} 0%, ${kF} 60%, ${Du} 130%)`},children:s.jsx("div",{className:"absolute top-4 left-6",children:s.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:QP},children:"Before You Go"})})}),s.jsxs("div",{className:"p-8 -mt-10",children:[s.jsx("div",{className:"mx-auto mb-5 h-16 w-16 rounded-full flex items-center justify-center",style:{background:kF,border:`1px solid ${Du}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:s.jsx(va,{className:"h-6 w-6",style:{color:Du}})}),s.jsx("h2",{className:"text-2xl font-serif text-white text-center leading-tight mb-2",children:"Wait — get a fresh list of homes."}),s.jsx("p",{className:"text-sm text-white/60 text-center mb-6 leading-relaxed",children:"Drop your email and we'll send you a curated list of homes matching your area, updated weekly."}),l?s.jsxs("div",{className:"py-4 text-center",children:[s.jsx("div",{className:"text-white font-medium",children:"Sent — check your inbox."}),s.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Your list is on its way."})]}):s.jsxs("form",{onSubmit:v,className:"space-y-4",children:[s.jsx(tZ,{values:n,setValues:i,honeypot:d,setHoneypot:p,showPhone:!1}),s.jsx(rZ,{type:"submit",disabled:a||!n.email,children:a?"Sending…":"Send My List"})]})]})]})})}function Nrt(){const[t,e]=N.useState([]);N.useEffect(()=>{try{const d=localStorage.getItem(pg.savedListings);d&&e(JSON.parse(d))}catch{}},[]);const r=d=>{e(d);try{localStorage.setItem(pg.savedListings,JSON.stringify(d))}catch{}},n=N.useCallback(d=>t.includes(d),[t]),i=d=>{t.includes(d)||r([...t,d])},a=d=>r(t.filter(p=>p!==d));return{ids:t,has:n,add:i,remove:a,toggle:d=>t.includes(d)?a(d):i(d)}}function Rrt({listingId:t,listingAddress:e,className:r}){const{has:n,add:i,remove:a}=Nrt(),c=n(t),[d,p]=N.useState(!1),l=()=>{if(c){a(t);return}if(QY()){i(t),lr.success("Saved to your favorites"),I5({lead_type:"saved_listing",email:jrt()||"unknown@local",listing_id:t,listing_address:e}).catch(()=>{});return}p(!0)};return s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:l,className:r,"aria-label":c?"Remove from favorites":"Save to favorites",children:s.jsx(cg,{className:`h-5 w-5 ${c?"fill-current":""}`})}),s.jsx(Lrt,{open:d,onClose:()=>p(!1),listingId:t,listingAddress:e,onSaved:()=>i(t)})]})}function Lrt({open:t,onClose:e,listingId:r,listingAddress:n,onSaved:i}){const{values:a,setValues:c,loading:d,setLoading:p,honeypot:l,setHoneypot:g}=eZ(),v=async E=>{if(E.preventDefault(),!!a.email){p(!0);try{await I5({lead_type:"saved_listing",email:a.email.trim().toLowerCase(),first_name:a.first_name.trim()||void 0,phone:a.phone.trim()||void 0,listing_id:r,listing_address:n}),i(),lr.success("Saved to your favorites"),e()}catch{lr.error("Something went wrong. Please try again.")}finally{p(!1)}}};return s.jsx(JY,{open:t,onClose:e,children:s.jsxs("div",{className:"p-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(cg,{className:"h-4 w-4",style:{color:Du}}),s.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:QP},children:"Save This Home"})]}),s.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"One click to save."}),s.jsx("p",{className:"text-sm text-white/60 mb-6 leading-relaxed",children:"Get an alert if the price drops or the status changes. No spam — just the updates that matter."}),s.jsxs("form",{onSubmit:v,className:"space-y-4",children:[s.jsx(tZ,{values:a,setValues:c,honeypot:l,setHoneypot:g}),s.jsx(rZ,{type:"submit",disabled:d||!a.email,children:d?"Saving…":"Save Home"})]})]})})}var Drt=Object.defineProperty,aa=(t,e)=>Drt(t,"name",{value:e,configurable:!0}),Nle={Horizontal:"horizontal"},Mrt={LTR:"ltr"},lEe=["PageUp","PageDown"],cEe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],uEe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},JP="Slider",[r9,Ort,Frt]=QT(JP),[nZ,sYt]=Nl(JP,[Frt]),[Brt,EA]=nZ(JP),dEe=N.forwardRef(aa(function(e,r){const{name:n,min:i=0,max:a=100,step:c=1,orientation:d=Nle.Horizontal,disabled:p=!1,minStepsBetweenThumbs:l=0,preserveThumbOrder:g=!1,defaultValue:v=[i],value:E,onValueChange:T=aa(()=>{},"onValueChange"),onValueCommit:j=aa(()=>{},"onValueCommit"),inverted:P=!1,form:C,...L}=e,O=N.useRef(new Set),F=N.useRef(0),$=N.useRef(!1),[G,W]=N.useState(null),Q=d===Nle.Horizontal?zrt:$rt,[ee,ie]=N.useState(null),oe=Jn(r,ie),[pe=[],Le]=ph({prop:E,defaultProp:v,onChange:aa(we=>{var Ae;(Ae=[...O.current][F.current])==null||Ae.focus({preventScroll:!0,focusVisible:$.current}),$.current=!1,T(we)},"onChange")}),be=N.useRef(pe),Re=N.useRef(pe);N.useEffect(()=>{const we=C?ee==null?void 0:ee.ownerDocument.getElementById(C):ee==null?void 0:ee.closest("form");if(we instanceof HTMLFormElement){const ke=aa(()=>Le(Re.current),"reset");return we.addEventListener("reset",ke),()=>we.removeEventListener("reset",ke)}},[ee,C,Le]);function Ie(we){const ke=_Ee(pe,we);$e(we,ke)}aa(Ie,"handleSlideStart");function Te(we){$e(we,F.current)}aa(Te,"handleSlideMove");function ge(){String(pe)!==String(be.current)&&j(pe)}aa(ge,"handleSlideEnd");function $e(we,ke,{commit:Ae}={commit:!1}){const He=sZ(c),ot=uj(Math.round((we-i)/c)*c+i,He),nt=lw(ot,[i,a]),tt=l*c;function vt(Ct){const Bt=g?lw(nt,[Ct[ke-1]===void 0?i:Ct[ke-1]+tt,Ct[ke+1]===void 0?a:Ct[ke+1]-tt]):nt,cr=yEe(Ct,Bt,ke);return wEe(cr,tt)?{nextValues:cr,changedIndex:g?ke:cr.indexOf(Bt),hasChanged:String(cr)!==String(Ct)}:null}aa(vt,"getNextValues");const Vt=vt(pe);Vt!=null&&Vt.hasChanged&&W(Vt.nextValues),Le((Ct=[])=>{const Bt=vt(Ct);return Bt?(F.current=Bt.changedIndex,Bt.hasChanged&&Ae&&j(Bt.nextValues),Bt.hasChanged?Bt.nextValues:Ct):Ct})}return aa($e,"updateValues"),s.jsx(Brt,{scope:e.__scopeSlider,name:n,disabled:p,min:i,max:a,valueIndexToChangeRef:F,thumbs:O.current,values:pe,orientation:d,form:C,userRequestedValues:G,children:s.jsx(r9.Provider,{scope:e.__scopeSlider,children:s.jsx(r9.Slot,{scope:e.__scopeSlider,children:s.jsx(Q,{"aria-disabled":p,"data-disabled":p?"":void 0,...L,ref:oe,onPointerDown:Qr(L.onPointerDown,()=>{p||(be.current=pe,$.current=!1)}),min:i,max:a,inverted:P,onSlideStart:p?void 0:Ie,onSlideMove:p?void 0:Te,onSlideEnd:p?void 0:ge,onHomeKeyDown:()=>{p||($.current=!0,$e(i,0,{commit:!0}))},onEndKeyDown:()=>{p||($.current=!0,$e(a,pe.length-1,{commit:!0}))},onStepKeyDown:({event:we,direction:ke})=>{if(!p){$.current=!0;const ot=lEe.includes(we.key)||we.shiftKey&&cEe.includes(we.key)?10:1,nt=F.current,tt=pe[nt],vt=SEe(tt,{min:i,step:c,direction:ke,multiplier:ot});$e(vt,nt,{commit:!0})}}})})})})},"Slider")),[hEe,fEe]=nZ(JP,{startEdge:"left",endEdge:"right",size:"width",direction:1}),zrt=N.forwardRef(aa(function(e,r){const{min:n,max:i,dir:a,inverted:c,onSlideStart:d,onSlideMove:p,onSlideEnd:l,onStepKeyDown:g,...v}=e,[E,T]=N.useState(null),j=Jn(r,T),P=N.useRef(void 0),C=Uv(a),L=C===Mrt.LTR,O=L&&!c||!L&&c;function F($){const G=P.current||E.getBoundingClientRect(),W=[0,G.width],Q=j5(W,O?[n,i]:[i,n]);return P.current=G,Q($-G.left)}return aa(F,"getValueFromPointer"),s.jsx(hEe,{scope:e.__scopeSlider,startEdge:O?"left":"right",endEdge:O?"right":"left",direction:O?1:-1,size:"width",children:s.jsx(mEe,{dir:C,"data-orientation":"horizontal",...v,ref:j,style:{...v.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:$=>{const G=F($.clientX);d==null||d(G)},onSlideMove:$=>{const G=F($.clientX);p==null||p(G)},onSlideEnd:()=>{P.current=void 0,l==null||l()},onStepKeyDown:$=>{const W=uEe[O?"from-left":"from-right"].includes($.key);g==null||g({event:$,direction:W?-1:1})}})})},"SliderHorizontal")),$rt=N.forwardRef(aa(function(e,r){const{min:n,max:i,inverted:a,onSlideStart:c,onSlideMove:d,onSlideEnd:p,onStepKeyDown:l,...g}=e,v=N.useRef(null),E=Jn(r,v),T=N.useRef(void 0),j=!a;function P(C){const L=T.current||v.current.getBoundingClientRect(),O=[0,L.height],$=j5(O,j?[i,n]:[n,i]);return T.current=L,$(C-L.top)}return aa(P,"getValueFromPointer"),s.jsx(hEe,{scope:e.__scopeSlider,startEdge:j?"bottom":"top",endEdge:j?"top":"bottom",size:"height",direction:j?1:-1,children:s.jsx(mEe,{"data-orientation":"vertical",...g,ref:E,style:{...g.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:C=>{const L=P(C.clientY);c==null||c(L)},onSlideMove:C=>{const L=P(C.clientY);d==null||d(L)},onSlideEnd:()=>{T.current=void 0,p==null||p()},onStepKeyDown:C=>{const O=uEe[j?"from-bottom":"from-top"].includes(C.key);l==null||l({event:C,direction:O?-1:1})}})})},"SliderVertical")),mEe=N.forwardRef(aa(function(e,r){const{__scopeSlider:n,onSlideStart:i,onSlideMove:a,onSlideEnd:c,onHomeKeyDown:d,onEndKeyDown:p,onStepKeyDown:l,...g}=e,v=EA(JP,n);return s.jsx(An.span,{...g,ref:r,onKeyDown:Qr(e.onKeyDown,E=>{E.key==="Home"?(d(E),E.preventDefault()):E.key==="End"?(p(E),E.preventDefault()):lEe.concat(cEe).includes(E.key)&&(l(E),E.preventDefault())}),onPointerDown:Qr(e.onPointerDown,E=>{const T=E.target;T.setPointerCapture(E.pointerId),E.preventDefault(),v.thumbs.has(T)?T.focus({preventScroll:!0,focusVisible:!1}):i(E)}),onPointerMove:Qr(e.onPointerMove,E=>{E.target.hasPointerCapture(E.pointerId)&&a(E)}),onPointerUp:Qr(e.onPointerUp,E=>{const T=E.target;T.hasPointerCapture(E.pointerId)&&(T.releasePointerCapture(E.pointerId),c(E))})})},"SliderImpl")),Urt="SliderTrack",Vrt=N.forwardRef(aa(function(e,r){const{__scopeSlider:n,...i}=e,a=EA(Urt,n);return s.jsx(An.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...i,ref:r})},"SliderTrack")),Rle="SliderRange",qrt=N.forwardRef(aa(function(e,r){const{__scopeSlider:n,...i}=e,a=EA(Rle,n),c=fEe(Rle,n),d=N.useRef(null),p=Jn(r,d),l=a.values.length,g=a.values.map(T=>iZ(T,a.min,a.max)),v=l>1?Math.min(...g):0,E=100-Math.max(...g);return s.jsx(An.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...i,ref:p,style:{...e.style,[c.startEdge]:v+"%",[c.endEdge]:E+"%"}})},"SliderRange")),Grt="SliderThumb",[Hrt,pEe]=nZ(Grt),Wrt="SliderThumbProvider";function gEe(t){const{__scopeSlider:e,name:r,children:n,internal_do_not_use_render:i}=t,a=EA(Wrt,e),c=Ort(e),[d,p]=N.useState(null),l=N.useMemo(()=>d?c().findIndex(C=>C.ref.current===d):-1,[c,d]),g=dA(d),v=d?!!a.form||!!d.closest("form"):!0,E=a.values[l],T=r??(a.name?a.name+(a.values.length>1?"[]":""):void 0),j=E===void 0?0:iZ(E,a.min,a.max);N.useEffect(()=>{if(d)return a.thumbs.add(d),()=>{a.thumbs.delete(d)}},[d,a.thumbs]);const P={value:E,name:T,form:a.form,isFormControl:v,index:l,thumb:d,onThumbChange:p,percent:j,size:g};return s.jsx(Hrt,{scope:e,...P,children:EEe(i)?i(P):n})}aa(gEe,"SliderThumbProvider");var RU="SliderThumbTrigger",Krt=N.forwardRef(aa(function(e,r){const{__scopeSlider:n,...i}=e,a=EA(RU,n),c=fEe(RU,n),{index:d,value:p,percent:l,size:g,onThumbChange:v}=pEe(RU,n),E=Jn(r,v),T=xEe(d,a.values.length),j=g==null?void 0:g[c.size],P=j?vEe(j,l,c.direction):0;return s.jsx("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[c.startEdge]:`calc(${l}% + ${P}px)`},children:s.jsx(r9.ItemSlot,{scope:n,children:s.jsx(An.span,{role:"slider","aria-label":e["aria-label"]||T,"aria-valuemin":a.min,"aria-valuenow":p,"aria-valuemax":a.max,"aria-orientation":a.orientation,"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,tabIndex:a.disabled?void 0:0,...i,ref:E,style:p===void 0?{display:"none"}:e.style,onFocus:Qr(e.onFocus,()=>{a.valueIndexToChangeRef.current=d})})})})},"SliderThumbTrigger")),Yrt=N.forwardRef(aa(function(e,r){const{__scopeSlider:n,name:i,...a}=e;return s.jsx(gEe,{__scopeSlider:n,name:i,internal_do_not_use_render:({index:c,isFormControl:d})=>s.jsxs(s.Fragment,{children:[s.jsx(Krt,{...a,ref:r,__scopeSlider:n}),d?s.jsx(Zrt,{__scopeSlider:n},c):null]})})},"SliderThumb")),Lle="SliderBubbleInput",Zrt=N.forwardRef(aa(function({__scopeSlider:e,onInput:r,...n},i){const{index:a,value:c,name:d,form:p}=pEe(Lle,e),{userRequestedValues:l}=EA(Lle,e),g=N.useRef(null),v=Jn(g,i),E=N.useRef(!1),T=N.useRef(c),j=N.useRef(l),P=N.useRef(l);return N.useEffect(()=>{const C=g.current;if(!C)return;const L=window.HTMLInputElement.prototype,F=Object.getOwnPropertyDescriptor(L,"value").set,$=T.current,G=$!==c;T.current=c;const W=l!==P.current;if(P.current=l,G&&F){const Z=l!==j.current;j.current=l;const Q=l==null?void 0:l[a],ee=Z&&(W&&Q!==$||Q===c);E.current=!ee;const ie=new Event("input",{bubbles:!0});F.call(C,c),C.dispatchEvent(ie),E.current=!1}},[a,c,l]),s.jsx(An.input,{style:{display:"none"},name:d,form:p,...n,ref:v,defaultValue:c,onInput:Qr(r,C=>{E.current&&C.stopPropagation()})})},"SliderBubbleInput"));function yEe(t=[],e,r){const n=[...t];return n[r]=e,n.sort((i,a)=>i-a)}aa(yEe,"getNextSortedValues");function iZ(t,e,r){const a=100/(r-e)*(t-e);return lw(a,[0,100])}aa(iZ,"convertValueToPercentage");function xEe(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}aa(xEe,"getLabel");function _Ee(t,e){if(t.length===1)return 0;const r=t.map(i=>Math.abs(i-e)),n=Math.min(...r);return r.indexOf(n)}aa(_Ee,"getClosestValueIndex");function vEe(t,e,r){const n=t/2,a=j5([0,50],[0,n]);return(n-a(e)*r)*r}aa(vEe,"getThumbInBoundsOffset");function bEe(t){return t.slice(0,-1).map((e,r)=>t[r+1]-e)}aa(bEe,"getStepsBetweenValues");function wEe(t,e){if(e>0){const r=bEe(t);return Math.min(...r)>=e}return!0}aa(wEe,"hasMinStepsBetweenValues");function j5(t,e){return r=>{if(t[0]===t[1]||e[0]===e[1])return e[0];const n=(e[1]-e[0])/(t[1]-t[0]);return e[0]+n*(r-t[0])}}aa(j5,"linearScale");function sZ(t){if(!Number.isFinite(t))return 0;const e=t.toString();if(e.includes("e")){const[n,i]=e.split("e"),a=n.split(".")[1]||"",c=Number(i);return Math.max(0,a.length-c)}const r=e.split(".")[1];return r?r.length:0}aa(sZ,"getDecimalCount");function uj(t,e){const r=Math.pow(10,e);return Math.round(t*r)/r}aa(uj,"roundValue");function SEe(t,{min:e,step:r,direction:n,multiplier:i}){const a=sZ(r),c=(t-e)/r,d=Math.round(c),p=uj(d*r+e,a)===uj(t,a);let l;return p?l=d+i*n:n>0?l=Math.ceil(c):l=Math.floor(c),uj(l*r+e,a)}aa(SEe,"getNextStepValue");function EEe(t){return typeof t=="function"}aa(EEe,"isFunction");const dj=N.forwardRef(({className:t,...e},r)=>s.jsxs(dEe,{ref:r,className:hr("relative flex w-full touch-none select-none items-center",t),...e,children:[s.jsx(Vrt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:s.jsx(qrt,{className:"absolute h-full bg-primary"})}),s.jsx(Yrt,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));dj.displayName=dEe.displayName;const Xrt=t=>jr({queryKey:["public-listings",t],queryFn:async()=>{let e=Be.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, listing_class, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).or("lifecycle_stage.is.null,lifecycle_stage.neq.pitch").or("listing_class.is.null,listing_class.neq.commercial").order("created_at",{ascending:!1});if(t!=null&&t.status?e=e.eq("status",t.status):e=e.not("status","in","(sold,temp_off_market,withdrawn)"),t!=null&&t.propertyType&&(e=e.eq("property_type",t.propertyType)),t!=null&&t.city){const i=t.city.replace(/[%,()]/g," ").trim();if(i){const a=`%${i}%`;e=e.or(`city.ilike.${a},neighborhood.ilike.${a},property_address.ilike.${a}`)}}t!=null&&t.minPrice&&(e=e.gte("price",t.minPrice)),t!=null&&t.maxPrice&&(e=e.lte("price",t.maxPrice));const{data:r,error:n}=await e;if(n)throw n;return r}}),Qrt=()=>jr({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:t,error:e}=await Be.from("listings").select("city, state, neighborhood, property_address").eq("is_approved",!0).eq("is_public",!0);if(e)throw e;const r=new Map,n=new Map,i=new Map;return(t||[]).forEach(a=>{if(a.city){const c=`${a.city}|${a.state||""}`.toLowerCase(),d=a.state?`${a.city}, ${a.state}`:a.city,p=r.get(c);p?p.count++:r.set(c,{label:d,city:a.city,state:a.state,count:1})}if(a.neighborhood){const c=`${a.neighborhood}|${a.city||""}`.toLowerCase(),d=a.city?`${a.neighborhood} — ${a.city}`:a.neighborhood,p=n.get(c);p?p.count++:n.set(c,{label:d,city:a.city||"",neighborhood:a.neighborhood,count:1})}if(a.property_address){const c=String(a.property_address).match(/\b(\d{5})(?:-\d{4})?\b/);if(c){const d=c[1],p=i.get(d);p?p.count++:i.set(d,{label:d,zip:d,count:1})}}}),{cities:Array.from(r.values()).sort((a,c)=>c.count-a.count),neighborhoods:Array.from(n.values()).sort((a,c)=>c.count-a.count),zips:Array.from(i.values()).sort((a,c)=>c.count-a.count)}}}),Jrt=t=>jr({queryKey:["public-listing",t],queryFn:async()=>{const e=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t);let r=Be.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, listing_class, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, page_config, page_theme, created_at, updated_at, co_agent_name, co_agent_email, co_agent_phone, co_agent_brokerage, co_agent_photo_url, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);e?r=r.eq("id",t):r=r.eq("slug",t);const{data:n,error:i}=await r.single();if(i)throw i;const a=n;return Array.isArray(a==null?void 0:a.photos)&&(a.photos=[...a.photos].sort((c,d)=>(c.sort_order??0)-(d.sort_order??0)||(d.is_primary?1:0)-(c.is_primary?1:0))),a},enabled:!!t}),ent=()=>zr({mutationFn:async({listingId:t,agentId:e,firstName:r,lastName:n,email:i,phone:a,shareToken:c,leadType:d="info_request",preferredDate:p,preferredTime:l,showingMode:g,message:v})=>{let E=null,T=null;if(c){const{data:O}=await Be.from("listing_shares").select("id, sharing_agent_id").eq("share_token",c).eq("listing_id",t).maybeSingle();O&&(E=O.id,T=O.sharing_agent_id)}const j=crypto.randomUUID(),P={id:j},{error:C}=await Be.from("listing_leads").insert({id:j,listing_id:t,agent_id:T||e,first_name:r,last_name:n,email:i,phone:a,share_id:E,referred_by_agent_id:T,lead_type:d,preferred_date:p||null,preferred_time:l||null,showing_mode:g||null,message:v||null});if(C)throw C;const{error:L}=await Be.functions.invoke("process-listing-lead",{body:{leadId:P.id}});return L&&console.error("Error processing lead:",L),P}}),tnt=()=>zr({mutationFn:async t=>{const{error:e}=await Be.rpc("increment_listing_share_click",{p_share_token:t});if(e)throw e}});function rnt({title:t,subtitle:e,areaLabel:r,sections:n,agent:i,tone:a="light"}){const c=a==="dark",d=c?"text-white/65":"text-muted-foreground",p=c?"border-white/10":"border-border";return s.jsxs("div",{className:c?"text-white":"text-foreground",id:"community-guide-print",children:[s.jsxs("header",{className:`border-b ${p} pb-6 mb-8`,children:[s.jsxs("div",{className:`flex items-center gap-2 text-[11px] uppercase tracking-[0.22em] ${d} mb-3`,children:[s.jsx(eT,{className:"h-3.5 w-3.5"}),"Insider's Community Guide"]}),s.jsx("h1",{className:"font-display text-3xl sm:text-4xl font-semibold leading-tight",children:t}),e&&s.jsx("p",{className:`mt-3 text-base leading-relaxed ${d}`,children:e}),r&&s.jsxs("p",{className:`mt-3 flex items-center gap-1.5 text-sm ${d}`,children:[s.jsx(Va,{className:"h-3.5 w-3.5"}),r]})]}),s.jsx("div",{className:"space-y-10",children:n.map((l,g)=>s.jsxs("section",{children:[s.jsxs("div",{className:"flex items-baseline gap-3 mb-2",children:[s.jsx("span",{className:"font-display text-2xl text-primary font-semibold",children:String(g+1).padStart(2,"0")}),s.jsx("h2",{className:"font-display text-xl sm:text-2xl font-semibold",children:l.heading})]}),l.intro&&s.jsx("p",{className:`text-sm sm:text-base leading-relaxed ${d} mb-4`,children:l.intro}),s.jsx("ul",{className:"space-y-3",children:(l.items??[]).map((v,E)=>s.jsxs("li",{className:`rounded-xl border ${p} ${c?"bg-white/[0.03]":"bg-muted/40"} px-4 py-3`,children:[s.jsx("p",{className:"font-medium text-sm sm:text-base",children:v.name}),v.note&&s.jsx("p",{className:`text-sm mt-1 leading-relaxed ${d}`,children:v.note})]},E))})]},g))}),(i==null?void 0:i.name)&&s.jsxs("footer",{className:`mt-10 pt-6 border-t ${p}`,children:[s.jsxs("div",{className:"flex items-center gap-4",children:[i.avatar_url?s.jsx("img",{src:i.avatar_url,alt:i.name,className:"h-14 w-14 rounded-full object-cover border border-primary/30"}):null,s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:`text-[11px] uppercase tracking-[0.2em] ${d}`,children:"Prepared for you by"}),s.jsx("p",{className:"font-display text-lg font-semibold leading-tight",children:i.name}),i.brokerage&&s.jsx("p",{className:`text-sm ${d}`,children:i.brokerage}),s.jsxs("div",{className:`flex flex-wrap gap-4 mt-1.5 text-sm ${d}`,children:[i.phone&&s.jsxs("a",{href:`tel:${i.phone}`,className:"flex items-center gap-1.5 hover:text-primary",children:[s.jsx(Ui,{className:"h-3.5 w-3.5"}),i.phone]}),i.email&&s.jsxs("a",{href:`mailto:${i.email}`,className:"flex items-center gap-1.5 hover:text-primary",children:[s.jsx(rs,{className:"h-3.5 w-3.5"}),i.email]})]})]})]}),s.jsxs("p",{className:`mt-4 text-sm ${d}`,children:["Thinking about a move in ",r||"the area","? Reach out any time — happy to share what never makes it online."]})]})]})}const ND="border-white/15 bg-white/5 text-white placeholder:text-white/40";function nnt({listingId:t}){const[e,r]=N.useState(null),[n,i]=N.useState({firstName:"",lastName:"",email:"",phone:""}),[a,c]=N.useState(!1),[d,p]=N.useState(null),[l,g]=N.useState(!1);if(N.useEffect(()=>{let E=!1;return Be.functions.invoke("community-guide-public",{body:{action:"teaser",listingId:t}}).then(({data:T})=>{!E&&T&&r(T)}).catch(()=>{}),()=>{E=!0}},[t]),!(e!=null&&e.available))return null;const v=async E=>{if(E.preventDefault(),!n.firstName.trim()||!n.email.trim()){lr.error("Please add your name and email.");return}c(!0);try{const{data:T,error:j}=await Be.functions.invoke("community-guide-public",{body:{action:"unlock",listingId:t,...n}});if(j||T!=null&&T.error)throw new Error((T==null?void 0:T.error)||"Something went wrong.");p(T),g(!0),lr.success("Your guide is ready!")}catch(T){lr.error((T==null?void 0:T.message)||"We could not send your guide. Please try again.")}finally{c(!1)}};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.2em] text-white/60 mb-3",children:[s.jsx(eT,{className:"h-3.5 w-3.5"}),"Free Community Guide"]}),s.jsx("h3",{className:"font-display text-xl text-white font-medium leading-snug",children:e.title}),e.subtitle&&s.jsx("p",{className:"text-sm text-white/60 mt-2 leading-relaxed",children:e.subtitle}),(e.teaser??[]).length>0&&s.jsx("ul",{className:"mt-4 space-y-2",children:e.teaser.map((E,T)=>s.jsxs("li",{className:"flex gap-2 text-sm text-white/70",children:[s.jsx(ql,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),E]},T))}),d?s.jsxs(Jt,{className:"w-full mt-5",onClick:()=>g(!0),children:[s.jsx(eT,{className:"h-4 w-4 mr-2"}),"Read your guide"]}):s.jsxs("form",{onSubmit:v,className:"mt-5 space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{htmlFor:"cg-first",className:"text-xs text-white/60",children:"First name"}),s.jsx(hn,{id:"cg-first",value:n.firstName,onChange:E=>i({...n,firstName:E.target.value}),className:ND,required:!0})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{htmlFor:"cg-last",className:"text-xs text-white/60",children:"Last name"}),s.jsx(hn,{id:"cg-last",value:n.lastName,onChange:E=>i({...n,lastName:E.target.value}),className:ND})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{htmlFor:"cg-email",className:"text-xs text-white/60",children:"Email"}),s.jsx(hn,{id:"cg-email",type:"email",value:n.email,onChange:E=>i({...n,email:E.target.value}),className:ND,required:!0})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{htmlFor:"cg-phone",className:"text-xs text-white/60",children:"Cell phone"}),s.jsx(hn,{id:"cg-phone",type:"tel",value:n.phone,onChange:E=>i({...n,phone:E.target.value}),className:ND})]}),s.jsxs(Jt,{type:"submit",className:"w-full",disabled:a,children:[a?s.jsx(gh,{className:"h-4 w-4 mr-2 animate-spin"}):s.jsx($u,{className:"h-4 w-4 mr-2"}),a?"Preparing your guide…":"Get the free guide"]}),s.jsxs("p",{className:"text-[11px] text-white/50 flex items-center gap-1.5 justify-center",children:[s.jsx(xv,{className:"h-3 w-3"}),"Instant access. We never share your details."]})]})]}),s.jsx(gl,{open:l,onOpenChange:g,children:s.jsx(Jo,{className:"max-w-2xl p-0 gap-0",children:s.jsx(Eg,{className:"max-h-[82vh]",children:s.jsxs("div",{className:"p-6 sm:p-8",children:[s.jsx("div",{id:"community-guide-print",children:d&&s.jsx(rnt,{title:d.title,subtitle:d.subtitle,areaLabel:d.area_label,sections:d.sections??[],agent:d.agent})}),s.jsx("div",{className:"mt-8 flex justify-end print:hidden",children:s.jsxs(Jt,{variant:"outline",onClick:()=>int(d==null?void 0:d.title),children:[s.jsx($u,{className:"h-4 w-4 mr-2"}),"Save as PDF"]})})]})})})})]})}function int(t){const e=document.getElementById("community-guide-print");if(!e)return window.print();const r=e.cloneNode(!0);r.removeAttribute("id"),r.setAttribute("data-print-root",""),document.body.appendChild(r),document.body.classList.add("printing-doc");const n=document.title;t&&(document.title=t);let i=!1;const a=()=>{i||(i=!0,r.remove(),document.body.classList.remove("printing-doc"),document.title=n,window.removeEventListener("afterprint",a))};window.addEventListener("afterprint",a);try{window.print()}finally{setTimeout(a,1e3)}}const Dle={sale:"For Sale",lease:"For Lease",sale_or_lease:"For Sale or Lease",investment:"Investment Offering"},TEe={office:"Office",retail:"Retail",industrial:"Industrial",flex:"Flex / R&D",multifamily:"Multifamily",land:"Land",medical:"Medical",hospitality:"Hospitality",self_storage:"Self Storage",mixed_use:"Mixed Use",special_purpose:"Special Purpose"},aYt=["NNN","Modified Gross","Full Service","Gross","Absolute Net","Ground Lease"],snt={sf_year:"/SF/YR",sf_month:"/SF/MO",month:"/MO"},ant={om:"Offering Memorandum",flyer:"Flyer",rent_roll:"Rent Roll",financials:"Financials",survey:"Survey",site_plan:"Site Plan",lease:"Lease Documents",other:"Other"},oYt={public:"Open download",email:"Email required",nda:"NDA required"},ont={principal:"Principal / Investor",broker:"Broker",tenant:"Tenant / User",lender:"Lender",other:"Other"},lYt=[{key:"pitch",label:"Pitch",blurb:"Competing for the assignment"},{key:"won",label:"Won",blurb:"Assignment secured"},{key:"launched",label:"Launch",blurb:"Microsite & materials live"},{key:"marketing",label:"Market",blurb:"Campaign in market"},{key:"under_contract",label:"Under Contract",blurb:"Deal in escrow"},{key:"closed",label:"Closed",blurb:"Transaction complete"}],LU=[{key:"photos",label:"Professional photography uploaded",detail:"At least 6 images for the microsite hero and gallery"},{key:"financials",label:"Financial snapshot completed",detail:"NOI, cap rate, occupancy or lease rate entered"},{key:"highlights",label:"Investment highlights written",detail:"3–6 reasons this opportunity matters"},{key:"om",label:"Offering Memorandum uploaded",detail:"Gated OM available for qualified prospects"},{key:"microsite",label:"Microsite published",detail:"Public commercial microsite is live"},{key:"email",label:"Broker & investor email sent",detail:"First distribution to your database"},{key:"social",label:"Social / LinkedIn announcement",detail:"Launch post published"},{key:"signage",label:"Signage & QR deployed",detail:"On-site QR code linking to the microsite"}],cYt=[{label:"Day 1 — Positioning & pricing",detail:"Finalize the pricing strategy, opportunity narrative and target buyer/tenant profile."},{label:"Day 2–4 — Institutional-grade materials",detail:"Photography, Offering Memorandum, investor teaser and branded flyer produced."},{label:"Day 5 — Property microsite goes live",detail:"Dedicated commercial microsite with gated OM, tour requests and full analytics."},{label:"Week 1 — Targeted broker & investor outreach",detail:"Direct email to qualified buyers, brokers and 1031 investors in the LevelUp database."},{label:"Week 2 — Digital & social distribution",detail:"LinkedIn campaign, syndication and QR-coded on-site signage."},{label:"Weekly — Owner activity reporting",detail:"Every week you receive views, OM requests, downloads, tours and prospect-level interest."}];function Gm(t,e=0){return t==null||Number.isNaN(Number(t))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:e}).format(Number(t))}function Mle(t){if(t==null)return null;const e=Number(t);return Number.isNaN(e)?null:e>=1e6?`$${(e/1e6).toFixed(e>=1e7?1:2).replace(/\.0+$/,"")}M`:e>=1e3?`$${Math.round(e/1e3)}K`:Gm(e)}function n9(t){return t==null?null:`${new Intl.NumberFormat("en-US").format(Number(t))} SF`}function AEe(t,e=2){return t==null?null:`${Number(t).toFixed(e).replace(/\.?0+$/,"")}%`}function i9(t){if(!(t!=null&&t.lease_rate))return null;const e=snt[t.lease_rate_unit||"sf_year"]??"";return`${t.lease_rate_unit==="month"?Gm(t.lease_rate):`$${Number(t.lease_rate).toFixed(2).replace(/\.00$/,"")}`}${e}${t.lease_type?` ${t.lease_type}`:""}`}function Ole(t,e){if(!t)return Gm(e)??"Price on request";if(t.deal_type==="lease")return i9(t)??"Rate on request";const r=t.asking_price??e;if(t.deal_type==="sale_or_lease"){const n=[Gm(r),i9(t)].filter(Boolean);return n.length?n.join(" · "):"Price on request"}return Gm(r)??"Price on request"}function lnt(t,e){return e!=null&&e.opportunity_title?e.opportunity_title:e!=null&&e.hide_address||e!=null&&e.is_confidential?`Confidential ${e!=null&&e.commercial_type?TEe[e.commercial_type]:"Commercial"} Opportunity`:t.property_address||`${t.city??""}, ${t.state??""}`}function cnt(t,e){const r=(e==null?void 0:e.submarket)||t.neighborhood,n=[t.city,t.state].filter(Boolean).join(", ");return r?`${r} · ${n}`:n}function uYt(t,e){var a;const r=(t==null?void 0:t.launch_checklist)??{},n=[],i={photos:e.photoCount>=6,financials:!!(t!=null&&t.noi||t!=null&&t.cap_rate||t!=null&&t.lease_rate||t!=null&&t.occupancy_pct),highlights:(((a=t==null?void 0:t.investment_highlights)==null?void 0:a.length)??0)>=3,om:e.hasOm,microsite:e.isPublic};for(const c of LU)(i[c.key]||r[c.key])&&n.push(c.key);return{done:n,total:LU.length,score:Math.round(n.length/LU.length*100)}}const dYt={om_download:10,om_request:9,tour_request:15,inquiry:12,doc_download:8,om_view:5,gallery_view:2,page_view:1,contact_click:4,share_click:2,email_click:3,email_open:1,map_view:1};function hYt(t){return t>=30?{label:"Hot",tone:"bg-amber-500/15 text-amber-600 border-amber-500/30"}:t>=12?{label:"Warm",tone:"bg-orange-500/10 text-orange-600 border-orange-500/20"}:{label:"Tracking",tone:"bg-muted text-muted-foreground border-border"}}const fYt="https://commercial.relevelup.com",gg=Be;function mYt(t){return jr({queryKey:["commercial-details",t],queryFn:async()=>{const{data:e,error:r}=await gg.from("commercial_listing_details").select("*").eq("listing_id",t).maybeSingle();if(r)throw r;return e??null},enabled:!!t})}function pYt(){const t=Ur(),{user:e}=_i();return zr({mutationFn:async({listingId:r,values:n})=>{const{data:i,error:a}=await gg.from("commercial_listing_details").upsert({listing_id:r,agent_id:e==null?void 0:e.id,...n},{onConflict:"listing_id"}).select().single();if(a)throw a;return i},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["commercial-details",n.listingId]}),t.invalidateQueries({queryKey:["listing",n.listingId]})}})}function gYt(t){return jr({queryKey:["commercial-pitch",t],queryFn:async()=>{const{data:e,error:r}=await gg.from("commercial_pitch_details").select("*").eq("listing_id",t).maybeSingle();if(r)throw r;return e??null},enabled:!!t})}function yYt(){const t=Ur(),{user:e}=_i();return zr({mutationFn:async({listingId:r,values:n})=>{const{data:i,error:a}=await gg.from("commercial_pitch_details").upsert({listing_id:r,agent_id:e==null?void 0:e.id,...n},{onConflict:"listing_id"}).select().single();if(a)throw a;return i},onSuccess:(r,n)=>t.invalidateQueries({queryKey:["commercial-pitch",n.listingId]})})}function xYt(){const t=Ur();return zr({mutationFn:async({listingId:e,stage:r,lostReason:n})=>{const i=r==="won",a=r==="lost",c={lifecycle_stage:r};i&&(c.status="coming_soon"),a&&(c.is_public=!1,c.allow_sharing=!1);const{error:d}=await gg.from("listings").update(c).eq("id",e);if(d)throw d;return(i||a)&&await gg.from("commercial_pitch_details").update({outcome:i?"won":"lost",won_at:i?new Date().toISOString():null,lost_at:a?new Date().toISOString():null,lost_reason:a?n??null:null}).eq("listing_id",e),r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["listing",r.listingId]}),t.invalidateQueries({queryKey:["commercial-pitch",r.listingId]}),t.invalidateQueries({queryKey:["my-listings"]}),t.invalidateQueries({queryKey:["listings"]})}})}function _Yt(){const t=Ur();return zr({mutationFn:async({listingId:e,values:r})=>{const{error:n}=await gg.from("listings").update(r).eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["listing",r.listingId]}),t.invalidateQueries({queryKey:["my-listings"]})}})}function vYt(t,e=90){return jr({queryKey:["commercial-engagement",t,e],queryFn:async()=>{const r=new Date(Date.now()-e*864e5).toISOString(),{data:n,error:i}=await gg.from("commercial_engagement_events").select("*").eq("listing_id",t).gte("created_at",r).order("created_at",{ascending:!1}).limit(1e3);if(i)throw i;return n??[]},enabled:!!t})}function bYt(t){return jr({queryKey:["commercial-leads",t],queryFn:async()=>{const{data:e,error:r}=await gg.from("listing_leads").select("*").eq("listing_id",t).order("created_at",{ascending:!1});if(r)throw r;return e??[]},enabled:!!t})}const Fle="lu_commercial_session";function kEe(){try{let t=localStorage.getItem(Fle);return t||(t=crypto.randomUUID(),localStorage.setItem(Fle,t)),t}catch{return"anonymous"}}async function IS(t,e,r={}){try{await gg.from("commercial_engagement_events").insert({listing_id:t,event_type:e,session_id:kEe(),source:typeof document<"u"&&document.referrer||null,metadata:r})}catch{}}const unt={om_request:{eyebrow:"Confidential materials",title:"Request the Offering Memorandum",blurb:"Complete the form below and the offering package will be released to you immediately.",cta:"Request access"},tour_request:{eyebrow:"Property tour",title:"Schedule a tour",blurb:"Tell us who you represent and preferred timing — the listing broker will confirm directly.",cta:"Request tour"},investor_inquiry:{eyebrow:"Investment inquiry",title:"Request information",blurb:"Send a note to the listing broker about this opportunity.",cta:"Send inquiry"}};function dnt({open:t,onOpenChange:e,listingId:r,kind:n,documentId:i,requiresNda:a,brokerName:c}){const d=unt[n],[p,l]=N.useState({firstName:"",lastName:"",email:"",phone:"",company:"",role:"principal",message:""}),[g,v]=N.useState(!1),[E,T]=N.useState(!1),[j,P]=N.useState(null),C=async()=>{if(!p.firstName.trim()||!p.email.trim()){lr.error("Name and email are required");return}if(a&&n==="om_request"&&!g){lr.error("Please acknowledge the confidentiality terms");return}T(!0);try{const{data:L,error:O}=await Be.functions.invoke("commercial-lead",{body:{listingId:r,documentId:i??null,leadType:n,firstName:p.firstName,lastName:p.lastName,email:p.email,phone:p.phone||null,company:p.company||null,role:p.role,message:p.message||null,ndaAccepted:g,sessionId:kEe()}});if(O)throw O;if(L!=null&&L.error)throw new Error(L.error);P({signedUrl:(L==null?void 0:L.signedUrl)??null,fileName:(L==null?void 0:L.fileName)??null}),L!=null&&L.signedUrl&&window.open(L.signedUrl,"_blank")}catch(L){lr.error(L.message||"Something went wrong. Please try again.")}finally{T(!1)}};return s.jsx(gl,{open:t,onOpenChange:L=>{e(L),L||P(null)},children:s.jsxs(Jo,{className:"max-w-lg overflow-hidden border-white/10 bg-[#0b0f14] p-0 text-white",children:[s.jsxs("div",{className:"border-b border-white/10 bg-gradient-to-b from-white/[0.06] to-transparent px-7 py-6",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:d.eyebrow}),s.jsx("h2",{className:"mt-2 font-serif text-2xl",children:j?"Access granted":d.title}),s.jsx("p",{className:"mt-1.5 text-sm text-white/60",children:j?j.signedUrl?"Your download has opened in a new tab. The secure link expires in 30 minutes.":`Your request has been sent${c?` to ${c}`:""}. You'll hear back shortly.`:d.blurb})]}),j?s.jsxs("div",{className:"space-y-4 px-7 py-7",children:[s.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-400/20 bg-emerald-400/10 px-4 py-3",children:[s.jsx(od,{className:"h-5 w-5 text-emerald-400"}),s.jsx("p",{className:"text-sm text-white/80",children:j.fileName??"Request received"})]}),j.signedUrl&&s.jsx(Jt,{className:"w-full",onClick:()=>window.open(j.signedUrl,"_blank"),children:"Download again"}),s.jsx(Jt,{variant:"ghost",className:"w-full text-white/60 hover:text-white",onClick:()=>e(!1),children:"Close"})]}):s.jsxs("div",{className:"space-y-4 px-7 py-6",children:[s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(ib,{label:"First name *",children:s.jsx(hn,{value:p.firstName,onChange:L=>l({...p,firstName:L.target.value}),className:"border-white/15 bg-white/5 text-white"})}),s.jsx(ib,{label:"Last name",children:s.jsx(hn,{value:p.lastName,onChange:L=>l({...p,lastName:L.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),s.jsx(ib,{label:"Email *",children:s.jsx(hn,{type:"email",value:p.email,onChange:L=>l({...p,email:L.target.value}),className:"border-white/15 bg-white/5 text-white"})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(ib,{label:"Company",children:s.jsx(hn,{value:p.company,onChange:L=>l({...p,company:L.target.value}),className:"border-white/15 bg-white/5 text-white"})}),s.jsx(ib,{label:"Phone",children:s.jsx(hn,{value:p.phone,onChange:L=>l({...p,phone:L.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),s.jsx(ib,{label:"I am a *",children:s.jsxs(Xo,{value:p.role,onValueChange:L=>l({...p,role:L}),children:[s.jsx(Mo,{className:"border-white/15 bg-white/5 text-white",children:s.jsx(Qo,{})}),s.jsx(Oo,{children:Object.entries(ont).map(([L,O])=>s.jsx($n,{value:L,children:O},L))})]})}),n!=="om_request"&&s.jsx(ib,{label:"Message",children:s.jsx(df,{rows:3,value:p.message,onChange:L=>l({...p,message:L.target.value}),className:"border-white/15 bg-white/5 text-white",placeholder:n==="tour_request"?"Preferred dates and times…":"Your question…"})}),a&&n==="om_request"&&s.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-xl border border-white/10 bg-white/[0.04] p-3",children:[s.jsx(XP,{checked:g,onCheckedChange:L=>v(!!L),className:"mt-0.5 border-white/30"}),s.jsxs("span",{className:"text-xs leading-relaxed text-white/65",children:[s.jsx(QW,{className:"mr-1 inline h-3.5 w-3.5"}),"I acknowledge these materials are confidential and agree not to distribute them without the listing broker's written consent."]})]}),s.jsxs(Jt,{className:"w-full",size:"lg",onClick:C,disabled:E,children:[E?s.jsx(gh,{className:"mr-2 h-4 w-4 animate-spin"}):s.jsx(xv,{className:"mr-2 h-4 w-4"}),d.cta]}),s.jsx("p",{className:"text-center text-[11px] text-white/40",children:"Your information is shared only with the listing broker."})]})]})})}function ib({label:t,children:e}){return s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{className:"text-[11px] font-medium uppercase tracking-wider text-white/50",children:t}),e]})}function IEe(t){if(!t)return[];const e=[],r=(n,i)=>{i&&e.push({label:n,value:i})};return r("Cap Rate",AEe(t.cap_rate)),r("NOI",Mle(t.noi)),r("Occupancy",t.occupancy_pct!=null?`${Math.round(Number(t.occupancy_pct))}%`:null),r("Building SF",n9(t.building_sf)),r("Available SF",n9(t.available_sf)),r("Lot Size",t.lot_acres!=null?`${Number(t.lot_acres)} AC`:null),r("Units",t.units!=null?String(t.units):null),r("Price / SF",t.price_per_sf!=null?Gm(t.price_per_sf,2):null),r("Price / Unit",Mle(t.price_per_unit)),r("Lease Rate",t.deal_type!=="sale"?i9(t):null),r("Year Built",null),r("Zoning",t.zoning??null),e}function wYt({details:t,className:e="",tone:r="light"}){const n=IEe(t).slice(0,8);if(!n.length)return null;const i=r==="dark";return s.jsx("div",{className:`grid gap-px overflow-hidden rounded-xl border ${i?"border-white/10 bg-white/10":"bg-border"} sm:grid-cols-2 lg:grid-cols-4 ${e}`,children:n.map(a=>s.jsxs("div",{className:`${i?"bg-[#0b0f14]":"bg-card"} px-5 py-4`,children:[s.jsx("p",{className:`text-[10px] font-semibold uppercase tracking-[0.18em] ${i?"text-white/45":"text-muted-foreground"}`,children:a.label}),s.jsx("p",{className:`mt-1.5 text-xl font-semibold tabular-nums ${i?"text-white":""}`,children:a.value})]},a.label))})}function hnt(t){return jr({queryKey:["commercial-microsite",t],queryFn:async()=>{const{data:e,error:r}=await Be.functions.invoke("commercial-public",{body:{slug:t}});if(r)throw r;if(e!=null&&e.error)throw new Error(e.error);return e},enabled:!!t})}function fnt({slug:t}){var oe,pe;const{data:e,isLoading:r,error:n}=hnt(t),[i,a]=N.useState(null),[c,d]=N.useState(null),p=e==null?void 0:e.listing,l=(e==null?void 0:e.details)??void 0,g=(e==null?void 0:e.documents)??[],v=(p==null?void 0:p.photos)??[],E=p==null?void 0:p.agent,T=!!(l!=null&&l.is_confidential||l!=null&&l.hide_address),j=N.useMemo(()=>IEe(l).slice(0,8),[l]);if(N.useEffect(()=>{p!=null&&p.id&&IS(p.id,"page_view",{slug:t})},[p==null?void 0:p.id,t]),N.useEffect(()=>{if(i===null)return;const Le=be=>{be.key==="Escape"&&a(null),be.key==="ArrowRight"&&a(Re=>Re===null?Re:(Re+1)%v.length),be.key==="ArrowLeft"&&a(Re=>Re===null?Re:(Re-1+v.length)%v.length)};return window.addEventListener("keydown",Le),()=>window.removeEventListener("keydown",Le)},[i,v.length]),r)return s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14]",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/70"})});if(n||!p)return s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14] px-6 text-center text-white/60",children:"This offering is no longer available."});const P=lnt(p,l),C=cnt(p,l),L=p.latitude&&p.longitude?`${p.latitude},${p.longitude}`:T?[l==null?void 0:l.submarket,p.city,p.state].filter(Boolean).join(", ")||null:[p.property_address,p.city,p.state].filter(Boolean).join(", ")||null,O=(oe=v[0])==null?void 0:oe.photo_url,F=(l==null?void 0:l.tenants)??[],$=(l==null?void 0:l.spaces)??[],G=(l==null?void 0:l.demographics)??{},W=(l==null?void 0:l.traffic_counts)??[],Z=(l==null?void 0:l.investment_highlights)??[],Q=(l==null?void 0:l.property_highlights)??[],ee=["radius_1","radius_3","radius_5"].some(Le=>(G==null?void 0:G[Le])&&Object.values(G[Le]).some(Boolean)),ie=(Le,be)=>{d({kind:Le,documentId:be}),IS(p.id,Le==="om_request"?"om_request":Le,{})};return s.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[s.jsxs(mc,{children:[s.jsx("title",{children:`${P} | ${C}`}),s.jsx("meta",{name:"description",content:(p.description??"").slice(0,155)||`${Dle[(l==null?void 0:l.deal_type)??"sale"]} — ${C}`}),T&&s.jsx("meta",{name:"robots",content:"noindex,nofollow"}),s.jsx("meta",{property:"og:title",content:P}),s.jsx("meta",{property:"og:type",content:"website"})]}),s.jsx("header",{className:"fixed inset-x-0 top-0 z-40 border-b border-white/10 bg-[#0b0f14]/80 backdrop-blur",children:s.jsxs("div",{className:"mx-auto flex max-w-7xl items-center justify-between px-6 py-3.5 md:px-10",children:[s.jsxs("a",{href:typeof window<"u"&&window.location.hostname.startsWith("commercial.")?"/":"/public/commercial",className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.22em] text-white/70 transition-colors hover:text-white",children:[s.jsx("span",{"aria-hidden":!0,children:"←"})," All opportunities"]}),s.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.22em] text-white/45",children:"LevelUp Commercial"})]})}),s.jsxs("section",{className:"relative min-h-[86vh] w-full overflow-hidden",children:[O?s.jsx("img",{src:O,alt:P,className:"absolute inset-0 h-full w-full object-cover"}):s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/60 to-[#0b0f14]/30"}),s.jsxs("div",{className:"relative mx-auto flex min-h-[86vh] max-w-7xl flex-col justify-end px-6 pb-16 pt-24 md:px-10",children:[s.jsxs("div",{className:"mb-5 flex flex-wrap items-center gap-2.5",children:[s.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:Dle[(l==null?void 0:l.deal_type)??"sale"]}),(l==null?void 0:l.commercial_type)&&s.jsx("span",{className:"rounded-full border border-white/15 bg-white/5 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-white/70",children:TEe[l.commercial_type]}),T&&s.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-amber-300/30 bg-amber-300/10 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-amber-200",children:[s.jsx(xv,{className:"h-3 w-3"})," Confidential offering"]})]}),s.jsx("h1",{className:"max-w-4xl font-serif text-4xl leading-[1.05] tracking-tight md:text-6xl lg:text-7xl",children:P}),s.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/60",children:[s.jsx(Va,{className:"h-4 w-4"})," ",C]}),s.jsxs("div",{className:"mt-8 flex flex-wrap items-end gap-x-10 gap-y-5",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:(l==null?void 0:l.deal_type)==="lease"?"Lease rate":"Asking price"}),s.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:Ole(l,p.price)})]}),(l==null?void 0:l.cap_rate)!=null&&s.jsxs("div",{children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:"Cap rate"}),s.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:AEe(l.cap_rate)})]})]}),s.jsxs("div",{className:"mt-9 flex flex-wrap gap-3",children:[s.jsxs(Jt,{size:"lg",className:"rounded-full px-7",onClick:()=>{var Le;return ie("om_request",((Le=g.find(be=>be.doc_kind==="om"))==null?void 0:Le.id)??null)},children:["Request Offering Memorandum ",s.jsx(lo,{className:"ml-2 h-4 w-4"})]}),s.jsx(Jt,{size:"lg",variant:"outline",className:"rounded-full border-white/25 bg-white/5 px-7 text-white hover:bg-white/10 hover:text-white",onClick:()=>ie("tour_request"),children:"Schedule a tour"})]})]})]}),j.length>0&&s.jsx("section",{className:"border-y border-white/10 bg-white/[0.02]",children:s.jsx("div",{className:"mx-auto grid max-w-7xl gap-px bg-white/10",style:{gridTemplateColumns:`repeat(${Math.min(j.length,4)}, minmax(0, 1fr))`},children:j.map(Le=>s.jsxs("div",{className:"bg-[#0b0f14] px-6 py-8",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:Le.label}),s.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums md:text-3xl",children:Le.value})]},Le.label))})}),Z.length>0&&s.jsx(y_,{eyebrow:"The opportunity",title:"Investment highlights",children:s.jsx("div",{className:"grid gap-x-12 gap-y-8 md:grid-cols-2",children:Z.map((Le,be)=>s.jsxs("div",{className:"flex gap-5 border-t border-white/10 pt-6",children:[s.jsx("span",{className:"font-serif text-2xl text-white/25 tabular-nums",children:String(be+1).padStart(2,"0")}),s.jsx("p",{className:"text-lg leading-relaxed text-white/85",children:Le})]},be))})}),(p.description||Q.length>0)&&s.jsx(y_,{eyebrow:"Property",title:"The asset",children:s.jsxs("div",{className:"grid gap-12 lg:grid-cols-[1.4fr_1fr]",children:[p.description&&s.jsx("div",{className:"space-y-5 text-lg leading-relaxed text-white/70",children:String(p.description).split(/\n{2,}/).map((Le,be)=>s.jsx("p",{children:Le},be))}),Q.length>0&&s.jsx("ul",{className:"space-y-3 self-start rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:Q.map((Le,be)=>s.jsxs("li",{className:"flex gap-3 text-sm text-white/75",children:[s.jsx("span",{className:"mt-2 h-1 w-1 shrink-0 rounded-full bg-white/50"})," ",Le]},be))})]})}),v.length>1&&s.jsx(y_,{eyebrow:"Gallery",title:"Property imagery",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:v.slice(1,10).map((Le,be)=>s.jsx("button",{onClick:()=>{a(be+1),IS(p.id,"gallery_view",{})},className:`group relative overflow-hidden rounded-xl ${be===0?"md:col-span-2 md:row-span-2":""}`,children:s.jsx("img",{src:Le.photo_url,alt:`${P} — image ${be+2}`,loading:"lazy",className:`w-full object-cover transition-transform duration-700 group-hover:scale-[1.04] ${be===0?"h-full min-h-[280px] md:min-h-[560px]":"h-[180px] md:h-[275px]"}`})},Le.id))})}),((l==null?void 0:l.noi)||(l==null?void 0:l.gross_income)||(l==null?void 0:l.operating_expenses)||(l==null?void 0:l.occupancy_pct)!=null)&&s.jsxs(y_,{eyebrow:"Financials",title:"Offering snapshot",children:[s.jsx("div",{className:"grid gap-px overflow-hidden rounded-2xl border border-white/10 bg-white/10 sm:grid-cols-2 lg:grid-cols-4",children:[{l:"Net operating income",v:Gm(l==null?void 0:l.noi)},{l:"Gross income",v:Gm(l==null?void 0:l.gross_income)},{l:"Operating expenses",v:Gm(l==null?void 0:l.operating_expenses)},{l:"Occupancy",v:(l==null?void 0:l.occupancy_pct)!=null?`${Math.round(Number(l.occupancy_pct))}%`:null},{l:"Price per SF",v:(l==null?void 0:l.price_per_sf)!=null?Gm(l.price_per_sf,2):null},{l:"Price per unit",v:Gm(l==null?void 0:l.price_per_unit)},{l:"Tenancy",v:l!=null&&l.tenancy?`${l.tenancy[0].toUpperCase()}${l.tenancy.slice(1)} tenant`:null},{l:"Broker co-op",v:(l==null?void 0:l.broker_coop_pct)!=null?`${l.broker_coop_pct}%`:null}].filter(Le=>Le.v).map(Le=>s.jsxs("div",{className:"bg-[#0b0f14] px-6 py-7",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:Le.l}),s.jsx("p",{className:"mt-2 text-xl font-semibold tabular-nums",children:Le.v})]},Le.l))}),(l==null?void 0:l.call_for_offers_at)&&s.jsxs("p",{className:"mt-6 inline-flex items-center gap-2 rounded-full border border-amber-300/25 bg-amber-300/10 px-5 py-2 text-sm text-amber-100",children:["Call for offers · ",new Date(l.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})]}),(F.length>0||$.length>0)&&s.jsx(y_,{eyebrow:"Occupancy",title:$.length?"Space availability":"Tenant roster",children:s.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:s.jsxs("table",{className:"w-full text-left text-sm",children:[s.jsx("thead",{className:"bg-white/[0.04] text-[10px] uppercase tracking-[0.18em] text-white/45",children:s.jsxs("tr",{children:[s.jsx("th",{className:"px-6 py-4",children:$.length?"Suite":"Tenant"}),s.jsx("th",{className:"px-6 py-4",children:"SF"}),s.jsx("th",{className:"px-6 py-4",children:$.length?"Rate":"Rent"}),s.jsx("th",{className:"px-6 py-4",children:$.length?"Availability":"Lease expiry"})]})}),s.jsx("tbody",{className:"divide-y divide-white/5",children:($.length?$:F).map((Le,be)=>s.jsxs("tr",{className:"text-white/80",children:[s.jsx("td",{className:"px-6 py-4 font-medium text-white",children:Le.suite??Le.name??"—"}),s.jsx("td",{className:"px-6 py-4 tabular-nums",children:Le.sf?n9(Number(Le.sf)):"—"}),s.jsx("td",{className:"px-6 py-4",children:Le.rate??Le.rent??"—"}),s.jsx("td",{className:"px-6 py-4",children:Le.availability??Le.lease_expiry??"—"})]},be))})]})})}),s.jsx(y_,{eyebrow:"Location",title:l!=null&&l.submarket?`${l.submarket} submarket`:C,children:s.jsxs("div",{className:"grid gap-8 lg:grid-cols-[1.2fr_1fr]",children:[L?s.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:s.jsx("iframe",{title:"Property location",className:"h-[420px] w-full",loading:"lazy",src:`https://www.google.com/maps?q=${encodeURIComponent(L)}&z=${p.latitude&&p.longitude?15:12}&output=embed`,onLoad:()=>IS(p.id,"map_view",{})})}):s.jsx("div",{className:"flex h-[420px] items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-center text-sm text-white/50",children:T?"Exact location released with the Offering Memorandum.":C}),s.jsxs("div",{className:"space-y-5",children:[(l==null?void 0:l.zoning)&&s.jsx(jS,{label:"Zoning",value:l.zoning}),(l==null?void 0:l.lot_acres)!=null&&s.jsx(jS,{label:"Site size",value:`${l.lot_acres} acres`}),(l==null?void 0:l.parking_spaces)!=null&&s.jsx(jS,{label:"Parking",value:`${l.parking_spaces} spaces`}),(l==null?void 0:l.opportunity_zone)&&s.jsx(jS,{label:"Opportunity Zone",value:"Qualified"}),W.filter(Le=>Le.road||Le.count).map((Le,be)=>s.jsx(jS,{label:`Traffic count — ${Le.road??"Adjacent road"}`,value:`${Le.count??"—"} VPD`},be)),!(l!=null&&l.zoning)&&(l==null?void 0:l.lot_acres)==null&&(l==null?void 0:l.parking_spaces)==null&&!(l!=null&&l.opportunity_zone)&&s.jsx(jS,{label:"Submarket",value:(l==null?void 0:l.submarket)||C})]})]})}),ee&&s.jsx(y_,{eyebrow:"Market",title:"Demographics",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[["radius_1","1 mile"],["radius_3","3 miles"],["radius_5","5 miles"]].map(([Le,be])=>{const Re=G==null?void 0:G[Le];return!Re||!Object.values(Re).some(Boolean)?null:s.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:be}),s.jsx("dl",{className:"mt-5 space-y-3 text-sm",children:[["Population",Re.population],["Households",Re.households],["Avg. income",Re.avg_income],["Daytime pop.",Re.daytime_pop]].filter(([,Ie])=>Ie).map(([Ie,Te])=>s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("dt",{className:"text-white/50",children:Ie}),s.jsx("dd",{className:"font-medium tabular-nums",children:Te})]},Ie))})]},Le)})})}),g.length>0&&s.jsx(y_,{eyebrow:"Deal room",title:"Offering documents",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:g.map(Le=>{const be=Le.gate_level==="public";return s.jsxs("div",{className:"flex items-center gap-4 rounded-2xl border border-white/10 bg-white/[0.03] p-5 transition-colors hover:border-white/20",children:[s.jsx("div",{className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/5",children:be?s.jsx($u,{className:"h-5 w-5"}):Le.gate_level==="nda"?s.jsx(QW,{className:"h-5 w-5"}):s.jsx(xv,{className:"h-5 w-5"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate font-medium",children:Le.title||ant[Le.doc_kind||"other"]}),s.jsx("p",{className:"text-xs text-white/45",children:be?"Available to download":Le.gate_level==="nda"?"Confidentiality acknowledgement required":"Registration required"})]}),s.jsx(Jt,{size:"sm",variant:"outline",className:"border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>ie("om_request",Le.id),children:be?"Download":"Request"})]},Le.id)})})}),E&&s.jsx("section",{className:"border-t border-white/10 bg-white/[0.02]",children:s.jsx("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10",children:s.jsxs("div",{className:"flex flex-col items-start gap-8 md:flex-row md:items-center md:justify-between",children:[s.jsxs("div",{className:"flex items-center gap-6",children:[E.avatar_url&&s.jsx("img",{src:E.avatar_url,alt:E.name,className:"h-24 w-24 rounded-full object-cover ring-1 ring-white/15"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.22em] text-white/40",children:"Exclusively listed by"}),s.jsx("p",{className:"mt-2 font-serif text-2xl",children:E.name}),s.jsx("p",{className:"text-sm text-white/55",children:((pe=E.brokerage)==null?void 0:pe.name)||E.brokerage_name})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-3",children:[E.email&&s.jsxs(Jt,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{IS(p.id,"contact_click",{}),window.location.href=`mailto:${E.email}`},children:[s.jsx(rs,{className:"mr-2 h-4 w-4"})," Email"]}),E.phone&&s.jsxs(Jt,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{IS(p.id,"contact_click",{}),window.location.href=`tel:${E.phone}`},children:[s.jsx(Ui,{className:"mr-2 h-4 w-4"})," Call"]}),s.jsx(Jt,{className:"rounded-full",onClick:()=>ie("investor_inquiry"),children:"Request information"})]})]})})}),s.jsx("footer",{className:"border-t border-white/10 py-10 text-center text-xs text-white/35",children:s.jsx("p",{children:"The information contained herein has been obtained from sources believed reliable but is not guaranteed. Prospective purchasers and tenants should conduct their own independent investigation."})}),s.jsx("div",{className:"sticky bottom-0 z-30 border-t border-white/10 bg-[#0b0f14]/90 backdrop-blur-xl",children:s.jsxs("div",{className:"mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-3 px-6 py-3.5 md:px-10",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"truncate text-sm font-medium",children:P}),s.jsxs("p",{className:"truncate text-xs text-white/50",children:[Ole(l,p.price)," · ",C]})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Jt,{size:"sm",variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>ie("tour_request"),children:"Tour"}),s.jsx(Jt,{size:"sm",className:"rounded-full",onClick:()=>{var Le;return ie("om_request",((Le=g.find(be=>be.doc_kind==="om"))==null?void 0:Le.id)??null)},children:"Request OM"})]})]})}),s.jsx(gl,{open:i!==null,onOpenChange:Le=>!Le&&a(null),children:s.jsx(Jo,{className:"max-w-[96vw] border-none bg-transparent p-0 shadow-none",children:i!==null&&v[i]&&s.jsxs("div",{className:"relative",children:[s.jsx("img",{src:v[i].photo_url,alt:"",className:"max-h-[88vh] w-full rounded-xl object-contain"}),s.jsx("button",{className:"absolute right-3 top-3 rounded-full bg-black/60 p-2",onClick:()=>a(null),children:s.jsx(Ra,{className:"h-5 w-5"})}),s.jsx("button",{className:"absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>a(Le=>(Le-1+v.length)%v.length),children:s.jsx(bg,{className:"h-6 w-6"})}),s.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>a(Le=>(Le+1)%v.length),children:s.jsx(uf,{className:"h-6 w-6"})})]})})}),c&&s.jsx(dnt,{open:!0,onOpenChange:Le=>!Le&&d(null),listingId:p.id,kind:c.kind,documentId:c.documentId,requiresNda:!!(l!=null&&l.requires_nda)||(l==null?void 0:l.om_gate_mode)==="nda",brokerName:E==null?void 0:E.name})]})}function y_({eyebrow:t,title:e,children:r}){return s.jsx("section",{className:"border-t border-white/10",children:s.jsxs("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10 md:py-24",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:t}),s.jsx("h2",{className:"mt-3 font-serif text-3xl tracking-tight md:text-4xl",children:e}),s.jsx("div",{className:"mt-12",children:r})]})})}function jS({label:t,value:e}){return s.jsxs("div",{className:"border-t border-white/10 pt-4",children:[s.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:t}),s.jsx("p",{className:"mt-1 text-lg",children:e})]})}const Ble="/assets/levelup-logo-color-BeKd2k_g.png",mnt={active:"bg-emerald-500",coming_soon:"bg-sky-500",office_exclusive:"bg-indigo-500",temp_off_market:"bg-amber-600",withdrawn:"bg-slate-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-600"},DU={active:"For Sale",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",temp_off_market:"Temporarily Off Market",withdrawn:"Withdrawn",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},zle={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},MU=t=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(t),oI=t=>new Intl.NumberFormat("en-US").format(t);function jEe(t){var e,r;if(!t)return null;try{const n=new URL(t.trim()),i=n.hostname.replace(/^www\.|^m\./,"");let a=null;if(i==="youtu.be"?a=n.pathname.slice(1).split("/")[0]:(i==="youtube.com"||i==="youtube-nocookie.com")&&(a=n.searchParams.get("v")||((e=n.pathname.match(/\/(?:embed|shorts|live)\/([^/?]+)/))==null?void 0:e[1])||null),a&&/^[\w-]{6,20}$/.test(a))return`https://www.youtube.com/embed/${a}`;if(i==="vimeo.com"||i==="player.vimeo.com"){const c=(r=n.pathname.match(/(\d{5,})/))==null?void 0:r[1];if(c)return`https://player.vimeo.com/video/${c}`}return null}catch{return null}}function aZ({slugOverride:t}={}){var ci,mo,_r,Da,pn,Vi,Yi;const e=Sg(),r=t||e.slugOrId,[n]=zv(),{data:i,isLoading:a}=Jrt(r||""),c=ent(),d=tnt(),p=n.get("ref"),[l,g]=N.useState(""),[v,E]=N.useState(""),[T,j]=N.useState(""),[P,C]=N.useState(""),[L,O]=N.useState(""),[F,$]=N.useState(""),[G,W]=N.useState(""),[Z,Q]=N.useState("in_person"),[ee,ie]=N.useState("info"),[oe,pe]=N.useState(!1),[Le,be]=N.useState(!1),[Re,Ie]=N.useState(null),[Te,ge]=N.useState(!1),[$e,we]=N.useState(!1),[ke,Ae]=N.useState(!1),[He,ot]=N.useState(20),[nt,tt]=N.useState(6.5),[vt,Vt]=N.useState(30),Ct=N.useRef(null),[Bt,cr]=N.useState(!1);N.useEffect(()=>{const nn=()=>cr(window.scrollY>300);return window.addEventListener("scroll",nn,{passive:!0}),()=>window.removeEventListener("scroll",nn)},[]),N.useEffect(()=>{p&&d.mutate(p)},[p]),N.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[r]);const ft=(i==null?void 0:i.photos)||[],Kt=ft.find(nn=>nn.is_primary)||ft[0],ir=N.useMemo(()=>{if(!(i!=null&&i.price))return 0;const nn=i.price*(1-He/100),Ke=nt/100/12,at=vt*12;return Ke===0?nn/at:nn*Ke/(1-Math.pow(1+Ke,-at))},[i==null?void 0:i.price,He,nt,vt]),Gr=async()=>{const nn=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:nn})}catch{}else await navigator.clipboard.writeText(nn),lr.success("Link copied to clipboard")},tr=async nn=>{if(nn.preventDefault(),!l.trim()||!T.trim()||!i)return;const Ke=ee==="showing";if(Ke&&!F){lr.error("Please pick a preferred date for your showing");return}pe(!0);try{await c.mutateAsync({listingId:i.id,agentId:i.agent_id,firstName:l.trim(),lastName:v.trim(),email:T.trim(),phone:P.trim(),shareToken:p,leadType:Ke?"showing_request":"info_request",preferredDate:Ke?F:null,preferredTime:Ke&&G||null,showingMode:Ke?Z:null,message:L.trim()||null}),be(!0),lr.success(Ke?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(at){console.error("Lead submission error:",at),lr.error(`Failed to submit: ${at.message||"Please try again"}`)}finally{pe(!1)}},Qt=()=>{Re!==null&&Ie(Re===0?ft.length-1:Re-1)},zt=()=>{Re!==null&&Ie(Re===ft.length-1?0:Re+1)};if((i==null?void 0:i.listing_class)==="commercial")return s.jsx(fnt,{slug:r});if(a)return s.jsx("div",{className:"min-h-screen bg-neutral-950",children:s.jsx(Mc,{className:"h-[100svh] w-full rounded-none bg-neutral-900"})});if(!i)return s.jsxs("div",{className:"min-h-screen bg-background",children:[s.jsx("header",{className:"border-b bg-card",children:s.jsx("div",{className:"container mx-auto px-4 py-4",children:s.jsx(Nn,{to:"/public/listings",className:"flex items-center gap-2",children:s.jsx("img",{src:Ble,alt:"LevelUp",className:"h-8"})})})}),s.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[s.jsx(Do,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),s.jsx("p",{className:"text-muted-foreground mb-6",children:"This listing may no longer be available."}),s.jsx(Jt,{asChild:!0,children:s.jsx(Nn,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const Vr=i.property_address?`${i.property_address} — ${i.city}, ${i.state}`:`${i.city}, ${i.state} Home for Sale`,Jr=((mo=(ci=i.agent)==null?void 0:ci.brokerage)==null?void 0:mo.name)||((_r=i.agent)==null?void 0:_r.brokerage_name),Fn=((Da=i.agent)==null?void 0:Da.name)||"",Ar=jEe(i.video_link),Tn=Jr||Fn||"",mn=DU[i.status]==="Sold"?"Just Sold":DU[i.status],li=mn?`${mn}: ${Vr}`:Vr,Lr=[`${MU(i.price)} · ${i.city}, ${i.state}`,Fn?`Presented by ${Fn}${Jr?`, ${Jr}`:""}.`:""].filter(Boolean).join(" · "),Or=i.latitude&&i.longitude?`https://maps.google.com/maps?q=${i.latitude},${i.longitude}&z=15&output=embed`:i.property_address?`https://maps.google.com/maps?q=${encodeURIComponent(`${i.property_address}, ${i.city}, ${i.state}`)}&z=15&output=embed`:null,si=i.description||"",ss=si.length>420,ps=ke||!ss?si:si.slice(0,420).trimEnd()+"…",Mi=i.page_config||{},gs=nn=>{var Ke;return(((Ke=Mi.sections)==null?void 0:Ke[nn])??!0)!==!1},ma=Array.isArray(Mi.addons)?Mi.addons:[],Ki=Mi.custom_note||"",Hr=Mi.accent_color||null;return s.jsxs(s.Fragment,{children:[s.jsxs(mc,{children:[s.jsx("title",{children:Tn?`${Vr} | ${Tn}`:Vr}),s.jsx("meta",{name:"description",content:`${MU(i.price)} · ${i.bedrooms||""}BD ${i.bathrooms||""}BA ${i.square_footage?i.square_footage.toLocaleString()+" sqft · ":""}${zle[i.property_type]} in ${i.city}, ${i.state}. ${si.slice(0,140)}`}),s.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${i.slug||i.id}`}),s.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),s.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:""}),s.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400;9..144,500;9..144,600&display=swap",rel:"stylesheet"}),s.jsx("meta",{property:"og:title",content:li}),s.jsx("meta",{property:"og:description",content:Lr}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${i.slug||i.id}`}),Kt&&s.jsx("meta",{property:"og:image",content:Kt.photo_url}),Tn&&s.jsx("meta",{property:"og:site_name",content:Tn}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),s.jsx("meta",{name:"twitter:title",content:li}),s.jsx("meta",{name:"twitter:description",content:Lr}),Kt&&s.jsx("meta",{name:"twitter:image",content:Kt.photo_url}),s.jsx("meta",{name:"robots",content:"index, follow"}),s.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateListing",name:i.property_address||`${i.city}, ${i.state} Home`,description:si,url:`https://listings.relevelup.com/${i.slug||i.id}`,datePosted:i.created_at,image:ft.map(nn=>nn.photo_url),address:{"@type":"PostalAddress",streetAddress:i.property_address||void 0,addressLocality:i.city,addressRegion:i.state,addressCountry:"US"},offers:{"@type":"Offer",price:i.price,priceCurrency:"USD",availability:i.status==="sold"?"https://schema.org/SoldOut":i.status==="under_contract"?"https://schema.org/LimitedAvailability":"https://schema.org/InStock"},numberOfRooms:i.bedrooms||void 0,numberOfBathroomsTotal:i.bathrooms||void 0,floorSize:i.square_footage?{"@type":"QuantitativeValue",value:i.square_footage,unitCode:"FTK"}:void 0,yearBuilt:i.year_built||void 0})}),s.jsx("style",{children:` .font-display { font-family: 'Fraunces', ui-serif, Georgia, serif; font-optical-sizing: auto; letter-spacing: -0.02em; } @keyframes kb-zoom { from { transform: scale(1.08); } to { transform: scale(1); } } .kb-zoom { animation: kb-zoom 12s ease-out forwards; } .noscroll::-webkit-scrollbar { display: none; } `})]}),s.jsxs("div",{className:"bg-neutral-950 text-neutral-100 min-h-screen",children:[s.jsx("header",{className:`fixed inset-x-0 top-0 z-40 transition-all duration-300 ${Bt?"bg-neutral-950/85 backdrop-blur-xl border-b border-white/10 py-3":"bg-gradient-to-b from-black/60 to-transparent py-4"}`,children:s.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 flex items-center justify-between gap-3",children:[s.jsxs(Nn,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",className:"flex items-center gap-2 text-white/90 hover:text-white",children:[s.jsx(yv,{className:"h-4 w-4"}),s.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),Bt&&s.jsx("div",{className:"hidden md:flex items-center gap-1 text-sm",children:[["overview","Overview"],["gallery","Gallery"],["story","The Story"],["video","Video"],["map","Location"],["payment","Payment"],["agent","Agent"]].map(([nn,Ke])=>s.jsx("a",{href:`#${nn}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:Ke},nn))}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Rrt,{listingId:i.id,listingAddress:i.property_address?`${i.property_address}, ${i.city}, ${i.state}`:`${i.city}, ${i.state}`,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition text-white"}),s.jsx("button",{onClick:Gr,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition","aria-label":"Share",children:s.jsx(RP,{className:"h-4 w-4 text-white"})}),s.jsx(Jt,{size:"sm",onClick:()=>ge(!0),className:"hidden sm:inline-flex bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4 font-medium",children:"Request Tour"})]})]})}),s.jsxs("section",{ref:Ct,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[Kt?s.jsx("img",{src:Kt.photo_url,alt:i.property_address||`${i.city}, ${i.state}`,className:"absolute inset-0 h-full w-full object-cover kb-zoom"}):s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-neutral-800 to-neutral-950"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black via-black/50 to-black/20"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/40 via-transparent to-transparent"}),s.jsxs("div",{className:"absolute top-24 right-4 sm:right-8 z-10 flex flex-col items-end gap-2",children:[s.jsx(Js,{className:`${mnt[i.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:DU[i.status]}),ft.length>0&&s.jsxs("button",{onClick:()=>Ie(0),className:"flex items-center gap-1.5 text-xs text-white/90 bg-black/40 backdrop-blur border border-white/20 rounded-full px-3 py-1.5 hover:bg-black/60 transition",children:[s.jsx(Vse,{className:"h-3.5 w-3.5"}),ft.length," photos"]})]}),s.jsx("div",{className:"absolute inset-x-0 bottom-0 z-10 px-4 sm:px-8 pb-10 sm:pb-14",children:s.jsxs("div",{className:"max-w-7xl mx-auto",children:[s.jsxs("div",{className:"flex items-end justify-between gap-6 flex-wrap",children:[s.jsxs("div",{className:"max-w-3xl",children:[i.neighborhood&&s.jsxs("p",{className:"text-white/70 uppercase tracking-[0.25em] text-xs mb-3 font-medium",children:[i.neighborhood," · ",i.city,", ",i.state]}),i.property_address&&s.jsx("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:i.property_address}),!i.property_address&&s.jsxs("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:[i.city,", ",i.state]}),s.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[s.jsx("p",{className:"font-display text-white text-3xl sm:text-4xl md:text-5xl font-medium",children:MU(i.price)}),s.jsx("div",{className:"h-8 w-px bg-white/30 hidden sm:block"}),s.jsxs("div",{className:"flex items-center gap-4 text-white/80 text-sm sm:text-base",children:[i.bedrooms&&s.jsxs("span",{children:[s.jsx("span",{className:"font-semibold text-white",children:i.bedrooms})," bd"]}),i.bathrooms&&s.jsxs("span",{children:[s.jsx("span",{className:"font-semibold text-white",children:i.bathrooms})," ba"]}),i.square_footage&&s.jsxs("span",{children:[s.jsx("span",{className:"font-semibold text-white",children:oI(i.square_footage)})," sqft"]})]})]})]}),s.jsxs("div",{className:"hidden md:flex flex-col gap-2",children:[i.agent&&s.jsxs("div",{className:"flex items-center gap-3 bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl px-4 py-3 shadow-2xl",children:[i.agent.avatar_url?s.jsx("img",{src:i.agent.avatar_url,alt:i.agent.name,className:"h-12 w-12 rounded-full object-cover"}):s.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 flex items-center justify-center",children:s.jsx(nd,{className:"h-6 w-6 text-white"})}),s.jsxs("div",{className:"pr-2 flex-1",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Listing Agent"}),s.jsx("p",{className:"text-white font-medium leading-tight",children:i.agent.name}),Jr&&s.jsx("p",{className:"text-xs text-white/60",children:Jr})]}),s.jsx(Jt,{size:"sm",onClick:()=>ge(!0),className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:"Contact"})]}),i.co_agent_name&&s.jsxs("div",{className:"flex items-center gap-3 bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl px-4 py-3 shadow-2xl",children:[i.co_agent_photo_url?s.jsx("img",{src:i.co_agent_photo_url,alt:i.co_agent_name,className:"h-12 w-12 rounded-full object-cover"}):s.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 flex items-center justify-center",children:s.jsx(nd,{className:"h-6 w-6 text-white"})}),s.jsxs("div",{className:"pr-2 flex-1",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Co-Listing Agent"}),s.jsx("p",{className:"text-white font-medium leading-tight",children:i.co_agent_name}),i.co_agent_brokerage&&s.jsx("p",{className:"text-xs text-white/60",children:i.co_agent_brokerage})]}),(i.co_agent_phone||i.co_agent_email)&&s.jsx(Jt,{asChild:!0,size:"sm",className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:s.jsx("a",{href:i.co_agent_phone?`tel:${i.co_agent_phone}`:`mailto:${i.co_agent_email}`,children:"Contact"})})]})]})]}),s.jsxs("div",{className:"mt-10 flex items-center gap-2 text-white/50 text-xs uppercase tracking-widest",children:[s.jsx("span",{className:"h-px w-8 bg-white/30"}),"Scroll to explore"]})]})})]}),gs("stats")&&s.jsx("section",{className:"border-b border-white/10 bg-neutral-950",children:s.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-8 grid grid-cols-2 md:grid-cols-5 gap-6",children:[i.bedrooms&&{icon:tA,label:"Bedrooms",value:i.bedrooms},i.bathrooms&&{icon:ww,label:"Bathrooms",value:i.bathrooms},i.square_footage&&{icon:JW,label:"Interior",value:`${oI(i.square_footage)} sqft`},i.lot_size&&{icon:k4,label:"Lot Size",value:i.lot_size},i.year_built&&{icon:Cl,label:"Year Built",value:i.year_built},!i.year_built&&i.square_footage&&{icon:eve,label:"Price / sqft",value:`$${oI(Math.round(i.price/i.square_footage))}`}].filter(Boolean).slice(0,5).map((nn,Ke)=>s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"h-10 w-10 rounded-full bg-white/5 border border-white/10 flex items-center justify-center shrink-0",children:s.jsx(nn.icon,{className:"h-4 w-4 text-white/70"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/50",children:nn.label}),s.jsx("p",{className:"font-display text-2xl text-white font-light",children:nn.value})]})]},Ke))})}),s.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-16 grid lg:grid-cols-3 gap-12",children:[s.jsxs("div",{className:"lg:col-span-2 space-y-20",children:[gs("story")&&si&&s.jsxs("section",{id:"story",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-3",children:"The Story"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light mb-6 text-white",children:"A closer look at this home"}),s.jsx("div",{className:"prose prose-invert prose-lg max-w-none",children:s.jsx("p",{className:"text-white/75 leading-relaxed whitespace-pre-wrap",children:ps})}),ss&&s.jsx("button",{onClick:()=>Ae(!ke),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:ke?"Show less":"Read more"}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[s.jsxs(Js,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[s.jsx(jl,{className:"h-3 w-3 mr-1.5"}),zle[i.property_type]]}),i.has_hoa&&s.jsx(Js,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),i.mls_link&&s.jsx(Jt,{variant:"outline",size:"sm",asChild:!0,className:"ml-2 border-white/20 bg-white/5 text-white hover:bg-white/15",children:s.jsxs("a",{href:i.mls_link,target:"_blank",rel:"noopener noreferrer",children:[s.jsx(rA,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(Ki||i.agent_notes&&i.agent_notes_public)&&s.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[s.jsx(va,{className:"h-4 w-4 text-amber-300"}),s.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),s.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',Ki||i.agent_notes,'"']})]})]}),gs("gallery")&&ft.length>1&&s.jsxs("section",{id:"gallery",children:[s.jsxs("div",{className:"flex items-end justify-between mb-6",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),s.jsxs("button",{onClick:()=>Ie(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",ft.length]})]}),s.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:ft.slice(0,7).map((nn,Ke)=>{const at=["col-span-4 sm:col-span-2 sm:row-span-2 aspect-square sm:aspect-auto","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square"],yt=Ke===6&&ft.length>7;return s.jsxs("button",{onClick:()=>Ie(Ke),className:`${at[Ke]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[s.jsx("img",{src:nn.photo_url,alt:`Photo ${Ke+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),yt&&s.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[s.jsx(Vse,{className:"h-6 w-6 mb-1"}),s.jsxs("span",{className:"font-medium",children:["+",ft.length-7," more"]})]})]},nn.id)})})]}),gs("video")&&!((pn=i.video)!=null&&pn.playback_url)&&Ar&&s.jsxs("section",{id:"video",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),s.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:s.jsx("iframe",{src:Ar,className:"absolute inset-0 h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Video Tour"})})]}),gs("video")&&((Vi=i.video)==null?void 0:Vi.playback_url)&&s.jsxs("section",{id:"video",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),s.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:s.jsx("iframe",{src:i.video.playback_url,className:"absolute inset-0 h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Video Tour"})})]}),gs("map")&&Or&&s.jsxs("section",{id:"map",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Location"}),s.jsxs("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:[i.neighborhood?i.neighborhood:i.city,", ",i.state]}),s.jsx("div",{className:"rounded-2xl overflow-hidden border border-white/10 shadow-2xl aspect-[16/10]",children:s.jsx("iframe",{src:Or,className:"w-full h-full grayscale-[.2] contrast-[1.05]",loading:"lazy",title:"Map"})}),s.jsxs("div",{className:"mt-4 flex items-center gap-2 text-white/60 text-sm",children:[s.jsx(Va,{className:"h-4 w-4"}),i.property_address?`${i.property_address}, `:"",i.city,", ",i.state]})]}),gs("payment")&&s.jsxs("section",{id:"payment",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Payment"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Estimate your monthly"}),s.jsxs("div",{className:"rounded-2xl border border-white/10 bg-gradient-to-br from-white/5 to-transparent p-6 sm:p-8",children:[s.jsxs("div",{className:"flex items-baseline gap-3 mb-8",children:[s.jsxs("p",{className:"font-display text-5xl sm:text-6xl font-light text-white",children:["$",oI(Math.round(ir))]}),s.jsx("p",{className:"text-white/60",children:"/ month"})]}),s.jsxs("div",{className:"grid sm:grid-cols-3 gap-8",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx(sn,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),s.jsxs("span",{className:"text-white font-medium",children:[He,"%"]})]}),s.jsx(dj,{value:[He],onValueChange:nn=>ot(nn[0]),min:0,max:50,step:1}),s.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",oI(Math.round(i.price*He/100))," down"]})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx(sn,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),s.jsxs("span",{className:"text-white font-medium",children:[nt.toFixed(2),"%"]})]}),s.jsx(dj,{value:[nt],onValueChange:nn=>tt(nn[0]),min:2,max:10,step:.125})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx(sn,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),s.jsxs("span",{className:"text-white font-medium",children:[vt," yr"]})]}),s.jsx(dj,{value:[vt],onValueChange:nn=>Vt(nn[0]),min:10,max:30,step:5})]})]}),s.jsx("p",{className:"text-xs text-white/40 mt-6",children:"Estimated principal & interest only. Taxes, insurance, and HOA not included."})]})]}),ma.map(nn=>{const Ke=nn.type,at=nn.data||{};if(Ke==="extra_video"&&at.url){const yt=String(at.url).includes("youtu")?`https://www.youtube.com/embed/${String(at.url).split(/[/=]/).pop()}`:at.url;return s.jsxs("section",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:at.eyebrow||"Featured Video"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:at.title||"Watch"}),s.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:s.jsx("iframe",{src:yt,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:at.title||"Video"})})]},nn.id)}return Ke==="3d_tour"&&at.url?s.jsxs("section",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"3D Tour"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:at.title||"Step inside"}),s.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:s.jsx("iframe",{src:at.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},nn.id):Ke==="floor_plan"&&at.image_url?s.jsxs("section",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Floor Plan"}),s.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:at.title||"Layout"}),s.jsx("img",{src:at.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},nn.id):Ke==="testimonial"&&at.quote?s.jsxs("section",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-8",children:[s.jsxs("p",{className:"font-display italic text-2xl text-white/90 leading-relaxed",children:['"',at.quote,'"']}),at.author&&s.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",at.author]})]},nn.id):Ke==="custom_cta"&&at.label?s.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:Hr?`${Hr}22`:"rgba(255,255,255,0.05)",border:`1px solid ${Hr||"rgba(255,255,255,0.1)"}`},children:[at.title&&s.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:at.title}),s.jsx(Jt,{asChild:!0,size:"lg",style:Hr?{background:Hr}:void 0,children:s.jsx("a",{href:at.url||"#agent",children:at.label})})]},nn.id):null})]}),s.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[s.jsx(nnt,{listingId:i.id}),i.agent&&s.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[s.jsxs("div",{className:"flex items-start gap-4",children:[i.agent.avatar_url?s.jsx("img",{src:i.agent.avatar_url,alt:i.agent.name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):s.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:s.jsx(nd,{className:"h-7 w-7 text-white/70"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Listing Agent"}),s.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:i.agent.name}),Jr&&s.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:Jr})]})]}),s.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[i.agent.phone&&s.jsx(Jt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:s.jsxs("a",{href:`tel:${i.agent.phone}`,children:[s.jsx(Ui,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),i.agent.email&&s.jsx(Jt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:s.jsxs("a",{href:`mailto:${i.agent.email}`,children:[s.jsx(rs,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),i.co_agent_name&&s.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[s.jsxs("div",{className:"flex items-start gap-4",children:[i.co_agent_photo_url?s.jsx("img",{src:i.co_agent_photo_url,alt:i.co_agent_name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):s.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:s.jsx(nd,{className:"h-7 w-7 text-white/70"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Co-Listing Agent"}),s.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:i.co_agent_name}),i.co_agent_brokerage&&s.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:i.co_agent_brokerage})]})]}),(i.co_agent_phone||i.co_agent_email)&&s.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[i.co_agent_phone&&s.jsx(Jt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:s.jsxs("a",{href:`tel:${i.co_agent_phone}`,children:[s.jsx(Ui,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),i.co_agent_email&&s.jsx(Jt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:s.jsxs("a",{href:`mailto:${i.co_agent_email}`,children:[s.jsx(rs,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),s.jsx("div",{id:"contact",className:"rounded-2xl border border-white/10 bg-white text-neutral-900 p-6 shadow-2xl",children:s.jsx($le,{submitted:Le,activeTab:ee,setActiveTab:ie,firstName:l,setFirstName:g,lastName:v,setLastName:E,email:T,setEmail:j,phone:P,setPhone:C,message:L,setMessage:O,preferredDate:F,setPreferredDate:$,preferredTime:G,setPreferredTime:W,showingMode:Z,setShowingMode:Q,isSubmitting:oe,onSubmit:tr})})]})]}),s.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-neutral-950/95 backdrop-blur-xl border-t border-white/10 px-4 py-3 flex items-center gap-2 safe-area-inset-bottom",children:[((Yi=i.agent)==null?void 0:Yi.phone)&&s.jsx(Jt,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15 flex-1",children:s.jsxs("a",{href:`tel:${i.agent.phone}`,children:[s.jsx(Ui,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),s.jsxs(Jt,{onClick:()=>ge(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[s.jsx(tve,{className:"h-4 w-4 mr-1.5"}),"Request Tour"]})]}),s.jsx("footer",{className:"border-t border-white/10 py-10 mt-24 mb-16 lg:mb-0",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 flex flex-col sm:flex-row items-center justify-between gap-4 text-sm text-white/50",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("img",{src:Ble,alt:"LevelUp",className:"h-6 opacity-80"}),s.jsxs("span",{children:["© ",new Date().getFullYear()," LevelUp"]})]}),s.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-white",children:"relevelup.com"})]})}),s.jsx(gl,{open:Re!==null,onOpenChange:()=>Ie(null),children:s.jsxs(Jo,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[s.jsx(Bc,{className:"sr-only",children:s.jsx(pc,{children:"Photo Gallery"})}),s.jsx("button",{onClick:()=>Ie(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:s.jsx(Ra,{className:"h-5 w-5"})}),Re!==null&&ft[Re]&&s.jsxs("div",{className:"relative",children:[s.jsx("img",{src:ft[Re].photo_url,alt:`Photo ${Re+1}`,className:"w-full max-h-[85vh] object-contain"}),ft.length>1&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:Qt,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:s.jsx(bg,{className:"h-6 w-6"})}),s.jsx("button",{onClick:zt,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:s.jsx(uf,{className:"h-6 w-6"})}),s.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/60 px-3 py-1 rounded-full text-sm",children:[Re+1," / ",ft.length]})]})]})]})}),s.jsx(gl,{open:Te,onOpenChange:ge,children:s.jsxs(Jo,{className:"max-w-md p-0 bg-white text-neutral-900",children:[s.jsx(Bc,{className:"sr-only",children:s.jsx(pc,{children:"Contact the agent"})}),s.jsx("div",{className:"p-6",children:s.jsx($le,{submitted:Le,activeTab:ee,setActiveTab:ie,firstName:l,setFirstName:g,lastName:v,setLastName:E,email:T,setEmail:j,phone:P,setPhone:C,message:L,setMessage:O,preferredDate:F,setPreferredDate:$,preferredTime:G,setPreferredTime:W,showingMode:Z,setShowingMode:Q,isSubmitting:oe,onSubmit:tr})})]})})]})]})}function $le(t){const{submitted:e,activeTab:r,setActiveTab:n,firstName:i,setFirstName:a,lastName:c,setLastName:d,email:p,setEmail:l,phone:g,setPhone:v,message:E,setMessage:T,preferredDate:j,setPreferredDate:P,preferredTime:C,setPreferredTime:L,showingMode:O,setShowingMode:F,isSubmitting:$,onSubmit:G}=t;return e?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"h-14 w-14 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:s.jsx(ql,{className:"h-7 w-7 text-emerald-600"})}),s.jsx("p",{className:"font-display text-2xl font-medium mb-1",children:r==="showing"?"Showing request sent!":"Thanks — you're all set!"}),s.jsx("p",{className:"text-sm text-neutral-600",children:r==="showing"?"The listing agent will reach out to confirm your showing time.":"The listing agent will contact you shortly with more details."})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-4",children:[s.jsx("p",{className:"text-[10px] uppercase tracking-[0.25em] text-neutral-500 mb-1",children:"Interested?"}),s.jsx("h3",{className:"font-display text-2xl font-medium",children:"Talk to the listing agent"})]}),s.jsxs(XY,{value:r,onValueChange:W=>n(W),children:[s.jsxs(k5,{className:"grid w-full grid-cols-2 mb-4",children:[s.jsxs(Dy,{value:"info",className:"gap-1.5",children:[s.jsx(ug,{className:"h-3.5 w-3.5"})," Get Info"]}),s.jsxs(Dy,{value:"showing",className:"gap-1.5",children:[s.jsx(tve,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),s.jsxs("form",{onSubmit:G,className:"space-y-3",children:[s.jsxs(uv,{value:"showing",className:"mt-0 space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"preferredDate",children:"Preferred Date *"}),s.jsx(hn,{id:"preferredDate",type:"date",value:j,onChange:W=>P(W.target.value),min:new Date().toISOString().split("T")[0],required:r==="showing"})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"preferredTime",children:"Preferred Time"}),s.jsxs(Xo,{value:C,onValueChange:L,children:[s.jsx(Mo,{id:"preferredTime",children:s.jsx(Qo,{placeholder:"Any time"})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"morning",children:"Morning (9am–12pm)"}),s.jsx($n,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),s.jsx($n,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"showingMode",children:"Tour Type"}),s.jsxs(Xo,{value:O,onValueChange:W=>F(W),children:[s.jsx(Mo,{id:"showingMode",children:s.jsx(Qo,{})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"in_person",children:"🏡 In-person showing"}),s.jsx($n,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),s.jsx($n,{value:"either",children:"Either works for me"})]})]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"firstName",children:"First Name *"}),s.jsx(hn,{id:"firstName",value:i,onChange:W=>a(W.target.value),required:!0})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"lastName",children:"Last Name"}),s.jsx(hn,{id:"lastName",value:c,onChange:W=>d(W.target.value)})]})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"email",children:"Email *"}),s.jsx(hn,{id:"email",type:"email",value:p,onChange:W=>l(W.target.value),required:!0})]}),s.jsxs("div",{children:[s.jsxs(sn,{htmlFor:"phone",children:["Phone ",r==="showing"&&"*"]}),s.jsx(hn,{id:"phone",type:"tel",value:g,onChange:W=>v(W.target.value),required:r==="showing"})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"message",children:r==="showing"?"Anything else?":"Message (optional)"}),s.jsx(df,{id:"message",value:E,onChange:W=>T(W.target.value),rows:2})]}),s.jsx(Jt,{type:"submit",disabled:$,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:$?"Sending…":r==="showing"?"Request Showing":"Get More Info"}),s.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const pnt=Object.freeze(Object.defineProperty({__proto__:null,default:aZ,toVideoEmbedUrl:jEe},Symbol.toStringTag,{value:"Module"})),Ule="/assets/levelup-logo-white-C2RAgAoG.png",gnt="/assets/listings-hero-noir-BHCJrhvU.jpg";var CEe={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(Ou,function(){let r,n,i,a,c;typeof self<"u"&&(self.__mapboxImport=l=>import(l));function d(l,g){if(!r)r=g,n=l;else if(!i)i=g,a=l;else{const v={},E=P=>P.map(C=>C==="require"?void 0:v);r(...E(n)),c=g(...E(l));const T=P=>P.map(C=>C==="require"?"undefined":"sharedChunk").join(", "),j="self.onerror = function() { console.error('An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling'); }; var sharedChunk = {}; self.__mapboxImport = (u) => import(u); ("+r+")("+T(n)+"); ("+i+")("+T(a)+"); self.onerror = null;";typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(c.workerUrl=window.URL.createObjectURL(new Blob([j],{type:"text/javascript"})))}}d(["require","exports"],function(l,g){var v="3.34.1",E=1e-6,T=typeof Float32Array<"u"?Float32Array:Array;function j(h,o){var u=o[0],m=o[1],x=o[2],b=o[3],S=u*b-x*m;return S?(h[0]=b*(S=1/S),h[1]=-m*S,h[2]=-x*S,h[3]=u*S,h):null}function P(){var h=new T(9);return T!=Float32Array&&(h[1]=0,h[2]=0,h[3]=0,h[5]=0,h[6]=0,h[7]=0),h[0]=1,h[4]=1,h[8]=1,h}function C(h,o,u){var m=o[0],x=o[1],b=o[2],S=o[3],A=o[4],I=o[5],D=o[6],B=o[7],U=o[8],q=u[0],K=u[1],X=u[2],J=u[3],se=u[4],ae=u[5],ue=u[6],ce=u[7],de=u[8];return h[0]=q*m+K*S+X*D,h[1]=q*x+K*A+X*B,h[2]=q*b+K*I+X*U,h[3]=J*m+se*S+ae*D,h[4]=J*x+se*A+ae*B,h[5]=J*b+se*I+ae*U,h[6]=ue*m+ce*S+de*D,h[7]=ue*x+ce*A+de*B,h[8]=ue*b+ce*I+de*U,h}function L(h,o){var u=Math.sin(o),m=Math.cos(o);return h[0]=m,h[1]=u,h[2]=0,h[3]=-u,h[4]=m,h[5]=0,h[6]=0,h[7]=0,h[8]=1,h}function O(){var h=new T(16);return T!=Float32Array&&(h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[11]=0,h[12]=0,h[13]=0,h[14]=0),h[0]=1,h[5]=1,h[10]=1,h[15]=1,h}function F(h){var o=new T(16);return o[0]=h[0],o[1]=h[1],o[2]=h[2],o[3]=h[3],o[4]=h[4],o[5]=h[5],o[6]=h[6],o[7]=h[7],o[8]=h[8],o[9]=h[9],o[10]=h[10],o[11]=h[11],o[12]=h[12],o[13]=h[13],o[14]=h[14],o[15]=h[15],o}function $(h,o){return h[0]=o[0],h[1]=o[1],h[2]=o[2],h[3]=o[3],h[4]=o[4],h[5]=o[5],h[6]=o[6],h[7]=o[7],h[8]=o[8],h[9]=o[9],h[10]=o[10],h[11]=o[11],h[12]=o[12],h[13]=o[13],h[14]=o[14],h[15]=o[15],h}function G(h){return h[0]=1,h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=1,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[10]=1,h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,h}function W(h,o){if(h===o){var u=o[1],m=o[2],x=o[3],b=o[6],S=o[7],A=o[11];h[1]=o[4],h[2]=o[8],h[3]=o[12],h[4]=u,h[6]=o[9],h[7]=o[13],h[8]=m,h[9]=b,h[11]=o[14],h[12]=x,h[13]=S,h[14]=A}else h[0]=o[0],h[1]=o[4],h[2]=o[8],h[3]=o[12],h[4]=o[1],h[5]=o[5],h[6]=o[9],h[7]=o[13],h[8]=o[2],h[9]=o[6],h[10]=o[10],h[11]=o[14],h[12]=o[3],h[13]=o[7],h[14]=o[11],h[15]=o[15];return h}function Z(h,o){var u=o[0],m=o[1],x=o[2],b=o[3],S=o[4],A=o[5],I=o[6],D=o[7],B=o[8],U=o[9],q=o[10],K=o[11],X=o[12],J=o[13],se=o[14],ae=o[15],ue=u*A-m*S,ce=u*I-x*S,de=u*D-b*S,xe=m*I-x*A,ve=m*D-b*A,Ue=x*D-b*I,Pe=B*J-U*X,De=B*se-q*X,Ve=B*ae-K*X,Fe=U*se-q*J,Ze=U*ae-K*J,st=q*ae-K*se,ut=ue*st-ce*Ze+de*Fe+xe*Ve-ve*De+Ue*Pe;return ut?(h[0]=(A*st-I*Ze+D*Fe)*(ut=1/ut),h[1]=(x*Ze-m*st-b*Fe)*ut,h[2]=(J*Ue-se*ve+ae*xe)*ut,h[3]=(q*ve-U*Ue-K*xe)*ut,h[4]=(I*Ve-S*st-D*De)*ut,h[5]=(u*st-x*Ve+b*De)*ut,h[6]=(se*de-X*Ue-ae*ce)*ut,h[7]=(B*Ue-q*de+K*ce)*ut,h[8]=(S*Ze-A*Ve+D*Pe)*ut,h[9]=(m*Ve-u*Ze-b*Pe)*ut,h[10]=(X*ve-J*de+ae*ue)*ut,h[11]=(U*de-B*ve-K*ue)*ut,h[12]=(A*De-S*Fe-I*Pe)*ut,h[13]=(u*Fe-m*De+x*Pe)*ut,h[14]=(J*ce-X*xe-se*ue)*ut,h[15]=(B*xe-U*ce+q*ue)*ut,h):null}function Q(h,o,u){var m=o[0],x=o[1],b=o[2],S=o[3],A=o[4],I=o[5],D=o[6],B=o[7],U=o[8],q=o[9],K=o[10],X=o[11],J=o[12],se=o[13],ae=o[14],ue=o[15],ce=u[0],de=u[1],xe=u[2],ve=u[3];return h[0]=ce*m+de*A+xe*U+ve*J,h[1]=ce*x+de*I+xe*q+ve*se,h[2]=ce*b+de*D+xe*K+ve*ae,h[3]=ce*S+de*B+xe*X+ve*ue,h[4]=(ce=u[4])*m+(de=u[5])*A+(xe=u[6])*U+(ve=u[7])*J,h[5]=ce*x+de*I+xe*q+ve*se,h[6]=ce*b+de*D+xe*K+ve*ae,h[7]=ce*S+de*B+xe*X+ve*ue,h[8]=(ce=u[8])*m+(de=u[9])*A+(xe=u[10])*U+(ve=u[11])*J,h[9]=ce*x+de*I+xe*q+ve*se,h[10]=ce*b+de*D+xe*K+ve*ae,h[11]=ce*S+de*B+xe*X+ve*ue,h[12]=(ce=u[12])*m+(de=u[13])*A+(xe=u[14])*U+(ve=u[15])*J,h[13]=ce*x+de*I+xe*q+ve*se,h[14]=ce*b+de*D+xe*K+ve*ae,h[15]=ce*S+de*B+xe*X+ve*ue,h}function ee(h,o,u){var m,x,b,S,A,I,D,B,U,q,K,X,J=u[0],se=u[1],ae=u[2];return o===h?(h[12]=o[0]*J+o[4]*se+o[8]*ae+o[12],h[13]=o[1]*J+o[5]*se+o[9]*ae+o[13],h[14]=o[2]*J+o[6]*se+o[10]*ae+o[14],h[15]=o[3]*J+o[7]*se+o[11]*ae+o[15]):(x=o[1],b=o[2],S=o[3],A=o[4],I=o[5],D=o[6],B=o[7],U=o[8],q=o[9],K=o[10],X=o[11],h[0]=m=o[0],h[1]=x,h[2]=b,h[3]=S,h[4]=A,h[5]=I,h[6]=D,h[7]=B,h[8]=U,h[9]=q,h[10]=K,h[11]=X,h[12]=m*J+A*se+U*ae+o[12],h[13]=x*J+I*se+q*ae+o[13],h[14]=b*J+D*se+K*ae+o[14],h[15]=S*J+B*se+X*ae+o[15]),h}function ie(h,o,u){var m=u[0],x=u[1],b=u[2];return h[0]=o[0]*m,h[1]=o[1]*m,h[2]=o[2]*m,h[3]=o[3]*m,h[4]=o[4]*x,h[5]=o[5]*x,h[6]=o[6]*x,h[7]=o[7]*x,h[8]=o[8]*b,h[9]=o[9]*b,h[10]=o[10]*b,h[11]=o[11]*b,h[12]=o[12],h[13]=o[13],h[14]=o[14],h[15]=o[15],h}function oe(h,o,u){var m=Math.sin(u),x=Math.cos(u),b=o[4],S=o[5],A=o[6],I=o[7],D=o[8],B=o[9],U=o[10],q=o[11];return o!==h&&(h[0]=o[0],h[1]=o[1],h[2]=o[2],h[3]=o[3],h[12]=o[12],h[13]=o[13],h[14]=o[14],h[15]=o[15]),h[4]=b*x+D*m,h[5]=S*x+B*m,h[6]=A*x+U*m,h[7]=I*x+q*m,h[8]=D*x-b*m,h[9]=B*x-S*m,h[10]=U*x-A*m,h[11]=q*x-I*m,h}function pe(h,o,u){var m=Math.sin(u),x=Math.cos(u),b=o[0],S=o[1],A=o[2],I=o[3],D=o[8],B=o[9],U=o[10],q=o[11];return o!==h&&(h[4]=o[4],h[5]=o[5],h[6]=o[6],h[7]=o[7],h[12]=o[12],h[13]=o[13],h[14]=o[14],h[15]=o[15]),h[0]=b*x-D*m,h[1]=S*x-B*m,h[2]=A*x-U*m,h[3]=I*x-q*m,h[8]=b*m+D*x,h[9]=S*m+B*x,h[10]=A*m+U*x,h[11]=I*m+q*x,h}function Le(h,o,u){var m=Math.sin(u),x=Math.cos(u),b=o[0],S=o[1],A=o[2],I=o[3],D=o[4],B=o[5],U=o[6],q=o[7];return o!==h&&(h[8]=o[8],h[9]=o[9],h[10]=o[10],h[11]=o[11],h[12]=o[12],h[13]=o[13],h[14]=o[14],h[15]=o[15]),h[0]=b*x+D*m,h[1]=S*x+B*m,h[2]=A*x+U*m,h[3]=I*x+q*m,h[4]=D*x-b*m,h[5]=B*x-S*m,h[6]=U*x-A*m,h[7]=q*x-I*m,h}function be(h,o){return h[0]=1,h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=1,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[10]=1,h[11]=0,h[12]=o[0],h[13]=o[1],h[14]=o[2],h[15]=1,h}function Re(h,o){return h[0]=o[0],h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=o[1],h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[10]=o[2],h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,h}function Ie(h,o,u){var m,x,b,S=u[0],A=u[1],I=u[2],D=Math.sqrt(S*S+A*A+I*I);return D0?(se=2*Math.sqrt(J+1),h[3]=.25*se,h[0]=(U-K)/se,h[1]=(q-I)/se,h[2]=(A-D)/se):S>B&&S>X?(se=2*Math.sqrt(1+S-B-X),h[3]=(U-K)/se,h[0]=.25*se,h[1]=(A+D)/se,h[2]=(q+I)/se):B>X?(se=2*Math.sqrt(1+B-S-X),h[3]=(q-I)/se,h[0]=(A+D)/se,h[1]=.25*se,h[2]=(U+K)/se):(se=2*Math.sqrt(1+X-S-B),h[3]=(A-D)/se,h[0]=(q+I)/se,h[1]=(U+K)/se,h[2]=.25*se),h}function $e(h,o){var u=o[0],m=o[1],x=o[2],b=o[3],S=u+u,A=m+m,I=x+x,D=u*S,B=m*S,U=m*A,q=x*S,K=x*A,X=x*I,J=b*S,se=b*A,ae=b*I;return h[0]=1-U-X,h[1]=B+ae,h[2]=q-se,h[3]=0,h[4]=B-ae,h[5]=1-D-X,h[6]=K+J,h[7]=0,h[8]=q+se,h[9]=K-J,h[10]=1-D-U,h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,h}var we=function(h,o,u,m,x){var b=1/Math.tan(o/2);if(h[0]=b/u,h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=b,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[11]=-1,h[12]=0,h[13]=0,h[15]=0,x!=null&&x!==1/0){var S=1/(m-x);h[10]=(x+m)*S,h[14]=2*x*m*S}else h[10]=-1,h[14]=-2*m;return h},ke=function(h,o,u,m,x,b,S){var A=1/(o-u),I=1/(m-x),D=1/(b-S);return h[0]=-2*A,h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=-2*I,h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[10]=2*D,h[11]=0,h[12]=(o+u)*A,h[13]=(x+m)*I,h[14]=(S+b)*D,h[15]=1,h},Ae=Q;function He(){var h=new T(3);return T!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0),h}function ot(h){var o=h[0],u=h[1],m=h[2];return Math.sqrt(o*o+u*u+m*m)}function nt(h,o,u){var m=new T(3);return m[0]=h,m[1]=o,m[2]=u,m}function tt(h,o,u,m){return h[0]=o,h[1]=u,h[2]=m,h}function vt(h,o,u){return h[0]=o[0]+u[0],h[1]=o[1]+u[1],h[2]=o[2]+u[2],h}function Vt(h,o,u){return h[0]=o[0]-u[0],h[1]=o[1]-u[1],h[2]=o[2]-u[2],h}function Ct(h,o,u){return h[0]=o[0]*u[0],h[1]=o[1]*u[1],h[2]=o[2]*u[2],h}function Bt(h,o,u){return h[0]=Math.min(o[0],u[0]),h[1]=Math.min(o[1],u[1]),h[2]=Math.min(o[2],u[2]),h}function cr(h,o,u){return h[0]=Math.max(o[0],u[0]),h[1]=Math.max(o[1],u[1]),h[2]=Math.max(o[2],u[2]),h}function ft(h,o,u){return h[0]=o[0]*u,h[1]=o[1]*u,h[2]=o[2]*u,h}function Kt(h,o,u,m){return h[0]=o[0]+u[0]*m,h[1]=o[1]+u[1]*m,h[2]=o[2]+u[2]*m,h}function ir(h,o){var u=o[0]-h[0],m=o[1]-h[1],x=o[2]-h[2];return Math.sqrt(u*u+m*m+x*x)}function Gr(h,o){var u=o[0]-h[0],m=o[1]-h[1],x=o[2]-h[2];return u*u+m*m+x*x}function tr(h){var o=h[0],u=h[1],m=h[2];return o*o+u*u+m*m}function Qt(h,o){return h[0]=-o[0],h[1]=-o[1],h[2]=-o[2],h}function zt(h,o){var u=o[0],m=o[1],x=o[2],b=u*u+m*m+x*x;return b>0&&(b=1/Math.sqrt(b)),h[0]=o[0]*b,h[1]=o[1]*b,h[2]=o[2]*b,h}function Vr(h,o){return h[0]*o[0]+h[1]*o[1]+h[2]*o[2]}function Jr(h,o,u){var m=o[0],x=o[1],b=o[2],S=u[0],A=u[1],I=u[2];return h[0]=x*I-b*A,h[1]=b*S-m*I,h[2]=m*A-x*S,h}function Fn(h,o,u,m){var x=o[0],b=o[1],S=o[2];return h[0]=x+m*(u[0]-x),h[1]=b+m*(u[1]-b),h[2]=S+m*(u[2]-S),h}function Ar(h,o,u){var m=o[0],x=o[1],b=o[2],S=u[3]*m+u[7]*x+u[11]*b+u[15];return h[0]=(u[0]*m+u[4]*x+u[8]*b+u[12])/(S=S||1),h[1]=(u[1]*m+u[5]*x+u[9]*b+u[13])/S,h[2]=(u[2]*m+u[6]*x+u[10]*b+u[14])/S,h}function Tn(h,o,u){var m=o[0],x=o[1],b=o[2];return h[0]=m*u[0]+x*u[3]+b*u[6],h[1]=m*u[1]+x*u[4]+b*u[7],h[2]=m*u[2]+x*u[5]+b*u[8],h}function mn(h,o,u){var m=u[0],x=u[1],b=u[2],S=u[3],A=o[0],I=o[1],D=o[2],B=x*D-b*I,U=b*A-m*D,q=m*I-x*A;return h[0]=A+S*(B+=B)+x*(q+=q)-b*(U+=U),h[1]=I+S*U+b*B-m*q,h[2]=D+S*q+m*U-x*B,h}function li(h){return h[0]=0,h[1]=0,h[2]=0,h}function Lr(h,o){return h[0]===o[0]&&h[1]===o[1]&&h[2]===o[2]}var Or=Vt,si=Ct,ss=ot;function ps(){var h=new T(4);return T!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0,h[3]=0),h}function Mi(h,o,u,m){var x=new T(4);return x[0]=h,x[1]=o,x[2]=u,x[3]=m,x}function gs(h,o,u){return h[0]=o[0]*u,h[1]=o[1]*u,h[2]=o[2]*u,h[3]=o[3]*u,h}function ma(h,o){var u=o[0],m=o[1],x=o[2],b=o[3],S=u*u+m*m+x*x+b*b;return S>0&&(S=1/Math.sqrt(S)),h[0]=u*S,h[1]=m*S,h[2]=x*S,h[3]=b*S,h}function Ki(h,o,u){var m=o[0],x=o[1],b=o[2],S=o[3];return h[0]=u[0]*m+u[4]*x+u[8]*b+u[12]*S,h[1]=u[1]*m+u[5]*x+u[9]*b+u[13]*S,h[2]=u[2]*m+u[6]*x+u[10]*b+u[14]*S,h[3]=u[3]*m+u[7]*x+u[11]*b+u[15]*S,h}function Hr(){var h=new T(4);return T!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0),h[3]=1,h}function ci(h){return h[0]=0,h[1]=0,h[2]=0,h[3]=1,h}function mo(h,o){var u=2*Math.acos(o[3]),m=Math.sin(u/2);return m>E?(h[0]=o[0]/m,h[1]=o[1]/m,h[2]=o[2]/m):(h[0]=1,h[1]=0,h[2]=0),u}function _r(h,o,u){u*=.5;var m=o[0],x=o[1],b=o[2],S=o[3],A=Math.sin(u),I=Math.cos(u);return h[0]=m*I+S*A,h[1]=x*I+b*A,h[2]=b*I-x*A,h[3]=S*I-m*A,h}function Da(h,o,u){u*=.5;var m=o[0],x=o[1],b=o[2],S=o[3],A=Math.sin(u),I=Math.cos(u);return h[0]=m*I-b*A,h[1]=x*I+S*A,h[2]=b*I+m*A,h[3]=S*I-x*A,h}function pn(h,o,u){u*=.5;var m=o[0],x=o[1],b=o[2],S=o[3],A=Math.sin(u),I=Math.cos(u);return h[0]=m*I+x*A,h[1]=x*I-m*A,h[2]=b*I+S*A,h[3]=S*I-b*A,h}He(),ps();var Vi,Yi,nn,Ke=ma,at=(Vi=He(),Yi=nt(1,0,0),nn=nt(0,1,0),function(h,o,u){var m=Vr(o,u);return m<-.999999?(Jr(Vi,Yi,o),ss(Vi)<1e-6&&Jr(Vi,nn,o),zt(Vi,Vi),function(x,b,S){S*=.5;var A=Math.sin(S);x[0]=A*b[0],x[1]=A*b[1],x[2]=A*b[2],x[3]=Math.cos(S)}(h,Vi,Math.PI),h):m>.999999?(h[0]=0,h[1]=0,h[2]=0,h[3]=1,h):(Jr(Vi,o,u),h[0]=Vi[0],h[1]=Vi[1],h[2]=Vi[2],h[3]=1+m,Ke(h,h))});function yt(){var h=new T(2);return T!=Float32Array&&(h[0]=0,h[1]=0),h}function rr(h,o){var u=new T(2);return u[0]=h,u[1]=o,u}function Er(h,o,u){return h[0]=o,h[1]=u,h}function Wr(h,o,u){return h[0]=o[0]+u[0],h[1]=o[1]+u[1],h}function Nr(h,o,u){return h[0]=o[0]-u[0],h[1]=o[1]-u[1],h}function Zr(h,o,u){return h[0]=o[0]*u,h[1]=o[1]*u,h}function $r(h){var o=h[0],u=h[1];return Math.sqrt(o*o+u*u)}function qn(h,o){var u=o[0],m=o[1],x=u*u+m*m;return x>0&&(x=1/Math.sqrt(x)),h[0]=o[0]*x,h[1]=o[1]*x,h}function ki(h,o){return h[0]*o[0]+h[1]*o[1]}Hr(),Hr(),P();var xs=Nr;function Ea(h,o,u,m){const x=3*h,b=3*(u-h)-x,S=1-x-b,A=3*o,I=3*(m-o)-A,D=1-A-I;return function(B,U=1e-6){if(B<=0)return 0;if(B>=1)return 1;let q=B;for(let J=0;J<8;J++){const se=((S*q+b)*q+x)*q-B;if(Math.abs(se)se?K=q:X=q,q=.5*(K+X)}return((D*q+I)*q+A)*q}}function jt(h,o){this.x=h,this.y=o}function Ha(h,o){if(Array.isArray(h)){if(!Array.isArray(o)||h.length!==o.length)return!1;for(let u=0;uu;){if(m-u>600){const I=m-u+1,D=o-u+1,B=Math.log(I),U=.5*Math.exp(2*B/3),q=.5*Math.sqrt(B*U*(I-U)/I)*(D-I/2<0?-1:1);wh(h,o,Math.max(u,Math.floor(o-D*U/I+q)),Math.min(m,Math.floor(o+(I-D)*U/I+q)),x)}const b=h[o];let S=u,A=m;for(Ud(h,u,o),x(h[m],b)>0&&Ud(h,u,m);S0;)A--}x(h[u],b)===0?Ud(h,u,A):(A++,Ud(h,A,m)),A<=o&&(u=A+1),o<=A&&(m=A-1)}}function Ud(h,o,u){const m=h[o];h[o]=h[u],h[u]=m}function mf(h,o){return ho?1:0}function Sh(h){let o=0;for(let u,m,x=0,b=h.length,S=b-1;x1)for(let S=0;S=o[2]||h[1]<=o[1]||h[3]>=o[3])}function WA(h,o,u){const m=h[0]-o[0],x=h[1]-o[1],b=h[0]-u[0],S=h[1]-u[1];return m*S-b*x===0&&m*b<=0&&x*S<=0}function Dw(h,o,u){return o[1]>h[1]!=u[1]>h[1]&&h[0]<(u[0]-o[0])*(h[1]-o[1])/(u[1]-o[1])+o[0]}function io(h,o,u=!1){let m=!1;for(let x=0,b=o.length;x0&&A<0||S<0&&A>0}function jg(h,o,u,m){return(x=[m[0]-u[0],m[1]-u[1]])[0]*(b=[o[0]-h[0],o[1]-h[1]])[1]-x[1]*b[0]!==0&&!(!Vd(h,o,u,m)||!Vd(u,m,h,o));var x,b}function up(h){const o=new jt(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),u=new jt(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const m of h[0])o.x>m.x&&(o.x=m.x),o.y>m.y&&(o.y=m.y),u.x=1)return 1;const o=h*h,u=o*h;return 4*(h<.5?u:3*(h-o)+u-.75)}const mx=Ea(.25,.1,.25,1);function cn(h,o,u){return Math.min(u,Math.max(o,h))}function rm(h,o,u){return(u=cn((u-h)/(o-h),0,1))*u*(3-2*u)}function uu(h,o,u){const m=u-o,x=((h-o)%m+m)%m+o;return x===o?u:x}function cd(h,o){const u={};for(let m=0;m>+o/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,h)}()}function r0(h){return h<=1?1:Math.pow(2,Math.ceil(Math.log2(h)))}function Pg(h){return!!h&&Mw.test(h)}function n0(h,o){const u=o;h.forEach(m=>{u[m]&&(u[m]=u[m].bind(o))})}function px(h,o,u){const m={};for(const x in h)m[x]=o.call(this,h[x],x,h);return m}function qd(h,o,u){const m={};for(const x in h)o.call(this,h[x],x,h)&&(m[x]=h[x]);return m}function ud(h){if(Array.isArray(h)){const o=new Array(h.length);for(let u=0;u(o.y-h.y)*(u.x-h.x)}function gx([h,o,u]){const m=Bn(o+90),x=Bn(u);return{x:h*Math.cos(m)*Math.sin(x),y:h*Math.sin(m)*Math.sin(x),z:h*Math.cos(x),azimuthal:o,polar:u}}function pf(h,o,u){const m=Math.sqrt(h*h+o*o+u*u),x=m>0?Math.acos(u/m)*tm:0;let b=h!==0||o!==0?Math.atan2(-o,-h)*tm+90:0;return b<0&&(b+=360),[m,b,x]}function fp(h){return(typeof self<"u"||h!==void 0)&&typeof WorkerGlobalScope<"u"&&(h!==void 0?h:self)instanceof WorkerGlobalScope}function nm(h){const o={};if(h.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(u,m,x,b)=>{const S=x||b;return o[m]=!S||S.toLowerCase(),""}),o["max-age"]){const u=parseInt(o["max-age"],10);isNaN(u)?delete o["max-age"]:o["max-age"]=u}return o}function Gd(h){return h?{cacheControl:h.get("cache-control"),expires:h.get("expires")}:{cacheControl:void 0,expires:void 0}}function du(h){try{const o=self[h];return o.setItem("_mapbox_test_",1),o.removeItem("_mapbox_test_"),!0}catch{return!1}}function gc(h,o){return[h[4*o],h[4*o+1],h[4*o+2],h[4*o+3]]}function s0(h,o,u){h[4*o+0]=u[0],h[4*o+1]=u[1],h[4*o+2]=u[2],h[4*o+3]=u[3]}function Uc(h){return[Math.pow(h[0],1/2.2),Math.pow(h[1],1/2.2),Math.pow(h[2],1/2.2)]}function Hd(h){return h>0?1/(1.001-h):1+h}function a0(h){return h>0?1-1/(1.001-h):-h}function Fw(h,o,u){return(h-o.min)*(u.max-u.min)/(o.max-o.min)+u.min}function o0(h){return h*h*h*h*h}function Th(h){return h>>>=0,h=Math.imul(2747636419^h,2654435769)>>>0,h=Math.imul(h^h>>>16,2654435769)>>>0,(h=Math.imul(h^h>>>16,2654435769)>>>0)/4294967296}let Bw,yx,zw,xx,dd,im;function $w(){return Bw??(Bw=self.OffscreenCanvas&&!!new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Bw}const hu={requestIdleCallback:h=>{if(typeof requestIdleCallback<"u")return requestIdleCallback(h);setTimeout(()=>h({didTimeout:!1,timeRemaining:()=>50}),0)},now:()=>xx!==void 0?xx:performance.now(),setNow(h){xx=h},restoreNow(){xx=void 0},frame(h){const o=requestAnimationFrame(h);return{cancel:()=>cancelAnimationFrame(o)}},getImageData(h,o=0){const{width:u,height:m}=h;dd||(dd=document.createElement("canvas"));const x=dd.getContext("2d",{willReadFrequently:!0});if(!x)throw new Error("failed to create canvas 2d context");return(u>dd.width||m>dd.height)&&(dd.width=u,dd.height=m),x.clearRect(-o,-o,u+2*o,m+2*o),x.drawImage(h,0,0,u,m),x.getImageData(-o,-o,u+2*o,m+2*o)},resolveURL:h=>(yx||(yx=document.createElement("a")),yx.href=h,yx.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(zw??(zw=window.matchMedia("(prefers-reduced-motion: reduce)")),zw.matches)},hasCanvasFingerprintNoise(){if(im!==void 0)return im;if(!$w())return im=!1,!1;const h=new OffscreenCanvas(85,1),o=h.getContext("2d",{willReadFrequently:!0});let u=0;for(let x=0;x0?`?${b}`:""}`}const je="mapbox-tiles";let Oe=500,ze=50;const Qe=["language","worldview","jobid"];let Xe;function Je(){try{return caches}catch{}}function rt(){const h=Je();h&&Xe==null&&(Xe=h.open(je))}let It=1/0;function wt(h){return Cn.API_URL_REGEX.test(h)}function St(h){return h.indexOf("mapbox:")===0}function Ot(h){return Cn.API_CDN_URL_REGEX.test(h)}function pr(h){return Cn.API_SPRITE_REGEX.test(h)}function Ht(h){return Cn.API_STYLE_REGEX.test(h)&&!pr(h)}const er={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(er);class Zt extends Error{constructor(o,u,m){super(),this.url=m,this.statusText=o,this.status=u}get message(){return this.status===401&&wt(this.url)?`${this.statusText}: you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/guides/#access-tokens-and-token-scopes`:this.statusText}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function Rr(h){return typeof h=="object"&&h!==null&&"status"in h&&h.status===404}const un=fp()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Zn=/^\w+:/,an=/[\r\n]+/;async function on(h,o){let u;return u=h.type==="arrayBuffer"?await o.arrayBuffer():h.type==="json"?await o.json():await o.text(),{data:u,headers:o.headers}}async function Ln(h,o){return o&&o.throwIfAborted(),(u=h.url).startsWith("file:")||un().startsWith("file:")&&!Zn.test(u)?async function(m,x){return new Promise((b,S)=>{const A=new XMLHttpRequest,I=()=>{x.removeEventListener("abort",I),A.abort(),S(x.reason)};x&&x.addEventListener("abort",I),A.open(m.method||"GET",m.url,!0),m.type==="arrayBuffer"&&(A.responseType="arraybuffer");for(const D in m.headers)A.setRequestHeader(D,m.headers[D]);m.type==="json"&&(A.responseType="text",A.setRequestHeader("Accept","application/json")),A.withCredentials=m.credentials==="include",A.onerror=()=>{x&&x.removeEventListener("abort",I),S(new Error(A.statusText))},A.onload=()=>{if(x&&x.removeEventListener("abort",I),(A.status>=200&&A.status<300||A.status===0)&&A.response!==null){let D=A.response;if(m.type==="json")try{D=JSON.parse(A.response)}catch(U){return void S(U)}const B=new Headers;A.getAllResponseHeaders().trim().split(an).forEach(U=>{const q=U.split(": "),K=q.shift(),X=q.join(": ");K&&B.set(K,X)}),b({data:D,headers:B})}else S(new Zt(A.statusText,A.status,m.url))},A.send(m.body)})}(h,o):async function(m,x){const b=new Request(m.url,{method:m.method||"GET",body:m.body,credentials:m.credentials,headers:m.headers,referrer:un(),referrerPolicy:m.referrerPolicy,signal:x}),S=(A=b.url).indexOf("sku=")>0&&wt(A);var A;if(m.type==="json"&&b.headers.set("Accept","application/json"),S){let q=null;try{q=await async function(K){if(rt(),Xe==null)return null;const X=await Xe;let J=_e(K.url,{persistentParams:Qe});const se=K.headers.get("Range");se&&(J=he(J,{range:se}));const ae=await X.match(J);if(!ae)return null;const ue=function(ce){if(!ce)return!1;const de=new Date(ce.headers.get("expires")||0),xe=nm(ce.headers.get("cache-control")||"");return Number(de)>Date.now()&&!xe["no-cache"]}(ae);return X.delete(J).catch(ce=>Xi(ce.message)),ue&&X.put(J,ae.clone()).catch(ce=>Xi(ce.message)),{response:ae,fresh:ue}}(b)}catch(K){K.message!=="SecurityError"&&Xi(K.toString())}if(q&&q.fresh)return x&&x.throwIfAborted(),on(m,q.response)}const I=Date.now();let D;try{D=await fetch(b)}catch(q){throw q.name==="AbortError"?q:new Error(`${q.message} ${m.url}`,{cause:q})}if(x&&x.throwIfAborted(),!D.ok)throw new Zt(D.statusText,D.status,m.url);const B=S?D.clone():null,U=await on(m,D);return B&&async function(q,K,X){if(rt(),Xe==null)return;const J=nm(K.headers.get("cache-control")||"");if(J["no-store"])return;const se={status:K.status,statusText:K.statusText,headers:new Headers(K.headers)};J["max-age"]&&se.headers.set("Expires",new Date(X+1e3*J["max-age"]).toUTCString());const ae=se.headers.get("expires");if(!ae||new Date(ae).getTime()-X<42e4)return;let ue=_e(q.url,{persistentParams:Qe});if(K.status===206){const xe=q.headers.get("Range");if(!xe)return;se.status=200,ue=he(ue,{range:xe})}const ce=new Response((de=K.status)!==200&&de!==404&&[101,103,204,205,304].includes(de)?null:K.body,se);var de;if(rt(),Xe!=null)try{await(await Xe).put(ue,ce)}catch(xe){Xi(xe.message)}}(b,B,I),U}(h,o);var u}async function ui(h,o){return Ln(Object.assign(h,{type:"json"}),o)}async function di(h,o){return Ln(Object.assign(h,{type:"arrayBuffer"}),o)}function Un(h){const o=document.createElement("a");return o.href=h,o.protocol===location.protocol&&o.host===location.host}let wn,ri;wn=[],ri=0;const Fi="01",vi={create:"create",load:"load",fullLoad:"fullLoad"},vs={mark(h){performance.mark(h)},measure(h,o,u){performance.measure(h,o,u)}};function en(h){const o=h.name.split("?")[0];return Ot(o)&&o.includes("mapbox-gl.js")?"javascript":Ot(o)&&o.includes("mapbox-gl.css")?"css":function(u){return Cn.API_FONTS_REGEX.test(u)}(o)?"fontRange":pr(o)?"sprite":Ht(o)?"style":function(u){return Cn.API_TILEJSON_REGEX.test(u)}(o)?"tilejson":"other"}const ai=/(\.(png|jpg)\d*)(?=$)/,Si=/^.+\/v4\//,Ta=/\.[\w]+$/,tl=/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/,Es=/^access_token=(.*)$/,Ts="NO_ACCESS_TOKEN",Gs=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function Rs(h){const o=h.match(Gs);if(!o)throw new Error("Unable to parse URL object");return{protocol:o[1],authority:o[2],path:o[3]||"/",params:o[4]?o[4].split("&"):[]}}function ko(h){const o=h.params.length?`?${h.params.join("&")}`:"";return`${h.protocol}://${h.authority}${h.path}${o}`}const yc="mapbox.eventData";function pa(h){if(!h)return null;const o=h.split(".");if(!o||o.length!==3)return null;try{return JSON.parse(decodeURIComponent(atob(o[1]).split("").map(m=>"%"+("00"+m.charCodeAt(0).toString(16)).slice(-2)).join("")))}catch{return null}}function so(h){return!(!Cn.EVENTS_URL||!h&&!Cn.ACCESS_TOKEN)}let ys;const as=/^[\w.+-]+(\/[\w.+-]+)?$/;let Rl="other";class Ma{constructor(o){this.type=o,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=!1}getStorageKey(o){const u=pa(Cn.ACCESS_TOKEN);let m="";return m=u&&u.u?btoa(encodeURIComponent(u.u).replace(/%([0-9A-F]{2})/g,(x,b)=>String.fromCharCode(+("0x"+b)))):Cn.ACCESS_TOKEN||"",o?`${yc}.${o}:${m}`:`${yc}:${m}`}fetchEventData(){const o=du("localStorage"),u=this.getStorageKey(),m=this.getStorageKey("uuid"),x=this.getStorageKey("uuidTimestamp");if(o)try{const b=localStorage.getItem(u);b&&(this.eventData=JSON.parse(b));const S=localStorage.getItem(m);S&&(this.anonId=S);const A=localStorage.getItem(x);A&&(this.anonIdTimestamp=Number(A));const I=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(u,JSON.stringify(this.eventData)),S&&localStorage.setItem(x,S.toString())}catch{Xi("Unable to write to LocalStorage")}}processRequests(){}postEvent(o,u,m,x){if(!Cn.EVENTS_URL)return;const b=Rs(Cn.EVENTS_URL);b.params.push(`access_token=${x||Cn.ACCESS_TOKEN||""}`);const S={event:this.type,created:new Date(o).toISOString()},A=u?Object.assign(S,u):S,I={url:ko(b),headers:{"Content-Type":"text/plain"},body:JSON.stringify([A])};this.pendingRequest=!0,async function(D){return Ln(Object.assign(D,{method:"POST"}),void 0)}(I).then(()=>{this.pendingRequest=!1,m(null),this.saveEventData(),this.processRequests()}).catch(D=>{this.pendingRequest=!1,m(D),this.saveEventData(),this.processRequests()})}queueRequest(o,u){this.queue.push({...o,customAccessToken:u}),this.processRequests()}}class qi extends Ma{constructor(o){super("metrics"),o&&(this.data=o)}postMetricsEvent(o){if(!so(o))return;this.anonId||this.fetchEventData(),Pg(this.anonId)||this.refreshUUID();const u={...this.data,sessionId:this.anonId};this.queueRequest({timestamp:Date.now(),payload:u},o)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:o,payload:u,customAccessToken:m}=this.queue.shift();this.postEvent(o,u,()=>{},m)}}const Wa=new class extends Ma{constructor(h){super("appUserTurnstile"),this._customAccessToken=h}postTurnstileEvent(h,o){so(o)&&Array.isArray(h)&&h.some(u=>St(u)||wt(u))&&this.queueRequest({timestamp:Date.now()},o)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const h=pa(Cn.ACCESS_TOKEN),o=h?h.u:Cn.ACCESS_TOKEN;let u=o!==this.eventData.tokenU;Pg(this.anonId)||(this.refreshUUID(),u=!0);const{timestamp:m,customAccessToken:x}=this.queue.shift();if(this.eventData.lastSuccess){const S=new Date(this.eventData.lastSuccess),A=new Date(m),I=(m-this.eventData.lastSuccess)/864e5;u=u||I>=1||I<-1||S.getDate()!==A.getDate()}else u=!0;if(!u)return void this.processRequests();const b={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:v,skuId:Fi,"enabled.telemetry":!1,userId:this.anonId,bundleFormat:"umd",bundleDistribution:Rl};ys&&(b.sdkInfo=ys),this.postEvent(m,b,S=>{S||(this.eventData.lastSuccess=m,this.eventData.tokenU=o)},x)}},Ll=Wa.postTurnstileEvent.bind(Wa),vl=new class extends Ma{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(h,o,u,m){this.skuToken=o,this.errorCb=m,Cn.EVENTS_URL&&(u||Cn.ACCESS_TOKEN?this.queueRequest({id:h,timestamp:Date.now()},u):this.errorCb(new Error(Ts)))}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{id:h,timestamp:o,customAccessToken:u}=this.queue.shift();if(h&&this.success[h])return;this.anonId&&this.anonIdTimestamp||this.fetchEventData(),Pg(this.anonId)||this.refreshUUID();const m={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:v,skuId:Fi,skuToken:this.skuToken,userId:this.anonId,bundleFormat:"umd",bundleDistribution:Rl};ys&&(m.sdkInfo=ys),this.postEvent(o,m,x=>{x?this.errorCb(x):h&&(this.success[h]=!0)},u)}remove(){this.errorCb=null}},bl=vl.postMapLoadEvent.bind(vl),Wd=new class extends Ma{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(h){let o=this.mapInstanceIdMap.get(h);return o||(o=dp(),this.mapInstanceIdMap.set(h,o)),o}getEventId(h){const o=this.eventIdPerMapInstanceMap.get(h)||0;return this.eventIdPerMapInstanceMap.set(h,o+1),o}postStyleLoadEvent(h,o){const{map:u,style:m,importedStyles:x}=o;if(!so(h))return;const b=this.getMapInstanceId(u),S={mapInstanceId:b,eventId:this.getEventId(b),style:m};x.length&&(S.importedStyles=x),this.queueRequest({timestamp:Date.now(),payload:S},h)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:h,payload:o,customAccessToken:u}=this.queue.shift();this.postEvent(h,o,()=>{},u)}},xc=Wd.postStyleLoadEvent.bind(Wd),ta=new qi({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Zs=ta.postMetricsEvent.bind(ta),Dl=new qi({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),Vc=Dl.postMetricsEvent.bind(Dl),fu=new class extends Ma{constructor(){super("gljs.performance")}postPerformanceEvent(h,o){so(h)&&this.queueRequest({timestamp:Date.now(),performanceData:o},h)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:h,performanceData:o,customAccessToken:u}=this.queue.shift(),m=function(x){const b=performance.getEntriesByType("resource"),S=performance.getEntriesByType("mark"),A=function(K){const X={};if(K){for(const J in K)if(J!=="other")for(const se of K[J]){const ae=`${J}ResolveRangeMin`,ue=`${J}ResolveRangeMax`,ce=`${J}RequestCount`,de=`${J}RequestCachedCount`;X[ae]=Math.min(X[ae]||1/0,se.startTime),X[ue]=Math.max(X[ue]||-1/0,se.responseEnd);const xe=ve=>{X[ve]===void 0&&(X[ve]=0),++X[ve]};se.transferSize!==void 0&&se.transferSize===0&&xe(de),xe(ce)}}return X}(function(K,X){const J={};if(K)for(const se of K){const ae=X(se);J[ae]===void 0&&(J[ae]=[]),J[ae].push(se)}return J}(b,en)),I=window.devicePixelRatio,D=navigator.connection||navigator.mozConnection||navigator.webkitConnection,B=D?D.effectiveType:void 0,U={counters:[],metadata:[],attributes:[]},q=(K,X,J)=>{J!=null&&K.push({name:X,value:J.toString()})};for(const K in A)q(U.counters,K,A[K]);if(x.interactionRange[0]!==1/0&&x.interactionRange[1]!==-1/0&&(q(U.counters,"interactionRangeMin",x.interactionRange[0]),q(U.counters,"interactionRangeMax",x.interactionRange[1])),S)for(const K of Object.values(vi)){const X=S.find(J=>J.name===K);X&&q(U.counters,K,X.startTime)}return q(U.counters,"visibilityHidden",x.visibilityHidden),q(U.attributes,"style",function(K){if(K)for(const X of K){const J=X.name.split("?")[0];if(Ht(J)){const se=J.split("/").slice(-2);if(se.length===2)return`mapbox://styles/${se[0]}/${se[1]}`}}}(b)),q(U.attributes,"terrainEnabled",x.terrainEnabled?"true":"false"),q(U.attributes,"fogEnabled",x.fogEnabled?"true":"false"),q(U.attributes,"projection",x.projection),q(U.attributes,"zoom",x.zoom),q(U.metadata,"devicePixelRatio",I),q(U.metadata,"connectionEffectiveType",B),q(U.metadata,"navigatorUserAgent",navigator.userAgent),q(U.metadata,"screenWidth",window.screen.width),q(U.metadata,"screenHeight",window.screen.height),q(U.metadata,"windowWidth",window.innerWidth),q(U.metadata,"windowHeight",window.innerHeight),q(U.metadata,"mapWidth",x.width/I),q(U.metadata,"mapHeight",x.height/I),q(U.metadata,"webglRenderer",x.renderer),q(U.metadata,"webglVendor",x.vendor),q(U.metadata,"sdkVersion",v),q(U.metadata,"sdkIdentifier","mapbox-gl-js"),U}(o);for(const x of m.metadata);for(const x of m.counters);for(const x of m.attributes);this.postEvent(h,m,()=>{},u)}},Ml=fu.postPerformanceEvent.bind(fu),Vu=new class extends Ma{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(h,o,u,m){if(!Cn.API_URL||!Cn.SESSION_PATH)return;const x=Rs(Cn.API_URL+Cn.SESSION_PATH);x.params.push(`sku=${o||""}`),x.params.push(`access_token=${m||Cn.ACCESS_TOKEN||""}`);const b={url:ko(x),headers:{"Content-Type":"text/plain"}};this.pendingRequest=!0,async function(S){return Ln(Object.assign(S,{method:"GET"}),void 0)}(b).then(()=>{this.pendingRequest=!1,u(null),this.saveEventData(),this.processRequests()}).catch(S=>{this.pendingRequest=!1,u(S),this.saveEventData(),this.processRequests()})}getSessionAPI(h,o,u,m){this.skuToken=o,this.errorCb=m,Cn.EVENTS_URL&&Cn.SESSION_PATH&&Cn.API_URL&&(u||Cn.ACCESS_TOKEN?this.queueRequest({id:h,timestamp:Date.now()},u):this.errorCb(new Error(Ts)))}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{id:h,timestamp:o,customAccessToken:u}=this.queue.shift();h&&this.success[h]||this.getSession(o,this.skuToken,m=>{m?this.errorCb(m):h&&(this.success[h]=!0)},u)}remove(){this.errorCb=null}},wl=Vu.getSessionAPI.bind(Vu),rl=new Set;function Kl(h,o=0){const x=h.length,b=x-(3&x);let S,A=0|o,I=0;for(;I>>17,S=Math.imul(S,461845907),A^=S,A=A<<13|A>>>19,A=Math.imul(A,5)+3864292196|0;S=0;const D=3&x;return D>0&&(D>=3&&(S^=(255&h.charCodeAt(I+2))<<16),D>=2&&(S^=(255&h.charCodeAt(I+1))<<8),S^=255&h.charCodeAt(I),S=Math.imul(S,3432918353),S=S<<15|S>>>17,S=Math.imul(S,461845907),A^=S),A^=x,A^=A>>>16,A=Math.imul(A,2246822507),A^=A>>>13,A=Math.imul(A,3266489909),A^=A>>>16,A>>>0}class nl{constructor(o,...u){Object.assign(this,u[0]||{}),this.type=o}}class Oa extends nl{constructor(o,u={}){super("error",{error:o,...u}),this.error=o}}function Yl(h,o,u){u[h]&&u[h].includes(o)||(u[h]=u[h]||[],u[h].push(o))}function Aa(h,o,u){if(u[h]){const m=u[h].indexOf(o);m!==-1&&u[h].splice(m,1)}}class ca{constructor(){this._listeners={},this._oneTimeListeners={}}on(o,u){return Yl(o,u,this._listeners),this}off(o,u){return Aa(o,u,this._listeners),Aa(o,u,this._oneTimeListeners),this}once(o,u){return u?(Yl(o,u,this._oneTimeListeners),this):new Promise(m=>{this.once(o,m)})}fire(o,u){const m=typeof o=="string"?new nl(o,u):o,x=m.type;if(this.listens(x)){m.target=this;const b=this._listeners[x]?this._listeners[x].slice():[];for(const I of b)I.call(this,m);const S=this._oneTimeListeners[x]?this._oneTimeListeners[x].slice():[];for(const I of S)Aa(x,I,this._oneTimeListeners),I.call(this,m);const A=this._eventedParent;if(A){const I=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(m,I),A.fire(m)}}else m instanceof Oa&&console.error(m.error);return this}listens(o){return!!(this._listeners[o]&&this._listeners[o].length>0||this._oneTimeListeners[o]&&this._oneTimeListeners[o].length>0||this._eventedParent&&this._eventedParent.listens(o))}setEventedParent(o,u){return this._eventedParent=o,this._eventedParentData=u,this}}class ga{constructor(o){typeof o=="string"?this.name=o:(this.name=o.name,this.iconsetId=o.iconsetId)}static from(o){return new ga(o)}static toString(o){return o.iconsetId?`${o.name}${o.iconsetId}`:o.name}static parse(o){const[u,m]=o.split("");return new ga({name:u,iconsetId:m})}static isEqual(o,u){return o.name===u.name&&o.iconsetId===u.iconsetId}toString(){return ga.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var Zl,Ka={},hd=function(){if(Zl)return Ka;Zl=1;var h={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function o(b){return(b=Math.round(b))<0?0:b>255?255:b}function u(b){return o(b[b.length-1]==="%"?parseFloat(b)/100*255:parseInt(b))}function m(b){return(S=b[b.length-1]==="%"?parseFloat(b)/100:parseFloat(b))<0?0:S>1?1:S;var S}function x(b,S,A){return A<0?A+=1:A>1&&(A-=1),6*A<1?b+(S-b)*A*6:2*A<1?S:3*A<2?b+(S-b)*(2/3-A)*6:b}try{Ka.parseCSSColor=function(b){var S,A=b.replace(/ /g,"").toLowerCase();if(A in h)return h[A].slice();if(A[0]==="#")return A.length===4?(S=parseInt(A.substr(1),16))>=0&&S<=4095?[(3840&S)>>4|(3840&S)>>8,240&S|(240&S)>>4,15&S|(15&S)<<4,1]:null:A.length===7&&(S=parseInt(A.substr(1),16))>=0&&S<=16777215?[(16711680&S)>>16,(65280&S)>>8,255&S,1]:null;var I=A.indexOf("("),D=A.indexOf(")");if(I!==-1&&D+1===A.length){var B=A.substr(0,I),U=A.substr(I+1,D-(I+1)).split(","),q=1;switch(B){case"rgba":if(U.length!==4)return null;q=m(U.pop());case"rgb":return U.length!==3?null:[u(U[0]),u(U[1]),u(U[2]),q];case"hsla":if(U.length!==4)return null;q=m(U.pop());case"hsl":if(U.length!==3)return null;var K=(parseFloat(U[0])%360+360)%360/360,X=m(U[1]),J=m(U[2]),se=J<=.5?J*(X+1):J+X-J*X,ae=2*J-se;return[o(255*x(ae,se,K+1/3)),o(255*x(ae,se,K)),o(255*x(ae,se,K-1/3)),q];default:return null}}return null}}catch{}return Ka}();function Kr(h,o,u){return h*(1-u)+o*u}const l0=new Map;class Vn{constructor(o,u,m,x=1){this.r=o,this.g=u,this.b=m,this.a=x}static parse(o){if(!o)return;if(o instanceof Vn)return o;if(typeof o!="string")return;const u=l0.get(o);if(u)return u;const m=hd.parseCSSColor(o);if(!m)return;const x=new Vn(m[0]/255,m[1]/255,m[2]/255,m[3]);return l0.set(o,x),x}toString(){const{r:o,g:u,b:m,a:x}=this;return`rgba(${Math.round(255*o)},${Math.round(255*u)},${Math.round(255*m)},${x})`}toNonPremultipliedRenderColor(o){const{r:u,g:m,b:x,a:b}=this;return new bx(o,u,m,x,b)}toPremultipliedRenderColor(o){const{r:u,g:m,b:x,a:b}=this;return new Uw(o,u*b,m*b,x*b,b)}clone(){return new Vn(this.r,this.g,this.b,this.a)}}class vx{constructor(o,u,m,x,b,S=!1){if(this.premultiplied=!1,this.premultiplied=S,o){const A=o.image.height,I=A*A;this.premultiplied?(u=b===0?0:u/b*(A-1),m=b===0?0:m/b*(A-1),x=b===0?0:x/b*(A-1)):(u*=A-1,m*=A-1,x*=A-1),u=Math.max(0,Math.min(A-1,u)),m=Math.max(0,Math.min(A-1,m)),x=Math.max(0,Math.min(A-1,x));const D=Math.floor(u),B=Math.floor(m),U=Math.floor(x),q=Math.ceil(u),K=Math.ceil(m),X=Math.ceil(x),J=u-D,se=m-B,ae=x-U,ue=o.image.data,ce=4*(D+B*I+U*A),de=4*(D+B*I+X*A),xe=4*(D+K*I+U*A),ve=4*(D+K*I+X*A),Ue=4*(q+B*I+U*A),Pe=4*(q+B*I+X*A),De=4*(q+K*I+U*A),Ve=4*(q+K*I+X*A);this.r=Kr(Kr(Kr(ue[ce],ue[de],ae),Kr(ue[xe],ue[ve],ae),se),Kr(Kr(ue[Ue],ue[Pe],ae),Kr(ue[De],ue[Ve],ae),se),J)/255*(this.premultiplied?b:1),this.g=Kr(Kr(Kr(ue[ce+1],ue[de+1],ae),Kr(ue[xe+1],ue[ve+1],ae),se),Kr(Kr(ue[Ue+1],ue[Pe+1],ae),Kr(ue[De+1],ue[Ve+1],ae),se),J)/255*(this.premultiplied?b:1),this.b=Kr(Kr(Kr(ue[ce+2],ue[de+2],ae),Kr(ue[xe+2],ue[ve+2],ae),se),Kr(Kr(ue[Ue+2],ue[Pe+2],ae),Kr(ue[De+2],ue[Ve+2],ae),se),J)/255*(this.premultiplied?b:1),this.a=b}else this.r=u,this.g=m,this.b=x,this.a=b}toArray(){const{r:o,g:u,b:m,a:x}=this;return[255*o,255*u,255*m,x]}toHslaArray(){let{r:o,g:u,b:m,a:x}=this;if(this.premultiplied){if(x===0)return[0,0,0,0];const X=1/x;o*=X,u*=X,m*=X}const b=Math.min(Math.max(o,0),1),S=Math.min(Math.max(u,0),1),A=Math.min(Math.max(m,0),1),I=Math.min(b,S,A),D=Math.max(b,S,A),B=D-I,U=.5*(I+D);if(B===0)return[0,0,100*U,x];const q=U>.5?B/(2-D-I):B/(D+I);let K;switch(D){case b:K=60*((S-A)/B+(SKr(m,o[x],u))}Vn.black=new Vn(0,0,0,1),Vn.white=new Vn(1,1,1,1),Vn.transparent=new Vn(0,0,0,0),Vn.red=new Vn(1,0,0,1),Vn.blue=new Vn(0,0,1,1);var Ah=Object.freeze({__proto__:null,array:yf,color:function(h,o,u){return new Vn(Kr(h.r,o.r,u),Kr(h.g,o.g,u),Kr(h.b,o.b,u),Kr(h.a,o.a,u))},number:Kr});class Xl extends Error{constructor(o,u){super(u),this.message=u,this.key=o}}class kh{constructor(o,u=[]){this.parent=o,this.bindings=Object.create(null);for(const[m,x]of u)this.bindings[m]=x}concat(o){return new kh(this,o)}get(o){if(this.bindings[o])return this.bindings[o];if(this.parent)return this.parent.get(o);throw new Error(`${o} not found in scope.`)}has(o){return!!this.bindings[o]||!!this.parent&&this.parent.has(o)}}const il={kind:"null"},Yr={kind:"number"},Ei={kind:"string"},Bi={kind:"boolean"},_c={kind:"color"},xf={kind:"object"},Pi={kind:"value"},mp={kind:"collator"},pp={kind:"formatted"},sm={kind:"resolvedImage"};function Bo(h,o){return{kind:"array",itemType:h,N:o}}function Xs(h){if(h.kind==="array"){const o=Xs(h.itemType);return typeof h.N=="number"?`array<${o}, ${h.N}>`:h.itemType.kind==="value"?"array":`array<${o}>`}return h.kind}function Ng(h,o){return Kd(h,o)?null:`Expected ${Xs(h)} but found ${Xs(o)} instead.`}function Kd(h,o){return o.kind==="error"||(h.kind==="array"?o.kind==="array"&&(o.N===0&&o.itemType.kind==="value"||Kd(h.itemType,o.itemType))&&(typeof h.N!="number"||h.N===o.N):h.kind===o.kind||h.kind==="value"&&o.kind!=="collator")}function _f(h,o){return o.some(u=>u==="null"?h===null:u==="array"?Array.isArray(h):u==="object"?h&&!Array.isArray(h)&&typeof h=="object":u===typeof h)}function gp(h,o){return h.kind==="array"&&o.kind==="array"?h.N===o.N&&gp(h.itemType,o.itemType):h.kind===o.kind}class Rg{constructor(o,u,m){this.sensitivity=o?u?"variant":"case":u?"accent":"base",this.locale=m,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(o,u){return this.collator.compare(o,u)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class yp{constructor(o,u,m,x,b){this.text=o.normalize?o.normalize():o,this.image=u,this.scale=m,this.fontStack=x,this.textColor=b}}class sl{constructor(o){this.sections=o}static fromString(o){return new sl([new yp(o,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(o=>o.text.length!==0||!!o.image&&o.image.hasPrimary())}static factory(o){return o instanceof sl?o:sl.fromString(o)}toString(){return this.sections.length===0?"":this.sections.map(o=>o.text).join("")}serialize(){const o=["format"];for(const u of this.sections){if(u.image){const x=u.image.getPrimary().id.toString();o.push(["image",x]);continue}o.push(u.text);const m={};u.fontStack&&(m["text-font"]=["literal",u.fontStack.split(",")]),u.scale&&(m["font-scale"]=u.scale),u.textColor&&(m["text-color"]=["rgba"].concat(u.textColor.toNonPremultipliedRenderColor(null).toArray())),o.push(m)}return o}}class Io{constructor(o,u={}){this.id=ga.from(o),this.params=u.params,this.sx=u.sx||1,this.sy=u.sy||1}toString(){return JSON.stringify(this)}static parse(o){let u,m,x,b;try{({id:u,params:m,sx:x,sy:b}=JSON.parse(o)||{})}catch{return null}return u?new Io(u,{params:m,sx:x,sy:b}):null}scaleSelf(o,u=o){return this.sx*=o,this.sy*=u,this}}class Ol{constructor(o,u,m,x,b=!1){this.primaryId=ga.from(o),this.primaryOptions=u,m&&(this.secondaryId=ga.from(m)),this.secondaryOptions=x,this.available=b}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new Io(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Io(this.secondaryId,this.secondaryOptions):null}static from(o){return typeof o!="string"?o:Ol.build({name:o})}static build(o,u,m,x){return!o||typeof o=="object"&&!("name"in o)?null:new Ol(o,m,u,x)}}function Lg(h,o,u,m){return typeof h=="number"&&h>=0&&h<=255&&typeof o=="number"&&o>=0&&o<=255&&typeof u=="number"&&u>=0&&u<=255?m===void 0||typeof m=="number"&&m>=0&&m<=1?null:`Invalid rgba value [${[h,o,u,m].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof m=="number"?[h,o,u,m]:[h,o,u]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function vf(h){if(h===null||typeof h=="string"||typeof h=="boolean"||typeof h=="number"||h instanceof Vn||h instanceof Rg||h instanceof sl||h instanceof Ol)return!0;if(Array.isArray(h)){for(const o of h)if(!vf(o))return!1;return!0}if(typeof h=="object"){for(const o in h)if(!vf(h[o]))return!1;return!0}return!1}function zo(h){if(h===null)return il;if(typeof h=="string")return Ei;if(typeof h=="boolean")return Bi;if(typeof h=="number")return Yr;if(h instanceof Vn)return _c;if(h instanceof Rg)return mp;if(h instanceof sl)return pp;if(h instanceof Ol)return sm;if(Array.isArray(h)){const o=h.length;let u;for(const m of h){const x=zo(m);if(u){if(u===x)continue;u=Pi;break}u=x}return Bo(u||Pi,o)}return xf}function qu(h){return h===null?"":typeof h=="string"||typeof h=="number"||typeof h=="boolean"?String(h):h instanceof sl||h instanceof Ol||h instanceof Vn?h.toString():JSON.stringify(h)}class qc{constructor(o,u){this.type=o,this.value=u}static parse(o,u){if(o.length!==2)return u.error(`'literal' expression requires exactly one argument, but found ${o.length-1} instead.`);if(!vf(o[1]))return u.error("invalid value");const m=o[1];let x=zo(m);const b=u.expectedType;return x.kind!=="array"||x.N!==0||!b||b.kind!=="array"||typeof b.N=="number"&&b.N!==0||(x=b),new qc(x,m)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Vn?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof sl?this.value.serialize():this.value}}class ra{constructor(o){this.name="ExpressionEvaluationError",this.message=o}toJSON(){return this.message}}const xp={string:Ei,number:Yr,boolean:Bi,object:xf};class fd{constructor(o,u){this.type=o,this.args=u}static parse(o,u){if(o.length<2)return u.error("Expected at least one argument.");let m,x=1;const b=o[0];if(b==="array"){let A,I;if(o.length>2){const D=o[1];if(typeof D!="string"||!(D in xp)||D==="object")return u.error('The item type argument of "array" must be one of string, number, boolean',1);A=xp[D],x++}else A=Pi;if(o.length>3){if(o[2]!==null&&(typeof o[2]!="number"||o[2]<0||o[2]!==Math.floor(o[2])))return u.error('The length argument to "array" must be a positive integer literal',2);I=o[2],x++}m=Bo(A,I)}else m=xp[b];const S=[];for(;xo.outputDefined())}serialize(){const o=this.type,u=[o.kind];if(o.kind==="array"){const m=o.itemType;if(m.kind==="string"||m.kind==="number"||m.kind==="boolean"){u.push(m.kind);const x=o.N;(typeof x=="number"||this.args.length>1)&&u.push(x)}}return u.concat(this.args.map(m=>m.serialize()))}}class kn{constructor(o){this.type=pp,this.sections=o}static parse(o,u){if(o.length<2)return u.error("Expected at least one argument.");const m=o[1];if(!Array.isArray(m)&&typeof m=="object")return u.error("First argument must be an image or text section.");const x=[];let b=!1;for(let S=1;S<=o.length-1;++S){const A=o[S];if(b&&typeof A=="object"&&!Array.isArray(A)){b=!1;let I=null;if(A["font-scale"]&&(I=u.parseObjectValue(A["font-scale"],S,"font-scale",Yr),!I))return null;let D=null;if(A["text-font"]&&(D=u.parseObjectValue(A["text-font"],S,"text-font",Bo(Ei)),!D))return null;let B=null;if(A["text-color"]&&(B=u.parseObjectValue(A["text-color"],S,"text-color",_c),!B))return null;const U=x.at(-1);U.scale=I,U.font=D,U.textColor=B}else{const I=u.parse(o[S],S,Pi);if(!I)return null;const D=I.type.kind;if(D!=="string"&&D!=="value"&&D!=="null"&&D!=="resolvedImage")return u.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");b=!0,x.push({content:I,scale:null,font:null,textColor:null})}}return new kn(x)}evaluate(o){return new sl(this.sections.map(u=>{const m=u.content.evaluate(o);return gp(zo(m),sm)?new yp("",m,null,null,null):new yp(qu(m),null,u.scale?u.scale.evaluate(o):null,u.font?u.font.evaluate(o).join(","):null,u.textColor?u.textColor.evaluate(o):null)}))}eachChild(o){for(const u of this.sections)o(u.content),u.scale&&o(u.scale),u.font&&o(u.font),u.textColor&&o(u.textColor)}outputDefined(){return!1}serialize(){const o=["format"];for(const u of this.sections){o.push(u.content.serialize());const m={};u.scale&&(m["font-scale"]=u.scale.serialize()),u.font&&(m["text-font"]=u.font.serialize()),u.textColor&&(m["text-color"]=u.textColor.serialize()),o.push(m)}return o}}class al{constructor(o,u,m,x){this._imageWarnHistory={},this.type=sm,this.namePrimary=o,this.nameSecondary=u,m&&(this.paramsPrimary=m.params,this.iconsetIdPrimary=m.iconset?m.iconset.id:void 0),x&&(this.paramsSecondary=x.params,this.iconsetIdSecondary=x.iconset?x.iconset.id:void 0)}static parse(o,u){if(o.length<2)return u.error("Expected two or more arguments.");let m=1;const x=[];function b(){if(mga.isEqual(S,b)),x.available){const S=x.getSecondary()?x.getSecondary().id:null;S&&(x.available=o.availableImages.some(A=>ga.isEqual(A,S)))}}return x}eachChild(o){if(o(this.namePrimary),this.paramsPrimary)for(const u in this.paramsPrimary)this.paramsPrimary[u]&&o(this.paramsPrimary[u]);if(this.nameSecondary&&(o(this.nameSecondary),this.paramsSecondary))for(const u in this.paramsSecondary)this.paramsSecondary[u]&&o(this.paramsSecondary[u])}outputDefined(){return!1}serializeOptions(o,u){const m={};if(u&&(m.iconset={id:u}),o){m.params={};for(const x in o)o[x]&&(m.params[x]=o[x].serialize())}return Object.keys(m).length>0?m:void 0}serialize(){const o=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const u=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);u&&o.push(u)}if(this.nameSecondary&&(o.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const u=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);u&&o.push(u)}return o}}function Gc(h){return c0(h)?"string":wx(h)?"number":As(h)?"boolean":Array.isArray(h)?"array":h===null?"null":Dg(h)?"object":typeof h}function Dg(h){return h!=null&&!Array.isArray(h)&&typeof h!="function"&&!(h instanceof String||h instanceof Number||h instanceof Boolean)&&typeof h=="object"}function c0(h){return typeof h=="string"||h instanceof String}function wx(h){return typeof h=="number"||h instanceof Number}function As(h){return typeof h=="boolean"||h instanceof Boolean}const Vw={"to-boolean":Bi,"to-color":_c,"to-number":Yr,"to-string":Ei};class Ih{constructor(o,u){this.type=o,this.args=u}static parse(o,u){if(o.length<2)return u.error("Expected at least one argument.");const m=o[0],x=[];let b=il;if(m==="to-array"){if(!Array.isArray(o[1]))return null;const S=o[1].length;if(u.expectedType){if(u.expectedType.kind!=="array")return u.error(`Expected ${u.expectedType.kind} but found array.`);b=Bo(u.expectedType.itemType,S)}else{if(!(S>0&&vf(o[1][0])))return null;b=Bo(zo(o[1][0]),S)}for(let A=0;A4?`Invalid rbga value ${JSON.stringify(u)}: expected an array containing either three or four numeric values.`:Lg(u[0],u[1],u[2],u[3]),!m))return new Vn(u[0]/255,u[1]/255,u[2]/255,u[3])}throw new ra(m||`Could not parse color from value '${typeof u=="string"?u:String(JSON.stringify(u))}'`)}if(this.type.kind==="number"){let u=null;for(const m of this.args){if(u=m.evaluate(o),u===null)return 0;const x=Number(u);if(!isNaN(x))return x}throw new ra(`Could not convert ${JSON.stringify(u)} to number.`)}return this.type.kind==="formatted"?sl.fromString(qu(this.args[0].evaluate(o))):this.type.kind==="resolvedImage"?Ol.build(qu(this.args[0].evaluate(o))):this.type.kind==="array"?this.args.map(u=>u.evaluate(o)):qu(this.args[0].evaluate(o))}eachChild(o){this.args.forEach(o)}outputDefined(){return this.args.every(o=>o.outputDefined())}serialize(){if(this.type.kind==="formatted")return new kn([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new al(this.args[0]).serialize();const o=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(u=>{o.push(u.serialize())}),o}}const qw=["Unknown","Point","LineString","Polygon"];class u0{constructor(o,u,m){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=o,this.options=u,this.iconImageUseTheme=m}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?qw[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}measureLight(o){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const o=this.featureDistanceData.center,u=this.featureDistanceData.scale,{x:m,y:x}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(m*u-o[0])+this.featureDistanceData.bearing[1]*(x*u-o[1])}return 0}parseColor(o){return Vn.parse(o)}getConfig(o){return this.options?this.options.get(o):null}}class Ql{constructor(o,u,m,x,b){this.name=o,this.type=u,this._evaluate=m,this.args=x,this._overloadIndex=b}evaluate(o){if(!this._evaluate){const u=Ql.definitions[this.name];this._evaluate=Array.isArray(u)?u[2]:u.overloads[this._overloadIndex][1]}return this._evaluate(o,this.args)}eachChild(o){this.args.forEach(o)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(o=>o.serialize()))}static parse(o,u){const m=o[0],x=Ql.definitions[m];if(!x)return u.error(`Unknown expression "${m}". If you wanted a literal array, use ["literal", [...]].`,0);const b=Array.isArray(x)?x[0]:x.type,S=Array.isArray(x)?[[x[1],x[2]]]:x.overloads,A=[];let I=null,D=-1;for(const[B,U]of S){if(Array.isArray(B)&&B.length!==o.length-1)continue;A.push(B),D++,I===null?I=u._forkForSignature():I.errors.length=0;const q=[];let K=!1;for(let X=1;Xq)).map(KA).join(" | "),U=[];for(let q=1;qu[2]){const x=.5*m;let b=h[0]-u[0]>x?-m:u[0]-h[0]>x?m:0;b===0&&(b=h[0]-u[2]>x?-m:u[2]-h[0]>x?m:0),h[0]+=b}_s(o,h)}function bN(h,o,u,m){const x=Math.pow(2,m.z)*pu,b=[m.x*pu,m.y*pu],S=[];if(!h)return S;for(const A of h)for(const I of A){const D=[I.x+b[0],I.y+b[1]];vN(D,o,u,x),S.push(D)}return S}function wN(h,o,u,m){const x=Math.pow(2,m.z)*pu,b=[m.x*pu,m.y*pu],S=[];if(!h)return S;for(const I of h){const D=[];for(const B of I){const U=[B.x+b[0],B.y+b[1]];_s(o,U),D.push(U)}S.push(D)}if(o[2]-o[0]<=x/2){(A=o)[0]=A[1]=1/0,A[2]=A[3]=-1/0;for(const I of S)for(const D of I)vN(D,o,u,x)}var A;return S}class Mg{constructor(o,u){this.type=Bi,this.geojson=o,this.geometries=u}static parse(o,u){if(o.length!==2)return u.error(`'within' expression requires exactly one argument, but found ${o.length-1} instead.`);if(vf(o[1])){const m=o[1];if(m.type==="FeatureCollection")for(let x=0;xmx?1:0){if(this.data=o,this.length=this.data.length,this.compare=u,this.length>0)for(let m=(this.length>>1)-1;m>=0;m--)this._down(m)}push(o){this.data.push(o),this._up(this.length++)}pop(){if(this.length===0)return;const o=this.data[0],u=this.data.pop();return--this.length>0&&(this.data[0]=u,this._down(0)),o}peek(){return this.data[0]}_up(o){const{data:u,compare:m}=this,x=u[o];for(;o>0;){const b=o-1>>1,S=u[b];if(m(x,S)>=0)break;u[o]=S,o=b}u[o]=x}_down(o){const{data:u,compare:m}=this,x=this.length>>1,b=u[o];for(;o=0)break;u[o]=u[S],o=S}u[o]=b}}var ar=8192;function SN(h,o,u){let m=h||"";return o&&(m=m?m+""+o:o),u&&(m=m?m+""+u:u),m}function JA(h,o){switch(h){case"string":return qu(o);case"number":return+o;case"boolean":return!!o;case"color":return Vn.parse(o);case"formatted":return sl.fromString(qu(o));case"resolvedImage":return Ol.build(qu(o))}return o}function EN(h,o,u,m){return m!==void 0&&(h=m*Math.round(h/m)),o!==void 0&&hu&&(h=u),h}class Ex{constructor(o,u,m,x=!1){this.type=o,this.key=u,this.scope=m,this.featureConstant=x}static parse(o,u){let m=u.expectedType;if(m??(m=Pi),o.length<2||o.length>3)return u.error("Invalid number of arguments for 'config' expression.");const x=u.parse(o[1],1);if(!(x instanceof qc))return u.error("Key name of 'config' expression must be a string literal.");let b,S=!0;const A=qu(x.value);if(o.length>=3){const I=u.parse(o[2],2);if(!(I instanceof qc))return u.error("Scope of 'config' expression must be a string literal.");b=qu(I.value)}if(u.options){const I=SN(A,b,u._scope),D=u.options.get(I);D&&(S=Og(D.value||D.default))}return new Ex(m,A,b,S)}evaluate(o){const u=SN(this.key,this.scope,o.scope),m=o.getConfig(u);if(!m)return null;const{type:x,value:b,values:S,minValue:A,maxValue:I,stepValue:D}=m,B=m.default.evaluate(o);let U=B;if(b){const q=o.scope,K=q||"",X=K.indexOf("");o.scope=X>=0?K.slice(X+1):"",U=b.evaluate(o),o.scope=q}return x&&(U=JA(x,U)),U===void 0||A===void 0&&I===void 0&&D===void 0||(typeof U=="number"?U=EN(U,A,I,D):Array.isArray(U)&&(U=U.map(q=>typeof q=="number"?EN(q,A,I,D):q))),b!==void 0&&U!==void 0&&S&&!S.includes(U)&&(U=B,x&&(U=JA(x,U))),(x&&x!==this.type||U!==void 0&&!gp(zo(U),this.type))&&(U=JA(this.type.kind,U)),U}eachChild(){}outputDefined(){return!1}serialize(){const o=["config",this.key];return this.scope&&o.push(this.scope),o}}function Og(h){if(h instanceof Ql&&(h.name==="get"&&h.args.length===1||h.name==="feature-state"||h.name==="has"&&h.args.length===1||h.name==="properties"||h.name==="geometry-type"||h.name==="id"||h.name.startsWith("filter-"))||h instanceof Mg||h instanceof y0)return!1;if(h instanceof Ex)return h.featureConstant;let o=!0;return h.eachChild(u=>{o&&!Og(u)&&(o=!1)}),o}function Fg(h){if(h instanceof Ql&&h.name==="feature-state")return!1;let o=!0;return h.eachChild(u=>{o&&!Fg(u)&&(o=!1)}),o}function h0(h,o){if(h instanceof Ql&&o.has(h.name))return!1;let u=!0;return h.eachChild(m=>{u&&!h0(m,o)&&(u=!1)}),u}function am(h,o){return h0(h,new Set(o))}const TN={zoom:1,pitch:1,"distance-from-center":1,"measure-light":2,"line-progress":4};function AN(h){let o=h instanceof Ql&&TN[h.name]||0;return h.eachChild(u=>{o|=AN(u)}),o}const kN=1/298.257223563,IN=kN*(2-kN),e2=Math.PI/180;function Ww(h){const o=6378.137*e2*1e3,u=Math.cos(h*e2),m=1/(1-IN*(1-u*u)),x=Math.sqrt(m);return[o*x*u,o*x*m*(1-IN)]}function Yd(h){for(;h<-180;)h+=360;for(;h>180;)h-=360;return h}function Tx(h,o,u,m){const x=Yd(h[0]-o[0])*u,b=(h[1]-o[1])*m;return Math.sqrt(x*x+b*b)}function f0(h,o,u,m,x){let b=o[0],S=o[1],A=Yd(u[0]-b)*m,I=(u[1]-S)*x;if(A!==0||I!==0){const D=(Yd(h[0]-b)*m*A+(h[1]-S)*x*I)/(A*A+I*I);D>1?(b=u[0],S=u[1]):D>0&&(b+=A/m*D,S+=I/x*D)}return A=Yd(h[0]-b)*m,I=(h[1]-S)*x,Math.sqrt(A*A+I*I)}function Kw(h,o){return o.dist-h.dist}function t2(h){const o=[1/0,1/0,-1/0,-1/0];if(o.length!==h.length)return!1;for(let u=0;u=h[0]&&h[1]h[1])return[null,null];const u=Yw(h);if(o){if(u===2)return[h,null];const m=Math.floor(u/2);return[[h[0],h[0]+m],[h[0]+m,h[1]]]}{if(u===1)return[h,null];const m=Math.floor(u/2)-1;return[[h[0],h[0]+m],[h[0]+m+1,h[1]]]}}function _p(h,o){const u=[1/0,1/0,-1/0,-1/0];if(!om(o,h.length))return u;for(let m=o[0];m<=o[1];++m)_s(u,h[m]);return u}function Xw(h){const o=[1/0,1/0,-1/0,-1/0];for(let u=0;uo[2]&&(x=h[0]-o[2]),h[1]>o[3]&&(b=h[1]-o[3]),h[3]1?(K=b[q+1][0],X=b[q+1][1]):ae>0&&(K+=J/A*ae,X+=se/I*ae)),J=Yd(S[0]-K)*A,se=(S[1]-X)*I;const ue=J*J+se*se;ue=x)return x;if(Fo(b,S)){if(CN(h,o))return 0}else if(CN(o,h))return 0;let A=x;for(const I of h)for(let D=0,B=I.length,U=B-1;D=S)continue;const U=B.range1;if(Yw(U)<=I){if(!om(U,h.length))return NaN;if(o){const q=KB(h,U,u,m,x);if((S=Math.min(S,q))===0)return S}else for(let q=U[0];q<=U[1];++q){const K=WB(h[q],u,m,x);if((S=Math.min(S,K))===0)return S}}else{const q=Zw(U,o);if(q[0]!==null){const K=lm(_p(h,q[0]),D,m,x);K=A)continue;const q=U.range1,K=U.range2;if(Yw(q)<=D&&Yw(K)<=B){if(!om(q,h.length)||!om(K,u.length))return NaN;if(o&&m?A=Math.min(A,GB(h,q,u,K,x,b)):o||m?o&&!m?A=Math.min(A,n2(u,K,h,q,x,b)):!o&&m&&(A=Math.min(A,n2(h,q,u,K,x,b))):A=Math.min(A,HB(h,q,u,K,x,b)),A===0)return A}else{const X=Zw(q,o),J=Zw(K,m);Qw(I,A,x,b,h,u,X[0],J[0]),Qw(I,A,x,b,h,u,X[0],J[1]),Qw(I,A,x,b,h,u,X[1],J[0]),Qw(I,A,x,b,h,u,X[1],J[1])}}return A}function Jw(h,o,u,m,x,b=1/0){let S=b;const A=_p(h,[0,h.length-1]);for(const I of u)if(!(S!==1/0&&lm(A,_p(I,[0,I.length-1]),m,x)>=S)&&(S=Math.min(S,s2(h,o,I,!0,m,x,S)),S===0))return S;return S}function p0(h,o,u,m,x,b=1/0){let S=b;const A=_p(h,[0,h.length-1]);for(const I of u){if(S!==1/0&&lm(A,Xw(I),m,x)>=S)continue;const D=NN(h,o,I,m,x,S);if(isNaN(D))return D;if((S=Math.min(S,D))===0)return S}return S}function a2(h,o,u){const m=[];for(const S of h)for(const A of S)m.push(m0(A,o));const[x,b]=Ww(m[0][1]);return u.type==="Point"||u.type==="MultiPoint"||u.type==="LineString"?s2(m,!1,u.type==="Point"?[u.coordinates]:u.coordinates,u.type==="LineString",x,b):u.type==="MultiLineString"?Jw(m,!1,u.coordinates,x,b):u.type==="Polygon"||u.type==="MultiPolygon"?p0(m,!1,u.type==="Polygon"?[u.coordinates]:u.coordinates,x,b):null}function YB(h,o,u){const m=[];for(const S of h){const A=[];for(const I of S)A.push(m0(I,o));m.push(A)}const[x,b]=Ww(m[0][0][1]);if(u.type==="Point"||u.type==="MultiPoint"||u.type==="LineString")return Jw(u.type==="Point"?[u.coordinates]:u.coordinates,u.type==="LineString",m,x,b);if(u.type==="MultiLineString"){let S=1/0;for(let A=0;A`[${x}]`).join("")}`;this.errors.push(new Xl(m,o))}checkSubtype(o,u,m){const x=Ng(o,u);return x&&this.error(x,...typeof m=="number"?[m]:[]),x}}const XB=new Set(["zoom","heatmap-density","worldview","line-progress","raster-value","sky-radial-progress","accumulated","is-supported-script","pitch","distance-from-center","measure-light","raster-particle-speed","is-active-floor"]);function o2(h,o,u){return u==="assert"?new fd(o,[h]):u==="coerce"?new Ih(o,[h]):h}function t1(h){if(h instanceof x0)return t1(h.boundExpression);if(h instanceof Ql&&h.name==="error"||h instanceof Sx||h instanceof Mg||h instanceof y0||h instanceof Ex)return!1;const o=h instanceof Ih||h instanceof fd;let u=!0;return h.eachChild(m=>{u=o?u&&t1(m):u&&m instanceof qc}),!!u&&Og(h)&&h0(h,XB)}function r1(h,o){const u=h.length-1;let m,x,b=0,S=u,A=0;for(;b<=S;)if(A=Math.floor((b+S)/2),m=h[A],x=h[A+1],m<=o){if(A===u||oo))throw new ra("Input is not a number.");S=A-1}return 0}class Ax{constructor(o,u,m){this.type=o,this.input=u,this.labels=[],this.outputs=[];for(const[x,b]of m)this.labels.push(x),this.outputs.push(b)}static parse(o,u){if(o.length-1<4)return u.error(`Expected at least 4 arguments, but found only ${o.length-1}.`);if((o.length-1)%2!=0)return u.error("Expected an even number of arguments.");const m=u.parse(o[1],1,Yr);if(!m)return null;const x=[];let b=null;u.expectedType&&u.expectedType.kind!=="value"&&(b=u.expectedType);for(let S=1;S=A)return u.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',D);const U=u.parse(I,B,b);if(!U)return null;b=b||U.type,x.push([A,U])}return new Ax(b,m,x)}evaluate(o){const u=this.labels,m=this.outputs;if(u.length===1)return m[0].evaluate(o);const x=this.input.evaluate(o);if(x<=u[0])return m[0].evaluate(o);const b=u.length;return x>=u[b-1]?m[b-1].evaluate(o):m[r1(u,x)].evaluate(o)}eachChild(o){o(this.input);for(const u of this.outputs)o(u)}outputDefined(){return this.outputs.every(o=>o.outputDefined())}serialize(){const o=["step",this.input.serialize()];for(let u=0;u0&&o.push(this.labels[u]),o.push(this.outputs[u].serialize());return o}}const LN=.95047,DN=1.08883,cm=4/29,Bg=6/29,n1=3*Bg*Bg,l2=Bg*Bg*Bg,_0=Math.PI/180,MN=180/Math.PI;function kx(h){return h>l2?Math.pow(h,1/3):h/n1+cm}function i1(h){return h>Bg?h*h*h:n1*(h-cm)}function Ix(h){return 255*(h<=.0031308?12.92*h:1.055*Math.pow(h,1/2.4)-.055)}function md(h){return(h/=255)<=.04045?h/12.92:Math.pow((h+.055)/1.055,2.4)}function s1(h){const o=md(h.r),u=md(h.g),m=md(h.b),x=kx((.4124564*o+.3575761*u+.1804375*m)/LN),b=kx((.2126729*o+.7151522*u+.072175*m)/1);return{l:116*b-16,a:500*(x-b),b:200*(b-kx((.0193339*o+.119192*u+.9503041*m)/DN)),alpha:h.a}}function c2(h){let o=(h.l+16)/116,u=isNaN(h.a)?o:o+h.a/500,m=isNaN(h.b)?o:o-h.b/200;return o=1*i1(o),u=LN*i1(u),m=DN*i1(m),new Vn(Ix(3.2404542*u-1.5371385*o-.4985314*m),Ix(-.969266*u+1.8760108*o+.041556*m),Ix(.0556434*u-.2040259*o+1.0572252*m),h.alpha)}function v0(h,o,u){const m=o-h;return h+u*(m>180||m<-180?m-360*Math.round(m/360):m)}const jx={forward:s1,reverse:c2,interpolate:function(h,o,u){return{l:Kr(h.l,o.l,u),a:Kr(h.a,o.a,u),b:Kr(h.b,o.b,u),alpha:Kr(h.alpha,o.alpha,u)}}},Cx={forward:function(h){const{l:o,a:u,b:m}=s1(h),x=Math.atan2(m,u)*MN;return{h:x<0?x+360:x,c:Math.sqrt(u*u+m*m),l:o,alpha:h.a}},reverse:function(h){const o=h.h*_0,u=h.c;return c2({l:h.l,a:Math.cos(o)*u,b:Math.sin(o)*u,alpha:h.alpha})},interpolate:function(h,o,u){return{h:v0(h.h,o.h,u),c:Kr(h.c,o.c,u),l:Kr(h.l,o.l,u),alpha:Kr(h.alpha,o.alpha,u)}}};var u2=Object.freeze({__proto__:null,hcl:Cx,lab:jx});class pd{constructor(o,u,m,x,b){this.type=o,this.operator=u,this.interpolation=m,this.input=x,this.labels=[],this.outputs=[];for(const[S,A]of b)this.labels.push(S),this.outputs.push(A)}static interpolationFactor(o,u,m,x){let b=0;if(o.name==="exponential")b=d2(u,o.base,m,x);else if(o.name==="linear")b=d2(u,1,m,x);else if(o.name==="cubic-bezier"){const S=o.controlPoints;b=Ea(S[0],S[1],S[2],S[3])(d2(u,1,m,x))}return b}static parse(o,u){let[m,x,b,...S]=o;if(!Array.isArray(x)||x.length===0)return u.error("Expected an interpolation type expression.",1);if(x[0]==="linear")x={name:"linear"};else if(x[0]==="exponential"){const D=x[1];if(typeof D!="number")return u.error("Exponential interpolation requires a numeric base.",1,1);x={name:"exponential",base:D}}else{if(x[0]!=="cubic-bezier")return u.error(`Unknown interpolation type ${String(x[0])}`,1,0);{const D=x.slice(1);if(D.length!==4||D.some(B=>typeof B!="number"||B<0||B>1))return u.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);x={name:"cubic-bezier",controlPoints:D}}}if(o.length-1<4)return u.error(`Expected at least 4 arguments, but found only ${o.length-1}.`);if(o.length-1>3&&(o.length-1)%2!=0)return u.error("Expected an even number of arguments.");if(b=u.parse(b,2,Yr),!b)return null;const A=[];let I=null;m==="interpolate-hcl"||m==="interpolate-lab"?I=_c:u.expectedType&&u.expectedType.kind!=="value"&&(I=u.expectedType);for(let D=0;D=B)return u.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',q);const X=u.parse(U,K,I);if(!X)return null;I=I||X.type,A.push([B,X])}return I.kind==="number"||I.kind==="color"||I.kind==="array"&&I.itemType.kind==="number"&&typeof I.N=="number"?new pd(I,m,x,b,A):u.error(`Type ${Xs(I)} is not interpolatable.`)}evaluate(o){const u=this.labels,m=this.outputs;if(u.length===1)return m[0].evaluate(o);const x=this.input.evaluate(o);if(x<=u[0])return m[0].evaluate(o);const b=u.length;if(x>=u[b-1])return m[b-1].evaluate(o);const S=r1(u,x),A=pd.interpolationFactor(this.interpolation,x,u[S],u[S+1]),I=m[S].evaluate(o),D=m[S+1].evaluate(o);return this.operator==="interpolate"?Ah[this.type.kind.toLowerCase()](I,D,A):this.operator==="interpolate-hcl"?Cx.reverse(Cx.interpolate(Cx.forward(I),Cx.forward(D),A)):jx.reverse(jx.interpolate(jx.forward(I),jx.forward(D),A))}eachChild(o){o(this.input);for(const u of this.outputs)o(u)}outputDefined(){return this.outputs.every(o=>o.outputDefined())}serialize(){let o;o=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const u=[this.operator,o,this.input.serialize()];for(let m=0;mNg(x,A.type));return new a1(S?Pi:m,b)}evaluate(o){let u,m=null,x=0;for(const b of this.args){if(x++,m=b.evaluate(o),m&&m instanceof Ol&&!m.available&&(u||(u=m),m=null,x===this.args.length))return u;if(m!==null)break}return m}eachChild(o){this.args.forEach(o)}outputDefined(){return this.args.every(o=>o.outputDefined())}serialize(){const o=["coalesce"];return this.eachChild(u=>{o.push(u.serialize())}),o}}const ON=/[^a-zA-Z0-9_]/;class o1{constructor(o,u){this.type=u.type,this.bindings=[].concat(o),this.result=u}evaluate(o){return this.result.evaluate(o)}eachChild(o){for(const u of this.bindings)o(u[1]);o(this.result)}static parse(o,u){if(o.length<4)return u.error(`Expected at least 3 arguments, but found ${o.length-1} instead.`);const m=[];for(let b=1;b=m.length)throw new ra("Array index out of bounds: index exceeds array size");if(u!==Math.floor(u))throw new ra("Array index must be an integer. Use at-interpolated for fractional indices");return m[u]}eachChild(o){o(this.index),o(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class l1{constructor(o,u,m){this.type=o,this.index=u,this.input=m}static parse(o,u){if(o.length!==3)return u.error(`Expected 2 arguments, but found ${o.length-1} instead.`);const m=u.parse(o[1],1,Yr),x=u.parse(o[2],2,Bo(u.expectedType||Pi));return m&&x?new l1(x.type.itemType,m,x):null}evaluate(o){const u=this.index.evaluate(o),m=this.input.evaluate(o);if(u<0)throw new ra(`Array index out of bounds: ${u} < 0.`);if(u>m.length-1)throw new ra(`Array index out of bounds: ${u} > ${m.length-1}.`);if(u===Math.floor(u))return m[u];const x=Math.floor(u),b=Math.ceil(u),S=m[x],A=m[b];if(typeof S!="number"||typeof A!="number")throw new ra(`Cannot interpolate between non-number values at index ${u}.`);return Kr(S,A,u-x)}eachChild(o){o(this.index),o(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class h2{constructor(o,u,m,x,b,S){this.inputType=o,this.type=u,this.input=m,this.cases=x,this.outputs=b,this.otherwise=S}static parse(o,u){if(o.length<5)return u.error(`Expected at least 4 arguments, but found only ${o.length-1}.`);if(o.length%2!=1)return u.error("Expected an even number of arguments.");let m,x;u.expectedType&&u.expectedType.kind!=="value"&&(x=u.expectedType);const b={},S=[];for(let D=2;DNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`,D);if(typeof K=="number"&&Math.floor(K)!==K)return u.error("Numeric branch labels must be integer values.",D);if(m){if(u.checkSubtype(m,zo(K),D))return null}else m=zo(K);if(b[String(K)]!==void 0)return u.error("Branch labels must be unique.",D);b[String(K)]=S.length}const q=u.parse(U,D,x);if(!q)return null;x=x||q.type,S.push(q)}const A=u.parse(o[1],1,Pi);if(!A)return null;const I=u.parse(o.at(-1),o.length-1,x);return I?A.type.kind!=="value"&&u.checkSubtype(m,A.type,1)?null:new h2(m,x,A,b,S,I):null}evaluate(o){const u=this.input.evaluate(o);return(gp(zo(u),this.inputType)&&this.outputs[this.cases[u]]||this.otherwise).evaluate(o)}eachChild(o){o(this.input),this.outputs.forEach(o),o(this.otherwise)}outputDefined(){return this.outputs.every(o=>o.outputDefined())&&this.otherwise.outputDefined()}serialize(){const o=["match",this.input.serialize()],u=Object.keys(this.cases).sort(),m=[],x={};for(const S of u){const A=x[this.cases[S]];A===void 0?(x[this.cases[S]]=m.length,m.push([this.cases[S],[S]])):m[A][1].push(S)}const b=S=>this.inputType.kind==="number"?Number(S):S;for(const[S,A]of m)o.push(A.length===1?b(A[0]):A.map(b)),o.push(this.outputs[S].serialize());return o.push(this.otherwise.serialize()),o}}class c1{constructor(o,u,m){this.type=o,this.branches=u,this.otherwise=m}static parse(o,u){if(o.length<4)return u.error(`Expected at least 3 arguments, but found only ${o.length-1}.`),null;if(o.length%2!=0)return u.error("Expected an odd number of arguments."),null;let m;u.expectedType&&u.expectedType.kind!=="value"&&(m=u.expectedType);const x=[];for(let S=1;Su.outputDefined())&&this.otherwise.outputDefined()}serialize(){const o=["case"];return this.eachChild(u=>{o.push(u.serialize())}),o}}class u1{constructor(o,u,m,x){this.type=o,this.input=u,this.beginIndex=m,this.endIndex=x}static parse(o,u){if(o.length<=2||o.length>=5)return u.error(`Expected 3 or 4 arguments, but found ${o.length-1} instead.`),null;const m=u.parse(o[1],1,Pi),x=u.parse(o[2],2,Yr);if(!m||!x)return null;if(b=m.type,![Bo(Pi),Ei,Pi].some(S=>S.kind===b.kind))return u.error(`Expected first argument to be of type array or string, but found ${Xs(m.type)} instead`),null;var b;if(o.length===4){const S=u.parse(o[3],3,Yr);return S?new u1(m.type,m,x,S):null}return new u1(m.type,m,x)}evaluate(o){const u=this.input.evaluate(o),m=this.beginIndex.evaluate(o);if(!_f(u,["string","array"]))throw new ra(`Expected first argument to be of type array or string, but found ${Xs(zo(u))} instead.`);if(this.endIndex){const x=this.endIndex.evaluate(o);return u.slice(m,x)}return u.slice(m)}eachChild(o){o(this.input),o(this.beginIndex),this.endIndex&&o(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const o=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),o]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}function jh(h,o){return h==="=="||h==="!="?o.kind==="boolean"||o.kind==="string"||o.kind==="number"||o.kind==="null"||o.kind==="value":o.kind==="string"||o.kind==="number"||o.kind==="value"}function f2(h,o,u,m){return m.compare(o,u)===0}function $g(h,o,u){const m=h!=="=="&&h!=="!=";return class PEe{constructor(b,S,A){this.type=Bi,this.lhs=b,this.rhs=S,this.collator=A,this.hasUntypedArgument=b.type.kind==="value"||S.type.kind==="value"}static parse(b,S){if(b.length!==3&&b.length!==4)return S.error("Expected two or three arguments.");const A=b[0];let I=S.parse(b[1],1,Pi);if(!I)return null;if(!jh(A,I.type))return S.error(`"${A}" comparisons are not supported for type '${Xs(I.type)}'.`,1);let D=S.parse(b[2],2,Pi);if(!D)return null;if(!jh(A,D.type))return S.error(`"${A}" comparisons are not supported for type '${Xs(D.type)}'.`,2);if(I.type.kind!==D.type.kind&&I.type.kind!=="value"&&D.type.kind!=="value")return S.error(`Cannot compare types '${Xs(I.type)}' and '${Xs(D.type)}'.`);m&&(I.type.kind==="value"&&D.type.kind!=="value"?I=new fd(D.type,[I]):I.type.kind!=="value"&&D.type.kind==="value"&&(D=new fd(I.type,[D])));let B=null;if(b.length===4){if(I.type.kind!=="string"&&D.type.kind!=="string"&&I.type.kind!=="value"&&D.type.kind!=="value")return S.error("Cannot use collator to compare non-string types.");if(B=S.parse(b[3],3,mp),!B)return null}return new PEe(I,D,B)}evaluate(b){const S=this.lhs.evaluate(b),A=this.rhs.evaluate(b);if(m&&this.hasUntypedArgument){const I=zo(S),D=zo(A);if(I.kind!==D.kind||I.kind!=="string"&&I.kind!=="number")throw new ra(`Expected arguments for "${h}" to be (string, string) or (number, number), but found (${I.kind}, ${D.kind}) instead.`)}if(this.collator&&!m&&this.hasUntypedArgument){const I=zo(S),D=zo(A);if(I.kind!=="string"||D.kind!=="string")return o(b,S,A)}return this.collator?u(b,S,A,this.collator.evaluate(b)):o(b,S,A)}eachChild(b){b(this.lhs),b(this.rhs),this.collator&&b(this.collator)}outputDefined(){return!0}serialize(){const b=[h];return this.eachChild(S=>{b.push(S.serialize())}),b}}}const b0=$g("==",function(h,o,u){return o===u},f2),d1=$g("!=",function(h,o,u){return o!==u},function(h,o,u,m){return!f2(0,o,u,m)}),QB=$g("<",function(h,o,u){return o",function(h,o,u){return o>u},function(h,o,u,m){return m.compare(o,u)>0}),ez=$g("<=",function(h,o,u){return o<=u},function(h,o,u,m){return m.compare(o,u)<=0}),FN=$g(">=",function(h,o,u){return o>=u},function(h,o,u,m){return m.compare(o,u)>=0});class w0{constructor(o,u,m,x,b,S){this.type=Ei,this.number=o,this.locale=u,this.currency=m,this.unit=x,this.minFractionDigits=b,this.maxFractionDigits=S}static parse(o,u){if(o.length!==3)return u.error("Expected two arguments.");const m=u.parse(o[1],1,Yr);if(!m)return null;const x=o[2];if(typeof x!="object"||Array.isArray(x))return u.error("NumberFormat options argument must be an object.");let b=null;if(x.locale&&(b=u.parseObjectValue(x.locale,2,"locale",Ei),!b))return null;let S=null;if(x.currency&&(S=u.parseObjectValue(x.currency,2,"currency",Ei),!S))return null;let A=null;if(x.unit&&(A=u.parseObjectValue(x.unit,2,"unit",Ei),!A))return null;let I=null;if(x["min-fraction-digits"]!==void 0&&(I=u.parseObjectValue(x["min-fraction-digits"],2,"min-fraction-digits",Yr),!I))return null;let D=null;return x["max-fraction-digits"]===void 0||(D=u.parseObjectValue(x["max-fraction-digits"],2,"max-fraction-digits",Yr),D)?new w0(m,b,S,A,I,D):null}evaluate(o){return new Intl.NumberFormat(this.locale?this.locale.evaluate(o):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(o):void 0,unit:this.unit?this.unit.evaluate(o):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(o):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(o):void 0}).format(this.number.evaluate(o))}eachChild(o){o(this.number),this.locale&&o(this.locale),this.currency&&o(this.currency),this.unit&&o(this.unit),this.minFractionDigits&&o(this.minFractionDigits),this.maxFractionDigits&&o(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const o={};return this.locale&&(o.locale=this.locale.serialize()),this.currency&&(o.currency=this.currency.serialize()),this.unit&&(o.unit=this.unit.serialize()),this.minFractionDigits&&(o["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(o["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),o]}}class Px{constructor(o){this.type=Yr,this.input=o}static parse(o,u){if(o.length!==2)return u.error(`Expected 1 argument, but found ${o.length-1} instead.`),null;const m=u.parse(o[1],1);return m?m.type.kind!=="array"&&m.type.kind!=="string"&&m.type.kind!=="value"?(u.error(`Expected argument of type string or array, but found ${Xs(m.type)} instead.`),null):new Px(m):null}evaluate(o){const u=this.input.evaluate(o);if(typeof u=="string"||Array.isArray(u))return u.length;throw new ra(`Expected value to be of type string or array, but found ${Xs(zo(u))} instead.`)}eachChild(o){o(this.input)}outputDefined(){return!1}serialize(){const o=["length"];return this.eachChild(u=>{o.push(u.serialize())}),o}}function Nx(h){return function(){h=1831565813+(h|=0)|0;let o=Math.imul(h^h>>>15,1|h);return o=o+Math.imul(o^o>>>7,61|o)^o,((o^o>>>14)>>>0)/4294967296}}const Rx=Object.assign(Object.create(null),{"==":b0,"!=":d1,">":JB,"<":QB,">=":FN,"<=":ez,array:fd,at:zg,"at-interpolated":l1,boolean:fd,case:c1,coalesce:a1,collator:Sx,format:kn,image:al,interpolate:pd,"interpolate-hcl":pd,"interpolate-lab":pd,length:Px,let:o1,literal:qc,match:h2,number:fd,"number-format":w0,object:fd,slice:u1,step:Ax,string:fd,"to-boolean":Ih,"to-color":Ih,"to-number":Ih,"to-string":Ih,var:x0,within:Mg,distance:y0,config:Ex});function S0(h,[o,u,m,x]){o=o.evaluate(h),u=u.evaluate(h),m=m.evaluate(h);const b=x?x.evaluate(h):1,S=Lg(o,u,m,b);if(S)throw new ra(S);return new Vn(o/255,u/255,m/255,b)}function BN(h,[o,u,m,x]){o=o.evaluate(h),u=u.evaluate(h),m=m.evaluate(h);const b=x?x.evaluate(h):1,S=function(D,B,U,q){return typeof D=="number"&&D>=0&&D<=360?typeof B=="number"&&B>=0&&B<=100&&typeof U=="number"&&U>=0&&U<=100?q===void 0||typeof q=="number"&&q>=0&&q<=1?null:`Invalid hsla value [${[D,B,U,q].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof q=="number"?[D,B,U,q]:[D,B,U]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof q=="number"?[D,B,U,q]:[D,B,U]).join(", ")}]: 'h' must be between 0 and 360.`}(o,u,m,b);if(S)throw new ra(S);const A=`hsla(${o}, ${u}%, ${m}%, ${b})`,I=Vn.parse(A);if(!I)throw new ra(`Failed to parse HSLA color: ${A}`);return I}function zN(h,o){return h in o}function m2(h,o){const u=o[h];return u===void 0?null:u}function vp(h){return{type:h}}function p2(h,o){if(!_f(h,["boolean","string","number","null"]))throw new ra(`Expected first argument to be of type boolean, string, number or null, but found ${Xs(zo(h))} instead.`);if(!_f(o,["string","array"]))throw new ra(`Expected second argument to be of type array or string, but found ${Xs(zo(o))} instead.`)}Ql.register(Rx,{error:[{kind:"error"},[Ei],(h,[o])=>{throw new ra(o.evaluate(h))}],typeof:[Ei,[Pi],(h,[o])=>Xs(zo(o.evaluate(h)))],"to-rgba":[Bo(Yr,4),[_c],(h,[o])=>o.evaluate(h).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Bo(Yr,4),[_c],(h,[o])=>o.evaluate(h).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[_c,[Yr,Yr,Yr],S0],rgba:[_c,[Yr,Yr,Yr,Yr],S0],hsl:[_c,[Yr,Yr,Yr],BN],hsla:[_c,[Yr,Yr,Yr,Yr],BN],has:{type:Bi,overloads:[[[Ei],(h,[o])=>zN(o.evaluate(h),h.properties())],[[Ei,xf],(h,[o,u])=>zN(o.evaluate(h),u.evaluate(h))]]},get:{type:Pi,overloads:[[[Ei],(h,[o])=>m2(o.evaluate(h),h.properties())],[[Ei,xf],(h,[o,u])=>m2(o.evaluate(h),u.evaluate(h))]]},"feature-state":[Pi,[Ei],(h,[o])=>m2(o.evaluate(h),h.featureState||{})],properties:[xf,[],h=>h.properties()],"geometry-type":[Ei,[],h=>h.geometryType()],worldview:[Ei,[],h=>h.globals.worldview||""],"is-active-floor":[Bi,vp(Ei),(h,o)=>{if(!(h.globals&&h.globals.activeFloors&&h.globals.activeFloors.size>0))return!1;if(o.length===0)return!0;const u=h.globals.activeFloors;return o.some(m=>{const x=m.evaluate(h);return u.has(x)})}],id:[Pi,[],h=>h.id()],zoom:[Yr,[],h=>h.globals.zoom],pitch:[Yr,[],h=>h.globals.pitch||0],"distance-from-center":[Yr,[],h=>h.distanceFromCenter()],"measure-light":[Yr,[Ei],(h,[o])=>h.measureLight(o.evaluate(h))],"heatmap-density":[Yr,[],h=>h.globals.heatmapDensity||0],"line-progress":[Yr,[],h=>h.globals.lineProgress||0],"raster-value":[Yr,[],h=>h.globals.rasterValue||0],"raster-particle-speed":[Yr,[],h=>h.globals.rasterParticleSpeed||0],"sky-radial-progress":[Yr,[],h=>h.globals.skyRadialProgress||0],accumulated:[Pi,[],h=>h.globals.accumulated===void 0?null:h.globals.accumulated],"+":[Yr,vp(Yr),(h,o)=>{let u=0;for(const m of o)u+=m.evaluate(h);return u}],"*":[Yr,vp(Yr),(h,o)=>{let u=1;for(const m of o)u*=m.evaluate(h);return u}],"-":{type:Yr,overloads:[[[Yr,Yr],(h,[o,u])=>o.evaluate(h)-u.evaluate(h)],[[Yr],(h,[o])=>-o.evaluate(h)]]},"/":[Yr,[Yr,Yr],(h,[o,u])=>o.evaluate(h)/u.evaluate(h)],"%":[Yr,[Yr,Yr],(h,[o,u])=>o.evaluate(h)%u.evaluate(h)],ln2:[Yr,[],()=>Math.LN2],pi:[Yr,[],()=>Math.PI],e:[Yr,[],()=>Math.E],"^":[Yr,[Yr,Yr],(h,[o,u])=>Math.pow(o.evaluate(h),u.evaluate(h))],sqrt:[Yr,[Yr],(h,[o])=>Math.sqrt(o.evaluate(h))],log10:[Yr,[Yr],(h,[o])=>Math.log(o.evaluate(h))/Math.LN10],ln:[Yr,[Yr],(h,[o])=>Math.log(o.evaluate(h))],log2:[Yr,[Yr],(h,[o])=>Math.log2(o.evaluate(h))],sin:[Yr,[Yr],(h,[o])=>Math.sin(o.evaluate(h))],cos:[Yr,[Yr],(h,[o])=>Math.cos(o.evaluate(h))],tan:[Yr,[Yr],(h,[o])=>Math.tan(o.evaluate(h))],asin:[Yr,[Yr],(h,[o])=>Math.asin(o.evaluate(h))],acos:[Yr,[Yr],(h,[o])=>Math.acos(o.evaluate(h))],atan:[Yr,[Yr],(h,[o])=>Math.atan(o.evaluate(h))],min:[Yr,vp(Yr),(h,o)=>Math.min(...o.map(u=>u.evaluate(h)))],max:[Yr,vp(Yr),(h,o)=>Math.max(...o.map(u=>u.evaluate(h)))],abs:[Yr,[Yr],(h,[o])=>Math.abs(o.evaluate(h))],round:[Yr,[Yr],(h,[o])=>{const u=o.evaluate(h);return u<0?-Math.round(-u):Math.round(u)}],floor:[Yr,[Yr],(h,[o])=>Math.floor(o.evaluate(h))],ceil:[Yr,[Yr],(h,[o])=>Math.ceil(o.evaluate(h))],"filter-==":[Bi,[Ei,Pi],(h,[o,u])=>h.properties()[o.value]===u.value],"filter-id-==":[Bi,[Pi],(h,[o])=>h.id()===o.value],"filter-type-==":[Bi,[Ei],(h,[o])=>h.geometryType()===o.value],"filter-<":[Bi,[Ei,Pi],(h,[o,u])=>{const m=h.properties()[o.value],x=u.value;return typeof m==typeof x&&m{const u=h.id(),m=o.value;return typeof u==typeof m&&u":[Bi,[Ei,Pi],(h,[o,u])=>{const m=h.properties()[o.value],x=u.value;return typeof m==typeof x&&m>x}],"filter-id->":[Bi,[Pi],(h,[o])=>{const u=h.id(),m=o.value;return typeof u==typeof m&&u>m}],"filter-<=":[Bi,[Ei,Pi],(h,[o,u])=>{const m=h.properties()[o.value],x=u.value;return typeof m==typeof x&&m<=x}],"filter-id-<=":[Bi,[Pi],(h,[o])=>{const u=h.id(),m=o.value;return typeof u==typeof m&&u<=m}],"filter->=":[Bi,[Ei,Pi],(h,[o,u])=>{const m=h.properties()[o.value],x=u.value;return typeof m==typeof x&&m>=x}],"filter-id->=":[Bi,[Pi],(h,[o])=>{const u=h.id(),m=o.value;return typeof u==typeof m&&u>=m}],"filter-has":[Bi,[Pi],(h,[o])=>o.value in h.properties()],"filter-has-id":[Bi,[],h=>h.id()!==null&&h.id()!==void 0],"filter-type-in":[Bi,[Bo(Ei)],(h,[o])=>o.value.includes(h.geometryType())],"filter-id-in":[Bi,[Bo(Pi)],(h,[o])=>o.value.includes(h.id())],"filter-in-small":[Bi,[Ei,Bo(Pi)],(h,[o,u])=>u.value.includes(h.properties()[o.value])],"filter-in-large":[Bi,[Ei,Bo(Pi)],(h,[o,u])=>function(m,x,b,S){for(;b<=S;){const A=b+S>>1;if(x[A]===m)return!0;x[A]>m?S=A-1:b=A+1}return!1}(h.properties()[o.value],u.value,0,u.value.length-1)],all:{type:Bi,overloads:[[[Bi,Bi],(h,[o,u])=>o.evaluate(h)&&u.evaluate(h)],[vp(Bi),(h,o)=>{for(const u of o)if(!u.evaluate(h))return!1;return!0}]]},any:{type:Bi,overloads:[[[Bi,Bi],(h,[o,u])=>o.evaluate(h)||u.evaluate(h)],[vp(Bi),(h,o)=>{for(const u of o)if(u.evaluate(h))return!0;return!1}]]},"!":[Bi,[Bi],(h,[o])=>!o.evaluate(h)],"is-supported-script":[Bi,[Ei],(h,[o])=>{const u=h.globals&&h.globals.isSupportedScript;return!u||u(o.evaluate(h))}],upcase:[Ei,[Ei],(h,[o])=>o.evaluate(h).toUpperCase()],downcase:[Ei,[Ei],(h,[o])=>o.evaluate(h).toLowerCase()],concat:[Ei,vp(Pi),(h,o)=>o.map(u=>qu(u.evaluate(h))).join("")],split:[Bo(Ei),[Ei,Ei],(h,[o,u])=>o.evaluate(h).split(u.evaluate(h))],in:[Bi,[Pi,Pi],(h,[o,u])=>{const m=o.evaluate(h),x=u.evaluate(h);return x!=null&&(p2(m,x),x.includes(m))}],"index-of":{type:Yr,overloads:[[[Pi,Pi],(h,[o,u])=>{const m=o.evaluate(h),x=u.evaluate(h);return p2(m,x),x.indexOf(m)}],[[Pi,Pi,Yr],(h,[o,u,m])=>{const x=o.evaluate(h),b=u.evaluate(h),S=m.evaluate(h);return p2(x,b),b.indexOf(x,S)}]]},"resolved-locale":[Ei,[mp],(h,[o])=>o.evaluate(h).resolvedLocale()],random:[Yr,[Yr,Yr,Pi],(h,o)=>{const[u,m,x]=o.map(S=>S.evaluate(h));if(u>m||u===m)return u;let b;if(typeof x=="string")b=function(S){let A=0;if(S.length===0)return A;for(let I=0;I{UN(u,o)})}function VN(h){const o={configDependencies:$N,isIndoorDependent:!1,isImageDependent:!1};return UN(h,o),o}function Ug(h){return{result:"success",value:h}}function bp(h){return{result:"error",value:h}}function h1(h,o){return!!h&&!!h.parameters&&h.parameters.includes(o)}function Lx(h){return h["property-type"]==="data-driven"}function qN(h){return h1(h.expression,"measure-light")}function GN(h){return h1(h.expression,"zoom")}function g2(h){return!!h.expression&&h.expression.interpolated}function y2(h){return typeof h=="object"&&h!==null&&!Array.isArray(h)}function HN(h){return h}function f1(h,o){let u=h;const m=o.type==="color",x=u.stops&&typeof u.stops[0][0]=="object",b=x||!(x||u.property!==void 0),S=u.type||(g2(o)?"exponential":"interval");if(m&&(u={...u},u.stops&&(u.stops=u.stops.map(B=>[B[0],Vn.parse(B[1])])),u.default=Vn.parse(u.default?u.default:o.default)),u.colorSpace&&u.colorSpace!=="rgb"&&!u2[u.colorSpace])throw new Error(`Unknown color space: ${u.colorSpace}`);let A,I,D;if(S==="exponential")A=x2;else if(S==="interval")A=T0;else if(S==="categorical"){A=tz,I=Object.create(null);for(const B of u.stops)I[B[0]]=B[1];D=typeof u.stops[0][0]}else{if(S!=="identity")throw new Error(`Unknown function type "${S}"`);A=WN}if(x){const B={},U=[];for(let X=0;XX[0]),evaluate:({zoom:X},J)=>x2({stops:q,base:u.base},o,X).evaluate(X,J)}}if(b){const B=S==="exponential"?{name:"exponential",base:u.base!==void 0?u.base:1}:null;return{kind:"camera",interpolationType:B,interpolationFactor:pd.interpolationFactor.bind(void 0,B),zoomStops:u.stops.map(U=>U[0]),evaluate:({zoom:U})=>A(u,o,U,I,D)}}return{kind:"source",evaluate(B,U){const q=U&&U.properties?U.properties[u.property]:void 0;return q===void 0?E0(u.default,o.default):A(u,o,q,I,D)}}}function E0(h,o,u){return h!==void 0?h:o!==void 0?o:u!==void 0?u:void 0}function tz(h,o,u,m,x){return E0(typeof u===x?m[u]:void 0,h.default,o.default)}function T0(h,o,u){if(!wx(u))return E0(h.default,o.default);const m=h.stops,x=m.length;if(x===1||u<=m[0][0])return m[0][1];if(u>=m[x-1][0])return m[x-1][1];const b=r1(m.map(S=>S[0]),u);return m[b][1]}function x2(h,o,u){const m=h.base!==void 0?h.base:1;if(!wx(u))return E0(h.default,o.default);const x=h.stops,b=x.length;if(b===1||u<=x[0][0])return x[0][1];if(u>=x[b-1][0])return x[b-1][1];const S=r1(x.map(U=>U[0]),u),A=function(U,q,K,X){const J=X-K,se=U-K;return J===0?0:q===1?se/J:(Math.pow(q,se)-1)/(Math.pow(q,J)-1)}(u,m,x[S][0],x[S+1][0]),I=x[S][1],D=x[S+1][1];let B=Ah[o.type]||HN;if(h.colorSpace&&h.colorSpace!=="rgb"){const U=u2[h.colorSpace];B=(q,K)=>U.reverse(U.interpolate(U.forward(q),U.forward(K),A))}return typeof I.evaluate=="function"?{evaluate(...U){const q=I.evaluate.apply(void 0,U),K=D.evaluate.apply(void 0,U);if(q!==void 0&&K!==void 0)return B(q,K,A)}}:B(I,D,A)}function WN(h,o,u){return o.type==="color"?u=Vn.parse(u):o.type==="formatted"?u=sl.fromString(u.toString()):o.type==="resolvedImage"?u=Ol.build(u.toString()):Gc(u)===o.type||o.type==="enum"&&o.values[u]||(u=void 0),E0(u,h.default,o.default)}class _2{constructor(o,u,m,x,b){this.expression=o,this._warningHistory={},this._scope=m,this._options=x,this._iconImageUseTheme=b,this._evaluator=new u0(m,x,b),this._defaultValue=u?function(A){return A.type==="color"&&(y2(A.default)||Array.isArray(A.default))?new Vn(0,0,0,0):A.type==="color"?Vn.parse(A.default)||null:A.default===void 0?null:A.default}(u):null,this._enumValues=u&&u.type==="enum"?u.values:null;const S=VN(o);this.configDependencies=S.configDependencies,this.isIndoorDependent=S.isIndoorDependent,this.isImageDependent=S.isImageDependent}evaluateWithoutErrorHandling(o,u,m,x,b,S,A,I){const D=this._evaluator;return D.globals=o,D.feature=u,D.featureState=m,D.canonical=x||null,D.availableImages=b||null,D.formattedSection=S,D.featureTileCoord=A||null,D.featureDistanceData=I||null,this.expression.evaluate(D)}evaluate(o,u,m,x,b,S,A,I,D){this._evaluator||(this._evaluator=new u0(this._scope,this._options,this._iconImageUseTheme)),this._evaluator.globals=o,this._evaluator.feature=u||null,this._evaluator.featureState=m||null,this._evaluator.canonical=x||null,this._evaluator.availableImages=b||null,this._evaluator.formattedSection=S||null,this._evaluator.featureTileCoord=A||null,this._evaluator.featureDistanceData=I||null,this._evaluator.iconImageUseTheme=D||null;try{const B=this.expression.evaluate(this._evaluator);if(B==null||typeof B=="number"&&B!=B)return this._defaultValue;if(this._enumValues&&!(B in this._enumValues))throw new ra(`Expected value to be one of ${Object.keys(this._enumValues).map(U=>JSON.stringify(U)).join(", ")}, but found ${JSON.stringify(B)} instead.`);return B}catch(B){const U=B;return this._warningHistory[U.message]||(this._warningHistory[U.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${U.message}`)),this._defaultValue}}}function m1(h){return Array.isArray(h)&&h.length>0&&typeof h[0]=="string"&&Object.hasOwn(Rx,h[0])}function Vg(h,o,u,m,x){const b=new e1(Rx,[],o?function(A){const I={color:_c,string:Ei,number:Yr,enum:Ei,boolean:Bi,formatted:pp,resolvedImage:sm,object:xf};return A.type==="array"?Bo(I[A.value]||Pi,A.length):I[A.type]}(o):void 0,void 0,void 0,u,m,x),S=b.parse(h,void 0,void 0,void 0,o&&o.type==="string"?{typeAnnotation:"coerce"}:void 0);return S?Ug(new _2(S,o,u,m,x)):bp(b.errors)}class p1{constructor(o,u,m,x){this.kind=o,this._styleExpression=u,this.isLightConstant=m,this.isLineProgressConstant=x,this.isStateDependent=o!=="constant"&&!Fg(u.expression),this.configDependencies=u.configDependencies,this.isIndoorDependent=u.isIndoorDependent}evaluateWithoutErrorHandling(o,u,m,x,b,S){return this._styleExpression.evaluateWithoutErrorHandling(o,u,m,x,b,S)}evaluate(o,u,m,x,b,S,A){return this._styleExpression.evaluate(o,u,m,x,b,S,void 0,void 0,A)}}class wp{constructor(o,u,m,x,b,S){this.kind=o,this.zoomStops=m,this._styleExpression=u,this.isStateDependent=o!=="camera"&&!Fg(u.expression),this.isIndoorDependent=u.isIndoorDependent,this.isLightConstant=b,this.isLineProgressConstant=S,this.configDependencies=u.configDependencies,this.interpolationType=x}evaluateWithoutErrorHandling(o,u,m,x,b,S){return this._styleExpression.evaluateWithoutErrorHandling(o,u,m,x,b,S)}evaluate(o,u,m,x,b,S){return this._styleExpression.evaluate(o,u,m,x,b,S)}interpolationFactor(o,u,m){return this.interpolationType?pd.interpolationFactor(this.interpolationType,o,u,m):0}}function KN(h,o,u,m,x){const b=Vg(h,o,u,m,x);if(b.result==="error")return b;const S=b.value.expression,A=Og(S);if(!A&&!Lx(o))return bp([new Xl("","data expressions not supported")]);const I=AN(S),D=!(1&I);if(!D&&!GN(o))return bp([new Xl("","zoom expressions not supported")]);const B=!(2&I);if(!B&&!qN(o))return bp([new Xl("","measure-light expression not supported")]);const U=!(4&I);if(!U&&!function(X){return h1(X.expression,"line-progress")}(o))return bp([new Xl("","line-progress expression not supported")]);const q=o.expression&&o.expression.relaxZoomRestriction,K=y1(S);return K||D||q?K instanceof Xl?bp([K]):K instanceof pd&&!g2(o)?bp([new Xl("",'"interpolate" expressions cannot be used with this property')]):Ug(K?new wp(A&&U?"camera":"composite",b.value,K.labels,K instanceof pd?K.interpolation:void 0,B,U):new p1(A&&U?"constant":"source",b.value,B,U)):bp([new Xl("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class g1{constructor(o,u){this._parameters=o,this._specification=u,Object.assign(this,f1(this._parameters,this._specification))}static deserialize(o){return new g1(o._parameters,o._specification)}static serialize(o){return{_parameters:o._parameters,_specification:o._specification}}}function y1(h){let o=null;if(h instanceof o1)o=y1(h.result);else if(h instanceof a1){for(const u of h.args)if(o=y1(u),o)break}else(h instanceof Ax||h instanceof pd)&&h.input instanceof Ql&&h.input.name==="zoom"&&(o=h);return o instanceof Xl||h.eachChild(u=>{const m=y1(u);m instanceof Xl?o=m:o&&m&&o!==m&&(o=new Xl("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),o}class Dx{constructor(o,u,m){if(this.boxSeen=new Uint32Array(0),this.circleSeen=new Uint32Array(0),this.generation=0,o instanceof ArrayBuffer){const x=new Int32Array(o);this.width=x[0],this.height=x[1],this.xCellCount=x[2],this.yCellCount=x[3],this.boxUid=x[4],this.circleUid=x[5];const b=this.xCellCount*this.yCellCount;let S=x[x[6+b]+b];this.boxCells=[],this.circleCells=[],this.cellData=x,this.boxKeys=x.subarray(S,S+this.boxUid),S+=this.boxUid,this.circleKeys=x.subarray(S,S+this.circleUid),S+=this.circleUid,this.bboxes=x.subarray(S,S+4*this.boxUid),S+=4*this.boxUid,this.circles=x.subarray(S,S+3*this.circleUid)}else{this.width=o,this.height=u,this.xCellCount=Math.ceil(o/m),this.yCellCount=Math.ceil(u/m);const x=this.xCellCount*this.yCellCount,b=[],S=[];for(let A=0;Athis.width||x<0||u>this.height)return S;const A=this._nextGen(),{boxCells:I,circleCells:D,boxKeys:B,circleKeys:U,bboxes:q,circles:K,boxSeen:X,circleSeen:J,xCellCount:se}=this,ae=this._xCell(o),ue=this._yCell(u),ce=this._xCell(m),de=this._yCell(x);for(let xe=ae;xe<=ce;xe++)for(let ve=ue;ve<=de;ve++){const Ue=se*ve+xe,Pe=I[Ue];for(let Ve=0;Ve=st&&x>=ut&&(!b||b(B[Fe]))&&S.push({key:B[Fe],x1:st,y1:ut,x2:ht,y2:_t})}const De=D[Ue];for(let Ve=0;Vethis.width||x<0||u>this.height)return S;const A=this._nextGen(),{boxCells:I,cellData:D,boxKeys:B,bboxes:U,boxSeen:q,xCellCount:K,xScale:X,yScale:J}=this,se=this._xCell(o),ae=this._yCell(u),ue=this._xCell(m),ce=this._yCell(x);for(let de=se;de<=ue;de++)for(let xe=ae;xe<=ce;xe++){if(b&&!b(de/X,xe/J,(de+1)/X,(xe+1)/J))continue;const ve=K*xe+de,Ue=D||I[ve],Pe=D?D[6+ve+1]:Ue.length;for(let De=D?D[6+ve]:0;De=Ze&&x>=st)&&S.push(B[Ve])}}return S}hitTest(o,u,m,x,b){if(m<0||o>this.width||x<0||u>this.height)return!1;const S=this._nextGen(),{boxCells:A,circleCells:I,boxKeys:D,circleKeys:B,bboxes:U,circles:q,boxSeen:K,circleSeen:X,xCellCount:J}=this,se=this._xCell(o),ae=this._yCell(u),ue=this._xCell(m),ce=this._yCell(x);for(let de=se;de<=ue;de++)for(let xe=ae;xe<=ce;xe++){const ve=J*xe+de,Ue=A[ve];for(let De=0;De=U[Fe]&&x>=U[Fe+1]&&(!b||b(D[Ve])))return!0}const Pe=I[ve];for(let De=0;Dethis.width||I<0||S>this.height)return!1;const D=this._nextGen(),{boxCells:B,circleCells:U,boxKeys:q,circleKeys:K,bboxes:X,circles:J,boxSeen:se,circleSeen:ae,xCellCount:ue}=this,ce=this._xCell(b),de=this._yCell(S),xe=this._xCell(A),ve=this._yCell(I);for(let Ue=ce;Ue<=xe;Ue++)for(let Pe=de;Pe<=ve;Pe++){const De=ue*Pe+Ue,Ve=B[De];for(let Ze=0;Ze>>0,this.generation===0&&(this.boxSeen.fill(0),this.circleSeen.fill(0),this.generation=1),this.generation}_circlesCollide(o,u,m,x,b,S){const A=x-o,I=b-u,D=m+S;return D*D>A*A+I*I}_circleAndRectCollide(o,u,m,x,b,S,A){const I=(S-x)/2,D=Math.abs(o-(x+I));if(D>I+m)return!1;const B=(A-b)/2,U=Math.abs(u-(b+B));if(U>B+m)return!1;if(D<=I||U<=B)return!0;const q=D-I,K=U-B;return q*q+K*K<=m*m}}const x1={};function vr(h,o,u={}){Object.defineProperty(h,"_classRegistryKey",{value:o,writable:!1}),x1[o]={klass:h,omit:u.omit||[]}}vr(Object,"Object"),vr(Dx,"Grid"),delete jt.prototype.constructor,vr(Vn,"Color"),vr(sl,"Formatted"),vr(yp,"FormattedSection"),vr(Ol,"ResolvedImage"),vr(g1,"StylePropertyFunction"),vr(_2,"StyleExpression",{omit:["_evaluator"]}),vr(ga,"ImageId"),vr(Io,"ImageVariant"),vr(wp,"ZoomDependentExpression"),vr(p1,"ZoomConstantExpression"),vr(Ql,"CompoundExpression",{omit:["_evaluate"]});for(const h in Rx)x1[Rx[h]._classRegistryKey]||vr(Rx[h],`Expression${h}`);function YN(h){return h&&(h instanceof ArrayBuffer||h.constructor&&h.constructor.name==="ArrayBuffer")}const ZN={Error,TypeError,RangeError,SyntaxError,ReferenceError,URIError,EvalError},_1=new Set(["message","stack","cause","errors","name","class"]);function gd(h,o){if(h===null)return null;if(typeof h!="object")return h;if(Array.isArray(h)){const b=h.length,S=[];S.length=b;for(let A=0;AD!==b).map(D=>gd(D,o)));const I=b;for(const D in I)Object.hasOwn(I,D)&&(_1.has(D)||(A[D]=gd(I[D],o)));return A}throw new Error(`Can't serialize object of unregistered class "${u.name}".`)}const x=u.serialize?u.serialize(h,o):{};if(x===null)return null;if(!u.serialize){const b=x1[m].omit,S=h;for(const A in S)Object.hasOwn(S,A)&&(b.includes(A)||(x[A]=gd(S[A],o)))}if(x.$name)throw new Error("$name property is reserved for worker serialization logic.");return m!=="Object"&&(x.$name=m),x}function yd(h){var x;if(h===null||typeof h!="object")return h;if(Array.isArray(h)){for(let b=0;bh>=1536&&h<=1791,v2=h=>h>=1872&&h<=1919,XN=h=>h>=2208&&h<=2303,QN=h=>h>=11904&&h<=12031,Mx=h=>h>=12032&&h<=12255,JN=h=>h>=12272&&h<=12287,b1=h=>h>=12288&&h<=12351,w1=h=>h>=12352&&h<=12447,S1=h=>h>=12448&&h<=12543,eR=h=>h>=12544&&h<=12591,b2=h=>h>=12704&&h<=12735,w2=h=>h>=12736&&h<=12783,um=h=>h>=12784&&h<=12799,S2=h=>h>=12800&&h<=13055,tR=h=>h>=13056&&h<=13311,Sp=h=>h>=13312&&h<=19903,E2=h=>h>=19968&&h<=40959,A0=h=>h>=40960&&h<=42127,T2=h=>h>=42128&&h<=42191,rR=h=>h>=44032&&h<=55215,nR=h=>h>=63744&&h<=64255,k0=h=>h>=64336&&h<=65023,E1=h=>h>=65040&&h<=65055,I0=h=>h>=65072&&h<=65103,A2=h=>h>=65104&&h<=65135,k2=h=>h>=65136&&h<=65279,Ox=h=>h>=65280&&h<=65519;function j0(h){for(const o of h)if(T1(o.charCodeAt(0)))return!0;return!1}function I2(h){return!(v1(h)||v2(h)||XN(h)||k0(h)||k2(h))}function T1(h){return!(h!==746&&h!==747&&(h<4352||!(b2(h)||eR(h)||I0(h)&&!(h>=65097&&h<=65103)||nR(h)||tR(h)||QN(h)||w2(h)||!(!b1(h)||h>=12296&&h<=12305||h>=12308&&h<=12319||h===12336)||Sp(h)||E2(h)||S2(h)||(o=>o>=12592&&o<=12687)(h)||(o=>o>=43360&&o<=43391)(h)||(o=>o>=55216&&o<=55295)(h)||(o=>o>=4352&&o<=4607)(h)||rR(h)||w1(h)||JN(h)||(o=>o>=12688&&o<=12703)(h)||Mx(h)||um(h)||S1(h)&&h!==12540||!(!Ox(h)||h===65288||h===65289||h===65293||h>=65306&&h<=65310||h===65339||h===65341||h===65343||h>=65371&&h<=65503||h===65507||h>=65512&&h<=65519)||!(!A2(h)||h>=65112&&h<=65118||h>=65123&&h<=65126)||(o=>o>=5120&&o<=5759)(h)||(o=>o>=6320&&o<=6399)(h)||E1(h)||(o=>o>=19904&&o<=19967)(h)||A0(h)||T2(h))))}function j2(h){return!(T1(h)||function(o){return!!((u=>u>=128&&u<=255)(o)&&(o===167||o===169||o===174||o===177||o===188||o===189||o===190||o===215||o===247)||(u=>u>=8192&&u<=8303)(o)&&(o===8214||o===8224||o===8225||o===8240||o===8241||o===8251||o===8252||o===8258||o===8263||o===8264||o===8265||o===8273)||(u=>u>=8448&&u<=8527)(o)||(u=>u>=8528&&u<=8591)(o)||(u=>u>=8960&&u<=9215)(o)&&(o>=8960&&o<=8967||o>=8972&&o<=8991||o>=8996&&o<=9e3||o===9003||o>=9085&&o<=9114||o>=9150&&o<=9165||o===9167||o>=9169&&o<=9179||o>=9186&&o<=9215)||(u=>u>=9216&&u<=9279)(o)&&o!==9251||(u=>u>=9280&&u<=9311)(o)||(u=>u>=9312&&u<=9471)(o)||(u=>u>=9632&&u<=9727)(o)||(u=>u>=9728&&u<=9983)(o)&&!(o>=9754&&o<=9759)||(u=>u>=11008&&u<=11263)(o)&&(o>=11026&&o<=11055||o>=11088&&o<=11097||o>=11192&&o<=11243)||b1(o)||S1(o)||(u=>u>=57344&&u<=63743)(o)||I0(o)||A2(o)||Ox(o)||o===8734||o===8756||o===8757||o>=9984&&o<=10087||o>=10102&&o<=10131||o===65532||o===65533)}(h))}function iR(h){return h>=1424&&h<=2303||k0(h)||k2(h)}function C2(h){return!(h>=2304&&h<=3583||h>=3840&&h<=4255||(o=>o>=6016&&o<=6143)(h))}function sR(h){for(const o of h)if(iR(o.charCodeAt(0)))return!0;return!1}class Hs{constructor(o,u){this.zoom=o,u?(this.now=u.now,this.fadeDuration=u.fadeDuration,this.transition=u.transition,this.pitch=u.pitch,this.brightness=u.brightness,this.worldview=u.worldview,this.activeFloors=u.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(o){return function(u){for(const m of u)if(!C2(m.charCodeAt(0)))return!1;return!0}(o)}}class P2{constructor(o,u,m,x,b){this.property=o,this.value=u,this.expression=function(D,B,U,q,K){if(y2(D))return new g1(D,B);if(m1(D)||Array.isArray(D)&&D.length>0){const X=KN(D,B,U,q,K);if(X.result==="error")throw new Error(X.value.map(J=>`${J.key}: ${J.message}`).join(", "));return X.value}{let X=D;return typeof D=="string"&&B.type==="color"&&(X=Vn.parse(D)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>X}}}(u===void 0?o.specification.default:u,o.specification,m,x,b);const{kind:S}=this.expression,A=o.specification.type,I=this.expression._styleExpression;this.deps=(S==="camera"||S==="composite"?1:0)|(this.expression.isLightConstant===!1?2:0)|(S!=="constant"&&S!=="camera"||!(A==="resolvedImage"||A==="formatted"||I&&I.isImageDependent)?0:4)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(o,u,m,x){return this.property.possiblyEvaluate(this,o,u,m,x)}}function A1(h,o,u,m,x){const b=o.now||0,S=h.value.possiblyEvaluate(o,u,m,x),A=h.prior;if(A){if(b>h.end||h.value.isDataDriven())return h.prior=null,S;if(b":1,">=":1,"<":1,"<=":1,"in":1,"!in":1,"all":1,"any":1,"none":1,"has":1,"!has":1}},"geometry_type":{"type":"enum","values":{"Point":1,"LineString":1,"Polygon":1}},"function_stop":{"type":"array","minimum":0,"maximum":24,"length":2,"value":["number","color"]},"fog":{"range":{"type":"array","default":[0.5,10],"minimum":-20,"maximum":20,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"high-color":{"type":"color","default":"#245cdf","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"space-color":{"type":"color","default":["interpolate",["linear"],["zoom"],4,"#010b19",7,"#367ab9"],"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"horizon-blend":{"type":"number","default":["interpolate",["linear"],["zoom"],4,0.2,7,0.1],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"star-intensity":{"type":"number","default":["interpolate",["linear"],["zoom"],5,0.35,6,0],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vertical-range":{"type":"array","default":[0,0],"minimum":0,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1}},"snow":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.85],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.3],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"center-thinning":{"type":"number","default":0.4,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"direction":{"type":"array","default":[0,50],"minimum":0,"maximum":360,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"flake-size":{"type":"number","default":0.71,"minimum":0,"maximum":5,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1}},"rain":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.5],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#03113d",0.3,"#a8adbc"],"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"opacity":{"type":"number","default":["interpolate",["linear"],["measure-light","brightness"],0,0.88,1,0.7],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,1],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette-color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#001736",0.3,"#464646"],"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"center-thinning":{"type":"number","default":0.57,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"direction":{"type":"array","default":[0,80],"minimum":0,"maximum":360,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"droplet-size":{"type":"array","default":[2.6,18.2],"minimum":0,"maximum":50,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"distortion-strength":{"type":"number","default":0.7,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1}},"camera":{"camera-projection":{"type":"enum","default":"perspective","values":{"perspective":1,"orthographic":1}}},"colorTheme":{"data":{"type":"string","expression":1}},"indoor_source":{"sourceId":{"type":"string"},"sourceLayers":{"type":"array","value":"string"}},"indoor":{"*":{"type":"indoor_source"}},"light":{"anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"position":{"type":"array","default":[1.15,210,30],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1,"use-theme":1},"intensity":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"projection":{"name":{"type":"enum","default":"mercator","values":{"albers":1,"equalEarth":1,"equirectangular":1,"lambertConformalConic":1,"mercator":1,"naturalEarth":1,"winkelTripel":1,"globe":1}},"center":{"type":"array","minimum":[-180,-90],"maximum":[180,90],"length":2,"value":"number"},"parallels":{"type":"array","minimum":[-90,-90],"maximum":[90,90],"length":2,"value":"number"}},"terrain":{"source":{"type":"string"},"exaggeration":{"type":"number","default":1,"minimum":0,"maximum":1000,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint":["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_building","paint_symbol","paint_raster","paint_raster-particle","paint_hillshade","paint_background","paint_sky","paint_model"],"paint_fill":{"fill-antialias":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"fill-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-outline-color":{"type":"color","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"fill-pattern":{"type":"resolvedImage","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"fill-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"fill-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"fill-z-offset":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","zoom"]},"transition":1,"property-type":"data-driven"},"fill-bridge-guard-rail-color":{"type":"color","default":"rgba(241, 236, 225, 255)","expression":{"interpolated":1,"parameters":["feature","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-tunnel-structure-color":{"type":"color","default":"rgba(241, 236, 225, 255)","expression":{"interpolated":1,"parameters":["feature","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-extrusion-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"fill-extrusion-pattern":{"type":"resolvedImage","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"fill-extrusion-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"fill-extrusion-height":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-base":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-height-alignment":{"type":"enum","default":"flat","values":{"terrain":1,"flat":1}},"fill-extrusion-base-alignment":{"type":"enum","default":"terrain","values":{"terrain":1,"flat":1}},"fill-extrusion-vertical-gradient":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-wall-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-flood-light-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"fill-extrusion-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"fill-extrusion-flood-light-wall-radius":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-flood-light-ground-radius":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["feature","feature-state"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-vertical-scale":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-rounded-roof":{"type":"boolean","default":true,"expression":{"parameters":["zoom"]}},"fill-extrusion-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":1},"fill-extrusion-front-cutoff":{"type":"array","default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]}},"fill-extrusion-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-line-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-cast-shadows":{"type":"boolean","default":true}},"paint_building":{"building-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"parameters":[]},"transition":1},"building-ambient-occlusion-ground-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-vertical-scale":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-cast-shadows":{"type":"boolean","default":true},"building-color":{"type":"color","default":"rgba(193, 154, 127, 1)","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"use-theme":1,"property-type":"data-driven"},"building-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-facade-emissive-chance":{"type":"number","default":0.35,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"building-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":1},"building-front-cutoff":{"type":"array","default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]}},"building-flood-light-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"building-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"building-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_line":{"line-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"line-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"line-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"line-width":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","line-progress","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-gap-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-offset":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-blur":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-dasharray":{"type":"array","minimum":0,"value":"number","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"line-pattern":{"type":"resolvedImage","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"line-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"line-gradient":{"type":"color","expression":{"interpolated":1,"parameters":["line-progress"]},"use-theme":1},"line-trim-offset":{"type":"array","default":[0,0],"minimum":[0,0],"maximum":[1,1],"length":2,"value":"number"},"line-trim-fade-range":{"type":"array","default":[0,0],"minimum":[0,0],"maximum":[1,1],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"line-trim-color":{"type":"color","default":"transparent","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"line-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["line-progress","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-border-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"line-border-color":{"type":"color","default":"rgba(0, 0, 0, 0)","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"line-border-gradient":{"type":"color","expression":{"interpolated":1,"parameters":["line-progress"]},"use-theme":1},"line-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"line-blend-mode":{"type":"enum","default":"default","values":{"default":1,"multiply":1,"additive":1},"expression":{"parameters":["zoom"]}},"line-blend-additive-clamp":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]}},"line-cutout-depth":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_circle":{"circle-radius":{"type":"number","default":5,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"circle-blur":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"circle-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"circle-pitch-scale":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"circle-pitch-alignment":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"circle-stroke-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-stroke-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"circle-stroke-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1}},"paint_heatmap":{"heatmap-radius":{"type":"number","default":30,"minimum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"heatmap-weight":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"property-type":"data-driven"},"heatmap-intensity":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"heatmap-color":{"type":"color","default":["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",0.1,"royalblue",0.3,"cyan",0.5,"lime",0.7,"yellow",1,"red"],"expression":{"interpolated":1,"parameters":["heatmap-density"]},"use-theme":1},"heatmap-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_symbol":{"icon-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-emissive-strength":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-emissive-strength":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1},"icon-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1},"icon-halo-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-halo-blur":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1,"appearance":1},"icon-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"icon-image-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"text-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1,"overridable":1},"text-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1},"text-halo-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-halo-blur":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1,"appearance":1},"text-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"icon-color-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":1},"icon-color-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":1},"icon-color-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":1},"icon-color-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":1},"symbol-z-offset":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"placement-priority":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["distance-from-center","feature","feature-state","measure-light","pitch","zoom"]},"property-type":"data-driven","appearance":1},"placement-group":{"type":"string","expression":{"parameters":["distance-from-center","feature","feature-state","measure-light","pitch","zoom"]},"property-type":"data-driven","appearance":1}},"paint_raster":{"raster-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-color":{"type":"color","expression":{"interpolated":1,"parameters":["raster-value"]},"use-theme":1},"raster-color-mix":{"type":"array","default":[0.2126,0.7152,0.0722,0],"length":4,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-color-range":{"type":"array","length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-color-scale":{"type":"enum","default":"linear","values":{"linear":1,"log":1},"expression":{"parameters":[]}},"raster-hue-rotate":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-resampling":{"type":"enum","default":"linear","values":{"linear":1,"nearest":1},"expression":{"parameters":["zoom"]}},"raster-fade-duration":{"type":"number","default":300,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]}},"raster-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"raster-array-band":{"type":"string"},"raster-elevation":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-elevation-reference":{"type":"enum","default":"sea","values":{"sea":1,"ground":1},"expression":1},"raster-mask":{"type":"string"},"raster-mask-import":{"type":"string"},"raster-mask-mode":{"type":"enum","default":"clip-path-intersect","values":{"clip-path-intersect":1,"clip-path-exclude":1}}},"paint_raster-particle":{"raster-particle-array-band":{"type":"string"},"raster-particle-count":{"type":"number","default":512,"minimum":1},"raster-particle-color":{"type":"color","expression":{"interpolated":1,"parameters":["raster-particle-speed"]},"use-theme":1},"raster-particle-max-speed":{"type":"number","default":1,"minimum":1},"raster-particle-speed-factor":{"type":"number","default":0.2,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-particle-fade-opacity-factor":{"type":"number","default":0.98,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-particle-reset-rate-factor":{"type":"number","default":0.8,"minimum":0,"maximum":1},"raster-particle-elevation":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_hillshade":{"hillshade-illumination-direction":{"type":"number","default":335,"minimum":0,"maximum":359,"expression":{"interpolated":1,"parameters":["zoom"]}},"hillshade-illumination-anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"hillshade-exaggeration":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"hillshade-shadow-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"hillshade-highlight-color":{"type":"color","default":"#FFFFFF","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"hillshade-accent-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"hillshade-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1}},"paint_background":{"background-pitch-alignment":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":[]}},"background-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"background-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom"]}},"background-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"background-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1}},"paint_sky":{"sky-type":{"type":"enum","default":"atmosphere","values":{"gradient":1,"atmosphere":1},"expression":{"parameters":["zoom"]}},"sky-atmosphere-sun":{"type":"array","minimum":[0,0],"maximum":[360,180],"length":2,"value":"number","expression":{"parameters":["zoom"]}},"sky-atmosphere-sun-intensity":{"type":"number","default":10,"minimum":0,"maximum":100},"sky-gradient-center":{"type":"array","default":[0,0],"minimum":[0,0],"maximum":[360,180],"length":2,"value":"number","expression":{"parameters":["zoom"]}},"sky-gradient-radius":{"type":"number","default":90,"minimum":0,"maximum":180,"expression":{"parameters":["zoom"]}},"sky-gradient":{"type":"color","default":["interpolate",["linear"],["sky-radial-progress"],0.8,"#87ceeb",1,"white"],"expression":{"interpolated":1,"parameters":["sky-radial-progress"]},"use-theme":1},"sky-atmosphere-halo-color":{"type":"color","default":"white","use-theme":1},"sky-atmosphere-color":{"type":"color","default":"white","use-theme":1},"sky-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_model":{"model-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-rotation":{"type":"array","default":[0,0,0],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-scale":{"type":"array","default":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-translation":{"type":"array","default":[0,0,0],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"model-color-mix-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"transition":1,"property-type":"data-driven"},"model-type":{"type":"enum","default":"common-3d","values":{"common-3d":1,"location-indicator":1}},"model-cast-shadows":{"type":"boolean","default":true},"model-receive-shadows":{"type":"boolean","default":true},"model-ambient-occlusion-intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"model-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"transition":1,"property-type":"data-driven"},"model-roughness":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state"]},"transition":1,"property-type":"data-driven"},"model-height-based-emissive-strength-multiplier":{"type":"array","default":[1,1,1,1,0],"length":5,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"transition":1,"property-type":"data-driven"},"model-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":1},"model-front-cutoff":{"type":"array","default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]}},"model-elevation-reference":{"type":"enum","default":"ground","values":{"sea":1,"ground":1,"hd-road-markup":1},"expression":1},"model-line-cutout-mode":{"type":"enum","default":"enabled","values":{"enabled":1,"disabled":1,"enabled-above-cutout":1},"expression":1}},"promoteId":{"*":{"type":"*"}}}');function aR(h){return h instanceof Number||h instanceof String||h instanceof Boolean?h.valueOf():h}function k1(h){if(Array.isArray(h))return h.map(k1);if(h instanceof Object&&!(h instanceof Number||h instanceof String||h instanceof Boolean)){const o={},u=h;for(const m in u)o[m]=k1(u[m]);return o}return aR(h)}function R2(h){if(h===!0||h===!1)return!0;if(!Array.isArray(h)||h.length===0)return!1;switch(h[0]){case"has":return h.length>=2&&h[1]!=="$id"&&h[1]!=="$type";case"in":return h.length>=3&&(typeof h[1]!="string"||Array.isArray(h[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return h.length!==3||Array.isArray(h[1])||Array.isArray(h[2]);case"any":case"all":for(const o of h.slice(1))if(!R2(o)&&typeof o!="boolean")return!1;return!0;default:return!0}}function L2(h,o="",u=null,m="fill"){if(h==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};R2(h)||(h=I1(h));const x=h;let b=!0;try{b=function(B){if(!hm(B))return B;let U=k1(B);return Fx(U),U=oR(U),U}(x)}catch{console.warn(`Failed to extract static filter. Filter will continue working, but at higher memory usage and slower framerate. This is most likely a bug, please report this via https://github.com/mapbox/mapbox-gl-js/issues/new?assignees=&labels=&template=Bug_report.md and paste the contents of this message in the report. Thank you! Filter Expression: ${JSON.stringify(x,null,2)} `)}let S=null,A=null;if(m!=="background"&&m!=="sky"&&m!=="slot"){A=lt[`filter_${m}`];const B=Vg(b,A,o,u);if(B.result==="error")throw new Error(B.value.map(U=>`${U.key}: ${U.message}`).join(", "));S=(U,q,K)=>B.value.evaluate(U,q,{},K)}let I=null,D=null;if(b!==x){const B=Vg(x,A,o,u);if(B.result==="error")throw new Error(B.value.map(U=>`${U.key}: ${U.message}`).join(", "));I=(U,q,K,X,J)=>B.value.evaluate(U,q,{},K,void 0,void 0,X,J),D=!Og(B.value.expression)}return{filter:S,dynamicFilter:I||void 0,needGeometry:D2(b),needFeature:!!D}}function oR(h){if(!Array.isArray(h))return h;const o=function(u){if(lR.has(u[0])){for(let m=1;moR(u))}function Fx(h){if(!Array.isArray(h))return;let o=!1;const u=[];if(h[0]==="case"){for(let m=1;m",">=","<","<=","to-boolean"]);function rz(h,o){return ho?1:0}function D2(h){if(!Array.isArray(h))return!1;if(h[0]==="within"||h[0]==="distance")return!0;for(let o=1;o"||o==="<="||o===">="?M2(h[1],h[2],o):o==="any"?(u=h.slice(1),["any"].concat(u.map(I1))):o==="all"?["all"].concat(h.slice(1).map(I1)):o==="none"?["all"].concat(h.slice(1).map(I1).map(j1)):o==="in"?O2(h[1],h.slice(2)):o==="!in"?j1(O2(h[1],h.slice(2))):o==="has"?P0(h[1]):o!=="!has"||j1(P0(h[1]));var u}function M2(h,o,u){switch(h){case"$type":return[`filter-type-${u}`,o];case"$id":return[`filter-id-${u}`,o];default:return[`filter-${u}`,h,o]}}function O2(h,o){if(o.length===0)return!1;switch(h){case"$type":return["filter-type-in",["literal",o]];case"$id":return["filter-id-in",["literal",o]];default:return o.length>200&&!o.some(u=>typeof u!=typeof o[0])?["filter-in-large",h,["literal",o.sort(rz)]]:["filter-in-small",h,["literal",o]]}}function P0(h){switch(h){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",h]}}function j1(h){return["!",h]}const N0="";function Bx(h,o){return o?`${h}${N0}${o}`:h}function cR(h){const o=h.indexOf(N0);return o>=0?h.slice(o+1):""}let uR,C1=1;const R0=()=>uR||(uR=new Ws({"icon-size":new sr(lt.layout_symbol["icon-size"]),"icon-image":new sr(lt.layout_symbol["icon-image"]),"icon-rotate":new sr(lt.layout_symbol["icon-rotate"]),"icon-offset":new sr(lt.layout_symbol["icon-offset"]),"text-size":new sr(lt.layout_symbol["text-size"]),"text-rotate":new sr(lt.layout_symbol["text-rotate"]),"text-offset":new sr(lt.layout_symbol["text-offset"])}));let Gu;const L0=()=>Gu||(Gu=new Ws({"icon-opacity":new sr(lt.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new sr(lt.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new sr(lt.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new sr(lt.paint_symbol["text-emissive-strength"]),"icon-color":new sr(lt.paint_symbol["icon-color"]),"icon-halo-color":new sr(lt.paint_symbol["icon-halo-color"]),"icon-halo-width":new sr(lt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new sr(lt.paint_symbol["icon-halo-blur"]),"icon-translate":new sr(lt.paint_symbol["icon-translate"]),"text-opacity":new sr(lt.paint_symbol["text-opacity"]),"text-occlusion-opacity":new sr(lt.paint_symbol["text-occlusion-opacity"]),"text-color":new sr(lt.paint_symbol["text-color"],{runtimeType:_c,getOverride:h=>h.textColor,hasOverride:h=>!!h.textColor}),"text-halo-color":new sr(lt.paint_symbol["text-halo-color"]),"text-halo-width":new sr(lt.paint_symbol["text-halo-width"]),"text-halo-blur":new sr(lt.paint_symbol["text-halo-blur"]),"text-translate":new sr(lt.paint_symbol["text-translate"]),"symbol-z-offset":new sr(lt.paint_symbol["symbol-z-offset"]),"placement-priority":new sr(lt.paint_symbol["placement-priority"]),"placement-group":new sr(lt.paint_symbol["placement-group"]),"icon-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}));class nz{constructor(o,u,m,x,b,S){this._conditionSpec=o,this._propertiesSpec=m;const A=Vg(o,lt.appearance.condition);if(A.result==="success"&&(this.condition=A.value),this.name=u,m){this.layoutProperties=new qg(R0()),this.unevaluatedLayout=new C0(R0(),x,b,S),this.paintProperties=new qg(L0()),this.unevaluatedPaint=new C0(L0(),x,b,"");for(const I in m)I in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(I,m[I]):I in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(I,m[I]);this.unevaluatedPaint.snap()}}isActive(o){return!(this.condition||!o.isHidden||this.name!=="hidden")||this.condition.evaluate(o.globals,o.feature,o.featureState,o.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(o){return this.layoutProperties.get(o)}getPaintProperty(o){return this.paintProperties.get(o)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(o){return this.unevaluatedLayout._values[o].value}getUnevaluatedPaintProperty(o){return this.unevaluatedPaint._values[o].value}recalculate(o,u,m){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(o,void 0,u,m)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(o,void 0,u,""))}serialize(){const o={};o.condition=this.condition.expression.serialize(),this.name&&(o.name=this.name);const u={...this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},...this.unevaluatedPaint?this.unevaluatedPaint.serialize():{}};return Object.keys(u).length>0&&(o.properties=u),o}hasIconLayoutProperties(){const o=this.hasLayoutProperty("icon-image"),u=this.hasLayoutProperty("icon-size"),m=this.hasLayoutProperty("icon-offset"),x=this.hasLayoutProperty("icon-rotate");return o||u||m||x}hasTextLayoutProperties(){const o=this.hasLayoutProperty("text-size"),u=this.hasLayoutProperty("text-offset"),m=this.hasLayoutProperty("text-rotate");return o||u||m}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(o=>!o.endsWith("-use-theme")).some(o=>(o.startsWith("icon-")||o==="symbol-z-offset")&&this.hasPaintProperty(o))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(o=>!o.endsWith("-use-theme")).some(o=>(o.startsWith("text-")||o==="symbol-z-offset")&&this.hasPaintProperty(o))}hasLayoutProperty(o){return this.unevaluatedLayout&&this.unevaluatedLayout._values[o].value.value!==void 0}hasPaintProperty(o){return this.unevaluatedPaint&&this.unevaluatedPaint._values[o].value.value!==void 0}}const dR="-transition",iz=new Set(["fill","line","background","hillshade","raster"]);class bc extends ca{constructor(o,u,m,x,b,S){if(super(),this.id=o.id,this.fqid=Bx(this.id,m),this.runtimeLayerUID=C1++,this.type=o.type,this.scope=m,this.lut=x,this.options=b,this.iconImageUseTheme=S,this.appearances=new Array,this.appearancesVersion=0,this.paintVersion=0,this._dirty=!0,this._recalcParameters=null,this._recalcImages=null,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,o.type!=="custom"&&(this.metadata=o.metadata,this.minzoom=o.minzoom,this.maxzoom=o.maxzoom,o.type&&o.type!=="background"&&o.type!=="sky"&&o.type!=="slot"&&o.type!=="placement-group"&&(this.source=o.source,this.sourceFqid=Bx(o.source,m),this.sourceLayer=o["source-layer"],this.filter=o.filter),o.slot&&(this.slot=o.slot),o.appearances&&this.setAppearances(o.appearances),u.layout&&(this._layoutValues=new C0(u.layout,this.scope,b,this.iconImageUseTheme)),u.paint)){this._paintValues=new C0(u.paint,this.scope,b);for(const A in o.paint)this.setPaintProperty(A,o.paint[A]);for(const A in o.layout)this.setLayoutProperty(A,o.layout[A]);this._paintValues.snap(),this.paint=new qg(u.paint)}}onAdd(o){}onRemove(o){}placeSymbols(o,u,m,x,b,S){}isDraped(o){return!this.is3D(!0)&&iz.has(this.type)}getLayoutProperty(o){return o==="visibility"?this.visibility:this._layoutValues.getValue(o)}setLayoutProperty(o,u){if(this.type==="custom"&&o==="visibility")return void(this.visibility=u);const m=this._layoutValues;m._properties.properties[o]&&(m.setValue(o,u),this._dirty=!0,o==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(o){this.appearances=[],o.forEach(u=>{this.appearances.push(new nz(u.condition,u.name,u.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++,this._dirty=!0}possiblyEvaluateVisibility(){const o=this.getLayoutPropertyValue("visibility");o&&(this.visibility=o.possiblyEvaluate({zoom:0}))}getLayoutPropertyValue(o){const u=this._layoutValues&&this._layoutValues._values[o];return u&&u.value}getPaintPropertyValue(o){const u=this._paintValues&&this._paintValues._values[o];return u&&u.value}getPaintProperty(o){return o.endsWith(dR)?this._paintValues.getTransition(o.slice(0,-11)):this._paintValues.getValue(o)}isPaintProperty(o){return!!this._paintValues._properties.properties[o]}setPaintProperty(o,u){const m=this._paintValues,x=m._properties.properties;if(o.endsWith(dR)){const U=o.slice(0,-11);return x[U]&&m.setTransition(U,u||void 0),!1}if(!x[o])return!1;const b=m._values[o],S=b.value.isDataDriven(),A=b.value;m.setValue(o,u),this._handleSpecialPaintPropertyUpdate(o);const I=m._values[o].value,D=I.isDataDriven(),B=o.endsWith("pattern")||o==="line-dasharray";return D||S||B||this._handleOverridablePaintPropertyUpdate(o,A,I)}_handleSpecialPaintPropertyUpdate(o){}getProgramIds(){return null}getDefaultProgramParams(o,u,m){return null}_handleOverridablePaintPropertyUpdate(o,u,m){return!1}isPlacementAffectedByPaintChanges(o){return!1}isHidden(o){return!!(this.minzoom&&o=this.maxzoom)||this.visibility==="none"}updateTransitions(o){this._paintValues.updateTransitions(o),this.paintVersion++,this._dirty=!0}hasTransition(){return this._paintValues.hasTransition()}getPropertyDependencies(){let o=(this._layoutValues?this._layoutValues.deps:0)|(this._paintValues?this._paintValues.deps:0);for(const{unevaluatedLayout:u,unevaluatedPaint:m}of this.appearances)u&&(o|=u.deps|m.deps);return o}recalculate(o,u){const m=this._recalcParameters;let x;(this._dirty||!m||o.worldview!==m.worldview||o.activeFloors!==m.activeFloors||(x=this.getPropertyDependencies()&((o.zoom!==m.zoom||o.pitch!==m.pitch?1:0)|(o.brightness!==m.brightness?2:0)|(u!==this._recalcImages?4:0)),x))&&(this._recalcParameters=o,this._recalcImages=u,this._layoutValues&&(this.layout=this._layoutValues.possiblyEvaluate(o,void 0,u,this.iconImageUseTheme,x)),this.hasTransition()&&this.paintVersion++,this.paint=this._paintValues.possiblyEvaluate(o,void 0,u,void 0,x),this._dirty=this.hasTransition(),this._finalizeEvaluated(o,u))}_finalizeEvaluated(o,u){}serialize(){const o={id:this.id,type:this.type,slot:this.slot,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._layoutValues&&this._layoutValues.serialize(),paint:this._paintValues&&this._paintValues.serialize()};return this.appearances.length!==0&&(o.appearances=this.appearances.map(u=>u.serialize())),qd(o,(u,m)=>!(u===void 0||m==="layout"&&!Object.keys(u).length||m==="paint"&&!Object.keys(u).length))}is3D(o){return!1}hasElevation(){return!1}mayUse(o){return!1}prepare(){return Promise.resolve()}isSky(){return!1}isTileClipped(){return!1}hasBlended3DDepthPrepass(){return!1}hasOffscreenPass(){return!1}hasShadowPass(){return!1}canCastShadows(){return!1}hasLightBeamPass(){return!1}cutoffRange(){return 0}tileCoverLift(){return 0}resize(){}_clear(){}isStateDependent(){for(const o in this.paint._values){const u=this.paint.get(o);if(u instanceof dm&&Lx(u.property.specification)&&(u.value.kind==="source"||u.value.kind==="composite")&&u.value.isStateDependent)return!0}for(const o of this.appearances)if(!Fg(o.condition.expression))return!0;return!1}compileFilter(o){this._filterCompiled||(this._featureFilter=L2(this.filter,this.scope,o),this._filterCompiled=!0)}invalidateCompiledFilter(){this._filterCompiled=!1}dynamicFilter(){return this._featureFilter.dynamicFilter}dynamicFilterNeedsFeature(){return this._featureFilter.needFeature}dynamicFilterNeedsGeometry(){return this._featureFilter.needGeometry}getLayerRenderingStats(){return this._stats}resetLayerRenderingStats(o){this._stats&&(o.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(o,u,m){return{}}queryRadius(o){}queryIntersectsFeature(o,u,m,x,b,S,A,I,D,B){}}function zx(h,o,u){var x;const m=(x=h.getLayoutPropertyValue(o))==null?void 0:x.value;return m!==void 0&&(typeof m!="string"||u(m))}function $x(h,o,u=2){const m=o&&o.length,x=m?o[0]*u:h.length;let b=P1(h,0,x,u,!0);const S=[];if(!b||b.next===b.prev)return S;let A,I,D;if(m&&(b=function(B,U,q,K){const X=[];for(let J=0,se=U.length;J80*u){A=h[0],I=h[1];let B=A,U=I;for(let q=u;qB&&(B=K),X>U&&(U=X)}D=Math.max(B-A,U-I),D=D!==0?32767/D:0}return D0(b,S,u,A,I,D,0),S}function P1(h,o,u,m,x){let b;if(x===function(S,A,I,D){let B=0;for(let U=A,q=I-D;U0)for(let S=o;S=o;S-=m)b=$2(S/m|0,h[S],h[S+1],b);return b&&Vx(b,b.next)&&(F0(b),b=b.next),b}function Gg(h,o){if(!h)return h;o||(o=h);let u,m=h;do if(u=!1,m.steiner||!Vx(m,m.next)&&go(m.prev,m,m.next)!==0)m=m.next;else{if(F0(m),m=o=m.prev,m===m.next)break;u=!0}while(u||m!==o);return o}function D0(h,o,u,m,x,b,S){if(!h)return;!S&&b&&function(I,D,B,U){let q=I;do q.z===0&&(q.z=B2(q.x,q.y,D,B,U)),q.prevZ=q.prev,q.nextZ=q.next,q=q.next;while(q!==I);q.prevZ.nextZ=null,q.prevZ=null,function(K){let X,J=1;do{let se,ae=K;K=null;let ue=null;for(X=0;ae;){X++;let ce=ae,de=0;for(let ve=0;ve0||xe>0&&ce;)de!==0&&(xe===0||!ce||ae.z<=ce.z)?(se=ae,ae=ae.nextZ,de--):(se=ce,ce=ce.nextZ,xe--),ue?ue.nextZ=se:K=se,se.prevZ=ue,ue=se;ae=ce}ue.nextZ=null,J*=2}while(X>1)}(q)}(h,m,x,b);let A=h;for(;h.prev!==h.next;){const I=h.prev,D=h.next;if(b?az(h,m,x,b):sz(h))o.push(I.i,h.i,D.i),F0(h),h=D.next,A=D.next;else if((h=D)===A){S?S===1?D0(h=hR(Gg(h),o),o,u,m,x,b,2):S===2&&F2(h,o,u,m,x,b):D0(Gg(h),o,u,m,x,b,1);break}}}function sz(h){const o=h.prev,u=h,m=h.next;if(go(o,u,m)>=0)return!1;const x=o.x,b=u.x,S=m.x,A=o.y,I=u.y,D=m.y,B=Math.min(x,b,S),U=Math.min(A,I,D),q=Math.max(x,b,S),K=Math.max(A,I,D);let X=m.next;for(;X!==o;){if(X.x>=B&&X.x<=q&&X.y>=U&&X.y<=K&&Ux(x,A,b,I,S,D,X.x,X.y)&&go(X.prev,X,X.next)>=0)return!1;X=X.next}return!0}function az(h,o,u,m){const x=h.prev,b=h,S=h.next;if(go(x,b,S)>=0)return!1;const A=x.x,I=b.x,D=S.x,B=x.y,U=b.y,q=S.y,K=Math.min(A,I,D),X=Math.min(B,U,q),J=Math.max(A,I,D),se=Math.max(B,U,q),ae=B2(K,X,o,u,m),ue=B2(J,se,o,u,m);let ce=h.prevZ,de=h.nextZ;for(;ce&&ce.z>=ae&&de&&de.z<=ue;){if(ce.x>=K&&ce.x<=J&&ce.y>=X&&ce.y<=se&&ce!==x&&ce!==S&&Ux(A,B,I,U,D,q,ce.x,ce.y)&&go(ce.prev,ce,ce.next)>=0||(ce=ce.prevZ,de.x>=K&&de.x<=J&&de.y>=X&&de.y<=se&&de!==x&&de!==S&&Ux(A,B,I,U,D,q,de.x,de.y)&&go(de.prev,de,de.next)>=0))return!1;de=de.nextZ}for(;ce&&ce.z>=ae;){if(ce.x>=K&&ce.x<=J&&ce.y>=X&&ce.y<=se&&ce!==x&&ce!==S&&Ux(A,B,I,U,D,q,ce.x,ce.y)&&go(ce.prev,ce,ce.next)>=0)return!1;ce=ce.prevZ}for(;de&&de.z<=ue;){if(de.x>=K&&de.x<=J&&de.y>=X&&de.y<=se&&de!==x&&de!==S&&Ux(A,B,I,U,D,q,de.x,de.y)&&go(de.prev,de,de.next)>=0)return!1;de=de.nextZ}return!0}function hR(h,o){let u=h;do{const m=u.prev,x=u.next.next;!Vx(m,x)&&N1(m,u,u.next,x)&&O0(m,x)&&O0(x,m)&&(o.push(m.i,u.i,x.i),F0(u),F0(u.next),u=h=x),u=u.next}while(u!==h);return Gg(u)}function F2(h,o,u,m,x,b){let S=h;do{let A=S.next.next;for(;A!==S.prev;){if(S.i!==A.i&&lz(S,A)){let I=pR(S,A);return S=Gg(S,S.next),I=Gg(I,I.next),D0(S,o,u,m,x,b,0),void D0(I,o,u,m,x,b,0)}A=A.next}S=S.next}while(S!==h)}function oz(h,o){let u=h.x-o.x;return u===0&&(u=h.y-o.y,u===0)&&(u=(h.next.y-h.y)/(h.next.x-h.x)-(o.next.y-o.y)/(o.next.x-o.x)),u}function fR(h,o){const u=function(x,b){let S=b;const A=x.x,I=x.y;let D,B=-1/0;if(Vx(x,S))return S;do{if(Vx(x,S.next))return S.next;if(I<=S.y&&I>=S.next.y&&S.next.y!==S.y){const J=S.x+(I-S.y)*(S.next.x-S.x)/(S.next.y-S.y);if(J<=A&&J>B&&(B=J,D=S.x=S.x&&S.x>=q&&A!==S.x&&M0(ID.x||S.x===D.x&&mR(D,S)))&&(D=S,X=J)}S=S.next}while(S!==U);return D}(h,o);if(!u)return o;const m=pR(u,h);return Gg(m,m.next),Gg(u,u.next)}function mR(h,o){return go(h.prev,h,o.prev)<0&&go(o.next,h,h.next)<0}function B2(h,o,u,m,x){return(h=1431655765&((h=858993459&((h=252645135&((h=16711935&((h=(h-u)*x|0)|h<<8))|h<<4))|h<<2))|h<<1))|(o=1431655765&((o=858993459&((o=252645135&((o=16711935&((o=(o-m)*x|0)|o<<8))|o<<4))|o<<2))|o<<1))<<1}function z2(h){let o=h,u=h;do(o.x=(h-S)*(b-A)&&(h-S)*(m-A)>=(u-S)*(o-A)&&(u-S)*(b-A)>=(x-S)*(m-A)}function Ux(h,o,u,m,x,b,S,A){return!(h===S&&o===A)&&M0(h,o,u,m,x,b,S,A)}function lz(h,o){return h.next.i!==o.i&&h.prev.i!==o.i&&!function(u,m){let x=u;do{if(x.i!==u.i&&x.next.i!==u.i&&x.i!==m.i&&x.next.i!==m.i&&N1(x,x.next,u,m))return!0;x=x.next}while(x!==u);return!1}(h,o)&&(O0(h,o)&&O0(o,h)&&function(u,m){let x=u,b=!1;const S=(u.x+m.x)/2,A=(u.y+m.y)/2;do x.y>A!=x.next.y>A&&x.next.y!==x.y&&S<(x.next.x-x.x)*(A-x.y)/(x.next.y-x.y)+x.x&&(b=!b),x=x.next;while(x!==u);return b}(h,o)&&(go(h.prev,h,o.prev)||go(h,o.prev,o))||Vx(h,o)&&go(h.prev,h,h.next)>0&&go(o.prev,o,o.next)>0)}function go(h,o,u){return(o.y-h.y)*(u.x-o.x)-(o.x-h.x)*(u.y-o.y)}function Vx(h,o){return h.x===o.x&&h.y===o.y}function N1(h,o,u,m){const x=L1(go(h,o,u)),b=L1(go(h,o,m)),S=L1(go(u,m,h)),A=L1(go(u,m,o));return x!==b&&S!==A||!(x!==0||!R1(h,u,o))||!(b!==0||!R1(h,m,o))||!(S!==0||!R1(u,h,m))||!(A!==0||!R1(u,o,m))}function R1(h,o,u){return o.x<=Math.max(h.x,u.x)&&o.x>=Math.min(h.x,u.x)&&o.y<=Math.max(h.y,u.y)&&o.y>=Math.min(h.y,u.y)}function L1(h){return h>0?1:h<0?-1:0}function O0(h,o){return go(h.prev,h,h.next)<0?go(h,o,h.next)>=0&&go(h,h.prev,o)>=0:go(h,o,h.prev)<0||go(h,h.next,o)<0}function pR(h,o){const u=U2(h.i,h.x,h.y),m=U2(o.i,o.x,o.y),x=h.next,b=o.prev;return h.next=o,o.prev=h,u.next=x,x.prev=u,m.next=u,u.prev=m,b.next=m,m.prev=b,m}function $2(h,o,u,m){const x=U2(h,o,u);return m?(x.next=m.next,x.prev=m,m.next.prev=x,m.next=x):(x.prev=x,x.next=x),x}function F0(h){h.next.prev=h.prev,h.prev.next=h.next,h.prevZ&&(h.prevZ.nextZ=h.nextZ),h.nextZ&&(h.nextZ.prevZ=h.prevZ)}function U2(h,o,u){return{i:h,x:o,y:u,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function gR(h,o,u=1){if(!h)return null;const m=typeof h=="string"?Ol.from(h).getPrimary():h.getPrimary(),x=typeof h=="string"?null:h.getSecondary();for(const b of[m,x]){if(!b)continue;const S=b.id.toString();o.has(S)||o.set(S,[]),b.scaleSelf(u),o.get(S).push(b)}return{primary:m.toString(),secondary:x?x.toString():null}}function V2(h,o,u,m){const x=m.patternDependencies;let b=!1;for(const S of o){const A=S.paint.get(`${h}-pattern`);A.isConstant()||(b=!0),gR(A.constantOr(null),x,u)&&(b=!0)}return b}function q2(h,o,u,m,x,b){const S=b.patternDependencies;for(const A of o){const I=A.paint.get(`${h}-pattern`).value;if(I.kind!=="constant"){const D=gR(I.evaluate({zoom:m},u,{},void 0,b.availableImages),S,x);if(!D)continue;const{primary:B,secondary:U}=D;B&&(u.patterns[A.id]=[B,U].filter(Boolean))}}return u}const Hc=ar/Math.PI/2,Hg=64,G2=[Hg,32,16],Xd=-Hc,gu=Hc;function qx(h,o,u,m=Hc){return u=Bn(u),[h*Math.sin(u)*m,-o*m,h*Math.cos(u)*m]}function Wg(h,o,u){return qx(Math.cos(Bn(h)),Math.sin(Bn(h)),o,u)}const fm=63710088e-1,H2=2*Math.PI*fm;class pi{constructor(o,u){if(isNaN(o)||isNaN(u))throw new Error(`Invalid LngLat object: (${o}, ${u})`);if(this.lng=+o,this.lat=+u,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new pi(uu(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(o){const u=Math.PI/180,m=this.lat*u,x=o.lat*u,b=Math.sin(m)*Math.sin(x)+Math.cos(m)*Math.cos(x)*Math.cos((o.lng-this.lng)*u);return fm*Math.acos(Math.min(b,1))}toBounds(o=0){const u=360*o/40075017,m=u/Math.cos(Math.PI/180*this.lat);return new Qd({lng:this.lng-m,lat:this.lat-u},{lng:this.lng+m,lat:this.lat+u})}toEcef(o){return Wg(this.lat,this.lng,Hc+o*Hc/fm)}static convert(o){if(o instanceof pi)return o;if(Array.isArray(o)&&(o.length===2||o.length===3))return new pi(Number(o[0]),Number(o[1]));if(!Array.isArray(o)&&typeof o=="object"&&o!==null)return new pi(Number("lng"in o?o.lng:o.lon),Number(o.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}class Qd{constructor(o,u){o&&(u?this.setSouthWest(o).setNorthEast(u):Array.isArray(o)&&o.length===4?this.setSouthWest([o[0],o[1]]).setNorthEast([o[2],o[3]]):this.setSouthWest(o[0]).setNorthEast(o[1]))}setNorthEast(o){return this._ne=o instanceof pi?new pi(o.lng,o.lat):pi.convert(o),this}setSouthWest(o){return this._sw=o instanceof pi?new pi(o.lng,o.lat):pi.convert(o),this}extend(o){const u=this._sw,m=this._ne;let x,b;if(o instanceof pi)x=o,b=o;else{if(!(o instanceof Qd))return Array.isArray(o)?o.length===4||o.every(Array.isArray)?this.extend(Qd.convert(o)):this.extend(pi.convert(o)):typeof o=="object"&&o!==null&&Object.hasOwn(o,"lat")&&(Object.hasOwn(o,"lon")||Object.hasOwn(o,"lng"))?this.extend(pi.convert(o)):this;if(x=o._sw,b=o._ne,!x||!b)return this}return u||m?(u.lng=Math.min(x.lng,u.lng),u.lat=Math.min(x.lat,u.lat),m.lng=Math.max(b.lng,m.lng),m.lat=Math.max(b.lat,m.lat)):(this._sw=new pi(x.lng,x.lat),this._ne=new pi(b.lng,b.lat)),this}getCenter(){return new pi((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new pi(this.getWest(),this.getNorth())}getSouthEast(){return new pi(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(o){const{lng:u,lat:m}=pi.convert(o);let x=this._sw.lng<=u&&u<=this._ne.lng;return this._sw.lng>this._ne.lng&&(x=this._sw.lng>=u&&u>=this._ne.lng),this._sw.lat<=m&&m<=this._ne.lat&&x}static convert(o){if(o)return o instanceof Qd?o:new Qd(o)}}function D1(h){return H2*Math.cos(h*Math.PI/180)}function ks(h,o){return h/D1(o)}function M1(h,o){return h*D1(Fa(o))}const wc=85.051129;function yR(h){return Math.cos(Bn(cn(h,-85.051129,wc)))}function bf(h,o){const u=cn(o,0,25.5),m=Math.pow(2,u);return yR(h)*H2/(512*m)}function W2(h){return 1/Math.cos(h*Math.PI/180)}function Wc(h,o=0){const u=Math.exp(Math.PI*(1-(h.y+o/ar)/(1<=I?(K2(h,o,u,D,B,b,U,A,I),K2(h,D,B,m,x,U,S,A,I)):h.push(S)}function xR(h,o,u){let m=h[0],x=m.x,b=m.y;o(m);const S=[m];for(let A=1;Ah.x+1||mh.y+1)&&Xi("Geometry exceeds allowed extent, reduce your vector tile buffer size"),h}function xd(h,o,u){const m=h.loadGeometry(),x=h.extent,b=ar/x;if(o&&u&&u.projection.isReprojectedInTileSpace){const S=1<{const K=Jl((o.x+q.x/x)/S),X=Fa((o.y+q.y/x)/S),J=B.project(K,X);q.x=(J.x*A-I)*x,q.y=(J.y*A-D)*x};for(let q=0;q=x||X.y<0||X.y>=x||(U(X),K.push(X));m[q]=K}}for(const S of m)for(const A of S)uz(A,b);return m}function Ch(h,o,u,m,x){return u&&!x.projection.isReprojectedInTileSpace?o.geometry:xd(h,m,x)}function Ph(h,o){return{type:h.type,id:h.id,properties:h.properties,geometry:o?xd(h):[]}}const B1={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class B0{constructor(o,u){this._structArray=o,this._pos1=u*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const Gx=new ArrayBuffer(0);class ls{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(o,u){return o._trim(),u&&o.arrayBuffer&&u.add(o.arrayBuffer),{length:o.length,arrayBuffer:o.arrayBuffer}}static deserialize(o){const u=Object.create(this.prototype);return u.arrayBuffer=o.arrayBuffer,u.length=o.length,o.arrayBuffer?u.capacity=o.arrayBuffer.byteLength/u.bytesPerElement:(u.capacity=0,u.arrayBuffer=Gx),u._refreshViews(),u}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(o){this.reserve(o),this.length=o}resizeExact(o){this.reserveExact(o),this.length=o}reserve(o){o>this.capacity&&this._allocate(Math.max(o,Math.floor(5*this.capacity),128))}reserveExact(o){(o>this.capacity||!this.arrayBuffer)&&this._allocate(o)}_allocate(o){this._reallocCount++,this.capacity=o,this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const u=this.uint8;this._refreshViews(),u&&this.uint8.set(u)}reserveForAdditional(o){this.reserve(this.length+o)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...o){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...o){throw new Error("StructArray#emplaceBack() must be implemented by each concrete StructArray layout")}destroy(){this.int8=this.uint8=this.int16=this.uint16=this.int32=this.uint32=this.float32=null,this.arrayBuffer=null}}function Gn(h,o=1){let u=0,m=0;return{members:h.map(x=>{const b=B1[x.type].BYTES_PER_ELEMENT,S=u=_R(u,Math.max(o,b)),A=x.components||1;return m=Math.max(m,b),u+=b*A,{name:x.name,type:x.type,components:A,offset:S,normalized:x.normalized}}),size:_R(u,Math.max(m,o)),alignment:o}}function _R(h,o){return Math.ceil(h/o)*o}class mm extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(o,u){const m=this.length;return this.resize(m+1),this.emplace(m,o,u)}emplace(o,u,m){const x=2*o;return this.int16[x+0]=u,this.int16[x+1]=m,o}}mm.prototype.bytesPerElement=4,vr(mm,"StructArrayLayout2i4");class z0 extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(o,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,o,u,m)}emplace(o,u,m,x){const b=3*o;return this.int16[b+0]=u,this.int16[b+1]=m,this.int16[b+2]=x,o}}z0.prototype.bytesPerElement=6,vr(z0,"StructArrayLayout3i6");class z1 extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(o,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,o,u,m,x)}emplace(o,u,m,x,b){const S=4*o;return this.int16[S+0]=u,this.int16[S+1]=m,this.uint16[S+2]=x,this.uint16[S+3]=b,o}}z1.prototype.bytesPerElement=8,vr(z1,"StructArrayLayout2i2ui8");class Hu extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o){const u=this.length;return this.resize(u+1),this.emplace(u,o)}emplace(o,u){return this.float32[1*o+0]=u,o}}Hu.prototype.bytesPerElement=4,vr(Hu,"StructArrayLayout1f4");class vR extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,o,u,m)}emplace(o,u,m,x){const b=4*o,S=2*o;return this.int16[b+0]=u,this.int16[b+1]=m,this.float32[S+1]=x,o}}vR.prototype.bytesPerElement=8,vr(vR,"StructArrayLayout2i1f8");class _ extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(o,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,o,u,m)}emplace(o,u,m,x){const b=4*o;return this.int16[b+0]=u,this.int16[b+1]=m,this.int16[b+2]=x,o}}_.prototype.bytesPerElement=8,vr(_,"StructArrayLayout3i8");class f extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(o,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,o,u,m,x)}emplace(o,u,m,x,b){const S=4*o;return this.int16[S+0]=u,this.int16[S+1]=m,this.int16[S+2]=x,this.int16[S+3]=b,o}}f.prototype.bytesPerElement=8,vr(f,"StructArrayLayout4i8");class y extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,o,u,m,x,b)}emplace(o,u,m,x,b,S){const A=5*o;return this.int16[A+0]=u,this.int16[A+1]=m,this.int16[A+2]=x,this.int16[A+3]=b,this.int16[A+4]=S,o}}y.prototype.bytesPerElement=10,vr(y,"StructArrayLayout5i10");class w extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S,A,I){const D=this.length;return this.resize(D+1),this.emplace(D,o,u,m,x,b,S,A,I)}emplace(o,u,m,x,b,S,A,I,D){const B=8*o,U=16*o,q=4*o;return this.int16[B+0]=u,this.int16[B+1]=m,this.uint8[U+4]=x,this.uint8[U+5]=b,this.uint8[U+6]=S,this.uint8[U+7]=A,this.float32[q+2]=I,this.float32[q+3]=D,o}}w.prototype.bytesPerElement=16,vr(w,"StructArrayLayout2i4ub1f1f16");class k extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,o,u,m)}emplace(o,u,m,x){const b=3*o;return this.float32[b+0]=u,this.float32[b+1]=m,this.float32[b+2]=x,o}}k.prototype.bytesPerElement=12,vr(k,"StructArrayLayout3f12");class R extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,o,u,m,x,b)}emplace(o,u,m,x,b,S){const A=6*o,I=3*o;return this.uint16[A+0]=u,this.uint16[A+1]=m,this.uint16[A+2]=x,this.uint16[A+3]=b,this.float32[I+2]=S,o}}R.prototype.bytesPerElement=12,vr(R,"StructArrayLayout4ui1f12");class M extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(o,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,o,u,m,x)}emplace(o,u,m,x,b){const S=4*o;return this.uint16[S+0]=u,this.uint16[S+1]=m,this.uint16[S+2]=x,this.uint16[S+3]=b,o}}M.prototype.bytesPerElement=8,vr(M,"StructArrayLayout4ui8");class z extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S){const A=this.length;return this.resize(A+1),this.emplace(A,o,u,m,x,b,S)}emplace(o,u,m,x,b,S,A){const I=6*o;return this.int16[I+0]=u,this.int16[I+1]=m,this.int16[I+2]=x,this.int16[I+3]=b,this.int16[I+4]=S,this.int16[I+5]=A,o}}z.prototype.bytesPerElement=12,vr(z,"StructArrayLayout6i12");class V extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S,A,I,D,B,U,q){const K=this.length;return this.resize(K+1),this.emplace(K,o,u,m,x,b,S,A,I,D,B,U,q)}emplace(o,u,m,x,b,S,A,I,D,B,U,q,K){const X=12*o;return this.int16[X+0]=u,this.int16[X+1]=m,this.int16[X+2]=x,this.int16[X+3]=b,this.uint16[X+4]=S,this.uint16[X+5]=A,this.uint16[X+6]=I,this.uint16[X+7]=D,this.int16[X+8]=B,this.int16[X+9]=U,this.int16[X+10]=q,this.int16[X+11]=K,o}}V.prototype.bytesPerElement=24,vr(V,"StructArrayLayout4i4ui4i24");class H extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S){const A=this.length;return this.resize(A+1),this.emplace(A,o,u,m,x,b,S)}emplace(o,u,m,x,b,S,A){const I=10*o,D=5*o;return this.int16[I+0]=u,this.int16[I+1]=m,this.int16[I+2]=x,this.float32[D+2]=b,this.float32[D+3]=S,this.float32[D+4]=A,o}}H.prototype.bytesPerElement=20,vr(H,"StructArrayLayout3i3f20");class Y extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,o,u,m,x)}emplace(o,u,m,x,b){const S=4*o;return this.float32[S+0]=u,this.float32[S+1]=m,this.float32[S+2]=x,this.float32[S+3]=b,o}}Y.prototype.bytesPerElement=16,vr(Y,"StructArrayLayout4f16");class te extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(o){const u=this.length;return this.resize(u+1),this.emplace(u,o)}emplace(o,u){return this.uint32[1*o+0]=u,o}}te.prototype.bytesPerElement=4,vr(te,"StructArrayLayout1ul4");class ne extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int32=new Int32Array(this.arrayBuffer)}emplaceBack(o,u){const m=this.length;return this.resize(m+1),this.emplace(m,o,u)}emplace(o,u,m){const x=2*o;return this.int32[x+0]=u,this.int32[x+1]=m,o}}ne.prototype.bytesPerElement=8,vr(ne,"StructArrayLayout2l8");class le extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(o,u){const m=this.length;return this.resize(m+1),this.emplace(m,o,u)}emplace(o,u,m){const x=2*o;return this.uint16[x+0]=u,this.uint16[x+1]=m,o}}le.prototype.bytesPerElement=4,vr(le,"StructArrayLayout2ui4");class me extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S,A,I,D,B,U,q,K){const X=this.length;return this.resize(X+1),this.emplace(X,o,u,m,x,b,S,A,I,D,B,U,q,K)}emplace(o,u,m,x,b,S,A,I,D,B,U,q,K,X){const J=20*o,se=10*o;return this.int16[J+0]=u,this.int16[J+1]=m,this.int16[J+2]=x,this.int16[J+3]=b,this.int16[J+4]=S,this.float32[se+3]=A,this.float32[se+4]=I,this.float32[se+5]=D,this.float32[se+6]=B,this.int16[J+14]=U,this.uint32[se+8]=q,this.uint16[J+18]=K,this.uint16[J+19]=X,o}}me.prototype.bytesPerElement=40,vr(me,"StructArrayLayout5i4f1i1ul2ui40");class fe extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S,A){const I=this.length;return this.resize(I+1),this.emplace(I,o,u,m,x,b,S,A)}emplace(o,u,m,x,b,S,A,I){const D=8*o;return this.int16[D+0]=u,this.int16[D+1]=m,this.int16[D+2]=x,this.int16[D+4]=b,this.int16[D+5]=S,this.int16[D+6]=A,this.int16[D+7]=I,o}}fe.prototype.bytesPerElement=16,vr(fe,"StructArrayLayout3i2i2i16");class Se extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,o,u,m,x,b)}emplace(o,u,m,x,b,S){const A=4*o,I=8*o;return this.float32[A+0]=u,this.float32[A+1]=m,this.float32[A+2]=x,this.int16[I+6]=b,this.int16[I+7]=S,o}}Se.prototype.bytesPerElement=16,vr(Se,"StructArrayLayout2f1f2i16");class Me extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S,A){const I=this.length;return this.resize(I+1),this.emplace(I,o,u,m,x,b,S,A)}emplace(o,u,m,x,b,S,A,I){const D=6*o,B=12*o;return this.float32[D+0]=u,this.float32[D+1]=m,this.float32[D+2]=x,this.float32[D+3]=b,this.float32[D+4]=S,this.int16[B+10]=A,this.int16[B+11]=I,o}}Me.prototype.bytesPerElement=24,vr(Me,"StructArrayLayout2f2f1f2i24");class qe extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S){const A=this.length;return this.resize(A+1),this.emplace(A,o,u,m,x,b,S)}emplace(o,u,m,x,b,S,A){const I=20*o,D=5*o;return this.uint8[I+0]=u,this.uint8[I+1]=m,this.float32[D+1]=x,this.float32[D+2]=b,this.float32[D+3]=S,this.float32[D+4]=A,o}}qe.prototype.bytesPerElement=20,vr(qe,"StructArrayLayout2ub4f20");class Ne extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(o,u,m){const x=this.length;return this.resize(x+1),this.emplace(x,o,u,m)}emplace(o,u,m,x){const b=3*o;return this.uint16[b+0]=u,this.uint16[b+1]=m,this.uint16[b+2]=x,o}}Ne.prototype.bytesPerElement=6,vr(Ne,"StructArrayLayout3ui6");class We extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae,ue,ce,de,xe){const ve=this.length;return this.resize(ve+1),this.emplace(ve,o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae,ue,ce,de,xe)}emplace(o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae,ue,ce,de,xe,ve){const Ue=30*o,Pe=15*o,De=60*o;return this.int16[Ue+0]=u,this.int16[Ue+1]=m,this.int16[Ue+2]=x,this.float32[Pe+2]=b,this.float32[Pe+3]=S,this.uint16[Ue+8]=A,this.uint16[Ue+9]=I,this.uint32[Pe+5]=D,this.uint32[Pe+6]=B,this.uint32[Pe+7]=U,this.uint16[Ue+16]=q,this.uint16[Ue+17]=K,this.uint16[Ue+18]=X,this.float32[Pe+10]=J,this.float32[Pe+11]=se,this.uint8[De+48]=ae,this.uint8[De+49]=ue,this.uint8[De+50]=ce,this.uint32[Pe+13]=de,this.int16[Ue+28]=xe,this.uint8[De+58]=ve,o}}We.prototype.bytesPerElement=60,vr(We,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class ct extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae,ue,ce,de,xe,ve,Ue,Pe,De,Ve,Fe,Ze,st,ut,ht,_t,Et){const Pt=this.length;return this.resize(Pt+1),this.emplace(Pt,o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae,ue,ce,de,xe,ve,Ue,Pe,De,Ve,Fe,Ze,st,ut,ht,_t,Et)}emplace(o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae,ue,ce,de,xe,ve,Ue,Pe,De,Ve,Fe,Ze,st,ut,ht,_t,Et,Pt){const Rt=20*o,Ye=40*o,At=80*o;return this.float32[Rt+0]=u,this.float32[Rt+1]=m,this.int16[Ye+4]=x,this.int16[Ye+5]=b,this.int16[Ye+6]=S,this.int16[Ye+7]=A,this.int16[Ye+8]=I,this.int16[Ye+9]=D,this.int16[Ye+10]=B,this.int16[Ye+11]=U,this.int16[Ye+12]=q,this.uint16[Ye+13]=K,this.uint16[Ye+14]=X,this.uint16[Ye+15]=J,this.uint16[Ye+16]=se,this.uint16[Ye+17]=ae,this.uint16[Ye+18]=ue,this.uint16[Ye+19]=ce,this.uint16[Ye+20]=de,this.uint16[Ye+21]=xe,this.uint16[Ye+22]=ve,this.uint16[Ye+23]=Ue,this.uint16[Ye+24]=Pe,this.uint16[Ye+25]=De,this.uint16[Ye+26]=Ve,this.uint16[Ye+27]=Fe,this.uint32[Rt+14]=Ze,this.float32[Rt+15]=st,this.float32[Rt+16]=ut,this.float32[Rt+17]=ht,this.float32[Rt+18]=_t,this.uint8[At+76]=Et,this.uint16[Ye+39]=Pt,o}}ct.prototype.bytesPerElement=80,vr(ct,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class it extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S){const A=this.length;return this.resize(A+1),this.emplace(A,o,u,m,x,b,S)}emplace(o,u,m,x,b,S,A){const I=6*o;return this.float32[I+0]=u,this.float32[I+1]=m,this.float32[I+2]=x,this.float32[I+3]=b,this.float32[I+4]=S,this.float32[I+5]=A,o}}it.prototype.bytesPerElement=24,vr(it,"StructArrayLayout6f24");class pt extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b){const S=this.length;return this.resize(S+1),this.emplace(S,o,u,m,x,b)}emplace(o,u,m,x,b,S){const A=5*o;return this.float32[A+0]=u,this.float32[A+1]=m,this.float32[A+2]=x,this.float32[A+3]=b,this.float32[A+4]=S,o}}pt.prototype.bytesPerElement=20,vr(pt,"StructArrayLayout5f20");class dt extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S,A){const I=this.length;return this.resize(I+1),this.emplace(I,o,u,m,x,b,S,A)}emplace(o,u,m,x,b,S,A,I){const D=7*o;return this.float32[D+0]=u,this.float32[D+1]=m,this.float32[D+2]=x,this.float32[D+3]=b,this.float32[D+4]=S,this.float32[D+5]=A,this.float32[D+6]=I,o}}dt.prototype.bytesPerElement=28,vr(dt,"StructArrayLayout7f28");class mt extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S,A,I,D,B,U){const q=this.length;return this.resize(q+1),this.emplace(q,o,u,m,x,b,S,A,I,D,B,U)}emplace(o,u,m,x,b,S,A,I,D,B,U,q){const K=11*o;return this.float32[K+0]=u,this.float32[K+1]=m,this.float32[K+2]=x,this.float32[K+3]=b,this.float32[K+4]=S,this.float32[K+5]=A,this.float32[K+6]=I,this.float32[K+7]=D,this.float32[K+8]=B,this.float32[K+9]=U,this.float32[K+10]=q,o}}mt.prototype.bytesPerElement=44,vr(mt,"StructArrayLayout11f44");class xt extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S,A,I,D){const B=this.length;return this.resize(B+1),this.emplace(B,o,u,m,x,b,S,A,I,D)}emplace(o,u,m,x,b,S,A,I,D,B){const U=9*o;return this.float32[U+0]=u,this.float32[U+1]=m,this.float32[U+2]=x,this.float32[U+3]=b,this.float32[U+4]=S,this.float32[U+5]=A,this.float32[U+6]=I,this.float32[U+7]=D,this.float32[U+8]=B,o}}xt.prototype.bytesPerElement=36,vr(xt,"StructArrayLayout9f36");class bt extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u){const m=this.length;return this.resize(m+1),this.emplace(m,o,u)}emplace(o,u,m){const x=2*o;return this.float32[x+0]=u,this.float32[x+1]=m,o}}bt.prototype.bytesPerElement=8,vr(bt,"StructArrayLayout2f8");class Ft extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(o,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,o,u,m,x)}emplace(o,u,m,x,b){const S=6*o;return this.uint32[3*o+0]=u,this.uint16[S+2]=m,this.uint16[S+3]=x,this.uint16[S+4]=b,o}}Ft.prototype.bytesPerElement=12,vr(Ft,"StructArrayLayout1ul3ui12");class Lt extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(o){const u=this.length;return this.resize(u+1),this.emplace(u,o)}emplace(o,u){return this.uint16[1*o+0]=u,o}}Lt.prototype.bytesPerElement=2,vr(Lt,"StructArrayLayout1ui2");class Mt extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int8=new Int8Array(this.arrayBuffer)}emplaceBack(o,u,m,x){const b=this.length;return this.resize(b+1),this.emplace(b,o,u,m,x)}emplace(o,u,m,x,b){const S=4*o;return this.int8[S+0]=u,this.int8[S+1]=m,this.int8[S+2]=x,this.int8[S+3]=b,o}}Mt.prototype.bytesPerElement=4,vr(Mt,"StructArrayLayout4b4");class or extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se){const ae=this.length;return this.resize(ae+1),this.emplace(ae,o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se)}emplace(o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae){const ue=16*o;return this.float32[ue+0]=u,this.float32[ue+1]=m,this.float32[ue+2]=x,this.float32[ue+3]=b,this.float32[ue+4]=S,this.float32[ue+5]=A,this.float32[ue+6]=I,this.float32[ue+7]=D,this.float32[ue+8]=B,this.float32[ue+9]=U,this.float32[ue+10]=q,this.float32[ue+11]=K,this.float32[ue+12]=X,this.float32[ue+13]=J,this.float32[ue+14]=se,this.float32[ue+15]=ae,o}}or.prototype.bytesPerElement=64,vr(or,"StructArrayLayout16f64");class fr extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(o){const u=this.length;return this.resize(u+1),this.emplace(u,o)}emplace(o,u){return this.int16[1*o+0]=u,o}}fr.prototype.bytesPerElement=2,vr(fr,"StructArrayLayout1i2");class Cr extends ls{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(o){const u=this.length;return this.resize(u+1),this.emplace(u,o)}emplace(o,u){return this.uint8[1*o+0]=u,o}}Cr.prototype.bytesPerElement=1,vr(Cr,"StructArrayLayout1ub1");class qr extends B0{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.int16[this._pos2+3]}get tileAnchorY(){return this._structArray.int16[this._pos2+4]}get x1(){return this._structArray.float32[this._pos4+3]}get y1(){return this._structArray.float32[this._pos4+4]}get x2(){return this._structArray.float32[this._pos4+5]}get y2(){return this._structArray.float32[this._pos4+6]}get padding(){return this._structArray.int16[this._pos2+14]}get featureIndex(){return this._structArray.uint32[this._pos4+8]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+18]}get bucketIndex(){return this._structArray.uint16[this._pos2+19]}}qr.prototype.size=40;class qt extends me{get(o){return new qr(this,o)}}vr(qt,"CollisionBoxArray");class Ut extends B0{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.float32[this._pos4+2]}get tileAnchorY(){return this._structArray.float32[this._pos4+3]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+8]}get numGlyphs(){return this._structArray.uint16[this._pos2+9]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+5]}get lineStartIndex(){return this._structArray.uint32[this._pos4+6]}get lineLength(){return this._structArray.uint32[this._pos4+7]}get segment(){return this._structArray.uint16[this._pos2+16]}get lowerSize(){return this._structArray.uint16[this._pos2+17]}get upperSize(){return this._structArray.uint16[this._pos2+18]}get lineOffsetX(){return this._structArray.float32[this._pos4+10]}get lineOffsetY(){return this._structArray.float32[this._pos4+11]}get writingMode(){return this._structArray.uint8[this._pos1+48]}get placedOrientation(){return this._structArray.uint8[this._pos1+49]}set placedOrientation(o){this._structArray.uint8[this._pos1+49]=o}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(o){this._structArray.uint8[this._pos1+50]=o}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(o){this._structArray.uint32[this._pos4+13]=o}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(o){this._structArray.uint8[this._pos1+58]=o}}Ut.prototype.size=60;class gr extends We{get(o){return new Ut(this,o)}}vr(gr,"PlacedSymbolArray");class Pr extends B0{get tileAnchorX(){return this._structArray.float32[this._pos4+0]}get tileAnchorY(){return this._structArray.float32[this._pos4+1]}get projectedAnchorX(){return this._structArray.int16[this._pos2+4]}get projectedAnchorY(){return this._structArray.int16[this._pos2+5]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+6]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+7]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+8]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+9]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+10]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+11]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+12]}get key(){return this._structArray.uint16[this._pos2+13]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+14]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+15]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+16]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+17]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+18]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+19]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+20]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+21]}get featureIndex(){return this._structArray.uint16[this._pos2+22]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+23]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+24]}get numIconVertices(){return this._structArray.uint16[this._pos2+25]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+26]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+27]}get crossTileID(){return this._structArray.uint32[this._pos4+14]}set crossTileID(o){this._structArray.uint32[this._pos4+14]=o}get textOffset0(){return this._structArray.float32[this._pos4+15]}get textOffset1(){return this._structArray.float32[this._pos4+16]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+17]}get zOffset(){return this._structArray.float32[this._pos4+18]}set zOffset(o){this._structArray.float32[this._pos4+18]=o}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}Pr.prototype.size=80;class ur extends ct{get(o){return new Pr(this,o)}}vr(ur,"SymbolInstanceArray");class Xt extends Hu{getoffsetX(o){return this.float32[1*o+0]}}vr(Xt,"GlyphOffsetArray");class mr extends mm{getx(o){return this.int16[2*o+0]}gety(o){return this.int16[2*o+1]}}vr(mr,"SymbolLineVertexArray");class tn extends B0{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}get layoutVertexArrayOffset(){return this._structArray.uint16[this._pos2+4]}}tn.prototype.size=12;class kr extends Ft{get(o){return new tn(this,o)}}vr(kr,"FeatureIndexArray");class vn extends le{geta_centroid_pos0(o){return this.uint16[2*o+0]}geta_centroid_pos1(o){return this.uint16[2*o+1]}}vr(vn,"FillExtrusionCentroidArray");class Xr extends B0{get a_join_normal_inside0(){return this._structArray.int16[this._pos2+0]}get a_join_normal_inside1(){return this._structArray.int16[this._pos2+1]}get a_join_normal_inside2(){return this._structArray.int16[this._pos2+2]}}Xr.prototype.size=6;class ei extends z0{get(o){return new Xr(this,o)}}vr(ei,"FillExtrusionWallArray");const Rn=Gn([{name:"a_pos",components:2,type:"Int16"}],4),Ni=Gn([{name:"a_road_z_offset",components:1,type:"Float32"}],4),zn=Gn([{name:"a_pos",components:2,type:"Int16"},{name:"a_height",components:1,type:"Float32"}],4),Qi=Gn([{name:"a_pos_normal_3",components:3,type:"Int16"}],4);class xn{constructor(o=[]){this.segments=o}_prepareSegment(o,u,m,x,b){let S=this.segments.at(-1);return o>xn.MAX_VERTEX_ARRAY_LENGTH&&Xi(`Max vertices per segment is ${xn.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${o}`),(!S||S.vertexLength+o>xn.MAX_VERTEX_ARRAY_LENGTH||S.sortKey!==x||b!==void 0&&S&&S.batchIndex!==void 0&&S.batchIndex!==b)&&(S={vertexOffset:u,primitiveOffset:m,vertexLength:0,primitiveLength:0},x!==void 0&&(S.sortKey=x),b!==void 0&&(S.batchIndex=b),this.segments.push(S)),S}prepareSegment(o,u,m,x,b){return this._prepareSegment(o,u.length,m.length,x,b)}get(){return this.segments}destroy(){for(const o of this.segments)for(const u in o.vaos)for(const m of o.vaos[u].values())m.destroy()}static simpleSegment(o,u,m,x){return new xn([{vertexOffset:o,primitiveOffset:u,vertexLength:m,primitiveLength:x,vaos:{},sortKey:0}])}}function Sn(h,o){return 256*(h=cn(Math.floor(h),0,255))+cn(Math.floor(o),0,255)}xn.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,vr(xn,"SegmentVector");const Dn=Gn([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),Ks=Gn([{name:"a_pattern_b",components:4,type:"Uint16"}]),ya=Gn([{name:"a_dash",components:4,type:"Uint16"}]);class Ti{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(o,u,m,x){this.ids.push(Ba(o)),this.positions.push(u,m,x)}eachPosition(o,u){const m=Ba(o);let x=0,b=this.ids.length-1;for(;x>1;this.ids[A]>=m?b=A:x=A+1}const S=this.ids[x]===m;for(;this.ids[x]===m;)u(this.positions[3*x],this.positions[3*x+1],this.positions[3*x+2]),x++;return S}static serialize(o,u){if(o.ids.length===0)return{};const m=new Float64Array(o.ids),x=new Uint32Array(o.positions);return bs(m,x,0,m.length-1),u&&(u.add(m.buffer),u.add(x.buffer)),{ids:m,positions:x}}static deserialize(o){const u=new Ti;let m;u.ids=o.ids||[],u.positions=o.positions||[];for(const x of u.ids)x!==m&&u.uniqueIds.push(x),m=x;return u.indexed=!0,u}}function Ba(h){const o=+h;return Number.isSafeInteger(o)?o:Kl(String(h))}function bs(h,o,u,m){for(;u>1];let b=u-1,S=m+1;for(;;){do b++;while(h[b]x);if(b>=S)break;Ri(h,b,S),Ri(o,3*b,3*S),Ri(o,3*b+1,3*S+1),Ri(o,3*b+2,3*S+2)}S-u`u_${b}`),this.type=m.property.specification.type,x&&(this.lutExpression=x.value)}static serialize(){return null}setUniform(o,u,m,x,b){const S=x.constantOr(this.value);u.set(o,b,S instanceof Vn?S.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):S)}getBinding(o,u){return this.type==="color"?new yu(o):new Dr(o)}}class na{constructor(o){this.uniformNames=o.map(u=>`u_${u}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(o,u){this.pixelRatio=o.pixelRatio||1,this.pattern=o.tl.concat(o.br),this.patternTransition=u?u.tl.concat(u.br):this.pattern}setUniform(o,u,m,x,b){let S=null;b!=="u_pattern"&&b!=="u_dash"||(S=this.pattern),b==="u_pattern_b"&&(S=this.patternTransition),b==="u_pixel_ratio"&&(S=this.pixelRatio),S&&u.set(o,b,S)}getBinding(o,u){return u==="u_pattern"||u==="u_pattern_b"||u==="u_dash"?new Ya(o):new Dr(o)}}class Ls{constructor(o,u,m,x){this.expression=o,this.type=m,this.maxValue=0,this.paintVertexAttributes=u.map(b=>({name:`a_${b}`,type:"Float32",components:m==="color"?2:1,offset:0})),this.paintVertexArray=new x}populatePaintArray(o,u,m,x,b,S,A,I){const D=this.paintVertexArray.length,B=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new Hs(0,{brightness:S,worldview:I}),u,{},b,x,A):this.expression.kind==="constant"&&this.expression.value,U=Ii(this.lutExpression,u,{},x,b,S,A,I);this.paintVertexArray.resize(o),this._setPaintValue(D,o,B,U?null:this.context.lut)}updatePaintArray(o,u,m,x,b,S,A,I){const D=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:A,worldview:I},m,x,void 0,b):this.expression.kind==="constant"&&this.expression.value,B=Ii(this.lutExpression,m,x,b,void 0,A,void 0,I);this._setPaintValue(o,u,D,B?null:this.context.lut)}_setPaintValue(o,u,m,x){if(this.type==="color"){const b=Ji(m.toPremultipliedRenderColor(x));for(let S=o;S`u_${S}_t`),this.type=m,this.useIntegerZoom=x,this.maxValue=0,this.paintVertexAttributes=u.map(S=>({name:`a_${S}`,type:"Float32",components:m==="color"?4:2,offset:0})),this.paintVertexArray=new b}populatePaintArray(o,u,m,x,b,S,A,I){const D=this.expression.evaluate(new Hs(this.context.zoom,{brightness:S,worldview:I}),u,{},b,x,A),B=this.expression.evaluate(new Hs(this.context.zoom+1,{brightness:S,worldview:I}),u,{},b,x,A),U=Ii(this.lutExpression,u,{},x,b,S,A,I),q=this.paintVertexArray.length;this.paintVertexArray.resize(o),this._setPaintValue(q,o,D,B,U?null:this.context.lut)}updatePaintArray(o,u,m,x,b,S,A,I){const D=this.expression.evaluate({zoom:this.context.zoom,brightness:A,worldview:I},m,x,void 0,b),B=this.expression.evaluate({zoom:this.context.zoom+1,brightness:A,worldview:I},m,x,void 0,b),U=Ii(this.lutExpression,m,x,b,void 0,A,void 0,I);this._setPaintValue(o,u,D,B,U?null:this.context.lut)}_setPaintValue(o,u,m,x,b){if(this.type==="color"){const S=Ji(m.toPremultipliedRenderColor(b)),A=Ji(x.toPremultipliedRenderColor(b));for(let I=o;I!0){this.binders={},this._buffers=[],this.context=u;const x=[],b=o;for(const S in o.paint._values){const A=b.paint.get(S);if(S.endsWith("-use-theme")||!m(S)||!(A instanceof dm&&Lx(A.property.specification)))continue;const I=Za(S,o.type),D=A.value,B=A.property.specification.type,U=!!A.property.useIntegerZoom,q=S==="line-dasharray"||S.endsWith("pattern"),K=b.paint.get(`${S}-use-theme`),X=S==="line-dasharray"&&b.layout.get("line-cap").value.kind!=="constant"||K&&K.value.kind!=="constant";if(D.kind!=="constant"||X)if(D.kind==="source"||X||q){const J=Nh(S,B,"source");this.binders[S]=q?new Sc(D,I,B,J,o.id):new Ls(D,I,B,J),x.push(`/a_${S}`)}else{const J=Nh(S,B,"composite");this.binders[S]=new ol(D,I,B,U,J),x.push(`/z_${S}`)}else this.binders[S]=q?new na(I):new Qs(b,S),x.push(`/u_${S}`);this.binders[S].context=u,K&&(this.binders[S].lutExpression=K.value)}this.cacheKey=x.sort().join("")}updateExpressions(o){const u=o;for(const m in this.binders){const x=this.binders[m]||(this.binders[m]=new Qs(u,m));x.context=this.context,Fl(x)&&(x.expression=u.paint.get(m).value)}}getMaxValue(o){const u=this.binders[o];return u instanceof Ls||u instanceof ol?u.maxValue:0}populatePaintArrays(o,u,m,x,b,S,A,I){for(const D in this.binders){const B=this.binders[D];Fl(B)&&B.populatePaintArray(o,u,m,x,b,S,A,I)}}setConstantPatternPositions(o,u){for(const m in this.binders){const x=this.binders[m];x instanceof na&&x.setConstantPatternPositions(o,u)}}getPatternTransitionVertexBuffer(o){const u=this.binders[o];return u instanceof Sc?u.paintTransitionVertexBuffer:null}updatePaintArrays(o,u,m,x,b,S,A,I,D,B){let U=!1;const q=Object.keys(o),K=q.length!==0&&!I,X=K?q:u.uniqueIds;this.context.lut=b.lut;for(const J in this.binders){const se=this.binders[J];if(!Fl(se))continue;const ae=se.expression;if(ae.kind==="constant"||(!ae.isStateDependent||I)&&ae.isLightConstant!==!1)continue;const ue=b.paint.get(J);se.expression=ue.value;const ce=(xe,ve)=>{const Ue=o[ve.toString()];return xe.eachPosition(ve,(Pe,De,Ve)=>{se.updatePaintArray(De,Ve,x.feature(Pe),Ue,S,A,D,B)})};let de=!K;for(const xe of X)de=ce(u,xe)||de;if(!K)for(const xe of m.uniqueIds)ce(m,xe);U=U||de}return U}defines(){const o=[];for(const u in this.binders){const m=this.binders[u];(m instanceof Qs||m instanceof na)&&o.push(...m.uniformNames.map(x=>`#define HAS_UNIFORM_${x}`))}return o}getPaintVertexBuffers(){return this._buffers}getUniforms(o){const u=[];for(const m in this.binders){const x=this.binders[m];if(x instanceof Qs||x instanceof na||x instanceof ol)for(const b of x.uniformNames)u.push({name:b,property:m,binding:x.getBinding(o,b)})}return u}setUniforms(o,u,m,x,b){for(const{name:S,property:A,binding:I}of m)this.binders[A].setUniform(o,I,b,x.get(A),S)}updatePaintBuffers(){this._buffers=[];for(const o in this.binders){const u=this.binders[o];Fl(u)&&u.paintVertexBuffer&&this._buffers.push(u.paintVertexBuffer),u instanceof Sc&&u.paintTransitionVertexBuffer&&this._buffers.push(u.paintTransitionVertexBuffer)}}upload(o){for(const u in this.binders){const m=this.binders[u];Fl(m)&&m.upload(o)}this.updatePaintBuffers()}destroy(){for(const o in this.binders){const u=this.binders[o];Fl(u)&&u.destroy()}}}class Hi{constructor(o,u,m=()=>!0){this.programConfigurations={};for(const x of o)this.programConfigurations[x.id]=new ji(x,u,m);this.needsUpload=!1,this._featureMap=new Ti,this._featureMapWithoutIds=new Ti,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(o,u,m,x,b,S,A,I,D){for(const B in this.programConfigurations)this.programConfigurations[B].populatePaintArrays(o,u,x,b,S,A,I,D);u.id!==void 0?this._featureMap.add(u.id,m,this._bufferOffset,o):(this._featureMapWithoutIds.add(this._idlessCounter,m,this._bufferOffset,o),this._idlessCounter+=1),this._bufferOffset=o,this.needsUpload=!0}updatePaintArrays(o,u,m,x,b,S,A,I){for(const D of m){const B=this.programConfigurations[D.id];B&&(this.needsUpload=B.updatePaintArrays(o,this._featureMap,this._featureMapWithoutIds,u,D,x,b,S,A||0,I)||this.needsUpload)}}get(o){return this.programConfigurations[o]}upload(o){if(this.needsUpload){for(const u in this.programConfigurations)this.programConfigurations[u].upload(o);this.needsUpload=!1}}destroy(){for(const o in this.programConfigurations)this.programConfigurations[o].destroy()}updateExpressions(o){const u=new Set;for(const m of o){const x=this.programConfigurations[m.id];x&&(x.updateExpressions(m),u.add(m.id))}for(const m in this.programConfigurations)u.has(m)||delete this.programConfigurations[m]}}const Os={"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-occlusion-opacity":["occlusion_opacity"],"icon-occlusion-opacity":["occlusion_opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-emissive-strength":["emissive_strength"],"icon-emissive-strength":["emissive_strength"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"symbol-z-offset":["z_offset"],"line-gap-width":["gapwidth"],"line-pattern":["pattern","pixel_ratio","pattern_b"],"fill-pattern":["pattern","pixel_ratio","pattern_b"],"fill-extrusion-pattern":["pattern","pixel_ratio","pattern_b"],"line-dasharray":["dash"],"fill-bridge-guard-rail-color":["structure_color"],"fill-tunnel-structure-color":["structure_color"]};function Za(h,o){return Os[h]||[h.replace(`${o}-`,"").replace(/-/g,"_")]}const Jd={"line-pattern":{source:R,composite:R},"fill-pattern":{source:R,composite:R},"fill-extrusion-pattern":{source:R,composite:R},"line-dasharray":{source:M,composite:M}},xu={color:{source:bt,composite:Y},number:{source:Hu,composite:bt}};function Nh(h,o,u){const m=Jd[h];return m&&m[u]||xu[o][u]}vr(Qs,"ConstantBinder"),vr(na,"PatternConstantBinder",{omit:["context"]}),vr(Ls,"SourceExpressionBinder",{omit:["expression","context"]}),vr(Sc,"PatternCompositeBinder",{omit:["expression","context"]}),vr(ol,"CompositeExpressionBinder",{omit:["expression","context"]}),vr(ji,"ProgramConfiguration",{omit:["_buffers"]}),vr(Hi,"ProgramConfigurationSet");class Ep{constructor(o,u,m){this.layoutVertexArray=new mm,this.indexArray=new Ne,this.lineIndexArray=new le,this.triangleSegments=new xn,this.lineSegments=new xn,this.programConfigurations=new Hi(o,{zoom:u,lut:m}),this.uploaded=!1}update(o,u,m,x,b,S,A,I){this.programConfigurations.updatePaintArrays(o,u,b,m,x,S,A,I)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(o){this.uploaded||(this.layoutVertexBuffer=o.createVertexBuffer(this.layoutVertexArray,Rn.members),this.indexBuffer=o.createIndexBuffer(this.indexArray),this.lineIndexBuffer=o.createIndexBuffer(this.lineIndexArray)),this.programConfigurations.upload(o),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(o,u,m,x,b,S,A){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,o,u,m,x,b,S,void 0,A)}}vr(Ep,"FillBufferData");class Tp{constructor(o){this.zoom=o.zoom,this.pixelRatio=o.pixelRatio,this.overscaling=o.overscaling,this.layers=o.layers,this.layerIds=this.layers.map(u=>u.fqid),this.index=o.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=o.lut,this.bufferData=new Ep(o.layers,o.zoom,o.lut),this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.projection=o.projection,this.sourceLayerIndex=o.sourceLayerIndex,this.sourceLayerName=o.sourceLayerName||"",this.worldview=o.worldview,this.hasAppearances=null}updateFootprints(o,u){}updateAppearances(o,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(o,u,m,x){this.hasPattern=V2("fill",this.layers,this.pixelRatio,u);const b=this.layers[0].layout.get("fill-sort-key"),S=[],A=new Hs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors});for(const{feature:I,id:D,index:B,sourceLayerIndex:U}of o){const q=this.layers[0]._featureFilter.needGeometry,K=Ph(I,q);if(!this.layers[0]._featureFilter.filter(A,K,m))continue;const X=b?b.evaluate(K,{},m,u.availableImages):void 0,J={id:D,properties:I.properties,type:I.type,sourceLayerIndex:U,index:B,geometry:Ch(I,K,q,m,x),patterns:{},sortKey:X};S.push(J)}b&&S.sort((I,D)=>I.sortKey-D.sortKey);for(const I of S){const{geometry:D,index:B,sourceLayerIndex:U}=I;if(this.hasPattern){const q=q2("fill",this.layers,I,this.zoom,this.pixelRatio,u);this.patternFeatures.push(q)}else this.addFeature(I,D,B,m,{},u.availableImages,u.brightness,u.elevationFeatures);u.featureIndex.insert(o[B].feature,D,B,U,this.index)}!this.hasPattern&&this.hdExt&&this.hdExt.buildFrcSegments(this)}update(o,u,m,x,b,S,A){this.bufferData.update(o,u,m,x,b,S,A,this.worldview),this.hdExt&&this.hdExt.update(o,u,m,x,b,S,A,this.worldview)}updateExpressions(o){this.bufferData.programConfigurations.updateExpressions(o),this.hdExt&&this.hdExt.updateExpressions(o)}addFeatures(o,u,m,x,b,S){for(const A of this.patternFeatures)this.addFeature(A,A.geometry,A.index,u,m,x,S,o.elevationFeatures);this.hdExt&&this.hdExt.buildFrcSegments(this)}isEmpty(){return this.bufferData.isEmpty()&&(!this.hdExt||this.hdExt.isEmpty())}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.hdExt!=null&&this.hdExt.needsUpload()}upload(o){this.bufferData.upload(o),this.hdExt&&this.hdExt.upload(o)}destroy(){this.bufferData.destroy(),this.hdExt&&this.hdExt.destroy()}addFeature(o,u,m,x,b,S=[],A,I){const D=this.hdExt?this.hdExt.trackFeatureFrc(o.properties):null,B=this.bufferData.indexArray.length,U=em(u,500);this.hdExt!=null&&this.hdExt.handleFeature(o,U,m,x,I,this)||this.addGeometry(U,this.bufferData),this.bufferData.populatePaintArrays(o,m,b,S,x,A,this.worldview),this.hdExt&&this.hdExt.populatePaintArrays(o,m,b,S,x,A,this.worldview),this.hdExt&&this.hdExt.recordFeatureRange(this,B,this.bufferData.indexArray.length,D)}addGeometry(o,u,m,x){let b=Number.POSITIVE_INFINITY,S=Number.NEGATIVE_INFINITY,A=null;m&&(A=m.elevationSampler.constantElevation(m.elevation,m.bias),A!=null&&(b=A,S=A));const I=m?u:null,D=(B,U,q)=>{if(m!=null)if(U.push(B),A!=null)I.elevatedLayoutVertexArray.emplaceBack(A),q.push(A);else{const K=m.elevationSampler.pointElevation(B,m.elevation,m.bias);I.elevatedLayoutVertexArray.emplaceBack(K),q.push(K),b=Math.min(b,K),S=Math.max(S,K)}};for(const B of o){let U=0;for(const xe of B)U+=xe.length;const q=u.triangleSegments.prepareSegment(U,u.layoutVertexArray,u.indexArray),K=q.vertexLength,X=[],J=[],se=[],ae=[],ue=[],ce=u.layoutVertexArray.length;for(const xe of B){if(xe.length===0)continue;xe!==B[0]&&J.push(X.length/2);const ve=u.lineSegments.prepareSegment(xe.length,u.layoutVertexArray,u.lineIndexArray),Ue=ve.vertexLength;m&&ue.push(u.layoutVertexArray.length-ce),D(xe[0],se,ae),u.layoutVertexArray.emplaceBack(xe[0].x,xe[0].y),u.lineIndexArray.emplaceBack(Ue+xe.length-1,Ue),X.push(xe[0].x),X.push(xe[0].y);for(let Pe=1;Pe0&&m&&x){const xe=m.elevation.isTunnel(),ve=m.elevation.safeArea,Ue=x.addVertices(se,ae);x.addTriangles(de,Ue,xe);const Pe=ue.length;if(Pe>0){for(let De=0;Deo.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${o.maxUniformBlockSize}`);u.isContextLost()||(this.headerBuffer=u.createBuffer(),u.bindBuffer(u.UNIFORM_BUFFER,this.headerBuffer),u.bufferData(u.UNIFORM_BUFFER,this._headerBytes(),u.DYNAMIC_DRAW),this.propertiesBuffer=u.createBuffer(),u.bindBuffer(u.UNIFORM_BUFFER,this.propertiesBuffer),u.bufferData(u.UNIFORM_BUFFER,this.totalBytes,u.DYNAMIC_DRAW),this._blockNames().length===3&&(this.blockIndicesBuffer=u.createBuffer(),u.bindBuffer(u.UNIFORM_BUFFER,this.blockIndicesBuffer),u.bufferData(u.UNIFORM_BUFFER,this.totalBytes,u.DYNAMIC_DRAW)),u.bindBuffer(u.UNIFORM_BUFFER,null))}markHeaderDirty(){this._headerDirty=!0}writeDataDrivenBlock(o,u,m=0){const x=this.headerData,b=4*x[2];if(b===0)return;const S=u*b;if(S+b>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${u} exceeds propertiesData capacity`);const A=x[0],I=this._propCount();for(let B=0;Bthis._propsDirtyMax&&(this._propsDirtyMax=D)}rightSizeForTransfer(){const o=this._propsDirtyMax===-1?0:this._propsDirtyMax;o0)if(o.interpolationType==null){b=S=1;for(const I of A)if(I>u&&Iu&&A[0]=0&&this._writePropertyZoomRange(u,m,x,I,b),!I)return D[A]=0,D[A+1]=0,D[A+2]=0,void(D[A+3]=1);const B=this._resolveProp(`${o}-use-theme`,S.activeAppearance,!0),U=this._effectiveLut(B,S.feature,S.featureState,S.availableImages,S.canonical,S.params.brightness,S.formattedSection),q=(I.isConstant()?I.constantOr(Vn.transparent):this._evalAt(I,S.params,S)||Vn.transparent).toNonPremultipliedRenderColor(U);if(D[A]=Sn(255*q.r,255*q.g),D[A+1]=Sn(255*q.b,255*q.a),m){const K=(this._evalAt(I,S.paramsNext,S)||Vn.transparent).toNonPremultipliedRenderColor(U);D[A+2]=Sn(255*K.r,255*K.g),D[A+3]=Sn(255*K.b,255*K.a)}else D[A+2]=D[A],D[A+3]=D[A+1]}_evaluateFloatValue(o,u,m,x,b,S,A,I){const D=this._resolveProp(o,S.activeAppearance),B=this._flatScratch();this._writePropertyZoomRange(u,m,x,D,b);const U=(D?D.isConstant()?D.constantOr(I):this._evalAt(D,S.params,S):I)??I;if(B[A]=U,m){const q=this._evalAt(D,S.paramsNext,S);B[A+1]=q??I}else B[A+1]=U}evaluateAllProperties(o,u,m,x,b,S,A){const I={brightness:b,worldview:this.worldview},D={feature:o,featureState:u,canonical:m,availableImages:x,params:new Hs(this.zoom,I),paramsNext:new Hs(this.zoom+1,I),formattedSection:S,activeAppearance:A},B=this._propNames().length;for(let U=0;Uec.indexOf(h)),Ap=[0,0,1,0,1,0,0,1,0,0,0,0],UNe=new Float32Array(pm.EVAL_FLAT_TOTAL);class hJ extends uJ{constructor(o,u,m,x="",b){super(o,u,m,x,b),this.maxValues=new Float32Array(ec.length),this._finishInitialization()}getMaxValue(o){const u=ec.indexOf(o);return u>=0?this.maxValues[u]:0}_propNames(){return ec}_headerDwords(){return pm.HEADER_DWORDS}_createUBO(o){return new pm(null,o,this.uboSizeDwords,this.header)}_flatScratch(){return UNe}populateUBO(o,u,m,x,b,S,A){this._pendingDashPosition=A;const I=super.populateUBO(o,u,m,x,b,S);return this._pendingDashPosition=null,I}evaluateAllProperties(o,u,m,x,b,S,A){const I=super.evaluateAllProperties(o,u,m,x,b,S,A);for(let B=0;B>3,S===0)continue}if(S--,b===1)A+=o.readSVarint(),I+=o.readSVarint(),x&&m.push(x),x=[new jt(A,I)];else if(b===2)A+=o.readSVarint(),I+=o.readSVarint(),x&&x.push(new jt(A,I));else{if(b!==7)throw new Error(`unknown command ${b}`);x&&x.push(x[0].clone())}}return x&&m.push(x),m}bbox(){if(this._geometry<0)throw new Error("feature has no geometry");const o=this._pbf;o.pos=this._geometry;const u=o.readVarint()+o.pos;let m=1,x=0,b=0,S=0,A=1/0,I=-1/0,D=1/0,B=-1/0;for(;o.pos>3,x===0)continue}if(x--,m===1||m===2)b+=o.readSVarint(),S+=o.readSVarint(),bI&&(I=b),SB&&(B=S);else if(m!==7)throw new Error(`unknown command ${m}`)}return[A,D,I,B]}toGeoJSON(o,u,m){const x=this.extent*Math.pow(2,m),b=this.extent*o,S=this.extent*u,A=this.loadGeometry();function I(q){return[360*(q.x+b)/x-180,360/Math.PI*Math.atan(Math.exp((1-2*(q.y+S)/x)*Math.PI))-90]}function D(q){return q.map(I)}let B;if(this.type===1){const q=[];for(const X of A)q.push(X[0]);const K=D(q);B=q.length===1?{type:"Point",coordinates:K[0]}:{type:"MultiPoint",coordinates:K}}else if(this.type===2){const q=A.map(D);B=q.length===1?{type:"LineString",coordinates:q[0]}:{type:"MultiLineString",coordinates:q}}else{if(this.type!==3)throw new Error("unknown feature type");{const q=function(X){const J=X.length;if(J<=1)return[X];const se=[];let ae,ue;for(let ce=0;ce=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[o];const u=this._pbf.readVarint()+this._pbf.pos;return new Wx(this._pbf,u,this.extent,this._keys,this._values)}}function GNe(h){let o=null;const u=h.readVarint()+h.pos;for(;h.pos1){if(pz(h,o))return!0;for(let m=0;m1?u:u.sub(o)._mult(x)._add(o))}function mJ(h,o){let u,m,x,b=!1;for(let S=0;So.y!=x.y>o.y&&o.x<(x.x-m.x)*(o.y-m.y)/(x.y-m.y)+m.x&&(b=!b)}return b}function Kx(h,o){let u=!1;for(let m=0,x=h.length-1;mo.y!=S.y>o.y&&o.x<(S.x-b.x)*(o.y-b.y)/(S.y-b.y)+b.x&&(u=!u)}return u}function xz(h,o,u,m,x){for(const S of h)if(o<=S.x&&u<=S.y&&m>=S.x&&x>=S.y)return!0;const b=[new jt(o,u),new jt(o,x),new jt(m,x),new jt(m,u)];if(h.length>2){for(const S of b)if(Kx(h,S))return!0}for(let S=0;Sx.x&&o.x>x.x||h.yx.y&&o.y>x.y)return!1;const b=Eh(h,o,u[0]);return b!==Eh(h,o,u[1])||b!==Eh(h,o,u[2])||b!==Eh(h,o,u[3])}function V1(h,o,u,m,x,b){let S=o.y-h.y,A=h.x-o.x;if(b=b||0){const I=S*S+A*A;if(I===0)return!0;const D=Math.sqrt(I);S/=D,A/=D}return!((u.x-h.x)*S+(u.y-h.y)*A-b<0||(m.x-h.x)*S+(m.y-h.y)*A-b<0||(x.x-h.x)*S+(x.y-h.y)*A-b<0)}function _z(h,o,u,m,x,b,S){return!(V1(h,o,m,x,b,S)||V1(o,u,m,x,b,S)||V1(u,h,m,x,b,S)||V1(m,x,h,o,u,S)||V1(x,b,h,o,u,S)||V1(b,m,h,o,u,S))}class U0 extends jt{constructor(o,u,m){super(o,u),this.z=m}}class pJ extends U0{constructor(o,u,m,x){super(o,u,m),this.w=x}}function gJ(h,o,u,m){const x=u==="x"?"y":"x",b=(m-h[u])/(o[u]-h[u]);h[x]=Math.round(h[x]+(o[x]-h[x])*b),h[u]=m,Object.hasOwn(h,"z")&&(h.z=Kr(h.z,o.z,b)),Object.hasOwn(h,"w")&&(h.w=Kr(h.w,o.w,b))}function yJ(h,o,u,m){const x=u,b=m;for(const S of["x","y"]){let A=h,I=o;A[S]>=I[S]&&(A=o,I=h),A[S]x&&gJ(A,I,S,x),A[S]b&&gJ(I,A,S,b)}}function vz(h,o,u,m,x,b){const S=[];for(let A=0;A=m&&X.x>=m||(K.x>=m?K=new jt(m,K.y+(m-K.x)/(X.x-K.x)*(X.y-K.y))._round():X.x>=m&&(X=new jt(m,K.y+(m-K.x)/(X.x-K.x)*(X.y-K.y))._round()),K.y>=x&&X.y>=x||(K.y>=x?K=new jt(K.x+(x-K.y)/(X.y-K.y)*(X.x-K.x),x)._round():X.y>=x&&(X=new jt(K.x+(x-K.y)/(X.y-K.y)*(X.x-K.x),x)._round()),D&&K.equals(D.at(-1))||(D=[K],S.push(D),b&&b.push({progress:{min:se+xJ(ae,ue,K)*J,max:1},parentIndex:A,prevPoint:ae,nextPoint:ue})),D.push(X),b&&(b.at(-1).progress.max=se+xJ(ae,ue,X)*J,b.at(-1).nextPoint=ue)))))}if(b&&U>0)for(let q=B;qD.t-B.t);let S=0,A=0,I=[];for(m.push(I);S!==h.length;){if(A===b.length){for(;S!==h.length;)I.length!==0&&I.at(-1).equals(h[S])||I.push(h[S]),S++;break}b[A].t<=S?(I.length!==0&&I.at(-1).equals(b[A].point)||I.push(b[A].point),Math.trunc(b[A].t),A++):(I.length!==0&&I.at(-1).equals(h[S])||I.push(h[S]),S++)}}function xJ(h,o,u){return h.x!==o.x?(u.x-h.x)/(o.x-h.x):h.y!==o.y?(u.y-h.y)/(o.y-h.y):0}function _J(h,{width:o,height:u},m,x){if(x){if(x instanceof Uint8ClampedArray)x=new Uint8Array(x.buffer);else if(x.length!==o*u*m)throw new RangeError("mismatched image size")}else x=new Uint8Array(o*u*m);return h.width=o,h.height=u,h.data=x,h}function vJ(h,o,u){const{width:m,height:x}=o;m===h.width&&x===h.height||(bz(h,o,{x:0,y:0},{x:0,y:0},{width:Math.min(h.width,m),height:Math.min(h.height,x)},u,null),h.width=m,h.height=x,h.data=o.data)}function bz(h,o,u,m,x,b,S,A){if(x.width===0||x.height===0)return o;if(x.width>h.width||x.height>h.height||u.x>h.width-x.width||u.y>h.height-x.height)throw new RangeError("out of range source coordinates for image copy");if(x.width>o.width||x.height>o.height||m.x>o.width-x.width||m.y>o.height-x.height)throw new RangeError("out of range destination coordinates for image copy");const I=h.data,D=o.data,B=b===4&&A;for(let U=0;U1&&(I=o[++A]);const B=Math.abs(D-I.left),U=Math.abs(D-I.right),q=Math.min(B,U);let K;const X=b/m*(x+1);if(I.isDash){const J=x-Math.abs(X);K=Math.sqrt(q*q+J*J)}else K=x-Math.sqrt(q*q+X*X);this.image.data[S+D]=Math.max(0,Math.min(255,K+128))}}}addRegularDash(o,u){for(let I=o.length-1;I>=0;--I){const D=o[I],B=o[I+1];D.zeroLength?o.splice(I,1):B&&B.isDash===D.isDash&&(B.left=D.left,o.splice(I,1))}const m=o[0],x=o.at(-1);m.isDash===x.isDash&&(m.left=x.left-this.width,x.right=m.right+this.width);const b=this.width*this.nextRow;let S=0,A=o[S];for(let I=0;I1&&(A=o[++S]);const D=Math.abs(I-A.left),B=Math.abs(I-A.right),U=Math.min(D,B);this.image.data[b+I]=Math.max(0,Math.min(255,(A.isDash?U:-U)+u+128))}}addDash(o,u){const m=this.getKey(o,u);if(this.positions[m])return this.positions[m];const x=u==="round",b=x?7:0,S=2*b+1;if(this.nextRow+S>this.height)return Xi("LineAtlas out of space"),null;o.length===0&&o.push(1);let A=0;for(let K=0;K=128&&D++}const B=Math.round(D/this.width*4095);this.nextRow+=S;const U=Math.floor(A),q={tl:[I,b|B<<4],br:[U,Math.round(65535*(A-U))]};return this.positions[m]=q,q}}vr(wJ,"LineAtlas");const Kg="3d_elevation_id",SJ="level",XNe=Wx.types,QNe=Math.cos(Math.PI/180*37.5),JNe=Math.cos(Math.PI/180*5);class wz{constructor(o){this.evaluationGlobals={zoom:0,lineProgress:void 0},this.elevationType="none",this.isSeaLevelReference=!1,this.showElevationIdDebug=!1,this.terrainEnabled=!1,this.zoom=o.zoom,this.evaluationGlobals.zoom=this.zoom,this.overscaling=o.overscaling,this.pixelRatio=o.pixelRatio,this.layers=o.layers,this.layerIds=this.layers.map(m=>m.fqid),this.index=o.index,this.projection=o.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.borderGradients={},this.layers.forEach(m=>{this.gradients[m.id]={},this.borderGradients[m.id]={}}),this.layoutVertexArray=new w,this.layoutVertexArray2=new k,this.patternVertexArray=new k,this.indexArray=new Ne;const u=o.layers.filter(m=>!!m.paint.get("line-pattern").constantOr(1));this.programConfigurations=new Hi(u,{zoom:o.zoom,lut:o.lut}),this.segments=new xn,this.sourceLayerName=o.sourceLayerName||"",this.maxLineLength=0,this.zOffsetVertexArray=new Y,this.elevationIdColVertexArray=new k,this.elevationGroundScaleVertexArray=new Hu,this.stateDependentLayerIds=this.layers.filter(m=>m.isStateDependent()).map(m=>m.id),this.tessellationStep=o.tessellationStep?o.tessellationStep:128,this.worldview=o.worldview,this.hasAppearances=null,this.maxUniformBlockSizeDwords=o.maxUniformBlockSizeDwords,this.uboBinders={},this.maxFeaturesPerBatch=Number.MAX_SAFE_INTEGER;for(const m of this.layers){const x=new hJ(m,o.zoom,o.lut,this.worldview,this.maxUniformBlockSizeDwords);this.uboBinders[m.id]=x,x.maxFeaturesPerBatchS-A),b=new Map;for(const S of x){const A=m.get(S);b.set(S,new xn(A))}return u&&(this.cachedBatchIndices=x,this.cachedBatchSegments=b),{batchIndices:x,batchSegments:b}}updateAppearances(o,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(o,u,m,x){this.showElevationIdDebug=u.showElevationIdDebug,this.terrainEnabled=u.terrainEnabled,this.hasPattern=V2("line",this.layers,this.pixelRatio,u);const b=this.layers[0].layout.get("line-sort-key");this.tileToMeter=Wc(m);const S=this.layers[0].layout.get("line-elevation-reference");if(S==="hd-road-markup")this.elevationType="road";else{const K=this.layers[0].layout.get("line-z-offset"),X=K.isConstant()&&!K.constantOr(0);this.elevationType=S!=="sea"&&S!=="ground"&&X?"none":"offset",this.elevationType==="offset"&&S==="none"&&Xi(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=S==="sea"}const A=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&A!==void 0;const I=[],D=new Hs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors});for(const{feature:K,id:X,index:J,sourceLayerIndex:se}of o){const ae=this.layers[0]._featureFilter.needGeometry,ue=Ph(K,ae);if(!this.layers[0]._featureFilter.filter(D,ue,m))continue;const ce=b?b.evaluate(ue,{},m):void 0,de={id:X,properties:K.properties,type:K.type,sourceLayerIndex:se,index:J,geometry:Ch(K,ue,ae,m,x),patterns:{},sortKey:ce};I.push(de)}b&&I.sort((K,X)=>K.sortKey-X.sortKey);const{lineAtlas:B,featureIndex:U}=u,q=this.addConstantDashes(B);for(const K of I){const{geometry:X,index:J,sourceLayerIndex:se}=K;if(q&&this.addFeatureDashes(K,B),this.hasPattern){const ae=q2("line",this.layers,K,this.zoom,this.pixelRatio,u);this.patternFeatures.push(ae)}else this.addFeature(K,X,J,m,B.positions,u.availableImages,u.brightness,u.elevationFeatures,u.elevationParams,u.crossSourceElevationEnabled);U.insert(o[J].feature,X,J,se,this.index)}if(!this.hasPattern&&this.hdExt&&this.hdExt.buildFrcSegments(this),this.hdExt&&this.hdExt.endPopulate(),!this.hasPattern)for(const K of this.layers)this.uboBinders[K.id].finalize()}addConstantDashes(o){let u=!1;for(const m of this.layers){const x=m.paint.get("line-dasharray").value,b=m.layout.get("line-cap").value;if(x.kind!=="constant"||b.kind!=="constant")u=!0;else{const S=b.value,A=x.value;if(!A)continue;o.addDash(A,S)}}return u}addFeatureDashes(o,u){const m=this.zoom;for(const x of this.layers){const b=x.paint.get("line-dasharray").value,S=x.layout.get("line-cap").value;if(b.kind==="constant"&&S.kind==="constant")continue;let A,I;if(b.kind==="constant"){if(A=b.value,!A)continue}else A=b.evaluate({zoom:m},o);I=S.kind==="constant"?S.value:S.evaluate({zoom:m},o),u.addDash(A,I),o.patterns[x.id]=[u.getKey(A,I)]}}update(o,u,m,x,b,S,A,I,D){if(this.programConfigurations.updatePaintArrays(o,u,b,m,x,S,A,D),I){if(S)for(const B of b){const U=this.uboBinders[B.id];U&&U.hasLightDependentBlocks(B)&&U.updateDynamicExpressions(B,u,I,m,o,A)}else if(Object.keys(o).length>0){const B=new Set(Object.keys(o).map(U=>{const q=Number(U);return!isNaN(q)&&Number.isSafeInteger(q)&&String(q)===U?q:U}));for(const U of b){const q=this.uboBinders[U.id];q&&q.hasStateDependentPaint(U)&&q.updateFeatures(B,U,u,I,m,o,A)}}}}updateExpressions(o){this.programConfigurations.updateExpressions(o)}addFeatures(o,u,m,x,b,S){for(const A of this.patternFeatures)this.addFeature(A,A.geometry,A.index,u,m,x,S,o.elevationFeatures,o.elevationParams,o.crossSourceElevationEnabled,o.lineAtlas.positions);this.hdExt&&(this.hdExt.buildFrcSegments(this),this.hdExt.endPopulate());for(const A of this.layers)this.uboBinders[A.id].finalize()}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(o){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=o.createVertexBuffer(this.layoutVertexArray2,tk)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=o.createVertexBuffer(this.patternVertexArray,dz)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=o.createVertexBuffer(this.zOffsetVertexArray,Z2.members,!0)),!this.elevationIdColVertexBuffer&&this.elevationIdColVertexArray.length>0&&(this.elevationIdColVertexBuffer=o.createVertexBuffer(this.elevationIdColVertexArray,X2.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=o.createVertexBuffer(this.elevationGroundScaleVertexArray,Q2.members,!0)),this.layoutVertexBuffer=o.createVertexBuffer(this.layoutVertexArray,J2),this.indexBuffer=o.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(o);for(const u of this.layers)this.uboBinders[u.id].upload(o);this.uploaded=!0}destroy(){if(this.layoutVertexBuffer){this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.elevationIdColVertexBuffer&&this.elevationIdColVertexBuffer.destroy(),this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy();for(const o of this.layers)this.uboBinders[o.id].destroy();this.segments.destroy()}}lineFeatureClips(o,u){let m,x;if(u&&u>0?(m=`mapbox_clip_start_${u}`,x=`mapbox_clip_end_${u}`):(m="mapbox_clip_start",x="mapbox_clip_end"),o.properties&&Object.hasOwn(o.properties,m)&&Object.hasOwn(o.properties,x))return{start:+o.properties[m],end:+o.properties[x]}}addFeature(o,u,m,x,b,S,A,I,D,B,U=b){const q=this.layers[0].layout,K=this.hdExt?this.hdExt.trackFeatureFrc(o.properties):null,X=this.indexArray.length,J=q.get("line-join").evaluate(o,{}),se=q.get("line-cap").evaluate(o,{}),ae=q.get("line-miter-limit"),ue=q.get("line-round-limit");this.lineClips=this.lineFeatureClips(o),this.lineFeature=o;const ce=!(!o.properties||!Object.hasOwn(o.properties,"mapbox_line_metrics"))&&o.properties.mapbox_line_metrics;this.zOffsetValue=q.get("line-z-offset").value;const de=this.layers[0].paint,xe=de.get("line-width").value;xe.kind!=="constant"&&xe.isLineProgressConstant===!1&&(this.variableWidthValue=xe);const ve=de.get("line-emissive-strength").value;if(ve.kind!=="constant"&&ve.isLineProgressConstant===!1&&(this.variableEmissiveStrengthValue=ve),this.isSeaLevelReference){const Pe=q.get("line-elevation-ground-scale").value;Pe.kind==="constant"&&Pe.value===0||(this.elevationGroundScaleValue=Pe)}this.currentFeatureBatchIndex=0,this.currentFeatureUboIndex=0;let Ue=!1;for(const Pe of this.layers){const De=this.uboBinders[Pe.id],Ve=(De.header[0]&wR)!==0&&o.patterns&&o.patterns[Pe.id]&&o.patterns[Pe.id][0],Fe=U&&Ve?U[Ve]:void 0,Ze=De.getCurrentBatchIndex(),st=De.populateUBO(o,m,x,S,A,void 0,Fe);De.isAllConstant||Ue||(this.currentFeatureBatchIndex=Ze,this.currentFeatureUboIndex=st,Ue=!0)}if(this.hdExt==null||!this.hdExt.handleFeature(o,u,x,I,D,!!B,J,se,ae,ue,this))for(let Pe=0;Pe0?Pe:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,o,m,b,S,x,A,void 0,this.worldview),this.hdExt&&this.hdExt.recordFeatureRange(this,X,this.indexArray.length,K)}fillNonElevatedRoadSegment(o){for(let u=Math.max(o,this.zOffsetVertexArray.length);u0,q=I&&I.progress.max<1;if(this.lineClips){let De={min:this.lineClips.start,max:this.lineClips.end},Ve=1;if(I){const st=this.lineClips.end-this.lineClips.start;De=function(ut,ht,_t){return{min:Fw(ut.min,ht,_t),max:Fw(ut.max,ht,_t)}}(I.progress,{min:0,max:1},De),st>0&&(Ve=(De.max-De.min)/st)}const Fe=+u.properties.mapbox_clip_feature_len,Ze=+u.properties.mapbox_clip_seg_len;if(Number.isNaN(Fe)||Number.isNaN(Ze)){for(let ut=0;ut=2&&o[X-1].equals(o[X-2]);)X--;let J=0;for(;J0,Rt=this.overscaling<=16?122880/(512*this.overscaling):0;if(Ve&&Fe==="round"){if(htS&&(Fe="bevel"),Fe==="bevel"&&(ht>2&&(Fe="flipbevel"),ht2*Rt){const Tt=ae.sub(ae.sub(ue)._mult(Rt/Ye)._round());this.updateDistance(ue,Tt),this.addCurrentVertex(Tt,de,0,0,se,Pe),ue=Tt}this.updateDistance(ue,ae),st._mult(ht),this.addCurrentVertex(ae,st,0,0,se,Pe);const At=ae.dist(ce);if(At>2*Rt){const Tt=ae.add(ce.sub(ae)._mult(Rt/At)._round());this.updateDistance(ae,Tt),this.addCurrentVertex(Tt,xe,0,0,se,Pe),ae=Tt}}else st._mult(ht),this.addCurrentVertex(ae,st,0,0,se,Pe);else if(Fe==="flipbevel"){if(ht>100)st=xe.mult(-1);else{const Ye=ht*de.add(xe).mag()/de.sub(xe).mag();st._perp()._mult(Ye*(Pt?-1:1))}this.addCurrentVertex(ae,st,0,0,se,Pe),this.addCurrentVertex(ae,st.mult(-1),0,0,se,Pe)}else if(Fe==="bevel"||Fe==="fakeround"){const Ye=ae.dist(ue);let At=1;if(this.elevationType==="offset"&&Fe==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&Pe!=null&&ue&&ce){const nr=4*Rt;Ye1){this.lineSoFar=o.w;const J=(u.x-o.x)/U,se=(u.y-o.y)/U,ae=(u.z-o.z)/U,ue=(u.w-o.w)/U,ce=u.x-o.x,de=u.y-o.y,xe=Math.sqrt(ce*ce+de*de);if(xe===0)return;const ve=-de/xe,Ue=ce/xe,Pe=ve,De=Ue,Ve=-ve,Fe=-Ue;for(let Ze=1;Ze=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,B),I.primitiveLength++),S?this.e2=B:this.e1=B,D!=null&&(this.zOffsetVertexArray.emplaceBack(D.zOffset,D.variableWidth,D.variableWidth,D.variableEmissiveStrength),this.showElevationIdDebug&&this.elevationIdColVertexArray.emplaceBack(0,0,0)),this.elevationGroundScaleValue){const U=D?D.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(U)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(o,u){this.prevDistance=this.distance,this.distance+=o.dist(u),this.updateScaledDistance()}}function Sz(h,o,u){return h.xu||h.yu}vr(wz,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside","lineFeature","cachedBatchIndices","cachedBatchSegments"]});const eRe=Gn([{name:"a_pos",components:2,type:"Int16"}],4),tRe=Gn([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),rRe=Gn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class ER{constructor(o){this.zoom=o.zoom,this.overscaling=o.overscaling,this.layers=o.layers,this.layerIds=this.layers.map(u=>u.fqid),this.index=o.index,this.hasPattern=!1,this.projection=o.projection,this.layoutVertexArray=new mm,this.indexArray=new Ne,this.segments=new xn,this.programConfigurations=new Hi(o.layers,{zoom:o.zoom,lut:o.lut}),this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.worldview=o.worldview,this.hasAppearances=null}updateFootprints(o,u){}updateAppearances(o,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(o,u,m,x){const b=this.layers[0],S=[];let A=null;b.type==="circle"&&(A=b.layout.get("circle-sort-key"));const I=new Hs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors});for(const{feature:B,id:U,index:q,sourceLayerIndex:K}of o){const X=this.layers[0]._featureFilter.needGeometry,J=Ph(B,X);if(!this.layers[0]._featureFilter.filter(I,J,m))continue;const se=A?A.evaluate(J,{},m):void 0,ae={id:U,properties:B.properties,type:B.type,sourceLayerIndex:K,index:q,geometry:Ch(B,J,X,m,x),patterns:{},sortKey:se};S.push(ae)}A&&S.sort((B,U)=>B.sortKey-U.sortKey);let D=null;x.projection.name==="globe"&&(this.globeExtVertexArray=new z,D=x.projection);for(const B of S){const{geometry:U,index:q,sourceLayerIndex:K}=B,X=o[q].feature;this.addFeature(B,U,q,u.availableImages,m,D,u.brightness,u.elevationFeatures),u.featureIndex.insert(X,U,q,K,this.index)}this.hdExt&&this.hdExt.finalize()}update(o,u,m,x,b,S,A){this.programConfigurations.updatePaintArrays(o,u,b,m,x,S,A,this.worldview)}updateExpressions(o){this.programConfigurations.updateExpressions(o)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(o){this.uploaded||(this.layoutVertexBuffer=o.createVertexBuffer(this.layoutVertexArray,eRe.members),this.indexBuffer=o.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=o.createVertexBuffer(this.globeExtVertexArray,rRe.members)),this.hdExt&&this.hdExt.upload(o)),this.programConfigurations.upload(o),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.hdExt&&this.hdExt.destroy())}addFeature(o,u,m,x,b,S,A,I){this.hdExt&&this.hdExt.beginFeature(o,I,b);for(const D of u)for(const B of D){const U=B.x,q=B.y;if(U<0||U>=ar||q<0||q>=ar)continue;if(S){const J=S.projectTilePoint(U,q,b),se=S.upVector(b,U,q);this.addGlobeExtVertex(J,se),this.addGlobeExtVertex(J,se),this.addGlobeExtVertex(J,se),this.addGlobeExtVertex(J,se)}const K=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,o.sortKey),X=K.vertexLength;this.addCircleVertex(U,q,-1,-1),this.addCircleVertex(U,q,1,-1),this.addCircleVertex(U,q,1,1),this.addCircleVertex(U,q,-1,1),this.hdExt&&this.hdExt.writeVertexQuad(U,q),this.indexArray.emplaceBack(X,X+1,X+2),this.indexArray.emplaceBack(X,X+2,X+3),K.vertexLength+=4,K.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,o,m,{},x,b,A,void 0,this.worldview)}addCircleVertex(o,u,m,x){this.layoutVertexArray.emplaceBack(2*o+(m+1)/2,2*u+(x+1)/2)}addGlobeExtVertex(o,u){this.globeExtVertexArray.emplaceBack(o.x,o.y,o.z,u[0]*16384,u[1]*16384,u[2]*16384)}}vr(ER,"CircleBucket",{omit:["layers"]});const nRe=Gn([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),iRe=Gn([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),sRe=Gn([{name:"a_projected_pos",components:4,type:"Float32"}],4);Gn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const aRe=Gn([{name:"a_fade_ref_time",components:2,type:"Int32"}],4),oRe=Gn([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),lRe=Gn([{name:"a_feature_index",components:1,type:"Float32"}],4),cRe=Gn([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),uRe=Gn([{name:"a_texb",components:2,type:"Uint16"}]),dRe=Gn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),hRe=Gn([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);Gn([{type:"Int16",name:"projectedAnchorX"},{type:"Int16",name:"projectedAnchorY"},{type:"Int16",name:"projectedAnchorZ"},{type:"Int16",name:"tileAnchorX"},{type:"Int16",name:"tileAnchorY"},{type:"Float32",name:"x1"},{type:"Float32",name:"y1"},{type:"Float32",name:"x2"},{type:"Float32",name:"y2"},{type:"Int16",name:"padding"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const EJ=Gn([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),fRe=Gn([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4),mRe=Gn([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_size",components:2,type:"Float32"},{name:"a_collision_padding",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);Gn([{name:"triangle",components:3,type:"Uint16"}]),Gn([{type:"Int16",name:"projectedAnchorX"},{type:"Int16",name:"projectedAnchorY"},{type:"Int16",name:"projectedAnchorZ"},{type:"Float32",name:"tileAnchorX"},{type:"Float32",name:"tileAnchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"},{type:"Uint8",name:"flipState"}]),Gn([{type:"Float32",name:"tileAnchorX"},{type:"Float32",name:"tileAnchorY"},{type:"Int16",name:"projectedAnchorX"},{type:"Int16",name:"projectedAnchorY"},{type:"Int16",name:"projectedAnchorZ"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",components:2,name:"textOffset"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Float32",name:"zOffset"},{type:"Uint8",name:"hasIconTextFit"},{type:"Uint16",name:"elevationFeatureIndex"}]),Gn([{type:"Float32",name:"offsetX"}]),Gn([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const nk=class a9 extends oJ{_headerBytes(){return a9.HEADER_BYTES}_propCount(){return 9}_blockNames(){return["SymbolPaintPropertiesHeaderUniform","SymbolPaintPropertiesUniform","SymbolPaintPropertiesIndexUniform"]}_copyFromFlat(o,u,m){let x=4;(u<2||u===8)&&(x=this.headerData[1]>>>u&1?8:4);const b=a9.EVAL_FLAT_OFFSETS[u];this.propertiesData.set(m.subarray(b,b+x),o)}};nk.HEADER_DWORDS=16,nk.HEADER_BYTES=64,nk.EVAL_FLAT_OFFSETS=[0,8,16,20,24,28,32,36,40],nk.EVAL_FLAT_TOTAL=48;let ik=nk;vr(ik,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});const q1=["icon","text"].map(h=>[`${h}-color`,`${h}-halo-color`,`${h}-opacity`,`${h}-halo-width`,`${h}-halo-blur`,`${h}-emissive-strength`,`${h}-occlusion-opacity`,"symbol-z-offset",`${h}-translate`]),Yg=new Float32Array(ik.EVAL_FLAT_TOTAL),Ez=new Float32Array(2),pRe=[0,0];class Tz extends uJ{constructor(o,u,m,x,b="",S){super(o,u,m,b,S),this.isText=x,this.allFormattedSections=[],this.activeAppearanceByVtIndex=null,this._finishInitialization()}_propNames(){return q1[+this.isText]}_headerDwords(){return ik.HEADER_DWORDS}_createUBO(o){return new ik(null,o,this.uboSizeDwords,this.header)}_flatScratch(){return Yg}updateHeader(){const o=this.layer.paint;let u=0,m=0,x=!1,b=0;const S=this._floorZoom,A=q1[+this.isText];for(let I=0;I<9;I++){const D=A[I],B=I<2,U=o.get(D),q=!(!U||typeof U.isConstant!="function"||U.isConstant()),K=this._appearancesHavePaintProperties(D);if(!q&&!K)continue;u|=1<{if(!D)return;this._computeZoomRange(D,u,Ez,0);const B=Ez[0],U=Ez[1];m?B===S&&U===A||(x=!0):(m=!0,S=B,A=U,b=D)};I(this._zoomExprOf(this._layerUnevaluated(o)));for(const D of this.layer.getAppearances()||[])D.hasPaintProperty(o)&&I(this._zoomExprOf(D.getUnevaluatedPaintProperty(o)));return{hasZoom:m,differs:x,representative:b}}_resolveProp(o,u,m=!1,x){const b=this.layer.paint,S=b.get(o),A=o,I=!(!u||!u.hasPaintProperty(A)),D=I?x&&S&&S.property.overrides&&S.property.overrides.hasOverride(x)?S:u.paintProperties.get(A):b.get(o);if(m||!D||typeof D.isConstant!="function"||!D.isConstant())return D;const B=I?u.getUnevaluatedPaintProperty(A):this._layerUnevaluated(o);return this._unbakeCamera(D,B)}_evaluateTranslateValue(o,u,m,x,b,S,A){const I=this._resolveProp(o,S.activeAppearance);this._writePropertyZoomRange(u,m,x,I,b);const D=!!I&&typeof I.isConstant=="function"&&!I.isConstant(),B=I?typeof I.isConstant!="function"?I:D?this._evalAt(I,S.params,S):I.constantOr(pRe):void 0;if(Yg[A]=B?B[0]:0,Yg[A+1]=B?B[1]:0,m){const U=D?this._evalAt(I,S.paramsNext,S):B;Yg[A+2]=U?U[0]:0,Yg[A+3]=U?U[1]:0}else Yg[A+2]=Yg[A],Yg[A+3]=Yg[A+1]}_evaluatePropertyAt(o,u){const m=q1[+this.isText][o],x=o<2,b=o===8,S=this.zoomDependency[o],A=S!==0,I=S===2,D=ik.EVAL_FLAT_OFFSETS[o],B=D+(x||b?4:2);if(x)this._evaluateColorValue(m,o,A,I,B,u,D);else if(b)this._evaluateTranslateValue(m,o,A,I,B,u,D);else{const U=m.endsWith("opacity")?1:0;this._evaluateFloatValue(m,o,A,I,B,u,D,U)}}_appearancesHavePaintProperties(o){return this.layer.getAppearances().some(u=>u.hasPaintProperty(o))}hasStateDependentPaint(o){if(super.hasStateDependentPaint(o))return!0;const u=q1[+this.isText];for(const m of o.getAppearances()||[])for(const x of u){const b=x;if(m.hasPaintProperty(b)&&lJ(m.paintProperties.get(b)))return!0}return!1}_dependsOnLight(o,u){if(super._dependsOnLight(o,u))return!0;const m=u;for(const x of o.getAppearances()||[])if(x.hasPaintProperty(m)&&2&x.getUnevaluatedPaintProperty(m).deps)return!0;return!1}hasPerFeatureTranslate(){return!!(256&this.header[0])}updateFeaturePaintForAppearance(o,u,m,x,b,S,A){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(o,A||null),this.header[0]===0))return!1;this._ensureRangeMaps();const I=this.featureVertexRangesFromVtIndex.get(o);if(!I)return!1;let D=!1;for(const B of I){const U=this.evaluateAllProperties(u,m,x,b,S,(this.allFormattedSections?this.allFormattedSections[B]:void 0)||void 0,A);D=this._writeFeatureBlock(B,U)||D}return D}_buildConstantUniforms(o){const u=q1[+this.isText];return{fill_np_color:this._constantColor(u[0],o,[0,0,0,1]),halo_np_color:this._constantColor(u[1],o,[0,0,0,1]),opacity:this._constantFloat(u[2],1),halo_width:this._constantFloat(u[3],0),halo_blur:this._constantFloat(u[4],0),emissive_strength:this._constantFloat(u[5],0),occlusion_opacity:this._constantFloat(u[6],1),z_offset:this._constantFloat(u[7],0)}}}vr(Tz,"SymbolPropertyBinderUBO",{omit:["layer","cachedConstantUniforms","cachedConstantBrightness","cachedConstantPaint","activeAppearanceByVtIndex","featureVertexRangesFromId","featureVertexRangesFromVtIndex"]});const G1=24;g.fP=null;let TJ=null;function gRe(h,o,u){return h.sections.forEach(m=>{m.text=function(x,b,S){const A=b.layout.get("text-transform").evaluate(S,{});return A==="uppercase"?x=x.toLocaleUpperCase():A==="lowercase"&&(x=x.toLocaleLowerCase()),g.fP&&(x=g.fP.applyArabicShaping(x)),x}(m.text,o,u)}),h}const Zg={horizontal:1,vertical:2,horizontalOnly:3};function AJ(h){let o=.5,u=.5;switch(h){case"right":case"top-right":case"bottom-right":o=1;break;case"left":case"top-left":case"bottom-left":o=0}switch(h){case"bottom":case"bottom-right":case"bottom-left":u=1;break;case"top":case"top-right":case"top-left":u=0}return{horizontalAlign:o,verticalAlign:u}}function kJ(h,o,u,m){const{horizontalAlign:x,verticalAlign:b}=AJ(m),S=u[0]-h.displaySize[0]*x,A=u[1]-h.displaySize[1]*b;return{imagePrimary:h,imageSecondary:o,top:A,bottom:A+h.displaySize[1],left:S,right:S+h.displaySize[0]}}function IJ(h,o,u,m,x,b){const S=h.imagePrimary;let A;if(S.content){const se=S.content,ae=S.pixelRatio||1;A=[se[0]/ae,se[1]/ae,S.displaySize[0]-se[2]/ae,S.displaySize[1]-se[3]/ae]}const I=o.left*b,D=o.right*b;let B,U,q,K;u==="width"||u==="both"?(K=x[0]+I-m[3],U=x[0]+D+m[1]):(K=x[0]+(I+D-S.displaySize[0])/2,U=K+S.displaySize[0]);const X=o.top*b,J=o.bottom*b;return u==="height"||u==="both"?(B=x[1]+X-m[0],q=x[1]+J+m[2]):(B=x[1]+(X+J-S.displaySize[1])/2,q=B+S.displaySize[1]),{imagePrimary:S,imageSecondary:void 0,top:B,right:U,bottom:q,left:K,collisionPadding:A}}const sk={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};function yRe(h){return h==="︶"||h==="﹈"||h==="︸"||h==="﹄"||h==="﹂"||h==="︾"||h==="︼"||h==="︺"||h==="︘"||h==="﹀"||h==="︐"||h==="︓"||h==="︔"||h==="`"||h===" ̄"||h==="︑"||h==="︒"}function xRe(h){return h==="︵"||h==="﹇"||h==="︷"||h==="﹃"||h==="﹁"||h==="︽"||h==="︻"||h==="︹"||h==="︗"||h==="︿"}const Zx=128;function H1(h,o,u,m){const{expression:x}=o;if(x.kind==="constant")return{kind:"constant",layoutSize:x.evaluate(new Hs(h+1,{worldview:u}),void 0,void 0,void 0,m)};if(x.kind==="source")return{kind:"source"};{const{zoomStops:b,interpolationType:S}=x;let A=0;for(;AI*A)}}function CJ(h,o,u,m,x,b,S){return{appearanceTextOffset:W1(h,o,u,m,"text-offset",x,([I,D])=>[I*G1,D*G1]),appearanceTextRotate:W1(h,o,u,m,"text-rotate",b),appearanceTextSize:W1(h,o,u,m,"text-size",S)}}function PJ(h,o,u,m,x,b,S,A,I,D){if(!h)return;const B=function(U,q,K,X,J,se,ae){if(U.kind==="camera")return U.maxSize;if(U.kind==="composite"){const ue=q.possiblyEvaluate(new Hs(U.maxZoom,{worldview:se}),K,ae).evaluate(J,{},K,ae),ce=q.possiblyEvaluate(new Hs(U.minZoom,{worldview:se}),K,ae).evaluate(J,{},K,ae);return Math.max(ue,ce)}return q.possiblyEvaluate(new Hs(X,{worldview:se}),K,ae).evaluate(J,{},K,ae)}(o,u,m,x,b,I,D);return h.scaleSelf(B*A*S)}function Az(h,o,u,m,x,b,S,A,I,D){return{iconPrimary:PJ(h.getPrimary(),o,u,m,x,b,S,A,I,D),iconSecondary:PJ(h.getSecondary(),o,u,m,x,b,S,A,I,D)}}function NJ(h,o,u,m,x,b){let S=null;return o.kind==="source"?(S=[Zx*u*m],S[0]>V0&&Xi(`${h}: Value for "text-size" or "icon-size" is >= 255. Reduce your "text-size" or "icon-size".`)):o.kind==="composite"&&(S=[Zx*x*m,Zx*b*m],(S[0]>V0||S[1]>V0)&&Xi(`${h}: Value for "text-size" or "icon-size" is >= 255. Reduce your "text-size" or "icon-size".`)),S}function kz(h,o){const u=h.layout;return u.get("symbol-placement")==="point"&&(o==="icon"?u.get("icon-rotation-alignment")==="map":u.get("text-rotation-alignment")==="map")}class bRe{constructor(o,u){this.pos=o,this.dir=u}intersectsPlane(o,u,m){const x=ki(u,this.dir);if(Math.abs(x)<1e-6)return!1;const b=((o[0]-this.pos[0])*u[0]+(o[1]-this.pos[1])*u[1])/x;return m[0]=this.pos[0]+this.dir[0]*b,m[1]=this.pos[1]+this.dir[1]*b,!0}}class AR{constructor(o,u){this.pos=o,this.dir=u}intersectsPlane(o,u,m){const x=Vr(u,this.dir);if(Math.abs(x)<1e-6)return!1;const b=((o[0]-this.pos[0])*u[0]+(o[1]-this.pos[1])*u[1]+(o[2]-this.pos[2])*u[2])/x;return m[0]=this.pos[0]+this.dir[0]*b,m[1]=this.pos[1]+this.dir[1]*b,m[2]=this.pos[2]+this.dir[2]*b,!0}closestPointOnSphere(o,u,m){if(function(K,X){var J=K[0],se=K[1],ae=K[2],ue=X[0],ce=X[1],de=X[2];return Math.abs(J-ue)<=E*Math.max(1,Math.abs(J),Math.abs(ue))&&Math.abs(se-ce)<=E*Math.max(1,Math.abs(se),Math.abs(ce))&&Math.abs(ae-de)<=E*Math.max(1,Math.abs(ae),Math.abs(de))}(this.pos,o)||u===0)return m[0]=m[1]=m[2]=0,!1;const[x,b,S]=this.dir,A=this.pos[0]-o[0],I=this.pos[1]-o[1],D=this.pos[2]-o[2],B=x*x+b*b+S*S,U=2*(A*x+I*b+D*S),q=U*U-4*B*(A*A+I*I+D*D-u*u);if(q<0){const K=Math.max(-U/2,0),X=A+x*K,J=I+b*K,se=D+S*K,ae=Math.hypot(X,J,se);return m[0]=X*u/ae,m[1]=J*u/ae,m[2]=se*u/ae,!1}{const K=(-U-Math.sqrt(q))/(2*B);if(K<0){const X=Math.hypot(A,I,D);return m[0]=A*u/X,m[1]=I*u/X,m[2]=D*u/X,!1}return m[0]=A+x*K,m[1]=I+b*K,m[2]=D+S*K,!0}}}class Iz{constructor(o,u,m,x,b){this.TL=o,this.TR=u,this.BR=m,this.BL=x,this.horizon=b}static fromInvProjectionMatrix(o,u,m){const x=[-1,1,1],b=[1,1,1],S=[1,-1,1],A=[-1,-1,1],I=Ar(x,x,o),D=Ar(b,b,o),B=Ar(S,S,o),U=Ar(A,A,o);return new Iz(I,D,B,U,u/m)}}function jz(h,o,u,m){const x=o[0],b=o[1],S=o[2],A=u[0],I=u[1],D=u[2];let B=1/0,U=-1/0;for(let q=0;qU&&(U=X)}return m[0]=B,m[1]=U,m}function RJ(h,o,u,m,x){let b=!0;for(let S=0;S0?u[0]:o[0])*I+(D>0?u[1]:o[1])*D+(B>0?x:m)*B+U>=0))return 0;!b||(I>0?o[0]:u[0])*I+(D>0?o[1]:u[1])*D+(B>0?m:x)*B+U>=0||(b=!1)}return b?2:1}const wRe=[0,0];function LJ(h,o){for(const u of h.projections){const m=jz(o,h.points[0],u.axis,wRe);if(u.projection[1]m[1])return 0}return 1}function DJ(h,o){const u=o[0],m=o[1],x=o[2],b=o[3];for(let S=0;S=0)return!0}return!1}class q0{constructor(o,u){this.points=o||new Array(8).fill([0,0,0]),this.planes=u||new Array(6).fill([0,0,0,0]),this.bounds=js.fromPoints(this.points),this.projections=[],this.frustumEdges=[Or([],this.points[2],this.points[3]),Or([],this.points[0],this.points[3]),Or([],this.points[4],this.points[0]),Or([],this.points[5],this.points[1]),Or([],this.points[6],this.points[2]),Or([],this.points[7],this.points[3])];for(const m of this.frustumEdges){const x=[0,-m[2],m[1]],b=[m[2],0,-m[0]];this.projections.push({axis:x,projection:jz(this.points,this.points[0],x,[0,0])}),this.projections.push({axis:b,projection:jz(this.points,this.points[0],b,[0,0])})}}static fromInvProjectionMatrix(o,u,m,x){const b=Math.pow(2,m),S=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map(D=>{const B=Ki([],D,o),U=1/B[3]/u*b;return function(q,K,X){return q[0]=K[0]*X[0],q[1]=K[1]*X[1],q[2]=K[2]*X[2],q[3]=K[3]*X[3],q}(B,B,[U,U,x?1/B[3]:U,U])}),A=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(D=>{const B=zt([],Jr([],Or([],S[D[0]],S[D[1]]),Or([],S[D[2]],S[D[1]]))),U=-Vr(B,S[D[1]]);return B.concat(U)}),I=[];for(let D=0;DX&&(X=ce)}let J=1/0,se=-1/0;for(let ae=0;aese&&(se=ce)}if(K>se||J>X)return 0}return 1}containsPoint(o){for(const u of this.planes){const m=u[3];if(Vr([u[0],u[1],u[2]],o)+m<0)return!1}return!0}}class js{static fromPoints(o){const u=[1/0,1/0,1/0],m=[-1/0,-1/0,-1/0];for(const x of o)Bt(u,u,x),cr(m,m,x);return new js(u,m)}static fromTileIdAndHeight(o,u,m){const x=1<o.max[u]||o.min[u]>this.max[u])return!1;return!0}intersectsAabbXY(o){return!(this.min[0]>o.max[0]||o.min[0]>this.max[0]||this.min[1]>o.max[1]||o.min[1]>this.max[1])}encapsulate(o){for(let u=0;u<3;u++)this.min[u]=Math.min(this.min[u],o.min[u]),this.max[u]=Math.max(this.max[u],o.max[u])}encapsulatePoint(o){for(let u=0;u<3;u++)this.min[u]=Math.min(this.min[u],o[u]),this.max[u]=Math.max(this.max[u],o[u])}closestPoint(o){return[Math.max(Math.min(this.max[0],o[0]),this.min[0]),Math.max(Math.min(this.max[1],o[1]),this.min[1]),Math.max(Math.min(this.max[2],o[2]),this.min[2])]}}vr(js,"Aabb");const SRe=Gn([{type:"Float32",name:"a_globe_pos",components:3},{type:"Float32",name:"a_uv",components:2}]),{members:kR}=SRe,ERe=Gn([{name:"a_pos_3",components:3,type:"Int16"}]);var Cz=Gn([{name:"a_pos",type:"Int16",components:2}]);function IR(h){return h*Hc/fm}const TRe=[new js([Xd,Xd,Xd],[gu,gu,gu]),new js([Xd,Xd,Xd],[0,0,gu]),new js([0,Xd,Xd],[gu,0,gu]),new js([Xd,0,Xd],[0,gu,gu]),new js([0,0,Xd],[gu,gu,gu])];function MJ(h,o,u,m=!0){const x=ft([],h._camera.position,h.worldSize),b=[o,u,1,1];Ki(b,b,h.pixelMatrixInverse),gs(b,b,1/b[3]);const S=zt([],Or([],b,x)),A=h.globeMatrix,I=[A[12],A[13],A[14]],D=Or([],I,x),B=ot(D),U=zt([],D),q=h.worldSize/(2*Math.PI),K=Vr(U,S),X=Math.asin(q/B);if(X1?null:function(m,x,b,S){const A=Math.sin(b);return m*(Math.sin((1-S)*b)/A)+x*(Math.sin(S*b)/A)}(h.a[o],h.b[o],h.angle,cn(u,0,1))+h.center[o]}function kp(h){if(h.z<=1)return TRe[h.z+2*h.y+h.x];const o=Rz(jR(h));return js.fromPoints(o)}function Qg(h,o,u){return ft(h,h,1-u),Kt(h,h,o,u)}function OJ(h,o,u){for(const m of h)Ar(m,m,o),ft(m,m,u)}function Nz(h,o,u,m){const x=o/h.worldSize,b=h.globeMatrix;if(u.z<=1){const De=kp(u).getCorners();return OJ(De,b,x),js.fromPoints(De)}const S=jR(u,m),A=Rz(S,Hc+IR(h._tileCoverLift));OJ(A,b,x);const I=Number.MAX_VALUE,D=[-I,-I,-I],B=[I,I,I];if(S.contains(h.center)){for(const Fe of A)Bt(B,B,Fe),cr(D,D,Fe);D[2]=0;const De=h.point,Ve=[De.x*x,De.y*x,0];return Bt(B,B,Ve),cr(D,D,Ve),new js(B,D)}if(h._tileCoverLift>0){for(const De of A)Bt(B,B,De),cr(D,D,De);return new js(B,D)}const U=[b[12]*x,b[13]*x,b[14]*x],q=S.getCenter(),K=cn(h.center.lat,-85.051129,wc),X=cn(q.lat,-85.051129,wc),J=mu(h.center.lng),se=vc(K);let ae=J-mu(q.lng);const ue=se-vc(X);ae>.5?ae-=1:ae<-.5&&(ae+=1);let ce=0;Math.abs(ae)>Math.abs(ue)?ce=ae>=0?1:3:(ce=ue>=0?0:2,Kt(U,U,[b[4]*x,b[5]*x,b[6]*x],-Math.sin(Bn(ue>=0?S.getSouth():S.getNorth()))*Hc));const de=A[ce],xe=A[(ce+1)%4],ve=new ARe(de,xe,U),Ue=[Pz(ve,0)||de[0],Pz(ve,1)||de[1],Pz(ve,2)||de[2]],Pe=Ip(h.zoom);if(Pe>0){const De=function({x:Fe,y:Ze,z:st},ut,ht,_t,Et){const Pt=1/(1<.5?$t=-1:Gt<-.5&&($t=1),Rt=((Rt+$t)*ut-(_t*=ut))*ht+_t,Ye=((Ye+$t)*ut-_t)*ht+_t,At=(At*ut-(Et*=ut))*ht+Et,Tt=(Tt*ut-Et)*ht+Et,[[Rt,Tt,0],[Ye,Tt,0],[Ye,At,0],[Rt,At,0]]}(u,o,h._pixelsPerMercatorPixel,J,se);for(let Fe=0;FeMath.PI/2*1.01}const VJ=Bn(85),kRe=Math.cos(VJ),IRe=Math.sin(VJ);class Xx{constructor(o,u,m){this.z=o,this.x=u,this.y=m,this.key=Qx(0,o,o,u,m)}equals(o){return this.z===o.z&&this.x===o.x&&this.y===o.y}isChildOf(o){const u=this.z-o.z;return o.z===0||o.z>u&&o.y===this.y>>u}url(o,u){const m=function(b,S,A){const I=2**A,D=2*Math.PI*6378137,B=D*(b/I-.5),U=D*(.5-(S+1)/I);return`${B},${U},${B+D/I},${U+D/I}`}(this.x,this.y,this.z),x=function(b,S,A){let I,D="";for(let B=b;B>0;B--)I=1<this.canonical.z?new ll(o,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new ll(o,this.wrap,o,this.canonical.x>>u,this.canonical.y>>u)}calculateScaledKey(o,u=!0){if(this.overscaledZ===o&&u)return this.key;if(o>this.canonical.z)return Qx(this.wrap*+u,o,this.canonical.z,this.canonical.x,this.canonical.y);{const m=this.canonical.z-o;return Qx(this.wrap*+u,o,o,this.canonical.x>>m,this.canonical.y>>m)}}isChildOf(o){if(o.wrap!==this.wrap)return!1;const u=this.canonical.z-o.canonical.z;return o.overscaledZ===0||o.overscaledZ>u&&o.canonical.y===this.canonical.y>>u}children(o){if(this.overscaledZ>=o)return[new ll(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const u=this.canonical.z+1,m=2*this.canonical.x,x=2*this.canonical.y;return[new ll(u,this.wrap,u,m,x),new ll(u,this.wrap,u,m+1,x),new ll(u,this.wrap,u,m,x+1),new ll(u,this.wrap,u,m+1,x+1)]}isLessThan(o){return this.wrapo.wrap)&&(this.overscaledZo.overscaledZ)&&(this.canonical.xo.canonical.x)&&this.canonical.y{let o=h.canonical.x-1,u=h.wrap;return o<0&&(o=(1<{let o=h.canonical.x+1,u=h.wrap;return o===1<new ll(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,(h.canonical.y===0?1<new ll(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,h.canonical.y===(1<ce&&(de(ve,ut,Pe,De,Ze,st),de(ut,Ue,Ze,st,Ve,Fe))}de(U,q,m,b,x,b),de(q,K,x,b,x,S),de(K,X,x,S,m,S),de(X,U,m,S,m,b),J-=ce,se-=ce,ae+=ce,ue+=ce;const xe=1/Math.max(ae-J,ue-se);return{scale:xe,x:J*xe,y:se*xe,x2:ae*xe,y2:ue*xe,projection:o}}function Oz(h,o,u){const{projection:m,scale:x}=h;if(!m.isReprojectedInTileSpace)return 0;const{lng:b,lat:S}=m.unproject((o/ar+h.x)/x,(u/ar+h.y)/x),A=1e-4,I=cn(S-A,-85.051129,wc),D=cn(S+A,-85.051129,wc);if(D===I)return 0;const B=m.project(b,I),U=m.project(b,D);return po(Math.atan2(U.x-B.x,B.y-U.y))}function GJ(h,o,u,m,x,b,S,A,I){if(I.name==="globe")return Nz(h,o,new Xx(u,m,x),!1);const D=LR({z:u,x:m,y:x},I);return new js([(b+D.x/D.scale)*o,o*(D.y/D.scale),S],[(b+D.x2/D.scale)*o,o*(D.y2/D.scale),A])}function HJ(h,o){const u=h.fovAboveCenter,m=h.elevation?h.elevation.getMinElevationBelowMSL()*o:0,x=Math.min(m,h.isOrthographic?-10*o:0),b=(h._camera.position[2]*h.worldSize-x)/Math.cos(h._pitch),S=Math.sin(u)*b/Math.sin(Math.max(Math.PI/2-h._pitch-u,.01));let A=Math.sin(h._pitch)*S+b;const I=b*(1/h._horizonShift);if(!h.elevation||h.elevation.exaggeration()===0){let D=Math.max(h.zoom-17,0);h.isOrthographic&&(D/=10),A*=1+D}return Math.min(1.01*A,I)}vr(Xx,"CanonicalTileID"),vr(ll,"OverscaledTileID",{omit:["projMatrix","expandedProjMatrix"]});const jRe=G(new Float32Array(16));class Jx{constructor(o){this.spec=o,this.name=o.name,this.wrap=!1,this.requiresDraping=!1,this.supportsWorldCopies=!1,this.supportsTerrain=!1,this.supportsFog=!1,this.supportsFreeCamera=!1,this.zAxisUnit="meters",this.isReprojectedInTileSpace=!0,this.unsupportedLayers=["custom"],this.center=[0,0],this.range=[3.5,7]}project(o,u){return{x:0,y:0,z:0}}unproject(o,u){return new pi(0,0)}projectTilePoint(o,u,m){return{x:o,y:u,z:0}}locationPoint(o,u,m,x=!0){return o._coordinatePoint(o.locationCoordinate(u,m),x)}globeCenterToScreenPoint(o){return null}pixelsPerMeter(o,u){return ks(1,o)*u}pixelSpaceConversion(o,u,m){return 1}farthestPixelDistance(o){return HJ(o,o.pixelsPerMeter)}pointCoordinate(o,u,m,x){const b=o.horizonLineFromTop(!1),S=new jt(u,Math.max(b,m));return o.rayIntersectionCoordinate(o.pointRayIntersection(S,x))}pointCoordinate3D(o,u,m){const x=new jt(u,m);if(o.elevation)return o.elevation.pointCoordinate(x);{const b=this.pointCoordinate(o,x.x,x.y,0);return[b.x,b.y,b.z]}}isPointAboveHorizon(o,u){if(o.elevation&&o.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(o,u.x,u.y);const m=o.horizonLineFromTop();return u.y0?u<-K1+m&&(u=-K1+m):u>K1-m&&(u=K1-m);const S=b/Math.pow(MR(u),x);let A=S*Math.sin(x*o),I=b-S*Math.cos(x*o);return A=.5*(A/Math.PI+.5),I=.5*(I/Math.PI+.5),{x:A,y:this.southernCenter?I:1-I,z:0}}unproject(o,u){o=(2*o-.5)*Math.PI,this.southernCenter&&(u=1-u),u=(2*(1-u)-.5)*Math.PI;const{n:m,f:x}=this,b=x-u,S=Math.sign(b),A=Math.sign(m)*Math.sqrt(o*o+b*b);let I=Math.atan2(o,Math.abs(b))*S;b*m<0&&(I-=Math.PI*Math.sign(o)*S);const D=cn(po(I/m)+this.center[0],-180,180),B=cn(po(2*Math.atan(Math.pow(x/A,1/m))-K1),-85.051129,wc);return new pi(D,this.southernCenter?-B:B)}}class WJ extends Jx{constructor(o){super(o),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(o,u){return{x:mu(o),y:vc(u),z:0}}unproject(o,u){const m=Jl(o),x=Fa(u);return new pi(m,x)}}const KJ=Bn(wc);class LRe extends Jx{project(o,u){const m=(u=Bn(u))*u,x=m*m;return{x:.5*((o=Bn(o))*(.8707-.131979*m+x*(x*(.003971*m-.001529*x)-.013791))/Math.PI+.5),y:1-.5*(u*(1.007226+m*(.015085+x*(.028874*m-.044475-.005916*x)))/Math.PI+1),z:0}}unproject(o,u){o=(2*o-.5)*Math.PI;let m=u=(2*(1-u)-1)*Math.PI,x=25,b=0,S=m*m;do{S=m*m;const D=S*S;b=(m*(1.007226+S*(.015085+D*(.028874*S-.044475-.005916*D)))-u)/(1.007226+S*(.045255+D*(.259866*S-.311325-.005916*11*D))),m=cn(m-b,-KJ,KJ)}while(Math.abs(b)>1e-6&&--x>0);S=m*m;const A=cn(po(o/(.8707+S*(S*(S*S*S*(.003971-.001529*S)-.013791)-.131979))),-180,180),I=po(m);return new pi(A,I)}}const YJ=Bn(wc);class DRe extends Jx{project(o,u){u=Bn(u),o=Bn(o);const m=Math.cos(u),x=2/Math.PI,b=Math.acos(m*Math.cos(o/2)),S=Math.sin(b)/b,A=.5*(o*x+2*m*Math.sin(o/2)/S)||0,I=.5*(u+Math.sin(u)/S)||0;return{x:.5*(A/Math.PI+.5),y:1-.5*(I/Math.PI+1),z:0}}unproject(o,u){let m=o=(2*o-.5)*Math.PI,x=u=(2*(1-u)-1)*Math.PI,b=25;const S=1e-6;let A=0,I=0;do{const D=Math.cos(x),B=Math.sin(x),U=2*B*D,q=B*B,K=D*D,X=Math.cos(m/2),J=Math.sin(m/2),se=2*X*J,ae=J*J,ue=1-K*X*X,ce=ue?1/ue:0,de=ue?Math.acos(D*X)*Math.sqrt(1/ue):0,xe=.5*(2*de*D*J+2*m/Math.PI)-o,ve=.5*(de*B+x)-u,Ue=.5*ce*(K*ae+de*D*X*q)+1/Math.PI,Pe=ce*(se*U/4-de*B*J),De=.125*ce*(U*J-de*B*K*se),Ve=.5*ce*(q*X+de*ae*D)+.5,Fe=Pe*De-Ve*Ue;A=(ve*Pe-xe*Ve)/Fe,I=(xe*De-ve*Ue)/Fe,m=cn(m-A,-Math.PI,Math.PI),x=cn(x-I,-YJ,YJ)}while((Math.abs(A)>S||Math.abs(I)>S)&&--b>0);return new pi(po(m),po(x))}}class ZJ extends Jx{constructor(o){super(o),this.center=o.center||[0,0],this.parallels=o.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Bn(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(o,u){const{scale:m,cosPhi:x}=this;return{x:Bn(o)*x*m+.5,y:-Math.sin(Bn(u))/x*m+.5,z:0}}unproject(o,u){const{scale:m,cosPhi:x}=this,b=-(u-.5)/m,S=cn(po((o-.5)/m)/x,-180,180),A=Math.asin(cn(b*x,-1,1)),I=cn(po(A),-85.051129,wc);return new pi(S,I)}}class MRe extends WJ{constructor(o){super(o),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(o,u,m){const x=ak(o,u,m);return Ar(x,x,NR(kp(m))),{x:x[0],y:x[1],z:x[2]}}locationPoint(o,u,m){const x=Wg(u.lat,u.lng),b=zt([],x),S=m?o._centerAltitude+m:o.elevation?o.elevation.getAtPointOrZero(o.locationCoordinate(u),o._centerAltitude):o._centerAltitude;Kt(x,x,b,ks(1,0)*ar*S);const A=G(new Float64Array(16));return Q(A,o.pixelMatrix,o.globeMatrix),Ar(x,x,A),new jt(x[0],x[1])}globeCenterToScreenPoint(o){return zJ(o)}pixelsPerMeter(o,u){return ks(1,0)*u}pixelSpaceConversion(o,u,m){const x=ks(1,o)*u,b=Kr(ks(1,45)*u,x,m);return this.pixelsPerMeter(o,u)/b}createTileMatrix(o,u,m){const x=Lz(kp(m.canonical));return Q(new Float64Array(16),o.globeMatrix,x)}createInversionMatrix(o,u){const{center:m}=o,x=NR(kp(u));return pe(x,x,Bn(m.lng)),oe(x,x,Bn(m.lat)),ie(x,x,[o._pixelsPerMercatorPixel,o._pixelsPerMercatorPixel,1]),Float32Array.from(x)}pointCoordinate(o,u,m,x){return MJ(o,u,m,!0)||new os(0,0)}pointCoordinate3D(o,u,m){const x=this.pointCoordinate(o,u,m,0);return[x.x,x.y,x.z]}isPointAboveHorizon(o,u){return!MJ(o,u.x,u.y,!1)}farthestPixelDistance(o){const u=function(x,b){const S=x.cameraToCenterDistance,A=x._centerAltitude*b,I=x._camera,D=x._camera.forward(),B=vt([],ft([],D,-S),[0,0,A]),U=x.worldSize/(2*Math.PI),q=[0,0,-U],K=x.width/x.height,X=Math.tan(x.fovAboveCenter),J=ft([],I.up(),X),se=ft([],I.right(),X*K),ae=zt([],vt([],vt([],D,J),se)),ue=[];let ce;if(new AR(B,ae).closestPointOnSphere(q,U,ue)){const de=vt([],ue,q),xe=Or([],de,B);ce=Math.cos(x.fovAboveCenter)*ot(xe)}else{const de=Or([],B,q),xe=Or([],q,B);zt(xe,xe);const ve=ot(de)-U;ce=Math.sqrt(ve*(ve+2*U));const Ue=Math.acos(ce/(U+ve))-Math.acos(Vr(D,xe));ce*=Math.cos(Ue)}return 1.01*ce}(o,this.pixelsPerMeter(o.center.lat,o.worldSize)),m=Ip(o.zoom);if(m>0){const x=HJ(o,ks(1,o.center.lat)*o.worldSize),b=o.worldSize/(2*Math.PI),S=Math.max(o.width,o.height)/o.worldSize*Math.PI;return Kr(u,x+b*(1-Math.cos(S)),Math.pow(m,10))}return u}upVector(o,u,m){return ak(u,m,o,1)}upVectorScale(o){return{metersToTile:IR(CR(kp(o)))}}}function OR(h){const o=h.parallels,u=!!o&&Math.abs(o[0]+o[1])<.01;switch(h.name){case"mercator":return new WJ(h);case"equirectangular":return new NRe(h);case"naturalEarth":return new LRe(h);case"equalEarth":return new PRe(h);case"winkelTripel":return new DRe(h);case"albers":return u?new ZJ(h):new CRe(h);case"lambertConformalConic":return u?new ZJ(h):new RRe(h);case"globe":return new MRe(h)}throw new Error(`Invalid projection name: ${h.name}`)}const dk=Number.MAX_SAFE_INTEGER,ORe=dk-1;function Fz(h,o,u,m){return h.ordero.max.x||h.max.xo.max.y||h.max.y1)return!1;const m=u.getSource().maxzoom,x=1<1)return u;const b=x.getSource().maxzoom,S=1<{const I=this.getAtTileOffset(o,b,S,A),D=x.upVector(o.canonical,b.x,b.y);return ft(D,D,I*x.upVectorScale(o.canonical,u,m).metersToTile),D}}getForTilePoints(o,u,m,x){if(this.isUsingMockSource())return!1;const b=Y1.create(this,o,x);return!!b&&(u.forEach(S=>{S[2]=this.exaggeration()*b.getElevationAt(S[0],S[1],m,!0)}),!0)}getMinMaxForTile(o){if(this.isUsingMockSource())return null;const u=this.findDEMTileFor(o);if(!u||!u.dem)return null;const m=u.dem.tree,x=u.tileID,b=1<"u"?null:new TextDecoder("utf-8");class GR{constructor(o){this.buf=ArrayBuffer.isView(o)?o:new Uint8Array(o),this.dataView=new DataView(this.buf.buffer,this.buf.byteOffset,this.buf.byteLength),this.pos=0,this.type=0,this._valueStart=-1,this.length=this.buf.length}readFields(o,u,m=this.length){let x;for(;x=this.nextField(m);)o(x,u,this);return u}readMessage(o,u){return this.readFields(o,u,this.readVarint()+this.pos)}readFixed32(){const o=this.dataView.getUint32(this.pos,!0);return this.pos+=4,o}readSFixed32(){const o=this.dataView.getInt32(this.pos,!0);return this.pos+=4,o}readFixed64(){const o=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*Hz;return this.pos+=8,o}readSFixed64(){const o=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*Hz;return this.pos+=8,o}readFloat(){const o=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,o}readDouble(){const o=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,o}readVarint(o){const u=this.buf,m=u[this.pos++];if(m<128)return m;let x,b=127&m;return x=u[this.pos++],b|=(127&x)<<7,x<128?b:(x=u[this.pos++],b|=(127&x)<<14,x<128?b:(x=u[this.pos++],b|=(127&x)<<21,x<128?b:(x=u[this.pos],b|=(15&x)<<28,function(S,A,I){const D=I.buf;let B,U;if(U=D[I.pos++],B=(112&U)>>4,U<128||(U=D[I.pos++],B|=(127&U)<<3,U<128)||(U=D[I.pos++],B|=(127&U)<<10,U<128)||(U=D[I.pos++],B|=(127&U)<<17,U<128)||(U=D[I.pos++],B|=(127&U)<<24,U<128)||(U=D[I.pos++],B|=(1&U)<<31,U<128))return Z1(S,B,A);throw new Error("Expected varint not more than 10 bytes")}(b,o,this))))}readSVarint(){const o=this.readVarint();return o%2==1?(o+1)/-2:o/2}readBoolean(){return!!this.readVarint()}readString(){const o=this.readVarint()+this.pos,u=this.pos;return this.pos=o,o-u>=12&&oee?oee.decode(this.buf.subarray(u,o)):function(m,x,b){let S="",A=x;for(;A239?4:I>223?3:I>191?2:1;if(A+K>b)break;K===1?I<128&&(q=I):K===2?(D=m[A+1],(192&D)==128&&(q=(31&I)<<6|63&D,q<=127&&(q=null))):K===3?(D=m[A+1],B=m[A+2],(192&D)==128&&(192&B)==128&&(q=(15&I)<<12|(63&D)<<6|63&B,(q<=2047||q>=55296&&q<=57343)&&(q=null))):K===4&&(D=m[A+1],B=m[A+2],U=m[A+3],(192&D)==128&&(192&B)==128&&(192&U)==128&&(q=(15&I)<<18|(63&D)<<12|(63&B)<<6|63&U,(q<=65535||q>=1114112)&&(q=null))),q===null?(q=65533,K=1):q>65535&&(q-=65536,S+=String.fromCharCode(q>>>10&1023|55296),q=56320|1023&q),S+=String.fromCharCode(q),A+=K}return S}(this.buf,u,o)}readBytes(){const o=this.readVarint()+this.pos,u=this.buf.subarray(this.pos,o);return this.pos=o,u}readPackedVarint(o=[],u){const m=this.readPackedEnd();for(;this.pos=o)return 0;const u=this.readVarint();return this.type=7&u,this._valueStart=this.pos,u>>>3}skip(o){const u=7&o;if(u===0)for(;this.buf[this.pos++]>127;);else if(u===2)this.pos=this.readVarint()+this.pos;else if(u===5)this.pos+=4;else{if(u!==1)throw new Error(`Unimplemented type: ${u}`);this.pos+=8}}}function Z1(h,o,u){return u?4294967296*o+(h>>>0):4294967296*(o>>>0)+(h>>>0)}function lee(h,o,u){const m=o<=16383?1:o<=2097151?2:o<=268435455?3:Math.floor(Math.log(o)/(7*Math.LN2));u.realloc(m),u.buf.copyWithin(h+m,h,u.pos)}function zRe(h,o){const u=h.length;let m=o.buf,x=o.pos,b=o.length;for(let S=0;Sb)o.pos=x,o.writeVarint(A),m=o.buf,x=o.pos,b=o.length;else{for(;A>127;)m[x++]=A%128|128,A=Math.floor(A/128);m[x++]=A}}o.pos=x}function $Re(h,o){for(let u=0;uA.h-S.h);const m=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(o/.95)),u),h:1/0}];let x=0,b=0;for(const S of h)for(let A=m.length-1;A>=0;A--){const I=m[A];if(!(S.w>I.w||S.h>I.h)){if(S.x=I.x,S.y=I.y,b=Math.max(b,S.y+S.h),x=Math.max(x,S.x+S.w),S.w===I.w&&S.h===I.h){const D=m.pop();D&&Ao.id?1:h.versiono.version?1:h.sxo.sx?1:h.syo.sy?1:0}function WR(h){let o=0;for(let u=0;u0,uee(o,m,this.iconDescriptors,S),uee(u,m,this.patternDescriptors,S),this.iconDescriptors.sort(HR),this.patternDescriptors.sort(HR);let A=0;A=Rh(A,WR(b)),A=Rh(A,1);const I=x?x.data:"";I&&(A=Rh(A,WR(I))),A=Rh(A,1);for(const D of this.iconDescriptors)A=Rh(A,WR(D.id)),A=Rh(A,D.version),A=Rh(A,D.sx),A=Rh(A,D.sy);A=Rh(A,1);for(const D of this.patternDescriptors)A=Rh(A,WR(D.id)),A=Rh(A,D.version),A=Rh(A,D.sx),A=Rh(A,D.sy);this.hash=A}subsetOf(o){return this.scope===o.scope&&this.isSubsetArray(this.iconDescriptors,o.iconDescriptors,HR)&&this.isSubsetArray(this.patternDescriptors,o.patternDescriptors,HR)}isSubsetArray(o,u,m){let x=0,b=0;if(o.length>u.length)return!1;for(;x0&&B>0){const q=this.useMipmap?Math.floor(Math.log2(Math.max(D,B)))+1:1;S.texStorage2D(S.TEXTURE_2D,q,this.format,D,B),this.size=[D,B]}this.size&&(U?S.texSubImage2D(S.TEXTURE_2D,0,A,I,Kz(this.format),Yz(this.format),o):"data"in o&&o.data&&S.texSubImage2D(S.TEXTURE_2D,0,A,I,m,x,Kz(this.format),Yz(this.format),o.data)),this.useMipmap&&S.generateMipmap(S.TEXTURE_2D)}bind(o,u,m=!1){const{context:x}=this,{gl:b}=x;b.bindTexture(b.TEXTURE_2D,this.texture),o!==this.minFilter&&(b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,o),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,this.useMipmap&&!m?o===b.NEAREST?b.NEAREST_MIPMAP_NEAREST:b.LINEAR_MIPMAP_LINEAR:o),this.minFilter=o),u!==this.wrapS&&(b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,u),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,u),this.wrapS=u)}bindExtraParam(o,u,m,x,b){const{context:S}=this,{gl:A}=S;A.bindTexture(A.TEXTURE_2D,this.texture),u!==this.magFilter&&(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MAG_FILTER,u),this.magFilter=u),o!==this.minFilter&&(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_MIN_FILTER,this.useMipmap?o===A.NEAREST?A.NEAREST_MIPMAP_NEAREST:A.LINEAR_MIPMAP_LINEAR:o),this.minFilter=o),m!==this.wrapS&&(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_S,m),this.wrapS=m),x!==this.wrapT&&(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_WRAP_T,x),this.wrapT=x),b!==this.compareMode&&(b?(A.texParameteri(A.TEXTURE_2D,A.TEXTURE_COMPARE_MODE,A.COMPARE_REF_TO_TEXTURE),A.texParameteri(A.TEXTURE_2D,A.TEXTURE_COMPARE_FUNC,b)):A.texParameteri(A.TEXTURE_2D,A.TEXTURE_COMPARE_MODE,A.NONE),this.compareMode=b)}destroy(){const{gl:o}=this.context;o.deleteTexture(this.texture),this.texture=null}}class dee{constructor(o,u,m,x){this.context=o,this.format=x,this.size=m,this.texture=o.gl.createTexture();const[b,S,A]=this.size,{gl:I}=o;I.bindTexture(I.TEXTURE_3D,this.texture),o.pixelStoreUnpackFlipY.set(!1),o.pixelStoreUnpack.set(1),o.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in u&&u.data&&I.texImage3D(I.TEXTURE_3D,0,this.format,b,S,A,0,Kz(this.format),Yz(this.format),u.data)}bind(o,u){const{context:m}=this,{gl:x}=m;x.bindTexture(x.TEXTURE_3D,this.texture),o!==this.minFilter&&(x.texParameteri(x.TEXTURE_3D,x.TEXTURE_MAG_FILTER,o),x.texParameteri(x.TEXTURE_3D,x.TEXTURE_MIN_FILTER,o),this.minFilter=o),u!==this.wrapS&&(x.texParameteri(x.TEXTURE_3D,x.TEXTURE_WRAP_S,u),x.texParameteri(x.TEXTURE_3D,x.TEXTURE_WRAP_T,u),this.wrapS=u)}destroy(){const{gl:o}=this.context;o.deleteTexture(this.texture),this.texture=null}}class mk{static getImagePositionScale(o,u,m){if(u&&o){const{sx:x,sy:b}=o;return{x,y:b}}return{x:m,y:m}}constructor(o,u,m,x){this.paddedRect=o;const{pixelRatio:b,version:S,stretchX:A,stretchY:I,content:D,sdf:B,usvg:U}=u;this.pixelRatio=b,this.stretchX=A,this.stretchY=I,this.content=D,this.version=S,this.padding=m,this.sdf=B,this.usvg=U,this.scale=mk.getImagePositionScale(x,U,b)}get tl(){return[this.paddedRect.x+this.padding,this.paddedRect.y+this.padding]}get br(){return[this.paddedRect.x+this.paddedRect.w-this.padding,this.paddedRect.y+this.paddedRect.h-this.padding]}get displaySize(){return[(this.paddedRect.w-2*this.padding)/this.scale.x,(this.paddedRect.h-2*this.padding)/this.scale.y]}}function hee(h,o,u){const m=Io.parse(h),x=function(b,S,A=[1,1]){return{x:0,y:0,w:(b.data?b.data.width:b.width*A[0])+2*S,h:(b.data?b.data.height:b.height*A[1])+2*S}}(o,u,[m.sx,m.sy]);return{bin:x,imagePosition:new mk(x,o,u,m),imageVariant:m}}function Zz(h,o){const u=[];for(const[x,b]of h.entries()){const S=Io.parse(x);S&&(u.push({key:x,value:b,variant:S}),o&&o.set(x,S))}u.sort((x,b)=>{const S=x.variant.id.toString().localeCompare(b.variant.id.toString());return S!==0?S:x.variant.sx!==b.variant.sx?x.variant.sx-b.variant.sx:x.variant.sy!==b.variant.sy?x.variant.sy-b.variant.sy:x.key.localeCompare(b.key)});const m=new Map;for(const x of u)m.set(x.key,x.value);return m}class fee{constructor(o){this.sourceAtlasHash=o}}class mee{constructor(o,u,m,x,b=""){const S=new Map,A=new Map;this.haveRenderCallbacks=[];const I=[],D=x!==void 0,B=D?new Map:void 0,U=D?Zz(o,B):o,q=D?Zz(u,B):u;this.addImages(U,S,1,I),this.addImages(q,A,2,I);const{w:K,h:X}=cee(I),J=new Ec({width:K||1,height:X||1});for(const[se,ae]of U.entries()){const ue=S.get(se).paddedRect;Ec.copy(ae.data,J,{x:0,y:0},{x:ue.x+1,y:ue.y+1},ae.data,null,ae.sdf)}for(const[se,ae]of q.entries()){const ue=A.get(se),ce=ue.paddedRect;let de=ue.padding;const xe=ce.x+de,ve=ce.y+de,Ue=ae.data.width,Pe=ae.data.height;de=de>1?de-1:de,Ec.copy(ae.data,J,{x:0,y:0},{x:xe,y:ve},ae.data,m),Ec.copy(ae.data,J,{x:0,y:Pe-de},{x:xe,y:ve-de},{width:Ue,height:de},m),Ec.copy(ae.data,J,{x:0,y:0},{x:xe,y:ve+Pe},{width:Ue,height:de},m),Ec.copy(ae.data,J,{x:Ue-de,y:0},{x:xe-de,y:ve},{width:de,height:Pe},m),Ec.copy(ae.data,J,{x:0,y:0},{x:xe+Ue,y:ve},{width:de,height:Pe},m),Ec.copy(ae.data,J,{x:Ue-de,y:Pe-de},{x:xe-de,y:ve-de},{width:de,height:de},m),Ec.copy(ae.data,J,{x:0,y:Pe-de},{x:xe+Ue,y:ve-de},{width:de,height:de},m),Ec.copy(ae.data,J,{x:0,y:0},{x:xe+Ue,y:ve+Pe},{width:de,height:de},m),Ec.copy(ae.data,J,{x:Ue-de,y:0},{x:xe-de,y:ve+Pe},{width:de,height:de},m)}this.lut=m,this.image=J,this.iconPositions=S,this.patternPositions=A,D&&(this.contentDescriptor=new Wz(U,q,x,m,b,B))}addImages(o,u,m,x){for(const[b,S]of o.entries()){const{bin:A,imagePosition:I,imageVariant:D}=hee(b,S,m);u.set(b,I),x.push(A),S.hasRenderCallback&&this.haveRenderCallbacks.push(D.id)}}patchUpdatedImages(o,u,m,x){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(b=>o.hasImage(b,m)),o.dispatchRenderCallbacks(this.haveRenderCallbacks,m);for(const b of o.getUpdatedImages(m)){for(const S of this.iconPositions.keys()){const A=Io.parse(S);if(ga.isEqual(A.id,b)){const I=o.getImage(b,m);this.patchUpdatedImage(this.iconPositions.get(S),I,u,null)}}for(const S of this.patternPositions.keys()){const A=Io.parse(S);if(ga.isEqual(A.id,b)){const I=o.getImage(b,m);this.patchUpdatedImage(this.patternPositions.get(S),I,u,x||this.lut)}}}}patchUpdatedImage(o,u,m,x=null){if(!o||!u||o.version===u.version)return;o.version=u.version;const[b,S]=o.tl,A=o.sdf;if(this.lut||A){const I={width:u.data.width,height:u.data.height},D=new Ec(I);Ec.copy(u.data,D,{x:0,y:0},{x:0,y:0},I,x,A),m.update(D,{position:{x:b,y:S},recreateWhenResize:!1})}else m.update(u.data,{position:{x:b,y:S},recreateWhenResize:!1})}}vr(mk,"ImagePosition"),vr(mee,"ImageAtlas",{omit:["lut"]}),vr(fee,"ImageAtlasReference");const pk=1e20,Xz=new Float64Array(256);for(let h=0;h<256;h++){const o=.5-Math.pow(h/255,.45454545454545453);Xz[h]=o*Math.abs(o)}function pee(h,o,u,m,x,b,S,A,I,D=0){for(let B=o+D;B-1);I++,b[I]=A,S[I]=U,S[I+1]=pk}for(let A=0,I=0;A=131072&&u<=173791||(m=>m>=66736&&m<=66815)(o));var u}draw(o,u){if(!this.supports(u))return;const m=function(J){return XRe.test(J)?"900":QRe.test(J)?"500":JRe.test(J)?"200":"400"}(o),x=this.glyphs[m][u];if(x)return x;let b=this.tinySDFs[m];b||(b=this.tinySDFs[m]=new NEe.TinySDF({fontFamily:this.fontFamily,fontWeight:m,fontSize:48,buffer:6,radius:16}));const S=String.fromCodePoint(u),{data:A,width:I,height:D,glyphWidth:B,glyphHeight:U,glyphLeft:q,glyphTop:K,glyphAdvance:X}=b.draw(S);return this.glyphs[m][u]={id:u,bitmap:new Yx({width:I,height:D},A),metrics:{width:B/2,height:U/2,left:q/2,top:K/2-27,advance:X/2,localGlyph:!0}}}};xee.TinySDF=class{constructor({fontSize:h=24,buffer:o=3,radius:u=8,cutoff:m=.25,fontFamily:x="sans-serif",fontWeight:b="normal",fontStyle:S="normal",lang:A=null}={}){o=this.buffer=Math.round(o),this.radius=u,this.cutoff=m,this.lang=A;const I=this.size=Math.ceil(h)+4*o,D=this._createCanvas(I),B=this.ctx=D.getContext("2d",{willReadFrequently:!0});B.font=`${S} ${b} ${h}px ${x}`,B.textBaseline="alphabetic",B.textAlign="left",B.fillStyle="black",A&&(B.lang=A);const U=(this.maxGlyphDim=I-o)+2*o;this.gridOuter=new Float64Array(U*U),this.gridInner=new Float64Array(U*U),this.f=new Float64Array(U),this.z=new Float64Array(U+1),this.v=new Uint16Array(U)}_createCanvas(h){if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(h,h);const o=document.createElement("canvas");return o.width=o.height=h,o}draw(h){const{width:o,actualBoundingBoxAscent:u,actualBoundingBoxDescent:m,actualBoundingBoxLeft:x,actualBoundingBoxRight:b}=this.ctx.measureText(h),S=Math.ceil(u),A=Math.floor(-x),I=Math.max(0,Math.min(this.maxGlyphDim,Math.ceil(b)-A)),D=Math.max(0,Math.min(this.maxGlyphDim,S+Math.ceil(m))),B=I+2*this.buffer,U=D+2*this.buffer,q=B*U,K=new Uint8ClampedArray(q),X={data:K,width:B,height:U,glyphWidth:I,glyphHeight:D,glyphTop:S,glyphLeft:A,glyphAdvance:o};if(I===0||D===0)return X;const{ctx:J,buffer:se,gridInner:ae,gridOuter:ue}=this;J.clearRect(se,se,I,D),J.fillText(h,se-A,se+S);const ce=J.getImageData(se,se,I,D);ue.fill(pk,0,q),ae.fill(0,0,q);let de=3;for(let Pe=0;Pe{const ht=ZR(Fe.stretch-ue,ce,B,h.left*x),_t=XR(Fe.fixed-ve,Ue,Fe.stretch,X),Et=ZR(Ze.stretch-de,xe,U,h.top*x),Pt=XR(Ze.fixed-Pe,De,Ze.stretch,J),Rt=ZR(st.stretch-ue,ce,B,h.left*x),Ye=XR(st.fixed-ve,Ue,st.stretch,X),At=ZR(ut.stretch-de,xe,U,h.top*x),Tt=XR(ut.fixed-Pe,De,ut.stretch,J),$t=new jt(ht,Et),Gt=new jt(Rt,Et),kt=new jt(Rt,At),Dt=new jt(ht,At),dr=new jt(_t/A,Pt/A),nr=new jt(Ye/A,Tt/A),yr=o*Math.PI/180;if(yr){const Fr=Math.sin(yr),ni=Math.cos(yr),ii=[ni,-Fr,Fr,ni];$t._matMult(ii),Gt._matMult(ii),Dt._matMult(ii),kt._matMult(ii)}const Br=Fe.stretch+Fe.fixed,br=st.stretch+st.fixed,dn=Ze.stretch+Ze.fixed,rn=ut.stretch+ut.fixed,wr=h.imageSecondary;return{tl:$t,tr:Gt,bl:Dt,br:kt,texPrimary:{x:S.paddedRect.x+1+Br,y:S.paddedRect.y+1+dn,w:br-Br,h:rn-dn},texSecondary:wr?{x:wr.paddedRect.x+1+Br,y:wr.paddedRect.y+1+dn,w:br-Br,h:rn-dn}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:dr,pixelOffsetBR:nr,minFontScaleX:Ue/A/B,minFontScaleY:De/A/U,isSDF:u}};if(S.stretchX||S.stretchY){const Fe=bee(q,se,X),Ze=bee(K,ae,J);for(let st=0;st0?[ue,-ce]:de<0?[-ue,ce]:ue===0?[ce,ue]:[ce,-ue]}(u);let K=Math.abs(o.top-o.bottom);for(const ae of o.positionedLines)K-=ae.lineOffset;const X=o.positionedLines.length,J=K/X;let se=o.top-u[1];for(let ae=0;aefunction(b){if(!b.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const S=b.condition.expression;return{featureDependent:!Og(S),stateDependent:!Fg(S),zoomDependent:!am(S,["zoom"]),pitchDependent:!am(S,["pitch"]),brightnessDependent:!am(S,["brightness","measure-light"]),worldviewDependent:!am(S,["worldview"])}}(x));this.anyFeatureDependent=m.some(x=>x.featureDependent),this.anyStateDependent=m.some(x=>x.stateDependent)}update(o,u){const m=this.lastParams,x=!m||m.zoom!==o.zoom||m.pitch!==(o.pitch||0)||m.brightness!==(o.brightness||0)||m.worldview!==o.worldview;this.lastParams={zoom:o.zoom,pitch:o.pitch||0,brightness:o.brightness||0,worldview:o.worldview};const b=u&&this.anyStateDependent;if(!x&&!b&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!b){const S=this.evaluateAllFeatures(o);return S===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=S,{kind:"all-features",appearanceIndex:S})}return{kind:"per-feature"}}evaluateAllFeatures(o){for(let u=0;uS-A),b=new Map;for(const S of x){const A=m.get(S);b.set(S,new xn(A))}return u&&(this.cachedBatchIndices=x,this.cachedBatchSegments=b),{batchIndices:x,batchSegments:b}}snapshotSymbolVertexData(o,u){const m=o*X1;return this.layoutVertexArray.uint16.slice(m,m+u*X1)}restoreSymbolVertexData(o,u){this.layoutVertexArray.uint16.set(u,o*X1)}snapshotIconTransitioningVertexData(o,u){const m=2*o;return this.iconTransitioningVertexArray.uint16.slice(m,m+2*u)}restoreIconTransitioningVertexData(o,u){this.iconTransitioningVertexArray.uint16.set(u,2*o)}updateSymbolVertexData(o,u,m,x,b,S,A,I,D,B,U,q,K){const X=this.layoutVertexArray.uint16,J=o*X1;X[J]=u,X[J+1]=m,X[J+2]=x,X[J+3]=b,X[J+4]=S,X[J+5]=A,X[J+6]=I,X[J+7]=D,X[J+8]=B,X[J+9]=U,X[J+10]=q,X[J+11]=K}upload(o,u,m,x,b,S){this.isEmpty()||(m&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=o.createVertexBuffer(this.layoutVertexArray,nRe.members,!!S),this.indexBuffer=o.createIndexBuffer(this.indexArray,u),this.dynamicLayoutVertexBuffer=o.createVertexBuffer(this.dynamicLayoutVertexArray,sRe.members,!0),this.opacityVertexBuffer=o.createVertexBuffer(this.opacityVertexArray,sLe,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=o.createVertexBuffer(this.iconTransitioningVertexArray,uRe.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=o.createVertexBuffer(this.globeExtVertexArray,iRe.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||b)&&(this.zOffsetVertexBuffer=o.createVertexBuffer(this.zOffsetVertexArray,oRe.members,!0),this.zOffsetVertexArray.clear(),this.zOffsetVertexArray._trim()),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=o.createVertexBuffer(this.orientationVertexArray,cRe.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray.length>0&&(this.featureIdBuffer=o.createVertexBuffer(this.featureIdArray,lRe.members,!1))),this.fadeUploadPending()&&(this.fadeVertexBuffer=o.createVertexBuffer(this.fadeVertexArray,aRe.members,!0)),(m||x)&&(this.programConfigurations.upload(o),this.uboBinder&&this.uboBinder.upload(o)))}fadeUploadPending(){return this.fadeVertexArray.length>0&&!this.fadeVertexBuffer}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy(),this.iconTransitioningVertexBuffer&&this.iconTransitioningVertexBuffer.destroy(),this.fadeVertexBuffer&&this.fadeVertexBuffer.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.orientationVertexBuffer&&this.orientationVertexBuffer.destroy(),this.featureIdBuffer&&this.featureIdBuffer.destroy(),this.uboBinder&&this.uboBinder.destroy())}}vr(Qz,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class Jz{constructor(o,u,m){this.layoutVertexArray=new o,this.layoutAttributes=u,this.indexArray=new m,this.segments=new xn,this.collisionVertexArray=new qe,this.collisionVertexArrayExt=new Y}upload(o){this.layoutVertexBuffer=o.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=o.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=o.createVertexBuffer(this.collisionVertexArray,dRe.members,!0),this.collisionVertexBufferExt=o.createVertexBuffer(this.collisionVertexArrayExt,hRe.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}vr(Jz,"CollisionBuffers");class _k{constructor(o){this.collisionBoxArray=o.collisionBoxArray,this.zoom=o.zoom,this.overscaling=o.overscaling,this.layers=o.layers,this.layerIds=this.layers.map(S=>S.fqid),this.index=o.index,this.pixelRatio=o.pixelRatio,this.sourceLayerIndex=o.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.placementVariantVisible=[],this.placementFadeRefTime=new Float64Array(0),this.placementFadeRunning=new Uint8Array(0),this._activeFadeCount=0,this._fadeDuration=0,this.collisionCircleArray=[],this.placementInvProjMatrix=G([]),this.placementViewportMatrix=G([]);const u=this.layers[0];this.worldview=o.worldview,this.localizable=o.localizable,this.maxUniformBlockSizeDwords=o.maxUniformBlockSizeDwords,this.textSizeData=H1(this.zoom,u.getLayoutPropertyValue("text-size"),this.worldview,o.availableImages),this.iconSizeData=H1(this.zoom,u.getLayoutPropertyValue("icon-size"),this.worldview,o.availableImages);const m=this.layers[0].layout,x=m.get("symbol-sort-key"),b=m.get("symbol-z-order");this.lut=o.lut,this.canOverlap=m.get("text-allow-overlap")||m.get("icon-allow-overlap")||m.get("text-ignore-placement")||m.get("icon-ignore-placement"),this.sortFeaturesByKey=b!=="viewport-y"&&x.constantOr(1)!==void 0,this.sortFeaturesByY=(b==="viewport-y"||b==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=m.get("text-writing-mode").map(S=>Zg[S]),this.stateDependentLayerIds=this.layers.filter(S=>S.isStateDependent()).map(S=>S.id),this.sourceID=o.sourceID,this.projection=o.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(o){const u=this.layers[0].getAppearances();if(!u||u.length===0)return!1;const m=Array.isArray(o)?o:[o];return u.some(x=>m.some(b=>x.hasLayoutProperty(b)))}getAppearanceFeatureData(o){return this.featureAppearanceData.get(o)}createArrays(){this.text=new Qz(new Hi(this.layers,{zoom:this.zoom,lut:this.lut},o=>o.startsWith("text")||o.startsWith("symbol"))),this.icon=new Qz(new Hi(this.layers,{zoom:this.zoom,lut:this.lut},o=>o.startsWith("icon")||o.startsWith("symbol"))),this.text.uboBinder=new Tz(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBlockSizeDwords),this.icon.uboBinder=new Tz(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBlockSizeDwords),this.glyphOffsetArray=new Xt,this.lineVertexArray=new mr,this.symbolInstances=new ur}calculateGlyphDependencies(o,u,m,x,b){for(const S of o){const A=S.codePointAt(0);if(A===void 0)break;if(u[A]=!0,x&&b&&A<=65535){const I=sk[S];I&&(u[I.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(o,u,m,x,b,S,A){if(!o.hasLayoutProperty("icon-size"))return A*S;let I=1;const D=o.getUnevaluatedLayoutProperty("icon-size"),B=H1(this.zoom,D,this.worldview,b),U=Xg(B,u);if(B.kind!=="constant"&&B.kind!=="camera"||(I=U.uSize),B.kind==="composite"){const{minZoom:q,maxZoom:K}=B,X=D.possiblyEvaluate(new Hs(q,{worldview:this.worldview}),x),J=D.possiblyEvaluate(new Hs(K,{worldview:this.worldview}),x),se=X.evaluate(m,{},x,b);I=se+(J.evaluate(m,{},x,b)-se)*U.uSizeT}return B.kind==="source"&&(I=D.possiblyEvaluate(new Hs(this.zoom,{worldview:this.worldview}),x).evaluate(m,{},x,b)),I*S}updateFootprints(o,u){}hideSymbolVariant(o,u){this._setSymbolVariantVisibility(o,!1,u)}showSymbolVariant(o,u){this._setSymbolVariantVisibility(o,!0,u)}_initPlacementOpacities(){const o=u=>{const m=u.layoutVertexArray.length;for(let x=0;x0}_writeFadeState(o,u,m,x){const b=(S,A)=>{if(A<0)return;const I=S.placedSymbolArray.get(A),D=I.vertexStartIndex;for(let B=0;B<4*I.numGlyphs;B++)S.fadeVertexArray.emplace(D+B,m,x);S.fadeVertexBuffer&&S.fadeVertexBuffer.updateData(S.fadeVertexArray)};this.hasTextData()&&b(this.text,this.defaultPlacedTextSymbolIndex(u,o)),this.hasIconData()&&b(this.icon,u.placedIconSymbolIndex)}_settleFinishedFade(o,u,m){this.placementFadeRunning[o]!==0&&(m-this.placementFadeRefTime[o]{for(let m=0;m0)return void Xi("new placement: symbol appearances are not supported yet; hiding symbols");if(ae.layout.get("symbol-placement")!=="point")return void Xi("new placement: along-line symbol placement is not supported yet; hiding symbols");const ue=!!ae.layout.get("text-variable-anchor"),ce=this.getProjection(),de=ce.name==="globe"?Ip(S.zoom):1,xe=de<1,ve=I.tileID.toUnwrapped(),Ue={overscaledZ:I.tileID.overscaledZ,wrap:I.tileID.wrap,canonical:I.tileID.canonical},Pe=S.pitch>0,De={},Ve=iee(ae.layout.get("icon-allow-overlap"),ae.layout.get("icon-ignore-placement")),Fe=iee(ae.layout.get("text-allow-overlap"),ae.layout.get("text-ignore-placement")),Ze=S.zoom,st=Xg(this.iconSizeData,Ze),ut=Xg(this.textSizeData,Ze),ht=ae.paint.get("symbol-z-offset"),_t=ae.layout.get("symbol-elevation-reference")==="sea",Et=!ht.isConstant(),Pt=Et?0:ht.evaluate(null,{}),Rt=S.elevation,Ye=see(U),At=wr=>{if(!wr)return Ye;const Fr=B.get(Bx(wr,ae.scope));return Fr!==void 0?Fr:(Xi(`global placement: placement-group "${wr}" does not match any placement-group layer; using the layer's implicit group`),Ye)},Tt=ae.paint.get("placement-priority"),$t=ae.paint.get("placement-group"),Gt=!Tt.isConstant(),kt=!$t.isConstant(),Dt=Gt?0:Tt.evaluate(null,{}),dr=kt?Ye:At($t.evaluate(null,{})),nr=Gt||kt,yr=o.isCollectingDebugData(),Br=Et||nr||yr?I.latestFeatureIndex:null;Br&&Br.loadVTLayers();const br=Br?Br.sourceLayerCoder.decode(this.sourceLayerIndex):"",dn=(wr,Fr,ni)=>{let ii;if(this.elevationType==="road")ii=_t?ni:ni+Vz.getAtTileOffset(I.tileID,new jt(wr.tileAnchorX,wr.tileAnchorY),Rt,null);else{const Fs=this.hdExt?this.hdExt.elevationFeatures[Fr.elevationFeatureIndex]:void 0;ii=_t?ni:ni+Vz.getAtTileOffset(I.tileID,new jt(wr.tileAnchorX,wr.tileAnchorY),Rt,Fs)}ii+=Fr.zOffset;let Xn=wr.projectedAnchorX,bi=wr.projectedAnchorY,mi=wr.projectedAnchorZ;const ws=!!ii;if(ws){const[Fs,Xa,ns]=ce.upVector(I.tileID.canonical,wr.tileAnchorX,wr.tileAnchorY),Gi=ce.upVectorScale(I.tileID.canonical,S.center.lat,S.worldSize).metersToTile*ii;Xn+=Fs*Gi,bi+=Xa*Gi,mi+=ns*Gi}if(ce.name==="globe"&&xe){const Fs=I.tileID.canonical,Xa=1<0?(Ki(Ia,Ia,Fs),_n&&Kc.name!=="globe"&&(oo=tee(_n,Xa,ns,Gi,Bs,ka)>.9)):Uz(Ia,Ia,Fs);const es=Ia[3];return{x:(Ia[0]/es+1)/2*ka.width,y:(-Ia[1]/es+1)/2*ka.height,perspectiveRatio:Math.min(.5+ka.getCameraToCenterDistance(Kc)/es*.5,1.5),occluded:Sl&&Ia[2]>es||oo}}(m,Xn,bi,mi,S,ce,Pe||ws||ce.name==="globe",D,ve)},rn=(wr,Fr,ni,ii,Xn)=>{if(!wr)return;const bi=dn(wr,ni,ii);if(bi.occluded||bi.perspectiveRatio<=.55)return;const mi=Xn(),ws=A*bi.perspectiveRatio,Fs=(wr.x1*mi-wr.padding)*ws+bi.x,Xa=(wr.y1*mi-wr.padding)*ws+bi.y,ns=(wr.x2*mi+wr.padding)*ws+bi.x,Gi=(wr.y2*mi+wr.padding)*ws+bi.y;Fs0||Fr.numVerticalGlyphVertices>0)){Xi("new placement: text-variable-anchor is not supported yet; skipping symbols");continue}if(Fr.numVerticalGlyphVertices>0){Xi("new placement: vertical text-writing-mode is not supported yet; skipping symbols");continue}const ni=this.getCollisionArrays(I.collisionBoxArray,Fr);if(!ni.iconBox&&!ni.textBox)continue;let ii=!1;for(const Gi of this.activeReplacements)if(!Fz(Gi,U,hk.Symbol,ae.scope)&&!(Gi.min.x>Fr.tileAnchorX||Fr.tileAnchorX>Gi.max.x||Gi.min.y>Fr.tileAnchorY||Fr.tileAnchorY>Gi.max.y)&&(ii=VR($z(Fr.tileAnchorX,Fr.tileAnchorY,I.tileID.canonical,Gi.footprintTileId.canonical),Gi.footprint),ii))break;const Xn={symbolId:{styleLayerId:u,symbolIdOrigin:1,symbolId:oLe(this.bucketInstanceId,wr)},variantIdx:0},bi=J.length>0&&J.some(Gi=>Fr.tileAnchorX>=Gi.min.x&&Fr.tileAnchorX=Gi.min.y&&Fr.tileAnchorYthis.getSymbolInstanceIconSize(st,Ze,Fr.placedIconSymbolIndex)),rn(ni.textBox,Fe,Fr,Gi,()=>this.getSymbolInstanceTextSize(ut,Fr,Ze,wr))}o.finishVariantProcessing()}}updateReplacement(o,u){if(u.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=u.updateTime;const m=u.getReplacementRegionsForTile(o.toUnwrapped(),!0);return!BR(this.activeReplacements,m)&&(this.activeReplacements=m,!0)}getResolvedImageFromTokens(o){return typeof o=="string"?Ol.build(o):o}populate(o,u,m,x){const b=this.layers[0],S=b.layout,A=this.projection.name==="globe",I=S.get("text-font"),D=S.get("text-field"),B=S.get("icon-image"),[U,q]=S.get("icon-size-scale-range"),K=cn(u.scaleFactor||1,U,q),[X,J]=S.get("text-size-scale-range"),se=cn(u.scaleFactor||1,X,J),ae=(D.value.kind!=="constant"||D.value.value instanceof sl&&!D.value.value.isEmpty()||D.value.value.toString().length>0)&&(I.value.kind!=="constant"||I.value.value.length>0),ue=B.value.kind!=="constant"||!!B.value.value||Object.keys(B.parameters).length>0,ce=this.hasAnyAppearanceLayoutProperty("icon-image"),de=this.layers[0].getAppearances().length>0,xe=S.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!ae&&!ue&&!ce)return;const ve=u.iconDependencies,Ue=u.glyphDependencies,Pe=u.availableImages,De=new Hs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),Ve=Fe=>{const Ze=Fe.id.toString();ve.has(Ze)?ve.get(Ze).push(Fe):ve.set(Ze,[Fe])};for(const Fe of o){const{feature:Ze,id:st,index:ut,sourceLayerIndex:ht}=Fe,_t=b._featureFilter.needGeometry,Et=Ph(Ze,_t);if(!b._featureFilter.filter(De,Et,m))continue;if(Et.geometry=Ch(Ze,Et,_t,m,x),A&&Ze.type!==1&&m.z<=5){const kt=Et.geometry,Dt=.98078528056,dr=(nr,yr)=>Vr(ak(nr.x,nr.y,m,1),ak(yr.x,yr.y,m,1)){if(!kt.getLayoutProperty("icon-image"))return;const{iconPrimary:Dt,iconSecondary:dr}=this.getCombinedIconVariants(kt,Ye,Et,m,Pe,$t,K);Dt&&(Ve(Dt),dr&&(this.hasAnySecondaryIcon=!0,Ve(dr)))}),Pt){const kt=I.evaluate(Et,{},m).join(","),Dt=S.get("text-rotation-alignment")==="map"&&S.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.includes(Zg.vertical);for(const dr of Pt.sections)if(dr.image){const nr=dr.image.getPrimary().scaleSelf(this.pixelRatio*se),yr=nr.id.toString(),Br=ve.get(yr)||[];Br.push(nr),ve.set(yr,Br)}else{const nr=j0(Pt.toString()),yr=dr.fontStack||kt,Br=Ue[yr]=Ue[yr]||{};this.calculateGlyphDependencies(dr.text,Br,Dt,this.allowVerticalPlacement,nr)}}}S.get("symbol-placement")==="line"&&(this.features=function(Fe){const Ze={},st={},ut=[];let ht=0;function _t(Ye){ut.push(Fe[Ye]),ht++}function Et(Ye,At,Tt){const $t=st[Ye];return delete st[Ye],st[At]=$t,ut[$t].geometry[0].pop(),ut[$t].geometry[0]=ut[$t].geometry[0].concat(Tt[0]),$t}function Pt(Ye,At,Tt){const $t=Ze[At];return delete Ze[At],Ze[Ye]=$t,ut[$t].geometry[0].shift(),ut[$t].geometry[0]=Tt[0].concat(ut[$t].geometry[0]),$t}function Rt(Ye,At,Tt){const $t=Tt?At[0].at(-1):At[0][0];return`${Ye}:${$t.x}:${$t.y}`}for(let Ye=0;Ye1){_t(Ye);continue}const Gt=Rt($t,Tt,!1),kt=Rt($t,Tt,!0);if(Gt in st&&kt in Ze&&st[Gt]!==Ze[kt]){const Dt=Pt(Gt,kt,Tt),dr=Et(Gt,kt,ut[Dt].geometry);delete Ze[Gt],delete st[kt],st[Rt($t,ut[dr].geometry,!0)]=dr,ut[Dt].geometry=null}else Gt in st?Et(Gt,kt,Tt):kt in Ze?Pt(Gt,kt,Tt):(_t(Ye),Ze[Gt]=ht-1,st[kt]=ht-1)}return ut.filter(Ye=>Ye.geometry)}(this.features)),S.get("symbol-elevation-reference")==="hd-road-markup"?(this.elevationType="road",this.hdExt&&(this.hdExt.configureCrossSource(m,u.elevationParams,u.crossSourceElevationEnabled,u.terrainEnabled),u.elevationFeatures&&u.elevationFeatures.length>0&&this.hdExt.addElevationFeatures(u.elevationFeatures,m))):S.get("symbol-z-elevate")&&(this.elevationType="offset"),this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Fe,Ze)=>Fe.sortKey-Ze.sortKey)}getCombinedIconVariants(o,u,m,x,b,S,A){let I;if(o.hasLayoutProperty("icon-image")){const D=u.getAppearanceValueAndResolveTokens(o,"icon-image",m,x,b);I=this.getResolvedImageFromTokens(D)}else{const D=u.getValueAndResolveTokens("icon-image",m,x,b);I=this.getResolvedImageFromTokens(D)}if(I){const D=o.hasLayoutProperty("icon-size")?o.getUnevaluatedLayoutProperty("icon-size"):u.getLayoutPropertyValue("icon-size"),B=H1(this.zoom,D,this.worldview,b),{iconPrimary:U,iconSecondary:q}=Az(I,B,D,x,this.zoom,S,this.pixelRatio,A,this.worldview,b);return{iconPrimary:U,iconSecondary:q}}return{iconPrimary:void 0,iconSecondary:void 0}}getCombinedIconPrimary(o,u,m,x,b,S,A){return this.getCombinedIconVariants(o,u,m,x,b,S,A).iconPrimary}updateSymbolInstanceIconVertices(o,u,m,x,b,S){const{canonical:A,availableImages:I,globalProperties:D,layer:B,iconScaleFactor:U,featureState:q,layoutIconOffset:K,layoutIconSize:X,layoutIconRotate:J,iconRotatesInTileSpace:se}=S;if(o.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(u.activeAppearanceIndex===m)return{vertexOffsetDelta:o.numIconVertices,hasChanges:!1};const ae=m>=0?B.appearances[m]:null;if(ae){const ue={sortKey:void 0,text:void 0,icon:null,index:o.featureIndex,sourceLayerIndex:o.featureIndex,geometry:[],properties:u.properties,type:"Point",id:u.id},{iconPrimary:ce,iconSecondary:de}=this.getCombinedIconVariants(ae,B,x,A,I,ue,U);if(!ce)return{vertexOffsetDelta:0,hasChanges:!1};const xe=ce.toString(),ve=this.iconAtlasPositions&&this.iconAtlasPositions.get(xe);if(ve){const{appearanceIconOffset:Ue,appearanceIconRotate:Pe}=jJ(ae,B,x,A,K,J,X,U),De=Pe+(se?Oz(this.getTileTransform(A),o.tileAnchorX,o.tileAnchorY):0),Ve=B.layout.get("icon-anchor").evaluate(x,q,A);let Fe=kJ(ve,de?this.iconAtlasPositions&&this.iconAtlasPositions.get(de.toString()):void 0,Ue,Ve);const Ze=ve.sdf,st=B.layout.get("icon-text-fit").constantOr("none");st!=="none"&&u.textShaping&&u.iconTextFitPadding&&u.fontScale&&(Fe=IJ(Fe,u.textShaping,st,u.iconTextFitPadding,Ue,u.fontScale));const ut=this.calculateEffectiveAppearanceIconSize(ae,D.zoom,x,A,I,U,X),ht=0,_t=1+(Math.min(V0,Math.round(ut*Zx))<<1),Et=vee(Fe,De,Ze,st!=="none",U),Pt=this.icon.iconTransitioningVertexArray.length>0;u.isUsingAppearanceIconVertexData||(u.isUsingAppearanceIconVertexData=!0,u.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(b,o.numIconVertices),Pt&&(u.layoutBasedIconTransitioningVertexData=this.icon.snapshotIconTransitioningVertexData(b,o.numIconVertices)));const Rt=Math.floor(o.numIconVertices/4),Ye=Math.min(Et.length,Rt);let At=b;const Tt=Pt?this.icon.iconTransitioningVertexArray.uint16:null;for(let Gt=0;Gt0||o.numVerticalGlyphVertices>0;if(!xe)return{vertexOffsetDelta:xe?o.numHorizontalGlyphVertices+o.numVerticalGlyphVertices:0,hasChanges:!1};if(u.activeAppearanceIndex===m)return{vertexOffsetDelta:o.numHorizontalGlyphVertices+o.numVerticalGlyphVertices,hasChanges:!1};const ve=m>=0?I.appearances[m]:null;if(ve&&u.textShaping){const{appearanceTextOffset:Ue,appearanceTextRotate:Pe,appearanceTextSize:De}=CJ(ve,I,x,A,q,X,K),Ve=Pe+(J?Oz(this.getTileTransform(A),o.tileAnchorX,o.tileAnchorY):0);u.fontScale=function(kt,Dt){return kt*Dt/24}(De,u.textScaleFactor);const Fe=ve.getUnevaluatedLayoutProperty("text-size");let Ze=this.textSizeData,st=ue,ut=ce;ve.hasLayoutProperty("text-size")&&(Ze=H1(this.zoom,Fe,this.worldview,de),st=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,ut=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const ht=u.textShaping.bottom-q[1],_t=u.textShaping.left-q[0],Et=u.textShaping.right-q[0];u.textShaping.top=Ue[1]+(u.textShaping.top-q[1]),u.textShaping.bottom=Ue[1]+ht,u.textShaping.left=Ue[0]+_t,u.textShaping.right=Ue[0]+Et;const Pt=See(0,u.textShaping,Ue,I,!1,x,B,this.allowVerticalPlacement,Ve),Rt=De&&Ze.kind==="composite"?Fe.possiblyEvaluate(new Hs(st,{}),A).evaluate(x,U,A):se,Ye=De&&Ze.kind==="composite"?Fe.possiblyEvaluate(new Hs(ut,{}),A).evaluate(x,U,A):ae,At=NJ(ve.name,Ze,De,D,Rt,Ye),Tt=Array.isArray(At)?At[1]:De,$t=0,Gt=1+(Math.min(V0,Math.round(Tt*Zx))<<1);u.isUsingAppearanceTextVertexData||(u.isUsingAppearanceTextVertexData=!0,u.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(b,o.numHorizontalGlyphVertices+o.numVerticalGlyphVertices));for(let kt=0;kt0){const D=b[0],B=[this.text.uboBinder,this.icon.uboBinder].filter(U=>U&&U.hasStateDependentPaint(D));if(B.length>0){const U=new Set(Object.keys(o).map(q=>{const K=Number(q);return!isNaN(K)&&Number.isSafeInteger(K)&&String(K)===q?K:q}));for(const q of B)q.updateFeatures(U,D,u,I,m,o,A)}}}}updateZOffset(){if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;const o=this.text.zOffsetVertexBuffer?cLe:this.text.zOffsetVertexArray,u=this.icon.zOffsetVertexBuffer?uLe:this.icon.zOffsetVertexArray;o.clear(),u.clear();for(let m=0;m0&&(x.placedIconSymbolIndex>=0&&eL(u,x.numIconVertices,b),x.verticalPlacedIconSymbolIndex>=0&&eL(u,x.numVerticalIconVertices,b))}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(o),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(u)}isEmpty(){return this.symbolInstances.length===0}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(o,u,m,x,b){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(o),this.iconCollisionBox.upload(o)),this.text.upload(o,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(S=>S.appearances&&S.appearances.length>0)),this.icon.upload(o,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(o,u,m,x,b,S=!1){const A={hasLayoutChanges:!1,hasUboChanges:!1};if(!o||!m||!this.featureAppearanceData)return A;const I=u||{},D=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,B=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!D&&!B)return A;const U=this.layers[0],q=U.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===U.appearancesVersion||(this.featureAppearances=new rLe(U.appearances,U.appearancesVersion));const K=this.featureAppearances.update(x,S);if(K.kind==="no-changes")return A;let X=1,J=0,se=!1,ae=!1;if(D){const[De,Ve]=q.get("icon-size-scale-range");X=cn(1,De,Ve)}const ue=D&&kz(U,"icon");let ce=1,de=0,xe=!1;if(B){const[De,Ve]=q.get("text-size-scale-range");ce=cn(1,De,Ve)}const ve=B&&kz(U,"text"),Ue=new Map;if(b&&m)for(const De of m){const Ve=b.getImage(De,U.scope);if(Ve){const Fe=new Io(De.toString());Ue.set(Fe.toString(),Ve)}}const Pe=[this.text.uboBinder,this.icon.uboBinder];for(let De=0;DePt.isActive({globals:x,feature:ut,canonical:o,featureState:st})):-1;ht=Et>=0?Et:-1}const _t=Fe.activeAppearanceIndex!==ht;if(B){const Et=q.get("text-size"),Pt=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Rt=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Ye={canonical:o,layer:U,featureState:st,availableImages:m,textScaleFactor:ce,imageMap:Ue,layoutTextOffset:q.get("text-offset").evaluate(ut,st,o).map(Tt=>Tt*G1),layoutTextSize:Et.evaluate(ut,st,o),layoutTextRotate:q.get("text-rotate").evaluate(ut,st,o),textRotatesInTileSpace:ve,layoutMinZoomSize:Et.evaluate(ut,{zoom:Pt},o),layoutMaxZoomSize:Et.evaluate(ut,{zoom:Rt},o),layoutTextSizeMinZoom:Pt,layoutTextSizeMaxZoom:Rt},At=this.updateSymbolInstanceTextVertices(Ve,Fe,ht,ut,de,Ye);de+=At.vertexOffsetDelta,xe=xe||At.hasChanges}if(D){const Et={canonical:o,layer:U,featureState:st,availableImages:m,globalProperties:x,iconScaleFactor:X,layoutIconOffset:q.get("icon-offset").evaluate(ut,st,o),layoutIconSize:q.get("icon-size").evaluate(ut,st,o,m),layoutIconRotate:q.get("icon-rotate").evaluate(ut,st,o),iconRotatesInTileSpace:ue},Pt=this.updateSymbolInstanceIconVertices(Ve,Fe,ht,ut,J,Et);J+=Pt.vertexOffsetDelta,se=se||Pt.hasChanges}if(_t){const Et=Ve.featureIndex,Pt=x?x.brightness:null,Rt=st||{},Ye=ht>=0?U.appearances[ht]:null;for(const At of Pe)At&&(At.layer=U,ae=At.updateFeaturePaintForAppearance(Et,ut,Rt,o,m,Pt,Ye)||ae)}Fe.activeAppearanceIndex=ht}return se&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),se&&this.icon.iconTransitioningVertexBuffer&&this.icon.iconTransitioningVertexArray.length>0&&this.icon.iconTransitioningVertexArray.length===this.icon.iconTransitioningVertexBuffer.length&&this.icon.iconTransitioningVertexBuffer.updateData(this.icon.iconTransitioningVertexArray),xe&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:se||xe,hasUboChanges:ae}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=OR(this.projection)),this.projectionInstance}getTileTransform(o){return this.tileTransformInstance||(this.tileTransformInstance=LR(o,this.getProjection())),this.tileTransformInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(o,u){const m=this.lineVertexArray.length;if(o.segment!==void 0)for(const{x,y:b}of u)this.lineVertexArray.emplaceBack(x,b);return{lineStartIndex:m,lineLength:this.lineVertexArray.length-m}}addSymbols(o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae,ue){const ce=o.indexArray,de=o.layoutVertexArray,xe=o.globeExtVertexArray,ve=ue,Ue=o.uboBinder?o.uboBinder.getCurrentBatchIndex():void 0,Pe=o.segments.prepareSegment(4*ve,de,ce,this.canOverlap?S.sortKey:void 0,Ue),De=this.glyphOffsetArray.length,Ve=Pe.vertexLength,Fe=this.allowVerticalPlacement&&A===Zg.vertical?Math.PI/2:0,Ze=S.text&&S.text.sections;let st=de.length,ut=-1;for(let Et=0;Et=0)){const Et=4*ht;for(let Pt=0;Pt=0?o.rightJustifiedTextSymbolIndex:o.centerJustifiedTextSymbolIndex>=0?o.centerJustifiedTextSymbolIndex:o.leftJustifiedTextSymbolIndex>=0?o.leftJustifiedTextSymbolIndex:o.verticalPlacedTextSymbolIndex>=0?o.verticalPlacedTextSymbolIndex:-1}getSymbolInstanceTextSize(o,u,m,x){const b=this.defaultPlacedTextSymbolIndex(u,x),S=this.text.placedSymbolArray.get(b),A=TR(this.textSizeData,o,S)/G1;return this.tilePixelRatio*A}getSymbolInstanceIconSize(o,u,m){const x=this.icon.placedSymbolArray.get(m),b=TR(this.iconSizeData,o,x);return this.tilePixelRatio*b}_commitDebugCollisionVertexUpdate(o,u,m,x){o.emplaceBack(u,-m,-m,x),o.emplaceBack(u,m,-m,x),o.emplaceBack(u,m,m,x),o.emplaceBack(u,-m,m,x)}_updateTextDebugCollisionBoxes(o,u,m,x,b,S,A){for(let I=x;I0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(o,u){const m=o.placedSymbolArray.get(u),x=m.vertexStartIndex+4*m.numGlyphs;for(let b=m.vertexStartIndex;bx[A]-x[I]||b[I]-b[A]),S}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let o=0;othis.symbolInstances.get(u).zOffset-this.symbolInstances.get(o).zOffset)}addToSortKeyRanges(o,u){const m=this.sortKeyRanges.at(-1);m&&m.sortKey===u?m.symbolInstanceEnd=o+1:this.sortKeyRanges.push({sortKey:u,symbolInstanceStart:o,symbolInstanceEnd:o+1})}sortFeatures(o){if(this.sortFeaturesByY&&this.sortedAngle!==o)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesByY=!1;else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(o),this.sortedAngle=o,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const u of this.symbolInstanceIndexes){const m=this.symbolInstances.get(u);this.featureSortOrder.push(m.featureIndex);const{rightJustifiedTextSymbolIndex:x,centerJustifiedTextSymbolIndex:b,leftJustifiedTextSymbolIndex:S,verticalPlacedTextSymbolIndex:A,placedIconSymbolIndex:I,verticalPlacedIconSymbolIndex:D}=m;x>=0&&this.addIndicesForPlacedSymbol(this.text,x),b>=0&&b!==x&&this.addIndicesForPlacedSymbol(this.text,b),S>=0&&S!==b&&S!==x&&this.addIndicesForPlacedSymbol(this.text,S),A>=0&&this.addIndicesForPlacedSymbol(this.text,A),I>=0&&this.addIndicesForPlacedSymbol(this.icon,I),D>=0&&this.addIndicesForPlacedSymbol(this.icon,D)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}}_k.maxBucketInstanceId=0,vr(_k,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features","projectionInstance","tileTransformInstance"]}),_k.addDynamicAttributes=G0;class Cee extends Ep{constructor(o,u,m){super(o,u,m),this.elevatedLayoutVertexArray=new Hu}upload(o){const u=this.uploaded;super.upload(o),!u&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=o.createVertexBuffer(this.elevatedLayoutVertexArray,Ni.members))}destroy(){this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),super.destroy()}}vr(Cee,"ElevatedFillBufferData");class Jg{constructor(){this.portals=[]}static isOnBorder(o,u){return o<=0&&u<=0||o>=ar&&u>=ar}static evaluate(o){if(o.length===0)return new Jg;let u=[];for(const I of o)u.push(...I.portals);if(u.length===0)return new Jg;for(const I of u){const D=I.va,B=I.vb;(Jg.isOnBorder(D.x,B.x)||Jg.isOnBorder(D.y,B.y))&&(I.type="border")}const m=u.filter(I=>I.type!=="unevaluated"),x=u.filter(I=>I.type==="unevaluated");if(x.length===0)return new Jg;x.sort((I,D)=>I.hash===D.hash?I.isTunnel===D.isTunnel?0:I.isTunnel?-1:1:I.hashI.hashb!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new Hi(u,{zoom:m,lut:x},b=>b!=="fill-bridge-guard-rail-color")}addVertices(o,u){const m=this.unevalVertices.length;for(let x=0;x=b.min.x&&U.x<=b.max.x&&U.y>=b.min.y&&U.y<=b.max.y||q.x>=b.min.x&&q.x<=b.max.x&&q.y>=b.min.y&&q.y<=b.max.y||U1(U,q,A))||this.isOnBorder(U.x,q.x)||this.isOnBorder(U.y,q.y))continue;const K=_d.computeEdgeHash(this.unevalVertices[D],this.unevalVertices[B]);let X,J=this.vertexHashLookup.get(_d.computePosHash(U));J!=null?X=J.next:(J=this.vertexHashLookup.get(_d.computePosHash(q)),X=J!=null?J.prev:K),this.unevalEdges.push({polygonIdx:o,a:D,b:B,hash:K,portalHash:X,isTunnel:x,type:"unevaluated",featureInfo:S})}}addPortalCandidates(o,u,m,x,b){if(u.length!==0){this.vertexHashLookup.clear();for(const S of u){if(S.length===0)continue;const A=S[0];let I=_d.computeEdgeHash(A[A.length-2],A.at(-1));for(let D=0;D({vertexOffset:0,primitiveOffset:this.indexArray.length}),m=q=>{q.primitiveLength=this.indexArray.length-q.primitiveOffset},x=new dLe(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(o.portals,this.unevalEdges);const b=u(),S=u(),A=u(),I=(q,K)=>{q.sort((J,se)=>J.type===K&&se.type!==K?-1:J.type!==K&&se.type===K?1:0);const X=q.findIndex(J=>J.type!==K);return X>=0?X:q.length};let D=0;this.unevalEdges.length>0&&(D=I(this.unevalEdges,"none"),this.constructBridgeStructures(x,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:D},this.tileToMeters)),m(A);const B=u(),U=u();if(this.unevalEdges.length>0){const q=this.unevalEdges.splice(D),K=I(q,"tunnel")+D;this.unevalEdges.push(...q),this.constructTunnelStructures(x,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:D},{min:D,max:K})}m(B),x.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),m(U),x.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),m(S),x.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights,4),m(b),this.maskSegments=xn.simpleSegment(0,U.primitiveOffset,0,U.primitiveLength),this.depthSegments=xn.simpleSegment(0,S.primitiveOffset,0,S.primitiveLength),this.renderableBridgeSegments=xn.simpleSegment(0,A.primitiveOffset,0,A.primitiveLength),this.renderableTunnelSegments=xn.simpleSegment(0,B.primitiveOffset,0,B.primitiveLength),this.shadowCasterSegments=xn.simpleSegment(0,b.primitiveOffset,0,b.primitiveLength)}update(o,u,m,x,b,S,A,I){this.bridgeProgramConfigurations.updatePaintArrays(o,u,b,m,x,S,A,I),this.tunnelProgramConfigurations.updatePaintArrays(o,u,b,m,x,S,A,I)}upload(o){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=o.createVertexBuffer(this.vertexPositions,zn.members),this.vertexBufferNormal=o.createVertexBuffer(this.vertexNormals,Qi.members),this.indexBuffer=o.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(o),this.tunnelProgramConfigurations.upload(o))}destroy(){this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBufferNormal.destroy(),this.indexBuffer.destroy()),this.maskSegments&&(this.maskSegments.destroy(),this.depthSegments.destroy(),this.renderableBridgeSegments.destroy(),this.renderableTunnelSegments.destroy(),this.shadowCasterSegments.destroy()),this.bridgeProgramConfigurations.destroy(),this.tunnelProgramConfigurations.destroy()}populatePaintArrays(o,u,m,x,b){const S=(A,I)=>{for(let D=0;Dtt(ht,u[_t].x,u[_t].y,m[_t]*I),U=He(),q=He(),K=He(),X=He(),J=He(),se=(ht,_t)=>{const Et=A.get(_d.computePosHash(u[_t])),Pt=Et.from,Rt=Et.to;if(!Pt||!Rt)return;B(U,Pt),B(q,_t),B(K,Rt),li(X),Lr(U,q)||(Or(J,q,U),zt(X,J)),Lr(K,q)||(Or(J,K,q),vt(X,X,zt(J,J)));const Ye=ss(X);return Ye>0?ft(ht,X,1/Ye):void 0};let ae=Number.POSITIVE_INFINITY;this.sortSubarray(x,b.min,b.max,(ht,_t)=>ht.featureInfo.featureIndex-_t.featureInfo.featureIndex);const ue=He(),ce=He(),de=He(),xe=He(),ve=He(),Ue=He(),Pe=He(),De=He(),Ve=He(),Fe=[He(),He(),He(),He()],Ze=[He(),He(),He(),He()],st=[{coord:new jt(0,0),height:0},{coord:new jt(0,0),height:0}],ut=(ht,_t)=>ht>_t;for(let ht=b.min;htae.featureInfo.featureIndex-ue.featureInfo.featureIndex;this.sortSubarray(x,b.min,b.max,I),this.sortSubarray(x,S.min,S.max,I);const D=ae=>zt(ae,ae),B=[{coord:new jt(0,0),height:0},{coord:new jt(0,0),height:0}],U=(ae,ue)=>aeA.hash===I.hash?I.polygonIdx-A.polygonIdx:I.hash>A.hash?1:-1);let m=0,x=0,b=0,S=u[m].polygonIdx;do x++,(x===u.length||u[m].hash!==u[x].hash)&&((x-m===1||u[x-1].polygonIdx!==S)&&(bD.portalHashB.hash?A++:B.hash>D.portalHash?I++:(D.type=B.type,A++)}}}isOnBorder(o,u){return o<=0&&u<=0||o>=ar&&u>=ar}addFeatureSection(o,u,m,x){return o!==u&&(u=o,m.push({featureIndex:o,vertexStart:x.getVertexCount()}),x.clearVertexLookup()),u}sortSubarray(o,u,m,x){const b=o.slice(u,m);b.sort(x),o.splice(u,b.length,...b)}static computeEdgeHash(o,u){const m=_d.computePosHash(o),x=_d.computePosHash(u);return Math.min(m,x)*e$*e$+Math.max(m,x)}static computePosHash(o){const u=Math.floor(o.x)+1,m=Math.floor(o.y)+1;return u*e$+m}}class hLe{constructor(){this._valid=!1}reset(o){return this.feature=o,this._valid=!0,this._geometry=o.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(o,u){return this._valid&&o(u(this._geometry)),this}require(o,u,m){return this.get(o,!0,u,m)}optional(o,u,m){return this.get(o,!1,u,m)}success(){return this._valid}get(o,u,m,x){const b=Object.hasOwn(this.feature.properties,o)?+this.feature.properties[o]:void 0;return this._valid&&b!==void 0&&!Number.isNaN(b)?m(x?x(b):b):u&&(this._valid=!1),this}}class Pee{constructor(o,u){this.featureFunc=o,this.vertexFunc=u}parseFeature(o,u,m){return this.featureFunc(o,u,m)}parseVertex(o,u,m){return this.vertexFunc(o,u,m)}}const fLe=new Pee((h,o,u)=>h.reset(o).require(Kg,m=>{u.id=m}).optional("fixed_height_relative",m=>{u.constantHeight=m},ey.decodeRelativeHeight).geometry(m=>{u.bounds=m},up).success(),(h,o,u)=>h.reset(o).require(Kg,m=>{u.id=m}).require("elevation_idx",m=>{u.idx=m}).require("extent",m=>{u.extent=m}).require("height_relative",m=>{u.height=m},ey.decodeRelativeHeight).geometry(m=>{u.position=m},ey.getPoint).success()),mLe=new Pee((h,o,u)=>h.reset(o).require(Kg,m=>{u.id=m}).optional("fixed_height",m=>{u.constantHeight=m},ey.decodeMetricHeight).geometry(m=>{u.bounds=m},up).success(),(h,o,u)=>h.reset(o).require(Kg,m=>{u.id=m}).require("elevation_idx",m=>{u.idx=m}).require("extent",m=>{u.extent=m}).require("height",m=>{u.height=m},ey.decodeMetricHeight).geometry(m=>{u.position=m},ey.getPoint).success());class ey{static getPoint(o){return rr(o[0][0].x,o[0][0].y)}static decodeRelativeHeight(o){return 1e-4*o*5}static decodeMetricHeight(o){return 1e-4*o}static getVersionSchema(o){return o?o==="1.0.1"?mLe:void 0:fLe}static parse(o){const u=[],m=[],x=o.length,b=new hLe;for(let S=0;SA.a0?ft(I,I,1/D):tt(I,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(o){if(this.edges.length===0)return;let u=0,m=Number.POSITIVE_INFINITY,x=0;const[b,S,A,I,D,B,U]=pLe;Er(U,o.x,o.y);const q=new bRe(U,null);for(let K=0;K0?ki(I,A)/de:0,ve=cn(xe,0,1),Ue=Math.abs((xe-ve)*this.edgeProps[K].len);Nr(D,U,se),Er(B,J[1],-J[0]);const Pe=Ue+Math.abs(ki(D,B));Pe=0;--S){const A=this.edges[S].a,I=this.edges[S].b,{position:D,height:B,extent:U}=this.vertices[A],{position:q,height:K,extent:X}=this.vertices[I],J=this.vertexProps[A].dir,se=this.vertexProps[I].dir;if(tt(u,D[0]/o,D[1]/o,B),tt(m,q[0]/o,q[1]/o,K),tt(x,J[1],-J[0],0),ft(x,x,U),tt(b,se[1],-se[0],0),ft(b,b,X),this.distSqLines(nt(u[0]+.5*x[0],u[1]+.5*x[1],u[2]+.5*x[2]),nt(m[0]-.5*b[0],m[1]-.5*b[1],m[2]-.5*b[2]),nt(u[0]-.5*x[0],u[1]-.5*x[1],u[2]-.5*x[2]),nt(m[0]+.5*b[0],m[1]+.5*b[1],m[2]+.5*b[2]))<=.0025000000000000005)continue;const ae=this.vertices.length,ue=Wr(yt(),D,q);this.vertices.push({position:Zr(ue,ue,.5),height:.5*(B+K),extent:.5*(U+X),index:.5*((this.vertices[A].index!==void 0?this.vertices[A].index:A)+(this.vertices[I].index!==void 0?this.vertices[I].index:I))});const ce=Wr(yt(),J,se);this.vertexProps.push({dir:qn(ce,ce)}),this.edges.splice(S,1),this.edgeProps.splice(S,1),this.edges.push({a:A,b:ae}),this.edges.push({a:ae,b:I});const de=Nr(yt(),this.vertices[ae].position,D),xe=$r(de),ve={vec:de,dir:Zr(yt(),de,1/xe),len:xe};this.edgeProps.push(ve),this.edgeProps.push(ve)}}distSqLines(o,u,m,x){const b=Vt(He(),u,o),S=Vt(He(),x,m),A=Vt(He(),o,m),I=Vr(b,b),D=Vr(b,S),B=Vr(b,A),U=Vr(S,S),q=Vr(S,A),K=I*U-D*D;if(K===0)return Gr(Fn(b,m,x,Vr(A,S)/Vr(S,S)),o);const X=(I*q-D*B)/K;return Gr(Fn(b,o,u,(D*q-B*U)/K),Fn(S,m,x,X))}static serialize(o,u){const m={id:o.id,heightRange:{min:o.heightRange.min,max:o.heightRange.max},safeArea:(x=o.safeArea,{min:{x:x.min.x,y:x.min.y},max:{x:x.max.x,y:x.max.y}})};var x;return o.constantHeight!=null?(m.constantHeight=o.constantHeight,m):o.vertices.length===0?(m.vertices=[],m.vertexProps=[],m.edges=[],m.edgeProps=[],m):(m.vertices=o.vertices.map(b=>({position:tL(b.position),height:b.height,extent:b.extent,index:b.index})),m.vertexProps=o.vertexProps.map(b=>({dir:tL(b.dir)})),m.edges=o.edges.map(b=>({a:b.a,b:b.b})),m.edgeProps=o.edgeProps.map(b=>({vec:tL(b.vec),dir:tL(b.dir),len:b.len})),m)}static deserialize(o){const u=function(x){return{min:new jt(x.min.x,x.min.y),max:new jt(x.max.x,x.max.y)}}(o.safeArea);if(o.constantHeight!=null)return new ty(o.id,u,o.constantHeight);if(!o.vertices||o.vertices.length===0){const x=Object.create(ty.prototype);return x.id=o.id,x.constantHeight=void 0,x.heightRange={min:o.heightRange.min,max:o.heightRange.max},x.safeArea=u,x.vertices=[],x.vertexProps=[],x.edges=[],x.edgeProps=[],x}const m=Object.create(ty.prototype);return m.id=o.id,m.constantHeight=void 0,m.heightRange={min:o.heightRange.min,max:o.heightRange.max},m.safeArea=u,m.vertices=o.vertices.map(x=>({position:rL(x.position),height:x.height,extent:x.extent,index:x.index})),m.vertexProps=(o.vertexProps||[]).map(x=>({dir:rL(x.dir)})),m.edges=(o.edges||[]).map(x=>({a:x.a,b:x.b})),m.edgeProps=(o.edgeProps||[]).map(x=>({vec:rL(x.vec),dir:rL(x.dir),len:x.len})),m}}class Q1{constructor(o,u){this.zScale=1,this.xOffset=0,this.yOffset=0,o.equals(u)||(this.zScale=Math.pow(2,u.z-o.z),this.xOffset=(o.x*this.zScale-u.x)*ar,this.yOffset=(o.y*this.zScale-u.y)*ar)}pointTransform(o){return rr(o[0]*this.zScale+this.xOffset,o[1]*this.zScale+this.yOffset)}pointTransformInPlace(o){o[0]=o[0]*this.zScale+this.xOffset,o[1]=o[1]*this.zScale+this.yOffset}constantElevation(o,u){if(o.constantHeight!=null)return this.computeBiasedHeight(o.constantHeight,u)}pointElevation(o,u,m){const x=this.constantElevation(u,m);return x??(o.x=o.x*this.zScale+this.xOffset,o.y=o.y*this.zScale+this.yOffset,this.computeBiasedHeight(u.pointElevation(o),m))}computeBiasedHeight(o,u){return u<=0?o:o+u*rm(0,u,o>=0?o:Math.abs(.5*o))}}function gLe(h){if(h===0)return[0,0,0];const o=Nx(h);return[o(),o(),o()]}function Ree(h,o){let u=0,m=h.length-1;for(;u<=m;){const x=u+m>>1;h[x].feature.idA.id===x);if(S&&m)return{tileId:m,feature:S}}if(!u||u.length===0)return;const b=Ree(u,x);if(!(b<0)){if(m){for(let S=b;So?1:h0))return u;u=u.left}}return null}contains(o){for(var u=this._root,m=this._compare;u;){var x=m(o,u.key);if(x===0)return!0;u=x<0?u.left:u.right}return!1}remove(o){var u=this.find(o);if(!u)return!1;if(this.splay(u),u.left)if(u.right){var m=this.minNode(u.right);m.parent!==u&&(this.replace(m,m.right),m.right=u.right,m.right.parent=m),this.replace(u,m),m.left=u.left,m.left.parent=m}else this.replace(u,u.left);else this.replace(u,u.right);return this._size--,!0}removeNode(o){if(!o)return!1;if(this.splay(o),o.left)if(o.right){var u=this.minNode(o.right);u.parent!==o&&(this.replace(u,u.right),u.right=o.right,u.right.parent=u),this.replace(o,u),u.left=o.left,u.left.parent=u}else this.replace(o,o.left);else this.replace(o,o.right);return this._size--,!0}erase(o){var u=this.find(o);if(u){this.splay(u);var m=u.left,x=u.right,b=null;m&&(m.parent=null,b=this.maxNode(m),this.splay(b),this._root=b),x&&(m?b.right=x:this._root=x,x.parent=b),this._size--}}pop(){var o=this._root,u=null;if(o){for(;o.left;)o=o.left;u={key:o.key,data:o.data},this.remove(o.key)}return u}next(o){var u=o;if(u)if(u.right)for(u=u.right;u&&u.left;)u=u.left;else for(u=o.parent;u&&u.right===o;)o=u,u=u.parent;return u}prev(o){var u=o;if(u)if(u.left)for(u=u.left;u&&u.right;)u=u.right;else for(u=o.parent;u&&u.left===o;)o=u,u=u.parent;return u}forEach(o){for(var u=this._root,m=[],x=!1,b=0;!x;)u?(m.push(u),u=u.left):m.length>0?(o(u=m.pop(),b++),u=u.right):x=!0;return this}range(o,u,m,x){const b=[],S=this._compare;let A,I=this._root;for(;b.length!==0||I;)if(I)b.push(I),I=I.left;else{if(I=b.pop(),A=S(I.key,u),A>0)break;if(S(I.key,o)>=0&&m.call(x,I))return this;I=I.right}return this}keys(){for(var o=this._root,u=[],m=[],x=!1;!x;)o?(u.push(o),o=o.left):u.length>0?(o=u.pop(),m.push(o.key),o=o.right):x=!0;return m}values(){for(var o=this._root,u=[],m=[],x=!1;!x;)o?(u.push(o),o=o.left):u.length>0?(o=u.pop(),m.push(o.data),o=o.right):x=!0;return m}at(o){for(var u=this._root,m=[],x=!1,b=0;!x;)if(u)m.push(u),u=u.left;else if(m.length>0){if(u=m.pop(),b===o)return u;b++,u=u.right}else x=!0;return null}load(o=[],u=[],m=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const x=o.length;return m&&n$(o,u,0,x-1,this._compare),this._root=r$(null,o,u,0,x),this._size=x,this}min(){var o=this.minNode(this._root);return o?o.key:null}max(){var o=this.maxNode(this._root);return o?o.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(o,u,m,x,b){return new t$(m,b).load(o,u,x)}}function r$(h,o,u,m,x){const b=x-m;if(b>0){const S=m+Math.floor(b/2),A={key:o[S],data:u[S],parent:h};return A.left=r$(A,o,u,m,S),A.right=r$(A,o,u,S+1,x),A}return null}function n$(h,o,u,m,x){if(u>=m)return;const b=h[u+m>>1];let S=u-1,A=m+1;for(;;){do S++;while(x(h[S],b)<0);do A--;while(x(h[A],b)>0);if(S>=A)break;let I=h[S];h[S]=h[A],h[A]=I,I=o[S],o[S]=o[A],o[A]=I}n$(h,o,u,A,x),n$(h,o,A+1,m,x)}const Lee=11102230246251565e-32,Wu=134217729,xLe=(3+8*Lee)*Lee;function i$(h,o,u,m,x){let b,S,A,I,D=o[0],B=m[0],U=0,q=0;B>D==B>-D?(b=D,D=o[++U]):(b=B,B=m[++q]);let K=0;if(UD==B>-D?(S=D+b,A=b-(S-D),D=o[++U]):(S=B+b,A=b-(S-B),B=m[++q]),b=S,A!==0&&(x[K++]=A);UD==B>-D?(S=b+D,I=S-b,A=b-(S-I)+(D-I),D=o[++U]):(S=b+B,I=S-b,A=b-(S-I)+(B-I),B=m[++q]),b=S,A!==0&&(x[K++]=A);for(;U0:(m[0]-o[0])*(u[1]-o[1])-(u[0]-o[0])*(m[1]-o[1])>0}isAbove(o){return!this.isBelow(o)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){let o=new REe(this.point,this.left,this.otherEvent,this.isSubject,this.type);return o.contourId=this.contourId,o.resultTransition=this.resultTransition,o.prevInResult=this.prevInResult,o.isExteriorRing=this.isExteriorRing,o.inOut=this.inOut,o.otherInOut=this.otherInOut,o}};function Sk(h,o,u){let m=function(x,b,S,A,I,D){const B=(b-D)*(S-I),U=(x-I)*(A-D),q=B-U;if(B===0||U===0||B>0!=U>0)return q;const K=Math.abs(B+U);return Math.abs(q)>=33306690738754716e-32*K?q:-function(X,J,se,ae,ue,ce,de){let xe,ve,Ue,Pe,De,Ve,Fe,Ze,st,ut,ht,_t,Et,Pt,Rt,Ye,At,Tt;const $t=X-ue,Gt=se-ue,kt=J-ce,Dt=ae-ce;Pt=$t*Dt,Ve=Wu*$t,Fe=Ve-(Ve-$t),Ze=$t-Fe,Ve=Wu*Dt,st=Ve-(Ve-Dt),ut=Dt-st,Rt=Ze*ut-(Pt-Fe*st-Ze*st-Fe*ut),Ye=kt*Gt,Ve=Wu*kt,Fe=Ve-(Ve-kt),Ze=kt-Fe,Ve=Wu*Gt,st=Ve-(Ve-Gt),ut=Gt-st,At=Ze*ut-(Ye-Fe*st-Ze*st-Fe*ut),ht=Rt-At,De=Rt-ht,J1[0]=Rt-(ht+De)+(De-At),_t=Pt+ht,De=_t-Pt,Et=Pt-(_t-De)+(ht-De),ht=Et-Ye,De=Et-ht,J1[1]=Et-(ht+De)+(De-Ye),Tt=_t+ht,De=Tt-_t,J1[2]=_t-(Tt-De)+(ht-De),J1[3]=Tt;let dr=function(dn,rn){let wr=rn[0];for(let Fr=1;Fr<4;Fr++)wr+=rn[Fr];return wr}(0,J1),nr=22204460492503146e-32*de;if(dr>=nr||-dr>=nr||(De=X-$t,xe=X-($t+De)+(De-ue),De=se-Gt,Ue=se-(Gt+De)+(De-ue),De=J-kt,ve=J-(kt+De)+(De-ce),De=ae-Dt,Pe=ae-(Dt+De)+(De-ce),xe===0&&ve===0&&Ue===0&&Pe===0)||(nr=11093356479670487e-47*de+xLe*Math.abs(dr),dr+=$t*Pe+Dt*xe-(kt*Ue+Gt*ve),dr>=nr||-dr>=nr))return dr;Pt=xe*Dt,Ve=Wu*xe,Fe=Ve-(Ve-xe),Ze=xe-Fe,Ve=Wu*Dt,st=Ve-(Ve-Dt),ut=Dt-st,Rt=Ze*ut-(Pt-Fe*st-Ze*st-Fe*ut),Ye=ve*Gt,Ve=Wu*ve,Fe=Ve-(Ve-ve),Ze=ve-Fe,Ve=Wu*Gt,st=Ve-(Ve-Gt),ut=Gt-st,At=Ze*ut-(Ye-Fe*st-Ze*st-Fe*ut),ht=Rt-At,De=Rt-ht,vd[0]=Rt-(ht+De)+(De-At),_t=Pt+ht,De=_t-Pt,Et=Pt-(_t-De)+(ht-De),ht=Et-Ye,De=Et-ht,vd[1]=Et-(ht+De)+(De-Ye),Tt=_t+ht,De=Tt-_t,vd[2]=_t-(Tt-De)+(ht-De),vd[3]=Tt;const yr=i$(4,J1,4,vd,Dee);Pt=$t*Pe,Ve=Wu*$t,Fe=Ve-(Ve-$t),Ze=$t-Fe,Ve=Wu*Pe,st=Ve-(Ve-Pe),ut=Pe-st,Rt=Ze*ut-(Pt-Fe*st-Ze*st-Fe*ut),Ye=kt*Ue,Ve=Wu*kt,Fe=Ve-(Ve-kt),Ze=kt-Fe,Ve=Wu*Ue,st=Ve-(Ve-Ue),ut=Ue-st,At=Ze*ut-(Ye-Fe*st-Ze*st-Fe*ut),ht=Rt-At,De=Rt-ht,vd[0]=Rt-(ht+De)+(De-At),_t=Pt+ht,De=_t-Pt,Et=Pt-(_t-De)+(ht-De),ht=Et-Ye,De=Et-ht,vd[1]=Et-(ht+De)+(De-Ye),Tt=_t+ht,De=Tt-_t,vd[2]=_t-(Tt-De)+(ht-De),vd[3]=Tt;const Br=i$(yr,Dee,4,vd,Mee);Pt=xe*Pe,Ve=Wu*xe,Fe=Ve-(Ve-xe),Ze=xe-Fe,Ve=Wu*Pe,st=Ve-(Ve-Pe),ut=Pe-st,Rt=Ze*ut-(Pt-Fe*st-Ze*st-Fe*ut),Ye=ve*Ue,Ve=Wu*ve,Fe=Ve-(Ve-ve),Ze=ve-Fe,Ve=Wu*Ue,st=Ve-(Ve-Ue),ut=Ue-st,At=Ze*ut-(Ye-Fe*st-Ze*st-Fe*ut),ht=Rt-At,De=Rt-ht,vd[0]=Rt-(ht+De)+(De-At),_t=Pt+ht,De=_t-Pt,Et=Pt-(_t-De)+(ht-De),ht=Et-Ye,De=Et-ht,vd[1]=Et-(ht+De)+(De-Ye),Tt=_t+ht,De=Tt-_t,vd[2]=_t-(Tt-De)+(ht-De),vd[3]=Tt;const br=i$(Br,Mee,4,vd,Oee);return Oee[br-1]}(x,b,S,A,I,D,K)}(h[0],h[1],o[0],o[1],u[0],u[1]);return m>0?-1:+(m<0)}function Lh(h,o){let u=h.point,m=o.point;return u[0]>m[0]?1:u[0]m[1]?1:-1}function e_(h,o,u){let m=new nL(o,!1,h,h.isSubject),x=new nL(o,!0,h.otherEvent,h.isSubject);return m.contourId=x.contourId=h.contourId,Lh(x,h.otherEvent)>0&&(h.otherEvent.left=!0,x.left=!1),h.otherEvent.otherEvent=x,h.otherEvent=m,u.push(x),u.push(m),u}function K0(h,o,u,m,x){return[h+u*m,o+u*x]}function Ku(h,o){return h[0]===o[0]&&h[1]===o[1]}function Bee(h,o){return Math.abs(h-o)<=4*2**-52*Math.max(Math.abs(h),Math.abs(o))}function _Le(h,o){return Bee(h[0],o[0])&&Bee(h[1],o[1])}function s$(h,o,u){let m=function(I,D,B,U){let q=I[0],K=I[1],X=B[0],J=B[1],se=D[0]-q,ae=D[1]-K,ue=U[0]-X,ce=U[1]-J,de=X-q,xe=J-K,ve=se*ce-ae*ue,Ue=ve*ve;if(Ue>0){let st=(de*ce-xe*ue)/ve;if(st<0||st>1)return null;let ut=(de*ae-xe*se)/ve;return ut<0||ut>1?null:st===0||st===1?[K0(q,K,st,se,ae)]:ut===0||ut===1?[K0(X,J,ut,ue,ce)]:[K0(q,K,st,se,ae)]}if(ve=de*ae-xe*se,Ue=ve*ve,Ue>0)return null;let Pe=se*se+ae*ae,De=(se*de+ae*xe)/Pe,Ve=De+(se*ue+ae*ce)/Pe,Fe=Math.min(De,Ve),Ze=Math.max(De,Ve);return Fe<=1&&Ze>=0?Fe===1?[K0(q,K,Fe>0?Fe:0,se,ae)]:Ze===0?[K0(q,K,Ze<1?Ze:1,se,ae)]:[K0(q,K,Fe>0?Fe:0,se,ae),K0(q,K,Ze<1?Ze:1,se,ae)]:null}(h.point,h.otherEvent.point,o.point,o.otherEvent.point);if(m===null)return 0;let x=m.length;if(x===1){let I=[h.point,h.otherEvent.point,o.point,o.otherEvent.point];for(let D of I)if(_Le(m[0],D)){m[0]=D;break}}if(x===1&&(Ku(h.point,o.point)||Ku(h.otherEvent.point,o.otherEvent.point))||x===2&&h.isSubject===o.isSubject)return 0;if(x===1)return!Ku(h.point,m[0])&&!Ku(h.otherEvent.point,m[0])&&e_(h,m[0],u),!Ku(o.point,m[0])&&!Ku(o.otherEvent.point,m[0])&&e_(o,m[0],u),1;let b=[],S=!1,A=!1;return Ku(h.point,o.point)?S=!0:Lh(h,o)===1?b.push(o,h):b.push(h,o),Ku(h.otherEvent.point,o.otherEvent.point)?A=!0:Lh(h.otherEvent,o.otherEvent)===1?b.push(o.otherEvent,h.otherEvent):b.push(h.otherEvent,o.otherEvent),S&&A||S?(o.type=1,h.type=o.inOut===h.inOut?2:3,S&&!A&&e_(b[1].otherEvent,b[0].point,u),2):A?(e_(b[0],b[1].point,u),3):b[0]===b[3].otherEvent?(e_(b[0],b[1].point,u),e_(b[3].otherEvent,b[2].point,u),3):(e_(b[0],b[1].point,u),e_(b[1],b[2].point,u),3)}function vLe(h,o){if(h===o)return 0;if(Sk(h.point,h.otherEvent.point,o.point)!==0||Sk(h.point,h.otherEvent.point,o.otherEvent.point)!==0)return Ku(h.point,o.point)?h.isBelow(o.otherEvent.point)?-1:1:h.point[0]===o.point[0]?h.point[1](o.contourId??0)?1:-1}return Lh(h,o)===1?1:-1}function bLe(h,o,u,m,x,b){let S,A,I=new t$(vLe),D=[],B=Math.min(m[2],x[2]),U=null;for(;h.length!==0;){let q=h.pop();if(D.push(q),b===0&&q.point[0]>B||b===2&&q.point[0]>m[2])break;if(q.left){A=S=q.node=I.insert(q),U=I.minNode(),S=S===U?null:I.prev(S),A=I.next(A);let K,X=S?S.key:null,J=h.length;if(wk(q,X,b),A&&s$(q,A.key,h)===2&&(wk(q,X,b),wk(A.key,q,b)),S&&s$(S.key,q,h)===2){let se=S;se=se===U?null:I.prev(se),K=se?se.key:null,wk(S.key,K,b),wk(q,X,b)}if(h.length>J){let se=h.peek();Ku(se.point,q.point)&&Lh(se,q)===-1&&Lh(q,se)===1&&(I.removeNode(q.node),q.node=null,D.pop(),h.push(q))}}else q=q.otherEvent,A=S=q.node,S&&A&&(S=S===U?null:I.prev(S),A=I.next(A),I.removeNode(q.node),q.node=null,A&&S&&s$(S.key,A.key,h))}return D}var wLe=class{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=0}isExterior(){return this.holeOf==null}};function SLe(h,o,u,m){let x=h+1,b=o[h].point,S=b,A=o.length;for(xm;)x--;return x}function ELe(h,o,u){let m=new wLe;if(h.prevInResult!=null){let x=h.prevInResult,b=x.outputContourId;if(x.resultTransition>0){let S=o[b];if(S.holeOf!=null){let A=S.holeOf;o[A].holeIds.push(u),m.holeOf=A,m.depth=o[b].depth}else o[b].holeIds.push(u),m.holeOf=b,m.depth=o[b].depth+1}else m.holeOf=null,m.depth=o[b].depth}else m.holeOf=null,m.depth=0;return m}function TLe(h){let o,u,m=function(S){let A,I,D,B,U,q=[];for(I=0,D=S.length;I{x[U]=1,U=m.length)&&m[D];);b.push(A)}return b}var ALe=class{constructor(h){this.index=0,this.heap=new Hw(void 0,Lh),this.sorted=h}get length(){return this.sorted.length-this.index+this.heap.length}push(h){this.heap.push(h)}peek(){let h=this.sorted[this.index],o=this.heap.peek();return o===void 0?h:h===void 0||Lh(o,h)<0?o:h}pop(){let h=this.sorted[this.index],o=this.heap.peek();return o!==void 0&&(h===void 0||Lh(o,h)<0)?this.heap.pop():(h!==void 0&&this.index++,h)}},zee=Math.max,$ee=Math.min,iL=0;function Uee(h,o,u,m,x,b){let S,A,I,D,B,U,q=h.length-1,K=h[0];for(S=0,A=K[0]===h[q][0]&&K[1]===h[q][1]?q:q+1;S0?U.left=!0:B.left=!0;let X=I[0],J=I[1];x[0]=$ee(x[0],X),x[1]=$ee(x[1],J),x[2]=zee(x[2],X),x[3]=zee(x[3],J),m.push(B,U)}}function kLe(h,o,u,m,x){let b,S,A,I,D,B,U=[];for(A=0,I=h.length;A1&&Ku(m[0],m[x-1])&&x--;let b=[];for(let D=0;D0&&Ku(b[U-1],B)))for(b.push(B);(U=b.length)>=3&&Ku(b[U-3],b[U-1]);)b.length=U-2}let S=0,A=b.length;for(;A-S>=3;)if(Ku(b[A-1],b[S]))A--;else if(Ku(b[A-2],b[S]))A-=2;else{if(!Ku(b[A-1],b[S+1]))break;S++,A--}let I=b.slice(S,A);return I.length>0&&I.push(I[0]),I}(h);return Vee(u)?null:(function(m){let x=m.length-1,b=0;for(let I=1;I0;let A=0;for(let I=0;I0}(u)===o&&u.reverse(),u)}function qee(h){let o=[];for(let u of h){let m=a$(u[0],!1);if(m===null)continue;let x=[m];for(let b=1;b0&&o.push(b)}}return o===null?h:o}function Hee(h,o,u){let m=h,x=o;typeof h[0][0][0]=="number"&&(m=[h]),typeof o[0][0][0]=="number"&&(x=[o]),m=Gee(m),x=Gee(x);let b=function(q,K,X){let J=null;return q.length*K.length===0&&(X===0?J=[]:X===2?J=q:(X===1||X===3)&&(J=q.length===0?K:q)),J}(m,x,u);if(b!==null)return qee(b);let S=[1/0,1/0,-1/0,-1/0],A=[1/0,1/0,-1/0,-1/0],I=kLe(m,x,S,A,u);if(b=function(q,K,X,J,se){let ae=null;return(X[0]>J[2]||J[0]>X[2]||X[1]>J[3]||J[1]>X[3])&&(se===0?ae=[]:se===2?ae=q:(se===1||se===3)&&(ae=q.concat(K))),ae}(m,x,S,A,u),b!==null)return qee(b);let D=TLe(bLe(I,0,0,S,A,u)),B=D.map(q=>a$(q.points,!q.isExterior())),U=[];for(let q=0;q0&&(x=Hee(x,b,2)),Kee(x,1/65536,.001)}function o$(h,o=1){return[h.map(u=>u.map(m=>[m.x*o,m.y*o]))]}function Wee(h,o){const u=Math.floor(h)+.5;return Math.abs(h-u)<=o?Math.round(u):Math.round(h)}class CLe{constructor(o){this.xs=[],this.ys=[],this.ixs=[],this.iys=[],this.buckets=new Map,this.tolerance=o}canonicalize(o,u){const m=this.tolerance,x=Math.floor(o/m),b=Math.floor(u/m);for(let I=-1;I<=1;I++){const D=this.buckets.get(x+I);if(D)for(let B=-1;B<=1;B++){const U=D.get(b+B);if(U){for(const q of U)if(Math.abs(this.xs[q]-o)<=m&&Math.abs(this.ys[q]-u)<=m){const K=this.ixs[q],X=this.iys[q];return this.xs[q]===o&&this.ys[q]===u||this.store(o,u,K,X,x,b),[K,X]}}}}const S=Wee(o,m),A=Wee(u,m);return this.store(o,u,S,A,x,b),[S,A]}store(o,u,m,x,b,S){const A=this.xs.length;this.xs.push(o),this.ys.push(u),this.ixs.push(m),this.iys.push(x);let I=this.buckets.get(b);I||(I=new Map,this.buckets.set(b,I));let D=I.get(S);D||(D=[],I.set(S,D)),D.push(A)}}function Kee(h,o=1,u){const m=u!=null?new CLe(u):null;return h.map(x=>x.map(b=>b.map(S=>{const A=S[0]*o,I=S[1]*o;if(m){const[D,B]=m.canonicalize(A,I);return new jt(D,B)}return new jt(Math.round(A),Math.round(I))})))}class l${constructor(){this.frcCoverage=new Set,this.featureTriSegments=[],this.frcPerLevel=new Map,this.frcNonRoadSegments=new xn}empty(){return this.frcCoverage.size===0}}function Yee(h,o,u){if(h.frcCoverage.size===0||h.featureTriSegments.length===0)return;const m=u.get(),x=o.uint16,b=[];h.featureTriSegments.sort((U,q)=>U.segIdx!==q.segIdx?U.segIdx-q.segIdx:U.frc===null&&q.frc===null?0:U.frc===null?-1:q.frc===null?1:q.frc-U.frc);const S=new Map;let A=0,I=h.featureTriSegments[0].frc,D={vertexOffset:m[A].vertexOffset,primitiveOffset:0,vertexLength:m[A].vertexLength,primitiveLength:0,vaos:{},sortKey:void 0,batchIndex:m[A].batchIndex};const B=()=>{D.primitiveLength>0&&(S.has(I)||S.set(I,[]),S.get(I).push({...D}))};for(const U of h.featureTriSegments){U.segIdx!==A&&(B(),A=U.segIdx,I=U.frc,D={vertexOffset:m[A].vertexOffset,primitiveOffset:b.length/3,vertexLength:m[A].vertexLength,primitiveLength:0,vaos:{},sortKey:void 0,batchIndex:m[A].batchIndex}),U.frc!==I&&(B(),I=U.frc,D={...D,primitiveOffset:b.length/3,primitiveLength:0});for(let q=U.start;q0?b.length-1:0,frc:x})}buildFrcSegments(o){this.frcData&&!this.frcData.empty()&&Yee(this.frcData,o.bufferData.indexArray,o.bufferData.triangleSegments)}handleFeature(o,u,m,x,b,S){const A=new Array;if(!this.elevationMode)return!1;const I=vk(o,b,void 0,x);if(!I)return!1;{const B=this.clipPolygonsToTile(u,1);B.length>0&&A.push({polygons:B,elevationFeature:I.feature,elevationTileID:I.tileId})}const D={guardRailEnabled:S.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(o,{},x),featureIndex:m};for(const B of A)if(B.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new _d(B.elevationTileID,S.layers,S.zoom,S.lut));const q=B.elevationFeature.isTunnel();let K=0;Object.hasOwn(o.properties,SJ)&&(K=+o.properties[SJ]),this.elevatedStructures.addPortalCandidates(B.elevationFeature.id,B.polygons,q,B.elevationFeature,K)}B.elevationFeature.constantHeight==null&&(B.polygons=this.prepareElevatedPolygons(B.polygons,B.elevationFeature,B.elevationTileID));const U=new Q1(x,B.elevationTileID);this.addElevatedGeometry(S,B.polygons,U,B.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,m,D)}return!0}populatePaintArrays(o,u,m,x,b,S,A){this.elevationBufferData&&this.elevationBufferData.populatePaintArrays(o,u,m,x,b,S,A)}update(o,u,m,x,b,S,A,I){this.elevationBufferData&&this.elevationBufferData.update(o,u,m,x,b,S,A,I),this.elevatedStructures&&this.elevatedStructures.update(o,u,m,x,b,S,A,I)}updateExpressions(o){this.elevationBufferData&&this.elevationBufferData.programConfigurations.updateExpressions(o),this.elevatedStructures&&(this.elevatedStructures.bridgeProgramConfigurations.updateExpressions(o),this.elevatedStructures.tunnelProgramConfigurations.updateExpressions(o))}upload(o){this.elevationBufferData&&this.elevationBufferData.upload(o),this.elevatedStructures&&this.elevatedStructures.upload(o)}destroy(){this.elevationBufferData&&this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(o,u,m,x,b,S){this.elevatedStructures&&(this.elevatedStructures.construct(o),this.elevatedStructures.populatePaintArrays(u,m,x,b,S))}addElevatedGeometry(o,u,m,x,b,S,A){const I={elevation:x,elevationSampler:m,bias:b,index:S,featureInfo:A},[D,B]=o.addGeometry(u,this.elevationBufferData,I,this.elevatedStructures);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:D,max:B}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,D),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,B))}prepareElevatedPolygons(o,u,m){const x=1/Wc(m),b=[];for(const S of o){const A=jLe(S,new Nee(u,x),.1);b.push(...A)}return b}clipPolygonsToTile(o,u){const m=-u,x=-u,b=ar+u,S=ar+u;let A=0;const I=[],D=[];for(;A=m&&K.max.x<=b&&K.min.y>=x&&K.max.y<=S?I:D).push(q)}if(I.length===o.length)return o;const B=[new jt(m,x),new jt(b,x),new jt(b,S),new jt(m,S),new jt(m,x)],U=I;for(const q of D)U.push(...ILe(q,B));return U}}function NLe(h,o){return h.nextPoint.sub(o.at(-2)).unit()}function RLe(h,o){return o[1].sub(h.prevPoint).unit()}vr(Zee,"FillHDExtension"),vr(_d,"ElevatedStructures",{omit:["unevaluatedPortals","bridgeFeatureSections","tunnelFeatureSections","vertexHashLookup","unevalVertices","unevalHeights","unevalTriangles","unevalTunnelTriangles","unevalEdges","tileToMeters"]});class Xee{constructor(o,u){this.elevationEnabled=o,this.hasDeferredElevationFeatures=!1,u&&(this.frcData=new l$)}isEmpty(){const o=!this.elevationEnabled||this.heightRange===void 0,u=!this.frcData||this.frcData.empty();return o&&u}trackFeatureFrc(o){if(!this.frcData)return null;const u=sL(o||{});return u!==null&&this.frcData.frcCoverage.add(u),u}recordFeatureRange(o,u,m,x){if(!this.frcData||m<=u)return;const b=o.segments.get();this.frcData.featureTriSegments.push({start:3*u,end:3*m,segIdx:b.length>0?b.length-1:0,frc:x})}buildFrcSegments(o){this.frcData&&!this.frcData.empty()&&Yee(this.frcData,o.indexArray,o.segments)}handleFeature(o,u,m,x,b,S,A,I,D,B,U){if(!this.elevationEnabled)return!1;if(!U.terrainEnabled){const se=vk(o,x,b?b.registry:void 0,m),ae=o.properties!=null&&Object.hasOwn(o.properties,Kg)&&!Number.isNaN(+o.properties[Kg]);if(!se&&ae&&S&&(!b||!b.allProvidersReady))return this.hasDeferredElevationFeatures=!0,!0;if(se){let ue=se.feature,ce=se.tileId;if(!se.tileId.equals(m)){const ve=this.mergedFeatureCache?this.mergedFeatureCache.get(ue.id):void 0;if(ve)ue=ve,ce=m;else{const Ue=function(Pe,De,Ve){if(!Pe.properties||!De||De.length===0)return[];const Fe=+Pe.properties[Kg];if(Number.isNaN(Fe))return[];const Ze=Ree(De,Fe);if(Ze<0)return[];const st=[];for(let ut=Ze;ut1&&(ue=function(Pe,De){const Ve=De.slice().sort((Pt,Rt)=>Rt.tileId.z-Pt.tileId.z),Fe=new jt(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),Ze=new jt(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY),st=[];for(const Pt of Ve){const Rt=new Q1(Pt.tileId,Pe);for(const At of Pt.feature.vertices)st.push({position:Rt.pointTransform(At.position),height:At.height,extent:At.extent,index:At.index});const Ye=Pt.feature.safeArea;H0[0]=Ye.min.x,H0[1]=Ye.min.y,W0[0]=Ye.max.x,W0[1]=Ye.max.y,Rt.pointTransformInPlace(H0),Rt.pointTransformInPlace(W0),Fe.x=Math.min(Fe.x,H0[0],W0[0]),Fe.y=Math.min(Fe.y,H0[1],W0[1]),Ze.x=Math.max(Ze.x,H0[0],W0[0]),Ze.y=Math.max(Ze.y,H0[1],W0[1])}const ut={min:Fe,max:Ze};if(Ve[0].feature.constantHeight!=null)return new ty(Ve[0].feature.id,ut,Ve[0].feature.constantHeight);st.sort((Pt,Rt)=>Pt.index-Rt.index);const ht=[];for(const Pt of st)ht.length!==0&&ht.at(-1).index===Pt.index||ht.push(Pt);const _t=[];for(let Pt=1;Pt>1,U.layoutVertexArray.int16[Fe*Ve+1]>>1),st=Pe.pointElevation(Ze,ue,.05);this.updateHeightRange(st),Fe0?ue.parentIndex:null)}return U.fillNonElevatedRoadSegment(K),!0}prepareElevatedLines(o,u,m,x){if(u.constantHeight!=null)return o;const b=[],S=1/Wc(x),A=m.equals(x)?null:new Q1(m,x);for(const I of o)ZNe(I,new Nee(u,S,A),0,b);return b}updateHeightRange(o){this.heightRange?(this.heightRange.min=Math.min(this.heightRange.min,o),this.heightRange.max=Math.max(this.heightRange.max,o)):this.heightRange={min:o,max:o}}endPopulate(){this.mergedFeatureCache=void 0}}vr(Xee,"LineHDExtension");class Qee{constructor(){this.elevatedLayoutVertexArray=new Hu,this.hasElevation=!1}beginFeature(o,u,m){const x=vk(o,u,void 0,m);this.currentFeatureElevation=x?x.feature:void 0}writeVertexQuad(o,u){const m=this.currentFeatureElevation?this.currentFeatureElevation.pointElevation(new jt(o,u)):0;this.hasElevation=this.hasElevation||m!==0;for(let x=0;x<4;x++)this.elevatedLayoutVertexArray.emplaceBack(m)}finalize(){this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}upload(o){this.elevatedLayoutVertexArray&&!this.elevatedLayoutVertexBuffer&&(this.elevatedLayoutVertexBuffer=o.createVertexBuffer(this.elevatedLayoutVertexArray,tRe.members))}destroy(){this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy()}}vr(Qee,"CircleHDExtension");const aL=(h,o,u,m)=>{for(let x=0;x=this.elevationFeatures.length)return!1;const m=this.elevationFeatureTileIds[o];return m!=null&&!m.equals(u)}getRoadFeatureHeightAtAnchor(o,u,m){if(o===65535||o>=this.elevationFeatures.length)return null;const x=this.elevationFeatures[o],b=this.elevationFeatureTileIds[o];return b.equals(m)?x.pointElevation(u):this.getElevationFeatureSampler(m,b).pointElevation(new jt(u.x,u.y),x,0)}sampleRoadFeatureHeight(o,u,m){const x=this.getRoadFeatureHeightAtAnchor(o,u,m);return x===null?void 0:x}clearWorkerState(){this.consumerCanonical=void 0,this.elevationParams=null,this.crossSourceElevationEnabled=!1,this.terrainEnabled=!1,this.elevationFeatureIdToIndex.clear()}updateRoadElevation(o,u){if(this.elevationStateComplete)return;this.elevationStateComplete=!0,o.hasAnyZOffset=!1;let m=!1;const x=Wc(u),b=1/x;let S=!1,A=!1;for(let I=0;I0||K>0,ae=X>0,ue=D.elevationFeatureIndex,ce=ue=0&&aL(o.icon.orientationVertexArray,X,B,U),xe>=0&&aL(o.icon.orientationVertexArray,J,B,U)}}S||(o.text.orientationVertexArray=void 0),A||(o.icon.orientationVertexArray=void 0),m&&(o.zOffsetBuffersNeedUpload=!0,o.zOffsetSortDirty=!0)}getRoadFeatureHeightForPlacedSymbol(o,u,m,x,b){const S=o.symbolInstances.get(u.symbolInstanceIndices[m]);return this.getRoadFeatureHeightAtAnchor(S.elevationFeatureIndex,x,b)}getElevationFeatureForPlacedSymbol(o,u,m){const x=o.symbolInstances.get(u.symbolInstanceIndices[m]).elevationFeatureIndex;if(x{const X=this.getRoadFeatureHeightForPlacedSymbol(o,u,m,K,x.canonical);return function(J,se,ae,ue,ce,de){const xe=ue.upVector(se,ae.x,ae.y);return ft(xe,xe,J*ue.upVectorScale(se,ce,de).metersToTile),[xe[0],xe[1],xe[2]]}(X!==null?X:0,x.canonical,K,A,I,D)},elevation:S,elevationFeature:null}:{getElevation:b,elevation:S,elevationFeature:U}}}vr(Jee,"SymbolHDExtension",{omit:["consumerCanonical","elevationParams","crossSourceElevationEnabled","terrainEnabled","hasDeferredElevationFeatures","elevationFeatureIdToIndex"]});let gm=null,oL=null,u$=null,lL=null;function ete(){var h;if(!u$)return lL!=null||(lL=(h=fetch(ye()),WebAssembly.instantiateStreaming(h,{}).then(o=>{const{sbrk:u,memory:m,meshopt_decodeVertexBuffer:x,meshopt_decodeIndexBuffer:b,meshopt_decodeIndexSequence:S,meshopt_decodeFilterOct:A,meshopt_decodeFilterQuat:I,meshopt_decodeFilterExp:D}=o.instance.exports,B={ATTRIBUTES:x,TRIANGLES:b,INDICES:S},U={OCTAHEDRAL:A,QUATERNION:I,EXPONENTIAL:D};return o.instance.exports.__wasm_call_ctors(),{decodeGltfBuffer(q,K,X,J,se,ae){const ue=K+3&-4,ce=u(ue*X),de=u(J.length),xe=new Uint8Array(m.buffer);xe.set(J,de);const ve=B[se](ce,K,X,de,J.length);if(ve===0&&U[ae]&&U[ae](ce,ue,X),q.set(xe.subarray(ce,ce+K*X)),u(ce-u(0)),ve!==0)throw new Error(`Malformed buffer data: ${ve}`)}}})).then(o=>{u$=o,lL=null})),lL}const tte=5120,rte=5121,nte=5122,ite=5123,ste=5125,ate=5126,eS={[tte]:Int8Array,[rte]:Uint8Array,[nte]:Int16Array,[ite]:Uint16Array,[ste]:Uint32Array,[ate]:Float32Array},LLe={[tte]:"DT_INT8",[rte]:"DT_UINT8",[nte]:"DT_INT16",[ite]:"DT_UINT16",[ste]:"DT_UINT32",[ate]:"DT_FLOAT32"},tS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};function ote(h,o,u){const m=u.json.bufferViews.length,x=u.buffers.length;o.bufferView=m,u.json.bufferViews[m]={buffer:x,byteLength:h.byteLength},u.buffers[x]=h}const d$="KHR_draco_mesh_compression";function DLe(h,o){const u=h.extensions&&h.extensions[d$];if(!u)return;const m=new gm.Decoder,x=dte(o,u.bufferView),b=new gm.Mesh;if(!m.DecodeArrayToMesh(x,x.byteLength,b))throw new Error("Failed to decode Draco mesh");const S=o.json.accessors[h.indices],A=eS[S.componentType],I=S.count*A.BYTES_PER_ELEMENT,D=gm._malloc(I);A===Uint16Array?m.GetTrianglesUInt16Array(b,I,D):m.GetTrianglesUInt32Array(b,I,D),ote(gm.memory.buffer.slice(D,D+I),S,o),gm._free(D);for(const B of Object.keys(u.attributes)){const U=m.GetAttributeByUniqueId(b,u.attributes[B]),q=o.json.accessors[h.attributes[B]],K=LLe[q.componentType],X=q.count*tS[q.type]*eS[q.componentType].BYTES_PER_ELEMENT,J=gm._malloc(X);m.GetAttributeDataArrayForAllPoints(b,U,gm[K],X,J),ote(gm.memory.buffer.slice(J,J+X),q,o),gm._free(J)}m.destroy(),b.destroy(),delete h.extensions[d$]}const cL="EXT_meshopt_compression";function MLe(h,o){if(!h.extensions||!h.extensions[cL])return;const u=h.extensions[cL],m=new Uint8Array(o.buffers[u.buffer],u.byteOffset||0,u.byteLength||0),x=new Uint8Array(u.count*u.byteStride);u$.decodeGltfBuffer(x,u.count,u.byteStride,m,u.mode,u.filter),h.buffer=o.buffers.length,h.byteOffset=0,o.buffers[h.buffer]=x.buffer,delete h.extensions[cL]}const lte=1179937895,cte=new TextDecoder("utf8");function ute(h,o){return new URL(h,o).href}async function OLe(h,o,u,m,x){const b=await fetch(ute(h.uri,m),{signal:x}),S=await b.arrayBuffer();o.buffers[u]=S}function dte(h,o){const u=h.json.bufferViews[o];return new Uint8Array(h.buffers[u.buffer],u.byteOffset||0,u.byteLength)}async function FLe(h,o,u,m,x){if(h.uri){const b=ute(h.uri,m),S=await fetch(b,{signal:x}),A=await S.blob(),I=await createImageBitmap(A);o.images[u]=I}else if(h.bufferView!==void 0){const b=dte(o,h.bufferView),S=new Blob([b],{type:h.mimeType}),A=await createImageBitmap(S);o.images[u]=A}}async function hte(h,o=0,u,m){const x={json:null,images:[],buffers:[]};if(new Uint32Array(h,o,1)[0]===lte){const K=new Uint32Array(h,o);let X=2;const J=(K[X++]>>2)-3,se=K[X++]>>2;if(X++,x.json=JSON.parse(cte.decode(K.subarray(X,X+se))),X+=se,X>>0,Math.ceil(1.2*ce)),xe=Math.ceil((de-ce)/65536);try{return J.grow(xe),se(),!0}catch{return!1}},b:ae}}).then(ue=>{const{Rb:ce,Qb:de,P:xe,T:ve,X:Ue,Ja:Pe,La:De,Qa:Ve,Va:Fe,Wa:Ze,eb:st,jb:ut,f:ht,e:_t,yb:Et,zb:Pt,Ab:Rt,Bb:Ye,Db:At,Gb:Tt}=ue.instance.exports;J=_t;const $t=(()=>{let Gt=0,kt=0,Dt=0,dr=0;return nr=>{Dt&&(ce(dr),ce(Gt),kt+=Dt,Dt=Gt=0),Gt||(kt+=128,Gt=de(kt));const yr=nr.length+7&-8;let Br=Gt;yr>=kt&&(Dt=yr,Br=dr=de(yr));for(let br=0;br{gm=K,oL=null})),oL}()),q&&B.push(ete()),S)for(let K=0;Kthis.max.x||this.min.x>o.x||o.y>this.max.y||this.min.y>o.y)return;const m=jp(o.x-this.min.x,this.xScale,this.cellsX),x=jp(o.y-this.min.y,this.yScale,this.cellsY)*this.cellsX+m,b=this.cellOffsets[x],S=this.cellOffsets[x+1];if(b!==S){this._lazyInitLookup();for(let A=b;Athis.max.x||this.min.x>u.x||o.y>this.max.y||this.min.y>u.y)return;this._lazyInitLookup();const x=jp(o.x-this.min.x,this.xScale,this.cellsX),b=jp(u.x-this.min.x,this.xScale,this.cellsX),S=jp(o.y-this.min.y,this.yScale,this.cellsY),A=jp(u.y-this.min.y,this.yScale,this.cellsY);for(let I=S;I<=A;I++)for(let D=x;D<=b;D++){const B=I*this.cellsX+D,U=this.cellOffsets[B+1];for(let q=this.cellOffsets[B];q0){const b=function(S,A){const I=A.worldSize,D=ks(1,0)*I*bf(A.center.lat,A.zoom)/Dz(I),B=ks(1,A.center.lat)*I,U=G([]);pe(U,U,Bn(A.center.lng)),oe(U,U,Bn(A.center.lat)),ee(U,U,[0,0,Hc]),ie(U,U,[D,D,D*B]);const q=A.point;return ee(U,U,[-q.x,-q.y,0]),Q(U,U,S),Q(U,A.globeMatrix,U)}(h,o);return function(S,A,I){const D=(X,J,se)=>{const ae=ot(X),ue=ot(J),ce=Qg(X,J,se);return ft(ce,ce,1/ot(ce)*Kr(ae,ue,se))},B=D([S[0],S[1],S[2]],[A[0],A[1],A[2]],I),U=D([S[4],S[5],S[6]],[A[4],A[5],A[6]],I),q=D([S[8],S[9],S[10]],[A[8],A[9],A[10]],I),K=Qg([S[12],S[13],S[14]],[A[12],A[13],A[14]],I);return[B[0],B[1],B[2],0,U[0],U[1],U[2],0,q[0],q[1],q[2],0,K[0],K[1],K[2],1]}(x,b,m)}return x}function f$(h,o,u,m){const x=js.projectAabbCorners(m,u);let b=Number.MAX_VALUE;for(let A=0;A0||se===0&&X[0]*J[0]+X[1]*J[1]>=0&&X[0]*X[0]+X[1]*X[1]>J[0]*J[0]+J[1]*J[1])&&(B=K)}U=B}while(U!==D);return I.length>0&&I.push(I[0]),I}(x);if(fz(h,S))return b}const Y0=64,xte=["","wall","door","roof","window","lamp","logo"],KLe=[1,1,1];function fL(h,o,u,m,x,b,S,A,I,D=!1){const B=u.zoom,U=u.project(m),q=bf(m.lat,B),K=1/q;G(h),ee(h,h,[U.x+S[0]*K,U.y+S[1]*K,S[2]]);let X=1,J=1;const se=u.worldSize;if(D){if(u.projection.name==="mercator"){let de=0;u.elevation&&(de=u.elevation.getAtPointOrZero(new os(U.x/se,U.y/se),0));const xe=Ki([],[U.x,U.y,de,1],u.projMatrix)[3]/u.cameraToCenterDistance;X=xe,J=xe*bf(u.center.lat,B)}else if(u.projection.name==="globe"){const de=hL(h,u),xe=[0,0,0,1];Ki(xe,xe,Q([],u.projMatrix,de));const ve=xe[3]/u.cameraToCenterDistance,Ue=Ip(B),Pe=u.projection.pixelsPerMeter(m.lat,se)*bf(m.lat,B),De=u.projection.pixelsPerMeter(u.center.lat,se)*bf(u.center.lat,B);X=ve/Kr(Pe,yR(u.center.lat),Ue),J=ve*q/Pe,X*=De,J*=De}}else X=K;ie(h,h,[X,X,J]);const ae=[...h],ue=o.orientation,ce=[];if(yte(ce,[ue[0]+(x?x[0]:0),ue[1]+(x?x[1]:0),ue[2]+(x?x[2]:0)],b),Q(h,ae,ce),A&&u.elevation){let de=0;const xe=[];if(I&&u.elevation){de=function(Ue,Pe,De,Ve,Fe){const Ze=Pe.elevation;if(!Ze)return 0;const st=js.projectAabbCorners(De,Ve),ut=ks(1,Fe.lat)*Pe.worldSize,ht=function(Dt,dr){const nr=[0,0,1],yr=[{corners:[0,1,3,2],dotProductWithUp:0},{corners:[1,5,2,6],dotProductWithUp:0},{corners:[0,4,1,5],dotProductWithUp:0},{corners:[2,6,3,7],dotProductWithUp:0},{corners:[4,7,5,6],dotProductWithUp:0},{corners:[0,3,4,7],dotProductWithUp:0}];for(const Br of yr){const br=Dt[Br.corners[0]],dn=Dt[Br.corners[1]],rn=Dt[Br.corners[2]],wr=[dn[0]-br[0],dn[1]-br[1],dr*(dn[2]-br[2])],Fr=Jr(wr,wr,[rn[0]-br[0],rn[1]-br[1],dr*(rn[2]-br[2])]);zt(Fr,Fr),Br.dotProductWithUp=Vr(Fr,nr)}return yr.sort((Br,br)=>Br.dotProductWithUp-br.dotProductWithUp),yr[0].corners}(st,ut),_t=st[ht[0]],Et=st[ht[1]],Pt=st[ht[2]],Rt=st[ht[3]],Ye=Ze.getAtPointOrZero(new os(_t[0]/Pe.worldSize,_t[1]/Pe.worldSize),0),At=Ze.getAtPointOrZero(new os(Et[0]/Pe.worldSize,Et[1]/Pe.worldSize),0),Tt=Ze.getAtPointOrZero(new os(Pt[0]/Pe.worldSize,Pt[1]/Pe.worldSize),0),$t=Ze.getAtPointOrZero(new os(Rt[0]/Pe.worldSize,Rt[1]/Pe.worldSize),0),Gt=(Ye+$t)/2,kt=(At+Tt)/2;return Gt>kt?At=o.gl.NEAREST_MIPMAP_NEAREST}),h.uploaded=!0,h.image=null)}function vte(h,o,u){h.indexBuffer=o.createIndexBuffer(h.indexArray,!1,!0),h.vertexBuffer=o.createVertexBuffer(h.vertexArray,BLe.members,!1,!0),h.normalArray&&(h.normalBuffer=o.createVertexBuffer(h.normalArray,qLe.members,!1,!0)),h.texcoordArray&&(h.texcoordBuffer=o.createVertexBuffer(h.texcoordArray,(h.texcoordArray.bytesPerElement===8?ULe:VLe).members,!1,!0)),h.colorArray&&(h.colorBuffer=o.createVertexBuffer(h.colorArray,(h.colorArray.bytesPerElement===12?zLe:$Le).members,!1,!0)),h.featureArray&&(h.featureBuffer=o.createVertexBuffer(h.featureArray,HLe.members,!1,!0)),h.segments=xn.simpleSegment(0,0,h.vertexArray.length,h.indexArray.length);const m=h.material;m.pbrMetallicRoughness.baseColorTexture&&Tk(m.pbrMetallicRoughness.baseColorTexture,o),m.pbrMetallicRoughness.metallicRoughnessTexture&&Tk(m.pbrMetallicRoughness.metallicRoughnessTexture,o),m.normalTexture&&Tk(m.normalTexture,o),m.occlusionTexture&&Tk(m.occlusionTexture,o,u),m.emissionTexture&&Tk(m.emissionTexture,o)}function m$(h,o,u){if(h.meshes)for(const m of h.meshes)vte(m,o,u);if(h.lodMeshes)for(const m of h.lodMeshes)vte(m,o,u);if(h.children)for(const m of h.children)m$(m,o,u)}function bte(h){h.indexArray.destroy(),h.vertexArray.destroy(),h.colorArray&&h.colorArray.destroy(),h.normalArray&&h.normalArray.destroy(),h.texcoordArray&&h.texcoordArray.destroy(),h.featureArray&&h.featureArray.destroy()}function mL(h){if(h.meshes)for(const o of h.meshes)bte(o);if(h.lodMeshes)for(const o of h.lodMeshes)bte(o);if(h.children)for(const o of h.children)mL(o)}function wte(h){var o;h.vertexBuffer&&(h.vertexBuffer.destroy(),h.indexBuffer.destroy(),h.normalBuffer&&h.normalBuffer.destroy(),h.texcoordBuffer&&h.texcoordBuffer.destroy(),h.colorBuffer&&h.colorBuffer.destroy(),h.featureBuffer&&h.featureBuffer.destroy(),h.segments.destroy(),h.material&&((o=h.material).pbrMetallicRoughness.baseColorTexture&&o.pbrMetallicRoughness.baseColorTexture.gfxTexture&&o.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),o.pbrMetallicRoughness.metallicRoughnessTexture&&o.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&o.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),o.normalTexture&&o.normalTexture.gfxTexture&&o.normalTexture.gfxTexture.destroy(),o.emissionTexture&&o.emissionTexture.gfxTexture&&o.emissionTexture.gfxTexture.destroy(),o.occlusionTexture&&o.occlusionTexture.gfxTexture&&o.occlusionTexture.gfxTexture.destroy()))}function p$(h){if(h.meshes)for(const o of h.meshes)wte(o);if(h.lodMeshes)for(const o of h.lodMeshes)wte(o);if(h.footprintDebugMesh&&(h.footprintDebugMesh.vertexBuffer.destroy(),h.footprintDebugMesh.indexBuffer.destroy(),h.footprintDebugMesh.segments.destroy()),h.children)for(const o of h.children)p$(o)}function g$(h,o,u,m,x){const b=3*u;return h[b]<=x[0]&&o[b]>=m[0]&&h[b+1]<=x[1]&&o[b+1]>=m[1]&&h[b+2]<=x[2]&&o[b+2]>=m[2]}function YLe(h,o,u,m,x,b,S,A,I,D,B){const U=.5*(D[0]+B[0]),q=.5*(D[1]+B[1]),K=.5*(D[2]+B[2]),X=.5*(B[0]-D[0]),J=.5*(B[1]-D[1]),se=.5*(B[2]-D[2]),ae=h-U,ue=o-q,ce=u-K,de=m-U,xe=x-q,ve=b-K,Ue=S-U,Pe=A-q,De=I-K,Ve=de-ae,Fe=xe-ue,Ze=ve-ce,st=Ue-de,ut=Pe-xe,ht=De-ve,_t=ae-Ue,Et=ue-Pe,Pt=ce-De;let Rt,Ye,At,Tt,$t,Gt;if(Rt=ce*Fe-ue*Ze,Ye=ve*Fe-xe*Ze,At=De*Fe-Pe*Ze,Tt=Math.min(Rt,Ye,At),$t=Math.max(Rt,Ye,At),Gt=Math.abs(Ze)*J+Math.abs(Fe)*se,Tt>Gt||$t<-Gt||(Rt=ce*ut-ue*ht,Ye=ve*ut-xe*ht,At=De*ut-Pe*ht,Tt=Math.min(Rt,Ye,At),$t=Math.max(Rt,Ye,At),Gt=Math.abs(ht)*J+Math.abs(ut)*se,Tt>Gt||$t<-Gt)||(Rt=ce*Et-ue*Pt,Ye=ve*Et-xe*Pt,At=De*Et-Pe*Pt,Tt=Math.min(Rt,Ye,At),$t=Math.max(Rt,Ye,At),Gt=Math.abs(Pt)*J+Math.abs(Et)*se,Tt>Gt||$t<-Gt)||(Rt=ae*Ze-ce*Ve,Ye=de*Ze-ve*Ve,At=Ue*Ze-De*Ve,Tt=Math.min(Rt,Ye,At),$t=Math.max(Rt,Ye,At),Gt=Math.abs(Ze)*X+Math.abs(Ve)*se,Tt>Gt||$t<-Gt)||(Rt=ae*ht-ce*st,Ye=de*ht-ve*st,At=Ue*ht-De*st,Tt=Math.min(Rt,Ye,At),$t=Math.max(Rt,Ye,At),Gt=Math.abs(ht)*X+Math.abs(st)*se,Tt>Gt||$t<-Gt)||(Rt=ae*Pt-ce*_t,Ye=de*Pt-ve*_t,At=Ue*Pt-De*_t,Tt=Math.min(Rt,Ye,At),$t=Math.max(Rt,Ye,At),Gt=Math.abs(Pt)*X+Math.abs(_t)*se,Tt>Gt||$t<-Gt)||(Rt=ue*Ve-ae*Fe,Ye=xe*Ve-de*Fe,At=Pe*Ve-Ue*Fe,Tt=Math.min(Rt,Ye,At),$t=Math.max(Rt,Ye,At),Gt=Math.abs(Fe)*X+Math.abs(Ve)*J,Tt>Gt||$t<-Gt)||(Rt=ue*st-ae*ut,Ye=xe*st-de*ut,At=Pe*st-Ue*ut,Tt=Math.min(Rt,Ye,At),$t=Math.max(Rt,Ye,At),Gt=Math.abs(ut)*X+Math.abs(st)*J,Tt>Gt||$t<-Gt)||(Rt=ue*_t-ae*Et,Ye=xe*_t-de*Et,At=Pe*_t-Ue*Et,Tt=Math.min(Rt,Ye,At),$t=Math.max(Rt,Ye,At),Gt=Math.abs(Et)*X+Math.abs(_t)*J,Tt>Gt||$t<-Gt)||(Tt=Math.min(ae,de,Ue),$t=Math.max(ae,de,Ue),Tt>X||$t<-X)||(Tt=Math.min(ue,xe,Pe),$t=Math.max(ue,xe,Pe),Tt>J||$t<-J)||(Tt=Math.min(ce,ve,De),$t=Math.max(ce,ve,De),Tt>se||$t<-se))return!1;const kt=Fe*ht-Ze*ut,Dt=Ze*st-Ve*ht,dr=Ve*ut-Fe*st,nr=-(kt*ae+Dt*ue+dr*ce);return Gt=X*Math.abs(kt)+J*Math.abs(Dt)+se*Math.abs(dr),!(Math.abs(nr)>Gt)}const ZLe=[];class Ste{serializeFromGltf(o,u,m,x){if(o.length<7)return;let b=0;if(o[b++]!==109||o[b++]!==98||o[b++]!==120||o[b++]!==98||o[b++]!==118||o[b++]!==104||o[b++]!==43)return;const S=new DataView(o.buffer,o.byteOffset),A=S.getUint16(b,!0);if(b+=2,A===0)return;this._nodeMin=u.slice(0,3*A),this._nodeMax=m.slice(0,3*A);const I=this._nodeData=new Uint32Array(3*A);for(let U=0;UB&&(B=x[U]);this._indices=B<65536?new Uint16Array(x.subarray(0,D)):x.slice(0,D)}setVertices(o){this._vertices=o}findHighestPoint(o,u){const m=this._nodeData;if(!m)return null;const x=this._nodeMin,b=this._nodeMax;if(!g$(x,b,0,o,u))return null;const S=this._indices,A=this._vertices,I=ZLe;I.length=0,I.push(0);let D=-1/0;for(;I.length>0;){const B=I.pop();if(b[3*B+2]<=D)continue;const U=m[3*B];if(U===65535){const J=m[3*B+1],se=m[3*B+2];for(let ae=0;ae=0?D:null}}function Ete(h){switch(h){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}function rS(h,o){const u=h.json.bufferViews[o.bufferView],m=eS[o.componentType];return new m(h.buffers[u.buffer],(o.byteOffset||0)+(u.byteOffset||0),o.count*(u.byteStride&&u.byteStride!==tS[o.type]*m.BYTES_PER_ELEMENT?u.byteStride/m.BYTES_PER_ELEMENT:tS[o.type]))}function Tte(h,o,u,m){const x=rS(h,o),b=x instanceof Float32Array?x:new Uint32Array(x.buffer,x.byteOffset,o.count),S=new le;S.reserveExact(o.count);let A=-1;for(let I=0;I>>16|b[I]<<16:b[I],B=65535&D,U=D>>>16;A=A<0&&(15&U)==2?B:A,S.emplaceBack(B,U)}m.featureArray=S,A>=0&&(m.doorVertexColor=A)}function y$(h,o,u,m,x=!0){const b=eS[o.componentType],S=tS[o.type],A=x?Ete(b):1,I=h.json.bufferViews[o.bufferView],D=I.byteStride?I.byteStride/b.BYTES_PER_ELEMENT:S,B=o.count*D;for(let U=0,q=0;U0){const ue=o.json.accessors[x.TEXCOORD_0],ce=rS(o,ue);ue.normalized&&eS[ue.componentType]===Uint16Array?(b.texcoordArray=new le,b.texcoordArray.resizeExact(ue.count),y$(o,ue,b.texcoordArray.uint16,ce,!1)):(b.texcoordArray=new bt,b.texcoordArray.resizeExact(ue.count),y$(o,ue,b.texcoordArray.float32,ce))}const se=!(!o.json.extensionsUsed||!o.json.extensionsUsed.includes("EXT_meshopt_compression"));x._FEATURE_ID_RGBA4444!==void 0&&se&&Tte(o,o.json.accessors[x._FEATURE_ID_RGBA4444],!1,b),x._FEATURE_RGBA4444!==void 0&&Tte(o,o.json.accessors[x._FEATURE_RGBA4444],!se,b),b.hasFeatureData=!!b.featureArray;const ae=h.material;return b.material=function(ue,ce){const{emissiveFactor:de=[0,0,0],alphaMode:xe="OPAQUE",alphaCutoff:ve=.5,normalTexture:Ue,occlusionTexture:Pe,emissiveTexture:De,doubleSided:Ve,name:Fe}=ue,{baseColorFactor:Ze=[1,1,1,1],metallicFactor:st=1,roughnessFactor:ut=1,baseColorTexture:ht,metallicRoughnessTexture:_t}=ue.pbrMetallicRoughness||{},Et=Pe?ce[Pe.index]:void 0;if(Pe&&Pe.extensions&&Pe.extensions.KHR_texture_transform&&Et){const Pt=Pe.extensions.KHR_texture_transform;Et.offsetScale=[Pt.offset[0],Pt.offset[1],Pt.scale[0],Pt.scale[1]]}return{name:Fe,pbrMetallicRoughness:{baseColorFactor:new Vn(...Ze),metallicFactor:st,roughnessFactor:ut,baseColorTexture:ht?ce[ht.index]:void 0,metallicRoughnessTexture:_t?ce[_t.index]:void 0},doubleSided:Ve,emissiveFactor:new Vn(...de),alphaMode:xe,alphaCutoff:ve,normalTexture:Ue?ce[Ue.index]:void 0,occlusionTexture:Et,emissionTexture:De?ce[De.index]:void 0,defined:ue.defined===void 0}}(ae!==void 0?o.json.materials[ae]:{defined:!1},u),b}function x$(h,o,u){const{matrix:m,rotation:x,translation:b,scale:S,mesh:A,extras:I,children:D,name:B}=h,U={};if(U.name=B,U.localMatrix=m?Float64Array.from(m):function(q,K,X,J){var se=K[0],ae=K[1],ue=K[2],ce=K[3],de=se+se,xe=ae+ae,ve=ue+ue,Ue=se*de,Pe=se*xe,De=se*ve,Ve=ae*xe,Fe=ae*ve,Ze=ue*ve,st=ce*de,ut=ce*xe,ht=ce*ve,_t=J[0],Et=J[1],Pt=J[2];return q[0]=(1-(Ve+Ze))*_t,q[1]=(Pe+ht)*_t,q[2]=(De-ut)*_t,q[3]=0,q[4]=(Pe-ht)*Et,q[5]=(1-(Ue+Ze))*Et,q[6]=(Fe+st)*Et,q[7]=0,q[8]=(De+ut)*Pt,q[9]=(Fe-st)*Pt,q[10]=(1-(Ue+Ve))*Pt,q[11]=0,q[12]=X[0],q[13]=X[1],q[14]=X[2],q[15]=1,q}(new Float64Array(16),x||[0,0,0,1],b||[0,0,0],S||[1,1,1]),U.globalMatrix=F(U.localMatrix),A!==void 0){U.meshes=u[A];const q=U.anchor=[0,0];for(const K of U.meshes){const{min:X,max:J}=K.aabb;q[0]+=X[0]+J[0],q[1]+=X[1]+J[1]}q[0]=Math.floor(q[0]/U.meshes.length/2),q[1]=Math.floor(q[1]/U.meshes.length/2)}if(I&&(I.id&&(U.id=I.id),I.lights&&(U.lights=function(q){if(!q.length)return[];const K=function(ue){const ce=atob(ue),de=new Uint8Array(ce.length);for(let xe=0;xe=ce.length||se>=ce.length||ae>=ce.length||ue>=ce.length)return null;const de=ce[J],xe=ce[se],ve=ce[ae],Ue=ce[ue];if(de.bufferView===void 0||xe.bufferView===void 0||ve.bufferView===void 0||Ue.bufferView===void 0)return null;const Pe=q.json.bufferViews;if(de.bufferView>=Pe.length||xe.bufferView>=Pe.length||ve.bufferView>=Pe.length||Ue.bufferView>=Pe.length)return null;const De=Pe[de.bufferView],Ve=Pe[xe.bufferView],Fe=Pe[ve.bufferView],Ze=Pe[Ue.bufferView];if(De.buffer>=q.buffers.length||Ve.buffer>=q.buffers.length||Fe.buffer>=q.buffers.length||Ze.buffer>=q.buffers.length)return null;const st=($t,Gt,kt)=>$t>=0&&$t<=kt&&Gt<=kt-$t,ut=de.byteOffset||0,ht=xe.byteOffset||0,_t=ve.byteOffset||0,Et=Ue.byteOffset||0;if(!(st(ut,0,De.byteLength)&&st(ht,3*xe.count*4,Ve.byteLength)&&st(_t,3*ve.count*4,Fe.byteLength)&&st(Et,4*Ue.count,Ze.byteLength)))return null;const Pt=new Uint8Array(q.buffers[De.buffer],(De.byteOffset||0)+ut,De.byteLength-ut),Rt=new Float32Array(q.buffers[Ve.buffer],(Ve.byteOffset||0)+ht,3*xe.count),Ye=new Float32Array(q.buffers[Fe.buffer],(Fe.byteOffset||0)+_t,3*ve.count),At=new Uint32Array(q.buffers[Ze.buffer],(Ze.byteOffset||0)+Et,Ue.count),Tt=new Ste;if(Tt.serializeFromGltf(Pt,Rt,Ye,At),X!==void 0&&q.json.meshes&&q.json.meshes[X]){const $t=q.json.meshes[X].primitives[0];if($t&&$t.attributes.POSITION!==void 0&&$t.attributes.POSITION1&&m.at(-1).equals(m[0])&&m.pop();let x=0;for(let S=0;S0&&m.reverse();const b=$x(m.flatMap(S=>[S.x,S.y]),[]);return b.length===0?null:{vertices:m,indices:b}}function eDe(h,o){const u=[],m=[];let x=0;const b=[];for(const S of h){x=u.length;const A=S.vertexArray.float32,I=S.indexArray.uint16;for(let D=0;D0&&([m[S+1],m[S+2]]=[m[S+2],m[S+1]])}return{vertices:u,indices:m}}function Ate(h,o){for(let u=0;u0){const J=Array.from(X.values()).sort((se,ae)=>se-ae);for(let se=J.length-1;se>=0;se--)B.splice(J[se],1)}})(I,A,h.json.nodes);const D=m?Ate(m,"LOD"):-1;if(D>=0){const B=m[D].nodes,U=new Map;for(const q of B){const K=x$(b[q],h,u);K.id&&U.set(K.id,K)}for(const q of I)if(q.id){const K=U.get(q.id);K&&K.meshes&&(q.lodMeshes=K.meshes,K.meshBVH&&(q.meshBVH=K.meshBVH))}}return I}function tDe(h){h.heightmap=new Float32Array(4096),h.heightmap.fill(-1);const o=h.vertexArray.float32,u=h.aabb.min[0]-1,m=h.aabb.min[1]-1,x=Y0/(h.aabb.max[0]-u+2),b=Y0/(h.aabb.max[1]-m+2);for(let S=0;Sh.heightmap[D*Y0+I]&&(h.heightmap[D*Y0+I]=A)}}function kte(h,o,u,m,x){u.reserve(u.length+4*h.length),m.reserve(m.length+10*h.length),x.reserve(x.length+10*h.length);let b=m.length;for(const S of h){const A=Math.min(10,Math.max(4,1.3*S.height))*o,I=[-S.normal[1],S.normal[0],0],D=Math.min(.29,.1*S.width/S.depth),B=S.width-2*S.depth*o*(D+.01),U=Kt([],S.pos,I,B/2),q=Kt([],S.pos,I,-B/2),K=[U[0],U[1],U[2]+S.height],X=[q[0],q[1],q[2]+S.height],J=Kt([],S.normal,I,D);ft(J,J,A);const se=Kt([],S.normal,I,-D);ft(se,se,A),vt(J,U,J),vt(se,q,se),U[2]+=.1,q[2]+=.1,m.emplaceBack(J[0],J[1],J[2]),m.emplaceBack(se[0],se[1],se[2]),m.emplaceBack(U[0],U[1],U[2]),m.emplaceBack(q[0],q[1],q[2]),m.emplaceBack(K[0],K[1],K[2]),m.emplaceBack(X[0],X[1],X[2]),m.emplaceBack(U[0],U[1],U[2]),m.emplaceBack(q[0],q[1],q[2]),m.emplaceBack(J[0],J[1],J[2]),m.emplaceBack(se[0],se[1],se[2]);const ae=B/A/2;x.emplaceBack(-ae-D,-1,ae,.8),x.emplaceBack(ae+D,-1,ae,.8),x.emplaceBack(-ae,0,ae,1.3),x.emplaceBack(ae,0,ae,1.3),x.emplaceBack(ae+D,-.8,ae,.7),x.emplaceBack(ae+D,-.8,ae,.7),x.emplaceBack(0,0,ae,1.3),x.emplaceBack(0,0,ae,1.3),x.emplaceBack(ae+D,-1.2,ae,.8),x.emplaceBack(ae+D,-1.2,ae,.8),u.emplaceBack(6+b,4+b,8+b),u.emplaceBack(7+b,9+b,5+b),u.emplaceBack(0+b,1+b,2+b),u.emplaceBack(1+b,3+b,2+b),b+=10}}function rDe(h,o,u){const m={};m.indexArray=new Ne,m.vertexArray=new k,m.colorArray=new Y,m.indexArray.reserveExact(4*h.length),m.vertexArray.reserveExact(10*h.length),m.colorArray.reserveExact(10*h.length),kte(h,o,m.indexArray,m.vertexArray,m.colorArray),m.featureArray=new le,m.featureArray.reserveExact(m.vertexArray.length);for(let S=0;S{S.push(new jt(U,I+(U-A)/(D-A)*(B-I)))}:(S,A,I,D,B,U)=>{S.push(new jt(A+(U-I)/(B-I)*(D-A),U))};for(const S of h){const A=[];for(const I of S){if(I.length<=2)continue;const D=[];for(let q=0;qo&&b(D,K,X,J,se,o):ae>u?ue=o&&b(D,K,X,J,se,o),ue>u&&ae<=u&&b(D,K,X,J,se,u)}let B=I.at(-1);const U=m===0?B.x:B.y;U>=o&&U<=u&&D.push(B),D.length&&(B=D.at(-1),D[0].x===B.x&&D[0].y===B.y||D.push(D[0]),A.push(D))}A.length&&x.push(A)}return x}const v$=[new jt(0,0),new jt(ar,0),new jt(ar,ar),new jt(0,ar)];function jte(h,o){const u=[];let m=[];if(!o||h.length<2)return[h];if(h.length===2)return U1(h[0],h[1],v$)?[h]:[];for(let x=0;x0&&(m.length>1&&u.push(m),m=[])}return m.length>1&&u.push(m),u}const b$=Wx.types,vDe=["fill-extrusion-base","fill-extrusion-height","fill-extrusion-color","fill-extrusion-pattern","fill-extrusion-flood-light-wall-radius","fill-extrusion-line-width","fill-extrusion-emissive-strength"],bDe=["fill-extrusion-flood-light-ground-radius"],wDe=Math.pow(2,13),SDe=Math.pow(2,15)-1,gL=new jt(0,1),ry=2147483648,yL=1073741824;function Ak(h,o,u,m,x,b,S,A){h.emplaceBack((o<<1)+S,(u<<1)+b,(Math.floor(m*wDe)<<1)+x,Math.round(A))}function kk(h,o,u){h.emplaceBack(o.x*ar,o.y*ar,u?1:0)}function xL(h,o,u,m,x,b){h.emplaceBack(o.x,o.y,(u.x<<1)+m,(u.y<<1)+x,b)}function Ik(h,o,u){h.emplaceBack(o.x,o.y,o.z,u[0]*16384,u[1]*16384,u[2]*16384)}class Cte{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class _L{constructor(){this.data=[]}get length(){return this.data.length}push(o){this.data.push(o)}get(o){return this.data[o]}static serialize(o,u){const m=o.data.length,x=new Uint32Array(4*m),b=[];b.length=m;for(let S=0;So.max.x&&(o.max.x=u.x,x=!0),u.yo.max.y&&(o.max.y=u.y,x=!0),((u.x===0||u.x===ar)&&u.x===m.x)!=((u.y===0||u.y===ar)&&u.y===m.y)&&this.processBorderOverlap(u,m),x&&this.checkBorderIntersection(u,m)}checkBorderIntersection(o,u){u.x<0!=o.x<0&&this.addBorderIntersection(0,Kr(u.y,o.y,(0-u.x)/(o.x-u.x))),u.x>ar!=o.x>ar&&this.addBorderIntersection(1,Kr(u.y,o.y,(ar-u.x)/(o.x-u.x))),u.y<0!=o.y<0&&this.addBorderIntersection(2,Kr(u.x,o.x,(0-u.y)/(o.y-u.y))),u.y>ar!=o.y>ar&&this.addBorderIntersection(3,Kr(u.x,o.x,(ar-u.y)/(o.y-u.y)))}addBorderIntersection(o,u){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const m=this.borders[o];um[1]&&(m[1]=u)}processBorderOverlap(o,u){if(o.x===u.x){if(o.y===u.y)return;const m=o.x===0?0:1;this.addBorderIntersection(m,u.y),this.addBorderIntersection(m,o.y)}else{const m=o.y===0?2:3;this.addBorderIntersection(m,u.x),this.addBorderIntersection(m,o.x)}}centroid(){return this.accCount===0?new jt(0,0):new jt(Math.floor(Math.max(0,this.acc.x)/this.accCount),Math.floor(Math.max(0,this.acc.y)/this.accCount))}intersectsCount(){return this.borders?this.borders.reduce((o,u)=>o+ +(u[0]!==Number.MAX_VALUE),0):0}}function Pte(h,o){const u=h.add(o)._unit(),m=cn(h.x*u.x+h.y*u.y,-1,1),x=(b=Math.acos(m),Math.min(4,Math.max(-4,Math.tan(b)))/4*SDe*function(S,A){return S.x*A.y-S.y*A.x<0?-1:1}(h,o));var b;return x}const EDe=[h=>h.x<0,h=>h.x>ar,h=>h.y<0,h=>h.y>ar];function TDe(h,o,u,m){const x=[4];if(m===0)return x;u._mult(m);const b=h.sub(u),S=o.sub(u),A=[h,o,b,S];for(let I=0;I<4;I++)for(const D of A)if(EDe[I](D)){x.push(I);break}return x}class E${constructor(o){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new y,this.indexArray=new Ne,this.programConfigurations=new Hi(o.layers,{zoom:o.zoom,lut:o.lut},u=>bDe.includes(u)),this._segments=new xn,this.hiddenByLandmarkVertexArray=new Cr,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new xn}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(o,u,m,x=!1){const b=o.length;if(b>2){let S=Math.max(0,this._segments.get().length-1);const A=this._segments._prepareSegment(4*b,this.vertexArray.length,2*this._segmentToGroundQuads[S].length);let I;S!==this._segments.get().length-1&&(S++,this._segmentToGroundQuads[S]=[],this._segmentToRegionTriCounts[S]=[0,0,0,0,0]);{const D=o[0],B=o[1];I=Pte(D.sub(o[b-1])._perp()._unit(),B.sub(D)._perp()._unit())}for(let D=0;Dx.region-b.region);for(let m=0;mI+D,0);let A=0;for(let I=0;I<=4;I++){const D=S[I];if(D!==0){let B=this.regionSegments[I];B||(B=this.regionSegments[I]=new xn);const U={vertexOffset:b.vertexOffset,primitiveOffset:b.primitiveOffset+A,vertexLength:b.vertexLength,primitiveLength:D};B.get().push(U)}A+=D}for(let I=0;I0?this.hiddenByLandmarkVertexBuffer=o.createVertexBuffer(this.hiddenByLandmarkVertexArray,yDe.members,!0):this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.updateData(this.hiddenByLandmarkVertexArray),this._needsHiddenByLandmarkUpdate=!1)}destroy(){if(this.vertexBuffer){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.destroy(),this.groundRadiusBuffer&&this.groundRadiusBuffer.destroy(),this._segments&&this._segments.destroy(),this.programConfigurations.destroy();for(let o=0;o<=4;o++){const u=this.regionSegments[o];u&&u.destroy()}}}}class bL{constructor(o){this.zoom=o.zoom,this.canonical=o.canonical,this.overscaling=o.overscaling,this.layers=o.layers,this.pixelRatio=o.pixelRatio,this.layerIds=this.layers.map(u=>u.fqid),this.index=o.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=o.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=new vL,this.footprintIndices=new Ne,this.footprintVertices=new mm,this.footprintSegments=new _L,this.layoutVertexArray=new f,this.centroidVertexArray=new vn,this.wallVertexArray=new ei,this.indexArray=new Ne,this.programConfigurations=new Hi(o.layers,{zoom:o.zoom,lut:o.lut},u=>vDe.includes(u)),this.segments=new xn,this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.groundEffect=new E$(o),this.maxHeight=0,this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=o.worldview,this.hasAppearances=null}updateFootprints(o,u){}updateAppearances(o,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(o,u,m,x){this.features=[],this.hasPattern=V2("fill-extrusion",this.layers,this.pixelRatio,u),this.featuresOnBorder=[],this.borderFeatureIndices=[[],[],[],[]],this.borderDoneWithNeighborZ=[-1,-1,-1,-1],this.selfDEMTileTimestamp=Number.MAX_VALUE,this.borderDEMTileTimestamp=[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],this.tileToMeter=Wc(m),this.edgeRadius=this.layers[0].layout.get("fill-extrusion-edge-radius")/this.tileToMeter,this.wallMode=this.layers[0].paint.get("fill-extrusion-line-width").constantOr(1)!==0;const b=new Hs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors});for(const{feature:S,id:A,index:I,sourceLayerIndex:D}of o){const B=this.layers[0]._featureFilter.needGeometry,U=Ph(S,B);if(!this.layers[0]._featureFilter.filter(b,U,m))continue;const q={id:A,sourceLayerIndex:D,index:I,geometry:Ch(S,U,B,m,x),properties:S.properties,type:S.type,patterns:{}},K=this.layoutVertexArray.length,X=b$[q.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:S.id,feature:q2("fill-extrusion",this.layers,q,this.zoom,this.pixelRatio,u)});else if(this.wallMode)for(const J of q.geometry)for(const se of jte(J,X))this.addFeature(S.id,q,[se],I,m,{},u.availableImages,x,u.brightness);else this.addFeature(S.id,q,q.geometry,I,m,{},u.availableImages,x,u.brightness);u.featureIndex.insert(S,q.geometry,I,D,this.index,K)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(o,u,m,x,b,S){for(const{featureId:A,feature:I}of this.features){const D=b$[I.type]==="Polygon",{geometry:B}=I;if(this.wallMode)for(const U of B)for(const q of jte(U,D))this.addFeature(A,I,[q],I.index,u,m,x,b,S);else this.addFeature(A,I,B,I.index,u,m,x,b,S)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(o,u,m,x,b,S,A){this.programConfigurations.updatePaintArrays(o,u,b,m,x,S,A,this.worldview),this.groundEffect.update(o,u,b,m,x,S,A,this.worldview)}updateExpressions(o){this.programConfigurations.updateExpressions(o),this.groundEffect.programConfigurations.updateExpressions(o)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(o){this.uploaded||(this.layoutVertexBuffer=o.createVertexBuffer(this.layoutVertexArray,_De),this.indexBuffer=o.createIndexBuffer(this.indexArray),this.wallVertexBuffer=o.createVertexBuffer(this.wallVertexArray,gDe.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=o.createVertexBuffer(this.layoutVertexExtArray,xDe.members,!0)),this.groundEffect.upload(o)),this.groundEffect.uploadPaintProperties(o),this.programConfigurations.upload(o),this.uploaded=!0}uploadCentroid(o){this.groundEffect.uploadHiddenByLandmark(o),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=o.createVertexBuffer(this.centroidVertexArray,pDe.members,!0):this.centroidVertexBuffer&&this.centroidVertexBuffer.updateData(this.centroidVertexArray),this.needsCentroidUpdate=!1)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.centroidVertexBuffer&&this.centroidVertexBuffer.destroy(),this.layoutVertexExtBuffer&&this.layoutVertexExtBuffer.destroy(),this.groundEffect.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),new xn(this.triangleSubSegments.map(o=>o.segment)).destroy())}addFeature(o,u,m,x,b,S,A,I,D){const B=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(u,{})/this.tileToMeter,U=[new jt(0,0),new jt(ar,ar)],q=I.projection,K=q.name==="globe",X=this.wallMode||b$[u.type]==="Polygon",J=new S$;J.centroidDataIndex=this.centroidData.length;const se=new w$;se.buildingId=o,u.properties&&Object.hasOwn(u.properties,"building_id")&&(se.buildingId=Number(u.properties.building_id)),J.buildingId=se.buildingId;const ae=this.layers[0].paint.get("fill-extrusion-base").evaluate(u,{},b)<=0,ue=this.layers[0].paint.get("fill-extrusion-height").evaluate(u,{},b);let ce;if(se.height=ue,se.vertexArrayOffset=this.layoutVertexArray.length,se.groundVertexArrayOffset=this.groundEffect.vertexArray.length,K&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new z),this.wallMode){if(K)return void Xi("Non zero fill-extrusion-line-width is not yet supported on globe.");if(m.length!==1)return;ce=function(Ve){const Fe=Ve[0].x===Ve.at(-1).x&&Ve[0].y===Ve.at(-1).y;(function(kt){let Dt=0;const dr=kt.length;for(let nr=0;nr=0})(Ve)||(Ve=Ve.reverse());const st={geometry:[],joinNormals:[],indices:[]},ut=[],ht=[],_t=[];let Et=Ve.length;for(;Et>=2&&Ve[Et-1].equals(Ve[Et-2]);)Et--;if(Et<(Fe?3:2))return st;let Pt,Rt,Ye,At,Tt,$t=0;for(;$t0;let Br="miter";const br=2;Br==="miter"&&nr>br&&(Br="bevel"),Br==="bevel"&&(nr>100&&(Br="flipbevel"),nr{const ii=new jt(rn.x,rn.y),Xn=new jt(rn.x,rn.y);ii.x+=wr.x*ni,ii.y+=wr.y*ni,Xn.x-=wr.x*Math.max(Fr,1),Xn.y-=wr.y*Math.max(Fr,1),_t.push(wr),ut.push(ii),ht.push(Xn)};if(Br==="miter")Dt._mult(nr),dn(Pt,Dt,0,0);else if(Br==="flipbevel")Dt=Tt.mult(-1),dn(Pt,Dt,0,0),dn(Pt,Dt.mult(-1),0,0);else{const rn=-Math.sqrt(nr*nr-1),wr=yr?rn:0,Fr=yr?0:rn;Rt&&dn(Pt,At,wr,Fr),Ye&&dn(Pt,Tt,wr,Fr)}}st.geometry=[...ut,...ht.reverse(),ut[0]],st.joinNormals=[..._t,..._t.reverse(),_t.at(-1)];const Gt=st.geometry.length-1;for(let kt=0;ktVe<(Fe.length-1)/2||Ve===Fe.length-1,xe=this.wallMode?[m]:em(m,500);for(let Ve=xe.length-1;Ve>=0;Ve--){const Fe=xe[Ve];(Fe.length===0||IDe(Fe[0]))&&xe.splice(Ve,1)}let ve;if(K)ve=Fte(xe,U,b);else{ve=[];for(const Ve of xe)ve.push({polygon:Ve,bounds:U})}const Ue=X?this.edgeRadius:0,Pe=Ue>0&&this.zoom<17,De=(Ve,Fe)=>{if(Ve.length===0)return!1;const Ze=Ve.at(-1);return Fe.x===Ze.x&&Fe.y===Ze.y};for(const{polygon:Ve,bounds:Fe}of ve){let Ze=0,st=0;for(const Et of Ve)X&&!Et[0].equals(Et.at(-1))&&Et.push(Et[0]),st+=X?Et.length-1:Et.length;const ut=this.segments.prepareSegment((X?5:4)*st,this.layoutVertexArray,this.indexArray);se.footprintSegIdx<0&&(se.footprintSegIdx=this.footprintSegments.length),se.polygonSegIdx<0&&(se.polygonSegIdx=this.polygonSegments.length);const ht={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},_t=new Cte;if(_t.vertexOffset=this.footprintVertices.length,_t.indexOffset=3*this.footprintIndices.length,_t.ringIndices=[],X){const Et=[],Pt=[];Ze=ut.vertexLength;for(let Ye=0;Ye4&&Dte(Pt[Pt.length-2],Pt[0],Pt[1]),Ye=Ue?kDe(Pt[Pt.length-2],Pt[0],Pt[1],Ue):0;const At=[];let Tt,$t,Gt;$t=Pt[1].sub(Pt[0])._perp()._unit();let kt=!0;for(let Dt=1,dr=0;Dt0?1:0,wr=nr.dist(yr);if(dr+wr>32768&&(dr=0),Ue){Gt=wL(yr,Br,$t);let Xn=Rte(nr,yr,Br,T$($t,Gt),Ue);isNaN(Xn)&&(Xn=0);const bi=ADe(nr,yr,new jt(0,0));nr=nr.add(bi.mult(Ye))._round(),yr=yr.add(bi.mult(-Xn))._round(),Ye=Xn,$t=Gt,ae&&this.zoom>=17&&(De(At,nr)||At.push(nr),De(At,yr)||At.push(yr))}const Fr=ut.vertexLength,ni=Pt.length>4&&Dte(nr,yr,Br);let ii=Mte(dr,Rt,kt);if(Ak(this.layoutVertexArray,nr.x,nr.y,dn,rn,0,0,ii),Ak(this.layoutVertexArray,nr.x,nr.y,dn,rn,0,1,ii),this.wallMode){const Xn=de(Dt-1,Pt),bi=ce.joinNormals[Dt-1];kk(this.wallVertexArray,bi,Xn),kk(this.wallVertexArray,bi,Xn)}if(dr+=wr,ii=Mte(dr,ni,!kt),Rt=ni,Ak(this.layoutVertexArray,yr.x,yr.y,dn,rn,0,0,ii),Ak(this.layoutVertexArray,yr.x,yr.y,dn,rn,0,1,ii),this.wallMode){const Xn=de(Dt,Pt),bi=ce.joinNormals[Dt];kk(this.wallVertexArray,bi,Xn),kk(this.wallVertexArray,bi,Xn)}if(ut.vertexLength+=4,this.indexArray.emplaceBack(Fr+0,Fr+1,Fr+2),this.indexArray.emplaceBack(Fr+1,Fr+3,Fr+2),ut.primitiveLength+=2,Ue){const Xn=Ze+(Dt===1?Pt.length-2:Dt-2),bi=Dt===1?Ze:Xn+1;if(this.indexArray.emplaceBack(Fr+1,Xn,Fr+3),this.indexArray.emplaceBack(Xn,bi,Fr+3),ut.primitiveLength+=2,Tt===void 0&&(Tt=Fr),!A$(Br,Pt[Dt],Fe)){const mi=Dt===Pt.length-1?Tt:ut.vertexLength;this.indexArray.emplaceBack(Fr+2,Fr+3,mi),this.indexArray.emplaceBack(Fr+3,mi+1,mi),this.indexArray.emplaceBack(Fr+3,bi,mi+1),ut.primitiveLength+=3}kt=!kt}if(K){const Xn=this.layoutVertexExtArray,bi=q.projectTilePoint(nr.x,nr.y,b),mi=q.projectTilePoint(yr.x,yr.y,b),ws=q.upVector(b,nr.x,nr.y),Fs=q.upVector(b,yr.x,yr.y);Ik(Xn,bi,ws),Ik(Xn,bi,ws),Ik(Xn,mi,Fs),Ik(Xn,mi,Fs)}}X&&(Ze+=Pt.length-1),ae&&Ue&&this.zoom>=17&&(At.length!==0&&De(At,At[0])&&At.pop(),this.groundEffect.addData(At,Fe,B,Ue>0))}this.footprintSegments.push(_t),ht.triangleCount=this.indexArray.length-ht.triangleArrayOffset,this.polygonSegments.push(ht),++se.footprintSegLen,++se.polygonSegLen}if(se.vertexCount=this.layoutVertexArray.length-se.vertexArrayOffset,se.groundVertexCount=this.groundEffect.vertexArray.length-se.groundVertexArrayOffset,se.vertexCount!==0){if(se.centroidXY=J.borders?gL:this.encodeCentroid(J.centroid(),se.min,se.max),u.properties&&Object.hasOwn(u.properties,"building_id")){const Ve=se.buildingId;let Fe=this.buildingGroups.get(Ve);Fe||(Fe={accX:0,accY:0,accCount:0,mergedMin:new jt(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new jt(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Ve,Fe)),Fe.accX+=J.acc.x,Fe.accY+=J.acc.y,Fe.accCount+=J.accCount,Fe.mergedMin.x=Math.min(Fe.mergedMin.x,se.min.x),Fe.mergedMin.y=Math.min(Fe.mergedMin.y,se.min.y),Fe.mergedMax.x=Math.max(Fe.mergedMax.x,se.max.x),Fe.mergedMax.y=Math.max(Fe.mergedMax.y,se.max.y),Fe.partIndices.push(this.centroidData.length)}if(this.centroidData.push(se),J.borders){this.featuresOnBorder.push(J);const Ve=this.featuresOnBorder.length-1;for(let Fe=0;Fethis.featuresOnBorder[u].borders[o][0]-this.featuresOnBorder[m].borders[o][0])}splitToSubtiles(){const o=[];for(let A=0;Aar),B=2*D+(+(I.min.x+I.max.x>ar)^D);for(let U=0;UA.triangleSegmentIdx===I.triangleSegmentIdx?A.subtile-I.subtile:A.triangleSegmentIdx-I.triangleSegmentIdx);let m=0,x=0,b=0;for(const A of o){if(A.triangleSegmentIdx!==m)break;b++}const S=o.length;for(;x!==o.length;){m=o[x].triangleSegmentIdx;let A=0,I=x,D=x;for(let B=I;B0&&this.triangleSubSegments.push({segment:K,min:U,max:q}),I=D;for(let X=I;X[Kr(J[0],se[0],ae[0]),Kr(J[1],se[1],ae[1])],K=[],X=[];for(const J of this.triangleSubSegments){K[0]=J.min.x/ar,K[1]=J.min.y/ar,X[0]=J.max.x/ar,X[1]=J.max.y/ar;const se=q(B,U,K),ae=q(B,U,X);if(new js([se[0],se[1],b],[ae[0],ae[1],S]).intersectsPrecise(m)===0){D&&(x.segments.push(D),D=void 0);continue}const ue=J.segment;D&&D.vertexOffset!==ue.vertexOffset&&(x.segments.push(D),D=void 0),D?(D.vertexLength+=ue.vertexLength,D.primitiveLength+=ue.primitiveLength):D={vertexOffset:ue.vertexOffset,primitiveLength:ue.primitiveLength,vertexLength:ue.vertexLength,primitiveOffset:ue.primitiveOffset,sortKey:void 0,vaos:ue.vaos}}return D&&x.segments.push(D),x}encodeCentroid(o,u,m){const x=Math.min(7,Math.round((m.x-u.x)*this.tileToMeter/10)),b=Math.min(6,Math.round((m.y-u.y)*this.tileToMeter/10));return new jt(cn(o.x,1,8191)<<3|x,cn(o.y,1,8191)<<3|b)}encodeBorderCentroid(o){if(!o.borders)return new jt(0,0);const u=o.borders,m=Number.MAX_VALUE;if(u[0][0]!==m||u[1][0]!==m){const x=u[0][0]!==m?0:1;return new jt(6|(u[0][0]!==m?0:65528),(u[x][0]+u[x][1])/2<<3|6)}{const x=u[2][0]!==m?2:3;return new jt((u[x][0]+u[x][1])/2<<3|6,6|(u[2][0]!==m?0:65528))}}setBuildingCentroid(o,u){const m=this.centroidData.data;if(!this.partsByBuildingId){const A=new Uint32Array(m.length);let I=0;for(let D=0;Dm[D].buildingId-m[B].buildingId)}const x=this.partsByBuildingId;let b=0,S=x.length;for(;b>1;m[x[A]].buildingIdI.max.x||I.min.x>S.max.x||S.min.y>I.max.y||I.min.y>S.max.y||S.footprint.buildingIds.has(I.buildingId)&&(I.flags|=S.clipMask!==hk.None?-1073741824:ry);else for(const I of this.centroidData)if(!(I.flags&ry||I.flags&yL||S.min.x>I.max.x||I.min.x>S.max.x||S.min.y>I.max.y||I.min.y>S.max.y))for(let D=0;Du!=K>u&&o<(this.footprintVertices.int16[2*(B+S.vertexOffset)+0]-U)*(u-q)/(K-q)+U&&(x=!x)}A=I}}return x}getHeightAtTileCoord(o,u){let m=Number.NEGATIVE_INFINITY,x=!0;const b=4*(o+ar)*ar+(u+ar);this.partLookup??(this.partLookup=new Map);const S=this.partLookup.get(b);if(S!==void 0)return S?{height:S.height,hidden:!!(S.flags&ry)}:void 0;const A=this.centroidData.buffer,I=this.centroidData.length;for(let D=0;DA[B+4]||A[B+2]>o||u>A[B+5]||A[B+3]>u)continue;const U=A[B+13];if(U<=m)continue;const q=this.centroidData.get(D);this.footprintContainsPoint(o,u,q)&&(m=U,this.partLookup.set(b,q),x=!!(q.flags&ry))}if(m!==Number.NEGATIVE_INFINITY)return{height:m,hidden:x};this.partLookup.set(b,null)}}function ADe(h,o,u){return h.equals(o)?u:o.sub(h)._unit()}function wL(h,o,u){return h.equals(o)?u:o.sub(h)._perp()._unit()}function Nte(h,o){const u=h.add(o),m=u.mag();return m===0?h:u.div(m)}function T$(h,o){const u=Nte(h,o);return h.x*u.x+h.y*u.y}function kDe(h,o,u,m){let x,b;return h.equals(o)?(b=wL(o,u,new jt(0,0)),x=b):(x=o.sub(h)._perp()._unit(),b=wL(o,u,x)),Rte(h,o,u,T$(x,b),m)}function Rte(h,o,u,m,x){const b=Math.sqrt(1-m*m);return Math.min(h.dist(o)/3,o.dist(u)/3,x*b/m)}function A$(h,o,u){return h.xu[1].x&&o.x>u[1].x||h.yu[1].y&&o.y>u[1].y}function Lte(h,o){return h.xo[1].x||h.yo[1].y}function IDe(h){return h.every(o=>o.x<=0)||h.every(o=>o.x>=ar)||h.every(o=>o.y<=0)||h.every(o=>o.y>=ar)}function Dte(h,o,u){if(h.x<0||h.x>=ar||o.x<0||o.x>=ar||u.x<0||u.x>=ar)return!1;const m=u.sub(o),x=m.perp(),b=h.sub(o);return(m.x*b.x+m.y*b.y)/Math.sqrt((m.x*m.x+m.y*m.y)*(b.x*b.x+b.y*b.y))>-.866&&x.x*b.x+x.y*b.y<0}function Mte(h,o,u){const m=o?2|h:-3&h;return u?1|m:-2&m}function Ote(){const h=Math.PI/32,o=Math.tan(h),u=fm;return u*Math.sqrt(1+2*o*o)-u}function Fte(h,o,u){const m=1<{for(const Pe of ve)X.push({polygon:Pe,bounds:Ue})},se=Math.ceil(Math.log2(B)),ae=Math.ceil(Math.log2(U)),ue=se-ae,ce=[];for(let ve=0;ve0?0:1);for(let ve=0;veUe+1?xe.push({polygons:ut,bounds:_t,depth:Ue+1}):J(ut,_t)}if(ht.length){const _t=[new jt(Pe===0?st:De.x,Pe===1?st:De.y),Ve];ce.length>Ue+1?xe.push({polygons:ht,bounds:_t,depth:Ue+1}):J(ht,_t)}}return X}(h,o,Math.ceil((b-x)/11.25),Math.ceil((S-A)/11.25),1,(I,D,B)=>{if(I===0)return .5*(D+B);{const U=Fa((u.y+D/ar)/m);return(vc(.5*(Fa((u.y+B/ar)/m)+U))*m-u.y)*ar}})}function jDe(h,o,u,m,x,b){const S=Math.pow(2,m.z-x.z);for(let A=0;Ak$?-1:(new Int32Array(this.module.heap32.buffer,u,o.length).set(o),u)}createFloatArray(o){const u=this.memoryStackNextFree;return this.memoryStackNextFree+=o.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>k$?-1:(new Float32Array(this.module.heapF32.buffer,u,o.length).set(o),u)}readStringBuffer(o){let u="";for(;this.module.heapU8[o]!==0;)u+=String.fromCharCode(this.module.heapU8[o]),++o;return u}setStyle(o){const u=o.normalScale;this.module.setStyle(u[0],u[1],u[2],o.tileToMeters)}setAOOptions(o,u){this.module.setAOOptions(o?1:0,u)}setMetricOptions(o,u){this.module.setMetricOptions(o?1:0,u)}setStructuralOptions(o){this.module.setStructuralOptions(o?1:0)}setFacadeOptions(o,u){this.module.setFacadeOptions(o,u?1:0)}setFauxFacadeOptions(o,u,m){this.module.setFauxFacadeOptions(o?1:0,u?1:0,m)}setFacadeClassifierOptions(o){this.module.setFacadeClassifierOptions(o)}generateMesh(o,u){this.memoryStackNextFree=this.memoryStack;for(const A of o){const I=this.createIntArray(A.ringIndices),D=this.createFloatArray(A.coordinates);if(I===-1||D===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(A.id,A.sourceId,A.minHeight,A.height,A.roofType,D,I,A.ringIndices.length-1)}for(const A of u){let I;I=A.entrances?JSON.parse(A.entrances):[];const D=this.createFloatArray(I),B=this.createFloatArray(A.coordinates);if(D===-1||B===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(A.sourceId,A.crossPerc,A.distanceToRoad,D,I.length,B,A.coordinates.length)}if(!this.module.generateMesh()){const A=this.module.getLastError();return this.readStringBuffer(A)}const m=this.module.getMeshCount(),x=new Array(m);for(let A=0;Au||x.y<-o||x.y>u)return!1;return!0}function RDe(h){switch(h){case"flat":return 3;case"hipped":return 1;case"gabled":return 2;case"parapet":return 0;case"mansard":return 4;case"skillion":return 5;case"pyramidal":return 6;default:throw new Error(`Unknown roof shape: ${h}`)}}let Ute,Vte,iS=null,qte=null,Dh=null;class j${constructor(){this.layoutVertexArray=new k,this.layoutAttenuationArray=new Y,this.layoutColorArray=new le,this.indexArray=new Ne,this.indexArrayForConflation=new Ne,this.segmentsBucket=new xn}}class C${constructor(o){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new xn,this.entranceBloom=new j$;const u=66560;this.layoutVertexArray=new ne,this.layoutVertexArray.reserve(u),this.layoutNormalArray=new Mt,this.layoutNormalArray.reserve(u),this.layoutCentroidArray=new z0,this.layoutCentroidArray.reserve(u),this.layoutColorArray=new le,this.layoutColorArray.reserve(u),this.layoutFloodLightDataArray=new fr,this.layoutFloodLightDataArray.reserve(u),this.layoutAOArray=new Cr,this.layoutAOArray.reserve(u),this.indexArray=new Ne,this.indexArray.reserve(66560),this.indexArrayForConflation=new Ne,this.segmentsBucket=new xn,this.entranceBloom=new j$,o&&(this.layoutFacadePaintArray=new le,this.layoutFacadeDataArray=new M,this.layoutFacadeVerticalRangeArray=new le)}reserve(o,u,m){this.layoutVertexArray.reserveForAdditional(o),this.layoutCentroidArray.reserveForAdditional(o),this.layoutFloodLightDataArray.reserveForAdditional(o),this.layoutNormalArray.reserveForAdditional(o),this.layoutAOArray.reserveForAdditional(o),this.layoutColorArray.reserveForAdditional(o),this.indexArray.reserveForAdditional(u),m&&(this.layoutFacadePaintArray.reserveForAdditional(o),this.layoutFacadeDataArray.reserveForAdditional(o),this.layoutFacadeVerticalRangeArray.reserveForAdditional(o))}}class Gte{constructor(o){this.requiresHDRuntime=!0,this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new bt,this.footprintsIndices=new Lt,this.footprintsMin=new jt(1/0,1/0),this.footprintsMax=new jt(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new C$(!1),this.buildingWithFacade=new C$(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=o.zoom,this.canonical=o.canonical,this.layers=o.layers,this.layerIds=this.layers.map(u=>u.fqid),this.index=o.index,this.hasPattern=!1,this.worldview=o.worldview,this.lut=o.lut,this.programConfigurations=new Hi(o.layers,{zoom:o.zoom,lut:o.lut}),this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.projection=o.projection,this.groundEffect=new E$(o),this.groundEffect.groundRadiusArray=new Hu,this.hasAppearances=null}updateFootprints(o,u){const m=new uL([],[],1),x={vertices:new Float64Array(0),indices:new Uint32Array(0),grid:m,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};u.push({footprint:x,id:o})}updateAppearances(o,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(o,u,m,x){if(!Dh)return;const b=Wc(m);this.tileToMeter=b,this.brightness=u.brightness,Dh.setStyle({normalScale:[1,-1,b],tileToMeters:b}),Dh.setAOOptions(!1,.3),Dh.setMetricOptions(!1,16),Dh.setStructuralOptions(!0),Dh.setFacadeClassifierOptions(3);const S=this.layers[0]._featureFilter,A=S.needGeometry,I=new Hs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),D=new Map,B=new Map;let U=0;for(const{feature:ce}of o){if(Bte[ce.type]!=="LineString"){D.set(ce.id,ce.properties.source_id);continue}const de=Ph(ce,A);if(!S.filter(I,de,m))continue;const xe=Ch(ce,de,A,m,x),ve=[];for(const Ve of xe)for(const Fe of Ve)ve.push(Fe.x),ve.push(Fe.y);const Ue={coordinates:ve,crossPerc:ce.properties.cross_perc,distanceToRoad:ce.properties.distance_to_road,entrances:ce.properties.entrances,sourceId:0},Pe=ce.properties.source_id;let De=B.get(Pe);De||(De=[],B.set(Pe,De)),De.push(Ue),++U}this.maxHeight=0;const q=new Array,K=new Set,X=ce=>{ce!=null&&K.add(ce)},J=(ce,de)=>{ce!=null&&q.push({buildingId:ce,footprintIndex:de})},se=64*(o.length-U),ae=se/2;this.buildingWithFacade.reserve(se,ae,!0),this.buildingWithoutFacade.reserve(2*se,2*ae,!1),this.footprintsIndices.reserve(16*(o.length-U)),this.footprintsVertices.reserve(8*(o.length-U));for(const{feature:ce,id:de,index:xe,sourceLayerIndex:ve}of o){if(Bte[ce.type]==="LineString")continue;let Ue=null;if(ce.properties&&Object.hasOwn(ce.properties,"building_id")&&(Ue=Number(ce.properties.building_id),K.has(Ue)))continue;const Pe=Ph(ce,A);if(!S.filter(I,Pe,m))continue;const De=Ch(ce,Pe,A,m,x),Ve=em(De,500);let Fe=!1;for(const En of Ve)if(En.length!==1){Fe=!0;break}if(Fe){X(Ue);continue}if(!NDe(De,163)){X(Ue);continue}const Ze=this.layers[0],st=RDe(Ze.layout.get("building-roof-shape").evaluate(ce,{},m)),ut=Ze.layout.get("building-base").evaluate(ce,{},m),ht=Ze.layout.get("building-height").evaluate(ce,{},m),_t=Ze.layout.get("building-flood-light-ground-radius").evaluate(ce,{},m),Et=Ze.paint.get("building-ambient-occlusion-intensity"),Pt=_t/this.tileToMeter;ce.properties["building-part"]="roof";const Rt=Ze.paint.get("building-color").evaluate(ce,{},this.canonical).toPremultipliedRenderColor(this.lut),Ye=Ze.paint.get("building-emissive-strength").evaluate(ce,{},this.canonical);ce.properties["building-part"]="wall";const At=Ze.paint.get("building-color").evaluate(ce,{},this.canonical).toPremultipliedRenderColor(this.lut),Tt=Ze.paint.get("building-emissive-strength").evaluate(ce,{},this.canonical);ce.properties["building-part"]="window";const $t=Ze.paint.get("building-color").evaluate(ce,{},this.canonical).toPremultipliedRenderColor(this.lut),Gt=Ze.paint.get("building-emissive-strength").evaluate(ce,{},this.canonical);ce.properties["building-part"]="door";const kt=Ze.paint.get("building-color").evaluate(ce,{},this.canonical).toPremultipliedRenderColor(this.lut),Dt=Ze.paint.get("building-emissive-strength").evaluate(ce,{},this.canonical);let dr=Ze.layout.get("building-flood-light-wall-radius").evaluate(ce,{},m);dr=cn(dr,0,2048);const nr=dr/2048*I$,yr=D.get(de),Br=B.get(yr)||[],br=Br.length!==0&&Ze.layout.get("building-facade").evaluate(ce,{},m);Dh.setFacadeOptions(4,!0),Dh.setFauxFacadeOptions(br,!1,1);let dn=0,rn=0,wr=0,Fr=0,ni=0,ii=0,Xn=0,bi=0,mi=0,ws=0,Fs=0;if(br){let En=Math.round(Ze.layout.get("building-facade-floors").evaluate(ce,{},m));if(ut===0){En=Math.max(1,En-(Br.length>0?1:0));let xa=4;if(ht>100){const ja=[10,13,15];xa=ja[ce.id?ce.id%ja.length:0]}else ht<=10&&(xa=3);Dh.setFacadeOptions(xa,!0),ni=(ht<15?1.3:1.61803)*xa/b}else ni=ut/b;ii=ht/b,ni=Math.min(ni,ii),wr=Ze.layout.get("building-facade-unit-width").evaluate(ce,{},m)/b,Fr=(ii-ni)/En,Dh.setFauxFacadeOptions(!0,!0,wr);const yo=Ze.layout.get("building-facade-window").evaluate(ce,{},m);dn=yo[0],rn=yo[1],Xn=Math.floor(65535*Math.min(1,ni/ar)),bi=Math.floor(65535*Math.min(1,ii/ar)),mi=Math.floor(255*dn)<<8|Math.floor(255*rn),ws=Math.floor(65535*Math.min(1,wr/ar)),Fs=Math.floor(65535*Math.min(1,Fr/ar))}const Xa=Array(Ve.length),ns={x:1/0,y:1/0},Gi={x:-1/0,y:-1/0},ka={x:0,y:0};let Kc=0;for(let En=0;En0){const xa=[],ja=Array(yo.length+1);ja[0]=0;for(let eh=0;ehar||ns.y<0||Gi.y>ar)&&this.featuresOnBorder.push({featureId:ce.id,footprintIndex:this.footprints.length});{const En=$x(l_,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+En.length),this.footprintsIndices.uint16.set(En,_m),this.buildingIds.add(Ue??ce.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,vu.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,vu.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,Yc.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,Yc.y);const yo={footprintVertexOffset:sy,footprintVertexLength:this.footprintsVertices.length-sy,footprintIndexOffset:_m,footprintIndexLength:this.footprintsIndices.length-_m,min:vu,max:Yc,hiddenFlags:0,indicesOffset:iy,indicesLength:J0,bloomIndicesOffset:Ss,bloomIndicesLength:Yu,groundEffectVertexOffset:eb,groundEffectVertexLength:vm,hasFauxFacade:br,height:Sf,promoteId:de,feature:Pe,parts:oo,buildingBloom:es},xa=this.footprints.length;ce.id!==void 0&&this.featureFootprintLookup.set(ce.id,xa),J(Ue,xa),this.footprints.push(yo)}this.programConfigurations.populatePaintArrays(_n.layoutVertexArray.length,ce,xe,{},u.availableImages,m,u.brightness),this.groundEffect.addPaintPropertiesData(ce,xe,{},u.availableImages,m,u.brightness),u.featureIndex.insert(ce,De,xe,ve,this.index,o_)}q.forEach(({buildingId:ce,footprintIndex:de})=>{K.has(ce)&&(this.footprints[de].hiddenFlags|=4)});const ue=new Set;this.buildingIds.forEach((ce,de,xe)=>{K.has(ce)||ue.add(ce)}),this.buildingIds=ue,this.groundEffect.prepareBorderSegments()}update(o,u,m,x,b,S,A){this.programConfigurations.updatePaintArrays(o,u,b,m,x,S,A),this.groundEffect.update(o,u,b,m,x,S,A),this.evaluate(this.layers[0],o,S),this.colorBufferUploaded=!1}updateExpressions(o){this.programConfigurations.updateExpressions(o),this.groundEffect.programConfigurations.updateExpressions(o)}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(o){const u=m=>{m.layoutVertexBuffer=o.createVertexBuffer(m.layoutVertexArray,nDe.members),m.layoutNormalBuffer=o.createVertexBuffer(m.layoutNormalArray,sDe.members),m.layoutCentroidBuffer=o.createVertexBuffer(m.layoutCentroidArray,aDe.members),m.layoutFloodLightDataBuffer=o.createVertexBuffer(m.layoutFloodLightDataArray,dDe.members),m.layoutFacadeDataArray&&m.layoutFacadeDataArray.length&&(m.layoutFacadeDataBuffer=o.createVertexBuffer(m.layoutFacadeDataArray,lDe.members)),m.layoutFacadeVerticalRangeArray&&m.layoutFacadeVerticalRangeArray.length&&(m.layoutFacadeVerticalRangeBuffer=o.createVertexBuffer(m.layoutFacadeVerticalRangeArray,cDe.members)),m.entranceBloom.layoutVertexArray.length&&(m.entranceBloom.layoutVertexBuffer=o.createVertexBuffer(m.entranceBloom.layoutVertexArray,iDe.members),m.entranceBloom.layoutAttenuationBuffer=o.createVertexBuffer(m.entranceBloom.layoutAttenuationArray,uDe.members)),this.uploadUpdatedColorBuffer(o),this.uploadUpdatedIndexBuffer(o)};this.uploaded||(u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.groundEffect.upload(o)),this.groundEffect.uploadPaintProperties(o),this.programConfigurations.upload(o),this.uploaded=!0}destroy(){const o=u=>{u.layoutVertexBuffer&&(u.layoutVertexBuffer.destroy(),u.layoutNormalBuffer.destroy(),u.layoutColorBuffer.destroy(),u.segmentsBucket.destroy(),u.indexBuffer&&u.indexBuffer.destroy(),u.entranceBloom.layoutVertexBuffer&&(u.entranceBloom.layoutVertexBuffer.destroy(),u.entranceBloom.layoutColorBuffer.destroy(),u.entranceBloom.layoutAttenuationBuffer.destroy(),u.entranceBloom.indexBuffer.destroy(),u.entranceBloom.segmentsBucket.destroy()))};o(this.buildingWithoutFacade),o(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(o,u,m=!0){let x=!1;const b=m?u:0,S=0|(m?-1:~u);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const A of o){const I=this.footprints[A],D=I.hiddenFlags&S|b;I.hiddenFlags!==D&&(I.hiddenFlags=D,x=!0,this.groundEffect.updateHiddenByLandmarkRange(I.groundEffectVertexOffset,I.groundEffectVertexLength,I.hiddenFlags!==0))}return x&&(this.indexArrayForConflationUploaded=!1),x}uploadUpdatedIndexBuffer(o){if(this.groundEffect.uploadHiddenByLandmark(o),this.indexArrayForConflationUploaded)return;const u=x=>{x.indexArray.length!==0&&(x.indexArrayForConflation.resize(x.indexArray.length),x.indexArrayForConflation.uint16.set(x.indexArray.uint16),x.entranceBloom.indexArrayForConflation.resize(x.entranceBloom.indexArray.length),x.entranceBloom.indexArrayForConflation.uint16.set(x.entranceBloom.indexArray.uint16))};u(this.buildingWithoutFacade),u(this.buildingWithFacade);for(const x of this.footprints){const b=x.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,S=x.indicesOffset+x.indicesLength;if(x.hiddenFlags!==0){for(let I=x.indicesOffset;I{x.indexArray.length!==0&&(x.indexBuffer?x.indexBuffer.updateData(x.indexArrayForConflation):x.indexBuffer=o.createIndexBuffer(x.indexArrayForConflation,!0),x.entranceBloom.indexBuffer?x.entranceBloom.indexBuffer.updateData(x.entranceBloom.indexArrayForConflation):x.entranceBloom.indexBuffer=o.createIndexBuffer(x.entranceBloom.indexArrayForConflation,!0))};m(this.buildingWithoutFacade),m(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(o){const u=m=>{m.layoutColorBuffer?m.layoutColorBuffer.updateData(m.layoutColorArray):m.layoutColorBuffer=o.createVertexBuffer(m.layoutColorArray,Ite.members,!0),m.layoutFacadePaintArray&&(m.layoutFacadePaintBuffer?m.layoutFacadePaintBuffer.updateData(m.layoutFacadePaintArray):m.layoutFacadePaintBuffer=o.createVertexBuffer(m.layoutFacadePaintArray,oDe.members,!0)),m.entranceBloom.layoutColorBuffer?m.entranceBloom.layoutColorBuffer.updateData(m.entranceBloom.layoutColorArray):m.entranceBloom.layoutColorBuffer=o.createVertexBuffer(m.entranceBloom.layoutColorArray,Ite.members,!0)};u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(o,u,m){const x=Object.keys(u),b=x.length!==0&&!m,S=o.paint.get("building-ambient-occlusion-intensity"),A=I=>{if(4&I.hiddenFlags)return;const D=u[I.promoteId],B=I.feature;B.properties["building-part"]="roof";const U=o.paint.get("building-color").evaluate(B,D,this.canonical).toPremultipliedRenderColor(this.lut),q=o.paint.get("building-emissive-strength").evaluate(B,D,this.canonical);B.properties["building-part"]="wall";const K=o.paint.get("building-color").evaluate(B,D,this.canonical).toPremultipliedRenderColor(this.lut),X=o.paint.get("building-emissive-strength").evaluate(B,D,this.canonical);B.properties["building-part"]="window";const J=o.paint.get("building-color").evaluate(B,D,this.canonical).toPremultipliedRenderColor(this.lut),se=o.paint.get("building-emissive-strength").evaluate(B,D,this.canonical);B.properties["building-part"]="door";const ae=o.paint.get("building-color").evaluate(B,D,this.canonical).toPremultipliedRenderColor(this.lut),ue=o.paint.get("building-emissive-strength").evaluate(B,D,this.canonical),ce=I.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const xe of I.parts){let ve,Ue=U;xe.part===1?(Ue=U,ve=q):xe.part===0?(Ue=K,ve=X):xe.part===2?(Ue=J,ve=se):xe.part===3&&(Ue=ae,ve=ue),ve=cn(ve,0,1);for(let Pe=0;PeS.max.x||I.max.xS.max.y||I.max.yA.max.x||A.min.x>o||u>A.max.y||A.min.y>u||A.height<=m||LDe(S,this.footprintsVertices.float32.subarray(2*A.footprintVertexOffset,2*(A.footprintVertexOffset+A.footprintVertexLength)),this.footprintsIndices.uint16.subarray(A.footprintIndexOffset,A.footprintIndexOffset+A.footprintIndexLength))&&(m=A.height,this.footprintLookup[b]=A,x=A.hiddenFlags!==0);if(m!==Number.NEGATIVE_INFINITY)return{height:m,hidden:x};this.footprintLookup[b]=void 0}}function LDe(h,o,u){for(let m=0;m0&&this.rings[0].length>0}}async function SL(){}function sS(h,o,u){const m=o.paint.get(h).value;return m.kind==="constant"?m.value:u.getMaxValue(h)}function EL(h){return Math.sqrt(h[0]*h[0]+h[1]*h[1])}function Wte(h,o,u,m,x){if(!o[0]&&!o[1])return h;const b=jt.convert(o)._mult(x);u==="viewport"&&b._rotate(-m);const S=[];for(let A=0;A{const o=[];return h.paint.get("circle-pitch-alignment")==="map"&&o.push("PITCH_WITH_MAP"),h.paint.get("circle-pitch-scale")==="map"&&o.push("SCALE_WITH_MAP"),o};function Zte(h,o,u,m,x,b,S,A,I){if(b&&h.queryGeometry.isAboveHorizon)return!1;b&&(I*=h.pixelToTileUnitsFactor);const D=h.tileID.canonical,B=u.projection.upVectorScale(D,u.center.lat,u.worldSize).metersToTile;for(const U of o)for(const q of U){const K=q.add(A),X=x&&u.elevation?u.elevation.exaggeration()*x.getElevationAt(K.x,K.y,!0):0,J=u.projection.projectTilePoint(K.x,K.y,D);if(X>0){const ce=u.projection.upVector(D,K.x,K.y);J.x+=ce[0]*B*X,J.y+=ce[1]*B*X,J.z+=ce[2]*B*X}const se=b?K:ODe(J.x,J.y,J.z,m),ae=b?h.tilespaceRays.map(ce=>BDe(ce,X)):h.queryGeometry.screenGeometry,ue=Ki([],[J.x,J.y,J.z,1],m);if(!S&&b?I*=ue[3]/u.cameraToCenterDistance:S&&!b&&(I*=u.cameraToCenterDistance/ue[3]),b){const ce=Fa((q.y/ar+D.y)/(1<Kr(o,u,m==="log"?(Math.pow(10,h)-1)/9:h);function jk(h){const{expression:o,evaluationKey:u,resolution:m=256,clips:x,scale:b="linear",lut:S=null}=h,A=x?x.length:1,I=h.image||new Ec({width:m,height:A}),D={},B=(U,q,K)=>{D[u]=K;const X=o.evaluate(D),J=(X==null?void 0:X.toNonPremultipliedRenderColor(S))??null;J&&(I.data[U+q+0]=Math.floor(255*J.r),I.data[U+q+1]=Math.floor(255*J.g),I.data[U+q+2]=Math.floor(255*J.b),I.data[U+q+3]=Math.floor(255*J.a))};for(let U=0,q=0;Uu.fqid),this.index=o.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.footprints=[],this.worldview=o.worldview,this.hasAppearances=null}updateFootprints(o,u){for(const m of this.footprints)u.push({footprint:m,id:o})}updateAppearances(o,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(o,u,m,x){const b=[],S=new Hs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors});for(const{feature:A,id:I,index:D,sourceLayerIndex:B}of o){const U=this.layers[0]._featureFilter.needGeometry,q=Ph(A,U);if(!this.layers[0]._featureFilter.filter(S,q,m))continue;const K={id:I,properties:A.properties,type:A.type,sourceLayerIndex:B,index:D,geometry:Ch(A,q,U,m,x),patterns:{}};b.push(K)}for(const A of b){const{geometry:I,index:D,sourceLayerIndex:B}=A;this.addFeature(A,I,D,m,{},u.availableImages,u.brightness),u.featureIndex.insert(o[D].feature,I,D,B,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(o){}update(o,u,m,x,b,S,A){}destroy(){}addFeature(o,u,m,x,b,S=[],A){for(const I of em(u,2)){const D=[],B=[],U=[],q=new jt(1/0,1/0),K=new jt(-1/0,-1/0);for(const se of I)if(se.length!==0){se!==I[0]&&U.push(B.length/2);for(let ae=0;ae{st[0]=ut,st[1]=ht,st[2]=_t,st[3]=1},Ze=Ote();K>0&&(K+=Ze),X+=Ze;for(const st of q){const ut=[],ht=[];for(const _t of st){const Et=_t.x+J.x,Pt=_t.y+J.y,Rt=U.projection.projectTilePoint(Et,Pt,xe),Ye=U.projection.upVector(xe,_t.x,_t.y);let At=K,Tt=X;if(ae){const $t=yre(Et,Pt,K,X,ae,ue,ce,de);At+=$t.base,Tt+=$t.top}K!==0?Fe(De,Rt.x+Ye[0]*Pe*At,Rt.y+Ye[1]*Pe*At,Rt.z+Ye[2]*Pe*At):Fe(De,Rt.x,Rt.y,Rt.z),Fe(Ve,Rt.x+Ye[0]*Pe*Tt,Rt.y+Ye[1]*Pe*Tt,Rt.z+Ye[2]*Pe*Tt),Ar(De,De,se),Ar(Ve,Ve,se),ut.push(new U0(De[0],De[1],De[2])),ht.push(new U0(Ve[0],Ve[1],Ve[2]))}ve.push(ut),Ue.push(ht)}return[ve,Ue]}(h,o,u,m,x,b,S,A,I,D,B):S?function(U,q,K,X,J,se,ae,ue,ce){const de=[],xe=[],ve=[0,0,0,1];for(const Ue of U){const Pe=[],De=[];for(const Ve of Ue){const Fe=Ve.x+X.x,Ze=Ve.y+X.y,st=yre(Fe,Ze,q,K,se,ae,ue,ce);ve[0]=Fe,ve[1]=Ze,ve[2]=st.base,ve[3]=1,Ki(ve,ve,J),ve[3]=Math.max(ve[3],1e-5);const ut=new U0(ve[0]/ve[3],ve[1]/ve[3],ve[2]/ve[3]);ve[0]=Fe,ve[1]=Ze,ve[2]=st.top,ve[3]=1,Ki(ve,ve,J),ve[3]=Math.max(ve[3],1e-5);const ht=new U0(ve[0]/ve[3],ve[1]/ve[3],ve[2]/ve[3]);Pe.push(ut),De.push(ht)}de.push(Pe),xe.push(De)}return[de,xe]}(o,u,m,x,b,S,A,I,D):function(U,q,K,X,J){const se=[],ae=[],ue=J[8]*q,ce=J[9]*q,de=J[10]*q,xe=J[11]*q,ve=J[8]*K,Ue=J[9]*K,Pe=J[10]*K,De=J[11]*K;for(const Ve of U){const Fe=[],Ze=[];for(const st of Ve){const ut=st.x+X.x,ht=st.y+X.y,_t=J[0]*ut+J[4]*ht+J[12],Et=J[1]*ut+J[5]*ht+J[13],Pt=J[2]*ut+J[6]*ht+J[14],Rt=J[3]*ut+J[7]*ht+J[15],Ye=_t+ue,At=Et+ce,Tt=Pt+de,$t=Math.max(Rt+xe,1e-5),Gt=_t+ve,kt=Et+Ue,Dt=Pt+Pe,dr=Math.max(Rt+De,1e-5);Fe.push(new U0(Ye/$t,At/$t,Tt/$t)),Ze.push(new U0(Gt/dr,kt/dr,Dt/dr))}se.push(Fe),ae.push(Ze)}return[se,ae]}(o,u,m,x,b)}function yre(h,o,u,m,x,b,S,A){const I=S*x.getElevationAt(h,o,!0,!0),D=b[0]!==0,B=D?b[1]===0?S*(b[0]/7-450):S*function(U,q,K){const X=Math.floor(q[0]/8),J=Math.floor(q[1]/8),se=10*(q[0]-8*X),ae=10*(q[1]-8*J),ue=U.getElevationAt(X,J,!0,!0),ce=U.getMeterToDEM(K),de=Math.floor(.5*(se*ce-1)),xe=Math.floor(.5*(ae*ce-1)),ve=U.tileCoordToPixel(X,J),Ue=2*de+1,Pe=2*xe+1,De=function(ht,_t,Et,Pt,Rt){return[ht.getElevationAtPixel(_t,Et,!0),ht.getElevationAtPixel(_t+Rt,Et,!0),ht.getElevationAtPixel(_t,Et+Rt,!0),ht.getElevationAtPixel(_t+Pt,Et+Rt,!0)]}(U,ve.x-de,ve.y-xe,Ue,Pe),Ve=Math.abs(De[0]-De[1]),Fe=Math.abs(De[2]-De[3]),Ze=Math.abs(De[0]-De[2])+Math.abs(De[1]-De[3]),st=Math.min(.25,.5*ce*(Ve+Fe)/Ue),ut=Math.min(.25,.5*ce*Ze/Pe);return ue+Math.max(st*se,ut*ae)}(x,b,A):I;return{base:I+(u===0?-1:u),top:D?Math.max(B+m,I+u+2):I+m}}function Pk(h,o,u){return o*(ar/(h.tileSize*Math.pow(2,u-h.tileID.overscaledZ)))}function xre(h,o){return 1/Pk(h,1,o.tileZoom)}function _re(h,o,u,m){return h.translatePosMatrix(m||o.tileID.projMatrix,o,u.paint.get("line-translate"),u.paint.get("line-translate-anchor"))}vr(fre,"ClipBucket",{omit:["layers"]});const vre=h=>{const o=[];h.paint.get("line-gradient")&&o.push("RENDER_LINE_GRADIENT"),h.paint.get("line-blend-mode")==="multiply"&&o.push("LINE_BLEND_MULTIPLY"),h.paint.get("line-blend-mode")==="additive"&&o.push("LINE_BLEND_ADDITIVE");const u=h.paint.get("line-trim-offset");u[0]===0&&u[1]===0||o.push("RENDER_LINE_TRIM_OFFSET"),h.paint.get("line-border-width").constantOr(1)!==0&&h.paint.get("line-border-gradient")&&o.push("RENDER_LINE_BORDER_GRADIENT");const m=h.layout.get("line-join").constantOr("miter")==="none",x=!!h.paint.get("line-pattern").constantOr(1);return m&&x&&o.push("LINE_JOIN_NONE"),o};function bre(h){const o=h.paint.get("line-dasharray").value;return o.kind!=="constant"||o.value!=null}let P$;const wre=()=>P$||(P$={layout:dre||(dre=new Ws({"line-cap":new sr(lt.layout_line["line-cap"]),"line-join":new sr(lt.layout_line["line-join"]),"line-miter-limit":new Yt(lt.layout_line["line-miter-limit"]),"line-round-limit":new Yt(lt.layout_line["line-round-limit"]),"line-sort-key":new sr(lt.layout_line["line-sort-key"]),"line-z-offset":new sr(lt.layout_line["line-z-offset"]),"line-elevation-reference":new Yt(lt.layout_line["line-elevation-reference"]),"line-cross-slope":new Yt(lt.layout_line["line-cross-slope"]),visibility:new Yt(lt.layout_line.visibility),"line-width-unit":new Yt(lt.layout_line["line-width-unit"]),"line-elevation-ground-scale":new sr(lt.layout_line["line-elevation-ground-scale"])})),paint:hre||(hre=new Ws({"line-opacity":new sr(lt.paint_line["line-opacity"]),"line-color":new sr(lt.paint_line["line-color"]),"line-translate":new Yt(lt.paint_line["line-translate"]),"line-translate-anchor":new Yt(lt.paint_line["line-translate-anchor"]),"line-width":new sr(lt.paint_line["line-width"]),"line-gap-width":new sr(lt.paint_line["line-gap-width"]),"line-offset":new sr(lt.paint_line["line-offset"]),"line-blur":new sr(lt.paint_line["line-blur"]),"line-dasharray":new sr(lt.paint_line["line-dasharray"]),"line-pattern":new sr(lt.paint_line["line-pattern"]),"line-pattern-cross-fade":new Yt(lt.paint_line["line-pattern-cross-fade"]),"line-gradient":new Zd(lt.paint_line["line-gradient"]),"line-trim-offset":new Yt(lt.paint_line["line-trim-offset"]),"line-trim-fade-range":new Yt(lt.paint_line["line-trim-fade-range"]),"line-trim-color":new Yt(lt.paint_line["line-trim-color"]),"line-emissive-strength":new sr(lt.paint_line["line-emissive-strength"]),"line-border-width":new sr(lt.paint_line["line-border-width"]),"line-border-color":new sr(lt.paint_line["line-border-color"]),"line-border-gradient":new Zd(lt.paint_line["line-border-gradient"]),"line-occlusion-opacity":new Yt(lt.paint_line["line-occlusion-opacity"]),"line-blend-mode":new Yt(lt.paint_line["line-blend-mode"]),"line-blend-additive-clamp":new Yt(lt.paint_line["line-blend-additive-clamp"]),"line-cutout-depth":new Yt(lt.paint_line["line-cutout-depth"]),"line-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"line-border-gradient-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},P$);class $De extends sr{possiblyEvaluate(o,u){return u=new Hs(Math.floor(u.zoom),{now:u.now,fadeDuration:u.fadeDuration,transition:u.transition,worldview:u.worldview}),super.possiblyEvaluate(o,u)}evaluate(o,u,m,x){return u={...u,zoom:Math.floor(u.zoom)},super.evaluate(o,u,m,x)}}let Nk,Sre,Ere,N$;function Tre(h,o){return o>0?o+2*h:h}function Are(h,o){return o.replace(/{([^{}]+)}/g,(u,m)=>m in h?String(h[m]):"")}class kre{constructor(o){this.type=o.property.overrides?o.property.overrides.runtimeType:il,this.defaultValue=o}evaluate(o){if(o.formattedSection){const u=this.defaultValue.property.overrides;if(u&&u.hasOverride(o.formattedSection))return u.getOverride(o.formattedSection)}return o.feature&&o.featureState?this.defaultValue.evaluate(o.feature,o.featureState):this.defaultValue.property.specification.default}eachChild(o){this.defaultValue.isConstant()||o(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}vr(kre,"FormatSectionOverride",{omit:["defaultValue"]});const UDe={};function Ire(h){return h.value.kind!=="constant"&&h.value.isStateDependent}const R$=()=>N$||(N$={layout:Sre||(Sre=new Ws({"symbol-placement":new Yt(lt.layout_symbol["symbol-placement"]),"symbol-spacing":new Yt(lt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Yt(lt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new sr(lt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Yt(lt.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new Yt(lt.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new Yt(lt.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new Yt(lt.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new Yt(lt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Yt(lt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Yt(lt.layout_symbol["icon-rotation-alignment"]),"icon-size":new sr(lt.layout_symbol["icon-size"]),"icon-size-scale-range":new Yt(lt.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new sr(lt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new sr(lt.layout_symbol["icon-text-fit-padding"]),"icon-image":new sr(lt.layout_symbol["icon-image"]),"icon-image-use-theme":new Yt({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new sr(lt.layout_symbol["icon-rotate"]),"icon-padding":new Yt(lt.layout_symbol["icon-padding"]),"icon-keep-upright":new Yt(lt.layout_symbol["icon-keep-upright"]),"icon-offset":new sr(lt.layout_symbol["icon-offset"]),"icon-anchor":new sr(lt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Yt(lt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Yt(lt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Yt(lt.layout_symbol["text-rotation-alignment"]),"text-field":new sr(lt.layout_symbol["text-field"]),"text-font":new sr(lt.layout_symbol["text-font"]),"text-size":new sr(lt.layout_symbol["text-size"]),"text-size-scale-range":new Yt(lt.layout_symbol["text-size-scale-range"]),"text-max-width":new sr(lt.layout_symbol["text-max-width"]),"text-line-height":new sr(lt.layout_symbol["text-line-height"]),"text-letter-spacing":new sr(lt.layout_symbol["text-letter-spacing"]),"text-justify":new sr(lt.layout_symbol["text-justify"]),"text-radial-offset":new sr(lt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Yt(lt.layout_symbol["text-variable-anchor"]),"text-anchor":new sr(lt.layout_symbol["text-anchor"]),"text-max-angle":new Yt(lt.layout_symbol["text-max-angle"]),"text-writing-mode":new Yt(lt.layout_symbol["text-writing-mode"]),"text-rotate":new sr(lt.layout_symbol["text-rotate"]),"text-padding":new Yt(lt.layout_symbol["text-padding"]),"text-keep-upright":new Yt(lt.layout_symbol["text-keep-upright"]),"text-transform":new sr(lt.layout_symbol["text-transform"]),"text-offset":new sr(lt.layout_symbol["text-offset"]),"text-allow-overlap":new Yt(lt.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new Yt(lt.layout_symbol["text-ignore-placement"]),"text-optional":new Yt(lt.layout_symbol["text-optional"]),visibility:new Yt(lt.layout_symbol.visibility)})),paint:Ere||(Ere=new Ws({"icon-opacity":new sr(lt.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new sr(lt.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new sr(lt.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new sr(lt.paint_symbol["text-emissive-strength"]),"icon-color":new sr(lt.paint_symbol["icon-color"]),"icon-halo-color":new sr(lt.paint_symbol["icon-halo-color"]),"icon-halo-width":new sr(lt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new sr(lt.paint_symbol["icon-halo-blur"]),"icon-translate":new Yt(lt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Yt(lt.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new Yt(lt.paint_symbol["icon-image-cross-fade"]),"text-opacity":new sr(lt.paint_symbol["text-opacity"]),"text-occlusion-opacity":new sr(lt.paint_symbol["text-occlusion-opacity"]),"text-color":new sr(lt.paint_symbol["text-color"],{runtimeType:_c,getOverride:h=>h.textColor,hasOverride:h=>!!h.textColor}),"text-halo-color":new sr(lt.paint_symbol["text-halo-color"]),"text-halo-width":new sr(lt.paint_symbol["text-halo-width"]),"text-halo-blur":new sr(lt.paint_symbol["text-halo-blur"]),"text-translate":new Yt(lt.paint_symbol["text-translate"]),"text-translate-anchor":new Yt(lt.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new Yt(lt.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new Yt(lt.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new Yt(lt.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new Yt(lt.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new sr(lt.paint_symbol["symbol-z-offset"]),"placement-priority":new sr(lt.paint_symbol["placement-priority"]),"placement-group":new sr(lt.paint_symbol["placement-group"]),"icon-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},N$);class TL extends bc{constructor(o,u,m,x){super(o,R$(),u,m,x,o.layout?o.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=G([]),this.hasOcclusionOpacityProperties=o.paint!==void 0&&("icon-occlusion-opacity"in o.paint||"text-occlusion-opacity"in o.paint),this._overridesTextField=null}_handleSpecialPaintPropertyUpdate(o){o!=="icon-occlusion-opacity"&&o!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}_finalizeEvaluated(o,u){this.appearances&&this.appearances.forEach(x=>{x.recalculate(o,u,this.iconImageUseTheme)}),this.appearances.length!==0&&delete this.layout._values["text-variable-anchor"],this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));const m=this.layout.get("text-writing-mode");if(m){const x=[];for(const b of m)x.includes(b)||x.push(b);this.layout._values["text-writing-mode"]=x}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(o,u,m,x){return this._saturation===o&&this._contrast===u&&this._brightnessMin===m&&this._brightnessMax===x||(this._colorAdjustmentMatrix=function(b,S,A,I){b=a0(b),S=Hd(S);const D=O(),B=b/3,U=1-2*B,q=Float64Array.of(U,B,B,0,B,U,B,0,B,B,U,0,0,0,0,1),K=.5-.5*S,X=Float64Array.of(S,0,0,0,0,S,0,0,0,0,S,0,K,K,K,1),J=I-A;return Q(D,Float64Array.of(J,0,0,0,0,J,0,0,0,0,J,0,A,A,A,1),X),Q(D,D,q),D}(o,u,m,x),this._saturation=o,this._contrast=u,this._brightnessMin=m,this._brightnessMax=x),this._colorAdjustmentMatrix}getValueAndResolveTokens(o,u,m,x){const b=this.layout.get(o).evaluate(u,{},m,x),S=this.getLayoutPropertyValue(o);return S.isDataDriven()||m1(S.value)||!b?b:Are(u.properties,b)}getAppearanceValueAndResolveTokens(o,u,m,x,b){const S=o.getLayoutProperty(u);if(!S)return;const A=S.evaluate(m,{},x,b),I=o.getUnevaluatedLayoutProperties()._values[u].value;return I.isDataDriven()||m1(I.value)||!A||typeof A!="string"?A:Are(m.properties,A)}createBucket(o){return new _k(o)}placeSymbols(o,u,m,x,b,S){const{globalPlacement:A,transform:I,buildingIndex:D,fogState:B,groupOrders:U,replacementSource:q,mercatorCenter:K,fadeDuration:X}=o,J=this.runtimeLayerUID,se=Ire(this.paint.get("placement-group"))||Ire(this.paint.get("placement-priority"))?x._state.getState(this.sourceLayer||"_geojsonTileLayer"):UDe;for(const ae of u){const ue=ae.getBucket(this);if(!ue||this.fqid!==ue.layerIds[0])continue;ue.elevationType==="offset"&&D?D.updateZOffset(ue,ae.tileID):ue.elevationType==="road"&&ue.hdExt&&ue.hdExt.updateRoadElevation(ue,ae.tileID.canonical),ue.updateZOffset(),A.startSymbolSourceProcessing(ue);const ce=ue.getProjection(),de=ce.name===I.projection.name?I:I.clone();de!==I&&de.setProjection(ue.projection);const xe=nee(ae.tileID,ce,de,de.projection.name),ve=ce.createInversionMatrix(de,ae.tileID.canonical),Ue=ae.tileSize/ar,Pe=S.get(ae.tileID.key)||[];ue.addToPlacement(A,J,xe,ve,K,de,Ue,ae,B,U,m,se,b?q:null,X,Pe),A.finishSourceProcessing()}}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){const o=this.layout.get("text-field");this._overridesTextField!==o&&(this._overridesTextField=o,this._overriddenProperties=R$().paint.overridableProperties.filter(u=>TL.hasPaintOverride(this.layout,u)));for(const u of this._overriddenProperties){const m=this.paint.get(u),x=new kre(m),b=new _2(x,m.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme")),S=m.value.kind==="constant"||m.value.isLightConstant;let A=null;A=m.value.kind==="constant"||m.value.kind==="source"?new p1("source",b,S):new wp("composite",b,m.value.zoomStops,m.value.interpolationType,S),this.paint._values[u]=new dm(m.property,A,m.parameters)}}isPlacementAffectedByPaintChanges(o){const u=o;return this.paint.get("symbol-z-offset").constantOr(void 0)!==u.get("symbol-z-offset").constantOr(void 0)}_handleOverridablePaintPropertyUpdate(o,u,m){return!(!this.layout||u.isDataDriven()||m.isDataDriven())&&TL.hasPaintOverride(this.layout,o)}static hasPaintOverride(o,u){const m=o.get("text-field"),x=R$().paint.properties[u];let b=!1;const S=A=>{for(const I of A)if(x.overrides&&x.overrides.hasOverride(I))return void(b=!0)};if(m.value.kind==="constant"&&m.value.value instanceof sl)S(m.value.value.sections);else if(m.value.kind==="source"){const A=D=>{b||(D instanceof qc&&zo(D.value)===pp?S(D.value.sections):D instanceof kn?S(D.sections):D.eachChild(A))},I=m.value;I._styleExpression&&A(I._styleExpression.expression)}return b}getProgramIds(){return["symbol"]}getDefaultProgramParams(o,u,m){return{config:new ji(this,{zoom:u,lut:m}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}mayUse(o){return o==="HD"&&zx(this,"symbol-elevation-reference",u=>u==="hd-road-markup")}prepare(){return this.mayUse("HD")?SL():Promise.resolve()}}let jre,Cre,Pre,Nre;const L$=1024,VDe=(Math.pow(L$,2)-1)/268170240;class Rre extends bc{constructor(o,u,m,x){super(o,{layout:Pre||(Pre=new Ws({visibility:new Yt(lt.layout_raster.visibility)})),paint:Nre||(Nre=new Ws({"raster-opacity":new Yt(lt.paint_raster["raster-opacity"]),"raster-color":new Zd(lt.paint_raster["raster-color"]),"raster-color-mix":new Yt(lt.paint_raster["raster-color-mix"]),"raster-color-range":new Yt(lt.paint_raster["raster-color-range"]),"raster-color-scale":new Yt(lt.paint_raster["raster-color-scale"]),"raster-hue-rotate":new Yt(lt.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Yt(lt.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Yt(lt.paint_raster["raster-brightness-max"]),"raster-saturation":new Yt(lt.paint_raster["raster-saturation"]),"raster-contrast":new Yt(lt.paint_raster["raster-contrast"]),"raster-resampling":new Yt(lt.paint_raster["raster-resampling"]),"raster-fade-duration":new Yt(lt.paint_raster["raster-fade-duration"]),"raster-emissive-strength":new Yt(lt.paint_raster["raster-emissive-strength"]),"raster-array-band":new Yt(lt.paint_raster["raster-array-band"]),"raster-elevation":new Yt(lt.paint_raster["raster-elevation"]),"raster-elevation-reference":new Yt(lt.paint_raster["raster-elevation-reference"]),"raster-mask":new Yt(lt.paint_raster["raster-mask"]),"raster-mask-import":new Yt(lt.paint_raster["raster-mask-import"]),"raster-mask-mode":new Yt(lt.paint_raster["raster-mask-mode"]),"raster-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},u,m,x),this.updateColorRamp(),this._curRampRange=[NaN,NaN]}getProgramIds(){return["raster"]}hasColorMap(){return!!this.getPaintPropertyValue("raster-color").value}mayUse(o){return o==="RasterArray"&&!!this.paint.get("raster-mask")}tileCoverLift(){return this.paint.get("raster-elevation")}isDraped(o){const u=o?o._source:null;return(!u||u.type!=="image"&&u.type!=="video"&&u.type!=="canvas"||!u.onNorthPole&&!u.onSouthPole)&&this.paint.get("raster-elevation")===0}_handleSpecialPaintPropertyUpdate(o){o!=="raster-color"&&o!=="raster-color-range"&&o!=="raster-color-scale"||(this._curRampRange=[NaN,NaN],this.updateColorRamp())}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}updateColorRamp(o){if(!this.hasColorMap()||!this._curRampRange)return;const u=this.getPaintPropertyValue("raster-color").expression,[m,x]=o||this.getPaintPropertyValue("raster-color-range").expression.evaluate({zoom:0})||[NaN,NaN];if(isNaN(m)&&isNaN(x)||m===this._curRampRange[0]&&x===this._curRampRange[1])return;const b=this.getPaintPropertyValue("raster-color-scale").expression.evaluate({zoom:0});this.colorRamp=jk({expression:u,evaluationKey:"rasterValue",image:this.colorRamp,clips:[{start:m,end:x}],resolution:L$,scale:b}),this.colorRampTexture=null,this._curRampRange=[m,x]}is3D(o){return this.paint.get("raster-elevation")>0}}let Lre,Dre,Mre,Ore,Fre,Bre,zre,$re;class Ure extends bc{constructor(o,u,m,x){super(o,{layout:Lre||(Lre=new Ws({visibility:new Yt(lt["layout_raster-particle"].visibility)})),paint:Dre||(Dre=new Ws({"raster-particle-array-band":new Yt(lt["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new Yt(lt["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new Zd(lt["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new Yt(lt["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new Yt(lt["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new Yt(lt["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new Yt(lt["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new Yt(lt["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},u,m,x),this._updateColorRamp(),this.lastInvalidatedAt=hu.now()}mayUse(o){return o==="HD"}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null),this.tileFramebuffer&&(this.tileFramebuffer.destroy(),this.tileFramebuffer=null),this.particleFramebuffer&&(this.particleFramebuffer.destroy(),this.particleFramebuffer=null)}onRemove(o){this.colorRampTexture&&this.colorRampTexture.destroy(),this.tileFramebuffer&&this.tileFramebuffer.destroy(),this.particleFramebuffer&&this.particleFramebuffer.destroy()}hasColorMap(){return!!this.getPaintPropertyValue("raster-particle-color").value}getProgramIds(){return["rasterParticle"]}hasOffscreenPass(){return this.visibility!=="none"}isDraped(o){return!1}_handleSpecialPaintPropertyUpdate(o){o!=="raster-particle-color"&&o!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),o==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const o=this.getPaintPropertyValue("raster-particle-color").expression,u=this.getPaintPropertyValue("raster-particle-max-speed").expression.evaluate({zoom:0});this.colorRamp=jk({expression:o,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:u}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=hu.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class qDe extends bc{constructor(o,u){super(o,{},u,null),this.implementation=o,o.slot&&(this.slot=o.slot)}is3D(o){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(o){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(o){this.implementation.onAdd&&this.implementation.onAdd(o,o.painter.context.gl)}onRemove(o){this.implementation.onRemove&&this.implementation.onRemove(o,o.painter.context.gl)}}function D$(h,o,u){const m=[0,0,1],x=ci([]);return Da(x,x,u?-Bn(h)+Math.PI:Bn(h)),_r(x,x,-Bn(o)),mn(m,m,x),zt(m,m)}const Cp=[];class Vre{constructor(o,u){this.feature=o,this.instancedDataOffset=u,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class qre{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new or,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(o){const u=16*o,m=this.instancedDataArray.float32;let x=Math.floor(m[u+2]);const b=1.05*(m[u+2]-x);return x/=100,[m[u]%1*1.05,m[u+1]%1*1.05,b,x]}tileCoordinatesForInstance(o){const u=16*o,m=this.instancedDataArray.float32;let x=m[u+0];return x=x>ar?x-ar:x,new jt(Math.trunc(x),Math.trunc(m[u+1]))}translationForInstance(o){const u=16*o,m=this.instancedDataArray.float32;return[m[u+4],m[u+5],m[u+6]]}rotationScaleForInstance(o){const u=16*o,m=this.instancedDataArray.float32;return[m[u+7],m[u+8],m[u+9],m[u+10],m[u+11],m[u+12],m[u+13],m[u+14],m[u+15]]}transformForInstance(o){const u=16*o,m=this.instancedDataArray.float32;return[m[u+7],m[u+8],m[u+9],m[u+4],m[u+10],m[u+11],m[u+12],m[u+5],m[u+13],m[u+14],m[u+15],m[u+6],0,0,0,1]}}class M${constructor(o){this.requiresStandardRuntime=!0,this.zoom=o.zoom,this.canonical=o.canonical,this.overscaledZ=this.canonical.z+Math.log2(o.overscaling),this.layers=o.layers,this.layerIds=this.layers.map(u=>u.fqid),this.projection=o.projection,this.index=o.index,this.worldview=o.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.hasPattern=!1,this.instancesPerModel={},this.validForExaggeration=0,this.maxVerticalOffset=0,this.maxScale=0,this.maxHeight=0,this.lookupDim=this.zoom>this.canonical.z+1?0:this.zoom>this.canonical.z?256:this.zoom>15?75:100,this.instanceCount=0,this.terrainElevationMin=0,this.terrainElevationMax=0,this.validForDEMTile={id:null,timestamp:0},this.modelUris=[],this.modelsRequested=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.styleDefinedModelURLs=o.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(o,u){}updateAppearances(o,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(o,u,m,x){this.tileToMeter=Wc(m);const b=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const S=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?u.elevationFeatures:void 0,A=new Hs(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors});for(const{feature:I,id:D,index:B,sourceLayerIndex:U}of o){const q=D??(I.properties&&Object.hasOwn(I.properties,"id")?I.properties.id:void 0),K=Ph(I,b);if(!this.layers[0]._featureFilter.filter(A,K,m))continue;const X={id:q,sourceLayerIndex:U,index:B,geometry:Ch(I,K,b,m,x),properties:I.properties,type:I.type,patterns:{}},J=this.addFeature(X,X.geometry,K,S,m);J&&u.featureIndex.insert(I,X.geometry,B,U,this.index,this.instancesPerModel[J].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const o=this.layers[0].modelManager,u=this.layers[0].scope;let m=0;for(const x of this.modelUris){const b=o.getModel(x,u);if(!b)continue;const S=this.instancesPerModel[x];if(S){const A=.5*ir(b.aabb.max,b.aabb.min)*S.maxScale+S.maxXYTranslationDistance,I=Math.min(ar,Math.max(A/this.tileToMeter,256));m=Math.max(I,m)}}return m}update(o,u,m,x){for(const b in this.instancesPerModel){const S=this.instancesPerModel[b];for(const A in o)if(Object.hasOwn(S.idToFeaturesIndex,A)){const I=S.features[S.idToFeaturesIndex[A]];I.featureStates=o[A],this.evaluate(I,o[A],S,!0),this.uploaded=!1}}this.maxHeight=0}updateZoomBasedPaintProperties(){const o=this.layers[0].paint;if(!this.hasZoomDependentProperties||o===this.evaluatedPaint)return!1;this.evaluatedPaint=o;const u=this.canonical,m=o.get("model-rotation"),x=o.get("model-scale"),b=o.get("model-translation");let S=!1;for(const A in this.instancesPerModel){const I=this.instancesPerModel[A];for(const D of I.features){const{feature:B,featureStates:U}=D,q=m.evaluate(B,U,u),K=x.evaluate(B,U,u),X=b.evaluate(B,U,u);Lr(D.rotation,q)&&Lr(D.scale,K)&&Lr(D.translation,X)||(this.evaluate(D,U,I,!0),S=!0)}}return S}updateReplacement(o,u,m,x){if(u.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=u.updateTime;const b=u.getReplacementRegionsForTile(o.toUnwrapped(),!0);if(BR(this.activeReplacements,b))return!1;this.activeReplacements=b;let S=!1;for(const A in this.instancesPerModel){const I=this.instancesPerModel[A],D=I.instancedDataArray;for(const B of I.features){const U=B.instancedDataOffset,q=B.instancedDataCount;for(let K=0;Kar;J=se?J-ar:J;const ae=Math.floor(J),ue=Math.floor(D.float32[X+1]);let ce=!1;for(const de of this.activeReplacements)if(!Fz(de,m,hk.Model,x)&&!(de.min.x>ae||ae>de.max.x||de.min.y>ue||ue>de.max.y)&&(ce=VR($z(ae,ue,o.canonical,de.footprintTileId.canonical),de.footprint),ce))break;D.float32[X]=ce?J+ar:J,S=S||ce!==se}}}return S}isEmpty(){for(const o in this.instancesPerModel)if(this.instancesPerModel[o].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(o){if(!this.uploaded)for(const u in this.instancesPerModel){const m=this.instancesPerModel[u];m.instancedDataArray.length<0||m.instancedDataArray.length===0||(m.instancedDataBuffer?m.instancedDataBuffer.updateData(m.instancedDataArray):m.instancedDataBuffer=o.createVertexBuffer(m.instancedDataArray,GLe.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(o){for(const m in this.instancesPerModel){const x=this.instancesPerModel[m];x.instancedDataArray.length!==0&&x.instancedDataBuffer&&x.instancedDataBuffer.destroy()}const u=this.layers[0].modelManager;if(o&&u&&this.modelUris&&this.modelsRequested)for(const m of this.modelUris)u.removeModel(m,"",!0)}addFeature(o,u,m,x,b){const S=this.layers[0],A=S.layout.get("model-id"),I=S.layout.get("model-allow-density-reduction"),D=A.evaluate(m,{},this.canonical);if(!D)return Xi(`modelId is not evaluated for layer ${S.id} and it is not going to get rendered.`),D;!D.includes("://")&&!this.styleDefinedModelURLs[D]||this.modelUris.includes(D)||this.modelUris.push(D),this.instancesPerModel[D]||(this.instancesPerModel[D]=new qre);const B=this.instancesPerModel[D],U=B.instancedDataArray,q=new Vre(m,U.length);let K;if(x){const X=vk(o,x,void 0,b);K=X?X.feature:void 0}for(const X of u)for(const J of X){if(J.x<0||J.x>=ar||J.y<0||J.y>=ar)continue;if(this.lookupDim!==0&&I){const ae=(this.lookupDim-1)/ar,ue=this.lookupDim*(J.y*ae|0)+J.x*ae|0;if(this.lookup){if(this.lookup[ue]!==0)continue;this.lookup[ue]=1}}this.instanceCount++;const se=U.length;if(U.resize(se+1),x){B.instancesRoadElevation||(B.instancesRoadElevation=[]);const ae=K?K.pointElevation(new jt(J.x,J.y)):0;B.instancesRoadElevation.push(ae)}B.instancesEvaluatedElevation.push(0),U.float32[16*se]=J.x,U.float32[16*se+1]=J.y}return q.instancedDataCount=B.instancedDataArray.length-q.instancedDataOffset,q.instancedDataCount>0&&(o.id&&(B.idToFeaturesIndex[o.id]=B.features.length),B.features.push(q),this.evaluate(q,{},B,!1)),D}getModelUris(){return this.modelUris}evaluate(o,u,m,x){const b=this.layers[0].paint,S=o.feature,A=this.canonical,I=o.rotation=b.get("model-rotation").evaluate(S,u,A),D=o.scale=b.get("model-scale").evaluate(S,u,A),B=o.translation=b.get("model-translation").evaluate(S,u,A),{r:U,g:q,b:K}=b.get("model-color").evaluate(S,u,A),X=b.get("model-color-mix-intensity").evaluate(S,u,A);this.maxVerticalOffset0?Math.sqrt(J):0;m.maxScale=Math.max(Math.max(m.maxScale,D[0]),Math.max(D[1],D[2])),m.maxXYTranslationDistance=Math.max(m.maxXYTranslationDistance,se),this.maxScale=Math.max(Math.max(this.maxScale,D[0]),Math.max(D[1],D[2])),yte(Cp,I,D);const ae=Math.round(100*X)+K/1.05,ue=m.instancedDataArray.float32;for(let ce=0;ce10?this.tileToMeter:Wc(A,Ue)),ue[xe+4]=B[0],ue[xe+5]=B[1],ue[xe+6]=B[2]+(m.instancesRoadElevation?m.instancesRoadElevation[de]:0)+ve,ue[xe+7]=Cp[0],ue[xe+8]=Cp[1],ue[xe+9]=Cp[2],ue[xe+10]=Cp[4],ue[xe+11]=Cp[5],ue[xe+12]=Cp[6],ue[xe+13]=Cp[8],ue[xe+14]=Cp[9],ue[xe+15]=Cp[10],m.instancesEvaluatedElevation[de]=B[2]}}}vr(M$,"ModelBucket",{omit:["layers"]}),vr(qre,"PerModelAttributes"),vr(Vre,"ModelFeature");const Gre=new WeakMap;class GDe{constructor(o,u){const m=o.gl;if(this.context=o,this.buffer=m.createBuffer(),!this.buffer)throw new Error("Failed to create model part style UBO buffer");m.bindBuffer(m.UNIFORM_BUFFER,this.buffer),m.bufferData(m.UNIFORM_BUFFER,u,m.DYNAMIC_DRAW),m.bindBuffer(m.UNIFORM_BUFFER,null)}update(o){const u=this.context.gl;u.bindBuffer(u.UNIFORM_BUFFER,this.buffer),u.bufferSubData(u.UNIFORM_BUFFER,0,o),u.bindBuffer(u.UNIFORM_BUFFER,null)}bind(o,u){let m=Gre.get(u);if(m===void 0){const b=o.gl,S=b.getUniformBlockIndex(u,"ModelPartStyleUniform");m=S!==b.INVALID_INDEX,m&&b.uniformBlockBinding(u,S,0),Gre.set(u,m)}if(!m)return;const x=o.gl;x.bindBufferBase(x.UNIFORM_BUFFER,0,this.buffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),this.buffer=null)}}let aS,r_;const AL=[0,0,0],kL=[0,0,0];function Hre(h){let o=0;if(h.meshes)for(const u of h.meshes)o=Math.max(o,u.aabb.max[2]);if(h.children)for(const u of h.children)o=Math.max(o,Hre(u));return o}function Wre(h,o,u){if(h.meshes)for(const m of h.meshes){if(m.aabb.min[0]===1/0)continue;const x=js.applyTransform(m.aabb,h.globalMatrix);u.insert(o,x.min[0],x.min[1],x.max[0],x.max[1])}if(h.children)for(const m of h.children)Wre(m,o,u)}class Kre{constructor(o){this.node=o,this.hiddenByReplacement=!1,this.evaluatedTranslation=[0,0,0],this.evaluatedScale=[1,1,1],this.emissiveStrength=0,this.partStyle=new Float32Array(112),this.partStyleUBO=null,this.needsPartStyleUBO=!1,this.cameraCollisionOpacity=1,this.targetLod=-1,this.feature={type:"Point",id:o.id,geometry:[],properties:{height:Hre(o)}},this.aabb=this._getLocalBounds(),this.state=null}_getLocalBounds(){if(!this.node.meshes)return new js([1/0,1/0,1/0],[-1/0,-1/0,-1/0]);if(!this.aabb){let o=0;const u=new js([1/0,1/0,1/0],[-1/0,-1/0,-1/0]);for(const m of this.node.meshes)this.node.lightMeshIndex!==o&&(m.transformedAabb=js.applyTransformFast(m.aabb,this.node.globalMatrix),u.encapsulate(m.transformedAabb)),o++;this.aabb=u}return this.aabb}}class Yre{constructor(o,u,m,x,b,S,A,I){this.requiresStandardRuntime=!0,this.isTiled3dModelBucket=!0,this.id=m,this.layers=o,this.layerIds=this.layers.map(D=>D.fqid),this.stateDependentLayerIds=this.layers.filter(D=>D.isStateDependent()).map(D=>D.id),this.modelTraits|=1,this.uploaded=!1,this.hasPattern=!1,x&&(this.modelTraits|=4),b&&(this.modelTraits|=8),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=S,this.worldview=I,this.dirty=!0,this.needsPartStyleUBOs=!1,this.filter=null,this.nodesInfo=[];for(const D of u)this.nodesInfo.push(new Kre(D)),Wre(D,A.featureIndexArray.length,A.grid),A.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,A.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(o,u){for(const m of this.getNodesInfo()){const x=m.node;x.footprint&&u.push({footprint:x.footprint,id:o})}}updateAppearances(o,u,m,x){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(o){const u=Object.keys(o).length!==0;if(u&&!this.stateDependentLayers.length)return;const m=u?this.stateDependentLayers:this.layers;if(!Ha(o,this.states))for(const x of m)this.evaluate(x,o,u);this.states=structuredClone(o)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsPartStyleUBOs}upload(o){if(this.needsPartStyleUBOs&&(this.createPartStyleUBOs(o),this.needsPartStyleUBOs=!1),!this.uploaded){const u=this.getNodesInfo();for(const m of u)m$(m.node,o,!0);for(const m of u)mL(m.node);this.uploaded=!0}}createPartStyleUBOs(o){for(const u of this.getNodesInfo())u.needsPartStyleUBO&&(u.partStyleUBO=new GDe(o,u.partStyle),u.needsPartStyleUBO=!1)}needsReEvaluation(o,u,m){const x=o.transform.projectionOptions,b=o.style.getBrightness(),S=this.brightness!==b;if(!this.uploaded||this.dirty||x.name!==this.projection.name||Rk(m.paint.get("model-color").value,S)||Rk(m.paint.get("model-color-mix-intensity").value,S)||Rk(m.paint.get("model-roughness").value,S)||Rk(m.paint.get("model-emissive-strength").value,S)||Rk(m.paint.get("model-height-based-emissive-strength-multiplier").value,S)){this.projection=x,this.brightness=b;const A=this.getNodesInfo();for(const I of A)I.state=null;return!0}return!1}evaluateTransform(o,u){if(o.transform.zoom===this.zoom)return;this.zoom=o.transform.zoom;const m=this.getNodesInfo(),x=this.id.canonical;for(const b of m){const S=b.feature;b.evaluatedTranslation=u.paint.get("model-translation").evaluate(S,{},x),b.evaluatedScale=u.paint.get("model-scale").evaluate(S,{},x)}}evaluate(o,u,m=!1){const x=this.getNodesInfo(),b=this.id.canonical,S=m&&u?new Set(Object.keys(u)):null;for(const A of x){if(!A.node.meshes)continue;const I=A.feature;if(S&&!S.has(String(I.id)))continue;const D=u&&u[I.id];if(Ha(D,A.state))continue;A.state=structuredClone(D);const B=A.node.meshes[0].hasFeatureData;if(A.hasTranslucentParts=!1,B){for(let U=0;U=ve)continue;const Et=aS[_t],Pt=Math.abs(Et);Pt>Fe&&(Ve=Et,Fe=Pt,Ze=ht,st=ut)}if(Fe>.1){const ut=1-(ve+.5*Math.abs(Ze*st))/X;let ht=u._dem.get(Pe,Ue)+Ve*ut;const _t=u._dem.get(Pe+Ze,Ue+st),Et=u._dem.get(Pe-Ze,Ue-st,!0);(ht-_t)*(ht-Et)>0&&(ht=(_t+Et)/2),aS[De]=u._dem.set(Pe,Ue,ht),r_[De]=ve}}}}}A&&(u._demTile.needsDEMTextureUpload=!0,u._dem._timestamp=hu.now())}setFilter(o){this.filter=o?L2(o):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(o=>this.filter.filter(new Hs(this.id.overscaledZ,{worldview:this.worldview}),o.feature,this.id.canonical)):this.nodesInfo}destroy(){const o=this.getNodesInfo();for(const u of o)mL(u.node),p$(u.node),u.partStyleUBO&&(u.partStyleUBO.destroy(),u.partStyleUBO=null)}isEmpty(){return!this.nodesInfo.length}updateReplacement(o,u){if(u.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=u.updateTime;const m=u.getReplacementRegionsForTile(o.toUnwrapped());for(const x of this.getNodesInfo()){const b=x.node.footprint;x.hiddenByReplacement=!!b&&!m.some(S=>S.footprint===b)}}getHeightAtTileCoord(o,u){const m=[0,0,0],x=G([]);for(const b of this.getNodesInfo()){const S=b.node.meshes[0],A=S.transformedAabb;if(oA.max[0]||u>A.max[1])continue;if(b.node.hidden===!0)return{height:1/0,maxHeight:b.feature.properties.height,hidden:!1,verticalScale:b.evaluatedScale[2]};if(b.node.meshBVH){const U=4*(o+ar)*ar+(u+ar);b.bvhHeightLookup??(b.bvhHeightLookup=new Map);let q=b.bvhHeightLookup.get(U);if(q===void 0&&(Z(x,b.node.globalMatrix),Ar(m,tt(m,o,u,0),x),AL[0]=m[0]-1,AL[1]=m[1]-1,AL[2]=-1e3,kL[0]=m[0]+1,kL[1]=m[1]+1,kL[2]=1e3,q=b.node.meshBVH.findHighestPoint(AL,kL),b.bvhHeightLookup.set(U,q)),q!==null)return{height:q,maxHeight:b.feature.properties.height,hidden:b.hiddenByReplacement,verticalScale:b.evaluatedScale[2]};continue}if(!S.heightmap)continue;Z(x,b.node.globalMatrix),Ar(m,tt(m,o,u,0),x);const I=(m[0]-S.aabb.min[0])/(S.aabb.max[0]-S.aabb.min[0])*Y0|0,D=Math.min(63,(m[1]-S.aabb.min[1])/(S.aabb.max[1]-S.aabb.min[1])*Y0|0)*Y0+Math.min(63,I),B=S.heightmap[D];if(B<0&&b.node.footprint){const U=[];if(b.node.footprint.grid.query(new jt(o,u),new jt(o,u),U),U.length>0)return{height:void 0,maxHeight:b.feature.properties.height,hidden:b.hiddenByReplacement,verticalScale:b.evaluatedScale[2]};continue}return b.hiddenByReplacement?void 0:{height:B,maxHeight:b.feature.properties.height,hidden:!1,verticalScale:b.evaluatedScale[2]}}}}function Rk(h,o){return h instanceof p1&&!h.isLightConstant&&o}function HDe(h,o,u,m,x,b,S,A){const I=cn(A[0],0,1),D=cn(A[1],0,1);h[o]=u.r,h[o+1]=u.g,h[o+2]=u.b,h[o+3]=cn(m,0,1),h[o+4]=x,h[o+5]=b,h[o+6]=cn(S,0,2),h[o+7]=u.a,I!==D?(h[o+8]=I,h[o+9]=D,h[o+10]=cn(A[2],0,1),h[o+11]=cn(A[3],0,1)-h[o+10],h[o+12]=Math.pow(10,cn(A[4],-1,1))):(h[o+8]=0,h[o+9]=1,h[o+10]=1,h[o+11]=0,h[o+12]=1),function(B,U){B[U+4]=16*Math.floor(15*B[U+4])/255,B[U+5]=16*Math.floor(15*B[U+5])/255,B[U+6]=Math.min(Math.floor(127.5*B[U+6]+.5),255)/255*2,B[U+7]=Math.floor(255*B[U+7])/255;const q=Math.floor(255*B[U+10])/256,K=Math.floor(255*(B[U+10]+B[U+11]))/256;B[U+10]=q,B[U+11]=K-q}(h,o)}vr(Yre,"Tiled3dModelBucket",{omit:["layers"]}),vr(Kre,"Tiled3dModelFeature",{omit:["partStyleUBO"]});class Zre{constructor(o){this._stringToNumber={},this._numberToString=[];for(let u=0;u{const u=h.style.light.properties,m=u.get("position"),x=[-m.x,-m.y,m.z];u.get("anchor")==="viewport"&&Tn(x,x,L(KDe,-h.transform.angle));const b=u.get("color").toNonPremultipliedRenderColor(null),S=o.paint.get("model-color").constantOr(Vn.white).toNonPremultipliedRenderColor(null).toArray01();return S[3]=o.paint.get("model-color-mix-intensity").constantOr(0),{lightPos:x,lightIntensity:u.get("intensity"),lightColor:[b.r,b.g,b.b],colorMix:S,aoIntensity:o.paint.get("model-ambient-occlusion-intensity")}},B$=(h,o,u,m,x,b,S,A,I=[0,0,0],D,B,U,q=1)=>{const K=S.pbrMetallicRoughness;let X=U||x.colorMix;if(B){const J=B.color;X=[J.r,J.g,J.b,B.colorMix],A=B.emissionStrength,b*=B.opacity}return{u_matrix:h,u_lighting_matrix:o,u_normal_matrix:u,u_node_matrix:m||O$,u_lightpos:x.lightPos,u_lightintensity:x.lightIntensity,u_lightcolor:x.lightColor,u_camera_pos:I,u_opacity:b,u_alphaMask:+(S.alphaMode==="MASK"),u_alphaCutoff:S.alphaCutoff,u_baseColorFactor:K.baseColorFactor.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:S.emissiveFactor.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:K.metallicFactor,u_roughnessFactor:K.roughnessFactor,u_baseColorTexture:_u.BaseColor,u_metallicRoughnessTexture:_u.MetallicRoughness,u_normalTexture:_u.Normal,u_occlusionTexture:_u.Occlusion,u_emissionTexture:_u.Emission,u_lutTexture:_u.LUT,u_color_mix:X,u_aoIntensity:x.aoIntensity,u_emissive_strength:A,u_occlusionTextureTransform:D||[0,0,0,0],u_dithered_discard_threshold:q,u_model_mesh_params:[0,1,0,0]}},Xre=(h,o=O$,u=O$)=>({u_matrix:h,u_instance:o,u_node_matrix:u}),z$=7680;class Mh{constructor(o,u,m,x,b,S){this.test=o,this.ref=u,this.mask=m,this.fail=x,this.depthFail=b,this.pass=S}}Mh.disabled=new Mh({func:519,mask:0},0,0,z$,z$,z$);const IL=770,oS=771;class ia{constructor(o,u,m,x){this.blendFunction=o,this.blendColor=u.toNonPremultipliedRenderColor(null),this.mask=m,this.blendEquation=x}}ia.Replace=[1,0,1,0],ia.disabled=new ia(ia.Replace,Vn.transparent,[!1,!1,!1,!1]),ia.unblended=new ia(ia.Replace,Vn.transparent,[!0,!0,!0,!0]),ia.alphaBlended=new ia([1,oS,1,oS],Vn.transparent,[!0,!0,!0,!0]),ia.alphaBlendedNonPremultiplied=new ia([IL,oS,IL,oS],Vn.transparent,[!0,!0,!0,!0]),ia.multiply=new ia([774,0,774,0],Vn.transparent,[!0,!0,!0,!0]),ia.multiplyAccumulateAlpha=new ia([774,0,1,oS],Vn.transparent,[!0,!0,!0,!0]),ia.additive=new ia([1,1,1,1],Vn.transparent,[!0,!0,!0,!0]),ia.additiveAlphaWeighted=new ia([IL,1,773,1],Vn.transparent,[!0,!0,!0,!0]),ia.additiveAlphaWeightedUnboundedAlpha=new ia([IL,1,1,1],Vn.transparent,[!0,!0,!0,!0]);class tc{constructor(o,u,m){this.func=o,this.mask=u,this.range=m}}tc.ReadOnly=!1,tc.ReadWrite=!0,tc.disabled=new tc(519,tc.ReadOnly,[0,1]);const $$=1029,U$=2305;class rc{constructor(o,u,m){this.enable=o,this.mode=u,this.frontFace=m}}rc.disabled=new rc(!1,$$,U$),rc.backCCW=new rc(!0,$$,U$),rc.backCW=new rc(!0,$$,2304),rc.frontCW=new rc(!0,1028,2304),rc.frontCCW=new rc(!0,1028,U$);class V${constructor(o=0,u=0,m=0,x=0){if(isNaN(o)||o<0||isNaN(u)||u<0||isNaN(m)||m<0||isNaN(x)||x<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=o,this.bottom=u,this.left=m,this.right=x}interpolate(o,u,m){return u.top!=null&&o.top!=null&&(this.top=Kr(o.top,u.top,m)),u.bottom!=null&&o.bottom!=null&&(this.bottom=Kr(o.bottom,u.bottom,m)),u.left!=null&&o.left!=null&&(this.left=Kr(o.left,u.left,m)),u.right!=null&&o.right!=null&&(this.right=Kr(o.right,u.right,m)),this}getCenter(o,u){return new jt(cn((this.left+o-this.right)/2,0,o),cn((this.top+u-this.bottom)/2,0,u))}equals(o){return this.top===o.top&&this.bottom===o.bottom&&this.left===o.left&&this.right===o.right}clone(){return new V$(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function Qre(h,o){const u=gc(h,3);$e(h,o),s0(h,3,u)}function q$(h,o){const u=ci([]);return pn(u,u,-o),_r(u,u,-h),u}function Jre(h,o){const u=[h[0],h[1],0],m=[o[0],o[1],0];if(ot(u)>=1e-15){const S=zt([],u);ft(m,S,Vr(m,S)),o[0]=m[0],o[1]=m[1]}const x=Jr([],o,h);if(ss(x)<1e-15)return null;const b=Math.atan2(-x[1],x[0]);return q$(Math.atan2(Math.sqrt(h[0]*h[0]+h[1]*h[1]),-h[2]),b)}class ene{constructor(o,u){this.position=o,this.orientation=u}get position(){return this._position}set position(o){if(o){const u=o instanceof os?o:new os(o[0],o[1],o[2]);this._renderWorldCopies&&(u.x=uu(u.x,0,1)),this._position=u}else this._position=null}lookAtPoint(o,u,m){if(this.orientation=null,!this.position)return;const x=this.position,b=m||(this._elevation?this._elevation.getAtPointOrZero(os.fromLngLat(o)):0),S=os.fromLngLat(o,b),A=[S.x-x.x,S.y-x.y,S.z-x.z];u||(u=[0,0,1]),u[2]=Math.abs(u[2]),this.orientation=Jre(A,u)}setPitchBearing(o,u){this.orientation=q$(Bn(o),Bn(-u))}}class jL{constructor(o,u){this._transform=G([]),this.orientation=u,this.position=o}get mercatorPosition(){const o=this.position;return new os(o[0],o[1],o[2])}get position(){const o=gc(this._transform,3);return[o[0],o[1],o[2]]}set position(o){var u;o&&s0(this._transform,3,[(u=o)[0],u[1],u[2],1])}get orientation(){return this._orientation}set orientation(o){this._orientation=o||ci([]),o&&Qre(this._transform,this._orientation)}getPitchBearing(){const o=this.forward(),u=this.right();return{bearing:Math.atan2(-u[1],u[0]),pitch:Math.atan2(Math.sqrt(o[0]*o[0]+o[1]*o[1]),-o[2])}}setPitchBearing(o,u){this._orientation=q$(o,u),Qre(this._transform,this._orientation)}forward(){const o=gc(this._transform,2);return[-o[0],-o[1],-o[2]]}up(){const o=gc(this._transform,1);return[-o[0],-o[1],-o[2]]}right(){const o=gc(this._transform,0);return[o[0],o[1],o[2]]}getCameraToWorld(o,u){const m=new Float64Array(16);return Z(m,this.getWorldToCamera(o,u)),m}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(o,u,m){const x=this.position;ft(x,x,-o);const b=new Float64Array(16);return Re(b,[m,m,m]),ee(b,b,x),b[10]*=u,b}getWorldToCamera(o,u){const m=new Float64Array(16),x=new Float64Array(4),b=this.position;return(S=x)[0]=-(A=this._orientation)[0],S[1]=-A[1],S[2]=-A[2],S[3]=A[3],ft(b,b,-o),$e(m,x),ee(m,m,b),m[1]*=-1,m[5]*=-1,m[9]*=-1,m[13]*=-1,m[8]*=u,m[9]*=u,m[10]*=u,m[11]*=u,m;var S,A}getCameraToClipPerspective(o,u,m,x){const b=new Float64Array(16);return we(b,o,u,m,x),b}getCameraToClipOrthographic(o,u,m,x,b,S){const A=new Float64Array(16);return ke(A,o,u,m,x,b,S),A}getDistanceToElevation(o,u=!1){const m=o===0?0:ks(o,u?Fa(this.position[1]):this.position[1]),x=this.forward();return(m-this.position[2])/x[2]}clone(){return new jL([...this.position],[...this.orientation])}}const YDe=Math.tan(85*Math.PI/180);function G$(h,o,u,m,x,b,S){const A=O();if(u)if(b.name==="globe"){const I=function(D,B){const{x:U,y:q}=D.point,K=BJ(U,q,D.worldSize/D._pixelsPerMercatorPixel,0,0);return Q(K,K,Lz(kp(B)))}(x,o);Q(A,A,I)}else{const I=j([],S);A[0]=I[0],A[1]=I[1],A[4]=I[2],A[5]=I[3],m||Le(A,A,x.angle)}else Q(A,x.labelPlaneMatrix,h);return A}function n_(h,o,u,m){const x=[h,o,u,1];u?Ki(x,x,m):Uz(x,x,m);const b=x[3];return x[0]/=b,x[1]/=b,x[2]/=b,x}function tne(h,o){return Math.min(.5+h/o*.5,1.5)}function ZDe(h,o){const u=h[0]/h[3],m=h[1]/h[3];return u>=-o[0]&&u<=o[0]&&m>=-o[1]&&m<=o[1]}function rne(h,o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae){const{lineStartIndex:ue,glyphStartIndex:ce,segment:de}=A,xe=ce+A.numGlyphs,ve=ue+A.lineLength,Ue=o.getoffsetX(ce),Pe=o.getoffsetX(xe-1),De=CL(h*Ue,u,m,x,b,S,de,ue,ve,I,D,B,U,q,!0,K,X,J,se,ae);if(!De)return null;const Ve=CL(h*Pe,u,m,x,b,S,de,ue,ve,I,D,B,U,q,!0,K,X,J,se,ae);return Ve?{first:De,last:Ve}:null}function nne(h,o,u,m){return h===Zg.horizontal&&Math.abs(m)>Math.abs(u)?{useVertical:!0}:h===Zg.vertical?m>0?{needsFlipping:!0}:null:o!==0&&function(x,b){return x===0||Math.abs(b/x)>YDe}(u,m)?o===1?{needsFlipping:!0}:null:u<0?{needsFlipping:!0}:null}function ine(h,o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae,ue,ce,de){const xe=o/24,ve=h.lineOffsetX*xe,Ue=h.lineOffsetY*xe,{lineStartIndex:Pe,glyphStartIndex:De,numGlyphs:Ve,segment:Fe,writingMode:Ze,flipState:st}=h,ut=Pe+h.lineLength,ht=_t=>{if(B){const[Ye,At,Tt]=_t.up,$t=D.length;JR(B,$t+0,Ye,At,Tt),JR(B,$t+1,Ye,At,Tt),JR(B,$t+2,Ye,At,Tt),JR(B,$t+3,Ye,At,Tt)}const[Et,Pt,Rt]=_t.point;G0(D,Et,Pt,Rt,_t.angle)};if(Ve>1){const _t=rne(xe,A,ve,Ue,u,U,q,h,I,b,K,J,!1,se,ae,ue,ce,de);if(!_t)return{notEnoughRoom:!0};if(m&&!u){let[Et,Pt,Rt]=_t.first.point,[Ye,At,Tt]=_t.last.point;[Et,Pt]=n_(Et,Pt,Rt,S),[Ye,At]=n_(Ye,At,Tt,S);const $t=nne(Ze,st,(Ye-Et)*X,At-Pt);if(h.flipState=$t&&$t.needsFlipping?1:2,$t)return $t}ht(_t.first);for(let Et=De+1;Et0?Ye:one(q,Rt,Et,1,x,void 0,se,ae.canonical),Tt=nne(Ze,st,(At[0]-Et[0])*X,At[1]-Et[1]);if(h.flipState=Tt&&Tt.needsFlipping?1:2,Tt)return Tt}const _t=CL(xe*A.getoffsetX(De),ve,Ue,u,U,q,Fe,Pe,ut,I,b,K,J,!1,!1,se,ae,ue,ce,de);if(!_t)return{notEnoughRoom:!0};ht(_t)}return{}}function sne(h,o,u){const m=1<0?1:-1,ve=0;m&&(xe*=-1,ve=Math.PI),xe<0&&(ve+=Math.PI);let Ue=A+S+(xe>0?0:1)|0,Pe=x,De=x,Ve=0,Fe=0;const Ze=Math.abs(de),st=[],ut=[];let ht=b,_t=ht,Et=li([]);const Pt=()=>one(_t,ht,De,Ze-Ve+1,B,q,J,se.canonical,ce);for(;Ve+Fe<=Ze;){if(Ue+=xe,Ue=I)return null;if(De=Pe,_t=ht,st.push(De),K&&ut.push(_t),ht=new jt(D.getx(Ue),D.gety(Ue)),Pe=U[Ue],!Pe){const nr=ane(ht,se.canonical,B,J,q,ce);Pe=nr[3]>0?U[Ue]=nr:Pt()}Ve+=Fe;const Dt=Or([],Pe,De),dr=ir(De,Pe);if(u&&dr>0&&Fe>0&&Vr(Et,Dt)/(Fe*dr)0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||o===Number.NEGATIVE_INFINITY&&(!u||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const m=this._elevation;u||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&m.exaggeration()&&this._centerAltitudeValidForExaggeration!==m.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*m.exaggeration(),this._centerAltitudeValidForExaggeration=m.exaggeration()):(this._centerAltitude=o||0,this._centerAltitudeValidForExaggeration=m.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const o=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(o)}sampleAverageElevation(){if(!this._elevation)return 0;const o=this._elevation,u=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],m=this.horizonLineFromTop();let x=0,b=0;for(let S=0;S{const se=Qx(q,U,K,X,J);I.has(se)||(b.push(new ll(U,q,K,X,J)),I.add(se))};for(let U=0;Uq.canonical.z)continue;const K=q.canonical,X=q.overscaledZ,J=q.wrap,se=1<0,ce=K.y+10,xe=q.wrap-(ue?0:1),ve=q.wrap+(ae?0:1),Ue=ue?K.x-1:se-1,Pe=ae?K.x+1:0;if(S)m[0]<0?(D(X,ve,K.z,Pe,K.y),m[1]<0&&ce&&(D(X,J,K.z,K.x,K.y+1),D(X,ve,K.z,Pe,K.y+1)),m[1]>0&&de&&(D(X,J,K.z,K.x,K.y-1),D(X,ve,K.z,Pe,K.y-1))):m[0]>0?(D(X,xe,K.z,Ue,K.y),m[1]<0&&ce&&(D(X,J,K.z,K.x,K.y+1),D(X,xe,K.z,Ue,K.y+1)),m[1]>0&&de&&(D(X,J,K.z,K.x,K.y-1),D(X,xe,K.z,Ue,K.y-1))):m[1]<0&&ce?D(X,J,K.z,K.x,K.y+1):de&&D(X,J,K.z,K.x,K.y-1);else{const De=q.visibleQuadrants;1&De&&(D(X,xe,K.z,Ue,K.y),de&&(D(X,J,K.z,K.x,K.y-1),D(X,xe,K.z,Ue,K.y-1))),2&De&&(D(X,ve,K.z,Pe,K.y),de&&(D(X,J,K.z,K.x,K.y-1),D(X,ve,K.z,Pe,K.y-1))),4&De&&(D(X,xe,K.z,Ue,K.y),ce&&(D(X,J,K.z,K.x,K.y+1),D(X,xe,K.z,Ue,K.y+1))),8&De&&(D(X,ve,K.z,Pe,K.y),ce&&(D(X,J,K.z,K.x,K.y+1),D(X,ve,K.z,Pe,K.y+1)))}}const B=[];for(const U of b)b.some(q=>U.isChildOf(q))||B.push(U);if(b=B.filter(U=>!o.some(q=>!!(U.overscaledZ{const ae=se.canonical.x+.5-K[0],ue=se.canonical.y+.5-K[1];return ae*ae+ue*ue{const Ue=Qx(ce,ue,de,xe,ve);b.has(Ue)||(x.push(new ll(ue,ce,de,xe,ve)),b.add(Ue))},A=o.reduce((ue,ce)=>Math.max(ue,ce.overscaledZ),m),I=1<{const de=Math.floor(ue[0]),xe=Math.floor(ue[1]),ve=(ue[0]-de)*ar,Ue=(ue[1]-xe)*ar,Pe=Math.floor(ce[0]),De=Math.floor(ce[1]),Ve=(ce[0]-Pe)*ar,Fe=(ce[1]-De)*ar;for(let Ze=-1;Ze<=1;Ze++){const st=de+Ze;if(!(st<0||st>=I)){B.x=ve-Ze*ar,U.x=Ve-(st-Pe)*ar;for(let ut=-1;ut<=1;ut++){const ht=xe+ut;B.y=Ue-ut*ar,U.y=Fe-(ht-De)*ar,U1(B,U,D)&&S(A,0,m,st,ht)}}}},K=u.points,X=K[3],J=K[2],se=this._projectToGround(X,K[7]),ae=this._projectToGround(J,K[6]);return q(X,se),q(J,ae),x}_projectToGround(o,u){return Fn(He(),o,u,o[2]/(o[2]-u[2]))}_projectToZ(o,u,m){const x=o[2]-u[2];return Math.abs(x)<1e-6?(b=o,(S=new T(3))[0]=b[0],S[1]=b[1],S[2]=b[2],S):Fn(He(),o,u,(o[2]-m)/x);var b,S}extendTileCoverForTunnels(o,u,m,x){if(m<18)return[];const b=u.points,S=b[0],A=b[1],I=b[4],D=b[5];if(I[2]>=0&&D[2]>=0||S[2]<=0||A[2]<=0)return[];const B=I[2]<0?this._projectToZ(S,I,0):I,U=D[2]<0?this._projectToZ(A,D,0):D,q=-x,K=I[2]3&&(J.length=3),J}_findExtensionTilesInQuad(o,u,m,x){const b=[],S=new Set;for(const Pe of o)S.add(Pe.key);const A=o.reduce((Pe,De)=>Math.max(Pe,De.overscaledZ),u),I=1<{const Ve=Pe.canonical.x+.5-ve,Fe=Pe.canonical.y+.5-Ue,Ze=De.canonical.x+.5-ve,st=De.canonical.y+.5-Ue;return Ve*Ve+Fe*Fe-(Ze*Ze+st*st)||Pe.canonical.x-De.canonical.x||Pe.canonical.y-De.canonical.y}),b}coveringTiles(o){let u=this.coveringZoomLevel(o);const m=u,x=this.elevation&&this.elevation.exaggeration(),b=x&&!o.isTerrainDEM,S=this.projection.name==="mercator";if(o.minzoom!==void 0&&uo.maxzoom&&(u=o.maxzoom);const A=this.locationCoordinate(this.center),I=this.center.lat,D=1<{const Tt=new os(Ye.x+25e-6,Ye.y,Ye.z),$t=new os(Ye.x,Ye.y+25e-6,Ye.z),Gt=Ye.toLngLat(),kt=Tt.toLngLat(),Dt=$t.toLngLat(),dr=this.locationCoordinate(Gt),nr=this.locationCoordinate(kt),yr=this.locationCoordinate(Dt),Br=Math.hypot(nr.x-dr.x,nr.y-dr.y),br=Math.hypot(yr.x-dr.x,yr.y-dr.y);return Math.sqrt(Br*br)*Pe/25e-6},Ve=Ye=>{const At=ve,Tt=Ue;return{aabb:GJ(this,D,0,0,0,Ye,Tt,At,this.projection),zoom:0,x:0,y:0,minZ:Tt,maxZ:At,wrap:Ye,fullyVisible:!1}},Fe=[];let Ze=[];const st=u,ut=o.reparseOverscaled?m:u,ht=(se-this._centerAltitude)*J,_t=Ye=>{if(!this._elevation||!Ye.tileID||!S)return;const At=this._elevation.getMinMaxForTile(Ye.tileID),Tt=Ye.aabb;At?(Tt.min[2]=At.min,Tt.max[2]=At.max,Tt.center[2]=(Tt.min[2]+Tt.max[2])/2):(Ye.shouldSplit=Pt(Ye),Ye.shouldSplit||(Tt.min[2]=Tt.max[2]=Tt.center[2]=this._centerAltitude))},Et=(Ye,At)=>{if(.707*At{if(Ye.zoom=.9)return!0}else if(b&&($t=Ye.aabb.distanceZ(ae)*J),this.projection.isReprojectedInTileSpace&&m<=5){const br=Math.pow(2,Ye.zoom),dn=De(new os((Ye.x+.5)/br,(Ye.y+.5)/br));Gt=dn>.85?1:dn}if(!S&&!U){const br=Math.sqrt(At*At+Tt*Tt+$t*$t);let dn=(1<=4?nr[2]:dr[2])-ae[2];U||(rn=b?rn*J:ht);const wr=((dn===1||dn===2?nr[0]:dr[0])-ae[0])*ce[0]+((dn>=2?nr[1]:dr[1])-ae[1])*ce[1]+rn*ce[2];wr0;){const Ye=Fe.pop(),At=Ye.x,Tt=Ye.y;let $t=Ye.fullyVisible;const Gt=()=>this.projection.name==="globe"&&(Ye.y===0||Ye.y===(1<kt)continue;let Dt=0;if(!$t){let Br=ue?Ye.aabb.intersectsPrecise(K):Ye.aabb.intersectsPreciseFlat(K);if(Br===0&&Gt()){const br=new Xx(Ye.zoom,At,Tt);Br=Nz(this,D,br,!0).intersectsPrecise(K)}if(Br===0)continue;if(o.calculateQuadrantVisibility)if(K.containsPoint(Ye.aabb.center))Dt=15;else for(let br=0;br<4;br++)Ye.aabb.quadrant(br).intersects(K)!==0&&(Dt|=1<>1),nr={aabb:S?Ye.aabb.quadrant(kt):GJ(this,D,Ye.zoom+1,Dt,dr,Ye.wrap,Ye.minZ,Ye.maxZ,this.projection),zoom:Ye.zoom+1,x:Dt,y:dr,wrap:Ye.wrap,fullyVisible:$t,tileID:void 0,shouldSplit:void 0,minZ:Ye.minZ,maxZ:Ye.maxZ};b&&!U&&(nr.tileID=new ll(Ye.zoom+1===st?ut:Ye.zoom+1,Ye.wrap,Ye.zoom+1,Dt,dr),_t(nr)),Fe.push(nr)}}if(this.fogCullDistSq){const Ye=this.fogCullDistSq,At=this.horizonLineFromTop();Ze=Ze.filter(Tt=>{const $t=[0,0,0,1],Gt=[ar,ar,0,1],kt=this.calculateFogTileMatrix(Tt.tileID.toUnwrapped());Ki($t,$t,kt),Ki(Gt,Gt,kt);const Dt=function(br,dn,rn){return br[0]=Math.min(dn[0],rn[0]),br[1]=Math.min(dn[1],rn[1]),br[2]=Math.min(dn[2],rn[2]),br[3]=Math.min(dn[3],rn[3]),br}([],$t,Gt),dr=function(br,dn,rn){return br[0]=Math.max(dn[0],rn[0]),br[1]=Math.max(dn[1],rn[1]),br[2]=Math.max(dn[2],rn[2]),br[3]=Math.max(dn[3],rn[3]),br}([],$t,Gt),nr=function(br,dn){let rn=0;for(let wr=0;wr<2;++wr)br[wr]>0&&(rn+=(br[wr]-0)*(br[wr]-0)),dn[wr]<0&&(rn+=(0-dn[wr])*(0-dn[wr]));return rn}(Dt,dr);if(nr===0)return!0;let yr=!1;const Br=this._elevation;if(Br&&nr>Ye&&At!==0){const br=this.calculateProjMatrix(Tt.tileID.toUnwrapped());let dn;o.isTerrainDEM||(dn=Br.getMinMaxForTile(Tt.tileID)),dn||(dn={min:Ue,max:ve});const rn=function(Fr){const ni=Math.round((Fr+45+360)%360/90)%4;return Ow[ni]}(this.rotation),wr=[rn[0]*ar,rn[1]*ar,dn.max];Ar(wr,wr,br),yr=(1-wr[1])*this.height*.5Ye.distanceSq-At.distanceSq).map(Ye=>Ye.tileID)}resize(o,u){this.width=o,this.height=u,this.pixelsToGLUnits=[2/o,-2/u],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(o){return Math.pow(2,o)}scaleZoom(o){return Math.log2(o)}project(o){const u=cn(o.lat,-85.051129,wc),m=this.projection.project(o.lng,u);return new jt(m.x*this.worldSize,m.y*this.worldSize)}unproject(o){return this.projection.unproject(o.x/this.worldSize,o.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/ks(1,this.center.lat)/this.worldSize}setLocationAtPoint(o,u){let m,x;const b=this.centerPoint;if(this.projection.name==="globe"){const A=this.worldSize;m=(u.x-b.x)/A,x=(u.y-b.y)/A}else{const A=this.pointCoordinate(u),I=this.pointCoordinate(b);m=A.x-I.x,x=A.y-I.y}const S=this.locationCoordinate(o);this.setLocation(new os(S.x-m,S.y-x))}setLocation(o){this.center=this.coordinateLocation(o),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(o,u){return this.projection.locationPoint(this,o,u)}locationPoint3D(o,u){return this.projection.locationPoint(this,o,u,!0)}pointLocation(o){return this.coordinateLocation(this.pointCoordinate(o))}pointLocation3D(o,u){return this.coordinateLocation(this.pointCoordinate3D(o,u))}locationCoordinate(o,u){const m=u?ks(u,o.lat):void 0,x=this.projection.project(o.lng,o.lat);return new os(x.x,x.y,m)}coordinateLocation(o){return this.projection.unproject(o.x,o.y)}pointRayIntersection(o,u){const m=u??this._centerAltitude,x=[o.x,o.y,0,1],b=[o.x,o.y,1,1];Ki(x,x,this.pixelMatrixInverse),Ki(b,b,this.pixelMatrixInverse);const S=b[3];gs(x,x,1/x[3]),gs(b,b,1/S);const A=x[2],I=b[2];return{p0:x,p1:b,t:A===I?0:(m-A)/(I-A)}}screenPointToMercatorRay(o){const u=[o.x,o.y,0,1],m=[o.x,o.y,1,1];return Ki(u,u,this.pixelMatrixInverse),Ki(m,m,this.pixelMatrixInverse),gs(u,u,1/u[3]),gs(m,m,1/m[3]),u[2]=ks(u[2],this._center.lat)*this.worldSize,m[2]=ks(m[2],this._center.lat)*this.worldSize,gs(u,u,1/this.worldSize),gs(m,m,1/this.worldSize),new AR([u[0],u[1],u[2]],zt([],Or([],m,u)))}rayIntersectionCoordinate(o){const{p0:u,p1:m,t:x}=o,b=ks(u[2],this._center.lat),S=ks(m[2],this._center.lat);return new os(Kr(u[0],m[0],x)/this.worldSize,Kr(u[1],m[1],x)/this.worldSize,Kr(b,S,x))}pointCoordinate(o,u=this._centerAltitude){return this.projection.pointCoordinate(this,o.x,o.y,u)}pointCoordinate3D(o,u){if(!this.elevation)return this.pointCoordinate(o,u);let m=this.projection.pointCoordinate3D(this,o.x,o.y);if(m)return new os(m[0],m[1],m[2]);let x=0,b=this.horizonLineFromTop();if(o.y>b)return this.pointCoordinate(o,u);const S=.02*b,A=o.clone();for(let I=0;I<10&&b-x>S;I++){A.y=Kr(x,b,.66);const D=this.projection.pointCoordinate3D(this,A.x,A.y);D?(b=A.y,m=D):x=A.y}return m?new os(m[0],m[1],m[2]):this.pointCoordinate(o)}isPointAboveHorizon(o){return this.projection.isPointAboveHorizon(this,o)}isPointOnSurface(o){if(o.y<0||o.y>this.height||o.x<0||o.x>this.width)return!1;if(this.elevation||this.zoom>=6)return!this.isPointAboveHorizon(o);const u=this.pointCoordinate(o);return u.y>=0&&u.y<=1}_coordinatePoint(o,u){const m=u&&this.elevation?this.elevation.getAtPointOrZero(o,this._centerAltitude):this._centerAltitude,x=[o.x*this.worldSize,o.y*this.worldSize,m+o.toAltitude(),1];return Ki(x,x,this.pixelMatrix),x[3]>0?new jt(x[0]/x[3],x[1]/x[3]):new jt(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:o,left:u}=this._edgeInsets,m=this.height-this._edgeInsets.bottom,x=this.width-this._edgeInsets.right,b=this.pointLocation3D(new jt(u,o)),S=this.pointLocation3D(new jt(x,o)),A=this.pointLocation3D(new jt(x,m)),I=this.pointLocation3D(new jt(u,m));let D=Math.min(b.lng,S.lng,A.lng,I.lng),B=Math.max(b.lng,S.lng,A.lng,I.lng),U=Math.min(b.lat,S.lat,A.lat,I.lat),q=Math.max(b.lat,S.lat,A.lat,I.lat);const K=Math.pow(2,-this.zoom)/16*270,X=this.projection.name==="globe"?1:4,J=(se,ae,ue,ce,de)=>{const xe=(se+ue)/2,ve=(ae+ce)/2,Ue=new jt(xe,ve),{lng:Pe,lat:De}=this.pointLocation3D(Ue),Ve=Math.max(0,D-Pe,U-De,Pe-B,De-q);D=Math.min(D,Pe),B=Math.max(B,Pe),U=Math.min(U,De),q=Math.max(q,De),(deK)&&(J(se,ae,xe,ve,de+1),J(xe,ve,ue,ce,de+1))};if(J(u,o,x,o,1),J(x,o,x,m,1),J(x,m,u,m,1),J(u,m,u,o,1),this.projection.name==="globe"){const[se,ae]=function(ue){const ce=G(new Float64Array(16));Q(ce,ue.pixelMatrix,ue.globeMatrix);const de=[0,Xd,0],xe=[0,gu,0];return Ar(de,de,ce),Ar(xe,xe,ce),[de[0]>0&&de[0]<=ue.width&&de[1]>0&&de[1]<=ue.height&&!Mz(ue,new pi(ue.center.lat,90)),xe[0]>0&&xe[0]<=ue.width&&xe[1]>0&&xe[1]<=ue.height&&!Mz(ue,new pi(ue.center.lat,-90))]}(this);se?(q=90,B=180,D=-180):ae&&(U=-90,B=180,D=-180)}return new Qd(new pi(D,U),new pi(B,q))}_getBoundsRectangular(o,u){const{top:m,left:x}=this._edgeInsets,b=this.height-this._edgeInsets.bottom,S=this.width-this._edgeInsets.right,A=new jt(x,m),I=new jt(S,m),D=new jt(S,b),B=new jt(x,b);let U=this.pointCoordinate(A,o),q=this.pointCoordinate(I,o);const K=this.pointCoordinate(D,u),X=this.pointCoordinate(B,u),J=(se,ae)=>(ae.y-se.y)/(ae.x-se.x);return U.y>1&&q.y>=0?U=new os((1-X.y)/J(X,U)+X.x,1):U.y<0&&q.y<=1&&(U=new os(-X.y/J(X,U)+X.x,0)),q.y>1&&U.y>=0?q=new os((1-K.y)/J(K,q)+K.x,1):q.y<0&&U.y<=1&&(q=new os(-K.y/J(K,q)+K.x,0)),new Qd().extend(this.coordinateLocation(U)).extend(this.coordinateLocation(q)).extend(this.coordinateLocation(X)).extend(this.coordinateLocation(K))}_getBoundsRectangularTerrain(){const o=this.elevation;if(!o.visibleDemTiles.length||o.isUsingMockSource())return this._getBoundsRectangular(0,0);const u=o.visibleDemTiles.reduce((m,x)=>{if(x.dem){const b=x.dem.tree;m.min=Math.min(m.min,b.minimums[0]),m.max=Math.max(m.max,b.maximums[0])}return m},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(u.min*o.exaggeration(),u.max*o.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(o=!0){const u=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,m=this.height/2-u*(1-this._horizonShift);return o?Math.max(0,m):m}getMaxBounds(){return this.maxBounds}setMaxBounds(o){this.maxBounds=o,this.minLat=-85.051129,this.maxLat=wc,this.minLng=-180,this.maxLng=180,o&&(this.minLat=o.getSouth(),this.maxLat=o.getNorth(),this.minLng=o.getWest(),this.maxLng=o.getEast(),this.maxLngU&&(A=U-D),U-BK&&(S=K-I),K-q{for(let st=0;st<16;st++)De[st]=Kr(Ve[st],Fe[st],Ze)})(A,A,I,o0(this.pitch>=lS?1:this.pitch/lS))}else A=I;this._cameraToClip=A;const D=Ae(new Float64Array(16),I,S),B=Ae(new Float64Array(16),A,S);if(this.projection.isReprojectedInTileSpace){const xe=this.locationCoordinate(this.center);G(this._mat4Scratch);const ve=this._mat4Scratch;ee(ve,ve,[xe.x*this.worldSize,xe.y*this.worldSize,0]),Q(ve,ve,mte(this)),ee(ve,ve,[-xe.x*this.worldSize,-xe.y*this.worldSize,0]),Q(B,B,ve),Q(D,D,ve),this.inverseAdjustmentMatrix=function(Ue){const Pe=mte(Ue,!0);return j([],[Pe[0],Pe[1],Pe[4],Pe[5]])}(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(ie(this.mercatorMatrix,B,[this.worldSize,this.worldSize,this.worldSize/b,1]),this.projMatrix=B,Z(this.invProjMatrix,this.projMatrix),this._frustumCache.clear(),u){const xe=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);xe[8]=2*-o.x/this.width,xe[9]=2*o.y/this.height,Ae(this._expandedFarZProjMatrixBuf,xe,S),this.expandedFarZProjMatrix=this._expandedFarZProjMatrixBuf}else this.expandedFarZProjMatrix=this.projMatrix;Z(this._mat4Scratch,A),this.frustumCorners=Iz.fromInvProjectionMatrix(this._mat4Scratch,this.horizonLineFromTop(),this.height),Re(this.skyboxMatrix,[1,-1,1]),oe(this.skyboxMatrix,this.skyboxMatrix,this._pitch),Le(this.skyboxMatrix,this.skyboxMatrix,this.angle),we(this.starsProjMatrix,this._fov,this.width/this.height,this._nearZ,this._farZ);const U=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;$(this._mat4Scratch,this.starsProjMatrix),this._mat4Scratch[8]=2*-o.x/this.width,this._mat4Scratch[9]=2*(o.y+U)/this.height,Q(this.skyboxMatrix,this._mat4Scratch,this.skyboxMatrix);const q=this.point,K=q.x,X=q.y,J=this.width%2/2,se=this.height%2/2,ae=Math.cos(this.angle),ue=Math.sin(this.angle),ce=K-Math.round(K)+ae*J+ue*se,de=X-Math.round(X)+ae*se+ue*J;if($(this.alignedProjMatrix,B),ee(this.alignedProjMatrix,this.alignedProjMatrix,[ce>.5?ce-1:ce,de>.5?de-1:de,0]),Re(this.labelPlaneMatrix,[this.width/2,-this.height/2,1]),ee(this.labelPlaneMatrix,this.labelPlaneMatrix,[1,-1,0]),Re(this.glCoordMatrix,[1,-1,1]),ee(this.glCoordMatrix,this.glCoordMatrix,[-1,-1,0]),ie(this.glCoordMatrix,this.glCoordMatrix,[2/this.width,2/this.height,1]),Q(this.pixelMatrix,this.labelPlaneMatrix,D),this._calcFogMatrices(),this._distanceTileDataCache.clear(),!Z(this.pixelMatrixInverse,this.pixelMatrix))throw new Error("failed to invert matrix");if(this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=function(ve){const{x:Ue,y:Pe}=ve.point,{lng:De,lat:Ve}=ve._center;return BJ(Ue,Pe,ve.worldSize,De,Ve)}(this);const xe=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=Ar(xe,xe,S),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=this.pixelMatrixInverse;this._worldToCamera=this.projection.name==="globe"?Q(new Float64Array(16),S,this.globeMatrix):S,this._posMatrixCache.clear(),this._projMatrixCache.clear(),this._alignedProjMatrixCache.clear(),this._pixelsToTileUnitsCache.clear(),this._expandedProjMatrixCache.clear()}_calcFogMatrices(){this._fogTileMatrixCache.clear();const o=this.cameraWorldSizeForFog,u=this.cameraPixelsPerMeter,m=this._camera.position,x=1/this.height/this._pixelsPerMercatorPixel,b=[o,o,u];ft(b,b,x),ft(m,m,-1),Ct(m,m,b),be(this.mercatorFogMatrix,m),ie(this.mercatorFogMatrix,this.mercatorFogMatrix,b),this.worldToFogMatrix=this._camera.getWorldToCameraPosition(o,u,x)}_computeCameraPosition(o){const u=(o=o||this.pixelsPerMeter)/this.pixelsPerMeter,m=this._camera.forward(),x=this.point,b=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*u-o/this.worldSize*this._centerAltitude;return[x.x/this.worldSize-m[0]*b,x.y/this.worldSize-m[1]*b,o/this.worldSize*this._centerAltitude-m[2]*b]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(o){const u=this._maxCameraBoundsDistance()*Math.cos(this._pitch),m=this._camera.position[2],x=o[2];let b=1;this.projection.wrap&&(this.center=this.center.wrap()),x>0&&(b=Math.min((u-m)/x,1)),this._camera.position=Kt([],this._camera.position,o,b),this._updateStateFromCamera()}_updateStateFromCamera(){const o=this._camera.position,u=this._camera.forward(),{pitch:m,bearing:x}=this._camera.getPitchBearing(),b=ks(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,S=this._mercatorZfromZoom(this._maxZoom)*Math.cos(Bn(this._maxPitch)),A=Math.max((o[2]-b)/Math.cos(m),S),I=this._zoomFromMercatorZ(A);Kt(o,o,u,A),this._pitch=cn(m,Bn(this.minPitch),Bn(this.maxPitch)),this.angle=uu(x,-Math.PI,Math.PI),this._setZoom(cn(I,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new os(o[0],o[1],o[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(o){return Math.pow(2,o)*this.tileSize}_mercatorZfromZoom(o){return this.cameraToCenterDistance/this._worldSizeFromZoom(o)}_minimumHeightOverTerrain(){const o=Math.min(this._seaLevelZoom??this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(o)}_zoomFromMercatorZ(o){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,o)*this.tileSize))}zoomFromMercatorZAdjusted(o){let u=0,m=6,x=0,b=1/0;for(;m-u>1e-6&&m>u;){const S=u+.5*(m-u),A=this.tileSize*Math.pow(2,S),I=this.getCameraToCenterDistance(this.projection,S,A),D=this.scaleZoom(I/(Math.max(0,o)*this.tileSize)),B=Math.abs(S-D);BD||q.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+po(this.fovAboveCenter)>88||this.anyCornerOffEdge(new jt(0,0),new jt(this.width,this.height))}zoomDeltaToMovement(o,u){const m=ot(Or([],this._camera.position,o)),x=this._zoomFromMercatorZ(m)+u;return m-this._mercatorZfromZoom(x)}getCameraPoint(){if(this.projection.name==="globe"){const o=function([u,m,x],b){const S=[u,m,x,1];Ki(S,S,b);const A=S[3]=Math.max(S[3],1e-6);return S[0]/=A,S[1]/=A,S[2]/=A,S}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new jt(o[0],o[1])}{const o=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new jt(0,o))}}getCameraToCenterDistance(o,u=this.zoom,m=this.worldSize){const x=Ek(o,u,this.width,this.height,1024),b=o.pixelSpaceConversion(this.center.lat,m,x);let S=.5/Math.tan(.5*this._fov)*this.height*b;return this.isOrthographic&&(S=Kr(1,S,o0(this.pitch>=lS?1:this.pitch/lS))),S}getWorldToCameraMatrix(){return this._worldToCamera}getCameraToClipMatrix(){return this._cameraToClip}getFrustum(o){let u=this._frustumCache.get(o);return u||(u=q0.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,o,this.projection.zAxisUnit==="meters"),this._frustumCache.set(o,u)),u}get cameraFrustum(){return this.getFrustum(0)}}const cS=(h,o)=>{if(o<=0||h.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const u=h.transform,m=u.pitch,x=u.isLODDisabled(!1)?60:30;if(m0,uniformValues:{u_cutoff_params:[u._nearZ,u._farZ,(B-u._nearZ)/b,(B-U-u._nearZ)/b]}}};function W$(h,o,u,m){const x=1<({u_matrix:h,u_color:o,u_overlay:0,u_overlay_scale:u}),i_=new Float64Array(16),s_=new Float64Array(16),cne=new Float64Array(16),K$=new Float64Array(16),uS=new Float64Array(16),XDe=new Float64Array(16),une=new Float64Array(16),X0=[0,0,0],PL=[0,0,0],QDe=new Float32Array(16),NL=[0,0,0],JDe=new Float64Array(16),dne=new Float64Array(16),eMe=new Float64Array(16),tMe=[0,0,0],Y$=[];function hne(h){const o=h.cameraWorldSizeForFog/h.worldSize;return ie(eMe,h.worldToFogMatrix,[o,o,1])}function Dk(h,o,u,m){return ee(h,o,u),Lr(m,KLe)||ie(h,h,m),h}function rMe(h,o,u,m){const x=u?o.lightsStyleAabb:h.aabb,b=x?x.min[2]:1/0,S=(x?x.max[2]:-1/0)-b;return[isFinite(b)?b:0,S>0&&isFinite(S)?S:1,m?1:0,0]}function nMe(h,o){return o.featureBuffer?h.partStyleUBO:null}function Z$(h,o,u,m,x,b=null){const S=u.material,A=m.context,{baseColorTexture:I,metallicRoughnessTexture:D}=S.pbrMetallicRoughness,{normalTexture:B,occlusionTexture:U,emissionTexture:q}=S;function K(J,se,ae){if(J&&(h.push(se),A.activeTexture.set(A.gl.TEXTURE0+ae),J.gfxTexture)){const{minFilter:ue,magFilter:ce,wrapS:de,wrapT:xe}=J.sampler;J.gfxTexture.bindExtraParam(ue,ce,de,xe)}}K(I,"HAS_TEXTURE_u_baseColorTexture",_u.BaseColor),K(D,"HAS_TEXTURE_u_metallicRoughnessTexture",_u.MetallicRoughness),K(B,"HAS_TEXTURE_u_normalTexture",_u.Normal),K(U,"HAS_TEXTURE_u_occlusionTexture",_u.Occlusion),K(q,"HAS_TEXTURE_u_emissionTexture",_u.Emission),x&&(x.texture||(x.texture=new dee(m.context,x.image,[x.image.height,x.image.height,x.image.height],A.gl.RGBA8)),A.activeTexture.set(A.gl.TEXTURE0+_u.LUT),x.texture&&x.texture.bind(A.gl.LINEAR,A.gl.CLAMP_TO_EDGE),h.push("APPLY_LUT_ON_GPU")),u.texcoordBuffer&&(h.push("HAS_ATTRIBUTE_a_uv_2f"),o.push(u.texcoordBuffer)),u.colorBuffer&&(h.push(u.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),o.push(u.colorBuffer)),u.normalBuffer&&(h.push("HAS_ATTRIBUTE_a_normal_4n"),o.push(u.normalBuffer)),b&&(h.push("HAS_ATTRIBUTE_a_feature"),o.push(u.featureBuffer)),S.alphaMode!=="OPAQUE"&&S.alphaMode!=="MASK"||h.push("UNPREMULT_TEXTURE_IN_SHADER"),S.defined||h.push("DIFFUSE_SHADED");const X=m.shadowRenderer;X&&(h.push("RENDER_SHADOWS"),X.useNormalOffset&&h.push("NORMAL_OFFSET"))}function X$(h,o,u,m,x,b,S){const A=h.modelOpacity,I=o.context,D=new tc(I.gl.LEQUAL,h.isLightMesh?tc.ReadOnly:tc.ReadWrite,o.depthRangeFor3D),B=o.transform,U=h.mesh,q=U.material,K=o.style.fog;B.projection.zAxisUnit==="pixels"?i_.set(h.nodeModelMatrix):Q(i_,x.zScaleMatrix,h.nodeModelMatrix),Q(i_,x.negCameraPosMatrix,i_),Z(s_,i_),W(s_,s_);const X=u.paint.get("model-color-use-theme").constantOr("default")==="none",J=u.paint.get("model-emissive-strength").constantOr(0),se={defines:[]},ae=[],ue=o.shadowRenderer;ue&&(ue.useNormalOffset=!1),Z$(se.defines,ae,U,o,X?null:u.lut);let ce=null;if(K&&(ce=Q(cne,hne(B),h.nodeModelMatrix),B.projection.name!=="globe")){const Ue=U.aabb.min,Pe=U.aabb.max,[De,Ve]=K.getOpacityForBounds(ce,Ue[0],Ue[1],Pe[0],Pe[1]);se.overrideFog=De>=fk||Ve>=fk}const de=cS(o,u.paint.get("model-cutoff-fade-range"));de.shouldRenderCutoff&&se.defines.push("RENDER_CUTOFF");const xe=o.getOrCreateProgram("model",se),ve=B$(h.worldViewProjection,i_,s_,null,m,A,q,J,void 0,void 0,h.materialOverride,h.modelColor);o.uploadCommonUniforms(I,xe,null,ce,de,h.lightOverrides),o.renderPass!=="shadow"&&ue&&ue.setupShadowsFromMatrix(h.nodeModelMatrix,xe),xe.draw(o,I.gl.TRIANGLES,D,b,S,U.material.doubleSided?rc.disabled:rc.backCCW,ve,u.id,U.vertexBuffer,U.indexBuffer,U.segments,u.paint,B.zoom,void 0,ae)}function fne(h,o){return h.style._importedAsBasemap?"basemap":o.scope}function Q$(h,o,u,m,x,b,S,A,I,D,B){const U=h.transform,q=!!o.isGeometryBloom&&o.isGeometryBloom;if(o.minZoom!==void 0&&h.transform.zoomo.maxZoom||q&&h.renderPass==="shadow")return;const K=U.projection.name==="globe"?hL(u,U):[...u];Q(K,K,o.globalMatrix);const X=Q([],m,K);if(o.meshes)for(const J of o.meshes){const se=A.get(J.material.name);if(se&&se.opacity<=0)continue;if(J.material.alphaMode!=="BLEND"){S.push({mesh:J,depth:0,modelIndex:x,worldViewProjection:X,nodeModelMatrix:K,isLightMesh:q,materialOverride:se,modelOpacity:I,modelColor:D,lightOverrides:B,node:o,modelMatrix:u});continue}const ae=Ar([],J.centroid,X);!U.isOrthographic&&ae[2]<=0||b.push({mesh:J,depth:ae[2],modelIndex:x,worldViewProjection:X,nodeModelMatrix:K,isLightMesh:q,materialOverride:se,modelOpacity:I,modelColor:D,lightOverrides:B,node:o,modelMatrix:u})}if(o.children)for(const J of o.children)Q$(h,J,u,m,x,b,S,A,I,D,B)}function Mk(h,o,u,m,x){const b=u.shadowRenderer;if(!b)return;const S=b.getShadowPassDepthMode(),A=x||b.calculateShadowPassMatrixFromMatrix(o),I=Xre(A);u.getOrCreateProgram("modelDepth").draw(u,u.context.gl.TRIANGLES,S,Mh.disabled,ia.disabled,rc.disabled,I,m.id,h.vertexBuffer,h.indexBuffer,h.segments,m.paint,u.transform.zoom,void 0,void 0)}function mne(h,o,u,m){const x=function(B,U){if(U.footprintDebugMesh)return U.footprintDebugMesh;if(!U.footprint)return null;const q=B.context,K=U.footprint.vertices,X=U.footprint.indices,J=new mm;J.reserve(K.length/2);for(let Ve=0;Ve0?I.findDEMTileFor(A):null,U=B&&B.dem;if(U||(D=0),D===0&&(S.terrainElevationMin=0,S.terrainElevationMax=0),D===S.validForExaggeration&&(D===0||B.tileID===S.validForDEMTile.id&&U._timestamp===S.validForDEMTile.timestamp))return!1;const q=U?Y1.create(I,A,B):null;let K,X;for(const J in S.instancesPerModel){const se=S.instancesPerModel[J];for(let ae=0;aeD&&(D=K.max)}const B=cn(u.x,b,S)-u.x,U=cn(u.y,A,I)-u.y,q=ks(D,o.center.lat)-u.z;return o._zoomFromMercatorZ(Math.sqrt(B*B+U*U+q*q))}function gne(h,o,u,m,x,b,S,A){const I=h.context,D=h.renderPass==="shadow",B=h.shadowRenderer,U=D&&B?B.getShadowPassDepthMode():new tc(I.gl.LEQUAL,tc.ReadWrite,h.depthRangeFor3D),q=h.isTileAffectedByFog(S),K=h.transform.projection.name==="globe";if(m.meshes)for(const X of m.meshes){const J=K?[]:["MODEL_POSITION_ON_GPU"],se=[];let ae,ue,ce;const de=!K&&x.instancedDataArray.length>20;de&&J.push("INSTANCED_ARRAYS");const xe=cS(h,o.paint.get("model-cutoff-fade-range"));if(xe.shouldRenderCutoff&&J.push("RENDER_CUTOFF"),D&&B)ae=h.getOrCreateProgram("modelDepth",{defines:J}),ue=Xre(A.shadowTileMatrix,A.shadowTileMatrix,m.globalMatrix),ce=ia.disabled;else{Z$(J,se,X,h,o.paint.get("model-color-use-theme").constantOr("default")==="none"?null:o.lut),ae=h.getOrCreateProgram("model",{defines:J,overrideFog:q});const Ue=X.material,Pe=o.paint.get("model-opacity").constantOr(1),De=o.paint.get("model-emissive-strength").constantOr(0);ue=B$(S.expandedProjMatrix,m.globalMatrix,QDe,null,u,Pe,Ue,De,b),B&&(A.shadowUniformsInitialized?ae.setShadowUniformValues(I,B.getShadowUniformValues()):(B.setupShadows(S.toUnwrapped(),ae,"model-tile"),A.shadowUniformsInitialized=!0)),ce=xe.shouldRenderCutoff||Pe<1||Ue.alphaMode!=="OPAQUE"?ia.alphaBlended:ia.unblended}h.uploadCommonUniforms(I,ae,S.toUnwrapped(),null,xe);const ve=X.material.doubleSided?rc.disabled:rc.backCCW;if(de)se.push(x.instancedDataBuffer),ae.draw(h,I.gl.TRIANGLES,U,Mh.disabled,ce,ve,ue,o.id,X.vertexBuffer,X.indexBuffer,X.segments,o.paint,h.transform.zoom,void 0,se,x.instancedDataArray.length);else{const Ue=D?"u_instance":"u_normal_matrix";for(let Pe=0;Pe0)if(h.targetLod<0)h.targetLod=o>m?1:0;else{const S=x>0?u/1e3/x:1;h.targetLod=cn(o>m?h.targetLod+S:h.targetLod-S,0,1)}else h.targetLod=0}function cMe(h,o,u,m){if(!u.modelManager)return!0;const x=u.modelManager;if(!u.shadowRenderer)return!0;const b=u.shadowRenderer,S=o.aabb;let A=!0,I=h.maxHeight;if(I===0){let B=0;for(const U in h.instancesPerModel){const q=x.getModel(U,m);q?B=Math.max(B,Math.max(Math.max(q.aabb.max[0],q.aabb.max[1]),q.aabb.max[2])):A=!1}I=h.maxScale*B*1.41+h.maxVerticalOffset,A&&(h.maxHeight=I)}S.max[2]=I,S.min[2]+=h.terrainElevationMin,S.max[2]+=h.terrainElevationMax,Ar(S.min,S.min,o.tileMatrix),Ar(S.max,S.max,o.tileMatrix);const D=S.intersects(b.getCurrentCascadeFrustum());return u.currentShadowCascade===0&&(h.isInsideFirstShadowMapFrustum=D===2),D===0}function uMe(h,o){const u=h.uniformValues.u_cutoff_params[0],m=h.uniformValues.u_cutoff_params[1],x=h.uniformValues.u_cutoff_params[2],b=h.uniformValues.u_cutoff_params[3];return m===u||b===x?1:cn(((o-u)/(m-u)-x)/(b-x),0,1)}function dMe(h,o,u,m){if(o.pitch<20)return 1;const x=Q(JDe,o.getWorldToCameraMatrix(),h),b=u.min[2];let S=1/0,A=0,I=-1/0,D=0;for(let se=0;se<4;se++){const ae=se<2?u.min[0]:u.max[0],ue=se===1||se===2?u.max[1]:u.min[1],ce=x[1]*ae+x[5]*ue+x[9]*b+x[13],de=x[2]*ae+x[6]*ue+x[10]*b+x[14];ceI&&(I=ce,D=de)}const B=cn(m[0],0,1),U=100*o.pixelsPerMeter*cn(m[1],0,1),q=cn(m[2],0,1),K=Kr(S,I,B),X=-Kr(A,D,B)*Math.tan(.5*o.fovX);if(U===0)return K<-Math.abs(X)?q:1;const J=cn(Kr(1,q,(-Math.abs(X)-K)/U),q,1);return Kr(1,J,cn((o.pitch-20)/20,0,1))}var J$=` #define EPSILON 0.0000001 #define PI 3.141592653589793 #define storage_depth_to_native_ndc_z(z01) ((z01)*2.0-1.0) #define native_ndc_z_to_storage_depth(ndc_z) ((ndc_z)*0.5+0.5) #define native_clip_z_to_cutoff_depth(clip_z,clip_w) (clip_z) #define native_depth_epsilon(eps) (eps) #define depth_range_to_native_ndc_z(z01,unpack) ((z01)*(unpack).x+(unpack).y) #define bottom_left_to_native_uv(uv) (uv) #define native_cubemap_direction(dir) vec3((dir).x,-(dir).y,(dir).z) #define ndc_xy_to_framebuffer_uv(ndc_xy) ((ndc_xy)*0.5+0.5) #define ndc_xy_to_depth_texture_uv(ndc_xy) bottom_left_to_native_uv((ndc_xy)*0.5+0.5) #ifdef RENDER_CUTOFF float cutoff_opacity(vec4 cutoff_params,float depth) {float near=cutoff_params.x;float far=cutoff_params.y;float cutoffStart=cutoff_params.z;float cutoffEnd=cutoff_params.w;float linearDepth=(depth-near)/(far-near);return clamp((linearDepth-cutoffStart)/(cutoffEnd-cutoffStart),0.0,1.0);} #endif`,yne=` #define fragcoord_to_bottom_left_uv(frag,size) ((frag)/(size)) #define fragcoord_to_ndc_y(fragY,invY) ((fragY)*(invY)*2.0-1.0) #define native_window_space_normal(fdx,fdy) (normalize(cross((fdx),(fdy)))*-1.0) #define fragcoord_to_framebuffer_uv(frag,inv) ((frag)*(inv)) #define native_window_space_tangent(axis) (axis) #define native_tbn_view_dir(position) (normalize(-(position))) #ifdef DUAL_SOURCE_BLENDING layout(location=0,index=0) out vec4 glFragColor;layout(location=0,index=1) out vec4 glFragColorSrc1; #elif defined(FLOAT_RENDER_TARGET) layout(location=0) out highp vec4 glFragColor; #else layout(location=0) out vec4 glFragColor; #endif #ifdef USE_MRT1 layout(location=1) out vec4 out_Target1; #endif highp float unpack_depth(highp vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return storage_depth_to_native_ndc_z(dot(rgba_depth,bit_shift));}highp vec4 pack_depth(highp float ndc_z) {highp float depth=native_ndc_z_to_storage_depth(ndc_z);const highp vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const highp vec4 bit_mask =vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);highp vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}const float DITHER_THRESHOLDS[16]=float[16]( 1.0/17.0, 9.0/17.0, 3.0/17.0,11.0/17.0,13.0/17.0, 5.0/17.0,15.0/17.0, 7.0/17.0,4.0/17.0,12.0/17.0, 2.0/17.0,10.0/17.0,16.0/17.0, 8.0/17.0,14.0/17.0, 6.0/17.0 );int viewport_dither_index(vec2 fragCoordXY) {return (int(fragCoordXY.x) % 4)*4+(int(fragCoordXY.y) % 4);} #ifdef DEBUG_WIREFRAME #define HANDLE_WIREFRAME_DEBUG \\ glFragColor=vec4(0.7,0.0,0.0,0.7); \\ gl_FragDepth=gl_FragCoord.z-0.0001; #else #define HANDLE_WIREFRAME_DEBUG #endif #ifdef RENDER_CUTOFF uniform highp vec4 u_cutoff_params;in float v_cutoff_opacity; #endif vec4 textureLodCustom(sampler2D image,highp vec2 pos,highp vec2 lod_coord) {highp vec2 size=vec2(textureSize(image,0));highp vec2 dx=dFdx(lod_coord.xy*size);highp vec2 dy=dFdy(lod_coord.xy*size);highp float delta_max_sqr=max(dot(dx,dx),dot(dy,dy));highp float lod=0.5*log2(delta_max_sqr);return textureLod(image,pos,lod);}vec4 premultiplyColor(vec3 nonPremultipliedColor,float a) {return vec4(nonPremultipliedColor*a,a);}vec3 unpremultiplyColor(vec4 premultipliedColor) {if (premultipliedColor.a > 0.0) {return premultipliedColor.rgb/premultipliedColor.a;}return premultipliedColor.rgb;}vec3 applyLUT(highp sampler3D lut,vec3 col) {vec3 size=vec3(textureSize(lut,0));vec3 uvw=(col.rbg*float(size-1.0)+0.5)/size;return texture(lut,uvw).rgb;}vec4 applyLUT(highp sampler3D lut,vec4 premultipliedColor) {return premultiplyColor(applyLUT(lut,unpremultiplyColor(premultipliedColor)),premultipliedColor.a);}void storeEmissiveColor(vec4 color,float emissiveStrength) { #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissiveStrength); #else #ifdef USE_MRT1 #ifdef USE_MRT1_RGBA out_Target1=vec4(color.rgb*emissiveStrength,color.a); #else out_Target1=vec4(emissiveStrength*color.a,0.0,0.0,glFragColor.a); #endif #endif #endif }`,xne=` #define EXTENT 8192.0 #define RAD_TO_DEG 180.0/PI #define DEG_TO_RAD PI/180.0 #define GLOBE_RADIUS EXTENT/PI/2.0 float wrap(float n,float min,float max) {float d=max-min;float w=mod(mod(n-min,d)+d,d)+min;return (w==min) ? max : w;} #ifdef PROJECTION_GLOBE_VIEW vec3 mercator_tile_position(mat4 matrix,vec2 tile_anchor,vec3 tile_id,vec2 mercator_center) { #ifndef PROJECTED_POS_ON_VIEWPORT float tiles=tile_id.z;vec2 mercator=(tile_anchor/EXTENT+tile_id.xy)/tiles;mercator-=mercator_center;mercator.x=wrap(mercator.x,-0.5,0.5);vec4 mercator_tile=vec4(mercator.xy*EXTENT,EXTENT/(2.0*PI),1.0);mercator_tile=matrix*mercator_tile;return mercator_tile.xyz; #else return vec3(0.0); #endif }vec3 mix_globe_mercator(vec3 globe,vec3 mercator,float t) {return mix(globe,mercator,t);}mat3 globe_mercator_surface_vectors(vec3 pos_normal,vec3 up_dir,float zoom_transition) {vec3 normal=zoom_transition==0.0 ? pos_normal : normalize(mix(pos_normal,up_dir,zoom_transition));vec3 xAxis=normalize(vec3(normal.z,0.0,-normal.x));vec3 yAxis=normalize(cross(normal,xAxis));return mat3(xAxis,yAxis,normal);} #endif vec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec4 decode_color(const vec2 encodedColor) {return vec4( unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0 );}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const vec2 units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (units_to_pixels*pos+offset)/pattern_size;}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {return get_pattern_pos(pixel_coord_upper,pixel_coord_lower,pattern_size,vec2(tile_units_to_pixels),pos);}float mercatorXfromLng(float lng) {return (180.0+lng)/360.0;}float mercatorYfromLat(float lat) {return (180.0-(RAD_TO_DEG*log(tan(PI/4.0+lat/2.0*DEG_TO_RAD))))/360.0;}vec3 latLngToECEF(vec2 latLng) {latLng=DEG_TO_RAD*latLng;float cosLat=cos(latLng[0]);float sinLat=sin(latLng[0]);float cosLng=cos(latLng[1]);float sinLng=sin(latLng[1]);float sx=cosLat*sinLng*GLOBE_RADIUS;float sy=-sinLat*GLOBE_RADIUS;float sz=cosLat*cosLng*GLOBE_RADIUS;return vec3(sx,sy,sz);} #ifdef RENDER_CUTOFF uniform vec4 u_cutoff_params;out float v_cutoff_opacity; #endif const vec4 AWAY=vec4(-1000.0,-1000.0,-1000.0,1);const float skirtOffset=24575.0;vec3 decomposeToPosAndSkirt(ivec2 posWithComposedSkirt) {float skirt=float(float(posWithComposedSkirt.x) >=skirtOffset);vec2 pos=vec2(posWithComposedSkirt)-vec2(skirt*skirtOffset,0.0);return vec3(pos,skirt);} #define GET_ATTRIBUTE_float(attrib,matInfo,attrib_id) attrib #define GET_ATTRIBUTE_vec4(attrib,matInfo,attrib_id) attrib #define GET_ATTRIBUTE_vec2(attrib,matInfo,attrib_id) attrib #define DECLARE_MATERIAL_TABLE_INFO `,_ne="in highp vec3 a_pos_3f;uniform lowp mat4 u_matrix;out highp vec3 v_uv;void main() {const mat3 half_neg_pi_around_x=mat3(1.0,0.0, 0.0,0.0,0.0,-1.0,0.0,1.0, 0.0);v_uv=half_neg_pi_around_x*a_pos_3f;vec4 pos=u_matrix*vec4(a_pos_3f,1.0);gl_Position=pos.xyww;}",vne=` #define ELEVATION_SCALE 7.0 #define ELEVATION_OFFSET 450.0 #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_tl_up;uniform vec3 u_tile_tr_up;uniform vec3 u_tile_br_up;uniform vec3 u_tile_bl_up;uniform float u_tile_up_scale; #endif vec3 elevationVector(vec2 pos) { #ifdef PROJECTION_GLOBE_VIEW vec2 uv=pos/EXTENT;vec3 up=normalize(mix( mix(u_tile_tl_up,u_tile_tr_up,uv.xxx),mix(u_tile_bl_up,u_tile_br_up,uv.xxx),uv.yyy));return up*u_tile_up_scale; #else return vec3(0,0,1); #endif } #ifdef TERRAIN uniform highp sampler2D u_dem; #ifdef TERRAIN_VERTEX_MORPHING uniform highp sampler2D u_dem_prev; #endif uniform vec2 u_dem_tl;uniform vec2 u_dem_tl_prev;uniform float u_dem_scale;uniform float u_dem_scale_prev;uniform float u_dem_size;uniform float u_dem_lerp;uniform float u_exaggeration;uniform float u_meter_to_dem;uniform mat4 u_label_plane_matrix_inv;vec4 tileUvToDemSample(vec2 uv,float dem_size,float dem_scale,vec2 dem_tl) {vec2 pos=dem_size*(uv*dem_scale+dem_tl)+1.0;vec2 f=fract(pos);return vec4((pos-f+0.5)/(dem_size+2.0),f);}float currentElevation(vec2 apos) { #ifdef TERRAIN_DEM_FLOAT_FORMAT vec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale+u_dem_tl)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem,pos).r; #else float dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale,u_dem_tl);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(dd,0)).r;float bl=texture(u_dem,pos+vec2(0,dd)).r;float br=texture(u_dem,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y); #endif } #ifdef TERRAIN_VERTEX_MORPHING float prevElevation(vec2 apos) { #ifdef TERRAIN_DEM_FLOAT_FORMAT vec2 pos=(u_dem_size*(apos/8192.0*u_dem_scale_prev+u_dem_tl_prev)+1.5)/(u_dem_size+2.0);return u_exaggeration*texture(u_dem_prev,pos).r; #else float dd=1.0/(u_dem_size+2.0);vec4 r=tileUvToDemSample(apos/8192.0,u_dem_size,u_dem_scale_prev,u_dem_tl_prev);vec2 pos=r.xy;vec2 f=r.zw;float tl=texture(u_dem_prev,pos).r;float tr=texture(u_dem_prev,pos+vec2(dd,0)).r;float bl=texture(u_dem_prev,pos+vec2(0,dd)).r;float br=texture(u_dem_prev,pos+vec2(dd,dd)).r;return u_exaggeration*mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y); #endif } #endif vec4 fourSample(vec2 pos,vec2 off) {float tl=texture(u_dem,pos).r;float tr=texture(u_dem,pos+vec2(off.x,0.0)).r;float bl=texture(u_dem,pos+vec2(0.0,off.y)).r;float br=texture(u_dem,pos+off).r;return vec4(tl,tr,bl,br);}float flatElevation(vec2 pack) {vec2 apos=floor(pack/8.0);vec2 span=10.0*(pack-apos*8.0);vec2 uvTex=(apos-vec2(1.0,1.0))/8190.0;float size=u_dem_size+2.0;float dd=1.0/size;vec2 pos=u_dem_size*(uvTex*u_dem_scale+u_dem_tl)+1.0;vec2 f=fract(pos);pos=(pos-f+0.5)*dd;vec4 h=fourSample(pos,vec2(dd));float z=mix(mix(h.x,h.y,f.x),mix(h.z,h.w,f.x),f.y);vec2 w=floor(0.5*(span*u_meter_to_dem-1.0));vec2 d=dd*w;h=fourSample(pos-d,2.0*d+vec2(dd));vec4 diff=abs(h.xzxy-h.ywzw);vec2 slope=min(vec2(0.25),u_meter_to_dem*0.5*(diff.xz+diff.yw)/(2.0*w+vec2(1.0)));vec2 fix=slope*span;float base=z+max(fix.x,fix.y);return u_exaggeration*base;}float elevationFromUint16(float word) {return u_exaggeration*(word/ELEVATION_SCALE-ELEVATION_OFFSET);} #endif float elevation(vec2 apos) { #ifdef TERRAIN #ifdef TERRAIN_VERTEX_MORPHING float nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp); #else return currentElevation(apos); #endif #else return 0.0; #endif } #ifdef DEPTH_OCCLUSION uniform highp sampler2D u_depth;uniform highp vec2 u_depth_size_inv;uniform highp vec2 u_depth_range_unpack;uniform highp float u_occluder_half_size;uniform highp float u_occlusion_depth_offset; #ifdef DEPTH_D24 float unpack_depth(float depth) {return depth_range_to_native_ndc_z(depth,u_depth_range_unpack);}vec4 unpack_depth4(vec4 depth) {return depth_range_to_native_ndc_z(depth,u_depth_range_unpack);} #else highp float unpack_depth_rgba(vec4 rgba_depth) {const highp vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return storage_depth_to_native_ndc_z(dot(rgba_depth,bit_shift));} #endif highp vec2 occlusionDepthUv(highp vec2 ndc_xy) {return ndc_xy_to_depth_texture_uv(ndc_xy);} #define occlusion_depth_bias native_depth_epsilon(u_occlusion_depth_offset) #define occlusion_fade_slope(native_delta) (300.0*(native_delta)/native_depth_epsilon(1.0)) bool isOccluded(vec4 frag) {vec3 coord=frag.xyz/frag.w;highp vec2 uv=occlusionDepthUv(coord.xy); #ifdef DEPTH_D24 float depth=unpack_depth(texture(u_depth,uv).r); #else float depth=unpack_depth_rgba(texture(u_depth,uv)); #endif return coord.z+occlusion_depth_bias > depth;}highp vec4 getCornerDepths(vec2 coord) {highp vec3 df=vec3(u_occluder_half_size*u_depth_size_inv,0.0);highp vec2 uv=occlusionDepthUv(coord); #ifdef DEPTH_D24 highp vec4 depth=vec4( texture(u_depth,uv-df.xz).r,texture(u_depth,uv+df.xz).r,texture(u_depth,uv-df.zy).r,texture(u_depth,uv+df.zy).r );depth=unpack_depth4(depth); #else highp vec4 depth=vec4( unpack_depth_rgba(texture(u_depth,uv-df.xz)),unpack_depth_rgba(texture(u_depth,uv+df.xz)),unpack_depth_rgba(texture(u_depth,uv-df.zy)),unpack_depth_rgba(texture(u_depth,uv+df.zy)) ); #endif return depth;}highp float occlusionFadeMultiSample(vec4 frag) {highp vec3 coord=frag.xyz/frag.w;highp vec2 uv=occlusionDepthUv(coord.xy);int NX=3;int NY=4;highp vec2 df=u_occluder_half_size*u_depth_size_inv;highp vec2 oneStep=2.0*u_occluder_half_size*u_depth_size_inv/vec2(NX-1,NY-1);highp float res=0.0;for (int y=0; y < NY;++y) {for (int x=0; x < NX;++x) { #ifdef DEPTH_D24 highp float depth=unpack_depth(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y)).r); #else highp float depth=unpack_depth_rgba(texture(u_depth,uv-df+vec2(float(x)*oneStep.x,float(y)*oneStep.y))); #endif res+=1.0-clamp(occlusion_fade_slope(coord.z+occlusion_depth_bias-depth),0.0,1.0);}}res=clamp(2.0*res/float(NX*NY)-0.5,0.0,1.0);return res;}highp float occlusionFade(vec4 frag) {highp vec3 coord=frag.xyz/frag.w;highp vec4 depth=getCornerDepths(coord.xy);return dot(vec4(0.25),vec4(1.0)-clamp(occlusion_fade_slope(vec4(coord.z+occlusion_depth_bias)-depth),0.0,1.0));} #else bool isOccluded(vec4 frag) { return false; }highp float occlusionFade(vec4 frag) { return 1.0; }highp float occlusionFadeMultiSample(vec4 frag) { return 1.0; } #endif`,bne=`#ifdef FOG uniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump mat4 u_fog_matrix;out vec3 v_fog_pos;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}vec3 fog_position(vec3 pos) {return (u_fog_matrix*vec4(pos,1.0)).xyz;}vec3 fog_position(vec2 pos) {return fog_position(vec3(pos,0.0));}float fog(vec3 pos) {float depth=length(pos);float opacity=fog_opacity(fog_range(depth));return opacity*fog_horizon_blending(pos/depth);} #endif`,wne=`#ifdef FOG uniform mediump vec4 u_fog_color;uniform mediump vec2 u_fog_range;uniform mediump float u_fog_horizon_blend;uniform mediump vec2 u_fog_vertical_limit;uniform mediump float u_fog_temporal_offset;in vec3 v_fog_pos;uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform highp vec2 u_viewport;uniform float u_globe_transition;uniform int u_is_globe;float fog_range(float depth) {return (depth-u_fog_range[0])/(u_fog_range[1]-u_fog_range[0]);}float fog_horizon_blending(vec3 camera_dir) {float t=max(0.0,camera_dir.z/u_fog_horizon_blend);return u_fog_color.a*exp(-3.0*t*t);}float fog_opacity(float t) {const float decay=6.0;float falloff=1.0-min(1.0,exp(-decay*t));falloff*=falloff*falloff;return u_fog_color.a*min(1.0,1.00747*falloff);}float globe_glow_progress() {highp vec2 uv=fragcoord_to_bottom_left_uv(gl_FragCoord.xy,u_viewport);highp vec3 ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float sdf=length(closest_point-u_globe_pos)/u_globe_radius;return sdf+PI*0.5;}float fog_opacity(vec3 pos) {float depth=length(pos);return fog_opacity(fog_range(depth));}vec3 fog_apply(vec3 color,vec3 pos,float opacity_limit) {float depth=length(pos);float opacity;if (u_is_globe==1) {float glow_progress=globe_glow_progress();float t=mix(glow_progress,depth,u_globe_transition);opacity=fog_opacity(fog_range(t));} else {opacity=fog_opacity(fog_range(depth));opacity*=fog_horizon_blending(pos/depth);}return mix(color,u_fog_color.rgb,min(opacity,opacity_limit));}vec3 fog_apply(vec3 color,vec3 pos) {return fog_apply(color,pos,1.0);}vec4 fog_apply_from_vert(vec4 color,float fog_opac) {float alpha=EPSILON+color.a;color.rgb=mix(color.rgb/alpha,u_fog_color.rgb,fog_opac)*alpha;return color;}vec3 fog_apply_sky_gradient(vec3 camera_ray,vec3 sky_color) {float horizon_blend=fog_horizon_blending(normalize(camera_ray));return mix(sky_color,u_fog_color.rgb,horizon_blend);}vec4 fog_apply_premultiplied(vec4 color,vec3 pos) {float alpha=EPSILON+color.a;color.rgb=fog_apply(color.rgb/alpha,pos)*alpha;return color;}vec4 fog_apply_premultiplied(vec4 color,vec3 pos,float heightMeters) {float verticalProgress=(u_fog_vertical_limit.x > 0.0 || u_fog_vertical_limit.y > 0.0) ? smoothstep(u_fog_vertical_limit.x,u_fog_vertical_limit.y,heightMeters) : 0.0;float opacityLimit=1.0-smoothstep(0.9,1.0,fog_opacity(pos));return mix(fog_apply_premultiplied(color,pos),color,min(verticalProgress,opacityLimit));}vec3 fog_dither(vec3 color) {return color;}vec4 fog_dither(vec4 color) {return vec4(fog_dither(color.rgb),color.a);} #endif`,Sne=` #ifndef MAX_UBO_SIZE_VEC4 #define MAX_UBO_SIZE_VEC4 1024u #endif float zoomFactor(float zm,float zM,float zoomFraction) {if (zm==zM) return zoomFraction-zm >=0.0 ? 1.0 : 0.0;return clamp((zoomFraction-zm)/(zM-zm),0.0,1.0);}`,e6=` #ifdef LIGHTING_3D_MODE uniform mediump vec3 u_lighting_ambient_color;uniform mediump vec3 u_lighting_directional_dir;uniform mediump vec3 u_lighting_directional_color;uniform mediump vec3 u_ground_radiance;float calculate_ambient_directional_factor(vec3 normal) {float NdotL=dot(normal,u_lighting_directional_dir);const float factor_reduction_max=0.3;float dir_luminance=dot(u_lighting_directional_color,vec3(0.2126,0.7152,0.0722));float directional_factor_min=1.0-factor_reduction_max*min(dir_luminance,1.0);float ambient_directional_factor=mix(directional_factor_min,1.0,min((NdotL+1.0),1.0));const float vertical_factor_min=0.92;float vertical_factor=mix(vertical_factor_min,1.0,normal.z*0.5+0.5);return vertical_factor*ambient_directional_factor;}vec3 linearProduct(vec3 srgbIn,vec3 k) {return srgbIn*pow(k,vec3(1./2.2));}vec3 apply_lighting(vec3 color,vec3 normal,float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return linearProduct(color,ambient_contrib+directional_contrib);}vec4 apply_lighting(vec4 color,vec3 normal,float dir_factor) {return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting(vec3 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return apply_lighting(color.rgb,normal,dir_factor);}vec4 apply_lighting(vec4 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting_ground(vec3 color) {return color*u_ground_radiance;}vec4 apply_lighting_ground(vec4 color) {return vec4(apply_lighting_ground(color.rgb),color.a);}float calculate_NdotL(vec3 normal) {const float ext=0.70710678118;return (clamp(dot(normal,u_lighting_directional_dir),-ext,1.0)+ext)/(1.0+ext);}vec4 apply_lighting_with_emission_ground(vec4 color,float emissive_strength) {return mix(apply_lighting_ground(color),color,emissive_strength);}vec3 compute_flood_lighting(vec3 flood_light_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=flood_light_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);float occlusion_ramp=smoothstep(0.0,0.2,1.0-occlusion);return mix(fully_occluded_color,flood_light_color,occlusion_ramp);}vec3 compute_emissive_draped(vec3 unlit_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=unlit_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);return mix(fully_occluded_color,unlit_color,1.0-occlusion);} #endif`,Ene=`#ifdef RASTER_ARRAY uniform highp sampler2D u_image0;uniform sampler2D u_image1;const vec4 NODATA=vec4(1);ivec4 _raTexLinearCoord(highp vec2 texCoord,highp vec2 texResolution,out highp vec2 fxy) {texCoord=texCoord*texResolution-0.5;fxy=fract(texCoord);texCoord-=fxy;return ivec4(texCoord.xxyy+vec2(1.5,0.5).xyxy);}vec2 _raTexLinearMix(highp vec2 fxy,highp vec4 colorMix,highp float colorOffset,highp vec4 t00,highp vec4 t10,highp vec4 t01,highp vec4 t11) {vec2 c00=t00==NODATA ? vec2(0) : vec2(colorOffset+dot(t00,colorMix),1);vec2 c10=t10==NODATA ? vec2(0) : vec2(colorOffset+dot(t10,colorMix),1);vec2 c01=t01==NODATA ? vec2(0) : vec2(colorOffset+dot(t01,colorMix),1);vec2 c11=t11==NODATA ? vec2(0) : vec2(colorOffset+dot(t11,colorMix),1);return mix(mix(c01,c11,fxy.x),mix(c00,c10,fxy.x),fxy.y);}vec2 raTexture2D_image0_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;ivec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texelFetch(u_image0,c.yz,0),texelFetch(u_image0,c.xz,0),texelFetch(u_image0,c.yw,0),texelFetch(u_image0,c.xw,0) );}vec2 raTexture2D_image1_linear(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec2 fxy;ivec4 c=_raTexLinearCoord(texCoord,texResolution,fxy);return _raTexLinearMix(fxy,colorMix,colorOffset,texelFetch(u_image1,c.yz,0),texelFetch(u_image1,c.xz,0),texelFetch(u_image1,c.yw,0),texelFetch(u_image1,c.xw,0) );}vec2 raTexture2D_image0_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texelFetch(u_image0,ivec2(texCoord*texResolution),0);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);}vec2 raTexture2D_image1_nearest(highp vec2 texCoord,highp vec2 texResolution,highp vec4 colorMix,highp float colorOffset) {vec4 t=texelFetch(u_image1,ivec2(texCoord*texResolution),0);return t==NODATA ? vec2(0) : vec2(colorOffset+dot(t,colorMix),1);} #endif`,Tne=`#ifdef RENDER_SHADOWS uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_normal_offset;vec3 shadow_normal_offset(vec3 normal) {float tileInMeters=u_shadow_normal_offset[0];vec3 n=vec3(-normal.xy,tileInMeters*normal.z);float dotScale=min(1.0-dot(normal,u_shadow_direction),1.0)*0.5+0.5;return n*dotScale;}vec3 shadow_normal_offset_model(vec3 normal) {vec3 transformed_normal=vec3(-normal.xy,normal.z);float NDotL=dot(normalize(transformed_normal),u_shadow_direction);float dotScale=min(1.0-NDotL,1.0)*0.5+0.5;return normal*dotScale;}float shadow_normal_offset_multiplier0() {return u_shadow_normal_offset[1];}float shadow_normal_offset_multiplier1() {return u_shadow_normal_offset[2];} #endif`,Ane=`#ifdef RENDER_SHADOWS precision highp sampler2DShadow;uniform sampler2DShadow u_shadowmap_0;uniform sampler2DShadow u_shadowmap_1;uniform float u_shadow_intensity;uniform float u_shadow_map_resolution;uniform float u_shadow_texel_size;uniform highp vec3 u_shadow_normal_offset;uniform vec2 u_fade_range;uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_bias;highp vec2 shadow_map_ndc_to_uv(highp vec2 ndc_xy) {return ndc_xy*0.5+0.5;}highp vec3 shadow_map_ndc_to_sample_space(highp vec3 ndc) {return vec3(shadow_map_ndc_to_uv(ndc.xy),native_ndc_z_to_storage_depth(ndc.z));}float shadow_sample(sampler2DShadow shadowmap,highp vec3 pos,highp float bias) {highp vec3 coord=vec3(shadow_map_ndc_to_uv(pos.xy),native_ndc_z_to_storage_depth(pos.z)-bias);return texture(shadowmap,coord);}float shadow_occlusion(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,highp float bias) {light_view_pos0.xyz/=light_view_pos0.w; #ifdef SHADOWS_SINGLE_CASCADE vec2 abs_bounds=abs(light_view_pos0.xy);if (abs_bounds.x >=1.0 || abs_bounds.y >=1.0) {return 0.0;}return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias); #else light_view_pos1.xyz/=light_view_pos1.w;vec4 abs_bounds=abs(vec4(light_view_pos0.xy,light_view_pos1.xy));if (abs_bounds.x < 1.0 && abs_bounds.y < 1.0) {return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias);}if (abs_bounds.z >=1.0 || abs_bounds.w >=1.0) {return 0.0;}float occlusion1=shadow_sample(u_shadowmap_1,light_view_pos1.xyz,bias);return clamp(mix(occlusion1,0.0,smoothstep(u_fade_range.x,u_fade_range.y,view_depth)),0.0,1.0); #endif }highp float calculate_shadow_bias(float NDotL) { #ifdef NORMAL_OFFSET return 0.5*u_shadow_bias.x; #else return 0.5*(u_shadow_bias.x+clamp(u_shadow_bias.y*tan(acos(NDotL)),0.0,u_shadow_bias.z)); #endif }float shadowed_light_factor_normal(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_opacity(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,float shadow_opacity) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias)*shadow_opacity;return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_unbiased(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}highp vec2 compute_receiver_plane_depth_bias(highp vec3 pos_dx,highp vec3 pos_dy) {highp vec2 biasUV=vec2( pos_dy.y*pos_dx.z-pos_dx.y*pos_dy.z,pos_dx.x*pos_dy.z-pos_dy.x*pos_dx.z);biasUV*=1.0/((pos_dx.x*pos_dy.y)-(pos_dx.y*pos_dy.x));return biasUV;}float shadowed_light_factor_plane_bias(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {highp vec3 light_view_pos0_xyz=shadow_map_ndc_to_sample_space(light_view_pos0.xyz/light_view_pos0.w);highp vec3 light_view_pos0_ddx=dFdx(light_view_pos0_xyz);highp vec3 light_view_pos0_ddy=dFdy(light_view_pos0_xyz);highp vec2 plane_depth_bias=compute_receiver_plane_depth_bias(light_view_pos0_ddx,light_view_pos0_ddy);highp float bias=dot(vec2(u_shadow_texel_size,u_shadow_texel_size),plane_depth_bias)+0.0001;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadowed_light_factor(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadow_occlusion(float ndotl,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=calculate_shadow_bias(ndotl);return shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);} #endif`;const kne=/^#include\s+"([^"]+)"\s*\r?\n/gm,Ine=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,hMe=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,fMe=new Set(["ifdef","ifndef","elif","if","defined"]),RL=new Set;dS(J$,RL),dS(xne,RL),dS(yne,RL);const jne={"_prelude_fog.vertex.glsl":bne,"_prelude_terrain.vertex.glsl":vne,"_prelude_shadow.vertex.glsl":Tne,"_prelude_material_table.vertex.glsl":"","_prelude_fog.fragment.glsl":wne,"_prelude_shadow.fragment.glsl":Ane,"_prelude_lighting.glsl":e6,"_prelude_ubo_properties.glsl":Sne,"_prelude_raster_array.glsl":Ene,"_prelude_indicator_cutout.fragment.glsl":` vec4 applyCutout(vec4 color,float height) {return color;}`,"_prelude_feature_cutout.fragment.glsl":`// feature cutout (gl-native only) `,"_prelude_feature_cutout.vertex.glsl":`// feature cutout (gl-native only) `},LL={},Cne="precision highp float;",Pne="precision mediump float;",Nne=` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,Rne={preludeTerrain:Zi("",vne),preludeUBOProperties:Zi("",Sne),preludeFog:Zi(wne,bne),preludeShadow:Zi(Ane,Tne),preludeRasterArray:Zi(Ene,""),preludeLighting:Zi(e6,e6),preludePrecisionQualifiers:Zi(Pne,Cne),prelude:Zi(yne,xne),preludeExtensions:Zi(Nne,"")},mMe=[Nne,Pne,J$,Rne.prelude.fragmentSource].join(` `),pMe=[Cne,J$,Rne.prelude.vertexSource].join(` `);var gMe={background:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" uniform vec4 u_color;uniform float u_opacity;uniform mediump float u_emissive_strength; #ifdef LIGHTING_3D_MODE in vec4 v_color; #endif void main() {vec4 out_color; #ifdef LIGHTING_3D_MODE out_color=v_color; #else out_color=u_color; #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*u_opacity;storeEmissiveColor(glFragColor,u_emissive_strength); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_lighting.glsl" in ivec2 a_pos;uniform mat4 u_matrix;uniform mediump float u_emissive_strength; #ifdef LIGHTING_3D_MODE uniform mediump vec4 u_color;out vec4 v_color; #endif void main() {gl_Position=u_matrix*vec4(a_pos,0,1); #ifdef LIGHTING_3D_MODE v_color=apply_lighting_with_emission_ground(u_color,u_emissive_strength); #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),backgroundPattern:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform vec2 u_pattern_tl;uniform vec2 u_pattern_br;uniform vec2 u_texsize;uniform float u_opacity;uniform float u_emissive_strength;uniform sampler2D u_image;in highp vec2 v_pos;void main() {highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(u_pattern_tl/u_texsize,u_pattern_br/u_texsize,imagecoord);vec4 out_color=textureLodCustom(u_image,pos,v_pos); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*u_opacity;storeEmissiveColor(glFragColor,u_emissive_strength); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pattern_size;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec2 u_pattern_units_to_pixels;in ivec2 a_pos;out highp vec2 v_pos;void main() {vec2 pos=vec2(a_pos);gl_Position=u_matrix*vec4(pos,0,1);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_pattern_size,u_pattern_units_to_pixels,pos); #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),circle:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" in vec3 v_data;in float v_visibility; #pragma mapbox: define highp vec4 color #pragma mapbox: define mediump float radius #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define highp vec4 stroke_color #pragma mapbox: define mediump float stroke_width #pragma mapbox: define lowp float stroke_opacity uniform float u_emissive_strength;void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize mediump float radius #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp vec4 stroke_color #pragma mapbox: initialize mediump float stroke_width #pragma mapbox: initialize lowp float stroke_opacity vec2 extrude=v_data.xy;float blur_positive=blur < 0.0 ? 0.0 : 1.0;lowp float antialiasblur=v_data.z;float extrude_length=length(extrude)+antialiasblur*(1.0-blur_positive);float antialiased_blur=-max(abs(blur),antialiasblur);float antialiase_blur_opacity=smoothstep(0.0,antialiasblur,extrude_length-1.0);float opacity_t=blur_positive==1.0 ? smoothstep(0.0,-antialiased_blur,1.0-extrude_length) : smoothstep(antialiased_blur,0.0,extrude_length-1.0)-antialiase_blur_opacity;float color_t=stroke_width < 0.01 ? 0.0 : smoothstep( antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width) );vec4 out_color=mix(color*opacity,stroke_color*stroke_opacity,color_t); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #endif #ifdef FOG out_color=fog_apply_premultiplied(out_color,v_fog_pos); #endif glFragColor=out_color*(v_visibility*opacity_t); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif }`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define NUM_VISIBILITY_RINGS 2 #define INV_SQRT2 0.70710678 #define ELEVATION_BIAS 0.0001 #define NUM_VISIBILITY_SAMPLES_PER_RING 16 uniform mat4 u_matrix;uniform mat2 u_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;in ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir; #endif #ifdef ELEVATED_ROADS in float a_circle_z_offset; #endif out vec3 v_data;out float v_visibility; #pragma mapbox: define highp vec4 color #pragma mapbox: define mediump float radius #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define highp vec4 stroke_color #pragma mapbox: define mediump float stroke_width #pragma mapbox: define lowp float stroke_opacity vec2 calc_offset(vec2 extrusion,float radius,float stroke_width, float perspective_scale) {return extrusion*(radius+stroke_width)*u_extrude_scale*perspective_scale;}float cantilevered_elevation(vec2 pos,float radius,float stroke_width,float perspective_scale) {vec2 c1=pos+calc_offset(vec2(-1.0,-1.0),radius,stroke_width,perspective_scale);vec2 c2=pos+calc_offset(vec2(1.0,-1.0),radius,stroke_width,perspective_scale);vec2 c3=pos+calc_offset(vec2(1.0,1.0),radius,stroke_width,perspective_scale);vec2 c4=pos+calc_offset(vec2(-1.0,1.0),radius,stroke_width,perspective_scale);float h1=elevation(c1)+ELEVATION_BIAS;float h2=elevation(c2)+ELEVATION_BIAS;float h3=elevation(c3)+ELEVATION_BIAS;float h4=elevation(c4)+ELEVATION_BIAS;return max(h4,max(h3,max(h1,h2)));}float circle_elevation(vec2 pos) { #if defined(TERRAIN) return elevation(pos)+ELEVATION_BIAS; #else return 0.0; #endif }vec4 project_vertex(vec2 extrusion,vec4 world_center,vec4 projected_center,float radius,float stroke_width, float perspective_scale,mat3 surface_vectors) {vec2 sample_offset=calc_offset(extrusion,radius,stroke_width,perspective_scale); #ifdef PITCH_WITH_MAP #ifdef PROJECTION_GLOBE_VIEW return u_matrix*( world_center+vec4(sample_offset.x*surface_vectors[0]+sample_offset.y*surface_vectors[1],0) ); #else return u_matrix*( world_center+vec4(sample_offset,0,0) ); #endif #else return projected_center+vec4(sample_offset,0,0); #endif }void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize mediump float radius #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp vec4 stroke_color #pragma mapbox: initialize mediump float stroke_width #pragma mapbox: initialize lowp float stroke_opacity vec2 pos2=vec2(a_pos);vec2 extrude=vec2(mod(pos2,2.0)*2.0-1.0);vec2 circle_center=floor(pos2*0.5);float height=circle_elevation(circle_center);vec4 world_center;mat3 surface_vectors; #ifdef PROJECTION_GLOBE_VIEW surface_vectors=globe_mercator_surface_vectors(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(circle_center)*height;vec3 globe_pos=vec3(a_pos_3)+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*height;vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,circle_center,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;vec3 pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition);world_center=vec4(pos,1); #else surface_vectors=mat3(1.0);world_center=vec4(circle_center,height,1); #endif #ifdef ELEVATED_ROADS world_center.z+=a_circle_z_offset+ELEVATION_BIAS; #endif vec4 projected_center=u_matrix*world_center;float perspective_scale=0.0; #ifdef PITCH_WITH_MAP #ifdef SCALE_WITH_MAP perspective_scale=1.0; #else perspective_scale=projected_center.w/u_camera_to_center_distance; #endif #else #ifdef SCALE_WITH_MAP perspective_scale=u_camera_to_center_distance; #else perspective_scale=projected_center.w; #endif #endif gl_Position=project_vertex(extrude,world_center,projected_center,radius,stroke_width,perspective_scale,surface_vectors);float terrain_visibility=0.0; #ifdef TERRAIN float arc;vec4 occlusion_world_center;vec4 occlusion_projected_center; #ifdef PITCH_WITH_MAP arc=2.0*PI;float cantilevered_height=cantilevered_elevation(circle_center,radius,stroke_width,perspective_scale);occlusion_world_center=vec4(circle_center,cantilevered_height,1);occlusion_projected_center=u_matrix*occlusion_world_center; #else arc=PI;occlusion_world_center=world_center;occlusion_projected_center=projected_center; #endif float step=arc/float(NUM_VISIBILITY_SAMPLES_PER_RING);for(int ring=0; ring < NUM_VISIBILITY_RINGS; ring++) {float ring_radius_fraction=(float(ring)+1.0)/float(NUM_VISIBILITY_RINGS);for(int i=0; i < NUM_VISIBILITY_SAMPLES_PER_RING; i++) {vec2 extrusion=vec2(cos(step*float(i)),-sin(step*float(i)))*ring_radius_fraction;vec4 frag_pos=project_vertex(extrusion,occlusion_world_center,occlusion_projected_center,radius,stroke_width,perspective_scale,surface_vectors);terrain_visibility+=float(!isOccluded(frag_pos));}}terrain_visibility/=float(NUM_VISIBILITY_RINGS)*float(NUM_VISIBILITY_SAMPLES_PER_RING); #else terrain_visibility=1.0; #endif #ifdef PROJECTION_GLOBE_VIEW terrain_visibility=1.0; #endif v_visibility=terrain_visibility;lowp float antialiasblur=1.0/u_device_pixel_ratio/(radius+stroke_width);v_data=vec3(extrude.x,extrude.y,antialiasblur); #ifdef FOG v_fog_pos=fog_position(world_center.xyz); #endif }`),clippingMask:Zi("void main() {glFragColor=vec4(1.0);}","in ivec2 a_pos;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);}"),heatmap:Zi(`#include "_prelude_fog.fragment.glsl" uniform highp float u_intensity;in vec2 v_extrude; #pragma mapbox: define highp float weight #define GAUSS_COEF 0.3989422804014327 void main() { #pragma mapbox: initialize highp float weight float d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);glFragColor=vec4(val,1.0,1.0,1.0); #ifdef FOG if (u_is_globe==0) {glFragColor.r*=pow(1.0-fog_opacity(v_fog_pos),2.0);} #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_terrain.vertex.glsl" #include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform float u_extrude_scale;uniform float u_intensity;in ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir; #endif out vec2 v_extrude; #pragma mapbox: define highp float weight #pragma mapbox: define mediump float radius const highp float ZERO=1.0/255.0/16.0; #define GAUSS_COEF 0.3989422804014327 void main() { #pragma mapbox: initialize highp float weight #pragma mapbox: initialize mediump float radius vec2 unscaled_extrude=vec2(mod(vec2(a_pos),2.0)*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 tilePos=floor(vec2(a_pos)*0.5);vec3 pos; #ifdef PROJECTION_GLOBE_VIEW vec3 pos_normal_3=vec3(a_pos_normal_3)/16384.0;mat3 surface_vectors=globe_mercator_surface_vectors(pos_normal_3,u_up_dir,u_zoom_transition);vec3 surface_extrusion=extrude.x*surface_vectors[0]+extrude.y*surface_vectors[1];vec3 globe_elevation=elevationVector(tilePos)*elevation(tilePos);vec3 globe_pos=vec3(a_pos_3)+surface_extrusion+globe_elevation;vec3 mercator_elevation=u_up_dir*u_tile_up_scale*elevation(tilePos);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,tilePos,u_tile_id,u_merc_center)+surface_extrusion+mercator_elevation;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #else pos=vec3(tilePos+extrude,elevation(tilePos)); #endif gl_Position=u_matrix*vec4(pos,1); #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),heatmapTexture:Zi(`uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));glFragColor=color*u_opacity; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(0.0); #endif HANDLE_WIREFRAME_DEBUG;}`,"in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=bottom_left_to_native_uv(vec2(a_pos)*0.5+0.5);}"),collisionBox:Zi("in float v_placed;in float v_notUsed;void main() {vec4 red =vec4(1.0,0.0,0.0,1.0);vec4 blue=vec4(0.0,0.0,1.0,0.5);glFragColor =mix(red,blue,step(0.5,v_placed))*0.5;glFragColor*=mix(1.0,0.1,step(0.5,v_notUsed));}",`#include "_prelude_terrain.vertex.glsl" in ivec4 a_pos;in ivec2 a_anchor_pos;in ivec2 a_extrude;in uvec2 a_placed;in vec2 a_shift;in vec2 a_elevation_from_sea;in float a_size_scale;in vec2 a_padding;in float a_auto_z_offset;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance; #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform float u_zoom_transition; #endif out float v_placed;out float v_notUsed;void main() {vec2 anchor_pos=vec2(a_anchor_pos);float feature_elevation=a_elevation_from_sea.x+a_auto_z_offset;float terrain_elevation=(a_elevation_from_sea.y==1.0 ? 0.0 : elevation(anchor_pos));vec3 proj_pos=vec3(a_pos)+elevationVector(anchor_pos)*(feature_elevation+terrain_elevation); #ifdef PROJECTION_GLOBE_VIEW #ifndef PROJECTED_POS_ON_VIEWPORT vec3 globe_pos=proj_pos;vec3 mercator_pos=mercator_tile_position(u_inv_rot_matrix,anchor_pos,u_tile_id,u_merc_center);proj_pos=mix_globe_mercator(globe_pos,mercator_pos,u_zoom_transition); #endif #endif vec4 projectedPoint=u_matrix*vec4(proj_pos,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp( 0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,1.5);gl_Position=projectedPoint;gl_Position.xy+=(vec2(a_extrude)*a_size_scale+a_shift+a_padding)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=float(a_placed.x);v_notUsed=float(a_placed.y);}`),collisionCircle:Zi("in float v_radius;in vec2 v_extrude;in float v_perspective_ratio;in float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);glFragColor=color*alpha*opacity_t;}",`in vec2 a_pos_2f;in float a_radius;in ivec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;out float v_radius;out vec2 v_extrude;out float v_perspective_ratio;out float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 anchorScreenPos=a_pos_2f;float radius=a_radius;int vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2( mix(-1.0,1.0,float(vertexIdx >=2)),mix(-1.0,1.0,float(vertexIdx >=1 && vertexIdx <=2)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(anchorScreenPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp( 0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=float(a_flags.x);gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}`),placementDebug:Zi("uniform vec4 u_color;uniform float u_outline_width;uniform float u_opacity;uniform float u_stroke_opacity;uniform float u_collision_padding_opacity;in vec2 v_offset;in vec2 v_half_size;in float v_is_circle;in float v_collision_padding;float boxDistance(vec2 offset,vec2 halfSize) {vec2 toCorner=abs(offset)-halfSize;return max(toCorner.x,toCorner.y);}float circleDistance(vec2 offset,float radius) {return length(offset)-radius;}float linearStep(float start,float end,float x) {return (clamp(x,start,end)-start)/(end-start);}float onePxLongLinearStepAt(float center,float x) {const float halfPx=0.5;return linearStep(center-halfPx,center+halfPx,x);}void main() {float distanceToEdge=mix(boxDistance(v_offset,v_half_size),circleDistance(v_offset,v_half_size.x),v_is_circle);float linearStepAtMinusOutlineWidth=onePxLongLinearStepAt(-u_outline_width,distanceToEdge);float linearStepAtZero=onePxLongLinearStepAt(0.0,distanceToEdge);float linearStepAtCollisionPadding=onePxLongLinearStepAt(v_collision_padding,distanceToEdge);float interiorCoverage=1.0-linearStepAtMinusOutlineWidth;float outlineCoverage=linearStepAtMinusOutlineWidth-linearStepAtZero;float collisionPaddingCoverage=linearStepAtZero-linearStepAtCollisionPadding;glFragColor=u_color*(u_opacity*interiorCoverage+u_stroke_opacity*outlineCoverage+u_collision_padding_opacity*collisionPaddingCoverage);}",` in vec2 a_pos_2f;in vec2 a_size;in float a_collision_padding;in ivec2 a_flags;uniform vec2 u_viewport_size;out vec2 v_offset;out vec2 v_half_size;out float v_is_circle;out float v_collision_padding;const vec2 QUAD_CORNERS[4]=vec2[4](vec2(-1.0,-1.0),vec2(1.0,-1.0),vec2(1.0,1.0),vec2(-1.0,1.0));const float AA_width=1.0;void main() {vec2 offset=QUAD_CORNERS[a_flags.y]*(a_size+a_collision_padding+AA_width);v_offset=offset;v_half_size=a_size;v_is_circle=float(a_flags.x);v_collision_padding=a_collision_padding;vec2 viewportPos=(a_pos_2f+offset)/u_viewport_size;gl_Position=vec4(viewportPos*vec2(2.0,-2.0)+vec2(-1.0,1.0),0.0,1.0);}`),debug:Zi("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);glFragColor=mix(u_color,overlay_color,overlay_color.a);}",`#include "_prelude_terrain.vertex.glsl" in ivec2 a_pos; #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3; #endif out vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {vec2 pos=vec2(a_pos);float h=elevation(pos);v_uv=pos/8192.0; #ifdef PROJECTION_GLOBE_VIEW gl_Position=u_matrix*vec4(vec3(a_pos_3)+elevationVector(pos)*h,1); #else gl_Position=u_matrix*vec4(pos*u_overlay_scale,h,1); #endif }`),fill:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity vec2 cutout_factors=vec2(0.0);vec4 out_color=color; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif out_color*=(opacity*u_opacity_multiplier);glFragColor=out_color;storeEmissiveColor(glFragColor,u_emissive_strength); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif uniform mat4 u_matrix;uniform lowp float u_opacity_multiplier; #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp float z_offset #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden); #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),fillOutline:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" in highp vec2 v_pos;uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier; #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #pragma mapbox: define highp vec4 outline_color #pragma mapbox: define lowp float opacity void main() { #pragma mapbox: initialize highp vec4 outline_color #pragma mapbox: initialize lowp float opacity float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=outline_color;vec2 cutout_factors=vec2(0.0); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*(alpha*opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif uniform mat4 u_matrix;uniform vec2 u_world;uniform lowp float u_opacity_multiplier;out highp vec2 v_pos; #pragma mapbox: define highp vec4 outline_color #pragma mapbox: define lowp float opacity #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize highp vec4 outline_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize highp float z_offset #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden);v_pos=ndc_xy_to_framebuffer_uv(gl_Position.xy/gl_Position.w)*u_world; #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(a_pos,z_offset);vec3 shd_pos1=vec3(a_pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),fillOutlinePattern:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_PATTERN_TRANSITION uniform float u_pattern_transition; #endif uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier; #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif in highp vec2 v_pos;in highp vec2 v_pos_world; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);float dist=length(v_pos_world-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif vec2 cutout_factors=vec2(0.0); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*(alpha*opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_world;uniform lowp float u_opacity_multiplier;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif out highp vec2 v_pos;out highp vec2 v_pos_world; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define lowp float pixel_ratio #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw); #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_pos_world=ndc_xy_to_framebuffer_uv(gl_Position.xy/gl_Position.w)*u_world; #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),fillPattern:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_PATTERN_TRANSITION uniform float u_pattern_transition; #endif in highp vec2 v_pos;uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier; #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif vec2 cutout_factors=vec2(0.0); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,u_emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y); #ifdef ELEVATED_ROADS out_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*(opacity*u_opacity_multiplier);storeEmissiveColor(glFragColor,u_emissive_strength); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" uniform mat4 u_matrix;uniform lowp float u_opacity_multiplier;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_tile_units_to_pixels;in ivec2 a_pos; #ifdef ELEVATED_ROADS in float a_road_z_offset;out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif out highp vec2 v_pos; #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp uvec4 pattern #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define lowp float pixel_ratio #pragma mapbox: define highp float z_offset void main() { #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump uvec4 pattern #pragma mapbox: initialize lowp float pixel_ratio #pragma mapbox: initialize highp float z_offset #ifdef FILL_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio; #ifdef ELEVATED_ROADS z_offset+=a_road_z_offset;v_road_z_offset=z_offset; #endif float hidden=float(opacity==0.0);vec2 pos=vec2(a_pos);gl_Position=mix(u_matrix*vec4(pos,z_offset,1),AWAY,hidden);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos); #ifdef RENDER_SHADOWS vec3 shd_pos0=vec3(pos,z_offset);vec3 shd_pos1=vec3(pos,z_offset); #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),lineBlendComposite:Zi(`uniform highp sampler2D u_image;uniform float u_opacity;uniform int u_blend_mode;uniform highp float u_max_density;in vec2 v_pos; #define ADDITIVE 1 void main() {vec4 color=texture(u_image,v_pos);if (u_blend_mode==ADDITIVE) {if (color.a <=0.0) {discard;}highp float density=color.a;vec3 avgColor=color.rgb/max(density,0.001);highp float n=density/max(u_max_density,0.001);highp float t=sqrt(n/(n+1.0));glFragColor=vec4(avgColor*t,t);} else {vec3 multiplyFactor=color.rgb*u_opacity+(1.0-u_opacity);glFragColor=vec4(multiplyFactor,1.0);} #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(0.0); #endif HANDLE_WIREFRAME_DEBUG;}`,"in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),lineBlendReduce:Zi("uniform highp sampler2D u_image;uniform vec2 u_texel_size;uniform bool u_first_pass;in vec2 v_pos;void main() {vec2 o=u_texel_size*0.5;vec4 s0=texture(u_image,v_pos+vec2(-o.x,-o.y));vec4 s1=texture(u_image,v_pos+vec2( o.x,-o.y));vec4 s2=texture(u_image,v_pos+vec2(-o.x, o.y));vec4 s3=texture(u_image,v_pos+vec2( o.x, o.y));float r0; float g0;float r1; float g1;float r2; float g2;float r3; float g3;if (u_first_pass) {float a0=s0.a;float a1=s1.a;float a2=s2.a;float a3=s3.a;r0=a0; g0=a0 > 0.0 ? 1.0 : 0.0;r1=a1; g1=a1 > 0.0 ? 1.0 : 0.0;r2=a2; g2=a2 > 0.0 ? 1.0 : 0.0;r3=a3; g3=a3 > 0.0 ? 1.0 : 0.0;} else {r0=s0.r; g0=s0.g;r1=s1.r; g1=s1.g;r2=s2.r; g2=s2.g;r3=s3.r; g3=s3.g;}glFragColor=vec4((r0+r1+r2+r3)*0.25,(g0+g1+g2+g3)*0.25,0.0,0.0);}","in ivec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos,0,1);v_pos=vec2(a_pos)*0.5+0.5;}"),fillExtrusion:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" in vec4 v_color;in vec4 v_flat; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) in float v_dither_opacity; #endif #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif uniform lowp float u_opacity; #ifdef FAUX_AO uniform lowp vec2 u_ao;in vec2 v_ao; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) in vec4 v_roof_color; #endif #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) in highp vec3 v_normal; #endif uniform vec3 u_flood_light_color;uniform highp float u_vertical_scale;uniform float u_flood_light_intensity;uniform vec3 u_ground_shadow_factor; #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) in float v_flood_radius;in float v_has_floodlight; #endif in float v_height; #pragma mapbox: define highp float emissive_strength void main() { #pragma mapbox: initialize highp float emissive_strength #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) vec3 normal=normalize(v_normal); #endif float z;vec4 color=v_color; #ifdef ZERO_ROOF_RADIUS z=float(normal.z > 0.00001); #ifdef LIGHTING_3D_MODE normal=mix(normal,vec3(0.0,0.0,1.0),z); #else color=mix(v_color,v_roof_color,z); #endif #endif float h=max(0.0,v_height);float ao_shade=1.0; #ifdef FAUX_AO float intensity=u_ao[0];float h_floors=h/(u_ao[1]*u_vertical_scale);float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);ao_shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x; #ifdef ZERO_ROOF_RADIUS concave*=(1.0-z); #endif float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);ao_shade*=mix(1.0,x_shade*x_shade*x_shade,concave); #ifdef LIGHTING_3D_MODE #ifdef FLOOD_LIGHT color.rgb*=mix(ao_shade,1.0,v_has_floodlight); #else color.rgb*=ao_shade; #endif #else color.rgb*=ao_shade; #endif #endif #ifdef LIGHTING_3D_MODE float flood_radiance=0.0; #ifdef FLOOD_LIGHT flood_radiance=(1.0-min(h/v_flood_radius,1.0))*u_flood_light_intensity*v_has_floodlight; #endif #ifdef RENDER_SHADOWS #ifdef FLOOD_LIGHT float ndotl_unclamped=dot(normal,u_shadow_direction);float ndotl=max(0.0,ndotl_unclamped);float occlusion=ndotl_unclamped < 0.0 ? 1.0 : shadow_occlusion(ndotl,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 litColor=apply_lighting(color.rgb,normal,(1.0-u_shadow_intensity*occlusion)*ndotl);vec3 floodLitColor=compute_flood_lighting(u_flood_light_color*u_opacity,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=mix(litColor,floodLitColor,flood_radiance); #else float shadowed_lighting_factor; #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif color.rgb=apply_lighting(color.rgb,normal,shadowed_lighting_factor); #endif #else color.rgb=apply_lighting(color.rgb,normal); #ifdef FLOOD_LIGHT color.rgb=mix(color.rgb,u_flood_light_color*u_opacity,flood_radiance); #endif #endif color.rgb=mix(color.rgb,v_flat.rgb,emissive_strength);color*=u_opacity; #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,h)); #endif #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) if (v_dither_opacity < 1.0) {int index=viewport_dither_index(gl_FragCoord.xy);if (v_dither_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_lighting.glsl" #include "_prelude_material_table.vertex.glsl" #include "_prelude_feature_cutout.vertex.glsl" uniform mat4 u_matrix; #ifndef LIGHTING_3D_MODE uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity; #endif uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_edge_radius;uniform float u_width_scale;in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift; #endif #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif uniform highp float u_vertical_scale; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params; #endif out float v_dither_opacity; #endif out vec4 v_color;out vec4 v_flat; #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) out vec4 v_roof_color; #endif #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) out highp vec3 v_normal; #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;out vec2 v_ao;invariant gl_Position; #endif #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) out float v_flood_radius;out float v_has_floodlight; #endif out float v_height;vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp vec4 color #pragma mapbox: define highp float flood_light_wall_radius #pragma mapbox: define highp float line_width #pragma mapbox: define highp float emissive_strength void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize highp float flood_light_wall_radius #pragma mapbox: initialize highp float line_width #pragma mapbox: initialize highp float emissive_strength base*=u_vertical_scale;height*=u_vertical_scale;vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0)); #if defined(ZERO_ROOF_RADIUS) || defined(RENDER_SHADOWS) || defined(LIGHTING_3D_MODE) v_normal=normal; #endif base=max(0.0,base);float attr_height=height;height=max(0.0,top_up_ny_start.y==0.0 && top_up_ny_start.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny_start.x;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif float ele=0.0;float h=0.0;float c_ele=0.0;vec3 pos; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && (int(centroid_pos.y) & 7)==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base; #else h=t > 0.0 ? height : base; #endif pos=vec3(pos_nx.xy,h); #ifdef PROJECTION_GLOBE_VIEW float lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*h);vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,pos.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*pos.z;pos=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #endif float cutoff=1.0;vec3 scaled_pos=pos; #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) vec2 centroid_decoded=pos.xy;bool isBorderCentroid=false;if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {int iy=int(centroid_pos.y);int spanYbits=iy & 7;if (spanYbits==7) {isBorderCentroid=true;int borderID=(iy >> 3) & 3;float coordAlongBorder=float(iy >> 5)*4.0;if (borderID==0) centroid_decoded=vec2(0.0,coordAlongBorder);else if (borderID==1) centroid_decoded=vec2(EXTENT,coordAlongBorder);else if (borderID==2) centroid_decoded=vec2(coordAlongBorder,0.0);else centroid_decoded=vec2(coordAlongBorder,EXTENT);} else {centroid_decoded=floor(centroid_pos/8.0);}} #endif #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) float frontCutoffOpacity=1.0;float routeFade=0.0; #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_decoded,ele,1.0); #endif #ifdef RENDER_CUTOFF cutoff=cutoff_opacity(u_cutoff_params,native_clip_z_to_cutoff_depth(ground.z,ground.w));if (centroid_pos.y !=0.0 && centroid_pos.x !=0.0) {vec3 centroid_random=vec3(centroid_pos.xy,centroid_pos.x+centroid_pos.y+1.0);vec3 ground_pos=centroid_random/8.0;vec3 g=floor(ground_pos);vec3 mod_=centroid_random-g*8.0;float seed=min(1.0,0.1*(min(3.5,max(mod_.x+mod_.y,0.2*attr_height))*0.35+mod_.z));if (cutoff < 0.8-seed) {cutoff=0.0;}}float cutoff_scale=cutoff;v_cutoff_opacity=cutoff;scaled_pos.z=mix(c_ele,h,cutoff_scale); #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (cutoff==0.0 && centroid_pos.x !=0.0) || (color.a==0.0)); #ifdef RENDER_FRONT_CUTOFF if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;if (!isBorderCentroid) {hidden=max(hidden,float(ndc_y < threshold-range_ndc));}float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);frontCutoffOpacity=mix(u_front_cutoff_params.z,1.0,t);} #endif #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) v_dither_opacity=1.0; #ifdef RENDER_FRONT_CUTOFF v_dither_opacity=min(v_dither_opacity,frontCutoffOpacity); #endif if (centroid_pos.x > 0.0 && centroid_pos.y > 0.0) {hidden=max(hidden,float(v_dither_opacity <=0.0));} #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);scaled_pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;scaled_pos.xy-=join_normal_inside.z*wall_offset*0.5; #endif gl_Position=mix(u_matrix*vec4(scaled_pos,1),AWAY,hidden);h=h-ele;v_height=h; #ifdef RENDER_SHADOWS vec3 shd_pos0=pos;vec3 shd_pos1=pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(normal);shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1); #endif float NdotL=0.0;float colorvalue=0.0; #ifndef LIGHTING_3D_MODE colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),NdotL);if (normal.y !=0.0) {float r=0.84;r=mix(0.7,0.98,1.0-u_lightintensity);NdotL*=( (1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));} #endif #ifdef FAUX_AO float concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height; #ifdef TERRAIN top_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height); #endif v_ao=vec2(mix(concave,-concave,start),y_ground);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]); #ifdef PROJECTION_GLOBE_VIEW top_height+=u_height_lift; #endif float z_bias=native_depth_epsilon(0.0000006);gl_Position.z-=(z_bias*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w; #endif #ifdef LIGHTING_3D_MODE #ifdef FLOOD_LIGHT float is_wall=1.0-float(t > 0.0 && top_up_ny_start.y > 0.0);v_has_floodlight=float(flood_light_wall_radius > 0.0 && is_wall > 0.0);v_flood_radius=flood_light_wall_radius*u_vertical_scale; #endif v_color=vec4(color.rgb,1.0);float ndotl=calculate_NdotL(normal);v_flat.rgb=sRGBToLinear(color.rgb);v_flat.rgb=v_flat.rgb*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);v_flat=vec4(linearTosRGB(v_flat.rgb),1.0); #else v_color=vec4(0.0,0.0,0.0,1.0);v_color.rgb+=clamp(color.rgb*NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_color*=u_opacity; #endif #if defined(ZERO_ROOF_RADIUS) && !defined(LIGHTING_3D_MODE) float roofNdotL=clamp(u_lightpos.z,0.0,1.0);roofNdotL=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),roofNdotL);v_roof_color=vec4(0.0,0.0,0.0,1.0);v_roof_color.rgb+=clamp(color.rgb*roofNdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_roof_color*=u_opacity; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),fillExtrusionPattern:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.glsl" uniform vec2 u_texsize;uniform sampler2D u_image; #ifdef FILL_EXTRUSION_PATTERN_TRANSITION uniform float u_pattern_transition; #endif #ifdef FAUX_AO uniform lowp vec2 u_ao;in vec3 v_ao; #endif #ifdef LIGHTING_3D_MODE in vec3 v_normal; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif in highp vec2 v_pos;in vec4 v_lighting;uniform lowp float u_opacity; #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define highp float pixel_ratio void main() { #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);highp vec2 imagecoord=mod(v_pos,1.0);highp vec2 pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,imagecoord);highp vec2 lod_pos=mix(pattern_tl/u_texsize,pattern_br/u_texsize,v_pos);vec4 out_color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef FILL_EXTRUSION_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl/u_texsize,pattern_b_br/u_texsize,imagecoord);vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);out_color=out_color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef LIGHTING_3D_MODE out_color=apply_lighting(out_color,normalize(v_normal))*u_opacity; #else out_color=out_color*v_lighting; #endif #ifdef FAUX_AO float intensity=u_ao[0];float h=max(0.0,v_ao.z);float h_floors=h/u_ao[1];float y_shade=1.0-0.9*intensity*min(v_ao.y,1.0);float shade=(1.0-0.08*intensity)*(y_shade+(1.0-y_shade)*(1.0-pow(1.0-min(h_floors/16.0,1.0),16.0)))+0.08*intensity*min(h_floors/160.0,1.0);float concave=v_ao.x*v_ao.x;float x_shade=mix(1.0,mix(0.6,0.75,min(h_floors/30.0,1.0)),intensity)+0.1*intensity*min(h,1.0);shade*=mix(1.0,x_shade*x_shade*x_shade,concave);out_color.rgb=out_color.rgb*shade; #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #include "_prelude_lighting.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform float u_tile_units_to_pixels;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform float u_width_scale; #ifndef LIGHTING_3D_MODE uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity; #endif in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_pos_3;in ivec4 a_pos_normal_3;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_tile_id;uniform float u_zoom_transition;uniform vec3 u_up_dir;uniform float u_height_lift; #endif #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif out highp vec2 v_pos;out vec4 v_lighting; #ifdef FAUX_AO uniform lowp vec2 u_ao;out vec3 v_ao;invariant gl_Position; #endif #ifdef LIGHTING_3D_MODE out vec3 v_normal; #endif #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp vec4 color #pragma mapbox: define mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define highp float pixel_ratio #pragma mapbox: define highp float line_width void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize mediump uvec4 pattern #ifdef FILL_EXTRUSION_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize highp float pixel_ratio #pragma mapbox: initialize highp float line_width vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec4 top_up_ny_start=vec4(a_pos_normal_ed & 1);vec4 pos_nx=vec4(a_pos_normal_ed >> 1);float x_normal=pos_nx.z/8192.0;vec3 normal=top_up_ny_start.y==1.0 ? vec3(0.0,0.0,1.0) : normalize(vec3(x_normal,(2.0*top_up_ny_start.z-1.0)*(1.0-abs(x_normal)),0.0));float edgedistance=float(a_pos_normal_ed.w);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;base=max(0.0,base);height=max(0.0,height);float t=top_up_ny_start.x;float z=t > 0.0 ? height : base;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif float ele=0.0;float h=z;vec3 p;float c_ele; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);h=t > 0.0 ? max(h_base,h_height) : h_base;p=vec3(pos_nx.xy,h); #else p=vec3(pos_nx.xy,z); #endif #ifdef PROJECTION_GLOBE_VIEW float lift=float((t+base) > 0.0)*u_height_lift;h+=lift;vec3 globe_normal=normalize(mix(vec3(a_pos_normal_3)/16384.0,u_up_dir,u_zoom_transition));vec3 globe_pos=vec3(a_pos_3)+globe_normal*(u_tile_up_scale*(p.z+lift));vec3 merc_pos=mercator_tile_position(u_inv_rot_matrix,p.xy,u_tile_id,u_merc_center)+u_up_dir*u_tile_up_scale*p.z;p=mix_globe_mercator(globe_pos,merc_pos,u_zoom_transition); #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);p.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;p.xy-=join_normal_inside.z*wall_offset*0.5; #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(p,1),AWAY,hidden);vec2 pos=normal.z==1.0 ? pos_nx.xy : vec2(edgedistance,z*u_height_factor);v_pos=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,display_size,u_tile_units_to_pixels,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float NdotL=0.0; #ifdef LIGHTING_3D_MODE NdotL=calculate_NdotL(normal); #else NdotL=clamp(dot(normal,u_lightpos),0.0,1.0);NdotL=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),NdotL); #endif if (normal.y !=0.0) {float r=0.84; #ifndef LIGHTING_3D_MODE r=mix(0.7,0.98,1.0-u_lightintensity); #endif NdotL*=( (1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),r,1.0)));} #ifdef FAUX_AO float concave=pos_nx.w-floor(pos_nx.w*0.5)*2.0;float start=top_up_ny_start.w;float y_ground=1.0-clamp(t+base,0.0,1.0);float top_height=height; #ifdef TERRAIN top_height=mix(max(c_ele+height,ele+base+2.0),ele+height,float(centroid_pos.x==0.0))-ele;y_ground+=y_ground*5.0/max(3.0,top_height); #endif v_ao=vec3(mix(concave,-concave,start),y_ground,h-ele);NdotL*=(1.0+0.05*(1.0-top_up_ny_start.y)*u_ao[0]); #ifdef PROJECTION_GLOBE_VIEW top_height+=u_height_lift; #endif float z_bias=native_depth_epsilon(0.0000006);gl_Position.z-=(z_bias*(min(top_height,500.)+2.0*min(base,500.0)+60.0*concave+3.0*start))*gl_Position.w; #endif #ifdef LIGHTING_3D_MODE v_normal=normal; #else v_lighting.rgb+=clamp(NdotL*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity; #endif #ifdef FOG v_fog_pos=fog_position(p); #endif }`),hillshadePrepare:Zi(`precision highp float;uniform highp sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;float getElevation(vec2 coord) {return texture(u_image,coord).r/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y));float b=getElevation(v_pos+vec2(0,-epsilon.y));float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y));float d=getElevation(v_pos+vec2(-epsilon.x,0));float e=getElevation(v_pos+vec2(epsilon.x,0));float f=getElevation(v_pos+vec2(-epsilon.x,epsilon.y));float g=getElevation(v_pos+vec2(0,epsilon.y));float h=getElevation(v_pos+vec2(epsilon.x,epsilon.y));float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2( (c+e+e+h)-(a+d+d+f),(f+g+g+h)-(a+b+b+c) )/pow(2.0,exaggeration+(19.2562-u_zoom));glFragColor=clamp(vec4( deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);}`,"uniform mat4 u_matrix;uniform vec2 u_dimension;in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(vec2(a_texture_pos)/8192.0)*scale+epsilon;}"),hillshade:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;uniform float u_emissive_strength;void main() {vec4 pixel=texture(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);glFragColor=accent_color*(1.0-shade_color.a)+shade_color; #ifdef LIGHTING_3D_MODE glFragColor=apply_lighting_with_emission_ground(glFragColor,u_emissive_strength); #endif #ifdef FOG glFragColor=fog_dither(fog_apply_premultiplied(glFragColor,v_fog_pos)); #endif storeEmissiveColor(glFragColor,u_emissive_strength); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=bottom_left_to_native_uv(vec2(a_texture_pos)/8192.0); #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),line:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" uniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform float u_alpha_discard_threshold;uniform lowp float u_opacity_multiplier; #ifdef ELEVATED_ROADS uniform bool u_clip_to_tile_borders;uniform vec4 u_child_quadrants; #endif in vec4 v_width2_dilute;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_tile_pos; #ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP in highp vec4 v_round_join_conflict_offset;in highp vec4 v_round_join_conflict_dir;in mediump vec2 v_round_join_conflict_test; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH in float stub_side;in highp vec2 v_distance; #endif uniform bool u_has_dash;uniform bool u_has_border;uniform sampler2D u_dash_image;uniform highp float u_floor_width_scale;in highp vec2 v_tex; #ifdef DEBUG_ELEVATION_ID in vec3 v_elevation_id_col; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) in highp vec3 v_uv; #endif #ifdef RENDER_LINE_GRADIENT uniform sampler2D u_gradient_image; #endif #ifdef RENDER_LINE_BORDER_GRADIENT uniform sampler2D u_border_gradient_image; #endif #ifdef RENDER_LINE_TRIM_OFFSET uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform highp vec2 u_trim_gradient_mix_range;uniform lowp vec4 u_trim_color; #endif #ifdef RENDER_SHADOWS uniform bool u_emissive_in_shadows;uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif float luminance(vec3 c) {return (c.r+c.r+c.b+c.g+c.g+c.g)*0.1667;}in highp vec4 v_line_color;in lowp vec4 v_border_color;in lowp float v_opacity;in lowp float v_blur;in lowp float v_floorwidth;in lowp float v_border_width;in lowp float v_emissive_strength;in highp vec2 v_dash; #ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP const highp float ROUND_JOIN_NO_CONFLICT=32768.0;highp float roundJoinConflictDistance(highp vec2 conflictOffset,highp vec2 conflictDir,mediump float test) {if (test <=0.0) {return ROUND_JOIN_NO_CONFLICT;}highp float dirLenSq=max(dot(conflictDir,conflictDir),1e-6);highp float t=clamp(dot(conflictOffset,conflictDir)/dirLenSq,0.0,1.0);return length(conflictOffset-t*conflictDir);}float insideRoundJoinTestArea(highp float dist,vec2 testBounds,float pxStep) {float inside=1.0-smoothstep(testBounds.y-pxStep,testBounds.y+pxStep,dist);float pastGap=testBounds.x > 0.0 ? smoothstep(testBounds.x-pxStep,testBounds.x+pxStep,dist) : 1.0;return inside*pastGap;}float insideRoundJoinConflictBody(highp float dist,vec3 testBounds,float pxStep) {vec2 body=vec2(testBounds.x,testBounds.y-pxStep);return insideRoundJoinTestArea(dist,body,pxStep);}float insideRoundJoinConflictFill(highp float dist,vec3 testBounds,float pxStep) {float gap=testBounds.x;float outer=testBounds.y;float border=testBounds.z;vec2 fill=vec2(gap+(gap > 0.0 ? border : 0.0),max(outer-border,0.0));return insideRoundJoinTestArea(dist,fill,pxStep);} #endif float linearstep(float edge0,float edge1,float x) {return clamp((x-edge0)/(edge1-edge0),0.0,1.0);}void main() {highp vec4 color=vec4(v_line_color.rgb*v_line_color.a,v_line_color.a);float floorwidth=v_floorwidth;float blur=v_blur;float opacity=v_opacity;float border_width=v_border_width;vec4 border_color=vec4(v_border_color.rgb*v_border_color.a,v_border_color.a);float emissive_strength=v_emissive_strength;float dist=length(v_normal)*v_width2_dilute.x;float ANTIALIASING=1.0/u_device_pixel_ratio/2.0; #ifndef VARIABLE_LINE_WIDTH if (u_has_border) {ANTIALIASING*=8.0;} #endif #ifdef VARIABLE_LINE_WIDTH blur=mix(blur,0.0,stub_side); #endif float diluted_opacity=opacity*v_width2_dilute.z;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha; #ifdef VARIABLE_LINE_WIDTH float centre_distance=length(v_distance);float edge=mix(v_width2_dilute.y,v_width2_dilute.x,0.5+0.5*v_distance.y/max(centre_distance,1e-4));float inv_radius=1.0/max(length(vec4(dFdx(v_distance),dFdy(v_distance))),1e-4);vec2 edges=clamp((vec2(edge,-edge)-centre_distance)*inv_radius,-1.0,1.0);vec2 window=edges*(1.0-0.5*abs(edges));float blur_fade=clamp(edge*(1.0-centre_distance/(edge+ANTIALIASING))/blur2,0.0,1.0);alpha=mix(window.x-window.y,blur_fade,smoothstep(1.0,2.0,u_width_scale*blur*inv_radius)); #else alpha=clamp(min(dist-(v_width2_dilute.y-blur2),v_width2_dilute.x-dist)/blur2,0.0,1.0); #endif float pxStep;float delta;float alpha2=1.0; #ifndef VARIABLE_LINE_WIDTH if (u_has_border) {pxStep=fwidth(dist);float out_edge=v_width2_dilute.x-dist;float in_edge=dist-(v_width2_dilute.y-2.0*ANTIALIASING);delta=v_width2_dilute.y > 0.0 ? min(in_edge,out_edge) : out_edge;float edge=ANTIALIASING;alpha=delta > 0.0 ? smoothstep(edge-pxStep,u_width_scale*blur+edge+pxStep,delta) : 0.0;float borderPx=border_width*u_width_scale;float edge2=borderPx+ANTIALIASING;alpha2=smoothstep(edge2-pxStep,edge2+pxStep,delta); #ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP if (alpha > 0.0 && alpha2 < 1.0 && (v_round_join_conflict_test.x > 0.0 || v_round_join_conflict_test.y > 0.0)) {highp float prevDist=roundJoinConflictDistance(v_round_join_conflict_offset.xy,v_round_join_conflict_dir.xy,v_round_join_conflict_test.x);highp float nextDist=roundJoinConflictDistance(v_round_join_conflict_offset.zw,v_round_join_conflict_dir.zw,v_round_join_conflict_test.y);vec3 testBounds=vec3(max(v_width2_dilute.y-ANTIALIASING,0.0),v_width2_dilute.x-ANTIALIASING,borderPx);float insideConflictFill=max(insideRoundJoinConflictFill(prevDist,testBounds,pxStep),insideRoundJoinConflictFill(nextDist,testBounds,pxStep));alpha2=max(alpha2,insideConflictFill);const float diluteEpsilon=0.004;if (u_alpha_discard_threshold !=0.0 && blur==0.0 && v_width2_dilute.z >=1.0-diluteEpsilon) {float insideConflictBody=max(insideRoundJoinConflictBody(prevDist,testBounds,pxStep),insideRoundJoinConflictBody(nextDist,testBounds,pxStep));alpha=max(alpha,delta >=edge ? insideConflictBody : 0.0);}} #endif } #endif if (u_has_dash) {highp float dash_len=v_dash.x;float sdfgamma=ANTIALIASING/float(dash_len);float scaled_floorwidth=(floorwidth*u_floor_width_scale);float periods_per_pixel=fwidth(v_tex.x);float dash_coverage=v_dash.y;float fade=linearstep(0.25,0.5,periods_per_pixel);float gamma=max(sdfgamma/scaled_floorwidth,0.5*periods_per_pixel);if (fade >=1.0) {alpha*=dash_coverage;} else if (periods_per_pixel < 0.1) {float sdfdist=texture(u_dash_image,v_tex).r;alpha*=linearstep(0.5-gamma,0.5+gamma,sdfdist);} else {float span=min(periods_per_pixel,1.0);float tap_offset=span*0.25;float sdf0=texture(u_dash_image,vec2(v_tex.x-tap_offset,v_tex.y)).r;float sdf1=texture(u_dash_image,vec2(v_tex.x+tap_offset,v_tex.y)).r;alpha*=mix(0.5*( linearstep(0.5-gamma,0.5+gamma,sdf0)+linearstep(0.5-gamma,0.5+gamma,sdf1) ),dash_coverage,fade);}}highp vec4 out_color; #ifdef RENDER_LINE_GRADIENT out_color=texture(u_gradient_image,v_uv.xy); #else out_color=color; #endif float trim_alpha=1.0; #ifdef RENDER_LINE_TRIM_OFFSET highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);highp float gradient_trim_color_mix_factor=0.0; #ifdef RENDER_LINE_GRADIENT gradient_trim_color_mix_factor=smoothstep(u_trim_gradient_mix_range.x,u_trim_gradient_mix_range.y,line_progress); #endif highp vec4 trim_color=mix(u_trim_color,out_color,gradient_trim_color_mix_factor);out_color=mix(u_trim_gradient_mix_range.x < 1.0 ? color : out_color,trim_color,transition_factor);trim_alpha=1.0-transition_factor;} #endif if (u_alpha_discard_threshold !=0.0) {if (alpha < u_alpha_discard_threshold) {discard;}} #ifdef VARIABLE_LINE_WIDTH if (alpha <=0.0) {discard;} #endif #ifndef VARIABLE_LINE_WIDTH if (u_has_border && alpha2 < 1.) { #ifdef RENDER_LINE_BORDER_GRADIENT vec4 border_gradient_color=texture(u_border_gradient_image,v_uv.xy);out_color=mix(border_gradient_color*trim_alpha,out_color,alpha2); #else if (border_color.a==0.0) { #ifndef RENDER_LINE_GRADIENT float Y=(out_color.a > 0.01) ? luminance(out_color.rgb/out_color.a) : 1.;float adjustment=(Y > 0.) ? 0.5/Y : 0.45;if (out_color.a > 0.25 && Y < 0.25) {vec3 borderColor=(Y > 0.) ? out_color.rgb : vec3(1,1,1)*out_color.a;out_color.rgb=out_color.rgb+borderColor*(adjustment*(1.0-alpha2));} else {out_color.rgb*=(0.6+0.4*alpha2);} #else out_color.rgb*=(0.6+0.4*alpha2); #endif } else {out_color=mix(border_color*trim_alpha,out_color,alpha2);} #endif out_color*=v_width2_dilute.w;} #endif vec2 cutout_factors=vec2(0.0); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);light=u_emissive_in_shadows ? mix(light,1.0,emissive_strength) : light; #ifdef ELEVATED_ROADS out_color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif out_color*=(alpha*diluted_opacity*u_opacity_multiplier); #ifdef LINE_BLEND_ADDITIVE {float cov=alpha*diluted_opacity;glFragColor=vec4(cov > 0.0 ? out_color.rgb/cov : vec3(0.0),cov);} #else #ifdef LINE_BLEND_MULTIPLY glFragColor=vec4(out_color.rgb+(1.0-out_color.a),1.0); #else glFragColor=out_color; #endif #endif storeEmissiveColor(glFragColor,emissive_strength); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif #ifdef DEBUG_ELEVATION_ID glFragColor=vec4(v_elevation_id_col,1.0); #endif #ifdef ELEVATED_ROADS if (u_clip_to_tile_borders) {if (v_tile_pos.x > 1.0 || v_tile_pos.y > 1.0 || v_tile_pos.x < 0.0 || v_tile_pos.y < 0.0) {discard;}vec2 quadrant=step(vec2(0.5),v_tile_pos);vec2 row=mix(u_child_quadrants.xz,u_child_quadrants.yw,quadrant.x);if (mix(row.x,row.y,quadrant.y) > 0.5) {discard;}} #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #include "_prelude_ubo_properties.glsl" #define EXTRUDE_SCALE 0.015873016 in ivec2 a_pos_normal;in uvec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) || defined(VARIABLE_LINE_WIDTH) || defined(VARIABLE_LINE_EMISSIVE_STRENGTH) in vec4 a_z_offset_width; #endif #ifdef DEBUG_ELEVATION_ID in vec3 a_elevation_id_col; #endif #ifdef DEBUG_ELEVATION_ID out vec3 v_elevation_id_col; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #endif #ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP in highp ivec4 a_round_join_conflict_segments; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) in highp vec3 a_packed; #endif uniform bool u_has_dash;uniform bool u_has_border;in float a_linesofar;uniform mat4 u_matrix;uniform mat2 u_pixels_to_tile_units;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;uniform float u_width_scale;uniform float u_z_offset;uniform highp float u_road_view_depth_bias; #ifdef ELEVATED uniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) { #ifdef ELEVATION_REFERENCE_SEA return 0.0; #else return elevation(apos); #endif } #endif out vec2 v_normal;out vec4 v_width2_dilute;out float v_gamma_scale;out highp vec2 v_tile_pos; #ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP out highp vec4 v_round_join_conflict_offset;out highp vec4 v_round_join_conflict_dir;out mediump vec2 v_round_join_conflict_test; #endif #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH out float stub_side;out highp vec2 v_distance;uniform float u_width_addition; #endif uniform highp float u_floor_width_scale;uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out highp vec2 v_tex; #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) out highp vec3 v_uv; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) uniform float u_image_height; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #define LPP_HEADER_SIZE_VEC4 5u struct LinePaintProperties {vec4 color;vec4 border_color;float opacity;float blur;float width;float gap_width;float offset;float floorwidth;float border_width;float emissive_strength;vec4 dash;float side_z_offset;};uniform highp vec4 u_lpp_color;uniform lowp vec4 u_lpp_border_color;uniform lowp float u_lpp_opacity;uniform lowp float u_lpp_blur;uniform mediump float u_lpp_width;uniform mediump float u_lpp_gap_width;uniform lowp float u_lpp_offset;uniform lowp float u_lpp_floorwidth;uniform lowp float u_lpp_border_width;uniform lowp float u_lpp_emissive_strength;uniform highp vec4 u_lpp_dash;uniform mediump float u_lpp_side_z_offset;uniform highp float u_lpp_zoom_fraction;in float a_feature_index;layout(std140) uniform LinePaintPropertiesHeaderUniform {uvec4 header[LPP_HEADER_SIZE_VEC4];} u_lpp_header;layout(std140) uniform LinePaintPropertiesUniform {vec4 properties[MAX_UBO_SIZE_VEC4];} u_lpp_properties;out highp vec4 v_line_color;out lowp vec4 v_border_color;out lowp float v_opacity;out lowp float v_blur;out lowp float v_floorwidth;out lowp float v_border_width;out lowp float v_emissive_strength;out highp vec2 v_dash;vec4 readColor(uint base,bool isDataDriven,uint offsetVec4,vec2 headerZoom,vec4 fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 value=u_lpp_properties.properties[base+offsetVec4];return unpack_mix_color(value,zoomFactor(headerZoom.x,headerZoom.y,u_lpp_zoom_fraction));}float readFloat(uint base,bool isDataDriven,uint offsetVec4,float fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 slot=u_lpp_properties.properties[base+offsetVec4];return unpack_mix_vec2(slot.xy,zoomFactor(slot.z,slot.w,u_lpp_zoom_fraction));}highp vec4 readRaw(uint base,bool isDataDriven,uint offsetVec4,highp vec4 fallbackValue) {if (!isDataDriven) return fallbackValue;return u_lpp_properties.properties[base+offsetVec4];}LinePaintProperties readLinePaintProperties() {uint dataDrivenMask=u_lpp_header.header[0][0];uint blockSizeVec4 =u_lpp_header.header[0][2];vec2 colorHeaderZoom =uintBitsToFloat(u_lpp_header.header[4].xy);vec2 borderHeaderZoom=uintBitsToFloat(u_lpp_header.header[4].zw);uint base=uint(a_feature_index)*blockSizeVec4;LinePaintProperties props;props.color =readColor(base,(dataDrivenMask & (1u << 0u)) !=0u,u_lpp_header.header[0][3],colorHeaderZoom,u_lpp_color);props.border_color =readColor(base,(dataDrivenMask & (1u << 1u)) !=0u,u_lpp_header.header[1][0],borderHeaderZoom,u_lpp_border_color);props.opacity =readFloat(base,(dataDrivenMask & (1u << 2u)) !=0u,u_lpp_header.header[1][1],u_lpp_opacity);props.blur =readFloat(base,(dataDrivenMask & (1u << 3u)) !=0u,u_lpp_header.header[1][2],u_lpp_blur);props.width =readFloat(base,(dataDrivenMask & (1u << 4u)) !=0u,u_lpp_header.header[1][3],u_lpp_width);props.gap_width =readFloat(base,(dataDrivenMask & (1u << 5u)) !=0u,u_lpp_header.header[2][0],u_lpp_gap_width);props.offset =readFloat(base,(dataDrivenMask & (1u << 6u)) !=0u,u_lpp_header.header[2][1],u_lpp_offset);props.floorwidth =readFloat(base,(dataDrivenMask & (1u << 7u)) !=0u,u_lpp_header.header[2][2],u_lpp_floorwidth);props.border_width =readFloat(base,(dataDrivenMask & (1u << 8u)) !=0u,u_lpp_header.header[2][3],u_lpp_border_width);props.emissive_strength=readFloat(base,(dataDrivenMask & (1u << 9u)) !=0u,u_lpp_header.header[3][0],u_lpp_emissive_strength);props.dash =readRaw(base,(dataDrivenMask & (1u << 10u)) !=0u,u_lpp_header.header[3][1],u_lpp_dash);props.side_z_offset =readFloat(base,(dataDrivenMask & (1u << 11u)) !=0u,u_lpp_header.header[3][2],u_lpp_side_z_offset);return props;} #ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP highp vec3 unpackRoundJoinTestCoordinate(highp int packedCoord) {highp int x=(((packedCoord & 0xfffe) ^ 0x8000)-0x8000) >> 1;return vec3(float(x),float(packedCoord >> 16),float(packedCoord & 1));} #endif void main() {LinePaintProperties paint_properties=readLinePaintProperties();v_line_color=paint_properties.color;float floorwidth=paint_properties.floorwidth;float blur=paint_properties.blur;float opacity=paint_properties.opacity;float gapwidth=paint_properties.gap_width;float offset=paint_properties.offset;float width=paint_properties.width;float border_width=paint_properties.border_width;vec4 border_color=paint_properties.border_color;float emissive_strength=paint_properties.emissive_strength;float side_z_offset=paint_properties.side_z_offset; #ifdef VARIABLE_LINE_EMISSIVE_STRENGTH emissive_strength=a_z_offset_width.w; #endif v_border_color=border_color;v_opacity=opacity;v_blur=blur;v_floorwidth=floorwidth;v_border_width=border_width;v_emissive_strength=emissive_strength;float a_z_offset=u_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset+=a_z_offset_width.x; #endif #ifdef DEBUG_ELEVATION_ID v_elevation_id_col=a_elevation_id_col; #endif highp float line_progress=0.0; #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) line_progress=a_packed[2]; #endif float arrow_head_fraction=-1.0;float ANTIALIASING=1.0/u_device_pixel_ratio/2.0; #ifndef VARIABLE_LINE_WIDTH if (u_has_border) {ANTIALIASING*=8.0;} #endif vec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);mediump vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;offset=-1.0*offset*u_width_scale;bool left=normal.y==1.0;gapwidth=gapwidth/2.0;float halfwidth;float dilute_scale=1.0;float dilute_border_scale=1.0;vec2 side_widths=vec2(0.0); #ifdef VARIABLE_LINE_WIDTH float left_width=a_z_offset_width.y;float right_width=a_z_offset_width.z;bool zero_right_width=border_width==0.0 && right_width==0.0;side_widths=u_width_scale*(zero_right_width ? vec2(left_width+u_width_addition) : vec2(left_width,right_width)+0.5*u_width_addition);halfwidth=left ? side_widths.x : (zero_right_width ? 0.0 : side_widths.y);if (side_z_offset !=0.0) {float left_f=step(1.0,normal.y);float is_negative=step(side_z_offset,0.0);float apply=mix(1.0-left_f,left_f,is_negative);a_extrude*=apply;a_z_offset+=abs(side_z_offset)*apply;v_normal*=apply;}offset=border_width > 0.0 ? (left_width+right_width+u_width_addition)*u_width_scale : offset;halfwidth=border_width > 0.0 ? border_width*u_width_scale*0.5 : halfwidth;side_widths=border_width > 0.0 ? vec2(halfwidth) : side_widths;stub_side=zero_right_width ?-normal.y : 0.0;v_normal=!left && zero_right_width ? vec2(0.0) : v_normal;ANTIALIASING=!left && zero_right_width ? 0.0 : ANTIALIASING; #else halfwidth=(u_width_scale*width)/2.0; #endif float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth > 0.0 ? ANTIALIASING : 0.0); #ifdef VARIABLE_LINE_WIDTH v_distance=v_normal*outset; #endif mediump vec2 dist=outset*a_extrude*EXTRUDE_SCALE;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*EXTRUDE_SCALE*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy; #ifdef ELEVATED_ROADS v_road_z_offset=a_z_offset;v_tile_pos=pos+offset2*u_pixels_to_tile_units;gl_Position=u_matrix*vec4(v_tile_pos,a_z_offset,1.0); #else #ifdef ELEVATED vec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset; #ifdef ELEVATION_GROUND_SCALE scaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale); #endif #ifdef CROSS_SLOPE_VERTICAL float top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0); #else #ifdef CROSS_SLOPE_HORIZONTAL float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset; #else float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset; #endif #endif v_tile_pos=offset_pos;gl_Position=u_matrix*vec4(v_tile_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden); #else v_tile_pos=pos+offset2*u_pixels_to_tile_units;gl_Position=u_matrix*vec4(v_tile_pos,0.0,1.0); #endif #endif #ifndef ELEVATED #ifndef VARIABLE_LINE_WIDTH #ifndef RENDER_TO_TEXTURE float base_w=gl_Position.w;vec2 screen_width=abs(projected_extrude.xy/base_w*u_units_to_pixels);float max_extrude_component=max(screen_width.x,screen_width.y);if (width >=1.0 && base_w > 0.0 && max_extrude_component > 0.0001) {float min_pixel=1.05;if (max_extrude_component < min_pixel) {vec2 abs_pos=abs(gl_Position.xy);float is_out=max(abs_pos.x,abs_pos.y)/base_w;dilute_scale=mix(max_extrude_component/min_pixel,1.0,smoothstep(2.5,4.5,is_out));projected_extrude/=dilute_scale;}else if (gapwidth > 0.0) {float visible_ratio=(halfwidth+ANTIALIASING)/outset;vec2 visible_screen_width=screen_width*visible_ratio;float max_visible_component=max(visible_screen_width.x,visible_screen_width.y);dilute_scale=min(1.0,max_visible_component/min_pixel);}else {if (u_has_border) {float border_ratio=(border_width*u_width_scale+ANTIALIASING)/outset;screen_width*=border_ratio;float max_border_component=max(screen_width.x,screen_width.y);dilute_border_scale=min(1.0,max_border_component/min_pixel);}}} #endif #endif #ifdef VARIABLE_LINE_WIDTH #ifndef RENDER_TO_TEXTURE vec2 ndc=gl_Position.xy/gl_Position.w;vec4 projected_tangent=u_matrix*vec4(extrude.y,-extrude.x,0.0,0.0);vec2 screen_extrude=(projected_extrude.xy-ndc*projected_extrude.w)*u_units_to_pixels;vec2 screen_tangent=(projected_tangent.xy-ndc*projected_tangent.w)*u_units_to_pixels;float thickness=abs(screen_extrude.x*screen_tangent.y-screen_extrude.y*screen_tangent.x)/max(length(screen_tangent),1e-6);float thickness_px=max(thickness,0.2*length(screen_extrude))/gl_Position.w*u_device_pixel_ratio;float headroom_scale=gl_Position.w > 0.0 ? 1.0+(1.0-smoothstep(2.0,4.0,thickness_px))/max(thickness_px,0.0001) : 1.0;projected_extrude*=headroom_scale;extrude*=headroom_scale;v_distance*=headroom_scale; #endif #endif v_tile_pos=(v_tile_pos+extrude)/EXTENT; #ifdef ELEVATED_ROADS gl_Position=gl_Position+projected_extrude; #ifdef VARIABLE_LINE_WIDTH #ifndef ELEVATED gl_Position.z-=u_road_view_depth_bias*smoothstep(-0.5,0.0,a_z_offset); #endif #endif #else gl_Position=mix(gl_Position+projected_extrude,AWAY,hidden); #endif #endif #ifdef ELEVATED_ROADS #ifdef RENDER_SHADOWS vec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #endif #ifndef RENDER_TO_TEXTURE float epsilon=0.0001;float extrude_length_without_perspective=max(length(dist),epsilon);float extrude_length_with_perspective=max(length(projected_extrude_xy/gl_Position.w*u_units_to_pixels),epsilon);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur)); #else v_gamma_scale=1.0; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) highp float a_uv_x=a_packed[0];float a_split_index=a_packed[1]; #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec3(a_uv_x,a_split_index*texel_height-half_texel_height,line_progress); #else v_uv=vec3(a_uv_x,0.0,line_progress); #endif #endif if (u_has_dash) {highp vec4 dashf=paint_properties.dash;highp float dash_w=dashf.w;highp float totalLength=dashf.z+dash_w/65535.0;float scale=totalLength==0.0 ? 0.0 : u_tile_units_to_pixels/totalLength;highp uint dash_bits=uint(dashf.y+0.5);float dash_half_height=float(dash_bits & 15u);float dash_coverage=float(dash_bits >> 4u)/4095.0;v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*dash_half_height+dashf.x+0.5)/u_texsize.y);v_dash=vec2(totalLength,dash_coverage);} else {v_tex=vec2(0.0);v_dash=vec2(0.0);}v_width2_dilute=vec4(outset,inset,dilute_scale,dilute_border_scale); #ifdef VARIABLE_LINE_WIDTH v_width2_dilute.xy=side_widths; #endif #ifdef LINE_ROUND_JOIN_CLIP_BORDER_OVERLAP highp float tileToPixels=1.0/u_pixels_to_tile_units[0][0];highp vec2 testPos=pos+extrude/dilute_scale;highp vec3 prevA=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.x);highp vec3 prevB=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.y);highp vec3 nextA=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.z);highp vec3 nextB=unpackRoundJoinTestCoordinate(a_round_join_conflict_segments.w);v_round_join_conflict_offset=vec4(testPos-prevA.xy,testPos-nextA.xy)*tileToPixels;v_round_join_conflict_dir=vec4(prevB.xy-prevA.xy,nextB.xy-nextA.xy)*tileToPixels;v_round_join_conflict_test=vec2(prevA.z,nextA.z); #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),linePattern:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" uniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;uniform lowp float u_opacity_multiplier;uniform highp vec2 u_texsize;uniform highp float u_tile_units_to_pixels;uniform highp vec2 u_trim_offset;uniform highp vec2 u_trim_fade_range;uniform lowp vec4 u_trim_color;uniform sampler2D u_image; #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #ifdef LINE_PATTERN_TRANSITION uniform float u_pattern_transition; #endif in vec2 v_normal;in vec2 v_width2;in highp float v_linesofar;in float v_gamma_scale;in float v_width; #ifdef RENDER_LINE_TRIM_OFFSET in highp vec3 v_uv; #endif #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef LINE_JOIN_NONE in vec2 v_pattern_data; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #pragma mapbox: define mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define mediump float pixel_ratio #pragma mapbox: define mediump float blur #pragma mapbox: define mediump float opacity #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize mediump float pixel_ratio #pragma mapbox: initialize mediump float blur #pragma mapbox: initialize mediump float opacity #pragma mapbox: initialize lowp float emissive_strength vec2 pattern_tl=vec2(pattern.xy);vec2 pattern_br=vec2(pattern.zw);vec2 display_size=(pattern_br-pattern_tl)/pixel_ratio;highp float pattern_size=display_size.x/u_tile_units_to_pixels;float aspect=display_size.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(u_width_scale*blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);highp float pattern_x=v_linesofar/pattern_size*aspect;highp float x=mod(pattern_x,1.0);highp float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;highp vec2 pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(x,y));highp vec2 lod_pos=mix(pattern_tl*texel_size-texel_size,pattern_br*texel_size+texel_size,vec2(pattern_x,y));vec4 color=textureLodCustom(u_image,pos,lod_pos); #ifdef APPLY_LUT_ON_GPU color=applyLUT(u_lutTexture,color); #endif #ifdef LINE_PATTERN_TRANSITION vec2 pattern_b_tl=vec2(pattern_b.xy);vec2 pattern_b_br=vec2(pattern_b.zw);highp vec2 pos_b=mix(pattern_b_tl*texel_size-texel_size,pattern_b_br*texel_size+texel_size,vec2(x,y));vec4 color_b=textureLodCustom(u_image,pos_b,lod_pos);color=color*(1.0-u_pattern_transition)+color_b*u_pattern_transition; #endif #ifdef RENDER_LINE_TRIM_OFFSET highp float trim_start=u_trim_offset[0];highp float trim_end=u_trim_offset[1];highp float line_progress=v_uv[2];if (trim_end > trim_start) {highp float start_transition=max(0.0,min(1.0,(line_progress-trim_start)/max(u_trim_fade_range[0],1.0e-9)));highp float end_transition=max(0.0,min(1.0,(trim_end-line_progress)/max(u_trim_fade_range[1],1.0e-9)));highp float transition_factor=min(start_transition,end_transition);color=mix(color,color.a*u_trim_color,transition_factor);} #endif #ifdef LINE_JOIN_NONE highp float pattern_len=pattern_size/aspect;highp float segment_phase=pattern_len-mod(v_linesofar-v_pattern_data.x+pattern_len,pattern_len);highp float visible_start=segment_phase-step(pattern_len*0.5,segment_phase)*pattern_len;highp float visible_end=floor((v_pattern_data.y-segment_phase)/pattern_len)*pattern_len+segment_phase;visible_end+=step(pattern_len*0.5,v_pattern_data.y-visible_end)*pattern_len;if (v_pattern_data.x < visible_start || v_pattern_data.x >=visible_end) {color=vec4(0.0);} #endif #ifdef LIGHTING_3D_MODE color=apply_lighting_with_emission_ground(color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth); #ifdef ELEVATED_ROADS color.rgb*=mix(v_road_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #else color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #endif color*=(alpha*opacity*u_opacity_multiplier);if (u_alpha_discard_threshold !=0.0) {if (color.a < u_alpha_discard_threshold) {discard;}}glFragColor=color;storeEmissiveColor(glFragColor,emissive_strength); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_terrain.vertex.glsl" #define scale 0.015873016 in ivec2 a_pos_normal;in uvec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) in vec4 a_z_offset_width; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #endif #ifdef RENDER_LINE_TRIM_OFFSET in highp vec3 a_packed; #endif in highp float a_linesofar; #ifdef LINE_JOIN_NONE in highp vec3 a_pattern_data;out vec2 v_pattern_data; #endif uniform mat4 u_matrix;uniform float u_tile_units_to_pixels;uniform vec2 u_units_to_pixels;uniform mat2 u_pixels_to_tile_units;uniform float u_device_pixel_ratio;uniform float u_width_scale;uniform float u_floor_width_scale; #ifdef ELEVATED uniform lowp float u_zbias_factor;uniform lowp float u_tile_to_meter;float sample_elevation(vec2 apos) { #ifdef ELEVATION_REFERENCE_SEA return 0.0; #else return elevation(apos); #endif } #endif out vec2 v_normal;out vec2 v_width2;out highp float v_linesofar;out float v_gamma_scale;out float v_width; #ifdef RENDER_LINE_TRIM_OFFSET out highp vec3 v_uv; #endif #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #pragma mapbox: define mediump float blur #pragma mapbox: define mediump float opacity #pragma mapbox: define mediump float offset #pragma mapbox: define mediump float gapwidth #pragma mapbox: define mediump float width #pragma mapbox: define mediump float floorwidth #pragma mapbox: define mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: define mediump uvec4 pattern_b #endif #pragma mapbox: define mediump float pixel_ratio #pragma mapbox: define lowp float emissive_strength void main() { #pragma mapbox: initialize mediump float blur #pragma mapbox: initialize mediump float opacity #pragma mapbox: initialize mediump float offset #pragma mapbox: initialize mediump float gapwidth #pragma mapbox: initialize mediump float width #pragma mapbox: initialize mediump float floorwidth #pragma mapbox: initialize mediump uvec4 pattern #ifdef LINE_PATTERN_TRANSITION #pragma mapbox: initialize mediump uvec4 pattern_b #endif #pragma mapbox: initialize mediump float pixel_ratio #pragma mapbox: initialize lowp float emissive_strength float a_z_offset; #if defined(ELEVATED) || defined(ELEVATED_ROADS) a_z_offset=a_z_offset_width.x; #endif float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(a_data.xy)-128.0;float a_direction=float(a_data.z & 3u)-1.0;vec2 pos_normal=vec2(a_pos_normal);vec2 pos=floor(pos_normal*0.5);vec2 normal=pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=(u_width_scale*width)/2.0;offset=-1.0*offset*u_width_scale;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);vec2 dist=outset*a_extrude*scale;float u=0.5*a_direction;float t=1.0-abs(u);vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float hidden=float(opacity==0.0);vec2 extrude=dist*u_pixels_to_tile_units;vec4 projected_extrude=u_matrix*vec4(extrude,0.0,0.0);vec2 projected_extrude_xy=projected_extrude.xy; #ifdef ELEVATED_ROADS v_road_z_offset=a_z_offset;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,a_z_offset,1.0)+projected_extrude; #else #ifdef ELEVATED vec2 offsetTile=offset2*u_pixels_to_tile_units;vec2 offset_pos=pos+offsetTile;float ele=0.0;float scaled_z_offset=a_z_offset; #ifdef ELEVATION_GROUND_SCALE scaled_z_offset=a_z_offset*mix(1.0,u_exaggeration,a_elevation_ground_scale); #endif #ifdef CROSS_SLOPE_VERTICAL float top=pos_normal.y-2.0*floor(pos_normal.y*0.5);float line_height=2.0*u_tile_to_meter*outset*top*u_pixels_to_tile_units[1][1]+scaled_z_offset;ele=sample_elevation(offset_pos)+line_height;projected_extrude=vec4(0); #else #ifdef CROSS_SLOPE_HORIZONTAL float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,max(ele1,ele2));ele=ele_max+scaled_z_offset; #else float ele0=sample_elevation(offset_pos);float ele1=max(sample_elevation(offset_pos+extrude),sample_elevation(offset_pos+extrude/2.0));float ele2=max(sample_elevation(offset_pos-extrude),sample_elevation(offset_pos-extrude/2.0));float ele_max=max(ele0,0.5*(ele1+ele2));ele=ele_max-ele0+ele1+scaled_z_offset; #endif #endif gl_Position=u_matrix*vec4(offset_pos,ele,1.0)+projected_extrude;float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor*u_exaggeration);gl_Position.z-=(gl_Position.w*zbias);gl_Position=mix(gl_Position,AWAY,hidden); #else gl_Position=mix(u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,0.0,1.0)+projected_extrude,AWAY,hidden); #endif #endif #ifdef ELEVATED_ROADS #ifdef RENDER_SHADOWS vec3 shd_pos=vec3(pos+(offset2+dist)*u_pixels_to_tile_units,a_z_offset);vec3 shd_pos0=shd_pos;vec3 shd_pos1=shd_pos; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #endif #ifndef RENDER_TO_TEXTURE float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude_xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=mix(extrude_length_without_perspective/extrude_length_with_perspective,1.0,step(0.01,blur)); #else v_gamma_scale=1.0; #endif #ifdef RENDER_LINE_TRIM_OFFSET highp float a_uv_x=a_packed[0];highp float line_progress=a_packed[2];v_uv=vec3(a_uv_x,0.0,line_progress); #endif v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=(floorwidth*u_floor_width_scale); #ifdef LINE_JOIN_NONE v_width=(floorwidth*u_floor_width_scale)+ANTIALIASING;mediump float pixels_to_tile_units=1.0/u_tile_units_to_pixels;mediump float pixel_ratio_inverse=1.0/pixel_ratio;mediump float aspect=v_width/(float(pattern.w-pattern.y)*pixel_ratio_inverse);highp float subt_multiple=float(pattern.z-pattern.x)*pixel_ratio_inverse*pixels_to_tile_units*aspect*32.0;highp float subt=floor(a_pattern_data.z/subt_multiple)*subt_multiple;float offset_sign=(fract(a_pattern_data.x)-0.5)*4.0;float line_progress_offset=offset_sign*v_width*0.5*pixels_to_tile_units;v_linesofar=(a_pattern_data.z-subt)+a_linesofar+line_progress_offset;v_pattern_data=vec2(a_pattern_data.x+line_progress_offset,a_pattern_data.y); #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif }`),raster:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_raster_array.glsl" uniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;uniform highp float u_zoom_transition;in vec2 v_pos0;in vec2 v_pos1;in float v_depth; #ifdef PROJECTION_GLOBE_VIEW in float v_split_fade; #endif uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;uniform float u_emissive_strength; #ifndef RASTER_ARRAY uniform highp sampler2D u_image0;uniform sampler2D u_image1; #endif #ifdef RASTER_COLOR uniform sampler2D u_color_ramp;uniform highp vec4 u_colorization_mix;uniform highp float u_colorization_offset;uniform vec2 u_texture_res;uniform highp float u_color_ramp_size; #endif void main() {vec4 color0,color1,color;vec2 value; #ifdef RASTER_COLOR #ifdef RASTER_ARRAY #ifdef RASTER_ARRAY_LINEAR value=mix( raTexture2D_image0_linear(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_linear(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t ); #else value=mix( raTexture2D_image0_nearest(v_pos0,u_texture_res,u_colorization_mix,u_colorization_offset),raTexture2D_image1_nearest(v_pos1,u_texture_res,u_colorization_mix,u_colorization_offset),u_fade_t ); #endif if (value.y > 0.0) value.x/=value.y; #ifdef RASTER_COLOR_SCALE_LOG float N=u_color_ramp_size;float vNorm=max((value.x-0.5/N)*N/(N-1.0),0.0);vNorm=log(vNorm*(10.0-1.0)+1.0)/log(10.0);value.x=0.5/N+vNorm*(N-1.0)/N; #endif #else color=mix(texture(u_image0,v_pos0),texture(u_image1,v_pos1),u_fade_t);value=vec2(u_colorization_offset+dot(color.rgb,u_colorization_mix.rgb),color.a); #endif color=texture(u_color_ramp,vec2(value.x,0.5));if (color.a > 0.0) color.rgb/=color.a;color.a*=value.y; #else color0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t); #endif color.a*=u_opacity; #ifdef GLOBE_POLES color.a*=1.0-smoothstep(0.0,0.05,u_zoom_transition); #endif vec3 rgb=color.rgb;rgb=vec3( dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);vec3 out_color=mix(u_high_vec,u_low_vec,rgb); #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),u_emissive_strength).rgb; #endif #ifdef FOG highp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit)); #endif glFragColor=vec4(out_color*color.a,color.a); #ifdef PROJECTION_GLOBE_VIEW glFragColor*=mix(1.0,1.0-smoothstep(0.0,0.05,u_zoom_transition),smoothstep(0.8,0.9,v_split_fade)); #endif #ifdef RENDER_CUTOFF glFragColor=glFragColor*cutoff_opacity(u_cutoff_params,v_depth); #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif storeEmissiveColor(glFragColor,u_emissive_strength);HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform vec2 u_perspective_transform;uniform vec2 u_texture_offset;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center; #ifdef ELEVATED uniform lowp float u_zbias_factor; #endif #define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8 #ifdef GLOBE_POLES in vec3 a_globe_pos;in vec2 a_uv; #else in ivec2 a_pos;in uvec2 a_texture_pos; #endif out vec2 v_pos0;out vec2 v_pos1;out float v_depth; #ifdef PROJECTION_GLOBE_VIEW out float v_split_fade; #endif void main() {vec2 uv; #ifdef GLOBE_POLES vec3 globe_pos=a_globe_pos;uv=a_uv;float ele=u_raster_elevation; #ifdef ELEVATION_REFERENCE_GROUND ele+=elevation(uv*EXTENT); #endif globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;gl_Position=u_matrix*u_globe_matrix*vec4(globe_pos,1.0); #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(a_globe_pos,1.0)).xyz); #endif #else vec4 world_pos; #ifdef PROJECTION_GLOBE_VIEW vec2 texture_pos=vec2(a_texture_pos);uv=texture_pos/8192.0;vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]);float tiles=u_grid_matrix[0][2];if (tiles > 0.0) {float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvY=mercatorY*tiles-idy;float uvX=mercatorX*tiles-idx;uv=vec2(uvX,uvY);}float ele=u_raster_elevation; #ifdef ELEVATION_REFERENCE_GROUND ele+=elevation(uv*EXTENT)-decomposed_pos_and_skirt.z; #endif vec4 merc_world_pos=vec4(0.0);v_split_fade=0.0;if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,ele,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;float opposite_merc_center=mod(u_merc_center.x+0.5,1.0);float dist_from_poles=(abs(mercatorY-0.5)*2.0);float range=0.1;v_split_fade=abs(opposite_merc_center-mercatorX);v_split_fade=clamp(1.0-v_split_fade,0.0,1.0);v_split_fade=max(smoothstep(1.0-range,1.0,dist_from_poles),max(smoothstep(1.0-range,1.0,v_split_fade),smoothstep(1.0-range,1.0,1.0-v_split_fade)));}vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*ele*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);world_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0); #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif #else float ele=0.0;vec2 decodedPos=vec2(a_pos); #ifdef ELEVATION_REFERENCE_GROUND vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;decodedPos=decomposedPosAndSkirt.xy;uv=decodedPos/8192.0;ele=elevation(decodedPos)-skirt; #else uv=vec2(a_texture_pos)/8192.0; #endif world_pos=vec4(decodedPos,(u_raster_elevation+ele),1.0); #ifdef FOG v_fog_pos=fog_position(decodedPos); #endif #endif float w=1.0+dot(uv*EXTENT,u_perspective_transform);gl_Position=u_matrix*world_pos*w; #endif v_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;v_pos0=u_texture_offset.x+u_texture_offset.y*v_pos0;v_pos1=u_texture_offset.x+u_texture_offset.y*v_pos1; #ifdef ELEVATED float z=clamp(gl_Position.z/gl_Position.w,0.5,1.0);float zbias=max(0.00005,(pow(z,0.8)-z)*u_zbias_factor);gl_Position.z-=(gl_Position.w*zbias); #endif #ifdef RENDER_CUTOFF v_depth=native_clip_z_to_cutoff_depth(gl_Position.z,gl_Position.w); #endif }`),symbol:Zi(`#include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" #define SDF_PX 8.0 #define SDF 1.0 #define ICON 0.0 uniform sampler2D u_texture; #ifdef RENDER_TEXT_AND_SYMBOL uniform sampler2D u_texture_icon; #endif uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_sdf;uniform lowp float u_scale_factor;uniform lowp float u_opacity_multiplier; #ifdef ICON_TRANSITION uniform float u_icon_transition; #endif #ifdef COLOR_ADJUSTMENT uniform mat4 u_color_adj_mat; #endif #ifdef RENDER_SHADOWS in highp float v_z_offset; #endif in vec2 v_tex_a; #ifdef ICON_TRANSITION in vec2 v_tex_b; #endif in float v_draw_halo;in vec3 v_gamma_scale_size_fade_opacity; #ifdef RENDER_TEXT_AND_SYMBOL in float is_sdf;in vec2 v_tex_a_icon; #endif #ifdef RENDER_SHADOWS uniform vec3 u_ground_shadow_factor;in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in highp float v_depth; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif in lowp float v_opacity;in lowp vec4 v_fill_np_color;in lowp vec4 v_halo_np_color;in lowp float v_halo_width;in lowp float v_halo_blur; #ifdef LIGHTING_3D_MODE in lowp float v_emissive_strength; #endif void main() {lowp float opacity=v_opacity;lowp vec4 fill_color=vec4(0.0);lowp vec4 halo_color=vec4(0.0);lowp float halo_width=0.0;lowp float halo_blur=0.0;if (u_is_sdf) {fill_color=vec4(v_fill_np_color.rgb*v_fill_np_color.a,v_fill_np_color.a);halo_color=vec4(v_halo_np_color.rgb*v_halo_np_color.a,v_halo_np_color.a);halo_width=v_halo_width;halo_blur=v_halo_blur;}lowp float emissive_strength=0.0; #ifdef LIGHTING_3D_MODE emissive_strength=v_emissive_strength; #endif vec4 out_color;float fade_opacity=v_gamma_scale_size_fade_opacity[2]; #ifdef RENDER_TEXT_AND_SYMBOL if (is_sdf==ICON) {vec2 tex_icon=v_tex_a_icon;lowp float alpha=opacity*fade_opacity*u_opacity_multiplier;glFragColor=texture(u_texture_icon,tex_icon)*alpha; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif return;} #endif vec2 cutout_factors=vec2(0.0);if (u_is_sdf) {float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_gamma_scale_size_fade_opacity.x;float size=v_gamma_scale_size_fade_opacity.y;float fontScale=u_is_text ? size/24.0 : size;out_color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;bool draw_halo=v_draw_halo > 0.0;if (draw_halo) {out_color=halo_color;gamma=(halo_blur*u_scale_factor*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width*u_scale_factor/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,v_tex_a).r;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);out_color*=alpha;} else { #ifdef ICON_TRANSITION vec4 a=texture(u_texture,v_tex_a)*(1.0-u_icon_transition);vec4 b=texture(u_texture,v_tex_b)*u_icon_transition;out_color=(a+b); #else out_color=texture(u_texture,v_tex_a); #endif #ifdef APPLY_LUT_ON_GPU out_color=applyLUT(u_lutTexture,out_color); #endif #ifdef COLOR_ADJUSTMENT out_color=u_color_adj_mat*out_color; #endif }out_color*=opacity*fade_opacity*u_opacity_multiplier; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(out_color,emissive_strength); #ifdef RENDER_SHADOWS float light=shadowed_light_factor(v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y); #ifdef TERRAIN out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #else out_color.rgb*=mix(v_z_offset !=0.0 ? u_ground_shadow_factor : vec3(1.0),vec3(1.0),light); #endif #endif #endif glFragColor=out_color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_terrain.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_ubo_properties.glsl" #define USING_APPEARANCE 1.0 in ivec4 a_pos_offset;in uvec4 a_tex_size;in ivec4 a_pixeloffset;in vec4 a_projected_pos; #define FADE_TIME_HALF_PERIOD 2147483648u #define FADE_TIME_PERIOD 4294967296.0 #ifdef GLOBAL_PLACEMENT_FADE in highp ivec2 a_fade_ref_time; #endif #ifdef LEGACY_PLACEMENT_FADE in uint a_fade_opacity; #endif #ifdef Z_OFFSET in float a_auto_z_offset; #endif #ifdef PROJECTION_GLOBE_VIEW in ivec4 a_globe_anchor;in vec3 a_globe_normal; #endif #ifdef ICON_TRANSITION in uvec2 a_texb; #endif #ifdef ELEVATED_ROADS in vec3 a_x_axis;in vec3 a_y_axis;uniform float u_normal_scale; #endif #ifdef RENDER_SHADOWS out highp float v_z_offset; #endif uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix; #ifdef RENDER_SHADOWS uniform mat4 u_inv_matrix; #endif uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_elevation_from_sea;uniform bool u_pitch_with_map;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance; #ifdef GLOBAL_PLACEMENT_FADE uniform highp int u_now;uniform float u_fade_duration; #endif #ifdef LEGACY_PLACEMENT_FADE uniform float u_fade_change; #endif uniform vec2 u_texsize; #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_up_vector; #endif #ifdef RENDER_TEXT_AND_SYMBOL uniform vec2 u_texsize_icon; #endif uniform bool u_is_halo; #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_tile_id;uniform mat4 u_inv_rot_matrix;uniform vec2 u_merc_center;uniform vec3 u_camera_forward;uniform float u_zoom_transition;uniform vec3 u_ecef_origin;uniform mat4 u_tile_matrix; #endif out vec2 v_tex_a; #ifdef ICON_TRANSITION out vec2 v_tex_b; #endif out float v_draw_halo;out vec3 v_gamma_scale_size_fade_opacity; #ifdef RENDER_TEXT_AND_SYMBOL out float is_sdf;out vec2 v_tex_a_icon; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out highp float v_depth; #endif #define SPP_HEADER_SIZE_VEC4 4u struct SymbolPaintProperties {vec4 fill_np_color;vec4 halo_np_color;float opacity;float halo_width;float halo_blur;float emissive_strength;float occlusion_opacity;float z_offset;vec2 translate;};uniform lowp vec4 u_spp_fill_np_color;uniform lowp vec4 u_spp_halo_np_color;uniform lowp float u_spp_opacity;uniform lowp float u_spp_halo_width;uniform lowp float u_spp_halo_blur;uniform lowp float u_spp_emissive_strength;uniform lowp float u_spp_occlusion_opacity;uniform highp float u_spp_z_offset;uniform lowp vec2 u_spp_translate_rotation;uniform highp float u_spp_zoom_fraction;in float a_feature_index;layout(std140) uniform SymbolPaintPropertiesHeaderUniform {uvec4 header[SPP_HEADER_SIZE_VEC4];} u_spp_header;layout(std140) uniform SymbolPaintPropertiesUniform {vec4 properties[MAX_UBO_SIZE_VEC4];} u_spp_properties;layout(std140) uniform SymbolPaintPropertiesIndexUniform {uvec4 block_indices[MAX_UBO_SIZE_VEC4];} u_spp_index;out lowp float v_opacity;out lowp vec4 v_fill_np_color;out lowp vec4 v_halo_np_color;out lowp float v_halo_width;out lowp float v_halo_blur; #ifdef LIGHTING_3D_MODE out lowp float v_emissive_strength; #endif uint uvec4At(uvec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}vec4 readColor(uint base,bool isDataDriven,uint offsetVec4,uint dzr,vec2 headerZoom,vec4 fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 value=u_spp_properties.properties[base+offsetVec4];vec2 blockZoom=u_spp_properties.properties[base+offsetVec4+dzr].xy;vec2 zr=mix(headerZoom,blockZoom,float(dzr));return unpack_mix_color(value,zoomFactor(zr.x,zr.y,u_spp_zoom_fraction));}float readScalar(uint base,bool isDataDriven,uint offsetVec4,float fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 slot=u_spp_properties.properties[base+offsetVec4];return unpack_mix_vec2(slot.xy,zoomFactor(slot.z,slot.w,u_spp_zoom_fraction));}vec2 readTranslate(uint base,bool isDataDriven,uint offsetVec4,uint dzr) {if (!isDataDriven) return vec2(0.0);vec4 value=u_spp_properties.properties[base+offsetVec4];vec2 blockZoom=u_spp_properties.properties[base+offsetVec4+dzr].xy;float t=zoomFactor(blockZoom.x,blockZoom.y,u_spp_zoom_fraction)*float(dzr);return mix(value.xy,value.zw,t);}SymbolPaintProperties readSymbolPaintProperties() {uint dataDrivenMask=u_spp_header.header[0][0];uint dzrMask =u_spp_header.header[0][1];uint blockSizeVec4 =u_spp_header.header[0][2];uint fillColorDzr=dzrMask & 1u;uint haloColorDzr=(dzrMask >> 1u) & 1u;vec2 fillColorHeaderZoom=uintBitsToFloat(u_spp_header.header[3].xy);vec2 haloColorHeaderZoom=uintBitsToFloat(u_spp_header.header[3].zw);uint featureIndex=uint(a_feature_index);uvec4 indexSlot=u_spp_index.block_indices[featureIndex/4u];uint base=uvec4At(indexSlot,featureIndex % 4u)*blockSizeVec4;SymbolPaintProperties props;props.fill_np_color =readColor(base,(dataDrivenMask & (1u << 0u)) !=0u,u_spp_header.header[0][3],fillColorDzr,fillColorHeaderZoom,u_spp_fill_np_color);props.halo_np_color =readColor(base,(dataDrivenMask & (1u << 1u)) !=0u,u_spp_header.header[1][0],haloColorDzr,haloColorHeaderZoom,u_spp_halo_np_color);props.opacity =readScalar(base,(dataDrivenMask & (1u << 2u)) !=0u,u_spp_header.header[1][1],u_spp_opacity);props.halo_width =readScalar(base,(dataDrivenMask & (1u << 3u)) !=0u,u_spp_header.header[1][2],u_spp_halo_width);props.halo_blur =readScalar(base,(dataDrivenMask & (1u << 4u)) !=0u,u_spp_header.header[1][3],u_spp_halo_blur);props.emissive_strength=readScalar(base,(dataDrivenMask & (1u << 5u)) !=0u,u_spp_header.header[2][0],u_spp_emissive_strength);props.occlusion_opacity=readScalar(base,(dataDrivenMask & (1u << 6u)) !=0u,u_spp_header.header[2][1],u_spp_occlusion_opacity);props.z_offset =readScalar(base,(dataDrivenMask & (1u << 7u)) !=0u,u_spp_header.header[2][2],u_spp_z_offset);uint translateDzr=(dzrMask >> 8u) & 1u;props.translate =readTranslate(base,(dataDrivenMask & (1u << 8u)) !=0u,u_spp_header.header[2][3],translateDzr);return props;}vec2 unpack_opacity(uint packedOpacity) {return vec2(float(packedOpacity/2u)/127.0,float(packedOpacity & 1u));}void main() {SymbolPaintProperties paint_properties=readSymbolPaintProperties();lowp float opacity=paint_properties.opacity;v_opacity=opacity;v_fill_np_color=paint_properties.fill_np_color;v_halo_np_color=paint_properties.halo_np_color;v_halo_width=paint_properties.halo_width;v_halo_blur=paint_properties.halo_blur; #ifdef LIGHTING_3D_MODE v_emissive_strength=paint_properties.emissive_strength; #endif lowp float occlusion_opacity=paint_properties.occlusion_opacity;highp float z_offset=paint_properties.z_offset;vec2 a_pos=vec2(a_pos_offset.xy);vec2 a_offset=vec2(a_pos_offset.zw);vec2 a_tex=vec2(a_tex_size.xy);vec2 a_size=vec2(a_tex_size.zw);float a_size_min=floor(a_size[0]*0.5);float a_size_max= floor(a_size[1]*0.5);float a_apperance=a_size[1]-2.0*a_size_max;vec2 a_pxoffset=vec2(a_pixeloffset.xy);vec2 a_min_font_scale=vec2(a_pixeloffset.zw)/256.0;highp float segment_angle=-a_projected_pos[3];float size;if (a_apperance==USING_APPEARANCE) {size=a_size_max/128.0;} else if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size_max,u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 tile_anchor=a_pos;float e=u_elevation_from_sea ? z_offset : z_offset+elevation(tile_anchor); #ifdef Z_OFFSET e+=a_auto_z_offset; #endif vec3 h=elevationVector(tile_anchor)*e;float globe_occlusion_fade;vec3 world_pos;vec3 mercator_pos;vec3 world_pos_globe; #ifdef PROJECTION_GLOBE_VIEW mercator_pos=mercator_tile_position(u_inv_rot_matrix,tile_anchor,u_tile_id,u_merc_center);world_pos_globe=vec3(a_globe_anchor)+h;world_pos=mix_globe_mercator(world_pos_globe,mercator_pos,u_zoom_transition);vec4 ecef_point=u_tile_matrix*vec4(world_pos,1.0);vec3 origin_to_point=ecef_point.xyz-u_ecef_origin;globe_occlusion_fade=dot(origin_to_point,u_camera_forward) >=0.0 ? 0.0 : 1.0; #else world_pos=vec3(tile_anchor,0)+h;globe_occlusion_fade=1.0; #endif vec4 projected_point=u_matrix*vec4(world_pos,1);highp float camera_to_anchor_distance=projected_point.w;highp float distance_ratio=u_pitch_with_map ? camera_to_anchor_distance/u_camera_to_center_distance : u_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp( 0.5+0.5*distance_ratio,0.0,1.5);size*=perspective_ratio;float font_scale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetprojected_point;vec2 a; #ifdef PROJECTION_GLOBE_VIEW vec3 displacement=vec3(a_globe_normal.z,0,-a_globe_normal.x);offsetprojected_point=u_matrix*vec4(vec3(a_globe_anchor)+displacement,1);vec4 projected_point_globe=u_matrix*vec4(world_pos_globe,1);a=projected_point_globe.xy/projected_point_globe.w; #else offsetprojected_point=u_matrix*vec4(tile_anchor+vec2(1,0),0,1);a=projected_point.xy/projected_point.w; #endif vec2 b=offsetprojected_point.xy/offsetprojected_point.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}vec4 projected_pos; #ifdef PROJECTION_GLOBE_VIEW #ifdef PROJECTED_POS_ON_VIEWPORT projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xyz+h,1.0); #else vec3 proj_pos=mix_globe_mercator(a_projected_pos.xyz,mercator_pos,u_zoom_transition)+h;projected_pos=u_label_plane_matrix*vec4(proj_pos,1.0); #endif #else projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,h.z,1.0); #endif highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);float z=0.0;vec2 offset=rotation_matrix*(a_offset/32.0*max(a_min_font_scale,font_scale)+a_pxoffset/16.0); #ifdef TERRAIN #ifdef PITCH_WITH_MAP_TERRAIN vec4 tile_pos=u_label_plane_matrix_inv*vec4(a_projected_pos.xy+offset,0.0,1.0);z=elevation(tile_pos.xy); #endif #endif #ifdef Z_OFFSET z+=u_pitch_with_map ? a_auto_z_offset+z_offset : 0.0; #else z+=u_pitch_with_map ? z_offset : 0.0; #endif float occlusion_fade=globe_occlusion_fade;float out_fade_opacity=occlusion_fade; #ifdef GLOBAL_PLACEMENT_FADE highp int fade_state=a_fade_ref_time.y;float fade_target=float(fade_state & 1);highp uint fade_elapsed_bits=uint(u_now)-uint(a_fade_ref_time.x);float fade_elapsed=float(fade_elapsed_bits);if (fade_elapsed_bits >=FADE_TIME_HALF_PERIOD) fade_elapsed-=FADE_TIME_PERIOD;bool fade_settled=(fade_state & 2) !=0;float fade_t=(fade_settled || u_fade_duration==0.0) ? 1.0 : fade_elapsed/u_fade_duration;float raw_fade_opacity=fade_target > 0.5 ? fade_t : 1.0-fade_t;out_fade_opacity=clamp(raw_fade_opacity,0.0,occlusion_fade); #endif #ifdef LEGACY_PLACEMENT_FADE vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change)); #endif #ifdef DEPTH_OCCLUSION float depth_occlusion=occlusionFadeMultiSample(projected_point);float depth_occlusion_multplier=mix(occlusion_opacity,1.0,depth_occlusion);out_fade_opacity*=depth_occlusion_multplier; #endif float alpha=opacity*out_fade_opacity;float hidden=float(alpha==0.0 || projected_point.w <=0.0 || occlusion_fade==0.0);vec3 pos; #ifdef PROJECTION_GLOBE_VIEW vec3 xAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,u_up_vector)) : vec3(1,0,0);vec3 yAxis=u_pitch_with_map ? normalize(cross(a_globe_normal,xAxis)) : vec3(0,1,0);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y; #else #ifdef ELEVATED_ROADS vec3 xAxis=vec3(a_x_axis.xy,a_x_axis.z*u_normal_scale);vec3 yAxis=vec3(a_y_axis.xy,a_y_axis.z*u_normal_scale);pos=projected_pos.xyz/projected_pos.w+xAxis*offset.x+yAxis*offset.y; #else pos=vec3(projected_pos.xy/projected_pos.w+offset,z); #endif #endif gl_Position=mix(u_coord_matrix*vec4(pos,1.0),AWAY,hidden);{vec2 tr=paint_properties.translate;vec2 rotated_tr=vec2( u_spp_translate_rotation.x*tr.x-u_spp_translate_rotation.y*tr.y,u_spp_translate_rotation.y*tr.x+u_spp_translate_rotation.x*tr.y );gl_Position.xy+=(u_coord_matrix*vec4(rotated_tr,0.0,0.0)).xy;}float gamma_scale=gl_Position.w;v_draw_halo=(u_is_halo && float(gl_InstanceID)==0.0) ? 1.0 : 0.0;v_gamma_scale_size_fade_opacity=vec3(gamma_scale,size,out_fade_opacity);v_tex_a=a_tex/u_texsize; #ifdef RENDER_TEXT_AND_SYMBOL is_sdf=a_size[0]-2.0*a_size_min;v_tex_a_icon=a_tex/u_texsize_icon; #endif #ifdef ICON_TRANSITION v_tex_b=vec2(a_texb)/u_texsize; #endif #ifdef RENDER_SHADOWS vec4 shd_pos=u_inv_matrix*vec4(pos,1.0);vec3 shd_pos0=shd_pos.xyz;vec3 shd_pos1=shd_pos.xyz; #ifdef NORMAL_OFFSET vec3 shd_pos_offset=shadow_normal_offset(vec3(0.0,0.0,1.0));shd_pos0+=shd_pos_offset*shadow_normal_offset_multiplier0();shd_pos1+=shd_pos_offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef RENDER_SHADOWS v_z_offset=e; #endif }`),skybox:Zi(`#include "_prelude_fog.fragment.glsl" in lowp vec3 v_uv;uniform lowp samplerCube u_cubemap;uniform lowp float u_opacity;uniform highp float u_temporal_offset;uniform highp vec3 u_sun_direction;float sun_disk(highp vec3 ray_direction,highp vec3 sun_direction) {highp float cos_angle=dot(normalize(ray_direction),sun_direction);const highp float cos_sun_angular_diameter=0.99996192306;const highp float smoothstep_delta=1e-5;return smoothstep( cos_sun_angular_diameter-smoothstep_delta,cos_sun_angular_diameter+smoothstep_delta,cos_angle);}float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec3 uv=v_uv;const float y_bias=0.015;uv.y+=y_bias;uv.y=pow(abs(uv.y),1.0/5.0);uv.y=map(uv.y,0.0,1.0,-1.0,1.0);vec3 sky_color=texture(u_cubemap,uv).rgb; #ifdef FOG sky_color=fog_apply_sky_gradient(v_uv.xzy,sky_color); #endif sky_color+=0.1*sun_disk(v_uv,u_sun_direction);glFragColor=vec4(sky_color*u_opacity,u_opacity); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif }`,_ne),skyboxGradient:Zi(`#include "_prelude_fog.fragment.glsl" in highp vec3 v_uv;uniform lowp sampler2D u_color_ramp;uniform highp vec3 u_center_direction;uniform lowp float u_radius;uniform lowp float u_opacity;uniform highp float u_temporal_offset;void main() {float progress=acos(dot(normalize(v_uv),u_center_direction))/u_radius;vec4 color=texture(u_color_ramp,vec2(progress,0.5)); #ifdef FOG color.rgb=fog_apply_sky_gradient(v_uv.xzy,color.rgb/color.a)*color.a; #endif color*=u_opacity;glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif }`,_ne),skyboxCapture:Zi(` in highp vec3 v_position;uniform highp float u_sun_intensity;uniform highp float u_luminance;uniform lowp vec3 u_sun_direction;uniform highp vec4 u_color_tint_r;uniform highp vec4 u_color_tint_m;precision highp float; #define BETA_R vec3(5.5e-6,13.0e-6,22.4e-6) #define BETA_M vec3(21e-6,21e-6,21e-6) #define MIE_G 0.76 #define DENSITY_HEIGHT_SCALE_R 8000.0 #define DENSITY_HEIGHT_SCALE_M 1200.0 #define PLANET_RADIUS 6360e3 #define ATMOSPHERE_RADIUS 6420e3 #define SAMPLE_STEPS 10 #define DENSITY_STEPS 4 float ray_sphere_exit(vec3 orig,vec3 dir,float radius) {float a=dot(dir,dir);float b=2.0*dot(dir,orig);float c=dot(orig,orig)-radius*radius;float d=sqrt(b*b-4.0*a*c);return (-b+d)/(2.0*a);}vec3 extinction(vec2 density) {return exp(-vec3(BETA_R*u_color_tint_r.a*density.x+BETA_M*u_color_tint_m.a*density.y));}vec2 local_density(vec3 point) {float height=max(length(point)-PLANET_RADIUS,0.0);float exp_r=exp(-height/DENSITY_HEIGHT_SCALE_R);float exp_m=exp(-height/DENSITY_HEIGHT_SCALE_M);return vec2(exp_r,exp_m);}float phase_ray(float cos_angle) {return (3.0/(16.0*PI))*(1.0+cos_angle*cos_angle);}float phase_mie(float cos_angle) {return (3.0/(8.0*PI))*((1.0-MIE_G*MIE_G)*(1.0+cos_angle*cos_angle))/((2.0+MIE_G*MIE_G)*pow(1.0+MIE_G*MIE_G-2.0*MIE_G*cos_angle,1.5));}vec2 density_to_atmosphere(vec3 point,vec3 light_dir) {float ray_len=ray_sphere_exit(point,light_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(DENSITY_STEPS);vec2 density_point_to_atmosphere=vec2(0.0);for (int i=0; i < DENSITY_STEPS;++i) {vec3 point_on_ray=point+light_dir*((float(i)+0.5)*step_len);density_point_to_atmosphere+=local_density(point_on_ray)*step_len;;}return density_point_to_atmosphere;}vec3 atmosphere(vec3 ray_dir,vec3 sun_direction,float sun_intensity) {vec2 density_orig_to_point=vec2(0.0);vec3 scatter_r=vec3(0.0);vec3 scatter_m=vec3(0.0);vec3 origin=vec3(0.0,PLANET_RADIUS,0.0);float ray_len=ray_sphere_exit(origin,ray_dir,ATMOSPHERE_RADIUS);float step_len=ray_len/float(SAMPLE_STEPS);for (int i=0; i < SAMPLE_STEPS;++i) {vec3 point_on_ray=origin+ray_dir*((float(i)+0.5)*step_len);vec2 density=local_density(point_on_ray)*step_len;density_orig_to_point+=density;vec2 density_point_to_atmosphere=density_to_atmosphere(point_on_ray,sun_direction);vec2 density_orig_to_atmosphere=density_orig_to_point+density_point_to_atmosphere;vec3 extinction=extinction(density_orig_to_atmosphere);scatter_r+=density.x*extinction;scatter_m+=density.y*extinction;}float cos_angle=dot(ray_dir,sun_direction);float phase_r=phase_ray(cos_angle);float phase_m=phase_mie(cos_angle);vec3 beta_r=BETA_R*u_color_tint_r.rgb*u_color_tint_r.a;vec3 beta_m=BETA_M*u_color_tint_m.rgb*u_color_tint_m.a;return (scatter_r*phase_r*beta_r+scatter_m*phase_m*beta_m)*sun_intensity;}const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;vec3 uncharted2_tonemap(vec3 x) {return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;}void main() {vec3 ray_direction=v_position;ray_direction.y=pow(ray_direction.y,5.0);const float y_bias=0.015;ray_direction.y+=y_bias;vec3 color=atmosphere(normalize(ray_direction),u_sun_direction,u_sun_intensity);float white_scale=1.0748724675633854;color=uncharted2_tonemap((log2(2.0/pow(u_luminance,4.0)))*color)*white_scale;glFragColor=vec4(color,1.0);}`,"in highp vec3 a_pos_3f;uniform mat3 u_matrix_3f;out highp vec3 v_position;float map(float value,float start,float end,float new_start,float new_end) {return ((value-start)*(new_end-new_start))/(end-start)+new_start;}void main() {vec4 pos=vec4(u_matrix_3f*a_pos_3f,1.0);v_position=native_cubemap_direction(pos.xyz);v_position.y=map(v_position.y,-1.0,1.0,0.0,1.0);gl_Position=vec4(a_pos_3f.xy,0.0,1.0);}"),globeAtmosphere:Zi(`#include "_prelude_fog.fragment.glsl" uniform float u_transition;uniform highp float u_fadeout_range;uniform highp float u_temporal_offset;uniform vec4 u_atmosphere_fog_color;uniform vec4 u_high_color;uniform vec4 u_space_color;uniform float u_horizon_angle;in highp vec3 v_ray_dir;in highp vec3 v_horizon_dir;void main() {highp vec3 dir=normalize(v_ray_dir);float globe_pos_dot_dir; #ifdef PROJECTION_GLOBE_VIEW globe_pos_dot_dir=dot(u_globe_pos,dir);highp vec3 closest_point_forward=abs(globe_pos_dot_dir)*dir;float norm_dist_from_center=length(closest_point_forward-u_globe_pos)/u_globe_radius;if (norm_dist_from_center < 0.98) { #ifdef ALPHA_PASS glFragColor=vec4(0,0,0,0);return; #else glFragColor=vec4(0,0,0,1);return; #endif } #endif highp vec3 horizon_dir=normalize(v_horizon_dir);float horizon_angle_mercator=dir.y < horizon_dir.y ? 0.0 : max(acos(clamp(dot(dir,horizon_dir),-1.0,1.0)),0.0);float horizon_angle; #ifdef PROJECTION_GLOBE_VIEW highp vec3 closest_point=globe_pos_dot_dir*dir;highp float closest_point_to_center=length(closest_point-u_globe_pos);highp float theta=asin(clamp(closest_point_to_center/length(u_globe_pos),-1.0,1.0));horizon_angle=globe_pos_dot_dir < 0.0 ? PI-theta-u_horizon_angle : theta-u_horizon_angle;float angle_t=pow(u_transition,10.0);horizon_angle=mix(horizon_angle,horizon_angle_mercator,angle_t); #else horizon_angle=horizon_angle_mercator; #endif horizon_angle/=PI;float t=exp(-horizon_angle/u_fadeout_range);float alpha_0=u_atmosphere_fog_color.a;float alpha_1=u_high_color.a;float alpha_2=u_space_color.a;vec3 color_stop_0=u_atmosphere_fog_color.rgb;vec3 color_stop_1=u_high_color.rgb;vec3 color_stop_2=u_space_color.rgb; #ifdef ALPHA_PASS float a0=mix(alpha_2,1.0,alpha_1);float a1=mix(a0,1.0,alpha_0);float a2=mix(a0,a1,t);float a =mix(alpha_2,a2,t);glFragColor=vec4(1.0,1.0,1.0,a); #else vec3 c0=mix(color_stop_2,color_stop_1,alpha_1);vec3 c1=mix(c0,color_stop_0,alpha_0);vec3 c2=mix(c0,c1,t);vec3 c=c2;glFragColor=vec4(c*t,t); #endif }`,`in vec3 a_pos;in vec2 a_uv;uniform vec3 u_frustum_tl;uniform vec3 u_frustum_tr;uniform vec3 u_frustum_br;uniform vec3 u_frustum_bl;uniform float u_horizon;out highp vec3 v_ray_dir;out highp vec3 v_horizon_dir;void main() {v_ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,a_uv.x),mix(u_frustum_bl,u_frustum_br,a_uv.x),a_uv.y);v_horizon_dir=mix( mix(u_frustum_tl,u_frustum_bl,u_horizon),mix(u_frustum_tr,u_frustum_br,u_horizon),a_uv.x);gl_Position=vec4(a_pos,1.0);}`),stars:Zi(`in highp vec2 v_uv;in mediump float v_intensity;float shapeCircle(in vec2 uv) {float beginFade=0.6;float lengthFromCenter=length(v_uv);return 1.0-clamp((lengthFromCenter-beginFade)/(1.0-beginFade),0.0,1.0);}void main() {float alpha=shapeCircle(v_uv);vec3 color=vec3(1.0,1.0,1.0);alpha*=v_intensity;glFragColor=vec4(color*alpha,alpha);HANDLE_WIREFRAME_DEBUG;}`,` in vec3 a_pos_3f;in vec2 a_uv;in float a_size_scale;in float a_opacity;uniform mat4 u_matrix;uniform vec3 u_up;uniform vec3 u_right;uniform float u_intensity_multiplier;out highp vec2 v_uv;out mediump float v_intensity;void main() {v_uv=a_uv;v_intensity=a_opacity*u_intensity_multiplier;vec3 pos=a_pos_3f;pos+=a_uv.x*u_right*a_size_scale;pos+=a_uv.y*u_up*a_size_scale;gl_Position=u_matrix*vec4(pos,1.0);}`),occlusion:Zi("uniform vec4 u_color;void main() {glFragColor=u_color;}",`#include "_prelude_terrain.vertex.glsl" in highp vec2 a_offset_xy;uniform highp vec3 u_anchorPos;uniform mat4 u_matrix;uniform vec2 u_screenSizePx;uniform vec2 u_occluderSizePx;void main() {vec3 world_pos=u_anchorPos; #ifdef TERRAIN float e=elevation(world_pos.xy);world_pos.z+=e; #endif vec4 projected_point=u_matrix*vec4(world_pos,1.0);projected_point.xy+=projected_point.w*a_offset_xy*0.5*u_occluderSizePx/u_screenSizePx;gl_Position=projected_point;}`)};function dS(h,o){const u=h.split(` `);for(let m of u){if(m=m.trimStart(),m[0]!=="#"||!m.includes("if")||m.startsWith("#endif"))continue;const x=m.match(hMe);if(x)for(const b of x)fMe.has(b)||o.add(b)}}function Lne(h){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(h)}function Zi(h,o){const u=new Set,m=[],x=[];h=h.replace(kne,(S,A)=>(x.push(A),"")),o=o.replace(kne,(S,A)=>(m.push(A),""));let b=new Set(RL);dS(h,b),dS(o,b);for(const S of[...m,...x])LL[S]||(LL[S]=new Set,dS(jne[S],LL[S])),b=new Set([...b,...LL[S]]);return{fragmentSource:h=h.replace(Ine,(S,A,I,D,B)=>(u.add(B),A==="define"?` #ifndef HAS_UNIFORM_u_${B} ${Lne(D)?"flat ":""}in ${I} ${D} ${B}; #else uniform ${I} ${D} u_${B}; #endif `:A==="initialize"?` #ifdef HAS_UNIFORM_u_${B} ${I} ${D} ${B} = u_${B}; #endif `:A==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${B} in ${I} ${D} ${B}; #endif `:A==="initialize-attribute"?"":void 0)),vertexSource:o=o.replace(Ine,(S,A,I,D,B)=>{const U=`MATERIAL_ATTRIBUTE_OFFSET_${B}`,q=D==="float"?"vec2":D,K=`GET_ATTRIBUTE_${q}(a_${B}, materialInfo, ${U})`,X=B.includes("color")?"color":q;return A==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${B} in ${I} ${D} a_${B}; #endif `:u.has(B)?A==="define"?` #ifndef HAS_UNIFORM_u_${B} uniform lowp float u_${B}_t; #if !defined(${U}) in ${I} ${q} a_${B}; #endif ${Lne(D)?"flat ":""}out ${I} ${D} ${B}; #else uniform ${I} ${D} u_${B}; #endif `:A==="initialize"?X==="vec4"||X==="uvec4"?` #ifndef HAS_UNIFORM_u_${B} ${B} = a_${B}; #else ${I} ${D} ${B} = u_${B}; #endif `:` #if !defined(HAS_UNIFORM_u_${B}) #ifdef ${U} ${B} = unpack_mix_${X}(${K}, u_${B}_t); #else ${B} = unpack_mix_${X}(a_${B}, u_${B}_t); #endif #else ${I} ${D} ${B} = u_${B}; #endif `:A==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${B} in ${I} ${D} a_${B}; out ${I} ${D} ${B}; #endif `:A==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${B} ${B} = a_${B}; #endif `:void 0:A==="define"?` #ifndef HAS_UNIFORM_u_${B} uniform lowp float u_${B}_t; #if !defined(${U}) in ${I} ${q} a_${B}; #endif #else uniform ${I} ${D} u_${B}; #endif `:A==="define-instanced"?X==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${B}0; in vec4 a_${B}1; in vec4 a_${B}2; in vec4 a_${B}3; #else uniform ${I} ${D} u_${B}; #endif `:` #ifdef INSTANCED_ARRAYS in ${I} ${q} a_${B}; #else uniform ${I} ${D} u_${B}; #endif `:A==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${B} ${I} ${D} ${B} = a_${B}; #endif `:X==="vec4"||X==="uvec4"?` #ifndef HAS_UNIFORM_u_${B} #ifdef ${U} ${I} ${D} ${B} = ${K}; #else ${I} ${D} ${B} = a_${B}; #endif #else ${I} ${D} ${B} = u_${B}; #endif `:` #ifndef HAS_UNIFORM_u_${B} #ifdef ${U} ${I} ${D} ${B} = unpack_mix_${X}(${K}, u_${B}_t); #else ${I} ${D} ${B} = unpack_mix_${X}(a_${B}, u_${B}_t); #endif #else ${I} ${D} ${B} = u_${B}; #endif `}),usedDefines:b,vertexIncludes:m,fragmentIncludes:x}}var yMe={model:Zi(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" uniform float u_opacity; #ifdef DITHERED_DISCARD uniform float u_dithered_discard_threshold; #endif #ifndef LIGHTING_3D_MODE uniform vec3 u_lightcolor;uniform vec3 u_lightpos;uniform float u_lightintensity; #endif uniform vec4 u_baseColorFactor;uniform vec4 u_emissiveFactor;uniform float u_metallicFactor;uniform float u_roughnessFactor;uniform float u_emissive_strength;in highp vec4 v_position_height;in lowp vec4 v_color_mix; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth_shadows; #endif #ifdef OCCLUSION_TEXTURE_TRANSFORM uniform vec4 u_occlusionTextureTransform; #endif #pragma mapbox: define-attribute highp vec4 normal_4n #pragma mapbox: define-attribute highp vec3 color_3f #pragma mapbox: define-attribute highp vec4 color_4f #pragma mapbox: define-attribute highp vec2 uv_2f #pragma mapbox: initialize-attribute highp vec4 normal_4n #pragma mapbox: initialize-attribute highp vec3 color_3f #pragma mapbox: initialize-attribute highp vec4 color_4f #pragma mapbox: initialize-attribute highp vec2 uv_2f #ifdef HAS_ATTRIBUTE_a_feature in lowp vec4 v_roughness_metallic_emissive_alpha;in mediump vec4 v_height_based_emission_params; #endif #ifdef HAS_TEXTURE_u_baseColorTexture uniform sampler2D u_baseColorTexture;uniform bool u_baseTextureIsAlpha;uniform bool u_alphaMask;uniform float u_alphaCutoff; #endif #ifdef HAS_TEXTURE_u_metallicRoughnessTexture uniform sampler2D u_metallicRoughnessTexture; #endif #ifdef HAS_TEXTURE_u_occlusionTexture uniform sampler2D u_occlusionTexture;uniform float u_aoIntensity; #endif #ifdef HAS_TEXTURE_u_normalTexture uniform sampler2D u_normalTexture; #endif #ifdef HAS_TEXTURE_u_emissionTexture uniform sampler2D u_emissionTexture; #endif #ifdef APPLY_LUT_ON_GPU uniform highp sampler3D u_lutTexture; #endif #define saturate(_x) clamp(_x,0.,1.) vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}float calculate_NdotL(vec3 normal,vec3 lightDir) {const float ext=0.70710678118;return (clamp(dot(normal,lightDir),-ext,1.0)+ext)/(1.0+ext);}vec3 getDiffuseShadedColor(vec3 albedo,vec3 normal,vec3 lightDir,vec3 lightColor) { #ifdef LIGHTING_3D_MODE vec3 transformed_normal=vec3(-normal.xy,normal.z);float lighting_factor; #ifdef RENDER_SHADOWS lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows); #else lighting_factor=saturate(dot(transformed_normal,u_lighting_directional_dir)); #endif return apply_lighting(albedo,transformed_normal,lighting_factor); #else vec3 n=normal;float colorvalue=((albedo.x*0.2126)+(albedo.y*0.7152))+(albedo.z*0.0722);vec3 c=vec3(0.03,0.03,0.03);float directional=clamp(dot(n,vec3(lightDir)),0.0,1.0);directional=mix(1.0-u_lightintensity,max((1.0-colorvalue)+u_lightintensity,1.0),directional);vec3 c3=c+clamp((albedo*directional)*lightColor,mix(vec3(0.0),vec3(0.3),vec3(1.0)-lightColor),vec3(1.0));return c3; #endif }vec4 getBaseColor() {vec4 albedo=u_baseColorFactor; #ifdef HAS_ATTRIBUTE_a_color_3f albedo*=vec4(color_3f,1.0); #endif #ifdef HAS_ATTRIBUTE_a_feature #else #ifdef HAS_ATTRIBUTE_a_color_4f albedo*=color_4f; #endif #endif #if defined (HAS_TEXTURE_u_baseColorTexture) && defined (HAS_ATTRIBUTE_a_uv_2f) vec4 texColor=texture(u_baseColorTexture,uv_2f);if(u_alphaMask) {if (texColor.w < u_alphaCutoff) {discard;}} #ifdef UNPREMULT_TEXTURE_IN_SHADER texColor=vec4(unpremultiplyColor(texColor),1.0); #endif if(u_baseTextureIsAlpha) {if (texColor.r < 0.5) {discard;}} else {texColor.rgb=sRGBToLinear(texColor.rgb);albedo*=texColor;} #endif vec4 color=vec4(mix(albedo.rgb,v_color_mix.rgb,v_color_mix.a),albedo.a); #ifdef APPLY_LUT_ON_GPU color=applyLUT(u_lutTexture,color); #endif return color;}highp mat3 cotangentFrame(highp vec3 N,highp vec3 p,highp vec2 uv ) { #ifdef HAS_TEXTURE_u_normalTexture highp vec3 dp1=vec3(dFdx(p.x),dFdx(p.y),dFdx(p.z));highp vec3 dp2=vec3(dFdy(p.x),dFdy(p.y),dFdy(p.z));highp vec2 duv1=vec2(dFdx(uv.x),dFdx(uv.y));highp vec2 duv2=vec2(dFdy(uv.x),dFdy(uv.y));highp vec3 dp2perp=cross( dp2,N );highp vec3 dp1perp=cross( N,dp1 );highp vec3 T=native_window_space_tangent(dp2perp*duv1.x+dp1perp*duv2.x);highp vec3 B=native_window_space_tangent(dp2perp*duv1.y+dp1perp*duv2.y);highp float lengthT=dot(T,T);highp float lengthB=dot(B,B);highp float maxLength=max(lengthT,lengthB);highp float invmax=inversesqrt( maxLength );highp mat3 res=mat3( T*invmax,B*invmax,N );return res; #else return mat3(1.0); #endif }highp vec3 getNormal(){highp vec3 n; #ifdef HAS_ATTRIBUTE_a_normal_4n n=normalize(normal_4n.xyz); #else highp vec3 fdx=vec3(dFdx(v_position_height.x),dFdx(v_position_height.y),dFdx(v_position_height.z));highp vec3 fdy=vec3(dFdy(v_position_height.x),dFdy(v_position_height.y),dFdy(v_position_height.z));n=native_window_space_normal(fdx,fdy); #endif #if defined(HAS_TEXTURE_u_normalTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) vec3 nMap=texture( u_normalTexture,uv_2f).xyz;nMap=normalize(2.0*nMap-vec3(1.0));highp vec3 v=native_tbn_view_dir(v_position_height.xyz);highp mat3 TBN=cotangentFrame(n,v,uv_2f);n=normalize(TBN*nMap); #endif return n;}struct Material {float perceptualRoughness;float alphaRoughness;float metallic;vec3 f90;vec4 baseColor;vec3 diffuseColor;vec3 specularColor;highp vec3 normal;};Material getPBRMaterial() {Material mat;mat.baseColor=getBaseColor();mat.perceptualRoughness=u_roughnessFactor;mat.metallic=u_metallicFactor; #ifdef HAS_ATTRIBUTE_a_feature mat.perceptualRoughness=v_roughness_metallic_emissive_alpha.x;mat.metallic=v_roughness_metallic_emissive_alpha.y;mat.baseColor.w*=v_roughness_metallic_emissive_alpha.w; #endif #if defined(HAS_TEXTURE_u_metallicRoughnessTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) vec4 mrSample=texture(u_metallicRoughnessTexture,uv_2f);mat.perceptualRoughness*=mrSample.g;mat.metallic*=mrSample.b; #endif const float c_minRoughness=0.04;mat.perceptualRoughness=clamp(mat.perceptualRoughness,c_minRoughness,1.0);mat.metallic=saturate(mat.metallic);mat.alphaRoughness=mat.perceptualRoughness*mat.perceptualRoughness;const vec3 f0=vec3(0.04);mat.diffuseColor=mat.baseColor.rgb*(vec3(1.0)-f0);mat.diffuseColor*=1.0-mat.metallic;mat.specularColor=mix(f0,mat.baseColor.rgb,mat.metallic);highp float reflectance=max(max(mat.specularColor.r,mat.specularColor.g),mat.specularColor.b);highp float reflectance90=saturate(reflectance*25.0);mat.f90=vec3(reflectance90);mat.normal=getNormal();return mat;}float V_GGX(float NdotL,float NdotV,float roughness) {float a2=roughness*roughness;float GGXV=NdotL*sqrt(NdotV*NdotV*(1.0-a2)+a2);float GGXL=NdotV*sqrt(NdotL*NdotL*(1.0-a2)+a2);return 0.5/(GGXV+GGXL);}float V_GGXFast(float NdotL,float NdotV,float roughness) {float a=roughness;float GGXV=NdotL*(NdotV*(1.0-a)+a);float GGXL=NdotV*(NdotL*(1.0-a)+a);return 0.5/(GGXV+GGXL);}vec3 F_Schlick(vec3 specularColor,vec3 f90,float VdotH) {return specularColor+(f90-specularColor)*pow(clamp(1.0-VdotH,0.0,1.0),5.0);}vec3 F_SchlickFast(vec3 specularColor,float VdotH) {float x=1.0-VdotH;float x4=x*x*x*x;return specularColor+(1.0-specularColor)*x4*x;}float D_GGX(highp float NdotH,float alphaRoughness) {highp float a4=alphaRoughness*alphaRoughness;highp float f=(NdotH*a4-NdotH)*NdotH+1.0;return a4/(PI*f*f);}vec3 diffuseBurley(Material mat,float LdotH,float NdotL,float NdotV) {float f90=2.0*LdotH*LdotH*mat.alphaRoughness-0.5;return (mat.diffuseColor/PI)*(1.0+f90*pow((1.0-NdotL),5.0))*(1.0+f90*pow((1.0-NdotV),5.0));}vec3 diffuseLambertian(Material mat) { #ifdef LIGHTING_3D_MODE return mat.diffuseColor; #else return mat.diffuseColor/PI; #endif }vec3 EnvBRDFApprox(vec3 specularColor,float roughness,highp float NdotV) {vec4 c0=vec4(-1,-0.0275,-0.572,0.022);vec4 c1=vec4(1,0.0425,1.04,-0.04);highp vec4 r=roughness*c0+c1;highp float a004=min(r.x*r.x,exp2(-9.28*NdotV))*r.x+r.y;vec2 AB=vec2(-1.04,1.04)*a004+r.zw;return specularColor*AB.x+AB.y;}vec3 computeIndirectLightContribution(Material mat,float NdotV,vec3 normal) {vec3 env_light=vec3(0.65,0.65,0.65); #ifdef LIGHTING_3D_MODE float ambient_factor=calculate_ambient_directional_factor(normal);env_light=u_lighting_ambient_color*ambient_factor; #endif vec3 envBRDF=EnvBRDFApprox(mat.specularColor,mat.perceptualRoughness,NdotV);vec3 indirectSpecular= envBRDF*env_light;vec3 indirectDiffuse=mat.diffuseColor*env_light;return indirectSpecular+indirectDiffuse;}vec3 computeLightContribution(Material mat,vec3 lightPosition,vec3 lightColor) {highp vec3 n=mat.normal;highp vec3 v=normalize(-v_position_height.xyz);highp vec3 l=normalize(lightPosition);highp vec3 h=normalize(v+l);float NdotV=clamp(abs(dot(n,v)),0.001,1.0);float NdotL=saturate(dot(n,l));highp float NdotH=saturate(dot(n,h));float VdotH=saturate(dot(v,h));vec3 f=F_SchlickFast(mat.specularColor,VdotH);float g=V_GGXFast(NdotL,NdotV,mat.alphaRoughness);float d=D_GGX(NdotH,mat.alphaRoughness);vec3 diffuseTerm=(1.0-f)*diffuseLambertian(mat);vec3 specularTerm=f*g*d;vec3 transformed_normal=vec3(-n.xy,n.z);float lighting_factor; #ifdef RENDER_SHADOWS lighting_factor=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth_shadows); #else lighting_factor=NdotL; #endif vec3 directLightColor=(specularTerm+diffuseTerm)*lighting_factor*lightColor;vec3 indirectLightColor=computeIndirectLightContribution(mat,NdotV,transformed_normal);vec3 color=(saturate(directLightColor)+indirectLightColor);float intensityFactor=1.0; #if !defined(LIGHTING_3D_MODE) const vec3 luminosityFactor=vec3(0.2126,0.7152,0.0722);float luminance=dot(diffuseTerm,luminosityFactor);intensityFactor=mix((1.0-u_lightintensity),max((1.0-luminance+u_lightintensity),1.0),NdotL); #endif color*=intensityFactor;return color;}void main() {vec3 lightDir;vec3 lightColor; #ifdef LIGHTING_3D_MODE lightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color; #else lightDir=u_lightpos;lightColor=u_lightcolor; #endif vec4 finalColor; #ifdef DIFFUSE_SHADED vec3 N=getNormal();vec3 baseColor=getBaseColor().rgb;vec3 diffuse=getDiffuseShadedColor(baseColor,N,lightDir,lightColor); #ifdef HAS_TEXTURE_u_occlusionTexture float ao=(texture(u_occlusionTexture,uv_2f).r-1.0)*u_aoIntensity+1.0;diffuse*=ao; #endif finalColor=vec4(mix(diffuse,baseColor,u_emissive_strength),1.0)*u_opacity; #else Material mat=getPBRMaterial();vec3 color=computeLightContribution(mat,lightDir,lightColor);float ao=1.0; #if defined (HAS_TEXTURE_u_occlusionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) #ifdef OCCLUSION_TEXTURE_TRANSFORM vec2 uv=uv_2f.xy*u_occlusionTextureTransform.zw+u_occlusionTextureTransform.xy; #else vec2 uv=uv_2f; #endif ao=(texture(u_occlusionTexture,uv).x-1.0)*u_aoIntensity+1.0;color*=ao; #endif vec4 emissive=u_emissiveFactor; #if defined(HAS_TEXTURE_u_emissionTexture) && defined(HAS_ATTRIBUTE_a_uv_2f) emissive.rgb*=sRGBToLinear(texture(u_emissionTexture,uv_2f).rgb); #endif #ifdef APPLY_LUT_ON_GPU float emissiveFactorLength=max(length(u_emissiveFactor.rgb),0.001);emissive.rgb=sRGBToLinear(applyLUT(u_lutTexture,linearTosRGB(emissive.rgb/emissiveFactorLength).rbg))*emissiveFactorLength; #endif color+=emissive.rgb;float opacity=mat.baseColor.w*u_opacity; #ifdef HAS_ATTRIBUTE_a_feature float resEmission=v_roughness_metallic_emissive_alpha.z;resEmission*=v_height_based_emission_params.z+v_height_based_emission_params.w*pow(clamp(v_height_based_emission_params.x,0.0,1.0),v_height_based_emission_params.y);vec3 color_mix=v_color_mix.rgb; #ifdef APPLY_LUT_ON_GPU color_mix=applyLUT(u_lutTexture,color_mix); #endif color=mix(color,color_mix,min(1.0,resEmission)); #ifdef HAS_ATTRIBUTE_a_color_4f float distance=length(vec2(1.3*max(0.0,abs(color_4f.x)-color_4f.z),color_4f.y));distance+= mix(0.5,0.0,clamp(resEmission-1.0,0.0,1.0));opacity*=v_roughness_metallic_emissive_alpha.w*saturate(1.0-distance*distance); #endif #endif vec3 unlitColor=mat.baseColor.rgb*ao+emissive.rgb;color=mix(color,unlitColor,u_emissive_strength);color=linearTosRGB(color);color*=opacity;finalColor=vec4(color,opacity); #endif #ifdef DITHERED_DISCARD if (abs(u_dithered_discard_threshold) < 1.0) {float ditherValue=fract(52.9829189*fract(0.06711056*gl_FragCoord.x+0.00583715*gl_FragCoord.y));float compareValue=mix(1.0-ditherValue,ditherValue,step(0.0,u_dithered_discard_threshold));if (abs(u_dithered_discard_threshold) < compareValue) {discard;}} #endif #ifdef FOG finalColor=fog_dither(fog_apply_premultiplied(finalColor,v_fog_pos,v_position_height.w)); #endif #ifdef RENDER_CUTOFF finalColor*=v_cutoff_opacity; #endif glFragColor=finalColor; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_feature_cutout.vertex.glsl" in vec3 a_pos_3f; #pragma mapbox: define-attribute highp vec4 normal_4n #pragma mapbox: define-attribute highp vec2 uv_2f #pragma mapbox: define-attribute highp vec3 color_3f #pragma mapbox: define-attribute highp vec4 color_4f #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 feature #define MODEL_PART_COUNT 7u #define MODEL_PART_STYLE_SIZE_VEC4 28u #ifdef HAS_ATTRIBUTE_a_feature struct ModelPartStyle {vec4 color_mix;vec4 rmea;vec4 gradient;float gradient_power;};layout(std140) uniform ModelPartStyleUniform {vec4 part_style[MODEL_PART_STYLE_SIZE_VEC4];} u_model_part_style;uniform vec4 u_model_mesh_params; #endif uniform mat4 u_matrix;uniform mat4 u_node_matrix;uniform mat4 u_lighting_matrix;uniform vec3 u_camera_pos;uniform vec4 u_color_mix; #ifdef INSTANCED_ARRAYS in vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3; #else uniform highp mat4 u_normal_matrix; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth_shadows; #endif out vec4 v_position_height;out lowp vec4 v_color_mix; #ifdef HAS_ATTRIBUTE_a_feature out lowp vec4 v_roughness_metallic_emissive_alpha;out mediump vec4 v_height_based_emission_params; #endif vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #ifdef HAS_ATTRIBUTE_a_feature uint decodeModelPartId(uvec2 feature) {uint partId=feature.y & 0xFu;return partId < MODEL_PART_COUNT ? partId : 0u;}vec4 decodeModelVertexColor(uvec2 feature) {uvec4 nibbles=uvec4(feature.x >> 12u,feature.x >> 8u,feature.x >> 4u,feature.x) & 0xFu;return vec4(nibbles*17u)/255.0;}ModelPartStyle readModelPartStyle(uint partId) {uint base=partId*4u;ModelPartStyle style;style.color_mix=u_model_part_style.part_style[base];style.rmea=u_model_part_style.part_style[base+1u];style.gradient=u_model_part_style.part_style[base+2u];style.gradient_power=u_model_part_style.part_style[base+3u].x;return style;}vec3 modelAlbedo(ModelPartStyle style,vec4 vertexColor) {float ambientOcclusion=mix(1.0,vertexColor.a,u_model_mesh_params.z);return ambientOcclusion*mix(vertexColor.rgb,style.color_mix.rgb,style.color_mix.a);}vec4 resolveModelEmissiveGradient(ModelPartStyle style,float height) {float begin=u_model_mesh_params.x+u_model_mesh_params.y*style.gradient.x;float span=u_model_mesh_params.y*(style.gradient.y-style.gradient.x);return vec4((height-begin)/span,style.gradient_power,style.gradient.z,style.gradient.w);} #endif void main() { #pragma mapbox: initialize-attribute highp vec4 normal_4n #pragma mapbox: initialize-attribute highp vec2 uv_2f #pragma mapbox: initialize-attribute highp vec3 color_3f #pragma mapbox: initialize-attribute highp vec4 color_4f #pragma mapbox: initialize-attribute-custom highp uvec2 feature highp mat4 normal_matrix; #ifdef INSTANCED_ARRAYS normal_matrix=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3); #else normal_matrix=u_normal_matrix; #endif vec3 local_pos;mat3 rs; #ifdef MODEL_POSITION_ON_GPU vec3 pos_color=normal_matrix[0].xyz;vec4 translate=normal_matrix[1];vec3 pos_a=floor(pos_color);vec3 rgb=1.05*(pos_color-pos_a);float hidden=float(pos_a.x > EXTENT);float color_mix=pos_a.z/100.0;v_color_mix=vec4(sRGBToLinear(rgb),color_mix);float meter_to_tile=normal_matrix[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);rs[0].x=normal_matrix[1].w;rs[0].yz=normal_matrix[2].xy;rs[1].xy=normal_matrix[2].zw;rs[1].z=normal_matrix[3].x;rs[2].xyz=normal_matrix[3].yzw;vec4 pos_node=u_lighting_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;local_pos=pos.xyz;gl_Position=mix(u_matrix*pos,AWAY,hidden);pos.z*=meter_to_tile;v_position_height.xyz=pos.xyz-u_camera_pos; #else local_pos=a_pos_3f;gl_Position=u_matrix*vec4(a_pos_3f,1);v_position_height.xyz=vec3(u_lighting_matrix*vec4(a_pos_3f,1));v_color_mix=vec4(sRGBToLinear(u_color_mix.rgb),u_color_mix.a); #endif v_position_height.w=a_pos_3f.z; #ifdef HAS_ATTRIBUTE_a_feature ModelPartStyle part_style=readModelPartStyle(decodeModelPartId(feature));v_color_mix=vec4(modelAlbedo(part_style,decodeModelVertexColor(feature)),1.0);v_roughness_metallic_emissive_alpha=part_style.rmea;v_height_based_emission_params=resolveModelEmissiveGradient(part_style,a_pos_3f.z); #endif #ifdef FOG v_fog_pos=fog_position(local_pos); #endif #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,native_clip_z_to_cutoff_depth(gl_Position.z,gl_Position.w)); #endif #ifdef HAS_ATTRIBUTE_a_normal_4n #ifdef MODEL_POSITION_ON_GPU float x_squared_scale=dot(rs[0],rs[0]);float y_squared_scale=dot(rs[1],rs[1]);float z_squared_scale=dot(rs[2],rs[2]);vec3 squared_scale=vec3(x_squared_scale,y_squared_scale,z_squared_scale);normal_4n=vec4(rs*((u_lighting_matrix*vec4(normal_4n.xyz,0.0)).xyz/squared_scale),0.0);normal_4n=normalize(normal_4n); #else normal_4n=vec4((normal_matrix*vec4(normal_4n.xyz,0)).xyz,0.0); #endif #endif #ifdef HAS_ATTRIBUTE_a_feature #ifdef HAS_ATTRIBUTE_a_color_4f v_roughness_metallic_emissive_alpha.w=clamp(color_4f.a*v_roughness_metallic_emissive_alpha.w*(v_roughness_metallic_emissive_alpha.z-1.0),0.0,1.0); #endif #endif #ifdef RENDER_SHADOWS vec4 shadow_pos=u_node_matrix*vec4(local_pos,1.0); #ifdef NORMAL_OFFSET #ifdef HAS_ATTRIBUTE_a_normal_4n #ifdef MODEL_POSITION_ON_GPU vec3 offset=shadow_normal_offset(vec3(-normal_4n.xy,normal_4n.z));shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #else vec3 offset=shadow_normal_offset_model(normal_4n.xyz);shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #endif #endif #endif v_pos_light_view_0=u_light_matrix_0*shadow_pos;v_pos_light_view_1=u_light_matrix_1*shadow_pos;v_depth_shadows=gl_Position.w; #endif }`),modelDepth:Zi("void main() {}",`in vec3 a_pos_3f;uniform mat4 u_matrix; #ifdef MODEL_POSITION_ON_GPU #ifdef INSTANCED_ARRAYS in vec4 a_normal_matrix0;in vec4 a_normal_matrix1;in vec4 a_normal_matrix2;in vec4 a_normal_matrix3; #else uniform highp mat4 u_instance; #endif uniform highp mat4 u_node_matrix; #endif void main() { #ifdef MODEL_POSITION_ON_GPU highp mat4 instance; #ifdef INSTANCED_ARRAYS instance=mat4(a_normal_matrix0,a_normal_matrix1,a_normal_matrix2,a_normal_matrix3); #else instance=u_instance; #endif vec3 pos_color=instance[0].xyz;vec4 translate=instance[1];vec3 pos_a=floor(pos_color);float hidden=float(pos_a.x > EXTENT);float meter_to_tile=instance[0].w;vec4 pos=vec4(pos_a.xy,translate.z,1.0);mat3 rs;rs[0].x=instance[1].w;rs[0].yz=instance[2].xy;rs[1].xy=instance[2].zw;rs[1].z=instance[3].x;rs[2].xyz=instance[3].yzw;vec4 pos_node=u_node_matrix*vec4(a_pos_3f,1.0);vec3 rotated_pos_node=rs*pos_node.xyz;vec3 pos_model_tile=(rotated_pos_node+vec3(translate.xy,0.0))*vec3(meter_to_tile,meter_to_tile,1.0);pos.xyz+=pos_model_tile;gl_Position=mix(u_matrix*pos,AWAY,hidden); #else gl_Position=u_matrix*vec4(a_pos_3f,1); #endif }`),fillExtrusionDepth:Zi("void main() {}",`#include "_prelude_terrain.vertex.glsl" #include "_prelude_material_table.vertex.glsl" uniform mat4 u_matrix;uniform float u_edge_radius;uniform float u_width_scale;uniform float u_vertical_scale; #ifdef TERRAIN uniform int u_height_type;uniform int u_base_type; #endif in ivec4 a_pos_normal_ed; #if defined(HAS_CENTROID) || defined(TERRAIN) in uvec2 a_centroid_pos; #endif #ifdef RENDER_WALL_MODE in ivec4 a_join_normal_inside; #endif #pragma mapbox: define highp float base #pragma mapbox: define highp float height #pragma mapbox: define highp float line_width #pragma mapbox: define highp vec4 color void main() {DECLARE_MATERIAL_TABLE_INFO #pragma mapbox: initialize highp float base #pragma mapbox: initialize highp float height #pragma mapbox: initialize highp float line_width #pragma mapbox: initialize highp vec4 color base*=u_vertical_scale;height*=u_vertical_scale;vec3 top_up_ny=vec3(a_pos_normal_ed.xyz & 1);vec3 pos_nx=vec3(a_pos_normal_ed.xyz >> 1);base=max(0.0,base);height=max(0.0,top_up_ny.y==0.0 && top_up_ny.x==1.0 ? height-u_edge_radius : height);float t=top_up_ny.x;vec2 centroid_pos=vec2(0.0); #if defined(HAS_CENTROID) || defined(TERRAIN) centroid_pos=vec2(a_centroid_pos); #endif vec3 pos; #ifdef TERRAIN bool is_flat_height=centroid_pos.x !=0.0 && u_height_type==1;bool is_flat_base=centroid_pos.x !=0.0 && u_base_type==1;float ele=elevation(pos_nx.xy);bool is_elevation_encoded=centroid_pos.y==0.0 || (centroid_pos.y > 0.0 && int(centroid_pos.y)-(int(centroid_pos.y)/8)*8==7);float c_ele=is_flat_height || is_flat_base ? (is_elevation_encoded ? elevationFromUint16(centroid_pos.x) : flatElevation(centroid_pos)) : ele;float h_height=is_flat_height ? max(c_ele+height,ele+base+2.0) : ele+height;float h_base=is_flat_base ? max(c_ele+base,ele+base) : ele+(base==0.0 ?-5.0 : base);float h=t > 0.0 ? max(h_base,h_height) : h_base;pos=vec3(pos_nx.xy,h); #else pos=vec3(pos_nx.xy,t > 0.0 ? height : base); #endif #ifdef RENDER_WALL_MODE vec3 join_normal_inside=vec3(a_join_normal_inside);vec2 wall_offset=u_width_scale*line_width*(join_normal_inside.xy/EXTENT);pos.xy+=(1.0-join_normal_inside.z)*wall_offset*0.5;pos.xy-=join_normal_inside.z*wall_offset*0.5; #endif float hidden=float((centroid_pos.x==0.0 && centroid_pos.y==1.0) || (color.a==0.0));gl_Position=mix(u_matrix*vec4(pos,1),AWAY,hidden);}`),fillExtrusionGroundEffect:Zi(`uniform highp float u_ao_pass;uniform highp float u_opacity;uniform highp float u_flood_light_intensity;uniform highp vec3 u_flood_light_color;uniform highp float u_attenuation;uniform sampler2D u_fb;uniform float u_fb_size; #ifdef SDF_SUBPASS in highp vec2 v_pos;in highp vec4 v_line_segment;in highp float v_flood_light_radius_tile;in highp vec2 v_ao;float line_df(highp vec2 a,highp vec2 b,highp vec2 p) {highp vec2 ba=b-a;highp vec2 pa=p-a;highp float r=clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);return length(pa-r*ba);} #ifdef FOG in highp float v_fog; #endif #endif void main() { #ifdef CLEAR_SUBPASS vec4 color=vec4(1.0); #ifdef CLEAR_FROM_TEXTURE color=texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size)); #endif glFragColor=color; #else #ifdef SDF_SUBPASS highp float d=line_df(v_line_segment.xy,v_line_segment.zw,v_pos);highp float effect_radius=mix(v_flood_light_radius_tile,v_ao.y,u_ao_pass);d/=effect_radius;d=min(d,1.0);d=1.0-pow(1.0-d,u_attenuation);highp float effect_intensity=mix(u_flood_light_intensity,v_ao.x,u_ao_pass);highp float fog=1.0; #ifdef FOG fog=v_fog; #endif #ifdef RENDER_CUTOFF fog*=v_cutoff_opacity; #endif glFragColor=vec4(vec3(0.0),mix(1.0,d,effect_intensity*u_opacity*fog)); #else #ifdef USE_MRT1 out_Target1=vec4(1.0-texture(u_fb,gl_FragCoord.xy/vec2(u_fb_size)).a,0.0,0.0,0.0); #else vec4 color=mix(vec4(u_flood_light_color,1.0),vec4(vec3(0.0),1.0),u_ao_pass); #ifdef OVERDRAW_INSPECTOR color=vec4(1.0); #endif glFragColor=color; #endif #endif HANDLE_WIREFRAME_DEBUG; #endif }`,`#include "_prelude_fog.vertex.glsl" in highp ivec4 a_pos_end;in highp int a_angular_offset_factor;in highp uint a_hidden_by_landmark; #ifdef SDF_SUBPASS out highp vec2 v_pos;out highp vec4 v_line_segment;out highp float v_flood_light_radius_tile;out highp vec2 v_ao; #ifdef FOG out highp float v_fog; #endif #endif uniform highp float u_flood_light_intensity;uniform highp mat4 u_matrix;uniform highp float u_ao_pass;uniform highp float u_meter_to_tile;uniform highp float u_edge_radius;uniform highp float u_dynamic_offset;uniform highp vec2 u_ao; #pragma mapbox: define highp float flood_light_ground_radius const float TANGENT_CUTOFF=4.0;const float NORM=32767.0;void main() { #pragma mapbox: initialize highp float flood_light_ground_radius vec4 pos_end=vec4(a_pos_end);vec2 p=pos_end.xy;vec2 q=floor(pos_end.zw*0.5);vec2 start_bottom=pos_end.zw-q*2.0;float fl_ground_radius=abs(flood_light_ground_radius);float direction=flood_light_ground_radius < 0.0 ?-1.0 : 1.0;float flood_radius_tile=fl_ground_radius*u_meter_to_tile;vec2 v=normalize(q-p);float ao_radius=u_ao.y/3.5;float effect_radius=mix(flood_radius_tile,ao_radius,u_ao_pass)+u_edge_radius;float angular_offset_factor=float(a_angular_offset_factor)/NORM*TANGENT_CUTOFF;float angular_offset=direction*angular_offset_factor*effect_radius;float top=1.0-start_bottom.y;float side=(0.5-start_bottom.x)*2.0;vec2 extrusion_parallel=v*side*mix(u_dynamic_offset,angular_offset,top);vec2 perp=vec2(v.y,-v.x);vec2 extrusion_perp=direction*perp*effect_radius*top;vec3 pos=vec3(mix(q,p,start_bottom.x),0.0);pos.xy+=extrusion_parallel+extrusion_perp; #ifdef SDF_SUBPASS v_pos=pos.xy;v_line_segment=vec4(p,q)+perp.xyxy*u_edge_radius;v_flood_light_radius_tile=flood_radius_tile;v_ao=vec2(u_ao.x,ao_radius); #ifdef FOG v_fog_pos=fog_position(pos);v_fog=1.0-fog(v_fog_pos); #endif #endif float hidden_by_landmark=0.0; #ifdef HAS_CENTROID hidden_by_landmark=float(a_hidden_by_landmark); #endif float isFloodlit=float(fl_ground_radius > 0.0 && u_flood_light_intensity > 0.0);float hidden=mix(1.0-isFloodlit,isFloodlit,u_ao_pass);hidden+=hidden_by_landmark;gl_Position=mix(u_matrix*vec4(pos,1.0),AWAY,float(hidden > 0.0)); #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,native_clip_z_to_cutoff_depth(gl_Position.z,gl_Position.w)); #endif }`),groundShadow:Zi(`#include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" precision highp float;uniform vec3 u_ground_shadow_factor;in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1; #ifdef FOG in float v_fog_opacity; #endif void main() {float light=shadowed_light_factor_plane_bias(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);vec3 shadow=mix(u_ground_shadow_factor,vec3(1.0),light); #ifdef RENDER_CUTOFF shadow=mix(vec3(1.0),shadow,cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w)); #endif #ifdef FOG shadow=mix(shadow,vec3(1.0),v_fog_opacity); #endif glFragColor=vec4(shadow,1.0);}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;in ivec2 a_pos;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1; #ifdef FOG out float v_fog_opacity; #endif void main() {gl_Position=u_matrix*vec4(a_pos,0.0,1.0);v_pos_light_view_0=u_light_matrix_0*vec4(a_pos,0.0,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(a_pos,0.0,1.0); #ifdef FOG v_fog_pos=fog_position(vec2(a_pos));v_fog_opacity=fog(v_fog_pos); #endif }`)};const xMe=(h,o)=>({u_matrix:h,u_ground_shadow_factor:o});function Dne(h,o,u=0){const m=Math.pow(2,o.tileID.overscaledZ),x=o.tileSize*Math.pow(2,h.transform.tileZoom)/m,b=x*(o.tileID.canonical.x+o.tileID.wrap*m),S=x*o.tileID.canonical.y;return{u_image:0,u_texsize:o.imageAtlasTexture?o.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/Pk(o,1,h.transform.tileZoom),u_pixel_coord_upper:[b>>16,S>>16],u_pixel_coord_lower:[65535&b,65535&S],u_pattern_transition:u}}const DL={terrain:0,flat:1},_Me=O(),Mne=[0,0,0],One=(h,o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae,ue=[0,0,1],ce=!1)=>{let de=Mne,xe=0,ve=Mne;if(!ce){const De=o.style.light,Ve=De.properties.get("position");if(de=[Ve.x,Ve.y,Ve.z],De.properties.get("anchor")==="viewport"){const Ze=P();L(Ze,-o.transform.angle),Tn(de,de,Ze)}const Fe=De.properties.get("color").toPremultipliedRenderColor(null);xe=De.properties.get("intensity"),ve=[Fe.r,Fe.g,Fe.b]}const Ue=o.transform,Pe={u_matrix:h,u_lightpos:de,u_lightintensity:xe,u_lightcolor:ve,u_vertical_gradient:+u,u_opacity:m,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:_Me,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:DL[D],u_base_type:DL[B],u_ao:x,u_edge_radius:b,u_width_scale:S,u_flood_light_color:X,u_vertical_scale:J,u_flood_light_intensity:se,u_ground_shadow_factor:ae,u_front_cutoff_params:ue};return Ue.projection.name==="globe"&&(Pe.u_tile_id=[A.canonical.x,A.canonical.y,1<{let Ye=De;_t.groundRadiusBuffer!=null&&(Ye=De.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const At=_t.programConfigurations.get(m.id),Tt=o.isTileAffectedByFog(ht),$t=o.getOrCreateProgram("fillExtrusionGroundEffect",{config:At,defines:Ye,overrideFog:Tt}),Gt=((Dt,dr,nr,yr,Br,br,dn,rn,wr,Fr)=>({u_matrix:Dt,u_opacity:dr,u_ao_pass:nr?1:0,u_meter_to_tile:yr,u_ao:Br,u_flood_light_intensity:br,u_flood_light_color:dn,u_attenuation:rn,u_edge_radius:wr,u_fb:0,u_fb_size:Fr,u_dynamic_offset:1}))(Pt,U,D,Rt,[q,K*Rt],X,J,se,Pe>=17?0:Ze*Rt,ce?ce.size[0]:0),kt=[];ae&&kt.push(_t.hiddenByLandmarkVertexBuffer),_t.groundRadiusBuffer!=null&&kt.push(_t.groundRadiusBuffer),o.uploadCommonUniforms(xe,$t,ht.toUnwrapped(),null,st),$t.draw(o,xe.gl.TRIANGLES,b,S,A,I,Gt,m.id,_t.vertexBuffer,_t.indexBuffer,Et,m.paint,Pe,At,kt)};for(const ht of x){const _t=u.getTile(ht),Et=_t.getBucket(m);if(!Et||Et.projection.name!==Ue.projection.name||!Et.groundEffect||Et.groundEffect&&!Et.groundEffect.hasData())continue;const Pt=Et.groundEffect,Rt=1/Et.tileToMeter;{const Ye=o.translatePosMatrix(ht.projMatrix,_t,Ve,Fe),At=Pt.getDefaultSegment();ut(ht,Pt,At,Ye,Rt)}if(ue)for(let Ye=0;Ye<4;Ye++){const At=qJ[Ye](ht),Tt=u.getTile(At);if(!Tt)continue;const $t=Tt.getBucket(m);if(!$t||$t.projection.name!==Ue.projection.name||!$t.groundEffect||$t.groundEffect&&!$t.groundEffect.hasData())continue;const Gt=$t.groundEffect;let kt,Dt;Ye===0?(kt=[-8192,0,0],Dt=1):Ye===1?(kt=[ar,0,0],Dt=0):Ye===2?(kt=[0,-8192,0],Dt=3):(kt=[0,ar,0],Dt=2);const dr=Gt.regionSegments[Dt];dr&&(ee(Fne,ht.projMatrix,kt),ut(ht,Gt,dr,o.translatePosMatrix(Fne,_t,Ve,Fe),Rt))}}}const vMe={model:h=>({u_matrix:new ua(h),u_lighting_matrix:new ua(h),u_normal_matrix:new ua(h),u_node_matrix:new ua(h),u_lightpos:new ti(h),u_lightintensity:new Dr(h),u_lightcolor:new ti(h),u_camera_pos:new ti(h),u_opacity:new Dr(h),u_baseColorFactor:new ao(h),u_emissiveFactor:new ao(h),u_metallicFactor:new Dr(h),u_roughnessFactor:new Dr(h),u_alphaMask:new yi(h),u_alphaCutoff:new Dr(h),u_baseColorTexture:new yi(h),u_metallicRoughnessTexture:new yi(h),u_normalTexture:new yi(h),u_occlusionTexture:new yi(h),u_emissionTexture:new yi(h),u_lutTexture:new yi(h),u_color_mix:new ao(h),u_aoIntensity:new Dr(h),u_emissive_strength:new Dr(h),u_occlusionTextureTransform:new ao(h),u_dithered_discard_threshold:new Dr(h),u_model_mesh_params:new ao(h)}),modelDepth:h=>({u_matrix:new ua(h),u_instance:new ua(h),u_node_matrix:new ua(h)}),groundShadow:h=>({u_matrix:new ua(h),u_ground_shadow_factor:new ti(h)}),fillExtrusionDepth:h=>({u_matrix:new ua(h),u_edge_radius:new Dr(h),u_width_scale:new Dr(h),u_vertical_scale:new Dr(h),u_height_type:new yi(h),u_base_type:new yi(h)}),fillExtrusionGroundEffect:h=>({u_matrix:new ua(h),u_opacity:new Dr(h),u_ao_pass:new Dr(h),u_meter_to_tile:new Dr(h),u_ao:new Pn(h),u_flood_light_intensity:new Dr(h),u_flood_light_color:new ti(h),u_attenuation:new Dr(h),u_edge_radius:new Dr(h),u_fb:new yi(h),u_fb_size:new Dr(h),u_dynamic_offset:new Dr(h)})};function zne(h){const o=h.properties.get("direction"),u=pf(o.x,o.y,o.z);u[2]=cn(u[2],0,75);const m=gx([u[0],u[1],u[2]]);return nt(m.x,m.y,m.z)}function $ne(h,o,u){const m=o.properties.get("color-use-theme")==="none",x=o.properties.get("color"),b=o.properties.get("intensity"),S=o.properties.get("direction"),A=[S.x,S.y,S.z],I=u.properties.get("color-use-theme")==="none",D=u.properties.get("color"),B=u.properties.get("intensity"),U=Math.max(Vr([0,0,1],A),0),q=[0,0,0];ft(q,D.toPremultipliedRenderColor(I?null:h.getLut(o.scope)).toArray01Linear().slice(0,3),B);const K=[0,0,0];return ft(K,x.toPremultipliedRenderColor(m?null:h.getLut(u.scope)).toArray01Linear().slice(0,3),U*b),Uc([q[0]>0?q[0]/(q[0]+K[0]):0,q[1]>0?q[1]/(q[1]+K[1]):0,q[2]>0?q[2]/(q[2]+K[2]):0])}const ML=[];function Une(h){return ML[h]=ML[h]||new Float64Array(16)}const OL=[],bMe=new Float32Array(16);class wMe{constructor(o,u){this.aabb=o,this.lastCascade=u}}class SMe{add(o,u){const m=this.receivers[o.key];m!==void 0?(m.aabb.min[0]=Math.min(m.aabb.min[0],u.min[0]),m.aabb.min[1]=Math.min(m.aabb.min[1],u.min[1]),m.aabb.min[2]=Math.min(m.aabb.min[2],u.min[2]),m.aabb.max[0]=Math.max(m.aabb.max[0],u.max[0]),m.aabb.max[1]=Math.max(m.aabb.max[1],u.max[1]),m.aabb.max[2]=Math.max(m.aabb.max[2],u.max[2])):this.receivers[o.key]=new wMe(u,null)}clear(){this.receivers={}}get(o){return this.receivers[o.key]}computeRequiredCascades(o,u,m){const x=js.fromPoints(o.points);let b=0;for(const S in this.receivers){const A=this.receivers[S];if(!A||!x.intersectsAabb(A.aabb))continue;A.aabb.min=x.closestPoint(A.aabb.min),A.aabb.max=x.closestPoint(A.aabb.max);const I=A.aabb.getCorners();for(let D=0;D1||q[1]<-1||q[1]>1){B=!1;break}}if(A.lastCascade=D,b=Math.max(b,D),B)break}}return b+1}}function FL(h,o,u){const m=Jr([],Or([],u,o),Or([],h,o)),x=ot(m);return x===0?[0,0,1,0]:(ft(m,m,1/x),[m[0],m[1],m[2],-Vr(m,o)])}function EMe(h,o,u,m,x,b){const S=h.zoom,A=h.scale,I=h.worldSize,D=1/I,B=h.aspect,U=Math.sqrt(1+B*B)*Math.tan(.5*h.fovX),q=U*U,K=m-u,X=m+u;let J,se;q>K/X?(J=m,se=m*U):(J=.5*X*(1+q),se=.5*Math.sqrt(K*K+2*(m*m+u*u)*q+X*X*q*q));const ae=h.projection.pixelsPerMeter(h.center.lat,I),ue=[0,0,-J*D];Ar(ue,ue,h._camera.getCameraToWorldMercator());let ce=se*D;const de=function(Rt){return Rt[0]/=A,Rt[1]/=A,Rt[2]=ks(Rt[2],h._center.lat),Rt},xe=h._edgeInsets;if(!(xe.left===0&&xe.top===0&&xe.right===0&&xe.bottom===0||xe.left===xe.right&&xe.top===xe.bottom)){const Rt=h._camera.getWorldToCamera(h.worldSize,h.projection.zAxisUnit==="meters"?ae:1),Ye=h._camera.getCameraToClipPerspective(h._fov,h.width/h.height,u,m);Ye[8]=2*-h.centerOffset.x/h.width,Ye[9]=2*h.centerOffset.y/h.height;const At=new Float64Array(16);Ae(At,Ye,Rt);const Tt=new Float64Array(16);Z(Tt,At);const $t=q0.fromInvProjectionMatrix(Tt,I,S,!0);for(const Gt of $t.points){const kt=de(Gt);ce=Math.max(ce,ss(Vt([],ue,kt)))}}ce*=x/(x-1);const ve=Math.acos(o[2]),Ue=Math.atan2(-o[0],-o[1]),Pe=new jL;Pe.position=ue,Pe.setPitchBearing(ve,Ue);const De=Pe.getWorldToCamera(I,ae),Ve=ce*I,Fe=Math.min(h._mercatorZfromZoom(17)*I*-2,-2*Ve),Ze=Pe.getCameraToClipOrthographic(-Ve,Ve,-Ve,Ve,Fe,(Ve+b*ae)/o[2]),st=new Float64Array(16);Q(st,Ze,De);const ut=.5*x,ht=[0,0,0];Ar(ht,nt(Math.floor(1e6*ue[0])/1e6*I,Math.floor(1e6*ue[1])/1e6*I,0),st),ft(ht,ht,ut);const _t=[Math.floor(ht[0]),Math.floor(ht[1]),Math.floor(ht[2])],Et=[0,0,0];Or(Et,ht,_t),ft(Et,Et,-1/ut);const Pt=new Float64Array(16);return G(Pt),ee(Pt,Pt,Et),Q(st,Pt,st),[st,Ve]}class ny extends ca{constructor(o,u,m,x){super(),this.id=o,this.type="model",this.models=[],this._options=u,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}async loadGLTFFromURI(o,u){return fte(await this.map._requestManager.transformRequest(o,er.Model,u),u)}async loadModel(o,u,m){try{const x=await this.loadGLTFFromURI(u.uri,m);if(m.aborted)return;const b=this._modelsInfo.get(o);if(!b)return;const S=_$(x),A=b.modelSpec,I=new _te(o,A.uri,A.position,A.orientation,S);ny.applyModelSpecification(I,A),I.computeBoundsAndApplyParent(),this.models.push(I),b.model=I}catch(x){if(m.aborted)return;this.fire(new Oa(new Error(`Could not load model ${o} from ${u.uri}`,{cause:x})))}}async load(){this._abortController||(this._abortController=new AbortController);const o=this._abortController.signal,u=[];for(const m in this._options.models){const x=this._options.models[m],b=this._modelsInfo.get(m);if(b&&b.model){b.modelSpec=x;const S=b.model;S.position=x.position!=null?new pi(x.position[0],x.position[1]):new pi(0,0),S.orientation=x.orientation??[0,0,0],ny.applyModelSpecification(S,x),S.computeBoundsAndApplyParent(),this.models.push(S)}else b?b.modelSpec=x:(this._modelsInfo.set(m,{modelSpec:x,model:null}),u.push(this.loadModel(m,x,o)))}u.length!==0?(await Promise.allSettled(u),o.aborted||this.fire(new nl("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new nl("data",{dataType:"source",sourceDataType:"metadata"}))}static arrayFromColorSpecification(o){const u=o;if(u===void 0)return;if(Array.isArray(u))return[u[0],u[1],u[2]];const m=Vn.parse(u);return m?[m.r,m.g,m.b]:void 0}static applyModelSpecification(o,u){if(u.nodeOverrides&&ny.convertNodeOverrides(o,u.nodeOverrides),u.materialOverrides&&ny.convertMaterialOverrides(o,u.materialOverrides),u.nodeOverrideNames&&(o.nodeOverrideNames=[...u.nodeOverrideNames]),u.materialOverrideNames&&(o.materialOverrideNames=[...u.materialOverrideNames]),u.featureProperties&&(o.featureProperties=u.featureProperties),u.lightOverrides){const m=u.lightOverrides,x=ny.arrayFromColorSpecification(m["light-ambient-color"]),b=ny.arrayFromColorSpecification(m["light-directional-color"]);o.lightOverrides={ambientIntensity:m["light-ambient-intensity"],ambientColor:x,directionalIntensity:m["light-directional-intensity"],directionalColor:b}}else o.lightOverrides=void 0}static convertNodeOverrides(o,u){if(Array.isArray(u)&&u.every(m=>typeof m=="string")){o.nodeOverrideNames=[];for(const m of u)o.nodeOverrideNames.push(m)}else Object.entries(u).forEach(([m,x])=>{const b={orientation:[0,0,0],minZoom:void 0,maxZoom:void 0};if(Object.hasOwn(x,"orientation")){const S=x.orientation;S&&(b.orientation=S)}Object.hasOwn(x,"minzoom")&&(b.minZoom=x.minzoom),Object.hasOwn(x,"maxzoom")&&(b.maxZoom=x.maxzoom),o.nodeOverrides.set(m,b)})}static convertMaterialOverrides(o,u){if(Array.isArray(u)&&u.every(m=>typeof m=="string")){o.materialOverrideNames=[];for(const m of u)o.materialOverrideNames.push(m)}else Object.entries(u).forEach(([m,x])=>{const b=ny.arrayFromColorSpecification(x["model-color"]),S={color:b!==void 0?new Vn(b[0],b[1],b[2]):new Vn(1,1,1),colorMix:0,emissionStrength:0,opacity:1},A=x["model-color-mix-intensity"];A!==void 0&&(S.colorMix=A);const I=x["model-emissive-strength"];I!==void 0&&(S.emissionStrength=I);const D=x["model-opacity"];D!==void 0&&(S.opacity=D),o.materialOverrides.set(m,S)})}onAdd(o){this.map=o,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const o of this._modelsInfo.values())if(o.model==null)return!1;return!0}getModels(){return this.models}loadTile(o,u){}serialize(){return this._options}setProperty(o,u){return!1}reload(){this.cancelModelRequests();const o=Bx(this.id,this.scope);this.map.style.clearSource(o),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(o){this.cancelModelRequests()}setModels(o){this.models=[];const u=new Map;for(const m in o){const x=o[m],b=this._modelsInfo.get(m);b&&b.modelSpec.uri===x.uri&&u.set(m,b)}if(this._modelsInfo.size!==u.size){this.cancelModelRequests();for(const[m,x]of u)x.model||u.delete(m)}this._modelsInfo=u,this._options.models=o,this.load()}}function Vne(h,o,u){try{o=function(x){if(!x.variants)return x;if(!Array.isArray(x.variants))throw new Error("variants must be an array");let b=null,S=null;for(const I of x.variants){if(I==null||typeof I!="object"||I.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(I.capabilities))throw new Error("capabilities must be an array");I.capabilities.length===1&&(I.capabilities[0]==="meshopt-v2+lod"?S=I:I.capabilities[0]==="meshopt"&&(b=I))}const A=S!==null?S:b;return A!==null?Object.assign(x,A):x}(o)}catch(x){return new Error("Failed to process TileJSON variants",{cause:x})}const m=cd({...o,...h},["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return h.url&&o.tiles&&h.tiles&&(m.tiles=o.tiles),m.tiles=u.canonicalizeTileset(m,h.url),m}function qne(h,o,u,m,x){const b=function(A,I){if(A)return x(A);if(I){h.url&&I.tiles&&h.tiles&&delete h.tiles;const D=Vne(h,I,o);if(D instanceof Error)return x(D);x(null,D)}},S=function(A,I,D){if(!A)return null;if(!I&&!D)return A;D=D||A.worldview_default;const B=Object.values(A.language||{});if(B.length===0)return null;const U=Object.values(A.worldview||{});if(U.length===0)return null;const q=B.every(X=>X===I),K=U.every(X=>X===D);return q&&K?A:null}(h.data,u,m);if(S)return hu.frame(()=>b(null,S));if(h.url){const A=new AbortController;return(async()=>{const I=await o.transformRequest(o.normalizeSourceURL(h.url,null,u,m),er.Source,A.signal),{data:D}=await ui(I,A.signal);b(null,D)})().catch(I=>{A.signal.aborted||b(I)}),{cancel:()=>A.abort()}}return hu.frame(()=>{const{data:A,...I}=h;b(null,I)})}function Gne(h,o){const u=Math.pow(2,o.z),m=Math.floor(mu(h.getWest())*u),x=Math.floor(vc(h.getNorth())*u),b=Math.ceil(mu(h.getEast())*u),S=Math.ceil(vc(h.getSouth())*u);return o.x>=m&&o.x=x&&o.y0?o.extra_bounds.map(u=>Qd.convert(this.validateBounds(u))):null,this.minzoom=o.minzoom||0,this.maxzoom=o.maxzoom||24}validateBounds(o){return Array.isArray(o)&&o.length===4?[Math.max(-180,o[0]),Math.max(-90,o[1]),Math.min(180,o[2]),Math.min(90,o[3])]:[-180,-90,180,90]}contains(o){if(o.z>this.maxzoom||o.z{D&&(D.useNormalOffset=!0,B||(D.enabled=!0))},q=o.getSource();if(h.renderPass==="light-beam"&&q.type!=="batched-model")return;if(q.type==="vector"||q.type==="geojson")return function(de,xe,ve,Ue,Pe){const De=de.transform,Ve=De.projection.name==="globe",Fe=De.getFreeCameraOptions().position;if(!de.modelManager)return;const Ze=de.modelManager;ve.modelManager=Ze;const st=de.shadowRenderer,ut=ve.getLayoutPropertyValue("model-id");if(ut.value===void 0)return;const ht={...ve.layout.get("model-id").parameters},_t=de.style.order.indexOf(ve.fqid),Et=ve.paint.get("model-opacity").constantOr(1),Pt=F$(de,ve);for(const Rt of Ue){const Ye=xe.getTile(Rt).getBucket(ve);if(!Ye||Ye.projection.name!==De.projection.name)continue;const At=Ye.getModelUris();if(At&&!Ye.modelsRequested&&(Ze.addModelsFromBucket(At,Pe),Ye.modelsRequested=!0),Ve)ht.zoom=Rt.overscaledZ;else{const yr=oMe(Rt,De,Fe);ht.zoom=yr}const Tt=ut.possiblyEvaluate(ht);if(aMe(de,Ye,Rt),Pp.shadowUniformsInitialized=!1,Pp.useSingleShadowCascade=!!st&&st.getMaxCascadeForTile(Rt.toUnwrapped())===0,de.renderPass==="shadow"&&st){if(de.currentShadowCascade===1&&Ye.isInsideFirstShadowMapFrustum)continue;const yr=De.calculatePosMatrix(Rt.toUnwrapped());if(Pp.tileMatrix.set(yr),Pp.shadowTileMatrix.set(st.calculateShadowPassMatrixFromMatrix(yr)),Pp.aabb.min=[0,0,0],Pp.aabb.max[0]=Pp.aabb.max[1]=ar,Pp.aabb.max[2]=0,cMe(Ye,Pp,de,ve.scope))continue}const $t=1<0&&de.style.isLayerClipped(ve,xe.getSource())&&Ye.updateReplacement(Rt,de.replacementSource,_t,ve.scope)&&(Ye.uploaded=!1,Ye.upload(de.context));let kt=0;const Dt=new Array,dr=new Array,nr=new Array;for(let yr in Ye.instancesPerModel){const Br=Ye.instancesPerModel[yr];Br.features.length>0&&!Ve&&(yr=Tt.evaluate(Br.features[0].feature,{}));const br=Ze.getModel(yr,Pe);if(br||Ze.hasURLBeenRequested(yr)||Ye.modelUris.includes(yr)||(Ye.modelUris.push(yr),Ye.modelsRequested=!1),br&&br.uploaded)if(Ve){const dn=ft([],[Fe.x,Fe.y,Fe.z],de.transform.worldSize);Qt(dn,dn);for(let rn=0;rn0&&ws.elevationUpdate(wr.terrain,Xn,mi,ni.source),ws.needsReEvaluation(wr,bi,ni)&&ws.evaluate(ni))}})(de,xe,ve,Ue),function(){const wr=new Map;let Fr,ni,ii;br?(Fr=Ue.length-1,ni=-1,ii=-1):(Fr=0,ni=Ue.length,ii=1);const Xn=He(),bi=new jt(0,0);for(let mi=Fr;mi!==ni;mi+=ii){const ws=Ue[mi],Fs=xe.getTile(ws).getBucket(ve);if(!Fs||!Fs.uploaded)continue;let Xa=!1;Fe&&(Xa=Fe.getMaxCascadeForTile(ws.toUnwrapped())===0);const ns=De.calculatePosMatrix(ws.toUnwrapped()),Gi=!!(4&Fs.modelTraits);Q(K$,De.expandedFarZProjMatrix,ns),Q(uS,Rt,ns),Z(uS,uS),W(uS,uS);const ka=!Tt&&Fe&&Fe.enabled?Fe.computeCascadeTileMatrices(ns):null;!Tt&&br&&(Z(s_,ns),Ar(Xn,st,s_),bi.x=Xn[0],bi.y=Xn[1]);const Kc=1/Wc(ws.canonical),Sl=[];Fs.setFilter(ve.filter);for(const _n of Fs.getNodesInfo()){if(_n.hiddenByReplacement||!_n.node.meshes)continue;const Bs=_n.node;let Ia=0;de.terrain&&Bs.elevation&&(Ia=Bs.elevation*de.terrain.exaggeration());const oo=_n.aabb,es=Dt.min,Ss=Dt.max;es[0]=oo.min[0],es[1]=oo.min[1],es[2]=oo.min[2]+Ia,Ss[0]=oo.max[0],Ss[1]=oo.max[1],Ss[2]=oo.max[2]+Ia,Ar(es,es,ns),Ar(Ss,Ss,ns);const Yu=_n.evaluatedScale;if(Yu[0]<=1&&Yu[1]<=1&&Yu[2]<=1&&Dt.intersects(yr)===0)continue;if(!Tt){NL[0]=.5*(es[0]+Ss[0]),NL[1]=.5*(es[1]+Ss[1]),NL[2]=.5*(es[2]+Ss[2]);const sy=ir(st,NL)*_t,l_=de._debugParams.lodSwitchDistance,vu=l_>=0;if(vu&&l_>=9999)_n.targetLod=0;else{let Yc;if(vu)Yc=l_;else{const c_=(Ss[2]-es[2])*_t*Yu[2],eb=Math.max(Ss[0]-es[0],Ss[1]-es[1])*_t*Math.max(Yu[0],Yu[1]);let vm;vm=c_>=30?1:eb>=80?.5:Math.max(c_,eb)>=20?.25:0,Yc=2e3+3e3*vm}lMe(_n,sy,Math.min(de.frameTimeDelta,1e3/30),Yc,de._debugParams.lodSwitchFadeDuration)}}if(!Tt&&br){const sy=.16666666666666666;_n.cameraCollisionOpacity=st[0]>es[0]&&st[0]es[1]&&st[1]!br||_n.opacity===1&&Bs.opacity===1?_n.depthBs.depth?-1:1);for(const _n of Sl){const{nodeInfo:Bs,tileTranslation:Ia,opacity:oo}=_n,{node:es,evaluatedScale:Ss}=Bs;let Yu=null;if(de._debugParams.show3DModelFootprints&&es.footprint){const vu=es.id||es.name||"footprint";if(!wr.has(vu)){const Yc=Dk(new Float64Array(16),K$,Ia,Ss);wr.set(vu,{node:es,mvp:Yc})}}const o_=Gi?0:Bs.emissiveStrength,Tc=Bs.targetLod,iy=es.lodMeshes&&es.lodMeshes.length>0,Sf=iy&&Tc>0&&Tc<1;if(Tt&&iy&&Math.round(Tc)===1)continue;const Qa=Dk(dne,ns,Ia,Ss);Q(Qa,Qa,es.globalMatrix);const J0=$t?Q(cne,$t,Qa):null,_m=Tt&&Fe?Fe.calculateShadowPassMatrixFromMatrix(Qa):null;Tt||(Q(une,De.expandedFarZProjMatrix,Qa),Q(i_,Rt,Qa),PL[0]=1/Ss[0],PL[1]=-1/Ss[1],PL[2]=1/Ss[2],ie(s_,uS,PL));const sy=Sf?2:1,l_=iy&&Math.round(Tc)===1;for(let vu=0;vu=fk||Uo>=fk}const wu=En.material;let $L;wu.occlusionTexture&&wu.occlusionTexture.offsetScale&&($L=wu.occlusionTexture.offsetScale,ja.defines.push("OCCLUSION_TEXTURE_TRANSFORM")),Sf&&ja.defines.push("DITHERED_DISCARD");const u_=de.getOrCreateProgram("model",ja);if(Fe&&Fe.enabled)if(Yu!==bu){for(let bm=0;bm0){const mi=Array.from(wr.keys()).sort();for(const ws of mi){const{node:Fs,mvp:Xa}=wr.get(ws);mne(de,0,Fs,Xa)}}}()}(h,o,u,m),void U();if(q.type!=="model")return;const K=q.getModels(),X=[],J=h.transform.getFreeCameraOptions().position,se=ft([],[J.x,J.y,J.z],h.transform.worldSize);Qt(se,se);const ae=[],ue=[];let ce=0;for(const de of K){const xe=o.getFeatureState("",de.id),ve={type:"Unknown",id:de.id,properties:de.featureProperties},Ue=u.paint.get("model-rotation").evaluate(ve,xe),Pe=u.paint.get("model-scale").evaluate(ve,xe),De=u.paint.get("model-translation").evaluate(ve,xe),Ve=u.paint.get("model-opacity").evaluate(ve,xe);iMe(u,de.id,xe,de.featureProperties,de.nodeOverrideNames,de.nodeOverrides),sMe(u,de.id,xe,de.featureProperties,de.materialOverrideNames,de.materialOverrides),de.nodeOverrides.size>0&&de.computeBoundsAndApplyParent(),de.computeModelMatrix(h,Ue,Pe,De,A,S,!1);const Fe=be([],se),Ze=Re([],[1,1,1/bf(de.position.lat,h.transform.zoom)]);X.push({zScaleMatrix:Ze,negCameraPosMatrix:Fe});for(const st of de.nodes)Q$(h,st,de.matrix,h.transform.expandedFarZProjMatrix,ce,ae,ue,de.materialOverrides,Ve,void 0,de.lightOverrides);ce++}if(ae.sort((de,xe)=>xe.depth-de.depth),h.renderPass!=="shadow"){if(h._debugParams.show3DModelFootprints){const de=h.transform.projMatrix,xe=new Map,ve=(Pe,De)=>{if(Pe.footprint){const Ve=Pe.id||Pe.name||"footprint";if(!xe.has(Ve)){const Fe=Q([],de,De);xe.set(Ve,{node:Pe,mvp:Fe})}}};for(const Pe of ue)ve(Pe.node,Pe.modelMatrix);for(const Pe of ae)ve(Pe.node,Pe.modelMatrix);const Ue=Array.from(xe.keys()).sort();for(const Pe of Ue){const{node:De,mvp:Ve}=xe.get(Pe);mne(h,0,De,Ve)}}pne(h,u,ae,ue,X),U()}else{for(const de of ue)Mk(de.mesh,de.nodeModelMatrix,h,u);for(const de of ae)Mk(de.mesh,de.nodeModelMatrix,h,u);U()}},prepare:function(h,o,u){const m=o.getSource();if(!m.loaded())return;if(m.type==="vector"||m.type==="geojson")return void(u.modelManager&&u.modelManager.upload(u,fne(u,h)));if(m.type==="batched-model"||m.type!=="model")return;const x=m.getModels();for(const b of x)b.upload(u.context)},shaders:yMe,programUniforms:vMe,ShadowRenderer:class{constructor(h){this.painter=h,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new SMe,this._depthMode=new tc(h.context.gl.LEQUAL,tc.ReadWrite,[0,1]),this._uniformValues={u_light_matrix_0:new Float32Array(16),u_light_matrix_1:new Float32Array(16),u_shadow_intensity:0,u_fade_range:[0,0],u_shadow_normal_offset:[1,1,1],u_shadow_texel_size:1,u_shadow_map_resolution:1,u_shadow_direction:[0,0,1],u_shadow_bias:[36e-5,.0012,.012],u_shadowmap_0:0,u_shadowmap_1:0},this._forceDisable=!1,this._devtoolsFolder=null,this.useNormalOffset=!1,this._shadowParameters={cascadeCount:2,normalOffset:3,shadowMapResolution:2048}}destroy(){for(const h of this._cascades)h.texture.destroy(),h.framebuffer.destroy();this._cascades=[]}_hasCasterGeometry(h,o){const u=this.painter.style.getLayerSourceCache(h);if(!u)return!1;const m=u.getSource();if(m.type==="model")return m.getModels().length>0;const x=o[u.id];if(!x)return!1;for(const b of x){const S=u.getTile(b);if(S&&S.getBucket(h))return!0}return!1}updateShadowParameters(h,o,u){const m=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!o||!o.properties)return;const x=o.properties.get("shadow-intensity"),b=o.properties.get("shadow-draw-before-layer");if(!o.shadowsEnabled()||x<=0)return;let S=-1,A=0;for(const ae of m.style.order){const ue=m.style._mergedLayers[ae];ue.hasShadowPass()&&!ue.isHidden(h.zoom)&&this._hasCasterGeometry(ue,u)&&(S=A),!b||b!==ae&&b!==ue.slot||(this._drawShadowAfterLayer=A>0?A-1:0),A+=1}if(this._enabled=S>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=S);const I=m.context,D=this._shadowParameters.shadowMapResolution,B=this._shadowParameters.shadowMapResolution;if(this._cascades.length===0||this._shadowParameters.shadowMapResolution!==this._cascades[0].texture.size[0]){this._cascades=[];for(let ae=0;aece.dem).forEach(ce=>{const de=ce.dem.tree;ue[0]=Math.min(ue[0],de.minimums[0]),ue[1]=Math.max(ue[1],de.maximums[0])}),ue[0]!==1e4&&(U=(ue[1]-ue[0])*ae.exaggeration())}const q=1.5*h.cameraToCenterDistance,K=3*q,X=new Float64Array(16);for(let ae=0;ae=0)return{};const x=function(A,I,D){const B=D/(1<0&&(vt(x[1],x[1],[m[0]*b,0,0]),vt(x[2],x[2],[m[0]*b,0,0])),m[1]<0?(vt(x[0],x[0],[0,m[1]*b,0]),vt(x[1],x[1],[0,m[1]*b,0])):m[1]>0&&(vt(x[2],x[2],[0,m[1]*b,0]),vt(x[3],x[3],[0,m[1]*b,0]));const S={};return S.vertices=x,S.planes=[FL(x[1],x[0],x[4]),FL(x[2],x[1],x[5]),FL(x[3],x[2],x[6]),FL(x[0],x[3],x[7])],S}addShadowReceiver(h,o,u){this._receivers.add(h,js.fromTileIdAndHeight(h,o,u))}getMaxCascadeForTile(h){const o=this._receivers.get(h);return o&&o.lastCascade?o.lastCascade:0}},drawGroundEffect:Bne,queryModelLayerRendered:function(h,o,u,m){const x=u.getSource();if(!x||x.type!=="model")return{};const b=x,S={};S[h.id]=[];const A=S[h.id];let I=0;for(const D of b.models){const B=u.getFeatureState(h.sourceLayer,D.id),U={type:"Unknown",id:D.id,properties:D.featureProperties},q=h.paint.get("model-rotation").evaluate(U,B),K=h.paint.get("model-scale").evaluate(U,B),X=h.paint.get("model-translation").evaluate(U,B),J=h.paint.get("model-elevation-reference");let se=[];fL(se,D,m,D.position,q,K,X,J==="ground",J==="ground",!1),m.projection.name==="globe"&&(se=hL(se,m));const ae=Q([],m.projMatrix,se),ue=f$(o.isPointQuery()?o.screenBounds:o.screenGeometry,m,ae,D.aabb);if(ue!=null){const ce=new Z0(void 0,0,0,0,D.id);ce.layer=h.layer,ce.properties=structuredClone(D.featureProperties),ce.properties.layer=h.id,ce.properties.uri=D.uri,ce.properties.orientation=D.orientation,ce.sourceLayer=h.sourceLayer,ce.geometry={type:"Point",coordinates:[D.position.lng,D.position.lat]},ce.state=B,ce.source=h.source,A.push({featureIndex:I,feature:ce,intersectionZ:ue})}++I}return S},queryModelLayerIntersectsFeature:function(h,o,u,m,x,b){if(!h.modelManager)return!1;const S=h.modelManager,A=o.tile.getBucket(h);if(!(A&&A instanceof M$))return!1;for(const I in A.instancesPerModel){const D=A.instancesPerModel[I],B=u.id!==void 0?u.id:u.properties&&Object.hasOwn(u.properties,"id")?u.properties.id:void 0;if(Object.hasOwn(D.idToFeaturesIndex,B)){const U=D.features[D.idToFeaturesIndex[B]],q=S.getModel(I,b||h.scope);if(!q)return!1;let K=[];const X=new pi(0,0),J=A.canonical;let se=Number.MAX_VALUE;for(let ae=0;aethis.map.style.clearSource(h))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(h){this._loaded=!1,this.fire(new nl("dataloading",{dataType:"source"}));const o=Array.isArray(this.map._language)?this.map._language.join():this.map._language,u=this.map.getWorldview();this._tileJSONRequest=qne(this._options,this.map._requestManager,o,u,(m,x)=>{this._tileJSONRequest=null,this._loaded=!0,m?(o&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${o}`),u&&u.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${u}`),this.fire(new Oa(m))):x&&(Object.assign(this,x),this.tileBounds=new Hne(x),Ll(x.tiles,this.map._requestManager._customAccessToken),this.fire(new nl("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new nl("data",{dataType:"source",sourceDataType:"content"}))),h&&h(m)})}hasTransition(){return!1}hasTile(h){return!this.tileBounds||this.tileBounds.contains(h.canonical)}loaded(){return this._loaded}async loadTile(h,o){const u=this.map._requestManager.normalizeTileURL(h.tileID.canonical.url(this.tiles,this.scheme)),m=!h.actor||h.state==="expired";if(m)h.actor=this.dispatcher.getActor();else{if(h.state==="loading")return void(h.reloadCallback=o);if(h.buckets){const A=Object.values(h.buckets);for(const I of A)I.dirty=!0;return void(h.state="loaded")}}const x=m?"loadTile":"reloadTile",b=new AbortController;h.request=b;const S=(A,I)=>(delete h.request,h.aborted?o(null):A&&!Rr(A)?o(A):(this.map._refreshExpiredTiles&&I&&h.setExpiryData(Gd(I.headers)),h.loadModelData(I,this.map.painter),h.state="loaded",o(null),void(h.reloadCallback&&(this.loadTile(h,h.reloadCallback),h.reloadCallback=null))));try{const A=await this.map._requestManager.transformRequest(u,er.Tile,b.signal);if(b.signal.aborted)return o(null);const I={request:A,data:void 0,uid:h.uid,tileID:h.tileID,tileZoom:h.tileZoom,zoom:h.tileID.overscaledZ,tileSize:this.tileSize*h.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:h.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:hu.devicePixelRatio,promoteId:this.promoteId};h.request=h.actor.sendCancelable(x,I,{},S)}catch(A){if(b.signal.aborted)return o(null);o(A)}}abortTile(h){h.request&&(h.request.abort(),delete h.request),h.actor&&h.actor.notify("abortTile",{uid:h.uid,type:this.type,source:this.id,scope:this.scope})}serialize(){return{...this._options}}},loadModel:async function(h,o,u){const m=await fte(h),x=new _te(o,u,void 0,void 0,_$(m));return x.computeBoundsAndApplyParent(),x}};class Wne{constructor(o,u){this.tileID=o,this.x=o.canonical.x,this.y=o.canonical.y,this.z=o.canonical.z,this.grid=new Dx(ar,ar,512),this.featureIndexArray=new kr,this.promoteId=u,this.is3DTile=!1,this.serializedLayersCache=new Map}insert(o,u,m,x,b,S=0,A=0){const I=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(m,x,b,S);const D=this.grid;for(let B=0;B=0&&q[3]>=0&&D.insert(I,q[0],q[1],q[2],q[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new hz(new GR(this.rawTileData)).layers,this.sourceLayerCoder=new Zre(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const o in this.vtLayers)this.vtFeatures[o]=[]}return this.vtLayers}query(o,u){const{tilespaceGeometry:m,transform:x,tileTransform:b,pixelPosMatrix:S,availableImages:A,worldview:I}=u;this.loadVTLayers(),this.serializedLayersCache.clear();const D=u.queryRadius?u.queryRadius:0,B=m.bufferedTilespaceBounds,U=this.grid.queryKeys(B.min.x,B.min.y,B.max.x,B.max.y,(J,se,ae,ue)=>xz(m.bufferedTilespaceGeometry,J-D,se-D,ae+D,ue+D));U.sort(TMe);let q=null;x.elevation&&U.length>0&&(q=Y1.create(x.elevation,this.tileID));const K={};let X;for(let J=0;J(ue||(ue=xd(ce,this.tileID.canonical,b)),de.queryIntersectsFeature(m,ce,xe,ue,this.z,x,S,q,ve,u.scope)))}return K}loadMatchingFeature(o,u,m,x,b,S){const{featureIndex:A,bucketIndex:I,sourceLayerIndex:D,layoutVertexArrayOffset:B}=u,U=this.bucketLayerIDs[I],q=m.layers,K=Object.keys(q);if(K.length&&!i0(K,U))return;const X=m.sourceCache,J=this.sourceLayerCoder.decode(D),se=this.vtLayers[J].feature(A),ae=this.getId(se,J);for(let ue=0;ue`${A.key}: ${A.message}`).join(", ");return void Xi(`Failed to create expression for promoteId: ${S}`)}this.promoteIdExpression=b.value}m=this.promoteIdExpression.evaluate({zoom:0},o)}else m=o.properties[x];typeof m=="boolean"&&(m=Number(m))}return m}}function Kne(h,o,u,m,x){return px(h,(b,S)=>{const A=o instanceof qg?o.get(S):null;return A&&A.evaluate?A.evaluate(u,m,void 0,x):A})}function TMe(h,o){return o-h}async function Yne(){return Promise.resolve()}vr(Wne,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const AMe={circle:class extends bc{constructor(h,o,u,m){super(h,{layout:Ute||(Ute=new Ws({"circle-sort-key":new sr(lt.layout_circle["circle-sort-key"]),"circle-elevation-reference":new Yt(lt.layout_circle["circle-elevation-reference"]),visibility:new Yt(lt.layout_circle.visibility)})),paint:Vte||(Vte=new Ws({"circle-radius":new sr(lt.paint_circle["circle-radius"]),"circle-color":new sr(lt.paint_circle["circle-color"]),"circle-blur":new sr(lt.paint_circle["circle-blur"]),"circle-opacity":new sr(lt.paint_circle["circle-opacity"]),"circle-translate":new Yt(lt.paint_circle["circle-translate"]),"circle-translate-anchor":new Yt(lt.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new Yt(lt.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new Yt(lt.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new sr(lt.paint_circle["circle-stroke-width"]),"circle-stroke-color":new sr(lt.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new sr(lt.paint_circle["circle-stroke-opacity"]),"circle-emissive-strength":new Yt(lt.paint_circle["circle-emissive-strength"]),"circle-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"circle-stroke-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},o,u,m)}createBucket(h){return new ER(h)}queryRadius(h){const o=h.programConfigurations.get(this.id);return sS("circle-radius",this,o)+sS("circle-stroke-width",this,o)+EL(this.paint.get("circle-translate"))}queryIntersectsFeature(h,o,u,m,x,b,S,A){const I=Kte(this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),b.angle,h.pixelToTileUnitsFactor),D=this.paint.get("circle-radius").evaluate(o,u)+this.paint.get("circle-stroke-width").evaluate(o,u);return Zte(h,m,b,S,A,this.paint.get("circle-pitch-alignment")==="map",this.paint.get("circle-pitch-scale")==="map",I,D)}getProgramIds(){return["circle"]}getDefaultProgramParams(h,o,u){const m=Yte(this);return{config:new ji(this,{zoom:o,lut:u}),defines:m,overrideFog:!1}}is3D(h){return!h&&!!this.layout&&this.layout.get("circle-elevation-reference")!=="none"}hasElevation(){return this.layout&&this.layout.get("circle-elevation-reference")!=="none"}mayUse(h){return h==="HD"&&zx(this,"circle-elevation-reference",o=>o==="hd-road-markup")}prepare(){return this.mayUse("HD")?SL():Promise.resolve()}},heatmap:class extends bc{createBucket(h){return new Qte(h)}constructor(h,o,u,m){super(h,{layout:Jte||(Jte=new Ws({visibility:new Yt(lt.layout_heatmap.visibility)})),paint:ere||(ere=new Ws({"heatmap-radius":new sr(lt.paint_heatmap["heatmap-radius"]),"heatmap-weight":new sr(lt.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Yt(lt.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Zd(lt.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Yt(lt.paint_heatmap["heatmap-opacity"]),"heatmap-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},o,u,m),this._updateColorRamp()}_handleSpecialPaintPropertyUpdate(h){h==="heatmap-color"&&this._updateColorRamp()}_updateColorRamp(){const h=this.getPaintPropertyValue("heatmap-color").expression;this.colorRamp=jk({expression:h,evaluationKey:"heatmapDensity",image:this.colorRamp}),this.colorRampTexture=null}resize(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null)}_clear(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null),this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}queryRadius(h){return sS("heatmap-radius",this,h.programConfigurations.get(this.id))}queryIntersectsFeature(h,o,u,m,x,b,S,A){const I=this.paint.get("heatmap-radius").evaluate(o,u);return Zte(h,m,b,S,A,!0,!0,new jt(0,0),I)}hasOffscreenPass(){return this.paint.get("heatmap-opacity")!==0&&this.visibility!=="none"}getProgramIds(){return["heatmap","heatmapTexture"]}getDefaultProgramParams(h,o,u){return h==="heatmap"?{config:new ji(this,{zoom:o,lut:u}),overrideFog:!1}:{}}},hillshade:class extends bc{constructor(h,o,u,m){super(h,{layout:tre||(tre=new Ws({visibility:new Yt(lt.layout_hillshade.visibility)})),paint:rre||(rre=new Ws({"hillshade-illumination-direction":new Yt(lt.paint_hillshade["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new Yt(lt.paint_hillshade["hillshade-illumination-anchor"]),"hillshade-exaggeration":new Yt(lt.paint_hillshade["hillshade-exaggeration"]),"hillshade-shadow-color":new Yt(lt.paint_hillshade["hillshade-shadow-color"]),"hillshade-highlight-color":new Yt(lt.paint_hillshade["hillshade-highlight-color"]),"hillshade-accent-color":new Yt(lt.paint_hillshade["hillshade-accent-color"]),"hillshade-emissive-strength":new Yt(lt.paint_hillshade["hillshade-emissive-strength"]),"hillshade-shadow-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"hillshade-highlight-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"hillshade-accent-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},o,u,m)}shouldRedrape(){return this.hasOffscreenPass()&&this.paint.get("hillshade-illumination-anchor")==="viewport"}hasOffscreenPass(){return this.paint.get("hillshade-exaggeration")!==0&&this.visibility!=="none"}getProgramIds(){return["hillshade","hillshadePrepare"]}getDefaultProgramParams(h,o,u){return{overrideFog:!1}}},fill:class extends bc{constructor(h,o,u,m){super(h,{layout:nre||(nre=new Ws({"fill-sort-key":new sr(lt.layout_fill["fill-sort-key"]),visibility:new Yt(lt.layout_fill.visibility),"fill-elevation-reference":new Yt(lt.layout_fill["fill-elevation-reference"]),"fill-construct-bridge-guard-rail":new sr(lt.layout_fill["fill-construct-bridge-guard-rail"])})),paint:ire||(ire=new Ws({"fill-antialias":new Yt(lt.paint_fill["fill-antialias"]),"fill-opacity":new sr(lt.paint_fill["fill-opacity"]),"fill-color":new sr(lt.paint_fill["fill-color"]),"fill-outline-color":new sr(lt.paint_fill["fill-outline-color"]),"fill-translate":new Yt(lt.paint_fill["fill-translate"]),"fill-translate-anchor":new Yt(lt.paint_fill["fill-translate-anchor"]),"fill-pattern":new sr(lt.paint_fill["fill-pattern"]),"fill-pattern-cross-fade":new Yt(lt.paint_fill["fill-pattern-cross-fade"]),"fill-emissive-strength":new Yt(lt.paint_fill["fill-emissive-strength"]),"fill-z-offset":new sr(lt.paint_fill["fill-z-offset"]),"fill-bridge-guard-rail-color":new sr(lt.paint_fill["fill-bridge-guard-rail-color"]),"fill-tunnel-structure-color":new sr(lt.paint_fill["fill-tunnel-structure-color"]),"fill-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"fill-outline-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"fill-bridge-guard-rail-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"fill-tunnel-structure-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},o,u,m)}getProgramIds(){const h=this.paint.get("fill-pattern"),o=h&&h.constantOr(1),u=[o?"fillPattern":"fill"];return this.paint.get("fill-antialias")&&u.push(o&&!this.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline"),u}getDefaultProgramParams(h,o,u){return{config:new ji(this,{zoom:o,lut:u}),overrideFog:!1}}_finalizeEvaluated(){const h=this.paint._values["fill-outline-color"];h.value.kind==="constant"&&h.value.value===void 0&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])}createBucket(h){return new Tp(h)}queryRadius(){return EL(this.paint.get("fill-translate"))}queryIntersectsFeature(h,o,u,m,x,b){return!h.queryGeometry.isAboveHorizon&&mz(Wte(h.tilespaceGeometry,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),b.angle,h.pixelToTileUnitsFactor),m)}isTileClipped(){return this.paint.get("fill-z-offset").constantOr(1)===0}is3D(h){if(this.paint.get("fill-z-offset").constantOr(1)!==0)return!0;const o=this.layout&&this.layout.get("fill-elevation-reference")!=="none";return h!=null?o&&!h:o}hasElevation(){return this.layout&&this.layout.get("fill-elevation-reference")!=="none"}mayUse(h){return h==="HD"&&zx(this,"fill-elevation-reference",o=>o!=="none")}prepare(){return this.mayUse("HD")?SL():Promise.resolve()}hasShadowPass(){return this.layout&&this.layout.get("fill-elevation-reference")!=="none"}},"fill-extrusion":class extends bc{constructor(h,o,u,m){super(h,{layout:ore||(ore=new Ws({visibility:new Yt(lt["layout_fill-extrusion"].visibility),"fill-extrusion-edge-radius":new Yt(lt["layout_fill-extrusion"]["fill-extrusion-edge-radius"]),"source-max-zoom":new Yt(lt["layout_fill-extrusion"]["source-max-zoom"])})),paint:lre||(lre=new Ws({"fill-extrusion-opacity":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new sr(lt["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new sr(lt["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-pattern-cross-fade":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-pattern-cross-fade"]),"fill-extrusion-height":new sr(lt["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new sr(lt["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-height-alignment":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-height-alignment"]),"fill-extrusion-base-alignment":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-base-alignment"]),"fill-extrusion-vertical-gradient":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"]),"fill-extrusion-ambient-occlusion-intensity":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-intensity"]),"fill-extrusion-ambient-occlusion-radius":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-radius"]),"fill-extrusion-ambient-occlusion-wall-radius":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-wall-radius"]),"fill-extrusion-ambient-occlusion-ground-radius":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-ground-radius"]),"fill-extrusion-ambient-occlusion-ground-attenuation":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-ground-attenuation"]),"fill-extrusion-flood-light-color":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-flood-light-color"]),"fill-extrusion-flood-light-intensity":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-flood-light-intensity"]),"fill-extrusion-flood-light-wall-radius":new sr(lt["paint_fill-extrusion"]["fill-extrusion-flood-light-wall-radius"]),"fill-extrusion-flood-light-ground-radius":new sr(lt["paint_fill-extrusion"]["fill-extrusion-flood-light-ground-radius"]),"fill-extrusion-flood-light-ground-attenuation":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-flood-light-ground-attenuation"]),"fill-extrusion-vertical-scale":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-vertical-scale"]),"fill-extrusion-rounded-roof":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-rounded-roof"]),"fill-extrusion-cutoff-fade-range":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-cutoff-fade-range"]),"fill-extrusion-front-cutoff":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-front-cutoff"]),"fill-extrusion-emissive-strength":new sr(lt["paint_fill-extrusion"]["fill-extrusion-emissive-strength"]),"fill-extrusion-line-width":new sr(lt["paint_fill-extrusion"]["fill-extrusion-line-width"]),"fill-extrusion-cast-shadows":new Yt(lt["paint_fill-extrusion"]["fill-extrusion-cast-shadows"]),"fill-extrusion-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"fill-extrusion-flood-light-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},o,u,m),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(h){return new bL(h)}queryRadius(){return EL(this.paint.get("fill-extrusion-translate"))}is3D(h){return!0}hasBlended3DDepthPrepass(){const h=this.paint.get("fill-extrusion-opacity");return!(h<=0||h>=1)&&this.paint.get("fill-extrusion-color").constantOr(Vn.white).a!==0}isPlacementAffectedByPaintChanges(h){const o=h;return this.paint.get("fill-extrusion-vertical-scale")!==o.get("fill-extrusion-vertical-scale")||this.paint.get("fill-extrusion-opacity")>0!=o.get("fill-extrusion-opacity")>0}hasShadowPass(){return this.paint.get("fill-extrusion-cast-shadows")}cutoffRange(){return this.paint.get("fill-extrusion-cutoff-fade-range")}canCastShadows(){return!0}getProgramIds(){return[this.paint.get("fill-extrusion-pattern").constantOr(1)?"fillExtrusionPattern":"fillExtrusion"]}queryIntersectsFeature(h,o,u,m,x,b,S,A,I){const D=Kte(this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),b.angle,h.pixelToTileUnitsFactor),B=this.paint.get("fill-extrusion-height").evaluate(o,u),U=this.paint.get("fill-extrusion-base").evaluate(o,u),q=[0,0],K=A&&b.elevation,X=b.elevation?b.elevation.exaggeration():1,J=h.tile.getBucket(this);if(J instanceof bL){const de=J.centroidData.find(xe=>I>=xe.vertexArrayOffset&&Ide.polygon).flat());const se=K?A:null,[ae,ue]=gre(b,m,U,B,D,S,se,q,X,b.center.lat,h.tileID.canonical),ce=h.queryGeometry;return pre(ae,ue,ce.isPointQuery()?ce.screenBounds:ce.screenGeometry)}},building:class extends bc{constructor(h,o,u,m){super(h,{layout:cre||(cre=new Ws({visibility:new Yt(lt.layout_building.visibility),"building-facade":new sr(lt.layout_building["building-facade"]),"building-facade-floors":new sr(lt.layout_building["building-facade-floors"]),"building-facade-unit-width":new sr(lt.layout_building["building-facade-unit-width"]),"building-facade-window":new sr(lt.layout_building["building-facade-window"]),"building-roof-shape":new sr(lt.layout_building["building-roof-shape"]),"building-height":new sr(lt.layout_building["building-height"]),"building-base":new sr(lt.layout_building["building-base"]),"building-flood-light-wall-radius":new sr(lt.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new sr(lt.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new sr(lt.layout_building["building-flip-roof-orientation"])})),paint:ure||(ure=new Ws({"building-opacity":new Yt(lt.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new Yt(lt.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new Yt(lt.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new Yt(lt.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new Yt(lt.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new Yt(lt.paint_building["building-vertical-scale"]),"building-cast-shadows":new Yt(lt.paint_building["building-cast-shadows"]),"building-color":new sr(lt.paint_building["building-color"]),"building-emissive-strength":new sr(lt.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new Yt(lt.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new Yt(lt.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new Yt(lt.paint_building["building-front-cutoff"]),"building-flood-light-color":new Yt(lt.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new Yt(lt.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new Yt(lt.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},o,u,m),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}mayUse(h){return h==="HD"}prepare(){return async function(){return function(){if(!fp(self)||Dh!=null||qte!=null)return null;if(iS!=null)return iS;const h=fetch(re());return iS=function(o){let u,m,x,b,S;function A(){u=new Uint8Array(S.buffer),m=new Int16Array(S.buffer),x=new Int32Array(S.buffer),b=new Float32Array(S.buffer)}function I(){throw new Error("Unexpected BuildingGen error.")}const D=()=>{},B={a:{a:I,f:function(U){const q=u.length,K=Math.max(U>>>0,Math.ceil(1.2*q)),X=Math.ceil((K-q)/65536);try{return S.grow(X),A(),!0}catch{return!1}},g:I,b:D,c:D,d:D,e:D}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(o,B):o.then(U=>U.arrayBuffer()).then(U=>WebAssembly.instantiate(U,B))).then(U=>{const q=U.instance.exports;return(0,q.g)(),S=q.f,A(),new CDe({setStyle:q.h,setAOOptions:q.i,setMetricOptions:q.j,setStructuralOptions:q.k,setFacadeOptions:q.l,setFauxFacadeOptions:q.m,setFacadeClassifierOptions:q.n,addFeature:q.o,addFacade:q.p,generateMesh:q.q,getLastError:q.r,getOuterRingLength:q.s,getMeshCount:q.t,getPositionsPtr:q.u,getPositionsLength:q.v,getNormalsPtr:q.w,getNormalsLength:q.x,getAOPtr:q.y,getAOLength:q.z,getUVPtr:q.A,getUVLength:q.B,getFauxFacadePtr:q.C,getFauxFacadeLength:q.D,getIndicesPtr:q.E,getIndicesLength:q.F,getBuildingPart:q.G,getRingCount:q.H,getRingPtr:q.I,getRingLength:q.J,malloc:q.K,free:q.L,heapU8:u,heap16:m,heap32:x,heapF32:b})})}(h).then(o=>{iS=null,Dh=o}).catch(o=>{Xi("Could not load building-gen"),iS=null,qte=o}),iS}()}()}createBucket(h){return new Gte(h)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}isPlacementAffectedByPaintChanges(h){const o=h;return this.paint.get("building-vertical-scale")!==o.get("building-vertical-scale")||this.paint.get("building-opacity")>0!=o.get("building-opacity")>0}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(h){return!0}hasBlended3DDepthPrepass(){const h=this.paint.get("building-opacity");return h>0&&h<1&&this.paint.get("building-vertical-scale")>0}queryRadius(h){return 0}queryIntersectsFeature(h,o,u,m,x,b,S,A,I,D){let B=this.layout.get("building-height").evaluate(o,u);const U=this.layout.get("building-base").evaluate(o,u),q=h.tile.getBucket(this).getFootprint(o);if(q){if(q.hiddenFlags!==0)return!1;B=q.height}const[K,X]=gre(b,m,U,B,new jt(0,0),S,null,[0,0],1,b.center.lat,h.tileID.canonical),J=h.queryGeometry;return pre(K,X,J.isPointQuery()?J.screenBounds:J.screenGeometry)}},line:class extends bc{constructor(h,o,u,m){const x=wre();super(h,x,o,u,m),x.layout&&(this.layout=new qg(x.layout)),this.gradientVersion=0,this.borderGradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1,this.lineBlendFbos=null,this.lineBlendDensityReadback=null}_handleSpecialPaintPropertyUpdate(h){if(h==="line-gradient"){const o=this.getPaintPropertyValue("line-gradient").expression;this.stepInterpolant=o._styleExpression&&o._styleExpression.expression instanceof Ax,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}else if(h==="line-gradient-use-theme")this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;else if(h==="line-border-gradient"){const o=this.getPaintPropertyValue("line-border-gradient").expression;this.borderStepInterpolant=o._styleExpression&&o._styleExpression.expression instanceof Ax,this.borderGradientVersion=(this.borderGradientVersion+1)%Number.MAX_SAFE_INTEGER}else h==="line-border-gradient-use-theme"&&(this.borderGradientVersion=(this.borderGradientVersion+1)%Number.MAX_SAFE_INTEGER)}_finalizeEvaluated(h){this.paint._values["line-floorwidth"]=(()=>{if(Nk)return Nk;const o=wre();return Nk=new $De(o.paint.properties["line-width"].specification),Nk.useIntegerZoom=!0,Nk})().possiblyEvaluate(this.getPaintPropertyValue("line-width"),h)}createBucket(h){return new wz(h)}getProgramIds(){const h=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&h.push("lineBlendComposite"),h}getDefaultProgramParams(h,o,u){if(h==="lineBlendComposite")return{};const m=vre(this);return{config:new ji(this,{zoom:o,lut:u}),defines:m,overrideFog:!1}}queryRadius(h){const o=h.uboBinders[this.id],u=Tre(sS("line-width",this,o),sS("line-gap-width",this,o)),m=sS("line-offset",this,o);return u/2+Math.abs(m)+EL(this.paint.get("line-translate"))}queryIntersectsFeature(h,o,u,m,x,b){if(h.queryGeometry.isAboveHorizon)return!1;const S=Wte(h.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),b.angle,h.pixelToTileUnitsFactor),A=h.pixelToTileUnitsFactor/2*Tre(this.paint.get("line-width").evaluate(o,u),this.paint.get("line-gap-width").evaluate(o,u)),I=this.paint.get("line-offset").evaluate(o,u);return I&&(m=function(D,B){const U=[],q=new jt(0,0);for(let K=0;K=3){for(let X=0;Xo==="hd-road-markup"):h==="Lite"&&function(o){var x,b;const u=(x=o.getLayoutPropertyValue("line-elevation-reference"))==null?void 0:x.value;if(u!==void 0&&(typeof u!="string"||u!=="none"))return!0;const m=(b=o.getLayoutPropertyValue("line-z-offset"))==null?void 0:b.value;return m!==void 0&&(typeof m!="number"||m!==0)}(this)}prepare(){return this.mayUse("HD")?SL():Promise.resolve()}hasOffscreenPass(){return this.paint.get("line-blend-mode")!=="default"&&this.paint.get("line-opacity").constantOr(1)!==0&&this.paint.get("line-width").constantOr(1)!==0&&this.visibility!=="none"}resize(){this._destroyLineBlendFbo()}onRemove(h){this._destroyLineBlendFbo(h.painter&&h.painter.context&&h.painter.context.gl||void 0)}_clear(){this._destroyLineBlendFbo()}_destroyLineBlendFbo(h){this.lineBlendFbos&&(this.lineBlendFbos.destroy(),this.lineBlendFbos=null),h&&this.lineBlendDensityReadback&&this.lineBlendDensityReadback.destroy(h),this.lineBlendDensityReadback=null}},symbol:TL,background:class extends bc{constructor(h,o,u,m){super(h,{layout:jre||(jre=new Ws({visibility:new Yt(lt.layout_background.visibility)})),paint:Cre||(Cre=new Ws({"background-pitch-alignment":new Yt(lt.paint_background["background-pitch-alignment"]),"background-color":new Yt(lt.paint_background["background-color"]),"background-pattern":new Yt(lt.paint_background["background-pattern"]),"background-opacity":new Yt(lt.paint_background["background-opacity"]),"background-emissive-strength":new Yt(lt.paint_background["background-emissive-strength"]),"background-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},o,u,m)}getProgramIds(){return[this.paint.get("background-pattern")?"backgroundPattern":"background"]}getDefaultProgramParams(h,o,u){return{overrideFog:!1}}is3D(h){return this.paint.get("background-pitch-alignment")==="viewport"}},raster:Rre,"raster-particle":Ure,sky:class extends bc{constructor(h,o,u,m){super(h,{layout:Mre||(Mre=new Ws({visibility:new Yt(lt.layout_sky.visibility)})),paint:Ore||(Ore=new Ws({"sky-type":new Yt(lt.paint_sky["sky-type"]),"sky-atmosphere-sun":new Yt(lt.paint_sky["sky-atmosphere-sun"]),"sky-atmosphere-sun-intensity":new Yt(lt.paint_sky["sky-atmosphere-sun-intensity"]),"sky-gradient-center":new Yt(lt.paint_sky["sky-gradient-center"]),"sky-gradient-radius":new Yt(lt.paint_sky["sky-gradient-radius"]),"sky-gradient":new Zd(lt.paint_sky["sky-gradient"]),"sky-atmosphere-halo-color":new Yt(lt.paint_sky["sky-atmosphere-halo-color"]),"sky-atmosphere-color":new Yt(lt.paint_sky["sky-atmosphere-color"]),"sky-opacity":new Yt(lt.paint_sky["sky-opacity"]),"sky-gradient-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-halo-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},o,u,m),this._updateColorRamp()}_clear(){this.skyboxFbo&&(this.skyboxFbo.destroy(),this.skyboxFbo=null),this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null),this._skyboxInvalidated=!0}_handleSpecialPaintPropertyUpdate(h){h==="sky-gradient"?this._updateColorRamp():h!=="sky-atmosphere-sun"&&h!=="sky-atmosphere-halo-color"&&h!=="sky-atmosphere-color"&&h!=="sky-atmosphere-sun-intensity"||(this._skyboxInvalidated=!0)}_updateColorRamp(){const h=this.getPaintPropertyValue("sky-gradient").expression;this.colorRamp=jk({expression:h,evaluationKey:"skyRadialProgress"}),this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}needsSkyboxCapture(h){if(this._skyboxInvalidated||!this.skyboxTexture||!this.skyboxGeometry)return!0;if(!this.paint.get("sky-atmosphere-sun")){const o=h.style.light.properties.get("position");return this._lightPosition.azimuthal!==o.azimuthal||this._lightPosition.polar!==o.polar}return!1}getCenter(h,o){if(this.paint.get("sky-type")==="atmosphere"){const m=this.paint.get("sky-atmosphere-sun"),x=!m,b=h.style.light,S=b.properties.get("position");return x&&b.properties.get("anchor")==="viewport"&&Xi("The sun direction is attached to a light with viewport anchor, lighting may behave unexpectedly."),x?D$(S.azimuthal,90-S.polar,o):D$(m[0],90-m[1],o)}const u=this.paint.get("sky-gradient-center");return D$(u[0],90-u[1],o)}isSky(){return!0}markSkyboxValid(h){this._skyboxInvalidated=!1,this._lightPosition=h.style.light.properties.get("position")}hasOffscreenPass(){return!0}getProgramIds(){const h=this.paint.get("sky-type");return h==="atmosphere"?["skyboxCapture","skybox"]:h==="gradient"?["skyboxGradient"]:null}},slot:class extends bc{constructor(h,o,u,m){super(h,{paint:Fre||(Fre=new Ws({}))},o,null)}},"placement-group":class extends bc{constructor(h,o,u,m){super(h,{paint:Bre||(Bre=new Ws({}))},o,u,m)}},model:class extends bc{constructor(h,o,u,m){super(h,{layout:zre||(zre=new Ws({visibility:new Yt(lt.layout_model.visibility),"model-id":new sr(lt.layout_model["model-id"]),"model-allow-density-reduction":new Yt(lt.layout_model["model-allow-density-reduction"])})),paint:$re||($re=new Ws({"model-opacity":new sr(lt.paint_model["model-opacity"]),"model-rotation":new sr(lt.paint_model["model-rotation"]),"model-scale":new sr(lt.paint_model["model-scale"]),"model-translation":new sr(lt.paint_model["model-translation"]),"model-color":new sr(lt.paint_model["model-color"]),"model-color-mix-intensity":new sr(lt.paint_model["model-color-mix-intensity"]),"model-type":new Yt(lt.paint_model["model-type"]),"model-cast-shadows":new Yt(lt.paint_model["model-cast-shadows"]),"model-receive-shadows":new Yt(lt.paint_model["model-receive-shadows"]),"model-ambient-occlusion-intensity":new Yt(lt.paint_model["model-ambient-occlusion-intensity"]),"model-emissive-strength":new sr(lt.paint_model["model-emissive-strength"]),"model-roughness":new sr(lt.paint_model["model-roughness"]),"model-height-based-emissive-strength-multiplier":new sr(lt.paint_model["model-height-based-emissive-strength-multiplier"]),"model-cutoff-fade-range":new Yt(lt.paint_model["model-cutoff-fade-range"]),"model-front-cutoff":new Yt(lt.paint_model["model-front-cutoff"]),"model-elevation-reference":new Yt(lt.paint_model["model-elevation-reference"]),"model-line-cutout-mode":new Yt(lt.paint_model["model-line-cutout-mode"]),"model-color-use-theme":new sr({type:"string",default:"default","property-type":"data-driven"})}))},o,u,m),this.layer=h,this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}mayUse(h){return h==="Standard"}prepare(){return Yne()}createBucket(h){return new M$(h)}getProgramIds(){return["model"]}is3D(h){return!0}hasShadowPass(){return this.paint.get("model-cast-shadows")}canCastShadows(){return!0}hasLightBeamPass(){return!0}cutoffRange(){return this.paint.get("model-cutoff-fade-range")}queryRadius(h){return h.isTiled3dModelBucket?8191:0}queryRenderedFeatures(h,o,u){return Q0.queryModelLayerRendered?Q0.queryModelLayerRendered(this,h,o,u):{}}queryIntersectsFeature(h,o,u,m,x,b,S,A,I,D){return!!Q0.queryModelLayerIntersectsFeature&&Q0.queryModelLayerIntersectsFeature(this,h,o,u,b,D)}_handleOverridablePaintPropertyUpdate(h,o,u){return!(!this.layout||o.isDataDriven()||u.isDataDriven()||h!=="model-color"&&h!=="model-color-mix-intensity"&&h!=="model-rotation"&&h!=="model-scale"&&h!=="model-translation"&&h!=="model-emissive-strength")}_isPropertyZoomDependent(h){const o=this.getPaintPropertyValue(h);return o!=null&&o.expression instanceof wp}isZoomDependent(){return this._isPropertyZoomDependent("model-scale")||this._isPropertyZoomDependent("model-rotation")||this._isPropertyZoomDependent("model-translation")}},clip:class extends bc{constructor(h,o,u,m){super(h,{layout:sre||(sre=new Ws({"clip-layer-types":new Yt(lt.layout_clip["clip-layer-types"]),"clip-layer-scope":new Yt(lt.layout_clip["clip-layer-scope"]),visibility:new Yt(lt.layout_clip.visibility)})),paint:are||(are=new Ws({}))},o,u,m)}createBucket(h){return new fre(h)}is3D(h){return!0}}};class t6{constructor(o){this.capacity=o,this.cache=new Map}get(o){if(!this.cache.has(o))return;const u=this.cache.get(o);return this.cache.delete(o),this.cache.set(o,u),u}put(o,u){this.cache.has(o)?this.cache.delete(o):this.cache.size===this.capacity&&this.cache.delete(this.cache.keys().next().value),this.cache.set(o,u)}delete(o){this.cache.delete(o)}}vr(t6,"LRUCache");class kMe{constructor(o){this._callback=o,this._triggered=!1,typeof MessageChannel<"u"&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._callback()})}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout(()=>{this._triggered=!1,this._callback()},0))}remove(){this._channel&&(this._channel.port1.close(),this._channel.port2.close()),this._callback=()=>{}}}const Zne={Other:0,Symbol:1,FillExtrusion:2,HdRoadCoverage:3};class IMe{constructor(){this.tasks=new Map,n0(["process"],this),this.invoker=new kMe(this.process),this.nextId=0}add(o,u){const m=this.nextId++,x=function({type:b,renderSourceType:S,zoom:A}){A=A||0;const I=S===Zne.Symbol;return b==="message"?0:b!=="maybePrepare"||I?b!=="parseTile"||I?b==="parseTile"&&I?300-A:b==="maybePrepare"&&I?400-A:500:200-A:100-A}(u);if(x===0){try{o()}finally{}return null}return this.tasks.set(m,{fn:o,metadata:u,priority:x,id:m}),this.invoker.trigger(),{cancel:()=>{this.tasks.delete(m)}}}process(){try{const o=this.pick();if(!o)return;this.tasks.delete(o.id),this.tasks.size>0&&this.invoker.trigger(),o.fn()}finally{}}pick(){let o=null,u=1/0;for(const m of this.tasks.values())m.priority=1;m--){const x=m===1?1:0,b=m===2?1:0;for(let S=0;S>>1^-(1&h[o]);return h}function OMe(h,o){switch(o){case"uint32":return h;case"uint16":for(let u=0;u>4|(61440&m)>>8|(240&x)<<4|61440&x,h[u+1]=15&m|(3840&m)>>4|(15&x)<<8|(3840&x)<<4}return h;case"uint8":for(let u=0;u>6|(192&x)>>4|(192&b)>>2|192&S,h[u+1]=(48&m)>>4|(48&x)>>2|48&b|(48&S)<<2,h[u+2]=(12&m)>>2|12&x|(12&b)<<2|(12&S)<<4,h[u+3]=3&m|(3&x)<<2|(3&b)<<4|(3&S)<<6}return h;default:throw new Error(`Invalid pixel format, "${o}"`)}}var Oh=Uint8Array,Ok=Uint16Array,FMe=Int32Array,Qne=new Oh([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,0,0,0]),Jne=new Oh([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,0,0]),BMe=new Oh([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),eie=function(h,o){for(var u=new Ok(31),m=0;m<31;++m)u[m]=o+=1<>1|(21845&jo)<<1;nie[jo]=((65280&(hS=(61680&(hS=(52428&hS)>>2|(13107&hS)<<2))>>4|(3855&hS)<<4))>>8|(255&hS)<<8)>>1}var Fk=function(h,o,u){for(var m=h.length,x=0,b=new Ok(o);x>I]=D;return S},Bk=new Oh(288);for(jo=0;jo<144;++jo)Bk[jo]=8;for(jo=144;jo<256;++jo)Bk[jo]=9;for(jo=256;jo<280;++jo)Bk[jo]=7;for(jo=280;jo<288;++jo)Bk[jo]=8;var iie=new Oh(32);for(jo=0;jo<32;++jo)iie[jo]=5;var UMe=Fk(Bk,9),VMe=Fk(iie,5),r6=function(h){for(var o=h[0],u=1;uo&&(o=h[u]);return o},ym=function(h,o,u){var m=o/8|0;return(h[m]|h[m+1]<<8)>>(7&o)&u},n6=function(h,o){var u=o/8|0;return(h[u]|h[u+1]<<8|h[u+2]<<16)>>(7&o)},qMe=function(h){return(h+7)/8|0},GMe=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],xm=function(h,o,u){var m=new Error(o||GMe[h]);if(m.code=h,Error.captureStackTrace&&Error.captureStackTrace(m,xm),!u)throw m;return m},HMe=new Oh(0),WMe=typeof TextDecoder<"u"&&new TextDecoder;try{WMe.decode(HMe,{stream:!0})}catch{}const KMe={gzip_data:"gzip"};class wf extends Error{constructor(o){super(o),this.name="MRTError"}}const YMe={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},sie={uint32:1,uint16:2,uint8:4},ZMe={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let i6;class BL{constructor(o=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=o}getLayer(o){const u=this.layers[o];if(!u)throw new wf(`Layer '${o}' not found`);return u}getHeaderLength(o){const u=new Uint8Array(o),m=new DataView(o);if(u[0]!==13)throw new wf("File is not a valid MRT.");return m.getUint32(1,!0)}parseHeader(o){const u=new Uint8Array(o),m=this.getHeaderLength(o);if(u.length= ${m} but got buffer of length ${u.length}`);const x=function(b){const S={headerLength:0,x:0,y:0,z:0,layers:[]};let A;for(;A=b.nextField(void 0);)A===1?S.headerLength=b.readFixed32():A===2?S.x=b.readVarint():A===3?S.y=b.readVarint():A===4?S.z=b.readVarint():A===5&&S.layers.push(RMe(b,b.readVarint()+b.pos));return S}(new i6(u.subarray(0,m)));if(!isNaN(this.x)&&(this.x!==x.x||this.y!==x.y||this.z!==x.z))throw new wf(`Invalid attempt to parse header ${x.z}/${x.x}/${x.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=x.x,this.y=x.y,this.z=x.z;for(const b of x.layers)this.layers[b.name]=new aie(b,{cacheSize:this._cacheSize});return this}createDecodingTask(o){const u=[],m=this.getLayer(o.layerName);for(let x of o.blockIndices){const b=m.dataIndex[x],S=b.firstByte-o.firstByte,A=b.lastByte-o.firstByte;if(m._blocksInProgress.has(x))continue;const I={layerName:m.name,firstByte:S,lastByte:A,pixelFormat:m.pixelFormat,blockIndex:x,blockShape:[b.bands.length].concat(m.bandShape),buffer:m.buffer,codec:b.codec.codec,filters:b.filters.map(D=>D.filter)};m._blocksInProgress.add(x),u.push(I)}return new oie(u,()=>{u.forEach(x=>m._blocksInProgress.delete(x.blockIndex))},(x,b)=>{if(u.forEach(S=>m._blocksInProgress.delete(S.blockIndex)),x)throw x;b.forEach(S=>{this.getLayer(S.layerName).processDecodedData(S)})})}}class aie{constructor({version:o,name:u,units:m,tileSize:x,pixelFormat:b,buffer:S,dataIndex:A},I){if(this.version=o,this.version!==1)throw new wf(`Cannot parse raster layer encoded with MRT version ${o}`);this.name=u,this.units=m,this.tileSize=x,this.buffer=S,this.pixelFormat=YMe[b],this.dataIndex=A,this.bandShape=[x+2*S,x+2*S,sie[this.pixelFormat]],this._decodedBlocks=new t6(I?I.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return sie[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:o})=>o).flat()}processDecodedData(o){const u=o.blockIndex.toString();this._decodedBlocks.get(u)||this._decodedBlocks.put(u,o.data)}getBlockForBand(o){let u=0;switch(typeof o){case"string":for(const[m,x]of this.dataIndex.entries()){for(const[b,S]of x.bands.entries())if(S===o)return{bandIndex:u+b,blockIndex:m,blockBandIndex:b};u+=x.bands.length}break;case"number":for(const[m,x]of this.dataIndex.entries()){if(o>=u&&othis.cacheSize)throw new wf(`Number of blocks to decode (${b.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:u,lastByte:m,blockIndices:x}}hasBand(o){const{blockIndex:u}=this.getBlockForBand(o);return u>=0}hasDataForBand(o){const{blockIndex:u}=this.getBlockForBand(o);return u>=0&&!!this._decodedBlocks.get(u.toString())}getBandView(o){const{blockIndex:u,blockBandIndex:m}=this.getBlockForBand(o);if(u<0)throw new wf(`Band not found: ${JSON.stringify(o)}`);const x=this._decodedBlocks.get(u.toString());if(!x)throw new wf(`Data for band ${JSON.stringify(o)} of layer "${this.name}" not decoded.`);const b=this.dataIndex[u],S=this.bandShape.reduce((D,B)=>D*B,1),A=m*S,I=x.subarray(A,A+S);return{data:I,bytes:new Uint8Array(I.buffer).subarray(I.byteOffset,I.byteOffset+I.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:b.offset,scale:b.scale}}}BL.setPbf=function(h){i6=h};class oie{constructor(o,u,m){this.tasks=o,this._onCancel=u,this._onComplete=m,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(o,u){this._finalized||(this._onComplete(o,u),this._finalized=!0)}}BL.performDecoding=function(h,o){const u=new Uint8Array(h);return Promise.all(o.tasks.map(m=>{const{layerName:x,firstByte:b,lastByte:S,pixelFormat:A,blockShape:I,blockIndex:D,filters:B,codec:U}=m,q=u.subarray(b,S+1),K=new Uint32Array(I[0]*I[1]*I[2]);let X;if(U!=="gzip_data")throw new wf(`Unhandled codec: ${U}`);return X=function(J,se){if(!globalThis.DecompressionStream&&se==="gzip_data")return Promise.resolve((ce=function(ve){ve[0]==31&&ve[1]==139&&ve[2]==8||xm(6,"invalid gzip data");var Ue=ve[3],Pe=10;4&Ue&&(Pe+=2+(ve[10]|ve[11]<<8));for(var De=(Ue>>3&1)+(Ue>>4&1);De>0;De-=!ve[Pe++]);return Pe+(2&Ue)}(ae=J),ce+8>ae.length&&xm(6,"invalid gzip data"),function(ve,Ue,Pe,De){var Ve=ve.length;if(!Ve||Ue.f&&!Ue.l)return Pe||new Oh(0);var Fe=!Pe,Ze=Fe||Ue.i!=2,st=Ue.i;Fe&&(Pe=new Oh(3*Ve));var ut=function(oo){var es=Pe.length;if(oo>es){var Ss=new Oh(Math.max(2*es,oo));Ss.set(Pe),Pe=Ss}},ht=Ue.f||0,_t=Ue.p||0,Et=Ue.b||0,Pt=Ue.l,Rt=Ue.d,Ye=Ue.m,At=Ue.n,Tt=8*Ve;do{if(!Pt){ht=ym(ve,_t,1);var $t=ym(ve,_t+1,3);if(_t+=3,!$t){var Gt=ve[(Fr=qMe(_t)+4)-4]|ve[Fr-3]<<8,kt=Fr+Gt;if(kt>Ve){st&&xm(0);break}Ze&&ut(Et+Gt),Pe.set(ve.subarray(Fr,kt),Et),Ue.b=Et+=Gt,Ue.p=_t=8*kt,Ue.f=ht;continue}if($t==1)Pt=UMe,Rt=VMe,Ye=9,At=5;else if($t==2){var Dt=ym(ve,_t,31)+257,dr=ym(ve,_t+10,15)+4,nr=Dt+ym(ve,_t+5,31)+1;_t+=14;for(var yr=new Oh(nr),Br=new Oh(19),br=0;br>4)<16)yr[br++]=Fr;else{var ii=0,Xn=0;for(Fr==16?(Xn=3+ym(ve,_t,3),_t+=2,ii=yr[br-1]):Fr==17?(Xn=3+ym(ve,_t,7),_t+=3):Fr==18&&(Xn=11+ym(ve,_t,127),_t+=7);Xn--;)yr[br++]=ii}}var bi=yr.subarray(0,Dt),mi=yr.subarray(Dt);Ye=r6(bi),At=r6(mi),Pt=Fk(bi,Ye),Rt=Fk(mi,At)}else xm(1);if(_t>Tt){st&&xm(0);break}}Ze&&ut(Et+131072);for(var ws=(1<>4;if((_t+=15&ii)>Tt){st&&xm(0);break}if(ii||xm(2),ns<256)Pe[Et++]=ns;else{if(ns==256){Xa=_t,Pt=null;break}var Gi=ns-254;ns>264&&(Gi=ym(ve,_t,(1<<(Sl=Qne[br=ns-257]))-1)+rie[br],_t+=Sl);var ka=Rt[n6(ve,_t)&Fs],Kc=ka>>4;if(ka||xm(3),_t+=15&ka,mi=$Me[Kc],Kc>3){var Sl=Jne[Kc];mi+=n6(ve,_t)&(1<Tt){st&&xm(0);break}Ze&&ut(Et+131072);var _n=Et+Gi;if(Etoo.length)&&(Ss=oo.length),new Oh(oo.subarray(0,Ss))}(Pe,0,Et):Pe.subarray(0,Et)}(ae.subarray(ce,-8),{i:2},new Oh(function(ve){var Ue=ve.length;return(ve[Ue-4]|ve[Ue-3]<<8|ve[Ue-2]<<16|ve[Ue-1]<<24)>>>0}(ae)),ue)));var ae,ue,ce;const de=KMe[se];if(!de)throw new Error(`Unhandled codec: ${se}`);const xe=new globalThis.DecompressionStream(de);return new Response(new Blob([J]).stream().pipeThrough(xe)).arrayBuffer().then(ve=>new Uint8Array(ve))}(q,U).then(J=>(function(se,ae){let ue;for(;ue=se.nextField();)if(ue===2)LMe(se,se.readVarint()+se.pos,ae);else if(ue===3)throw new Error("Not implemented")}(new i6(J),K),new ZMe[A](K.buffer))),X.then(J=>{for(let se=B.length-1;se>=0;se--)switch(B[se]){case"delta_filter":DMe(J,I);break;case"zigzag_filter":MMe(J);break;case"bitshuffle_filter":OMe(J,A);break;default:throw new wf(`Unhandled filter "${B[se]}"`)}return{layerName:x,blockIndex:D,data:J}}).catch(J=>{throw J})}))},vr(oie,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),vr(BL,"MapboxRasterTile"),vr(aie,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const s6=new Map,lie=new Map;class cie{constructor(o){this.size=o,this.minimums=[],this.maximums=[],this.leaves=[]}isLeaf(o,u){return this.leaves[this.toIdx(o,u)]}toIdx(o,u){return u*this.size+o}}function uie(h,o,u,m){let x=0,b=Number.MAX_VALUE;for(let S=0;S<3;S++)if(Math.abs(m[S])<1e-15){if(u[S]o[S])return null}else{const A=1/m[S];let I=(h[S]-u[S])*A,D=(o[S]-u[S])*A;if(I>D){const B=I;I=D,D=B}if(I>x&&(x=I),Db)return null}return x}function die(h,o,u,m,x,b,S,A,I,D,B){const U=m-h,q=x-o,K=b-u,X=S-h,J=A-o,se=I-u,ae=B[1]*se-B[2]*J,ue=B[2]*X-B[0]*se,ce=B[0]*J-B[1]*X,de=U*ae+q*ue+K*ce;if(Math.abs(de)<1e-15)return null;const xe=1/de,ve=D[0]-h,Ue=D[1]-o,Pe=D[2]-u,De=(ve*ae+Ue*ue+Pe*ce)*xe;if(De<0||De>1)return null;const Ve=Ue*K-Pe*q,Fe=Pe*U-ve*K,Ze=ve*q-Ue*U,st=(B[0]*Ve+B[1]*Fe+B[2]*Ze)*xe;return st<0||De+st>1?null:(X*Ve+J*Fe+se*Ze)*xe}function hie(h,o,u,m,x,b,S,A,I){const D=1<{const ve=de?1:0,Ue=(ae+1)*ce-ve,Pe=ue*ce,De=(ue+1)*ce-ve;xe[0]=ae*ce,xe[1]=Pe,xe[2]=Ue,xe[3]=De};let q=new cie(B);const K=1/B,{floatView:X,stride:J}=S,se=[];for(let ae=0;aest&&(st=Et)}}q.minimums.push(Pe),q.maximums.push(st),q.leaves.push(1)}for(D.push(q),B/=2;B>=1;B/=2){const ae=D.at(-1);q=new cie(B);for(let ue=0;ueS+A.size*A.size,0);if(this.maximums=new Float32Array(m),this.minimums=new Float32Array(m),this.leaves=new Uint8Array(m),this.childOffsets=new Uint32Array(m),!this.dem)return;const x=u.length-1,b=u[x];this._addNode(b.minimums[0],b.maximums[0],b.leaves[0]),this._construct(u,0,0,x,0),this.maximums=this.maximums.subarray(0,this.nodeCount),this.minimums=this.minimums.subarray(0,this.nodeCount),this.leaves=this.leaves.subarray(0,this.nodeCount),this.childOffsets=this.childOffsets.subarray(0,this.nodeCount)}raycastRoot(o,u,m,x,b,S,A=1){return uie([o,u,-100],[m,x,this.maximums[0]*A],b,S)}raycast(o,u,m,x,b,S,A=1){if(!this.nodeCount)return null;const I=this.raycastRoot(o,u,m,x,b,S,A);if(I==null)return null;const D=[],B=[],U=[],q=[],K=[{idx:0,t:I,nodex:0,nodey:0,depth:0}];for(;K.length>0;){const{idx:X,t:J,nodex:se,nodey:ae,depth:ue}=K.pop();if(this.leaves[X]){hie(se,ae,ue,o,u,m,x,U,q);const de=1<1e-10,kt=Math.abs(S[1])>1e-10,Dt=S[0]>=0?1:-1,dr=S[1]>=0?1:-1;let nr=Math.max(0,Math.min(ht-1,Math.floor((Tt-Et)/Rt))),yr=Math.max(0,Math.min(_t-1,Math.floor(($t-Pt)/Ye)));const Br=Gt?Math.abs(Rt/S[0]):Number.MAX_VALUE,br=kt?Math.abs(Ye/S[1]):Number.MAX_VALUE;let dn=Gt?At+(Et+(S[0]>=0?nr+1:nr)*Rt-Tt)/S[0]:Number.MAX_VALUE,rn=kt?At+(Pt+(S[1]>=0?yr+1:yr)*Ye-$t)/S[1]:Number.MAX_VALUE;const wr=(ka,Kc)=>Ve[(Kc+1)*Fe+ka+1]*A;let Fr=wr(Ze+nr,ut+yr),ni=wr(Ze+nr+1,ut+yr),ii=wr(Ze+nr,ut+yr+1),Xn=wr(Ze+nr+1,ut+yr+1),bi=null;for(let ka=0;ka=0||b[2]+S[2]*Kc<=Math.max(Fr,ni,ii,Xn)){const _n=Et+nr*Rt,Bs=_n+Rt,Ia=Pt+yr*Ye,oo=Ia+Ye,es=die(Bs,Ia,ni,_n,Ia,Fr,_n,oo,ii,b,S),Ss=die(_n,oo,ii,Bs,oo,Xn,Bs,Ia,ni,b,S);es!=null&&es>=0&&(bi===null||es=0&&(bi===null||Ss=ht||yr<0||yr>=_t||bi!==null&&Kc>bi)break;Sl?Dt>0?(Fr=ni,ii=Xn,ni=wr(Ze+nr+1,ut+yr),Xn=wr(Ze+nr+1,ut+yr+1)):(ni=Fr,Xn=ii,Fr=wr(Ze+nr,ut+yr),ii=wr(Ze+nr,ut+yr+1)):dr>0?(Fr=ii,ni=Xn,ii=wr(Ze+nr,ut+yr+1),Xn=wr(Ze+nr+1,ut+yr+1)):(ii=Fr,Xn=ni,Fr=wr(Ze+nr,ut+yr),ni=wr(Ze+nr+1,ut+yr))}if(bi!==null)return bi||0;const mi=Kt([],b,S,J),ws=(mi[0]-U[0])/(q[0]-U[0]),Fs=(mi[1]-U[1])/(q[1]-U[1]),Xa=a_(xe,Ue,this.dem)*A,ns=a_(ve,Ue,this.dem)*A,Gi=a_(ve,Pe,this.dem)*A;if(mie(Xa,ns,a_(xe,Pe,this.dem)*A,Gi,ws,Fs)>=mi[2])return J;continue}let ce=0;for(let de=0;de<4;de++){hie((se<<1)+(1&de),(ae<<1)+(de>>1),ue+1,o,u,m,x,U,q),U[2]=-100,q[2]=this.maximums[this.childOffsets[X]+de]*A;const xe=uie(U,q,b,S);if(xe!=null){const ve=xe;D[de]=ve;let Ue=!1;for(let Pe=0;Pe=D[B[Pe]]&&(B.splice(Pe,0,de),Ue=!0);Ue||(B[ce]=de),ce++}}for(let de=0;de>1),depth:ue+1})}}return null}_addNode(o,u,m){const x=this.nodeCount++;return this.minimums[x]=o,this.maximums[x]=u,this.leaves[x]=m,x}_construct(o,u,m,x,b){if(o[x].isLeaf(u,m)===1)return;this.childOffsets[b]||(this.childOffsets[b]=this.nodeCount);const S=x-1,A=o[S];let I=0,D=0;for(let B=0;B<4;B++){const U=A.toIdx(2*u+(1&B),2*m+(B>>1)),q=A.leaves[U],K=this._addNode(A.minimums[U],A.maximums[U],q);q&&(I|=1<>1),S,D+B)}}function mie(h,o,u,m,x,b){return Kr(Kr(h,u,b),Kr(o,m,b),x)}function a_(h,o,u){const m=u.dim,x=cn(h*m-.5,0,m-1),b=cn(o*m-.5,0,m-1),S=Math.floor(x),A=Math.floor(b),I=Math.min(S+1,m-1),D=Math.min(A+1,m-1);return mie(u.get(S,A),u.get(I,A),u.get(S,D),u.get(I,D),x-S,b-A)}const XMe={mapbox:[6553.6,25.6,.1,1e4],terrarium:[256,1,1/256,32768]};function QMe(h,o,u){return(256*h*256+256*o+u)/10-1e4}function JMe(h,o,u){return 256*h+o+u/256-32768}class zL{get tree(){return this._tree||this._buildQuadTree(),this._tree}constructor(o,u,m,x=!1){if(this.uid=o,u.height!==u.width)throw new RangeError("DEM tiles must be square");if(m&&m!=="mapbox"&&m!=="terrarium")return void Xi(`"${m}" is not a valid encoding type. Valid types include "mapbox" and "terrarium".`);this.stride=u.height;const b=this.dim=u.height-2,S=new Uint32Array(u.data.buffer);if(this.pixels=new Uint8Array(u.data.buffer),this.floatView=new Float32Array(u.data.buffer),this.borderReady=x,this._modifiedForSources={},!x){for(let I=0;I=this.dim+1||u<-1||u>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(u+1)*this.stride+(o+1)}static pack(o,u){const m=[0,0,0,0],x=zL.getUnpackVector(u);let b=Math.floor((o+x[3])/x[2]);return m[2]=b%256,b=Math.floor(b/256),m[1]=b%256,b=Math.floor(b/256),m[0]=b,m}getPixels(){return new bJ({width:this.stride,height:this.stride},this.pixels)}backfillBorder(o,u,m){if(this.dim!==o.dim)throw new Error("dem dimension mismatch");let x=u*this.dim,b=u*this.dim+this.dim,S=m*this.dim,A=m*this.dim+this.dim;switch(u){case-1:x=b-1;break;case 1:b=x+1}switch(m){case-1:S=A-1;break;case 1:A=S+1}const I=-u*this.dim,D=-m*this.dim;for(let B=S;B>4;if(x!==1)throw new Error(`Got v${x} data when expected v1.`);const b=pie[15&m];if(!b)throw new Error("Unrecognized array type.");const[S]=new Uint16Array(o,2,1),[A]=new Uint32Array(o,4,1);return new a6(A,S,b,void 0,o)}constructor(o,u=64,m=Float64Array,x=ArrayBuffer,b){if(isNaN(o)||o<0)throw new Error(`Unexpected numItems value: ${o}.`);this.numItems=+o,this.nodeSize=Math.min(Math.max(+u,2),65535),this.ArrayType=m,this.IndexArrayType=o<65536?Uint16Array:Uint32Array;const S=pie.indexOf(this.ArrayType),A=2*o*this.ArrayType.BYTES_PER_ELEMENT,I=o*this.IndexArrayType.BYTES_PER_ELEMENT,D=(8-I%8)%8;if(S<0)throw new Error(`Unexpected typed array class: ${m}.`);if(b)this.data=b,this.ids=new this.IndexArrayType(b,8,o),this.coords=new m(b,8+I+D,2*o),this._pos=2*o,this._finished=!0;else{const B=this.data=new x(8+A+I+D);this.ids=new this.IndexArrayType(B,8,o),this.coords=new m(B,8+I+D,2*o),this._pos=0,this._finished=!1,new Uint8Array(B,0,2).set([219,16+S]),new Uint16Array(B,2,1)[0]=u,new Uint32Array(B,4,1)[0]=o}}add(o,u){const m=this._pos>>1;return this.ids[m]=m,this.coords[this._pos++]=o,this.coords[this._pos++]=u,m}finish(){const o=this._pos>>1;if(o!==this.numItems)throw new Error(`Added ${o} items when expected ${this.numItems}.`);return o6(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(o,u,m,x){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:b,coords:S,nodeSize:A}=this;$o[0]=0,$o[1]=b.length-1,$o[2]=0;let I=3;const D=[];for(;I>0;){const B=$o[--I],U=$o[--I],q=$o[--I];if(U-q<=A){for(let se=q;se<=U;se++){const ae=S[2*se],ue=S[2*se+1];ae>=o&&ae<=m&&ue>=u&&ue<=x&&D.push(b[se])}continue}const K=q+U>>1,X=S[2*K],J=S[2*K+1];X>=o&&X<=m&&J>=u&&J<=x&&D.push(b[K]),(B===0?o<=X:u<=J)&&($o[I++]=q,$o[I++]=K-1,$o[I++]=1-B),(B===0?m>=X:x>=J)&&($o[I++]=K+1,$o[I++]=U,$o[I++]=1-B)}return D}within(o,u,m){const x=[];return this.withinInto(o,u,m,x),x}withinInto(o,u,m,x){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:b,coords:S,nodeSize:A}=this;$o[0]=0,$o[1]=b.length-1,$o[2]=0;let I=3,D=0;const B=m*m;for(;I>0;){const U=$o[--I],q=$o[--I],K=$o[--I];if(q-K<=A){for(let ae=K;ae<=q;ae++)yie(S[2*ae],S[2*ae+1],o,u)<=B&&(x[D++]=b[ae]);continue}const X=K+q>>1,J=S[2*X],se=S[2*X+1];yie(J,se,o,u)<=B&&(x[D++]=b[X]),(U===0?o-m<=J:u-m<=se)&&($o[I++]=K,$o[I++]=X-1,$o[I++]=1-U),(U===0?o+m>=J:u+m>=se)&&($o[I++]=X+1,$o[I++]=q,$o[I++]=1-U)}return D}}function o6(h,o,u,m,x,b){if(x-m<=u)return;const S=m+x>>1;gie(h,o,S,m,x,b),o6(h,o,u,m,S-1,1-b),o6(h,o,u,S+1,x,1-b)}function gie(h,o,u,m,x,b){for(;x>m;){if(x-m>600){const D=x-m+1,B=u-m+1,U=Math.log(D),q=.5*Math.exp(2*U/3),K=.5*Math.sqrt(U*q*(D-q)/D)*(B-D/2<0?-1:1);gie(h,o,u,Math.max(m,Math.floor(u-B*q/D+K)),Math.min(x,Math.floor(u+(D-B)*q/D+K)),b)}const S=o[2*u+b];let A=m,I=x;for(zk(h,o,m,u),o[2*x+b]>S&&zk(h,o,m,x);AS;)I--}o[2*m+b]===S?zk(h,o,m,I):(I++,zk(h,o,I,x)),I<=u&&(m=I+1),u<=I&&(x=I-1)}}function zk(h,o,u,m){l6(h,u,m),l6(o,2*u,2*m),l6(o,2*u+1,2*m+1)}function l6(h,o,u){const m=h[o];h[o]=h[u],h[u]=m}function yie(h,o,u,m){const x=h-u,b=o-m;return x*x+b*b}g.$=function(h,o){const u=Ip(o.zoom);if(u===0)return kp(h);const m=jR(h),x=Rz(m),b=mu(m.getWest())*o.worldSize,S=mu(m.getEast())*o.worldSize,A=vc(m.getNorth())*o.worldSize,I=vc(m.getSouth())*o.worldSize,D=[b,A,0],B=[S,A,0],U=[b,I,0],q=[S,I,0],K=Z([],o.globeMatrix);return Ar(D,D,K),Ar(B,B,K),Ar(U,U,K),Ar(q,q,K),x[0]=Qg(x[0],U,u),x[1]=Qg(x[1],q,u),x[2]=Qg(x[2],B,u),x[3]=Qg(x[3],D,u),js.fromPoints(x)},g.A=g2,g.B=Lx,g.C=Vn,g.D=GN,g.E=ca,g.F=m1,g.G=k1,g.H=KN,g.I=ga,g.J=Fg,g.K=am,g.L=t6,g.M=Og,g.N=Ql,g.O=As,g.P=jt,g.Q=c0,g.R=er,g.S=R2,g.T=KR,g.U=/^(.*)-use-theme$/,g.V=/^(.*)-transition$/,g.W=y2,g.X=qN,g.Y=Ha,g.Z=F,g._=Ip,g.a=async function(h,o){h.headers||(h.headers={}),h.headers.accept="image/webp,*/*";const u=await function(m){return new Promise((x,b)=>{if(m&&m.aborted)return void b(m.reason);const S=()=>{const D=wn.shift();D?D():ri--};if(ri{m&&m.removeEventListener("abort",I),x(S)},I=()=>{const D=wn.indexOf(A);D!==-1&&wn.splice(D,1),b(m.reason)};m&&m.addEventListener("abort",I),wn.push(A)})}(o);try{const{data:m,headers:x}=await di(h,o);let b;try{b=await createImageBitmap(new Blob([new Uint8Array(m)],{type:"image/png"}))}catch(S){throw new Error(`Could not load image because of ${S.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`,{cause:S})}return o&&o.throwIfAborted(),{data:b,headers:x}}finally{u()}},g.a$=Bne,g.a0=Lz,g.a1=Q,g.a2=O,g.a3=tc,g.a4=Mh,g.a5=rc,g.a6=lne,g.a7=ia,g.a8=Pn,g.a9=Dr,g.aA=function(h,o,u){const m=os.fromLngLat(o),x=u.elevation?u.elevation.getAtPointOrZero(m):0;return ree(h,m.x,m.y,x,u)},g.aB=function(h,o,u,m,x,b,S){const A=[[u,m,0],[x,m,0],[x,b,0],[u,b,0]];let I=Number.MAX_VALUE,D=-Number.MAX_VALUE;for(const B of A){const U=ot(Ar([],B,o));I=Math.min(I,U),D=Math.max(D,U)}return[qR(h,I,S.pitch),qR(h,D,S.pitch)]},g.aC=yf,g.aD=ree,g.aE=fk,g.aF=Bn,g.aG=function(){return Cg++},g.aH=class{constructor(h,o,u){this.target=h,this.parent=o,this.mapId=u,this.pendingResponses=new Map,n0(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new IMe}send(h,o,u){const{signal:m,targetMapId:x,metadata:b}=u||{},S=Math.round(1e18*Math.random()).toString(36).substring(0,10),A=new Set;return m&&m.aborted?Promise.reject(m.reason):(this.target.postMessage({id:S,type:h,targetMapId:x,sourceMapId:this.mapId,data:gd(o,A)},[...A]),new Promise((I,D)=>{const B={resolve:I,reject:D,metadata:b||Xne};if(m){const U=()=>{this.pendingResponses.delete(S),D(m.reason)};m.addEventListener("abort",U,{once:!0}),B.detach=()=>m.removeEventListener("abort",U)}this.pendingResponses.set(S,B)}))}notify(h,o,u){const{targetMapId:m}=u||{},x=new Set;this.target.postMessage({type:h,targetMapId:m,sourceMapId:this.mapId,data:gd(o,x)},[...x])}sendCancelable(h,o,u,m){const x=new AbortController;return this.send(h,o,{...u,signal:x.signal}).then(b=>m(null,b)).catch(b=>{b.name!=="AbortError"&&m(b)}),x}getWorkerSourceActor(h){return{scheduler:this.scheduler,send:(o,u,m)=>this.send(o,u,{...m,targetMapId:h}),notify:(o,u)=>{this.notify(o,u,{targetMapId:h})},sendCancelable:(o,u,m,x)=>this.sendCancelable(o,u,{...m,targetMapId:h},x)}}receive(h){const o=h.data;if(!o)return;const u=o.id;if(!o.targetMapId||this.mapId===o.targetMapId)if(fp(self)){const m=this.pendingResponses.get(u);this.scheduler.add(()=>{this.processTask(u,o)},m&&m.metadata||Xne)}else this.processTask(u,o)}async processTask(h,o){if(o.type===""){const x=this.pendingResponses.get(h);if(this.pendingResponses.delete(h),x){x.detach&&x.detach();try{o.error?x.reject(yd(o.error)):x.resolve(yd(o.data))}catch(b){x.reject(b)}}return}const u=new Set,m=yd(o.data);try{let x;if(this.parent[o.type])x=await this.parent[o.type](o.sourceMapId,m);else{if(!this.parent.getWorkerSource)throw new Error(`Could not find function ${o.type}`);{const b=o.type.split("."),{source:S,scope:A}=m;x=await this.parent.getWorkerSource(o.sourceMapId,{type:b[0],source:S,scope:A})[b[1]](m)}}if(!h)return;this.target.postMessage({id:h,type:"",sourceMapId:this.mapId,error:null,data:gd(x,u)},[...u])}catch(x){this.target.postMessage({id:h,type:"",sourceMapId:this.mapId,error:gd(x),data:null},[])}}remove(){for(const h of this.pendingResponses.values())h.detach&&h.detach(),h.reject(new DOMException("Actor removed","AbortError"));this.pendingResponses.clear(),this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},g.aI=class{constructor(h){this.specification=h}possiblyEvaluate(h,o){return function([u,m]){const x=gx([1,u,m]);return{x:x.x,y:x.y,z:x.z}}(h.expression.evaluate(o))}interpolate(h,o,u){return{x:Kr(h.x,o.x,u),y:Kr(h.y,o.y,u),z:Kr(h.z,o.z,u)}}},g.aJ=Q0,g.aK=q0,g.aL=bf,g.aM=qJ,g.aN=bL,g.aO=Ote,g.aP=cS,g.aQ=$ne,g.aR=Ol,g.aS=(h,o,u,m,x,b,S,A,I,D,B,U,q,K,X,J,se,ae,ue=!1)=>{const ce=One(h,o,u,m,x,b,S,A,D,B,U,q,K,X,J,se,1,[0,0,0],[0,0,1],ue),de={u_height_factor:-Math.pow(2,A.overscaledZ)/I.tileSize/8};return Object.assign(ce,Dne(o,I,ae),de)},g.aT=One,g.aU=ry,g.aV=450,g.aW=7,g.aX=(h,o,u,m,x,b)=>({u_matrix:h,u_edge_radius:o,u_width_scale:u,u_vertical_scale:m,u_height_type:DL[x],u_base_type:DL[b]}),g.aY=ie,g.aZ=Z,g.a_=W,g.aa=ua,g.ab=ti,g.ac=ar,g.ad=mu,g.ae=vc,g.af=function(h,o,u){if(o.projection.name===u.projection.name)return h.projMatrix;const m=u.clone();return m.setProjection(o.projection),qz(m,o.getProjection(),h)},g.ag=Ae,g.ah=Se,g.ai=fRe,g.aj=xn,g.ak=Ne,g.al=yu,g.am=Me,g.an=mRe,g.ao=C0,g.ap=qg,g.aq=Ws,g.ar=Yt,g.as=class{constructor(h){this.specification=h}possiblyEvaluate(h,o){return gx(h.expression.evaluate(o))}interpolate(h,o,u){return{x:Kr(h.x,o.x,u),y:Kr(h.y,o.y,u),z:Kr(h.z,o.z,u),azimuthal:Kr(h.azimuthal,o.azimuthal,u),polar:Kr(h.polar,o.polar,u)}}},g.at=A1,g.au=Hs,g.av=wp,g.aw=Kr,g.ax=rm,g.ay=65,g.az=45,g.b=Ec,g.b$=os,g.b0=4,g.b1=2,g.b2=fz,g.b3=mz,g.b4=n0,g.b5=class{static calculate(h,o,u){const m=new Set,x=new Map,b=new Set,S=new Set;for(const I of Object.values(h))for(const[D,B]of Object.entries(I.floors)){b.add(D),B.isDefault&&S.add(D),B.conflicts&&x.set(D,B.conflicts);const U=D===o,q=B.connections&&o&&B.connections.has(o);(U||q)&&m.add(D)}const A=I=>{const D=x.get(I)||new Set;for(const B of m)if((x.get(B)||new Set).has(I)||D.has(B))return!0;return!1};if(u)for(const I of u)b.has(I)&&(A(I)||m.add(I));for(const I of S)m.has(I)||A(I)||m.add(I);return m}},g.b6=yi,g.b7=ao,g.b8=class extends gi{constructor(h){super(h),this.current=new Float32Array(9)}set(h,o,u){if(!this.fetchUniformLocation(h,o))return;const m=this.current;for(let x=0;x<9;x++)if(u[x]!==m[x]){m.set(u),this.gl.uniformMatrix3fv(this.location,!1,m);break}}},g.b9=Gn,g.bA=LR,g.bB=Jl,g.bC=Fa,g.bD=z1,g.bE=qt,g.bF=_k,g.bG=wz,g.bH=L2,g.bI=Ph,g.bJ=Z0,g.bK=nm,g.bL=Tp,g.bM=xd,g.bN=mm,g.bO=Lt,g.bP=Cz,g.bQ=$x,g.bR=ak,g.bS=Ar,g.bT=Qg,g.bU=z0,g.bV=ERe,g.bW=Re,g.bX=ee,g.bY=Rr,g.bZ=ll,g.b_=Zne,g.ba=fr,g.bb=cn,g.bc=6,g.bd=jR,g.be=function(h){const o=80.051129;h=cn(h,-80.051129,o)/o*90;const u=Math.pow(Math.abs(Math.sin(Bn(h))),3);return Math.round(u*(G2.length-1))},g.bf=NR,g.bg=kp,g.bh=function(h){const o=h.pixelsPerMeter,u=o/ks(1,h.center.lat),m=G(new Float64Array(16));return ee(m,m,[h.point.x,h.point.y,0]),ie(m,m,[u,u,o]),Float32Array.from(m)},g.bi=function(h,o,u,m){const x=o.getNorth(),b=o.getSouth(),S=o.getWest(),A=o.getEast(),I=1<0){const X=180/m;C(K,K,[X/D+1,0,0,0,X/B+1,0,-.5*X/U,.5*X/q,1])}return K[2]=I,K[5]=h.x,K[8]=h.y,K},g.bj=Th,g.bk=256,g.bl=jne,g.bm=Zi,g.bn=bt,g.bo=ci,g.bp=_r,g.bq=pn,g.br=$e,g.bs=nt,g.bt=Nx,g.bu=fm,g.bv=xt,g.bw=mt,g.bx=M1,g.by=lS,g.bz=o0,g.c=Vg,g.c$=function(h,o,u,m){for(;o>1;h[x]<=m?o=x+1:u=x}return o},g.c0="hd_road_coverage",g.c1=Xx,g.c2=RR,g.c3=ke,g.c4=pf,g.c5=fx,g.c6=function(h,o,u){const m=Ip(u.zoom),x=h.style.map._antialias,b=h.terrain&&h.terrain.exaggeration()>0;return m===0&&!x&&!b},g.c7=function(h,o,u){const m=G(new Float64Array(16)),x=(o/(1<ze&&(h.getActor().notify("enforceCacheSizeLimit",Oe),It=0)},g.cC=Hne,g.cD=Ll,g.cE=async function(h,o,u){const m=h.url&&!h.tiles?await o.transformRequest(h.url,er.Source,u):void 0;return{request:m,options:m?{...h,url:m.url}:h}},g.cF=async function(h,o){const u=lie.get(h);if(u)return u;const m=s6.get(h);if(m!==void 0)return m;const x=self.__mapboxImport(o).catch(b=>{throw new Error(`TileProvider "${h}" failed to load: ${b instanceof Error?b.message:String(b)}`)}).then(b=>{const S=b.default;if(typeof S!="function")throw new Error(`TileProvider "${h}" module must default-export a class`);if(typeof S.prototype.loadTile!="function")throw new Error(`TileProvider "${h}" class must have a loadTile method`);return lie.set(h,S),S}).finally(()=>{s6.delete(h)});return s6.set(h,x),x},g.cG=function(h,o,u){return o?Vne(h,o,u):h.tiles&&h.tiles.length>0?{tiles:h.tiles}:new Error('TileJSON is missing required "tiles" property')},g.cH=Rre,g.cI=Ure,g.cJ=pi,g.cK=BL,g.cL=function(h,o,u=0,m=!0){const x=new jt(u,u),b=h.sub(x),S=o.add(x),A=[b,new jt(S.x,b.y),S,new jt(b.x,S.y)];return m&&A.push(b.clone()),A},g.cM=function(h,o){const u=[];for(let m=0;m{m(b,S)},o):m(b,S),()=>{}}return x.callbacks.push(m),x.cancel||(x.cancel=u((b,S)=>{x.result=[b,S];for(const A of x.callbacks)this.scheduler?this.scheduler.add(()=>{A(b,S)},o):A(b,S);setTimeout(()=>delete this.entries[h],3e3)})),()=>{x.result||(x.callbacks=x.callbacks.filter(b=>b!==m),x.callbacks.length||(x.cancel(),delete this.entries[h]))}}},g.cX=St,g.cY=function(h,o,u){const m=JSON.stringify(h.request);return h.data&&(this.deduped.entries[m]={result:[null,h.data]}),this.deduped.request(m,{type:"parseTile",renderSourceType:h.renderSourceType,zoom:h.tileZoom},x=>{const b=new AbortController;return di(h.request,b.signal).then(({data:S,headers:A})=>{x(null,{rawData:S,vectorTile:u?void 0:new hz(new GR(S)),headers:A})}).catch(S=>{b.signal.aborted||(Rr(S)?x(null,null):x(S))}),()=>{b.abort(),x(null,null)}},o)},g.cZ=class{constructor(h,o){this.context=h,this.texture=o}bind(h,o){const{context:u}=this,{gl:m}=u;m.bindTexture(m.TEXTURE_2D,this.texture),h!==this.minFilter&&(m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MAG_FILTER,h),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_MIN_FILTER,h),this.minFilter=h),o!==this.wrapS&&(m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_S,o),m.texParameteri(m.TEXTURE_2D,m.TEXTURE_WRAP_T,o),this.wrapS=o)}},g.c_=wc,g.ca=ks,g.cb=IR,g.cc=128,g.cd=Ki,g.ce=gs,g.cf=Vt,g.cg=zt,g.ch=Kt,g.ci=Dne,g.cj=FJ,g.ck=Pk,g.cl=L$,g.cm=Hd,g.cn=a0,g.co=function(h,o){const u=[0,0,0];return Ar(u,u,NR(kp(o.canonical))),Ar(u,u,h),u},g.cp=_u,g.cq=function(h,o,u,m,x,b){const{width:S,height:A}=m.imageManager.getPixelSize(o),I=Math.pow(2,b.tileID.overscaledZ),D=b.tileSize*Math.pow(2,m.transform.tileZoom)/I,B=D*(b.tileID.canonical.x+b.tileID.wrap*I),U=D*b.tileID.canonical.y;return{u_image:0,u_pattern_tl:u.tl,u_pattern_br:u.br,u_texsize:[S,A],u_pattern_size:u.displaySize,u_pattern_units_to_pixels:x?[m.transform.width,-1*m.transform.height]:[1/Pk(b,1,m.transform.tileZoom),1/Pk(b,1,m.transform.tileZoom)],u_pixel_coord_upper:[B>>16,U>>16],u_pixel_coord_lower:[65535&B,65535&U]}},g.cr=h=>({u_matrix:new ua(h),u_texsize:new Pn(h),u_pixels_to_tile_units:new Is(h),u_device_pixel_ratio:new Dr(h),u_width_scale:new Dr(h),u_floor_width_scale:new Dr(h),u_image:new yi(h),u_units_to_pixels:new Pn(h),u_tile_units_to_pixels:new Dr(h),u_alpha_discard_threshold:new Dr(h),u_trim_offset:new Pn(h),u_trim_fade_range:new Pn(h),u_trim_gradient_mix_range:new Pn(h),u_trim_color:new ao(h),u_zbias_factor:new Dr(h),u_tile_to_meter:new Dr(h),u_ground_shadow_factor:new ti(h),u_pattern_transition:new Dr(h),u_opacity_multiplier:new Dr(h)}),g.cs=h=>({u_matrix:new ua(h),u_pixels_to_tile_units:new Is(h),u_device_pixel_ratio:new Dr(h),u_width_scale:new Dr(h),u_floor_width_scale:new Dr(h),u_units_to_pixels:new Pn(h),u_dash_image:new yi(h),u_has_dash:new yi(h),u_has_border:new yi(h),u_gradient_image:new yi(h),u_border_gradient_image:new yi(h),u_image_height:new Dr(h),u_texsize:new Pn(h),u_tile_units_to_pixels:new Dr(h),u_alpha_discard_threshold:new Dr(h),u_trim_offset:new Pn(h),u_trim_fade_range:new Pn(h),u_trim_gradient_mix_range:new Pn(h),u_trim_color:new ao(h),u_zbias_factor:new Dr(h),u_road_view_depth_bias:new Dr(h),u_tile_to_meter:new Dr(h),u_ground_shadow_factor:new ti(h),u_opacity_multiplier:new Dr(h),u_lpp_color:new ao(h),u_lpp_border_color:new ao(h),u_lpp_opacity:new Dr(h),u_lpp_blur:new Dr(h),u_lpp_width:new Dr(h),u_lpp_gap_width:new Dr(h),u_lpp_offset:new Dr(h),u_lpp_floorwidth:new Dr(h),u_lpp_border_width:new Dr(h),u_lpp_emissive_strength:new Dr(h),u_lpp_dash:new ao(h),u_lpp_side_z_offset:new Dr(h),u_lpp_zoom_fraction:new Dr(h)}),g.ct=h=>({u_color:new yu(h),u_matrix:new ua(h),u_overlay:new yi(h),u_overlay_scale:new Dr(h)}),g.cu=h=>({u_camera_to_center_distance:new Dr(h),u_extrude_scale:new Is(h),u_device_pixel_ratio:new Dr(h),u_matrix:new ua(h),u_inv_rot_matrix:new ua(h),u_merc_center:new Pn(h),u_tile_id:new ti(h),u_zoom_transition:new Dr(h),u_up_dir:new ti(h),u_emissive_strength:new Dr(h)}),g.cv=h=>({u_matrix:new ua(h),u_lightpos:new ti(h),u_lightintensity:new Dr(h),u_lightcolor:new ti(h),u_vertical_gradient:new Dr(h),u_height_factor:new Dr(h),u_edge_radius:new Dr(h),u_width_scale:new Dr(h),u_ao:new Pn(h),u_height_type:new yi(h),u_base_type:new yi(h),u_tile_id:new ti(h),u_zoom_transition:new Dr(h),u_inv_rot_matrix:new ua(h),u_merc_center:new Pn(h),u_up_dir:new ti(h),u_height_lift:new Dr(h),u_image:new yi(h),u_texsize:new Pn(h),u_pixel_coord_upper:new Pn(h),u_pixel_coord_lower:new Pn(h),u_tile_units_to_pixels:new Dr(h),u_opacity:new Dr(h),u_pattern_transition:new Dr(h)}),g.cw=h=>({u_matrix:new ua(h),u_lightpos:new ti(h),u_lightintensity:new Dr(h),u_lightcolor:new ti(h),u_vertical_gradient:new Dr(h),u_opacity:new Dr(h),u_edge_radius:new Dr(h),u_width_scale:new Dr(h),u_ao:new Pn(h),u_height_type:new yi(h),u_base_type:new yi(h),u_tile_id:new ti(h),u_zoom_transition:new Dr(h),u_inv_rot_matrix:new ua(h),u_merc_center:new Pn(h),u_up_dir:new ti(h),u_height_lift:new Dr(h),u_flood_light_color:new ti(h),u_vertical_scale:new Dr(h),u_flood_light_intensity:new Dr(h),u_ground_shadow_factor:new ti(h),u_front_cutoff_params:new ti(h)}),g.cx=cd,g.cy=function(h){if("provider"in h&&!h.provider)return null;let o=h.provider;if(!o&&"url"in h&&h.url&&(o=function(x){try{const b=new URL(x).pathname.split("/").pop()||"",S=b.lastIndexOf(".");return S>=0?b.slice(S+1):""}catch{return""}}(h.url)),!o)return null;const u=Cn.TILE_PROVIDER_URLS[o];if(!u)return null;let m;try{m=new URL(u,Cn.API_URL).href}catch{return new Error(`TileProvider "${o}" has an invalid URL: "${u}"`)}return{name:o,url:m}},g.cz=qne,g.d=GR,g.d$=Vr,g.d0=function(h,o,u,m){for(;o>1;h[x]{o.onloadstart=()=>u(),o.onerror=()=>m(new Error(`Could not load video: ${h.join(", ")}`))}),o},g.d6=["type","source","source-layer","minzoom","maxzoom","filter","layout"],g.d7=Dx,g.d8=rr,g.d9=Zr,g.dA=function(h,[o,u]){let m=0,x=0;if(u===_Re){o<0&&(o=0);const b=o/vRe;switch(h){case"top-right":case"top-left":x=b-7;break;case"bottom-right":case"bottom-left":x=7-b;break;case"bottom":x=7-o;break;case"top":x=o-7}switch(h){case"top-right":case"bottom-right":m=-b;break;case"top-left":case"bottom-left":m=b;break;case"left":m=o;break;case"right":m=-o}}else{switch(o=Math.abs(o),u=Math.abs(u),h){case"top-right":case"top-left":case"top":x=u-7;break;case"bottom-right":case"bottom-left":case"bottom":x=7-u}switch(h){case"top-right":case"bottom-right":case"right":m=-o;break;case"top-left":case"bottom-left":case"left":m=o}}return[m,x]},g.dB=function(h){switch(h){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"},g.dC=a6,g.dD=Gz,g.dE=P2,g.dF=yee,g.dG=function(){return{API_URL:Cn.API_URL,DRACO_URL:Cn.DRACO_URL,MESHOPT_URL:Cn.MESHOPT_URL,MESHOPT_SIMD_URL:Cn.MESHOPT_SIMD_URL,BUILDING_GEN_URL:Cn.BUILDING_GEN_URL,RTL_TEXT_URL:Cn.RTL_TEXT_URL}},g.dH=un,g.dI=function(h){if(typeof document>"u"||!document.fonts)return!1;const o=x=>x.trim().replace(/^["']|["']$/g,"").toLowerCase(),u=h.split(",").map(o);let m=!1;return document.fonts.forEach(x=>{u.includes(o(x.family))&&(m=!0)}),m},g.dJ=_e,g.dK=Kl,g.dL=ud,g.dM=function(h){const o=h.indexOf(N0);return o>=0?h.slice(0,o):h},g.dN=function(h){return h.includes(N0)},g.dO=function(h){const o=h.lastIndexOf(N0);return o>=0?h.slice(o+1):""},g.dP=function(h,o={}){const u=o.type&&!o.array&&Array.isArray(h)?{type:o.type,"property-type":"data-constant"}:void 0;return Vg(h===null||typeof h!="object"||Array.isArray(h)?h:["literal",h],u)},g.dQ=function(h){const o=[],u=h.id;return u===void 0&&o.push({message:`layers.${u}: missing required property "id"`}),h.render===void 0&&o.push({message:`layers.${u}: missing required method "render"`}),h.renderingMode&&h.renderingMode!=="2d"&&h.renderingMode!=="3d"&&o.push({message:`layers.${u}: property "renderingMode" must be either "2d" or "3d"`}),o},g.dR=function(h,o,u,m){return h.type==="custom"?new qDe(h,o):new AMe[h.type](h,o,u,m)},g.dS=qd,g.dT=cR,g.dU=class extends Z0{constructor(h,o){super(h._vectorTileFeature,h._z,h._x,h._y,h.id),h.state&&(this.state={...h.state}),this.target=o.target,this.namespace=o.namespace,o.properties&&(this.properties=o.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=h.source,this.sourceLayer=h.sourceLayer,this.layer=h.layer)}toJSON(){const h=super.toJSON();return h.target=this.target,h.namespace=this.namespace,h}},g.dV=zne,g.dW=see,g.dX=function(h,o){return[Math.pow(h[0],2.2)*o,Math.pow(h[1],2.2)*o,Math.pow(h[2],2.2)*o]},g.dY=ft,g.dZ=vt,g.d_=Uc,g.da=Wr,g.db=xs,g.dc=uu,g.dd=Mi,g.de=.55,g.df=n_,g.dg=rne,g.dh=vz,g.di=tee,g.dj=Uz,g.dk=G,g.dl=G1,g.dm=.9,g.dn=nee,g.dp=function(h,o,u,m,x,b,S){const A=G$(h,o,u,m,x,b,S);return b.name==="globe"&&u||(A[2]=A[6]=A[10]=A[14]=0),A},g.dq=function(h,o,u,m,x,b,S){if(u){if(b.name==="globe"){const A=G$(h,o,u,m,x,b,S);return Z(A,A),Q(A,h,A),A}{const A=F(h),[I,D,B,U]=S,[q,K,X,J,se,ae,ue,ce]=A;return A[0]=I*q+D*se,A[1]=I*K+D*ae,A[2]=I*X+D*ue,A[3]=I*J+D*ce,A[4]=B*q+U*se,A[5]=B*K+U*ae,A[6]=B*X+U*ue,A[7]=B*J+U*ce,m||Le(A,A,-x.angle),A}}return x.glCoordMatrix},g.dr=Xg,g.ds=Fz,g.dt=hk,g.du=$z,g.dv=VR,g.dw=ps,g.dx=TR,g.dy=Zg,g.dz=AJ,g.e=hu,g.e$=function(h,o){o?rl.add(h):rl.delete(h)},g.e0=mMe,g.e1=pMe,g.e2=h=>({u_cutoff_params:new ao(h)}),g.e3=h=>({u_light_matrix_0:new ua(h),u_light_matrix_1:new ua(h),u_fade_range:new Pn(h),u_shadow_normal_offset:new ti(h),u_shadow_intensity:new Dr(h),u_shadow_texel_size:new Dr(h),u_shadow_map_resolution:new Dr(h),u_shadow_direction:new ti(h),u_shadow_bias:new ti(h),u_shadowmap_0:new yi(h),u_shadowmap_1:new yi(h)}),g.e4=function(h,o,u){return o.name===u.projection.name?h.projMatrix:qz(u,o,h)},g.e5=G$,g.e6=Lk,g.e7=tne,g.e8=G0,g.e9=function(h,o,u,m,x,b,S,A,I,D,B=1){const U=u.transform,q=m?h.textSizeData:h.iconSizeData,K=Xg(q,u.transform.zoom,B),X=U.projection.name==="globe",J=(()=>{if(!X)return null;const Pe=Ip(U.zoom);return Pe===0?null:{t:Pe,invMatrix:U.projection.createInversionMatrix(U,D.canonical),mercCenter:[mu(U.center.lng),vc(U.center.lat)]}})(),se=[256/u.width*2+1,256/u.height*2+1],ae=m?h.text.dynamicLayoutVertexArray:h.icon.dynamicLayoutVertexArray;ae.clear();let ue=null;X&&(ue=m?h.text.globeExtVertexArray:h.icon.globeExtVertexArray);const ce=h.lineVertexArray,de=m?h.text.placedSymbolArray:h.icon.placedSymbolArray,xe=u.transform.width/u.transform.height;let ve,Ue=!1;for(let Pe=0;Pe0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(h,o=!1){const u=QJ(new jt(0,0),new jt(ar,ar),h),m=[];if(o&&!Bz(u,this._globalClipBounds))return m;for(const x of this._activeRegions){if(x.hiddenByOverlap||!Bz(u,x))continue;const b=FRe(x.min,x.max,h);m.push({min:b.min,max:b.max,sourceId:this._sourceIds[x.priority],footprint:x.footprint,footprintTileId:x.tileId,order:x.order,clipMask:x.clipMask,clipScope:x.clipScope})}return m}setSources(h){this._setSources(h.map(o=>({getSourceId:()=>o.cache.id,getFootprints:()=>{const u=[];for(const m of o.cache.getVisibleCoordinates()){const x=o.cache.getTile(m).buckets[o.layer];x&&x.updateFootprints(m.toUnwrapped(),u)}return u},getOrder:()=>o.order,getClipMask:()=>o.clipMask,getClipScope:()=>o.clipScope})))}_addSource(h){const o=h.getFootprints();if(o.length===0)return;const u=h.getOrder(),m=h.getClipMask(),x=h.getClipScope();for(const b of o){if(!b.footprint)continue;const S=QJ(b.footprint.min,b.footprint.max,b.id);this._activeRegions.push({min:S.min,max:S.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:b.id,footprint:b.footprint,order:u,clipMask:m,clipScope:x})}this._sourceIds.push(h.getSourceId())}_computeReplacement(){this._activeRegions.sort((o,u)=>o.priority-u.priority||FR(o.min,u.min)||FR(o.max,u.max)||o.order-u.order||o.clipMask-u.clipMask||function(m,x){const b=(S,A)=>S+A;return m.length-x.length||m.reduce(b,"").localeCompare(x.reduce(b,""))}(o.clipScope,u.clipScope));let h=this._activeRegions.length!==this._prevRegions.length;if(!h){let o=0;for(;!h&&o!==this._activeRegions.length;){const u=this._activeRegions[o],m=this._prevRegions[o];h=u.priority!==m.priority||!XJ(u,m)||u.order!==m.order||u.clipMask!==m.clipMask||!Ha(u.clipScope,m.clipScope),this._activeRegions[o].hiddenByOverlap=m.hiddenByOverlap,++o}}if(h){++this._updateTime;for(const u of this._activeRegions)u.order!==dk&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,u.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,u.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,u.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,u.max.y));const o=u=>{const m=this._activeRegions;if(u>=m.length)return u;const x=m[u].priority;for(;u1){let u=0,m=o(u);for(;u!==m;){let x=u;const b=u;for(;x!==m;){const S=this._activeRegions[x];S.hiddenByOverlap=!1;for(let A=0;A=0;o--)this._addSource(h[o]);this._computeReplacement()}},g.eC=dk,g.eD=class{constructor(h){this._createGrid(h),this._createPoles(h)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const h of this._poleSegments)h.destroy();for(const h of this._gridSegments)h.withSkirts.destroy(),h.withoutSkirts.destroy()}_fillGridMeshWithLods(h,o){const u=new mm,m=new Ne,x=[],b=h+1+2,S=o[0]+1,A=o[0]+1+(1+o.length),I=(D,B,U)=>{let q=D===b-1?D-2:D===0?D:D-1;return q+=U?24575:0,[q,B]};for(let D=0;Dthis._skuTokenExpiresAt}async transformRequest(h,o,u){if(!this._transformRequestFn)return{url:h};const m=u?{signal:u}:{};return await this._transformRequestFn(h,o,m)||{url:h}}normalizeStyleURL(h,o){if(!St(h))return h;const u=Rs(h);return u.params.push(`sdk=js-${v}`),u.path=`/styles/v1${u.path}`,this._makeAPIURL(u,this._customAccessToken||o)}normalizeGlyphsURL(h,o){if(!St(h))return h;const u=Rs(h);return u.path=`/fonts/v1${u.path}`,this._makeAPIURL(u,this._customAccessToken||o)}normalizeModelURL(h,o){if(!St(h))return h;const u=Rs(h);return u.path=`/models/v1${u.path}`,this._makeAPIURL(u,this._customAccessToken||o)}normalizeSourceURL(h,o,u,m){if(!St(h))return h;const x=Rs(h);return x.path=`/v4/${x.authority}.json`,x.params.push("secure"),u&&x.params.push(`language=${u}`),m&&x.params.push(`worldview=${m}`),this._makeAPIURL(x,this._customAccessToken||o)}normalizeIconsetURL(h,o){const u=Rs(h);return St(h)?(u.path=`/styles/v1${u.path}/iconset.pbf`,this._makeAPIURL(u,this._customAccessToken||o)):ko(u)}normalizeSpriteURL(h,o,u,m){const x=Rs(h);return St(h)?(x.path=`/styles/v1${x.path}/sprite${o}${u}`,this._makeAPIURL(x,this._customAccessToken||m)):(x.path+=`${o}${u}`,ko(x))}normalizeTileURL(h,o,u){if(this._isSkuTokenExpired()&&this._createSkuToken(),h&&!St(h))return h;const m=Rs(h);m.path=m.path.replace(ai,(o||u&&m.authority!=="raster"&&u===512?"@2x":"")+".webp"),m.authority==="raster"?m.path=`/${Cn.RASTER_URL_PREFIX}${m.path}`:m.authority==="rasterarrays"?m.path=`/${Cn.RASTERARRAYS_URL_PREFIX}${m.path}`:m.authority==="3dtiles"?m.path=`/${Cn.TILES3D_URL_PREFIX}${m.path}`:(m.path=m.path.replace(Si,"/"),m.path=`/${Cn.TILE_URL_VERSION}${m.path}`);const x=this._customAccessToken||function(b){for(const S of b){const A=S.match(Es);if(A)return A[1]}return null}(m.params)||Cn.ACCESS_TOKEN;return Cn.REQUIRE_ACCESS_TOKEN&&x&&this._skuToken&&m.params.push(`sku=${this._skuToken}`),this._makeAPIURL(m,x)}canonicalizeTileURL(h,o){const u=Rs(h);if(!tl.test(u.path)||!Ta.test(u.path))return h;let m="mapbox://";u.path.startsWith("/raster/v1/")?m+=`raster/${u.path.replace(`/${Cn.RASTER_URL_PREFIX}/`,"")}`:u.path.startsWith("/rasterarrays/v1/")?m+=`rasterarrays/${u.path.replace(`/${Cn.RASTERARRAYS_URL_PREFIX}/`,"")}`:m+=`tiles/${u.path.replace(`/${Cn.TILE_URL_VERSION}/`,"")}`;let x=u.params;return o&&(x=x.filter(b=>!b.match(Es))),x.length&&(m+=`?${x.join("&")}`),m}canonicalizeTileset(h,o){const u=!!o&&St(o),m=[];for(const x of h.tiles||[])wt(x)?m.push(this.canonicalizeTileURL(x,u)):m.push(x);return m}_makeAPIURL(h,o){const u="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",m=Rs(Cn.API_URL);if(h.protocol=m.protocol,h.authority=m.authority,h.protocol==="http"){const x=h.params.indexOf("secure");x>=0&&h.params.splice(x,1)}if(m.path!=="/"&&(h.path=`${m.path}${h.path}`),!Cn.REQUIRE_ACCESS_TOKEN)return ko(h);if(o=o||Cn.ACCESS_TOKEN,!this._silenceAuthErrors){if(!o)throw new Error(`An API access token is required to use Mapbox GL. ${u}`);if(o[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${u}`)}return h.params=h.params.filter(x=>!x.includes("access_token")),h.params.push(`access_token=${o||""}`),ko(h)}},g.e_=pa,g.ea=dee,g.eb=Yte,g.ec=(h,o,u,m,x,b)=>{const S=h.transform,A=S.projection.name==="globe";let I;if(b.paint.get("circle-pitch-alignment")==="map")if(A){const B=FJ(S.zoom,o.canonical)*S._pixelsPerMercatorPixel;I=Float32Array.from([B,0,0,B])}else I=S.calculatePixelsToTileUnitsMatrix(u);else I=new Float32Array([S.pixelsToGLUnits[0],0,0,S.pixelsToGLUnits[1]]);const D={u_camera_to_center_distance:h.transform.getCameraToCenterDistance(S.projection),u_matrix:h.translatePosMatrix(o.projMatrix,u,b.paint.get("circle-translate"),b.paint.get("circle-translate-anchor")),u_device_pixel_ratio:hu.devicePixelRatio,u_extrude_scale:I,u_inv_rot_matrix:MDe,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:b.paint.get("circle-emissive-strength")};if(A){D.u_inv_rot_matrix=m,D.u_merc_center=x,D.u_tile_id=[o.canonical.x,o.canonical.y,1<{const B=h.transform,U=B.pitch<15?Kr(.07,.7,cn((14-B.zoom)/5,0,1)):.07,q=u.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:_re(h,o,u,m),u_texsize:o.imageAtlasTexture?o.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:B.calculatePixelsToTileUnitsMatrix(o),u_device_pixel_ratio:x,u_width_scale:b,u_floor_width_scale:S,u_image:0,u_tile_units_to_pixels:xre(o,B),u_units_to_pixels:[1/B.pixelsToGLUnits[0],1/B.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:A,u_trim_fade_range:u.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:u.paint.get("line-trim-color").toPremultipliedRenderColor(q?null:u.lut).toArray01(),u_zbias_factor:U,u_tile_to_meter:Wc(o.tileID.canonical,0),u_ground_shadow_factor:I,u_pattern_transition:D,u_opacity_multiplier:1}},g.ef=(h,o,u,m,x,b,S,A,I,D)=>{const B=h.transform,U=B.calculatePixelsToTileUnitsMatrix(o),q=u.paint.get("line-trim-color-use-theme").constantOr("default")==="none",K=B.pitch<15?Kr(.07,.7,cn((14-B.zoom)/5,0,1)):.07;return{u_matrix:_re(h,o,u,m),u_pixels_to_tile_units:U,u_device_pixel_ratio:b,u_width_scale:S,u_floor_width_scale:A,u_units_to_pixels:[1/B.pixelsToGLUnits[0],1/B.pixelsToGLUnits[1]],u_has_dash:+bre(u),u_has_border:+(u.paint.get("line-border-width").constantOr(1)!==0),u_dash_image:0,u_gradient_image:1,u_border_gradient_image:2,u_image_height:x,u_texsize:bre(u)&&o.lineAtlasTexture?o.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:xre(o,h.transform),u_alpha_discard_threshold:0,u_trim_offset:I,u_trim_fade_range:u.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:u.paint.get("line-trim-color").toPremultipliedRenderColor(q?null:u.lut).toArray01(),u_zbias_factor:K,u_road_view_depth_bias:0,u_tile_to_meter:Wc(o.tileID.canonical,0),u_ground_shadow_factor:D,u_opacity_multiplier:1,u_lpp_color:[0,0,0,1],u_lpp_border_color:[0,0,0,0],u_lpp_opacity:1,u_lpp_blur:0,u_lpp_width:1,u_lpp_gap_width:0,u_lpp_offset:0,u_lpp_floorwidth:1,u_lpp_border_width:0,u_lpp_emissive_strength:0,u_lpp_dash:[0,0,0,0],u_lpp_side_z_offset:0,u_lpp_zoom_fraction:0}},g.eg=0,g.eh=$Ne,g.ei=r0,g.ej=jk,g.ek=5,g.el=VDe,g.em=$J,g.en=ot,g.eo=k,g.ep=function(h,o){var u=Math.sin(o),m=Math.cos(o);return h[0]=m,h[1]=0,h[2]=-u,h[3]=0,h[4]=0,h[5]=1,h[6]=0,h[7]=0,h[8]=u,h[9]=0,h[10]=m,h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,h},g.eq=function(h,o){var u=Math.sin(o),m=Math.cos(o);return h[0]=1,h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=m,h[6]=u,h[7]=0,h[8]=0,h[9]=-u,h[10]=m,h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,h},g.er=function(h,o){return h[0]=o[0],h[1]=o[1],h[2]=o[2],h[3]=o[4],h[4]=o[5],h[5]=o[6],h[6]=o[8],h[7]=o[9],h[8]=o[10],h},g.es=P,g.et=pt,g.eu=1,g.ev=oS,g.ew=dt,g.ex=function(h,o,u,m,x){return cn((h-o)/(u-o)*(x-m)+m,m,x)},g.ey=Da,g.ez=function(h,o){var u=o[0],m=o[1],x=o[2],b=o[3],S=o[4],A=o[5],I=o[6],D=o[7],B=o[8],U=B*S-A*D,q=-B*b+A*I,K=D*b-S*I,X=u*U+m*q+x*K;return X?(h[0]=U*(X=1/X),h[1]=(-B*m+x*D)*X,h[2]=(A*m-x*S)*X,h[3]=q*X,h[4]=(B*u-x*I)*X,h[5]=(-A*u+x*b)*X,h[6]=K*X,h[7]=(-D*u+m*I)*X,h[8]=(S*u-m*b)*X,h):null},g.f=class{constructor(h){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(h&&h.maxTextureMemoryMB?h.maxTextureMemoryMB:256)*1024,this.currentFrameAtlases=new Set,this.previousFrameAtlases=new Set,this.finalizationRegistry=new FinalizationRegistry(o=>{var u;(u=this.cache.get(o))!=null&&u.deref()||this.cache.delete(o),this.clearExpiredTextures()})}beginFrame(){const h=this.previousFrameAtlases;this.previousFrameAtlases=this.currentFrameAtlases,this.currentFrameAtlases=h,h.clear()}calculateTextureMemory(h,[o,u]){return Math.ceil(o*u*4*(h.patternPositions.size>0?1.33:1))}evictTexture(h){const o=this.textures.get(h);if(o){this.isAtlasCached(h)&&this.cache.delete(h.contentDescriptor.hash);const u=this.calculateTextureMemory(h,o.size);o.destroy(),this.textures.delete(h),this.textureAccessTimes.delete(h),this.textureMemoryUsed-=u}}evictTexturesIfNeeded(h){for(;this.textureMemoryUsed+h>this.maxTextureMemory&&this.textures.size>0;){let o=null,u=1/0;for(const[m]of this.textures.entries()){if(this.currentFrameAtlases.has(m)||this.previousFrameAtlases.has(m))continue;const x=this.textureAccessTimes.get(m)||0;x0&&c$(o,h.layers[0].source,h.sourceLayerName);(m||x)&&(h.hdExt=new Zee(h,m,x))},g.fE=function(h,o){const u=h.layers[0].layout.get("line-elevation-reference")==="hd-road-markup",m=!!o&&o.length>0&&c$(o,h.layers[0].source,h.sourceLayerName);(u||m)&&(h.hdExt=new Xee(u,m))},g.fF=ER,g.fG=function(h){const o=h.layers[0];o.type==="circle"&&o.layout.get("circle-elevation-reference")==="hd-road-markup"&&(h.hdExt=new Qee)},g.fH=function(h){h.layers[0].layout.get("symbol-elevation-reference")==="hd-road-markup"&&(h.hdExt=new Jee)},g.fI=ete,g.fJ=Wne,g.fK=function(h){let o=0;if(new Uint32Array(h,0,1)[0]!==lte){const u=new Uint32Array(h,0,7),[,,m,x,b,S]=u;o=u.byteLength+x+b+S+b,(m!==h.byteLength||o>=h.byteLength)&&Xi("Invalid b3dm header information.")}return hte(h,o)},g.fL=function(h,o){const u=_$(h);for(const m of u){if(!m.meshBVH)for(const x of m.meshes)tDe(x);if(m.lights){let x=65535;for(const b of m.meshes)b.doorVertexColor!==void 0&&(x=b.doorVertexColor,m.lightsStyleAabb=b.aabb);m.lightMeshIndex=m.meshes.length,m.meshes.push(rDe(m.lights,o,x))}}return u},g.fM=Wc,g.fN=Yre,g.fO=vr,g.fQ=function(h,o){let u="";for(let m=0;m=8592&&h<=8595||h===8208||h===8229||h===8741||h>=9472&&h<=9547||h===65294||h===65309||h===65374||h===65507},g.fV=3,g.fW=Hw,g.fX=fJ,g.fY=Kg,g.fZ=function(h){for(const o of h)if(!I2(o.charCodeAt(0)))return!1;return!0},g.f_=j0,g.fa=v,g.fb=vi,g.fc=function(h,o){Oe=h,ze=o},g.fd=Mz,g.fe=po,g.ff=UJ,g.fg=zJ,g.fh=function(h){Rl=h},g.fi=Ot,g.fj=ene,g.fk=function(h,o){if(!h||!o)throw new Error("TileProvider name and URL are required");Cn.TILE_PROVIDER_URLS[h]=hu.resolveURL(o)},g.fl=function(h){typeof h!="string"||h.length>64||!as.test(h)?Xi(`Invalid SDK info "${h}"; expected a "Name/version" string. Ignoring.`):ys=h},g.fm=function(h){Cn.BUILDING_GEN_URL=hu.resolveURL(h)},g.fn=re,g.fo=function(h){const o=hu.resolveURL(h);Cn.MESHOPT_URL=o,Cn.MESHOPT_SIMD_URL=o},g.fp=ye,g.fq=function(h){Cn.DRACO_URL=hu.resolveURL(h)},g.fr=_x,g.fs=function(h){const o=Je();if(!o)return;const u=o.delete(je);h&&u.then(()=>h()).catch(h)},g.ft=function(h){Cn.MAX_PARALLEL_IMAGE_REQUESTS=h},g.fu=function(h){Cn.API_URL=h},g.fv=function(h){Cn.ACCESS_TOKEN=h},g.fw="hd_road_elevation",g.fx=class{static parseFrom(h,o){const u=ey.parse(h);if(!u)return[];let{vertices:m,features:x}=u;const b=1/Wc(o);x.sort((D,B)=>D.id-B.id),m.sort((D,B)=>D.id-B.id||D.idx-B.idx),m=m.filter((D,B,U)=>B===U.findIndex(q=>q.id===D.id&&q.idx===D.idx));const S=new Array;let A=0;const I=m.length;for(const D of x){if(D.constantHeight){S.push(new ty(D.id,D.bounds,D.constantHeight));continue}for(;A!==I&&m[A].id>1)+se]=K.charCodeAt(se);return J}function U(K,X){return D.decode(new Uint16Array(u.buffer,K,X))}function q(K,X,J){if(!K)return[J?[K,J]:K];const se=K.length,ae=X.length,ue=B(K,10*se+8*ae),ce=ue+2*se,de=ue+4*se>>2,xe=de+se,ve=xe+ae;I.set(X,xe);const Ue=x(ue,se,xe<<2,ae,ce,de<<2,ve<<2);if(Ue<=0)return S(ue),Ue?[]:[J?[K,J]:K];const Pe=U(ce,I[ve+Ue-1]),De=[];for(let Ve=0,Fe=0;Ve{g.fP=h})),TJ},g.gl=px,g.gm=Zz,g.gn=Wz,g.go=fee,g.gp=mee,g.gq=hz,g.gr=function(h){return h<=1?1:Math.pow(2,Math.floor(Math.log2(h)))},g.gs=zL,g.gt=Wx,g.gu=class{constructor(h=new Uint8Array(16)){this.buf=ArrayBuffer.isView(h)?h:new Uint8Array(h),this.dataView=new DataView(this.buf.buffer,this.buf.byteOffset,this.buf.byteLength),this.pos=0,this.length=this.buf.length}writeTag(h,o){this.writeVarint(h<<3|o)}realloc(h){let o=this.length||16;for(;o=0&&h<128)return this.pos>=this.length&&this.realloc(1),void(this.buf[this.pos++]=h);h>268435455||h<0?function(o,u){let m,x;if(o>=0?(m=o%4294967296|0,x=o/4294967296|0):(m=~(-o%4294967296),x=~(-o/4294967296),4294967295^m?m=m+1|0:(m=0,x=x+1|0)),o>=18446744073709552e3||o<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");u.realloc(10),function(b,S,A){A.buf[A.pos++]=127&b|128,b>>>=7,A.buf[A.pos++]=127&b|128,b>>>=7,A.buf[A.pos++]=127&b|128,b>>>=7,A.buf[A.pos++]=127&b|128,A.buf[A.pos]=127&(b>>>=7)}(m,0,u),function(b,S){const A=(7&b)<<4;S.buf[S.pos++]|=A|((b>>>=3)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b|((b>>>=7)?128:0),b&&(S.buf[S.pos++]=127&b)))))}(x,u)}(h,this):(this.realloc(4),this.buf[this.pos++]=127&h|(h>127?128:0),h<=127||(this.buf[this.pos++]=127&(h>>>=7)|(h>127?128:0),h<=127||(this.buf[this.pos++]=127&(h>>>=7)|(h>127?128:0),h<=127||(this.buf[this.pos++]=h>>>7&127))))}writeSVarint(h){this.writeVarint(h<0?2*-h-1:2*h)}writeBoolean(h){this.writeVarint(+h)}writeString(h){h=String(h),this.realloc(4*h.length),this.pos++;const o=this.pos;this.pos=function(m,x,b){for(let S,A,I=0;I55295&&S<57344){if(!A){S>56319||I+1===x.length?(m[b++]=239,m[b++]=191,m[b++]=189):A=S;continue}if(S<56320){m[b++]=239,m[b++]=191,m[b++]=189,A=S;continue}S=A-55296<<10|S-56320|65536,A=null}else A&&(m[b++]=239,m[b++]=191,m[b++]=189,A=null);S<128?m[b++]=S:(S<2048?m[b++]=S>>6|192:(S<65536?m[b++]=S>>12|224:(m[b++]=S>>18|240,m[b++]=S>>12&63|128),m[b++]=S>>6&63|128),m[b++]=63&S|128)}return b}(this.buf,h,this.pos);const u=this.pos-o;u>=128&&lee(o,u,this),this.pos=o-1,this.writeVarint(u),this.pos+=u}writeFloat(h){this.realloc(4),this.dataView.setFloat32(this.pos,h,!0),this.pos+=4}writeDouble(h){this.realloc(8),this.dataView.setFloat64(this.pos,h,!0),this.pos+=8}writeBytes(h){const o=h.length;this.writeVarint(o),this.realloc(o),this.buf.set(h,this.pos),this.pos+=o}writeRawMessage(h,o){this.pos++;const u=this.pos;h(o,this);const m=this.pos-u;m>=128&&lee(u,m,this),this.pos=u-1,this.writeVarint(m),this.pos+=m}writeMessage(h,o,u){this.writeTag(h,2),this.writeRawMessage(o,u)}writePackedVarint(h,o){o.length&&this.writeMessage(h,zRe,o)}writePackedSVarint(h,o){o.length&&this.writeMessage(h,$Re,o)}writePackedBoolean(h,o){o.length&&this.writeMessage(h,qRe,o)}writePackedFloat(h,o){o.length&&this.writeMessage(h,URe,o)}writePackedDouble(h,o){o.length&&this.writeMessage(h,VRe,o)}writePackedFixed32(h,o){o.length&&this.writeMessage(h,GRe,o)}writePackedSFixed32(h,o){o.length&&this.writeMessage(h,HRe,o)}writePackedFixed64(h,o){o.length&&this.writeMessage(h,WRe,o)}writePackedSFixed64(h,o){o.length&&this.writeMessage(h,KRe,o)}writeBytesField(h,o){this.writeTag(h,2),this.writeBytes(o)}writeFixed32Field(h,o){this.writeTag(h,5),this.writeFixed32(o)}writeSFixed32Field(h,o){this.writeTag(h,5),this.writeSFixed32(o)}writeFixed64Field(h,o){this.writeTag(h,1),this.writeFixed64(o)}writeSFixed64Field(h,o){this.writeTag(h,1),this.writeSFixed64(o)}writeVarintField(h,o){this.writeTag(h,0),this.writeVarint(o)}writeSVarintField(h,o){this.writeTag(h,0),this.writeSVarint(o)}writeStringField(h,o){this.writeTag(h,2),this.writeString(o)}writeFloatField(h,o){this.writeTag(h,5),this.writeFloat(o)}writeDoubleField(h,o){this.writeTag(h,1),this.writeDouble(o)}writeBooleanField(h,o){this.writeVarintField(h,+o)}},g.gv=fp,g.gw=OR,g.gx=Yne,g.gy=function(h){rt(),Xe!=null&&Xe.then(o=>{o.keys().then(u=>{for(let m=0;mXi(x.message))}).catch(u=>Xi(u.message))}).catch(o=>Xi(o.message))},g.h=Oa,g.i=nl,g.j=Io,g.k=2,g.l=mk,g.m=Bx,g.n=di,g.o=$w,g.p=cee,g.q=function(h){return function(o){const u={glyphs:[]};let m;for(;m=o.nextField();)m===1&&YRe(o,o.readVarint()+o.pos,u);return u}(new GR(h))},g.r=eLe,g.s=lt,g.t=Cn,g.u=function(h,o,u){if(!h.length)return u(null,[]);let m=h.length;const x=new Array(h.length);let b=null;h.forEach((S,A)=>{o(S,(I,D)=>{I&&(b=I),x[A]=D,--m===0&&u(b,x)})})},g.v=Dg,g.w=Xi,g.x=aR,g.y=Gc,g.z=wx}),d(["./shared"],function(l){function g(ye){const re=ye?ye.url.toString():void 0;return re?performance.getEntriesByName(re):[]}function v(ye,re){if(Object.hasOwn(ye.layers,l.fw))return l.fx.parseFrom(ye.layers[l.fw],re)}function E({buckets:ye,data:re,sourceLayerCoder:he,canonical:_e,options:je}){if(!je.elevationFeatures||je.elevationFeatures.length===0)return;const Oe=[];for(const Qe of Object.values(ye))if(Qe instanceof l.bL&&Qe.hdExt){const Xe=Qe.hdExt.getUnevaluatedPortalGraph();Xe&&Oe.push(Xe)}const ze=l.fy.evaluate(Oe);for(const Qe of Object.values(ye))if(Qe instanceof l.bL&&Qe.hdExt){const Xe=re.layers[he.decode(Qe.sourceLayerIndex)];Qe.hdExt.setEvaluatedPortalGraph(ze,Xe,_e,je.availableImages,je.brightness,Qe.worldview)}}function T(ye){const re=[];for(let he=0;he0){let Xe=!1;for(const Je of ze[0])if(Je.x<0||Je.x>l.ac||Je.y<0||Je.y>l.ac){Xe=!0;break}if(Xe)continue}const Qe=ze.length===1&&ze[0].length===5&&ze[0].some(Xe=>Xe.x<=0&&Xe.y<=0)&&ze[0].some(Xe=>Xe.x>=l.ac&&Xe.y<=0)&&ze[0].some(Xe=>Xe.x>=l.ac&&Xe.y>=l.ac)&&ze[0].some(Xe=>Xe.x<=0&&Xe.y>=l.ac);re.push(new l.fz(Oe,Qe?[]:ze))}return re}function j(ye,re,he,_e,je){const Oe=l.fA(re);if(Oe===null)return!1;let ze=he.x,Qe=he.y;const Xe=je??_e.z;if(_e.z!==Xe){const Je=1<<_e.z-Xe,rt=l.ac/Je;ze=_e.x%Je*rt+he.x/Je,Qe=_e.y%Je*rt+he.y/Je}for(const Je of ye){if(!(Je.hasGeometry()&&Je.frcMask&1<It.map(wt=>[wt.x,wt.y]));if(l.fB([ze,Qe],rt))return!0}return!1}function P(ye,re,he,_e){const je=re.indoorState.activeFloorsVisible;if(!re.sourceLayers)return je?re.indoorState.activeFloors:void 0;const Oe=function(Xe,Je){if(!Xe)return l.w("No source layers defined in indoor specification"),Je;if(Xe.size===0)return Je;const rt=Xe.difference(Je);for(const It of rt)l.w(`Missing source layer required in indoor specification: ${It}`);return Je.intersection(Je)}(re.sourceLayers,new Set(Object.keys(ye.layers))),ze=re.indoorState,Qe=function(Xe,Je,rt,It,wt){const St={};for(const Ot of Je){const pr=Xe.layers[Ot];if(pr)for(let Ht=0;HtOt.map(pr=>l.fC(pr,It,rt.extent)));return St.length===0?void 0:{type:"Polygon",coordinates:[St[0]]}}(ye,re);return{id:he,isDefault:_e,connections:je,conflicts:Oe,buildings:ze,name:Qe,zIndex:Xe,geometry:Je}}function $(ye,re){return re.every(he=>ye.properties&&ye.properties[he]!=null)}function G(ye){return $(ye,["type","id","name"])&&ye.properties.type==="structure"}function W(ye){return $(ye,["type","id","name","z_index"])&&ye.properties.type==="floor"}function Z(ye,re){ye instanceof l.bL?l.fD(ye,re):ye instanceof l.bG?l.fE(ye,re):ye instanceof l.fF?l.fG(ye):ye instanceof l.bF&&l.fH(ye)}function Q(ye){for(const re in ye){const he=ye[re];if(he instanceof l.bG&&he.hdExt&&he.hdExt.hasDeferredElevationFeatures||he instanceof l.bF&&he.hdExt&&he.hdExt.hasDeferredElevationFeatures)return!0}return!1}class ee{constructor(re,he,_e){this.tileID=new l.bZ(re.tileID.overscaledZ,re.tileID.wrap,re.tileID.canonical.z,re.tileID.canonical.x,re.tileID.canonical.y),this.tileZoom=re.tileZoom,this.uid=re.uid,this.zoom=re.zoom,this.canonical=re.tileID.canonical,this.pixelRatio=re.pixelRatio,this.tileSize=re.tileSize,this.source=re.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=re.projection,this.brightness=he,this.worldview=_e}async parse(re,he,_e){this.status="parsing";const je=new l.bZ(_e.tileID.overscaledZ,_e.tileID.wrap,_e.tileID.canonical.z,_e.tileID.canonical.x,_e.tileID.canonical.y),Oe=[],ze=he.familiesBySource[_e.source],Qe=new l.fJ(je,_e.promoteId);Qe.bucketLayerIDs=[],Qe.is3DTile=!0;const Xe=await l.fK(re),Je=Xe.json.extensionsUsed&&Xe.json.extensionsUsed.includes("MAPBOX_mesh_features")||Xe.json.asset.extras&&Xe.json.asset.extras.MAPBOX_mesh_features,rt=Xe.json.extensionsUsed&&Xe.json.extensionsUsed.includes("EXT_meshopt_compression"),It=new l.au(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const wt in ze)for(const St of ze[wt]){const Ot=St[0];Qe.bucketLayerIDs.push(St.map(er=>l.m(er.id,er.scope))),Ot.recalculate(It,[]);const pr=l.fL(Xe,1/l.fM(_e.tileID.canonical)),Ht=new l.fN(St,pr,je,Je,rt,this.brightness,Qe,this.worldview);Oe.push(Ht),Ht.evaluate(Ot)}return this.status="done",{buckets:Oe,featureIndex:Qe,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null}}}class ie{constructor({actor:re,layerIndex:he,availableImages:_e,availableModels:je,brightness:Oe,worldview:ze}){this.actor=re,this.layerIndex=he,this.availableImages=_e,this.availableModels=je,this.brightness=Oe,this.loading={},this.loaded={},this.worldview=ze}async loadTile(re){var Qe;const he=re.uid;(Qe=l.fI())==null||Qe.catch(()=>{});const _e=new AbortController,je=this.loading[he]=new ee(re,this.brightness,this.worldview);je.abort=()=>_e.abort();const Oe=(Xe,Je)=>{const rt=je.reloadCallback;rt&&(delete je.reloadCallback,rt(Xe,Je))};let ze;try{ze=(await l.n(re.request,_e.signal)).data}catch(Xe){if(delete this.loading[he],je.status="done",this.loaded[he]=je,_e.signal.aborted)return null;throw Xe}if(delete this.loading[he],!ze||ze.byteLength===0)return je.status="done",this.loaded[he]=je,null;try{const Xe=await je.parse(ze,this.layerIndex,re);return this.loaded[he]=je,Oe(null,Xe),Xe}catch(Xe){throw this.loaded[he]=je,Oe(Xe),Xe}}async reloadTile(re){const he=this.loaded&&this.loaded[re.uid];if(he)return he.projection=re.projection,he.brightness=re.brightness,he.status==="parsing"&&await new Promise((_e,je)=>{he.reloadCallback=Oe=>{Oe?je(Oe):_e()}}),this.loadTile(re)}abortTile(re){const he=re.uid,_e=this.loading[he];_e&&(_e.abort&&_e.abort(),delete this.loading[he])}removeTile(re){const he=this.loaded,_e=re.uid;he&&he[_e]&&delete he[_e]}}function oe(ye){if(typeof ye=="number"||typeof ye=="boolean"||typeof ye=="string"||ye==null)return JSON.stringify(ye);if(Array.isArray(ye)){let he="[";for(const _e of ye)he+=`${oe(_e)},`;return`${he}]`}let re="{";for(const he of Object.keys(ye).sort())re+=`${he}:${oe(ye[he])},`;return`${re}}`}function pe(ye){let re="";for(const he of l.d6)re+=`/${oe(ye[he])}`;return re}function Le(ye,re){return function he(_e){return typeof _e=="string"&&_e===re||(Array.isArray(_e)?_e.some(he):!(!_e||typeof _e!="object")&&Object.values(_e).some(he))}(ye)}class be{constructor(re){this.keyCache=Object.create(null),this._layers=Object.create(null),this._layerConfigs=Object.create(null),re&&this.replace(re)}replace(re,he){this._layerConfigs=Object.create(null),this._layers=Object.create(null),this.update(re,[],he)}update(re,he,_e){this._options=_e;for(const Oe of re)this._layerConfigs[Oe.id]=Oe,(this._layers[Oe.id]=l.dR(Oe,this.scope,null,this._options)).compileFilter(_e),this.keyCache[Oe.id]&&delete this.keyCache[Oe.id];for(const Oe of he)delete this.keyCache[Oe],delete this._layerConfigs[Oe],delete this._layers[Oe];this.familiesBySource=Object.create(null);const je=function(Oe,ze){const Qe=Object.create(null);for(let Je=0;Jethis._layers[wt.id]),Qe=ze[0];if(Qe.visibility==="none")continue;Qe.prepare();const Xe=Qe.source||"";let Je=this.familiesBySource[Xe];Je||(Je=this.familiesBySource[Xe]=Object.create(null));const rt=Qe.sourceLayer||"_geojsonTileLayer";let It=Je[rt];It||(It=Je[rt]=[]),It.push(ze)}}}class Re extends l.P{constructor(re,he,_e,je,Oe){super(re,he),this.angle=je,this.z=_e,Oe!==void 0&&(this.segment=Oe)}clone(){return new Re(this.x,this.y,this.z,this.angle,this.segment)}}function Ie(ye,re,he,_e,je){if(re.segment===void 0)return!0;let Oe=re,ze=re.segment+1,Qe=0;for(;Qe>-he/2;){if(ze--,ze<0)return!1;Qe-=ye[ze].dist(Oe),Oe=ye[ze]}Qe+=ye[ze].dist(ye[ze+1]),ze++;const Xe=[];let Je=0;for(;Qe_e;)Je-=Xe.shift().angleDelta;if(Je>je)return!1;ze++,Qe+=rt.dist(It)}return!0}function Te(ye){let re=0;for(let he=0;heJe){const Ot=(Je-Xe)/St,pr=l.aw(It.x,wt.x,Ot),Ht=l.aw(It.y,wt.y,Ot),er=new Re(pr,Ht,0,wt.angleTo(It),rt);return!ze||Ie(ye,er,Qe,ze,re)?er:void 0}Xe+=St}}function ke(ye,re,he,_e,je,Oe,ze,Qe,Xe){const Je=ge(_e,Oe,ze),rt=$e(_e,je),It=rt*ze,wt=ye[0].x===0||ye[0].x===Xe||ye[0].y===0||ye[0].y===Xe;return re-It=0&&un=0&&Zn=0&&wt+Je<=rt){const an=new Re(un,Zn,0,Zt,Ot);_e&&!Ie(ye,an,Oe,_e,je)||St.push(an)}}It+=er}return Qe||St.length||ze||(St=Ae(ye,It/2,he,_e,je,Oe,ze,!0,Xe)),St}l.fO(Re,"Anchor");class He{constructor(){this.scale=1,this.fontStack="",this.image=null}static forText(re,he){const _e=new He;return _e.scale=re||1,_e.fontStack=he,_e}static forImage(re){const he=new He;return he.image=re,he}}class ot{constructor(){this.text="",this.sectionIndex=[],this.sections=[],this.imageSectionID=null}static fromFeature(re,he,_e,je=1){const Oe=new ot;for(let ze=0;ze=0&&_e>=re&&vt[this.text.charCodeAt(_e)];_e--)he--;this.text=this.text.substring(re,he),this.sectionIndex=this.sectionIndex.slice(re,he)}substring(re,he){const _e=new ot;return _e.text=this.text.substring(re,he),_e.sectionIndex=this.sectionIndex.slice(re,he),_e.sections=this.sections,_e}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((re,he)=>Math.max(re,this.sections[he].scale),0)}addTextSection(re,he){this.text+=re.text,this.sections.push(He.forText(re.scale,re.fontStack||he));const _e=this.sections.length-1;for(let je=0;je=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function nt(ye,re){if(!ye.image)return!1;const he=re.get(ye.image.toString());return!!he&&he.sdf}function tt(ye,re,he,_e,je,Oe,ze,Qe,Xe,Je,rt,It,wt,St,Ot=1,pr=1){const Ht=ot.fromFeature(ye,je,Ot,pr);It===l.dy.vertical&&Ht.verticalizePunctuation(wt);const er=Ht.toString();if(function(an,on){const Ln=an.sections.findIndex(wn=>nt(wn,on));if(Ln===-1)return;l.w(`SDF image ${an.sections[Ln].image.id.name} is not supported in text-field`);const ui=an.sections.map(wn=>nt(wn,on));let di="";const Un=[];for(let wn=0;wn0&&Yl>Ma&&(Ma=Yl)}else{const rl=Ln[bl.fontStack];if(!rl)continue;rl[xc]&&(Dl=rl[xc]);const Kl=on[bl.fontStack];if(!Kl)continue;const nl=Kl.glyphs[xc];if(!nl)continue;if(Zs=nl.metrics,fu=xc!==8203?l.dl:0,Ts){const Oa=Kl.ascender!==void 0?Math.abs(Kl.ascender):0,Yl=Kl.descender!==void 0?Math.abs(Kl.descender):0,Aa=(Oa+Yl)*ta;qiOe)&&(Oe=Ot.x),(!St||Ot.y>ze)&&(ze=Ot.y)}const Xe=Math.min(Oe-_e,ze-je);let Je=Xe/2;const rt=new l.fW([],tr);if(Xe===0)return new l.P(_e,je);for(let St=_e;StIt.d||!It.d)&&(It=St,he&&console.log("found best %d after %d probes",Math.round(1e4*St.d)/1e4,wt)),St.max-It.d<=re||(Je=St.h/2,rt.push(new Qt(St.p.x-Je,St.p.y-Je,Je,ye)),rt.push(new Qt(St.p.x+Je,St.p.y-Je,Je,ye)),rt.push(new Qt(St.p.x-Je,St.p.y+Je,Je,ye)),rt.push(new Qt(St.p.x+Je,St.p.y+Je,Je,ye)),wt+=4)}return he&&(console.log(`num probes: ${wt}`),console.log(`best distance: ${It.d}`)),It.p}function tr(ye,re){return re.max-ye.max}class Qt{constructor(re,he,_e,je){this.p=new l.P(re,he),this.h=_e,this.d=function(Oe,ze){let Qe=!1,Xe=1/0;for(let Je=0;JeOe.y!=pr.y>Oe.y&&Oe.x<(pr.x-Ot.x)*(Oe.y-Ot.y)/(pr.y-Ot.y)+Ot.x&&(Qe=!Qe),Xe=Math.min(Xe,l.fX(Oe,Ot,pr))}}return(Qe?1:-1)*Math.sqrt(Xe)}(this.p,je),this.max=this.d+this.h*Math.SQRT2}}const zt=Object.keys;function Vr(ye){return ye.imagePrimary!==void 0&&ye.top!==void 0&&ye.bottom!==void 0&&ye.left!==void 0&&ye.right!==void 0}function Jr(ye){return!ye.imagePrimary.stretchX}function Fn(ye){return!ye.imagePrimary.stretchY}function Ar(ye){return{width:ye.right-ye.left,height:ye.bottom-ye.top}}const Tn=Number.POSITIVE_INFINITY;function mn(ye,re,he,_e,je,Oe){const ze=Vr(ye)&&ye.collisionPadding?ye.collisionPadding:[0,0,0,0],Qe={top:ye.top-ze[1],bottom:ye.bottom+ze[3],left:ye.left-ze[0],right:ye.right+ze[2],scaled:!1};return _e!==void 0&&function(Xe,Je){Xe.top*=Je,Xe.bottom*=Je,Xe.left*=Je,Xe.right*=Je,Xe.scaled=!0}(Qe,_e),Oe&&(Qe.left+=Oe[0],Qe.right+=Oe[0],Qe.top+=Oe[1],Qe.bottom+=Oe[1]),he&&function(Xe,Je,rt){if(!Je)return;const It=l.aF(Je),wt=new l.P(rt?rt[0]:0,rt?rt[1]:0),St=new l.P(Xe.left,Xe.top),Ot=new l.P(Xe.right,Xe.top),pr=new l.P(Xe.left,Xe.bottom),Ht=new l.P(Xe.right,Xe.bottom);St._rotateAround(It,wt),Ot._rotateAround(It,wt),pr._rotateAround(It,wt),Ht._rotateAround(It,wt),Xe.left=Math.min(St.x,Ot.x,pr.x,Ht.x),Xe.right=Math.max(St.x,Ot.x,pr.x,Ht.x),Xe.top=Math.min(St.y,Ot.y,pr.y,Ht.y),Xe.bottom=Math.max(St.y,Ot.y,pr.y,Ht.y)}(Qe,he,je),re?{top:Math.min(re.top,Qe.top),bottom:Math.max(re.bottom,Qe.bottom),left:Math.min(re.left,Qe.left),right:Math.max(re.right,Qe.right),scaled:re.scaled||Qe.scaled}:Qe}function li(ye,re,he,_e,je,Oe,ze,Qe=1,Xe,Je,rt,It,wt,St,Ot,pr,Ht){ye.createArrays(),ye.tilePixelRatio=l.ac/(512*ye.overscaling),ye.compareText={},ye.iconsNeedLinear=!1;const er=ye.layers[0].layout,Zt={};Zt.scaleFactor=Qe,Zt.textSizeScaleRange=er.get("text-size-scale-range"),Zt.iconSizeScaleRange=er.get("icon-size-scale-range");const[Rr,un]=Zt.textSizeScaleRange,[Zn,an]=Zt.iconSizeScaleRange;Zt.textScaleFactor=l.bb(Zt.scaleFactor,Rr,un),Zt.iconScaleFactor=l.bb(Zt.scaleFactor,Zn,an);const on=ye.layers[0].getLayoutPropertyValue("text-size"),Ln=ye.layers[0].getLayoutPropertyValue("icon-size");if(ye.textSizeData.kind==="composite"){const{minZoom:en,maxZoom:ai}=ye.textSizeData;Zt.compositeTextSizes=[on.possiblyEvaluate(new l.au(en,{worldview:rt}),Oe),on.possiblyEvaluate(new l.au(ai,{worldview:rt}),Oe)]}if(ye.iconSizeData.kind==="composite"){const{minZoom:en,maxZoom:ai}=ye.iconSizeData;Zt.compositeIconSizes=[Ln.possiblyEvaluate(new l.au(en,{worldview:rt}),Oe,It),Ln.possiblyEvaluate(new l.au(ai,{worldview:rt}),Oe,It)]}const{maxzoom:ui}=ye.layers[0],di=ui!=null?Math.min(ze+1,ui):ze+1;Zt.layoutTextSize=on.possiblyEvaluate(new l.au(di,{worldview:rt}),Oe),Zt.layoutIconSize=Ln.possiblyEvaluate(new l.au(di,{worldview:rt}),Oe,It),Zt.textMaxSize=on.possiblyEvaluate(new l.au(18,{worldview:rt}),Oe);const Un=er.get("symbol-placement"),wn=er.get("text-rotation-alignment")==="map"&&Un!=="point",ri=er.get("text-size");let Fi=!1;const vi=[],vs=wt!=null&&wt!==0;for(const en of ye.features){if(vs&&en.properties&&pr&&pr(en.properties,wt))continue;let ai=65535;if(ye.hdExt&&en.properties&&Object.hasOwn(en.properties,l.fY)){const Zs=+en.properties[l.fY];if(!Number.isNaN(Zs)){const Dl=ye.hdExt.resolveRoadElevation(en,Zs);if(Dl==="defer")continue;ai=Dl}}const Si=er.get("text-font").evaluate(en,{},Oe).join(","),Ta=Math.max(Zt.layoutTextSize.evaluate(en,{},Oe),ri.evaluate(en,{},Oe))*Zt.textScaleFactor,tl=Zt.layoutIconSize.evaluate(en,{},Oe,It)*Zt.iconScaleFactor,Es={horizontal:{},vertical:void 0},Ts=en.text;let Gs,Rs=[0,0];if(Ts){const Zs=Ts.toString(),Dl=er.get("text-letter-spacing").evaluate(en,{},Oe)*l.dl,Vc=er.get("text-line-height").evaluate(en,{},Oe)*l.dl,fu=l.fZ(Zs)?Dl:0,Ml=er.get("text-anchor").evaluate(en,{},Oe),Vu=er.get("text-variable-anchor");if(!Vu){const Oa=er.get("text-radial-offset").evaluate(en,{},Oe);if(Oa)Rs=l.dA(Ml,[Oa*l.dl,Tn]);else{const Yl=er.get("text-offset").evaluate(en,{},Oe);Rs=[Yl[0]*l.dl,Yl[1]*l.dl]}}let wl=wn?"center":er.get("text-justify").evaluate(en,{},Oe);const rl=Un==="point",Kl=rl?er.get("text-max-width").evaluate(en,{},Oe)*l.dl:1/0,nl=Oa=>{ye.allowVerticalPlacement&&l.f_(Zs)&&(Es.vertical=tt(Ts,re,he,je,Si,Kl,Vc,Ml,Oa,fu,Rs,l.dy.vertical,!0,Ta,Xe,Zt.textScaleFactor))};if(!wn&&Vu){const Oa=wl==="auto"?Vu.map(Aa=>l.dB(Aa)):[wl];let Yl=!1;for(let Aa=0;Aa0?er/Xe:1;Zt&&(ye.iconBBox=mn(Zt,ye.iconBBox,Ht,Zn!==1?Zn:void 0)),Rr&&(ye.iconVerticalBBox=mn(Rr,ye.iconVerticalBBox,Ht+90,Zn!==1?Zn:void 0))}function si(ye,re,he,_e,je,Oe,ze,Qe){let Xe=null;const Je=re.getAppearanceValueAndResolveTokens(he,"icon-image",_e,je,Qe);if(Je){const rt=ye.getResolvedImageFromTokens(Je),It=he.hasLayoutProperty("icon-size")?he.getUnevaluatedLayoutProperty("icon-size"):re.getLayoutPropertyValue("icon-size"),wt=l.g7(ye.zoom,It,ye.worldview,Qe),St=l.f$(rt,wt,It,je,ye.zoom,_e,ye.pixelRatio,ze,ye.worldview,Qe);Xe=Oe.get(St.iconPrimary.toString())}return Xe}function ss(ye,re,he,_e,je,Oe,ze,Qe,Xe,Je){const{appearanceTextOffset:rt,appearanceTextRotate:It,appearanceTextSize:wt}=l.g5(he,re,_e,je,Oe,ze,Qe),St=wt/Qe,Ot=[(rt[0]-Oe[0])*St,(rt[1]-Oe[1])*St],pr=Ot[0]!==0||Ot[1]!==0;Xe&&(ye.textBBox=mn(Xe,ye.textBBox,It,St,rt,pr?Ot:void 0)),Je&&(ye.textVerticalBBox=mn(Je,ye.textVerticalBBox,It+90,St,rt,pr?Ot:void 0))}function ps(ye,re,he,_e,je,Oe,ze,Qe){if(!ye||!ye.usvg)return;const Xe=Ar(he),Je=Ar(_e),rt=je!=="both"&&je!=="width"||!Jr(he)?1:Je.width/Xe.width,It=je!=="both"&&je!=="height"||!Fn(he)?1:Je.height/Xe.height;re.scaleSelf(rt,It);const wt=re.toString();Oe.set(wt,re),ze.set(wt,ye);const{imagePosition:St}=l.g2(wt,ye,l.g3);Qe.set(wt,St)}function Mi(ye,re,he){if(!re)return;const _e=he.get(ye.toString()),je=he.get(re.toString());_e&&je&&(_e.paddedRect.w===je.paddedRect.w&&_e.paddedRect.h===je.paddedRect.h||l.w(`Mismatch in icon variant sizes: ${ye.toString()} and ${re.toString()}`),_e.usvg!==je.usvg&&l.w(`Mismatch in icon variant image types: ${ye.id} and ${re.id}`))}function gs(ye,re,he,_e,je,Oe,ze,Qe,Xe,Je){ye.iconAtlasPositions=Je.iconPositions;const{featureData:rt,sizes:It,textAlongLine:wt,symbolPlacement:St,coveragePolygons:Ot,coverageTileZoom:pr,symbolAnchorInFrcCoverage:Ht}=re,er=re.hasAnySecondaryIcon||ye.hasAnySecondaryIcon;for(const Zt of rt){const{shapedIcon:Rr,verticallyShapedIcon:un,feature:Zn,shapedTextOrientations:an,shapedText:on,layoutTextSize:Ln,textOffset:ui,isSDFIcon:di,iconPrimary:Un,iconSecondary:wn,iconTextFit:ri,iconOffset:Fi,iconCollisionBounds:vi,iconVerticalCollisionBounds:vs,textCollisionBounds:en,textVerticalCollisionBounds:ai,elevationFeatureIndex:Si}=Zt;ma(Rr,Je.iconPositions,Un,wn),ma(un,Je.iconPositions,Un,wn),Ki(an,Je.iconPositions),Mi(Un,wn,Je.iconPositions),(on||Rr)&&mo(ye,Zn,an,Rr,un,Xe,It,Ln,0,ui,di,_e,je,ze,Qe,er,ri,Fi,wt,St,vi,vs,en,ai,0,Ot,pr,Ht,Si)}he&&ye.generateCollisionDebugBuffers(Oe,ye.collisionBoxArray,It.textScaleFactor),ye.layers[0].getAppearances().length===0&&(ye.iconAtlasPositions=void 0),ye.text.uboBinder&&ye.text.uboBinder.finalize(),ye.icon.uboBinder&&ye.icon.uboBinder.finalize()}function ma(ye,re,he,_e){if(!ye)return;const je=re.get(he.toString());if(je&&(ye.imagePrimary=je),_e){const Oe=re.get(_e.toString());ye.imageSecondary=Oe}}function Ki(ye,re){for(const he in ye.horizontal)Hr(ye.horizontal[he],re);Hr(ye.vertical,re)}function Hr(ye,re){if(ye){for(const he of ye.positionedLines)for(const _e of he.positionedGlyphs)if(_e.image!==null){const je=_e.image.toString();_e.rect=re.get(je).paddedRect}}}function ci(ye,re,he,_e,je,Oe,ze,Qe,Xe){const Je=Da(Oe.horizontal)||Oe.vertical,rt=he.get("icon-text-fit-padding").evaluate(_e,{},je);let It,wt=re;return re&&Xe!=="none"&&(ye.allowVerticalPlacement&&Oe.vertical&&(It=l.g1(re,Oe.vertical,Xe,rt,Qe,ze)),Je&&(wt=l.g1(re,Je,Xe,rt,Qe,ze))),{defaultShapedIcon:wt,verticallyShapedIcon:It}}function mo(ye,re,he,_e,je,Oe,ze,Qe,Xe,Je,rt,It,wt,St,Ot,pr,Ht,er,Zt,Rr,un,Zn,an,on,Ln,ui,di,Un,wn=65535){const ri=ze.textMaxSize.evaluate(re,{},wt)*ze.textScaleFactor,Fi=ye.layers[0].layout,vi=l.dl,vs=Qe/vi,en=Da(he.horizontal)||he.vertical,ai=ye.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),Si=ye.getAppearanceFeatureData(re.index);(Ht!=="none"||ai)&&Si&&(Si.textShaping=en,Si.iconTextFitPadding=Fi.get("icon-text-fit-padding").evaluate(re,{},wt),Si.fontScale=vs,Si.textScaleFactor=ze.textScaleFactor);const Ta=St.name==="globe",tl=ye.tilePixelRatio*ri/vi,Es=(pa=ye.overscaling,ye.zoom>18&&pa>2&&(pa>>=1),Math.max(l.ac/(512*pa),1)*Fi.get("symbol-spacing")),Ts=Fi.get("text-padding")*ye.tilePixelRatio,Gs=Fi.get("icon-padding")*ye.tilePixelRatio,Rs=l.aF(Fi.get("text-max-angle")),ko=Fi.get("icon-rotation-alignment")==="map"&&Rr!=="point",yc=Es/2;var pa;ye.hasAnyIconTextFit===!1&&Ht!=="none"&&(ye.hasAnyIconTextFit=!0);const so=(ys,as,Rl)=>{if(as.x<0||as.x>=l.ac||as.y<0||as.y>=l.ac||ui&&ui.length>0&&re.properties&&Un&&Un(ui,re.properties,as,wt,di))return;let Ma=null;if(Ta){const{x:qi,y:Wa,z:Ll}=St.projectTilePoint(as.x,as.y,Rl);Ma={anchor:new Re(qi,Wa,Ll,0,void 0),up:St.upVector(Rl,as.x,as.y)}}(function(qi,Wa,Ll,vl,bl,Wd,xc,ta,Zs,Dl,Vc,fu,Ml,Vu,wl,rl,Kl,nl,Oa,Yl,Aa,ca,ga,Zl,Ka,hd,Kr,l0,Vn,vx,bx,Uw,yf){const Ah=qi.addToLineVertexArray(Wa,vl);let Xl,kh,il,Yr,Ei,Bi,_c,xf=0,Pi=0,mp=0,pp=0,sm=-1,Bo=-1;const Xs={};let Ng=l.dK("");const Kd=Ll?Ll.anchor:Wa,_f=l0!=="none",gp=l.g8(Zs,"icon"),Rg=l.g8(Zs,"text"),yp=gp||Rg?l.g9(qi.getTileTransform(Ka),Wa.x,Wa.y):0,sl=gp?yp:0,Io=Rg?yp:0,Ol=Zs.layout.get("icon-rotate").evaluate(Aa,{},Ka)+sl,Lg=Zs.layout.get("text-rotate").evaluate(Aa,{},Ka)+Io,vf=vx?sl:Ol,zo=Uw?Io:Lg;let qu=0,qc=0;if(Zs.getLayoutPropertyValue("text-radial-offset").value===void 0){const kn=Zs.layout.get("text-offset").evaluate(Aa,{},Ka);qu=kn[0]*l.dl,qc=kn[1]*l.dl}else qu=Zs.layout.get("text-radial-offset").evaluate(Aa,{},Ka)*l.dl,qc=Tn;if(qi.allowVerticalPlacement&&bl.vertical){const kn=bl.vertical;if(wl)Bi=Vi(kn),ta&&(_c=Vi(ta));else{const al=Lg+90,Gc=bx?sl:al;il=pn(Dl,Kd,Wa,Vc,fu,Ml,kn,Vu,yf?Io:al,rl,yf),ta&&(Yr=pn(Dl,Kd,Wa,Vc,fu,Ml,ta,nl,Gc,null,bx))}}if(Wd){const kn=l.ga(Wd,Ol,ga,_f,ca.iconScaleFactor),al=ta?l.ga(ta,Ol,ga,_f,ca.iconScaleFactor):void 0;kh=pn(Dl,Kd,Wa,Vc,fu,Ml,Wd,nl,vf,null,vx);const Gc=function(Vw,Ih,qw,u0,Ql,KA,Sx,mu,vc){const Jl=Vw.layers[0],Fa=Jl.appearances;let pu=Ih.length;if(qw&&(pu=Math.max(pu,qw.length)),Fa.length===0)return pu;const[YA,ZA]=u0.get("icon-size-scale-range"),XA=l.bb(1,YA,ZA);for(const d0 of Fa)if(d0.hasLayoutProperty("icon-image")){const Gw=si(Vw,Jl,d0,Ql,KA,Sx,XA,vc);Gw&&(pu=Math.max(pu,l.gc(Gw)))}return pu}(qi,kn,al,Zs.layout,Aa,Ka,qi.iconAtlasPositions,0,Zl);xf=4*Gc;const Dg=Zs.layout.get("icon-size").evaluate(Aa,{},Ka,Zl),c0=ca.compositeIconSizes?ca.compositeIconSizes[0].evaluate(Aa,{},Ka,Zl):0,wx=ca.compositeIconSizes?ca.compositeIconSizes[1].evaluate(Aa,{},Ka,Zl):0,As=l.gb(qi.layerIds[0],qi.iconSizeData,Dg,Wd.imagePrimary.usvg?1:ca.iconScaleFactor,c0,wx);qi.addSymbols(qi.icon,kn,As,Yl,Oa,Aa,void 0,Ll,Wa,Ah.lineStartIndex,Ah.lineLength,-1,Zl,Ka,hd,Kr,qi.symbolInstances.length,Gc),sm=qi.icon.placedSymbolArray.length-1,al&&(Pi=4*Gc,qi.addSymbols(qi.icon,al,As,Yl,Oa,Aa,l.dy.vertical,Ll,Wa,Ah.lineStartIndex,Ah.lineLength,-1,Zl,Ka,hd,Kr,qi.symbolInstances.length,Gc),Bo=qi.icon.placedSymbolArray.length-1)}for(const kn in bl.horizontal){const al=kn,Gc=bl.horizontal[al];Xl||(Ng=l.dK(Gc.text),wl?Ei=Vi(Gc):Xl=pn(Dl,Kd,Wa,Vc,fu,Ml,Gc,Vu,zo,rl,Uw));const Dg=Gc.positionedLines.length===1;if(mp+=_r(qi,Ll,Wa,Gc,xc,Zs,wl,Aa,rl,Ah,bl.vertical?l.dy.horizontal:l.dy.horizontalOnly,Dg?zt(bl.horizontal):[al],Xs,sm,ca,Zl,Ka,qi.symbolInstances.length,Lg,hd),Dg)break}bl.vertical&&(pp+=_r(qi,Ll,Wa,bl.vertical,xc,Zs,wl,Aa,rl,Ah,l.dy.vertical,["vertical"],Xs,Bo,ca,Zl,Ka,qi.symbolInstances.length,Lg,hd));let ra=-1;const xp=(kn,al)=>kn?Math.max(kn,al):al;ra=xp(Ei,ra),ra=xp(Bi,ra),ra=xp(_c,ra);const fd=ra>-1?1:0;qi.glyphOffsetArray.length>=65535&&l.w("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),Aa.sortKey!==void 0&&qi.addToSortKeyRanges(qi.symbolInstances.length,Aa.sortKey),qi.symbolInstances.emplaceBack(Wa.x,Wa.y,Kd.x,Kd.y,Kd.z,Xs.right>=0?Xs.right:-1,Xs.center>=0?Xs.center:-1,Xs.left>=0?Xs.left:-1,Xs.vertical>=0?Xs.vertical:-1,sm,Bo,Ng,Xl!==void 0?Xl:qi.collisionBoxArray.length,Xl!==void 0?Xl+1:qi.collisionBoxArray.length,il!==void 0?il:qi.collisionBoxArray.length,il!==void 0?il+1:qi.collisionBoxArray.length,kh!==void 0?kh:qi.collisionBoxArray.length,kh!==void 0?kh+1:qi.collisionBoxArray.length,Yr||qi.collisionBoxArray.length,Yr?Yr+1:qi.collisionBoxArray.length,Vc,mp,pp,xf,Pi,fd,0,qu,qc,ra,0,_f?1:0,Vn)})(ye,as,Ma,ys,he,_e,Oe,je,ye.layers[0],ye.collisionBoxArray,re.index,re.sourceLayerIndex,ye.index,Ts,Zt,Je,0,Gs,ko,er,re,ze,rt,It,wt,Ot,pr,Ht,wn,un,Zn,an,on)};if(Rr==="line")for(const ys of l.dh(re.geometry,0,0,l.ac,l.ac)){const as=ke(ys,Es,Rs,he.vertical||en,_e,vi,tl,ye.overscaling,l.ac);for(const Rl of as)en&&Yi(ye,en.text,yc,Rl)||so(ys,Rl,wt)}else if(Rr==="line-center"){for(const ys of re.geometry)if(ys.length>1){const as=we(ys,Rs,he.vertical||en,_e,vi,tl);as&&so(ys,as,wt)}}else if(re.type==="Polygon")for(const ys of l.g6(re.geometry,0)){const as=Gr(ys,16);so(ys[0],new Re(as.x,as.y,0,0,void 0),wt)}else if(re.type==="LineString")for(const ys of re.geometry)so(ys,new Re(ys[0].x,ys[0].y,0,0,void 0),wt);else if(re.type==="Point")for(const ys of re.geometry)for(const as of ys)so([as],new Re(as.x,as.y,0,0,void 0),wt)}function _r(ye,re,he,_e,je,Oe,ze,Qe,Xe,Je,rt,It,wt,St,Ot,pr,Ht,er,Zt,Rr){const un=l.gd(he,_e,Xe,Oe,ze,Qe,je,ye.allowVerticalPlacement,Zt,Ot.textScaleFactor),Zn=Oe.layout.get("text-size").evaluate(Qe,{},Ht),an=Ot.compositeTextSizes?Ot.compositeTextSizes[0].evaluate(Qe,{},Ht):0,on=Ot.compositeTextSizes?Ot.compositeTextSizes[1].evaluate(Qe,{},Ht):0,Ln=l.gb(ye.layerIds[0],ye.textSizeData,Zn,Ot.textScaleFactor,an,on);ye.addSymbols(ye.text,un,Ln,Xe,ze,Qe,rt,re,he,Je.lineStartIndex,Je.lineLength,St,pr,Ht,Rr,!1,er,un.length);for(const ui of It)wt[ui]=ye.text.placedSymbolArray.length-1;return 4*un.length}function Da(ye){for(const re in ye)return ye[re];return null}function pn(ye,re,he,_e,je,Oe,ze,Qe,Xe,Je,rt){let It,wt,St,Ot;if(It=rt?rt.top:ze.top,wt=rt?rt.bottom:ze.bottom,St=rt?rt.left:ze.left,Ot=rt?rt.right:ze.right,Vr(ze)&&ze.collisionPadding){const pr=ze.collisionPadding;St-=pr[0],It-=pr[1],Ot+=pr[2],wt+=pr[3]}if(Xe){const pr=new l.P(St,It),Ht=new l.P(Ot,It),er=new l.P(St,wt),Zt=new l.P(Ot,wt),Rr=l.aF(Xe);let un=new l.P(0,0);Je&&(un=new l.P(Je[0],Je[1])),pr._rotateAround(Rr,un),Ht._rotateAround(Rr,un),er._rotateAround(Rr,un),Zt._rotateAround(Rr,un),St=Math.min(pr.x,Ht.x,er.x,Zt.x),Ot=Math.max(pr.x,Ht.x,er.x,Zt.x),It=Math.min(pr.y,Ht.y,er.y,Zt.y),wt=Math.max(pr.y,Ht.y,er.y,Zt.y)}return ye.emplaceBack(re.x,re.y,re.z,he.x,he.y,St,It,Ot,wt,Qe,_e,je,Oe),ye.length-1}function Vi(ye){Vr(ye)&&ye.collisionPadding&&(ye.top-=ye.collisionPadding[1],ye.bottom+=ye.collisionPadding[3]);const re=ye.bottom-ye.top;return re>0?Math.max(10,re):null}function Yi(ye,re,he,_e){const je=ye.compareText;if(re in je){const Oe=je[re];for(let ze=Oe.length-1;ze>=0;ze--)if(_e.dist(Oe[ze])=re.maxzoom||re.visibility==="none")}parse(re,he,_e,je,Oe,ze){this._parseAfterHD(re,he,_e,je,Oe,ze)}_parseAfterHD(re,he,_e,je,Oe,ze){let Qe;if(this.status="parsing",this.data=re,this.renderSourceType===l.b_.HdRoadCoverage){const Ht=re.layers[l.c0];Qe=Ht&&T?T(Ht):[]}this.collisionBoxArray=new l.bE;const Xe=new l.gg(Object.keys(re.layers).sort()),Je=new l.fJ(this.tileID,this.promoteId);Je.bucketLayerIDs=[];const rt={},It=new l.gh(256,256),wt={featureIndex:Je,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:It,availableImages:_e,brightness:this.brightness,scaleFactor:this.scaleFactor,showElevationIdDebug:this.showElevationIdDebug,elevationFeatures:void 0,elevationParams:this.elevation,crossSourceElevationEnabled:this.crossSourceElevationEnabled,terrainEnabled:this.terrainEnabled,activeFloors:void 0};this.indoor&&P&&(wt.activeFloors=P(re,this.indoor,Oe,this.canonical));const St=[],Ot=he.familiesBySource[this.source];if(this.deferRoadStructure=!1,this.renderSourceType!==l.b_.HdRoadCoverage&&this.frcCoverage!=null&&!this.frcCoverage.resolved&&this.frcCoverage.frcMask===null){for(const Ht in Ot)if(l.gi&&l.gi(this.frcCoverage.sourceLayers,this.source,Ht)){this.deferRoadStructure=!0;break}}for(const Ht in Ot){const er=re.layers[Ht];if(!er)continue;let Zt=!1,Rr=!1,un=!1,Zn=!1;for(const Un of Ot[Ht])Un[0].type==="symbol"?Zt=!0:Un[0].type==="fill-extrusion"?Rr=!0:un=!0,Un[0].is3D()&&Un[0].type!=="model"&&(Zn=!0);if(this.extraShadowCaster&&!Zn||this.renderSourceType===l.b_.Symbol&&!Zt||this.renderSourceType===l.b_.FillExtrusion&&!Rr||(this.renderSourceType===l.b_.Other||this.renderSourceType===l.b_.HdRoadCoverage)&&!un)continue;const an=this.frcCoverage!=null&&!!l.gi&&l.gi(this.frcCoverage.sourceLayers,this.source,Ht);if(this.deferRoadStructure&&an)continue;er.version===1&&l.w(`Vector tile source "${this.source}" layer "${Ht}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const on=Xe.encode(Ht),Ln=[],ui=this.localizableLayerIds&&this.localizableLayerIds.has(Ht);let di=!1;for(let Un=0,wn=0;Unl.m(vi.id,vi.scope)));const Fi=()=>{Wr(Un,this.zoom,wt.brightness,_e,this.worldview,wt.activeFloors);const vi=rt[wn.id]=wn.createBucket({index:ri,layers:Un,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:on,sourceLayerName:Ht,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:je,worldview:this.worldview,localizable:ui,availableImages:_e,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords});Z&&Z(vi,this.frcCoverage?this.frcCoverage.sourceLayers:null),vi.populate(Ln,wt,this.tileID.canonical,this.tileTransform);const vs=vi instanceof l.bF&&vi.hasRTLText&&l.gk();if(vs)return vs.then(Fi)};if(wn.mayUse("HD")||wn.mayUse("Standard"))St.push(wn.prepare().then(()=>Fi()));else{const vi=Fi();vi&&St.push(vi)}}}const pr=()=>{It.trim();const Ht=!(!wt.elevationFeatures||!wt.elevationFeatures.some(wn=>wn.heightRange.min<0));let er,Zt,Rr,un,Zn,an,on,Ln=wt.elevationFeatures;this.crossSourceElevationEnabled&&v&&(Ln=Ln||v(re,this.canonical)||[]);const ui={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},di=()=>{if(er)return this.status="done",ze(er);if(this.extraShadowCaster){this.status="done";const wn=Object.values(rt).filter(ri=>!ri.isEmpty());ze(null,{buckets:wn,containsHdExt:at(wn),containsStandardExt:yt(wn),featureIndex:Je,collisionBoxArray:null,hasTunnelGeometry:Ht,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:wt.brightness,hasDeferredElevationFeatures:!!Q&&Q(rt),parsedElevationFeatures:Ln,glyphMap:null,iconMap:null,glyphPositions:null})}else if(Zt&&Rr&&un&&on){const ri=new Ke(Zt),Fi=new Map;for(const[vs,en]of Rr.entries()){const{imagePosition:ai}=l.g2(vs,en,l.g3);Fi.set(vs,ai)}const vi={};for(const vs in rt){const en=rt[vs];if(en instanceof l.bF){Wr(en.layers,this.zoom,wt.brightness,_e,this.worldview,wt.activeFloors);const ai=rr(this.frcCoverage,this.source,en.layers[0].sourceLayer);vi[vs]=li(en,Zt,ri.positions,Rr,Fi,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Zn,this.worldview,_e,ai.frcMask,ai.polygons,ai.tileZoom,l.gj||null,j||null)}}Zn.size||an.size?this.rasterizeTask=Oe.sendCancelable("rasterizeImages",{scope:this.scope,iconTasks:Zn,patternTasks:an},{},(vs,en)=>{if(!vs)for(const[ai,Si]of en.entries())Rr.has(ai)&&Rr.set(ai,Object.assign(Rr.get(ai),{data:Si})),un.has(ai)&&un.set(ai,Object.assign(un.get(ai),{data:Si}));Un(vi,ri,void 0,on)}):Un(vi,ri,void 0,on)}},Un=(wn,ri,Fi,vi)=>{const vs=Rr.size>0||un.size>0,en=Object.keys(wn).length>0;if(!vs&&!en){this.status="done";const Si=Object.values(rt).filter(Ta=>!Ta.isEmpty());return void ze(null,{buckets:Si,containsHdExt:at(Si),containsStandardExt:yt(Si),featureIndex:Je,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Ht,glyphAtlasImage:ri.image,lineAtlas:It,imageAtlas:null,brightness:wt.brightness,hasDeferredRoadStructure:this.deferRoadStructure,frcCoveragePolygons:Qe,hasDeferredElevationFeatures:!!Q&&Q(rt),parsedElevationFeatures:Ln})}const ai=(Si,Ta)=>{for(const Es in rt){const Ts=rt[Es];if(Es in wn)gs(Ts,wn[Es],this.showCollisionBoxes,_e,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,Rr,Ta);else if(Ts.hasPattern&&(Ts instanceof l.bG||Ts instanceof l.bL||Ts instanceof l.aN)){Wr(Ts.layers,this.zoom,wt.brightness,_e,this.worldview,wt.activeFloors);const Gs=Object.fromEntries(Ta.patternPositions);Ts.addFeatures(wt,this.tileID.canonical,Gs,_e,this.tileTransform,this.brightness)}}this.status="done";const tl=Object.values(rt).filter(Es=>!Es.isEmpty());ze(null,{buckets:tl,containsHdExt:at(tl),containsStandardExt:yt(tl),featureIndex:Je,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Ht,glyphAtlasImage:ri.image,lineAtlas:It,imageAtlas:Si,brightness:wt.brightness,hasDeferredRoadStructure:this.deferRoadStructure,frcCoveragePolygons:Qe,hasDeferredElevationFeatures:!!Q&&Q(rt),parsedElevationFeatures:Ln})};if(vs){const Si=new Map,Ta=l.gm(Rr,Si),tl=l.gm(un,Si),Es=new l.gn(Ta,tl,vi,this.lut,this.scope,Si);Oe.send("checkAtlasCache",{descriptor:Es,scope:this.scope}).then(Ts=>{let Gs,Rs;if(Ts)Gs=new l.go(Ts.sourceHash),Rs=Ts;else{const ko=new l.gp(Rr,un,this.lut,vi,this.scope);Gs=ko,Rs=ko}ai(Gs,Rs)}).catch(Ts=>{Ts.name!=="AbortError"&&l.w(`[Worker] Error checking atlas cache: ${Ts.message}`);const Gs=new l.gp(Rr,un,this.lut,vi,this.scope);ai(Gs,Gs)})}else ai(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const wn=l.gl(wt.glyphDependencies,en=>Object.keys(en).map(Number)),ri={};if(this.localGlyphs)for(const en in wn)ri[en]=wn[en].filter(ai=>this.localGlyphs.supports(ai)),wn[en]=wn[en].filter(ai=>!this.localGlyphs.supports(ai));const Fi={};Object.keys(wn).length?Oe.send("getGlyphs",{uid:this.uid,stacks:wn},{metadata:ui}).then(en=>{if(!er){Zt=en;for(const ai in Fi)Object.assign(Zt[ai].glyphs,Fi[ai]);di()}}).catch(en=>{er||(er=en,di())}):Zt={},on=new Map;const vi=Array.from(wt.iconDependencies.keys()).map(en=>l.I.parse(en)),vs=Array.from(wt.patternDependencies.keys()).map(en=>l.I.parse(en));vi.length||vs.length?Oe.send("getImages",{icons:vi,patterns:vs,source:this.source,scope:this.scope,tileID:this.tileID},{metadata:ui}).then(en=>{if(!er){Rr=new Map,un=new Map,Zn=this.updateImageMapAndGetImageTaskQueue(Rr,en.images,wt.iconDependencies),an=this.updateImageMapAndGetImageTaskQueue(un,en.images,wt.patternDependencies);for(const[ai,Si]of en.versions.entries())on.set(ai,Si);di()}}).catch(en=>{er||(er=en,di())}):(Rr=new Map,un=new Map,Zn=new Map,an=new Map);for(const en in ri){const ai=Fi[en]={};for(const Si of ri[en])ai[Si]=this.localGlyphs.draw(en,Si)}}E&&E({buckets:rt,data:re,sourceLayerCoder:Xe,canonical:this.tileID.canonical,options:wt}),di()};St.length>0?Promise.allSettled(St).then(pr).catch(ze):pr()}updateParameters(re){this.scaleFactor=re.scaleFactor,this.showCollisionBoxes=re.showCollisionBoxes,this.showElevationIdDebug=re.showElevationIdDebug,this.projection=re.projection,this.brightness=re.brightness,this.tileTransform=l.bA(re.tileID.canonical,re.projection),this.extraShadowCaster=re.extraShadowCaster,this.lut=re.lut,this.worldview=re.worldview,this.indoor=re.indoor,this.frcCoverage=re.frcCoverage||null,this.elevation=re.elevation||null,this.crossSourceElevationEnabled=!!re.crossSourceElevationEnabled,this.terrainEnabled=!!re.terrainEnabled}updateImageMapAndGetImageTaskQueue(re,he,_e){const je=new Map;for(const Oe of he.keys()){const ze=_e.get(Oe)||[];for(const Qe of ze){const Xe=Qe.toString(),Je=he.get(Qe.id.toString());Je.usvg?je.has(Xe)||(je.set(Xe,Qe),re.set(Xe,{...Je})):re.set(Xe,Je)}}return je}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.abort()}}function Wr(ye,re,he,_e,je,Oe){const ze=new l.au(re,{brightness:he,worldview:je,activeFloors:Oe});for(const Qe of ye)Qe.recalculate(ze,_e)}class Nr extends l.E{constructor({actor:re,layerIndex:he,availableImages:_e,availableModels:je,isSpriteLoaded:Oe,tileProvider:ze,brightness:Qe,maxUniformBlockSizeDwords:Xe,localGlyphs:Je}){super(),this.actor=re,this.layerIndex=he,this.availableImages=_e,this.availableModels=je,this.loadVectorData=l.cY,this.tileProvider=ze,this.loading={},this.loaded={},this.deduped=new l.cW(re.scheduler),this.isSpriteLoaded=Oe,this.scheduler=re.scheduler,this.brightness=Qe,this.maxUniformBlockSizeDwords=Xe,this.localGlyphs=Je}loadTileData(re,he){if(!this.tileProvider)return this.loadVectorData(re,he);const _e=new AbortController;return this.loadTileWithProvider(this.tileProvider,re,_e,he),()=>_e.abort()}async loadTileWithProvider(re,he,_e,je){const{z:Oe,x:ze,y:Qe}=he.tileID.canonical;try{const Xe=await re.loadTile({z:Oe,x:ze,y:Qe},{request:he.request,signal:_e.signal});if(_e.signal.aborted)return;if(Xe==null){const rt=new Error("Tile not found");return rt.status=404,je(rt)}if(Xe.data==null)return je(null,null);if(Xe.data instanceof ImageBitmap)return je(new Error("Vector tiles require ArrayBuffer data"));const Je=new Headers;Xe.expires&&Je.set("expires",Xe.expires),Xe.cacheControl&&Je.set("cache-control",Xe.cacheControl),je(null,{rawData:Xe.data,headers:Je})}catch(Xe){if(_e.signal.aborted)return;je(Xe instanceof Error?Xe:new Error(String(Xe)))}}_fetchTileData(re,he){return new Promise((_e,je)=>{re.abort=this.loadTileData(he,(Oe,ze)=>{Oe?je(Oe):_e(ze)})})}async _parse(re,he){const _e=!this.isSpriteLoaded;return _e&&await this.once("isSpriteLoaded"),new Promise((je,Oe)=>{const ze=()=>re.parse(re.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(Qe,Xe)=>{Qe?Oe(Qe):je(Xe)});_e&&this.scheduler?this.scheduler.add(ze,{type:"parseTile",renderSourceType:he.renderSourceType,zoom:he.tileZoom}):ze()})}async loadTile(re){const he=re.uid,_e=re&&re.request,je=_e&&_e.collectResourceTiming,Oe=this.loading[he]=new Er(re);Oe.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,Oe.localGlyphs=this.localGlyphs;const ze=(Ot,pr)=>{const Ht=Oe.reloadCallback;Ht&&(delete Oe.reloadCallback,Ot||!pr?Ht(Ot,null):Oe.parse(Oe.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Ht))};let Qe,Xe;try{Qe=await this._fetchTileData(Oe,re)}catch(Ot){Xe=Ot}const Je=!this.loading[he];if(delete this.loading[he],Oe.cancelRasterize(),Xe||Je||!Qe){if(Oe.status="done",Je||(this.loaded[he]=Oe),Xe)throw Xe;return null}const rt=Qe.rawData;let It;Oe.vectorTile=Qe.vectorTile||new l.gq(new l.d(rt)),this.loaded=this.loaded||{},this.loaded[he]=Oe;try{It=await this._parse(Oe,re)}catch(Ot){throw ze(Ot),Ot}if(!It)return ze(null,null),null;const wt={};if(je){const Ot=g(_e);Ot.length>0&&(wt.resourceTiming=JSON.parse(JSON.stringify(Ot)))}const St={rawTileData:rt.slice(0),headers:Qe.headers,...It,...wt};return ze(null,It),St}async reloadTile(re){const he=this.loaded,_e=re.uid;if(he&&he[_e])return new Promise((je,Oe)=>{const ze=he[_e];ze.updateParameters(re);const Qe=(Xe,Je)=>{const rt=ze.reloadCallback;rt&&(delete ze.reloadCallback,ze.parse(ze.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,rt)),Xe?Oe(Xe):je(Je)};ze.status==="parsing"?ze.reloadCallback=Qe:ze.status==="done"?ze.vectorTile?ze.parse(ze.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Qe):Qe():je(void 0)})}abortTile(re){const he=re.uid,_e=this.loading[he];_e&&(_e.abort&&_e.abort(),delete this.loading[he])}removeTile(re){const he=this.loaded,_e=re.uid;he&&he[_e]&&delete he[_e]}}class Zr{constructor(re){this.tileProvider=re.tileProvider,this.loading={}}async loadTile(re){const he=re.uid,_e=new AbortController;if(this.loading[he]={cancel:()=>_e.abort()},this.tileProvider)return this.loadTileWithProvider(this.tileProvider,he,re,_e);try{const{data:je,headers:Oe}=await l.n(re.request,_e.signal);if(!je)return null;const ze=await this.decodeTile(he,je,re.encoding);return ze.headers=Oe,ze}catch(je){if(_e.signal.aborted)return null;throw je}finally{delete this.loading[he]}}async decodeTile(re,he,_e){const je=he instanceof ImageBitmap?he:await createImageBitmap(new Blob([new Uint8Array(he)],{type:"image/png"})),Oe=1-(je.width-l.gr(je.width))/2,ze=Oe<1,Qe=this.getImageData(je,Oe);je.close();const Xe=new l.gs(re,Qe,_e,ze);return Xe._buildQuadTree(),{dem:Xe,borderReady:ze}}async loadTileWithProvider(re,he,_e,je){const{z:Oe,x:ze,y:Qe}=_e.tileID.canonical;try{const Xe=await re.loadTile({z:Oe,x:ze,y:Qe},{request:_e.request,signal:je.signal});if(je.signal.aborted)return null;if(Xe==null){const It=new Error("Tile not found");throw It.status=404,It}if(Xe.data==null)return null;const Je=await this.decodeTile(he,Xe.data,_e.encoding);if(je.signal.aborted)return null;const rt=new Headers;return Xe.expires&&rt.set("expires",Xe.expires),Xe.cacheControl&&rt.set("cache-control",Xe.cacheControl),Je.headers=rt,Je}catch(Xe){if(je.signal.aborted)return null;throw Xe}finally{delete this.loading[he]}}async reloadTile(re){}abortTile(re){const he=re.uid,_e=this.loading[he];_e&&(_e.cancel(),delete this.loading[he])}removeTile(re){}getImageData(re,he){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(re.width,re.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=re.width,this.offscreenCanvas.height=re.height,this.offscreenCanvasContext.drawImage(re,0,0,re.width,re.height);const _e=this.offscreenCanvasContext.getImageData(-he,-he,re.width+2*he,re.height+2*he);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),_e}}const $r=l.gt.prototype.toGeoJSON;class qn{constructor(re){this._feature=re,this.extent=l.ac,this.type=re.type===4?1:re.type,this.properties=re.tags||{},"id"in re&&!isNaN(re.id)&&(this.id=parseInt(re.id,10))}loadGeometry(){const re=this._feature,he=[];if(re.type===4)he.push([new l.P(re.x,re.y)]);else if(re.type===1)for(let _e=0;_e(Oe-Ea)/je&&_e>(ze-Ea)/je}function wh(ye){const{id:re,geometry:he,properties:_e}=ye;if(he.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:je,coordinates:Oe}=he,ze={id:re,type:1,geometry:[],tags:_e,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},Qe=ze.geometry;if(je==="Point")Ud(Oe,Qe,ze);else if(je==="MultiPoint")for(const Xe of Oe)Ud(Xe,Qe,ze);else if(je==="LineString")ze.type=2,mf(Oe,Qe,ze);else if(je==="MultiLineString")ze.type=2,Sh(Oe,Qe,ze);else if(je==="Polygon")ze.type=3,Sh(Oe,Qe,ze,!0);else{if(je!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");ze.type=3;for(const Xe of Oe)Sh(Xe,Qe,ze,!0)}return ze}function Ud([ye,re],he,_e){const je=l.ad(ye);let Oe=l.ae(re);Oe=Oe<0?0:Oe>1?1:Oe,he.push(je,Oe),_e.minX=Math.min(_e.minX,je),_e.minY=Math.min(_e.minY,Oe),_e.maxX=Math.max(_e.maxX,je),_e.maxY=Math.max(_e.maxY,Oe)}function mf(ye,re,he,_e=!1,je=!1){const Oe=[];for(const ze of ye)Ud(ze,Oe,he);re.push(Oe),_e&&function(ze,Qe){let Xe=0;for(let Je=0,rt=ze.length,It=rt-2;Je0===Qe)for(let Je=0,rt=ze.length;Je=ze&&It>=ze||(Je>=ze?(rt+=Math.round(Ot*((ze-Je)/St)),Je=ze):It>=ze&&(wt=rt+Math.round(Ot*((ze-Je)/St)),It=ze),rt>=ze&&wt>=ze||(rt>=ze?(Je+=Math.round(St*((ze-rt)/Ot)),rt=ze):wt>=ze&&(It=Je+Math.round(St*((ze-rt)/Ot)),wt=ze),Qe&&Je===Qe.at(-2)&&rt===Qe.at(-1)||(Qe=[Je,rt],je.push(Qe)),Qe.push(It,wt)))))}}function _s(ye,re,he,_e,je){const Oe=(he-Ea)/re,ze=(_e-Ea)/re,Qe=(he+1+Ea)/re,Xe=(_e+1+Ea)/re;function Je(wt,St){let Ot=0;return wtQe&&(Ot|=2),StXe&&(Ot|=8),Ot}let rt=[];for(let wt=1;wt<=8;wt*=2){let St=ye.at(-2),Ot=ye.at(-1),pr=!(Je(St,Ot)&wt);for(let Ht=0;Ht>31}function jg(ye,re){if(ye.type===4)return re.writeVarint(io(1,1)),re.writeVarint(Vd(ye.x)),void re.writeVarint(Vd(ye.y));let he=0,_e=0;if(ye.type===1){const{geometry:je}=ye;re.writeVarint(io(1,je.length>>1));for(let Oe=0;Oe>1)-(je?1:0);for(let Qe=0;Qeye},tm=1073741824,Mw=1/tm,Bn=ye=>(ye-.5)*tm,po=ye=>ye*Mw+.5;class Ow{constructor(re){const he=this.options=Object.assign(Object.create(t0),re);he.maxZoom=Math.min(he.maxZoom,30),he.minZoom=Math.min(he.minZoom,he.maxZoom),this.trees=new Array(he.maxZoom+1),this.stride=he.reduce?7:6,this.clusterProps=[]}load(re){const{log:he,minZoom:_e,maxZoom:je}=this.options;he&&console.time("total time");const Oe=je+1,ze=`z${Oe}: ${re.length} points`;he&&console.time(ze);const Qe=this.stride;let Xe=re.length;for(const Zt of re){const Rr=Zt.geometry;Rr&&Rr.type==="MultiPoint"&&(Xe+=Rr.coordinates.length-1)}this.numPoints=Xe;const Je=this.props=new Array(Xe),rt=this.coords=new Float64Array(2*Xe);let It=null;const wt=new Int32Array(Xe*Qe);let St=0,Ot=0;for(const Zt of re){const Rr=Zt.geometry;if(!Rr){Ot++;continue}const un=Rr.coordinates,Zn=Rr.type==="MultiPoint";for(let an=0,on=Zn?un.length:1;an=_e;Zt--){const Rr=performance.now(),un=er||new Int32Array(Ht*Qe);er=null;const Zn=this._cluster(pr,Ht,Zt,un);Zn===Ht?(this.trees[Zt]=this.trees[Zt+1],er=un):(this.trees[Zt]=this._createTree(un,Zn),pr=un,Ht=Zn),he&&console.log(`z${Zt}: ${this.trees[Zt].numItems} clusters in ${(performance.now()-Rr).toFixed(2)}ms`)}return he&&console.timeEnd("total time"),this}getClusters(re,he){let _e=((re[0]+180)%360+360)%360-180;const je=Math.max(-90,Math.min(90,re[1]));let Oe=re[2]===180?180:((re[2]+180)%360+360)%360-180;const ze=Math.max(-90,Math.min(90,re[3]));if(re[2]-re[0]>=360)_e=-180,Oe=180;else if(_e>Oe){const It=this.getClusters([_e,je,180,ze],he),wt=this.getClusters([-180,je,Oe,ze],he);return It.concat(wt)}const Qe=this.trees[this._limitZoom(he)],Xe=Qe.range(Bn(mx(_e)),Bn(cn(ze)),Bn(mx(Oe)),Bn(cn(je))),Je=Qe.data,rt=[];for(const It of Xe)rt.push(this._featureJSON(Je,this.stride*It));return rt}getChildren(re){const he=this._getOriginId(re),_e=this._getOriginZoom(re),je="No cluster with the specified id.",Oe=this.trees[_e];if(!Oe)throw new Error(je);const ze=Oe.data;if(he>=Oe.numItems)throw new Error(je);const Qe=this.options.radius/(this.options.extent*Math.pow(2,_e-1)),Xe=Oe.within(ze[he*this.stride],ze[he*this.stride+1],Qe*tm),Je=[];for(const rt of Xe){const It=rt*this.stride;ze[It+4]===re&&Je.push(this._featureJSON(ze,It))}if(Je.length===0)throw new Error(je);return Je}getLeaves(re,he,_e){const je=[];return this._appendLeaves(je,re,he=he||10,_e=_e||0,0),je}getTile(re,he,_e){return this._getTile(re,he,_e,!1)}getTileRaw(re,he,_e){return this._getTile(re,he,_e,!0)}_getTile(re,he,_e,je){const Oe=this.trees[this._limitZoom(re)],ze=Math.pow(2,re),{extent:Qe,radius:Xe}=this.options,Je=Xe/Qe,rt=Bn((_e-Je)/ze),It=Bn((_e+1+Je)/ze),wt={features:[]};return this._addTileFeatures(Oe.range(Bn((he-Je)/ze),rt,Bn((he+1+Je)/ze),It),Oe.data,he,_e,ze,wt,je),he===0&&this._addTileFeatures(Oe.range(Bn(1-Je/ze),rt,Bn(1),It),Oe.data,ze,_e,ze,wt,je),he===ze-1&&this._addTileFeatures(Oe.range(Bn(0),rt,Bn(Je/ze),It),Oe.data,-1,_e,ze,wt,je),wt.features.length?wt:null}getClusterExpansionZoom(re){let he=this._getOriginZoom(re)-1;for(;he<=this.options.maxZoom;){const _e=this.getChildren(re);if(he++,_e.length!==1)break;re=_e[0].properties.cluster_id}return he}_appendLeaves(re,he,_e,je,Oe){const ze=this.getChildren(he);for(const Qe of ze){const Xe=Qe.properties;if(Xe&&Xe.cluster?Oe+Xe.point_count<=je?Oe+=Xe.point_count:Oe=this._appendLeaves(re,Xe.cluster_id,_e,je,Oe):Oe1;let It,wt,St;if(rt)It=fx(he,Je,this.clusterProps),wt=po(he[Je]),St=po(he[Je+1]);else{const Rr=he[Je+3];It=this.props[Rr],wt=this.coords[2*Rr],St=this.coords[2*Rr+1]}const Ot=Math.round(this.options.extent*(wt*Oe-_e)),pr=Math.round(this.options.extent*(St*Oe-je)),Ht=Qe?{type:4,x:Ot,y:pr,tags:It}:{type:1,geometry:[[Ot,pr]],tags:It},er=he[Je+3],Zt=rt||this.options.generateId?er:this.ids?this.ids[er]:void 0;Zt!==void 0&&(Ht.id=Zt),ze.features.push(Ht)}}_limitZoom(re){return Math.max(this.options.minZoom,Math.min(Math.floor(+re),this.options.maxZoom+1))}_cluster(re,he,_e,je){const{radius:Oe,extent:ze,reduce:Qe,minPoints:Xe,maxZoom:Je}=this.options,rt=Oe/(ze*(1<<_e))*tm,It=Je+1,wt=this.trees[_e+1],St=this.stride,Ot=he*St,pr=new Uint32Array(he);let Ht=0;for(let er=0;er_e&&(an+=re[Ln+5])}if(an>Zn&&an>=Xe){let on,Ln=Zt*Zn,ui=Rr*Zn,di=-1;const Un=(er/St<<5)+(_e+1)+this.numPoints;for(let wn=0;wn1)for(let on=0;on>5}_getOriginZoom(re){return(re-this.numPoints)%32}_featureJSON(re,he){const _e=re[he+3],je=re[he+5]>1,Oe=je?_e:this.ids?this.ids[_e]:void 0,ze={type:"Feature",properties:je?fx(re,he,this.clusterProps):this.props[_e],geometry:{type:"Point",coordinates:je?[rm(po(re[he])),uu(po(re[he+1]))]:[rm(this.coords[2*_e]),uu(this.coords[2*_e+1])]}};return Oe!==void 0&&(ze.id=Oe),ze}_map(re,he,_e){if(re[he+5]>1){const ze=this.clusterProps[re[he+6]];return _e?Object.assign({},ze):ze}const je=this.props[re[he+3]],Oe=this.options.map(je);return _e&&Oe===je?Object.assign({},Oe):Oe}}function fx(ye,re,he){const _e=ye[re+5],je=_e>=1e4?`${Math.round(_e/1e3)}k`:_e>=1e3?Math.round(_e/100)/10+"k":_e,Oe=ye[re+6],ze=Oe===-1?{}:Object.assign({},he[Oe]);return Object.assign(ze,{cluster:!0,cluster_id:ye[re+3],point_count:_e,point_count_abbreviated:je})}function mx(ye){return ye/360+.5}function cn(ye){const re=Math.sin(ye*Math.PI/180),he=.5-.25*Math.log((1+re)/(1-re))/Math.PI;return he<0?0:he>1?1:he}function rm(ye){return 360*(ye-.5)}function uu(ye){const re=(180-360*ye)*Math.PI/180;return 360*Math.atan(Math.exp(re))/Math.PI-90}const cd=2147483647;function Cg(ye,re,he,_e){return{id:ye,type:4,x:re,y:he,tags:_e}}function dp(ye,re,he,_e){const je={id:ye,type:re,geometry:he,tags:_e,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(re===1)r0(je,he,0,he.length);else{const Oe=re===3;for(let ze=0;ze=0)&&r0(je,he,Qe,Xe),ze=Xe}}return je}function r0(ye,re,he,_e){for(let je=he;je<_e;je+=3){const Oe=re[je],ze=re[je+1];Oeye.maxX&&(ye.maxX=Oe),ze>ye.maxY&&(ye.maxY=ze)}}function Pg(ye,re,he,_e){let je=_e;const Oe=re+(he-re>>1);let ze,Qe=he-re;const Xe=ye[re],Je=ye[re+1],rt=ye[he],It=ye[he+1];for(let wt=re+3;wtje)ze=wt,je=St;else if(St===je){const Ot=Math.abs(wt-Oe);Ot_e){const wt=ze;wt-re>3&&Pg(ye,re,wt,_e),ye[wt+2]=Math.min(Math.sqrt(je),cd),he-wt>3&&Pg(ye,wt,he,_e)}}function n0(ye,re,he,_e,je,Oe){let ze=je-he,Qe=Oe-_e;if(ze!==0||Qe!==0){const Xe=((ye-he)*ze+(re-_e)*Qe)/(ze*ze+Qe*Qe);Xe>1?(he=je,_e=Oe):Xe>0&&(he+=ze*Xe,_e+=Qe*Xe)}return ze=ye-he,Qe=re-_e,ze*ze+Qe*Qe}const px="Input data is not a valid GeoJSON object.";let qd=!1;function ud(ye,re,he,_e){var pr;const je=re.geometry;if(!je)return;const Oe=je.type==="GeometryCollection"?je.geometries:je.coordinates;if(!Oe)throw new Error(px);if(!Oe.length)return;const ze=he.tolerance*he.worldScale/((1<=2147483648&&(qd=!0),er[3*Zt+1]=pf(nm(Ht[Zt][1],rt,It),wt)}Xi(ye,St,1,er,Xe,he)}else if(je.type==="LineString")Eh(ye,St,je.coordinates,Xe,Qe,he);else if(je.type==="MultiLineString"&&he.lineMetrics)for(const Ht of je.coordinates)Eh(ye,St,Ht,Xe,Qe,he);else if(je.type==="MultiLineString"||je.type==="Polygon"||je.type==="MultiPolygon"){const Ht=je.type!=="MultiLineString",er=je.type==="MultiPolygon"?je.coordinates:[je.coordinates];let Zt=0;for(const Zn of er)Zt+=i0(Zn);const Rr=new Je(Zt);let un=0;for(const Zn of er)for(let an=0;an0&&(re+=2+3*he.length);return re}let hp=0;function Xi(ye,re,he,_e,je,Oe,ze){const Qe=dp(re,he,_e,je);he===2&&Oe.lineMetrics&&(Qe.start=0,Qe.end=Qe.size=ze),ye.push(Qe)}function Eh(ye,re,he,_e,je,Oe){const ze=new Oe.CoordArray(2+3*he.length);gx(ze,0,he,je,!1,!1,Oe.worldScale,Oe.originShift,Oe.useInt32),Xi(ye,re,2,ze,_e,Oe,hp)}function gx(ye,re,he,_e,je,Oe,ze,Qe,Xe){if(he.length===0)return re;const Je=re,rt=re+=2;let It=0,wt=0,St=0;for(let Ht=0;Ht=2147483648&&(qd=!0),re+=3,Ht>0)if(je)St+=(It*Zt-er*wt)/2;else{const Rr=er-It,un=Zt-wt;St+=Math.sqrt(Rr*Rr+un*un)}It=er,wt=Zt}const Ot=re;if(je&&(Oe&&St<0||!Oe&&St>=0)){const Ht=Ot-rt;for(let er=0;er1?1:je)-he)*re}function Gd(ye,re,he,_e,je,Oe,ze){if(je>=re&&Oe=he)return null;const Qe=ze.lineMetrics;let Xe=null;for(let Je=0;Je=re&&Ht=re&&Ot=he){Xe===null&&(Xe=ye.slice(0,Je));continue}Xe===null&&(Xe=ye.slice(0,Je));const pr=wt.constructor;It!==1?gc(wt,It,re,he,_e,rt,Xe,Qe,pr):du(wt,re,he,_e,rt,Xe,pr)}return Xe===null?ye:Xe.length?Xe:null}function du(ye,re,he,_e,je,Oe,ze){let Qe=0;for(let rt=0;rt=re&&ye[rt+_e]=re&&ye[rt+_e]=_e&&(Je++,rt++):St>je?Ot<=je&&(Je++,rt++):Je++,Ot<_e&&St>=_e&&(Je++,rt++,pr=!0),Ot>je&&St<=je&&(Je++,rt++,pr=!0),!ze&&pr&&(Je>0&&(Xe+=Je,Qe++),Je=0)}const It=ye[he-3+Oe];return It>=_e&&It<=je&&Je++,ze&&Je>=2&&rt>=1&&Je++,Je>0&&(Xe+=Je,Qe++),3*Xe+2*Qe}function Uc(ye,re,he,_e,je,Oe,ze,Qe,Xe,Je,rt,It,wt){const St=It!==null;let Ot=Oe;je[Oe]=0,je[Oe+1]=_e;let pr=Oe+=2,Ht=wt,er=Ht,Zt=0,Rr=0;for(let di=re;di=ze&&(Rr=Hd(je,Oe,Un,wn,Fi,vi,ze,Xe,rt),Oe+=3,St&&(er=Ht+Zt*Rr)):vs>Qe?en<=Qe&&(Rr=Hd(je,Oe,Un,wn,Fi,vi,Qe,Xe,rt),Oe+=3,St&&(er=Ht+Zt*Rr)):(je[Oe]=Un,je[Oe+1]=wn,je[Oe+2]=ri,Oe+=3),en=ze&&(Rr=Hd(je,Oe,Un,wn,Fi,vi,ze,Xe,rt),Oe+=3,ai=!0),en>Qe&&vs<=Qe&&(Rr=Hd(je,Oe,Un,wn,Fi,vi,Qe,Xe,rt),Oe+=3,ai=!0),!Je&&ai){const Si=(Oe-pr)/3;Si>0&&(je[Ot]=Si,St&&It.push(er,Ht+Zt*Rr),Ot=Oe,je[Oe]=0,je[Oe+1]=_e,pr=Oe+=2)}St&&(Ht+=Zt)}const un=he-3,Zn=ye[un],an=ye[un+1],on=ye[un+2],Ln=Xe===0?Zn:an;Ln>=ze&&Ln<=Qe&&(je[Oe]=Zn,je[Oe+1]=an,je[Oe+2]=on,Oe+=3),Je&&Oe-pr>=6&&(je[Oe-3]!==je[pr]||je[Oe-2]!==je[pr+1])&&(je[Oe]=je[pr],je[Oe+1]=je[pr+1],je[Oe+2]=je[pr+2],Oe+=3);const ui=(Oe-pr)/3;return ui>0?(je[Ot]=ui,St&&It.push(er,Ht)):Oe=Ot,Oe}function Hd(ye,re,he,_e,je,Oe,ze,Qe,Xe){let Je;if(Qe===0){Je=(ze-he)/(je-he);const rt=_e+(Oe-_e)*Je;ye[re]=ze,ye[re+1]=Xe?Math.floor(rt+.5):rt}else{Je=(ze-_e)/(Oe-_e);const rt=he+(je-he)*Je;ye[re]=Xe?Math.floor(rt+.5):rt,ye[re+1]=ze}return ye[re+2]=cd,Je}function a0(ye,re){const he=[];for(const _e of ye){if(_e.type===4){he.push(Cg(_e.id,_e.x+re,_e.y,_e.tags));continue}const je=Fw(_e.geometry,_e.type,re),Oe=dp(_e.id,_e.type,je,_e.tags);_e.start!==void 0&&(Oe.start=_e.start,Oe.end=_e.end,Oe.size=_e.size),he.push(Oe)}return he}function Fw(ye,re,he){const _e=ye.slice();if(re===1)for(let je=0;je<_e.length;je+=3)_e[je]+=he;else for(let je=0;je<_e.length;){const Oe=je+2+3*_e[je];for(let ze=je+2;zeye.maxX&&(ye.maxX=Ht),er>ye.maxY&&(ye.maxY=er),ye.numPoints++,ye.numSimplified++;const Zt={x:Th(Ht,je,Oe,Qe,Je,rt),y:Th(er,je,ze,Qe,Je,rt),type:4,tags:re.tags||null};return re.id!==void 0&&(Zt.id=re.id),void ye.features.push(Zt)}const wt=re.geometry;let St;if(re.minXye.maxX&&(ye.maxX=re.maxX),re.maxY>ye.maxY&&(ye.maxY=re.maxY),It===1){const Ht=wt.length/3;St=new Xe(2*Ht);for(let er=0,Zt=0;er0?Math.max(0,Ht/Zt):0,Ot.mapbox_clip_end=er>=Zt?1:er/Zt}const pr={geometry:St,type:It,tags:Ot};re.id!==void 0&&(pr.id=re.id),ye.features.push(pr)}function yx(ye,re,he,_e,je,Oe,ze,Qe,Xe,Je,rt,It,wt,St,Ot){const pr=(_e-he)/3;if(Math.abs(je)ze&&Ht++;Oe.numPoints+=pr,Oe.numSimplified+=Ht;const er=new wt(2*Ht);let Zt=0;for(let Rr=he;Rr<_e;Rr+=3)(ze===0||re[Rr+2]>ze)&&(er[Zt++]=Th(re[Rr],Xe,Je,It,St,Ot),er[Zt++]=Th(re[Rr+1],Xe,rt,It,St,Ot));ye.push(er)}const zw={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,promoteId:null,generateId:!1,debug:0};class xx{constructor(re,he){const _e=this.options=Object.assign(Object.create(zw),he),je=_e.debug;if(je&&console.time("preprocess data"),_e.maxZoom<0||_e.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");if(_e.promoteId&&_e.generateId)throw new Error("promoteId and generateId cannot be used together.");const Oe=(_e.extent+2*_e.buffer)*(1<<_e.maxZoom)<4294967296;_e.useInt32=Oe,_e.CoordArray=Oe?Int32Array:Float64Array,_e.worldScale=Oe?_e.extent*(1<<_e.maxZoom):1,_e.originShift=Oe?.5:0;let ze=function(Qe,Xe){const Je=[];if(Qe.type==="FeatureCollection")for(let rt=0;rt1&&console.time("creation"),Ot=this.tiles[St]=o0(re,he,_e,je,rt),this.tileCoords.push({z:he,x:_e,y:je}),this.stats[he]=(this.stats[he]||0)+1,this.total++,It>1&&(console.log(`tile z${he}-${_e}-${je} (features: ${Ot.numFeatures}, points: ${Ot.numPoints}, simplified: ${Ot.numSimplified})`),console.timeEnd("creation"))),Ot.source=re,Oe==null){if(he===rt.indexMaxZoom||Ot.numPoints<=rt.indexMaxPoints)continue}else{if(he===rt.maxZoom||he===Oe)continue;{const Un=Oe-he;if(_e!==ze>>Un||je!==Qe>>Un)continue}}if(Ot.source=null,re.length===0)continue;It>1&&console.time("clipping");const pr=rt.worldScale,Ht=rt.originShift,er=pr/wt,Zt=.5*rt.buffer*pr/(wt*rt.extent),Rr=(_e/wt-Ht)*pr,un=(je/wt-Ht)*pr;let Zn=null,an=null,on=null,Ln=null;const ui=Gd(re,Rr-Zt,Rr+er/2+Zt,0,Ot.minX,Ot.maxX,rt),di=Gd(re,Rr+er/2-Zt,Rr+er+Zt,0,Ot.minX,Ot.maxX,rt);ui&&(Zn=Gd(ui,un-Zt,un+er/2+Zt,1,Ot.minY,Ot.maxY,rt),an=Gd(ui,un+er/2-Zt,un+er+Zt,1,Ot.minY,Ot.maxY,rt)),di&&(on=Gd(di,un-Zt,un+er/2+Zt,1,Ot.minY,Ot.maxY,rt),Ln=Gd(di,un+er/2-Zt,un+er+Zt,1,Ot.minY,Ot.maxY,rt)),It>1&&console.timeEnd("clipping"),Xe.push(Zn||[],an||[],on||[],Ln||[]),Je.push(he+1,2*_e,2*je,he+1,2*_e,2*je+1,he+1,2*_e+1,2*je,he+1,2*_e+1,2*je+1)}}getTile(re,he,_e){const je=this.findTile(re,he,_e);return je?function(Oe){const ze=[];for(const Qe of Oe.features){let Xe;Xe=Qe.type===4?{type:1,geometry:[[Qe.x,Qe.y]],tags:Qe.tags??null}:Qe.type===1?{type:1,geometry:dd(Qe.geometry),tags:Qe.tags??null}:{type:Qe.type,geometry:Qe.geometry.map(dd),tags:Qe.tags??null},Qe.id!=null&&(Xe.id=Qe.id),ze.push(Xe)}return{features:ze}}(je):null}getTileRaw(re,he,_e){const je=this.findTile(re,he,_e);return je?{features:je.features}:null}findTile(re,he,_e){const je=this.options.debug;if((re=+re)<0||re>24)return null;const Oe=1<1&&console.log("drilling down to z%d-%d-%d",re,he,_e);let Qe,Xe=re,Je=he,rt=_e;for(;!Qe&&Xe>0;)Xe--,Je>>=1,rt>>=1,Qe=this.tiles[im(Xe,Je,rt)];return Qe&&Qe.source?(je>1&&(console.log("found parent tile z%d-%d-%d",Xe,Je,rt),console.time("drilling down")),this.splitTile(Qe.source,Xe,Je,rt,re,he,_e),je>1&&console.timeEnd("drilling down"),this.tiles[ze]??null):null}}function dd(ye){const re=[];for(let he=0;heJe.tags&&"3d_elevation_id"in Je.tags&&"source"in Je.tags&&Je.tags.source==="elevation",Oe=_e.features.filter(je);let ze={_geojsonTileLayer:_e.features};Oe.length>0&&(ze={_geojsonTileLayer:_e.features.filter(Je=>!je(Je)),hd_road_elevation:Oe});const Qe=new xs(ze),Xe=function(Je){const rt=new l.gu;for(const It of Object.keys(Je))rt.writeMessage(3,Fo,{name:It,features:Je[It]});return rt.finish()}(ze).buffer;re(null,{vectorTile:Qe,rawData:Xe,headers:new Headers})}class hu extends Nr{constructor(re){super(re),this.loadVectorData=$w,this._dynamicIndex=new jt}async loadData(re){const he=re&&re.request,_e=he&&he.collectResourceTiming;this._geoJSONIndex=null;let je=await new Promise((ze,Qe)=>{this.loadGeoJSON(re,(Xe,Je)=>{Xe?Qe(Xe):ze(Je)})});if(!je)return{};if(typeof je!="object")throw new Error(`Input data given to '${re.source}' is not a valid GeoJSON object.`);if(re.filter){const ze=l.c(re.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(ze.result==="error")throw new Error(ze.value.map(Qe=>`${Qe.key}: ${Qe.message}`).join(", "));je.features=je.features.filter(Qe=>ze.value.evaluate({zoom:0},Qe))}re.dynamic?(je.type==="Feature"&&(je={type:"FeatureCollection",features:[je]}),re.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(je.features,this.loaded),re.cluster&&(je.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=re.cluster?new Ow(function({superclusterOptions:ze,clusterProperties:Qe}){if(!Qe||!ze)return ze;const Xe={},Je={},rt={accumulated:null,zoom:0},It={properties:null},wt=Object.keys(Qe);for(const St of wt){const[Ot,pr]=Qe[St],Ht=l.c(pr),er=l.c(typeof Ot=="string"?[Ot,["accumulated"],["get",St]]:Ot);Xe[St]=Ht.value,Je[St]=er.value}return ze.map=St=>{It.properties=St;const Ot={};for(const pr of wt)Ot[pr]=Xe[pr].evaluate(rt,It);return Ot},ze.reduce=(St,Ot)=>{It.properties=Ot;for(const pr of wt)rt.accumulated=St[pr],St[pr]=Je[pr].evaluate(rt,It)},ze}(re)).load(je.features):re.dynamic?this._dynamicIndex:new xx(je,re.geojsonVtOptions);const Oe={};if(_e){const ze=g(he);ze&&(Oe.resourceTiming={},Oe.resourceTiming[re.source]=JSON.parse(JSON.stringify(ze)))}return Oe}async reloadTile(re){const he=this.loaded;return he&&he[re.uid]?re.partial?void 0:super.reloadTile(re):this.loadTile(re)}loadGeoJSON(re,he){if(re.request)l.g(re.request).then(({data:_e})=>he(null,_e)).catch(_e=>he(_e));else{if(typeof re.data!="string")return he(new Error(`Input data given to '${re.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return he(null,JSON.parse(re.data))}catch{return he(new Error(`Input data given to '${re.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(re){return this._geoJSONIndex.getClusterExpansionZoom(re.clusterId)}getClusterChildren(re){return this._geoJSONIndex.getChildren(re.clusterId)}getClusterLeaves(re){return this._geoJSONIndex.getLeaves(re.clusterId,re.limit,re.offset)}}l.cK.setPbf(l.d);class gf{constructor(re){this._mrt=new l.cK(re.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=re.uid,this.tileID=re.tileID,this.source=re.source}async parse(re){const he=this._mrt;this.status="parsing",this._entireBuffer=re,he.parseHeader(re),this._isHeaderLoaded=!0;const _e=[];for(const je in he.layers){const Oe=he.getLayer(je),ze=Oe.getDataRange(Oe.getBandList()),Qe=he.createDecodingTask(ze),Xe=re.slice(ze.firstByte,ze.lastByte+1);_e.push(l.cK.performDecoding(Xe,Qe).then(Je=>Qe.complete(null,Je)).catch(Je=>Qe.complete(Je,null)))}return await Promise.allSettled(_e),he}}class Cn{constructor({actor:re}){this.actor=re,this.loading={},this.loaded={}}async loadTile(re){const he=re.uid,_e=new AbortController,je=this.loading[he]=new gf(re);je.abort=()=>_e.abort();try{const{data:Oe,headers:ze}=await l.n(re.request,_e.signal);return Oe?(this.loaded[he]=je,{mrt:await je.parse(Oe),headers:ze}):(je.status="done",this.loaded[he]=je,null)}catch(Oe){if(_e.signal.aborted)return null;throw je.status="done",this.loaded[he]=je,Oe}finally{delete this.loading[he]}}async reloadTile(re){}abortTile(re){const he=re.uid,_e=this.loading[he];_e&&(_e.abort&&_e.abort(),delete this.loading[he])}removeTile(re){const he=re.uid;this.loaded[he]&&delete this.loaded[he]}async decodeRasterArray(re){return l.cK.performDecoding(re.buffer,re.task)}}class _x{constructor(re){this.self=re,this.actor=new l.aH(re,this),this.layerIndexes={},this.availableImages={},this.availableModels={},this.isSpriteLoaded={},this.localGlyphs={},this.projections={},this.defaultProjection=l.gw({name:"mercator"}),this.workerSourceTypes={vector:Nr,geojson:hu,"raster-dem":Zr},this.workerSources={}}clearCaches(re,he){delete this.layerIndexes[re],delete this.availableImages[re],delete this.availableModels[re],delete this.workerSources[re],delete this.isSpriteLoaded[re],delete this.localGlyphs[re]}checkIfReady(re,he){}spriteLoaded(re,he){const{scope:_e}=he;if(this.isSpriteLoaded[re]||(this.isSpriteLoaded[re]={}),this.isSpriteLoaded[re][_e]=!0,this.workerSources[re]&&this.workerSources[re][_e])for(const je in this.workerSources[re][_e]){const Oe=this.workerSources[re][_e][je];for(const ze in Oe){const Qe=Oe[ze];Qe instanceof Nr&&(Qe.isSpriteLoaded=!0,Qe.fire(new l.i("isSpriteLoaded")))}}}setImages(re,he){this.availableImages[re]||(this.availableImages[re]={});const{scope:_e,images:je}=he;if(this.availableImages[re][_e]=je,he.isSpriteLoaded&&this.spriteLoaded(re,{scope:_e}),this.workerSources[re]&&this.workerSources[re][_e])for(const Oe in this.workerSources[re][_e]){const ze=this.workerSources[re][_e][Oe];for(const Qe in ze)ze[Qe].availableImages=je}}setModels(re,{scope:he,models:_e}){if(this.availableModels[re]||(this.availableModels[re]={}),this.availableModels[re][he]=_e,this.workerSources[re]&&this.workerSources[re][he])for(const je in this.workerSources[re][he]){const Oe=this.workerSources[re][he][je];for(const ze in Oe)Oe[ze].availableModels=_e}}setProjection(re,he){this.projections[re]=l.gw(he)}setGlobalParams(re,he){this.referrer=he.referrer,Object.assign(l.t,he.config),he.contextOptions&&(this.maxUniformBlockSizeDwords=he.contextOptions.maxUniformBlockSizeDwords),he.localGlyphs&&l.o()&&(this.localGlyphs[re]=new l.r(he.localGlyphs))}upsertRenderParams(re,he){he.brightness!==void 0&&(this.brightness=he.brightness),he.worldview!==void 0&&(this.worldview=he.worldview)}setLayers(re,he){this.getLayerIndex(re,he.scope).replace(he.layers,he.options)}updateLayers(re,he){this.getLayerIndex(re,he.scope).update(he.layers,he.removedIds,he.options)}async loadTile(re,he){if(he.projection=this.projections[re]||this.defaultProjection,he.type==="batched-model"&&!this.workerSourceTypes["batched-model"]){if(await l.gx(),!ie)throw new Error('Could not load Standard module for "batched-model" source.');this.workerSourceTypes["batched-model"]=ie}return he.type==="raster-array"&&await this.ensureRasterArrayWorkerSource(),this.getWorkerSource(re,he).loadTile(he)}async ensureRasterArraySource(re,he){await this.ensureRasterArrayWorkerSource()}async ensureRasterArrayWorkerSource(){if(!this.workerSourceTypes["raster-array"]){if(await async function(){return Promise.resolve()}(),!Cn)throw new Error('Could not load raster-array module for "raster-array" source.');this.workerSourceTypes["raster-array"]=Cn}}async decodeRasterArray(re,he){return await this.ensureRasterArrayWorkerSource(),this.getWorkerSource(re,he).decodeRasterArray(he)}reloadTile(re,he){return he.projection=this.projections[re]||this.defaultProjection,this.getWorkerSource(re,he).reloadTile(he)}abortTile(re,he){const _e=this.getExistingWorkerSource(re,he);return _e?_e.abortTile(he):void 0}removeTile(re,he){const _e=this.getExistingWorkerSource(re,he);return _e?_e.removeTile(he):void 0}getExistingWorkerSource(re,he){const{type:_e,source:je,scope:Oe}=he,ze=this.workerSources[re];if(ze&&ze[Oe]&&ze[Oe][_e])return ze[Oe][_e][je]}async removeSource(re,he){const{type:_e,source:je,scope:Oe}=he,ze=this.workerSources[re]&&this.workerSources[re][Oe]&&this.workerSources[re][Oe][_e],Qe=ze&&ze[je];Qe&&(delete ze[je],Qe.removeSource&&await Qe.removeSource({source:je}))}async loadTileProvider(re,he){const _e=new(await l.cF(he.name,he.url))(he.options);return this.getWorkerSource(re,{type:he.type,source:he.source,scope:he.scope},_e),_e.load&&he.request?_e.load({request:he.request}):null}getAvailableImages(re,he){this.availableImages[re]||(this.availableImages[re]={});let _e=this.availableImages[re][he];return _e||(_e=[]),_e}getAvailableModels(re,he){this.availableModels[re]||(this.availableModels[re]={});let _e=this.availableModels[re][he];return _e||(_e={}),_e}getLayerIndex(re,he){this.layerIndexes[re]||(this.layerIndexes[re]={});let _e=this.layerIndexes[re][he];return _e||(_e=this.layerIndexes[re][he]=new be,_e.scope=he),_e}getWorkerSource(re,he,_e){const{type:je,source:Oe,scope:ze}=he,Qe=this.workerSources;if(Qe[re]||(Qe[re]={}),Qe[re][ze]||(Qe[re][ze]={}),Qe[re][ze][je]||(Qe[re][ze][je]={}),this.isSpriteLoaded[re]||(this.isSpriteLoaded[re]={}),this.getExistingWorkerSource(re,he))_e&&(Qe[re][ze][je][Oe].tileProvider=_e);else{const Xe=this.actor.getWorkerSourceActor(re),Je=this.workerSourceTypes[je];if(!Je)throw new Error(`Unknown worker source type "${je}".`);Qe[re][ze][je][Oe]=new Je({actor:Xe,layerIndex:this.getLayerIndex(re,ze),availableImages:this.getAvailableImages(re,ze),availableModels:this.getAvailableModels(re,ze),isSpriteLoaded:this.isSpriteLoaded[re][ze],tileProvider:_e,brightness:this.brightness,worldview:this.worldview,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,localGlyphs:this.localGlyphs[re]})}return Qe[re][ze][je][Oe]}enforceCacheSizeLimit(re,he){l.gy(he)}}return l.gv(self)&&(self.worker=new _x(self)),_x}),d(["./shared"],function(l){const g={antialias:!1,alpha:!0,stencil:!0,depth:!0};let v,E;function T(_){const f=document.createElement("canvas"),y=Object.create(g);y.failIfMajorPerformanceCaveat=_;const w=f.getContext("webgl2",y);if(!w)return!1;let k;try{k=w.createShader(w.VERTEX_SHADER)}catch{return!1}return!(!k||w.isContextLost())&&(w.shaderSource(k,"void main() {}"),w.compileShader(k),w.getShaderParameter(k,w.COMPILE_STATUS)===!0)}const j=/firefox/i,P=/macintosh/i;function C(_,f,y){const w=document.createElement(_);return f!=null&&(w.className=f),y&&y.appendChild(w),w}function L(_,f,y){const w=document.createElementNS("http://www.w3.org/2000/svg",_);for(const k of Object.keys(f))w.setAttributeNS(null,k,String(f[k]));return y&&y.appendChild(w),w}const O=typeof document<"u"?document.documentElement&&document.documentElement.style:null,F=O&&O.userSelect!==void 0?"userSelect":"WebkitUserSelect";let $;function G(){O&&F&&($=O[F],O[F]="none")}function W(){O&&F&&(O[F]=$)}function Z(_){_.preventDefault(),_.stopPropagation(),window.removeEventListener("click",Z,!0)}function Q(){window.addEventListener("click",Z,!0),window.setTimeout(()=>{window.removeEventListener("click",Z,!0)},0)}function ee(_,f){const y=_.getBoundingClientRect();return pe(_,y,f)}function ie(_,f){const y=_.getBoundingClientRect(),w=[];for(let k=0;kf?M.has(f):M.size!==0,{_layoutValues:w,_paintValues:k}=this._layer;if(w&&y(w.configDependencies)||k&&y(k.configDependencies))return!0;for(const{unevaluatedLayout:M,unevaluatedPaint:z}of this._layer.appearances)if(M&&(y(M.configDependencies)||y(z.configDependencies)))return!0;const R=this._filterDeps;return!!R&&y(R.configDependencies)}get isIndoorDependent(){const{_layoutValues:f,_paintValues:y}=this._layer;if(f&&f.isIndoorDependent()||y&&y.isIndoorDependent())return!0;const w=this._filterDeps;return!!w&&w.isIndoorDependent}}function Re(_){const{userImage:f}=_;return!!(f&&f.render&&f.render())&&(_.data.replace(new Uint8Array(f.data.buffer)),!0)}const Ie=new l.C(0,0,0);function Te(_,f){const y=[],w=_[`stretch_${f}`];let k=null;for(let R=0;R>16&255)/255,(_>>8&255)/255,(255&_)/255,1)}function Bt(_,f){const y={spread_method:1,stops:[],x1:0,y1:0,x2:1,y2:0};let w;for(;w=_.nextField(f);)w===1?y.transform=nt(_,_.readVarint()+_.pos):w===2?y.spread_method=_.readVarint():w===3?y.stops.push(cr(_,_.readVarint()+_.pos)):w===4?y.x1=_.readFloat():w===5?y.y1=_.readFloat():w===6?y.x2=_.readFloat():w===7&&(y.y2=_.readFloat());return y}function cr(_,f){const y={offset:0,opacity:255,rgb_color:Ie};let w;for(;w=_.nextField(f);)w===1?y.offset=_.readFloat():w===2?y.opacity=_.readVarint():w===3&&(y.rgb_color=Ct(_.readVarint()));return y}function ft(_,f){const y={spread_method:1,stops:[],cx:.5,cy:.5,r:.5,fx:.5,fy:.5,fr:0};let w;for(;w=_.nextField(f);)w===1?y.transform=nt(_,_.readVarint()+_.pos):w===2?y.spread_method=_.readVarint():w===3?y.stops.push(cr(_,_.readVarint()+_.pos)):w===4?y.cx=_.readFloat():w===5?y.cy=_.readFloat():w===6?y.r=_.readFloat():w===7?y.fx=_.readFloat():w===8?y.fy=_.readFloat():w===9&&(y.fr=_.readFloat());return y}function Kt(_,f){const y={children:[]};let w;for(;w=_.nextField(f);)w===1?y.transform=nt(_,_.readVarint()+_.pos):w===2?y.clip_path_idx=_.readVarint():w===3&&y.children.push(He(_,_.readVarint()+_.pos));return y}function ir(_,f){const y={left:0,width:20,mask_type:1,children:[]};let w;for(;w=_.nextField(f);)w===1?y.left=y.top=_.readFloat():w===2?y.width=y.height=_.readFloat():w===3?y.top=_.readFloat():w===4?y.height=_.readFloat():w===5?y.mask_type=_.readVarint():w===6?y.mask_idx=_.readVarint():w===7&&y.children.push(He(_,_.readVarint()+_.pos));return y.height??(y.height=y.width),y.top??(y.top=y.left),y}class Gr{static calculate(f={},y=[]){const w=new Map,k=new Map;if(Object.keys(f).length===0)return w;y.forEach(R=>{k.set(R.name,R.rgb_color||new l.C(0,0,0))});for(const[R,M]of Object.entries(f))k.has(R)?w.set(k.get(R).toString(),M):console.warn(`Ignoring unknown image variable "${R}"`);return w}}function tr(_,f=255,y){const w=y.get(_.toString())||_;return f===255?w.toString():new l.C(w.r,w.g,w.b,w.a*f/255).toString()}const Qt=[];let zt=0;function Vr(_,f){if(zt>=Qt.length){const w=l.o()?new OffscreenCanvas(_,f).getContext("2d",{willReadFrequently:!0}):document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Qt.push(w)}const y=Qt[zt++];return y.canvas.width=_,y.canvas.height=f,y}function Jr(){zt--}function Fn(_,f,y,w,k){for(const R of w.children)Ar(_,f,y,R,k)}function Ar(_,f,y,w,k){w.group?(_.save(),function(R,M,z,V,H){const Y=V.mask_idx!=null?z.masks[V.mask_idx]:null,te=V.clip_path_idx!=null?z.clip_paths[V.clip_path_idx]:null;if(V.transform&&(M=Mi(V.transform).preMultiplySelf(M)),!function(le,me,fe){return le.opacity!==255||me||fe}(V,te!=null,Y!=null))return void Fn(R,M,z,V,H);const ne=Vr(R.canvas.width,R.canvas.height);Fn(ne,M,z,V,H),te&&ss(ne,M,z,te),Y&&ps(ne,M,z,Y,H),R.globalAlpha=V.opacity/255,R.drawImage(ne.canvas,0,0),Jr()}(_,f,y,w.group,k),_.restore()):w.path&&(_.save(),function(R,M,z,V,H){R.setTransform(M),V.paint_order===1?(Tn(R,z,V,H),li(R,z,V,H)):(li(R,z,V,H),Tn(R,z,V,H))}(_,f,y,w.path,k),_.restore())}function Tn(_,f,y,w){const k=y.fill;if(!k)return;const R=k.opacity/255;switch(_.save(),_.beginPath(),gs(y,_),k.paint){case"rgb_color":_.fillStyle=tr(k.rgb_color,k.opacity,w);break;case"linear_gradient_idx":{const M=f.linear_gradients[k.linear_gradient_idx];M.transform&&_.setTransform(Mi(M.transform).preMultiplySelf(_.getTransform())),_.fillStyle=Lr(_,M,R,w);break}case"radial_gradient_idx":{const M=f.radial_gradients[k.radial_gradient_idx];M.transform&&_.setTransform(Mi(M.transform).preMultiplySelf(_.getTransform())),_.fillStyle=Or(_,M,R,w)}}_.fill(mn(y)),_.restore()}function mn(_){return _.rule===1?"nonzero":_.rule===2?"evenodd":void 0}function li(_,f,y,w){const k=y.stroke;if(!k)return;const R=ma(y);_.lineWidth=k.width,_.miterLimit=k.miterlimit,_.setLineDash(k.dasharray),_.lineDashOffset=k.dashoffset;const M=k.opacity/255;switch(k.paint){case"rgb_color":_.strokeStyle=tr(k.rgb_color,k.opacity,w);break;case"linear_gradient_idx":_.strokeStyle=Lr(_,f.linear_gradients[k.linear_gradient_idx],M,w,!0);break;case"radial_gradient_idx":_.strokeStyle=Or(_,f.radial_gradients[k.radial_gradient_idx],M,w,!0)}switch(k.linejoin){case 2:case 1:_.lineJoin="miter";break;case 3:_.lineJoin="round";break;case 4:_.lineJoin="bevel"}switch(k.linecap){case 1:_.lineCap="butt";break;case 2:_.lineCap="round";break;case 3:_.lineCap="square"}_.stroke(R)}function Lr(_,f,y,w,k=!1){if(f.stops.length===1){const ne=f.stops[0];return tr(ne.rgb_color,ne.opacity*y,w)}const{x1:R,y1:M,x2:z,y2:V}=f;let H=new DOMPoint(R,M),Y=new DOMPoint(z,V);if(k){const ne=Mi(f.transform);H=ne.transformPoint(H),Y=ne.transformPoint(Y)}const te=_.createLinearGradient(H.x,H.y,Y.x,Y.y);for(const ne of f.stops)te.addColorStop(ne.offset,tr(ne.rgb_color,ne.opacity*y,w));return te}function Or(_,f,y,w,k=!1){if(f.stops.length===1){const Me=f.stops[0];return tr(Me.rgb_color,Me.opacity*y,w)}const R=Mi(f.transform),{fx:M,fy:z,fr:V,cx:H,cy:Y,r:te}=f;let ne=new DOMPoint(M,z),le=new DOMPoint(H,Y),me=V,fe=te;if(k){ne=R.transformPoint(ne),le=R.transformPoint(le);const Me=(R.a+R.d)/2;me=V*Me,fe=f.r*Me}const Se=_.createRadialGradient(ne.x,ne.y,me,le.x,le.y,fe);for(const Me of f.stops)Se.addColorStop(Me.offset,tr(Me.rgb_color,Me.opacity*y,w));return Se}function si(_,f,y,w){const k=w.transform?Mi(w.transform).preMultiplySelf(f):f,R=Vr(_.canvas.width,_.canvas.height);for(const z of w.children)if(z.group)si(R,k,y,z.group);else if(z.path){const V=z.path,H=new Path2D;H.addPath(ma(V),k),R.fill(H,mn(V))}const M=w.clip_path_idx!=null?y.clip_paths[w.clip_path_idx]:null;M&&ss(R,k,y,M),_.globalCompositeOperation="source-over",_.drawImage(R.canvas,0,0),Jr()}function ss(_,f,y,w){const k=Vr(_.canvas.width,_.canvas.height);si(k,f,y,w),_.globalCompositeOperation="destination-in",_.drawImage(k.canvas,0,0),Jr()}function ps(_,f,y,w,k){if(w.children.length===0)return;const R=w.mask_idx!=null?y.masks[w.mask_idx]:null;R&&ps(_,f,y,R,k);const M=_.canvas.width,z=_.canvas.height,V=Vr(M,z),H=w.width,Y=w.height,te=w.left,ne=w.top,le=new Path2D,me=new Path2D;me.rect(te,ne,H,Y),le.addPath(me,f),V.clip(le);for(const Me of w.children)Ar(V,f,y,Me,k);const fe=V.getImageData(0,0,M,z),Se=fe.data;if(w.mask_type===1)for(let Me=0;Mel.I.from(y))}hasImageProviderForSource(f,y){const w=this.imageProviders.get(y);if(!w)return!1;for(const k of w.values())if(k.sourceCache.getSource().id===f)return!0;return!1}getImages(f,y,w){const k=[],R=[],M=this.imageProviders.get(y);for(const Y of f){if(!Y.iconsetId){k.push(Y);continue}const te=M.get(Y.iconsetId);te&&(this.getImage(Y,y)?R.push(Y):te.addPendingRequest(Y))}if(k.length===0)return void this._notify(R,y,w);let z=!0;const V=!!this.loaded.get(y),H=this.images.get(y);if(!V)for(const Y of k)H.has(Y.toString())||(z=!1);V||z?this._notify(k,y,w):this.requestors.push({ids:k,scope:y,callback:w})}rasterizeImages(f,y){const w=new Map,{iconTasks:k,patternTasks:R,scope:M}=f;for(const z of[k,R])for(const[V,H]of z.entries()){const Y=this.getImage(H.id,M);Y&&w.set(V,{image:Y,imageVariant:H})}y(null,this._rasterizeImages(M,w))}_rasterizeImages(f,y){const w=new Map;for(const[k,{image:R,imageVariant:M}]of y.entries())w.set(k,this.imageRasterizer.rasterize(M,R,f,0));return w}getUpdatedImages(f){return this.updatedImages.get(f)||new Set}_notify(f,y,w){const k=this.images.get(y),R=new Map,M=this.imageVersions.get(y),z=new Map;for(const V of f){if(!k.get(V.toString())){if(V.iconsetId)continue;this.fire(new l.i("styleimagemissing",{id:V.name}))}const H=k.get(V.toString());if(!H){l.w(`Image "${V.name}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);continue}const Y={data:H.usvg?null:H.data.clone(),pixelRatio:H.pixelRatio,sdf:H.sdf,usvg:H.usvg,stretchX:H.stretchX,stretchY:H.stretchY,content:H.content,hasRenderCallback:!!(H.userImage&&H.userImage.render)};H.usvg&&Object.assign(Y,{width:H.icon.usvg_tree.width,height:H.icon.usvg_tree.height});const te=l.I.toString(V);R.set(te,Y);const ne=M&&M.get(te);ne&&z.set(te,ne)}w(null,{images:R,versions:z})}getPixelSize(f){const{width:y,height:w}=this.atlasImage.get(f);return{width:y,height:w}}getPattern(f,y,w){const k=f.toString(),R=this.patterns.get(y),M=R.get(k),z=this.getImage(f,y);if(!z)return null;if(M){if(M.position.version===z.version)return M.position;M.position.version=z.version}else{if(z.usvg&&!z.data){const V=this.getPatternInFlightId(k,y);if(this.patternsInFlight.has(V))return null;this.patternsInFlight.add(V);const H=new l.j(f).scaleSelf(l.e.devicePixelRatio),Y=new Map([[H.toString(),{image:z,imageVariant:H}]]),te=this._rasterizeImages(y,Y);return this.storePatternImage(H,y,z,w,te),null}this.storePattern(f,y,z)}return this._updatePatternAtlas(y,w),R.get(k).position}getPatternInFlightId(f,y){return l.m(f,y)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(f,y,w,k,R){const M=f.toString(),z=R?R.get(M):void 0;z&&(w.data=z,this.storePattern(f.id,y,w),this._updatePatternAtlas(y,k),this.patternsInFlight.delete(this.getPatternInFlightId(f.id.toString(),y)))}storePattern(f,y,w){const k={w:w.data.width+2*l.k,h:w.data.height+2*l.k,x:0,y:0},R=new l.l(k,w,l.k);this.patterns.get(y).set(f.toString(),{bin:k,position:R})}destroyAtlasTextures(){for(const f of this.atlasTexture.values())f&&f.destroy();this.atlasTexture.clear()}bind(f,y){const w=f.gl;let k=this.atlasTexture.get(y);k?this.dirty&&(k.update(this.atlasImage.get(y)),this.dirty=!1):(k=new l.T(f,this.atlasImage.get(y),w.RGBA8),this.atlasTexture.set(y,k)),k.bind(w.LINEAR,w.CLAMP_TO_EDGE)}_updatePatternAtlas(f,y){const w=this.patterns.get(f),k=Array.from(w.values()).map(({bin:H})=>H),{w:R,h:M}=l.p(k),z=this.atlasImage.get(f);z.resize({width:R||1,height:M||1});const V=this.images.get(f);for(const[H,{bin:Y,position:te}]of w.entries()){let ne=te.padding;const le=Y.x+ne,me=Y.y+ne,fe=V.get(H).data,Se=fe.width,Me=fe.height;ne=ne>1?ne-1:ne,l.b.copy(fe,z,{x:0,y:0},{x:le,y:me},{width:Se,height:Me},y),l.b.copy(fe,z,{x:0,y:Me-ne},{x:le,y:me-ne},{width:Se,height:ne},y),l.b.copy(fe,z,{x:0,y:0},{x:le,y:me+Me},{width:Se,height:ne},y),l.b.copy(fe,z,{x:Se-ne,y:0},{x:le-ne,y:me},{width:ne,height:Me},y),l.b.copy(fe,z,{x:0,y:0},{x:le+Se,y:me},{width:ne,height:Me},y),l.b.copy(fe,z,{x:Se-ne,y:Me-ne},{x:le-ne,y:me-ne},{width:ne,height:ne},y),l.b.copy(fe,z,{x:0,y:Me-ne},{x:le+Se,y:me-ne},{width:ne,height:ne},y),l.b.copy(fe,z,{x:0,y:0},{x:le+Se,y:me+Me},{width:ne,height:ne},y),l.b.copy(fe,z,{x:Se-ne,y:0},{x:le-ne,y:me+Me},{width:ne,height:ne},y)}this.dirty=!0}beginFrame(){for(const f of this.images.keys())this.callbackDispatchedThisFrame.set(f,new Set);this.imageAtlasCache.beginFrame()}dispatchRenderCallbacks(f,y){const w=this.images.get(y);for(const k of f){if(this.callbackDispatchedThisFrame.get(y).has(k.toString()))continue;this.callbackDispatchedThisFrame.get(y).add(k.toString());const R=w.get(k.toString());Re(R)&&this.updateImage(k,y,R)}}}class ci{constructor(f){this.pendingRequests=new Map,this.cachedRanges=new Map,this.fontstackCompositing=f&&f.fontstackCompositing||"client"}loadGlyphRange(f,y,w,k,R){if(this.fontstackCompositing==="server")return void ci.loadGlyphRange(f,y,w,k,R);const M=f.split(",").map(z=>z.trim()).filter(z=>z.length>0);M.length!==0?M.length!==1?this._loadMultipleFonts(M,y,w,k,R):this._loadFont(M[0],y,w,k,R):R(new Error("Empty fontstack"))}_loadMultipleFonts(f,y,w,k,R){const M=f.map(()=>null),z={completed:0,firstError:null,callbackCalled:!1},V=(H,Y,te)=>{if(!z.callbackCalled&&(Y&&!z.firstError&&(z.firstError=Y),te&&(M[H]=te),z.completed++,z.completed===f.length)){z.callbackCalled=!0;const ne=M.filter(me=>me!==null);if(ne.length===0)return void R(z.firstError||new Error("All fonts failed to load"));const le=this._composeGlyphs(ne);R(null,le)}};for(let H=0;H{V(H,Y,te)})}_loadFont(f,y,w,k,R){const M=`${f}:${y}`;if(this.cachedRanges.has(M)){const V=this.cachedRanges.get(M);return void l.e.frame(()=>R(null,V))}const z=this.pendingRequests.get(M);z?z.push(R):(this.pendingRequests.set(M,[R]),ci.loadGlyphRange(f,y,w,k,(V,H)=>{V||this.cachedRanges.set(M,H||null);const Y=this.pendingRequests.get(M);if(this.pendingRequests.delete(M),Y)for(const te of Y)te(V,H)}))}_composeGlyphs(f){const y={};let w,k;for(const R of f)if(w===void 0&&R.ascender!==void 0&&(w=R.ascender),k===void 0&&R.descender!==void 0&&(k=R.descender),R.glyphs)for(const M in R.glyphs)y[M]===void 0&&(y[M]=R.glyphs[M]);return{glyphs:y,ascender:w,descender:k}}}ci.loadGlyphRange=async function(_,f,y,w,k){const R=256*f,M=R+255;let z;try{const V=await w.transformRequest(w.normalizeGlyphsURL(y).replace("{fontstack}",_).replace("{range}",`${R}-${M}`),l.R.Glyphs),{data:H}=await l.n(V),Y={},te=l.q(H);for(const ne of te.glyphs)Y[ne.id]=ne;z={glyphs:Y,ascender:te.ascender,descender:te.descender}}catch(V){return k(V)}k(null,z)};class mo{constructor(f,y,w,k){this.requestManager=f,this.localGlyphs=new l.r({mode:y,fontFamily:w}),this.url="",this.entries={},this.glyphLoader=new ci({fontstackCompositing:k})}setURL(f){this.url=f}getGlyphs(f,y){const w=[],k=Object.keys(f),R=this.url||l.t.GLYPHS_URL;for(const M in f)for(const z of f[M])w.push({stack:M,id:z});l.u(w,({stack:M,id:z},V)=>{let H=this.entries[M];H||(H=this.entries[M]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let Y=H.glyphs[z];if(Y!==void 0)return void V(null,{stack:M,id:z,glyph:Y});if(Y=this.localGlyphs.draw(M,z),Y)return H.glyphs[z]=Y,void V(null,{stack:M,id:z,glyph:Y});const te=Math.floor(z/256);if(256*te>65535)return l.w("glyphs > 65535 not supported"),void V(null,{stack:M,id:z,glyph:Y});if(H.ranges[te])return void V(null,{stack:M,id:z,glyph:Y});let ne=H.requests[te];ne||(ne=H.requests[te]=[],this.glyphLoader.loadGlyphRange(M,te,R,this.requestManager,(le,me)=>{if(me){H.ascender=me.ascender,H.descender=me.descender;for(const fe in me.glyphs)this.localGlyphs.supports(+fe)||(H.glyphs[+fe]=me.glyphs[+fe]);H.ranges[te]=!0}for(const fe of ne)fe(le,me);delete H.requests[te]})),ne.push((le,me)=>{le?V(le):me&&V(null,{stack:M,id:z,glyph:me.glyphs[z]||null})})},(M,z)=>{if(M)y(M);else if(z){const V={};for(const H of k){const Y=this.entries[H];V[H]={glyphs:{},ascender:Y&&Y.ascender,descender:Y&&Y.descender}}for(const{stack:H,id:Y,glyph:te}of z)V[H].glyphs[Y]=te&&{id:te.id,bitmap:te.bitmap.clone(),metrics:te.metrics};y(null,V)}})}}class _r{constructor(f,y,w,k){this.message=(f?`${f}: `:"")+w,k&&(this.identifier=k),y!=null&&y.__line__&&(this.line=y.__line__)}}class Da extends _r{}function pn(_){const f=_.value,y=_.valueSpec,w=_.style,k=_.styleSpec,R=_.key,M=_.arrayElementValidator||_s;if(!Array.isArray(f))return[new _r(R,f,`array expected, ${l.y(f)} found`)];if(y.length&&f.length!==y.length)return[new _r(R,f,`array length ${y.length} expected, length ${f.length} found`)];if(y["min-length"]&&f.lengthk)return[new _r(f,y,`${y} is greater than the maximum value ${k}`)]}return[]}function Yi(_){const f=_.key,y=_.value;if(!l.v(y))return[new _r(f,y,`object expected, ${l.y(y)} found`)];const w=_.valueSpec,k=l.x(y.type);let R,M,z,V={};const H=k!=="categorical"&&y.property===void 0,Y=!H,te=function(fe){const Se=fe.stops;return Array.isArray(Se)&&Array.isArray(Se[0])&&l.v(Se[0][0])}(y),ne=Fo({key:_.key,value:_.value,valueSpec:_.styleSpec.function,style:_.style,styleSpec:_.styleSpec,objectElementValidators:{stops:function(fe){if(k==="identity")return[new _r(fe.key,fe.value,'identity function may not have a "stops" property')];let Se=[];const Me=fe.value;return Se=Se.concat(pn({key:fe.key,value:Me,valueSpec:fe.valueSpec,style:fe.style,styleSpec:fe.styleSpec,arrayElementValidator:le})),Array.isArray(Me)&&Me.length===0&&Se.push(new _r(fe.key,Me,"array must have at least one stop")),Se},default:function(fe){return _s({key:fe.key,value:fe.value,valueSpec:w,style:fe.style,styleSpec:fe.styleSpec})}}});return k==="identity"&&H&&ne.push(new _r(_.key,_.value,'missing required property "property"')),k==="identity"||y.stops||ne.push(new _r(_.key,_.value,'missing required property "stops"')),k==="exponential"&&w.expression&&!l.A(w)&&ne.push(new _r(_.key,_.value,"exponential functions not supported")),_.styleSpec.$version>=8&&(Y&&!l.B(w)?ne.push(new _r(_.key,_.value,"property functions not supported")):H&&!l.D(w)&&ne.push(new _r(_.key,_.value,"zoom functions not supported"))),k!=="categorical"&&!te||y.property!==void 0||ne.push(new _r(_.key,_.value,'"property" property is required')),ne;function le(fe){let Se=[];const Me=fe.value,qe=fe.key;if(!Array.isArray(Me))return[new _r(qe,Me,`array expected, ${l.y(Me)} found`)];if(Me.length!==2)return[new _r(qe,Me,`array length 2 expected, length ${Me.length} found`)];if(te){if(!l.v(Me[0]))return[new _r(qe,Me,`object expected, ${l.y(Me[0])} found`)];const Ne=Me[0];if(Ne.zoom===void 0)return[new _r(qe,Me,"object stop key must have zoom")];if(Ne.value===void 0)return[new _r(qe,Me,"object stop key must have value")];const We=l.x(Ne.zoom);if(typeof We!="number")return[new _r(qe,Ne.zoom,"stop zoom values must be numbers")];if(z&&z>We)return[new _r(qe,Ne.zoom,"stop zoom values must appear in ascending order")];We!==z&&(z=We,M=void 0,V={}),Se=Se.concat(Fo({key:`${qe}[0]`,value:Me[0],valueSpec:{zoom:{}},style:fe.style,styleSpec:fe.styleSpec,objectElementValidators:{zoom:Vi,value:me}}))}else Se=Se.concat(me({key:`${qe}[0]`,value:Me[0],style:fe.style,styleSpec:fe.styleSpec},Me));return l.F(l.G(Me[1]))?Se.concat([new _r(`${qe}[1]`,Me[1],"expressions are not allowed in function stops.")]):Se.concat(_s({key:`${qe}[1]`,value:Me[1],valueSpec:w,style:fe.style,styleSpec:fe.styleSpec}))}function me(fe,Se){const Me=l.y(fe.value),qe=l.x(fe.value),Ne=fe.value!==null?fe.value:Se;if(R){if(Me!==R)return[new _r(fe.key,Ne,`${Me} stop domain type must match previous stop domain type ${R}`)]}else R=Me;if(Me!=="number"&&Me!=="string"&&Me!=="boolean"&&typeof qe!="number"&&typeof qe!="string"&&typeof qe!="boolean")return[new _r(fe.key,Ne,"stop domain value must be a number, string, or boolean")];if(Me!=="number"&&k!=="categorical"){let We=`number expected, ${Me} found`;return l.B(w)&&k===void 0&&(We+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new _r(fe.key,Ne,We)]}return k!=="categorical"||Me!=="number"||typeof qe=="number"&&isFinite(qe)&&Math.floor(qe)===qe?k!=="categorical"&&Me==="number"&&typeof qe=="number"&&typeof M=="number"&&M!==void 0&&qenew _r(`${_.key}${w.key}`,_.value,w.message));const y=f.value.expression||f.value._styleExpression.expression;if(_.expressionContext==="property"&&_.propertyKey==="text-font"&&!y.outputDefined())return[new _r(_.key,_.value,`Invalid data expression for "${_.propertyKey}". Output values must be contained as literals within the expression.`)];if(_.expressionContext==="property"&&_.propertyType==="layout"&&!l.J(y))return[new _r(_.key,_.value,'"feature-state" data expressions are not supported with layout properties.')];if(_.expressionContext==="filter")return Ke(y,_);if(_.expressionContext==="appearance")return yt(y,_);if(_.expressionContext&&_.expressionContext.indexOf("cluster")===0){if(!l.K(y,["zoom","feature-state"]))return[new _r(_.key,_.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(_.expressionContext==="cluster-initial"&&!l.M(y))return[new _r(_.key,_.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Ke(_,f){const y=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(f.valueSpec&&f.valueSpec.expression)for(const k of f.valueSpec.expression.parameters)y.delete(k);if(y.size===0)return[];const w=[];return _ instanceof l.N&&y.has(_.name)?[new _r(f.key,f.value,`["${_.name}"] expression is not supported in a filter for a ${f.object.type} layer with id: ${f.object.id}`)]:(_.eachChild(k=>{w.push(...Ke(k,f))}),w)}const at=new Set(["get","has","properties","geometry-type","id"]);function yt(_,f){const y=new Set(["zoom","pitch","distance-from-center","feature","feature-state","measure-light","heatmap-density","line-progress","raster-value","raster-particle-speed","sky-radial-progress"]);if(f.valueSpec&&f.valueSpec.expression)for(const k of f.valueSpec.expression.parameters)y.delete(k);if(y.size===0)return[];const w=[];if(_ instanceof l.N){const k=at.has(_.name)?"feature":_.name;if(y.has(k))return[new _r(f.key,f.value,`["${_.name}"] is not an allowed parameter`)]}return _.eachChild(k=>{w.push(...yt(k,f))}),w}function rr(_){const f=_.key,y=_.value,w=_.valueSpec,k=[];return Array.isArray(w.values)?w.values.includes(l.x(y))||k.push(new _r(f,y,`expected one of [${w.values.join(", ")}], ${JSON.stringify(y)} found`)):Object.keys(w.values).includes(l.x(y))||k.push(new _r(f,y,`expected one of [${Object.keys(w.values).join(", ")}], ${JSON.stringify(y)} found`)),k}function Er(_){if(l.S(l.G(_.value))){const f=_.layerType||"fill";return nn({..._,expressionContext:"filter",valueSpec:_.styleSpec[`filter_${f}`]})}return Wr(_)}function Wr(_){const f=_.value,y=_.key;if(!Array.isArray(f))return[new _r(y,f,`array expected, ${l.y(f)} found`)];if(f.length<1)return[new _r(y,f,"filter array must have at least 1 element")];const w=_.styleSpec;let k=rr({key:`${y}[0]`,value:f[0],valueSpec:w.filter_operator});const R=()=>{f.length>=2&&(l.Q(f[1])||k.push(new _r(`${y}[1]`,f[1],`string expected, ${l.y(f[1])} found`)));for(let M=2;M":case">=":f.length>=2&&l.x(f[1])==="$type"&&k.push(new _r(y,f,`"$type" cannot be use with operator "${f[0]}"`)),f.length!==3&&k.push(new _r(y,f,`filter array for operator "${f[0]}" must have 3 elements`)),R();break;case"==":case"!=":f.length!==3&&k.push(new _r(y,f,`filter array for operator "${f[0]}" must have 3 elements`)),R();break;case"in":case"!in":R();break;case"any":case"all":case"none":for(let M=1;M{H in y&&f.push(new _r(w,y[H],`"${H}" is prohibited for ref layers`))}),k.layers.forEach(H=>{l.x(H.id)===z&&(V=H)}),V?V.ref?f.push(new _r(w,y.ref,"ref cannot reference another ref layer")):M=l.x(V.type):typeof z=="string"&&f.push(new _r(w,y.ref,`ref layer "${z}" not found`))}else if(M!=="background"&&M!=="sky"&&M!=="slot"&&M!=="placement-group")if(y.source)if(l.Q(y.source)){const V=k.sources&&Object.hasOwn(k.sources,y.source)?k.sources[y.source]:void 0,H=V&&l.x(V.type);V?H==="vector"&&M==="raster"?f.push(new _r(w,y.source,`layer "${y.id}" requires a raster source`)):H==="raster"&&M!=="raster"?f.push(new _r(w,y.source,`layer "${y.id}" requires a vector source`)):H!=="vector"||y["source-layer"]?H==="raster-dem"&&M!=="hillshade"?f.push(new _r(w,y.source,"raster-dem source can only be used with layer type 'hillshade'.")):H!=="raster-array"||["raster","raster-particle"].includes(M)?M==="line"&&y.paint&&y.paint["line-gradient"]&&H==="geojson"&&!V.lineMetrics?f.push(new _r(w,y,`layer "${y.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):M==="line"&&y.paint&&y.paint["line-trim-offset"]&&H==="geojson"&&!V.lineMetrics?f.push(new _r(w,y,`layer "${y.id}" specifies a line-trim-offset, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):M==="raster-particle"&&H!=="raster-array"&&f.push(new _r(w,y.source,`layer "${y.id}" requires a 'raster-array' source.`)):f.push(new _r(w,y.source,"raster-array source can only be used with layer type 'raster'.")):f.push(new _r(w,y,`layer "${y.id}" must specify a "source-layer"`)):f.push(new _r(w,y.source,`source "${y.source}" not found`))}else f.push(new _r(`${w}.source`,y.source,'"source" must be a string'));else f.push(new _r(w,y,'missing required property "source"'));if(M==="raster"&&l.v(y.paint)){const V=y.paint,H=l.x(V["raster-mask"]),Y=l.x(V["raster-mask-import"]);if(l.Q(H)&&H)if(l.Q(Y)&&Y)(k.imports||[]).some(te=>l.x(te.id)===Y)||f.push(new _r(`${w}.paint.raster-mask-import`,V["raster-mask-import"],`import "${Y}" not found`));else{const te=(k.layers||[]).find(ne=>l.x(ne.id)===H);te?l.x(te.type)!=="fill"&&f.push(new _r(`${w}.paint.raster-mask`,V["raster-mask"],`layer "${H}" must be a "fill" layer`)):f.push(new _r(`${w}.paint.raster-mask`,V["raster-mask"],`layer "${H}" not found`))}}return f=f.concat(Fo({key:w,value:y,valueSpec:R.layer,style:_.style,styleSpec:_.styleSpec,objectElementValidators:{"*":()=>[],type:()=>_s({key:`${w}.type`,value:y.type,valueSpec:R.layer.type,style:_.style,styleSpec:_.styleSpec,object:y,objectKey:"type"}),filter:V=>Er({layerType:M,...V}),layout:V=>Fo({layer:y,key:V.key,value:V.value,valueSpec:{},style:V.style,styleSpec:V.styleSpec,objectElementValidators:{"*":H=>qn({layerType:M,...H})}}),paint:V=>Fo({layer:y,key:V.key,value:V.value,valueSpec:{},style:V.style,styleSpec:V.styleSpec,objectElementValidators:{"*":H=>$r({layerType:M,layer:y,...H})}}),appearances(V){const H=pn({key:V.key,value:V.value,valueSpec:V.valueSpec,style:V.style,styleSpec:V.styleSpec,arrayElementValidator:ne=>function(le){const{key:me,layer:fe,layerType:Se}=le,Me=l.x(le.value),qe=l.x(Me.name),Ne=l.x(Me.condition),We=Fo({key:me,value:Me,valueSpec:le.styleSpec.appearance,style:le.style,styleSpec:le.styleSpec,objectElementValidators:{condition:ct=>function(it){const pt=[];return pt.push(...nn({key:it.key,value:it.object.condition,valueSpec:it.styleSpec.appearance.condition,expressionContext:"appearance"})),pt}({...ct}),properties:ct=>function(it){const pt=[],{styleSpec:dt,layer:mt,layerType:xt}=it,bt=dt[`paint_${xt}`],Ft=dt[`layout_${xt}`],Lt=it.object[it.objectKey];for(const Mt in Lt){const or=Mt in bt?"paint":Mt in Ft?"layout":void 0;if(!or){pt.push(new _r(it.key,Mt,`unknown property "${Mt}" for layer type "${xt}"`));continue}const fr={...it,key:`${it.key}.${Mt}`,objectKey:Mt,layer:mt,layerType:xt,value:Lt[Mt],valueSpec:or==="paint"?bt[Mt]:Ft[Mt]};pt.push(...Zr(fr,or))}return pt}({layer:fe,layerType:Se,...ct})}});return qe!=="hidden"&&Ne===void 0&&We.push(new _r(le.key,"name",'Appearance with name different than "hidden" must have a condition')),We}({layerType:M,layer:y,...ne})}),Y=Array.isArray(V.value)?V.value:[],te=new Set;return Y.forEach((ne,le)=>{const me=l.x(ne.name);if(me)if(te.has(me)){const fe=l.x(y.id);H.push(new _r(V.key,me,`Duplicated appearance name "${me}" for layer "${fe}"`))}else te.add(me)}),H}}})),f}function xs({key:_,value:f}){return l.Q(f)?[]:[new _r(_,f,`string expected, ${l.y(f)} found`)]}const Ea={promoteId:function _({key:f,value:y}){if(l.Q(y))return xs({key:f,value:y});if(Array.isArray(y)){const k=[],R=l.G(y),M=l.c(R);return M.result==="error"?(M.value.forEach(z=>{k.push(new _r(`${f}${z.key}`,null,`${z.message}`))}),k):(l.K(M.value.expression,["zoom","heatmap-density","line-progress","raster-value","sky-radial-progress","accumulated","is-supported-script","pitch","distance-from-center","measure-light","raster-particle-speed"])||k.push(new _r(`${f}`,null,"promoteId expression should be only feature dependent")),k)}if(!l.v(y))return[new _r(f,y,`string, expression or object expected, "${l.y(y)}" found`)];const w=[];for(const k in y)w.push(..._({key:`${f}.${k}`,value:y[k]}));return w}};function jt(_){const f=_.value,y=_.key,w=_.styleSpec,k=_.style;if(!l.v(f))return[new _r(y,f,`object expected, ${l.y(f)} found`)];if(!("type"in f))return[new _r(y,f,'"type" is required')];const R=l.x(f.type);let M=[];switch(["vector","raster","raster-dem","raster-array"].includes(R)&&("url"in f||"tiles"in f||M.push(new Da(y,f,'Either "url" or "tiles" is required.'))),R){case"vector":case"raster":case"raster-dem":case"raster-array":return M=M.concat(Fo({key:y,value:f,valueSpec:w[`source_${R.replace("-","_")}`],style:_.style,styleSpec:w,objectElementValidators:Ea})),M;case"geojson":if(M=Fo({key:y,value:f,valueSpec:w.source_geojson,style:k,styleSpec:w,objectElementValidators:Ea}),"cluster"in f&&"clusterProperties"in f){if(!l.v(f.clusterProperties))return[new _r(`${y}.clusterProperties`,f,`object expected, ${l.y(f)} found`)];for(const z in f.clusterProperties){const V=f.clusterProperties[z];if(!Array.isArray(V))return[new _r(`${y}.clusterProperties.${z}`,V,"array expected")];const[H,Y]=V,te=typeof H=="string"?[H,["accumulated"],["get",z]]:H;M.push(...nn({key:`${y}.${z}.map`,value:Y,expressionContext:"cluster-map"})),M.push(...nn({key:`${y}.${z}.reduce`,value:te,expressionContext:"cluster-reduce"}))}}return M;case"video":return Fo({key:y,value:f,valueSpec:w.source_video,style:k,styleSpec:w});case"image":return Fo({key:y,value:f,valueSpec:w.source_image,style:k,styleSpec:w});case"canvas":return[new _r(y,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return rr({key:`${y}.type`,value:f.type,valueSpec:{values:Ha(w)}})}}function Ha(_){return _.source.reduce((f,y)=>{const w=_[y];return w.type.type==="enum"&&(f=f.concat(Object.keys(w.type.values||{}))),f},[])}function wh(_,f){const y=!_.includes("://");try{return new URL(_,y&&f?"http://example.com":void 0),!0}catch{return!1}}function Ud(_){const f=_.value;return f?l.Q(f)?wh(f,!0)?[]:[new _r(_.key,f,`invalid url "${f}"`)]:[new _r(_.key,f,`string expected, "${l.y(f)}" found`)]:[]}function mf(_){const f=_.value,y=_.styleSpec,w=y.light,k=_.style;if(f===void 0)return[];if(!l.v(f))return[new _r("light",f,`object expected, ${l.y(f)} found`)];let R=[];for(const M in f){const z=M.match(l.V),V=M.match(l.U);R=R.concat(V&&w[V[1]]?_s({key:M,value:f[M],valueSpec:{type:"string"},style:k,styleSpec:y}):z&&w[z[1]]&&w[z[1]].transition?_s({key:M,value:f[M],valueSpec:y.transition,style:k,styleSpec:y}):w[M]?_s({key:M,value:f[M],valueSpec:w[M],style:k,styleSpec:y}):[new _r(M,f[M],`unknown property "${M}"`)])}return R}function Sh(_){const f=_.value;if(!f)return[];const y=_.key;if(!l.v(f))return[new _r(y,f,`object expected, ${l.y(f)} found`)];let w=[];const k=_.styleSpec,R=k["light-3d"],M=_.style,z=_.style.lights;for(const Y of["type","id"])if(!(Y in f))return w=w.concat([new _r(y,f,`missing property "${Y}"`)]),w;if(!l.Q(f.type))return w=w.concat([new _r(`${y}.type`,f.type,"string expected")]),w;if(z)for(let Y=0;Y<_.arrayIndex;Y++){const te=l.x(f.type),ne=z[Y];l.x(ne.type)===te&&w.push(new _r(y,f.id,`duplicate light type "${f.type}", previously defined at line ${ne.id.__line__}`))}const V=`properties_light_${f.type}`;if(!(V in k))return w=w.concat([new _r(`${y}.type`,f,`Invalid light type ${f.type}`)]),w;const H=k[V];for(const Y in f)if(Y==="properties"){const te=f[Y];if(!l.v(te))return w=w.concat([new _r("properties",te,`object expected, ${l.y(te)} found`)]),w;for(const ne in te){const le=ne.match(l.V),me=ne.match(l.U);w=w.concat(me&&H[me[1]]?_s({key:ne,value:te[ne],valueSpec:{type:"string"},style:M,styleSpec:k}):le&&H[le[1]]&&H[le[1]].transition?_s({key:ne,value:te[ne],valueSpec:k.transition,style:M,styleSpec:k}):H[ne]?_s({key:ne,value:te[ne],valueSpec:H[ne],style:M,styleSpec:k}):[new Da(_.key,te[ne],`unknown property "${ne}"`)])}}else w=w.concat(R[Y]?_s({key:Y,value:f[Y],valueSpec:R[Y],style:M,styleSpec:k}):[new Da(Y,f[Y],`unknown property "${Y}"`)]);return w}function cu(_){const f=_.value,y=_.key,w=_.style,k=_.styleSpec,R=k.terrain;if(f==null)return[];if(!l.v(f))return[new _r("terrain",f,`object expected, ${l.y(f)} found`)];let M=[];for(const z in f){const V=z.match(l.V),H=z.match(l.U);M=M.concat(H&&R[H[1]]?_s({key:z,value:f[z],valueSpec:{type:"string"},style:w,styleSpec:k}):V&&R[V[1]]&&R[V[1]].transition?_s({key:z,value:f[z],valueSpec:k.transition,style:w,styleSpec:k}):R[z]?_s({key:z,value:f[z],valueSpec:R[z],style:w,styleSpec:k}):[new Da(z,f[z],`unknown property "${z}"`)])}if(f.source)if(l.Q(f.source)){const z=w.sources&&Object.hasOwn(w.sources,f.source)?w.sources[f.source]:void 0,V=z&&l.x(z.type);z?V!=="raster-dem"&&M.push(new _r(`${y}.source`,f.source,`terrain cannot be used with a source of type ${V}, it only be used with a "raster-dem" source type`)):M.push(new _r(`${y}.source`,f.source,`source "${f.source}" not found`))}else M.push(new _r(`${y}.source`,f.source,"source must be a string"));else M.push(new _r(y,f,'terrain is missing required property "source"'));return M}function Ig(_){const f=_.value,y=_.style,w=_.styleSpec,k=w.fog;if(f===void 0)return[];if(!l.v(f))return[new _r("fog",f,`object expected, ${l.y(f)} found`)];let R=[];for(const M in f){const z=M.match(l.V),V=M.match(l.U);R=R.concat(V&&k[V[1]]?_s({key:M,value:f[M],valueSpec:{type:"string"},style:y,styleSpec:w}):z&&k[z[1]]&&k[z[1]].transition?_s({key:M,value:f[M],valueSpec:w.transition,style:y,styleSpec:w}):k[M]?_s({key:M,value:f[M],valueSpec:k[M],style:y,styleSpec:w}):[new Da(M,f[M],`unknown property "${M}"`)])}return R}const em={"*":()=>[],array:pn,boolean:function(_){const f=_.value,y=_.key;return l.O(f)?[]:[new _r(y,f,`boolean expected, ${l.y(f)} found`)]},number:Vi,color:function({key:_,value:f}){return l.Q(f)?l.C.parse(l.x(f))===void 0?[new _r(_,f,`color expected, "${f}" found`)]:[]:[new _r(_,f,`color expected, ${l.y(f)} found`)]},enum:rr,filter:Er,function:Yi,layer:ki,object:Fo,source:jt,model:Ud,light:mf,"light-3d":Sh,terrain:cu,fog:Ig,string:xs,formatted:function(_){return xs(_).length===0?[]:nn(_)},resolvedImage:function(_){return xs(_).length===0?[]:nn(_)},projection:function(_){const f=_.value,y=_.styleSpec,w=y.projection,k=_.style;if(l.v(f)){let R=[];for(const M in f)R=R.concat(_s({key:M,value:f[M],valueSpec:w[M],style:k,styleSpec:y}));return R}return l.Q(f)?[]:[new _r("projection",f,`object or string expected, ${l.y(f)} found`)]},import:function(_){const f=_.key,{value:y,styleSpec:w}=_;if(!l.v(y))return[new _r(f,y,"import must be an object")];const{data:k,...R}=y;Object.defineProperty(R,"__line__",{value:y.__line__,enumerable:!1});let M=Fo({..._,value:R,valueSpec:w.import});l.x(R.id)===""&&M.push(new _r(`${_.key}.id`,R,"import id can't be an empty string"));const z=l.x(R.id);return z!=="__proto__"&&z!=="constructor"&&z!=="prototype"||M.push(new _r(`${_.key}.id`,R,`import id can't be "${String(z)}"`)),k&&(M=M.concat(Dw(k,w,{key:`${_.key}.data`}))),M},iconset:function(_){const f=_.value,y=_.key,w=_.styleSpec,k=_.style;if(!l.v(f))return[new _r(y,f,"object expected")];if(!f.type)return[new _r(y,f,'"type" is required')];const R=l.x(f.type);let M=[];if(M=M.concat(Fo({key:y,value:f,valueSpec:w[`iconset_${R}`],style:k,styleSpec:w})),function(z,V){return!(z!=="source"||!V.source)}(R,f)){const z=k.sources&&Object.hasOwn(k.sources,f.source)?k.sources[f.source]:void 0,V=z&&l.x(z.type);z?V!=="raster-array"&&M.push(new _r(y,f.source,`iconset cannot be used with a source of type ${String(V)}, it only be used with a "raster-array" source type`)):M.push(new _r(y,f.source,`source "${f.source}" not found`))}return M},option:function(_){const f=_.styleSpec,y=_.value,w=l.v(y)&&l.x(y.array)===!0||!l.v(y)?void 0:l.x(y.type);return Fo({..._,valueSpec:f.option,objectElementValidators:{default:k=>{const R=k.value;return l.v(R)?_s({...k,valueSpec:{...k.valueSpec,type:"*",expression:void 0}}):w&&Array.isArray(R)?_s({...k,valueSpec:{...k.valueSpec,type:w}}):_s(k)}}})}};function _s(_,f=!1){const y=_.value,w=_.valueSpec,k=_.styleSpec;if(w.expression){if(l.W(l.x(y)))return Yi(_);if(l.F(l.G(y)))return nn(_)}if(w.type&&em[w.type]){const R=em[w.type](_);return f===!0&&R.length>0&&Array.isArray(_.value)?nn(_):R}return Fo({..._,valueSpec:w.type?k[w.type]:w})}function Fo(_){const f=_.key,y=_.value,w=_.valueSpec||{},k=_.objectElementValidators||{},R=_.style,M=_.styleSpec;if(!l.v(y))return[new _r(f,y,`object expected, ${l.y(y)} found`)];let z=[];for(const V in y){if(!Object.hasOwn(y,V))continue;const H=V.split(".")[0],Y=Object.hasOwn(w,H),te=Object.hasOwn(w,"*"),ne=Y?w[H]:te?w["*"]:void 0;let le;Object.hasOwn(k,H)?le=k[H]:Y?le=_s:Object.hasOwn(k,"*")?le=k["*"]:te&&(le=_s),le?z=z.concat(le({key:(f&&`${f}.`)+V,value:y[V],valueSpec:ne,style:R,styleSpec:M,object:y,objectKey:V},y)):z.push(new Da(f,y[V],`unknown property "${V}"`))}for(const V in w){if(!Object.hasOwn(w,V)||Object.hasOwn(k,V))continue;const H=w[V];!H.required||H.default!==void 0||Object.hasOwn(y,V)&&y[V]!==void 0||z.push(new _r(f,y,`missing required property "${V}"`))}return z}function WA({key:_,value:f}){const y=xs({key:_,value:f});if(y.length)return y;const w=f;return w.includes("{fontstack}")||y.push(new _r(_,f,'"glyphs" url must include a "{fontstack}" token')),w.includes("{range}")||y.push(new _r(_,f,'"glyphs" url must include a "{range}" token')),y}function Dw(_,f=l.s,y={}){return Fo({key:y.key||"",value:_,valueSpec:{...f.$root,"*":{type:"*"}},styleSpec:f,style:_,objectElementValidators:{glyphs:WA}})}function io(_){return _.slice().sort((f,y)=>f.line&&y.line?f.line-y.line:0)}const Vd="setStyle",jg="addLayer",up="removeLayer",t0="setPaintProperty",tm="setLayerProperty",Mw="setTerrain",Bn="removeImport",po="addIconset",Ow="removeIconset";function fx(_,f,y){y.push({command:"addSource",args:[_,f[_]]})}function mx(_,f,y){f.push({command:"removeSource",args:[_]}),y[_]=!0}function cn(_,f,y,w){mx(_,y,w),fx(_,f,y)}function rm(_,f,y){let w;for(w in _[y])if(Object.hasOwn(_[y],w)&&w!=="data"&&!l.Y(_[y][w],f[y][w]))return!1;for(w in f[y])if(Object.hasOwn(f[y],w)&&w!=="data"&&!l.Y(_[y][w],f[y][w]))return!1;return!0}function uu(_,f,y,w,k,R){let M;for(M in f=f||{},_=_||{})Object.hasOwn(_,M)&&(l.Y(_[M],f[M])||y.push({command:R,args:[w,M,f[M],k]}));for(M in f)Object.hasOwn(f,M)&&!Object.hasOwn(_,M)&&(l.Y(_[M],f[M])||y.push({command:R,args:[w,M,f[M],k]}))}function cd(_){return _.id}function Cg(_,f){return _[f.id]=f,_}const dp=new l.C(1,0,0,1),r0=new l.C(0,1,0,1),Pg=new l.C(0,0,1,1),n0=new l.C(1,0,1,1),px=new l.C(0,1,1,1);function qd(_,f,y,w,k,R,M){const z=_.context,V=_.transform,H=z.gl,Y=V.projection.name==="globe",te=Y?["PROJECTION_GLOBE_VIEW"]:[];let ne=l.Z(y.projMatrix);if(Y&&l._(V.zoom)>0){const Ft=l.$(y.canonical,V),Lt=l.a0(Ft);ne=l.a1(new Float32Array(16),V.globeMatrix,Lt),l.a1(ne,V.projMatrix,ne)}const le=l.a2();le[12]+=2*k/(l.e.devicePixelRatio*V.width),le[13]+=2*R/(l.e.devicePixelRatio*V.height),l.a1(ne,le,ne);const me=_.getOrCreateProgram("debug",{defines:te}),fe=f.getTileByID(y.key);_.terrain&&_.terrain.setupElevationDraw(fe,me);const Se=l.a3.disabled,Me=l.a4.disabled,qe=_.colorModeForRenderPass(),Ne="$debug";z.activeTexture.set(H.TEXTURE0),_.emptyTexture.bind(H.LINEAR,H.CLAMP_TO_EDGE),Y?fe._makeGlobeTileDebugBuffers(_.context,V):fe._makeDebugTileBoundsBuffers(_.context,V.projection);const We=fe._tileDebugBuffer||_.debugBuffer,ct=fe._tileDebugIndexBuffer||_.debugIndexBuffer,it=fe._tileDebugSegments||_.debugSegments;if(me.draw(_,H.LINE_STRIP,Se,Me,qe,l.a5.disabled,l.a6(ne,w.toPremultipliedRenderColor(null)),Ne,We,ct,it,null,null,null,[fe._globeTileDebugBorderBuffer]),M){const Ft=fe.latestRawTileData,Lt=Math.floor((Ft&&Ft.byteLength||0)/1024);let Mt=y.canonical.toString();y.overscaledZ!==y.canonical.z&&(Mt+=` => ${y.overscaledZ}`),Mt+=` ${fe.state}`,Mt+=` ${Lt}kb`,function(or,fr){or.initDebugOverlayCanvas();const Cr=or.debugOverlayCanvas,qr=or.context.gl,qt=or.debugOverlayCanvas.getContext("2d");qt.clearRect(0,0,Cr.width,Cr.height),qt.shadowColor="white",qt.shadowBlur=2,qt.lineWidth=1.5,qt.strokeStyle="white",qt.textBaseline="top",qt.font="bold 36px Open Sans, sans-serif",qt.fillText(fr,5,5),qt.strokeText(fr,5,5),or.debugOverlayTexture.update(Cr),or.debugOverlayTexture.bind(qr.LINEAR,qr.CLAMP_TO_EDGE)}(_,Mt)}const pt=f.getTile(y).tileSize,dt=512/Math.min(pt,512)*(y.overscaledZ/V.zoom)*.5,mt=fe._tileDebugTextBuffer||_.debugBuffer,xt=fe._tileDebugTextIndexBuffer||_.quadTriangleIndexBuffer,bt=fe._tileDebugTextSegments||_.debugSegments;me.draw(_,H.TRIANGLES,Se,Me,l.a7.alphaBlended,l.a5.disabled,l.a6(ne,l.C.transparent.toPremultipliedRenderColor(null),dt),Ne,mt,xt,bt,null,null,null,[fe._globeTileDebugTextBuffer])}function ud(_,f,y,w){hp(_,0,f+y/2,_.transform.width,y,w)}function i0(_,f,y,w){hp(_,f-y/2,0,y,_.transform.height,w)}function hp(_,f,y,w,k,R){const M=_.context,z=M.gl;z.enable(z.SCISSOR_TEST),z.scissor(f*l.e.devicePixelRatio,y*l.e.devicePixelRatio,w*l.e.devicePixelRatio,k*l.e.devicePixelRatio),M.clear({color:R}),z.disable(z.SCISSOR_TEST)}function Xi(_,f,y){const w=_.context,k=w.gl,R=y.projMatrix,M=_.getOrCreateProgram("debug"),z=f.getTileByID(y.key);_.terrain&&_.terrain.setupElevationDraw(z,M);const V=l.a3.disabled,H=l.a4.disabled,Y=_.colorModeForRenderPass(),te="$debug";w.activeTexture.set(k.TEXTURE0),_.emptyTexture.bind(k.LINEAR,k.CLAMP_TO_EDGE);const ne=z.queryGeometryDebugViz,le=z.queryBoundsDebugViz;if(ne&&ne.vertices.length>0){ne.lazyUpload(w);const me=ne.vertexBuffer,fe=ne.indexBuffer,Se=ne.segments;me!=null&&fe!=null&&Se!=null&&M.draw(_,k.LINE_STRIP,V,H,Y,l.a5.disabled,l.a6(R,ne.color.toPremultipliedRenderColor(null)),te,me,fe,Se)}if(le&&le.vertices.length>0){le.lazyUpload(w);const me=le.vertexBuffer,fe=le.indexBuffer,Se=le.segments;me!=null&&fe!=null&&Se!=null&&M.draw(_,k.LINE_STRIP,V,H,Y,l.a5.disabled,l.a6(R,le.color.toPremultipliedRenderColor(null)),te,me,fe,Se)}}const Eh=(_,f,y,w,k,R,M,z)=>{const V=l.ac/R.tileSize;return{u_matrix:_,u_inv_rot_matrix:f,u_camera_to_center_distance:y.getCameraToCenterDistance(z),u_extrude_scale:[y.pixelsToGLUnits[0]/V,y.pixelsToGLUnits[1]/V],u_zoom_transition:w,u_tile_id:M,u_merc_center:k}},gx=(_,f,y,w)=>({u_matrix:_,u_inv_matrix:f,u_camera_to_center_distance:y.getCameraToCenterDistance(w),u_viewport_size:[y.width,y.height]});let pf;const fp=(_,f,y,w,k,R)=>({u_viewport_size:_,u_color:f,u_outline_width:y,u_opacity:w,u_stroke_opacity:k,u_collision_padding_opacity:R}),nm=[{status:1,color:new l.C(1,0,0,1).toPremultipliedRenderColor(null)},{status:2,color:new l.C(1,1,0,1).toPremultipliedRenderColor(null)},{status:3,color:new l.C(1,0,1,1).toPremultipliedRenderColor(null)},{status:0,color:new l.C(0,0,1,1).toPremultipliedRenderColor(null)}];function Gd(_,f,y,w,k,R){let M,z,V,H,Y;w.kind==="box"?(M=.5*(w.left+w.right),z=.5*(w.top+w.bottom),V=.5*(w.right-w.left),H=.5*(w.bottom-w.top),Y=0):(M=w.x,z=w.y,V=w.radius,H=w.radius,Y=1);const te=y.prepareSegment(4,_,f),ne=te.vertexLength;for(let le=0;le<4;le++)_.emplaceBack(M*R,z*R,V*R,H*R,k*R,Y,le);f.emplaceBack(ne,ne+1,ne+2),f.emplaceBack(ne,ne+2,ne+3),te.vertexLength+=4,te.primitiveLength+=2}const du={loaded:!0,validateStyle:function(_,f=l.s){return io(Dw(_,f))},validateSource:_=>io(jt(_)),validateLight:_=>io(mf(_)),validateLights:_=>io(Sh(_)),validateTerrain:_=>io(cu(_)),validateFog:_=>io(Ig(_)),validateSnow:_=>io(function(f){const y=f.value,w=f.style,k=f.styleSpec,R=k.snow;if(y===void 0)return[];if(!l.v(y))return[new _r("snow",y,`object expected, ${l.y(y)} found`)];let M=[];for(const z in y){const V=z.match(l.V);M=M.concat(V&&R[V[1]]&&R[V[1]].transition?_s({key:z,value:y[z],valueSpec:k.transition,style:w,styleSpec:k}):R[z]?_s({key:z,value:y[z],valueSpec:R[z],style:w,styleSpec:k}):[new Da(z,y[z],`unknown property "${z}"`)])}return M}(_)),validateRain:_=>io(function(f){const y=f.value,w=f.style,k=f.styleSpec,R=k.rain;if(y===void 0)return[];if(!l.v(y))return[new _r("rain",y,`object expected, ${l.y(y)} found`)];let M=[];for(const z in y){const V=z.match(l.V);M=M.concat(V&&R[V[1]]&&R[V[1]].transition?_s({key:z,value:y[z],valueSpec:k.transition,style:w,styleSpec:k}):R[z]?_s({key:z,value:y[z],valueSpec:R[z],style:w,styleSpec:k}):[new Da(z,y[z],`unknown property "${z}"`)])}return M}(_)),validateLayer:_=>io(ki(_)),validateFilter:_=>io(Er(_)),validatePaintProperty:_=>io($r(_)),validateLayoutProperty:_=>io(qn(_)),validateModel:_=>io(Ud(_)),diffStyles:function(_,f){if(!_)return[{command:Vd,args:[f]}];let y=[];try{if(!l.Y(_.version,f.version))return[{command:Vd,args:[f]}];if(l.Y(_.center,f.center)||y.push({command:"setCenter",args:[f.center]}),l.Y(_.zoom,f.zoom)||y.push({command:"setZoom",args:[f.zoom]}),l.Y(_.bearing,f.bearing)||y.push({command:"setBearing",args:[f.bearing]}),l.Y(_.pitch,f.pitch)||y.push({command:"setPitch",args:[f.pitch]}),l.Y(_.sprite,f.sprite)||y.push({command:"setSprite",args:[f.sprite]}),l.Y(_.glyphs,f.glyphs)||y.push({command:"setGlyphs",args:[f.glyphs]}),l.Y(_.imports,f.imports)||function(z=[],V=[],H){V=V||[];const Y=(z=z||[]).map(cd),te=V.map(cd),ne=z.reduce(Cg,{}),le=V.reduce(Cg,{}),me=Y.slice();let fe,Se,Me,qe;for(fe=0,Se=0;fe{z.source&&w[z.source]?y.push({command:up,args:[z.id]}):R.push(z)});let M=_.terrain;M&&w[M.source]&&(y.push({command:Mw,args:[void 0]}),M=void 0),y=y.concat(k),l.Y(M,f.terrain)||y.push({command:Mw,args:[f.terrain]}),function(z,V,H){V=V||[];const Y=(z=z||[]).map(cd),te=V.map(cd),ne=z.reduce(Cg,{}),le=V.reduce(Cg,{}),me=Y.slice(),fe=Object.create(null);let Se,Me,qe,Ne,We,ct,it;for(Se=0,Me=0;Se0){const kr=l.a2(),vn=ur;l.ag(kr,bt.placementInvProjMatrix,H.glCoordMatrix),l.ag(kr,kr,bt.placementViewportMatrix),Se.push({circleArray:mr,circleOffset:qe,transform:vn,invTransform:kr,projection:bt.getProjection()}),Me+=mr.length/4,qe=Me}if(!Xt)continue;_.terrain&&_.terrain.setupElevationDraw(xt,Pr);const tn=Ut?[mt.canonical.x,mt.canonical.y,1<{const me=new l.aj;for(const fe of f)if(fe.status===le)for(const Se of fe.geometry)Gd(M,z,me,Se,fe.collisionPadding,R);return me});if(M.length===0)return;const H=y.createVertexBuffer(M,l.an.members,!0),Y=y.createIndexBuffer(z,!0),te=_.getOrCreateProgram("placementDebug"),ne=[k.width*R,k.height*R];for(let le=0;le{const y=du[_];return y?y(...f):[]}}const Hd=Uc("validateStyle"),a0=Uc("validateSource"),Fw=Uc("validateLight"),o0=Uc("validateLights"),Th=Uc("validateTerrain"),Bw=Uc("validateFog"),yx=Uc("validateSnow"),zw=Uc("validateRain"),xx=Uc("validateLayer"),dd=Uc("validateFilter"),im=Uc("validatePaintProperty"),$w=Uc("validateLayoutProperty"),hu=Uc("validateModel");class gf extends l.E{constructor(f,y,w){super(),this.scope=y,this._transitionable=new l.ao(f,y,w),this.properties=new l.ap(f)}_setValues(f,y){this._values=f,this._transitionable.setTransitionOrValue(f,y?new Map(y):void 0)}updateConfig(f){this._transitionable.setTransitionOrValue(this._values,new Map(f))}resetConfig(f){this.updateConfig(f),this._transitionable.snap()}updateTransitions(f){this._transitionable.updateTransitions(f)}hasTransition(){return this._transitionable.hasTransition()}recalculate(f){this.properties=this._transitionable.possiblyEvaluate(f)}_validate(f,y,w){return(!w||w.validate!==!1)&&s0(this,f.call(Hd,{value:y,style:{glyphs:!0,sprite:!0},styleSpec:l.s}))}}const Cn=l.s.light;let _x;class ye extends gf{constructor(f,y="flat"){super(_x||(_x=new l.aq({anchor:new l.ar(Cn.anchor),position:new l.as(Cn.position),color:new l.ar(Cn.color),intensity:new l.ar(Cn.intensity)}))),this.setLight(f,y),this._transitionable.snap()}getLight(){return this._transitionable.serialize()}setLight(f,y,w={}){this._validate(Fw,f,w)||(this._setValues(f),this.id=y)}}const re=l.s.terrain;let he=class extends gf{constructor(_,f,y,w,k){super(new l.aq({source:new l.ar(re.source),exaggeration:new l.ar(re.exaggeration)}),y,w),this._transitionable.setTransitionOrValue(_,w),this._transitionable.snap(),this.drapeRenderMode=f,this.worldview=k}get(){return this._transitionable.serialize()}set(_,f){this._transitionable.setTransitionOrValue(_,f)}getExaggeration(_){return l.at(this._transitionable._values.exaggeration.state,new l.au(_,{worldview:this.worldview}))}getAttenuationRange(){if(!this.isZoomDependent())return null;const _=this._transitionable._values.exaggeration.value.expression;let f=-1,y=-1,w=1;for(const k of _.zoomStops)w=_.evaluate(new l.au(k,{worldview:this.worldview})),w>.01?(f=k,y=-1):y=k;return w<.01&&f>0&&y>f?[f,y]:null}isZoomDependent(){return this._transitionable._values.exaggeration.value.expression instanceof l.av}};function _e(_,f){const y=_?_.terrain:null;return!!y&&(!f||!!f.projection.requiresDraping||!y.isZoomDependent()||y.getExaggeration(f.zoom)>0)}const je=l.s.fog;class Oe extends gf{constructor(f,y,w,k){super(new l.aq({range:new l.ar(je.range),color:new l.ar(je.color),"color-use-theme":new l.ar({type:"string","property-type":"data-constant",default:"default"}),"high-color":new l.ar(je["high-color"]),"high-color-use-theme":new l.ar({type:"string","property-type":"data-constant",default:"default"}),"space-color":new l.ar(je["space-color"]),"space-color-use-theme":new l.ar({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new l.ar(je["horizon-blend"]),"star-intensity":new l.ar(je["star-intensity"]),"vertical-range":new l.ar(je["vertical-range"])}),w,new Map(k)),this._transform=y,this.set(f),this._transitionable.snap()}get state(){const f=this._transform,y=f.projection.name==="globe",w=l._(f.zoom),k=this.properties.get("range"),R=[2,4.5],M=.5/Math.tan(.5*f._fov),z=[k[0]+M,k[1]+M];return{range:y?[l.aw(R[0],z[0],w),l.aw(R[1],z[1],w)]:z,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(f,y,w={}){if(this._validate(Bw,f,w))return;const k={...f};for(const R of Object.keys(je))k[R]===void 0&&(k[R]=je[R].default);this._setValues(k,y)}getOpacity(f){if(!this._transform.projection.supportsFog)return 0;const y=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:l.ax(l.az,l.ay,f))*y.a}getOpacityAtLatLng(f,y){return this._transform.projection.supportsFog?l.aA(this.state,f,y):0}getOpacityForTile(f){if(!this._transform.projection.supportsFog)return[1,1];const y=this._transform.calculateFogTileMatrix(f.toUnwrapped());return l.aB(this.state,y,0,0,l.ac,l.ac,this._transform)}getOpacityForBounds(f,y,w,k,R){return this._transform.projection.supportsFog?l.aB(this.state,f,y,w,k,R,this._transform):[1,1]}getRangeForProjection(){return this._transform.projection.supportsFog?this.state.range:[0,1]}isVisibleOnFrustum(f){if(!this._transform.projection.supportsFog)return!1;const y=[4,5,6,7];for(const w of y){const k=f.points[w];let R;if(k[2]>=0)R=k;else{const M=f.points[w-4];R=l.aC(M,k,M[2]/(M[2]-k[2]))}if(l.aD(this.state,R[0],R[1],0,this._transform)>=l.aE)return!0}return!1}}let ze,Qe,Xe=class extends gf{constructor(_,f,y,w){super(ze||(ze=new l.aq({density:new l.ar(l.s.snow.density),intensity:new l.ar(l.s.snow.intensity),color:new l.ar(l.s.snow.color),opacity:new l.ar(l.s.snow.opacity),vignette:new l.ar(l.s.snow.vignette),"vignette-color":new l.ar(l.s.snow["vignette-color"]),"center-thinning":new l.ar(l.s.snow["center-thinning"]),direction:new l.ar(l.s.snow.direction),"flake-size":new l.ar(l.s.snow["flake-size"])})),y,new Map(w)),this.set(_),this._transitionable.snap()}get state(){const _=this.properties.get("opacity"),f=this.properties.get("color"),y=this.properties.get("direction"),w=l.aF(y[0]),k=-Math.max(l.aF(y[1]),.01),R=[Math.cos(w)*Math.cos(k),Math.sin(w)*Math.cos(k),Math.sin(k)],M=this.properties.get("vignette"),z=this.properties.get("vignette-color"),V=new l.C(z.r,z.g,z.b,M);return{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new l.C(f.r,f.g,f.b,f.a*_),direction:R,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:V}}get(){return this._transitionable.serialize()}set(_,f,y={}){if(this._validate(yx,_,y))return;const w={..._},k=l.s.snow;for(const R of Object.keys(k))w[R]===void 0&&(w[R]=k[R].default);this._setValues(w,f)}},Je=class extends gf{constructor(_,f,y,w){super(Qe||(Qe=new l.aq({density:new l.ar(l.s.rain.density),intensity:new l.ar(l.s.rain.intensity),color:new l.ar(l.s.rain.color),opacity:new l.ar(l.s.rain.opacity),vignette:new l.ar(l.s.rain.vignette),"vignette-color":new l.ar(l.s.rain["vignette-color"]),"center-thinning":new l.ar(l.s.rain["center-thinning"]),direction:new l.ar(l.s.rain.direction),"droplet-size":new l.ar(l.s.rain["droplet-size"]),"distortion-strength":new l.ar(l.s.rain["distortion-strength"])})),y,new Map(w)),this.set(_),this._transitionable.snap()}get state(){const _=this.properties.get("opacity"),f=this.properties.get("color"),y=this.properties.get("direction"),w=l.aF(y[0]),k=-Math.max(l.aF(y[1]),.01),R=[Math.cos(w)*Math.cos(k),Math.sin(w)*Math.cos(k),Math.sin(k)],M=this.properties.get("vignette-color"),z=new l.C(M.r,M.g,M.b,this.properties.get("vignette"));return{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new l.C(f.r,f.g,f.b,f.a*_),direction:R,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:z}}get(){return this._transitionable.serialize()}set(_,f,y={}){if(this._validate(zw,_,y))return;const w={..._},k=l.s.rain;for(const R of Object.keys(k))w[R]===void 0&&(w[R]=k[R].default);this._setValues(w,f)}};const rt={workerUrl:"",workerClass:null,workerParams:void 0};function It(_){return rt.workerClass!=null?new rt.workerClass:new self.Worker(rt.workerUrl,{name:_,type:"module",...rt.workerParams})}const wt="mapboxgl_preloaded_worker_pool";class St{constructor(f){this.active={},this.workers=null,this.name=f}acquire(f,y=St.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{y.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[wt]}numActive(){return Object.keys(this.active).length}}St.workerCount=2;class Ot{constructor(f,y,w="Worker",k=St.workerCount){this.workerPool=f,this.actors=[],this.currentActor=0,this.id=l.aG();const R=this.workerPool.acquire(this.id,k);for(let M=0;M{this.ready=!0}).catch(()=>{})}send(f,y,w){return Promise.all(this.actors.map(k=>k.send(f,y,w)))}broadcast(f,y){for(const w of this.actors)w.notify(f,y)}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(f=>{f.remove()}),this.actors=[],this.workerPool.release(this.id)}}Ot.Actor=l.aH;class pr extends gf{constructor(f,y,w,k){super(y,w,new Map(k)),this.set(f),this._transitionable.snap()}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(f,y){this._options=f,this._setValues(f.properties,y)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}let Ht;const er=()=>Ht||(Ht=new l.aq({color:new l.ar(l.s.properties_light_ambient.color),"color-use-theme":new l.ar({type:"string",default:"default","property-type":"data-constant"}),intensity:new l.ar(l.s.properties_light_ambient.intensity)}));let Zt;const Rr=()=>Zt||(Zt=new l.aq({direction:new l.aI(l.s.properties_light_directional.direction),color:new l.ar(l.s.properties_light_directional.color),"color-use-theme":new l.ar({type:"string",default:"default","property-type":"data-constant"}),intensity:new l.ar(l.s.properties_light_directional.intensity),"cast-shadows":new l.ar(l.s.properties_light_directional["cast-shadows"]),"shadow-quality":new l.ar(l.s.properties_light_directional["shadow-quality"]),"shadow-intensity":new l.ar(l.s.properties_light_directional["shadow-intensity"]),"shadow-draw-before-layer":new l.ar(l.s.properties_light_directional["shadow-draw-before-layer"])})),un=(_,f,y,w,k,R,M,z,V,H=[0,0,1])=>({u_matrix:_,u_normal_matrix:f,u_opacity:y,u_faux_facade_ao_intensity:w,u_camera_pos:k,u_tile_to_meter:R,u_facade_emissive_chance:M,u_flood_light_color:z,u_flood_light_intensity:V,u_front_cutoff_params:H}),Zn=_=>({u_matrix:_}),an=_=>({u_matrix:_}),on=l.aJ;async function Ln(){return Promise.resolve()}function ui(_,f,y,w,k,R,M,z){y.resetLayerRenderingStats(_);const V=_.context,H=V.gl,Y=_.transform,te=y.paint.get("fill-extrusion-pattern"),ne=y.paint.get("fill-extrusion-pattern-cross-fade"),le=te.constantOr(null),me=te.constantOr(1),fe=y.paint.get("fill-extrusion-opacity"),Se=_.style.enable3dLights(),Me=y.paint.get(Se&&!me?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),qe=[y.paint.get("fill-extrusion-ambient-occlusion-intensity"),Me],Ne=y.layout.get("fill-extrusion-edge-radius"),We=Ne>0&&!y.paint.get("fill-extrusion-rounded-roof"),ct=We?0:Ne,it=Y.projection.name==="globe"?l.aO():0,pt=Y.projection.name==="globe",dt=pt?l._(Y.zoom):0,mt=[l.ad(Y.center.lng),l.ae(Y.center.lat)],xt=y.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",bt=y.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(xt?null:y.lut).toArray01().slice(0,3),Ft=y.paint.get("fill-extrusion-flood-light-intensity"),Lt=y.paint.get("fill-extrusion-vertical-scale"),Mt=y.paint.get("fill-extrusion-line-width").constantOr(1)!==0,or=y.paint.get("fill-extrusion-height-alignment"),fr=y.paint.get("fill-extrusion-base-alignment"),Cr=l.aP(_,y.paint.get("fill-extrusion-cutoff-fade-range")),qr=y.paint.get("fill-extrusion-front-cutoff"),qt=Un(Y.pitch,qr,!!_.terrain),Ut=qt[2]<1;Ut&&(_.maxFrontCutoffRawStart=Math.max(_.maxFrontCutoffRawStart,qr[0]));const gr=[];let Pr;pt&&gr.push("PROJECTION_GLOBE_VIEW"),qe[0]>0&&gr.push("FAUX_AO"),We&&gr.push("ZERO_ROOF_RADIUS"),z&&gr.push("HAS_CENTROID"),Ft>0&&gr.push("FLOOD_LIGHT"),Cr.shouldRenderCutoff&&gr.push("RENDER_CUTOFF"),Ut&&gr.push("RENDER_FRONT_CUTOFF"),Mt&&gr.push("RENDER_WALL_MODE");const ur=_.renderPass==="shadow",Xt=_.shadowRenderer,mr=ur&&!!Xt,tn=ur?l.a5.disabled:l.a5.backCCW;_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!0);let kr=[0,0,0];if(Xt){const ei=_.style.directionalLight,Rn=_.style.ambientLight;ei&&Rn&&(kr=l.aQ(_.style,ei,Rn)),ur||(gr.push("RENDER_SHADOWS"),Xt.useNormalOffset&&gr.push("NORMAL_OFFSET")),Pr=gr.concat(["SHADOWS_SINGLE_CASCADE"])}const vn=mr?"fillExtrusionDepth":me?"fillExtrusionPattern":"fillExtrusion",Xr=y.getLayerRenderingStats();for(const ei of w){const Rn=f.getTile(ei),Ni=Rn.getBucket(y);if(!Ni||Ni.projection.name!==Y.projection.name)continue;let zn=!1;Xt&&(zn=Xt.getMaxCascadeForTile(ei.toUnwrapped())===0);const Qi=_.isTileAffectedByFog(ei),xn=Ni.programConfigurations.get(y.id);let Sn=!1;if(le&&Rn.imageAtlas){const Ri=Rn.imageAtlas,gi=l.aR.from(le),yi=gi.getPrimary().scaleSelf(l.e.devicePixelRatio).toString(),Dr=gi.getSecondary(),Pn=Ri.patternPositions.get(yi),ti=Dr?Ri.patternPositions.get(Dr.scaleSelf(l.e.devicePixelRatio).toString()):null;Sn=!!Pn&&!!ti,Pn&&xn.setConstantPatternPositions(Pn,ti)}ne>0&&(Sn||xn.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&gr.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Dn=_.getOrCreateProgram(vn,{config:xn,defines:zn?Pr:gr,overrideFog:Qi});if(_.terrain&&_.terrain.setupElevationDraw(Rn,Dn,{useMeterToDem:!0}),!Ni.centroidVertexBuffer){const Ri=Dn.getAttributeLocation(H,"a_centroid_pos");Ri!==-1&&H.vertexAttribI4ui(Ri,0,0,0,0)}!ur&&Xt&&Xt.setupShadows(Rn.tileID.toUnwrapped(),Dn,"vector-tile"),me&&(_.context.activeTexture.set(H.TEXTURE0),Rn.imageAtlasTexture&&Rn.imageAtlasTexture.bind(H.LINEAR,H.CLAMP_TO_EDGE),xn.updatePaintBuffers());const Ks=y.paint.get("fill-extrusion-vertical-gradient"),ya=1/Ni.tileToMeter;let Ti;if(ur&&Xt){if(vs(Rn.tileID,Ni.maxHeight,_))continue;const Ri=Xt.calculateShadowPassMatrixFromTile(Rn.tileID.toUnwrapped());Ti=l.aX(Ri,ct,ya,Lt,or,fr)}else{const Ri=_.translatePosMatrix(ei.expandedProjMatrix,Rn,y.paint.get("fill-extrusion-translate"),y.paint.get("fill-extrusion-translate-anchor")),gi=Y.projection.createInversionMatrix(Y,ei.canonical),yi=Dn.fixedDefines.includes("LIGHTING_3D_MODE");Ti=me?l.aS(Ri,_,Ks,fe,qe,ct,ya,ei,Rn,it,or,fr,dt,mt,gi,bt,Lt,ne,yi):l.aT(Ri,_,Ks,fe,qe,ct,ya,ei,it,or,fr,dt,mt,gi,bt,Lt,Ft,kr,qt,yi)}_.uploadCommonUniforms(V,Dn,ei.toUnwrapped(),null,Cr);let Ba=Ni.segments;if(Y.projection.name==="mercator"&&!ur&&(Ba=Ni.getVisibleSegments(Rn.tileID,_.terrain,_.transform.getFrustum(0)),!Ba.get().length))continue;if(Xr)if(ur)for(const Ri of Ba.get())Xr.numRenderedVerticesInShadowPass+=Ri.primitiveLength;else for(const Ri of Ba.get())Xr.numRenderedVerticesInTransparentPass+=Ri.primitiveLength;const bs=[];(_.terrain||z)&&bs.push(Ni.centroidVertexBuffer),pt&&bs.push(Ni.layoutVertexExtBuffer),Mt&&bs.push(Ni.wallVertexBuffer),Dn.draw(_,V.gl.TRIANGLES,k,R,M,tn,Ti,y.id,Ni.layoutVertexBuffer,Ni.indexBuffer,Ba,y.paint,_.transform.zoom,xn,bs)}_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!1)}class di{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function Un(_,f,y){if(!(f[2]<1)||y)return[0,0,1];const w=180*_/Math.PI;if(w<15)return[-.5,f[1],f[2]];const k=Math.min(1,Math.max(0,(w-15)/5)),R=k*k*(3-2*k);return[-.5*(1-R)+f[0]*R,f[1],f[2]]}function wn(_,f,y,w,k,R,M){w.centroidVertexArray.length===0&&w.createCentroidsBuffer();const z=R?R.findDEMTileFor(y):null;if(!(z&&z.dem||M))return;R&&z&&z.dem&&w.selfDEMTileTimestamp!==z.dem._timestamp&&(w.borderDoneWithNeighborZ=[-1,-1,-1,-1],w.selfDEMTileTimestamp=z.dem._timestamp);const V=(Ne,We)=>{(Ne.flags|We.flags)&l.aU?(Ne.flags|=l.aU,We.flags|=l.aU):(Ne.flags&=~l.aU,We.flags&=~l.aU)},H=Ne=>new l.P(Math.ceil((Ne+l.aV)*l.aW),0),Y=(Ne,We,ct)=>{const it=Math.ceil((Ne+l.aV)*l.aW),pt=Math.floor(Math.max(0,Math.min(l.ac-1,ct))/4);return new l.P(it,pt<<5|(3&We)<<3|7)},te=(Ne,We)=>{const ct=Number.MAX_VALUE,it=We[0][0]!==ct,pt=We[1][0]!==ct,dt=We[2][0]!==ct,mt=We[3][0]!==ct;if(!((it?1:0)+(pt?1:0)+(dt?1:0)+(mt?1:0)>2))return Ne<2?dt===mt?void 0:dt?0:l.ac-1:it===pt?void 0:it?0:l.ac-1},ne=(Ne,We,ct,it)=>(We?te(Ne,We):void 0)??(it?te(ct,it):void 0),le=Ne=>{const We=f.getSource().minzoom,ct=pt=>{const dt=f.getTileByID(pt);if(dt&&dt.hasData())return dt.getBucket(k)},it=[0,-1,1];for(const pt of it){if(Ne.overscaledZ+pt(me[0]=Math.min(Ne.min.y,We.min.y),me[1]=Math.max(Ne.max.y,We.max.y),me[2]=l.ac-We.min.x>Ne.max.x?We.min.x-l.ac:Ne.max.x,me),Se=(Ne,We)=>(me[0]=Math.min(Ne.min.x,We.min.x),me[1]=Math.max(Ne.max.x,We.max.x),me[2]=l.ac-We.min.y>Ne.max.y?We.min.y-l.ac:Ne.max.y,me),Me=[(Ne,We)=>fe(Ne,We),(Ne,We)=>fe(We,Ne),(Ne,We)=>Se(Ne,We),(Ne,We)=>Se(We,Ne)],qe=(Ne,We,ct,it,pt,dt,mt)=>{if(!R)return 0;const xt=[[dt?ct:Ne,dt?Ne:ct,0],[dt?ct:We,dt?We:ct,0]],bt=mt<0?l.ac+mt:mt,Ft=[dt?bt:(Ne+We)/2,dt?(Ne+We)/2:bt,0];return ct===0&&mt<0||ct!==0&&mt>0?R.getForTilePoints(pt,[Ft],!0,it):xt.push(Ft),R.getForTilePoints(y,xt,!0,z),Math.max(xt[0][2],xt[1][2],Ft[2])/R.exaggeration()};for(let Ne=0;Ne<4;Ne++){const We=w.borderFeatureIndices[Ne];if(We.length===0)continue;const ct=l.aM[Ne](y),it=le(ct);if(!(it&&it instanceof l.aN))continue;const pt=R?R.findDEMTileFor(ct):null;if(!(pt&&pt.dem||M)||(R&&pt&&pt.dem&&w.borderDEMTileTimestamp[Ne]!==pt.dem._timestamp&&(w.borderDoneWithNeighborZ[Ne]=-1,w.borderDEMTileTimestamp[Ne]=pt.dem._timestamp),w.borderDoneWithNeighborZ[Ne]===it.canonical.z))continue;it.centroidVertexArray.length===0&&it.createCentroidsBuffer();const dt=(Ne<2?1:5)-Ne,mt=it.borderDoneWithNeighborZ[dt]!==w.canonical.z,xt=it.borderFeatureIndices[dt];let bt=0;if(w.canonical.z!==it.canonical.z){for(const or of We)w.showCentroid(w.featuresOnBorder[or],"discard");if(mt)for(const or of xt)it.showCentroid(it.featuresOnBorder[or],"discard");w.borderDoneWithNeighborZ[Ne]=it.canonical.z,it.borderDoneWithNeighborZ[dt]=w.canonical.z;continue}const Ft=new Map,Lt=new Set,Mt=new Set;for(let or=0;or1||qt.intersectsCount()>1;{let tn=0;if(pt&&pt.dem&&!mr){const kr=Me[Ne](Cr,Ut),vn=Ne%2?l.ac-1:0;tn=qe(kr[0],Math.min(l.ac-1,kr[1]),vn,pt,ct,Ne<2,kr[2])}Cr.centroidXY=Y(tn,Ne,Xt),Ut.centroidXY=Y(tn,dt,Xt)}w.writeCentroidToBuffer(Cr),it.writeCentroidToBuffer(Ut),w.setBuildingCentroid(fr.buildingId,Cr.centroidXY),it.setBuildingCentroid(fr.buildingId,Ut.centroidXY)}for(const or of We){if(Lt.has(or))continue;const fr=w.featuresOnBorder[or],Cr=w.centroidData.get(fr.centroidDataIndex),qr=fr.borders[Ne];let qt;for(;btqr[0]+3||Ut[0]>qr[0]-3)break;it.showCentroid(qt,"keep"),bt++}if(qt&&btqr[1]-3||(gr++,++bt===xt.length))break;qt=it.featuresOnBorder[xt[bt]]}for(;Ut=xt.length){w.showCentroid(fr,"keep");continue}qt=it.featuresOnBorder[xt[Ut]];let Pr=!1;if(gr>=1){const mr=qt.borders[dt];Math.abs(qr[0]-mr[0])<3&&Math.abs(qr[1]-mr[1])<3&&(gr=1,Pr=!0,bt=Ut+1)}else if(gr===0){w.showCentroid(fr,"keep");continue}const ur=it.centroidData.get(qt.centroidDataIndex);M&&Pr&&V(Cr,ur);const Xt=fr.intersectsCount()>1||qt.intersectsCount()>1;if(gr>1)bt=Ut,Cr.centroidXY=ur.centroidXY=new l.P(0,0);else if(pt&&pt.dem&&!Xt){const mr=Me[Ne](Cr,ur),tn=Ne%2?l.ac-1:0,kr=qe(mr[0],Math.min(l.ac-1,mr[1]),tn,pt,ct,Ne<2,mr[2]);Cr.centroidXY=ur.centroidXY=H(kr)}else if(Xt){const mr=R?void 0:ne(Ne,fr.borders,dt,qt.borders);mr!==void 0?(Cr.centroidXY=Y(0,Ne,mr),ur.centroidXY=Y(0,dt,mr)):Cr.centroidXY=ur.centroidXY=new l.P(0,0)}else Cr.centroidXY=w.encodeBorderCentroid(fr),ur.centroidXY=it.encodeBorderCentroid(qt);w.writeCentroidToBuffer(Cr),it.writeCentroidToBuffer(ur)}else w.showCentroid(fr,"keep")}w.borderDoneWithNeighborZ[Ne]=it.canonical.z,it.borderDoneWithNeighborZ[dt]=w.canonical.z}(w.needsCentroidUpdate||!w.centroidVertexBuffer&&w.centroidVertexArray.length!==0)&&w.uploadCentroid(_)}const ri=[1,0,0],Fi=[0,1,0],vi=[0,0,1];function vs(_,f,y){const w=y.transform,k=y.shadowRenderer;if(!k)return!0;const R=y.frameCounter,M=y.currentShadowCascade;let z=y._shadowCullCache;if(!z||z.frame!==R||z.cascade!==M){const Me=w.tileSize*k._cascades[M].scale,qe=w.scaleZoom(Me),Ne=k.shadowDirection,We=[Ne[0],Ne[1],-Ne[2]],ct=[ri,Fi,vi,We,[We[0],0,We[2]],[0,We[1],We[2]]];z={frame:R,cascade:M,cameraFrustum:l.aK.fromInvProjectionMatrix(w.invProjMatrix,w.worldSize,qe,w.projection.name!=="globe"),edges:ct,shadowDir:We,ws:Me,zoom:qe},y._shadowCullCache=z}const{cameraFrustum:V,edges:H,shadowDir:Y,ws:te,zoom:ne}=z;let le=f;if(w.elevation){const Me=w.elevation.getMinMaxForTile(_);Me&&(le+=Me.max)}le/=l.aL(w.center.lat,ne);const me=k.computeSimplifiedTileShadowVolume(_.toUnwrapped(),le,te,Y);if(!me)return!1;const{vertices:fe,planes:Se}=me;return V.intersectsPrecise(fe,Se,H)===0||k.getCurrentCascadeFrustum().intersectsPrecise(fe,Se,H)===0}const en=new Float32Array(16),ai=new Float32Array(16);function Si(_){const{painter:f,source:y,layer:w,coords:k}=_;let R=_.defines;const M=f.context,z=f.renderPass==="shadow",V=f.renderPass==="light-beam",H=f.shadowRenderer,Y=l.aL(f.transform.center.lat,f.transform.zoom),te=l.aP(f,w.paint.get("building-cutoff-fade-range"));te.shouldRenderCutoff&&(R=R.concat("RENDER_CUTOFF"));const ne=w.paint.get("building-front-cutoff"),le=ne[2]<1&&!f.terrain,me=Un(f.transform.pitch,ne,!!f.terrain);le&&(R=R.concat("RENDER_FRONT_CUTOFF"),f.maxFrontCutoffRawStart=Math.max(f.maxFrontCutoffRawStart,ne[0])),_.floodLightIntensity>0&&(R=R.concat("FLOOD_LIGHT"));for(const fe of k){const Se=y.getTile(fe),Me=Se.getBucket(w);if(!Me)continue;H&&H.getMaxCascadeForTile(fe.toUnwrapped())===0&&(R=R.concat("SHADOWS_SINGLE_CASCADE"));const qe=Me.programConfigurations.get(w.id);let Ne,We;const ct=f.translatePosMatrix(fe.expandedProjMatrix,Se,[0,0],"map");l.aY(en,ct,[1,1,_.verticalScale]);const it=en;let pt;if(z&&H){if(vs(Se.tileID,Me.maxHeight*Y,f))continue;const mt=H.calculateShadowPassMatrixFromTile(Se.tileID.toUnwrapped());l.aY(mt,mt,[1,1,_.verticalScale]),pt=an(mt),Ne=We=f.getOrCreateProgram("buildingDepth",{config:qe,defines:R,overrideFog:!1})}else if(V)Ne=We=f.getOrCreateProgram("buildingBloom",{config:qe,defines:R,overrideFog:!1}),pt=Zn(it);else{const mt=l.aY(new Float64Array(16),f.transform.calculatePosMatrix(fe.toUnwrapped()),[1,1,_.verticalScale]);l.aY(ai,mt,[1,-1,1/Y]),l.aZ(ai,ai),l.a_(ai,ai);const xt=ai,bt=f.transform.getFreeCameraOptions().position,Ft=1<{if(V){const bt=mt.entranceBloom;xt.draw(f,M.gl.TRIANGLES,_.depthMode,l.a4.disabled,_.blendMode,l.a5.disabled,pt,w.id,bt.layoutVertexBuffer,bt.indexBuffer,bt.segmentsBucket,w.paint,f.transform.zoom,qe,[bt.layoutAttenuationBuffer,bt.layoutColorBuffer])}else{const bt=mt.segmentsBucket;let Ft=[mt.layoutNormalBuffer,mt.layoutCentroidBuffer,mt.layoutColorBuffer,mt.layoutFloodLightDataBuffer];mt.layoutFacadePaintBuffer&&(Ft=Ft.concat([mt.layoutFacadeDataBuffer,mt.layoutFacadeVerticalRangeBuffer,mt.layoutFacadePaintBuffer])),xt.draw(f,M.gl.TRIANGLES,_.depthMode,_.stencilMode||l.a4.disabled,_.blendMode,z?l.a5.disabled:l.a5.backCW,pt,w.id,mt.layoutVertexBuffer,mt.indexBuffer,bt,w.paint,f.transform.zoom,qe,Ft)}};f.uploadCommonUniforms(M,We,fe.toUnwrapped(),null,te),Me.buildingWithoutFacade&&dt(Me.buildingWithoutFacade,We),Me.buildingWithFacade&&(Ne!==We&&f.uploadCommonUniforms(M,Ne,fe.toUnwrapped(),null,te),dt(Me.buildingWithFacade,Ne))}}function Ta(_,f,y,w,k,R,M,z,V,H,Y,te,ne,le){const me=_.context.gl,fe=_.depthModeForSublayer(1,l.a3.ReadOnly,me.LEQUAL,!0),Se=l.aw(.1,3,Y),Me=_._showOverdrawInspector,qe=te,Ne=new di;if(!Me){const We=new l.a4({func:me.ALWAYS,mask:255},255,255,me.KEEP,me.KEEP,me.REPLACE),ct=new l.a7([me.ONE,me.ONE,me.ONE,me.ONE],l.C.transparent,[!1,!1,!1,!0],me.MIN);l.a$(Ne,_,f,y,w,fe,We,ct,l.a5.disabled,k,"sdf",R,M,z,V,H,Se,qe,!1,void 0)}{const We=Me?l.a4.disabled:new l.a4({func:me.EQUAL,mask:255},255,255,me.KEEP,me.DECR,me.DECR),ct=Me?_.colorModeForRenderPass():new l.a7([me.ONE_MINUS_DST_ALPHA,me.DST_ALPHA,me.ONE,me.ONE],l.C.transparent,[!0,!0,!0,!0]);l.a$(Ne,_,f,y,w,fe,We,ct,l.a5.disabled,k,"color",R,M,z,V,H,Se,qe,!1,void 0)}}class tl{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(f,y,w,k,R){if(wV*this._hysteresisRatio&&(M=this._previousClosestBuildingId):H&&!M&&(M=this._previousClosestBuildingId),this._previousClosestBuildingId=M,M}_calculateDistance(f,y){if(!y.center)return Number.MAX_VALUE;const w=f.lat-y.center[1],k=f.lng-y.center[0];return w*w+k*k}_isBuildingVisible(f,y,w){if(!w)return!1;for(const k of f.floorIds){const R=f.floors[k];if(!R.geometry)continue;const M=R.geometry;if(M.type==="Polygon"){const z=this._convertRingToPoints(M.coordinates[0]);if(l.b2(z,w))return!0}else if(M.type==="MultiPolygon"){const z=this._convertMultiPolygonToPoints(M.coordinates);if(l.b3(w,z))return!0}}return!1}_convertRingToPoints(f){return f.map(y=>new l.P(y[0],y[1]))}_convertMultiPolygonToPoints(f){return f.map(y=>y.length===0?[]:y[0].map(w=>new l.P(w[0],w[1])))}}const Es=.05,Ts=(_,f,y,w,k,R,M,z,V,H,Y,te)=>({u_matrix:_,u_normalize_matrix:f,u_globe_matrix:y,u_merc_matrix:w,u_grid_matrix:k,u_tl_parent:R,u_scale_parent:H,u_fade_t:Y.mix,u_opacity:Y.opacity,u_image0:0,u_image1:1,u_raster_elevation:te,u_zoom_transition:M,u_merc_center:z,u_cutoff_params:V}),Gs=(_,f,y,w,k,R,M,z,V,H)=>({u_particle_texture:_,u_particle_texture_side_len:f,u_tile_offset:y,u_velocity:w,u_color_ramp:R,u_velocity_res:k,u_max_speed:M,u_uv_offset:z,u_data_scale:[255*V[0],255*V[1]],u_data_offset:H,u_particle_pos_scale:1.1,u_particle_pos_offset:[Es,Es]}),Rs=(_,f,y,w,k,R,M,z,V,H)=>({u_particle_texture:_,u_particle_texture_side_len:f,u_velocity:y,u_velocity_res:w,u_max_speed:k,u_speed_factor:R,u_reset_rate:M,u_rand_seed:Math.random(),u_uv_offset:z,u_data_scale:[255*V[0],255*V[1]],u_data_offset:H,u_particle_pos_scale:1.1,u_particle_pos_offset:[Es,Es]});function ko(_,[f,y,w,k],[R,M]){if(R===M)return[0,0,0,0];const z=255*(_-1)/(_*(M-R));return[f*z,y*z,w*z,k*z]}function yc(_,f,[y,w]){return y===w?0:.5/_+(f-y)*(_-1)/(_*(w-y))}var pa=l.b9([{name:"a_index",type:"Int16",components:1}]);class so{constructor(f,y,w,k){const R={width:w[0],height:w[1],data:null},M=f.gl;this.targetColorTexture=new l.T(f,R,M.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new l.T(f,R,M.RGBA8,{useMipmap:!1}),this.context=f,this.updateParticleTexture(y,k),this.lastInvalidatedAt=0}updateParticleTexture(f,y){if(this.particleTextureDimension===y.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const w=this.context.gl,k=y.width*y.height;this.particleTexture0=new l.T(this.context,y,w.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new l.T(this.context,y,w.RGBA8,{premultiply:!1,useMipmap:!1});const R=new l.ba;R.reserve(k);for(let M=0;M0){const R=l.e.now(),M=(R-_.timeAdded)/k,z=f?(R-f.timeAdded)/k:-1,V=y.getSource(),H=w.coveringZoomLevel({tileSize:V.tileSize,roundZoom:V.roundZoom}),Y=!f||Math.abs(f.tileID.overscaledZ-H)>Math.abs(_.tileID.overscaledZ-H),te=Y&&_.refreshedUponExpiration?1:l.bb(Y?M:1-z,0,1);return f?{opacity:1,mix:1-te,isFading:M<1}:{opacity:te,mix:0,isFading:M<1}}return{opacity:1,mix:0,isFading:!1}}function as(_,f,y){if(!_)return null;const w=f.getTextureDescriptor(_,y,!0);if(!w)return null;let{texture:k,mix:R,offset:M,tileSize:z,buffer:V,format:H}=w;if(!k||!H)return null;let Y=!1;return H==="uint32"&&(Y=!0,R[3]=0,R=ko(l.bk,R,[0,y.paint.get("raster-particle-max-speed")]),M=yc(l.bk,M,[0,y.paint.get("raster-particle-max-speed")])),{texture:k,textureOffset:[V/(z+2*V),z/(z+2*V)],tileSize:z,scalarData:Y,scale:R,offset:M,defines:["RASTER_ARRAY",{uint8:"DATA_FORMAT_UINT8",uint16:"DATA_FORMAT_UINT16",uint32:"DATA_FORMAT_UINT32"}[H]]}}function Rl(_){const f=_._nearZ,y=_.projection.farthestPixelDistance(_),w=y-f,k=.2*_.height,R=f+k;return[f,y,(R-k-f)/w,(R-f)/w]}var Ma=`#ifdef RASTER_ARRAY uniform sampler2D u_velocity;uniform mediump vec2 u_velocity_res;uniform mediump float u_max_speed;const vec4 NO_DATA=vec4(1);const vec2 INVALID_VELOCITY=vec2(-1);uniform highp vec2 u_uv_offset;uniform highp float u_data_offset;uniform highp vec2 u_data_scale;ivec4 rasterArrayLinearCoord(highp vec2 texCoord,highp vec2 texResolution,out highp vec2 fxy) {texCoord=texCoord*texResolution-0.5;fxy=fract(texCoord);texCoord-=fxy;return ivec4(texCoord.xxyy+vec2(1.5,0.5).xyxy);}highp vec2 lookup_velocity(highp vec2 uv) {uv=u_uv_offset.x+u_uv_offset.y*uv;highp vec2 fxy;ivec4 c=rasterArrayLinearCoord(uv,u_velocity_res,fxy);highp vec4 tl=texelFetch(u_velocity,c.yz,0);highp vec4 tr=texelFetch(u_velocity,c.xz,0);highp vec4 bl=texelFetch(u_velocity,c.yw,0);highp vec4 br=texelFetch(u_velocity,c.xw,0);if (tl==NO_DATA) {return INVALID_VELOCITY;}if (tr==NO_DATA) {return INVALID_VELOCITY;}if (bl==NO_DATA) {return INVALID_VELOCITY;}if (br==NO_DATA) {return INVALID_VELOCITY;}highp vec4 t=mix(mix(bl,br,fxy.x),mix(tl,tr,fxy.x),fxy.y);highp vec2 velocity=u_data_offset+vec2(dot(t.rg,u_data_scale),dot(t.ba,u_data_scale));velocity.y=-velocity.y;velocity/=max(u_max_speed,length(velocity));return velocity;} #endif uniform highp float u_particle_pos_scale;uniform highp vec2 u_particle_pos_offset;highp vec4 pack_pos_to_rgba(highp vec2 p) {highp vec2 v=(p+u_particle_pos_offset)/u_particle_pos_scale;highp vec4 r=vec4(v.x,fract(v.x*255.0),v.y,fract(v.y*255.0));return vec4(r.x-r.y/255.0,r.y,r.z-r.w/255.0,r.w);}highp vec2 unpack_pos_from_rgba(highp vec4 v) {v=floor(v*255.0+0.5)/255.0;highp vec2 p=vec2(v.x+(v.y/255.0),v.z+(v.w/255.0));return u_particle_pos_scale*p-u_particle_pos_offset;}`;l.bl["_prelude_raster_particle.glsl"]||(l.bl["_prelude_raster_particle.glsl"]=Ma);var qi={building:l.bm(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" const float window_depth=0.5;const float ao_radius=0.2;in vec4 v_color;in highp vec3 v_normal;in highp vec3 v_pos; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) in float v_dither_opacity; #endif #ifdef BUILDING_FAUX_FACADE in lowp float v_faux_facade;in highp float v_faux_facade_ed;in highp vec2 v_faux_facade_window;in highp vec2 v_faux_facade_floor;in highp vec2 v_faux_facade_range;in highp float v_aspect;in highp vec3 v_tbn_0;in highp vec3 v_tbn_1;in highp vec3 v_tbn_2;in highp vec4 v_faux_color_emissive;uniform float u_faux_facade_ao_intensity; #endif #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT in highp float v_flood_radius;in float v_has_flood_light; #endif uniform lowp float u_opacity;uniform vec3 u_camera_pos;uniform highp float u_tile_to_meter;uniform float u_facade_emissive_chance;uniform vec3 u_flood_light_color;uniform float u_flood_light_intensity;vec3 linearTosRGB(in vec3 color) {return pow(color,vec3(1./2.2));} #ifdef BUILDING_FAUX_FACADE highp float hash12(in highp vec2 p) {highp vec3 p3 =fract(vec3(p.xyx)*0.1031);p3+=dot(p3,p3.yzx+33.33);return fract((p3.x+p3.y)*p3.z);}float min3(in vec3 v) {return min(min(v.x,v.y),v.z);}highp vec2 get_uv_mask_id(in highp vec2 q,out highp float mask,out highp vec2 id) {highp vec2 p=q;mask=step(v_faux_facade_range.x,p.y)*step(p.y,v_faux_facade_range.y);p.y=p.y-v_faux_facade_range.x;highp vec2 uv=modf(p/v_faux_facade_floor,id);highp vec4 d=(v_faux_facade_floor.xyxy+vec4(-v_faux_facade_window,v_faux_facade_window))*0.5;highp vec4 edge=d/v_faux_facade_floor.xyxy;highp vec2 m=step(edge.xy,uv)*step(uv,edge.zw);mask*=m.x*m.y;uv-=vec2(0.5);uv*=vec2(0.5)/(vec2(0.5)-edge.xy);uv+=vec2(0.5);return uv;}highp float ray_unit_box(in highp vec3 ray_o,in highp vec3 ray_d,in highp vec3 bmin,in highp vec3 bmax) {highp vec3 planes=mix(bmin,bmax,step(0.0,ray_d));highp vec3 t=(planes-ray_o)/ray_d;return min3(t);}float get_emissive(in vec2 id) {if (u_facade_emissive_chance > 0.0) {return (step(hash12(id),u_facade_emissive_chance)+0.05)*v_faux_color_emissive.a;}return 0.0;}vec3 get_shade_info(in highp vec3 v,in highp vec3 v_normalized,in vec3 color,in vec2 id,in mat3 tbn,inout vec3 out_normal,inout float out_emissive) {vec3 out_color=color;highp vec3 abs_v=abs(v_normalized);bool x_major=abs_v.x >=abs_v.y && abs_v.x >=abs_v.z;bool y_major=abs_v.y >=abs_v.x && abs_v.y >=abs_v.z;bool z_major=abs_v.z >=abs_v.x && abs_v.z >=abs_v.y;if (x_major) {out_normal=-sign(v.x)*tbn[0];} else if (y_major) {out_normal=vec3(0.0,0.0,-sign(v.y));} else if (z_major) {out_color=v_faux_color_emissive.rgb;out_emissive=v.z <=0.0 ? get_emissive(id) : out_emissive;}float ao=1.0;if (u_faux_facade_ao_intensity > 0.0) {vec4 ao_range=v_faux_facade_window.xxyy*0.5-vec4(0,ao_radius,0,ao_radius);vec2 ao_range_z=vec2(window_depth*0.5)-vec2(0.0,ao_radius);if (x_major || y_major) {ao*=smoothstep(-ao_range_z.x,-ao_range_z.y,v.z);} else if (z_major) {ao*=smoothstep(-ao_range.x,-ao_range.y,v.x)*(1.0-smoothstep(ao_range.y,ao_range.x,v.x));ao*=smoothstep(-ao_range.z,-ao_range.w,v.y)*(1.0-smoothstep(ao_range.w,ao_range.z,v.y));}ao=mix(1.0,min(1.0,ao+0.25),u_faux_facade_ao_intensity);}out_color*=ao;return out_color;} #endif vec3 apply_lighting_linear(in vec3 color,in vec3 normal,in float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return color*(ambient_contrib+directional_contrib);}void main() {vec3 normal=normalize(v_normal);vec3 base_color=v_color.rgb;float emissive=v_color.a; #ifdef BUILDING_FAUX_FACADE if (v_faux_facade > 0.0) {highp mat3 tbn=mat3(v_tbn_0,v_tbn_1,v_tbn_2);highp vec3 v=vec3(v_pos.xy,v_pos.z/u_tile_to_meter)-u_camera_pos;highp vec3 view_tangent=transpose(tbn)*v;highp vec2 q=vec2(v_faux_facade_ed,v_pos.z);float mask=0.0;vec2 id=vec2(0.0);highp vec2 uv=get_uv_mask_id(q,mask,id);uv*=v_faux_facade_window;highp vec3 bmin=vec3(0.0,0.0,-window_depth);highp vec3 bmax=bmin+vec3(v_faux_facade_window,window_depth);highp vec3 ray_o=vec3(uv,0.0);highp vec3 ray_d=normalize(view_tangent);highp float t_min=ray_unit_box(ray_o,ray_d,bmin,bmax);highp vec3 hit=ray_o+t_min*ray_d;highp vec3 r=vec3(v_faux_facade_window,-window_depth);hit-=r*0.5;highp vec3 normalized=hit/r;vec3 out_normal=normal;float out_emissive=emissive;vec3 room_color=get_shade_info(hit,normalized,base_color,id,tbn,out_normal,out_emissive);base_color=mix(base_color,room_color,mask);normal=mix(normal,out_normal,mask);emissive=mix(emissive,out_emissive,mask);} #endif vec4 color=vec4(base_color,1.0);vec3 xy_flipped_normal=vec3(-normal.xy,normal.z);float shadowed_lighting_factor=0.0; #ifdef RENDER_SHADOWS #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity); #else shadowed_lighting_factor=shadowed_light_factor_normal(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif #else shadowed_lighting_factor=max(0.0,dot(xy_flipped_normal,u_lighting_directional_dir)); #endif color.rgb=apply_lighting_linear(color.rgb,xy_flipped_normal,shadowed_lighting_factor);color.rgb=linearTosRGB(color.rgb); #ifdef FLOOD_LIGHT float flood_radiance=(1.0-min(v_pos.z/v_flood_radius,1.0))*u_flood_light_intensity*v_has_flood_light;color.rgb=mix(color.rgb,u_flood_light_color,flood_radiance); #endif color.rgb=mix(color.rgb,linearTosRGB(base_color.rgb),emissive); #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,v_pos.z)); #endif color*=u_opacity; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) if (v_dither_opacity < 1.0) {int index=viewport_dither_index(gl_FragCoord.xy);if (v_dither_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif glFragColor=color; #ifdef DEBUG_SHOW_NORMALS color.rgb=xy_flipped_normal*0.5+vec3(0.5,0.5,0.5);color.a=1.0;glFragColor=color; #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_feature_cutout.vertex.glsl" in ivec2 a_pos_packed;in vec4 a_normal_4n;in ivec4 a_centroid_3; #ifdef FLOOD_LIGHT in int a_flood_light_wall_radius_1i16; #endif #ifdef BUILDING_FAUX_FACADE in uvec4 a_faux_facade_data;in uvec2 a_faux_facade_vertical_range; #endif uniform mat4 u_matrix;uniform mat4 u_normal_matrix;uniform highp float u_tile_to_meter; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params; #endif out float v_dither_opacity; #endif out vec4 v_color;out vec3 v_normal;out highp vec3 v_pos; #ifdef BUILDING_FAUX_FACADE out lowp float v_faux_facade;out highp float v_faux_facade_ed;out highp vec2 v_faux_facade_window;out highp vec2 v_faux_facade_floor;out highp vec2 v_faux_facade_range;out highp float v_aspect;out highp vec3 v_tbn_0;out highp vec3 v_tbn_1;out highp vec3 v_tbn_2;out highp vec4 v_faux_color_emissive; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT out highp float v_flood_radius;out float v_has_flood_light; #endif const float MAX_UINT_16=65535.0;const float MAX_INT_16=32767.0;const float MAX_UINT_8=255.0;const float MAX_INT_8=127.0;const float TWO_POW_8=256.0;const float FLOOD_LIGHT_MAX_RADIUS_METER=2048.0;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #ifdef BUILDING_FAUX_FACADE mat3 get_tbn(in vec3 normal) {const vec3 bitangent=vec3(0.0,0.0,1.0);vec3 tangent=normalize(vec3(normal.y,-normal.x,0.0));return mat3(tangent,bitangent,normal);} #endif #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 part_color_emissive #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 faux_facade_color_emissive invariant gl_Position;void main() { #pragma mapbox: initialize-attribute-custom highp uvec2 part_color_emissive #pragma mapbox: initialize-attribute-custom highp uvec2 faux_facade_color_emissive #ifdef FLOOD_LIGHT v_flood_radius=(float(a_flood_light_wall_radius_1i16)/MAX_INT_16*FLOOD_LIGHT_MAX_RADIUS_METER);v_has_flood_light=step(0.0,v_flood_radius); #endif vec4 color_emissive=decode_color(vec2(part_color_emissive));v_color=vec4(sRGBToLinear(color_emissive.rgb),color_emissive.a);v_normal=vec3(u_normal_matrix*vec4(a_normal_4n.xyz,0.0));float hidden=0.0;float depth_offset=0.0;float frontCutoffOpacity=1.0;float routeFade=0.0;vec2 centroid_xy=vec2(a_centroid_3.xy >> 2);vec2 spanBits=vec2(a_centroid_3.xy & 3); #ifdef BUILDING_FAUX_FACADE vec4 faux_facade_data=vec4(a_faux_facade_data);v_faux_facade=faux_facade_data.x;if (v_faux_facade > 0.0) {v_faux_facade_ed=faux_facade_data.x *u_tile_to_meter;float window_x_perc=floor(faux_facade_data.y/TWO_POW_8);float window_y_perc=faux_facade_data.y-TWO_POW_8*window_x_perc;vec2 window_perc=vec2(window_x_perc,window_y_perc)/MAX_UINT_8;v_faux_facade_floor=(faux_facade_data.zw/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_faux_facade_window=window_perc*v_faux_facade_floor;v_faux_facade_range=(vec2(a_faux_facade_vertical_range)/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_aspect=v_faux_facade_window.x/v_faux_facade_window.y;mat3 tbn=get_tbn(normalize(v_normal));v_tbn_0=tbn[0];v_tbn_1=tbn[1];v_tbn_2=tbn[2];v_faux_color_emissive=decode_color(vec2(faux_facade_color_emissive));v_faux_color_emissive.rgb=sRGBToLinear(v_faux_color_emissive.rgb);depth_offset=min(1000.0,float(a_centroid_3.z))*0.0000002;} #endif v_pos=vec3(float(a_pos_packed.x >> 16),float((a_pos_packed.x << 16) >> 16),intBitsToFloat(a_pos_packed.y)); #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) float halfSpanX=spanBits.x*10.0/u_tile_to_meter;float halfSpanY=spanBits.y*10.0/u_tile_to_meter;vec2 screenUpInTile=vec2(u_matrix[0][1],u_matrix[1][1]);vec2 spanOffset=vec2(halfSpanX,halfSpanY)*sign(screenUpInTile);vec2 cutoff_highestCorner=centroid_xy+spanOffset;vec2 cutoff_lowestCorner=centroid_xy-spanOffset; #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_xy,0.0,1.0); #endif #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,native_clip_z_to_cutoff_depth(ground.z,ground.w));hidden=float(v_cutoff_opacity==0.0);v_pos.z*=v_cutoff_opacity; #endif #ifdef RENDER_SHADOWS vec3 shadow_pos=v_pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset_model(v_normal);shadow_pos+=offset*shadow_normal_offset_multiplier0(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shadow_pos,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(shadow_pos,1.0); #endif #ifdef FOG v_fog_pos=fog_position(v_pos); #endif #ifdef RENDER_FRONT_CUTOFF {hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;hidden=max(hidden,float(ndc_y < threshold-range_ndc));float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);frontCutoffOpacity=mix(u_front_cutoff_params.z,1.0,t);} #endif #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) v_dither_opacity=1.0; #ifdef RENDER_FRONT_CUTOFF v_dither_opacity=min(v_dither_opacity,frontCutoffOpacity); #endif hidden=max(hidden,float(v_dither_opacity <=0.0)); #endif gl_Position=mix(u_matrix*vec4(v_pos,1),AWAY,hidden);gl_Position.z-=depth_offset*gl_Position.w;}`),buildingBloom:l.bm(`in vec4 v_color_emissive; #pragma mapbox: define-attribute highp vec4 bloom_attenuation float saturate(float val) {return clamp(val,0.0,1.0);}void main() { #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation float emission=v_color_emissive.a;float opacity=1.0; #ifdef HAS_ATTRIBUTE_a_bloom_attenuation float distance=length(vec2(1.3*max(0.0,abs(bloom_attenuation.x)-bloom_attenuation.z),bloom_attenuation.y));distance+= mix(0.5,0.0,clamp(emission-1.0,0.0,1.0));opacity*=saturate(1.0-distance*distance); #endif #ifdef RENDER_CUTOFF opacity*=v_cutoff_opacity; #endif glFragColor=vec4(v_color_emissive.rgb,1.0)*opacity;}`,`in vec3 a_pos_3f; #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 part_color_emissive #pragma mapbox: define-attribute highp vec4 bloom_attenuation out vec4 v_color_emissive;uniform mat4 u_matrix;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() { #pragma mapbox: initialize-attribute-custom highp uvec2 part_color_emissive #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation #ifdef HAS_ATTRIBUTE_a_part_color_emissive vec4 color_emissive=decode_color(vec2(part_color_emissive));float part_emissive=color_emissive.a*5.0;v_color_emissive=vec4(sRGBToLinear(color_emissive.rgb),part_emissive); #else v_color_emissive=vec4(1.0); #endif gl_Position=u_matrix*vec4(a_pos_3f,1.0); #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,native_clip_z_to_cutoff_depth(gl_Position.z,gl_Position.w)); #endif }`),buildingDepth:l.bm("void main() {}","in ivec2 a_pos_packed;uniform mat4 u_matrix;void main() {vec3 pos=vec3(float(a_pos_packed.x >> 16),float((a_pos_packed.x << 16) >> 16),intBitsToFloat(a_pos_packed.y));gl_Position=u_matrix*vec4(pos,1.0);}"),rasterParticle:l.bm(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;in vec2 v_pos0;in vec2 v_pos1;uniform sampler2D u_image0;uniform sampler2D u_image1;void main() {vec4 color0,color1,color;color0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 out_color=color.rgb; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),1.0).rgb; #endif #ifdef FOG highp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit)); #endif glFragColor=vec4(out_color*color.a,color.a); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center; #define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8 in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {float w=1.0;vec2 uv; #ifdef PROJECTION_GLOBE_VIEW vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]);float tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvX=mercatorX*tiles-idx;float uvY=mercatorY*tiles-idy;uv=vec2(uvX,uvY);vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,u_raster_elevation,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition)*w,w);gl_Position=u_matrix*interpolated_pos; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif #else uv=vec2(a_texture_pos)/8192.0;gl_Position=u_matrix*vec4(vec2(a_pos)*w,u_raster_elevation*w,w); #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #endif v_pos0=bottom_left_to_native_uv(uv);v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}`),rasterParticleDraw:l.bm("uniform sampler2D u_color_ramp;in float v_particle_speed;void main() {glFragColor=texture(u_color_ramp,vec2(v_particle_speed,0.5));}",`#include "_prelude_raster_particle.glsl" in int a_index;uniform sampler2D u_particle_texture;uniform float u_particle_texture_side_len;uniform vec2 u_tile_offset;out float v_particle_speed;void main() {ivec2 pixel_coord=ivec2( mod(float(a_index),u_particle_texture_side_len),float(a_index)/u_particle_texture_side_len);vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);vec2 pos=unpack_pos_from_rgba(pixel)+u_tile_offset;vec2 tex_coord=fract(pos);vec2 velocity=lookup_velocity(tex_coord);if (velocity==INVALID_VELOCITY) {gl_Position=AWAY;v_particle_speed=0.0;} else {gl_Position=vec4(2.0*pos-1.0,0,1);v_particle_speed=length(velocity);}gl_PointSize=1.0;}`),rasterParticleTexture:l.bm("uniform sampler2D u_texture;uniform float u_opacity;in vec2 v_tex_pos;void main() {vec4 color=texture(u_texture,v_tex_pos);glFragColor=vec4(floor(255.0*color*u_opacity)/255.0);}","in ivec2 a_pos;out vec2 v_tex_pos;void main() {vec2 uv=0.5*vec2(a_pos)+vec2(0.5);v_tex_pos=bottom_left_to_native_uv(uv);gl_Position=vec4(a_pos,0.0,1.0);}"),rasterParticleUpdate:l.bm(`#include "_prelude_raster_particle.glsl" uniform sampler2D u_particle_texture;uniform mediump float u_particle_texture_side_len;uniform mediump float u_speed_factor;uniform highp float u_reset_rate;uniform highp float u_rand_seed;in highp vec2 v_tex_coord;vec2 linearstep(vec2 edge0,vec2 edge1,vec2 x) {return clamp((x-edge0)/(edge1-edge0),vec2(0),vec2(1));}const highp vec3 rand_constants=vec3(12.9898,78.233,4375.85453);highp float rand(const highp vec2 co) {highp float t=dot(rand_constants.xy,co);return fract(sin(t)*(rand_constants.z+t));}void main() {ivec2 pixel_coord=ivec2(v_tex_coord*u_particle_texture_side_len);highp vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);highp vec2 pos=unpack_pos_from_rgba(pixel);highp vec2 velocity=lookup_velocity(clamp(pos,0.0,1.0));highp vec2 dp=velocity==INVALID_VELOCITY ? vec2(0) : velocity*u_speed_factor;pos=pos+dp;highp vec2 seed=(pos+v_tex_coord)*u_rand_seed;highp vec2 random_pos=vec2(rand(seed+1.3),rand(seed+2.1));highp vec2 persist_rate=pow( linearstep(vec2(-u_particle_pos_offset),vec2(0),pos)*linearstep(vec2(1.0+u_particle_pos_offset),vec2(1),pos),vec2(4) );highp vec2 per_frame_persist=pow(persist_rate,abs(dp)/u_particle_pos_offset);highp float drop_rate=1.0-per_frame_persist.x*per_frame_persist.y;drop_rate=any(greaterThanEqual(abs(pos-0.5),vec2(0.5+u_particle_pos_offset))) ? 1.0 : drop_rate;highp float drop=step(1.0-drop_rate-u_reset_rate,rand(seed));highp vec2 next_pos=mix(pos,random_pos,drop);glFragColor=pack_pos_to_rgba(next_pos);}`,"in ivec2 a_pos;out vec2 v_tex_coord;void main() {v_tex_coord=0.5*vec2(a_pos+ivec2(1));gl_Position=vec4(a_pos,0.0,1.0);}"),snowParticle:l.bm("in highp vec2 uv;in highp float alphaMultiplier;uniform vec4 u_particleColor;uniform vec2 u_simpleShapeParameters;void main() {float t=clamp((length(uv)-u_simpleShapeParameters.x)/(1.0-u_simpleShapeParameters.x),0.0,1.0);float alpha=1.0-pow(t,pow(10.0,u_simpleShapeParameters.y));alpha*=alphaMultiplier;alpha*=u_particleColor.a;vec3 color=u_particleColor.rgb*alpha;glFragColor=vec4(color,alpha) ;HANDLE_WIREFRAME_DEBUG;}",` in highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_snowParticleData;in highp vec4 a_snowParticleDataHorizontalOscillation;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform vec2 u_screenSize;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture;uniform float u_velocity;uniform vec3 u_direction;uniform float u_horizontalOscillationRadius;uniform float u_horizontalOscillationRate;uniform float u_billboardSize;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;out highp vec2 uv;out highp float alphaMultiplier;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos.xyz*=halfBoxSize;pos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_snowParticleData.z;float coneAngleHeadingRad=a_snowParticleData.w*radians(360.0);vec3 localZ=normalize(u_direction);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 direction;direction.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.z=cos(coneAnglePichRad);direction=normalize(direction);vec3 simPosLocal=vec3(0,0,0);float velocityScale=(1.0+3.0*a_snowParticleData.y)*u_velocity;simPosLocal+=direction*velocityScale*u_time;float horizontalOscillationRadius=u_horizontalOscillationRadius*a_snowParticleDataHorizontalOscillation.x;float horizontalOscillationAngle=u_horizontalOscillationRate*u_time*(-1.0+2.0*a_snowParticleDataHorizontalOscillation.y);simPosLocal.xy+=horizontalOscillationRadius*vec2(cos(horizontalOscillationAngle),sin(horizontalOscillationAngle));vec3 simPos=localX*simPosLocal.x+localY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);float clipZ=-u_cam_pos.z+pos.z;vec4 posView=u_modelview*vec4(pos,1.0);float size=u_billboardSize;alphaMultiplier=1.0;vec4 posScreen=u_projection*posView;posScreen/=posScreen.w;posScreen.xy=vec2(0.5)+posScreen.xy*0.5;posScreen.xy*=u_screenSize;vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=u_screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-posScreen.xy)/(0.5*u_screenSize));screenDist+=a_snowParticleData.x*u_thinningParticleOffset;float scaleFactorMode=0.0;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);if (a_snowParticleData.x < u_thinningAffectedRatio) {scaleFactorMode=1.0-thinningFadeRatio;alphaMultiplier=thinningFadeRatio;}}vec4 posScreen1=u_projection*vec4(posView.x-size,posView.yzw);posScreen1/=posScreen1.w;vec4 posScreen2=u_projection*vec4(posView.x+size,posView.yzw);posScreen2/=posScreen2.w;posScreen1.xy=vec2(0.5)+posScreen1.xy*0.5;posScreen1.xy*=u_screenSize;posScreen2.xy=vec2(0.5)+posScreen2.xy*0.5;posScreen2.xy*=u_screenSize;float screenLength=length(posScreen1.xy-posScreen2.xy);float screenEpsilon=3.0;float scaleFactor=1.0;if (screenLength < screenEpsilon) {scaleFactor=screenEpsilon/max(screenLength,0.01);scaleFactor=mix(scaleFactor,1.0,scaleFactorMode);}float screenEpsilon2=15.0;if (screenLength > screenEpsilon2) {scaleFactor=screenEpsilon2/max(screenLength,0.01);}size*=scaleFactor;vec2 right=size*vec2(1,0);vec2 up=size*vec2(0,1);posView.xy+=right*a_uv.x;posView.xy+=up*a_uv.y;uv=a_uv;gl_Position=u_projection*posView;}`),rainParticle:l.bm("in highp vec2 uv;in highp float particleRandomValue;uniform sampler2D u_texScreen;uniform float u_distortionStrength;uniform vec4 u_color;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;uniform float u_shapeDirectionalPower;uniform float u_mode;void main() {vec2 st=uv*0.5+vec2(0.5);vec2 uvm=uv;uvm.y=-1.0+2.0*pow(st.y,u_shapeDirectionalPower);float shape=clamp(1.0-length(uvm),0.0,1.0);float alpha=abs(shape)*u_color.a;vec2 screenSize=vec2(textureSize(u_texScreen,0));vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-gl_FragCoord.xy)/(0.5*screenSize));screenDist+=(0.5+0.5*particleRandomValue)*u_thinningParticleOffset;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;float thinningAlpha=1.0;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);thinningAlpha*=thinningFadeRatio;}vec2 offsetXY=normalize(uvm)*abs(shape);vec2 stScreen=(gl_FragCoord.xy+offsetXY*u_distortionStrength*thinningAlpha)/screenSize;vec3 colorScreen=texture(u_texScreen,stScreen).rgb;alpha*=thinningAlpha;glFragColor=mix(vec4(colorScreen,1.0),vec4(u_color.rgb*alpha,alpha),u_mode);HANDLE_WIREFRAME_DEBUG;}",` in highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_rainParticleData;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture;uniform float u_velocity;uniform vec2 u_rainDropletSize;uniform vec3 u_rainDirection;out highp vec2 uv;out highp float particleRandomValue;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos*=halfBoxSize;pos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_rainParticleData.z;float coneAngleHeadingRad=a_rainParticleData.w*radians(360.0);vec3 localZ=normalize(u_rainDirection);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 directionLocal;directionLocal.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.z=cos(coneAnglePichRad);directionLocal=normalize(directionLocal);vec3 directionWorld=localX*directionLocal.x+localY*directionLocal.y+localZ*directionLocal.z;float velocityScale=(1.0+3.0*a_rainParticleData.y)*u_velocity;vec3 simPosLocal=vec3(0,0,0);simPosLocal+=directionLocal*velocityScale*u_time;vec3 simPos=localX*simPosLocal.x+localY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);vec4 posView=u_modelview*vec4(pos,1.0);vec3 directionView=normalize((u_modelview*vec4(directionWorld,0.0)).xyz);vec3 side=cross(directionView,normalize(posView.xyz));posView.xyz+=side*a_uv.x*u_rainDropletSize.x;posView.xyz+=directionView*a_uv.y*u_rainDropletSize.y;uv=a_uv;particleRandomValue=a_rainParticleData.x;gl_Position=u_projection*posView;}`),vignette:l.bm("uniform vec3 u_vignetteShape;uniform vec4 u_vignetteColor;in vec2 st;void main() {float screenDist=length(st);float alpha=clamp((screenDist-u_vignetteShape.x)/u_vignetteShape.y,0.0,1.0);alpha=pow(alpha,u_vignetteShape.z)*u_vignetteColor.a;vec3 color=u_vignetteColor.rgb;glFragColor=vec4(color*alpha,alpha) ;}","in vec2 a_pos_2f;out vec2 st;void main() {st=a_pos_2f;gl_Position=vec4(a_pos_2f,0,1);}"),elevatedStructuresDepth:l.bm("void main() {}","in ivec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform float u_depth_bias;void main() {gl_Position=u_matrix*vec4(a_pos,a_height,1);gl_Position.z=gl_Position.z+u_depth_bias;}"),elevatedStructures:l.bm(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" in vec3 v_normal;in float v_height; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth; #endif vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}vec3 compute_view_dependent_emissive_color(float ndotl,float emissive_strength,vec3 color) {color=sRGBToLinear(color);color=color*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);color=linearTosRGB(color.rgb);return color;}uniform float u_emissive_strength;uniform float u_opacity_multiplier; #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color vec3 color=structure_color.xyz;vec2 cutout_factors=vec2(0.0); #ifdef LIGHTING_3D_MODE vec3 normal=normalize(v_normal);vec3 transformed_normal=vec3(-normal.xy,normal.z);float ndotl=calculate_NdotL(transformed_normal);float emissive_strength=u_emissive_strength;emissive_strength=0.0;vec3 emissive_color=compute_view_dependent_emissive_color(ndotl,emissive_strength,color.xyz); #ifdef RENDER_SHADOWS float light=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);color.rgb=apply_lighting(color.rgb,transformed_normal,light); #else color=apply_lighting(color,transformed_normal); #endif color=mix(color,emissive_color,emissive_strength);if (v_height < 0.0) {float penetration=max(v_height+7.5,0.0);float occlusion=1.0-1.0/PI*acos(1.0-penetration/4.0);color=color*(1.0-pow(occlusion,2.0)*0.3);} #endif #ifdef FOG color=fog_apply(color,v_fog_pos); #endif vec4 out_color=vec4(color,1.0);out_color*=u_opacity_multiplier;glFragColor=out_color;HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos;in float a_height;in ivec4 a_pos_normal_3;uniform mat4 u_matrix;out vec3 v_normal;out float v_height; #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth; #endif #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color v_normal=vec3(a_pos_normal_3)/16384.0;v_height=a_height;vec3 pos=vec3(vec2(a_pos),a_height);gl_Position=u_matrix*vec4(pos,1); #ifdef RENDER_SHADOWS vec3 shd_pos0=pos;vec3 shd_pos1=pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(-v_normal.xy,v_normal.z));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),elevatedStructuresDepthReconstruct:l.bm(`#include "_prelude_feature_cutout.fragment.glsl" #ifdef DEPTH_RECONSTRUCTION in float v_height; #endif void main() { #ifdef DEPTH_RECONSTRUCTION if (v_height >=0.0) discard; #else #endif glFragColor=vec4(1.0,0.0,0.0,1.0);}`,`in ivec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform vec3 u_camera_pos;uniform highp float u_depth_bias;uniform lowp float u_height_scale;uniform lowp float u_reset_depth; #ifdef DEPTH_RECONSTRUCTION out float v_height; #endif void main() {vec3 vpos=vec3(a_pos,a_height*u_height_scale); #ifdef DEPTH_RECONSTRUCTION if (u_camera_pos.z > vpos.z) {vpos-=(u_camera_pos-vpos)*(vpos.z/(u_camera_pos.z-vpos.z));}v_height=a_height; #endif gl_Position=u_matrix*vec4(vpos,1);gl_Position.z=u_reset_depth==1.0 ? gl_Position.w : gl_Position.z+u_depth_bias;}`)};l.bm(Ma,"");const Wa=l.b9([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]),Ll=l.b9([{type:"Float32",name:"a_pos_2f",components:2}]);class vl{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(f,y){const w=f.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const M=new l.bn,z=new l.ak;M.emplaceBack(-1,-1),M.emplaceBack(1,-1),M.emplaceBack(1,1),M.emplaceBack(-1,1),z.emplaceBack(0,1,2),z.emplaceBack(0,2,3),this.vignetteVx=f.context.createVertexBuffer(M,Ll.members),this.vignetteIdx=f.context.createIndexBuffer(z)}const k=l.aj.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){f.uploadCommonUniforms(f.context,w);const M={u_vignetteShape:(R={vignetteShape:[y.start,y.range,Math.pow(10,y.fadePower)],vignetteColor:[y.color.r,y.color.g,y.color.b,y.color.a*y.strength]}).vignetteShape,u_vignetteColor:R.vignetteColor};w.draw(f,f.context.gl.TRIANGLES,l.a3.disabled,l.a4.disabled,l.a7.alphaBlended,l.a5.disabled,M,"vignette",this.vignetteVx,this.vignetteIdx,k)}var R}}class bl{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(f,y){const w=f.getFreeCameraOptions().position,k=w.toAltitude(),R=w.toLngLat(),M=l.aF(R.lng),z=l.aF(R.lat),V=f.pixelsPerMeter/y,H=M*l.bu,Y=l.bu*Math.log(Math.tan(Math.PI/4+z/2));if(this._offsetXPrev===void 0)this._offsetXPrev=0,this._offsetYPrev=0,this._elevationPrev=0,this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0;else{const te=-this._offsetYPrev+Y,ne=-this._elevationPrev+k;this._accumulatedOffsetX+=(-this._offsetXPrev+H)*V,this._accumulatedOffsetY+=te*V,this._accumulatedElevation+=ne*V,this._offsetXPrev=H,this._offsetYPrev=Y,this._elevationPrev=k}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Wd(_,f){return[-(_[0]-Math.floor(_[0]/f)*f),-(_[1]-Math.floor(_[1]/f)*f),-(_[2]-Math.floor(_[2]/f)*f)]}function xc(_){const f=l.bt(1323123451230),y=[];for(let w=0;w<_;++w){const k=2*f()-1,R=2*f()-1,M=2*f()-1;y.push(l.bs(k,R,M))}return y}function ta(_,f,y,w,k){const R=l.bb((k-y)/(w-y),0,1);return l.aw(_,f,R)}class Zs{constructor(f){this._movement=new bl,this._accumulatedTimeFromStart=0,this._prevTime=Date.now()/1e3,this._vignette=new vl,this._ppmScaleFactor=f}destroy(){this.particlesVx&&this.particlesVx.destroy(),this.particlesIdx&&this.particlesIdx.destroy(),this._vignette&&this._vignette.destroy()}updateOnRender(f,y){const w=f.transform;this._movement.update(w,this._ppmScaleFactor);const k=w.starsProjMatrix,R=l.bo([]);l.bp(R,R,l.aF(90)-w._pitch),l.bq(R,R,-w.angle);const M=l.br(new Float32Array(16),R),z=new Float32Array([1,0,0,0,0,0,1,0,0,-1,0,0,0,0,0,1]),V=l.a_([],z),H=l.a1([],V,M),Y=Date.now()/1e3;return this._accumulatedTimeFromStart+=(Y-this._prevTime)*y,this._prevTime=Y,{projectionMatrix:k,modelviewMatrix:H}}}const Dl=l.b9([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_snowParticleData",components:4},{type:"Float32",name:"a_snowParticleDataHorizontalOscillation",components:2}]),Vc=(_,f)=>({u_matrix:_,u_depth_bias:f}),fu=(_,f)=>({u_matrix:_,u_ground_shadow_factor:f,u_opacity_multiplier:1}),Ml=(_,f,y,w,k)=>({u_matrix:_,u_camera_pos:[f[0],f[1],f[2]],u_depth_bias:y,u_height_scale:w,u_reset_depth:k}),Vu={building:_=>({u_matrix:new l.aa(_),u_normal_matrix:new l.aa(_),u_opacity:new l.a9(_),u_faux_facade_ao_intensity:new l.a9(_),u_camera_pos:new l.ab(_),u_tile_to_meter:new l.a9(_),u_facade_emissive_chance:new l.a9(_),u_flood_light_color:new l.ab(_),u_flood_light_intensity:new l.a9(_),u_front_cutoff_params:new l.ab(_)}),buildingBloom:_=>({u_matrix:new l.aa(_)}),buildingDepth:_=>({u_matrix:new l.aa(_)}),elevatedStructuresDepth:_=>({u_matrix:new l.aa(_),u_depth_bias:new l.a9(_)}),elevatedStructures:_=>({u_matrix:new l.aa(_),u_ground_shadow_factor:new l.ab(_),u_opacity_multiplier:new l.a9(_)}),elevatedStructuresDepthReconstruct:_=>({u_matrix:new l.aa(_),u_camera_pos:new l.ab(_),u_depth_bias:new l.a9(_),u_height_scale:new l.a9(_),u_reset_depth:new l.a9(_)}),rasterParticle:_=>({u_matrix:new l.aa(_),u_normalize_matrix:new l.aa(_),u_globe_matrix:new l.aa(_),u_merc_matrix:new l.aa(_),u_grid_matrix:new l.b8(_),u_tl_parent:new l.a8(_),u_scale_parent:new l.a9(_),u_fade_t:new l.a9(_),u_opacity:new l.a9(_),u_image0:new l.b6(_),u_image1:new l.b6(_),u_raster_elevation:new l.a9(_),u_zoom_transition:new l.a9(_),u_merc_center:new l.a8(_),u_cutoff_params:new l.b7(_)}),rasterParticleTexture:_=>({u_texture:new l.b6(_),u_opacity:new l.a9(_)}),rasterParticleDraw:_=>({u_particle_texture:new l.b6(_),u_particle_texture_side_len:new l.a9(_),u_tile_offset:new l.a8(_),u_velocity:new l.b6(_),u_color_ramp:new l.b6(_),u_velocity_res:new l.a8(_),u_max_speed:new l.a9(_),u_uv_offset:new l.a8(_),u_data_scale:new l.a8(_),u_data_offset:new l.a9(_),u_particle_pos_scale:new l.a9(_),u_particle_pos_offset:new l.a8(_)}),rasterParticleUpdate:_=>({u_particle_texture:new l.b6(_),u_particle_texture_side_len:new l.a9(_),u_velocity:new l.b6(_),u_velocity_res:new l.a8(_),u_max_speed:new l.a9(_),u_speed_factor:new l.a9(_),u_reset_rate:new l.a9(_),u_rand_seed:new l.a9(_),u_uv_offset:new l.a8(_),u_data_scale:new l.a8(_),u_data_offset:new l.a9(_),u_particle_pos_scale:new l.a9(_),u_particle_pos_offset:new l.a8(_)}),snowParticle:_=>({u_modelview:new l.aa(_),u_projection:new l.aa(_),u_time:new l.a9(_),u_cam_pos:new l.ab(_),u_velocityConeAperture:new l.a9(_),u_velocity:new l.a9(_),u_horizontalOscillationRadius:new l.a9(_),u_horizontalOscillationRate:new l.a9(_),u_boxSize:new l.a9(_),u_billboardSize:new l.a9(_),u_simpleShapeParameters:new l.a8(_),u_screenSize:new l.a8(_),u_thinningCenterPos:new l.a8(_),u_thinningShape:new l.ab(_),u_thinningAffectedRatio:new l.a9(_),u_thinningParticleOffset:new l.a9(_),u_particleColor:new l.b7(_),u_direction:new l.ab(_)}),rainParticle:_=>({u_modelview:new l.aa(_),u_projection:new l.aa(_),u_time:new l.a9(_),u_cam_pos:new l.ab(_),u_texScreen:new l.b6(_),u_velocityConeAperture:new l.a9(_),u_velocity:new l.a9(_),u_boxSize:new l.a9(_),u_rainDropletSize:new l.a8(_),u_distortionStrength:new l.a9(_),u_rainDirection:new l.ab(_),u_color:new l.b7(_),u_screenSize:new l.a8(_),u_thinningCenterPos:new l.a8(_),u_thinningShape:new l.ab(_),u_thinningAffectedRatio:new l.a9(_),u_thinningParticleOffset:new l.a9(_),u_shapeDirectionalPower:new l.a9(_),u_shapeNormalPower:new l.a9(_),u_mode:new l.a9(_)}),vignette:_=>({u_vignetteShape:new l.ab(_),u_vignetteColor:new l.b7(_)})};function wl(_,f){const y=1<<_.canonical.z,w=(f.x*y-_.canonical.x-_.wrap*y)*l.ac,k=(f.y*y-_.canonical.y)*l.ac,R=l.bx(f.z,f.y);return l.bs(w,k,R)}function rl(_){let f=0;for(const y of _)f|=y.frcMask;return f}class Kl{constructor(f=[]){this.tiles=f}getTile(f){for(const y of this.tiles)if(y.tileId.z===f.z&&y.tileId.x===f.x&&y.tileId.y===f.y)return y;return null}getTileOrParent(f){for(let y=f.z;y>0;--y){const w=Math.floor(f.x/(1<0;--te){const ne=Math.floor(f.x/(1<z[qe]!=fe>z[qe]&&M[qe]w&&(Se|=2),lek&&(Se|=8),mew&&(Me|=2),fek&&(Me|=8),!(Se&Me)&&(Se===0||Me===0||Oa(ne,le,me,fe,f,y,w,k)))return!1}}for(let V=0;V<4;++V)if(!(1&R[V]))return!1;return!0}function Oa(_,f,y,w,k,R,M,z){const V=(H,Y,te,ne,le,me,fe,Se)=>{const Me=(te-H)*(me-Y)-(ne-Y)*(le-H),qe=(te-H)*(Se-Y)-(ne-Y)*(fe-H);if(Me>0&&qe>0||Me<0&&qe<0)return!1;const Ne=(fe-le)*(Y-me)-(Se-me)*(H-le),We=(fe-le)*(ne-me)-(Se-me)*(te-le);return!(Ne>0&&We>0||Ne<0&&We<0)};return!!(V(_,f,y,w,k,R,M,R)||V(_,f,y,w,M,R,M,z)||V(_,f,y,w,k,z,M,z)||V(_,f,y,w,k,R,k,z))}class Yl{constructor(){this._tileCoverages=[],this._snapshot=new Kl}clear(){this._tileCoverages=[]}addTileCoverage(f,y){this._tileCoverages.push({tileId:f,polygons:y,frcMask:rl(y)})}empty(){return this._tileCoverages.length===0}updateSnapshotIfNeeded(){if(this._snapshot.equals(this._tileCoverages))return this._snapshot;const f=this._tileCoverages.map(y=>({tileId:y.tileId,polygons:y.polygons,frcMask:y.frcMask}));return this._snapshot=new Kl(f),this._snapshot}}function Aa(_,f){const y={};if(!f)return y;for(const w of _){const k=w.layerIds.map(R=>f.getLayer(R)).filter(Boolean);if(k.length!==0){w.layers=k,w.stateDependentLayerIds&&(w.stateDependentLayers=w.stateDependentLayerIds.map(R=>k.filter(M=>M.id===R)[0])),w.updateExpressions&&w.updateExpressions(k);for(const R of k)y[R.fqid]=w}}return y}const ca=32,ga=33,Zl=new Uint16Array(8184);for(let _=0;_<2046;_++){let f=_+2,y=0,w=0,k=0,R=0,M=0,z=0;for(1&f?k=R=M=ca:y=w=z=ca;(f>>=1)>1;){const H=y+k>>1,Y=w+R>>1;1&f?(k=y,R=w,y=M,w=z):(y=k,w=R,k=M,R=z),M=H,z=Y}const V=4*_;Zl[V+0]=y,Zl[V+1]=w,Zl[V+2]=k,Zl[V+3]=R}const Ka=new Uint16Array(2178),hd=new Uint8Array(1089),Kr=new Uint16Array(1089);function l0(_){return _===0?-.03125:_===32?.03125:0}var Vn=l.b9([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);const vx={type:2,extent:l.ac,loadGeometry:()=>[[new l.P(0,0),new l.P(l.ac+1,0),new l.P(l.ac+1,l.ac+1),new l.P(0,l.ac+1),new l.P(0,0)]]};let bx,Uw=0;class yf{constructor(f,y,w,k,R,M){this.tileID=f,this.uid=l.aG(),this.uses=0,this.tileSize=y,this.tileZoom=w,this.dashIdealZ=f.overscaledZ,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasTunnelGeometry=!1,this.dependencies={},this.isRaster=R,k&&k.style&&(this._lastUpdatedBrightness=k.style.getBrightness()),this._lastAvailableImagesCount=0,this._firstPrepareComplete=!1,this._queryPaddingPaintVersions={},this.expiredRequestCount=0,this.state="loading",k&&k.transform&&(this.projection=k.transform.projection),this.worldview=M,this._hasAppearances=null}registerFadeDuration(f){const y=f+this.timeAdded;y0&&(this.frcCoveragePolygons=f.frcCoveragePolygons),this.hasDeferredRoadStructure=!!f.hasDeferredRoadStructure,f.parsedElevationFeatures!==void 0&&(this.parsedElevationFeatures=f.parsedElevationFeatures,this.parsedElevationGeneration=++Uw),this.hasDeferredElevationFeatures=!!f.hasDeferredElevationFeatures,this.hasSymbolBuckets=!1,this.hasTunnelGeometry=!!f.hasTunnelGeometry;for(const k in this.buckets){const R=this.buckets[k];if(R instanceof l.bF){if(this.hasSymbolBuckets=!0,!w)break;R.justReloaded=!0}}this.queryPadding=0,this._queryPaddingPaintVersions={};for(const k in this.buckets){const R=this.buckets[k];R instanceof l.bF&&!R.bucketInstanceId&&(R.bucketInstanceId=l.bF.maxBucketInstanceId++);const M=y.style.getOwnLayer(k);if(!M)continue;const z=M.queryRadius(R)||0;this.queryPadding=Math.max(this.queryPadding,z),this._queryPaddingPaintVersions[k]=M.paintVersion}f.imageAtlas&&(this.imageAtlas=y.style.imageManager.imageAtlasCache.getOrCache(f.imageAtlas)),f.glyphAtlasImage&&(this.glyphAtlasImage=f.glyphAtlasImage),f.lineAtlas&&(this.lineAtlas=f.lineAtlas),this._lastUpdatedBrightness=f.brightness}else this.collisionBoxArray=new l.bE}resetPlacementVisibility(){var f,y;for(const w in this.buckets)(y=(f=this.buckets[w]).resetPlacementVisibility)==null||y.call(f)}unloadVectorData(){if(this.hasData()){for(const f in this.buckets)this.buckets[f].destroy();this.buckets={},this.imageAtlas&&(this.imageAtlas=null),this.lineAtlas&&(this.lineAtlas=null),this.imageAtlasTexture&&(this.imageAtlasTexture=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.lineAtlasTexture&&this.lineAtlasTexture.destroy(),this._tileBoundsBuffer&&(this._tileBoundsBuffer.destroy(),this._tileBoundsIndexBuffer.destroy(),this._tileBoundsSegments.destroy(),this._tileBoundsBuffer=null),this._tileDebugBuffer&&(this._tileDebugBuffer.destroy(),this._tileDebugSegments.destroy(),this._tileDebugBuffer=null),this._tileDebugIndexBuffer&&(this._tileDebugIndexBuffer.destroy(),this._tileDebugIndexBuffer=null),this._globeTileDebugBorderBuffer&&(this._globeTileDebugBorderBuffer.destroy(),this._globeTileDebugBorderBuffer=null),this._tileDebugTextBuffer&&(this._tileDebugTextBuffer.destroy(),this._tileDebugTextSegments.destroy(),this._tileDebugTextIndexBuffer.destroy(),this._tileDebugTextBuffer=null),this._globeTileDebugTextBuffer&&(this._globeTileDebugTextBuffer.destroy(),this._globeTileDebugTextBuffer=null),this.latestFeatureIndex=null,this.state="unloaded"}}loadModelData(f,y,w){f&&(f.resourceTiming&&(this.resourceTiming=f.resourceTiming),this.buckets={...this.buckets,...Aa(f.buckets,y.style)},f.featureIndex&&(this.latestFeatureIndex=f.featureIndex))}getBucket(f){return this.buckets[f.fqid]}upload(f,y){for(const R in this.buckets){const M=this.buckets[R];if(M.uploadPending()){let z={},V=[],H={zoom:0,pitch:0,brightness:0,worldview:""};if(y){if(y.style){V=y.style.listImages();const Y=M.layers[0],te=Y.sourceLayer||"_geojsonTileLayer",ne=y.style.getLayerSourceCache(Y);ne&&(z=ne._state.getState(te,void 0))}H={zoom:y.transform.zoom||0,pitch:y.transform.pitch||0,brightness:y.style.getBrightness()||0,worldview:y.worldview||""}}M.upload(f,this.tileID.canonical,z,V,H)}}const w=f.gl,k=this.imageAtlas;k&&y&&(this.imageAtlasTexture=y.style.imageManager.imageAtlasCache.getTextureForAtlas(k,f,w.RGBA8)),this.glyphAtlasImage&&(this.glyphAtlasTexture=new l.T(f,this.glyphAtlasImage,w.R8),this.glyphAtlasImage=null),this.lineAtlas&&!this.lineAtlas.uploaded&&(this.lineAtlasTexture=new l.T(f,this.lineAtlas.image,w.R8),this.lineAtlas.uploaded=!0)}prepare(f,y,w){if(this.imageAtlas&&this.imageAtlasTexture&&y){const H=y.style.getLut(w);this.imageAtlas.patchUpdatedImages(f,this.imageAtlasTexture,w,H)}if(!y||!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData)return;const k=y.style.getBrightness(),R=y.style.listImages(),M=R.length,z=this._firstPrepareComplete&&M!==this._lastAvailableImagesCount;this._updatePaint(y,R,k,z),this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(y));const V=this._lastUpdatedBrightness!==k;this._lastAvailableImagesCount=M,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||k||this._hasAppearances||z)&&(!this._hasAppearances&&!z&&this._lastUpdatedBrightness&&k&&Math.abs(this._lastUpdatedBrightness-k)<.001||(this.updateBuckets(y,V,void 0,z,R),this._lastUpdatedBrightness=k))}_updatePaint(f,y,w,k){const R=f.style;for(const M in this.buckets){const z=this.buckets[M],V=R.getOwnLayer(M);V&&(z instanceof l.bG&&V.type==="line"?this._updateBinderPaint(f,z,z.uboBinders[V.id],V,y,w,k):z instanceof l.bF&&V.type==="symbol"&&(this._updateBinderPaint(f,z,z.text.uboBinder,V,y,w,k),this._updateBinderPaint(f,z,z.icon.uboBinder,V,y,w,k)),this._queryPaddingPaintVersions[M]!==V.paintVersion&&(this._queryPaddingPaintVersions[M]=V.paintVersion,this.queryPadding=Math.max(this.queryPadding,V.queryRadius(z)||0)))}}_updateBinderPaint(f,y,w,k,R,M,z){if(!w)return;const V=w.updatePaint(k);if(V!=="unchanged"||z){if(V==="features"||z){const H=y.layers[0],Y=H.sourceLayer||"_geojsonTileLayer",te=f.style.getLayerSourceCache(H),ne=te?te._state.getState(Y,void 0):{},le=this.latestFeatureIndex.loadVTLayers()[Y];w.updateDynamicExpressions(k,le,this.tileID.canonical,R,ne,M)}w.upload(f.context)}}evaluateQueryRenderedFeaturePadding(){let f=0;for(const y in this.buckets){const w=this.buckets[y];w.evaluateQueryRenderedFeaturePadding&&(f=Math.max(f,w.evaluateQueryRenderedFeaturePadding()))}return f}queryRenderedFeatures(f,y,w,k,R,M,z){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const V=this.evaluateQueryRenderedFeaturePadding(),H=function(Y,te){const ne=l.bW([],[.5*Y.width,.5*-Y.height,1]);return l.bX(ne,ne,[1,-1,0]),l.a1(ne,ne,Y.calculateProjMatrix(te.toUnwrapped())),Float32Array.from(ne)}(R,this.tileID);return this.latestFeatureIndex.query(f,{tilespaceGeometry:y,pixelPosMatrix:H,transform:k,availableImages:w,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:V,scope:z})}querySourceFeatures(f,y){const w=this.latestFeatureIndex;if(!w||!w.rawTileData)return;const k=w.loadVTLayers(),R=y?y.sourceLayer:"",M=k._geojsonTileLayer||k[R];if(!M)return;const z=l.bH(y&&y.filter),{z:V,x:H,y:Y}=this.tileID.canonical,te={z:V,x:H,y:Y};for(let ne=0;new)k=!1;else if(y)if(this.expirationTimew.appearances&&w.appearances.length>0))return!0;return!1}updateBuckets(f,y,w,k,R){if(!this.latestFeatureIndex||!f.style)return;const M=R||f.style.listImages(),z=f.style.getBrightness();for(const V in this.buckets){if(!f.style.hasLayer(V))continue;const H=this.buckets[V],Y=H.layers[0],te=Y.sourceLayer||"_geojsonTileLayer",ne=f.style.getLayerSourceCache(Y);let le=w&&w[te]||{};ne&&!w&&(le=ne._state.getState(te,void 0));const me=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},fe=Object.keys(le).length>0&&!y;H.hasAppearances=H.layers.some(Ne=>Ne.appearances&&Ne.appearances.length>0);const Se=fe?H.stateDependentLayers:H.layers,Me=fe&&H.stateDependentLayers.length!==0;if(Me||y||k){const Ne=this.latestFeatureIndex.loadVTLayers();if(H.update(le,Ne[te],M,me,Se,y,z,this.tileID.canonical),H instanceof l.bF)H.text.uboBinder&&H.text.uboBinder.upload(f.context),H.icon.uboBinder&&H.icon.uboBinder.upload(f.context);else if(H instanceof l.bG)for(const{id:We}of H.layers)H.uboBinders[We].upload(f.context)}if(Me||y||H.hasAppearances){const Ne={zoom:f.transform.zoom,pitch:f.transform.pitch,brightness:f.style.getBrightness()||0,worldview:f.worldview},We=H.updateAppearances(this.tileID.canonical,le,M,Ne,f.imageManager,Me);We&&We.hasUboChanges&&H instanceof l.bF&&(H.text.uboBinder&&H.text.uboBinder.upload(f.context),H.icon.uboBinder&&H.icon.uboBinder.upload(f.context))}(H instanceof l.bG||H instanceof l.bL)&&f._terrain&&f._terrain.enabled&&ne&&H.uploadPending()&&f._terrain._clearRenderCacheForTile(ne.id,this.tileID);const qe=f&&f.style&&f.style.getOwnLayer(V);qe&&(this.queryPadding=Math.max(this.queryPadding,qe.queryRadius(H)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Se--){const Me=4*Se,qe=Zl[Me+0],Ne=Zl[Me+1],We=Zl[Me+2],ct=Zl[Me+3],it=qe+We>>1,pt=Ne+ct>>1,dt=it+pt-Ne,mt=pt+qe-it,xt=Ne*ga+qe,bt=ct*ga+We,Ft=pt*ga+it,Lt=Math.hypot((Ka[2*xt+0]+Ka[2*bt+0])/2-Ka[2*Ft+0],(Ka[2*xt+1]+Ka[2*bt+1])/2-Ka[2*Ft+1])>=16;hd[Ft]=hd[Ft]||(Lt?1:0),Se<1022&&(hd[Ft]=hd[Ft]||hd[(Ne+mt>>1)*ga+(qe+dt>>1)]||hd[(ct+mt>>1)*ga+(We+dt>>1)])}const te=new l.bD,ne=new l.ak;let le=0;function me(Se,Me){const qe=Me*ga+Se;return Kr[qe]===0&&(te.emplaceBack(Ka[2*qe+0],Ka[2*qe+1],Se*l.ac/ca,Me*l.ac/ca),Kr[qe]=++le),Kr[qe]-1}function fe(Se,Me,qe,Ne,We,ct){const it=Se+qe>>1,pt=Me+Ne>>1;if(Math.abs(Se-We)+Math.abs(Me-ct)>1&&hd[pt*ga+it])fe(We,ct,Se,Me,it,pt),fe(qe,Ne,We,ct,it,pt);else{const dt=me(Se,Me),mt=me(qe,Ne),xt=me(We,ct);ne.emplaceBack(dt,mt,xt)}}return fe(0,0,ca,ca,ca,0),fe(ca,ca,0,0,0,ca),{vertices:te,indices:ne}}(this.tileID.canonical,y);k=M.vertices,R=M.indices}else{k=new l.bD,R=new l.ak;for(const{x:z,y:V}of w)k.emplaceBack(z,V,0,0);const M=l.bQ(k.int16.subarray(0,4*k.length),void 0,4);for(let z=0;z0&&(V=l.aZ(new Float64Array(16),y.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(f,k,y,M,V,z),this._makeGlobeTileDebugTextBuffer(f,k,y,M,V,z)}_globePoint(f,y,w,k,R,M,z){let V=l.bR(f,y,w);if(M){const H=1<.5?le=-1:ne<-.5&&(le=1);let me=(f/l.ac+w.x)/H+le,fe=(y/l.ac+w.y)/H;me=(me-Y)*k._pixelsPerMercatorPixel+Y,fe=(fe-te)*k._pixelsPerMercatorPixel+te;const Se=[me*k.worldSize,fe*k.worldSize,0];l.bS(Se,Se,M),V=l.bT(V,Se,z)}return l.bS(V,V,R)}_makeGlobeTileDebugBorderBuffer(f,y,w,k,R,M){const z=new l.bN,V=new l.bO,H=new l.bU,Y=(ne,le,me,fe,Se)=>{const Me=(me-ne)/(Se-1),qe=(fe-le)/(Se-1),Ne=z.length;for(let We=0;Wete*le+me;for(let le=0;le{this.remove(f,R)},w)),this.data[k].push(R),this.order.push(k),this.order.length>this.max){const M=this._getAndRemoveByKey(this.order[0]);M&&this.onRemove(M)}return this}has(f){return f.wrapped().key in this.data}getAndRemove(f){return this.has(f)?this._getAndRemoveByKey(f.wrapped().key):null}_getAndRemoveByKey(f){const y=this.data[f].shift();return y.timeout&&clearTimeout(y.timeout),this.data[f].length===0&&delete this.data[f],this.order.splice(this.order.indexOf(f),1),y.value}getByKey(f){const y=this.data[f];return y?y[0].value:null}get(f){return this.has(f)?this.data[f.wrapped().key][0].value:null}remove(f,y){if(!this.has(f))return this;const w=f.wrapped().key,k=y===void 0?0:this.data[w].indexOf(y),R=this.data[w][k];return this.data[w].splice(k,1),R.timeout&&clearTimeout(R.timeout),this.data[w].length===0&&delete this.data[w],this.onRemove(R.value),this.order.splice(this.order.indexOf(w),1),this}setMaxSize(f){for(this.max=f;this.order.length>this.max;){const y=this._getAndRemoveByKey(this.order[0]);y&&this.onRemove(y)}return this}filter(f){const y=[];for(const w in this.data)for(const k of this.data[w])f(k.value)||y.push(k);for(const w of y)this.remove(w.value.tileID,w)}}class Xl{constructor(){this.state=Object.create(null),this.stateChanges=Object.create(null),this.deletedStates=Object.create(null)}updateState(f,y,w){const k=String(y);if(this.stateChanges[f]=this.stateChanges[f]||Object.create(null),this.stateChanges[f][k]=this.stateChanges[f][k]||Object.create(null),Object.assign(this.stateChanges[f][k],w),this.deletedStates[f]===null){this.deletedStates[f]=Object.create(null);for(const R in this.state[f])R!==k&&(this.deletedStates[f][R]=null)}else if(this.deletedStates[f]&&this.deletedStates[f][k]===null){this.deletedStates[f][k]=Object.create(null);for(const R in this.state[f][k])w[R]||(this.deletedStates[f][k][R]=null)}else for(const R in w)this.deletedStates[f]&&this.deletedStates[f][k]&&this.deletedStates[f][k][R]===null&&delete this.deletedStates[f][k][R]}removeFeatureState(f,y,w){if(this.deletedStates[f]===null)return;const k=String(y);if(this.deletedStates[f]=this.deletedStates[f]||Object.create(null),w&&y!==void 0)this.deletedStates[f][k]!==null&&(this.deletedStates[f][k]=this.deletedStates[f][k]||Object.create(null),this.deletedStates[f][k][w]=null);else if(y!==void 0)if(this.stateChanges[f]&&this.stateChanges[f][k])for(w in this.deletedStates[f][k]=Object.create(null),this.stateChanges[f][k])this.deletedStates[f][k][w]=null;else this.deletedStates[f][k]=null;else this.deletedStates[f]=null}getState(f,y){const w=this.state[f]||Object.create(null),k=this.stateChanges[f]||Object.create(null),R=this.deletedStates[f];if(R===null)return Object.create(null);if(y!==void 0){const z=String(y),V=Object.assign(Object.create(null),w[z],k[z]);if(R){const H=R[y];if(H===null)return Object.create(null);for(const Y in H)delete V[Y]}return V}const M=Object.assign(Object.create(null),w,k);if(R)for(const z in R)delete M[z];return M}initializeTileState(f,y){f.refreshFeatureState(y)}coalesceChanges(f,y){const w=Object.create(null);for(const k in this.stateChanges){this.state[k]=this.state[k]||Object.create(null);const R=Object.create(null);for(const M in this.stateChanges[k])this.state[k][M]||(this.state[k][M]=Object.create(null)),Object.assign(this.state[k][M],this.stateChanges[k][M]),R[M]=this.state[k][M];w[k]=R}for(const k in this.deletedStates){this.state[k]=this.state[k]||Object.create(null);const R=Object.create(null);if(this.deletedStates[k]===null)for(const M in this.state[k])R[M]=Object.create(null),this.state[k][M]=Object.create(null);else for(const M in this.deletedStates[k]){if(this.deletedStates[k][M]===null)this.state[k][M]=Object.create(null);else if(this.state[k][M])for(const z of Object.keys(this.deletedStates[k][M]))delete this.state[k][M][z];R[M]=this.state[k][M]}w[k]=w[k]||Object.create(null),Object.assign(w[k],R)}if(this.stateChanges=Object.create(null),this.deletedStates=Object.create(null),Object.keys(w).length!==0)for(const k of f.values())k.refreshFeatureState(y,w)}}class kh extends l.E{constructor(f,y,w,k){super(),this.id=f,this.type=y.type,this._options=y,this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.setEventedParent(k)}hasTransition(){return!1}startLoad(){const f=this._loader;this._loader=void 0,f&&f()}loaded(){return this._loader!==void 0}onAdd(f){}onRemove(f){}loadTile(f,y){}serialize(){return this._options}}class il extends l.E{constructor(f,y,w){super(),this.id=f,this._renderSourceType=w,this._maxzoomOverride=null,this.setSource(y),this._tiles=new Map,this._cache=new Ah(0,this._unloadTile.bind(this)),this._timers=new Map,this._minTileCacheSize=y.minTileCacheSize,this._maxTileCacheSize=y.maxTileCacheSize,this._loadedParentTiles=new Map,this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles=new Set,this._shadowCasterTiles=new Set,this._state=new Xl,this._isRaster=this._source.type==="raster"||this._source.type==="raster-dem"||this._source.type==="raster-array"||this._source.type==="custom"&&"_dataType"in this._source&&this._source._dataType==="raster",this._supportsFading=this._source.type==="raster"||this._source.type==="raster-array"||this._source.type==="image"||this._source.type==="video"||this._source.type==="custom",this._isRasterElevatedOverTerrain=!1}onAdd(f){this.map=f,this._minTileCacheSize=this._minTileCacheSize===void 0&&f?f._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&f?f._maxTileCacheSize:this._maxTileCacheSize}setSource(f){f.on("data",y=>{y.dataType==="source"&&y.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&y.dataType==="source"&&y.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),f.on("error",()=>{this._sourceErrored=!0}),this._source=f}loaded(){if(this._sourceErrored)return!0;if(this._source instanceof kh)return this._source.loaded();if(!this._sourceLoaded||!this._source.loaded())return!1;for(const f of this._tiles.values())if(!f.loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const f=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,f&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(f){this._maxzoomOverride=f}_loadTile(f,y){return f.renderSourceType=this._renderSourceType,f.isExtraShadowCaster=this._shadowCasterTiles.has(f.tileID.key),this._source.loadTile(f,y)}_unloadTile(f){if(f.aborted=!0,this._abortTile(f),this._source.unloadTile)return this._source.unloadTile(f)}_abortTile(f){if(this._source.abortTile)return this._source.abortTile(f)}serialize(){return this._source.serialize()}prepare(f){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const[y,w]of this._tiles)w.upload(f,this.map?this.map.painter:void 0),w.imageAtlas&&!w.imageAtlasTexture&&w.state==="loaded"&&this._reloadTile(y,"reloading"),w.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}getIds(){return Array.from(this._tiles.values(),f=>f.tileID).sort(Yr).map(f=>f.key)}getRenderableIds(f,y){const w=[];for(const k of this._tiles.values())this._isTileRenderable(k,f,y)&&w.push(k);return f?w.sort((k,R)=>{const M=k.tileID,z=R.tileID,V=new l.P(M.canonical.x,M.canonical.y)._rotate(this.transform.angle),H=new l.P(z.canonical.x,z.canonical.y)._rotate(this.transform.angle);return M.overscaledZ-z.overscaledZ||H.y-V.y||H.x-V.x}).map(k=>k.tileID.key):w.map(k=>k.tileID).sort(Yr).map(k=>k.key)}hasRenderableParent(f){const y=this.findLoadedParent(f,0);return!!y&&this._isIdRenderable(y.tileID.key)}_isIdRenderable(f,y,w){const k=this._tiles.get(f);return!!k&&this._isTileRenderable(k,y,w)}_isTileRenderable(f,y,w){const k=f.tileID.key;return f.hasData()&&!this._coveredTiles.has(k)&&(y||!f.holdingForFade())&&(w||!this._shadowCasterTiles.has(k))}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const[f,y]of this._tiles)y.state!=="errored"&&this._reloadTile(f,"reloading")}}_reloadTile(f,y){const w=this._tiles.get(f);w&&(w.state!=="loading"&&(w.state=y),this._loadTile(w,this._tileLoaded.bind(this,w,f,y)))}_tileLoaded(f,y,w,k,R){if(f.aborted)return;if(k){if(f.state="errored",l.bY(k)){if(this._source.fire(new l.i("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:f})),!this._loadedParentTiles.has(f.tileID.key))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const z=this.map.painter.terrain;this.update(this.transform,z.getScaledDemTileSize(),!0),z.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new l.h(k,{tile:f}));return}f.timeAdded=l.e.now(),w==="expired"&&(f.refreshedUponExpiration=!0),this._setTileReloadTimer(y,f),this._source.type==="raster-dem"&&f.dem&&this._backfillDEM(f),this._state.initializeTileState(f,this.map?this.map.painter:null);let M=new Headers;R&&R.headers&&(M=R.headers),this._source.fire(new l.i("data",{dataType:"source",tile:f,coord:f.tileID,sourceCacheId:this.id,responseHeaders:M}))}_hasTunnelGeometry(){for(const f of this._tiles.values())if(f.hasTunnelGeometry)return!0;return!1}_backfillDEM(f){const y=this.getRenderableIds();for(let k=0;k1||(Math.abs(M)>1&&(Math.abs(M+V)===1?M+=V:Math.abs(M-V)===1&&(M-=V)),R.dem&&k.dem&&(k.dem.backfillBorder(R.dem,M,z),k.neighboringTiles&&k.neighboringTiles[H]&&(k.neighboringTiles[H].backfilled=!0)))}}getTile(f){return this.getTileByID(f.key)}getTileByID(f){return this._tiles.get(f)}_retainLoadedChildren(f,y,w,k){const R=this._source.type==="raster-array";for(const[M,z]of this._tiles){let V=z;if(k.has(M)||!V.hasData()||V.tileID.overscaledZ<=y||V.tileID.overscaledZ>w||R&&V.parentTile)continue;let H=V.tileID;for(;V&&V.tileID.overscaledZ>y+1;){const te=V.tileID.scaledTo(V.tileID.overscaledZ-1);V=this._tiles.get(te.key),V&&V.hasData()&&(H=te)}let Y=H;for(;Y.overscaledZ>y;)if(Y=Y.scaledTo(Y.overscaledZ-1),f.has(Y.key)){k.set(H.key,H);const te=this._tiles.get(H.key);te&&(te.dashIdealZ=Y.overscaledZ);break}}}findLoadedParent(f,y){if(this._loadedParentTiles.has(f.key)){const w=this._loadedParentTiles.get(f.key);return w&&w.tileID.overscaledZ>=y?w:null}for(let w=f.overscaledZ-1;w>=y;w--){const k=f.scaledTo(w),R=this._getLoadedTile(k);if(R)return R}}_getLoadedTile(f){const y=this._tiles.get(f.key);return y&&y.hasData()?y:this._cache.getByKey(this._source.reparseOverscaled?f.wrapped().key:f.canonical.key)}updateCacheSize(f,y){y=y||this._source.tileSize;const w=Math.ceil(f.width/y)+1,k=Math.ceil(f.height/y)+1,R=Math.floor(w*k*5),M=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,R):R,z=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,M):M;this._cache.setMaxSize(z)}handleWrapJump(f){const y=Math.round((f-(this._prevLng===void 0?f:this._prevLng))/360);if(this._prevLng=f,y){const w=new Map;for(const k of this._tiles.values())k.tileID=k.tileID.unwrapTo(k.tileID.wrap+y),w.set(k.tileID.key,k);this._tiles=w;for(const k of this._timers.values())clearTimeout(k);this._timers.clear();for(const[k,R]of this._tiles)this._setTileReloadTimer(k,R)}}update(f,y,w,k,R){if(this.transform=f,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!w)return;this.updateCacheSize(f,y),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles=new Set,this._coveredTiles=new Set;const M=this._source.type==="batched-model";let z,V=this._source.maxzoom;this._maxzoomOverride!==null&&(V=Math.min(V,this._maxzoomOverride));const H=this.map&&this.map.painter?this.map.painter._terrain:null;if(H&&H.sourceCache===this&&H.attenuationRange()){const ne=H.attenuationRange()[0],le=Math.floor(ne)-Math.log2(H.getDemUpscale());V>le&&(V=le)}const Y=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain)if(this._source.tileID)z=f.getVisibleUnwrappedCoordinates(this._source.tileID).map(ne=>new l.bZ(ne.canonical.z,ne.wrap,ne.canonical.z,ne.canonical.x,ne.canonical.y));else if(this.tileCoverLift!==0){const ne=f.clone();ne.tileCoverLift=this.tileCoverLift,z=ne.coveringTiles({tileSize:y||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:V,roundZoom:this._source.roundZoom&&!w,reparseOverscaled:Y,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:M}),this._source.minzoom<=1&&f.projection.name==="globe"&&(z.push(new l.bZ(1,0,1,0,0)),z.push(new l.bZ(1,0,1,1,0)),z.push(new l.bZ(1,0,1,0,1)),z.push(new l.bZ(1,0,1,1,1)))}else z=f.coveringTiles({tileSize:y||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:V,roundZoom:this._source.roundZoom&&!w,reparseOverscaled:Y,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:M});else z=[];if(z.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const ne=f.coveringZoomLevel({tileSize:y||this._source.tileSize,roundZoom:this._source.roundZoom&&!w}),le=Math.min(ne,V);if(M){const me=f.extendTileCover(z,le);for(const fe of me)z.push(fe)}else if(R){const me=this.transform.getFrustum(le),fe=f.extendTileCoverToNearPlane(z,me,le);for(const Se of fe)z.push(Se);if(le>=18&&this._hasTunnelGeometry()){const Se=f.extendTileCoverForTunnels(z,me,le,20);for(const Me of Se)z.push(Me)}}else if(this.castsShadows&&k){const me=f.extendTileCover(z,le,k,16);for(const fe of me)this._shadowCasterTiles.add(fe.key),z.push(fe)}}for(const ne of this._tiles.values())ne.dashIdealZ=ne.tileID.overscaledZ;this._source.hasTile&&(z=z.filter(ne=>this._source.hasTile(ne)));const te=this._updateRetainedTiles(z);if(this._supportsFading&&z.length!==0){const ne=new Map,le=new Set,me=l.e.now();for(const[Se,Me]of te){const qe=this._tiles.get(Se);if(!qe||qe.fadeEndTime!==void 0&&qe.fadeEndTime<=me)continue;const Ne=this.findLoadedParent(Me,Math.max(Me.overscaledZ-il.maxOverzooming,this._source.minzoom));Ne&&(this._addTile(Ne.tileID),ne.set(Ne.tileID.key,Ne.tileID)),le.add(Se)}const fe=z.at(-1).overscaledZ;for(const[Se,Me]of this._tiles){if(te.has(Se)||!Me.hasData())continue;let qe=Me.tileID;for(;qe.overscaledZ>fe;){qe=qe.scaledTo(qe.overscaledZ-1);const Ne=this._tiles.get(qe.key);if(Ne&&Ne.hasData()&&le.has(qe.key)){te.set(Se,Me.tileID);break}}}for(const[Se,Me]of ne)te.has(Se)||(this._coveredTiles.add(Se),te.set(Se,Me))}for(const ne of te.keys())this._tiles.get(ne).clearFadeHold();for(const[ne,le]of this._tiles)te.has(ne)||(le.hasSymbolBuckets&&!le.holdingForFade()?le.setHoldDuration(this.map._fadeDuration):le.hasSymbolBuckets&&!le.symbolFadeFinished()||this._removeTile(ne));this._updateLoadedParentTileCache(),this._renderSourceType===l.b_.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const[f,y]of this._tiles)y.holdingForFade()&&this._removeTile(f)}_updateRetainedTiles(f){const y=new Map;if(f.length===0)return y;const w=new Set,k=f.reduce((H,Y)=>Math.min(H,Y.overscaledZ),1/0),R=f[0].overscaledZ,M=Math.max(R-il.maxOverzooming,this._source.minzoom),z=Math.max(R+il.maxUnderzooming,this._source.minzoom),V=new Set;for(const H of f){const Y=this._addTile(H);y.set(H.key,H),Y.hasData()||k=this._source.maxzoom){const ne=H.children(this._source.maxzoom)[0],le=this.getTile(ne);if(le&&le.hasData()){y.set(ne.key,ne),le.dashIdealZ=H.overscaledZ;continue}}else{const ne=H.children(this._source.maxzoom);if(y.has(ne[0].key)&&y.has(ne[1].key)&&y.has(ne[2].key)&&y.has(ne[3].key))continue}let te=Y.wasRequested();for(let ne=H.overscaledZ-1;ne>=M;--ne){const le=H.scaledTo(ne);if(w.has(le.key)||(w.add(le.key),Y=this.getTile(le),!Y&&te&&(Y=this._addTile(le)),Y&&(y.set(le.key,le),Y.dashIdealZ=H.overscaledZ,te=Y.wasRequested(),Y.hasData())))break}}return y}_updateLoadedParentTileCache(){this._loadedParentTiles.clear();for(const f of this._tiles.values()){const y=[];let w,k=f.tileID;for(;k.overscaledZ>0;){if(this._loadedParentTiles.has(k.key)){w=this._loadedParentTiles.get(k.key);break}y.push(k.key);const R=k.scaledTo(k.overscaledZ-1);if(w=this._getLoadedTile(R),w)break;k=R}for(const R of y)this._loadedParentTiles.set(R,w)}}_addTile(f){let y=this._tiles.get(f.key);const w=this._shadowCasterTiles.has(f.key);if(y)return y.isExtraShadowCaster!==!0||w||this._reloadTile(f.key,"reloading"),y;y=this._cache.getAndRemove(f),y&&(this._setTileReloadTimer(f.key,y),y.tileID=f,this._state.initializeTileState(y,this.map?this.map.painter:null),y.resetPlacementVisibility());const k=!!y;if(!k){const R=this.map?this.map.painter:null,M=this._source.tileSize*f.overscaleFactor();y=this._source.type==="raster-array"?function(z,V,H,Y,te){if(!bx)throw new Error("Raster-array module is not loaded.");return bx(z,V,H,Y,te)}(f,M,this.transform.tileZoom,R,this._isRaster):new yf(f,M,this.transform.tileZoom,R,this._isRaster,this._source.worldview),this._loadTile(y,this._tileLoaded.bind(this,y,f.key,y.state))}return y.uses++,this._tiles.set(f.key,y),k||this._source.fire(new l.i("dataloading",{tile:y,coord:y.tileID,dataType:"source"})),y}_setTileReloadTimer(f,y){clearTimeout(this._timers.get(f)),this._timers.delete(f);const w=y.getExpiryTimeout();w&&this._timers.set(f,setTimeout(()=>{this._reloadTile(f,"expired"),this._timers.delete(f)},w))}_removeTile(f){const y=this._tiles.get(f);y&&(y.uses--,this._tiles.delete(f),clearTimeout(this._timers.get(f)),this._timers.delete(f),y.uses>0||(y.hasData()&&y.state!=="reloading"||y.state==="empty"?this._cache.add(y.tileID,y,y.getExpiryTimeout()):this._unloadTile(y)))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const f of this._tiles.keys())this._removeTile(f);this._source._clear&&this._source._clear(),this._cache.reset(),this.map&&this.usedForTerrain&&this.map.painter.terrain&&this.map.painter.terrain.resetTileLookupCache(this.id)}tilesIn(f,y,w){const k=[],R=this.transform;if(!R)return k;const M=R.projection.name==="globe",z=l.ad(R.center.lng),V=R.getFreeCameraOptions().position||new l.b$(0,0,0);for(const H of this._tiles.values()){if(w&&H.clearQueryDebugViz(),H.holdingForFade())continue;let Y;if(M){const te=H.tileID.canonical;if(te.z===0){const ne=[Math.abs(l.bb(z,...Ei(te,-1))-z),Math.abs(l.bb(z,...Ei(te,1))-z)];Y=[0,2*ne.indexOf(Math.min(...ne))-1]}else{const ne=[Math.abs(l.bb(z,...Ei(te,-1))-z),Math.abs(l.bb(z,...Ei(te,0))-z),Math.abs(l.bb(z,...Ei(te,1))-z)];Y=[ne.indexOf(Math.min(...ne))-1]}}else Y=[0];for(const te of Y){const ne=f.containsTile(H,R,y,te,V);ne&&k.push(ne)}}return k}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(f){return this._getRenderableCoordinates(f)}_getRenderableCoordinates(f,y){if(!this.transform)return[];const w=this.getRenderableIds(f,y).map(R=>this._tiles.get(R).tileID),k=this.transform.projection.name==="globe";for(const R of w)R.projMatrix=this.transform.calculateProjMatrix(R.toUnwrapped()),R.expandedProjMatrix=k?this.transform.calculateProjMatrix(R.toUnwrapped(),!1,!0):R.projMatrix;return w}sortCoordinatesByDistance(f){if(!this.transform)return f.slice();const y=f.slice(),w=this.transform._camera.position,k=this.transform._camera.forward(),R=new Map;for(const M of y){const z=1/(1<R.get(M.key)-R.get(z.key)),y}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const f=l.e.now();for(const y of this._tiles.values())if(y.fadeEndTime!==void 0&&y.fadeEndTime>=f)return!0}return!1}setFeatureState(f,y,w){this._state.updateState(f=f||"_geojsonTileLayer",y,w)}removeFeatureState(f,y,w){this._state.removeFeatureState(f=f||"_geojsonTileLayer",y,w)}getFeatureState(f,y){return this._state.getState(f=f||"_geojsonTileLayer",y)}setDependencies(f,y,w){const k=this._tiles.get(f);k&&k.setDependencies(y,w)}reloadTilesForDependencies(f,y){for(const[w,k]of this._tiles)k.hasDependency(f,y)&&this._reloadTile(w,"reloading");this._cache.filter(w=>!w.hasDependency(f,y))}_preloadTiles(f,y){if(!this._sourceLoaded){const V=()=>{this._sourceLoaded&&(this._source.off("data",V),this._preloadTiles(f,y))};return void this._source.on("data",V)}const w=new Map,k=Array.isArray(f)?f:[f],R=this.map.painter.terrain,M=this.usedForTerrain&&R?R.getScaledDemTileSize():this._source.tileSize;for(const V of k){const H=V.coveringTiles({tileSize:M,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const Y of H)w.set(Y.key,Y);this.usedForTerrain&&V.updateElevation(!1)}const z=Array.from(w.values());l.u(z,(V,H)=>{const Y=new yf(V,this._source.tileSize*V.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(Y,te=>{this._source.type==="raster-dem"&&Y.dem&&this._backfillDEM(Y),H(te,Y)})},y)}}function Yr(_,f){const y=Math.abs(2*_.wrap)-+(_.wrap<0),w=Math.abs(2*f.wrap)-+(f.wrap<0);return _.overscaledZ-f.overscaledZ||w-y||f.canonical.y-_.canonical.y||f.canonical.x-_.canonical.x}function Ei(_,f){const y=1<<_.z;return[_.x/y+f,(_.x+1)/y+f]}function Bi(_,f){if(_.z<=f.z){const w=f.z-_.z;return f.x>>w===_.x&&f.y>>w===_.y}const y=_.z-f.z;return _.x>>y===f.x&&_.y>>y===f.y}function _c(_,f){return _.sourceFQID!==f.sourceFQID?_.sourceFQID{return!!z.hasDeferredElevationFeatures||M&&(V=k,mp(w,H=z.tileID.canonical)!==mp(V,H));var V,H})}const Io=_=>({u_matrix:_});function Ol(_,f){const y=_.context.gl,w=_._tileClippingMaskIDs.get(f.key)||0;return new l.a4({func:y.EQUAL,mask:255},w,0,y.KEEP,y.KEEP,y.KEEP)}function Lg(_,f){const y=_.context.gl,w=_._tileClippingMaskIDs.get(f.key)||0;return new l.a4({func:y.EQUAL,mask:255},255&~w,0,y.KEEP,y.KEEP,y.KEEP)}function vf(_,f){if(!_.frcCoverageSnapshot||!_.frcCoverageRenderer)return null;const y=_.frcCoverageSnapshot.getTileOrParent(f.canonical);if(!y||y.frcMask===0)return null;const w=_.frcCoverageRenderer.getBuffers(y.tileId);if(!w)return null;const k=new l.c1(y.tileId.z,y.tileId.x,y.tileId.y),R=new l.c2(f.wrap,k);return{buffers:w,projMatrix:_.transform.calculateProjMatrix(R),coverageTile:y}}function zo(_,f,y){if(!_.frcCoverageSnapshot)return;const w=_.context,k=w.gl,R=_.getOrCreateProgram("clippingMask");w.setColorMode(l.a7.disabled),w.setDepthMode(l.a3.disabled);for(const M of f){const z=vf(_,M);if(!z)continue;const V=z.buffers.frcLevelSegments[y];if(!V)continue;const H=_._tileClippingMaskIDs.get(M.key)||0;R.draw(_,k.TRIANGLES,l.a3.disabled,new l.a4({func:k.EQUAL,mask:255},H,255,k.KEEP,k.KEEP,k.INVERT),l.a7.disabled,l.a5.disabled,Io(z.projMatrix),`$frc_coverage_${y}`,z.buffers.vertexBuffer,z.buffers.indexBuffer,V)}}function qu(_,f,y){if(!_.frcCoverageSnapshot)return;const w=_.context,k=w.gl,R=_.getOrCreateProgram("clippingMask");w.setColorMode(l.a7.disabled),w.setDepthMode(l.a3.disabled);for(const M of f){const z=vf(_,M);if(!z)continue;const V=z.buffers.frcLevelSegments[y];if(!V)continue;const H=_._tileClippingMaskIDs.get(M.key)||0;R.draw(_,k.TRIANGLES,l.a3.disabled,new l.a4({func:k.EQUAL,mask:255},255&~H,255,k.KEEP,k.KEEP,k.INVERT),l.a7.disabled,l.a5.disabled,Io(z.projMatrix),`$frc_coverage_restore_${y}`,z.buffers.vertexBuffer,z.buffers.indexBuffer,V)}}function qc(_,f,y,w,k){if(f.length===0)return;let R=0;for(const z of f)R|=z.frcMask;const M=f.map(z=>z.coord);for(let z=0;z<9;++z)if(R&1<0&&k)for(const V of f)V.frcMask&1<0&&f.rings[0].length>0)return!0;return!1}function xp(_){const f=_.frcCoverageFadeRange;return!f||f[1]<=f[0]?0:1-Math.max(0,Math.min(1,(_.transform.zoom-f[0])/(f[1]-f[0])))}const fd={loaded:!0,drawBuilding:function(_,f,y,w){_.currentLayer<_.firstLightBeamLayer&&(_.firstLightBeamLayer=_.currentLayer);const k=y.paint.get("building-ambient-occlusion-ground-intensity"),R=y.paint.get("building-ambient-occlusion-ground-radius"),M=y.paint.get("building-ambient-occlusion-ground-attenuation"),z=y.paint.get("building-opacity");if(z<=0)return;let V=k>0&&R>0,H=!0;const Y=y.paint.get("building-vertical-scale");if(Y<=0)return;_.shadowRenderer||(H=!1);const te=_.conflationActive&&_.style.isLayerClipped(y,f.getSource()),ne=_.style.order.indexOf(y.fqid);if(function(le,me,fe,Se,Me,qe){for(const Ne of qe){const We=me.getTile(Ne).getBucket(fe);We&&(Me&&We.updateReplacement(Ne,le.replacementSource,Se),We.uploadUpdatedIndexBuffer(le.context))}}(_,f,y,ne,te,w),function(le,me,fe,Se){for(const Me of Se){const qe=me.getTile(Me).getBucket(fe);qe&&qe.needsEvaluation()&&qe.uploadUpdatedColorBuffer(le.context)}}(_,f,y,w),y.resetLayerRenderingStats(_),_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!0),_.renderPass==="shadow"&&_.shadowRenderer){const le=[],me=_.shadowRenderer.getShadowPassDepthMode();Si({painter:_,source:f,layer:y,coords:w,defines:le,blendMode:l.a7.disabled,depthMode:me,opacity:z,verticalScale:Y,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(_.renderPass==="translucent"){let le=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];H&&(le=le.concat("RENDER_SHADOWS")),_.shadowRenderer&&_.shadowRenderer.useNormalOffset&&(le=le.concat("NORMAL_OFFSET"));const me=y.paint.get("building-facade-emissive-chance"),fe=y.paint.get("building-ambient-occlusion-intensity"),Se=y.paint.get("building-flood-light-intensity"),Me=y.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",qe=y.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(Me?null:y.lut).toArray01().slice(0,3),Ne=y.paint.get("building-flood-light-ground-attenuation"),We=Se>0,ct=new l.a3(_.context.gl.LEQUAL,l.a3.ReadWrite,_.depthRangeFor3D),it=y.hasBlended3DDepthPrepass(),pt=()=>Si({painter:_,source:f,layer:y,coords:w,defines:le,blendMode:l.a7.disabled,depthMode:ct,opacity:z,verticalScale:Y,facadeEmissiveChance:me,facadeAOIntensity:fe,floodLightIntensity:Se,floodLightColor:qe,depthOnly:!0});if(_.depthPrepassPhase)return void(it&&pt());it&&!_.hasGrouped3DDepthPrepass(_.currentLayer)&&pt();const dt=_.colorModeForRenderPass();Si({painter:_,source:f,layer:y,coords:w,defines:le,blendMode:dt,depthMode:ct,opacity:z,verticalScale:Y,facadeEmissiveChance:me,facadeAOIntensity:fe,floodLightIntensity:Se,floodLightColor:qe,stencilMode:it?_.stencilModeFor3DGroup(_.currentLayer):void 0});const mt=y.paint.get("building-front-cutoff");Un(_.transform.pitch,mt,!!_.terrain),V&&Ta(_,f,y,w,!0,z,k,R,Se,qe,M,te),We&&Ta(_,f,y,w,!1,z,k,R,Se,qe,Ne,te)}else if(_.renderPass==="light-beam"){const le=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],me=new l.a3(_.context.gl.LEQUAL,l.a3.ReadOnly,_.depthRangeFor3D);Si({painter:_,source:f,layer:y,coords:w,defines:le,blendMode:l.a7.alphaBlended,depthMode:me,opacity:z,verticalScale:Y,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}_.shadowRenderer&&(_.shadowRenderer.useNormalOffset=!1),_.resetStencilClippingMasks()},BuildingTileBorderManager:class{constructor(){this.visibleTiles=[]}updateBorders(_,f){const y=[],w=[],k=_._getRenderableCoordinates(!1,!0);for(const z of k){const V=_.getTile(z);if(!V.hasData())continue;const H=V.getBucket(f);H&&(H.isEmpty()||(y.push(z.key),w.push({bucket:H,tileID:z.canonical})))}let R=y.length!==this.visibleTiles.length;if(!R){y.sort();for(let z=0;zz.tileID.z-V.tileID.z||z.tileID.x-V.tileID.x||z.tileID.y-V.tileID.y);for(const z of w){const V=new Array,H=new Array,Y=z.bucket;for(const te of Y.featuresOnBorder)Y.footprints[te.footprintIndex].hiddenFlags&l.b0||(M.has(te.featureId)?H.push(te.footprintIndex):(M.add(te.featureId),V.push(te.footprintIndex)));Y.updateFootprintHiddenFlags(V,l.b1,!1),Y.updateFootprintHiddenFlags(H,l.b1,!0)}}},drawRasterParticle:function(_,f,y,w,k,R){_.renderPass==="offscreen"&&function(M,z,V,H){if(!H.length)return;const Y=M.context,te=Y.gl,ne=z.getSource();if(ne.type!=="raster-array")return;const le=Math.ceil(Math.sqrt(V.paint.get("raster-particle-count")));let me=V.particlePositionRGBAImage;if(!me||me.width!==le){const Ne=function(We){const ct=We*We,it=new Uint8Array(4*ct),pt=.9090909090909091;for(let dt=0;dtl.aM[Ut](Lt));Cr.push(Lt);const qr=Lt.canonical.x,qt=Lt.canonical.y;for(const Ut of Cr){const gr=We.getTile(xt?Ut.wrapped():Ut);if(!gr)continue;const Pr=gr.rasterParticleState;if(!Pr)continue;const ur=Ut.canonical.x+(1<f.getTileByID(z));for(const z of M)z.updateNeeded(_.id,R)&&(z._isHeaderLoaded||z.parentTile)&&w.prepareTile(z,k,_.id,R)},Rain:class extends Zs{constructor(){super(4.25),this._params={intensity:.5,timeFactor:1,velocityConeAperture:0,velocity:300,boxSize:2500,dropletSizeX:1,dropletSizeYScale:10,distortionStrength:70,screenThinning:{intensity:.57,start:.46,range:1.17,fadePower:.17,affectedRatio:1,particleOffset:-.2},color:{r:.66,g:.68,b:.74,a:.7},direction:{x:-50,y:-35},shapeDirPower:2,shapeNormalPower:1},this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3,this._devtoolsFolder=null,this._painter=null}destroy(){super.destroy()}update(_){const f=_.context;if(!this.particlesVx){const y=xc(this.particlesCount),w=new l.bv,k=new l.ak;let R=0;const M=l.bt(1323123451230);for(let z=0;zM)return;const z=ta(0,1,w.revealStart,w.revealStart+w.revealRange,M);if(!this.particlesVx||!this.particlesIdx)return;R.strength*=z;const V=this.updateOnRender(_,y.timeFactor),H=_.context,Y=H.gl,te=_.transform;this.screenTexture&&this.screenTexture.size[0]===_.width&&this.screenTexture.size[1]===_.height||(this.screenTexture=new l.T(H,{width:_.width,height:_.height,data:null},Y.RGBA8)),y.distortionStrength>0&&(H.activeTexture.set(Y.TEXTURE0),this.screenTexture.bind(Y.LINEAR,Y.CLAMP_TO_EDGE),Y.copyTexSubImage2D(Y.TEXTURE_2D,0,0,0,0,0,_.width,_.height));const ne=_.getOrCreateProgram("rainParticle");_.uploadCommonUniforms(H,ne),H.activeTexture.set(Y.TEXTURE0),this.screenTexture.bind(Y.LINEAR,Y.CLAMP_TO_EDGE);const le=[y.color.r,y.color.g,y.color.b,y.color.a],me=(fe,Se)=>{const Me=Wd(this._movement.getPosition(),fe),qe=y.dropletSizeX,Ne=y.dropletSizeX*y.dropletSizeYScale,We=_.width/2,ct=_.height/2,it=ta(0,y.screenThinning.start,0,1,y.screenThinning.intensity),pt=ta(.001,y.screenThinning.range,0,1,y.screenThinning.intensity),dt=ta(0,y.screenThinning.particleOffset,0,1,y.screenThinning.intensity),mt=(xt={modelview:V.modelviewMatrix,projection:V.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:Me,velocityConeAperture:y.velocityConeAperture,velocity:y.velocity,boxSize:fe,rainDropletSize:[qe,Ne],distortionStrength:y.distortionStrength,rainDirection:k,color:le,screenSize:[te.width,te.height],thinningCenterPos:[We,ct],thinningShape:[it,pt,Math.pow(10,y.screenThinning.fadePower)],thinningAffectedRatio:y.screenThinning.affectedRatio,thinningParticleOffset:dt,shapeDirectionalPower:y.shapeDirPower,shapeNormalPower:y.shapeNormalPower,mode:Se?0:1},{u_modelview:Float32Array.from(xt.modelview),u_projection:Float32Array.from(xt.projection),u_time:xt.time,u_cam_pos:xt.camPos,u_texScreen:0,u_velocityConeAperture:xt.velocityConeAperture,u_velocity:xt.velocity,u_boxSize:xt.boxSize,u_rainDropletSize:xt.rainDropletSize,u_distortionStrength:xt.distortionStrength,u_rainDirection:xt.rainDirection,u_color:xt.color,u_screenSize:xt.screenSize,u_thinningCenterPos:xt.thinningCenterPos,u_thinningShape:xt.thinningShape,u_thinningAffectedRatio:xt.thinningAffectedRatio,u_thinningParticleOffset:xt.thinningParticleOffset,u_shapeDirectionalPower:xt.shapeDirectionalPower,u_shapeNormalPower:xt.shapeNormalPower,u_mode:xt.mode});var xt;const bt=Math.round(y.intensity*this.particlesCount),Ft=l.aj.simpleSegment(0,0,4*bt,2*bt);ne.draw(_,Y.TRIANGLES,l.a3.disabled,l.a4.disabled,l.a7.alphaBlended,l.a5.disabled,mt,"rain_particles",this.particlesVx,this.particlesIdx,Ft)};y.distortionStrength>0&&me(y.boxSize,!0),me(y.boxSize,!1),this._vignette.draw(_,R)}},Snow:class extends Zs{constructor(){super(2.25),this._params={intensity:.85,timeFactor:.75,velocityConeAperture:70,velocity:40,horizontalOscillationRadius:4,horizontalOscillationRate:1.5,boxSize:2e3,billboardSize:2,shapeFadeStart:.27,shapeFadePower:.21,screenThinning:{intensity:.4,start:.15,range:1.4,fadePower:.24,affectedRatio:1,particleOffset:-.2},color:{r:1,g:1,b:1,a:1},direction:{x:-50,y:-35}},this._vignetteParams={strength:.3,start:.78,range:.46,fadePower:.2,color:{r:1,g:1,b:1,a:1}},this.particlesCount=16e3,this._devtoolsFolder=null,this._painter=null}destroy(){super.destroy()}update(_){const f=_.context;if(!this.particlesVx){const y=xc(this.particlesCount),w=new l.bw,k=new l.ak;let R=0;const M=l.bt(1323123451230);for(let z=0;zM)return;const z=ta(0,1,w.revealStart,w.revealStart+w.revealRange,M);R.strength*=z;const V=this.updateOnRender(_,y.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const H=_.context,Y=H.gl,te=_.transform,ne=_.getOrCreateProgram("snowParticle");_.uploadCommonUniforms(H,ne),((le,me,fe)=>{const Se=Wd(this._movement.getPosition(),le),Me=te.width/2,qe=te.height/2,Ne=ta(0,fe.screenThinning.start,0,1,fe.screenThinning.intensity),We=ta(.001,fe.screenThinning.range,0,1,fe.screenThinning.intensity),ct=ta(0,fe.screenThinning.particleOffset,0,1,fe.screenThinning.intensity),it=(pt={modelview:V.modelviewMatrix,projection:V.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:Se,velocityConeAperture:fe.velocityConeAperture,velocity:fe.velocity,horizontalOscillationRadius:fe.horizontalOscillationRadius,horizontalOscillationRate:fe.horizontalOscillationRate,boxSize:le,billboardSize:1*fe.billboardSize,simpleShapeParameters:[fe.shapeFadeStart,fe.shapeFadePower],screenSize:[te.width,te.height],thinningCenterPos:[Me,qe],thinningShape:[Ne,We,Math.pow(10,fe.screenThinning.fadePower)],thinningAffectedRatio:fe.screenThinning.affectedRatio,thinningParticleOffset:ct,color:[fe.color.r,fe.color.g,fe.color.b,fe.color.a],direction:k},{u_modelview:Float32Array.from(pt.modelview),u_projection:Float32Array.from(pt.projection),u_time:pt.time,u_cam_pos:pt.camPos,u_velocityConeAperture:pt.velocityConeAperture,u_velocity:pt.velocity,u_horizontalOscillationRadius:pt.horizontalOscillationRadius,u_horizontalOscillationRate:pt.horizontalOscillationRate,u_boxSize:pt.boxSize,u_billboardSize:pt.billboardSize,u_simpleShapeParameters:pt.simpleShapeParameters,u_screenSize:pt.screenSize,u_thinningCenterPos:pt.thinningCenterPos,u_thinningShape:pt.thinningShape,u_thinningAffectedRatio:pt.thinningAffectedRatio,u_thinningParticleOffset:pt.thinningParticleOffset,u_particleColor:pt.color,u_direction:pt.direction});var pt;const dt=Math.round(fe.intensity*this.particlesCount),mt=l.aj.simpleSegment(0,0,4*dt,2*dt);this.particlesVx&&this.particlesIdx&&ne.draw(_,Y.TRIANGLES,l.a3.disabled,l.a4.disabled,l.a7.alphaBlended,l.a5.disabled,it,"snow_particles",this.particlesVx,this.particlesIdx,mt)})(y.boxSize,0,y),this._vignette.draw(_,R)}},shaders:qi,programUniforms:Vu,drawElevatedStructures:function(_){const{painter:f,sourceCache:y,layer:w,coords:k,colorMode:R}=_,M=f.context.gl,z=_.painter.shadowRenderer,V=!!z&&z.enabled,H=new l.a3(f.context.gl.LEQUAL,l.a3.ReadOnly,f.depthRangeFor3D);let Y=[0,0,0];if(V){const ne=f.style.directionalLight,le=f.style.ambientLight;ne&&le&&(Y=l.aQ(f.style,ne,le))}const te=ne=>{for(const le of k){const me=y.getTile(le),fe=me.getBucket(w);if(!fe)continue;const Se=fe.hdExt?fe.hdExt.elevatedStructures:void 0;if(!Se)continue;let Me,qe;if(ne?(Me=Se.renderableBridgeSegments,qe=Se.bridgeProgramConfigurations.get(w.id)):(Me=Se.renderableTunnelSegments,qe=Se.tunnelProgramConfigurations.get(w.id)),!Me||Me.segments[0].primitiveLength===0)continue;qe.updatePaintBuffers(),f.prepareDrawTile();const Ne=f.isTileAffectedByFog(le),We=[];V&&We.push("RENDER_SHADOWS","NORMAL_OFFSET");const ct=f.getOrCreateProgram("elevatedStructures",{config:qe,overrideFog:Ne,defines:We}),it=f.translatePosMatrix(le.projMatrix,me,w.paint.get("fill-translate"),w.paint.get("fill-translate-anchor"));V&&z.setupShadows(me.tileID.toUnwrapped(),ct,"vector-tile");const pt=fu(it,Y);f.uploadCommonUniforms(f.context,ct,le.toUnwrapped()),ct.draw(f,M.TRIANGLES,H,l.a4.disabled,R,l.a5.backCCW,pt,w.id,Se.vertexBuffer,Se.indexBuffer,Me,w.paint,f.transform.zoom,qe,[Se.vertexBufferNormal])}};te(!0),te(!1)},drawElevatedFillShadows:function(_){const{painter:f,sourceCache:y,layer:w,coords:k}=_,R=f.context.gl,M=_.painter.shadowRenderer;for(const z of k){const V=y.getTile(z),H=V.getBucket(w);if(!H)continue;const Y=H.hdExt?H.hdExt.elevatedStructures:void 0;if(!Y||!Y.shadowCasterSegments||Y.shadowCasterSegments.segments[0].primitiveLength===0)continue;f.prepareDrawTile();const te=H.bufferData.programConfigurations.get(w.id),ne=f.isTileAffectedByFog(z),le=f.getOrCreateProgram("elevatedStructuresDepth",{config:te,overrideFog:ne}),me=M.calculateShadowPassMatrixFromTile(V.tileID.toUnwrapped());f.uploadCommonUniforms(f.context,le,z.toUnwrapped());const fe=Vc(me,0);le.draw(f,R.TRIANGLES,M.getShadowPassDepthMode(),l.a4.disabled,l.a7.disabled,l.a5.disabled,fe,w.id,Y.vertexBuffer,Y.indexBuffer,Y.shadowCasterSegments,w.paint,f.transform.zoom,te)}},drawDepthPrepass:function(_,f,y,w,k){if(!f||!y.layout||y.layout.get("fill-elevation-reference")==="none"||y.paint.get("fill-opacity").constantOr(1)===0)return;const R=_.context.gl,M=new l.a3(_.context.gl.LEQUAL,l.a3.ReadWrite,_.depthRangeFor3D),z=new l.a3(_.context.gl.GREATER,l.a3.ReadWrite,_.depthRangeFor3D),V=function(ne){let le=.01;return ne.isOrthographic&&(le=l.aw(1e-4,le,l.bz(ne.pitch>=l.by?1:ne.pitch/l.by))),2*le}(_.transform),H=_.transform.getFreeCameraOptions().position,Y="elevatedStructuresDepthReconstruct";let te;for(const ne of w){const le=f.getTile(ne),me=le.getBucket(y);if(!me||!me.hdExt)continue;const fe=me.hdExt.elevatedStructures,Se=me.hdExt.elevationBufferData;if(!fe||!fe.depthSegments||!Se)continue;const Me=Se.heightRange,qe=wl(ne.toUnwrapped(),H),Ne=_.translatePosMatrix(ne.projMatrix,le,y.paint.get("fill-translate"),y.paint.get("fill-translate-anchor"));let We,ct,it;if(k==="initialize"){if(!Me||Me.min>=1||fe.depthSegments.segments[0].primitiveLength===0)continue;We=Ml(Ne,qe,V,1,0),ct=M,it=fe.depthSegments,te=te||_.getOrCreateProgram(Y,{defines:["DEPTH_RECONSTRUCTION"]})}else if(k==="reset"){if(!Me||Me.min>=0||fe.maskSegments.segments[0].primitiveLength===0)continue;We=Ml(Ne,qe,0,0,1),ct=z,it=fe.maskSegments,te=te||_.getOrCreateProgram(Y,{defines:["DEPTH_RECONSTRUCTION"]})}else if(k==="geometry"){if(fe.depthSegments.segments[0].primitiveLength===0)continue;We=Ml(Ne,qe,V,1,0),ct=M,it=fe.depthSegments,te=te||_.getOrCreateProgram(Y)}te.draw(_,R.TRIANGLES,ct,l.a4.disabled,l.a7.disabled,l.a5.disabled,We,y.id,fe.vertexBuffer,fe.indexBuffer,it,y.paint,_.transform.zoom)}},drawGroundShadowMask:function(_,f,y,w){if(!f||!y.layout||y.layout.get("fill-elevation-reference")==="none"||y.paint.get("fill-opacity").constantOr(1)===0)return;const k=_.context.gl,R=new l.a3(k.LEQUAL,l.a3.ReadOnly,_.depthRangeFor3D),M=new l.a4({func:k.ALWAYS,mask:255},255,255,k.KEEP,k.KEEP,k.REPLACE),z=_.transform.getFreeCameraOptions().position;let V;for(const H of w){const Y=f.getTile(H),te=Y.getBucket(y);if(!te)continue;const ne=te.hdExt?te.hdExt.elevatedStructures:void 0;if(!ne||!ne.depthSegments||ne.depthSegments.segments[0].primitiveLength===0)continue;const le=wl(H.toUnwrapped(),z),me=_.translatePosMatrix(H.projMatrix,Y,y.paint.get("fill-translate"),y.paint.get("fill-translate-anchor"));V=V||_.getOrCreateProgram("elevatedStructuresDepthReconstruct");const fe=Ml(me,le,0,1,0);V.draw(_,k.TRIANGLES,R,M,l.a7.disabled,l.a5.disabled,fe,y.id,ne.vertexBuffer,ne.indexBuffer,ne.depthSegments,y.paint,_.transform.zoom)}},IndoorManager:class extends l.E{constructor(_,f=!1){super(),this._style=_,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new tl,this._initialLoadDone=!1,l.b4(["_updateUI"],this);const y=()=>{this._style.isIndoorEnabled()&&(this._style.map.on("load",()=>{this._initialLoadDone=!0,this._indoorState&&this._indoorState.needsUpdate&&(this._indoorState.needsUpdate=!1,this._style.updateIndoorDependentLayers()),this._updateUI()}),this._style.map.on("move",this._updateUI),this._style.map.on("idle",this._updateUI))};f?(this._initialLoadDone=!0,y()):this._style.on("style.load",y)}destroy(){this._buildings={},this._activeFloors=new Set,this._indoorState=null}selectFloor(_){_===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=_,this._recalculateActiveFloors())}setActiveFloorsVisibility(_){this._updateActiveFloors(_),this._updateIndoorSelector()}setIndoorData(_){let f=!1;for(const[y,w]of Object.entries(_.buildings))if(this._buildings[y])for(const k of w.floorIds)this._buildings[y].floorIds.add(k),this._buildings[y].floors[k]?this._mergeFloors(this._buildings[y].floors[k],w.floors[k]):(this._buildings[y].floors[k]=w.floors[k],f=!0);else this._buildings[y]=w,f=!0;f&&this._recalculateActiveFloors()}getIndoorTileOptions(_,f){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(_,f),indoorState:this._indoorState}:null}getControlState(){const _=this._buildings,f=this._closestBuildingId,y=f&&_?_[f]:void 0;if(!y)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let w=null;for(const R of y.floorIds)if(this._activeFloors&&this._activeFloors.has(R)){w=R;break}const k=Array.from(y.floorIds).map(R=>({id:R,name:y.floors[R].name,zIndex:y.floors[R].zIndex})).sort((R,M)=>M.zIndex-R.zIndex).filter((R,M,z)=>M===0||R.zIndex!==z[M-1].zIndex);return{selectedFloorId:w,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:k}}_updateUI(){this._initialLoadDone=!0;const _=this._style.map.transform,f=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,_.center,_.zoom,_.getBounds(),this._makeViewportPolygon());if(f!==this._closestBuildingId){const y=this._closestBuildingId;this._closestBuildingId=f,this._onBuildingTransition(y,f),this._updateIndoorSelector()}}_onBuildingTransition(_,f){if(!this._indoorState)return;!f&&_?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!f&&!_&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new l.i("selector-update",this.getControlState()))}_updateActiveFloors(_){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:_,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const _=l.b5.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(f,y){if(f===y)return!0;if(!f||!y||f.size!==y.size)return!1;for(const w of f)if(!y.has(w))return!1;return!0})(_,this._activeFloors)||(this._activeFloors=_,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(_,f){f.geometry&&(_.geometry?(_.geometry.type==="Polygon"&&(_.geometry={type:"MultiPolygon",coordinates:[_.geometry.coordinates]}),f.geometry.type==="Polygon"?_.geometry.coordinates.push(f.geometry.coordinates):f.geometry.type==="MultiPolygon"&&_.geometry.coordinates.push(...f.geometry.coordinates)):_.geometry=f.geometry)}_makeViewportPolygon(){const _=this._style.map.transform,f=_.width,y=_.height;return[_.pointLocation(new l.P(0,0)),_.pointLocation(new l.P(f,0)),_.pointLocation(new l.P(f,y)),_.pointLocation(new l.P(0,y))].map(w=>new l.P(w.lng,w.lat))}},HdCoverageState:class{constructor(){this.coverageSourceCaches={},this.manager=new Yl}},updateFrcCoverage:function(_,f){f.manager.clear();for(const w in _._mergedHdRoadCoverageSourceCaches){const k=_._mergedHdRoadCoverageSourceCaches[w]._tiles;for(const R of k.values()){if(!R.loaded())continue;const M=R.frcCoveragePolygons;f.manager.addTileCoverage(R.tileID.canonical,M&&M.length>0?M:[])}}const y=f.manager.updateSnapshotIfNeeded();if(_.map.painter&&(_.map.painter.frcCoverageSnapshot=y.empty()?null:y),!y.empty()){const w=[_._mergedOtherSourceCaches,_._mergedSymbolSourceCaches];for(const k of w)for(const R in k){const M=k[R];for(const[z,V]of M._tiles)V.hasDeferredRoadStructure&&(V.hasDeferredRoadStructure=!1,M._reloadTile(z,"reloading"))}}},updateHdCoverageSourceCache:function(_,f,y){if(y.type!=="fill"||y.sourceLayer!==l.c0||f.coverageSourceCaches[y.source])return;const w=_.getOwnSource(y.source);if(!w||w.type!=="vector")return;const k=`hd-road-coverage:${y.source}`,R=l.m(k,_.scope),M=_._sourceCaches[k]=new il(R,w,l.b_.HdRoadCoverage);f.coverageSourceCaches[y.source]=M,M.setMaxzoomOverride(14),M.onAdd(_.map);const z=_._otherSourceCaches[y.source];z&&z._sourceLoaded&&(M._sourceLoaded=!0)},updateFrcCoverageFadeRange:function(_,f){let y=null,w=null;const k={globals:{zoom:0}};_.forEachFragmentStyle(R=>{if(y)return;const M=R.stylesheet?R.stylesheet.schema:null;if(!M||!M.sdCoverageFadeRange)return;const z=l.m("sdCoverageFadeRange",R.scope),V=R.options?R.options.get(z):void 0,H=V?V.value||V.default:null;if(H){const le=H.evaluate(k);Array.isArray(le)&&le.length===2&&(le[0]>0||le[1]>0)&&(y=[le[0],le[1]])}const Y=l.m("sdCoverageSourceLayers",R.scope),te=R.options?R.options.get(Y):void 0,ne=te?te.value||te.default:null;if(ne){const le=ne.evaluate(k);Array.isArray(le)&&le.length>0&&(w=le)}else{const le=_.stylesheet&&_.stylesheet.imports||[];for(const me of le)if(me.id===R.scope){const fe=me.config?me.config.sdCoverageSourceLayers:void 0;Array.isArray(fe)&&fe.length>0&&(w=fe);break}}}),f.frcCoverageFadeRange=y,f.frcCoverageSourceLayers=y!=null?w||["road","structure"]:[]},HdElevationState:gp,setupAndUpdateElevationCoverage:function(_){if(!function(k){for(const R in k._mergedLayers)if(Bo(k._mergedLayers[R]))return!0;return!1}(_))return void yp(_);const f=_e(_,_.map&&_.map.transform);_._hdElevation||(_._hdElevation=new gp);const y=_._hdElevation._terrainActiveLast;if(_._hdElevation._terrainActiveLast=f,y!==void 0&&y!==f&&_f(_,void 0,!0),f)return void(_.map.painter&&(_.map.painter.elevationCoverageSnapshot=null));if(!Ng(_))return void yp(_);y===void 0&&_f(_,void 0,!0);const w=_._hdElevation;w._needsCrossSourceElevation=!0,_._crossSourceElevationActive=!0,w._ingestFQIDs=Kd(_),sl(_,w)},updateElevationCoverage:sl,updateCrossSourceElevationGate:function(_){_._crossSourceElevationActive=Ng(_)},buildElevationRequestParams:function(_,f,y){if(_e(_.style,_.transform)||!y)return null;const w=_.painter?_.painter.elevationCoverageSnapshot:null,k=!(!_.painter||!_.painter.elevationProvidersReady);return w?function(R,M,z){const V=R.getTilesIntersecting(M);if(V.length===0)return{registry:[],hasCoveringTile:!1,allProvidersReady:z};const H=[];for(const Y of V)for(const te of Y.features)H.push({tileId:Y.tileId,feature:te});return H.sort((Y,te)=>Y.feature.id-te.feature.id),{registry:H,hasCoveringTile:!0,allProvidersReady:z}}(w,f.tileID.canonical,k):{registry:[],hasCoveringTile:!1,allProvidersReady:k}},FrcCoverageRenderer:class{constructor(){this.tileBuffers=new Map,this._context=null}update(_,f){this._context=_;const y=new Set;for(const w of f){if(w.frcMask===0)continue;let k=!1;for(const M of w.polygons)if(M.hasGeometry()){k=!0;break}if(!k)continue;const R=`${w.tileId.z}/${w.tileId.x}/${w.tileId.y}`;if(y.add(R),!this.tileBuffers.has(R)){const M=this._createBuffers(_,w);M&&this.tileBuffers.set(R,M)}}for(const w of this.tileBuffers.keys())if(!y.has(w)){const k=this.tileBuffers.get(w);k.vertexBuffer.destroy(),k.indexBuffer.destroy();for(const R of k.frcLevelSegments)R&&R.destroy();this.tileBuffers.delete(w)}}getBuffers(_){return this.tileBuffers.get(`${_.z}/${_.x}/${_.y}`)||null}destroy(){for(const _ of this.tileBuffers.values()){_.vertexBuffer.destroy(),_.indexBuffer.destroy();for(const f of _.frcLevelSegments)f&&f.destroy()}this.tileBuffers.clear()}_createBuffers(_,f){const y=new l.bN,w=new l.ak,k=[];for(const M of f.polygons){if(!M.hasGeometry()||M.rings.length===0)continue;const z=y.length,V=w.length,H=y.length,Y=[],te=[];let ne=0;for(let me=0;me0&&te.push(ne);for(const Se of fe)y.emplaceBack(Se.x,Se.y),Y.push(Se.x,Se.y),ne++}}const le=l.bQ(Y,te.length>0?te:void 0);for(let me=0;me{ne||(ne=new l.aj),ne.segments.push({vertexOffset:0,primitiveOffset:V,vertexLength:Y,primitiveLength:H-V,vaos:{},sortKey:0})};for(const me of k)me.frcMask&z?(te||(V=me.indexOffset,te=!0),H=me.indexOffset+me.indexCount,Y=me.vertexOffset+me.vertexCount):te&&(le(),te=!1);te&&le(),ne&&(R[M]=ne)}return{vertexBuffer:_.createVertexBuffer(y,l.bP.members),indexBuffer:_.createIndexBuffer(w),frcLevelSegments:R}}},drawFillFrcCoverageFirstPass:function(_){const{painter:f,bucket:y,coord:w,elevatedGeometry:k}=_,R=y.sourceLayerName==="road",M=y.sourceLayerName==="structure";if(!R&&!M||!f.frcCoverageSnapshot||k)return"fallthrough";const z=f.frcCoverageSnapshot.getTileOrParent(w.canonical);if(!z||z.frcMask===0)return"fallthrough";const V=y.hdExt&&y.hdExt.frcData,H=!!V&&!V.empty(),Y=ra(z.polygons);if(M&&!Y)return"skip";if(M&&Y)return _.polygonCoverageTiles.push({coord:_.coord,bufferData:_.bufferData,program:_.program,programConfiguration:_.programConfiguration,uniformValues:_.uniformValues,depthMode:_.depthMode,dynamicBuffers:_.dynamicBuffers,indexBuffer:_.indexBuffer,segments:_.segments,frcMask:z.frcMask}),"deferred";if(R&&H&&V){const te=z.frcMask,ne=f.transform.zoom;for(const[le,me]of V.frcPerLevel)te&1<0&&_.program.draw(f,_.drawMode,_.depthMode,_.stencilMode,_.colorMode,l.a5.disabled,_.uniformValues,_.layer.id,_.bufferData.layoutVertexBuffer,_.indexBuffer,V.frcNonRoadSegments,_.layer.paint,ne,_.programConfiguration,_.dynamicBuffers),"drawn"}return"fallthrough"},drawFillFrcCoverageSecondPass:function(_,f,y,w,k){if(y.length===0)return;const R=xp(_),M=_.transform.zoom,z=(V,H,Y)=>{Y!==1&&(V.uniformValues.u_opacity_multiplier=Y),V.program.draw(_,w,V.depthMode,H,k,l.a5.disabled,V.uniformValues,f.id,V.bufferData.layoutVertexBuffer,V.indexBuffer,V.segments,f.paint,M,V.programConfiguration,V.dynamicBuffers),Y!==1&&(V.uniformValues.u_opacity_multiplier=1)};qc(_,y,R,(V,H,Y)=>z(V,Y,1),(V,H,Y)=>z(V,Y,R))},drawLineFrcCoverageDetect:function(_,f,y,w,k,R){const M=f.hdExt&&f.hdExt.frcData;if(!M||M.frcPerLevel.size===0||!_.frcCoverageSnapshot||w)return null;const z=_.frcCoverageSnapshot.getTileOrParent(y.canonical);if(!z||z.frcMask===0)return null;const V=ra(z.polygons),H=_.frcCoverageFadeRange,Y=H!=null&&_.transform.zoom>=H[0];if(V&&Y){let te=!1;for(const ne of M.frcPerLevel.keys())if(z.frcMask&1<0&&w(y,M)},drawLineFrcFadePass:function(_,f,y,w,k,R,M){if(w.hasPolygonGeometry)return;const z=f.hdExt&&f.hdExt.frcData;if(!z||!_.frcCoverageFadeRange)return;const[V,H]=_.frcCoverageFadeRange;if(V>=H)return;const Y=1-Math.max(0,Math.min(1,(_.transform.zoom-V)/(H-V)));if(Y<=0)return;const te=k?R:_.stencilModeForClipping(y),ne=w.frcMask;for(const[le,me]of z.frcPerLevel)ne&1<{const H=R.bucket.hdExt&&R.bucket.hdExt.frcData,Y=H&&H.frcPerLevel.get(M);R.drawWithSegments(z,Y,V)};qc(_,y,w,(R,M,z)=>k(R,M,z),(R,M,z)=>k(R,M,z,w))}},kn=fd;async function al(){return Promise.resolve()}function Gc(_,f){const y=Math.pow(2,f.canonical.z),w=f.canonical.y;return[new l.b$(0,w/y).toLngLat().lat,new l.b$(0,(w+1)/y).toLngLat().lat]}function Dg(_,f,y,w,k,R,M){const z=_.context,V=z.gl,H=y.hillshadeFBO;if(!H)return;_.prepareDrawTile();const Y=_.isTileAffectedByFog(f),te=[];_.terrain&&_.terrain.renderingToTexture&&_.isEmissiveMrtActive()&&(te.push("USE_MRT1"),_.emissiveMode==="mrt-full-rgba"&&te.push("USE_MRT1_RGBA"));const ne=_.getOrCreateProgram("hillshade",{overrideFog:Y,defines:te});z.activeTexture.set(V.TEXTURE0),V.bindTexture(V.TEXTURE_2D,H.colorAttachment0.get());const le=((Me,qe,Ne,We)=>{const ct=Ne.paint.get("hillshade-shadow-color"),it=Ne.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",pt=Ne.paint.get("hillshade-highlight-color"),dt=Ne.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",mt=Ne.paint.get("hillshade-accent-color"),xt=Ne.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",bt=Ne.paint.get("hillshade-emissive-strength");let Ft=l.aF(Ne.paint.get("hillshade-illumination-direction"));if(Ne.paint.get("hillshade-illumination-anchor")==="viewport")Ft-=Me.transform.angle;else if(Me.style&&Me.style.enable3dLights()&&Me.style.directionalLight){const Mt=Me.style.directionalLight.properties.get("direction"),or=l.c4(Mt.x,Mt.y,Mt.z);Ft=l.aF(or[1])}const Lt=!Me.options.moving;return{u_matrix:We||Me.transform.calculateProjMatrix(qe.tileID.toUnwrapped(),Lt),u_image:0,u_latrange:Gc(0,qe.tileID),u_light:[Ne.paint.get("hillshade-exaggeration"),Ft],u_shadow:ct.toPremultipliedRenderColor(it?null:Ne.lut),u_highlight:pt.toPremultipliedRenderColor(dt?null:Ne.lut),u_emissive_strength:bt,u_accent:mt.toPremultipliedRenderColor(xt?null:Ne.lut)}})(_,y,w,_.terrain?f.projMatrix:null);_.uploadCommonUniforms(z,ne,f.toUnwrapped());const{tileBoundsBuffer:me,tileBoundsIndexBuffer:fe,tileBoundsSegments:Se}=_.getTileBoundsBuffers(y);ne.draw(_,V.TRIANGLES,k,R,M,l.a5.disabled,le,w.id,me,fe,Se)}function c0(_,f,y){if(!f.needsDEMTextureUpload)return;const w=_.context,k=w.gl;w.pixelStoreUnpackPremultiplyAlpha.set(!1),f.demTexture=f.demTexture||_.getTileTexture(y.stride);const R=y.getPixels();f.demTexture?f.demTexture.update(R,{premultiply:!1}):f.demTexture=new l.T(w,R,k.R32F,{premultiply:!1}),f.needsDEMTextureUpload=!1}function wx(_,f,y){const w=_.context,k=w.gl;if(!f.dem)return;const R=f.dem;if(w.activeTexture.set(k.TEXTURE1),c0(_,f,R),!f.demTexture)return;f.demTexture.bind(k.NEAREST,k.CLAMP_TO_EDGE);const M=R.dim;w.activeTexture.set(k.TEXTURE0);let z=f.hillshadeFBO;if(!z){const ne=new l.T(w,{width:M,height:M,data:null},k.RGBA8);ne.bind(k.LINEAR,k.CLAMP_TO_EDGE),z=f.hillshadeFBO=w.createFramebuffer(M,M,1,"renderbuffer"),z.colorAttachment0.set(ne.texture)}w.bindFramebuffer.set(z.framebuffer),w.viewport.set([0,0,M,M]);const{tileBoundsBuffer:V,tileBoundsIndexBuffer:H,tileBoundsSegments:Y}=_.getMercatorTileBoundsBuffers(),te=[];_.linearFloatFilteringSupported()&&te.push("TERRAIN_DEM_FLOAT_FORMAT"),_.terrain&&_.terrain.renderingToTexture&&_.isEmissiveMrtActive()&&(te.push("USE_MRT1"),_.emissiveMode==="mrt-full-rgba"&&te.push("USE_MRT1_RGBA")),_.getOrCreateProgram("hillshadePrepare",{defines:te}).draw(_,k.TRIANGLES,l.a3.disabled,l.a4.disabled,l.a7.unblended,l.a5.disabled,((ne,le)=>{const me=le.stride,fe=l.a2();return l.c3(fe,0,l.ac,-l.ac,0,0,1),l.bX(fe,fe,[0,-l.ac,0]),{u_matrix:fe,u_image:1,u_dimension:[me,me],u_zoom:ne.overscaledZ}})(f.tileID,R),y.id,V,H,Y),f.needsHillshadePrepare=!1}class As{constructor(f){this.gl=f.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(f){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class Vw extends As{getDefault(){return l.C.transparent.toNonPremultipliedRenderColor(null)}set(f){const y=this.current;(f.r!==y.r||f.g!==y.g||f.b!==y.b||f.a!==y.a||this.dirty)&&(this.gl.clearColor(f.r,f.g,f.b,f.a),this.current=f,this.dirty=!1)}}class Ih extends As{getDefault(){return 1}set(f){(f!==this.current||this.dirty)&&(this.gl.clearDepth(f),this.current=f,this.dirty=!1)}}class qw extends As{getDefault(){return 0}set(f){(f!==this.current||this.dirty)&&(this.gl.clearStencil(f),this.current=f,this.dirty=!1)}}class u0 extends As{getDefault(){return[!0,!0,!0,!0]}set(f){const y=this.current;(f[0]!==y[0]||f[1]!==y[1]||f[2]!==y[2]||f[3]!==y[3]||this.dirty)&&(this.gl.colorMask(f[0],f[1],f[2],f[3]),this.current=f,this.dirty=!1)}}class Ql extends As{getDefault(){return!0}set(f){(f!==this.current||this.dirty)&&(this.gl.depthMask(f),this.current=f,this.dirty=!1)}}class KA extends As{getDefault(){return 255}set(f){(f!==this.current||this.dirty)&&(this.gl.stencilMask(f),this.current=f,this.dirty=!1)}}class Sx extends As{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(f){const y=this.current;(f.func!==y.func||f.ref!==y.ref||f.mask!==y.mask||this.dirty)&&(this.gl.stencilFunc(f.func,f.ref,f.mask),this.current=f,this.dirty=!1)}}class mu extends As{getDefault(){const f=this.gl;return[f.KEEP,f.KEEP,f.KEEP]}set(f){const y=this.current;(f[0]!==y[0]||f[1]!==y[1]||f[2]!==y[2]||this.dirty)&&(this.gl.stencilOp(f[0],f[1],f[2]),this.current=f,this.dirty=!1)}}class vc extends As{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const y=this.gl;f?y.enable(y.STENCIL_TEST):y.disable(y.STENCIL_TEST),this.current=f,this.dirty=!1}}class Jl extends As{getDefault(){return[0,1]}set(f){const y=this.current;(f[0]!==y[0]||f[1]!==y[1]||this.dirty)&&(this.gl.depthRange(f[0],f[1]),this.current=f,this.dirty=!1)}}class Fa extends As{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const y=this.gl;f?y.enable(y.DEPTH_TEST):y.disable(y.DEPTH_TEST),this.current=f,this.dirty=!1}}class pu extends As{getDefault(){return this.gl.LESS}set(f){(f!==this.current||this.dirty)&&(this.gl.depthFunc(f),this.current=f,this.dirty=!1)}}class YA extends As{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const y=this.gl;f?y.enable(y.BLEND):y.disable(y.BLEND),this.current=f,this.dirty=!1}}class ZA extends As{getDefault(){const f=this.gl;return[f.ONE,f.ZERO,f.ONE,f.ZERO]}set(f){const y=this.current;(f[0]!==y[0]||f[1]!==y[1]||f[2]!==y[2]||f[3]!==y[3]||this.dirty)&&(this.gl.blendFuncSeparate(f[0],f[1],f[2],f[3]),this.current=f,this.dirty=!1)}}class XA extends As{getDefault(){return l.C.transparent.toNonPremultipliedRenderColor(null)}set(f){const y=this.current;(f.r!==y.r||f.g!==y.g||f.b!==y.b||f.a!==y.a||this.dirty)&&(this.gl.blendColor(f.r,f.g,f.b,f.a),this.current=f,this.dirty=!1)}}class d0 extends As{getDefault(){return this.gl.FUNC_ADD}set(f){(f!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(f,f),this.current=f,this.dirty=!1)}}class Gw extends As{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const y=this.gl;f?y.enable(y.CULL_FACE):y.disable(y.CULL_FACE),this.current=f,this.dirty=!1}}class QA extends As{getDefault(){return this.gl.BACK}set(f){(f!==this.current||this.dirty)&&(this.gl.cullFace(f),this.current=f,this.dirty=!1)}}class _N extends As{getDefault(){return this.gl.CCW}set(f){(f!==this.current||this.dirty)&&(this.gl.frontFace(f),this.current=f,this.dirty=!1)}}let vN=class extends As{getDefault(){return null}set(_){(_!==this.current||this.dirty)&&(this.gl.useProgram(_),this.current=_,this.dirty=!1)}};class bN extends As{getDefault(){return this.gl.TEXTURE0}set(f){(f!==this.current||this.dirty)&&(this.gl.activeTexture(f),this.current=f,this.dirty=!1)}}class wN extends As{getDefault(){const f=this.gl;return[0,0,f.drawingBufferWidth,f.drawingBufferHeight]}set(f){const y=this.current;(f[0]!==y[0]||f[1]!==y[1]||f[2]!==y[2]||f[3]!==y[3]||this.dirty)&&(this.gl.viewport(f[0],f[1],f[2],f[3]),this.current=f,this.dirty=!1)}}class Mg extends As{getDefault(){return null}set(f){if(f===this.current&&!this.dirty)return;const y=this.gl;y.bindFramebuffer(y.FRAMEBUFFER,f),this.current=f,this.dirty=!1}}class Hw extends As{getDefault(){return null}set(f){if(f===this.current&&!this.dirty)return;const y=this.gl;y.bindRenderbuffer(y.RENDERBUFFER,f),this.current=f,this.dirty=!1}}class ar extends As{getDefault(){return null}set(f){if(f===this.current&&!this.dirty)return;const y=this.gl;y.bindTexture(y.TEXTURE_2D,f),this.current=f,this.dirty=!1}}class SN extends As{getDefault(){return null}set(f){if(f===this.current&&!this.dirty)return;const y=this.gl;y.bindBuffer(y.ARRAY_BUFFER,f),this.current=f,this.dirty=!1}}class JA extends As{getDefault(){return null}set(f){const y=this.gl;y.bindBuffer(y.ELEMENT_ARRAY_BUFFER,f),this.current=f,this.dirty=!1}}class EN extends As{getDefault(){return null}set(f){this.gl&&(f!==this.current||this.dirty)&&(this.gl.bindVertexArray(f),this.current=f,this.dirty=!1)}}class Ex extends As{getDefault(){return 4}set(f){if(f===this.current&&!this.dirty)return;const y=this.gl;y.pixelStorei(y.UNPACK_ALIGNMENT,f),this.current=f,this.dirty=!1}}class Og extends As{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const y=this.gl;y.pixelStorei(y.UNPACK_PREMULTIPLY_ALPHA_WEBGL,f),this.current=f,this.dirty=!1}}class Fg extends As{getDefault(){return!1}set(f){if(f===this.current&&!this.dirty)return;const y=this.gl;y.pixelStorei(y.UNPACK_FLIP_Y_WEBGL,f),this.current=f,this.dirty=!1}}class h0 extends As{constructor(f,y){super(f),this.context=f,this.parent=y}getDefault(){return null}}class am extends h0{constructor(f,y,w=0){super(f,y),this.attachmentPoint=f.gl.COLOR_ATTACHMENT0+w}setDirty(){this.dirty=!0}set(f){if(f===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const y=this.gl;y.framebufferTexture2D(y.FRAMEBUFFER,this.attachmentPoint,y.TEXTURE_2D,f,0),this.current=f,this.dirty=!1}}class TN extends h0{attachment(){return this.gl.DEPTH_ATTACHMENT}set(f){if(f===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const y=this.gl;y.framebufferRenderbuffer(y.FRAMEBUFFER,this.attachment(),y.RENDERBUFFER,f),this.current=f,this.dirty=!1}}class AN extends h0{attachment(){return this.gl.DEPTH_ATTACHMENT}set(f){if(f===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const y=this.gl;y.framebufferTexture2D(y.FRAMEBUFFER,this.attachment(),y.TEXTURE_2D,f,0),this.current=f,this.dirty=!1}}class kN extends TN{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const IN=(_,f,y,w)=>({u_matrix:_,u_image0:0,u_image1:1,u_skirt_height:f,u_ground_shadow_factor:y,u_emissive_texture_available:w}),e2=(_,f,y,w,k,R,M,z,V,H,Y,te,ne,le,me,fe,Se)=>({u_proj_matrix:Float32Array.from(_),u_globe_matrix:f,u_normalize_matrix:Float32Array.from(w),u_merc_matrix:y,u_zoom_transition:k,u_merc_center:R,u_image0:0,u_image1:1,u_frustum_tl:M,u_frustum_tr:z,u_frustum_br:V,u_frustum_bl:H,u_globe_pos:Y,u_globe_radius:te,u_viewport:ne,u_grid_matrix:Se?Float32Array.from(Se):new Float32Array(9),u_skirt_height:le,u_far_z_cutoff:me,u_emissive_texture_available:fe});function Ww(_,f){return _!=null&&f!=null&&!(!_.hasData()||!f.hasData())&&_.demTexture!=null&&f.demTexture!=null&&_.tileID.key!==f.tileID.key}const Yd=new class{constructor(){this.operations={}}newMorphing(_,f,y,w,k){if(_ in this.operations){const R=this.operations[_];R.to.tileID.key!==y.tileID.key&&(R.queued=y)}else this.operations[_]={startTime:w,phase:0,duration:k,from:f,to:y,queued:null}}getMorphValuesForProxy(_){if(!(_ in this.operations))return null;const f=this.operations[_];return{from:f.from,to:f.to,phase:f.phase}}update(_){for(const f in this.operations){const y=this.operations[f];for(y.phase=(_-y.startTime)/y.duration;y.phase>=1||!this._validOp(y);)if(!this._nextOp(y,_)){delete this.operations[f];break}}}_nextOp(_,f){return!!_.queued&&(_.from=_.to,_.to=_.queued,_.queued=null,_.phase=0,_.startTime=f,!0)}_validOp(_){return _.from.hasData()&&_.to.hasData()}};function Tx(_,f,y){if(f===0)return 0;const w=f<1&&y===514?.25/f:1;return 6*Math.pow(1.5,22-_)*Math.max(f,1)*w}function f0(_,f){const y=1<<_.z;return!f&&(_.x===0||_.x===y-1)||_.y===0||_.y===y-1}function Kw(_,f){if(!_.style||!_.style.enable3dLights())return;const y=_.context,w=y.gl;y.activeTexture.set(w.TEXTURE1),f?f.bind(w.LINEAR,w.CLAMP_TO_EDGE):_.emptyTexture.bind(w.LINEAR,w.CLAMP_TO_EDGE)}class t2 extends l.E{constructor(f,y,w,k,R,M){super(),this.id=f,this.type=y,this.tileSize=w,this.minzoom=k,this.maxzoom=R,this.roundZoom=!1,this.reparseOverscaled=M}loaded(){return!0}loadTile(f,y){y(null)}serialize(){return{type:this.type}}}class Yw extends il{constructor(f){const y=new t2("mock-dem","raster-dem",512,0,Math.ceil(f.transform.maxZoom),!1);super("mock-dem",y,null),y.setEventedParent(this),this._sourceLoaded=!0}_loadTile(f,y){f.state="loaded",y(null)}}class om extends il{constructor(f){const y=new t2("proxy","geojson",512,0,Math.ceil(f.transform.maxZoom),!0);super("proxy",y,null),y.setEventedParent(this),this.map=this.getSource().map=f,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(f,y,w){if(f.freezeTileCoverage)return;this.transform=f;const k=f.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),R=new Set;for(const M of k)if(R.add(M.key),!this._tiles.has(M.key)){const z=new yf(M,this._source.tileSize*M.overscaleFactor(),f.tileZoom,void 0,void 0,this._source.worldview);z.state="loaded",this._tiles.set(M.key,z)}for(const[M,z]of this._tiles)R.has(M)||(this.freeFBO(M),z.unloadVectorData(),this._tiles.delete(M))}freeFBO(f){const y=this.proxyCachedFBO[f];if(y!==void 0){const w=Object.values(y);this.renderCachePool.push(...w),delete this.proxyCachedFBO[f]}}deallocRenderCache(){this.renderCache.forEach(f=>f.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class Zw extends l.bZ{constructor(f,y,w){super(f.overscaledZ,f.wrap,f.canonical.z,f.canonical.x,f.canonical.y),this.proxyTileKey=y,this.projMatrix=w}}function _p(_,f){return f==="rgba8"?_.RGBA8:_.R8}class Xw extends l.c8{constructor(f,y){super(),this.painter=f,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[w,k,R]=function(){const V=new l.bN,H=new l.ak,Y=131;V.reserve(17161),H.reserve(33800);const te=l.ac/128,ne=l.ac+te/2,le=ne+te;for(let fe=-te;fene||fe<0||fe>ne?24575:0,qe=l.bb(Math.round(Se),0,l.ac),Ne=l.bb(Math.round(fe),0,l.ac);V.emplaceBack(qe+Me,Ne)}const me=(fe,Se)=>{const Me=Se*Y+fe;H.emplaceBack(Me+1,Me,Me+Y),H.emplaceBack(Me+Y,Me+Y+1,Me+1)};for(let fe=1;fe<129;fe++)for(let Se=1;Se<129;Se++)me(Se,fe);return[0,129].forEach(fe=>{for(let Se=0;Se<130;Se++)me(Se,fe),me(fe,Se)}),[V,H,32768]}(),M=f.context;this.gridBuffer=M.createVertexBuffer(w,l.bP.members),this.gridIndexBuffer=M.createIndexBuffer(k),this.gridSegments=l.aj.simpleSegment(0,0,w.length,k.length),this.gridNoSkirtSegments=l.aj.simpleSegment(0,0,w.length,R),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new om(y.map),this.orthoMatrix=l.a2(),l.c3(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,l.ac,0,l.ac,0,1);const z=M.gl;this._overlapStencilMode=new l.a4({func:z.GEQUAL,mask:255},0,255,z.KEEP,z.KEEP,z.REPLACE),this._previousZoom=f.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=y,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Yw(y.map),this._pendingGroundEffectLayers=[],this._emissiveTexture="none",this._devtoolsFolder=null}set style(f){f.on("data",this._onStyleDataEvent.bind(this)),this._style=f,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(f,y,w){if(f&&f.terrain){this._style!==f&&(this.style=f,this._evaluationZoom=void 0);const k=f.terrain.properties,R=f.terrain.drapeRenderMode===0,M=f.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=l.e.now();const z=f.terrain&&f.terrain.scope,V=k.get("source"),H=R?this._mockSourceCache:f.getSourceCache(V,z);if(!H)return void l.w(`Couldn't find terrain source "${V}".`);if(this.sourceCache=H,this._attenuationRange=f.terrain.getAttenuationRange(),this._exaggeration=M?this.calculateExaggeration(y):k.get("exaggeration"),!y.projection.requiresDraping&&M&&this._exaggeration===0)return void this._disable();this.enabled=!0;const Y=()=>{this.sourceCache.used&&l.w(`Raster DEM source '${this.sourceCache.id}' is used both for terrain and as layer source. This leads to lower resolution of hillshade. For full hillshade resolution but higher memory consumption, define another raster DEM source.`);const te=this.getScaledDemTileSize();this.sourceCache.update(y,te,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,Y(),this._initializing=!0),Y(),y.updateElevation(!0,w),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(y),this._emptyDEMTextureDirty=!0,this._previousZoom=y.zoom}else this._disable()}calculateExaggeration(f){if(this._attenuationRange&&f.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(f.zoom);const y=this._previousCameraAltitude,w=f.getFreeCameraOptions().position.z/f.pixelsPerMeter*f.worldSize;this._previousCameraAltitude=w;const k=y!=null?w-y:Number.MAX_VALUE;if(Math.abs(k)<2)return this._exaggeration;const R=f.zoom,M=this._style.terrain;if(!this._previousUpdateTimestamp)return M.getExaggeration(R);let z=R-this._previousZoom;const V=this._previousUpdateTimestamp;let H=R;this._evaluationZoom!=null&&(H=this._evaluationZoom,Math.abs(R-H)>.5&&(z=.5*(R-H+z)),z*k<0&&(H+=z)),this._evaluationZoom=H;const Y=M.getExaggeration(H),te=Y===M.getExaggeration(Math.max(0,H-.1));if(te&&Math.abs(Y-this._exaggeration)<.01)return Y;let ne=Math.min(.1,.00375*(this._updateTimestamp-V));return(te||Y<.1||Math.abs(z)<1e-4)&&(ne=Math.min(.2,4*ne)),l.aw(this._exaggeration,Y,ne)}resetTileLookupCache(f){this._findCoveringTileCache[f]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(f){f.dataType==="source"&&f.coord?this._clearRenderCacheForTile(f.sourceCacheId,f.coord):f.dataType==="style"&&(this.invalidateRenderCache=!0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this._previousCameraAltitude=void 0)}_disable(){if(this.enabled&&(this.enabled=!1,this._emptyDEMTextureDirty=!0,this._sharedDepthStencil=void 0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this.proxySourceCache.deallocRenderCache(),this._style))for(const f in this._style._mergedSourceCaches)this._style._mergedSourceCaches[f].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(f=>f.fb.destroy()),this.pool=[],this.framebufferCopyTexture&&this.framebufferCopyTexture.destroy()}_source(){return this.enabled?this.sourceCache:null}isUsingMockSource(){return this.sourceCache===this._mockSourceCache}exaggeration(){return this.enabled?this._exaggeration:0}get visibleDemTiles(){return this._visibleDemTiles}get drapeBufferSize(){const f=2*this.proxySourceCache.getSource().tileSize;return[f,f]}set useVertexMorphing(f){this._useVertexMorphing=f}updateTileBinding(f){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const y=this.proxySourceCache,w=this.painter.transform;this._initializing&&(this._initializing=w._centerAltitude===0&&this.getAtPointOrZero(l.b$.fromLngLat(w.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const k=this.proxyCoords=y.getIds().map(V=>{const H=y.getTileByID(V).tileID;return H.projMatrix=w.calculateProjMatrix(H.toUnwrapped()),H});(function(V,H){const Y=H.transform.pointCoordinate(H.transform.getCameraPoint()),te=new l.P(Y.x,Y.y);V.sort((ne,le)=>{if(le.overscaledZ-ne.overscaledZ)return le.overscaledZ-ne.overscaledZ;const me=new l.P(ne.canonical.x+(1<{this.proxyToSource[V.key]={}}),this.terrainTileForTile={};const M=this._style._mergedSourceCaches;for(const V in M){const H=M[V];if(!H.used||!H.transform||(H!==this.sourceCache&&this.resetTileLookupCache(H.id),this._setupProxiedCoordsForOrtho(H,f[V],R),H.usedForTerrain))continue;const Y=f[V];(H.getSource().reparseOverscaled||H._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Y)}this.proxiedCoords[y.id]=k.map(V=>new Zw(V,V.key,this.orthoMatrix)),this._assignTerrainTiles(k),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(R),this.renderingToTexture=!1;const z={};this._visibleDemTiles=[];for(const V of this.proxyCoords){const H=this.terrainTileForTile[V.key];if(!H)continue;const Y=H.tileID.key;Y in z||(this._visibleDemTiles.push(H),z[Y]=Y)}}_assignTerrainTiles(f){this._initializing||f.forEach(y=>{if(this.terrainTileForTile[y.key])return;const w=this._findTileCoveringTileID(y,this.sourceCache);w&&(this.terrainTileForTile[y.key]=w)})}_prepareDEMTextures(){const f=this.painter.context,y=f.gl;for(const w in this.terrainTileForTile){const k=this.terrainTileForTile[w],R=k.dem;!R||k.demTexture&&!k.needsDEMTextureUpload||(f.activeTexture.set(y.TEXTURE1),c0(this.painter,k,R))}}_prepareDemTileUniforms(f,y,w,k){if(!y||y.demTexture==null)return!1;const R=f.tileID.canonical,M=Math.pow(2,y.tileID.canonical.z-R.z),z=k||"";return w[`u_dem_tl${z}`]=[R.x*M%1,R.y*M%1],w[`u_dem_scale${z}`]=M,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let f=0;const y=this._visibleDemTiles.reduce((w,k)=>{if(!k.dem)return w;const R=k.dem.tree.minimums[0];return R>0&&f++,w+R},0);return f?y/f:0}_updateEmptyDEMTexture(){const f=this.painter.context,y=f.gl;f.activeTexture.set(y.TEXTURE2);const w=this._getLoadedAreaMinimum(),k=new l.c9({width:1,height:1},new Float32Array([w]));this._emptyDEMTextureDirty=!1;let R=this._emptyDEMTexture;return R?R.update(k,{premultiply:!1}):R=this._emptyDEMTexture=new l.T(f,k,y.R32F,{premultiply:!1}),R}setupElevationDraw(f,y,w){const k=this.painter.context,R=k.gl,M={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0};M.u_exaggeration=this.exaggeration();let z=null,V=null,H=1;if(w&&w.morphing&&this._useVertexMorphing){const le=w.morphing.srcDemTile,me=w.morphing.dstDemTile;H=w.morphing.phase,le&&me&&(this._prepareDemTileUniforms(f,le,M,"_prev")&&(V=le),this._prepareDemTileUniforms(f,me,M)&&(z=me))}const Y=le=>le&&le.demTexture&&this.painter.linearFloatFilteringSupported()?R.LINEAR:R.NEAREST;let te=null;var ne;if(this.enabled?V&&z?(te=z.demTexture,k.activeTexture.set(R.TEXTURE4),V.demTexture.bind(Y(V),R.CLAMP_TO_EDGE),M.u_dem_lerp=H):(z=this.terrainTileForTile[f.tileID.key],te=this._prepareDemTileUniforms(f,z,M)?z.demTexture:this.emptyDEMTexture):te=this.emptyDEMTexture,k.activeTexture.set(R.TEXTURE2),te&&(M.u_dem_size=(ne=te).size[0]===1?1:ne.size[0]-2,te.bind(Y(z),R.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(w&&w.useDepthForOcclusion,y,M),w&&w.useMeterToDem&&z){const le=(1<{if(Me===Mt)return;const or=[];Mt===1&&or.push("TERRAIN_VERTEX_MORPHING"),or.push("PROJECTION_GLOBE_VIEW"),Ne&&or.push("CUSTOM_ANTIALIASING");const fr=H.isTileAffectedByFog(Lt);Se=H.getOrCreateProgram("globeRaster",{defines:or,overrideFog:fr}),Me=Mt},ct=H.colorModeForRenderPass(),it=new l.a3(fe.LEQUAL,l.a3.ReadWrite,H.depthRangeFor3D);Yd.update(le);const pt=l.bh(qe),dt=[l.ad(qe.center.lng),l.ae(qe.center.lat)],mt=H.globeSharedBuffers,xt=[qe.width*l.e.devicePixelRatio,qe.height*l.e.devicePixelRatio],bt=Float32Array.from(qe.globeMatrix),Ft={useDenormalizedUpVectorScale:!0};{const Lt=H.transform,Mt=Tx(Lt.zoom,Y.exaggeration(),Y.sourceCache._source.tileSize);Me=-1;const or=fe.TRIANGLES;for(const fr of ne){const Cr=te.getTile(fr),qr=l.a4.disabled,qt=Y.prevTerrainTileForTile[fr.key],Ut=Y.terrainTileForTile[fr.key];Ww(qt,Ut)&&Yd.newMorphing(fr.key,qt,Ut,le,250),Kw(H,Cr.emissiveTexture),me.activeTexture.set(fe.TEXTURE0),Cr.texture&&Cr.texture.bind(fe.LINEAR,fe.CLAMP_TO_EDGE);const gr=Yd.getMorphValuesForProxy(fr.key),Pr=gr?1:0;gr&&Object.assign(Ft,{morphing:{srcDemTile:gr.from,dstDemTile:gr.to,phase:l.c5(gr.phase)}});const ur=l.bd(fr.canonical),Xt=l.be(ur.getCenter().lat),mr=l.bi(fr.canonical,ur,Xt,Lt.worldSize/Lt._pixelsPerMercatorPixel),tn=l.bf(l.bg(fr.canonical)),kr=H.isEmissiveMrtActive()?1:0,vn=e2(Lt.expandedFarZProjMatrix,bt,pt,tn,l._(Lt.zoom),dt,Lt.frustumCorners.TL,Lt.frustumCorners.TR,Lt.frustumCorners.BR,Lt.frustumCorners.BL,Lt.globeCenterInViewSpace,Lt.globeRadius,xt,Mt,Lt._farZ,kr,mr);if(We(fr,Pr),Se&&(Y.setupElevationDraw(Cr,Se,Ft),H.uploadCommonUniforms(me,Se,fr.toUnwrapped()),mt)){const[Xr,ei,Rn]=mt.getGridBuffers(Xt,Mt!==0);Se.draw(H,or,it,qr,ct,l.a5.backCCW,vn,"globe_raster",Xr,ei,Rn)}}}if(mt&&(H.renderDefaultNorthPole||H.renderDefaultSouthPole)){const Lt=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Ne&&Lt.push("CUSTOM_ANTIALIASING"),Se=H.getOrCreateProgram("globeRaster",{defines:Lt});for(const Mt of ne){const{x:or,y:fr,z:Cr}=Mt.canonical,qr=fr===0,qt=fr===(1<Xr.draw(H,fe.TRIANGLES,it,l.a4.disabled,ct,l.a5.disabled,e2(qe.expandedFarZProjMatrix,mr,mr,tn,0,dt,qe.frustumCorners.TL,qe.frustumCorners.TR,qe.frustumCorners.BR,qe.frustumCorners.BL,qe.globeCenterInViewSpace,qe.globeRadius,xt,0,qe._farZ,kr),"globe_pole_raster",ei,Pr,ur);Y.setupElevationDraw(Xt,Se,Ft),H.uploadCommonUniforms(me,Se,Mt.toUnwrapped()),qr&&H.renderDefaultNorthPole&&vn(Se,Ut),qt&&H.renderDefaultSouthPole&&(mr=l.aY(l.a2(),mr,[1,-1,1]),vn(Se,gr))}}}})(k,R,M,z,V);else{const H=k.context,Y=H.gl;let te,ne;const le=k.shadowRenderer,me=l.aP(k,k.longestCutoffRange),fe=ct=>{if(ne===ct)return;const it=[];ct===1&&it.push("TERRAIN_VERTEX_MORPHING"),me.shouldRenderCutoff&&it.push("RENDER_CUTOFF"),le&&(it.push("RENDER_SHADOWS"),le.useNormalOffset&&it.push("NORMAL_OFFSET")),te=k.getOrCreateProgram("terrainRaster",{defines:it}),ne=ct},Se=k.colorModeForRenderPass(),Me=new l.a3(Y.LEQUAL,l.a3.ReadWrite,k.depthRangeFor3D);Yd.update(V);const qe=k.transform,Ne=Tx(qe.zoom,R.exaggeration(),R.sourceCache._source.tileSize);let We=[0,0,0];if(le){const ct=k.style.directionalLight,it=k.style.ambientLight;ct&&it&&(We=l.aQ(k.style,ct,it))}{ne=-1;const ct=Y.TRIANGLES,[it,pt]=[R.gridIndexBuffer,R.gridSegments];for(const dt of z){const mt=M.getTile(dt),xt=l.a4.disabled,bt=R.prevTerrainTileForTile[dt.key],Ft=R.terrainTileForTile[dt.key];Ww(bt,Ft)&&Yd.newMorphing(dt.key,bt,Ft,V,250),Kw(k,mt.emissiveTexture),H.activeTexture.set(Y.TEXTURE0),mt.texture&&mt.texture.bind(Y.LINEAR,Y.CLAMP_TO_EDGE);const Lt=Yd.getMorphValuesForProxy(dt.key),Mt=Lt?1:0;let or;Lt&&(or={morphing:{srcDemTile:Lt.from,dstDemTile:Lt.to,phase:l.c5(Lt.phase)}});const fr=k.isEmissiveMrtActive()?1:0,Cr=IN(dt.projMatrix,f0(dt.canonical,qe.renderWorldCopies)?Ne/10:Ne,We,fr);if(fe(Mt),!te)continue;R.setupElevationDraw(mt,te,or);const qr=dt.toUnwrapped();le&&le.setupShadows(qr,te),k.uploadCommonUniforms(H,te,qr,null,me),te.draw(k,ct,Me,xt,Se,l.a5.backCCW,Cr,"terrain_raster",R.gridBuffer,it,pt)}}}}(y,this,this.proxySourceCache,f,this._updateTimestamp),this.renderingToTexture=!0,y.gpuTimingDeferredRenderEnd(),f.splice(0,f.length))}renderBatch(f){if(this._drapedRenderBatches.length===0)return f+1;this.renderingToTexture=!0;const y=this.painter,w=this.painter.context,k=this.proxySourceCache,R=this.proxiedCoords[k.id],M=this._drapedRenderBatches.shift(),z=y.style.order,V=[];this._updateFBOs(y.emissiveMode==="mrt-full-rgba"?"rgba8":y.emissiveMode==="mrt-fallback"?"r8":"none");let H=0;for(const Y of R){const te=k.getTileByID(Y.proxyTileKey),ne=k.proxyCachedFBO[Y.key]?k.proxyCachedFBO[Y.key][f]:void 0,le=ne!==void 0?k.renderCache[ne]:this.pool[H++],me=ne!==void 0;if(te.texture=le.tex,te.emissiveTexture=le.emissiveTex,me&&!le.dirty){V.push(te.tileID);continue}w.bindFramebuffer.set(le.fb.framebuffer);const fe=w.gl;let Se;y.isEmissiveMrtActive()?fe.drawBuffers([fe.COLOR_ATTACHMENT0,fe.COLOR_ATTACHMENT1]):fe.drawBuffers([fe.COLOR_ATTACHMENT0]),this.renderedToTile=!1,le.dirty&&(w.clear({color:l.C.transparent,stencil:0}),le.dirty=!1);for(let Me=M.start;Me<=M.end;++Me){const qe=y.style._mergedLayers[z[Me]];if(qe.isHidden(y.transform.zoom))continue;const Ne=y.style.getLayerSourceCache(qe),We=Ne?this.proxyToSource[Y.key][Ne.id]:[Y];if(!We)continue;this._currentProxyKey=Y.key;const ct=We;w.viewport.set([0,0,le.fb.width,le.fb.height]),Se!==(Ne?Ne.id:null)&&(this._setupStencil(le,We,qe,Ne),Se=Ne?Ne.id:null),y.renderLayer(y,Ne,qe,ct)}if(fe.drawBuffers([fe.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const Me of this._pendingGroundEffectLayers){const qe=y.style._mergedLayers[z[Me]];if(qe.isHidden(y.transform.zoom))continue;const Ne=y.style.getLayerSourceCache(qe),We=Ne?this.proxyToSource[Y.key][Ne.id]:[Y];if(!We)continue;const ct=We;w.viewport.set([0,0,le.fb.width,le.fb.height]),Se!==(Ne?Ne.id:null)&&(this._setupStencil(le,We,qe,Ne),Se=Ne?Ne.id:null),y.renderLayer(y,Ne,qe,ct)}this.renderedToTile?(le.dirty=!0,V.push(te.tileID)):me||--H,H===5&&(H=0,this.renderToBackBuffer(V))}return this.renderToBackBuffer(V),this.renderingToTexture=!1,w.bindFramebuffer.set(null),w.viewport.set([0,0,y.width,y.height]),M.end+1}postRender(){}isLayerOrderingCorrect(f){const y=f.order.length;let w=-1,k=y;for(let R=0;Rw}getMinElevationBelowMSL(){let f=0;return this._visibleDemTiles.filter(y=>y.dem).forEach(y=>{f=Math.min(f,y.dem.tree.minimums[0])}),f===0?f:(f-30)*this._exaggeration}raycast(f,y,w){if(!this._visibleDemTiles)return null;const k=this._visibleDemTiles.filter(R=>R.dem).map(R=>{const M=R.tileID,z=1<(R.t!==null?R.t:Number.MAX_VALUE)-(M.t!==null?M.t:Number.MAX_VALUE));for(const R of k){if(R.t==null)return null;const M=R.tile.dem.tree.raycast(R.minx,R.miny,R.maxx,R.maxy,f,y,w);if(M!=null)return M}return null}_createFBO(){const f=this.painter.context,y=f.gl,w=this.drapeBufferSize;f.activeTexture.set(y.TEXTURE0);const k=new l.T(f,{width:w[0],height:w[1],data:null},y.RGBA8);k.bind(y.LINEAR,y.CLAMP_TO_EDGE);const R=f.createFramebuffer(w[0],w[1],1,null);let M;return R.colorAttachment0.set(k.texture),this._emissiveTexture!=="none"&&(M=new l.T(f,{width:w[0],height:w[1],data:null},_p(y,this._emissiveTexture)),M.bind(y.LINEAR,y.CLAMP_TO_EDGE),R.createColorAttachment(f,1),R.colorAttachment1.set(M.texture)),R.depthAttachment=new kN(f,R.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=f.createRenderbuffer(f.gl.DEPTH_STENCIL,w[0],w[1]),this._stencilRef=0,R.depthAttachment.set(this._sharedDepthStencil),f.clear({stencil:0})):R.depthAttachment.set(this._sharedDepthStencil),f.extTextureFilterAnisotropic&&y.texParameterf(y.TEXTURE_2D,f.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,f.extTextureFilterAnisotropicMax),{fb:R,tex:k,emissiveTex:M,dirty:!1}}_updateFBOs(f){if(this._emissiveTexture!==f){for(const y of this.pool)this._updateFBO(y,f);for(const y of this.proxySourceCache.renderCache)this._updateFBO(y,f);this._emissiveTexture=f}}_updateFBO(f,y){const w=f.fb,k=this.painter.context,R=k.gl,M=this.drapeBufferSize;if(y!=="none"){const z=new l.T(k,{width:M[0],height:M[1],data:null},_p(R,y));z.bind(R.LINEAR,R.CLAMP_TO_EDGE),f.emissiveTex=z,w.createColorAttachment(k,1),w.colorAttachment1.set(z.texture)}else f.emissiveTex=void 0,w.removeColorAttachment(k,1);f.dirty=!0}_initFBOPool(){for(;this.pool.length{const y=this._style._mergedLayers[f],w=y.isHidden(this.painter.transform.zoom);return y.type==="hillshade"||y.type==="custom"?!w&&y.shouldRedrape():!w&&y.hasTransition()})}_clearLineLayersFromRenderCache(){let f=!1;for(const w of this._style.getSources())if(w.type==="vector"){f=!0;break}if(!f)return;const y={};for(let w=0;wV>z.end)||l.w("fill-extrusion with flood lighting and/or ground ambient occlusion should be moved to be on top of all draped layers.")}this._drapedRenderBatches=w}_setupRenderCache(f){const y=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,y.renderCache.length>y.renderCachePool.length){const M=Object.values(y.proxyCachedFBO);y.proxyCachedFBO={};for(let z=0;z=0;M--){const z=w[M];if(y.getTileByID(z.key),y.proxyCachedFBO[z.key]!==void 0){const V=f[z.key],H=this.proxyToSource[z.key];let Y=0;for(const te in H){const ne=H[te],le=V[te];if(!le||le.length!==ne.length||ne.some((me,fe)=>me!==le[fe]||k[te]&&Object.hasOwn(k[te],me.key))){Y=-1;break}++Y}for(const te in y.proxyCachedFBO[z.key])y.renderCache[y.proxyCachedFBO[z.key][te]].dirty=Y<0||Y!==Object.values(V).length}}const R=[...this._drapedRenderBatches];R.sort((M,z)=>z.end-z.start-(M.end-M.start));for(const M of R)for(const z of w){if(y.proxyCachedFBO[z.key])continue;let V=y.renderCachePool.pop();V===void 0&&y.renderCache.length<50&&(V=y.renderCache.length,y.renderCache.push(this._createFBO())),V!==void 0&&(y.proxyCachedFBO[z.key]={},y.proxyCachedFBO[z.key][M.start]=V,y.renderCache[V].dirty=!0)}this._tilesDirty={}}_setupStencil(f,y,w,k){if(!k||!this._sourceTilesOverlap[k.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const R=this.painter.context,M=R.gl;if(y.length<=1)return void(this._overlapStencilType=!1);let z;if(w.isTileClipped())z=y.length,this._overlapStencilMode.test={func:M.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(y[0].overscaledZ>y.at(-1).overscaledZ))return void(this._overlapStencilType=!1);z=1,this._overlapStencilMode.test={func:M.GREATER,mask:255},this._overlapStencilType="Mask"}const V=w.type==="raster"&&w.paint.get("raster-mask")?l.cc-1:255;this._stencilRef+z>V&&(R.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=z,this._overlapStencilMode.ref=this._stencilRef,w.isTileClipped()&&this._renderTileClippingMasks(y,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}getCurrentProxiedCoords(f){if(this._currentProxyKey==null)return null;const y=this.proxyToSource[this._currentProxyKey];return y?y[f]:null}stencilModeForRTTOverlap(f){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs.get(f.key)),this._overlapStencilMode):l.a4.disabled}_renderTileClippingMasks(f,y){const w=this.painter,k=this.painter.context,R=k.gl;w._tileClippingMaskIDs=new Map,k.setColorMode(l.a7.disabled),k.setDepthMode(l.a3.disabled);const M=w.getOrCreateProgram("clippingMask");for(const z of f){const V=--y;w._tileClippingMaskIDs.set(z.key,V),M.draw(w,R.TRIANGLES,l.a3.disabled,new l.a4({func:R.ALWAYS,mask:0},V,255,R.KEEP,R.KEEP,R.REPLACE),l.a7.disabled,l.a5.disabled,Io(z.projMatrix),"$clipping",w.tileExtentBuffer,w.quadTriangleIndexBuffer,w.tileExtentSegments)}}pointCoordinate(f){const y=this.painter.transform;if(f.x<0||f.x>y.width||f.y<0||f.y>y.height)return null;const w=[f.x,f.y,1,1];l.cd(w,w,y.pixelMatrixInverse),l.ce(w,w,1/w[3]),w[0]/=y.worldSize,w[1]/=y.worldSize;const k=y._camera.position,R=l.ca(1,y.center.lat),M=[k[0],k[1],k[2]/R,0],z=l.cf([],w.slice(0,3),M);l.cg(z,z);const V=this.raycast(M,z,this._exaggeration);return V!==null&&V?(l.ch(M,M,z,V),M[3]=M[2],M[2]*=R,M):null}_setupProxiedCoordsForOrtho(f,y,w){if(["image","video","canvas"].includes(f.getSource().type))return this._setupProxiedCoordsForImageSource(f,y,w);this._findCoveringTileCache[f.id]=this._findCoveringTileCache[f.id]||{};const k=this.proxiedCoords[f.id]=[],R=this.proxyCoords;for(let V=0;VY.overscaledZ-H.overscaledZ)}_setupProxiedCoordsForImageSource(f,y,w){if(!f.getSource().loaded())return;const k=this.proxiedCoords[f.id]=[],R=this.proxyCoords,M=f.getSource(),z=M.tileID;if(!z)return;const V=new l.P(z.x,z.y)._div(1<(te.min.x=Math.min(te.min.x,ne.x-V.x),te.min.y=Math.min(te.min.y,ne.y-V.y),te.max.x=Math.max(te.max.x,ne.x-V.x),te.max.y=Math.max(te.max.y,ne.y-V.y),te),{min:new l.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new l.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),Y=(te,ne)=>{const le=te.wrap+te.canonical.x/(1<Se+H.max.x||me+feMe+H.max.y};for(let te=0;teM.key===y.tileID.key);if(R)return R}if(y.tileID.key!==f.key){const R=f.canonical.z-y.tileID.canonical.z;let M,z,V;k=l.a2();const H=y.tileID.wrap-f.wrap<0?(M=l.ac>>R,z=M*((y.tileID.canonical.x<=te){const ne=f.canonical.z-te;y.getSource().reparseOverscaled?(z=Math.max(f.canonical.z+2,y.transform.tileZoom),M=new l.bZ(z,f.wrap,te,f.canonical.x>>ne,f.canonical.y>>ne)):ne!==0&&(z=te,M=new l.bZ(z,f.wrap,te,f.canonical.x>>ne,f.canonical.y>>ne))}M.key!==f.key&&(H.push(M.key),w=y.getTile(M))}const Y=te=>{H.forEach(ne=>{k[ne]=te}),H.length=0};for(z-=1;z>=V&&(!w||!w.hasData());z--){w&&Y(w.tileID.key);const te=M.calculateScaledKey(z);if(w=y.getTileByID(te),w&&w.hasData())break;const ne=k[te];if(ne===null)break;ne===void 0?H.push(te):w=y.getTileByID(ne)}return Y(w?w.tileID.key:null),w&&w.hasData()?w:null}findDEMTileFor(f){return this.enabled?this._findTileCoveringTileID(f,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(f,y){let w=this._tilesDirty[f];w||(w=this._tilesDirty[f]={}),w[y.key]=!0}}let lm=null;const m0=[];function jN(_,f){return lm?lm.create(_,f):null}const r2=(_,f,y)=>({u_matrix:_,u_emissive_strength:f,u_ground_shadow_factor:y,u_opacity_multiplier:1}),n2=(_,f,y,w,k,R=0)=>Object.assign(r2(_,f,k),l.ci(y,w,R)),i2=(_,f,y,w)=>({u_matrix:_,u_world:y,u_emissive_strength:f,u_ground_shadow_factor:w,u_opacity_multiplier:1}),GB=(_,f,y,w,k,R,M=0)=>Object.assign(n2(_,f,y,w,R,M),{u_world:k}),HB=(_,f,y)=>({u_image:_,u_texel_size:f,u_first_pass:y?1:0}),WB=l.a2(),KB=(_,f,y,w,k,R,M)=>{const z=_.transform,V=z.projection.name==="globe",H=V?l.cj(z.zoom,f.canonical)*z._pixelsPerMercatorPixel:l.ck(y,1,R),Y={u_matrix:f.projMatrix,u_extrude_scale:H,u_intensity:M,u_inv_rot_matrix:WB,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(V){Y.u_inv_rot_matrix=w,Y.u_merc_center=k,Y.u_tile_id=[f.canonical.x,f.canonical.y,1<({u_matrix:f,u_normalize_matrix:y,u_globe_matrix:w,u_merc_matrix:k,u_grid_matrix:R,u_tl_parent:M,u_scale_parent:Y,u_fade_t:te.mix,u_opacity:te.opacity*ne.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:ne.paint.get("raster-brightness-min"),u_brightness_high:ne.paint.get("raster-brightness-max"),u_saturation_factor:l.cn(ne.paint.get("raster-saturation")),u_contrast_factor:l.cm(ne.paint.get("raster-contrast")),u_spin_weights:Qw(ne.paint.get("raster-hue-rotate")),u_perspective_transform:le,u_raster_elevation:me,u_zoom_transition:z,u_merc_center:V,u_cutoff_params:H,u_colorization_mix:ko(l.cl,Se,qe),u_colorization_offset:yc(l.cl,Me,qe),u_color_ramp:fe,u_color_ramp_size:l.cl,u_texture_offset:[We/(Ne+2*We),Ne/(Ne+2*We)],u_texture_res:[Ne+2*We,Ne+2*We],u_emissive_strength:ct,u_zbias_factor:CN(_)});function Qw(_){_*=Math.PI/180;const f=Math.sin(_),y=Math.cos(_);return[(2*y+1)/3,(-Math.sqrt(3)*f-y+1)/3,(Math.sqrt(3)*f-y+1)/3]}const NN=l.a2(),s2=(_,f,y,w,k,R,M,z,V,H,Y,te,ne,le,me,fe,Se,Me,qe,Ne,We,ct,it,pt,dt)=>{const mt=k.transform,xt={u_is_size_zoom_constant:+(_==="constant"||_==="source"),u_is_size_feature_constant:+(_==="constant"||_==="camera"),u_size_t:f?f.uSizeT:0,u_size:f?f.uSize:0,u_camera_to_center_distance:mt.getCameraToCenterDistance(Ne),u_rotate_symbol:+y,u_aspect_ratio:mt.width/mt.height,u_fade_change:k.options.fadeDuration?k.symbolFadeChange:1,u_now:0|Math.round(k.now),u_fade_duration:k.options.fadeDuration,u_matrix:R,u_label_plane_matrix:M,u_coord_matrix:z,u_is_text:+H,u_is_sdf:+Y,u_elevation_from_sea:V?1:0,u_pitch_with_map:+w,u_texsize:te,u_texsize_icon:ne,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:NN,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:NN,u_up_vector:[0,-1,0],u_color_adj_mat:it,u_icon_transition:pt||0,u_gamma_scale:Y?w?k.transform.getCameraToCenterDistance(Ne)*Math.cos(k.terrain?0:k.transform._pitch):1:0,u_device_pixel_ratio:l.e.devicePixelRatio,u_is_halo:1,u_scale_factor:dt||1,u_ground_shadow_factor:We,u_inv_matrix:l.aZ(l.a2(),M),u_normal_scale:ct,u_lutTexture:l.cp.LUT,u_spp_fill_np_color:[0,0,0,1],u_spp_halo_np_color:[0,0,0,0],u_spp_opacity:1,u_spp_halo_width:0,u_spp_halo_blur:0,u_spp_emissive_strength:0,u_spp_occlusion_opacity:1,u_spp_z_offset:0,u_spp_translate_rotation:[1,0],u_spp_zoom_fraction:0,u_opacity_multiplier:1};return Ne.name==="globe"&&(xt.u_tile_id=[me.canonical.x,me.canonical.y,1<({u_matrix:_,u_emissive_strength:f,u_opacity:y,u_color:w}),p0=(_,f,y,w,k,R,M,z,V)=>Object.assign(l.cq(k,R,M,w,z,V),{u_matrix:_,u_emissive_strength:f,u_opacity:y}),a2={fillExtrusion:l.cw,fillExtrusionPattern:l.cv,fill:_=>({u_matrix:new l.aa(_),u_emissive_strength:new l.a9(_),u_ground_shadow_factor:new l.ab(_),u_opacity_multiplier:new l.a9(_)}),fillPattern:_=>({u_matrix:new l.aa(_),u_emissive_strength:new l.a9(_),u_image:new l.b6(_),u_texsize:new l.a8(_),u_pixel_coord_upper:new l.a8(_),u_pixel_coord_lower:new l.a8(_),u_tile_units_to_pixels:new l.a9(_),u_ground_shadow_factor:new l.ab(_),u_pattern_transition:new l.a9(_),u_opacity_multiplier:new l.a9(_)}),fillOutline:_=>({u_matrix:new l.aa(_),u_emissive_strength:new l.a9(_),u_world:new l.a8(_),u_ground_shadow_factor:new l.ab(_),u_opacity_multiplier:new l.a9(_)}),fillOutlinePattern:_=>({u_matrix:new l.aa(_),u_emissive_strength:new l.a9(_),u_world:new l.a8(_),u_image:new l.b6(_),u_texsize:new l.a8(_),u_pixel_coord_upper:new l.a8(_),u_pixel_coord_lower:new l.a8(_),u_tile_units_to_pixels:new l.a9(_),u_ground_shadow_factor:new l.ab(_),u_pattern_transition:new l.a9(_),u_opacity_multiplier:new l.a9(_)}),lineBlendComposite:_=>({u_image:new l.b6(_),u_opacity:new l.a9(_),u_blend_mode:new l.b6(_),u_max_density:new l.a9(_)}),lineBlendReduce:_=>({u_image:new l.b6(_),u_texel_size:new l.a8(_),u_first_pass:new l.b6(_)}),circle:l.cu,collisionBox:_=>({u_matrix:new l.aa(_),u_inv_rot_matrix:new l.aa(_),u_camera_to_center_distance:new l.a9(_),u_extrude_scale:new l.a8(_),u_zoom_transition:new l.a9(_),u_merc_center:new l.a8(_),u_tile_id:new l.ab(_)}),collisionCircle:_=>({u_matrix:new l.aa(_),u_inv_matrix:new l.aa(_),u_camera_to_center_distance:new l.a9(_),u_viewport_size:new l.a8(_)}),placementDebug:_=>({u_viewport_size:new l.a8(_),u_color:new l.al(_),u_outline_width:new l.a9(_),u_opacity:new l.a9(_),u_stroke_opacity:new l.a9(_),u_collision_padding_opacity:new l.a9(_)}),debug:l.ct,clippingMask:_=>({u_matrix:new l.aa(_)}),heatmap:_=>({u_extrude_scale:new l.a9(_),u_intensity:new l.a9(_),u_matrix:new l.aa(_),u_inv_rot_matrix:new l.aa(_),u_merc_center:new l.a8(_),u_tile_id:new l.ab(_),u_zoom_transition:new l.a9(_),u_up_dir:new l.ab(_)}),heatmapTexture:_=>({u_image:new l.b6(_),u_color_ramp:new l.b6(_),u_opacity:new l.a9(_)}),hillshade:_=>({u_matrix:new l.aa(_),u_image:new l.b6(_),u_latrange:new l.a8(_),u_light:new l.a8(_),u_shadow:new l.al(_),u_highlight:new l.al(_),u_emissive_strength:new l.a9(_),u_accent:new l.al(_)}),hillshadePrepare:_=>({u_matrix:new l.aa(_),u_image:new l.b6(_),u_dimension:new l.a8(_),u_zoom:new l.a9(_)}),line:l.cs,linePattern:l.cr,raster:_=>({u_matrix:new l.aa(_),u_normalize_matrix:new l.aa(_),u_globe_matrix:new l.aa(_),u_merc_matrix:new l.aa(_),u_grid_matrix:new l.b8(_),u_tl_parent:new l.a8(_),u_scale_parent:new l.a9(_),u_fade_t:new l.a9(_),u_opacity:new l.a9(_),u_image0:new l.b6(_),u_image1:new l.b6(_),u_brightness_low:new l.a9(_),u_brightness_high:new l.a9(_),u_saturation_factor:new l.a9(_),u_contrast_factor:new l.a9(_),u_spin_weights:new l.ab(_),u_perspective_transform:new l.a8(_),u_raster_elevation:new l.a9(_),u_zoom_transition:new l.a9(_),u_merc_center:new l.a8(_),u_cutoff_params:new l.b7(_),u_colorization_mix:new l.b7(_),u_colorization_offset:new l.a9(_),u_color_ramp:new l.b6(_),u_color_ramp_size:new l.a9(_),u_texture_offset:new l.a8(_),u_texture_res:new l.a8(_),u_emissive_strength:new l.a9(_),u_zbias_factor:new l.a9(_)}),symbol:_=>({u_is_size_zoom_constant:new l.b6(_),u_is_size_feature_constant:new l.b6(_),u_size_t:new l.a9(_),u_size:new l.a9(_),u_camera_to_center_distance:new l.a9(_),u_rotate_symbol:new l.b6(_),u_aspect_ratio:new l.a9(_),u_fade_change:new l.a9(_),u_now:new l.b6(_),u_fade_duration:new l.a9(_),u_matrix:new l.aa(_),u_label_plane_matrix:new l.aa(_),u_coord_matrix:new l.aa(_),u_is_text:new l.b6(_),u_is_sdf:new l.b6(_),u_elevation_from_sea:new l.b6(_),u_pitch_with_map:new l.b6(_),u_texsize:new l.a8(_),u_texsize_icon:new l.a8(_),u_texture:new l.b6(_),u_texture_icon:new l.b6(_),u_gamma_scale:new l.a9(_),u_device_pixel_ratio:new l.a9(_),u_tile_id:new l.ab(_),u_zoom_transition:new l.a9(_),u_inv_rot_matrix:new l.aa(_),u_merc_center:new l.a8(_),u_camera_forward:new l.ab(_),u_tile_matrix:new l.aa(_),u_up_vector:new l.ab(_),u_ecef_origin:new l.ab(_),u_is_halo:new l.b6(_),u_icon_transition:new l.a9(_),u_color_adj_mat:new l.aa(_),u_scale_factor:new l.a9(_),u_ground_shadow_factor:new l.ab(_),u_inv_matrix:new l.aa(_),u_normal_scale:new l.a9(_),u_lutTexture:new l.b6(_),u_spp_fill_np_color:new l.b7(_),u_spp_halo_np_color:new l.b7(_),u_spp_opacity:new l.a9(_),u_spp_halo_width:new l.a9(_),u_spp_halo_blur:new l.a9(_),u_spp_emissive_strength:new l.a9(_),u_spp_occlusion_opacity:new l.a9(_),u_spp_z_offset:new l.a9(_),u_spp_translate_rotation:new l.a8(_),u_spp_zoom_fraction:new l.a9(_),u_opacity_multiplier:new l.a9(_)}),background:_=>({u_matrix:new l.aa(_),u_emissive_strength:new l.a9(_),u_opacity:new l.a9(_),u_color:new l.al(_)}),backgroundPattern:_=>({u_matrix:new l.aa(_),u_emissive_strength:new l.a9(_),u_opacity:new l.a9(_),u_image:new l.b6(_),u_pattern_tl:new l.a8(_),u_pattern_br:new l.a8(_),u_texsize:new l.a8(_),u_pattern_size:new l.a8(_),u_pixel_coord_upper:new l.a8(_),u_pixel_coord_lower:new l.a8(_),u_pattern_units_to_pixels:new l.a8(_)}),skybox:_=>({u_matrix:new l.aa(_),u_sun_direction:new l.ab(_),u_cubemap:new l.b6(_),u_opacity:new l.a9(_),u_temporal_offset:new l.a9(_)}),skyboxGradient:_=>({u_matrix:new l.aa(_),u_color_ramp:new l.b6(_),u_center_direction:new l.ab(_),u_radius:new l.a9(_),u_opacity:new l.a9(_),u_temporal_offset:new l.a9(_)}),skyboxCapture:_=>({u_matrix_3f:new l.b8(_),u_sun_direction:new l.ab(_),u_sun_intensity:new l.a9(_),u_color_tint_r:new l.b7(_),u_color_tint_m:new l.b7(_),u_luminance:new l.a9(_)}),globeAtmosphere:_=>({u_frustum_tl:new l.ab(_),u_frustum_tr:new l.ab(_),u_frustum_br:new l.ab(_),u_frustum_bl:new l.ab(_),u_horizon:new l.a9(_),u_transition:new l.a9(_),u_fadeout_range:new l.a9(_),u_atmosphere_fog_color:new l.b7(_),u_high_color:new l.b7(_),u_space_color:new l.b7(_),u_temporal_offset:new l.a9(_),u_horizon_angle:new l.a9(_)}),stars:_=>({u_matrix:new l.aa(_),u_up:new l.ab(_),u_right:new l.ab(_),u_intensity_multiplier:new l.a9(_)}),occlusion:_=>({u_matrix:new l.aa(_),u_anchorPos:new l.ab(_),u_screenSizePx:new l.a8(_),u_occluderSizePx:new l.a8(_),u_color:new l.b7(_)})};var YB={terrainRaster:l.bm(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image0; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS uniform sampler2D u_image1;uniform float u_emissive_texture_available; #endif in vec2 v_pos0; #ifdef FOG in float v_fog_opacity; #endif #ifdef RENDER_SHADOWS in vec4 v_pos_light_view_0;in vec4 v_pos_light_view_1; #endif uniform vec3 u_ground_shadow_factor;void main() {vec4 image_color=texture(u_image0,v_pos0);vec4 color; #ifdef LIGHTING_3D_MODE const vec3 normal=vec3(0.0,0.0,1.0); #ifdef RENDER_SHADOWS float cutoffOpacity=1.0; #ifdef RENDER_CUTOFF cutoffOpacity=cutoff_opacity(u_cutoff_params,1.0/gl_FragCoord.w); #endif #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS vec3 unlit_base;vec3 emissive_base; #ifdef USE_MRT1_RGBA vec4 emissive_premult=vec4(0.0);if (u_emissive_texture_available > 0.5) {emissive_premult=texture(u_image1,v_pos0);}unlit_base=image_color.rgb-emissive_premult.rgb;emissive_base=emissive_premult.rgb; #else float emissive_strength=image_color.a;if (u_emissive_texture_available > 0.5) {emissive_strength=texture(u_image1,v_pos0).r;}unlit_base=image_color.rgb*(1.0-emissive_strength);emissive_base=image_color.rgb*emissive_strength; #endif float ndotl=u_shadow_direction.z;float occlusion=1.0;if (ndotl >=0.0) {occlusion=shadow_occlusion(v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,0.0);}ndotl=max(0.0,ndotl);vec3 lit=apply_lighting(unlit_base,normal,mix(1.0,(1.0-(u_shadow_intensity*occlusion))*ndotl,cutoffOpacity));vec3 emissive=compute_emissive_draped(emissive_base,1.0-u_shadow_intensity,occlusion,u_ground_shadow_factor);color.rgb=lit+emissive;color.a=1.0; #else float lighting_factor=shadowed_light_factor_normal_unbiased(normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w);color=apply_lighting(image_color,normal,mix(1.0,lighting_factor,cutoffOpacity)); #endif #else float lighting_factor=u_lighting_directional_dir.z; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS #ifdef USE_MRT1_RGBA vec4 emissive_premult=vec4(0.0);if (u_emissive_texture_available > 0.5) {emissive_premult=texture(u_image1,v_pos0);}vec3 unlit_base=image_color.rgb-emissive_premult.rgb;color.rgb=apply_lighting(unlit_base,normal,lighting_factor)+emissive_premult.rgb;color.a=1.0; #else color=apply_lighting(image_color,normal,lighting_factor);float emissive_strength=image_color.a;if (u_emissive_texture_available > 0.5) {emissive_strength=texture(u_image1,v_pos0).r;}color.rgb=mix(color.rgb,image_color.rgb,emissive_strength);color.a=1.0; #endif #else color=apply_lighting(image_color,normal,lighting_factor); #endif #endif #else color=image_color; #endif #ifdef FOG color=fog_dither(fog_apply_from_vert(color,v_fog_opacity)); #endif glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;uniform float u_skirt_height;in ivec2 a_pos;out vec2 v_pos0; #ifdef FOG out float v_fog_opacity; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out vec4 v_pos_light_view_0;out vec4 v_pos_light_view_1; #endif void main() {vec3 decomposedPosAndSkirt=decomposeToPosAndSkirt(a_pos);float skirt=decomposedPosAndSkirt.z;vec2 decodedPos=decomposedPosAndSkirt.xy;float elevation=elevation(decodedPos)-skirt*u_skirt_height;v_pos0=bottom_left_to_native_uv(decodedPos/8192.0);gl_Position=u_matrix*vec4(decodedPos,elevation,1.0); #ifdef FOG v_fog_opacity=fog(fog_position(vec3(decodedPos,elevation))); #endif #ifdef RENDER_SHADOWS vec3 pos=vec3(decodedPos,elevation);v_pos_light_view_0=u_light_matrix_0*vec4(pos,1.);v_pos_light_view_1=u_light_matrix_1*vec4(pos,1.); #endif }`),terrainDepth:l.bm("precision highp float;in float v_depth;void main() {glFragColor=pack_depth(v_depth);}",`#include "_prelude_terrain.vertex.glsl" uniform mat4 u_matrix;in ivec2 a_pos;out float v_depth;void main() {float elevation=elevation(vec2(a_pos));gl_Position=u_matrix*vec4(a_pos,elevation,1.0);v_depth=gl_Position.z/gl_Position.w;}`),globeRaster:l.bm(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform sampler2D u_image0; #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS uniform sampler2D u_image1;uniform float u_emissive_texture_available; #endif uniform float u_far_z_cutoff;in vec2 v_pos0; #ifndef FOG uniform highp vec3 u_frustum_tl;uniform highp vec3 u_frustum_tr;uniform highp vec3 u_frustum_br;uniform highp vec3 u_frustum_bl;uniform highp vec3 u_globe_pos;uniform highp float u_globe_radius;uniform vec2 u_viewport; #endif void main() {vec4 color; #ifdef CUSTOM_ANTIALIASING highp vec2 uv=fragcoord_to_bottom_left_uv(gl_FragCoord.xy,u_viewport);highp vec3 ray_dir=mix( mix(u_frustum_tl,u_frustum_tr,uv.x),mix(u_frustum_bl,u_frustum_br,uv.x),1.0-uv.y);highp vec3 dir=normalize(ray_dir);highp vec3 closest_point=dot(u_globe_pos,dir)*dir;highp float norm_dist_from_center=1.0-length(closest_point-u_globe_pos)/u_globe_radius;const float antialias_pixel=2.0;highp float antialias_factor=antialias_pixel*fwidth(norm_dist_from_center);highp float antialias=smoothstep(0.0,antialias_factor,norm_dist_from_center);vec4 raster=texture(u_image0,v_pos0); #ifdef LIGHTING_3D_MODE #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS #ifdef USE_MRT1_RGBA vec4 emissive_premult=vec4(0.0);if (u_emissive_texture_available > 0.5) {emissive_premult=texture(u_image1,v_pos0);}vec3 unlit_base=raster.rgb-emissive_premult.rgb;raster.rgb=apply_lighting_ground(vec4(unlit_base,1.0)).rgb+emissive_premult.rgb;color=vec4(clamp(raster.rgb,vec3(0),vec3(1))*antialias,antialias); #else float emissive_strength=raster.a;if (u_emissive_texture_available > 0.5) {emissive_strength=texture(u_image1,v_pos0).r;}raster=apply_lighting_with_emission_ground(raster,emissive_strength);color=vec4(clamp(raster.rgb,vec3(0),vec3(1))*antialias,antialias); #endif #else raster=apply_lighting_ground(raster);color=vec4(raster.rgb*antialias,raster.a*antialias); #endif #else color=vec4(raster.rgb*antialias,raster.a*antialias); #endif #else color=texture(u_image0,v_pos0); #ifdef LIGHTING_3D_MODE #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS #ifdef USE_MRT1_RGBA vec4 emissive_premult=vec4(0.0);if (u_emissive_texture_available > 0.5) {emissive_premult=texture(u_image1,v_pos0);}vec3 unlit_base=color.rgb-emissive_premult.rgb;color.rgb=apply_lighting_ground(vec4(unlit_base,1.0)).rgb+emissive_premult.rgb;color.a=1.0; #else float emissive_strength=color.a;if (u_emissive_texture_available > 0.5) {emissive_strength=texture(u_image1,v_pos0).r;}color=apply_lighting_with_emission_ground(color,emissive_strength);color.a=1.0; #endif #else color=apply_lighting_ground(color); #endif #endif #endif #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #endif color*=1.0-step(u_far_z_cutoff,1.0/gl_FragCoord.w);glFragColor=color; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_terrain.vertex.glsl" uniform mat4 u_proj_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix; #ifndef GLOBE_POLES uniform mat4 u_merc_matrix; #endif uniform float u_zoom_transition;uniform vec2 u_merc_center; #ifndef GLOBE_POLES uniform mat3 u_grid_matrix; #endif uniform float u_skirt_height; #ifdef GLOBE_POLES in vec3 a_globe_pos;in vec2 a_uv; #else in ivec2 a_pos; #endif out vec2 v_pos0;void main() { #ifdef GLOBE_POLES vec3 globe_pos=a_globe_pos;vec2 uv=a_uv; #else float tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float uvY=mercatorY*tiles-idy;float mercatorX=mercatorXfromLng(latLng[1]);float uvX=mercatorX*tiles-idx;vec3 globe_pos=latLngToECEF(latLng.xy);vec2 merc_pos=vec2(mercatorX,mercatorY);vec2 uv=vec2(uvX,uvY); #endif v_pos0=bottom_left_to_native_uv(uv);vec2 tile_pos=uv*EXTENT;vec3 globe_derived_up_vector=normalize(globe_pos)*u_tile_up_scale; #ifdef GLOBE_POLES vec3 up_vector=globe_derived_up_vector; #else vec3 up_vector=elevationVector(tile_pos); #endif float height=elevation(tile_pos);globe_pos+=up_vector*height; #ifndef GLOBE_POLES globe_pos-=globe_derived_up_vector*u_skirt_height*decomposed_pos_and_skirt.z; #endif #ifdef GLOBE_POLES vec4 interpolated_pos=u_globe_matrix*vec4(globe_pos,1.0); #else vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {merc_world_pos=vec4(merc_pos,height-u_skirt_height*decomposed_pos_and_skirt.z,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition),1.0); #endif gl_Position=u_proj_matrix*interpolated_pos; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif }`)};(function(_){lm=_;for(const f of m0.splice(0))f()})({create:(_,f)=>new Xw(_,f)}),Object.assign(a2,{terrainRaster:_=>({u_matrix:new l.aa(_),u_image0:new l.b6(_),u_image1:new l.b6(_),u_skirt_height:new l.a9(_),u_ground_shadow_factor:new l.ab(_),u_emissive_texture_available:new l.a9(_)}),globeRaster:_=>({u_proj_matrix:new l.aa(_),u_globe_matrix:new l.aa(_),u_normalize_matrix:new l.aa(_),u_merc_matrix:new l.aa(_),u_zoom_transition:new l.a9(_),u_merc_center:new l.a8(_),u_image0:new l.b6(_),u_image1:new l.b6(_),u_grid_matrix:new l.b8(_),u_skirt_height:new l.a9(_),u_far_z_cutoff:new l.a9(_),u_frustum_tl:new l.ab(_),u_frustum_tr:new l.ab(_),u_frustum_br:new l.ab(_),u_frustum_bl:new l.ab(_),u_globe_pos:new l.ab(_),u_globe_radius:new l.a9(_),u_viewport:new l.a8(_),u_emissive_texture_available:new l.a9(_)})});const ZB={shaders:YB};class g0 extends l.E{constructor(f,y,w,k){super(),this.id=f,this.dispatcher=w,this.setEventedParent(k),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options={type:"raster",...y},Object.assign(this,l.cx(y,["url","scheme","tileSize"]))}load(f){this._loaded=!1,this.fire(new l.i("dataloading",{dataType:"source"}));const y=this.map.getWorldview(),w=(R,M)=>{this._tileJSONRequest=null,this._loaded=!0,R?this.fire(new l.h(R)):M&&(Object.assign(this,M),M.raster_layers&&(this.rasterLayers=M.raster_layers,this.rasterLayerIds=this.rasterLayers.map(z=>z.id)),this.tileBounds=new l.cC(M),l.cD(M.tiles),this.fire(new l.i("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new l.i("data",{dataType:"source",sourceDataType:"content"}))),f&&f(R)};this.provider=typeof this._options.provider=="string"?this._options.provider:void 0,this._tileProvider=void 0;const k=l.cy(this._options);return k instanceof Error?(this._loaded=!0,this.fire(new l.h(k)),void(f&&f())):this.provider&&!k?(this._loaded=!0,this.fire(new l.h(new Error(`TileProvider "${this.provider}" is not registered`))),void(f&&f())):void(this._tileJSONRequest=k?this.loadTileJSONWithProvider(k,w):l.cz(this._options,this.map._requestManager,null,y,w))}loadTileJSONWithProvider(f,y){this.provider=f.name;const w=new AbortController;return(async()=>{const{request:k,options:R}=await l.cE(this._options,this.map._requestManager,w.signal);if(w.signal.aborted)return;const M=await l.cF(f.name,f.url);if(w.signal.aborted)return;const z=new M(R);let V=null;if(z.load&&k&&(V=await z.load({request:k}),w.signal.aborted))return;this._tileProvider=z;const H=l.cG(this._options,V,this.map._requestManager);H instanceof Error?y(H):y(null,H)})().catch(k=>{w.signal.aborted||y(new Error(`Could not load tile provider ${f.name}`,{cause:k}))}),{cancel:()=>w.abort()}}loaded(){return this._loaded}onAdd(f){this.map=f,this.load()}reload(){this.cancelTileJSONRequest();const f=l.m(this.id,this.scope);this.load(()=>this.map.style.clearSource(f))}setTiles(f){return this._options.tiles=f,this.reload(),this}setUrl(f){return this.url=f,this._options.url=f,this.reload(),this}onRemove(f){this.cancelTileJSONRequest()}serialize(){return{...this._options}}hasTile(f){return!this.tileBounds||this.tileBounds.contains(f.canonical)}async loadTile(f,y){const w=l.e.devicePixelRatio>=2,k=this.map._requestManager.normalizeTileURL(f.tileID.canonical.url(this.tiles,this.scheme),w,this.tileSize),R=new AbortController;if(f.request=R,this._tileProvider)this.loadTileWithProvider(f,this._tileProvider,k,R,y);else try{const M=await this.map._requestManager.transformRequest(k,l.R.Tile,R.signal);if(R.signal.aborted)return delete f.request,y(null);const{data:z,headers:V}=await l.a(M,R.signal);if(delete f.request,f.aborted)return y(null);const H=l.cA(V);this.map._refreshExpiredTiles&&f.setExpiryData(H),f.setTexture(z,this.map.painter),f.state="loaded",l.cB(this.dispatcher),y(null)}catch(M){if(delete f.request,R.signal.aborted)return y(null);f.state="errored",y(M)}}async loadTileWithProvider(f,y,w,k,R){const{z:M,x:z,y:V}=f.tileID.canonical;try{const H=await this.map._requestManager.transformRequest(w,l.R.Tile,k.signal);if(k.signal.aborted)return R(null);const Y=await y.loadTile({z:M,x:z,y:V},{request:H,signal:k.signal});if(k.signal.aborted)return R(null);if(Y==null){const ne=new Error("Tile not found");return ne.status=404,f.state="errored",R(ne)}if(Y.data==null)return f.state="loaded",R(null);const te=Y.data instanceof ImageBitmap?Y.data:await createImageBitmap(new Blob([Y.data]));if(k.signal.aborted)return R(null);f.setTexture(te,this.map.painter),f.state="loaded",this.map._refreshExpiredTiles&&f.setExpiryData({cacheControl:Y.cacheControl,expires:Y.expires}),R(null)}catch(H){if(k.signal.aborted)return R(null);f.state="errored",R(new Error(`Could not load tile from ${w}`,{cause:H}))}finally{delete f.request}}abortTile(f,y){f.request&&(f.request.abort(),delete f.request),y&&y()}unloadTile(f,y){f.texture&&f.texture instanceof l.T?(f.destroy(!1),f.texture&&f.texture instanceof l.T&&this.map.painter.saveTileTexture(f.texture)):f.destroy(),y&&y()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function RN([_,f],y,w,{scaled:k=!0}={}){const{tileSize:R,buffer:M}=w,{x:z,y:V,z:H}=y;if(!isFinite(z)||!isFinite(V)||!isFinite(H))throw new Error("Invalid MRT header");const Y=2**H,te=Y*l.ad(_),ne=Y*l.ae(f);return function([le,me],fe,{scaled:Se=!0}={}){if(!fe)throw new Error("bandView is undefined");const{data:Me,tileSize:qe,buffer:Ne,offset:We,scale:ct,dimension:it}=fe;if(le<-Ne||le>qe+Ne||me<-Ne||me>qe+Ne)throw new Error(`Point (${le}, ${me}) out of bounds for tileSize=${qe}, buffer=${Ne}`);const pt=(me+Ne)*(qe+2*Ne)+(le+Ne);if(new Uint32Array(Me.buffer)[pt]===4294967295)return null;let dt=[];dt=Se?[]:new fe.data.constructor(it);for(let mt=0;mt=ne||te<0||te>=ne)throw new t1(`Invalid overzoom, ${V}/${M}/${z} is not a child of ${R}/${w}/${k}.`);const le=0|Math.log2(_),me=Math.min(H,le),fe=H-me,Se=_>>me;return{offset:[(Y>>fe)*Se,(te>>fe)*Se],tileSize:Se,deltaZ:H}}l.cK.setPbf(l.d);class LN extends yf{constructor(f,y,w,k,R){super(f,y,w,k,R),this._workQueuePerLayer=new Map,this._fetchQueuePerLayer=new Map,this._taskQueue=new Map,this._isHeaderLoaded=!1,this._isLoadInProgress=!1,this.textureDescriptorPerLayer=new Map,this.texturePerLayer=new Map,this.parentTile=null,this.overzoomCoordsPerLayer=null}getLayers(){return this._mrt?Object.values(this._mrt.layers):[]}getLayer(f){return this._mrt&&this._mrt.getLayer(f)}setTexturePerLayer(f,y,w){const k=w.context,R=k.gl;let M=this.texturePerLayer.get(f)||w.getTileTexture(y.width);M&&M instanceof l.T?M.update(y,{premultiply:!1}):(M=new l.T(k,y,R.RGBA8,{premultiply:!1}),M.bind(R.LINEAR,R.CLAMP_TO_EDGE)),this.texturePerLayer.has(f)||this.texturePerLayer.set(f,M)}flushQueues(f){const y=this._workQueuePerLayer.get(f)||[],w=this._fetchQueuePerLayer.get(f)||[];for(;y.length;)y.pop()();for(;w.length;)w.pop()()}flushAllQueues(){for(const f of this._workQueuePerLayer.keys()){const y=this._workQueuePerLayer.get(f)||[];for(;y.length;)y.pop()()}for(const f of this._fetchQueuePerLayer.keys()){const y=this._fetchQueuePerLayer.get(f)||[];for(;y.length;)y.pop()()}}fetchHeader(f=16384,y){const w=this._mrt=new l.cK(30),k={...this.requestParams,headers:{Range:"bytes=0-"+(f-1)}};this.entireBuffer=null;const R=new AbortController;return this.request=R,l.n(k,R.signal).then(({data:M,headers:z})=>{try{const V=w.getHeaderLength(M);if(V>f)return void(this.request=this.fetchHeader(V,y));w.parseHeader(M),this._isHeaderLoaded=!0;let H=0;for(const Y of Object.values(w.layers))H=Math.max(H,Y.dataIndex.at(-1).lastByte);M.byteLength>=H&&(this.entireBuffer=M),y(null,this.entireBuffer||M,z)}catch(V){y(V)}}).catch(M=>{R.signal.aborted||y(M)}),this.request}fetchBandForRender(f,y,w,k){this.fetchBand(f,y,w,R=>{if(R)return void k(R);this.updateTextureDescriptor(f,y,w);const M=this.textureDescriptorPerLayer.get(y);k(null,M?M.img:null)})}fetchBand(f,y,w,k){const R=this._mrt;if(!this._isHeaderLoaded||!R)return void k(new Error("Tile header is not ready"));if(this.parentTile&&this.overzoomCoordsPerLayer)return void k(null,null);const M=this.actor;if(!M)return void k(new Error("Can't fetch tile band without an actor"));let z;const V=l.m(String(w),l.m(this.tileID.key,f));let H=this._taskQueue.get(V);H?H.add(k):(H=new Set,H.add(k),this._taskQueue.set(V,H));const Y=(me,fe)=>{z.complete(me,fe),me?k(me):(H.forEach(Se=>Se(null,fe)),this._taskQueue.delete(V))},te=(me,fe)=>{if(me)return k(me);let Se,Me=!1;if(y!==null){const Ne=this._workQueuePerLayer.get(y)||[];Ne.push(()=>{Me=!0,Se&&Se.abort(),z.cancel()}),this._workQueuePerLayer.has(y)||this._workQueuePerLayer.set(y,Ne)}const qe=()=>{Me||(Se=M.sendCancelable("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:fe,task:z},{},Y))};this.workerReady!==void 0?this.workerReady.then(qe).catch(Ne=>k(Ne)):qe()};let ne;try{ne=R.getLayer(f)}catch(me){if(this.parentTile&&this.overzoomCoordsPerLayer)return void k(new Error(`Layer '${f}' not found in parent tile MRT`));if(this.state==="reloading")return;throw me}if(!ne)return void k(new Error(`Unknown sourceLayer "${f}"`));if(ne.hasDataForBand(w))return H.forEach(me=>me(null,null)),void this._taskQueue.delete(V);const le=ne.getDataRange([w]);if(z=R.createDecodingTask(le),!z||z.tasks.length)if(y!==null&&this.flushQueues(y),this.entireBuffer)te(null,this.entireBuffer.slice(le.firstByte,le.lastByte+1));else{const me={...this.requestParams,headers:{Range:`bytes=${le.firstByte}-${le.lastByte}`}},fe=new AbortController;if(l.n(me,fe.signal).then(({data:Se})=>te(null,Se)).catch(Se=>{fe.signal.aborted||te(Se)}),y!==null){const Se=this._fetchQueuePerLayer.get(y)||[];Se.push(()=>{fe.abort(),z.cancel()}),this._fetchQueuePerLayer.has(y)||this._fetchQueuePerLayer.set(y,Se)}}}updateNeeded(f,y){return(!this.textureDescriptorPerLayer.get(f)||this.textureDescriptorPerLayer.get(f).band!==y||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(f,y,w){if(!this._mrt)return;let k;try{k=this._mrt.getLayer(f)}catch{return}if(!k||!k.hasBand(w)||!k.hasDataForBand(w))return;let{bytes:R,tileSize:M,buffer:z,offset:V,scale:H}=k.getBandView(w);if(this.parentTile&&this.overzoomCoordsPerLayer){const le=this.overzoomCoordsPerLayer.get(f);le&&(R=this.cropBandData(R,M,z,le),M=le.tileSize)}const Y=M+2*z,te=new l.b({width:Y,height:Y},R),ne=this.texturePerLayer.get(y);ne&&ne instanceof l.T&&ne.update(te,{premultiply:!1}),this.textureDescriptorPerLayer.set(y,{layer:f,band:w,img:te,buffer:z,offset:V,tileSize:M,format:k.pixelFormat,mix:[H,256*H,65536*H,16777216*H]})}cropBandData(f,y,w,k){const{offset:R,tileSize:M}=k,z=y+2*w,V=M+2*w;return function(H,Y,te,ne){const le=function(We){if(We instanceof Uint8Array)return"uint8";if(We instanceof Uint16Array)return"uint16";if(We instanceof Uint32Array)return"uint32";throw new Error("Invalid array type")}(H),me=r1[le];if(!me)throw new Error(`Invalid data type "${le}"`);const fe=Y[2]*Y[3],Se=Y[1]*fe,Me=te[2]*te[3],qe=te[1]*Me,Ne=new me(qe*te[0]);for(let We=0;Wenew LN(_,f,y,w,k);const DN={RasterArrayTileSource:class extends g0{get partial(){return!this.map.style.imageManager.hasImageProviderForSource(this.id,this.scope)}constructor(_,f,y,w){super(_,f,y,w),this.type="raster-array",this.maxzoom=f.maxzoom!==void 0?f.maxzoom:22,this._loadTilePending={},this._loadTileLoaded={},this._pendingParentWaiters=new Map,this._options={type:"raster-array",...f}}onAdd(_){super.onAdd(_);const f=y=>{y.dataType==="source"&&y.sourceDataType==="metadata"&&(this.off("data",f),this._dataMaxzoom===void 0&&(this._dataMaxzoom=this.maxzoom))};this.on("data",f)}getDataMaxzoom(){return this._dataMaxzoom}collectOverzoomParentTileIDs(_,f){const y=[];for(const k of _.values()){const R=k.parentTile;R&&_.has(R.tileID.key)&&y.push(R.tileID)}const w=this._dataMaxzoom;if(w!==void 0)for(const k of f){if(k.canonical.z<=w)continue;const R=k.scaledTo(w);_.has(R.key)&&y.push(R)}return y}_narrowDataMaxzoom(_){const f=Math.max(this.minzoom,_-1);(this._dataMaxzoom===void 0||f0}_waitForParent(_,f){if(this._isParentReady(_))return void f(null);if(_.state==="errored")return void f(new Error("Parent tile failed to load"));const y=this._pendingParentWaiters.get(_.uid);if(y)return void y.push(f);this._pendingParentWaiters.set(_.uid,[f]);const w=k=>{if(k.dataType!=="source"||k.tile!==_)return;const R=this._isParentReady(_);if(!R&&_.state!=="errored")return;this.off("data",w);const M=this._pendingParentWaiters.get(_.uid)||[];this._pendingParentWaiters.delete(_.uid);const z=R?null:new Error("Parent tile failed to load");for(const V of M)V(z)};this.on("data",w)}triggerRepaint(_){const f=this.map.painter._terrain,y=this.map.style.getSourceCache(this.id);f&&f.enabled&&y&&f._clearRenderCacheForTile(y.id,_.tileID),this.map.triggerRepaint()}_setupOverzoomTile(_,f){const y=this._dataMaxzoom!==void 0?this._dataMaxzoom:this.maxzoom,w=this.map.style.getSourceCache(this.id);if(!w)return void f(new Error("Source cache not found"));_._isLoadInProgress=!0;const k=_.tileID.scaledTo(y);let R=w.getTile(k);for(;R&&R.parentTile;)R=R.parentTile;R||(R=w._addTile(k));const M=z=>{_._isLoadInProgress=!1,f(z)};this._waitForParent(R,z=>{if(z||!_.setupOverzoom(R))return _.state="errored",void M(z||new Error("Parent tile setup failed"));_.state="loaded",M(null)})}async loadTile(_,f){const y=_.tileID.canonical.z>(this._dataMaxzoom!==void 0?this._dataMaxzoom:this.maxzoom);if(_.state==="loaded"||_._isLoadInProgress)return void f(null);if(y)return void this._setupOverzoomTile(_,f);const w=this.map._requestManager.normalizeTileURL(_.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);_.source=this.id,_.scope=this.scope,this._workerReady===void 0&&(this._workerReady=this.dispatcher.send("ensureRasterArraySource",void 0).then(()=>{}),this._workerReady.catch(()=>{})),_.workerReady=this._workerReady,_.actor||(_.actor=this.dispatcher.getActor());const k=new AbortController;_.request=k;const R=(M,z,V)=>{if(delete _.request,_.aborted)return f(null);if(M)return(M.status===404||typeof M.message=="string"&&M.message.includes("Not Found"))&&(this._narrowDataMaxzoom(_.tileID.canonical.z),this._dataMaxzoom!==void 0&&_.tileID.canonical.z>this._dataMaxzoom)?void this._setupOverzoomTile(_,f):(_.state="errored",f(M));if(this.map._refreshExpiredTiles&&z&&_.setExpiryData(l.cA(V)),this.partial&&_.state!=="expired")_.state="empty";else if(!this.partial){if(!z)return f(null);_.state="loaded",_._isHeaderLoaded=!0,_._mrt=z}f(null)};try{const M=await this.map._requestManager.transformRequest(w,l.R.Tile,k.signal);if(k.signal.aborted)return f(null);_.requestParams=M;const z={request:M,uid:_.uid,tileID:_.tileID,type:this.type,source:this.id,scope:this.scope,partial:this.partial};_.request=this.partial?_.fetchHeader(void 0,(V,H,Y)=>{R(V,H,Y)}):_.actor.sendCancelable("loadTile",z,{},(V,H)=>V?R(V):H?void R(null,H.mrt,H.headers):R(null,null))}catch(M){if(k.signal.aborted)return f(null);_.state="errored",f(M)}}abortTile(_){_.request&&(_.request.abort(),delete _.request),_.actor&&_.actor.notify("abortTile",{uid:_.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(_,f){const y=_.texturePerLayer;if(_.flushAllQueues(),y.size){_.destroy(!1);for(const w of y.values())this.map.painter.saveTileTexture(w)}else _.destroy()}prepareTile(_,f,y,w){_.tileID.canonical.z>(this._dataMaxzoom!==void 0?this._dataMaxzoom:this.maxzoom)&&(!_.parentTile||!_.overzoomCoordsPerLayer)||_._isHeaderLoaded&&(_.state!=="empty"&&(_.state="reloading"),_.fetchBandForRender(f,y,w,(k,R)=>{k?(_.state="errored",this.fire(new l.h(k))):R&&(_._isHeaderLoaded=!0,_.setTexturePerLayer(y,R,this.map.painter),_.state="loaded"),this.triggerRepaint(_)}))}getInitialBand(_){if(!this.rasterLayers)return 0;const f=this.rasterLayers.find(({id:k})=>k===_),y=f&&f.fields,w=y&&y.bands&&y.bands;return w?w[0]:0}getTextureDescriptor(_,f,y){if(!_)return;const w=f.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!w)return;let k=null;f instanceof l.cH?k=f.paint.get("raster-array-band"):f instanceof l.cI&&(k=f.paint.get("raster-particle-array-band"));const R=k||this.getInitialBand(w);return R==null||!_.textureDescriptorPerLayer.get(f.id)||_.updateNeeded(f.id,R)&&!y?void 0:{..._.textureDescriptorPerLayer.get(f.id),texture:_.texturePerLayer.get(f.id)}}getImages(_,f){const y=new Map;for(const w of _)for(const k of f){const[R,M]=k.split("/"),z=w.getLayer(R);if(!z||!z.hasBand(M)||!z.hasDataForBand(M))continue;const{bytes:V,tileSize:H,buffer:Y}=z.getBandView(M),te=H+2*Y,ne={data:new l.b({width:te,height:te},V),pixelRatio:2,sdf:!1,usvg:!1,version:0};y.set(k,ne)}return y}queryRasterArrayValueByBandId(_,f,y){const w=f._mrt;return new Promise(k=>{const R={},M=new Set;for(const[z,V]of Object.entries(w.layers)){if(y.layerName&&z!==y.layerName)continue;const H={};R[z]=H;for(const{bands:Y}of V.dataIndex)for(const te of Y)y.bands&&!y.bands.includes(te)||(M.add(l.m(z,te)),f.fetchBand(z,null,te,ne=>{l.e.frame(()=>{H[te]=ne?null:RN([_.lng,_.lat],w,V.getBandView(te)),M.delete(l.m(z,te)),M.size===0&&k(R)})}))}M.size===0&&k(R)})}_loadTileForQuery(_){if(this._loadTileLoaded[_.uid])return Promise.resolve(_._mrt);if(_.uid in this._loadTilePending)return this._loadTilePending[_.uid];const f=this._fetchTileForQuery(_);return this._loadTilePending[_.uid]=f,f}async _fetchTileForQuery(_){const f=this.map._requestManager.normalizeTileURL(_.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);try{const y={request:await this.map._requestManager.transformRequest(f,l.R.Tile),uid:_.uid,tileID:_.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},w=await _.actor.send("loadTile",y);if(!w)return null;const k=w.mrt;return this.map._refreshExpiredTiles&&_.setExpiryData(l.cA(w.headers)),_._mrt=k,_._isHeaderLoaded=!0,_.state="loaded",this._loadTileLoaded[_.uid]=!0,k}finally{delete this._loadTilePending[_.uid]}}async queryRasterArrayValueByAllBands(_,f,y){return await this._loadTileForQuery(f)?this.queryRasterArrayValueByBandId(_,f,y):null}queryRasterArrayValue(_,f){const y=l.cJ.convert(_),w=this.findLoadedParent(y);return w&&w._mrt?f.bands||!this.partial?this.queryRasterArrayValueByBandId(y,w,f):this.queryRasterArrayValueByAllBands(y,w,f):Promise.resolve(null)}findLoadedParent(_){const f=l.b$.fromLngLat(_,this.map.transform.tileSize),y=this.maxzoom+1,w=1<=w||M<0||M>=w)return null;const z=this.map.style.getSourceCache(this.id),V=new l.bZ(y,k,y,R,M);return z.findLoadedParent(V,this.minzoom)}},resolveRasterMask:function(_,f){const y=f.paint.get("raster-mask");if(!y)return null;if(f.paint.get("raster-elevation")>0)return l.w(`raster-mask: not supported together with "raster-elevation" (layer "${f.id}"); the raster layer is not drawn.`),"unavailable";const w=_.style,k=f.paint.get("raster-mask-import")||void 0,R=!(!_.terrain||!_.terrain.enabled),M=[];for(const z of function(V,H,Y,te){if(!te){const Me=V.getLayer(l.m(Y,H.scope));return Me?[Me]:(l.w(`raster-mask: no layer found with id "${Y}" (referenced by layer "${H.id}"); the raster layer is not drawn.`),[])}const ne=V.getFragmentStyle(H.scope),le=ne?ne.getFragmentStyle(te):void 0;if(!le)return l.w(`raster-mask: no import found with id "${te}" (referenced by layer "${H.id}"); the raster layer is not drawn.`),[];if(!le._loaded||!le.stylesheet)return[];const me=le.stylesheet.featuresets,fe=me?me[Y]:void 0;if(!fe)return l.w(`raster-mask: import "${te}" has no featureset "${Y}" (referenced by layer "${H.id}"); the raster layer is not drawn.`),[];const Se=new Set;for(const Me of fe.selectors){const qe=le.getOwnLayer(Me.layer);qe&&Se.add(qe)}return Se.size||l.w(`raster-mask: featureset "${Y}" of import "${te}" selects no layers (referenced by layer "${H.id}"); the raster layer is not drawn.`),Array.from(Se)}(w,f,y,k)){if(z.type!=="fill"){l.w(`raster-mask: layer "${z.id}" is of type "${z.type}"; only "fill" layers are used as a mask (referenced by layer "${f.id}").`);continue}if(z.isHidden(_.transform.zoom)){l.w(`raster-mask: layer "${z.id}" is hidden at the current zoom or by its visibility, so it is not part of the mask of layer "${f.id}". Use "fill-opacity": 0 to keep a mask layer invisible.`);continue}if(z.is3D(R)){l.w(`raster-mask: elevated fill layer "${z.id}" is not supported as a mask (referenced by layer "${f.id}").`);continue}const V=w.getLayerSourceCache(z);V?M.push({layer:z,sourceCache:V}):l.w(`raster-mask: no source found for layer "${z.id}" (referenced by layer "${f.id}").`)}return M.length?{sources:M,inside:f.paint.get("raster-mask-mode")!=="clip-path-exclude"}:"unavailable"},renderRasterMask:function(_,f){const y=_.context.gl,w=new l.a4({func:y.ALWAYS,mask:0},l.cc,l.cc,y.KEEP,y.KEEP,y.REPLACE),k=new l.a4({func:y.ALWAYS,mask:0},0,l.cc,y.KEEP,y.KEEP,y.REPLACE);x0(_,l.cc);const R=[];for(const{layer:M,sourceCache:z}of f.sources)for(const V of y0(_,z)){const H=z.getTile(V);e1(H,M)&&R.push({layer:M,tile:H,coord:V})}if(f.inside)for(const{layer:M,tile:z,coord:V}of R){const H=z.getBucket(M);H&&o2(_,H,V,k)}else{for(const{tile:M,coord:z}of R)XB(_,M,z,k);for(const{layer:M,tile:z,coord:V}of R){const H=z.getBucket(M);H&&o2(_,H,V,w)}}},clearRasterMask:function(_){x0(_,0)},stencilModeWithRasterMask:function(_,f){const y=_.context.gl;return f&&f!==l.a4.disabled&&f.test.mask!==0?f:new l.a4({func:y.EQUAL,mask:l.cc},0,0,y.KEEP,y.KEEP,y.KEEP)}},cm=DN;async function Bg(){return Promise.resolve()}class n1{constructor(f,y,w){this.screenBounds=f,this.cameraPoint=w.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=y,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,w)}static createFromScreenPoints(f,y){let w,k;if(f instanceof l.P||typeof f[0]=="number"){const R=l.P.convert(f);w=[R],k=y.isPointAboveHorizon(R)}else{const R=l.P.convert(f[0]),M=l.P.convert(f[1]),z=R.add(M)._div(2);w=[R,M],k=l.cL(R,M).every(V=>y.isPointAboveHorizon(V))&&y.isPointAboveHorizon(z)}return new n1(w,k,y)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(f){return l.cL(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],f)}bufferedCameraGeometry(f){const y=this.screenBounds[0],w=this.screenBounds.length===1?this.screenBounds[0].add(new l.P(1,1)):this.screenBounds[1],k=l.cL(y,w,0,!1);return this.cameraPoint.y>w.y&&(this.cameraPoint.x>y.x&&this.cameraPoint.x=w.x?k[2]=this.cameraPoint:this.cameraPoint.x<=y.x&&(k[3]=this.cameraPoint)),l.cM(k,f)}bufferedCameraGeometryGlobe(f){const y=this.screenBounds[0],w=this.screenBounds.length===1?this.screenBounds[0].add(new l.P(1,1)):this.screenBounds[1],k=l.cL(y,w,f),R=this.cameraPoint.clone(),M=+(R.x>y.x)+ +(R.x>w.x);switch(3*(+(R.y>y.y)+ +(R.y>w.y))+M){case 0:k[0]=R,k[4]=R.clone();break;case 1:k.splice(1,0,R);break;case 2:k[1]=R;break;case 3:k.splice(4,0,R);break;case 5:k.splice(2,0,R);break;case 6:k[3]=R;break;case 7:k.splice(3,0,R);break;case 8:k[2]=R}return k}containsTile(f,y,w,k=0,R){const M=Math.max(f.queryPadding,f.evaluateQueryRenderedFeaturePadding())/y._pixelsPerMercatorPixel+1,z=w?this._bufferedCameraMercator(M,y):this._bufferedScreenMercator(M,y);let V=f.tileID.wrap+(z.unwrapped?k:0);const H=z.polygon.map(Se=>l.cN(f.tileTransform,Se,V));if(!l.cO(H,0,0,l.ac,l.ac))return;V=f.tileID.wrap+(this.screenGeometryMercator.unwrapped?k:0);const Y=this.screenGeometryMercator.polygon.map(Se=>l.cP(f.tileTransform,Se,V)),te=Y.map(Se=>new l.P(Se[0],Se[1])),ne=l.cP(f.tileTransform,R,V),le=Y.map(Se=>{const Me=l.cQ(Se,Se,ne);return l.cg(Me,Me),new l.cR(ne,Me)}),me=l.ck(f,1,y.zoom)*y._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:te,tilespaceRays:le,bufferedTilespaceGeometry:H,bufferedTilespaceBounds:(fe=l.cS(H),fe.min.x=l.bb(fe.min.x,0,l.ac),fe.min.y=l.bb(fe.min.y,0,l.ac),fe.max.x=l.bb(fe.max.x,0,l.ac),fe.max.y=l.bb(fe.max.y,0,l.ac),fe),tile:f,tileID:f.tileID,pixelToTileUnitsFactor:me};var fe}_bufferedScreenMercator(f,y){const w=MN(f);if(this._screenRaycastCache[w])return this._screenRaycastCache[w];{let k;return k=y.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(f),y):{polygon:this.bufferedScreenGeometry(f).map(R=>y.pointCoordinate3D(R)),unwrapped:!0},this._screenRaycastCache[w]=k,k}}_bufferedCameraMercator(f,y){const w=MN(f);if(this._cameraRaycastCache[w])return this._cameraRaycastCache[w];{let k;return k=y.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(f),y):{polygon:this.bufferedCameraGeometry(f).map(R=>y.pointCoordinate3D(R)),unwrapped:!0},this._cameraRaycastCache[w]=k,k}}_projectAndResample(f,y){const w=function(R,M){const z=l.a1([],M.pixelMatrix,M.globeMatrix),V=[0,-l.cT,0,1],H=[0,l.cT,0,1],Y=[0,0,0,1];l.cd(V,V,z),l.cd(H,H,z),l.cd(Y,Y,z);const te=new l.P(V[0]/V[3],V[1]/V[3]),ne=new l.P(H[0]/H[3],H[1]/H[3]),le=l.cU(R,te)&&V[3]1?l2(R.slice(0,Se),M):[],Ne=Senew l.P(_0(dt.x),dt.y)),Ne=Ne.map(dt=>new l.P(_0(dt.x),dt.y));const We=[...qe];We.length===0&&We.push(Ne.at(-1));const ct=We.at(-1),it=l.aw(ct.y,(Ne.length===0?qe[0]:Ne[0]).y,Me);let pt;return pt=le?[new l.P(0,it),new l.P(0,0),new l.P(1,0),new l.P(1,it)]:[new l.P(1,it),new l.P(1,1),new l.P(0,1),new l.P(0,it)],We.push(...pt),Ne.length===0?We.push(qe[0]):We.push(...Ne),{polygon:We.map(dt=>new l.b$(dt.x,dt.y)),unwrapped:!1}}(f,y);if(w)return w;const k=function(R,M){let z=!1,V=-1/0,H=0;for(let te=0;teV&&(V=R[te].x,H=te);for(let te=0;te.5&&(le.x{te.x-=1}),{polygon:R,unwrapped:z}}(l2(f,y).map(R=>new l.P(_0(R.x),R.y)),y);return{polygon:k.polygon.map(R=>new l.b$(R.x,R.y)),unwrapped:k.unwrapped}}}function l2(_,f){return l.cV(_,y=>{const w=f.pointCoordinate3D(y);y.x=w.x,y.y=w.y},1/256)}function _0(_){return _<0?1+_%1:_%1}function MN(_){return 100*_|0}function kx(_,f,y,w,k,R,M,z){const V=[_,f,1,y,w,1,k,R,1],H=[M,z,1],Y=l.d3([],V),[te,ne,le]=l.d2(H,H,Y);return l.d4(V,V,[te,0,0,0,ne,0,0,0,le])}function i1(_,f,y,w,k,R,M,z){const V=function(H,Y,te,ne,le,me,fe,Se){const Me=kx(0,0,1,0,1,1,0,1),qe=kx(H,Y,te,ne,le,me,fe,Se),Ne=l.d3([],Me);return l.d4(qe,qe,Ne)}(_,f,y,w,k,R,M,z);return[V[2]/V[8]/l.ac,V[5]/V[8]/l.ac]}function Ix(_){return[_[0],Math.min(Math.max(_[1],-l.c_),l.c_)]}class md extends l.E{constructor(f,y,w,k){super(),this.id=f,this.dispatcher=w,this.coordinates=y.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.onNorthPole=!1,this.onSouthPole=!1,this.setEventedParent(k),this.options=y,this._dirty=!1}async load(f,y){if(this._loaded=y||!1,this.fire(new l.i("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return f&&(this.coordinates=f),this._loaded=!0,void this._finishLoading();const w=new AbortController;this._imageRequest=w;try{const k=await this.map._requestManager.transformRequest(this.url,l.R.Image,w.signal),{data:R}=await l.a(k,w.signal);this._imageRequest=null,this._loaded=!0,this.image=R,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,f&&(this.coordinates=f),this._finishLoading()}catch(k){if(w.signal.aborted)return;this._imageRequest=null,this._loaded=!0,this.fire(new l.h(k))}}loaded(){return this._loaded}updateImage(f){return f.url?(this._imageRequest&&f.url!==this.options.url&&(this._imageRequest.abort(),this._imageRequest=null),this.options.url=f.url,this.load(f.coordinates,this._loaded),this):this}setTexture(f){if(!(f.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new l.cZ(this.map.painter.context,f.handle),this.width=f.dimensions[0],this.height=f.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new l.i("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(f){this.map=f,this.load()}onRemove(f){this._imageRequest&&(this._imageRequest.abort(),this._imageRequest=null),!this.texture||this.texture instanceof l.cZ||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(f){if(this.coordinates=f,this._boundsArray=void 0,this._unsupportedCoords=!1,!f.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let y=f[0][1],w=f[0][1];for(const R of f)R[1]>w&&(w=R[1]),R[1]l.c_?this.onNorthPole=!0:k<-l.c_&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const R=f.map(l.b$.fromLngLat);this.tileID=function(M){let z=1/0,V=1/0,H=-1/0,Y=-1/0;for(const fe of M)z=Math.min(z,fe.x),V=Math.min(V,fe.y),H=Math.max(H,fe.x),Y=Math.max(Y,fe.y);const te=Math.max(H-z,Y-V),ne=Math.max(0,Math.floor(-Math.log2(te))),le=Math.pow(2,ne);let me=Math.floor((z+H)/2*le);return me>1&&(me-=1),new l.c1(ne,me,Math.floor((V+Y)/2*le))}(R),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new l.i("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof l.cZ||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(f){for(const ct in this.tiles){const it=this.tiles[ct];it.state!=="loaded"&&(it.state="loaded",it.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const y=l.bA(new l.c1(0,0,0),this.map.transform.projection),w=[y.projection.project(this.coordinates[0][0],this.coordinates[0][1]),y.projection.project(this.coordinates[1][0],this.coordinates[1][1]),y.projection.project(this.coordinates[2][0],this.coordinates[2][1]),y.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(ct){const it=ct[1].x-ct[0].x,pt=ct[1].y-ct[0].y,dt=ct[2].x-ct[1].x,mt=ct[2].y-ct[1].y,xt=ct[3].x-ct[2].x,bt=ct[3].y-ct[2].y,Ft=ct[0].x-ct[3].x,Lt=ct[0].y-ct[3].y,Mt=it*mt-dt*pt,or=dt*bt-xt*mt,fr=xt*Lt-Ft*bt,Cr=Ft*pt-it*Lt;return Mt>0&&or>0&&fr>0&&Cr>0||Mt<0&&or<0&&fr<0&&Cr<0}(w))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const k=l.bA(this.tileID,this.map.transform.projection),[R,M,z,V]=this.coordinates.map(ct=>{const it=k.projection.project(ct[0],ct[1]);return l.cN(k,it)._round()});this.perspectiveTransform=i1(R.x,R.y,M.x,M.y,z.x,z.y,V.x,V.y);const H=this._boundsArray=new l.bD;H.emplaceBack(R.x,R.y,0,0),H.emplaceBack(M.x,M.y,l.ac,0),H.emplaceBack(V.x,V.y,0,l.ac),H.emplaceBack(z.x,z.y,l.ac,l.ac),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=f.createVertexBuffer(H,Vn.members),this.boundsSegments=l.aj.simpleSegment(0,0,4,2);const Y=l.d1,te=Y+1,ne=Y+1,le=te*ne,me=Y*Y*2,fe=[],Se=function(ct){return[Ix(ct[0]),Ix(ct[1]),Ix(ct[2]),Ix(ct[3])]}(this.coordinates),[Me,qe,Ne,We]=function(ct){let it=ct[0][0],pt=it,dt=ct[0][1],mt=dt;for(let xt=1;xtpt&&(pt=ct[xt][0]),ct[xt][1]mt&&(mt=ct[xt][1]);return[it,dt,pt-it,mt-dt]}(Se);{const ct=new l.bD,[it,pt,dt,mt]=function(gr){let Pr=gr[0].x,ur=Pr,Xt=gr[0].y,mr=Xt;for(let tn=1;tnur&&(ur=gr[tn].x),gr[tn].ymr&&(mr=gr[tn].y);return[Pr,Xt,ur-Pr,mr-Xt]}(w),xt=gr=>[(gr.x-it)/dt,(gr.y-pt)/mt],[bt,Ft,Lt,Mt]=w.map(xt),or=function(gr,Pr,ur,Xt,mr,tn,kr,vn){const Xr=kx(0,0,1,0,1,1,0,1),ei=kx(gr,Pr,ur,Xt,mr,tn,kr,vn),Rn=l.d3([],ei);return l.d4(Xr,Xr,Rn)}(bt[0],bt[1],Ft[0],Ft[1],Lt[0],Lt[1],Mt[0],Mt[1]);this.elevatedGlobePerspectiveTransform=i1(bt[0],bt[1],Ft[0],Ft[1],Lt[0],Lt[1],Mt[0],Mt[1]);const fr=(gr,Pr)=>{fe.push(gr.lng);const ur=Math.round((gr.lng-Me)/Ne*l.ac),Xt=Math.round((gr.lat-qe)/We*l.ac),mr=xt(Pr),tn=l.d2([],[mr[0],mr[1],1],or),kr=Math.round(tn[0]/tn[2]*l.ac),vn=Math.round(tn[1]/tn[2]*l.ac);ct.emplaceBack(ur,Xt,kr,vn)},Cr=w[3].x-w[0].x,qr=w[3].y-w[0].y,qt=w[2].x-w[1].x,Ut=w[2].y-w[1].y;for(let gr=0;gr{it.emplaceBack(dt,mt,xt);const bt=fe[dt],Ft=fe[mt],Lt=fe[xt],Mt=Math.min(Math.min(bt,Ft),Lt),or=Math.max(Math.max(bt,Ft),Lt)-Mt;or>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=or),ct.push(Mt+or/2)};for(let dt=0;dtMt);xt.sort((Lt,Mt)=>dt[Lt]-dt[Mt]);const bt=[],Ft=new l.ak;for(let Lt=0;Lt{M.segments.push({vertexOffset:0,primitiveOffset:te,vertexLength:y.segments[0].vertexLength,primitiveLength:ne,sortKey:void 0,vaos:{}})},V=.51*this.maxLongitudeTriangleSize;if(Math.abs(w[0]-k)<=V){const te=l.c$(w,0,w.length,k+V);return te===w.length||z(te,l.d0(w,te+1,w.length,k+360-V)-te),M}k{this._tileJSONRequest=null,this._loaded=!0,R?(f&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${f}`),y&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${y}`),this.fire(new l.h(R))):M&&(this._setTileJSON(M),kn.updateCrossSourceElevationGate&&this.map.style&&kn.updateCrossSourceElevationGate(this.map.style),l.cD(M.tiles,this.map._requestManager._customAccessToken),this.fire(new l.i("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new l.i("data",{dataType:"source",sourceDataType:"content"}))),_&&_(R)};this.provider=this._options.provider;const k=l.cy(this._options);return k instanceof Error?(this._loaded=!0,this.fire(new l.h(k)),void(_&&_())):this.provider&&!k?(this._loaded=!0,this.fire(new l.h(new Error(`TileProvider "${this.provider}" is not registered`))),void(_&&_())):void(this._tileJSONRequest=k?this.loadTileJSONWithProvider(k,w):l.cz(this._options,this.map._requestManager,f,y,w))}loadTileJSONWithProvider(_,f){this.provider=_.name;const y=new AbortController;return(async()=>{const{request:w,options:k}=await l.cE(this._options,this.map._requestManager,y.signal);if(y.signal.aborted)return;const R=await this.dispatcher.send("loadTileProvider",{name:_.name,url:_.url,source:this.id,scope:this.scope,type:this.type,options:k,request:w},{signal:y.signal});if(y.signal.aborted)return;const M=R?R.find(V=>V!=null):null,z=l.cG(this._options,M,this.map._requestManager);z instanceof Error?f(z):f(null,z)})().catch(w=>{y.signal.aborted||f(w)}),{cancel:()=>y.abort()}}_setTileJSON(_){if(Object.assign(this,_),this.hasWorldviews=!!_.worldview_options,_.worldview_default&&(this.worldviewDefault=_.worldview_default),_.vector_layers){this.vectorLayers=_.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const f of _.vector_layers)this.vectorLayerIds.push(f.id),_.worldview&&_.worldview[f.source]&&this.localizableLayerIds.add(f.id)}this.tileBounds=new l.cC(_)}loaded(){return this._loaded}hasTile(_){return!this.tileBounds||this.tileBounds.contains(_.canonical)}onAdd(_){this.map=_,this.load()}reload(){this.cancelTileJSONRequest();const _=l.m(this.id,this.scope);this.load(()=>this.map.style.clearSource(_))}setTiles(_){return this._options.tiles=_,this.reload(),this}setUrl(_){return this.url=_,this._options.url=_,this.reload(),this}onRemove(_){this.cancelTileJSONRequest()}serialize(){return{...this._options}}async loadTile(_,f){const y=_.tileID.canonical.url(this.tiles,this.scheme),w=this.map._requestManager.normalizeTileURL(y),k=!_.actor||_.state==="expired";if(!k&&_.state==="loading")return void(_.reloadCallback=f);k&&(_.actor=this._tileWorkers[w]=this._tileWorkers[w]||this.dispatcher.getActor());const R=new AbortController;_.request=R;try{const M=await this.map._requestManager.transformRequest(w,l.R.Tile,R.signal);if(R.signal.aborted)return f(null);this.dispatchTile(_,w,y,M,R,k,f)}catch(M){if(R.signal.aborted)return f(null);f(M)}}dispatchTile(_,f,y,w,k,R,M){const z=this.map.style?this.map.style.getLut(this.scope):null,V=z?{image:z.image.clone()}:null,H=!(!this.map.style||!this.map.style._crossSourceElevationActive),Y=!(!this.map.style||!H),te={request:w,data:void 0,uid:_.uid,tileID:_.tileID,tileZoom:_.tileZoom,zoom:_.tileID.overscaledZ,maxZoom:this.maxzoom,lut:V,tileSize:this.tileSize*_.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:l.e.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,renderSourceType:_.renderSourceType,frcCoverage:(()=>{const le=this.map.painter,me=le?le.frcCoverageFadeRange:null;if(me==null)return null;const fe=le?le.frcCoverageSnapshot:null,Se=this.map.transform.zoom=Math.ceil(me[1]),Ne=fe&&qe?fe.getFullCoverageMask(_.tileID.canonical):null;return{frcMask:qe?Ne??null:null,resolved:Se||fe!=null,polygons:Me&&Me.frcMask!==0?Me.polygons:null,tileZoom:Me&&Me.frcMask!==0?Me.tileId.z:null,sourceLayers:le?le.frcCoverageSourceLayers:["road","structure"]}})(),terrainEnabled:_e(this.map.style,this.map.transform),crossSourceElevationEnabled:Y,elevation:kn.buildElevationRequestParams?kn.buildElevationRequestParams(this.map,_,H):null,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:_.isExtraShadowCaster,tessellationStep:this.map._tessellationStep,scaleFactor:this.map.getScaleFactor(),worldview:this.map.getWorldview()||this.worldviewDefault,indoor:this.map.getIndoorTileOptions(this.id,this.scope)};if(this.hasWorldviews&&l.cX(y)&&(te.localizableLayerIds=this.localizableLayerIds),te.request.collectResourceTiming=this._collectResourceTiming,R)if(this.dispatcher.ready||this.provider)_.request=_.actor.sendCancelable("loadTile",te,{},ne.bind(this));else{const le=l.cY.call({deduped:this._deduped},te,(me,fe)=>{_.aborted||(me||!fe?ne.call(this,me):(te.data={rawData:fe.rawData.slice(0),headers:fe.headers},_.actor&&(_.request=_.actor.sendCancelable("loadTile",te,{},ne.bind(this)))))},!0);k.signal.addEventListener("abort",le,{once:!0})}else _.request=_.actor.sendCancelable("reloadTile",te,{},ne.bind(this));function ne(le,me){return delete _.request,_.aborted?M(null):le?M(le):(me&&me.resourceTiming&&(_.resourceTiming=me.resourceTiming),this.map._refreshExpiredTiles&&me&&_.setExpiryData(l.cA(me.headers)),void(function(){if(_.aborted)return M(null);_.loadVectorData(me,this.map.painter),l.cB(this.dispatcher),M(null,me),_.reloadCallback&&(this.loadTile(_,_.reloadCallback),_.reloadCallback=null)}).call(this))}}abortTile(_){_.request&&(_.request.abort(),delete _.request),_.actor&&_.actor.notify("abortTile",{uid:_.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(_,f){_.actor&&_.actor.notify("removeTile",{uid:_.uid,type:this.type,source:this.id,scope:this.scope}),_.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}},raster:g0,"raster-dem":class extends g0{constructor(_,f,y,w){super(_,f,y,w),this.type="raster-dem",this.maxzoom=22,this._options={type:"raster-dem",...f},this.encoding=f.encoding||"mapbox"}loadTileJSONWithProvider(_,f){this.provider=_.name;const y=new AbortController;return(async()=>{const{request:w,options:k}=await l.cE(this._options,this.map._requestManager,y.signal);if(y.signal.aborted)return;const R=await this.dispatcher.send("loadTileProvider",{name:_.name,url:_.url,source:this.id,scope:this.scope,type:this.type,options:k,request:w},{signal:y.signal});if(y.signal.aborted)return;const M=R?R.find(V=>V!=null):null,z=l.cG(this._options,M,this.map._requestManager);z instanceof Error?f(z):f(null,z)})().catch(w=>{y.signal.aborted||f(w)}),{cancel:()=>y.abort()}}async loadTile(_,f){if(_.actor&&_.state!=="expired")return;const y=this.map._requestManager.normalizeTileURL(_.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);_.actor=this.dispatcher.getActor();const w=new AbortController;_.request=w;try{const k=await this.map._requestManager.transformRequest(y,l.R.Tile,w.signal);if(w.signal.aborted)return f(null);_.request=_.actor.sendCancelable("loadTile",{uid:_.uid,tileID:_.tileID,source:this.id,type:this.type,scope:this.scope,request:k,encoding:this.encoding},{},(function(R,M){return delete _.request,_.aborted?f(null):R?(_.state="errored",f(R)):(M&&(this.map._refreshExpiredTiles&&_.setExpiryData(l.cA(M.headers)),M.borderReady||_.neighboringTiles||(_.neighboringTiles=this._getNeighboringTiles(_.tileID)),_.dem=M.dem,_.dem.onDeserialize(),_.needsHillshadePrepare=!0,_.needsDEMTextureUpload=!0),_.state="loaded",void f(null))}).bind(this))}catch(k){if(w.signal.aborted)return f(null);_.state="errored",f(k)}}abortTile(_,f){_.request&&(_.request.abort(),delete _.request),_.actor&&_.actor.notify("abortTile",{uid:_.uid,type:this.type,source:this.id,scope:this.scope}),f&&f()}_getNeighboringTiles(_){const f=_.canonical,y=Math.pow(2,f.z),w=(f.x-1+y)%y,k=f.x===0?_.wrap-1:_.wrap,R=(f.x+1+y)%y,M=f.x+1===y?_.wrap+1:_.wrap,z={};return z[new l.bZ(_.overscaledZ,k,f.z,w,f.y).key]={backfilled:!1},z[new l.bZ(_.overscaledZ,M,f.z,R,f.y).key]={backfilled:!1},f.y>0&&(z[new l.bZ(_.overscaledZ,k,f.z,w,f.y-1).key]={backfilled:!1},z[new l.bZ(_.overscaledZ,_.wrap,f.z,f.x,f.y-1).key]={backfilled:!1},z[new l.bZ(_.overscaledZ,M,f.z,R,f.y-1).key]={backfilled:!1}),f.y+1f(null,y)).catch(y=>f(y)),this}getClusterChildren(_,f){return this.actor.send("geojson.getClusterChildren",{clusterId:_,source:this.id,scope:this.scope}).then(y=>f(null,y)).catch(y=>f(y)),this}getClusterLeaves(_,f,y,w){return this.actor.send("geojson.getClusterLeaves",{source:this.id,scope:this.scope,clusterId:_,limit:f,offset:y}).then(k=>w(null,k)).catch(k=>w(k)),this}async _updateWorkerData(_=!1){if(this._pendingLoad)return void(this._coalesce=!0);this.fire(new l.i("dataloading",{dataType:"source"})),this._loaded=!1;const f={append:_,...this.workerOptions};f.scope=this.scope;const y=this._data,w=new AbortController;this._pendingLoad=w;try{if(typeof y=="string"){if(f.request=await this.map._requestManager.transformRequest(l.e.resolveURL(y),l.R.Source,w.signal),w.signal.aborted)return this._pendingLoad=null,void(this._coalesce=!1);f.request.collectResourceTiming=this._collectResourceTiming}else f.data=JSON.stringify(y);const k=await this.actor.send(`${this.type}.loadData`,f,{signal:w.signal});this._loaded=!0,this._pendingLoad=null;const R={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&k&&k.resourceTiming&&k.resourceTiming[this.id]&&(R.resourceTiming=k.resourceTiming[this.id]),_&&(this._partialReload=!0),this.fire(new l.i("data",R)),this._partialReload=!1,this._metadataFired=!0}catch(k){if(w.signal.aborted)return this._pendingLoad=null,void(this._coalesce=!1);this._loaded=!0,this._pendingLoad=null,this.fire(new l.h(k))}this._coalesce&&(this._updateWorkerData(_),this._coalesce=!1)}loaded(){return this._loaded}reload(){const _=l.m(this.id,this.scope);this.map.style.clearSource(_),this._updateWorkerData()}loadTile(_,f){const y=_.actor?"reloadTile":"loadTile";_.actor=this.actor;const w=this.map.style?this.map.style.getLut(this.scope):null,k=w?{image:w.image.clone()}:null,R=this._partialReload,M={type:this.type,uid:_.uid,tileID:_.tileID,tileZoom:_.tileZoom,zoom:_.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:k,scope:this.scope,pixelRatio:l.e.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:_.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:R,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};_.request=this.actor.sendCancelable(y,M,{},(z,V)=>R&&!V?(_.state="loaded",f(null)):(delete _.request,_.destroy(!1),_.aborted?f(null):z?f(z):(_.loadVectorData(V,this.map.painter,y==="reloadTile"),void f(null))))}abortTile(_){_.request&&(_.request.abort(),delete _.request),_.aborted=!0}unloadTile(_,f){this.actor.notify("removeTile",{uid:_.uid,type:this.type,source:this.id,scope:this.scope}),_.destroy()}onRemove(_){this._pendingLoad&&this._pendingLoad.abort()}serialize(){return{...this._options,type:this.type,data:this._data}}hasTransition(){return!1}},video:class extends md{constructor(_,f,y,w){super(_,f,y,w),this.roundZoom=!0,this.type="video",this.options=f}async load(){this._loaded=!1;const _=this.options,f=new AbortController;this._imageRequest=f;try{const y=await Promise.all(_.urls.map(async k=>(await this.map._requestManager.transformRequest(k,l.R.Source,f.signal)).url));if(f.signal.aborted)return;this.urls=y;const w=await l.d5(y);if(f.signal.aborted)return;this._imageRequest=null,this.video=w,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading()}catch(y){if(f.signal.aborted)return;this.fire(new l.h(y))}finally{this._loaded=!0}}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(_){if(this.video){const f=this.video.seekable;_f.end(0)?this.fire(new l.h(new _r(`sources.${this.id}`,null,`Playback for this video can be set only between the ${f.start(0)} and ${f.end(0)}-second mark.`))):this.video.currentTime=_}}getVideo(){return this.video}onAdd(_){this.map||(this.map=_,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))}prepare(){if(Object.keys(this.tiles).length===0||this.video.readyState<2)return;const _=this.map.painter.context,f=_.gl;this.texture?this.video.paused||(this.texture.bind(f.LINEAR,f.CLAMP_TO_EDGE),f.texSubImage2D(f.TEXTURE_2D,0,0,0,f.RGBA,f.UNSIGNED_BYTE,this.video)):(this.texture=new l.T(_,this.video,f.RGBA8),this.texture.bind(f.LINEAR,f.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(_)}serialize(){return{type:"video",urls:this.options.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:md,canvas:class extends md{constructor(_,f,y,w){super(_,f,y,w),f.coordinates?Array.isArray(f.coordinates)&&f.coordinates.length===4&&!f.coordinates.some(k=>!Array.isArray(k)||k.length!==2||k.some(R=>typeof R!="number"))||this.fire(new l.h(new _r(`sources.${_}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new l.h(new _r(`sources.${_}`,null,'missing required property "coordinates"'))),f.animate&&typeof f.animate!="boolean"&&this.fire(new l.h(new _r(`sources.${_}`,null,'optional "animate" property must be a boolean value'))),f.canvas?typeof f.canvas=="string"||f.canvas instanceof HTMLCanvasElement||this.fire(new l.h(new _r(`sources.${_}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new l.h(new _r(`sources.${_}`,null,'missing required property "canvas"'))),this.options=f,this.animate=f.animate===void 0||f.animate}async load(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new l.h(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}getCanvas(){return this.canvas}onAdd(_){this.map=_,this.load(),this.canvas&&this.animate&&this.play()}onRemove(_){this.pause()}prepare(){let _=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,_=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,_=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const f=this.map.painter.context;this.texture?!_&&!this._playing||this.texture instanceof l.cZ||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new l.T(f,this.canvas,f.gl.RGBA8,{premultiply:!0}),this._prepareData(f)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const _ of[this.canvas.width,this.canvas.height])if(isNaN(_)||_<=0)return!0;return!1}},custom:class extends l.E{constructor(_,f,y,w){super(),this.id=_,this.type="custom",this._dataType="raster",this._dispatcher=y,this._implementation=f,this.setEventedParent(w),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new l.h(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new l.h(new Error(`Missing loadTile implementation for ${this.id} custom source`)));const k=f;k.update=this._update.bind(this),k.clearTiles=this._clearTiles.bind(this),k.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,l.cx(f,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"])),this._implementation.bounds&&(this.tileBounds=new l.cC({bounds:this._implementation.bounds,minzoom:this.minzoom,maxzoom:this.maxzoom}))}serialize(){return l.cx(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new l.i("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new l.i("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(_){this.map=_,this._loaded=!1,this.fire(new l.i("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(_),this.load()}onRemove(_){this._implementation.onRemove&&this._implementation.onRemove(_)}hasTile(_){if(this._implementation.hasTile){const{x:f,y,z:w}=_.canonical;return this._implementation.hasTile({x:f,y,z:w})}return!this.tileBounds||this.tileBounds.contains(_.canonical)}async loadTile(_,f){const{x:y,y:w,z:k}=_.tileID.canonical,R=new AbortController;_.request=R;try{const M=await this._implementation.loadTile({x:y,y:w,z:k},{signal:R.signal});if(delete _.request,_.aborted)return _.state="unloaded",f(null);if(M===void 0)return _.state="errored",f(null);if(M===null)return this.loadTileData(_,{width:this.tileSize,height:this.tileSize,data:null}),_.state="loaded",f(null);if(!function(z){return z instanceof ImageData||z instanceof HTMLCanvasElement||z instanceof ImageBitmap||z instanceof HTMLImageElement}(M))return _.state="errored",f(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`));this.loadTileData(_,M),_.state="loaded",f(null)}catch(M){if(R.signal.aborted)return;_.state="errored",f(M)}}loadTileData(_,f){_.setTexture(f,this.map.painter)}unloadTile(_,f){if(_.texture&&_.texture instanceof l.T?(_.destroy(!1),_.texture&&_.texture instanceof l.T&&this.map.painter.saveTileTexture(_.texture)):_.destroy(),this._implementation.unloadTile){const{x:y,y:w,z:k}=_.tileID.canonical;this._implementation.unloadTile({x:y,y:w,z:k})}f&&f()}abortTile(_,f){_.request&&(_.request.abort(),delete _.request),f&&f()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(_=>({x:_.canonical.x,y:_.canonical.y,z:_.canonical.z}))}_clearTiles(){const _=l.m(this.id,this.scope);this.map.style.clearSource(_)}_update(){this.fire(new l.i("data",{dataType:"source",sourceDataType:"content"}))}}},c2=function(_,f,y,w){const k=v0(f.type);if(!k)throw new Error(`Unknown source type "${f.type}"`);const R=new k(_,f,y,w);if(R.id!==_)throw new Error(`Expected Source id to be ${_} instead of ${R.id}`);return l.b4(["load","abort","unload","serialize","prepare"],R),R},v0=function(_){return Object.hasOwn(s1,_)?s1[_]:void 0},jx={model:()=>Ln().then(()=>on.ModelSource),"batched-model":()=>Ln().then(()=>on.Tiled3dModelSource),"raster-array":()=>Bg().then(()=>cm.RasterArrayTileSource)};function Cx(_,f,y=""){return`${y}:${f.id||""}:${f.layer.id}:${function(w){if("layerId"in w)return`layer:${w.layerId}`;{const{featuresetId:k,importId:R}=w;return`featureset:${k}${R?`:import:${R}`:""}`}}(_.target)}`}function u2(_,f,y,w=""){if(_.uniqueFeatureID){const k=Cx(_,f,w);if(y.has(k))return!0;y.add(k)}return!1}function pd(_,f,y,w,k=!1,R=void 0){const M=f.sourceCache.transform,z=f.sourceCache.tilesIn(_,f.has3DLayers,k);z.sort(ON);const V=[];for(const H of z){const Y=H.tile.queryRenderedFeatures(f,H,y,w,M,k,R);Object.keys(Y).length&&V.push({wrappedTileID:H.tile.tileID.wrapped().key,queryResults:Y})}for(const H in f.layers){const Y=f.layers[H];if(Y.styleLayer){const te=Y.styleLayer.queryRenderedFeatures(_,f.sourceCache,w);Object.keys(te).length&&V.push({wrappedTileID:0,queryResults:te})}}return V.length===0?{}:function(H){const Y={},te={};for(const ne of H){const le=ne.queryResults,me=ne.wrappedTileID,fe=te[me]=te[me]||{};for(const Se in le){const Me=le[Se],qe=fe[Se]=fe[Se]||{},Ne=Y[Se]=Y[Se]||[];for(const We of Me)qe[We.featureIndex]||(qe[We.featureIndex]=!0,Ne.push(We))}}return Y}(V)}function d2(_,f,y,w,k,R){const M={},z=w.queryRenderedSymbols(_),V=[];for(const H of Object.keys(z).map(Number))V.push(k[H]);V.sort(ON);for(const H of V){const Y=H.featureIndex.lookupSymbolFeatures(z[H.bucketInstanceId],H.bucketIndex,H.sourceLayerIndex,f,y,R);for(const te in Y){const ne=M[te]=M[te]||[],le=Y[te];le.sort((me,fe)=>{const Se=H.featureSortOrder;if(Se){const Me=Se.indexOf(me.featureIndex);return Se.indexOf(fe.featureIndex)-Me}return fe.featureIndex-me.featureIndex});for(const me of le)ne.push(me)}}return M}function a1(_,f){const y=_.getRenderableIds().map(R=>_.getTileByID(R)),w=[],k={};for(let R=0;R0:w.type==="building"?k=!w.isHidden(f)&&w.paint.get("building-opacity")>0:w.type==="model"&&(k=!w.isHidden(f)&&w.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!k&&y.visible,y.visible=k}}updateZOffset(f,y){this.currentBuildingBuckets=[];for(const k of this.layers){const R=k.layer,M=this.style.getLayerSourceCache(R);let z=1;R.type==="fill-extrusion"?z=k.visible?R.paint.get("fill-extrusion-vertical-scale"):0:R.type==="building"&&(z=k.visible?R.paint.get("building-vertical-scale"):0);let V=M?M.getTile(y):null;if(!V&&M){for(const H of M._tiles.values())if(y.canonical.isChildOf(H.tileID.canonical)){V=H;break}}this.currentBuildingBuckets.push({bucket:V?V.getBucket(R):null,tileID:V?V.tileID:y,verticalScale:z})}f.hasAnyZOffset=!1;let w=!1;for(let k=0;k{M in k&&(R[M]=k[M])}),y}function c1(_){_=_.slice();const f=Object.create(null);for(const y of _)f[y.id]=y;for(let y=0;y<_.length;y++){const w=_[y];if(w&&"ref"in w){const k=f[w.ref];k&&(_[y]=h2(w,k))}}return _}class u1{constructor(f,y){this.reset(f,y)}reset(f,y){this.points=f||[],this._distances=[0];for(let w=1;w0?(k-M)/z:0;return this.points[R].mult(1-V).add(this.points[y].mult(V))}}const jh=100;class f2{constructor(f,y){this.gridRightBoundary=0,this.gridBottomBoundary=0,this.clippedSymbols=new Map,this.reset(f,y)}reset(f,y){const w=f.width+200,k=f.height+200;w!==this.gridRightBoundary||k!==this.gridBottomBoundary?(this.grid=new l.d7(w,k,25),this.ignoredGrid=new l.d7(w,k,25)):(this.grid.clear(),this.ignoredGrid.clear()),this.transform=f,this.fogState=y,this.pitchfactor=Math.cos(f._pitch)*f.cameraToCenterDistance,this.screenRightBoundary=f.width+jh,this.screenBottomBoundary=f.height+jh,this.gridRightBoundary=w,this.gridBottomBoundary=k,this.clippedSymbols.clear()}clearClippedSymbolsForBucket(f){this.clippedSymbols.delete(f)}markSymbolAsClipped(f,y){let w=this.clippedSymbols.get(f);w||(w=new Set,this.clippedSymbols.set(f,w)),w.add(y)}placeCollisionBox(f,y,w,k,R,M,z,V,H,Y,te){let ne=w.projectedAnchorX,le=w.projectedAnchorY,me=w.projectedAnchorZ;const fe=w.tileAnchorX,Se=w.tileAnchorY,Me=w.elevation,qe=w.tileID,Ne=f.getProjection();if(Me&&qe){const[Lt,Mt,or]=Ne.upVector(qe.canonical,w.tileAnchorX,w.tileAnchorY),fr=Ne.upVectorScale(qe.canonical,this.transform.center.lat,this.transform.worldSize).metersToTile;ne+=Lt*Me*fr,le+=Mt*Me*fr,me+=or*Me*fr}const We=f.projection.name==="globe",ct=f.projection.name==="globe"?l._(this.transform.zoom):0;if(qe&&We&&ct<1&&!M){const Lt=1<0,Ne),pt=H*it.perspectiveRatio,dt=(w.x1*y+z.x-w.padding)*pt+it.point.x,mt=(w.y1*y+z.y-w.padding)*pt+it.point.y,xt=(w.x2*y+z.x+w.padding)*pt+it.point.x,bt=(w.y2*y+z.y+w.padding)*pt+it.point.y,Ft=it.perspectiveRatio<=l.de||it.occluded;return!this.isInsideGrid(dt,mt,xt,bt)||!V&&this.grid.hitTest(dt,mt,xt,bt,te)||Ft?{box:[],offscreen:!1,occluded:it.occluded}:{box:[dt,mt,xt,bt],offscreen:this.isOffscreen(dt,mt,xt,bt),occluded:!1}}placeCollisionCircles(f,y,w,k,R,M,z,V,H,Y,te,ne,le,me,fe,Se){const Me=[],qe=this.transform.elevation,Ne=f.getProjection(),We=f.elevationType==="road",ct=!!qe||We,it=l.c8.getAtTileOffsetFunc(Se,this.transform.center.lat,this.transform.worldSize,Ne),pt=new l.P(w.tileAnchorX,w.tileAnchorY),dt=new l.P(w.tileAnchorX,w.tileAnchorY);let{x:mt,y:xt,z:bt}=Ne.projectTilePoint(dt.x,dt.y,Se.canonical),Ft=null;if(ct){Ft=We&&f.hdExt?f.hdExt.makeRoadSymbolElevationParams(f,f.text,k,Se,it,qe,Ne,this.transform.center.lat,this.transform.worldSize):{getElevation:it,elevation:qe,elevationFeature:null};const[tn,kr,vn]=Ft.getElevation(pt,qe,Ft.elevationFeature);mt+=tn,xt+=kr,bt+=vn}const Lt=Ne.name==="globe",Mt=this.projectAndGetPerspectiveRatio(V,mt,xt,bt,Se,Lt||!!qe||this.transform.pitch>0,Ne),{perspectiveRatio:or}=Mt,fr=(ne?z/or:z*or)/l.dl,Cr=l.df(mt,xt,bt,H),qr=w.lineOffsetX*fr,qt=w.lineOffsetY*fr,Ut=l.aF(f.layers[0].layout.get("text-max-angle")),gr=Math.cos(Ut),Pr=Mt.signedDistanceFromCamera>0?l.dg(fr,M,qr,qt,We&&w.flipState===1,Cr,dt,w,R,H,{},ct&&!ne?Ft:null,ne&&ct,Ne,Se,ne,gr):null;let ur=!1,Xt=!1,mr=!0;if(Pr&&!Mt.occluded){const tn=.5*me*or+fe,kr=new l.P(-100,-100),vn=new l.P(this.screenRightBoundary,this.screenBottomBoundary),Xr=new u1,{first:ei,last:Rn}=Pr,Ni=ei.path.length;let zn=[];for(let Sn=Ni-1;Sn>=1;Sn--)zn.push(ei.path[Sn]);for(let Sn=1;Sn(ct&&!Lt&&(Ks=Ft.getElevation(yaSn[3]<=0)&&(zn=[]));let xn=[];if(zn.length>0){let Sn=1/0,Dn=-1/0,Ks=1/0,ya=-1/0;for(const Ti of zn)Sn=Math.min(Sn,Ti[0]),Ks=Math.min(Ks,Ti[1]),Dn=Math.max(Dn,Ti[0]),ya=Math.max(ya,Ti[1]);Dn>=kr.x&&Sn<=vn.x&&ya>=kr.y&&Ks<=vn.y&&(xn=[zn.map(Ti=>new l.P(Ti[0],Ti[1]))],(Snvn.x||Ksvn.y)&&(xn=l.dh(xn,kr.x,kr.y,vn.x,vn.y)))}for(const Sn of xn){Xr.reset(Sn,.25*tn);let Dn=0;Dn=Xr.length<=.5*tn?1:Math.ceil(Xr.paddedLength/Qi)+1;for(let Ks=0;Ks0?(l.cd(V,V,f),this.fogState&&R&&z.name!=="globe"&&(H=l.di(this.fogState,y,w,k,R.toUnwrapped(),this.transform)>l.dm)):l.dj(V,V,f);const Y=V[3];return{point:new l.P((V[0]/Y+1)/2*this.transform.width+jh,(-V[1]/Y+1)/2*this.transform.height+jh),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(z)/Y*.5,1.5),signedDistanceFromCamera:Y,occluded:M&&V[2]>Y||H}}isOffscreen(f,y,w,k){return w=this.screenRightBoundary||kthis.screenBottomBoundary}isInsideGrid(f,y,w,k){return w>=0&&f=0&&yw.collisionGroupID===y}}return this.collisionGroups[f]}}function FN(_,f,y,w,k){const{horizontalAlign:R,verticalAlign:M}=l.dz(_),z=-(R-.5)*f,V=-(M-.5)*y,H=l.dA(_,w);return new l.P(z+H[0]*k,V+H[1]*k)}function w0(_,f,y,w,k){const R=new l.P(_,f);return y&&R._rotate(w?k:-k),R}function Px(_,f,y,w){const{leftJustifiedTextSymbolIndex:k,centerJustifiedTextSymbolIndex:R,rightJustifiedTextSymbolIndex:M,verticalPlacedTextSymbolIndex:z,crossTileID:V}=y,H=l.dB(f),Y=w===l.dy.vertical?z:H==="left"?k:H==="center"?R:H==="right"?M:-1;k>=0&&(_.text.placedSymbolArray.get(k).crossTileID=Y>=0&&k!==Y?0:V),R>=0&&(_.text.placedSymbolArray.get(R).crossTileID=Y>=0&&R!==Y?0:V),M>=0&&(_.text.placedSymbolArray.get(M).crossTileID=Y>=0&&M!==Y?0:V),z>=0&&(_.text.placedSymbolArray.get(z).crossTileID=Y>=0&&z!==Y?0:V)}function Nx(_,f,y){const w=f===l.dy.horizontal||f===l.dy.horizontalOnly?f:0,k=f===l.dy.vertical?f:0,{leftJustifiedTextSymbolIndex:R,centerJustifiedTextSymbolIndex:M,rightJustifiedTextSymbolIndex:z,verticalPlacedTextSymbolIndex:V}=y,H=_.text.placedSymbolArray;R>=0&&(H.get(R).placedOrientation=w),M>=0&&(H.get(M).placedOrientation=w),z>=0&&(H.get(z).placedOrientation=w),V>=0&&(H.get(V).placedOrientation=k)}class Rx{constructor(f,y,w,k,R,M,z){this.transform=f.clone(),this.projection=f.projection.name,z instanceof f2?(z.reset(this.transform,R),this.collisionIndex=z):this.collisionIndex=new f2(this.transform,R),this.buildingIndex=M,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=y,this.retainedQueryData={},this.collisionGroups=new ez(w),this.collisionCircleArrays={},this.prevPlacement=k,k&&(k.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(f,y,w,k,R=1){const M=w.getBucket(y),z=w.latestFeatureIndex;if(!M||!z||y.fqid!==M.layerIds[0])return;const V=M.layers[0].layout,H=M.layers[0].paint,Y=w.collisionBoxArray,te=Math.pow(2,this.transform.zoom-w.tileID.overscaledZ),ne=w.tileSize/l.ac,le=w.tileID.toUnwrapped();this.transform.setProjection(M.projection);const me=l.dn(w.tileID,M.getProjection(),this.transform,this.projection),fe=V.get("text-pitch-alignment")==="map",Se=V.get("text-rotation-alignment")==="map";y.compileFilter(y.options);const Me=y.dynamicFilter(),qe=y.dynamicFilterNeedsFeature(),Ne=y.dynamicFilterNeedsGeometry(),We=this.transform.calculatePixelsToTileUnitsMatrix(w),ct=l.dp(me,w.tileID.canonical,fe,Se,this.transform,M.getProjection(),We);let it=null;const pt=M.getProjection().createInversionMatrix(this.transform,w.tileID.canonical);if(fe){const fr=l.dq(me,w.tileID.canonical,fe,Se,this.transform,M.getProjection(),We);it=l.a1([],this.transform.labelPlaneMatrix,fr)}let dt=null;Me&&w.latestFeatureIndex&&(dt={unwrappedTileID:le,dynamicFilter:Me,dynamicFilterNeedsFeature:qe,needGeometry:Ne}),this.retainedQueryData[M.bucketInstanceId]=new JB(M.bucketInstanceId,z,M.sourceLayerIndex,M.index,w.tileID);const[mt,xt]=M.layers[0].layout.get("text-size-scale-range"),bt=l.bb(R,mt,xt),[Ft,Lt]=V.get("icon-size-scale-range"),Mt=l.bb(R,Ft,Lt),or={bucket:M,layout:V,paint:H,posMatrix:me,invMatrix:pt,mercatorCenter:[l.ad(this.transform.center.lng),l.ae(this.transform.center.lat)],textLabelPlaneMatrix:ct,labelToScreenMatrix:it,clippingData:dt,scale:te,textPixelRatio:ne,holdingForFade:w.holdingForFade(),collisionBoxArray:Y,partiallyEvaluatedTextSize:l.dr(M.textSizeData,this.transform.zoom,bt),partiallyEvaluatedIconSize:l.dr(M.iconSizeData,this.transform.zoom,Mt),collisionGroup:this.collisionGroups.get(M.sourceID),latestFeatureIndex:w.latestFeatureIndex};if(k)for(const fr of M.sortKeyRanges){const{sortKey:Cr,symbolInstanceStart:qr,symbolInstanceEnd:qt}=fr;f.push({sortKey:Cr,symbolInstanceStart:qr,symbolInstanceEnd:qt,parameters:or})}else f.push({symbolInstanceStart:0,symbolInstanceEnd:M.symbolInstances.length,parameters:or})}placeLayerBucketPart(f,y,w,k=1){const{bucket:R,layout:M,paint:z,posMatrix:V,textLabelPlaneMatrix:H,labelToScreenMatrix:Y,clippingData:te,textPixelRatio:ne,mercatorCenter:le,invMatrix:me,holdingForFade:fe,collisionBoxArray:Se,partiallyEvaluatedTextSize:Me,partiallyEvaluatedIconSize:qe,collisionGroup:Ne,latestFeatureIndex:We}=f.parameters,ct=M.get("text-optional"),it=M.get("icon-optional"),pt=M.get("text-allow-overlap"),dt=M.get("icon-allow-overlap"),mt=M.get("text-rotation-alignment")==="map",xt=M.get("icon-rotation-alignment")==="map",bt=M.get("text-pitch-alignment")==="map",Ft=z.get("symbol-z-offset"),Lt=M.get("symbol-elevation-reference")==="sea",Mt=M.get("symbol-placement"),or=M.get("text-variable-anchor"),fr=mt&&Mt!=="point",Cr=xt&&Mt!=="point",qr=or&&R.hasTextData(),qt=R.hasIconTextFit()&&qr&&R.hasIconData();this.transform.setProjection(R.projection);const Ut=qr||fr,gr=Cr||qt;let Pr=pt&&(dt||!R.hasIconData()||it),ur=dt&&(pt||!R.hasTextData()||ct);const Xt=!Ft.isConstant(),mr=(kr,vn)=>{const{crossTileID:Xr,numVerticalGlyphVertices:ei}=kr,Rn=R.getCollisionArrays(Se,kr);let Ni=null;if(te&&te.dynamicFilterNeedsFeature||Xt){const Is=this.retainedQueryData[R.bucketInstanceId],Ji=We.loadFeature({featureIndex:kr.featureIndex,bucketIndex:Is.bucketIndex,sourceLayerIndex:Is.sourceLayerIndex,layoutVertexArrayOffset:0}),Ii=Ji.properties?Ji.properties.worldview:null;if(R.localizable&&R.worldview&&typeof Ii=="string")if(Ii==="all")Ji.properties.$localized=!0;else{if(!Ii.split(",").includes(R.worldview))return;Ji.properties.$localized=!0,Ji.properties.worldview=R.worldview}Ni=te&&te.needGeometry?l.bI(Ji,!0):Ji}if(te&&!(0,te.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:R.worldview},Ni,this.retainedQueryData[R.bucketInstanceId].tileID.canonical,new l.P(kr.tileAnchorX,kr.tileAnchorY),this.transform.calculateDistanceTileData(te.unwrappedTileID)))return this.placements[Xr]=new d1(!1,!1,!1,!0),void y.add(Xr);const zn=Ft.evaluate(Ni,{});if((kr.zOffset||0)+(zn||0)>0&&this.frontCutoffStart>0){const Is=2*this.frontCutoffStart-1,Ji=[kr.tileAnchorX,kr.tileAnchorY,0,1],Ii=l.cd(l.dw(),Ji,V);if(Ii[1]/Ii[3]{Is.tileID=this.retainedQueryData[R.bucketInstanceId].tileID;const Ji=this.transform.elevation;if(R.elevationType==="road")Is.elevation=Lt?zn:zn+l.c8.getAtTileOffset(Is.tileID,new l.P(Is.tileAnchorX,Is.tileAnchorY),Ji,null);else{const Ii=R.hdExt?R.hdExt.elevationFeatures[kr.elevationFeatureIndex]:void 0;Is.elevation=Lt?zn:zn+l.c8.getAtTileOffset(Is.tileID,new l.P(Is.tileAnchorX,Is.tileAnchorY),Ji,Ii)}Is.elevation+=kr.zOffset},Ya=Rn.textBox;if(Ya){ti(Ya);const Is=Ii=>{let Qs=l.dy.horizontal;if(R.allowVerticalPlacement&&!Ii&&this.prevPlacement){const na=this.prevPlacement.placedOrientations[Xr];na&&(this.placedOrientations[Xr]=na,Qs=na,Nx(R,Qs,kr))}return Qs},Ji=(Ii,Qs)=>{if(R.allowVerticalPlacement&&ei>0&&Rn.verticalTextBox){for(const na of R.writingModes)if(na===l.dy.vertical?(Ti=Qs(),Ba=Ti):Ti=Ii(),Ti&&Ti.box&&Ti.box.length)break}else Ti=Ii()};if(or){let Ii=or;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Xr]){const Ls=this.prevPlacement.variableOffsets[Xr];Ii.indexOf(Ls.anchor)>0&&(Ii=Ii.filter(ol=>ol!==Ls.anchor),Ii.unshift(Ls.anchor))}const Qs=(Ls,ol,Sc)=>{const Fl=R.getSymbolInstanceTextSize(Me,kr,this.transform.zoom,vn),ji=(Ls.x2-Ls.x1)*Fl+2*Ls.padding,Hi=(Ls.y2-Ls.y1)*Fl+2*Ls.padding,Os=kr.hasIconTextFit&&!dt?ol:null;Os&&ti(Os);let Za={box:[],offscreen:!1,occluded:!1};const Jd=pt?2*Ii.length:Ii.length;for(let xu=0;xu=Ii.length,kr,vn,R,Sc,Os,Me,qe);if(Nh&&(Za=Nh.placedGlyphBoxes,Za&&Za.box&&Za.box.length)){Qi=!0,ya=Nh.shift;break}}return Za};Ji(()=>Qs(Ya,Rn.iconBox,l.dy.horizontal),()=>{const Ls=Rn.verticalTextBox;return Ls&&ti(Ls),R.allowVerticalPlacement&&!(Ti&&Ti.box&&Ti.box.length)&&ei>0&&Ls?Qs(Ls,Rn.verticalIconBox,l.dy.vertical):{box:null,offscreen:null,occluded:null}}),Ti&&(Qi=Ti.box,Sn=Ti.offscreen,Dn=Ti.occluded);const na=Is(!(!Ti||!Ti.box));if(!Qi&&this.prevPlacement){const Ls=this.prevPlacement.variableOffsets[Xr];Ls&&(this.variableOffsets[Xr]=Ls,Px(R,Ls.anchor,kr,na))}}else{const Ii=(Qs,na)=>{const Ls=R.getSymbolInstanceTextSize(Me,kr,this.transform.zoom,vn),ol=this.collisionIndex.placeCollisionBox(R,Ls,Qs,le,me,Ut,new l.P(0,0),pt,ne,V,Ne.predicate);return ol&&ol.box&&ol.box.length&&(Nx(R,na,kr),this.placedOrientations[Xr]=na),ol};Ji(()=>Ii(Ya,l.dy.horizontal),()=>{const Qs=Rn.verticalTextBox;return R.allowVerticalPlacement&&ei>0&&Qs?(ti(Qs),Ii(Qs,l.dy.vertical)):{box:null,offscreen:null,occluded:null}}),Is(!!(Ti&&Ti.box&&Ti.box.length))}}if(bs=Ti,Qi=bs&&bs.box&&bs.box.length>0,Sn=bs&&bs.offscreen,Dn=bs&&bs.occluded,kr.useRuntimeCollisionCircles){const Is=kr.centerJustifiedTextSymbolIndex>=0?kr.centerJustifiedTextSymbolIndex:kr.verticalPlacedTextSymbolIndex,Ji=R.text.placedSymbolArray.get(Is),Ii=l.dx(R.textSizeData,Me,Ji),Qs=M.get("text-padding");Ri=this.collisionIndex.placeCollisionCircles(R,pt,Ji,Is,R.lineVertexArray,R.glyphOffsetArray,Ii,V,H,Y,w,bt,Ne.predicate,kr.collisionCircleDiameter*Ii/l.dl,Qs,this.retainedQueryData[R.bucketInstanceId].tileID),Qi=pt||Ri.circles.length>0&&!Ri.collisionDetected,Sn=Sn&&Ri.offscreen,Dn=Ri.occluded}if(Rn.iconFeatureIndex&&(Pn=Rn.iconFeatureIndex),Rn.iconBox){const Is=Ji=>{ti(Ji);const Ii=kr.hasIconTextFit&&ya?w0(ya.x,ya.y,mt,bt,this.transform.angle):new l.P(0,0),Qs=R.getSymbolInstanceIconSize(qe,this.transform.zoom,kr.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(R,Qs,Ji,le,me,gr,Ii,dt,ne,V,Ne.predicate)};Ba&&Ba.box&&Ba.box.length&&Rn.verticalIconBox?(gi=Is(Rn.verticalIconBox),xn=gi.box.length>0):(gi=Is(Rn.iconBox),xn=gi.box.length>0),Sn=Sn&&gi.offscreen,Ks=gi.occluded}const ao=ct||kr.numHorizontalGlyphVertices===0&&ei===0,yu=it||kr.numIconVertices===0;if(ao||yu?yu?ao||(xn=xn&&Qi):Qi=xn&&Qi:xn=Qi=xn&&Qi,Qi&&bs&&bs.box&&this.collisionIndex.insertCollisionBox(bs.box,M.get("text-ignore-placement"),R.bucketInstanceId,Ba&&Ba.box&&Dr?Dr:yi,Ne.ID),xn&&gi&&this.collisionIndex.insertCollisionBox(gi.box,M.get("icon-ignore-placement"),R.bucketInstanceId,Pn,Ne.ID),Ri&&(Qi&&this.collisionIndex.insertCollisionCircles(Ri.circles,M.get("text-ignore-placement"),R.bucketInstanceId,yi,Ne.ID),w)){const Is=R.bucketInstanceId;let Ji=this.collisionCircleArrays[Is];Ji===void 0&&(Ji=this.collisionCircleArrays[Is]=new QB);for(let Ii=0;Ii=0;--vn){const Xr=kr[vn];mr(R.symbolInstances.get(Xr),Xr)}R.hasAnyZOffset&&l.w(`${R.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(R.hasAnyZOffset){const kr=R.getSortedIndexesByZOffset();for(let vn=0;vn0){let Ft;return this.prevPlacement&&this.prevPlacement.variableOffsets[dt]&&this.prevPlacement.placements[dt]&&this.prevPlacement.placements[dt].text&&(Ft=this.prevPlacement.variableOffsets[dt].anchor),this.variableOffsets[dt]={textOffset:mt,width:M,height:z,anchor:f,textScale:V,prevAnchor:Ft},Px(Me,f,fe,qe),Me.allowVerticalPlacement&&(Nx(Me,qe,fe),this.placedOrientations[dt]=qe),{shift:xt,placedGlyphBoxes:bt}}}commit(f){this.commitTime=f,this.zoomAtLastRecencyCheck=this.transform.zoom;const y=this.prevPlacement;let w=!1;this.prevZoomAdjustment=y?y.zoomAdjustment(this.transform.zoom):0;const k=y?y.symbolFadeChange(f):1,R=y?y.opacities:{},M=y?y.variableOffsets:{},z=y?y.placedOrientations:{};for(const V in this.placements){const H=this.placements[V],Y=R[V];Y?(this.opacities[V]=new b0(Y,k,H.text,H.icon,null,H.clipped),w=w||H.text!==Y.text.placed||H.icon!==Y.icon.placed):(this.opacities[V]=new b0(null,k,H.text,H.icon,H.skipFade,H.clipped),w=w||H.text||H.icon)}for(const V in R){const H=R[V];if(!this.opacities[V]){const Y=new b0(H,k,!1,!1);Y.isHidden()||(this.opacities[V]=Y,w=w||H.text.placed||H.icon.placed)}}for(const V in M)this.variableOffsets[V]||!this.opacities[V]||this.opacities[V].isHidden()||(this.variableOffsets[V]=M[V]);for(const V in z)this.placedOrientations[V]||!this.opacities[V]||this.opacities[V].isHidden()||(this.placedOrientations[V]=z[V]);w?this.lastPlacementChangeTime=f:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=y?y.lastPlacementChangeTime:f)}updateLayerOpacities(f,y,w,k,R=!1,M=1){k&&(this.lastReplacementSourceUpdateTime=k.updateTime);const z=new Set;for(const V of y){const H=V.getBucket(f);if(H&&V.latestFeatureIndex&&f.fqid===H.layerIds[0]&&(this.updateBucketOpacities(H,z,V,V.collisionBoxArray,w,k,V.tileID,f.scope),H.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(H,V.tileID),H.elevationType==="road"&&H.hdExt&&H.hdExt.updateRoadElevation(H,V.tileID.canonical),H.updateZOffset(),R&&V.collisionBoxArray)){const Y=H.layers[0].layout,[te,ne]=Y.get("text-size-scale-range"),[le,me]=Y.get("icon-size-scale-range"),fe=l.bb(M,te,ne),Se=l.bb(M,le,me);H.updateCollisionDebugBuffers(this.transform.zoom,V.collisionBoxArray,fe,Se)}}}updateBucketOpacities(f,y,w,k,R,M,z,V){f.hasTextData()&&f.text.opacityVertexArray.clear(),f.hasIconData()&&f.icon.opacityVertexArray.clear(),f.hasIconCollisionBoxData()&&f.iconCollisionBox.collisionVertexArray.clear(),f.hasTextCollisionBoxData()&&f.textCollisionBox.collisionVertexArray.clear();const H=f.layers[0].layout,Y=f.layers[0].paint,te=!!f.layers[0].dynamicFilter(),ne=new b0(null,0,!1,!1,!0),le=H.get("text-allow-overlap"),me=H.get("icon-allow-overlap"),fe=H.get("text-variable-anchor"),Se=H.get("text-rotation-alignment")==="map",Me=H.get("text-pitch-alignment")==="map",qe=Y.get("symbol-z-offset"),Ne=H.get("symbol-elevation-reference")==="sea",We=!qe.isConstant(),ct=new b0(null,0,le&&(me||!f.hasIconData()||H.get("icon-optional")),me&&(le||!f.hasTextData()||H.get("text-optional")),!0),it=(xt,bt,Ft)=>{const Lt=xt.opacityVertexArray;let Mt=!1;for(let or=0;or0||Lt>0,Xt=or>0,mr=this.placedOrientations[Mt],tn=mr===l.dy.vertical,kr=mr===l.dy.horizontal||mr===l.dy.horizontalOnly;!ur&&!Xt||Pr.isHidden()||mt++;let vn=!1;if((ur||Xt)&&M)for(const Xr of f.activeReplacements){if(l.ds(Xr,R,l.dt.Symbol,V)||Xr.min.x>fr||fr>Xr.max.x||Xr.min.y>Cr||Cr>Xr.max.y)continue;const ei=l.du(fr,Cr,z.canonical,Xr.footprintTileId.canonical);if(vn=l.dv(ei,Xr.footprint),vn)break}if(vn&&this.collisionIndex.markSymbolAsClipped(f.bucketInstanceId,bt.featureIndex),ur){const Xr=vn?Ug:VN(Pr.text);it(f.text,Ft,tn?Ug:Xr)&&(pt=!0),it(f.text,Lt,kr?Ug:Xr)&&(pt=!0);const ei=Pr.text.isHidden(),{leftJustifiedTextSymbolIndex:Rn,centerJustifiedTextSymbolIndex:Ni,rightJustifiedTextSymbolIndex:zn,verticalPlacedTextSymbolIndex:Qi}=bt,xn=f.text.placedSymbolArray,Sn=ei||tn?1:0;Rn>=0&&(xn.get(Rn).hidden=Sn),Ni>=0&&(xn.get(Ni).hidden=Sn),zn>=0&&(xn.get(zn).hidden=Sn),Qi>=0&&(xn.get(Qi).hidden=ei||kr?1:0);const Dn=this.variableOffsets[Mt];Dn&&Px(f,Dn.anchor,bt,mr);const Ks=this.placedOrientations[Mt];Ks&&(Px(f,"left",bt,Ks),Nx(f,Ks,bt))}if(Xt){const Xr=vn?Ug:VN(Pr.icon),{placedIconSymbolIndex:ei,verticalPlacedIconSymbolIndex:Rn}=bt,Ni=f.icon.placedSymbolArray,zn=Pr.icon.isHidden()?1:0;ei>=0&&(it(f.icon,or,tn?Ug:Xr)&&(dt=!0),Ni.get(ei).hidden=zn),Rn>=0&&(it(f.icon,bt.numVerticalIconVertices,kr?Ug:Xr)&&(dt=!0),Ni.get(Rn).hidden=zn)}if((f.hasIconCollisionBoxData()||f.hasTextCollisionBoxData())&&k){const Xr=bt.textBoxStartIndexf}isStale(){return this.stale}setStale(){this.stale=!0}}function S0(_,f,y,w,k,R,M){_.emplaceBack(f?1:0,y?1:0,R||0,M||0,w,k?1:0),_.emplaceBack(f?1:0,y?1:0,R||0,M||0,w,k?1:0),_.emplaceBack(f?1:0,y?1:0,R||0,M||0,w,k?1:0),_.emplaceBack(f?1:0,y?1:0,R||0,M||0,w,k?1:0)}const BN=Math.pow(2,25),zN=Math.pow(2,24),m2=Math.pow(2,17),vp=Math.pow(2,16),p2=Math.pow(2,9),$N=Math.pow(2,8),UN=Math.pow(2,1);function VN(_){if(_.opacity===0&&!_.placed)return 0;if(_.opacity===1&&_.placed)return 4294967295;const f=_.placed?1:0,y=Math.floor(127*_.opacity);return y*BN+f*zN+y*m2+f*vp+y*p2+f*$N+y*UN+f}const Ug=0;class bp{constructor(f){this._sortAcrossTiles=f.layout.get("symbol-z-order")!=="viewport-y"&&f.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(f,y,w,k,R,M){const z=this._bucketParts;for(;this._currentTileIndexV.sortKey-H.sortKey));this._currentPartIndex!this.isFullPlacementRequested()&&this._fadeDuration!==0&&l.e.now()-M>2;for(;this._currentPlacementIndex>=0;){const V=y[f[this._currentPlacementIndex]],H=this.placement.collisionIndex.transform.zoom;if(V.type==="symbol"&&V.visibility!=="none"&&(!V.minzoom||V.minzoom<=H)&&(!V.maxzoom||V.maxzoom>H)){const Y=V,te=Y.layout.get("symbol-z-elevate"),ne=Y.layout.get("symbol-sort-key").constantOr(1)!==void 0,le=Y.layout.get("symbol-z-order"),me=le==="viewport-y"||le==="auto"&&!(le!=="viewport-y"&&ne),fe=Y.layout.get("text-allow-overlap")||Y.layout.get("icon-allow-overlap")||Y.layout.get("text-ignore-placement")||Y.layout.get("icon-ignore-placement"),Se=me&&fe,Me=this._inProgressLayer=this._inProgressLayer||new bp(Y),qe=l.m(V.source,V.scope);if(Me.continuePlacement(te||Se?k[qe]:w[qe],this.placement,this._showCollisionBoxes,V,z,R))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(f){return this._retiredCI=this.placement.prevPlacement?this.placement.prevPlacement.collisionIndex:null,this.placement.commit(f),this.placement}}const Lx=512/l.ac/2;class qN{constructor(f,y,w){this.tileID=f,this.bucketInstanceId=w,this.index=new l.dC(y.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const k=f.canonical.x*l.ac,R=f.canonical.y*l.ac;for(let M=0;MSe-Me);for(const Se of fe){const Me=this.crossTileIDs[Se];if(this.keys[Se]===Y&&!w.has(Me)){w.add(Me),H.crossTileID=Me;break}}}}}class GN{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class g2{constructor(){this.indexes=[],this.usedCrossTileIDs=[],this.lng=0}handleWrapJump(f){const y=Math.round((f-this.lng)/360);if(y!==0)for(let w=0;wk)for(const Y of H.values())Y.tileID.isChildOf(f)&&Y.findMatches(y.symbolInstances,f,M);else{const Y=H.get(f.scaledTo(V).key);Y&&Y.findMatches(y.symbolInstances,f,M)}}for(let V=0;V=_.radius+y)return!1;const k=(f.bottom-f.top)/2,R=Math.abs(_.y-(f.top+k));if(R>=_.radius+k)return!1;if(w{if(!f1(this._geometries[Y],M))return!1;const te=this._geometryData[Y];return!(te!==void 0&&w(te)||(z=te,0))},H=M.kind==="box"?this._grid.hitTest(M.left+R,M.top+R,M.right+R,M.bottom+R,V):this._grid.hitTestCircle(M.x+R,M.y+R,M.radius,V);return H&&z!==void 0&&k(z),H?"intersects":"does-not-intersect"}insert(f,y){const w=this._padding;let k=!1;for(const R of f){if(!f1(R,this._workingArea))continue;const M=this._geometries.length;this._geometries.push(R),this._geometryData.push(y),R.kind==="box"?this._grid.insert(M,R.left+w,R.top+w,R.right+w,R.bottom+w):this._grid.insertCircle(M,R.x+w,R.y+w,R.radius),k=!0}return k}}function tz(){}function T0(_){return 2*_.styleLayerId+_.symbolIdOrigin}function x2(_,f){const y=_.get(T0(f.symbolId));if(!y)return!1;const w=y.get(f.symbolId.symbolId);return w!==void 0&&w.has(f.variantIdx)}function WN(_,f){const y=T0(f.symbolId);let w=_.get(y);w||(w=new Map,_.set(y,w));let k=w.get(f.symbolId.symbolId);k||(k=new Set,w.set(f.symbolId.symbolId,k)),k.add(f.variantIdx)}class _2{constructor(){this._runStarted=!1,this._grid=null,this._timestamp=0,this._symbols=[],this._onlyIfPlacedReferencedIds=new Map,this._placedVariantIds=new Map,this._placedSymbolIds=new Map,this._processingSource=null,this._variantProcessingStarted=!1,this._collectDebugData=!1,this._debugSymbols=[],this._lastBlockedBy=void 0}isCollectingDebugData(){return this._collectDebugData}startPlacement(f,y,w,k=!1){if(this._runStarted)throw new Error("Attempt to start a placement run before finishing the previous one");this._runStarted=!0,this._grid?this._grid.clearAndResize(y,w):this._grid=new E0(y,w,100,32),this._timestamp=f,this._symbols=[],this._onlyIfPlacedReferencedIds.clear(),this._placedVariantIds.clear(),this._placedSymbolIds.clear(),this._collectDebugData=k,this._debugSymbols=[]}debugSymbols(){return this._debugSymbols}timestamp(){return this._timestamp}_hasPlacedSymbol(f){const y=this._placedSymbolIds.get(T0(f));return y!==void 0&&y.has(f.symbolId)}_placedVariantIdxFor(f){const y=this._placedSymbolIds.get(T0(f));return y&&y.get(f.symbolId)}_addPlacedSymbol(f){const y=T0(f.symbolId);let w=this._placedSymbolIds.get(y);w||(w=new Map,this._placedSymbolIds.set(y,w)),w.set(f.symbolId.symbolId,f.variantIdx)}startSymbolSourceProcessing(f){if(!this._runStarted)throw new Error("Attempt to start symbol source processing outside of a placement run");if(this._processingSource)throw new Error("Attempt to start a placement symbol source processing before finishing the previous one");this._processingSource=f}startSymbolVariantProcessing(f,y,w,k,R){const M=this._processingSource;if(!M)throw new Error("Attempt to start a symbol variant processing outside of symbol source processing");if(this._variantProcessingStarted)throw new Error("Attempt to begin a symbol variant processing before finishing the previous one");this._symbols.push({priority:y,source:M,variantId:f,parts:[],placementRules:w,tileID:k,featureId:R}),w.onlyIfPlaced&&WN(this._onlyIfPlacedReferencedIds,w.onlyIfPlaced),this._variantProcessingStarted=!0}addSymbolVariantPart(f,y){if(!this._variantProcessingStarted)throw new Error("Attempt to add a symbol variant part outside of symbol variant processing");if(f.length===0)throw new Error("Attempt to add a symbol variant part without geometry");this._symbols.at(-1).parts.push({geometry:f,rules:y})}finishVariantProcessing(){if(!this._variantProcessingStarted)throw new Error("Attempt to finish a symbol variant processing that was not started");this._variantProcessingStarted=!1;const f=this._symbols.at(-1);f.parts.length===0&&(f.priority.symbolVariantVisibility===l.dD.VARIANT_VISIBLE&&f.source.hideSymbolVariant(f.variantId,this._timestamp),this._symbols.pop())}finishSourceProcessing(){this._processingSource=null}_placeSymbolVariant(f,y){const w=this._grid;if(this._lastBlockedBy=void 0,this._hasPlacedSymbol(f.variantId.symbolId)){if(this._collectDebugData){const Y=this._placedVariantIdxFor(f.variantId.symbolId);Y!==void 0&&(this._lastBlockedBy={symbolId:f.variantId.symbolId,variantIdx:Y})}return 2}const k=f.placementRules.onlyIfPlaced;if(k&&!x2(this._placedVariantIds,k))return 3;const R=this._collectDebugData?Y=>{this._lastBlockedBy=Y}:tz;let M=!1,z=!1;for(const Y of f.parts){const te=Y.rules.collisionRules;if(!te)continue;M=!0;const ne=te.symbolVariantToIgnoreCollisionWith,le=w.intersects(Y.geometry,y,me=>{return ne!==void 0&&(fe=me).variantIdx===(Se=ne).variantIdx&&fe.symbolId.styleLayerId===Se.symbolId.styleLayerId&&fe.symbolId.symbolIdOrigin===Se.symbolId.symbolIdOrigin&&fe.symbolId.symbolId===Se.symbolId.symbolId;var fe,Se},R);if(le==="intersects")return 1;le==="does-not-intersect"&&(z=!0)}if(M&&!z)return 4;let V=!1,H=!1;for(const Y of f.parts)Y.rules.insertIntoCollisionGrid&&(w.insert(Y.geometry,f.variantId)?V=!0:H=!0);return H&&!V?4:0}finishPlacementRun(){if(!this._runStarted)throw new Error("Attempt to finish a placement run that was not started");this._runStarted=!1;const f=this._timestamp;this._symbols.sort((y,w)=>function(k,R){return k.placementSubgroupOrder-R.placementSubgroupOrder||k.symbolPlacementPriority-R.symbolPlacementPriority||k.symbolVariantVisibility-R.symbolVariantVisibility||k.symbolPlacementType-R.symbolPlacementType||k.styleLayerOrder-R.styleLayerOrder||k.symbolDisplayOrder-R.symbolDisplayOrder}(w.priority,y.priority));for(const y of this._symbols){const w=y.priority.symbolVariantVisibility===l.dD.VARIANT_VISIBLE,k=w?0:1,R=this._placeSymbolVariant(y,k),M=R===0;if(M&&(this._addPlacedSymbol(y.variantId),x2(this._onlyIfPlacedReferencedIds,y.variantId)&&WN(this._placedVariantIds,y.variantId)),w!==M&&(M?y.source.showSymbolVariant(y.variantId,f):y.source.hideSymbolVariant(y.variantId,f)),this._collectDebugData){const z=M?0:k,V=[];for(const H of y.parts)V.push(...H.geometry);this._debugSymbols.push({geometry:V,collisionPadding:z,variantId:y.variantId,tileID:y.tileID,featureId:y.featureId,placementRules:y.placementRules,partPlacementRules:y.parts.map(H=>H.rules),status:R,blockedBy:this._lastBlockedBy})}}}}class m1 extends l.E{constructor(f){super(),this.requestManager=f,this.models=Object.create(null),this.models[""]=Object.create(null),this.modelUris=Object.create(null),this.modelUris[""]=Object.create(null),this.modelByURL=Object.create(null),this.numModelsLoading=Object.create(null)}async loadModel(f,y){try{const w=await this.requestManager.transformRequest(y,l.R.Model);return this.modelByURL[y]?(await Ln(),on.loadModel?await on.loadModel(w,f,y):null):null}catch(w){if(w.status===404)return null;this.fire(new l.h(new Error(`Could not load model ${f} from ${y}`,{cause:w})))}}load(f,y,w={forceReload:!1}){this.models[y]||(this.models[y]=Object.create(null));const k=Object.keys(f),R=[],M=[];for(const z of k){const V=f[z];this.hasURLBeenRequested(V)&&!w.forceReload||(this.modelByURL[V]={modelId:z,scope:y},R.push(this.loadModel(z,V)),M.push(z)),this.models[y][z]||(this.models[y][z]={model:null,numReferences:1})}M.length!==0&&(this.numModelsLoading[y]=(this.numModelsLoading[y]||0)+M.length,Promise.allSettled(R).then(z=>{for(let V=0;V{this.fire(new l.h(new Error(`Could not load models: ${z.message}`)))}))}isLoaded(){for(const f in this.numModelsLoading)if(this.numModelsLoading[f]>0)return!1;return!0}hasModel(f,y,w={exactIdMatch:!1}){return!!(w.exactIdMatch?this.getModel(f,y):this.getModelByURL(this.modelUris[y][f]))}getModel(f,y){return this.models[y]||(this.models[y]=Object.create(null)),this.models[y][f]?this.models[y][f].model:void 0}getModelByURL(f){if(!f)return null;const y=this.modelByURL[f];return y?this.models[y.scope][y.modelId].model:null}hasModelBeenAdded(f,y){return this.models[y]&&this.models[y][f]!==void 0}getModelURIs(f){return this.modelUris[f]||Object.create(null)}addModel(f,y,w){this.models[w]||(this.models[w]=Object.create(null)),this.modelUris[w]||(this.modelUris[w]=Object.create(null));const k=this.requestManager.normalizeModelURL(y);if((this.hasModel(f,w,{exactIdMatch:!0})||this.hasModelBeenAdded(f,w))&&this.modelUris[w][f]===k)this.models[w][f].numReferences++;else if(this.hasURLBeenRequested(k)){const{scope:R,modelId:M}=this.modelByURL[k];this.models[R][M].numReferences++}else this.modelUris[w][f]=k,this.load({[f]:this.modelUris[w][f]},w)}addModelURLs(f,y){this.models[y]||(this.models[y]=Object.create(null)),this.modelUris[y]||(this.modelUris[y]=Object.create(null));const w=this.modelUris[y];for(const k of Object.keys(f))w[k]=this.requestManager.normalizeModelURL(f[k])}reloadModels(f){this.load(this.modelUris[f],f,{forceReload:!0})}addModelsFromBucket(f,y){this.models[y]||(this.models[y]=Object.create(null)),this.modelUris[y]||(this.modelUris[y]=Object.create(null));const w=Object.create(null);for(const k of f)this.hasModel(k,y,{exactIdMatch:!0})||this.hasURLBeenRequested(k)?this.models[y][k].numReferences++:this.modelUris[y][k]&&!this.hasURLBeenRequested(k)?w[k]=this.modelUris[y][k]:!this.hasURLBeenRequested(k)&&wh(k,!1)&&(this.modelUris[y][k]=this.requestManager.normalizeModelURL(k),w[k]=this.modelUris[y][k]);this.load(w,y)}hasURLBeenRequested(f){return this.modelByURL[f]!==void 0}removeModel(f,y,w=!1,k=!1){if(this.models[y]&&this.models[y][f]&&(this.models[y][f].numReferences--,this.models[y][f].numReferences===0||k)){const R=this.modelUris[y][f];w||delete this.modelUris[y][f],delete this.modelByURL[R];const M=this.models[y][f].model;if(!M)return;delete this.models[y][f],M.destroy()}}destroy(){for(const f of Object.keys(this.models))for(const y of Object.keys(this.models[f])){const w=this.models[f][y].model;delete this.models[f][y],w&&w.destroy()}this.models=Object.create(null),this.models[""]=Object.create(null),this.modelUris=Object.create(null),this.modelUris[""]=Object.create(null),this.modelByURL=Object.create(null),this.numModelsLoading=Object.create(null)}listModels(f){return this.models[f]||(this.models[f]=Object.create(null)),Object.keys(this.models[f])}upload(f,y){this.models[y]||(this.models[y]=Object.create(null));for(const w in this.models[y])this.models[y][w].model&&this.models[y][w].model.upload(f.context)}}const Vg=["RENDER_SHADOWS","NORMAL_OFFSET"],p1=new Set(["symbol","circle"]),wp=class o9{constructor(){this._queue=[],this._needsBuild=!0,this._idleHandle=null}needsBuild(){return this._needsBuild}buildQueue(f,y,w){this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._idleHandle=null,this._queue=[],this._needsBuild=!1;const k=!!w.fog,R=w.hasTerrain(),M=!(!w.projection||w.projection.name!=="globe"),z=R||M,V=!(!w.directionalLight||!w.directionalLight.shadowsEnabled()),H=w.map&&w.map.painter,Y=!H||!H.context.extParallelShaderCompile,te=!!H&&(H.emissiveMode==="mrt-fallback"||H.emissiveMode==="mrt-full-rgba"),ne=(le,me=[],fe={})=>{this._queue.push({programId:le,params:{...fe.params,defines:me,overrideFog:!!fe.fog,overrideTerrain:!!fe.terrain,overrideGlobe:!!fe.globe,overrideRtt:!!fe.rtt,precompiled:!0}})};for(const le of f){if(le.visibility==="none")continue;const me=le.getProgramIds();if(me)for(const fe of me){if(p1.has(fe))continue;const Se=le.getDefaultProgramParams(fe,y.zoom,w._styleColorTheme.lut);if(!Se)continue;const Me=H?H.getShaderSource(fe):null,qe=z&&(!Me||Me.usedDefines.has("RENDER_TO_TEXTURE"));let Ne=Se.defines;if(te&&qe&&(Ne=(Ne||[]).concat("USE_MRT1"),H.emissiveMode==="mrt-full-rgba"&&(Ne=(Ne||[]).concat("USE_MRT1_RGBA"))),Y){ne(fe,Se.defines,{params:Se}),qe&&ne(fe,Ne,{params:Se,rtt:!0});continue}const We=k&&(!Me||Me.usedDefines.has("FOG")),ct=R&&!le.isDraped()&&(!Me||Me.usedDefines.has("TERRAIN")),it=M&&(!Me||Me.usedDefines.has("GLOBE")),pt=V&&le.hasElevation()&&(!Me||Me.usedDefines.has("RENDER_SHADOWS"));for(const dt of pt?[!1,!0]:[!1]){const mt=dt?(Se.defines||[]).concat(Vg):Se.defines||[];for(const xt of ct?[!1,!0]:[!1])for(const bt of it?[!1,!0]:[!1])for(const Ft of We?[!1,!0]:[!1])ne(fe,mt,{params:Se,fog:Ft,terrain:xt,globe:bt})}qe&&ne(fe,Ne,{params:Se,rtt:!0})}}if(ne("clippingMask"),R)for(const le of[!1,!0])ne("terrainRaster",le?["TERRAIN_VERTEX_MORPHING"]:[],{terrain:!0,fog:k});if(!Y){if(f.some(le=>le.type==="hillshade")&&ne("hillshadePrepare"),V)for(const le of[!1,!0])for(const me of[!1,!0]){const fe=[];le&&fe.push("RENDER_CUTOFF"),fe.push("RENDER_SHADOWS"),me&&fe.push("NORMAL_OFFSET"),ne("groundShadow",fe),k&&ne("groundShadow",fe,{fog:!0})}if(M){for(const le of[[],["TERRAIN_VERTEX_MORPHING"],["GLOBE_POLES"]])for(const me of[!1,!0]){const fe=[...le,"PROJECTION_GLOBE_VIEW"];me&&fe.push("CUSTOM_ANTIALIASING"),ne("globeRaster",fe,{terrain:R,globe:!0,fog:k})}for(const le of[!1,!0]){const me=le?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];ne("globeAtmosphere",me,{fog:!0,terrain:R,globe:le}),ne("globeAtmosphere",[...me,"ALPHA_PASS"],{fog:!0,terrain:R,globe:le})}ne("stars",[],{fog:k,terrain:R,globe:!0})}}}_executeBatch(f,y,w){if(w.map&&w.map.isMoving())return void(this._idleHandle=l.e.requestIdleCallback(z=>this._executeBatch(z,y,w)));y.context.sweepPendingPrograms();const k=y.context.extParallelShaderCompile?o9.DEADLINE_MARGIN_KHR_MS:o9.DEADLINE_MARGIN_SYNC_MS;let R=0;for(;this._queue.length>0;){const z=this._queue.shift();if(!z||z.programId in a2&&(y.style=w,y._fogVisible=!!z.params.overrideFog,y.getOrCreateProgram(z.programId,z.params),R++,f.timeRemaining()<=k))break}const M=this._queue.length===0||f.timeRemaining()>k;R>0&&M&&y.context.gl.flush(),this._idleHandle=this._queue.length>0||y.context._pendingPrograms.size>0?l.e.requestIdleCallback(z=>this._executeBatch(z,y,w)):null}processQueue(f,y){this._queue.length!==0&&(this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._idleHandle=l.e.requestIdleCallback(w=>this._executeBatch(w,f,y)))}reset(){this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._queue=[],this._idleHandle=null,this._needsBuild=!0}};wp.DEADLINE_MARGIN_KHR_MS=5,wp.DEADLINE_MARGIN_SYNC_MS=25;let KN=wp;const g1=new l.ar(l.s.colorTheme.data);function y1(_){if(!_.metadata||!_.metadata.content_area)return;const f=l.e.devicePixelRatio,{left:y,top:w,width:k,height:R}=_.metadata.content_area,M=y*f,z=w*f;return[M,z,M+k*f,z+R*f]}function Dx(_){if(_)return _.map(([f,y])=>[f*l.e.devicePixelRatio,y*l.e.devicePixelRatio])}class x1{constructor(f,y,w){this.id=f,this.scope=y,this.sourceCache=w,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(f){this.missingRequests.has(f.name)||this.pendingRequests.has(f.name)||this.pendingRequests.add(f.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const f=new Map;if(!this.sourceCache.loaded())return f;const y=this.sourceCache.getVisibleCoordinates();if(y.length===0)return f;const w=this.sourceCache.getSource();if(w.type!=="raster-array")return f;const k=y.map(M=>this.sourceCache.getTile(M)),R=w.getImages(k,Array.from(this.pendingRequests));for(const[M,z]of R)f.set(l.I.from({name:M,iconsetId:this.id}),z),this.pendingRequests.delete(M);for(const M of this.pendingRequests)this.missingRequests.add(M);return this.pendingRequests.clear(),f}}const vr=(_,f)=>s0(_,f&&f.filter(y=>y.identifier!=="source.canvas")),YN=new Set(["addLayer","removeLayer","setLights","setPaintProperty","setLayoutProperty","setLayerProperty","setSlot","setFilter","addSource","removeSource","setLayerZoomRange","setLight","setTransition","setGeoJSONSourceData","setTerrain","setFog","setSnow","setRain","setProjection","setCamera","addImport","removeImport","updateImport","addIconset","removeIconset"]),ZN=new Set(["setCenter","setZoom","setBearing","setPitch"]),_1=new Set(["background","sky","slot","custom","placement-group"]),gd={version:8,layers:[],sources:{}},yd={duration:300,delay:0};function v1(_,f,y){return`${_}_${f}_${y}`}function v2(_,f,y){const w={min:l.du(0,0,y.tileID.canonical,f.tileID.canonical),max:l.du(l.ac,l.ac,y.tileID.canonical,f.tileID.canonical)},k=_.get(f.tileID.key);k?k.push(w):_.set(f.tileID.key,[w])}function XN(_,f){const y=new Map;let w=1/0;for(const k of _){const{z:R,x:M,y:z}=k.tileID.canonical;R1)for(const H of V)H!==k&&H.tileID.overscaledZ=w;H--){const Y=R-H,te=y.get(v1(H,M>>Y,z>>Y));if(te)for(const ne of te)v2(f,ne,k)}}}function QN(_){const f=new Map;if(_.length<2)return f;const y=new Map;for(const w of _){const k=y.get(w.tileID.wrap);k?k.push(w):y.set(w.tileID.wrap,[w])}for(const w of y.values())w.length>1&&XN(w,f);return f}class Mx extends l.E{constructor(f,y={}){super(),this.map=f,this.scope=y.scope||"",this.globalId=null,this.fragments=[],this.importDepth=y.importDepth||0,this.importsCache=y.importsCache||new Map,this.resolvedImports=y.resolvedImports||new Set,this.transition={...yd},this._buildingIndex=new o1(this),this.crossTileSymbolIndex=new y2,this.globalPlacement=null,this._groupOrders=null,this._groupOrdersVersion=-1,this._mergedOrder=[],this._mergedOrderVersion=0,this._drapedFirstOrder=[],this._mergedLayers=Object.create(null),this._mergedIndoor={},this._indoorEnabled=!1,this._mergedSourceCaches={},this._mergedOtherSourceCaches=Object.create(null),this._mergedSymbolSourceCaches=Object.create(null),this._mergedFillExtrusionSourceCaches=Object.create(null),this._mergedHdRoadCoverageSourceCaches=Object.create(null),this._hdCoverage=null,this._hdElevation=null,this._crossSourceElevationActive=!1,this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=y.styleChanges||new Le,this._hasDataDrivenEmissive=!1,this.indoorManager=null,this.dispatcher=y.dispatcher?y.dispatcher:new Ot(l1(),this),this.glyphManager=y.glyphManager?y.glyphManager:new mo(f._requestManager,y.localFontFamily?l.dF.all:y.localIdeographFontFamily?l.dF.ideographs:l.dF.none,y.localFontFamily||y.localIdeographFontFamily,y.fontstackCompositing);const w={referrer:l.dH(),config:l.dG()};if(this.map.painter&&this.map.painter.context){const k=Math.floor(this.map.painter.context.maxUniformBlockSize/4);w.contextOptions={maxUniformBlockSizeDwords:k}}if(this.isRootStyle()){const{mode:k,fontFamily:R}=this.glyphManager.localGlyphs;R&&!l.dI(R)&&(w.localGlyphs={mode:k,fontFamily:R}),this.dispatcher.broadcast("setGlobalParams",w)}y.imageManager?this.imageManager=y.imageManager:(this.imageManager=new Hr(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),y.modelManager?this.modelManager=y.modelManager:(this.modelManager=new m1(f._requestManager),this.modelManager.setEventedParent(this)),this._layers=Object.create(null),this._sourceCaches={},this._otherSourceCaches=Object.create(null),this._symbolSourceCaches=Object.create(null),this._fillExtrusionSourceCaches=Object.create(null),this._hdCoverage=null,this._hdElevation=null,this._crossSourceElevationActive=!1,this._loaded=!1,this._drapingLoaded=void 0,this._rasterArrayLoaded=void 0,this._initialBroadcastDone=!1,this._programPrecompiler=this.map._precompilePrograms&&this.isRootStyle()?new KN:null,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=y.configOptions?y.configOptions:new Map,this._layerExpressionDependencies=y.layerExpressionDependencies?y.layerExpressionDependencies:new Map,this._config=y.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:y.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=y.initialConfig,this.on("data",k=>{if(k.dataType!=="source"||k.sourceDataType!=="metadata")return;const R=this.getOwnSource(k.sourceId);if(R&&R.vectorLayerIds)for(const M in this._layers){const z=this._layers[M];z.source===R.id&&this._validateLayer(z)}})}load(f){return f?(typeof f=="string"?this.loadURL(f):this.loadJSON(f),this):this}_getGlobalId(f){if(!f)return null;if(typeof f=="string"){if(l.cX(f))return f;const y=l.dJ(f);if(!y.startsWith("http"))try{return new URL(y,location.href).toString()}catch{return y}return y}return`json://${l.dK(JSON.stringify(f))}`}_diffStyle(f,y,w){this.globalId=this._getGlobalId(f),gc();const k=(R,M)=>{try{M(null,this.setState(R,w))}catch(z){M(z,!1)}};if(typeof f=="string"){const R=this.map._requestManager.normalizeStyleURL(f),M=new AbortController;this._request={cancel:()=>M.abort()},(async()=>{const z=await this.map._requestManager.transformRequest(R,l.R.Style,M.signal),{data:V}=await l.g(z,M.signal);this._request=null,k(V,y)})().catch(z=>{this._request=null,M.signal.aborted||this.fire(new l.h(z))})}else typeof f=="object"&&k(f,y)}loadURL(f,y={}){this.fire(new l.i("dataloading",{dataType:"style"}));const w=typeof y.validate=="boolean"?y.validate:!l.cX(f);w&&gc(),f.startsWith("mapbox://styles/mapbox/standard")&&Ln(),this.globalId=this._getGlobalId(f),f=this.map._requestManager.normalizeStyleURL(f,y.accessToken),this.resolvedImports.add(f);const k=this.importsCache.get(f);if(k)return void this._load(k,w);const R=new AbortController;this._request={cancel:()=>R.abort()},(async()=>{const M=await this.map._requestManager.transformRequest(f,l.R.Style,R.signal),{data:z}=await l.g(M,R.signal);this._request=null,this.importsCache.set(f,z),this._load(z,w)})().catch(M=>{this._request=null,R.signal.aborted||this.fire(new l.h(M))})}loadJSON(f,y={}){this.fire(new l.i("dataloading",{dataType:"style"}));const w=y.validate!==!1;w&&gc(),this.globalId=this._getGlobalId(f),this._request=l.e.frame(()=>{this._request=null,this._load(f,w)})}loadEmpty(){this.fire(new l.i("dataloading",{dataType:"style"})),this._load(gd,!1)}_loadImports(f,y,w){if(this.importDepth>=4)return l.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const k=[];for(const R of f){const M=this._createFragmentStyle(R),z=new Promise(Y=>{M.once("style.import.load",Y),M.once("error",te=>{M._loaded||Y(te)})}).then(()=>{this.mergeAll(),this.fire(new l.i("data",{dataType:"style"}))});if(k.push(z),this.resolvedImports.has(R.url)){M.loadEmpty();continue}const V=R.data||this.importsCache.get(R.url);V?(R.data?(M.fire(new l.i("dataloading",{dataType:"style"})),M.globalId=M._getGlobalId(V),y&&gc(),queueMicrotask(()=>{M._load(V,y)})):M.loadJSON(V,{validate:y}),this._isInternalStyle(V)&&(M.globalId=null)):R.url?M.loadURL(R.url,{validate:y}):M.loadEmpty();const H={style:M,id:R.id,config:R.config};if(w){const Y=this.fragments.findIndex(({id:te})=>te===w);this.fragments=this.fragments.slice(0,Y).concat(H).concat(this.fragments.slice(Y))}else this.fragments.push(H)}return Promise.allSettled(k)}getImportGlobalIds(f=this,y=new Set){for(const w of f.fragments)w.style.globalId&&y.add(w.style.globalId),this.getImportGlobalIds(w.style,y);return[...y.values()]}_createFragmentStyle(f){const y=this.scope?l.m(f.id,this.scope):f.id;let w;const k=this._initialConfig&&this._initialConfig[y];(f.config||k)&&(w={...f.config,...k});const R=new Mx(this.map,{scope:y,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:w,configOptions:this.options,colorThemeOverride:f["color-theme"],layerExpressionDependencies:this._layerExpressionDependencies});return R.setEventedParent(this.map,{style:R}),R}_reloadImports(f=!1){this.mergeAll(),this._updateMapProjection(),f?this._updateEnvConfig("reset"):this.updateConfigDependencies(),this._updateLayers(this._dependentLayerIds(y=>y.isIndoorDependent)),this.map._triggerCameraUpdate(this.camera),(!f||this.isRootStyle()||this.map.style._initialBroadcastDone)&&(f&&this.isRootStyle()?(this.forEachFragmentStyle(y=>{this.dispatcher.broadcast("setLayers",{layers:y._serializeLayers(y._order),scope:y.scope,options:y.options})}),this._initialBroadcastDone=!0):this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}))}_isInternalStyle(f){return this.isRootStyle()&&(f.fragment||!!f.schema&&f.fragment!==!1)}async _load(f,y){if(this._isInternalStyle(f)){const R={id:"basemap",data:f,url:""},M={...gd,imports:[R],...f.center?{center:f.center}:{},...f.bearing?{bearing:f.bearing}:{},...f.pitch?{pitch:f.pitch}:{},...f.zoom?{zoom:f.zoom}:{},...f.light?{light:f.light}:{}};return this._importedAsBasemap=!0,void this._load(M,y)}if(y&&(await gc(),!this.dispatcher.actors.length||vr(this,Hd(f))))return;f.sprite&&this._loadIconset(f.sprite),this._loaded=!0,this.updateConfig(this._config,f.schema);for(const R in f.sources)this.addSource(R,f.sources[R],{validate:!1,isInitialLoad:!0});this.stylesheet=l.dL(f);const w=()=>{if(f.iconsets)for(const H in f.iconsets)this.addIconset(H,f.iconsets[H]);f.sprite||(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope})),!this.glyphManager.url&&f.glyphs&&this.glyphManager.setURL(f.glyphs);const R=c1(this.stylesheet.layers);if(this._order=R.map(H=>H.id),this.stylesheet.light&&l.w("The `light` root property is deprecated, prefer using `lights` with `flat` light type instead."),this.stylesheet.lights)if(this.stylesheet.lights.length===1&&this.stylesheet.lights[0].type==="flat"){const H=this.stylesheet.lights[0];this.light=new ye(H.properties,H.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new ye(this.stylesheet.light)),this._layers=Object.create(null);let M=!1;for(const H of R){const Y=l.dR(H,this.scope,this._styleColorTheme.lut,this.options);this._layerExpressionDependencies.set(Y.fqid,new be(Y)),this._hasAppearances=this._hasAppearances||Y.getAppearances().length!==0,Y.setEventedParent(this,{layer:{id:Y.id}}),this._layers[Y.id]=Y,this._updateHdCoverageSourceCache(Y)&&(M=!0);const te=this.getOwnLayerSourceCache(Y),ne=!!this.directionalLight&&this.directionalLight.shadowsEnabled();te&&Y.canCastShadows()&&ne&&(te.castsShadows=!0)}M&&al().then(()=>{if(!this.map)return;for(const Y in this._layers)this._updateHdCoverageSourceCache(this._layers[Y]);this.map.style.mergeAll();const H=this.map.transform;for(const Y in this.map.style._mergedHdRoadCoverageSourceCaches){const te=this.map.style._mergedHdRoadCoverageSourceCaches[Y];te.used=!0,H&&te.update(H)}this.map._update()}),this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const z=this.stylesheet.terrain;z&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||(this._startLiteLoad(),this._createTerrain(z,1))),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.snow&&this._createSnow(this.stylesheet.snow),this.stylesheet.rain&&this._createRain(this.stylesheet.rain),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new l.i("data",{dataType:"style"}));const V=this.isRootStyle();f.imports?this._loadImports(f.imports,y).then(()=>{this._reloadImports(!0),this.fire(new l.i(V?"style.load":"style.import.load"))}).catch(H=>{this.fire(new l.h(new Error("Failed to load imports",H))),this.fire(new l.i(V?"style.load":"style.import.load"))}):(this._reloadImports(!0),this.fire(new l.i(V?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const k=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(k){const R=this._evaluateColorThemeData(k);this._loadColorTheme(R).then(()=>{w()}).catch(M=>{l.w(`Couldn't load color theme from the stylesheet: ${M}`),w()})}else this._styleColorTheme.lut=null,w()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(f=>f.style.hasAppearances())}mergeAll(){let f,y,w,k,R,M,z,V,H,Y;const te={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(ne=>{if(ne.stylesheet){if(ne.disableElevatedTerrain&&(this.disableElevatedTerrain=!0),ne.light!=null&&(f=ne.light),ne.stylesheet.lights)for(const le of ne.stylesheet.lights)le.type==="ambient"&&ne.ambientLight!=null&&(y=ne.ambientLight),le.type==="directional"&&ne.directionalLight!=null&&(w=ne.directionalLight);k=this._prioritizeTerrain(k,ne.terrain,ne.stylesheet.terrain),ne.stylesheet.fog&&ne.fog!=null&&(R=ne.fog),ne.stylesheet.snow&&ne.snow!=null&&(M=ne.snow),ne.stylesheet.rain&&ne.rain!=null&&(z=ne.rain),ne.stylesheet.camera!=null&&(Y=ne.stylesheet.camera),ne.stylesheet.projection!=null&&(V=ne.stylesheet.projection),ne.stylesheet.transition!=null&&(H=ne.stylesheet.transition),te[ne.scope]=ne._styleColorTheme}}),this.light=f,this.ambientLight=y,this.directionalLight=w,this.fog=R,this.snow=M,this.rain=z,this._styleColorThemeForScope=te,k===null?delete this.terrain:this.terrain=k,this.camera=Y||{"camera-projection":"perspective"},this.projection=V||{name:"mercator"},this.transition={...yd,...H},this.mergeSources(),this.mergeLayers(),this.mergeIndoor(),this._programPrecompiler&&this._programPrecompiler.reset()}forEachFragmentStyle(f){const y=w=>{for(const k of w.fragments)y(k.style);f(w)};y(this)}_prioritizeTerrain(f,y,w){const k=f&&f.drapeRenderMode===0;return w===null?y&&y.drapeRenderMode===0?y:k?f:null:y!=null&&(!f||k||y&&y.drapeRenderMode===1)?y:f}mergeTerrain(){let f;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(y=>{f=this._prioritizeTerrain(f,y.terrain,y.stylesheet.terrain)}),f===null?delete this.terrain:this.terrain=f,this._programPrecompiler&&this._programPrecompiler.reset()}mergeProjection(){let f;this.forEachFragmentStyle(y=>{y.stylesheet.projection!=null&&(f=y.stylesheet.projection)}),this.projection=f||{name:"mercator"},this._programPrecompiler&&this._programPrecompiler.reset()}mergeSources(){const f={},y=Object.create(null),w=Object.create(null),k=Object.create(null),R=Object.create(null);this.forEachFragmentStyle(M=>{for(const z in M._sourceCaches){const V=l.m(z,M.scope);f[V]=M._sourceCaches[z]}for(const z in M._otherSourceCaches){const V=l.m(z,M.scope);y[V]=M._otherSourceCaches[z]}for(const z in M._symbolSourceCaches){const V=l.m(z,M.scope);w[V]=M._symbolSourceCaches[z]}for(const z in M._fillExtrusionSourceCaches){const V=l.m(z,M.scope);k[V]=M._fillExtrusionSourceCaches[z]}if(M._hdCoverage){const z=M._hdCoverage.coverageSourceCaches;for(const V in z)R[l.m(V,M.scope)]=z[V]}}),this._mergedSourceCaches=f,this._mergedOtherSourceCaches=y,this._mergedSymbolSourceCaches=w,this._mergedFillExtrusionSourceCaches=k,this._mergedHdRoadCoverageSourceCaches=R,Object.keys(R).length>0&&!this._hdCoverage&&kn.HdCoverageState&&(this._hdCoverage=new kn.HdCoverageState),kn.updateCrossSourceElevationGate&&kn.updateCrossSourceElevationGate(this)}mergeIndoor(){this._mergedIndoor={},this.forEachFragmentStyle(f=>{if(f.stylesheet&&f.stylesheet.indoor)for(const y of Object.values(f.stylesheet.indoor)){const w=y,k=l.m(w.sourceId,f.scope);this._mergedIndoor[k]=new Set(w.sourceLayers||[])}}),this._updateIndoorEnabled()}_updateIndoorEnabled(){const f=this._indoorEnabled;if(this._indoorEnabled=!1,Object.keys(this._mergedIndoor).length>0)for(const y of this._mergedOrder){const w=this._mergedLayers[y];if(w.visibility!=="none"&&this._mergedIndoor[l.m(w.source,w.scope)]){this._indoorEnabled=!0;break}}!this._indoorEnabled||f||this.indoorManager||al().then(()=>{this._initIndoorManager()})}_initIndoorManager(){if(!this.indoorManager&&kn.IndoorManager&&this.isRootStyle()&&Object.keys(this._mergedIndoor).length!==0&&(this.indoorManager=new kn.IndoorManager(this,this._loaded),this._loaded))for(const f of Object.keys(this._mergedIndoor)){const y=this._mergedSourceCaches[f]||this._mergedOtherSourceCaches[f];y&&y.reload()}}mergeLayers(){const f={},y=[],w=Object.create(null);this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(M=>{for(const z of M._order){const V=M._layers[z];if(V.type==="slot"){const H=l.dM(z);if(f[H])continue;f[H]=[]}V.slot&&f[V.slot]?f[V.slot].push(V):y.push(V)}}),this._mergedOrder=[];let k=-1;const R=(M=[])=>{for(const z of M)if(z.type==="slot"){const V=l.dM(z.id);f[V]&&R(f[V]),this._mergedSlots.push(V)}else{const V=l.m(z.id,z.scope);this._mergedOrder.push(V),w[V]=z,z.is3D(!!this.terrain)&&(this._has3DLayers=!0,k=this._mergedOrder.length-1),z.type==="circle"&&(this._hasCircleLayers=!0),z.type==="symbol"&&(this._hasSymbolLayers=!0),z.type==="clip"&&(this._clipLayerPresent=!0)}};if(R(y),this._has3DLayers){const M={};for(let z=0;zM[z]-M[V])}this._mergedLayers=w,this._mergedOrderVersion++,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(f){return this.stylesheet.camera={...this.stylesheet.camera,...f},this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(f){return f.data?new l.dE(g1,f.data,this.scope,this.options).possiblyEvaluate(new l.au(0)):null}_loadColorTheme(f){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const y=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((w,k)=>{const R="data:image/png;base64,";if(!f||f.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void w();let M=f;M.startsWith(R)||(M=R+M);const z=l.I.from("mapbox-reserved-lut"),V=new Image;V.src=M,V.onerror=()=>{this._styleColorTheme.lutLoading=!1,k(new Error("Failed to load image data"))},V.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==y)return void w();this._styleColorTheme.lutLoading=!1;const{width:H,height:Y,data:te}=l.e.getImageData(V);if(Y>32)return void k(new Error("The height of the image must be less than or equal to 32 pixels."));if(H!==Y*Y)return void k(new Error("The width of the image must be equal to the height squared."));this.getImage(z)&&this.removeImage(z),this.addImage(z,{data:new l.b({width:H,height:Y},te),pixelRatio:1,sdf:!1,usvg:!1,version:0});const ne=this.imageManager.getImage(z,this.scope);ne?(this._styleColorTheme.lut={image:ne.data,data:f},w()):k(new Error("Missing LUT image."))}})}getLut(f){const y=this._styleColorThemeForScope[f];return y?y.lut:null}setProjection(f){f?this.stylesheet.projection=f:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){this.map.transform.projection.requiresDraping&&this._startLiteLoad(),this._loaded&&(this.dispatcher.broadcast("setProjection",this.map.transform.projectionOptions),this.map.transform.projection.requiresDraping?(this.getTerrain()||this.stylesheet.terrain)&&!this.disableElevatedTerrain||this.setTerrainForDraping():this.terrainSetForDrapingOnly()&&this.setTerrain(null,0))}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection))}_loadSprite(f){const y=new AbortController;this._spriteRequest=y,function(w,k,R,M){let z,V,H;const Y=l.e.devicePixelRatio>1?"@2x":"";function te(ne){H||ne&&R.aborted||(ne&&(H=ne),function(){if(H)M(H);else if(z&&V){const le=l.e.getImageData(V),me={};for(const fe in z){const{width:Se,height:Me,x:qe,y:Ne,sdf:We,pixelRatio:ct,stretchX:it,stretchY:pt,content:dt}=z[fe],mt=new l.b({width:Se,height:Me});l.b.copy(le,mt,{x:qe,y:Ne},{x:0,y:0},{width:Se,height:Me},null),me[fe]={data:mt,pixelRatio:ct!==void 0?ct:1,sdf:We!==void 0&&We,stretchX:it,stretchY:pt,content:dt,usvg:!1,version:0}}M(null,me)}}())}(async function(){const ne=await k.transformRequest(k.normalizeSpriteURL(w,Y,".json"),l.R.SpriteJSON,R),{data:le}=await l.g(ne,R);H||(z=le)})().then(()=>te(void 0),ne=>te(ne)),async function(){const ne=await k.transformRequest(k.normalizeSpriteURL(w,Y,".png"),l.R.SpriteImage,R),{data:le}=await l.a(ne,R);H||(V=le)}().then(()=>te(void 0),ne=>te(ne))}(f,this.map._requestManager,y.signal,(w,k)=>{if(this._spriteRequest=null,w)this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new l.h(w));else if(k){const R=new Map;for(const M in k)R.set(l.I.from(M),k[M]);this.addImages(R,!0)}this.imageManager.setLoaded(!0,this.scope),this.fire(new l.i("data",{dataType:"style"}))})}addIconset(f,y){if(y.type==="sprite")return void this._loadSprite(y.url);const w=this.getOwnSourceCache(y.source);if(!w)return void this.fire(new l.h(new Error(`Source "${y.source}" as specified by iconset "${f}" does not exist and cannot be used as an iconset source`)));if(w.getSource().type!=="raster-array")return void this.fire(new l.h(new Error(`Source "${y.source}" as specified by iconset "${f}" is not a "raster-array" source and cannot be used as an iconset source`)));const k=new x1(f,this.scope,w);this.imageManager.addImageProvider(k,this.scope)}removeIconset(f){this.imageManager.removeImageProvider(f,this.scope)}_loadIconset(f){if(!l.cX(f)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(f);const y=this.map._spriteFormat==="auto",w=new AbortController;this._spriteRequest=w,async function(k,R,M,z){try{const V=await R.transformRequest(R.normalizeIconsetURL(k),l.R.Iconset,M),{data:H}=await l.n(V,M),Y={},te=function(ne){const le={icons:[]};let me;for(;me=ne.nextField(void 0);)me===1&&le.icons.push(ge(ne,ne.readVarint()+ne.pos));return le}(new l.d(H));for(const ne of te.icons){const le={version:1,pixelRatio:l.e.devicePixelRatio,content:y1(ne),stretchX:ne.metadata?Dx(ne.metadata.stretch_x_areas):void 0,stretchY:ne.metadata?Dx(ne.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:ne};Y[ne.name]=le}z(null,Y)}catch(V){M.aborted||z(V)}}(f,this.map._requestManager,w.signal,(k,R)=>{if(this._spriteRequest=null,k)y?this._loadSprite(f):(this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new l.h(k)));else if(R){const M=new Map;for(const z in R)M.set(l.I.from(z),R[z]);this.addImages(M,!0)}this.imageManager.setLoaded(!0,this.scope),this.fire(new l.i("data",{dataType:"style"}))})}_validateLayer(f){const y=this.getOwnSource(f.source);if(!y)return;const w=f.sourceLayer;w&&(y.type==="geojson"||y.vectorLayerIds&&!y.vectorLayerIds.includes(w))&&this.fire(new l.h(new Error(`Source layer "${w}" does not exist on source "${y.id}" as specified by style layer "${f.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const f in this._sourceCaches)if(!this._sourceCaches[f].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading||this._drapingLoaded===!1||this._rasterArrayLoaded===!1)return!1;for(const{style:f}of this.fragments)if(!f.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((f,y)=>{const w=this.fragments[y];return w&&w.style&&(f.data=w.style.serialize()),f})}_serializeSources(){const f={};for(const y in this._sourceCaches){const w=this._sourceCaches[y].getSource();f[w.id]||(f[w.id]=w.serialize())}return f}_serializeLayers(f){const y=[];for(const w of f){const k=this._layers[w];k&&k.type!=="custom"&&y.push(k.serialize())}return y}hasLightTransitions(){return!(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return!!this.fog&&this.fog.hasTransition()}hasSnowTransition(){return!!this.snow&&this.snow.hasTransition()}hasRainTransition(){return!!this.rain&&this.rain.hasTransition()}hasTransitions(){if(this.hasLightTransitions()||this.hasFogTransition()||this.hasSnowTransition()||this.hasRainTransition())return!0;for(const f in this._mergedSourceCaches)if(this._mergedSourceCaches[f].hasTransition())return!0;for(const f in this._mergedLayers)if(this._mergedLayers[f].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const f in this._mergedLayers){const y=this._mergedLayers[f].getPaintPropertyValue("line-emissive-strength");if(y&&y.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(f){return f?this.order:this._mergedOrder}isLayerDraped(f){return!!this.terrain&&f.isDraped(this.getLayerSourceCache(f))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(f){const y=this.getOwnLayer(f);if(y)return y;this.fire(new l.h(new Error(`The layer '${f}' does not exist in the map's style.`)))}_checkSource(f){const y=this.getOwnSource(f);if(y)return y;this.fire(new l.h(new Error(`The source '${f}' does not exist in the map's style.`)))}_resolveLayerFragment(f){const y=this.getLayer(f);if(!y)return void this.fire(new l.h(new Error(`The layer '${f}' does not exist in the map's style.`)));const w=this.getFragmentStyle(y.scope);return w?{layer:y,fragment:w}:void 0}handleIdle(){const f=this.map.painter;f&&(f.context.sweepPendingPrograms(),this._programPrecompiler&&this._programPrecompiler.processQueue(f,this))}handleContextLost(){this._programPrecompiler&&this._programPrecompiler.reset()}update(f){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(f),this.directionalLight&&this.directionalLight.recalculate(f);const y=this.calculateLightsBrightness();f.brightness=y||0;let w=!1;y!==this._brightness&&(this._brightness=y,w=!0),f.worldview!==this._worldview&&(this._worldview=f.worldview,w=!0),w&&this.dispatcher.broadcast("upsertRenderParams",{brightness:this._brightness,worldview:this._worldview});const k=this._changes.isDirty();let R=!1;if(this._changes.isDirty()){const H=this._changes.getLayerUpdatesByScope();for(const Y in H){const{updatedIds:te,removedIds:ne}=H[Y];(te||ne)&&(this._updateWorkerLayers(Y,te,ne),R=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(f),this.light&&this.light.updateTransitions(f),this.ambientLight&&this.ambientLight.updateTransitions(f),this.directionalLight&&this.directionalLight.updateTransitions(f),this.fog&&this.fog.updateTransitions(f),this.snow&&this.snow.updateTransitions(f),this.rain&&this.rain.updateTransitions(f),this._changes.reset()}const M={};for(const H in this._mergedSourceCaches){const Y=this._mergedSourceCaches[H];M[H]=Y.used,Y.used=!1,Y.tileCoverLift=0}const z={};for(const H of this._mergedOrder){const Y=this._mergedLayers[H],te=Y.paint;if(Y.visibility==="none"&&!Y.hasTransition()||!Y._dirty&&Y.isHidden(f.zoom)||Y.recalculate(f,this._availableImages),te&&te!==Y.paint&&Y.isPlacementAffectedByPaintChanges(te)&&this._setLabelPlacementStale(),!Y.isHidden(f.zoom)){Y.mayUse("HD")&&(Y.prepare(),al()),Y.mayUse("Standard")&&(Y.prepare(),Ln()),Y.mayUse("Lite")&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this._startLiteLoad()),Y.mayUse("RasterArray")&&this._startRasterArrayLoad();const ne=this.getLayerSourceCache(Y);ne&&(ne.used=!0,ne.tileCoverLift=Math.max(ne.tileCoverLift,Y.tileCoverLift()))}if(Y.source){const ne=this._mergedHdRoadCoverageSourceCaches[Y.sourceFqid];ne&&!ne.used&&(ne.used=!0)}if(Y.type==="fill-extrusion"){const ne=l.m(Y.source,Y.scope);if(ne in this._mergedFillExtrusionSourceCaches){const le=Y.layout&&Y.layout.get("source-max-zoom");if(le!=null){const me=z[ne];z[ne]=me==null?le:Math.min(me,le)}}}}if(this._programPrecompiler&&this._programPrecompiler.needsBuild()){const H=this._mergedOrder.map(Y=>this._mergedLayers[Y]);this._programPrecompiler.buildQueue(H,f,this)}for(const H in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[H].setMaxzoomOverride(z[H]??null);this.terrain&&R&&this.mergeLayers();const V=this.imageManager.getPendingImageProviders();for(const H of V)H.sourceCache.used=!0;for(const H in M){const Y=this._mergedSourceCaches[H],te=Y.getSource();Y.used&&te instanceof kh&&te.startLoad(),M[H]!==Y.used&&te.fire(new l.i("data",{sourceDataType:"visibility",dataType:"source",sourceId:te.id}))}this.light&&this.light.recalculate(f),this.terrain&&this.terrain.recalculate(f),this.fog&&this.fog.recalculate(f),this.snow&&this.snow.recalculate(f),this.rain&&this.rain.recalculate(f),this.z=f.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),k&&this.fire(new l.i("data",{dataType:"style"}))}updateImageProviders(){const f=this.imageManager.getPendingImageProviders();for(const y of f){const w=y.resolvePendingRequests(),k=this.getFragmentStyle(y.scope);k&&k.addImages(w)}}_updateTilesForChangedImages(){const f={};for(const y in this._mergedSourceCaches){const w=this._mergedSourceCaches[y].getSource().scope;f[w]=f[w]||this._changes.getUpdatedImages(w),f[w].length!==0&&this._mergedSourceCaches[y].reloadTilesForDependencies(["icons","patterns"],f[w])}for(const y in f)this._changes.resetUpdatedImages(y)}_updateWorkerLayers(f,y,w){const k=this.getFragmentStyle(f);k&&this.dispatcher.broadcast("updateLayers",{layers:y?k._serializeLayers(y):[],scope:f,removedIds:w||[],options:k.options})}setState(f,y){if(this._checkLoaded(),vr(this,Hd(f)))return!1;if((f=l.dL(f)).layers=c1(f.layers),!du.diffStyles)throw new Error("Debug module not loaded; cannot diff style.");const w=du.diffStyles(this.serialize(),f).filter(M=>!ZN.has(M.command));if(w.length===0)return!1;const k=w.filter(M=>!YN.has(M.command));if(k.length>0)throw new Error(`Unimplemented: ${k.map(M=>M.command).join(", ")}.`);const R=[];return w.forEach(M=>{R.push(this[M.command](...M.args))}),y&&Promise.all(R).then(y).catch(y),this.stylesheet=f,this.mergeAll(),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}_updateWorkerImages(f=!1){this._availableImages=this.imageManager.listImages(this.scope);const y={scope:this.scope,images:this._availableImages};f&&(y.isSpriteLoaded=!0),this.dispatcher.broadcast("setImages",y)}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(f,y){if(f.size===0)return y&&this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this;for(const[w,k]of f.entries()){if(this.getImage(w))return this.fire(new l.h(new Error(`An image with the name "${w.name}" already exists.`)));this.imageManager.addImage(w,this.scope,k),this._changes.updateImage(w,this.scope)}return this._updateWorkerImages(y),this.fire(new l.i("data",{dataType:"style"})),this}addImage(f,y){return this.getImage(f)?this.fire(new l.h(new Error(`An image with the name "${f.name}" already exists.`))):(this.imageManager.addImage(f,this.scope,y),this._changes.updateImage(f,this.scope),this._updateWorkerImages(),this.fire(new l.i("data",{dataType:"style"})),this)}updateImage(f,y,w=!1){this.imageManager.updateImage(f,this.scope,y),w&&(this._changes.updateImage(f,this.scope),this._updateWorkerImages(),this.fire(new l.i("data",{dataType:"style"})))}getImage(f){return this.imageManager.getImage(f,this.scope)}removeImage(f){return this.getImage(f)?(this.imageManager.removeImage(f,this.scope),this._changes.updateImage(f,this.scope),this._updateWorkerImages(),this.fire(new l.i("data",{dataType:"style"})),this):this.fire(new l.h(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(f){return this.modelManager.addModelURLs(f,this.getActualScope()),this._updateWorkerModels(),this.fire(new l.i("data",{dataType:"style"})),this}addModel(f,y,w={}){return this._checkLoaded(),this._validate(hu,`models.${f}`,y,null,w)||(this.modelManager.addModel(f,y,this.getActualScope()),this.fire(new l.i("data",{dataType:"style"}))),this}hasModel(f){return this.modelManager.hasModel(f,this.getActualScope())}removeModel(f){return this.hasModel(f)?(this.modelManager.removeModel(f,this.getActualScope(),!1,!0),this.fire(new l.i("data",{dataType:"style"})),this):this.fire(new l.h(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(f,y,w={}){if(this._checkLoaded(),this.getOwnSource(f)!==void 0)throw new Error(`There is already a source with ID "${f}".`);if(!y.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(y).join(", ")}.`);if(["vector","raster","geojson","video","image"].includes(y.type)&&this._validate(a0,`sources.${f}`,y,null,w))return;this.map&&this.map._collectResourceTiming&&(y.collectResourceTiming=!0);const k=Object.hasOwn(jx,y.type)&&!v0(y.type)?new kh(f,y,this.dispatcher,this):void 0,R=k||c2(f,y,this.dispatcher,this);R.scope=this.scope;const M=V=>{V.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(V.id),source:V.serialize(),sourceId:V.id}))};M(R);const z=V=>{const H=(V===l.b_.Symbol?"symbol:":V===l.b_.FillExtrusion?"fill-extrusion:":"other:")+R.id,Y=l.m(H,this.scope),te=this._sourceCaches[H]=new il(Y,R,V);V===l.b_.Symbol?this._symbolSourceCaches[R.id]=te:V===l.b_.FillExtrusion?this._fillExtrusionSourceCaches[R.id]=te:this._otherSourceCaches[R.id]=te,te.onAdd(this.map)};z(l.b_.Other),y.type!=="vector"&&y.type!=="geojson"||(z(l.b_.Symbol),y.type==="vector"&&z(l.b_.FillExtrusion)),R.onAdd&&R.onAdd(this.map),k&&(k._loader=()=>{(async function(V){if(v0(V))return;const H=jx[V];if(!H)throw new Error(`Unknown source type "${V}"`);const Y=await H();Y&&!v0(V)&&function(te,ne){s1[te]=ne}(V,Y)})(y.type).then(()=>{const V=v0(y.type),H=this._otherSourceCaches[f];if(!H||H.getSource()!==R)return;if(!V)return void this.fire(new l.h(new Error(`Could not load module for source type "${y.type}".`)));const Y=c2(f,y,this.dispatcher,this);Y.scope=this.scope,M(Y),H.setSource(Y),Y.onAdd&&Y.onAdd(this.map),this._changes.setDirty()})}),w.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(f){this._checkLoaded();const y=this.getOwnSource(f);if(!y)throw new Error("There is no source with this ID");for(const k in this._layers)if(this._layers[k].source===f)return this.fire(new l.h(new Error(`Source "${f}" cannot be removed while layer "${k}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===f)return this.fire(new l.h(new Error(`Source "${f}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const k=Object.entries(this.stylesheet.iconsets).find(([R,M])=>M.type==="source"&&M.source===f);if(k)return this.fire(new l.h(new Error(`Source "${f}" cannot be removed while iconset "${k[0]}" is using it.`)))}const w=this.getOwnSourceCaches(f);for(const k of w){const R=l.dM(k.id);delete this._sourceCaches[R],this._changes.discardSourceCacheUpdate(k.id),k.fire(new l.i("data",{sourceDataType:"metadata",dataType:"source",sourceId:k.getSource().id})),k.setEventedParent(null),k.clearTiles()}return delete this._otherSourceCaches[f],delete this._symbolSourceCaches[f],delete this._fillExtrusionSourceCaches[f],this._hdCoverage&&delete this._hdCoverage.coverageSourceCaches[f],this.mergeSources(),y.setEventedParent(null),y.onRemove&&y.onRemove(this.map),this.dispatcher.broadcast("removeSource",{type:y.type,source:f,scope:y.scope}),this._changes.setDirty(),this}setGeoJSONSourceData(f,y){this._checkLoaded(),this.getOwnSource(f).setData(y),this._changes.setDirty()}getOwnSource(f){const y=this.getOwnSourceCache(f);return y&&y.getSource()}getOwnSources(){const f=[];for(const y in this._otherSourceCaches){const w=this.getOwnSourceCache(y);w&&f.push(w.getSource())}return f}areTilesLoaded(){const f=this._mergedSourceCaches;for(const y in f){const w=f[y];for(const k of w._tiles.values())if(k.state!=="loaded"&&k.state!=="errored")return!1}return!0}setLights(f){if(this._checkLoaded(),this._programPrecompiler&&this._programPrecompiler.reset(),!f)return delete this.ambientLight,void delete this.directionalLight;const y=this._getTransitionParameters();for(const R of f){if(this._validate(o0,"lights",R))return;switch(R.type){case"ambient":if(this.ambientLight){const M=this.ambientLight;M.set(R),M.updateTransitions(y)}else this.ambientLight=new pr(R,er(),this.scope,this.options);break;case"directional":if(this.directionalLight){const M=this.directionalLight;M.set(R),M.updateTransitions(y)}else this.directionalLight=new pr(R,Rr(),this.scope,this.options)}}const w=Object.assign(y,{worldview:this.map.getWorldview()}),k=new l.au(this.z||0,w);this.ambientLight&&this.ambientLight.recalculate(k),this.directionalLight&&this.directionalLight.recalculate(k),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("upsertRenderParams",{brightness:this._brightness})}calculateLightsBrightness(){const f=this.directionalLight,y=this.ambientLight;if(!f||!y)return;const w=ne=>.2126*(ne[0]<=.03928?ne[0]/12.92:Math.pow((ne[0]+.055)/1.055,2.4))+.7152*(ne[1]<=.03928?ne[1]/12.92:Math.pow((ne[1]+.055)/1.055,2.4))+.0722*(ne[2]<=.03928?ne[2]/12.92:Math.pow((ne[2]+.055)/1.055,2.4)),k=f.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),R=f.properties.get("intensity"),M=f.properties.get("direction"),z=1-l.c4(M.x,M.y,M.z)[2]/90,V=w(k)*R*z,H=y.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Y=y.properties.get("intensity"),te=w(H)*Y;return Number(((V+te)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const f=[];return this.directionalLight&&f.push(this.directionalLight.get()),this.ambientLight&&f.push(this.ambientLight.get()),f}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(f){if(f==null||f===""&&this.isRootStyle())return this;if(l.dN(f)){const y=l.dO(f),w=this.fragments.find(({id:R})=>R===y);if(!w)return;const k=l.dM(f);return w.style.getFragmentStyle(k)}{const y=this.fragments.find(({id:w})=>w===f);return y?y.style:void 0}}setFeaturesetSelectors(f){if(!f)return;const y=(w,k="")=>`${w}::${k}`;this._featuresetSelectors={};for(const w in f){const k={},R=this._featuresetSelectors[w]=[];for(const M of f[w].selectors){if(M.featureNamespace){const V=this.getOwnLayer(M.layer);if(!V){l.w(`Layer is undefined for selector: ${M.layer}`);continue}const H=y(V.source,V.sourceLayer);if(H in k&&k[H]!==M.featureNamespace){l.w(`"featureNamespace ${M.featureNamespace} of featureset ${w}'s selector is not associated to the same source, skip this selector`);continue}k[H]=M.featureNamespace}let z;if(M.properties)for(const V in M.properties){const H=l.c(M.properties[V]);H.result==="success"&&(z=z||{},z[V]=H.value)}R.push({layerId:M.layer,namespace:M.featureNamespace,properties:z,uniqueFeatureID:M._uniqueFeatureID})}}}getFeaturesetDescriptors(f){const y=this.getFragmentStyle(f);if(!y||!y.stylesheet.featuresets)return[];const w=[];for(const k in y.stylesheet.featuresets)w.push({featuresetId:k,importId:y.scope?y.scope:void 0});return w}getFeaturesetLayers(f,y){const w=this.getFragmentStyle(y),k=w.stylesheet.featuresets;if(!k||!k[f])return this.fire(new l.h(new Error(`The featureset '${f}' does not exist in the map's style and cannot be queried.`))),[];const R=[];for(const M of k[f].selectors){const z=w.getOwnLayer(M.layer);z&&R.push(z)}return R}getConfigProperty(f,y){const w=this.getFragmentStyle(f);if(!w)return null;const k=l.m(y,w.scope),R=w.options.get(k),M=R?R.value||R.default:null;return M?M.serialize():null}isIndoorEnabled(){return this._indoorEnabled}getIndoorSourceLayers(f,y){const w=l.m(f,y);return this._mergedIndoor[w]}setIndoorData(f,y){this.indoorManager&&this.indoorManager.setIndoorData(y)}updateIndoorDependentLayers(){this._updateLayers(this._dependentLayerIds(f=>f.isIndoorDependent)),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(f,y,w){const k=this.getFragmentStyle(f);if(!k)return;const R=k.stylesheet.schema;if(!R||!R[y])return;const M=l.dP(w,R[y]);if(M.result!=="success")return void vr(this,M.value);const z=M.value.expression,V=l.m(y,k.scope),H=k.options.get(V);if(!H)return;let Y;const{minValue:te,maxValue:ne,stepValue:le,type:me,values:fe}=R[y],Se=l.dP(R[y].default,R[y]);Se.result==="success"&&(Y=Se.value.expression),Y?(this.options.set(V,{...H,value:z,default:Y,minValue:te,maxValue:ne,stepValue:le,type:me,values:fe}),this.updateConfigDependencies(y)):this.fire(new l.h(new Error(`No schema defined for the config option "${y}" in the "${f}" fragment.`)))}getConfig(f){const y=this.getFragmentStyle(f);if(!y)return null;const w=y.stylesheet.schema;if(!w)return null;const k={};for(const R in w){const M=l.m(R,y.scope),z=y.options.get(M),V=z?z.value||z.default:null;k[R]=V?V.serialize():null}return k}setConfig(f,y){const w=this.getFragmentStyle(f);w&&(w.updateConfig(y,w.stylesheet.schema),this.updateConfigDependencies())}getSchema(f){const y=this.getFragmentStyle(f);return y?y.stylesheet.schema:null}setSchema(f,y){const w=this.getFragmentStyle(f);w&&(w.stylesheet.schema=y,w.updateConfig(w._config,y),this.updateConfigDependencies())}updateConfig(f,y){if(this._config=f,f||y)if(y)for(const w in y){let k,R;const M=l.dP(y[w].default,y[w]);if(M.result==="success"&&(k=M.value.expression),f&&f[w]!==void 0){const ne=l.dP(f[w],y[w]);ne.result==="success"&&(R=ne.value.expression)}const{minValue:z,maxValue:V,stepValue:H,type:Y,values:te}=y[w];if(k){const ne=l.m(w,this.scope);this.options.set(ne,{default:k,value:R,minValue:z,maxValue:V,stepValue:H,type:Y,values:te})}else this.fire(new l.h(new Error(`No schema defined for config option "${w}".`)))}else this.fire(new l.h(new Error("Attempting to set config for a style without schema.")))}_updateLayers(f){for(const y of f){const w=this.getLayer(y);w&&(w.possiblyEvaluateVisibility(),w._dirty=!0,this._updateLayer(w),this._changes.setDirty())}}_dependentLayerIds(f){const y=[];for(const[w,k]of this._layerExpressionDependencies)f(k)&&y.push(w);return y}_updateEnvConfig(f="update"){const y=f==="reset"?"resetConfig":"updateConfig";this.ambientLight&&this.ambientLight[y](this.options),this.directionalLight&&this.directionalLight[y](this.options),this.fog&&this.fog[y](this.options),this.snow&&this.snow[y](this.options),this.rain&&this.rain[y](this.options)}updateConfigDependencies(f){this._updateLayers(this._dependentLayerIds(y=>y.hasConfigDependency(f))),this._updateEnvConfig(),this.forEachFragmentStyle(y=>{const w=y._styleColorTheme.colorThemeOverride?y._styleColorTheme.colorThemeOverride:y._styleColorTheme.colorTheme;if(w){const k=y._evaluateColorThemeData(w);(!y._styleColorTheme.lut&&k!==""||y._styleColorTheme.lut&&k!==y._styleColorTheme.lut.data)&&y.setColorTheme(w)}}),this._updateIndoorEnabled(),this._changes.setDirty()}addLayer(f,y,w={}){this._checkLoaded();const k=f.id;if(this._layers[k])return void this.fire(new l.h(new Error(`Layer with id "${k}" already exists on this map`)));let R;if(f.type==="custom"){if(vr(this,l.dQ(f)))return;R=l.dR(f,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof f.source=="object"&&(this.addSource(k,f.source),f=l.dL(f),f=Object.assign(f,{source:k})),this._validate(xx,`layers.${k}`,f,{arrayIndex:-1},w))return;R=l.dR(f,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(R),R.setEventedParent(this,{layer:{id:k}})}this._layerExpressionDependencies.set(R.fqid,new be(R));let M=this._order.length;if(y){const Y=this._order.indexOf(y);if(Y===-1)return void this.fire(new l.h(new Error(`Layer with id "${y}" does not exist on this map.`)));R.slot&&R.slot!==this._layers[y].slot?l.w(`Layer with id "${y}" has a different slot. Layers can only be rearranged within the same slot.`):M=Y}this._order.splice(M,0,k),this._handleLayerOrderChange(),this._layers[k]=R;const z=this.getOwnLayerSourceCache(R),V=!!this.directionalLight&&this.directionalLight.shadowsEnabled();z&&R.canCastShadows()&&V&&(z.castsShadows=!0);const H=this._changes.getRemovedLayer(R);if(H&&R.source&&z&&R.type!=="custom"){this._changes.discardLayerRemoval(R);const Y=l.m(R.source,R.scope);H.type!==R.type?this._changes.updateSourceCache(Y,"clear"):(this._changes.updateSourceCache(Y,"reload"),z.pause())}this._updateLayer(R),R.onAdd&&R.onAdd(this.map),R.scope=this.scope,this.mergeLayers()}moveLayer(f,y){this._checkLoaded();const w=this._checkLayer(f);if(!w||f===y)return;const k=this._order.indexOf(f);this._order.splice(k,1);let R=this._order.length;if(y){const M=this._order.indexOf(y);if(M===-1)return void this.fire(new l.h(new Error(`Layer with id "${y}" does not exist on this map.`)));w.slot&&w.slot!==this._layers[y].slot?l.w(`Layer with id "${y}" has a different slot. Layers can only be rearranged within the same slot.`):R=M}this._order.splice(R,0,f),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(f){this._checkLoaded();const y=this._checkLayer(f);if(!y)return;y.setEventedParent(null);const w=this._order.indexOf(f);this._order.splice(w,1),delete this._layers[f],this._changes.setDirty(),this._handleLayerOrderChange(),this._layerExpressionDependencies.delete(y.fqid),this._changes.removeLayer(y);const k=this.getOwnLayerSourceCache(y);if(k&&k.castsShadows){let R=!1;for(const M in this._layers)if(this._layers[M].source===y.source&&this._layers[M].canCastShadows()){R=!0;break}k.castsShadows=R}y.onRemove&&y.onRemove(this.map),this.mergeLayers()}getOwnLayer(f){return this._layers[f]}hasLayer(f){return f in this._mergedLayers}hasLayerType(f){for(const y in this._layers)if(this._layers[y].type===f)return!0;return!1}setLayerZoomRange(f,y,w){this._checkLoaded();const k=this._checkLayer(f);k&&(k.minzoom===y&&k.maxzoom===w||(y!=null&&(k.minzoom=y),w!=null&&(k.maxzoom=w),this._updateLayer(k)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(f,y){this._checkLoaded();const w=this._checkLayer(f);w&&w.slot!==y&&(w.slot=y,this._updateLayer(w))}setFilter(f,y,w={}){this._checkLoaded();const k=this._checkLayer(f);if(!k||l.Y(k.filter,y))return;const R=this._layerExpressionDependencies.get(k.fqid);if(y==null)return k.filter=void 0,R&&R.invalidateFilter(),void this._updateLayer(k);this._validate(dd,`layers.${k.id}.filter`,y,{layerType:k.type},w)||(k.filter=l.dL(y),R&&R.invalidateFilter(),this._updateLayer(k))}getFilter(f){const y=this._checkLayer(f);if(y)return l.dL(y.filter)}setLayoutProperty(f,y,w,k={}){this._checkLoaded();const R=this._checkLayer(f);if(R&&!l.Y(R.getLayoutProperty(y),w)){if(w!=null&&(!k||k.validate!==!1)&&vr(R,$w.call(Hd,{key:`layers.${f}.layout.${y}`,layerType:R.type,objectKey:y,value:w,styleSpec:l.s,style:{glyphs:!0,sprite:!0}})))return;R.setLayoutProperty(y,w),this._updateLayer(R)}}getLayerProperty(f,y){const w=this._checkLayer(f);if(w){switch(y){case"minzoom":return w.minzoom;case"maxzoom":return w.maxzoom;case"filter":return this.getFilter(f);case"slot":return w.slot;case"appearances":return w.getAppearances().map(k=>k.serialize())}return w.isPaintProperty(y)?this.getPaintProperty(f,y):this.getLayoutProperty(f,y)}}setLayerProperty(f,y,w,k={}){this._checkLoaded();const R=this._checkLayer(f);if(R){switch(y){case"appearances":return R.setAppearances(w),void this._updateLayer(R);case"minzoom":return this.setLayerZoomRange(f,w);case"maxzoom":return this.setLayerZoomRange(f,null,w);case"filter":return this.setFilter(f,w,k);case"slot":return this.setSlot(f,w)}R.isPaintProperty(y)?this.setPaintProperty(f,y,w,k):this.setLayoutProperty(f,y,w,k)}}getLayoutProperty(f,y){const w=this._checkLayer(f);if(w)return w.getLayoutProperty(y)}setPaintProperty(f,y,w,k={}){this._checkLoaded();const R=this._checkLayer(f);R&&(l.Y(R.getPaintProperty(y),w)||(w==null||k&&k.validate===!1||!vr(R,im.call(Hd,{key:`layers.${f}.paint.${y}`,layerType:R.type,objectKey:y,value:w,styleSpec:l.s})))&&(R.setPaintProperty(y,w)&&this._updateLayer(R),this._changes.updatePaintProperties(R)))}getPaintProperty(f,y){const w=this._checkLayer(f);if(w)return w.getPaintProperty(y)}setFeatureState(f,y){if(this._checkLoaded(),"target"in f){if("featuresetId"in f.target){const{featuresetId:V,importId:H}=f.target,Y=this.getFragmentStyle(H),te=Y.getFeaturesetLayers(V);for(const{source:ne,sourceLayer:le}of te)Y.setFeatureState({id:f.id,source:ne,sourceLayer:le},y)}else if("layerId"in f.target){const V=this._resolveLayerFragment(f.target.layerId);V==null||V.fragment.setFeatureState({id:f.id,source:V.layer.source,sourceLayer:V.layer.sourceLayer},y)}return}const w=f.source,k=f.sourceLayer,R=this._checkSource(w);if(!R)return;const M=R.type;if(M==="geojson"&&k)return void this.fire(new l.h(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(M==="vector"&&!k)return void this.fire(new l.h(new Error("The sourceLayer parameter must be provided for vector source types.")));f.id===void 0&&this.fire(new l.h(new Error("The feature id parameter must be provided.")));const z=this.getOwnSourceCaches(w);for(const V of z)V.setFeatureState(k,f.id,y)}removeFeatureState(f,y){if(this._checkLoaded(),"target"in f){if("featuresetId"in f.target){const{featuresetId:V,importId:H}=f.target,Y=this.getFragmentStyle(H),te=Y.getFeaturesetLayers(V);for(const{source:ne,sourceLayer:le}of te)Y.removeFeatureState({id:f.id,source:ne,sourceLayer:le},y)}else if("layerId"in f.target){const V=this._resolveLayerFragment(f.target.layerId);V==null||V.fragment.removeFeatureState({id:f.id,source:V.layer.source,sourceLayer:V.layer.sourceLayer},y)}return}const w=f.source,k=this._checkSource(w);if(!k)return;const R=k.type,M=R==="vector"?f.sourceLayer:void 0;if(R==="vector"&&!M)return void this.fire(new l.h(new Error("The sourceLayer parameter must be provided for vector source types.")));if(y&&typeof f.id!="string"&&typeof f.id!="number")return void this.fire(new l.h(new Error("A feature id is required to remove its specific state property.")));const z=this.getOwnSourceCaches(w);for(const V of z)V.removeFeatureState(M,f.id,y)}getFeatureState(f){if(this._checkLoaded(),"target"in f){let R;if("featuresetId"in f.target){const{featuresetId:M,importId:z}=f.target,V=this.getFragmentStyle(z),H=V.getFeaturesetLayers(M);for(const{source:Y,sourceLayer:te}of H){const ne=V.getFeatureState({id:f.id,source:Y,sourceLayer:te});if(ne&&!R)R=ne;else if(!l.Y(R,ne))return void this.fire(new l.h(new Error("The same feature id exists in multiple sources in the featureset, but their feature states are not consistent through the sources.")))}}else if("layerId"in f.target){const M=this._resolveLayerFragment(f.target.layerId);R=M==null?void 0:M.fragment.getFeatureState({id:f.id,source:M.layer.source,sourceLayer:M.layer.sourceLayer})}return R}const y=f.source,w=f.sourceLayer,k=this._checkSource(y);if(k){if(k.type!=="vector"||w)return f.id===void 0&&this.fire(new l.h(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(y)[0].getFeatureState(w,f.id);this.fire(new l.h(new Error("The sourceLayer parameter must be provided for vector source types.")))}}resetFeatureStates(f){if(this._checkLoaded(),"featuresetId"in f){const{featuresetId:y,importId:w}=f,k=this.getFragmentStyle(w);if(!k)return;const R=k.getFeaturesetLayers(y);for(const{source:M,sourceLayer:z}of R)k.removeFeatureState({source:M,sourceLayer:z})}else{const y=this._resolveLayerFragment(f.layerId);y==null||y.fragment.removeFeatureState({source:y.layer.source,sourceLayer:y.layer.sourceLayer})}}setTransition(f){return this.stylesheet.transition={...this.stylesheet.transition,...f},this.transition=this.stylesheet.transition,this}getTransition(){return{...this.stylesheet.transition}}setWorldview(f){f!==this._worldview&&(this._worldview=f,this.dispatcher.broadcast("upsertRenderParams",{worldview:this._worldview}),this.reloadSources())}serialize(){this._checkLoaded();const f=this.getTerrain(),y=f&&this.terrain&&this.terrain.scope===this.scope?f:this.stylesheet.terrain;return l.dS({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,featuresets:this.stylesheet.featuresets,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:y,fog:this.stylesheet.fog,snow:this.stylesheet.snow,rain:this.stylesheet.rain,indoor:this.stylesheet.indoor,center:this.stylesheet.center,"color-theme":this.stylesheet["color-theme"],zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,projection:this.stylesheet.projection,sources:this._serializeSources(),layers:this._serializeLayers(this._order)},w=>w!==void 0)}_updateFilteredLayers(f){for(const y of Object.values(this._mergedLayers))f(y)&&this._updateLayer(y)}_updateLayer(f){this._changes.updateLayer(f);const y=this.getLayerSourceCache(f),w=f.sourceFqid,k=this._changes.getUpdatedSourceCaches();f.source&&!k[w]&&y&&y.getSource().type!=="raster"&&(this._changes.updateSourceCache(w,"reload"),y.pause()),f.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(f){const y=z=>this._mergedLayers[z].is3D(!!this.terrain),w=this.order,k={},R=[];for(let z=w.length-1;z>=0;z--){const V=w[z];if(y(V)){k[V]=z;for(const H of f){const Y=H[V];if(Y)for(const te of Y)R.push(te)}}}R.sort((z,V)=>V.intersectionZ-z.intersectionZ);const M=[];for(let z=w.length-1;z>=0;z--){const V=w[z];if(y(V))for(let H=R.length-1;H>=0;H--){const Y=R[H].feature;if(Y.layer&&k[Y.layer.id]{if(_1.has(Y.type))return;const te=this.getOwnLayerSourceCache(Y),ne=R[te.id]=R[te.id]||{sourceCache:te,layers:{},has3DLayers:!1};Y.is3D(!!this.terrain)&&(ne.has3DLayers=!0),ne.layers[Y.fqid]=ne.layers[Y.fqid]||{styleLayer:Y,targets:[]},ne.layers[Y.fqid].targets.push({filter:k})};if(y&&y.layers){if(!Array.isArray(y.layers))return this.fire(new l.h(new Error("parameters.layers must be an Array."))),[];for(const Y of y.layers){const te=this._layers[Y];if(!te)return this.fire(new l.h(new Error(`The layer '${Y}' does not exist in the map's style and cannot be queried for features.`))),[];M(te)}}else for(const Y in this._layers)M(this._layers[Y]);const z=this._queryRenderedFeatures(f,R,w),V=this._flattenAndSortRenderedFeatures(z),H=[];for(const Y of V)l.dT(Y.layer.id)===this.scope&&H.push(Y);return H}queryRenderedFeatureset(f,y,w){let k;y&&!Array.isArray(y)&&y.filter&&(this._validate(dd,"queryRenderedFeatures.filter",y.filter,null,y),k=l.bH(y.filter));const R="mock",M=[];if(y&&y.target)M.push({...y,targetId:R,filter:k});else{const Y=this.getFeaturesetDescriptors();for(const te of Y)M.push({targetId:R,filter:k,target:te});for(const{style:te}of this.fragments){const ne=te.getFeaturesetDescriptors();for(const le of ne)M.push({targetId:R,filter:k,target:le})}}const z=this.queryRenderedTargets(f,M,w),V=[],H=new Set;for(const Y of z)for(const te of Y.variants[R])u2(te,Y,H)||V.push(new l.dU(Y,te));return V}queryRenderedTargets(f,y,w){const k={},R=(z,V,H,Y)=>{const te=k[V.id]=k[V.id]||{sourceCache:V,layers:{},has3DLayers:!1};if(te.layers[z.fqid]=te.layers[z.fqid]||{styleLayer:z,targets:[]},z.is3D(!!this.terrain)&&(te.has3DLayers=!0),!Y)return H.uniqueFeatureID=!1,void te.layers[z.fqid].targets.push(H);te.layers[z.fqid].targets.push({...H,namespace:Y.namespace,properties:Y.properties,uniqueFeatureID:Y.uniqueFeatureID})};for(const z of y)if("featuresetId"in z.target){const{featuresetId:V,importId:H}=z.target,Y=this.getFragmentStyle(H);if(!Y||!Y._featuresetSelectors)continue;const te=Y._featuresetSelectors[V];if(!te){this.fire(new l.h(new Error(`The featureset '${V}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const ne of te){const le=Y.getOwnLayer(ne.layerId);le&&!_1.has(le.type)&&R(le,Y.getOwnLayerSourceCache(le),z,ne)}}else if("layerId"in z.target){const{layerId:V}=z.target,H=this.getLayer(V);if(!H||_1.has(H.type))continue;R(H,this.getLayerSourceCache(H),z)}const M=this._queryRenderedFeatures(f,k,w);return this._flattenAndSortRenderedFeatures(M)}_queryRenderedFeatures(f,y,w){const k=[],R=!!this.map._showQueryGeometry,M=n1.createFromScreenPoints(f,w);for(const z in y){const V=pd(M,y[z],this._availableImages,w,R,this.getActualScope());Object.keys(V).length&&k.push(V)}if(this.placement)for(const z in y){if(y[z].sourceCache._renderSourceType!==l.b_.Symbol)continue;const V=d2(M.screenGeometry,y[z],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(V).length&&k.push(V)}return k}querySourceFeatures(f,y){const w=y&&y.filter;w&&this._validate(dd,"querySourceFeatures.filter",w,null,y);let k=[];const R=this.getOwnSourceCaches(f);for(const M of R)k=k.concat(a1(M,y));return k}getFlatLight(){return this.light.getLight()}setFlatLight(f,y,w={}){this._checkLoaded();const k=this.light.getLight();let R=!1;for(const z in f)if(!l.Y(f[z],k[z])){R=!0;break}if(!R)return;const M=this._getTransitionParameters();this.light.setLight(f,y,w),this.light.updateTransitions(M)}hasTerrain(){return!!this.terrain&&this.terrain.drapeRenderMode===1}getTerrain(){return this.hasTerrain()?this.terrain.get():null}_startLiteLoad(){this._drapingLoaded===void 0&&(this._drapingLoaded=!1,async function(){return Promise.resolve()}().then(()=>{this._drapingLoaded=!0,this.map._removed||this.dispatcher.actors.length===0||this.map.triggerRepaint()}))}_getRasterMaskUser(f,y){for(const w of this._order){const k=this._layers[w];if(k.type!=="raster"||!k.getPaintProperty("raster-mask"))continue;const R=k.getPaintProperty("raster-mask-import");if(y==="import"?R===f:!R&&k.getPaintProperty("raster-mask")===f)return w}}_startRasterArrayLoad(){this._rasterArrayLoaded===void 0&&(this._rasterArrayLoaded=!1,Bg().then(()=>{this._rasterArrayLoaded=!0,this.map._removed||this.map.triggerRepaint()}))}setTerrainForDraping(){this._startLiteLoad(),this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){this.disableElevatedTerrain===void 0&&(this.disableElevatedTerrain=l.e.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&l.w("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(f,y=1){if(this._checkLoaded(),!f)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),y===0&&delete this.terrain,f===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let w=f;const k=!("source"in f)||f.source==null;if(y===1){if(this._startLiteLoad(),this.disableElevatedTerrain)return;if("source"in w&&typeof w.source=="object"){const z="terrain-dem-src";this.addSource(z,w.source),w=l.dL(w),w=Object.assign(w,{source:z})}const R={...w},M={};if(this.terrain&&k){R.source=this.terrain.get().source;const z=this.terrain?this.getFragmentStyle(this.terrain.scope):null;z&&(M.style=z.serialize())}if(this._validate(Th,"terrain",R,M))return}if(!this.terrain||this.terrain.scope!==this.scope&&!k||this.terrain&&y!==this.terrain.drapeRenderMode){if(!w)return;this._createTerrain(w,y),this.fire(new l.i("data",{dataType:"style"}))}else{const R=this.terrain,M=R.get();for(const z of Object.keys(l.s.terrain))!Object.hasOwn(w,z)&&l.s.terrain[z].default&&(w[z]=l.s.terrain[z].default);for(const z in f)if(!l.Y(f[z],M[z])){R.set(f,this.options),this.stylesheet.terrain=f;const V=this._getTransitionParameters({duration:0});R.updateTransitions(V),this.fire(new l.i("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(f){const y=this.fog=new Oe(f,this.map.transform,this.scope,this.options);this.stylesheet.fog=y.get();const w=this._getTransitionParameters({duration:0});y.updateTransitions(w)}_createSnow(f){const y=this.snow=new Xe(f,this.map.transform,this.scope,this.options);this.stylesheet.snow=y.get();const w=this._getTransitionParameters({duration:0});y.updateTransitions(w)}_createRain(f){const y=this.rain=new Je(f,this.map.transform,this.scope,this.options);this.stylesheet.rain=y.get();const w=this._getTransitionParameters({duration:0});y.updateTransitions(w)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const f of this.map._markers)f._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(f){if(this._checkLoaded(),f)if(this.fog){const y=this.fog;if(!l.Y(y.get(),f)){y.set(f,this.options),this.stylesheet.fog=y.get();const w=this._getTransitionParameters({duration:0});y.updateTransitions(w)}}else this._createFog(f);else delete this.fog,delete this.stylesheet.fog;this._markersNeedUpdate=!0,this._programPrecompiler&&this._programPrecompiler.reset()}getSnow(){return this.snow?this.snow.get():null}setSnow(f){if(this._checkLoaded(),!f)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const y=this.snow;if(!l.Y(y.get(),f)){y.set(f,this.options),this.stylesheet.snow=y.get();const w=this._getTransitionParameters({duration:0});y.updateTransitions(w)}}else this._createSnow(f);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(f){if(this._checkLoaded(),!f)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const y=this.rain;if(!l.Y(y.get(),f)){y.set(f,this.options),this.stylesheet.rain=y.get();const w=this._getTransitionParameters({duration:0});y.updateTransitions(w)}}else this._createRain(f);this._markersNeedUpdate=!0}_reloadColorTheme(){const f=()=>{for(const k in this._layers)this._layers[k].lut=this._styleColorTheme.lut;for(const k in this._sourceCaches)this._sourceCaches[k].clearTiles()},y=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!y)return this._styleColorTheme.lut=null,void f();const w=this._evaluateColorThemeData(y);this._loadColorTheme(w).then(()=>{this.fire(new l.i("colorthemeset")),f()}).catch(k=>{l.w(`Couldn't set color theme: ${k}`)})}setColorTheme(f){this._checkLoaded(),this._styleColorTheme.colorThemeOverride&&l.w("Note: setColorTheme is called on a style with a color-theme override, the passed color-theme won't be visible."),this._styleColorTheme.colorTheme=f,this._reloadColorTheme()}setImportColorTheme(f,y){const w=this.getFragmentStyle(f);w&&(w._styleColorTheme.colorThemeOverride=y,w._reloadColorTheme())}_getTransitionParameters(f){return{now:l.e.now(),transition:Object.assign(this.transition,f)}}updateDrapeFirstLayers(){if(!this.terrain)return;const f=[],y=[];for(const w of this._mergedOrder)this.isLayerDraped(this._mergedLayers[w])?f.push(w):y.push(w);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...f),this._drapedFirstOrder.push(...y)}_createTerrain(f,y){const w=this.terrain=new he(f,y,this.scope,this.options,this.map.getWorldview());y===1&&(this.stylesheet.terrain=f),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const k=this._getTransitionParameters({duration:0});w.updateTransitions(k);const R=new l.au(this.z||0,{...k,worldview:this.map.getWorldview()});w.recalculate(R)}_force3DLayerUpdate(){for(const f in this._layers){const y=this._layers[f];y.type==="fill-extrusion"&&this._updateLayer(y)}}_forceSymbolLayerUpdate(){for(const f in this._layers){const y=this._layers[f];y.type==="symbol"&&this._updateLayer(y)}}_validate(f,y,w,k,R={}){if(R&&R.validate===!1)return!1;const M={...this.serialize()};return vr(this,f.call(Hd,{key:y,style:M,value:w,styleSpec:l.s,...k}))}_remove(){this._programPrecompiler&&(this._programPrecompiler.reset(),this._programPrecompiler=null),this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.abort(),this._spriteRequest=null);for(const f in this._mergedLayers)this._mergedLayers[f].setEventedParent(null);for(const f in this._mergedSourceCaches){const y=this._mergedSourceCaches[f];y.clearTiles(),y.setEventedParent(null);const w=y.getSource();w&&w.onRemove&&w.onRemove(this.map)}this.imageManager.removeScope(this.scope),this.isRootStyle()?this.imageManager.imageAtlasCache.clear():this.imageManager.imageAtlasCache.removeScope(this.scope),this.setEventedParent(null),delete this.fog,delete this.snow,delete this.rain,delete this.terrain,delete this.ambientLight,delete this.directionalLight,this.indoorManager&&this.indoorManager.destroy(),this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(f){const y=this.getSourceCaches(f);for(const w of y)w.clearTiles()}clearSources(){for(const f in this._mergedSourceCaches)this._mergedSourceCaches[f].clearTiles()}clearLayers(){for(const f in this._mergedLayers){const y=this._mergedLayers[f];y._clear&&y._clear()}}reloadSource(f){const y=this.getSourceCaches(f);for(const w of y)w.resume(),w.reload()}reloadSources(){for(const f of this.getSources())f.reload&&f.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(f=>{f.modelManager.reloadModels(f.scope)})}updateSources(f){let y;this.directionalLight&&(y=l.dV(this.directionalLight));const w=new Set,k=new Set,R=new Set;for(const M in this._mergedLayers){const z=this._mergedLayers[M];z.type==="building"?w.add(z.source):z.type==="raster"&&z.paint&&z.paint.get("raster-elevation-reference")==="ground"&&R.add(z.source),z.hasElevation()&&!k.has(z.source)&&k.add(z.source)}this.updateFrcCoverageFadeRange();for(const M in this._mergedSourceCaches){const z=this._mergedSourceCaches[M],V=k.has(z._source.id);z._isRasterElevatedOverTerrain=R.has(z._source.id),w.has(z._source.id)&&(z._source.reparseOverscaled=!1),z.update(f,void 0,void 0,y,V)}this.updateFrcCoverage(),this.updateElevationCoverage()}_reloadSources(){for(const f in this._sourceCaches){const y=this._sourceCaches[f];y.resume(),y.reload()}}updateFrcCoverageFadeRange(){this.map.painter&&kn.updateFrcCoverageFadeRange&&kn.updateFrcCoverageFadeRange(this,this.map.painter)}updateFrcCoverage(){this._hdCoverage&&kn.updateFrcCoverage&&kn.updateFrcCoverage(this,this._hdCoverage)}updateElevationCoverage(){this.isRootStyle()&&kn.setupAndUpdateElevationCoverage&&kn.setupAndUpdateElevationCoverage(this)}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new l.i("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new h1),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(f,y,w,k,R,M){this.pauseablePlacement||(this.pauseablePlacement=new h1);let z=!1,V=!1;const H={},Y={},te=M==="global",ne=te?[]:this._mergedOrder;let le=!1;te&&(le=this._driveGlobalPlacement(f,R,w,y));for(const Ne of ne){const We=this._mergedLayers[Ne];if(We.type!=="symbol")continue;const ct=l.m(We.source,We.scope);let it=H[ct];if(!it){const dt=this.getLayerSourceCache(We);if(!dt)continue;const mt=dt.getRenderableIds(!0).map(xt=>dt.getTileByID(xt));Y[ct]=mt.slice(),it=H[ct]=mt.sort((xt,bt)=>bt.tileID.overscaledZ-xt.tileID.overscaledZ||(xt.tileID.isLessThan(bt.tileID)?-1:1))}const pt=this.crossTileSymbolIndex.addLayer(We,it,f.center.lng,f.projection);z=z||pt}this.crossTileSymbolIndex.pruneUnusedLayers(ne);const me=!!(this.placement&&!f.equals(this.placement.transform)),fe=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!R||this.placement.lastReplacementSourceUpdateTime!==R.updateTime)),Se=me||fe||z,Me=(Se||this.pauseablePlacement.isStale())&&w===0,qe=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(l.e.now(),f.zoom)&&w!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||Me||qe)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(f,ne,y,w,k,this.placement,this.fog&&f.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const Ne=this.map.painter.maxFrontCutoffRawStart;if(Ne>0){const We=180*f.pitch/Math.PI;if(We>=15){const ct=Math.min(1,Math.max(0,(We-15)/5)),it=ct*ct*(3-2*ct);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-it)+Ne*it}}}if(this.pauseablePlacement.isDone()?Se&&w!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(ne,this._mergedLayers,H,Y,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(l.e.now()),V=!0),z&&this.pauseablePlacement.setStale()),V||z){this._buildingIndex.onNewFrame(f.zoom);for(let Ne=0;Nefe.getTileByID(We)),qe=te[Se]=QN(Me));const Ne=this.isLayerClipped(me);me.placeSymbols(H,Me,le,fe,Ne,qe);for(const We of Me){const ct=We.getBucket(me);ct&&me.fqid===ct.layerIds[0]&&ct.hasActiveFade()&&(ne=!0)}}return R.finishPlacementRun(),ne}_releaseSymbolFadeTiles(){for(const f in this._sourceCaches)this._sourceCaches[f].releaseSymbolFadeTiles()}addImport(f,y){if(this._checkLoaded(),new Set(["__proto__","constructor","prototype"]).has(f.id))return void this.fire(new l.h(new Error(`Import id can't be "${f.id}".`)));const w=this.stylesheet.imports=this.stylesheet.imports||[];if(w.findIndex(({id:R})=>R===f.id)!==-1)return void this.fire(new l.h(new Error(`Import with id '${f.id}' already exists in the map's style.`)));if(!y)return w.push(f),this._loadImports([f],!0);const k=w.findIndex(({id:R})=>R===y);return k===-1&&this.fire(new l.h(new Error(`Import with id "${y}" does not exist on this map.`))),this.stylesheet.imports=w.slice(0,k).concat(f).concat(w.slice(k)),this._loadImports([f],!0,y)}updateImport(f,y){this._checkLoaded();const w=this.stylesheet.imports||[],k=this.getImportIndex(f);return k===-1?this:typeof y=="string"?(this.setImportUrl(f,y),this):(y.url&&y.url!==w[k].url&&this.setImportUrl(f,y.url),l.Y(y.config,w[k].config)||this.setImportConfig(f,y.config,y.data.schema),l.Y(y.data,w[k].data)||this.setImportData(f,y.data),this)}moveImport(f,y){this._checkLoaded();let w=this.stylesheet.imports||[];const k=this.getImportIndex(f);if(k===-1)return this;const R=this.getImportIndex(y);if(R===-1)return this;const M=w[k],z=this.fragments[k];return w=w.filter(({id:V})=>V!==f),this.fragments=this.fragments.filter(({id:V})=>V!==f),this.stylesheet.imports=w.slice(0,R).concat(M).concat(w.slice(R)),this.fragments=this.fragments.slice(0,R).concat(z).concat(this.fragments.slice(R)),this.mergeLayers(),this}setImportUrl(f,y){this._checkLoaded();const w=this.stylesheet.imports||[],k=this.getImportIndex(f);if(k===-1)return this;w[k].url=y;const R=this.fragments[k];return R.style=this._createFragmentStyle(w[k]),R.style.on("style.import.load",()=>this.mergeAll()),R.style.loadURL(y),this}setImportData(f,y){this._checkLoaded();const w=this.getImportIndex(f),k=this.stylesheet.imports||[];return w===-1?this:y?(this.fragments[w].style.setState(y),this._reloadImports(),this):(delete k[w].data,this.setImportUrl(f,k[w].url))}setImportConfig(f,y,w){this._checkLoaded();const k=this.getImportIndex(f),R=this.stylesheet.imports||[];if(k===-1)return this;y?R[k].config=y:delete R[k].config;const M=this.fragments[k];w&&M.style.stylesheet&&(M.style.stylesheet.schema=w);const z=M.style.stylesheet&&M.style.stylesheet.schema;return M.config=y,M.style.updateConfig(y,z),this.updateConfigDependencies(),this}removeImport(f){this._checkLoaded();const y=this.stylesheet.imports||[],w=this.getImportIndex(f);w!==-1&&(y.splice(w,1),this.fragments[w].style._remove(),this.fragments.splice(w,1),this._reloadImports())}getImportIndex(f){const y=(this.stylesheet.imports||[]).findIndex(w=>w.id===f);return y===-1&&this.fire(new l.h(new Error(`Import '${f}' does not exist in the map's style and cannot be updated.`))),y}getLayer(f){return this._mergedLayers[f]}getSources(){const f=[];for(const y in this._mergedOtherSourceCaches){const w=this._mergedOtherSourceCaches[y];w&&f.push(w.getSource())}return f}getSource(f,y){const w=this.getSourceCache(f,y);return w&&w.getSource()}getLayerSource(f){const y=this.getLayerSourceCache(f);return y&&y.getSource()}getSourceCache(f,y){const w=l.m(f,y);return this._mergedOtherSourceCaches[w]}getLayerSourceCache(f){const y=f.sourceFqid;return f.type==="symbol"?this._mergedSymbolSourceCaches[y]:f.type==="fill-extrusion"?this._mergedFillExtrusionSourceCaches[y]||this._mergedOtherSourceCaches[y]:f.type==="fill"&&f.sourceLayer===l.c0&&this._mergedHdRoadCoverageSourceCaches[y]?this._mergedHdRoadCoverageSourceCaches[y]:this._mergedOtherSourceCaches[y]}getSourceCaches(f){return f==null?Object.values(this._mergedSourceCaches):[this._mergedOtherSourceCaches[f],this._mergedSymbolSourceCaches[f],this._mergedFillExtrusionSourceCaches[f],this._mergedHdRoadCoverageSourceCaches[f]].filter(Boolean)}updateSourceCaches(){const f=this._changes.getUpdatedSourceCaches();for(const y in f){const w=f[y];w==="reload"?this.reloadSource(y):w==="clear"&&this.clearSource(y)}}updateLayers(f){const y=this._changes.getUpdatedPaintProperties();for(const w of y){const k=this.getLayer(w);k&&k.updateTransitions(f)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(f){this.stylesheet.glyphs=f,this.glyphManager.setURL(f)}getOwnSourceCache(f){return this._otherSourceCaches[f]}getOwnLayerSourceCache(f){return f.type==="symbol"?this._symbolSourceCaches[f.source]:f.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[f.source]||this._otherSourceCaches[f.source]}getOwnSourceCaches(f){return[this._otherSourceCaches[f],this._symbolSourceCaches[f],this._fillExtrusionSourceCaches[f],this._hdCoverage&&this._hdCoverage.coverageSourceCaches[f]].filter(Boolean)}_updateHdCoverageSourceCache(f){return kn.HdCoverageState&&kn.updateHdCoverageSourceCache?(this._hdCoverage||(this._hdCoverage=new kn.HdCoverageState),kn.updateHdCoverageSourceCache(this,this._hdCoverage,f),!1):f.type==="fill"&&f.sourceLayer===l.c0}_isSourceCacheLoaded(f){const y=this.getOwnSourceCaches(f);return y.length===0?(this.fire(new l.h(new Error(`There is no source with ID '${f}'`))),!1):y.every(w=>w.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(f,y){if(!this._clipLayerPresent&&f.type!=="fill-extrusion"&&f.type!=="building")return!1;const w=f.type==="fill-extrusion"&&(f.sourceLayer==="building"||f.sourceLayer==="procedural_buildings"),k=f.type==="building";if(f.is3D(!!this.terrain)){if(w||k||y&&y.type==="batched-model"||f.type==="model")return!0}else if(f.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(f=>{f.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}async getImages(f,y){const w=new Promise((V,H)=>{this.imageManager.getImages(y.icons.concat(y.patterns),y.scope,(Y,te)=>{Y?H(Y):V(te)})});this._updateTilesForChangedImages();const k=y.icons.map(V=>l.I.toString(V)),R=y.patterns.map(V=>l.I.toString(V)),M=V=>{V&&(V.setDependencies(y.tileID.key,"icons",k),V.setDependencies(y.tileID.key,"patterns",R))},z=l.m(y.source,y.scope);return M(this._mergedOtherSourceCaches[z]),M(this._mergedSymbolSourceCaches[z]),(y.icons.some(V=>V.iconsetId)||y.patterns.some(V=>V.iconsetId))&&this.fire(new l.i("data",{dataType:"style"})),w}async rasterizeImages(f,y){return new Promise((w,k)=>{this.imageManager.rasterizeImages(y,(R,M)=>{R?k(R):w(M)})})}async checkAtlasCache(f,y){const w=this.imageManager.imageAtlasCache.findCachedAtlas(y.descriptor);return w&&w.contentDescriptor?{iconPositions:w.iconPositions,patternPositions:w.patternPositions,sourceHash:w.contentDescriptor.hash}:null}async getGlyphs(f,y){return new Promise((w,k)=>{this.glyphManager.getGlyphs(y.stacks,(R,M)=>{R?k(R):w(M)})})}}class JN{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(f,y,w,k,R,M,z,V){this.context=f;let H=this.boundPaintVertexBuffers.length!==k.length;for(let te=0;!H&&te{const k=_.properties.get("direction"),R=_.properties.get("color-use-theme")==="none",M=_.properties.get("color").toNonPremultipliedRenderColor(R?null:y.getLut(_.scope)).toArray01();let z=_.properties.get("intensity");const V=f.properties.get("color-use-theme")==="none",H=f.properties.get("color").toNonPremultipliedRenderColor(V?null:y.getLut(f.scope)).toArray01();let Y=f.properties.get("intensity");const te=[k.x,k.y,k.z];w&&(w.ambientIntensity!==void 0&&(Y=w.ambientIntensity),w.directionalIntensity!==void 0&&(z=w.directionalIntensity),w.ambientColor!==void 0&&(H[0]=w.ambientColor[0],H[1]=w.ambientColor[1],H[2]=w.ambientColor[2]),w.directionalColor!==void 0&&(M[0]=w.directionalColor[0],M[1]=w.directionalColor[1],M[2]=w.directionalColor[2]));const ne=l.dX(H,Y),le=l.dX(M,z);return{u_lighting_ambient_color:ne,u_lighting_directional_dir:te,u_lighting_directional_color:le,u_ground_radiance:b1(te,le,ne)}},S1=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],eR=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];function b2(_,f,y){for(const w of y)(w.includes(" ")||f.usedDefines.has(w))&&(_+=`/${w}`);return _}class w2{static cacheKey(f,y,w,k,R){let M=y;return R&&(M+=`/${R.cacheKey}`),M=b2(M,f,w),k?b2(M,f,k):M}constructor(f,y,w,k,R,M,z=!1){const V=f.gl;this.program=V.createProgram(),this._context=f,this._fixedUniformsFn=R,this._pending=!0,this._precompiled=z,this.attributes={},this.configuration=k,this.name=y,this.fixedDefines=[...M],z?f._compileStats.precompiled++:f._compileStats.onDemand++;const H=`#version 300 es ${(k?k.defines():[]).concat(M.map(Se=>`#define ${Se}`)).join(` `)}`,Y=[H,l.e0];for(const Se of w.fragmentIncludes)Y.push(l.bl[Se]);Y.push(w.fragmentSource);const te=Y.join(` `),ne=[H,l.e1];for(const Se of w.vertexIncludes)ne.push(l.bl[Se]);this.forceManualRenderingForInstanceIDShaders=f.forceManualRenderingForInstanceIDShaders&&w.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&ne.push("uniform int u_instanceID;"),ne.push(w.vertexSource);let le=ne.join(` `);this.forceManualRenderingForInstanceIDShaders&&(le=le.replaceAll("gl_InstanceID","u_instanceID"));const me=V.createShader(V.FRAGMENT_SHADER);if(V.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);V.shaderSource(me,te),V.compileShader(me),V.attachShader(this.program,me);const fe=V.createShader(V.VERTEX_SHADER);if(V.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);V.shaderSource(fe,le),V.compileShader(fe),V.attachShader(this.program,fe),V.linkProgram(this.program),this._fragmentShader=me,this._vertexShader=fe,f.extParallelShaderCompile?f._pendingPrograms.add(this):this._finalize()}_finalize(){if(!this._pending)return;this._pending=!1;const f=this._context,y=f.gl;f._pendingPrograms.delete(this);const w=l.e.now(),k=y.getProgramParameter(this.program,y.LINK_STATUS),R=l.e.now()-w,M=f._compileStats;if(M.totalStallMs+=R,R>M.maxStallMs&&(M.maxStallMs=R),R>1){M.framesMissed+=Math.floor(60*R/1e3);const H=this.fixedDefines.join(",");M.stalls.push({name:`${this.name}${H?"/":""}${H}`,ms:R,timestamp:w})}if(this._fragmentShader&&(k||l.w(`Fragment shader '${this.name}': ${y.getShaderInfoLog(this._fragmentShader)}`),y.deleteShader(this._fragmentShader),this._fragmentShader=null),this._vertexShader&&(k||l.w(`Vertex shader '${this.name}': ${y.getShaderInfoLog(this._vertexShader)}`),y.deleteShader(this._vertexShader),this._vertexShader=null),!k)return l.w(`Failed to link program '${this.name}': ${y.getProgramInfoLog(this.program)}`),void(this.failedToCreate=!0);this.fixedUniforms=this._fixedUniformsFn(f),this.activeUniforms=Object.entries(this.fixedUniforms).filter(([H,Y])=>Y.fetchUniformLocation(this.program,H)),this.binderUniforms=this.configuration?this.configuration.getUniforms(f):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(H=>({u_instanceID:new l.b6(H)}))(f));const z=this.fixedDefines,V=this.name;(z.includes("TERRAIN")||z.includes("ELEVATED")||V.includes("symbol")||V.includes("circle"))&&(this.terrainUniforms=(H=>({u_dem:new l.b6(H),u_dem_prev:new l.b6(H),u_dem_tl:new l.a8(H),u_dem_scale:new l.a9(H),u_dem_tl_prev:new l.a8(H),u_dem_scale_prev:new l.a9(H),u_dem_size:new l.a9(H),u_dem_lerp:new l.a9(H),u_exaggeration:new l.a9(H),u_depth:new l.b6(H),u_depth_size_inv:new l.a8(H),u_depth_range_unpack:new l.a8(H),u_occluder_half_size:new l.a9(H),u_occlusion_depth_offset:new l.a9(H),u_meter_to_dem:new l.a9(H),u_label_plane_matrix_inv:new l.aa(H)}))(f)),z.includes("GLOBE")&&(this.globeUniforms=(H=>({u_tile_tl_up:new l.ab(H),u_tile_tr_up:new l.ab(H),u_tile_br_up:new l.ab(H),u_tile_bl_up:new l.ab(H),u_tile_up_scale:new l.a9(H)}))(f)),z.includes("FOG")&&(this.fogUniforms=(H=>({u_fog_matrix:new l.aa(H),u_fog_range:new l.a8(H),u_fog_color:new l.b7(H),u_fog_horizon_blend:new l.a9(H),u_fog_vertical_limit:new l.a8(H),u_fog_temporal_offset:new l.a9(H),u_frustum_tl:new l.ab(H),u_frustum_tr:new l.ab(H),u_frustum_br:new l.ab(H),u_frustum_bl:new l.ab(H),u_globe_pos:new l.ab(H),u_globe_radius:new l.a9(H),u_globe_transition:new l.a9(H),u_is_globe:new l.b6(H),u_viewport:new l.a8(H)}))(f)),z.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=l.e2(f)),z.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(H=>({u_lighting_ambient_color:new l.ab(H),u_lighting_directional_dir:new l.ab(H),u_lighting_directional_color:new l.ab(H),u_ground_radiance:new l.ab(H)}))(f)),z.includes("RENDER_SHADOWS")&&(this.shadowUniforms=l.e3(f))}maybeFinalize(){if(!this._pending)return;const f=this._context.extParallelShaderCompile;f&&!this._context.gl.getProgramParameter(this.program,f.COMPLETION_STATUS_KHR)||this._finalize()}_ensureReady(){this._pending&&(this._finalize(),this._context.sweepPendingPrograms())}getAttributeLocation(f,y){this._ensureReady();let w=this.attributes[y];return w===void 0&&(w=this.attributes[y]=f.getAttribLocation(this.program,y)),w}_setUniformGroup(f,y,w){this._ensureReady();const k=this[y];if(!this.failedToCreate&&k){f.program.set(this.program);for(const R in w){const M=k[R];M&&M.set(this.program,R,w[R])}}}setTerrainUniformValues(f,y){this._setUniformGroup(f,"terrainUniforms",y)}setGlobeUniformValues(f,y){this._setUniformGroup(f,"globeUniforms",y)}setFogUniformValues(f,y){this._setUniformGroup(f,"fogUniforms",y)}setCutoffUniformValues(f,y){this._setUniformGroup(f,"cutoffUniforms",y)}setLightsUniformValues(f,y){this._setUniformGroup(f,"lightsUniforms",y)}setShadowUniformValues(f,y){this._setUniformGroup(f,"shadowUniforms",y)}_drawDebugWireframe(f,y,w,k,R,M,z,V,H,Y,te){const ne=f.options.wireframe;if(ne.terrain===!1&&ne.layers2D===!1&&ne.layers3D===!1)return;const le=f.context;if(!(!(!ne.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!ne.layers2D||f._terrain&&f._terrain.renderingToTexture||!S1.includes(this.name))||!(!ne.layers3D||!eR.includes(this.name))))return;const me=le.gl,fe=f.wireframeDebugCache.getLinesFromTrianglesBuffer(f.frameCounter,R,le);if(!fe)return;const Se=[...this.fixedDefines,"DEBUG_WIREFRAME"],Me=f.getOrCreateProgram(this.name,{config:this.configuration,defines:Se});Me._ensureReady(),le.program.set(Me.program),te&&te.bind(le,Me.program);const qe=(ct,it,pt)=>{if(it[ct]&&pt[ct])for(const dt in it[ct])pt[ct][dt]&&pt[ct][dt].set(pt.program,dt,it[ct][dt].current)};H&&H.setUniforms(Me.program,le,Me.binderUniforms,z,{zoom:V}),qe("fixedUniforms",this,Me),qe("terrainUniforms",this,Me),qe("globeUniforms",this,Me),qe("fogUniforms",this,Me),qe("lightsUniforms",this,Me),qe("shadowUniforms",this,Me),fe.bind(),le.setColorMode(new l.a7([me.ONE,me.ONE_MINUS_SRC_ALPHA,me.ZERO,me.ONE],l.C.transparent,[!0,!0,!0,!1])),le.setDepthMode(new l.a3(y.func===me.LESS?me.LEQUAL:y.func,l.a3.ReadOnly,y.range)),le.setStencilMode(l.a4.disabled);const Ne=3*M.primitiveLength*2,We=3*M.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const ct=Y||1;for(let it=0;it1?me.drawElementsInstanced(me.LINES,Ne,me.UNSIGNED_SHORT,We,Y):me.drawElements(me.LINES,Ne,me.UNSIGNED_SHORT,We);R.bind(),le.program.set(this.program),le.setDepthMode(y),le.setStencilMode(w),le.setColorMode(k)}checkUniforms(f,y,w){if(this.fixedDefines.includes(y)){for(const k of Object.keys(w))if(!w[k].initialized)throw new Error(`Program '${this.name}', from draw '${f}': uniform ${k} not set but required by ${y} being defined`)}}draw(f,y,w,k,R,M,z,V,H,Y,te,ne,le,me,fe,Se,Me){const qe=f.context,Ne=qe.gl;if(this._ensureReady(),this.failedToCreate)return;qe.program.set(this.program),qe.setDepthMode(w),qe.setStencilMode(k),qe.setColorMode(R),qe.setCullFace(M);for(const[mt,xt]of this.activeUniforms)xt.set(this.program,mt,z[mt]);me&&me.setUniforms(this.program,qe,this.binderUniforms,ne,{zoom:le});const We={[Ne.POINTS]:1,[Ne.LINES]:2,[Ne.TRIANGLES]:3,[Ne.LINE_STRIP]:1}[y];this.checkUniforms(V,"RENDER_SHADOWS",this.shadowUniforms);const ct=fe||[],it=me?me.getPaintVertexBuffers():[],pt=y===Ne.TRIANGLES&&Y,dt=Se&&Se>0?1:void 0;for(const mt of te.get()){const xt=mt.vaos||(mt.vaos={}),bt=xt[V]||(xt[V]=new Map);let Ft=bt.get(this.program);if(Ft||bt.set(this.program,Ft=new JN),Ft.bind(qe,this,H,it,Y,mt.vertexOffset,ct,dt),this.forceManualRenderingForInstanceIDShaders){const Lt=Se||1;for(let Mt=0;Mt1?Ne.drawElementsInstanced(y,mt.primitiveLength*We,Ne.UNSIGNED_SHORT,mt.primitiveOffset*We*2,Se):Y?Ne.drawElements(y,mt.primitiveLength*We,Ne.UNSIGNED_SHORT,mt.primitiveOffset*We*2):Ne.drawArrays(y,mt.vertexOffset,mt.vertexLength);pt&&this._drawDebugWireframe(f,w,k,R,Y,mt,ne,le,me,Se,Me)}}}class um{constructor(f,y,w,k){this.id=um.uniqueIdxCounter,um.uniqueIdxCounter++,this.context=f;const R=f.gl;this.buffer=R.createBuffer(),this.dynamicDraw=!!w,this.context.unbindVAO(),f.bindElementBuffer.set(this.buffer),R.bufferData(R.ELEMENT_ARRAY_BUFFER,y.arrayBuffer,this.dynamicDraw?R.DYNAMIC_DRAW:R.STATIC_DRAW),this.dynamicDraw||k||y.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(f){this.id=um.uniqueIdxCounter,um.uniqueIdxCounter++;const y=this.context.gl;this.context.unbindVAO(),this.bind(),y.bufferSubData(y.ELEMENT_ARRAY_BUFFER,0,f.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}um.uniqueIdxCounter=0;const S2={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class tR{constructor(f,y,w,k,R,M){this.length=y.length,this.attributes=w,this.itemSize=y.bytesPerElement,this.dynamicDraw=k,this.instanceCount=M,this.context=f;const z=f.gl;this.buffer=z.createBuffer(),f.bindVertexBuffer.set(this.buffer),z.bufferData(z.ARRAY_BUFFER,y.arrayBuffer,this.dynamicDraw?z.DYNAMIC_DRAW:z.STATIC_DRAW),this.dynamicDraw||R||y.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(f){const y=this.context.gl;this.bind(),y.bufferSubData(y.ARRAY_BUFFER,0,f.uint8,0,f.length*f.bytesPerElement)}enableAttributes(f,y){for(const w of this.attributes){const k=y.getAttributeLocation(f,w.name);k!==-1&&f.enableVertexAttribArray(k)}}setVertexAttribPointers(f,y,w){for(const k of this.attributes){const R=y.getAttributeLocation(f,k.name);if(R!==-1){const M=k.offset+this.itemSize*(w||0);k.type==="Float32"||k.normalized?f.vertexAttribPointer(R,k.components,f[S2[k.type]],!!k.normalized,this.itemSize,M):f.vertexAttribIPointer(R,k.components,f[S2[k.type]],this.itemSize,M)}}}setVertexAttribDivisor(f,y,w){for(let k=0;k0&&f.vertexAttribDivisor(R,w)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Sp{constructor(f,y,w,k,R){this.context=f,this.width=y,this.height=w;const M=this.framebuffer=f.gl.createFramebuffer();k>0&&(this.colorAttachment0=new am(f,M,0)),k>1&&(this.colorAttachment1=new am(f,M,1)),R&&(this.depthAttachmentType=R,this.depthAttachment=R==="renderbuffer"?new TN(f,M):new AN(f,M))}static createWithTexture(f,y,w,k,R){const M=f.gl;if(f.activeTexture.set(M.TEXTURE1),f.viewport.set([0,0,w,k]),y&&y.width===w&&y.height===k)return M.bindTexture(M.TEXTURE_2D,y.colorAttachment0.get()),f.bindFramebuffer.set(y.framebuffer),y;y&&y.destroy();const z=f.extRenderToTextureHalfFloat||f.extColorBufferFloat?f.gl.RGBA16F:f.gl.RGBA8,V=new l.T(f,{width:w,height:k,data:null},z);V.bind(M.LINEAR,M.CLAMP_TO_EDGE);const H=f.createFramebuffer(w,k,1,null);if(H.format=z,H.colorAttachment0.set(V.texture),R){const Y=f.createRenderbuffer(M.DEPTH24_STENCIL8,w,k);f.bindFramebuffer.set(H.framebuffer),M.framebufferRenderbuffer(M.FRAMEBUFFER,M.DEPTH_STENCIL_ATTACHMENT,M.RENDERBUFFER,Y),H._stencilRbo=Y}return H}createColorAttachment(f,y){y===0?this.colorAttachment0=new am(f,this.framebuffer,0):y===1&&(this.colorAttachment1=new am(f,this.framebuffer,1))}removeColorAttachment(f,y){const w=this.context.gl;let k;y===0?(k=this.colorAttachment0.get(),this.colorAttachment0=void 0):y===1&&(k=this.colorAttachment1.get(),this.colorAttachment1=void 0),k&&w.deleteTexture(k)}destroy(){const f=this.context.gl;if(this.colorAttachment0){const y=this.colorAttachment0.get();y&&f.deleteTexture(y)}if(this.colorAttachment1){const y=this.colorAttachment1.get();y&&f.deleteTexture(y)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const y=this.depthAttachment.get();y&&f.deleteRenderbuffer(y)}else{const y=this.depthAttachment.get();y&&f.deleteTexture(y)}this._stencilRbo&&(f.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),f.deleteFramebuffer(this.framebuffer)}}class E2{constructor(f,y){this.gl=f,this._pendingPrograms=new Set,this._compileStats={precompiled:0,onDemand:0,totalStallMs:0,maxStallMs:0,framesMissed:0,stalls:[]},this.clearColor=new Vw(this),this.clearDepth=new Ih(this),this.clearStencil=new qw(this),this.colorMask=new u0(this),this.depthMask=new Ql(this),this.stencilMask=new KA(this),this.stencilFunc=new Sx(this),this.stencilOp=new mu(this),this.stencilTest=new vc(this),this.depthRange=new Jl(this),this.depthTest=new Fa(this),this.depthFunc=new pu(this),this.blend=new YA(this),this.blendFunc=new ZA(this),this.blendColor=new XA(this),this.blendEquation=new d0(this),this.cullFace=new Gw(this),this.cullFaceSide=new QA(this),this.frontFace=new _N(this),this.program=new vN(this),this.activeTexture=new bN(this),this.viewport=new wN(this),this.bindFramebuffer=new Mg(this),this.bindRenderbuffer=new Hw(this),this.bindTexture=new ar(this),this.bindVertexBuffer=new SN(this),this.bindElementBuffer=new JA(this),this.bindVertexArrayOES=new EN(this),this.pixelStoreUnpack=new Ex(this),this.pixelStoreUnpackPremultiplyAlpha=new Og(this),this.pixelStoreUnpackFlipY=new Fg(this),this.options=y?{...y}:{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=f.getExtension("EXT_texture_filter_anisotropic")||f.getExtension("MOZ_EXT_texture_filter_anisotropic")||f.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=f.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=f.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=f.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=f.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=y&&!!y.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.includes("PowerVR"),this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=f.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=f.getExtension("EXT_color_buffer_half_float"),this.extColorBufferFloat=f.getExtension("EXT_color_buffer_float"),this.extTimerQuery=f.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=f.getParameter(f.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(f.getParameter(f.MAX_UNIFORM_BLOCK_SIZE),32768),this.extBlendFuncExtended=f.getExtension("WEBGL_blend_func_extended"),this.extParallelShaderCompile=f.getExtension("KHR_parallel_shader_compile")}sweepPendingPrograms(){if(this._pendingPrograms.size!==0)for(const f of this._pendingPrograms)f.maybeFinalize()}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArrayOES.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(f,y,w){return new um(this,f,y,w)}createVertexBuffer(f,y,w,k,R){return new tR(this,f,y,w,k,R)}createRenderbuffer(f,y,w){const k=this.gl,R=k.createRenderbuffer();return this.bindRenderbuffer.set(R),k.renderbufferStorage(k.RENDERBUFFER,f,y,w),this.bindRenderbuffer.set(null),R}createFramebuffer(f,y,w,k){return new Sp(this,f,y,w,k)}clear({color:f,depth:y,stencil:w,colorMask:k}){const R=this.gl;let M=0;f&&(M|=R.COLOR_BUFFER_BIT,this.clearColor.set(f.toNonPremultipliedRenderColor(null)),this.colorMask.set(k||[!0,!0,!0,!0])),y!==void 0&&(M|=R.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(y),this.depthMask.set(!0)),w!==void 0&&(M|=R.STENCIL_BUFFER_BIT,this.clearStencil.set(w),this.stencilMask.set(255)),R.clear(M)}setCullFace(f){f.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(f.mode),this.frontFace.set(f.frontFace))}setDepthMode(f){f.func!==this.gl.ALWAYS||f.mask?(this.depthTest.set(!0),this.depthFunc.set(f.func),this.depthMask.set(f.mask),this.depthRange.set(f.range)):this.depthTest.set(!1)}setStencilMode(f){f.test.func!==this.gl.ALWAYS||f.mask?(this.stencilTest.set(!0),this.stencilMask.set(f.mask),this.stencilOp.set([f.fail,f.depthFail,f.pass]),this.stencilFunc.set({func:f.test.func,ref:f.ref,mask:f.test.mask})):this.stencilTest.set(!1)}setColorMode(f){f.blendFunction===l.a7.Replace?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(f.blendFunction),this.blendColor.set(f.blendColor),f.blendEquation?this.blendEquation.set(f.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(f.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}const A0=l.a2();function T2(_){const f=_._camera.getWorldToCamera(_.worldSize,1),y=l.a1(new Float64Array(16),f,_.globeMatrix);l.aZ(y,y);const w=[0,0,0],k=[0,1,0,0];return l.cd(k,k,y),w[0]=k[0],w[1]=k[1],w[2]=k[2],l.cg(w,w),w}function rR({width:_,height:f,anchor:y,textOffset:w,textScale:k},R){const{horizontalAlign:M,verticalAlign:z}=l.dz(y),V=-(M-.5)*_,H=-(z-.5)*f,Y=l.dA(y,w);return new l.P((V/k+Y[0])*R,(H/k+Y[1])*R)}function nR(_,f,y,w,k,R,M,z,V,H){const Y=_.text.placedSymbolArray,te=_.text.dynamicLayoutVertexArray,ne=_.icon.dynamicLayoutVertexArray,le={},me=_.getProjection(),fe=l.e4(M,me,k),Se=k.elevation,Me=me.upVectorScale(M.canonical,k.center.lat,k.worldSize).metersToTile;te.clear();for(let qe=0;qe=0&&(le[Ne.associatedIconIndex]={x:Ft,y:Lt,z:Mt,angle:qt})}else l.e6(it,te)}if(H){ne.clear();const qe=_.icon.placedSymbolArray;for(let Ne=0;Ne{let Pn=[0,0,0];if(Dr){const ti=_.style.directionalLight,Ya=_.style.ambientLight;ti&&Ya&&(Pn=l.aQ(_.style,ti,Ya))}return Pn},xn=Dr=>{const Pn=Math.floor(_.context.maxUniformBlockSize/4),ti=Math.floor(Pn/4);Dr.push(`MAX_UBO_SIZE_VEC4 ${ti}u`)},Sn=Dr=>{mt.depthOcclusionForSymbolsAndCircles&&(y.hasOcclusionOpacityProperties||_.terrain)&&(Dr.push("DEPTH_D24"),Dr.push("DEPTH_OCCLUSION"))},Dn=Dr=>{y.lut&&!it&&(y.lut.texture||(y.lut.texture=new l.ea(_.context,y.lut.image,[y.lut.image.height,y.lut.image.height,y.lut.image.height],pt.gl.RGBA8)),pt.activeTexture.set(pt.gl.TEXTURE0+l.cp.LUT),y.lut.texture&&y.lut.texture.bind(pt.gl.LINEAR,pt.gl.CLAMP_TO_EDGE),Dr.push("APPLY_LUT_ON_GPU"))},Ks=()=>{const Dr=xt&&y.layout.get("symbol-placement")!=="point",Pn=[];Sn(Pn),Dn(Pn);const ti=Dr||Rn,Ya=mr.elevationType==="road",ao=_.shadowRenderer,yu=Ya&&Ft&&!!ao&&ao.enabled,ua=Qi(yu),Is=Ya&&Ft&&!_.terrain?Cr:fr,Ji=y.paint.get("icon-image-cross-fade");_.terrainRenderModeElevated()&&Ft&&Pn.push("PITCH_WITH_MAP_TERRAIN"),tn&&(Pn.push("PROJECTION_GLOBE_VIEW"),ti&&Pn.push("PROJECTED_POS_ON_VIEWPORT")),Ji>0&&mr.hasAnySecondaryIcon&&Pn.push("ICON_TRANSITION"),!mr.icon.zOffsetVertexBuffer||Ya&&_.terrain||Pn.push("Z_OFFSET"),Pn.push(mr.icon.fadeVertexBuffer?"GLOBAL_PLACEMENT_FADE":"LEGACY_PLACEMENT_FADE"),Me===0&&qe===0&&Ne===0&&We===1||Pn.push("COLOR_ADJUSTMENT"),yu&&Pn.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ya&&Ft&&!_.terrain&&mr.icon.orientationVertexBuffer&&Pn.push("ELEVATED_ROADS"),xn(Pn);const Ii=_.getOrCreateProgram("symbol",{defines:Pn}),Qs=Xt.imageAtlasTexture?Xt.imageAtlasTexture.size:[0,0],na=mr.iconSizeData,Ls=l.dr(na,mt.zoom),ol=Ft||!mt.isOrthographic,Sc=l.e5(vn,Xt.tileID.canonical,Ft,xt,mt,mr.getProjection(),Xr),Fl=l.dq(vn,Xt.tileID.canonical,Ft,xt,mt,mr.getProjection(),Xr),ji=mr.icon.uboBinder&&mr.icon.uboBinder.hasPerFeatureTranslate()?[0,0]:z,Hi=_.translatePosMatrix(Fl,Xt,ji,H,!0),Os=_.translatePosMatrix(vn,Xt,ji,H),Za=ti?A0:Sc,Jd=xt&&!Ft&&!Dr;let xu=Pr;!Ut&&!mt.mercatorFromTransition||xt||(xu=T2(mt));const Nh=tn?xu:Pr,Ep=y.getColorAdjustmentMatrix(Me,qe,Ne,We),Tp=s2(na.kind,Ls,Jd,Ft,_,Os,Za,Hi,ct,!1,mr.sdfIcons,Qs,[0,0],0,ur,kr,qr,Ni,Nh,mr.getProjection(),ua,zn,Ep,Ji,null),$0=Xt.imageAtlasTexture?Xt.imageAtlasTexture:null,Z2=y.layout.get("icon-size").constantOr(0)!==1||mr.iconsNeedLinear,X2=mr.sdfIcons||_.options.rotating||_.options.zooming||Z2||ol?dt.LINEAR:dt.NEAREST,Q2=mr.sdfIcons&&y.paint.get("icon-halo-width").constantOr(1)!==0,J2=_.terrain&&Ft&&Dr?l.aZ(l.a2(),Sc):A0;if(Dr&&mr.icon){const ek=l.c8.getAtTileOffsetFunc(ur,mt.center.lat,mt.worldSize,mr.getProjection()),tk=l.dp(vn,Xt.tileID.canonical,Ft,xt,mt,mr.getProjection(),Xr),bR=y.layout.get("icon-size-scale-range"),dz=l.bb(_.scaleFactor,bR[0],bR[1]);l.e9(mr,vn,_,!1,tk,Fl,Ft,fe,ek,ur,dz)}return{program:Ii,buffers:mr.icon,uniformValues:Tp,atlasTexture:$0,atlasTextureIcon:null,atlasInterpolation:X2,atlasInterpolationIcon:null,isSDF:mr.sdfIcons,hasHalo:Q2,depthMode:Is,tile:Xt,renderWithShadows:yu,labelPlaneMatrixInv:J2}},ya=()=>{const Dr=bt&&y.layout.get("symbol-placement")!=="point",Pn=[],ti=Dr||qt||Rn,Ya=mr.elevationType==="road",ao=_.shadowRenderer,yu=Ya&&Lt&&!!ao&&ao.enabled,ua=Qi(yu),Is=Ya&&Lt&&!_.terrain?Cr:fr;_.terrainRenderModeElevated()&&Lt&&Pn.push("PITCH_WITH_MAP_TERRAIN"),tn&&(Pn.push("PROJECTION_GLOBE_VIEW"),ti&&Pn.push("PROJECTED_POS_ON_VIEWPORT")),!mr.text.zOffsetVertexBuffer||Ya&&_.terrain||Pn.push("Z_OFFSET"),Pn.push(mr.text.fadeVertexBuffer?"GLOBAL_PLACEMENT_FADE":"LEGACY_PLACEMENT_FADE"),mr.iconsInText&&Pn.push("RENDER_TEXT_AND_SYMBOL"),yu&&Pn.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ya&&Lt&&!_.terrain&&mr.text.orientationVertexBuffer&&Pn.push("ELEVATED_ROADS"),Sn(Pn),xn(Pn);const Ji=_.getOrCreateProgram("symbol",{defines:Pn});let Ii,Qs=[0,0],na=null;const Ls=mr.textSizeData;mr.iconsInText&&(Qs=Xt.imageAtlasTexture?Xt.imageAtlasTexture.size:[0,0],na=Xt.imageAtlasTexture?Xt.imageAtlasTexture:null,Ii=Lt||!mt.isOrthographic||_.options.rotating||_.options.zooming||Ls.kind==="composite"||Ls.kind==="camera"?dt.LINEAR:dt.NEAREST);const ol=Xt.glyphAtlasTexture?Xt.glyphAtlasTexture.size:[0,0],Sc=y.layout.get("text-size-scale-range"),Fl=l.bb(_.scaleFactor,Sc[0],Sc[1]),ji=l.dr(Ls,mt.zoom,Fl),Hi=l.e5(vn,Xt.tileID.canonical,Lt,bt,mt,mr.getProjection(),Xr),Os=l.dq(vn,Xt.tileID.canonical,Lt,bt,mt,mr.getProjection(),Xr),Za=mr.text.uboBinder&&mr.text.uboBinder.hasPerFeatureTranslate()?[0,0]:V,Jd=_.translatePosMatrix(Os,Xt,Za,Y,!0),xu=_.translatePosMatrix(vn,Xt,Za,Y),Nh=ti?A0:Hi,Ep=bt&&!Lt&&!Dr;let Tp=Pr;!Ut&&!mt.mercatorFromTransition||bt||(Tp=T2(mt));const $0=s2(Ls.kind,ji,Ep,Lt,_,xu,Nh,Jd,ct,!0,!0,ol,Qs,0,ur,kr,qr,Ni,tn?Tp:Pr,mr.getProjection(),ua,zn,null,null,Fl),Z2=Xt.glyphAtlasTexture?Xt.glyphAtlasTexture:null,X2=dt.LINEAR,Q2=y.paint.get("text-halo-width").constantOr(1)!==0,J2=_.terrain&&Lt&&Dr?l.aZ(l.a2(),Hi):A0;if(Dr&&mr.text){const ek=l.c8.getAtTileOffsetFunc(ur,mt.center.lat,mt.worldSize,mr.getProjection()),tk=l.dp(vn,Xt.tileID.canonical,Lt,bt,mt,mr.getProjection(),Xr);l.e9(mr,vn,_,!0,tk,Os,Lt,Se,ek,ur,Fl)}return{program:Ji,buffers:mr.text,uniformValues:$0,atlasTexture:Z2,atlasTextureIcon:na,atlasInterpolation:X2,atlasInterpolationIcon:Ii,isSDF:!0,hasHalo:Q2,depthMode:Is,tile:Xt,renderWithShadows:yu,labelPlaneMatrixInv:J2}},Ti=mr.icon.segments.get().length,Ba=mr.text.segments.get().length,bs=Ti&&!M.onlyText?Ks():null,Ri=Ba&&!M.onlyIcons?ya():null,gi=y.paint.get("icon-opacity").constantOr(1),yi=y.paint.get("text-opacity").constantOr(1);if(Mt&&mr.canOverlap){or=!0;const Dr=gi&&!M.onlyText?mr.icon.segments.get():[],Pn=yi&&!M.onlyIcons?mr.text.segments.get():[];for(const ti of Dr)gr.push({segments:new l.aj([ti]),sortKey:ti.sortKey,state:bs});for(const ti of Pn)gr.push({segments:new l.aj([ti]),sortKey:ti.sortKey,state:Ri})}else M.onlyText||gr.push({segments:gi?mr.icon.segments:new l.aj([]),sortKey:0,state:bs}),M.onlyIcons||gr.push({segments:yi?mr.text.segments:new l.aj([]),sortKey:0,state:Ri})}or&&gr.sort((ur,Xt)=>ur.sortKey-Xt.sortKey);for(const ur of gr){const Xt=ur.state;if(Xt)if(_.terrain?_.terrain.setupElevationDraw(Xt.tile,Xt.program,{useDepthForOcclusion:mt.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:Xt.labelPlaneMatrixInv}):_.setupDepthForOcclusion(mt.depthOcclusionForSymbolsAndCircles,Xt.program),pt.activeTexture.set(dt.TEXTURE0),Xt.atlasTexture&&Xt.atlasTexture.bind(Xt.atlasInterpolation,dt.CLAMP_TO_EDGE,!0),Xt.atlasTextureIcon&&(pt.activeTexture.set(dt.TEXTURE1),Xt.atlasTextureIcon&&Xt.atlasTextureIcon.bind(Xt.atlasInterpolationIcon,dt.CLAMP_TO_EDGE,!0)),Xt.renderWithShadows&&_.shadowRenderer.setupShadows(Xt.tile.tileID.toUnwrapped(),Xt.program,"vector-tile"),_.uploadCommonLightUniforms(_.context,Xt.program),Xt.hasHalo){const mr=Xt.uniformValues;mr.u_is_halo=1,E1(Xt.buffers,ur.segments,y,_,Xt.program,Xt.depthMode,k,R,mr,2),mr.u_is_halo=0}else{if(Xt.isSDF){const mr=Xt.uniformValues;Xt.hasHalo&&(mr.u_is_halo=1,E1(Xt.buffers,ur.segments,y,_,Xt.program,Xt.depthMode,k,R,mr,1)),mr.u_is_halo=0}E1(Xt.buffers,ur.segments,y,_,Xt.program,Xt.depthMode,k,R,Xt.uniformValues,1)}}}function E1(_,f,y,w,k,R,M,z,V,H){const Y=w.context,te=Y.gl,ne=[_.dynamicLayoutVertexBuffer,_.opacityVertexBuffer,_.iconTransitioningVertexBuffer,_.globeExtVertexBuffer,_.zOffsetVertexBuffer,_.orientationVertexBuffer];_.featureIdBuffer&&ne.push(_.featureIdBuffer),_.fadeVertexBuffer&&ne.push(_.fadeVertexBuffer);const le=_.uboBinder?null:_.programConfigurations.get(y.id);if(_.uboBinder){_.uboBinder.layer=y;const Se=w.transform.zoom,Me=w.style.getBrightness?w.style.getBrightness():null,qe=_.uboBinder.getConstantUniformValues(Me);V.u_spp_fill_np_color=qe.fill_np_color,V.u_spp_halo_np_color=qe.halo_np_color,V.u_spp_opacity=qe.opacity,V.u_spp_halo_width=qe.halo_width,V.u_spp_halo_blur=qe.halo_blur,V.u_spp_emissive_strength=qe.emissive_strength,V.u_spp_occlusion_opacity=qe.occlusion_opacity,V.u_spp_z_offset=qe.z_offset,V.u_spp_zoom_fraction=Se-_.uboBinder._floorZoom;const Ne=y.paint.get(_.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),We=_.uboBinder.hasPerFeatureTranslate()&&Ne==="map"?w.transform.angle:0;V.u_spp_translate_rotation=[Math.cos(We),Math.sin(We)]}const{batchIndices:me,batchSegments:fe}=_.getBatchGrouping(f);for(const Se of me){const Me=fe.get(Se);_.uboBinder&&_.uboBinder.bind(Y,k.program,Se),k.draw(w,te.TRIANGLES,R,M,z,l.a5.disabled,V,y.id,_.layoutVertexBuffer,_.indexBuffer,Me,y.paint,w.transform.zoom,le,ne,H,_.uboBinder?_.uboBinder.getUBO(Se):void 0)}}function I0(_,f,y,w,k,R){const M=y.paint.get("line-width"),z=y.paint.get("line-emissive-strength").isConstant(),V=y.paint.get("line-emissive-strength").constantOr(0),H=y.paint.get("line-occlusion-opacity"),Y=y.layout.get("line-elevation-reference"),te=y.layout.get("line-width-unit")==="meters",ne=Y==="sea",le=!(!_.terrain||!_.terrain.enabled),me=_.context,fe=me.gl;if(y.hasElevatedBuckets&&_.transform.projection.name==="globe")return;const Se=y.layout.get("line-cross-slope"),Me=Se!==void 0,qe=Se<1,Ne=k||_.colorModeForDrapableLayerRenderPass(z?V:null),We=_.terrain&&_.terrain.renderingToTexture||R,ct=We?1:l.e.devicePixelRatio,it=y.paint.get("line-dasharray"),pt=it.constantOr(1),dt=y.layout.get("line-cap"),mt=it.constantOr(null),xt=dt.constantOr(null),bt=y.paint.get("line-pattern"),Ft=bt.constantOr(1),Lt=y.paint.get("line-pattern-cross-fade"),Mt=bt.constantOr(null),or=y.paint.get("line-opacity").constantOr(1);let fr=!Ft&&or!==1||_.depthOcclusion&&H>0&&H<1;const Cr=y.paint.get("line-gradient"),qr=y.paint.get("line-border-width").constantOr(1)!==0?y.paint.get("line-border-gradient"):null,qt=Ft?"linePattern":"line",Ut=l.ed(y);if(!Ft){const Xr=Math.floor(_.context.maxUniformBlockSize/4),ei=Math.floor(Xr/4);Ut.push(`MAX_UBO_SIZE_VEC4 ${ei}u`)}let gr;if(We&&_.terrain&&_.terrain.clipOrMaskOverlapStencilType()&&(fr=!1),H!==0&&_.depthOcclusion){const Xr=y.paint._values["line-opacity"];Xr&&Xr.value&&Xr.value.kind==="constant"?gr=Xr.value:l.w(`Occlusion opacity for layer ${y.id} is supported only when line-opacity isn't data-driven.`)}M.value.kind!=="constant"&&M.value.isLineProgressConstant===!1&&Ut.push("VARIABLE_LINE_WIDTH");const Pr=y.paint.get("line-emissive-strength");Ft||Pr.value.kind==="constant"||Pr.value.isLineProgressConstant!==!1||Ut.push("VARIABLE_LINE_EMISSIVE_STRENGTH"),_._debugParams.showElevationIdDebug&&Ut.push("DEBUG_ELEVATION_ID"),We&&(_.emissiveMode!=="dual-source-blending"||z?_.isEmissiveMrtActive()&&(Ut.push("USE_MRT1"),_.emissiveMode==="mrt-full-rgba"&&Ut.push("USE_MRT1_RGBA")):Ut.push("DUAL_SOURCE_BLENDING"));const ur={};let Xt=null;const mr=[],tn=(Xr,ei,Rn,Ni,zn,Qi)=>{for(const xn of Xr){const Sn=f.getTile(xn);if(Ft&&!Sn.patternsLoaded())continue;const Dn=Sn.getBucket(y);if(!Dn||Dn.elevationType!=="none"&&!zn||Dn.elevationType==="none"&&zn)continue;_.prepareDrawTile();const Ks=[...ei],ya=Dn.elevationType==="road",Ti=_.shadowRenderer,Ba=ya&&!!Ti&&Ti.enabled;let bs=[0,0,0];if(Ba){const ji=_.style.directionalLight,Hi=_.style.ambientLight;ji&&Hi&&(bs=l.aQ(_.style,ji,Hi)),Ks.push("RENDER_SHADOWS","NORMAL_OFFSET")}const Ri=Ft?Dn.programConfigurations.get(y.id):null,gi=Ft?null:Dn.uboBinders[y.id];let yi=!1;if(Ri&&Mt&&Sn.imageAtlas){const ji=l.aR.from(Mt),Hi=ji.getPrimary().scaleSelf(ct).toString(),Os=Sn.imageAtlas.patternPositions.get(Hi),Za=ji.getSecondary(),Jd=Za?Sn.imageAtlas.patternPositions.get(Za.scaleSelf(ct).toString()):null;yi=!!Os&&!!Jd,Os&&Ri.setConstantPatternPositions(Os,Jd)}Ri&&Lt>0&&(yi||Ri.getPatternTransitionVertexBuffer("line-pattern"))&&Ks.push("LINE_PATTERN_TRANSITION"),Dn.elevationGroundScaleVertexBuffer&&Ks.push("ELEVATION_GROUND_SCALE");const Dr=_.isTileAffectedByFog(xn),Pn=_.getOrCreateProgram(qt,{config:Ri,defines:Ks,overrideFog:Dr});let ti=null;!Ft&&mt&&xt&&Sn.lineAtlas&&(ti=Sn.lineAtlas.getDash(mt,xt)),Ba&&Ti.setupShadows(Sn.tileID.toUnwrapped(),Pn,"vector-tile");let[Ya,ao]=y.paint.get("line-trim-offset");(xt==="round"||xt==="square")&&Ya!==ao&&(Ya===0&&(Ya-=1),ao===1&&(ao+=1));const yu=We?xn.projMatrix:null,ua=te?1/Dn.tileToMeter/l.ck(Sn,1,_.transform.zoom):1,Is=te?1/Dn.tileToMeter/l.ck(Sn,1,Math.floor(_.transform.zoom)):1,Ji=Ft&&pt?y.paint._values["line-floorwidth"]:null;let Ii;const Qs=Sn.dashIdealZ;if(Ji&&Ji.value.kind==="constant"&&Qs!==Sn.tileID.overscaledZ){const ji=Dn.zoom;ji in ur||(ur[ji]=Math.max(.01,y.getPaintPropertyValue("line-width").expression.evaluate({zoom:ji}))),Ii=Ji.value.value,Ji.value.value=ur[ji]*Math.pow(2,Qs-ji)}const na=Ft?l.ee(_,Sn,y,yu,ct,ua,Is,[Ya,ao],bs,Lt):l.ef(_,Sn,y,yu,Dn.lineClipsArray.length,ct,ua,Is,[Ya,ao],bs),Ls=(ji,Hi,Os,Za,Jd,xu)=>{let Nh=ji.texture;if(Hi!==ji.version){let Ep=256;if(Os){const Tp=f.getSource().maxzoom,$0=xn.canonical.z===Tp?Math.ceil(1<<_.transform.maxZoom-xn.canonical.z):1;Ep=l.bb(l.ei(Dn.maxLineLength/l.ac*1024*$0),256,me.maxTextureSize)}ji.gradient=l.ej({expression:Za,evaluationKey:"lineProgress",resolution:Ep,image:ji.gradient||void 0,clips:Dn.lineClipsArray,lut:Jd?null:y.lut}),ji.texture?ji.texture.update(ji.gradient):ji.texture=new l.T(me,ji.gradient,fe.RGBA8),ji.version=Hi,Nh=ji.texture}me.activeTexture.set(xu),Nh.bind(Os?fe.NEAREST:fe.LINEAR,fe.CLAMP_TO_EDGE)};if(gi){gi.layer=y;const ji=_.transform.zoom;if(!Xt){const Za=_.style.getBrightness?_.style.getBrightness():null;Xt=gi.getConstantUniformValues(Za)}const Hi=Xt,Os=na;if(Os.u_lpp_color=Hi.color_np_color,Os.u_lpp_border_color=Hi.border_np_color,Os.u_lpp_opacity=Hi.opacity,Os.u_lpp_blur=Hi.blur,Os.u_lpp_width=Hi.width,Os.u_lpp_gap_width=Hi.gap_width,Os.u_lpp_offset=Hi.offset,Os.u_lpp_floorwidth=Hi.floorwidth,Os.u_lpp_border_width=Hi.border_width,Os.u_lpp_emissive_strength=Hi.emissive_strength,Os.u_lpp_side_z_offset=Hi.side_z_offset,ti&&(Os.u_lpp_dash=[ti.tl[0],ti.tl[1],ti.br[0],ti.br[1]]),Os.u_lpp_zoom_fraction=ji-gi._floorZoom,pt&&Qs!==Sn.tileID.overscaledZ&&(gi.header[l.eg]&l.eh)===0){const Za=Dn.zoom;Za in ur||(ur[Za]=Math.max(.01,y.getPaintPropertyValue("line-width").expression.evaluate({zoom:Za}))),Os.u_lpp_floorwidth=ur[Za]*Math.pow(2,Qs-Za)}}Cr&&Ls(Dn.gradients[y.id],y.gradientVersion,y.stepInterpolant,y.getPaintPropertyValue("line-gradient").expression,y.paint.get("line-gradient-use-theme").constantOr("default")==="none",fe.TEXTURE1),qr&&Ls(Dn.borderGradients[y.id],y.borderGradientVersion,y.borderStepInterpolant,y.getPaintPropertyValue("line-border-gradient").expression,y.paint.get("line-border-gradient-use-theme").constantOr("default")==="none",fe.TEXTURE2),pt?(me.activeTexture.set(fe.TEXTURE0),Sn.lineAtlasTexture&&Sn.lineAtlasTexture.bind(fe.LINEAR,fe.REPEAT)):Ft||(me.activeTexture.set(fe.TEXTURE0),_.emptyTexture.bind(fe.LINEAR,fe.CLAMP_TO_EDGE)),Ft&&Ri&&(me.activeTexture.set(fe.TEXTURE0),Sn.imageAtlasTexture&&Sn.imageAtlasTexture.bind(fe.LINEAR,fe.CLAMP_TO_EDGE),Ri.updatePaintBuffers()),zn&&!ya&&_.terrain.setupElevationDraw(Sn,Pn),_.uploadCommonUniforms(me,Pn,xn.toUnwrapped());const ol=(ji,Hi,Os)=>{if(Hi&&Hi.get().length!==0){if(gr!=null&&(gr.value=or*H,gi&&(na.u_lpp_opacity=or*H)),Os!==void 0&&(na.u_opacity_multiplier=Os),gi){const{batchIndices:Za,batchSegments:Jd}=Dn.getBatchGrouping(Hi);for(const xu of Za)gi.bind(me,Pn.program,xu),Pn.draw(_,fe.TRIANGLES,Rn,ji,Ne,l.a5.disabled,na,y.id,Dn.layoutVertexBuffer,Dn.indexBuffer,Jd.get(xu),y.paint,_.transform.zoom,Ri,[Dn.layoutVertexBuffer2,Dn.patternVertexBuffer,Dn.zOffsetVertexBuffer,Dn.elevationIdColVertexBuffer,Dn.elevationGroundScaleVertexBuffer],void 0,gi.getUBO(xu))}else Pn.draw(_,fe.TRIANGLES,Rn,ji,Ne,l.a5.disabled,na,y.id,Dn.layoutVertexBuffer,Dn.indexBuffer,Hi,y.paint,_.transform.zoom,Ri,[Dn.layoutVertexBuffer2,Dn.patternVertexBuffer,Dn.zOffsetVertexBuffer,Dn.elevationIdColVertexBuffer,Dn.elevationGroundScaleVertexBuffer]);Os!==void 0&&(na.u_opacity_multiplier=1),gr!=null&&(gr.value=or,gi&&(na.u_lpp_opacity=or))}},Sc=kn.drawLineFrcCoverageDetect?kn.drawLineFrcCoverageDetect(_,Dn,xn,zn,ol,mr):null,Fl=ji=>{Sc&&Sc.active&&kn.drawLineFrcRenderLine?kn.drawLineFrcRenderLine(Dn,Sc,ji,ol):ol(ji,Dn.segments)};if(fr&&!zn){const ji=_.stencilModeForClipping(xn).ref;ji===0&&We&&me.clear({stencil:0});const Hi={func:fe.EQUAL,mask:255};na.u_alpha_discard_threshold=.8,Fl(new l.a4(Hi,ji,255,fe.KEEP,fe.KEEP,fe.INVERT)),na.u_alpha_discard_threshold=0,Fl(new l.a4(Hi,ji,255,fe.KEEP,fe.KEEP,fe.KEEP))}else na.u_alpha_discard_threshold=fr&&zn&&Qi?.8:0,Fl(zn?Ni:_.stencilModeForClipping(xn));Sc&&kn.drawLineFrcFadePass&&kn.drawLineFrcFadePass(_,Dn,xn,Sc,zn,Ni,ol),Ii!==void 0&&(Ji.value.value=Ii)}};let kr=_.depthModeForSublayer(0,l.a3.ReadOnly);const vn=new l.a3(_.depthOcclusion?fe.GREATER:fe.LEQUAL,l.a3.ReadOnly,_.depthRangeFor3D);if(y.hasNonElevatedBuckets){const Xr=!We&&_.terrain;H!==0&&Xr?l.w(`Occlusion opacity for layer ${y.id} is supported on terrain only if the layer has line-z-offset enabled.`):Xr?l.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${y.id}.`):tn(w,Ut,kr,l.a4.disabled,!1,!0)}if(y.hasElevatedBuckets){Y==="hd-road-markup"?le||(kr=vn,Ut.push("ELEVATED_ROADS")):(Ut.push("ELEVATED"),kr=vn,Me&&Ut.push(qe?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),ne&&Ut.push("ELEVATION_REFERENCE_SEA"));const Xr=fr?_.stencilModeFor3D():l.a4.disabled;Y!=="hd-road-markup"&&(_.forceTerrainMode=!0),tn(w,Ut,kr,Xr,!0,!0),fr&&tn(w,Ut,kr,Xr,!0,!1),Y!=="hd-road-markup"&&(_.forceTerrainMode=!1)}kn.drawLineFrcCoverageSecondPass&&kn.drawLineFrcCoverageSecondPass(_,y,mr),fr&&(_.resetStencilClippingMasks(),We&&me.clear({stencil:0})),H===0||_.depthOcclusion||We||_.layersWithOcclusionOpacity.push(_.currentLayer)}class A2{destroy(){this.fbo&&(this.fbo.destroy(),this.fbo=null),this.drapeFbo&&(this.drapeFbo.destroy(),this.drapeFbo=null)}}class k2{constructor(f){this.pbo=f.createBuffer(),this.sync=null,this.fboA=null,this.fboB=null,this.maxDensity=0}destroy(f){this.sync&&(f.deleteSync(this.sync),this.sync=null),f.deleteBuffer(this.pbo),this.fboA&&(this.fboA.destroy(),this.fboA=null),this.fboB&&(this.fboB.destroy(),this.fboB=null)}}const Ox={additive:{clearColor:new l.C(0,0,0,0),colorMode:l.a7.additiveAlphaWeighted,compositeUniformValue:1},multiply:{clearColor:new l.C(1,1,1,1),colorMode:l.a7.multiply,compositeUniformValue:0}};function j0(_){return!(!_.extRenderToTextureHalfFloat&&!_.extColorBufferFloat)}function I2(_,f){return _==="additive"&&j0(f)?l.a7.additiveAlphaWeightedUnboundedAlpha:Ox[_].colorMode}function T1(_,f,y){const w=_.context,k=w.gl;let R=y.width,M=y.height,z=y.colorAttachment0.get();f.lineBlendDensityReadback||(f.lineBlendDensityReadback=new k2(k));const V=f.lineBlendDensityReadback;let H=0,Y=!0;for(;R>1||M>1;){const le=Math.max(1,Math.floor(R/2)),me=Math.max(1,Math.floor(M/2)),fe=H===0?"fboA":"fboB";V[fe]=Sp.createWithTexture(w,V[fe],le,me,!1);const Se=V[fe];w.bindFramebuffer.set(Se.framebuffer),w.viewport.set([0,0,le,me]),w.activeTexture.set(k.TEXTURE0),k.bindTexture(k.TEXTURE_2D,z),_.getOrCreateProgram("lineBlendReduce").draw(_,k.TRIANGLES,l.a3.disabled,l.a4.disabled,l.a7.unblended,l.a5.disabled,HB(0,[1/R,1/M],Y),f.id,_.viewportBuffer,_.quadTriangleIndexBuffer,_.viewportSegments,f.paint,_.transform.zoom),R=le,M=me,z=Se.colorAttachment0.get(),H=1-H,Y=!1}const te=j0(w),ne=te?16:4;V.sync&&(k.deleteSync(V.sync),V.sync=null),k.bindBuffer(k.PIXEL_PACK_BUFFER,V.pbo),k.bufferData(k.PIXEL_PACK_BUFFER,ne,k.STREAM_READ),k.readPixels(0,0,1,1,k.RGBA,te?k.FLOAT:k.UNSIGNED_BYTE,0),k.bindBuffer(k.PIXEL_PACK_BUFFER,null),V.sync=k.fenceSync(k.SYNC_GPU_COMMANDS_COMPLETE,0),w.viewport.set([0,0,_.width,_.height])}function j2(_,f,y){if(!j0(_.context))return;const w=f.lineBlendDensityReadback;w&&w.sync?(function(k,R,M){if(k.sync&&R.getSyncParameter(k.sync,R.SYNC_STATUS)===R.SIGNALED){if(R.deleteSync(k.sync),k.sync=null,R.bindBuffer(R.PIXEL_PACK_BUFFER,k.pbo),j0(M)){const z=new Float32Array(4);R.getBufferSubData(R.PIXEL_PACK_BUFFER,0,z);const V=z[1];k.maxDensity=Math.max(2*(V>0?z[0]/V:0),1)}else k.maxDensity=1;R.bindBuffer(R.PIXEL_PACK_BUFFER,null)}}(w,_.context.gl,_.context),w.sync||(T1(_,f,y),_.style.map.triggerRepaint())):(T1(_,f,y),_.style.map.triggerRepaint())}function iR(_,f,y,w,k,R){const M=_.context,z=M.gl,V=y==="additive"?1:f.paint.get("line-opacity").constantOr(1),H=y==="additive"?function(te,ne){const le=ne.paint.get("line-blend-additive-clamp");if(le>0)return le;const me=ne.lineBlendDensityReadback;return me&&me.maxDensity!==0?me.maxDensity:null}(0,f):1;if(H===null)return;M.bindFramebuffer.set(k),R&&M.viewport.set([0,0,R[0],R[1]]),M.activeTexture.set(z.TEXTURE0),z.bindTexture(z.TEXTURE_2D,w.colorAttachment0.get());const Y=I2(y,_.context);_.getOrCreateProgram("lineBlendComposite").draw(_,z.TRIANGLES,l.a3.disabled,l.a4.disabled,Y,l.a5.disabled,((te,ne,le,me)=>({u_image:0,u_opacity:ne,u_blend_mode:le,u_max_density:me}))(0,V,Ox[y].compositeUniformValue,H),f.id,_.viewportBuffer,_.quadTriangleIndexBuffer,_.viewportSegments,f.paint,_.transform.zoom)}function C2(_,f,y,w){const{painter:k,sourceCache:R,layer:M,coords:z,colorMode:V,elevationType:H,terrainEnabled:Y,pass:te}=_,ne=k.context.gl,le=M.paint.get("fill-pattern"),me=M.paint.get("fill-pattern-cross-fade"),fe=le.constantOr(null);let Se=H;H!=="road"||f&&!Y||(Se="none");const Me=Se==="road",qe=_.painter.shadowRenderer,Ne=Me&&!!qe&&qe.enabled,We=new l.a3(k.context.gl.LEQUAL,l.a3.ReadOnly,k.depthRangeFor3D);let ct=[0,0,0];if(Ne){const mt=k.style.directionalLight,xt=k.style.ambientLight;mt&&xt&&(ct=l.aQ(k.style,mt,xt))}const it=le&&le.constantOr(1),pt=k.terrain&&k.terrain.renderingToTexture,dt=(mt,xt)=>{let bt,Ft,Lt,Mt,or;xt?(bt=it&&!M.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",Lt=ne.LINES):(bt=it?"fillPattern":"fill",Lt=ne.TRIANGLES);const fr=[];for(const Cr of z){const qr=R.getTile(Cr);if(it&&!qr.patternsLoaded())continue;const qt=qr.getBucket(M);if(!qt)continue;const Ut=f?qt.hdExt&&qt.hdExt.elevationBufferData:qt.bufferData;if(!Ut||Ut.isEmpty())continue;k.prepareDrawTile();const gr=Ut.programConfigurations.get(M.id),Pr=k.isTileAffectedByFog(Cr),ur=[],Xt=[];Me&&(ur.push("ELEVATED_ROADS"),Xt.push(Ut.elevatedLayoutVertexBuffer)),Ne&&ur.push("RENDER_SHADOWS","NORMAL_OFFSET"),pt&&y&&(ur.push("USE_MRT1"),k.emissiveMode==="mrt-full-rgba"&&ur.push("USE_MRT1_RGBA")),it&&(k.context.activeTexture.set(ne.TEXTURE0),qr.imageAtlasTexture&&qr.imageAtlasTexture.bind(ne.LINEAR,ne.CLAMP_TO_EDGE),gr.updatePaintBuffers());let mr=!1;if(fe&&qr.imageAtlas){const Ni=qr.imageAtlas,zn=l.aR.from(fe),Qi=zn.getPrimary().scaleSelf(l.e.devicePixelRatio).toString(),xn=zn.getSecondary(),Sn=Ni.patternPositions.get(Qi),Dn=xn?Ni.patternPositions.get(xn.scaleSelf(l.e.devicePixelRatio).toString()):null;mr=!!Sn&&!!Dn,Sn&&gr.setConstantPatternPositions(Sn,Dn)}me>0&&(mr||gr.getPatternTransitionVertexBuffer("fill-pattern"))&&ur.push("FILL_PATTERN_TRANSITION");const tn=k.getOrCreateProgram(bt,{config:gr,overrideFog:Pr,defines:ur}),kr=k.translatePosMatrix(Cr.projMatrix,qr,M.paint.get("fill-translate"),M.paint.get("fill-translate-anchor"));Ne&&qe.setupShadows(qr.tileID.toUnwrapped(),tn,"vector-tile");const vn=M.paint.get("fill-emissive-strength");if(xt){Mt=Ut.lineIndexBuffer,or=Ut.lineSegments;const Ni=k.terrain&&k.terrain.renderingToTexture?k.terrain.drapeBufferSize:[ne.drawingBufferWidth,ne.drawingBufferHeight];Ft=bt==="fillOutlinePattern"&&it?GB(kr,vn,k,qr,Ni,ct,me):i2(kr,vn,Ni,ct)}else Mt=Ut.indexBuffer,or=Ut.triangleSegments,Ft=it?n2(kr,vn,k,qr,ct,me):r2(kr,vn,ct);k.uploadCommonUniforms(k.context,tn,Cr.toUnwrapped());let Xr=mt;if((H==="road"&&!Y||H==="offset")&&(Xr=We),!or||or.get&&or.get().length===0)continue;const ei=w||k.stencilModeForClipping(Cr);let Rn="fallthrough";!xt&&kn.drawFillFrcCoverageFirstPass&&(Rn=kn.drawFillFrcCoverageFirstPass({painter:k,layer:M,bucket:qt,coord:Cr,elevatedGeometry:f,program:tn,programConfiguration:gr,uniformValues:Ft,drawMode:Lt,depthMode:Xr,stencilMode:ei,colorMode:V,bufferData:Ut,indexBuffer:Mt,segments:or,dynamicBuffers:Xt,polygonCoverageTiles:fr})),Rn==="fallthrough"&&tn.draw(k,Lt,Xr,ei,V,l.a5.disabled,Ft,M.id,Ut.layoutVertexBuffer,Mt,or,M.paint,k.transform.zoom,gr,Xt)}!xt&&kn.drawFillFrcCoverageSecondPass&&kn.drawFillFrcCoverageSecondPass(k,M,fr,Lt,V)};k.renderPass===te&&dt(k.depthModeForSublayer(1,k.renderPass==="opaque"?l.a3.ReadWrite:l.a3.ReadOnly),!1),Se==="none"&&k.renderPass==="translucent"&&M.paint.get("fill-antialias")&&dt(k.depthModeForSublayer(M.getPaintProperty("fill-outline-color")?2:0,l.a3.ReadOnly),!0)}function sR(_){return[_[0]*l.el,_[1]*l.el,_[2]*l.el,0]}function Hs(_,f,y,w,k,R,M,z,V,H){const Y=k.getSource(),te=w.globeSharedBuffers;if(!te)return;let ne,le,me;if(y&&(ne=k.getTile(y)),Y instanceof md?(le=Y.texture,me=l.c7(0,0,w.transform)):ne&&y&&(le=ne.texture,me=l.c7(y.canonical.z,y.canonical.x,w.transform)),!le||!me)return;f||(me=l.aY(l.a2(),me,[1,-1,1]));const fe=w.context,Se=fe.gl,Me=R.paint.get("raster-resampling")==="nearest"?Se.NEAREST:Se.LINEAR,qe=w.colorModeForDrapableLayerRenderPass(M),Ne=z.defines;Ne.push("GLOBE_POLES");const We=new l.a3(Se.LEQUAL,l.a3.ReadWrite,w.depthRangeFor3D),ct=w.transform.expandedFarZProjMatrix,it=Float32Array.from(l.bf(l.bg(new l.c1(0,0,0))));w.terrain&&w.terrain.prepareDrawTile(),fe.activeTexture.set(Se.TEXTURE0),le.bind(Me,Se.CLAMP_TO_EDGE),fe.activeTexture.set(Se.TEXTURE1),le.bind(Me,Se.CLAMP_TO_EDGE),"useMipmap"in le&&fe.extTextureFilterAnisotropic&&w.transform.pitch>20&&Se.texParameterf(Se.TEXTURE_2D,fe.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,fe.extTextureFilterAnisotropicMax);const[pt,dt,mt,xt]=y?te.getPoleBuffers(y.canonical.z,!1):te.getPoleBuffers(0,!0),bt=_;let Ft;f?(Ft=pt,w.renderDefaultNorthPole=bt!==0):(Ft=dt,w.renderDefaultSouthPole=bt!==0);const Lt=sR(z.mix),Mt=((fr,Cr,qr,qt,Ut,gr,Pr,ur,Xt,mr,tn,kr,vn,Xr)=>PN(fr,Cr,qr,qt,new Float32Array(16),new Float32Array(9),[0,0],Ut,[0,0],[0,0,0,0],1,{opacity:1,mix:0},Pr,[0,0],Xt,2,tn,kr,vn,1,0,Xr))(w,ct,it,me,l._(w.transform.zoom),0,R,0,bt,0,Lt,z.offset,z.range,M),or=w.getOrCreateProgram("raster",{defines:Ne});w.uploadCommonUniforms(fe,or,null),or.draw(w,Se.TRIANGLES,We,H,qe,V,Mt,R.id,Ft,mt,xt)}function P2(_){if(_.isOrthographic)return[0,0,0,0];const f=_._nearZ,y=_.projection.farthestPixelDistance(_),w=y-f,k=.2*_.height,R=f+k;return[f,y,(R-k-f)/w,(R-f)/w]}function A1(_,f,y,w){if(_)return f.type==="raster-array"?f.getTextureDescriptor(_,y,!0):{texture:_.texture,mix:sR(w.mix),offset:w.offset,buffer:0,tileSize:1}}const N2=l.dk(new Float32Array(16)),C0={"dual-source-blending":"dual-source-blending","mrt-fallback":"mrt","mrt-full-rgba":"mrt-rgba"},dm=l.b9([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:qg}=dm;function Yt(_,f,y,w){_.emplaceBack(f,y,w)}class sr{constructor(f){this.vertexArray=new l.eo,this.indices=new l.ak,Yt(this.vertexArray,-1,-1,1),Yt(this.vertexArray,1,-1,1),Yt(this.vertexArray,-1,1,1),Yt(this.vertexArray,1,1,1),Yt(this.vertexArray,-1,-1,-1),Yt(this.vertexArray,1,-1,-1),Yt(this.vertexArray,-1,1,-1),Yt(this.vertexArray,1,1,-1),this.indices.emplaceBack(5,1,3),this.indices.emplaceBack(3,7,5),this.indices.emplaceBack(6,2,0),this.indices.emplaceBack(0,4,6),this.indices.emplaceBack(2,6,7),this.indices.emplaceBack(7,3,2),this.indices.emplaceBack(5,4,0),this.indices.emplaceBack(0,1,5),this.indices.emplaceBack(0,2,3),this.indices.emplaceBack(3,1,0),this.indices.emplaceBack(7,6,4),this.indices.emplaceBack(4,5,7),this.vertexBuffer=f.createVertexBuffer(this.vertexArray,qg),this.indexBuffer=f.createIndexBuffer(this.indices),this.segment=l.aj.simpleSegment(0,0,36,12)}}function Zd(_,f,y,w,k,R){const M=_.context.gl,z=f.paint.get("sky-atmosphere-color"),V=f.paint.get("sky-atmosphere-halo-color"),H=f.paint.get("sky-atmosphere-sun-intensity"),Y=((te,ne,le,me,fe)=>({u_matrix_3f:te,u_sun_direction:ne,u_sun_intensity:le,u_color_tint_r:[me.r,me.g,me.b,me.a],u_color_tint_m:[fe.r,fe.g,fe.b,fe.a],u_luminance:5e-5}))(l.er(l.es(),w),k,H,z.toPremultipliedRenderColor(null),V.toPremultipliedRenderColor(null));M.framebufferTexture2D(M.FRAMEBUFFER,M.COLOR_ATTACHMENT0,M.TEXTURE_CUBE_MAP_POSITIVE_X+R,f.skyboxTexture,0),y.draw(_,M.TRIANGLES,l.a3.disabled,l.a4.disabled,l.a7.unblended,l.a5.frontCW,Y,"skyboxCapture",f.skyboxGeometry.vertexBuffer,f.skyboxGeometry.indexBuffer,f.skyboxGeometry.segment)}const Ws=l.b9([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class lt{constructor(f){const y=new l.et;y.emplaceBack(-1,1,1,0,0),y.emplaceBack(1,1,1,1,0),y.emplaceBack(1,-1,1,1,1),y.emplaceBack(-1,-1,1,0,1);const w=new l.ak;w.emplaceBack(0,1,2),w.emplaceBack(2,3,0),this.vertexBuffer=f.createVertexBuffer(y,Ws.members),this.indexBuffer=f.createIndexBuffer(w),this.segments=l.aj.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const aR=l.b9([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_size_scale",components:1},{type:"Float32",name:"a_opacity",components:1}]);class k1{constructor(){this.colorModeAlphaBlendedWriteRGB=new l.a7([l.eu,l.ev,l.eu,l.ev],l.C.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new l.a7(l.a7.Replace,l.C.transparent,[!1,!1,!1,!0]),this.params={starsCount:16e3,sizeMultiplier:.15,sizeRange:100,intensityRange:200},this.updateNeeded=!0,this._painter=null,this._devtoolsFolder=null}update(f){this._painter=f;const y=f.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new lt(y);let w=this.params;const k=w.sizeRange,R=w.intensityRange,M=function(te){const ne=l.bt(30),le=[];for(let me=0;me{const dt=R.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];pt&&dt.push("ALPHA_PASS");const mt=f.getOrCreateProgram("globeAtmosphere",{defines:dt}),xt=((Ft,Lt,Mt,or,fr,Cr,qr,qt,Ut,gr,Pr,ur)=>({u_frustum_tl:Ft,u_frustum_tr:Lt,u_frustum_br:Mt,u_frustum_bl:or,u_horizon:fr,u_transition:Cr,u_fadeout_range:qr,u_atmosphere_fog_color:qt.toArray01(),u_high_color:Ut.toArray01(),u_space_color:gr.toArray01(),u_temporal_offset:Pr,u_horizon_angle:ur}))(R.frustumCorners.TL,R.frustumCorners.TR,R.frustumCorners.BR,R.frustumCorners.BL,R.frustumCorners.horizon,z,Se,Y,ne,me,qe,ct);f.uploadCommonUniforms(w,mt);const bt=this.atmosphereBuffer;bt&&mt.draw(f,k.TRIANGLES,M,l.a4.disabled,pt?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,l.a5.backCW,xt,pt?"atmosphere_glow_alpha":"atmosphere_glow",bt.vertexBuffer,bt.indexBuffer,bt.segments)};it(!1),it(!0)}drawStars(f,y){const w=l.bb(y.properties.get("star-intensity"),0,1);if(w===0)return;const k=f.context,R=k.gl,M=f.transform,z=f.getOrCreateProgram("stars"),V=l.bo([]);l.bp(V,V,-M._pitch),l.bq(V,V,-M.angle),l.bp(V,V,l.aF(M._center.lat)),l.ey(V,V,-l.aF(M._center.lng));const H=l.br(new Float32Array(16),V),Y=l.a1([],M.starsProjMatrix,H),te=l.er([],H),ne=l.ez([],te);let le=this.params.sizeMultiplier;const me=[0,1,0];l.d2(me,me,ne),l.dY(me,me,le);const fe=[1,0,0];l.d2(fe,fe,ne),l.dY(fe,fe,le);const Se=(Me=me,qe=fe,Ne=w,{u_matrix:Float32Array.from(Y),u_up:Me,u_right:qe,u_intensity_multiplier:Ne});var Me,qe,Ne;f.uploadCommonUniforms(k,z),this.starsVx&&this.starsIdx&&z.draw(f,R.TRIANGLES,l.a3.disabled,l.a4.disabled,this.colorModeAlphaBlendedWriteRGB,l.a5.disabled,Se,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class R2{}class L2{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(f,y,w){{const te=this._storage.get(y.id);if(te)return te.lastUsedFrameIdx=f,te.buf}const k=w.gl,R=k.getBufferParameter(k.ELEMENT_ARRAY_BUFFER,k.BUFFER_SIZE),M=new ArrayBuffer(R),z=new Int16Array(M);k.getBufferSubData(k.ELEMENT_ARRAY_BUFFER,0,new Int16Array(M));const V=new l.eA;for(let te=0;te30&&(w.buf.destroy(),this._storage.delete(y))}destroy(){for(const[f,y]of this._storage)y.buf.destroy(),this._storage.delete(f)}}class oR{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const Fx={symbol:function(_,f,y,w,k){if(_.renderPass!=="translucent")return;const R=l.a4.disabled,M=_.colorModeForRenderPass(),z=y.layout.get("text-variable-anchor"),V=y.layout.get("text-size-scale-range"),H=l.bb(_.scaleFactor,V[0],V[1]);z&&function(ne,le,me,fe,Se,Me,qe,Ne){const We=le.transform,ct=Se==="map",it=Me==="map";for(const pt of ne){const dt=fe.getTile(pt),mt=dt.getBucket(me);if(!mt||!mt.text||!mt.text.segments.get().length)continue;const xt=l.dr(mt.textSizeData,We.zoom,Ne),bt=l.e4(pt,mt.getProjection(),We),Ft=We.calculatePixelsToTileUnitsMatrix(dt),Lt=l.e5(bt,dt.tileID.canonical,it,ct,We,mt.getProjection(),Ft),Mt=mt.hasIconTextFit()&&mt.hasIconData();xt&&nR(mt,ct,it,qe,We,Lt,pt,Math.pow(2,We.zoom-dt.tileID.overscaledZ),xt,Mt)}}(w,_,y,f,y.layout.get("text-rotation-alignment"),y.layout.get("text-pitch-alignment"),k,H);const Y=y.paint.get("icon-opacity").constantOr(1)!==0,te=y.paint.get("text-opacity").constantOr(1)!==0;y.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(Y||te)?k0(_,f,y,w,R,M):(Y&&k0(_,f,y,w,R,M,{onlyIcons:!0}),te&&k0(_,f,y,w,R,M,{onlyText:!0})),f.map.showCollisionBoxes&&f.map._placementAlgorithm!=="global"&&du.drawCollisionDebug&&(du.drawCollisionDebug(_,f,y,w,y.paint.get("text-translate"),y.paint.get("text-translate-anchor"),!0),du.drawCollisionDebug(_,f,y,w,y.paint.get("icon-translate"),y.paint.get("icon-translate-anchor"),!1))},circle:function(_,f,y,w){if(_.renderPass!=="translucent")return;const k=y.paint.get("circle-opacity"),R=y.paint.get("circle-stroke-width"),M=y.paint.get("circle-stroke-opacity"),z=y.layout.get("circle-sort-key").constantOr(1)!==void 0,V=y.paint.get("circle-emissive-strength");if(k.constantOr(1)===0&&(R.constantOr(1)===0||M.constantOr(1)===0))return;const H=_.context,Y=H.gl,te=_.transform,ne=!(!_.terrain||!_.terrain.enabled),le=y.layout.get("circle-elevation-reference"),me=_.depthModeForSublayer(0,l.a3.ReadOnly),fe=new l.a3(_.context.gl.LEQUAL,l.a3.ReadOnly,_.depthRangeFor3D),Se=le==="none"||ne?me:fe,Me=l.a4.disabled,qe=_.colorModeForDrapableLayerRenderPass(V),Ne=te.projection.name==="globe",We=[l.ad(te.center.lng),l.ae(te.center.lat)],ct=[];for(let pt=0;ptpt.sortKey-dt.sortKey);const it={useDepthForOcclusion:te.depthOcclusionForSymbolsAndCircles};for(const pt of ct){const{programConfiguration:dt,program:mt,layoutVertexBuffer:xt,dynamicBuffers:bt,indexBuffer:Ft,uniformValues:Lt,tile:Mt}=pt.state,or=pt.segments;_.terrain&&_.terrain.setupElevationDraw(Mt,mt,it),_.uploadCommonUniforms(H,mt,Mt.tileID.toUnwrapped()),mt.draw(_,Y.TRIANGLES,Se,Me,qe,l.a5.disabled,Lt,y.id,xt,Ft,or,y.paint,te.zoom,dt,bt)}},heatmap:function(_,f,y,w){if(y.paint.get("heatmap-opacity")!==0)if(_.renderPass==="offscreen"){const k=_.context,R=k.gl,M=l.a4.disabled,z=new l.a7([R.ONE,R.ONE,R.ONE,R.ONE],l.C.transparent,[!0,!0,!0,!0]),V=_.transform.projection.name==="globe"?.5:.25;y.heatmapFbo=Sp.createWithTexture(k,y.heatmapFbo,_.width*V,_.height*V),k.clear({color:l.C.transparent});const H=_.transform,Y=H.projection.name==="globe",te=Y?["PROJECTION_GLOBE_VIEW"]:[],ne=Y?l.a5.frontCCW:l.a5.disabled,le=[l.ad(H.center.lng),l.ae(H.center.lat)];for(let me=0;me({u_image:0,u_color_ramp:1,u_opacity:te.paint.get("heatmap-opacity")}))(0,R),R.id,k.viewportBuffer,k.quadTriangleIndexBuffer,k.viewportSegments,R.paint,k.transform.zoom)}(_,y))},line:function(_,f,y,w){const k=y.paint.get("line-opacity"),R=y.paint.get("line-width");if(k.constantOr(1)===0||R.constantOr(1)===0)return;const M=y.paint.get("line-blend-mode"),z=_.terrain&&_.terrain.renderingToTexture;if(M==="default"||_.transform.projection.name==="globe")_.renderPass==="translucent"&&I0(_,f,y,w);else{if(z)return void function(V,H,Y,te,ne){if(V.renderPass!=="translucent")return;const le=V.context,me=le.gl,fe=V.terrain;if(!fe)return;const Se=le.bindFramebuffer.current,Me=V.isEmissiveMrtActive(),qe=fe.drapeBufferSize[0],Ne=fe.drapeBufferSize[1];Y.lineBlendFbos||(Y.lineBlendFbos=new A2),Y.lineBlendFbos.drapeFbo=Sp.createWithTexture(le,Y.lineBlendFbos.drapeFbo,qe,Ne,!0),Me&&me.drawBuffers([me.COLOR_ATTACHMENT0]),le.clear({color:Ox[ne].clearColor,depth:1,stencil:0});const We=V.currentStencilSource,ct=V._tileClippingMaskIDs,it=V.nextStencilID;V.currentStencilSource=void 0,V._tileClippingMaskIDs=new Map,V.nextStencilID=1;const pt=V._terrain;V._terrain=null,V._renderTileClippingMasks(Y,H,te),I0(V,H,Y,te,I2(ne,V.context),!0),V._terrain=pt,V.currentStencilSource=We,V._tileClippingMaskIDs=ct,V.nextStencilID=it,Me&&me.drawBuffers([me.COLOR_ATTACHMENT0,me.COLOR_ATTACHMENT1]);const dt=fe.drapeBufferSize,mt=Y.lineBlendFbos&&Y.lineBlendFbos.drapeFbo;mt&&(ne==="additive"&&j2(V,Y,mt),iR(V,Y,ne,mt,Se,dt))}(_,f,y,w,M);if(_.renderPass==="offscreen")return void function(V,H,Y,te,ne){const le=V.context,me=Math.ceil(V.width),fe=Math.ceil(V.height);Y.lineBlendFbos||(Y.lineBlendFbos=new A2),Y.lineBlendFbos.fbo=Sp.createWithTexture(le,Y.lineBlendFbos.fbo,me,fe,!0),le.clear({color:Ox[ne].clearColor,depth:1,stencil:0});const Se=V.currentStencilSource,Me=V._tileClippingMaskIDs,qe=V.nextStencilID;V.currentStencilSource=void 0,V._tileClippingMaskIDs=new Map,V.nextStencilID=1,V._renderTileClippingMasks(Y,H,te);const Ne=V.renderPass;V.renderPass="translucent",I0(V,H,Y,te,I2(ne,V.context)),V.renderPass=Ne,V.currentStencilSource=Se,V._tileClippingMaskIDs=Me,V.nextStencilID=qe,le.viewport.set([0,0,V.width,V.height]),ne==="additive"&&j2(V,Y,Y.lineBlendFbos.fbo)}(_,f,y,w,M);if(_.renderPass==="translucent"){const V=y.lineBlendFbos&&y.lineBlendFbos.fbo;return void(V&&iR(_,y,M,V,null))}}},fill:function(_,f,y,w){const k=y.paint.get("fill-color"),R=y.paint.get("fill-opacity");if(R.constantOr(1)===0)return;const M=y.paint.get("fill-emissive-strength"),z=_.colorModeForDrapableLayerRenderPass(M),V=y.paint.get("fill-pattern"),H=_.opaquePassEnabledForLayer()&&!V.constantOr(1)&&k.constantOr(l.C.transparent).a===1&&R.constantOr(0)===1?"opaque":"translucent";let Y="none";y.layout.get("fill-elevation-reference")!=="none"?Y="road":y.paint.get("fill-z-offset").constantOr(1)!==0&&(Y="offset");const te=!(!_.terrain||!_.terrain.enabled),ne={painter:_,sourceCache:f,layer:y,coords:w,colorMode:z,elevationType:Y,terrainEnabled:te,pass:H};if(_.renderPass==="shadow")return void(_.shadowRenderer&&Y==="road"&&!te&&kn.drawElevatedFillShadows&&kn.drawElevatedFillShadows(ne));const le=_.isEmissiveMrtActive();if(Y!=="offset"){if(C2(ne,!1,le),Y==="road"){const me=!te&&_.renderPass==="translucent";me&&kn.drawDepthPrepass&&kn.drawDepthPrepass(_,f,y,w,"geometry"),C2(ne,!0,le,l.a4.disabled),me&&kn.drawElevatedStructures&&kn.drawElevatedStructures(ne)}}else C2(ne,!1,le,_.stencilModeFor3D())},"fill-extrusion":function(_,f,y,w){const k=y.paint.get("fill-extrusion-opacity"),R=_.context,M=R.gl,z=_.terrain,V=z&&z.renderingToTexture;if(k===0)return;const H=_.isEmissiveMrtActive(),Y=_.conflationActive&&_.style.isLayerClipped(y,f.getSource()),te=_.style.order.indexOf(y.fqid);if(Y&&function(ne,le,me,fe,Se){for(const Me of fe){const qe=le.getTile(Me).getBucket(me);qe&&(qe.updateReplacement(Me,ne.replacementSource,Se),qe.uploadCentroid(ne.context))}}(_,f,y,w,te),z||Y)for(const ne of w){const le=f.getTile(ne).getBucket(y);le&&wn(_.context,f,ne,le,y,z,Y)}if(_.depthPrepassPhase){if(!V){const ne=new l.a3(M.LEQUAL,l.a3.ReadWrite,_.depthRangeFor3D);ui(_,f,y,w,ne,l.a4.disabled,l.a7.disabled,Y)}}else if(_.renderPass==="shadow"&&_.shadowRenderer){const ne=_.shadowRenderer;if(z&&k<.65&&y.getPaintPropertyValue("fill-extrusion-opacity").expression instanceof l.av)return;const le=ne.getShadowPassDepthMode();ui(_,f,y,w,le,l.a4.disabled,l.a7.disabled,Y)}else if(_.renderPass==="translucent"){const ne=!y.paint.get("fill-extrusion-pattern").constantOr(1),le=y.paint.get("fill-extrusion-color").constantOr(l.C.white);if(!V&&le.a!==0){const fe=new l.a3(_.context.gl.LEQUAL,l.a3.ReadWrite,_.depthRangeFor3D);k===1&&ne?ui(_,f,y,w,fe,l.a4.disabled,l.a7.unblended,Y):(_.hasGrouped3DDepthPrepass(_.currentLayer)||ui(_,f,y,w,fe,l.a4.disabled,l.a7.disabled,Y),ui(_,f,y,w,fe,_.stencilModeFor3DGroup(_.currentLayer),_.colorModeForRenderPass(),Y),_.resetStencilClippingMasks())}const me=_.style.enable3dLights()&&ne&&(!z&&_.transform.projection.name!=="globe"||V);if(me&&!on.drawGroundEffect&&Ln(),me&&on.drawGroundEffect){const fe=y.paint.get("fill-extrusion-opacity"),Se=y.paint.get("fill-extrusion-ambient-occlusion-intensity"),Me=y.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),qe=y.paint.get("fill-extrusion-flood-light-intensity"),Ne=y.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",We=y.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Ne?null:y.lut).toArray01().slice(0,3),ct=Se>0&&Me>0,it=qe>0,pt=new di;pt.translate=y.paint.get("fill-extrusion-translate"),pt.translateAnchor=y.paint.get("fill-extrusion-translate-anchor"),pt.edgeRadius=y.layout.get("fill-extrusion-edge-radius"),pt.cutoffFadeRange=y.paint.get("fill-extrusion-cutoff-fade-range");const dt=mt=>{const xt=_.depthModeForSublayer(1,l.a3.ReadOnly,M.LEQUAL,!0),bt=y.paint.get(mt?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Ft=l.aw(.1,3,bt),Lt=_._showOverdrawInspector;if(!Lt){const Mt=new l.a4({func:M.ALWAYS,mask:255},255,255,M.KEEP,M.KEEP,M.REPLACE),or=new l.a7([M.ONE,M.ONE,M.ONE,M.ONE],l.C.transparent,[!1,!1,!1,!0],M.MIN);on.drawGroundEffect(pt,_,f,y,w,xt,Mt,or,l.a5.disabled,mt,"sdf",fe,Se,Me,qe,We,Ft,Y,!1)}{const Mt=Lt?l.a4.disabled:new l.a4({func:M.EQUAL,mask:255},255,255,M.KEEP,M.DECR,M.DECR),or=Lt?_.colorModeForRenderPass():new l.a7([M.ONE_MINUS_DST_ALPHA,M.DST_ALPHA,M.ONE,M.ONE],l.C.transparent,[!0,!0,!0,!0]);on.drawGroundEffect(pt,_,f,y,w,xt,Mt,or,l.a5.disabled,mt,"color",fe,Se,Me,qe,We,Ft,Y,!1)}};if(V){const mt=()=>{const bt=z.drapeBufferSize[0],Ft=z.drapeBufferSize[1];let Lt=z.framebufferCopyTexture;return Lt&&(!Lt||Lt.size[0]===bt&&Lt.size[1]===Ft)||(Lt&&Lt.destroy(),Lt=z.framebufferCopyTexture=new l.T(R,new l.b({width:bt,height:Ft}),M.RGBA8)),Lt.bind(M.LINEAR,M.CLAMP_TO_EDGE),M.copyTexSubImage2D(M.TEXTURE_2D,0,0,0,0,0,bt,Ft),Lt},xt=(bt,Ft,Lt)=>{const Mt=_.depthModeForSublayer(1,l.a3.ReadOnly,M.LEQUAL,!1),or=y.paint.get(bt?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),fr=l.aw(.1,3,or);{const Cr=new l.a7([M.ONE,M.ONE,M.ONE,M.ONE],l.C.transparent,[!1,!1,!1,!0]);on.drawGroundEffect(pt,_,f,y,w,Mt,l.a4.disabled,Cr,l.a5.disabled,bt,"clear",fe,Se,Me,qe,We,fr,Y,Ft)}{const Cr=new l.a4({func:M.ALWAYS,mask:255},255,255,M.KEEP,M.KEEP,M.REPLACE),qr=new l.a7([M.ONE,M.ONE,M.ONE,M.ONE],l.C.transparent,[!1,!1,!1,!0],M.MIN);on.drawGroundEffect(pt,_,f,y,w,Mt,Cr,qr,l.a5.disabled,bt,"sdf",fe,Se,Me,qe,We,fr,Y,Ft)}H&&!bt&&(Lt=mt());{const Cr=bt?M.ZERO:M.ONE_MINUS_DST_ALPHA,qr=new l.a4({func:M.EQUAL,mask:255},255,255,M.KEEP,M.DECR,M.DECR),qt=new l.a7([Cr,M.DST_ALPHA,M.ONE_MINUS_DST_ALPHA,M.ZERO],l.C.transparent,[!0,!0,!0,!0]);on.drawGroundEffect(pt,_,f,y,w,Mt,qr,qt,l.a5.disabled,bt,"color",fe,Se,Me,qe,We,fr,Y,Ft)}if(!H||bt){const Cr=new l.a7([M.ONE,M.ONE,M.ONE,bt?M.ZERO:M.ONE],l.C.transparent,[!1,!1,!1,!0],bt?M.FUNC_ADD:M.MAX);on.drawGroundEffect(pt,_,f,y,w,Mt,l.a4.disabled,Cr,l.a5.disabled,bt,"clear",fe,Se,Me,qe,We,fr,Y,Ft,Lt)}else{M.drawBuffers([M.NONE,M.COLOR_ATTACHMENT1]);const Cr=new l.a4({func:M.EQUAL,mask:255},254,255,M.KEEP,M.DECR,M.DECR),qr=new l.a7([M.ONE,M.ONE,M.ONE,M.ONE],l.C.transparent,[!0,!1,!1,!1],M.MAX);on.drawGroundEffect(pt,_,f,y,w,Mt,Cr,qr,l.a5.disabled,bt,"emissive",fe,Se,Me,qe,We,fr,Y,Ft,Lt),M.drawBuffers([M.COLOR_ATTACHMENT0])}};if(ct||it){let bt;_.prepareDrawTile(),H&&!ct||(bt=mt()),ct&&xt(!0,!1,bt),it&&xt(!1,!0,bt)}}else ct&&dt(!0),it&&dt(!1),(ct||it)&&_.resetStencilClippingMasks()}}},hillshade:function(_,f,y,w){if(_.renderPass!=="offscreen"&&_.renderPass!=="translucent"||_.style.disableElevatedTerrain)return;const k=_.context,R=_.terrain&&_.terrain.renderingToTexture,[M,z]=_.renderPass!=="translucent"||R?[{},w]:_.stencilConfigForOverlap(w);for(const V of z){const H=f.getTile(V);if(H.needsHillshadePrepare&&_.renderPass==="offscreen")wx(_,H,y);else if(_.renderPass==="translucent"){const Y=_.depthModeForSublayer(0,l.a3.ReadOnly),te=y.paint.get("hillshade-emissive-strength"),ne=_.colorModeForDrapableLayerRenderPass(te),le=R&&_.terrain?_.terrain.stencilModeForRTTOverlap(V):M[V.overscaledZ];Dg(_,V,H,y,Y,le,ne)}}k.viewport.set([0,0,_.width,_.height]),_.resetStencilClippingMasks()},raster:function(_,f,y,w,k,R){if(_.renderPass!=="translucent")return;const M=y.paint.get("raster-opacity");if(M===0)return;const z=_.transform.projection.name==="globe",V=y.paint.get("raster-elevation"),H=y.paint.get("raster-elevation-reference")==="ground",Y=V>0,te=_.terrain&&_.terrain.exaggeration()>0&&Y&&H,ne=Y&&z,le=!z&&te;if(_.renderElevatedRasterBackface&&!ne)return;const me=_.context,fe=me.gl,Se=f.getSource(),Me=function(Lt,Mt,or,fr,Cr){const qr=or.paint.get("raster-color"),qt=Mt.type==="raster-array",Ut=[],gr=or.paint.get("raster-resampling"),Pr=or.paint.get("raster-color-mix");let ur=or.paint.get("raster-color-range");const Xt=[Pr[0],Pr[1],Pr[2],0],mr=Pr[3];let tn=gr==="nearest"?Cr.NEAREST:Cr.LINEAR;if(qt&&(Ut.push("RASTER_ARRAY"),qr||Ut.push("RASTER_COLOR"),gr==="linear"&&Ut.push("RASTER_ARRAY_LINEAR"),tn=Cr.NEAREST,qr&&or.paint.get("raster-color-scale")==="log"&&Ut.push("RASTER_COLOR_SCALE_LOG"),!ur&&Mt.rasterLayers)){const kr=Mt.rasterLayers.find(({id:vn})=>vn===or.sourceLayer);kr&&kr.fields&&kr.fields.range&&(ur=kr.fields.range)}if(ur=ur||[0,1],qr){Ut.push("RASTER_COLOR"),fr.activeTexture.set(Cr.TEXTURE2),or.updateColorRamp(ur);let kr=or.colorRampTexture;kr||(kr=or.colorRampTexture=new l.T(fr,or.colorRamp,Cr.RGBA8)),kr.bind(tn,Cr.CLAMP_TO_EDGE)}return Lt.terrain&&Lt.terrain.renderingToTexture&&Lt.isEmissiveMrtActive()&&(Ut.push("USE_MRT1"),Lt.emissiveMode==="mrt-full-rgba"&&Ut.push("USE_MRT1_RGBA")),{mix:Xt,range:ur,offset:mr,defines:Ut,resampling:tn}}(_,Se,y,me,fe);if(Se instanceof md&&!w.length&&!z)return;const qe=y.paint.get("raster-emissive-strength"),Ne=_.colorModeForDrapableLayerRenderPass(qe),We=_.terrain&&_.terrain.renderingToTexture,ct=!_.options.moving,it=y.paint.get("raster-resampling")==="nearest"?fe.NEAREST:fe.LINEAR;if(Se instanceof md&&!w.length&&(Se.onNorthPole||Se.onSouthPole)){const Lt=Y?_.stencilModeFor3D():l.a4.disabled;return void Hs(V,!!Se.onNorthPole,null,_,f,y,qe,Me,l.a5.disabled,Lt)}if(!w.length||y.paint.get("raster-mask")&&!cm.resolveRasterMask)return;const pt=cm.resolveRasterMask?cm.resolveRasterMask(_,y):null;if(pt==="unavailable")return;let dt=!1;const[mt,xt]=Se instanceof md||We?[{},w]:_.stencilConfigForOverlap(w,pt?l.cc:void 0),bt=xt.at(-1).overscaledZ;ne&&Me.defines.push("PROJECTION_GLOBE_VIEW"),Y&&Me.defines.push("RENDER_CUTOFF","ELEVATED"),te&&Me.defines.push("ELEVATION_REFERENCE_GROUND");const Ft=(Lt,Mt,or)=>{for(const fr of Lt){const Cr=fr.toUnwrapped(),qr=f.getTile(fr);if(We&&(!qr||!qr.hasData()))continue;me.activeTexture.set(fe.TEXTURE0);const qt=A1(qr,Se,y,Me);if(!qt||!qt.texture)continue;const{texture:Ut,mix:gr,offset:Pr,tileSize:ur,buffer:Xt}=qt;let mr,tn;We?(mr=l.a3.disabled,tn=fr.projMatrix):Y?(mr=new l.a3(fe.LEQUAL,l.a3.ReadWrite,_.depthRangeFor3D),tn=z?_.transform.expandedFarZProjMatrix:_.transform.calculateProjMatrix(Cr,ct)):(mr=_.depthModeForSublayer(fr.overscaledZ-bt,M===1?l.a3.ReadWrite:l.a3.ReadOnly,fe.LESS),tn=_.transform.calculateProjMatrix(Cr,ct));let kr=_.terrain&&We?_.terrain.stencilModeForRTTOverlap(fr):mt[fr.overscaledZ];dt&&(kr=cm.stencilModeWithRasterMask(_,kr));const vn=R?0:y.paint.get("raster-fade-duration");qr.registerFadeDuration(vn);const Xr=f.findLoadedParent(fr,0),ei=ys(qr,Xr,f,_.transform,vn);let Rn,Ni;!ei.isFading&&qr.refreshedUponExpiration&&(qr.refreshedUponExpiration=!1),_.terrain&&_.terrain.prepareDrawTile(),me.activeTexture.set(fe.TEXTURE0),Ut.bind(it,fe.CLAMP_TO_EDGE),me.activeTexture.set(fe.TEXTURE1),Xr?(Xr.texture&&Xr.texture.bind(it,fe.CLAMP_TO_EDGE),Rn=Math.pow(2,Xr.tileID.overscaledZ-qr.tileID.overscaledZ),Ni=[qr.tileID.canonical.x*Rn%1,qr.tileID.canonical.y*Rn%1]):Ut.bind(it,fe.CLAMP_TO_EDGE),"useMipmap"in Ut&&me.extTextureFilterAnisotropic&&_.transform.pitch>20&&fe.texParameterf(fe.TEXTURE_2D,me.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,me.extTextureFilterAnisotropicMax);const zn=_.transform;let Qi;const xn=Y?P2(zn):[0,0,0,0];let Sn,Dn,Ks,ya,Ti,Ba=0;if(ne&&Se instanceof md&&Se.coordinates.length>3)Sn=Float32Array.from(l.bf(l.bg(new l.c1(0,0,0)))),Dn=Float32Array.from(zn.globeMatrix),Ks=Float32Array.from(l.bh(zn)),ya=[l.ad(zn.center.lng),l.ae(zn.center.lat)],Qi=Se.elevatedGlobePerspectiveTransform,Ti=Se.elevatedGlobeGridMatrix||new Float32Array(9);else if(ne){const yi=l.bd(fr.canonical);Ba=l.be(yi.getCenter().lat),Sn=Float32Array.from(l.bf(l.bg(fr.canonical))),Dn=Float32Array.from(zn.globeMatrix),Ks=Float32Array.from(l.bh(zn)),ya=[l.ad(zn.center.lng),l.ae(zn.center.lat)],Qi=[0,0],Ti=Float32Array.from(l.bi(fr.canonical,yi,Ba,zn.worldSize/zn._pixelsPerMercatorPixel))}else Qi=Se instanceof md?Se.perspectiveTransform:[0,0],Sn=new Float32Array(16),Dn=new Float32Array(9),Ks=new Float32Array(16),ya=[0,0],Ti=new Float32Array(9);const bs=PN(_,tn,Sn,Dn,Ks,Ti,Ni||[0,0],l._(_.transform.zoom),ya,xn,Rn||1,ei,y,Qi,V,2,gr,Pr,Me.range,ur,Xt,qe),Ri=_.isTileAffectedByFog(fr),gi=_.getOrCreateProgram("raster",{defines:Me.defines,overrideFog:Ri});if(_.uploadCommonUniforms(me,gi,Cr),Se instanceof md){const yi=dt?cm.stencilModeWithRasterMask(_,l.a4.disabled):l.a4.disabled,Dr=Se.elevatedGlobeVertexBuffer,Pn=Se.elevatedGlobeIndexBuffer;if(We||!z)Se.boundsBuffer&&Se.boundsSegments&&gi.draw(_,fe.TRIANGLES,mr,yi,Ne,l.a5.disabled,bs,y.id,Se.boundsBuffer,_.quadTriangleIndexBuffer,Se.boundsSegments);else if(Dr&&Pn){const ti=zn.zoom<=l.ek?Se.elevatedGlobeSegments:Se.getSegmentsForLongitude(zn.center.lng);ti&&gi.draw(_,fe.TRIANGLES,mr,yi,Ne,Mt,bs,y.id,Dr,Pn,ti)}}else if(ne){mr=new l.a3(fe.LEQUAL,l.a3.ReadOnly,_.depthRangeFor3D);const yi=_.globeSharedBuffers;if(yi){te&&(_.terrain.setupElevationDraw(qr,gi),_.uploadCommonUniforms(me,gi,qr.tileID.toUnwrapped()));const[Dr,Pn,ti]=yi.getGridBuffers(Ba,!1),Ya=gi.getAttributeLocation(fe,"a_texture_pos");Ya!==-1&&fe.vertexAttribI4ui(Ya,0,0,0,0),gi.draw(_,fe.TRIANGLES,mr,or||kr,_.colorModeForRenderPass(),Mt,bs,y.id,Dr,Pn,ti)}}else if(le)mr=new l.a3(fe.LEQUAL,l.a3.ReadOnly,_.depthRangeFor3D),_.terrain.setupElevationDraw(qr,gi),_.uploadCommonUniforms(me,gi,qr.tileID.toUnwrapped()),zn.pitch>20&&gi.draw(_,fe.TRIANGLES,mr,l.a4.disabled,l.a7.disabled,l.a5.frontCCW,bs,y.id,_.terrain.gridBuffer,_.terrain.gridIndexBuffer,_.terrain.gridSegments),gi.draw(_,fe.TRIANGLES,mr,kr,Ne,l.a5.backCCW,bs,y.id,_.terrain.gridBuffer,_.terrain.gridIndexBuffer,_.terrain.gridSegments);else{const{tileBoundsBuffer:yi,tileBoundsIndexBuffer:Dr,tileBoundsSegments:Pn}=_.getTileBoundsBuffers(qr);gi.draw(_,fe.TRIANGLES,mr,kr,Ne,l.a5.disabled,bs,y.id,yi,Dr,Pn)}}if(!(Se instanceof md)&&ne)for(const fr of Lt){const Cr=fr.canonical.y===(1<pt.tileID)),le&&(H.activeTexture.set(Y.TEXTURE0),_.imageManager.bind(_.context,y.scope));const it=[];if(_.terrain&&_.terrain.renderingToTexture&&_.isEmissiveMrtActive()&&(it.push("USE_MRT1"),_.emissiveMode==="mrt-full-rgba"&&it.push("USE_MRT1_RGBA")),V){const pt=_.getOrCreateProgram(Ne,{overrideFog:!1,overrideRtt:!0,defines:it}),dt=N2,mt=new l.bZ(0,0,0,0,0),xt=le?p0(dt,z,M,_,le,y.scope,me,V,{tileID:mt,tileSize:ne}):Jw(dt,z,M,k.toPremultipliedRenderColor(R?null:y.lut));return void pt.draw(_,Y.TRIANGLES,Me,Se,qe,l.a5.disabled,xt,y.id,_.viewportBuffer,_.quadTriangleIndexBuffer,_.viewportSegments)}for(const pt of ct){const dt=_.isTileAffectedByFog(pt),mt=_.getOrCreateProgram(Ne,{overrideFog:dt,defines:it}),xt=pt.toUnwrapped(),bt=w?pt.projMatrix:_.transform.calculateProjMatrix(xt);_.prepareDrawTile();const Ft=f?f.getTile(pt):We?We[pt.key]:new yf(pt,ne,te.zoom,_),Lt=le?p0(bt,z,M,_,le,y.scope,me,V,{tileID:pt,tileSize:ne}):Jw(bt,z,M,k.toPremultipliedRenderColor(R?null:y.lut));_.uploadCommonUniforms(H,mt,xt);const{tileBoundsBuffer:Mt,tileBoundsIndexBuffer:or,tileBoundsSegments:fr}=_.getTileBoundsBuffers(Ft);mt.draw(_,Y.TRIANGLES,Me,Se,qe,l.a5.disabled,Lt,y.id,Mt,or,fr)}},sky:function(_,f,y){const w=_._atmosphere?l._(_.transform.zoom):1,k=y.paint.get("sky-opacity")*w;if(k===0)return;const R=_.context,M=y.paint.get("sky-type"),z=new l.a3(R.gl.LEQUAL,l.a3.ReadOnly,[0,1]),V=_.frameCounter/1e3%1;M==="atmosphere"?_.renderPass==="offscreen"?y.needsSkyboxCapture(_)&&(function(H,Y){const te=H.context,ne=te.gl;let le=Y.skyboxFbo;if(!le){le=Y.skyboxFbo=te.createFramebuffer(32,32,1,null),Y.skyboxGeometry=new sr(te),Y.skyboxTexture=te.gl.createTexture(),ne.bindTexture(ne.TEXTURE_CUBE_MAP,Y.skyboxTexture),ne.texParameteri(ne.TEXTURE_CUBE_MAP,ne.TEXTURE_WRAP_S,ne.CLAMP_TO_EDGE),ne.texParameteri(ne.TEXTURE_CUBE_MAP,ne.TEXTURE_WRAP_T,ne.CLAMP_TO_EDGE),ne.texParameteri(ne.TEXTURE_CUBE_MAP,ne.TEXTURE_MIN_FILTER,ne.LINEAR),ne.texParameteri(ne.TEXTURE_CUBE_MAP,ne.TEXTURE_MAG_FILTER,ne.LINEAR);for(let Me=0;Me<6;++Me)ne.texImage2D(ne.TEXTURE_CUBE_MAP_POSITIVE_X+Me,0,ne.RGBA,32,32,0,ne.RGBA,ne.UNSIGNED_BYTE,null)}te.bindFramebuffer.set(le.framebuffer),te.viewport.set([0,0,32,32]);const me=Y.getCenter(H,!0),fe=H.getOrCreateProgram("skyboxCapture"),Se=new Float64Array(16);l.ep(Se,.5*-Math.PI),Zd(H,Y,fe,Se,me,0),l.ep(Se,.5*Math.PI),Zd(H,Y,fe,Se,me,1),l.eq(Se,.5*-Math.PI),Zd(H,Y,fe,Se,me,2),l.eq(Se,.5*Math.PI),Zd(H,Y,fe,Se,me,3),l.dk(Se),Zd(H,Y,fe,Se,me,4),l.ep(Se,Math.PI),Zd(H,Y,fe,Se,me,5),te.viewport.set([0,0,H.width,H.height])}(_,y),y.markSkyboxValid(_)):_.renderPass==="sky"&&function(H,Y,te,ne,le){const me=H.context,fe=me.gl,Se=H.transform,Me=H.getOrCreateProgram("skybox");me.activeTexture.set(fe.TEXTURE0),fe.bindTexture(fe.TEXTURE_CUBE_MAP,Y.skyboxTexture);const qe=((Ne,We,ct,it,pt)=>({u_matrix:Ne,u_sun_direction:We,u_cubemap:0,u_opacity:it,u_temporal_offset:pt}))(Se.skyboxMatrix,Y.getCenter(H,!1),0,ne,le);H.uploadCommonUniforms(me,Me),Me.draw(H,fe.TRIANGLES,te,l.a4.disabled,H.colorModeForRenderPass(),l.a5.backCW,qe,"skybox",Y.skyboxGeometry.vertexBuffer,Y.skyboxGeometry.indexBuffer,Y.skyboxGeometry.segment)}(_,y,z,k,V):M==="gradient"&&_.renderPass==="sky"&&function(H,Y,te,ne,le){const me=H.context,fe=me.gl,Se=H.transform,Me=H.getOrCreateProgram("skyboxGradient");Y.skyboxGeometry||(Y.skyboxGeometry=new sr(me)),me.activeTexture.set(fe.TEXTURE0);let qe=Y.colorRampTexture;qe||(qe=Y.colorRampTexture=new l.T(me,Y.colorRamp,fe.RGBA8)),qe.bind(fe.LINEAR,fe.CLAMP_TO_EDGE);const Ne=((We,ct,it,pt,dt)=>({u_matrix:We,u_color_ramp:0,u_center_direction:ct,u_radius:l.aF(it),u_opacity:pt,u_temporal_offset:dt}))(Se.skyboxMatrix,Y.getCenter(H,!1),Y.paint.get("sky-gradient-radius"),ne,le);H.uploadCommonUniforms(me,Me),Me.draw(H,fe.TRIANGLES,te,l.a4.disabled,H.colorModeForRenderPass(),l.a5.backCW,Ne,"skyboxGradient",Y.skyboxGeometry.vertexBuffer,Y.skyboxGeometry.indexBuffer,Y.skyboxGeometry.segment)}(_,y,z,k,V)},custom:function(_,f,y,w){const k=_.context,R=y.implementation;if(_.transform.projection.unsupportedLayers&&_.transform.projection.unsupportedLayers.includes("custom")&&(!_.terrain||!_.terrain.renderingToTexture&&_.renderPass!=="offscreen"||!y.isDraped(f)))return void l.w("Custom layers are not yet supported with this projection. Use mercator or globe to enable usage of custom layers.");const M=function(z){if(z._customRenderArgs&&z._customRenderArgsFrameCounter===z.frameCounter)return z._customRenderArgs;const V=z.transform;let H=null,Y=null;if(V.projection.name==="globe"){const ne=l.em(V),le=l.en(ne);if(le>0){const fe=l.dY([],ne,1/le);H=[fe[0],fe[1],fe[2],-l.cT*l.cT/le]}const me=V.projection.globeCenterToScreenPoint(V);me&&(Y=[me.x,me.y])}const te={projectionMatrix:new Float64Array(V.getCameraToClipMatrix()),viewMatrix:new Float64Array(V.getWorldToCameraMatrix()),globeClippingPlane:H,globeCenterInScreenPixels:Y};return z._customRenderArgs=te,z._customRenderArgsFrameCounter=z.frameCounter,te}(_);if(_.renderPass==="offscreen"){const z=R.prerender;if(z){if(_.setCustomLayerDefaults(),k.setColorMode(_.colorModeForRenderPass()),_.transform.projection.name==="globe"){const V=_.transform.pointMerc;z.call(R,k.gl,_.transform.customLayerMatrix(),_.transform.getProjection(),_.transform.globeToMercatorMatrix(),l._(_.transform.zoom),[V.x,V.y],_.transform.pixelsPerMeterRatio,M)}else z.call(R,k.gl,_.transform.customLayerMatrix(),void 0,void 0,void 0,void 0,void 0,M);k.setDirty(),_.setBaseState()}}else if(_.renderPass==="translucent"){if(_.terrain&&_.terrain.renderingToTexture){const V=R.renderToTile;if(V){const H=w[0].canonical,Y={x:H.x+w[0].wrap*(R.wrapTileId?0:1<f.getTileByID(z));for(const z of M)z.updateNeeded(_.id,R)&&w.prepareTile(z,k,_.id,R)}};async function lR(_){if(await Ln(),Object.assign(Fx,{model:on.drawModels}),Object.assign(hm,{model:on.prepare}),_&&!_._destroyed&&!_._shadowRenderer){const f=on.ShadowRenderer;f&&(_._shadowRenderer=new f(_))}}class rz{constructor(f,y,w,k,R,M){this._lightsUniforms=null,this._fogUniforms=null,this._forceFullRgbaEmissive=!1,this.context=new E2(f,y),this._forceFullRgbaEmissive=M==="exact",this.transform=w,this.cache=new Map,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this.frcCoverageSnapshot=null,this.elevationCoverageSnapshot=null,this.elevationProvidersReady=void 0,this.frcCoverageFadeRange=null,this.frcCoverageSourceLayers=[],this.frcCoverageRenderer=kn.FrcCoverageRenderer?new kn.FrcCoverageRenderer:null,this._debugParams={averageFPS:0,fpsHistory:[],fpsWindow:30,continousRedraw:!1,enabledLayers:{},buildingsShowNormals:!1,buildingsDrawGroundAO:!0,buildingsDrawShadowPass:!0,buildingsDrawTranslucentPass:!0,showTerrainProxyTiles:!1,terrainSortTilesHiZFirst:!0,terrainDisableRenderCache:!1,forceEnablePrecipitation:!1,overrideSnowParams:!1,snowParamsOverride:null,snowRevealParamsOverride:null,snowVignetteParamsOverride:null,overrideRainParams:!1,rainParamsOverride:null,rainRevealParamsOverride:null,rainVignetteParamsOverride:null,overrideStarsParams:!1,starsParamsOverride:null,show3DModelFootprints:!1,showElevationIdDebug:!1,lodSwitchDistance:-1,lodSwitchFadeDuration:.5},this.occlusionParams=new oR,this.setup(),this.numSublayers=il.maxUnderzooming+il.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this.frameTimeDelta=0,this.lastPaintStartTimeStamp=0,this._shadowCullCache=null,this._backgroundTiles={},this.depthPrepassPhase=!1,this._grouped3DDepthPrepassStart=-1,this._grouped3DDepthPrepassEnd=-1,this._grouped3DStencil=null,this.conflationActive=!1,this.replacementSource=new l.eB,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities=new Map,this._wireframeDebugCache=new L2,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const z=new l.b({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new l.T(this.context,z,f.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=k,this.maxFrontCutoffRawStart=0,this.worldview=R,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(f,y){const w=!!f&&!!f.terrain&&this.transform.projection.supportsTerrain;var k;(w||this._terrain&&this._terrain.enabled)&&(this._terrain||(this._terrain=jN(this,f),this._terrain)?(this.transform.elevation=w?this._terrain:null,this._terrain.update(f,this.transform,y),this.transform.elevation&&!this._terrain.enabled&&(this.transform.elevation=null)):this._terrainRendererRetryPending||(this._terrainRendererRetryPending=!0,k=()=>{this._terrainRendererRetryPending=!1,this.style&&this.style.map&&this.style.map._update(!1)},lm?k():m0.push(k)))}_updateFog(f){const y=f.fog;if(!y||this.transform.projection.name==="globe"||y.getOpacity(this.transform.pitch)<1||y.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[w,k]=y.getRangeForProjection();if(w>k)return void(this.transform.fogCullDistSq=null);const R=w+.78*(k-w);this.transform.fogCullDistSq=R*R}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(f){f&&!this._terrain&&(this._terrain=jN(this,this.style),this._terrain||console.warn("forceTerrainMode: Lite module not loaded yet, terrain renderer unavailable")),this._forceTerrainMode=f}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(f,y){if(this.width=f*l.e.devicePixelRatio,this.height=y*l.e.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const w of this.style.order)this.style._mergedLayers[w].resize()}setup(){const f=this.context,y=new l.bN;y.emplaceBack(0,0),y.emplaceBack(l.ac,0),y.emplaceBack(0,l.ac),y.emplaceBack(l.ac,l.ac),this.tileExtentBuffer=f.createVertexBuffer(y,l.bP.members),this.tileExtentSegments=l.aj.simpleSegment(0,0,4,2);const w=new l.bN;w.emplaceBack(0,0),w.emplaceBack(l.ac,0),w.emplaceBack(0,l.ac),w.emplaceBack(l.ac,l.ac),this.debugBuffer=f.createVertexBuffer(w,l.bP.members),this.debugSegments=l.aj.simpleSegment(0,0,4,5);const k=new l.bN;k.emplaceBack(-1,-1),k.emplaceBack(1,-1),k.emplaceBack(-1,1),k.emplaceBack(1,1),this.viewportBuffer=f.createVertexBuffer(k,l.bP.members),this.viewportSegments=l.aj.simpleSegment(0,0,4,2);const R=new l.bD;R.emplaceBack(0,0,0,0),R.emplaceBack(l.ac,0,l.ac,0),R.emplaceBack(0,l.ac,0,l.ac),R.emplaceBack(l.ac,l.ac,l.ac,l.ac),this.mercatorBoundsBuffer=f.createVertexBuffer(R,Vn.members),this.mercatorBoundsSegments=l.aj.simpleSegment(0,0,4,2);const M=new l.ak;M.emplaceBack(0,1,2),M.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=f.createIndexBuffer(M);const z=new l.bO;for(const H of[0,1,3,2,0])z.emplaceBack(H);this.debugIndexBuffer=f.createIndexBuffer(z),this.emptyTexture=new l.T(f,new l.b({width:1,height:1},Uint8Array.of(0,0,0,0)),f.gl.RGBA8),this.identityMat=l.a2();const V=this.context.gl;this.stencilClearMode=new l.a4({func:V.ALWAYS,mask:0},0,255,V.ZERO,V.ZERO,V.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(f){return f._makeTileBoundsBuffers(this.context,this.transform.projection),f._tileBoundsBuffer?{tileBoundsBuffer:f._tileBoundsBuffer,tileBoundsIndexBuffer:f._tileBoundsIndexBuffer,tileBoundsSegments:f._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const f=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs=new Map,this._grouped3DStencil=null,this.getOrCreateProgram("clippingMask").draw(this,f.TRIANGLES,l.a3.disabled,this.stencilClearMode,l.a7.disabled,l.a5.disabled,Io(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs=new Map)}_renderTileClippingMasks(f,y,w){if(!y||this.currentStencilSource===y.id||!f.isTileClipped()||!w||w.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let z=!1;for(const V of w)if(!this._tileClippingMaskIDs.has(V.key)){z=!0;break}if(!z)return}this.currentStencilSource=y.id;const k=this.context,R=k.gl;this.nextStencilID+w.length-1>253&&this.clearStencil(),k.setColorMode(l.a7.disabled),k.setDepthMode(l.a3.disabled);const M=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs=new Map;for(const z of w){const V=y.getTile(z),H=this.nextStencilID++;this._tileClippingMaskIDs.set(z.key,H);const{tileBoundsBuffer:Y,tileBoundsIndexBuffer:te,tileBoundsSegments:ne}=this.getTileBoundsBuffers(V);M.draw(this,R.TRIANGLES,l.a3.disabled,new l.a4({func:R.ALWAYS,mask:0},H,255,R.KEEP,R.KEEP,R.REPLACE),l.a7.disabled,l.a5.disabled,Io(z.projMatrix),"$clipping",Y,te,ne)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID>253&&this.clearStencil();const f=this.nextStencilID++,y=this.context.gl;return new l.a4({func:y.NOTEQUAL,mask:255},f,255,y.KEEP,y.KEEP,y.REPLACE)}_beginGrouped3DDepthPrepass(f,y){const w=this.currentLayer;if(!f[w].hasBlended3DDepthPrepass())return;const k=[];let R=w;for(let M=w;M=this._grouped3DDepthPrepassStart&&fV.overscaledZ-z.overscaledZ),R=k.at(-1).overscaledZ,M=k[0].overscaledZ-R+1;if(M>1){this.currentStencilSource=void 0,this.nextStencilID+M>y&&this.clearStencil();const z={};for(let V=0;V{const Xr=qt.transform,ei=Ut.properties.get("color-use-theme")==="none",Rn=Ut.properties.get("color").toNonPremultipliedRenderColor(ei?null:qt.style.getLut(Ut.scope)).toArray01();Rn[3]=gr;const Ni=qt.frameCounter/1e3%1,[zn,Qi]=Ut.properties.get("vertical-range");return{u_fog_matrix:qt.identityMat,u_fog_range:Ut.getRangeForProjection(),u_fog_color:Rn,u_fog_horizon_blend:Ut.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(zn,Qi),Qi],u_fog_temporal_offset:Ni,u_frustum_tl:Pr,u_frustum_tr:ur,u_frustum_br:Xt,u_frustum_bl:mr,u_globe_pos:tn,u_globe_radius:kr,u_viewport:vn,u_globe_transition:l._(Xr.zoom),u_is_globe:+(Xr.projection.name==="globe")}})(this,f.fog,f.fog.getOpacity(R.pitch),R.frustumCorners.TL,R.frustumCorners.TR,R.frustumCorners.BR,R.frustumCorners.BL,R.globeCenterInViewSpace,R.globeRadius,[this.width,this.height]):null,this.frcCoverageSnapshot&&!this.frcCoverageSnapshot.empty()&&(!this.frcCoverageRenderer&&kn.FrcCoverageRenderer&&(this.frcCoverageRenderer=new kn.FrcCoverageRenderer),this.frcCoverageRenderer&&this.frcCoverageRenderer.update(this.context,this.frcCoverageSnapshot.tiles));const M=this.style._mergedLayers,z=!(!this.terrain||!this.terrain.enabled),V=()=>this.style._getOrder(z);let H=V(),Y=!1,te=!1,ne=null,le=0,me=!1;for(const qt of H){const Ut=M[qt];Ut.visibility!=="none"&&(Ut.type==="circle"?Y=!0:Ut.type==="building"?(ne=Ut,++le):Ut.type==="symbol"&&(Ut.hasOcclusionOpacityProperties?te=!0:Y=!0))}this.updateEmissiveMode();let fe=H.map(qt=>M[qt]);const Se=this.style._mergedSourceCaches;this.imageManager=f.imageManager,this.modelManager=f.modelManager,this.now=l.e.now(),this.symbolFadeChange=f.placement?f.placement.symbolFadeChange(this.now):1,this.imageManager.beginFrame();for(const qt in Se){const Ut=Se[qt];Ut.used&&(Ut.prepare(this.context),Ut.getSource().usedInConflation&&++le)}let Me=!1;for(const qt of fe)qt.isHidden(this.transform.zoom)||(qt.type==="clip"&&(Me=!0),this.prepareLayer(qt));const qe={},Ne={},We={},ct={},it={};for(const qt in Se){const Ut=Se[qt];qe[qt]=Ut.getVisibleCoordinates(),Ne[qt]=qe[qt].slice().reverse(),We[qt]=Ut.getVisibleCoordinates(!0).reverse(),ct[qt]=Ut.getShadowCasterCoordinates(),it[qt]=Ut.sortCoordinatesByDistance(qe[qt])}const pt=qt=>{const Ut=this.style.getLayerSourceCache(qt);return Ut&&Ut.used?Ut.getSource():null};if(le||Me||this._clippingActiveLastFrame){const qt=[],Ut=[];let gr=0;for(const Pr of fe)this.isSourceForClippingOrConflation(Pr,pt(Pr))&&(qt.push(Pr),Ut.push(gr)),gr++;if(qt&&(Me||qt.length>1)||this._clippingActiveLastFrame){Me=!1;const Pr=[];for(let ur=0;ur0){const Pr=pt(Ut);Pr&&(this.minCutoffZoom=Math.max(Pr.minzoom,this.minCutoffZoom)),Ut.minzoom&&(this.minCutoffZoom=Math.max(Ut.minzoom,this.minCutoffZoom))}Ut.is3D(z)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=qt),this._lastOcclusionLayer=qt)}const dt=this.style&&this.style.fog;dt?(this._fogVisible=dt.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=dt.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities.clear(),this.terrain&&(this.terrain.updateTileBinding(We),this.opaquePassCutoff=0,H=V(),fe=H.map(qt=>M[qt])),this.style.enable3dLights()&&!this._shadowRenderer&&lR(this);const mt=this._shadowRenderer;if(mt){mt.updateShadowParameters(this.transform,this.style.directionalLight,ct);for(const qt in Se)for(const Ut of qe[qt]){let gr={min:0,max:0};this.terrain&&(gr=this.terrain.getMinMaxForTile(Ut)||gr),mt.addShadowReceiver(Ut.toUnwrapped(),gr.min,gr.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new l.eD(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new k1),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);let xt=!(!this.style||!this.style.snow),bt=!(!this.style||!this.style.rain);if(xt&&!this._snow&&kn.Snow&&(this._snow=new kn.Snow),!xt&&this._snow&&(this._snow.destroy(),delete this._snow),bt&&!this._rain&&kn.Rain&&(this._rain=new kn.Rain),!bt&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),ne&&(!this.buildingTileBorderManager&&kn.BuildingTileBorderManager&&(this.buildingTileBorderManager=new kn.BuildingTileBorderManager),this.buildingTileBorderManager)){const qt=this.style.getLayerSourceCache(ne);this.buildingTileBorderManager.updateBorders(qt,ne)}if(!l.eE(this.context.gl))return;this.renderPass="offscreen";for(const qt of fe){const Ut=f.getLayerSourceCache(qt);if(!qt.hasOffscreenPass()||qt.isHidden(this.transform.zoom))continue;const gr=Ut?Ne[Ut.id]:void 0;(qt.type==="custom"||qt.type==="raster"||qt.type==="raster-particle"||qt.isSky()||gr&&gr.length)&&this.renderLayer(this,Ut,qt,gr)}this.depthRangeFor3D=[0,1-(fe.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,ct)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const Ft=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),Lt=(()=>{if(y.showOverdrawInspector)return l.C.black;const qt=this.style.fog;if(qt&&this.transform.projection.supportsFog){const Ut=this.style.getLut(qt.scope);if(!Ft){const gr=qt.properties.get("color-use-theme")==="none",Pr=qt.properties.get("color").toNonPremultipliedRenderColor(gr?null:Ut).toArray01();return new l.C(...Pr)}if(Ft){const gr=qt.properties.get("space-color-use-theme")==="none",Pr=qt.properties.get("space-color").toNonPremultipliedRenderColor(gr?null:Ut).toArray01();return new l.C(...Pr)}}return l.C.transparent})();if(this.context.clear({color:Lt,depth:1}),this.clearStencil(),this._showOverdrawInspector=y.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ft&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=H.length-1;this.currentLayer>=0;this.currentLayer--){const qt=fe[this.currentLayer],Ut=f.getLayerSourceCache(qt);if(qt.isSky())continue;const gr=Ut?(qt.is3D(z)?it:Ne)[Ut.id]:void 0;this._renderTileClippingMasks(qt,Ut,gr),this.renderLayer(this,Ut,qt,gr)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ft&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||l._(this.transform.zoom)>0)&&(this.transform.projection.name==="globe"||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer{for(this.currentLayer=0;this.currentLayer=this._lastOcclusionLayer&&this.layersWithOcclusionOpacity.length>0){const gr=this.currentLayer;this.depthOcclusion=!0;for(const Pr of this.layersWithOcclusionOpacity){this.currentLayer=Pr;const ur=fe[this.currentLayer],Xt=f.getLayerSourceCache(ur),mr=Xt?Ne[Xt.id]:void 0;this.terrain||this._renderTileClippingMasks(ur,Xt,Xt?qe[Xt.id]:void 0),this.renderLayer(this,Xt,ur,mr)}this.depthOcclusion=!1,this.currentLayer=gr,this.renderPass="translucent",this.layersWithOcclusionOpacity=[]}++this.currentLayer}}if(this.terrain&&this.terrain.postRender(),this._snow&&this._snow.draw(this),this._rain&&this._rain.draw(this),this.options.showTileBoundaries||this.options.showQueryGeometry||this.options.showTileAABBs){let qt=null;fe.forEach(Ut=>{const gr=f.getLayerSourceCache(Ut);gr&&!Ut.isHidden(this.transform.zoom)&&gr.getVisibleCoordinates().length&&(!qt||qt.getSource().maxzoom0?y.pop():null}terrainRenderModeElevated(){return this.style&&this.style.hasTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(f,y,w,k,R){const M=w===void 0?!!this._terrain&&this._terrain.renderingToTexture:w,z=k===void 0?this.terrainRenderModeElevated():k,V=R===void 0?this.transform.projection.name==="globe":R,H=[];return this.style&&this.style.enable3dLights()&&(f==="globeRaster"||f==="terrainRaster"?(H.push("LIGHTING_3D_MODE"),H.push("LIGHTING_3D_ALPHA_EMISSIVENESS"),this.emissiveMode==="mrt-full-rgba"&&H.push("USE_MRT1_RGBA")):M||H.push("LIGHTING_3D_MODE")),z&&(H.push("TERRAIN"),this.linearFloatFilteringSupported()&&H.push("TERRAIN_DEM_FLOAT_FORMAT")),V&&H.push("GLOBE"),!this._fogVisible||M||y!==void 0&&!y||H.push("FOG"),M&&H.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&H.push("OVERDRAW_INSPECTOR"),H}getOrCreateProgram(f,y){const{defines:w,config:k,overrideFog:R,overrideRtt:M,overrideTerrain:z,overrideGlobe:V,precompiled:H}=y||{},Y=this.currentGlobalDefines(f,R,M,z,V),te=this.getShaderSource(f),ne=w2.cacheKey(te,f,Y,w,k);let le=this.cache.get(ne);if(!le){const me=kn.programUniforms,fe=on.programUniforms,Se=a2[f]||me&&me[f]||fe&&fe[f],Me=w?Y.concat(w):Y;le=new w2(this.context,f,te,k,Se,Me,H),this.cache.set(ne,le)}return le}getShaderSource(f){const y=kn.shaders,w=on.shaders,k=ZB.shaders;return l.eF[f]||y&&y[f]||w&&w[f]||k&&k[f]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.frontFace.setDefault(),this.context.cullFaceSide.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const f=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(f.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new l.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA8))}destroy(){this._terrain&&this._terrain.destroy(),this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0),this.globeSharedBuffers&&this.globeSharedBuffers.destroy(),this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this._wireframeDebugCache.destroy(),this.depthFBO&&(this.depthFBO.destroy(),this.depthFBO=void 0,this.depthTexture=void 0),this.emptyDepthTexture&&this.emptyDepthTexture.destroy(),this._destroyed=!0}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(f,y,w){const k=w&&this._lightsUniforms?w1(this.style.directionalLight,this.style.ambientLight,this.style,w):this._lightsUniforms;k&&y.setLightsUniformValues(f,k)}uploadCommonUniforms(f,y,w,k,R,M){if(this.uploadCommonLightUniforms(f,y,M),this.terrain&&this.terrain.renderingToTexture)return;const z=this._fogUniforms;z&&(z.u_fog_matrix=w?this.transform.calculateFogTileMatrix(w):k||this.identityMat,y.setFogUniformValues(f,z)),R&&y.setCutoffUniformValues(f,R.uniformValues)}setTileLoadedFlag(f){this.tileLoaded=f}saveCanvasCopy(){const f=this.canvasCopy();f&&(this.frameCopies.push(f),this.tileLoaded=!1)}canvasCopy(){const f=this.context.gl,y=f.createTexture();return f.bindTexture(f.TEXTURE_2D,y),f.copyTexImage2D(f.TEXTURE_2D,0,f.RGBA,0,0,f.drawingBufferWidth,f.drawingBufferHeight,0),y}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const f=this.style&&this.style.fog;return!!f&&f.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const f=this._backgroundTiles,y=this._backgroundTiles={},w=this.transform.coveringTiles({tileSize:512});for(const k of w)y[k.key]=f[k.key]||new yf(k,512,this.transform.tileZoom,this,void 0,this.worldview);return y}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(f,y){return!(!f.is3D(!(!this.terrain||!this.terrain.enabled))||f.type!=="clip"&&f.type!=="building"&&(f.minzoom&&f.minzoom>this.transform.zoom||(this.style._clipLayerPresent||f.sourceLayer!=="building"&&f.sourceLayer!=="procedural_buildings")&&(!y||y.type!=="batched-model")))}isTileAffectedByFog(f){if(!this._fogVisible)return!1;if(this.transform.projection.name==="globe")return!0;let y=this._cachedTileFogOpacities.get(f.key);return y||(y=this.style.fog.getOpacityForTile(f),this._cachedTileFogOpacities.set(f.key,y)),y[0]>=l.aE||y[1]>=l.aE}setupDepthForOcclusion(f,y,w){const k=this.context,R=k.gl,M=!!w;var z;w||(w={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),k.activeTexture.set(R.TEXTURE3),f&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(R.NEAREST,R.CLAMP_TO_EDGE),w.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],w.u_depth_range_unpack=[2/((z=this.depthRangeFor3D)[1]-z[0]),-1-2*z[0]/(z[1]-z[0])],w.u_occluder_half_size=.5*this.occlusionParams.occluderSize,w.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(R.NEAREST,R.CLAMP_TO_EDGE),k.activeTexture.set(R.TEXTURE0),M||y.setTerrainUniformValues(k,w)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const f=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=this._forceFullRgbaEmissive?"mrt-full-rgba":f?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function D2(_,f){let y=!1,w=null;const k=()=>{w=null,y&&(_(),w=setTimeout(k,f),y=!1)};return()=>(y=!0,w||k(),w)}const I1=/(#.+)?$/;class M2{constructor(f){this._hashName=f&&encodeURIComponent(f),l.b4(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=D2(this._updateHashUnthrottled.bind(this),300)}addTo(f){return this._map=f,window.addEventListener("hashchange",this._onHashChange,!1),f.on("moveend",this._updateHash),this}remove(){return this._map?(this._map.off("moveend",this._updateHash),window.removeEventListener("hashchange",this._onHashChange,!1),clearTimeout(this._updateHash()),this._map=void 0,this):this}getHashString(){const f=this._map;if(!f)return"";const y=O2(f);if(this._hashName){const w=this._hashName;let k=!1;const R=location.hash.slice(1).split("&").map(M=>{const z=M.split("=")[0];return z===w?(k=!0,`${z}=${y}`):M}).filter(M=>M);return k||R.push(`${w}=${y}`),`#${R.join("&")}`}return`#${y}`}_getCurrentHash(){const f=location.hash.replace("#","");if(this._hashName){let y;return f.split("&").map(w=>w.split("=")).forEach(w=>{w[0]===this._hashName&&(y=w)}),(y&&y[1]||"").split("/")}return f.split("/")}_onHashChange(){const f=this._map;if(!f)return!1;const y=this._getCurrentHash();if(y.length>=3&&!y.some(w=>isNaN(Number(w)))){const w=f.dragRotate.isEnabled()&&f.touchZoomRotate.isEnabled()?+(y[3]||0):f.getBearing();return f.jumpTo({center:[+y[2],+y[1]],zoom:+y[0],bearing:w,pitch:+(y[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(I1,this.getHashString()))}}function O2(_,f){const y=_.getCenter(),w=Math.round(100*_.getZoom())/100,k=Math.ceil((w*Math.LN2+Math.log(512/360/.5))/Math.LN10),R=Math.pow(10,k),M=Math.round(y.lng*R)/R,z=Math.round(y.lat*R)/R,V=_.getBearing(),H=_.getPitch();let Y=f?`/${M}/${z}/${w}`:`${w}/${z}/${M}`;return(V||H)&&(Y+="/"+Math.round(10*V)/10),H&&(Y+=`/${Math.round(H)}`),Y}const P0={linearity:.3,easing:l.eH(0,0,.3,1)},j1={deceleration:2500,maxSpeed:1400,...P0},N0={deceleration:20,maxSpeed:1400,...P0},Bx={deceleration:1e3,maxSpeed:360,...P0},cR={deceleration:1e3,maxSpeed:90,...P0};class uR{constructor(f){this._map=f,this.clear()}clear(){this._inertiaBuffer=[]}record(f){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:l.e.now(),settings:f})}_drainInertiaBuffer(){const f=this._inertiaBuffer,y=l.e.now();for(;f.length>0&&y-f[0].time>160;)f.shift()}_onMoveEnd(f){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const y={zoom:0,bearing:0,pitch:0,pan:new l.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:R}of this._inertiaBuffer)y.zoom+=R.zoomDelta||0,y.bearing+=R.bearingDelta||0,y.pitch+=R.pitchDelta||0,R.panDelta&&y.pan._add(R.panDelta),R.around&&(y.around=R.around),R.pinchAround&&(y.pinchAround=R.pinchAround);const w=this._inertiaBuffer.at(-1).time-this._inertiaBuffer[0].time,k={};if(y.pan.mag()){const R=R0(y.pan.mag(),w,{...j1,...f||{}});k.offset=y.pan.mult(R.amount/y.pan.mag()),k.center=this._map.transform.center,C1(k,R)}if(y.zoom){const R=R0(y.zoom,w,N0);k.zoom=this._map.transform.zoom+R.amount,C1(k,R)}if(y.bearing){const R=R0(y.bearing,w,Bx);k.bearing=this._map.transform.bearing+l.bb(R.amount,-179,179),C1(k,R)}if(y.pitch){const R=R0(y.pitch,w,cR);k.pitch=this._map.transform.pitch+R.amount,C1(k,R)}if(k.zoom||k.bearing){const R=y.pinchAround===void 0?y.around:y.pinchAround;k.around=R?this._map.unproject(R):this._map.getCenter()}return this.clear(),k.noMoveStart=!0,k}}function C1(_,f){(!_.duration||_.durationy.unproject(V)),z=R.reduce((V,H,Y,te)=>V.add(H.div(te.length)),new l.P(0,0));super(f,{points:R,point:z,lngLats:M,lngLat:y.unproject(z),originalEvent:w}),this._defaultPrevented=!1}}class nz extends l.i{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(f,y){super("wheel",{originalEvent:y}),this._defaultPrevented=!1}}class dR{constructor(f,y){this._map=f,this._clickTolerance=y.clickTolerance}reset(){this._mousedownPos=void 0}wheel(f){return this._firePreventable(new nz(this._map,f))}mousedown(f,y){return this._mousedownPos=y,this._firePreventable(new Gu(f.type,this._map,f))}mouseup(f){this._map.fire(new Gu(f.type,this._map,f))}preclick(f){const y=new MouseEvent("preclick",f);this._map.fire(new Gu(y.type,this._map,y))}click(f,y){this._mousedownPos&&this._mousedownPos.dist(y)>=this._clickTolerance||(this.preclick(f),this._map.fire(new Gu(f.type,this._map,f)))}dblclick(f){return this._firePreventable(new Gu(f.type,this._map,f))}mouseover(f){this._map.fire(new Gu(f.type,this._map,f))}mouseout(f){this._map.fire(new Gu(f.type,this._map,f))}touchstart(f){return this._firePreventable(new L0(f.type,this._map,f))}touchmove(f){this._map.fire(new L0(f.type,this._map,f))}touchend(f){this._map.fire(new L0(f.type,this._map,f))}touchcancel(f){this._map.fire(new L0(f.type,this._map,f))}_firePreventable(f){if(this._map.fire(f),f.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class iz{constructor(f){this._map=f}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(f){this._map.fire(new Gu(f.type,this._map,f))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Gu("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(f){this._delayContextMenu?this._contextMenuEvent=f:this._map.fire(new Gu(f.type,this._map,f)),this._map.listens("contextmenu")&&f.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class bc{constructor(f,y){this._map=f,this._el=f.getCanvasContainer(),this._container=f.getContainer(),this._clickTolerance=y.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(f,y){this.isEnabled()&&f.shiftKey&&f.button===0&&(G(),this._startPos=this._lastPos=y,this._active=!0)}mousemoveWindow(f,y){if(!this._active)return;const w=y,k=this._startPos,R=this._lastPos;if(!k||!R||R.equals(w)||!this._box&&w.dist(k){this._box&&(this._box.style.transform=`translate(${M}px,${V}px)`,this._box.style.width=z-M+"px",this._box.style.height=H-V+"px")})}mouseupWindow(f,y){if(!this._active)return;const w=this._startPos,k=y;if(w&&f.button===0){if(this.reset(),Q(),w.x!==k.x||w.y!==k.y)return this._map.fire(new l.i("boxzoomend",{originalEvent:f})),{cameraAnimation:R=>R.fitScreenCoordinates(w,k,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",f)}}keydown(f){this._active&&f.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",f))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),W(),delete this._startPos,delete this._lastPos}_fireEvent(f,y){return this._map.fire(new l.i(f,{originalEvent:y}))}}function zx(_,f){const y={};for(let w=0;w<_.length;w++)y[_[w].identifier]=f[w];return y}class $x{constructor(f){this.reset(),this.numTouches=f.numTouches}reset(){this.centroid=void 0,this.startTime=0,this.touches={},this.aborted=!1}touchstart(f,y,w){(this.centroid||w.length>this.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=f.timeStamp),w.length===this.numTouches&&(this.centroid=function(k){const R=new l.P(0,0);for(const M of k)R._add(M);return R.div(k.length)}(y),this.touches=zx(w,y)))}touchmove(f,y,w){if(this.aborted||!this.centroid)return;const k=zx(w,y);for(const R in this.touches){const M=k[R];(!M||M.dist(this.touches[R])>30)&&(this.aborted=!0)}}touchend(f,y,w){if((!this.centroid||f.timeStamp-this.startTime>500)&&(this.aborted=!0),w.length===0){const k=!this.aborted&&this.centroid;if(this.reset(),k)return k}}}class P1{constructor(f){this.singleTap=new $x(f),this.numTaps=f.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(f,y,w){this.singleTap.touchstart(f,y,w)}touchmove(f,y,w){this.singleTap.touchmove(f,y,w)}touchend(f,y,w){const k=this.singleTap.touchend(f,y,w);if(k){const R=f.timeStamp-this.lastTime<500,M=!this.lastTap||this.lastTap.dist(k)<30;if(R&&M||this.reset(),this.count++,this.lastTime=f.timeStamp,this.lastTap=k,this.count===this.numTaps)return this.reset(),k}}}class Gg{constructor(){this._zoomIn=new P1({numTouches:1,numTaps:2}),this._zoomOut=new P1({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(f,y,w){this._zoomIn.touchstart(f,y,w),this._zoomOut.touchstart(f,y,w)}touchmove(f,y,w){this._zoomIn.touchmove(f,y,w),this._zoomOut.touchmove(f,y,w)}touchend(f,y,w){const k=this._zoomIn.touchend(f,y,w),R=this._zoomOut.touchend(f,y,w);return k?(this._active=!0,f.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:M=>M.easeTo({duration:300,zoom:M.getZoom()+1,around:M.unproject(k)},{originalEvent:f})}):R?(this._active=!0,f.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:M=>M.easeTo({duration:300,zoom:M.getZoom()-1,around:M.unproject(R)},{originalEvent:f})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const D0=0,sz=2,az={[D0]:1,[sz]:2},hR={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class F2{constructor(f){this.reset(),this._clickTolerance=f.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(f,y){return!1}_move(f,y){return{}}mousedown(f,y){if(this._lastPoint)return;const w=oe(f);this._correctButton(f,w)&&(this._lastPoint=y,this._eventButton=w)}mousemoveWindow(f,y){const w=this._lastPoint;if(w){if(f.preventDefault(),this._eventButton!=null&&function(k,R){const M=az[R];return k.buttons===void 0||(k.buttons&M)!==M}(f,this._eventButton))this.reset();else if(this._moved||!(y.dist(w)0&&(this._active=!0);const k=zx(w,y),R=new l.P(0,0),M=new l.P(0,0);let z=0;for(const H in k){const Y=k[H],te=this._touches[H];te&&(R._add(Y),M._add(Y.sub(te)),z++,k[H]=Y)}if(this._touches=k,z{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class z2{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(f){}_move(f,y,w){return{}}touchstart(f,y,w){this._firstTwoTouches||w.length<2||(this._firstTwoTouches=[w[0].identifier,w[1].identifier],this._start([y[0],y[1]]))}touchmove(f,y,w){const k=this._firstTwoTouches;if(!k)return;f.preventDefault();const[R,M]=k,z=M0(w,y,R),V=M0(w,y,M);if(!z||!V)return;const H=this._aroundCenter?null:z.add(V).div(2);return this._move([z,V],H,f)}touchend(f,y,w){if(!this._firstTwoTouches)return;const[k,R]=this._firstTwoTouches,M=M0(w,y,k),z=M0(w,y,R);M&&z||(this._active&&Q(),this.reset())}touchcancel(){this.reset()}enable(f){this._enabled=!0,this._aroundCenter=!!f&&f.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function M0(_,f,y){for(let w=0;w<_.length;w++)if(_[w].identifier===y)return f[w]}function Ux(_,f){return Math.log2(_/f)}class lz extends z2{reset(){super.reset(),this._distance=0,this._startDistance=0}_start(f){this._startDistance=this._distance=f[0].dist(f[1])}_move(f,y){const w=this._distance;if(this._distance=f[0].dist(f[1]),this._active||!(Math.abs(Ux(this._distance,this._startDistance))<.1))return this._active=!0,{zoomDelta:Ux(this._distance,w),pinchAround:y}}}function go(_,f){return 180*_.angleWith(f)/Math.PI}class Vx extends z2{reset(){super.reset(),this._minDiameter=0,this._startVector=void 0,this._vector=void 0}_start(f){this._startVector=this._vector=f[0].sub(f[1]),this._minDiameter=f[0].dist(f[1])}_move(f,y){const w=this._vector;if(this._vector=f[0].sub(f[1]),w&&(this._active||!this._isBelowThreshold(this._vector)))return this._active=!0,{bearingDelta:go(this._vector,w),pinchAround:y}}_isBelowThreshold(f){this._minDiameter=Math.min(this._minDiameter,f.mag());const y=25/(Math.PI*this._minDiameter)*360,w=this._startVector;if(!w)return!1;const k=go(f,w);return Math.abs(k)Math.abs(_.x)}class R1 extends z2{constructor(f){super(),this._map=f}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(f){this._lastPoints=f,N1(f[0].sub(f[1]))&&(this._valid=!1)}_move(f,y,w){const k=this._lastPoints;if(!k)return;const R=f[0].sub(k[0]),M=f[1].sub(k[1]);return this._map._cooperativeGestures&&!l.eI()&&w.touches.length<3||(this._valid=this.gestureBeginsVertically(R,M,w.timeStamp),!this._valid)?void 0:(this._lastPoints=f,this._active=!0,{pitchDelta:(R.y+M.y)/2*-.5})}gestureBeginsVertically(f,y,w){if(this._valid!==void 0)return this._valid;const k=f.mag()>=2,R=y.mag()>=2;if(!k&&!R)return;if(!k||!R)return this._firstMove??(this._firstMove=w),w-this._firstMove<100&&void 0;const M=f.y>0==y.y>0;return N1(f)&&N1(y)&&M}}const L1={panStep:100,bearingStep:15,pitchStep:10};class O0{constructor(){const f=L1;this._panStep=f.panStep,this._bearingStep=f.bearingStep,this._pitchStep=f.pitchStep,this._bearingDisabled=!1,this._pitchDisabled=!1,this._panDisabled=!1,this._zoomDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(f){if(f.altKey||f.ctrlKey||f.metaKey||!this.isEnabled())return;let y=0,w=0,k=0,R=0,M=0;switch(f.keyCode){case 61:case 107:case 171:case 187:y=1;break;case 189:case 109:case 173:y=-1;break;case 37:f.shiftKey?w=-1:(f.preventDefault(),R=-1);break;case 39:f.shiftKey?w=1:(f.preventDefault(),R=1);break;case 38:f.shiftKey?k=1:(f.preventDefault(),M=-1);break;case 40:f.shiftKey?k=-1:(f.preventDefault(),M=1);break;default:return}return this._bearingDisabled&&(w=0),this._pitchDisabled&&(k=0),this._panDisabled&&(R=0,M=0),this._zoomDisabled&&(y=0),{cameraAnimation:z=>{const V=z.getZoom();z.easeTo({duration:300,easeId:"keyboardHandler",easing:pR,zoom:y?Math.round(V)+y*(f.shiftKey?2:1):V,bearing:z.getBearing()+w*this._bearingStep,pitch:z.getPitch()+k*this._pitchStep,offset:[-R*this._panStep,-M*this._panStep],center:z.getCenter()},{originalEvent:f})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled&&!(this._bearingDisabled&&this._pitchDisabled&&this._panDisabled&&this._zoomDisabled)}isActive(){return this._active}disableRotation(){this._pitchDisabled=!0,this._bearingDisabled=!0}enableRotation(){this._pitchDisabled=!1,this._bearingDisabled=!1}isRotationEnabled(){return!this._pitchDisabled&&!this._bearingDisabled}disablePan(){this._panDisabled=!0}enablePan(){this._panDisabled=!1}isPanEnabled(){return!this._panDisabled}disableZoom(){this._zoomDisabled=!0}enableZoom(){this._zoomDisabled=!1}isZoomEnabled(){return!this._zoomDisabled}disablePitch(){this._pitchDisabled=!0}enablePitch(){this._pitchDisabled=!1}isPitchEnabled(){return!this._pitchDisabled}disableBearing(){this._bearingDisabled=!0}enableBearing(){this._bearingDisabled=!1}isBearingEnabled(){return!this._bearingDisabled}}function pR(_){return _*(2-_)}const $2=4.000244140625,F0=1/450,U2=/(Mac|iPad)/i;class gR{constructor(f,y){this._map=f,this._el=f.getCanvasContainer(),this._handler=y,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=F0,l.b4(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(f){this._defaultZoomRate=f}setWheelZoomRate(f){this._wheelZoomRate=f}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(f){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!f&&f.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(f){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(f.ctrlKey||f.metaKey||this.isZooming()||l.eI()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let y=f.deltaMode===WheelEvent.DOM_DELTA_LINE?40*f.deltaY:f.deltaY;const w=l.e.now(),k=w-(this._lastWheelEventTime||0);this._lastWheelEventTime=w,y!==0&&y%$2===0?this._type="wheel":y!==0&&Math.abs(y)<4?this._type="trackpad":k>400?(this._type=null,this._lastValue=y,this._timeout=window.setTimeout(this._onTimeout,40,f)):this._type||(this._type=Math.abs(k*y)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,y+=this._lastValue)),f.shiftKey&&y&&(y/=4),this._type&&(this._lastWheelEvent=f,this._delta-=y,this._active||this._start(f)),f.preventDefault()}_onTimeout(f){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(f)}_start(f){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const y=ee(this._el,f);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:y,this._aroundCoord=this._map.transform.pointCoordinate3D(this._aroundPoint),this._targetZoom=void 0,this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame())}renderFrame(){if(!this._frameId||(this._frameId=null,!this.isActive()))return;const f=this._map.transform;this._type==="wheel"&&f.projection.wrap&&(f._center.lng>=180||f._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const y=()=>f._terrainEnabled()&&this._aroundCoord?f.computeZoomRelativeTo(this._aroundCoord):f.zoom;if(this._delta!==0){const H=this._type==="wheel"&&Math.abs(this._delta)>$2?this._wheelZoomRate:this._defaultZoomRate;let Y=2/(1+Math.exp(-Math.abs(this._delta*H)));this._delta<0&&Y!==0&&(Y=1/Y);const te=y(),ne=Math.pow(2,te),le=typeof this._targetZoom=="number"?f.zoomScale(this._targetZoom):ne;this._targetZoom=Math.min(f.maxZoom,Math.max(f.minZoom,f.scaleZoom(le*Y))),this._type==="wheel"&&(this._startZoom=te,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const w=typeof this._targetZoom=="number"?this._targetZoom:y(),k=this._startZoom,R=this._easing;let M,z=!1;if(this._type==="wheel"&&k&&R){const H=Math.min((l.e.now()-this._lastWheelEventTime)/200,1),Y=R(H);M=l.aw(k,w,Y),H<1?this._frameId||(this._frameId=!0):z=!0}else M=w,z=!0;this._active=!0,z&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let V=M-y();return V*this._lastDelta<0&&(V=0),{noInertia:!0,needsRenderFrame:!z,zoomDelta:V,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(f){let y=l.eJ;if(this._prevEase){const w=this._prevEase,k=(l.e.now()-w.start)/w.duration,R=w.easing(k+.01)-w.easing(k),M=.27/Math.sqrt(R*R+1e-4)*.01,z=Math.sqrt(.0729-M*M);y=l.eH(M,z,.25,1)}return this._prevEase={start:l.e.now(),duration:f,easing:y},y}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=C("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=U2.test(navigator.userAgent)?this._map._getUIString("ScrollZoomBlocker.CmdMessage"):this._map._getUIString("ScrollZoomBlocker.CtrlMessage"),this._alertContainer.style.fontSize=`${Math.max(10,Math.min(24,Math.floor(.05*this._el.clientWidth)))}px`)}_showBlockerAlert(){this._alertContainer.style.visibility="visible",this._alertContainer.classList.add("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.setAttribute("role","alert"),clearTimeout(this._alertTimer),this._alertTimer=window.setTimeout(()=>{this._alertContainer.classList.remove("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.removeAttribute("role")},200)}}class V2{constructor(f,y){this._clickZoom=f,this._tapZoom=y}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class q2{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(f,y){return f.preventDefault(),{cameraAnimation:w=>{w.easeTo({duration:300,zoom:w.getZoom()+(f.shiftKey?-1:1),around:w.unproject(y)},{originalEvent:f})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Hc{constructor(){this._tap=new P1({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(f,y,w){this._swipePoint||(this._tapTime&&f.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?w.length>0&&(this._swipePoint=y[0],this._swipeTouch=w[0].identifier):this._tap.touchstart(f,y,w))}touchmove(f,y,w){if(this._tapTime){if(this._swipePoint){if(w[0].identifier!==this._swipeTouch)return;const k=y[0],R=k.y-this._swipePoint.y;return this._swipePoint=k,f.preventDefault(),this._active=!0,{zoomDelta:R/128}}}else this._tap.touchmove(f,y,w)}touchend(f,y,w){this._tapTime?this._swipePoint&&w.length===0&&this.reset():this._tap.touchend(f,y,w)&&(this._tapTime=f.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Hg{constructor(f,y,w){this._el=f,this._mousePan=y,this._touchPan=w}enable(f){this._inertiaOptions=f||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("mapboxgl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class G2{constructor(f,y,w){this._pitchWithRotate=f.pitchWithRotate,this._mouseRotate=y,this._mousePitch=w,this._pitchDisabled=!1,this._rotationDisabled=!1}enable(){this._rotationDisabled||this._mouseRotate.enable(),this._pitchWithRotate&&!this._pitchDisabled&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._pitchWithRotate?!this._rotationDisabled&&this._mouseRotate.isEnabled()||!this._pitchDisabled&&this._mousePitch.isEnabled():!this._rotationDisabled&&this._mouseRotate.isEnabled()}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}disablePitch(){this._pitchDisabled=!0,this._mousePitch.disable()}enablePitch(){this._pitchDisabled=!1,this._pitchWithRotate&&this._mousePitch.enable()}isPitchEnabled(){return!this._pitchDisabled&&this._mousePitch.isEnabled()}disableRotation(){this._rotationDisabled=!0,this._mouseRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._mouseRotate.enable()}isRotationEnabled(){return!this._rotationDisabled&&this._mouseRotate.isEnabled()}}class Xd{constructor(f,y,w,k){this._el=f,this._touchZoom=y,this._touchRotate=w,this._tapDragZoom=k,this._rotationDisabled=!1,this._tapDragZoomDisabled=!1,this._enabled=!0}enable(f){this._touchZoom.enable(f),this._rotationDisabled||this._touchRotate.enable(f),this._tapDragZoomDisabled||this._tapDragZoom.enable(),this._el.classList.add("mapboxgl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("mapboxgl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()||!this._rotationDisabled&&this._touchRotate.isEnabled()||!this._tapDragZoomDisabled&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}isRotationEnabled(){return!this._rotationDisabled}disableTapDragZoom(){this._tapDragZoomDisabled=!0,this._tapDragZoom.disable()}enableTapDragZoom(){this._tapDragZoomDisabled=!1,this._touchZoom.isEnabled()&&this._tapDragZoom.enable()}isTapDragZoomEnabled(){return!this._tapDragZoomDisabled}}const gu=_=>_.zoom||_.drag||_.pitch||_.rotate;class qx extends l.i{}class Wg{constructor(){this.constants=[1,1,.01],this.radius=0}setup(f,y){const w=l.cQ([],y,f);this.radius=l.en(w[2]<0?l.eL([],w,this.constants):[w[0],w[1],0])}projectRay(f){l.eL(f,f,this.constants),l.cg(f,f),l.eM(f,f,this.constants);const y=l.dY([],f,this.radius);if(y[2]>0){const w=l.dY([],[0,0,1],l.d$(y,[0,0,1])),k=l.dY([],l.cg([],[y[0],y[1],0]),this.radius),R=l.dZ([],y,l.dY([],l.cQ([],l.dZ([],k,w),y),2));y[0]=R[0],y[1]=R[1]}return y}}function fm(_){return _.panDelta&&_.panDelta.mag()||_.zoomDelta||_.bearingDelta||_.pitchDelta}class H2{constructor(f,y){this._map=f,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new uR(f),this._bearingSnap=y.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new Wg,this._dragOrigin=null,this._mouseBeingPressed=!1,this._activeTouchCount=0,this._eventsInProgress={},this._addDefaultHandlers(y),l.b4(["handleEvent","handleWindowEvent"],this);const w=this._el;this._listeners=[[w,"touchstart",{passive:!0}],[w,"touchmove",{passive:!1}],[w,"touchend",void 0],[w,"touchcancel",void 0],[w,"mousedown",void 0],[w,"mousemove",void 0],[w,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[w,"mouseover",void 0],[w,"mouseout",void 0],[w,"dblclick",void 0],[w,"click",void 0],[w,"keydown",{capture:!1}],[w,"keyup",void 0],[w,"wheel",{passive:!1}],[w,"contextmenu",void 0],[window,"blur",void 0]];for(const[k,R,M]of this._listeners){const z=k===document?this.handleWindowEvent:this.handleEvent;k.addEventListener(R,z,M)}}destroy(){for(const[f,y,w]of this._listeners){const k=f===document?this.handleWindowEvent:this.handleEvent;f.removeEventListener(y,k,w)}}_addDefaultHandlers(f){const y=this._map,w=y.getCanvasContainer();this._add("mapEvent",new dR(y,f));const k=y.boxZoom=new bc(y,f);this._add("boxZoom",k);const R=new Gg,M=new q2;y.doubleClickZoom=new V2(M,R),this._add("tapZoom",R),this._add("clickZoom",M);const z=new Hc;this._add("tapDragZoom",z);const V=y.touchPitch=new R1(y);this._add("touchPitch",V);const H=new fR(f),Y=new mR(f);y.dragRotate=new G2(f,H,Y),this._add("mouseRotate",H,["mousePitch"]),this._add("mousePitch",Y,["mouseRotate"]);const te=new oz(f),ne=new B2(y,f);y.dragPan=new Hg(w,te,ne),this._add("mousePan",te),this._add("touchPan",ne,["touchZoom","touchRotate"]);const le=new Vx,me=new lz;y.touchZoomRotate=new Xd(w,me,le,z),this._add("touchRotate",le,["touchPan","touchZoom"]),this._add("touchZoom",me,["touchPan","touchRotate"]),this._add("blockableMapEvent",new iz(y));const fe=y.scrollZoom=new gR(y,this);this._add("scrollZoom",fe,["mousePan"]);const Se=y.keyboard=new O0;this._add("keyboard",Se);for(const Me of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])f.interactive&&f[Me]&&y[Me].enable(f[Me])}_add(f,y,w){this._handlers.push({handlerName:f,handler:y,allowed:w}),this._handlersById[f]=y}stop(f="never"){if(!this._updatingCamera&&!(f==="always"||f==="ifPointerDown"&&this._isPointerDown())){for(const{handler:y}of this._handlers)y.reset();this._inertia.clear(),this._fireEvents({},{},!1),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:f}of this._handlers)if(f.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!gu(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(f,y,w){for(const k in f)if(!(k===w||y&&y.includes(k)))return!0;return!1}handleWindowEvent(f){this.handleEvent(f,`${f.type}Window`)}_getMapTouches(f){const y=[];for(const w of f)this._el.contains(w.target)&&y.push(w);return y}_updatePointerLiveness(f){switch(f.type){case"mousedown":this._mouseBeingPressed=!0;break;case"mousemove":f.buttons===0&&(this._mouseBeingPressed=!1);break;case"mouseup":this._mouseBeingPressed=!1;break;case"touchstart":case"touchmove":case"touchend":case"touchcancel":this._activeTouchCount=f.touches?f.touches.length:0;break;case"blur":this._mouseBeingPressed=!1,this._activeTouchCount=0}}_isPointerDown(){return this._mouseBeingPressed||this._activeTouchCount>0}handleEvent(f,y){this._updatePointerLiveness(f),this._updatingCamera=!0;const w=f.type==="renderFrame",k=w?void 0:f,R={needsRenderFrame:!1},M={},z={},V=f.touches?this._getMapTouches(f.touches):void 0,H=V?ie(this._el,V):w?void 0:ee(this._el,f);for(const{handlerName:ne,handler:le,allowed:me}of this._handlers){if(!le.isEnabled())continue;let fe;this._blockedByActive(z,me,ne)?le.reset():le[y||f.type]&&(fe=le[y||f.type](f,H,V),this.mergeHandlerResult(R,M,fe,ne,k),fe&&fe.needsRenderFrame&&this._triggerRenderFrame()),(fe||le.isActive())&&(z[ne]=le)}const Y={};for(const ne in this._previousActiveHandlers)z[ne]||(Y[ne]=k);this._previousActiveHandlers=z,(Object.keys(Y).length||fm(R))&&(this._changes.push([R,M,Y]),this._triggerRenderFrame()),(Object.keys(z).length||fm(R))&&this._map._stop({keepGesture:"always"}),this._updatingCamera=!1;const{cameraAnimation:te}=R;te&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],te(this._map))}mergeHandlerResult(f,y,w,k,R){if(!w)return;Object.assign(f,w);const M={handlerName:k,originalEvent:w.originalEvent||R};w.zoomDelta!==void 0&&(y.zoom=M),w.panDelta!==void 0&&(y.drag=M),w.pitchDelta!==void 0&&(y.pitch=M),w.bearingDelta!==void 0&&(y.rotate=M)}_applyChanges(){const f={},y={},w={};for(const[k,R,M]of this._changes)k.panDelta&&(f.panDelta=(f.panDelta||new l.P(0,0))._add(k.panDelta)),k.zoomDelta&&(f.zoomDelta=(f.zoomDelta||0)+k.zoomDelta),k.bearingDelta&&(f.bearingDelta=(f.bearingDelta||0)+k.bearingDelta),k.pitchDelta&&(f.pitchDelta=(f.pitchDelta||0)+k.pitchDelta),k.around!==void 0&&(f.around=k.around),k.aroundCoord!==void 0&&(f.aroundCoord=k.aroundCoord),k.pinchAround!==void 0&&(f.pinchAround=k.pinchAround),k.noInertia&&(f.noInertia=k.noInertia),Object.assign(y,R),Object.assign(w,M);this._updateMapTransform(f,y,w),this._changes=[]}_updateMapTransform(f,y,w){const k=this._map,R=k.transform,M=qe=>[qe.x,qe.y,qe.z];if((()=>{const qe=this._eventsInProgress.drag;return qe&&!this._handlersById[qe.handlerName].isActive()})()&&!fm(f)){const qe=R.zoom;R.cameraElevationReference="sea",this._originalZoom!=null&&R._orthographicProjectionAtLowPitch&&R.projection.name!=="globe"&&R.pitch===0?(R.cameraElevationReference="ground",R.zoom=this._originalZoom):(R.recenterOnTerrain(),R.cameraElevationReference="ground"),qe!==R.zoom&&this._map._update(!0)}if(R._isCameraConstrained&&k._stop({keepGesture:"always"}),!fm(f))return void this._fireEvents(y,w,!0);let{panDelta:z,zoomDelta:V,bearingDelta:H,pitchDelta:Y,around:te,aroundCoord:ne,pinchAround:le}=f;R._isCameraConstrained&&(V>0&&(V=0),R._isCameraConstrained=!1),le!==void 0&&(te=le),(V||(qe=>y[qe]&&!this._eventsInProgress[qe])("drag"))&&te&&(this._dragOrigin=M(R.pointCoordinate3D(te)),this._originalZoom=R.zoom,this._trackingEllipsoid.setup(R._camera.position,this._dragOrigin)),R.cameraElevationReference="sea",k._stop({keepGesture:"always"}),te=te||k.transform.centerPoint,H&&(R.bearing+=H),Y&&(R.pitch+=Y),R._updateCameraState();const me=[0,0,0];if(z)if(R.projection.name==="mercator"){const qe=this._trackingEllipsoid.projectRay(R.screenPointToMercatorRay(te).dir),Ne=this._trackingEllipsoid.projectRay(R.screenPointToMercatorRay(te.sub(z)).dir);me[0]=Ne[0]-qe[0],me[1]=Ne[1]-qe[1]}else{const qe=R.pointCoordinate(te);if(R.projection.name==="globe"){z=z.rotate(-R.angle);const Ne=R._pixelsPerMercatorPixel/R.worldSize;me[0]=-z.x*l.eK(l.bC(qe.y))*Ne,me[1]=-z.y*l.eK(R.center.lat)*Ne}else{const Ne=R.pointCoordinate(te.sub(z));qe&&Ne&&(me[0]=Ne.x-qe.x,me[1]=Ne.y-qe.y)}}const fe=R.zoom,Se=[0,0,0];if(V){const qe=M(ne||R.pointCoordinate3D(te)),Ne={dir:l.cg([],l.cQ([],qe,R._camera.position))};if(Ne.dir[2]<0){const We=R.zoomDeltaToMovement(qe,V);l.dY(Se,Ne.dir,We)}}const Me=l.dZ(me,me,Se);R._translateCameraConstrained(Me),V&&Math.abs(R.zoom-fe)>1e-4&&R.recenterOnTerrain(),R.cameraElevationReference="ground",this._map._update(),f.noInertia||this._inertia.record(f),this._fireEvents(y,w,!0)}_fireEvents(f,y,w){const k=gu(this._eventsInProgress),R=gu(f),M={};for(const Y in f){const{originalEvent:te}=f[Y];this._eventsInProgress[Y]||(M[`${Y}start`]=te),this._eventsInProgress[Y]=f[Y]}!k&&R&&this._fireEvent("movestart",R.originalEvent);for(const Y in M)this._fireEvent(Y,M[Y]);R&&this._fireEvent("move",R.originalEvent);for(const Y in f){const{originalEvent:te}=f[Y];this._fireEvent(Y,te)}const z={};let V;for(const Y in this._eventsInProgress){const{handlerName:te,originalEvent:ne}=this._eventsInProgress[Y];this._handlersById[te].isActive()||(delete this._eventsInProgress[Y],V=y[te]||ne,z[`${Y}end`]=V)}for(const Y in z)this._fireEvent(Y,z[Y]);const H=gu(this._eventsInProgress);if(w&&(k||R)&&!H){this._updatingCamera=!0;const Y=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),te=ne=>ne!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new qx("renderFrame",{timeStamp:f})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const pi="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class Qd extends l.E{constructor(f,y){super(),this._moving=!1,this._zooming=!1,this.transform=f,this._bearingSnap=y.bearingSnap,this._respectPrefersReducedMotion=y.respectPrefersReducedMotion!==!1,l.b4(["_renderFrameCallback"],this)}getCenter(){return new l.cJ(this.transform.center.lng,this.transform.center.lat)}setCenter(f,y){return this.jumpTo({center:f},y)}panBy(f,y,w){return f=l.P.convert(f).mult(-1),this.panTo(this.transform.center,{offset:f,...y},w)}panTo(f,y,w){return this.easeTo({center:f,...y},w)}getZoom(){return this.transform.zoom}setZoom(f,y){return this.jumpTo({zoom:f},y),this}zoomTo(f,y,w){return this.easeTo({zoom:f,...y},w)}zoomIn(f,y){return this.zoomTo(this.getZoom()+1,f,y),this}zoomOut(f,y){return this.zoomTo(this.getZoom()-1,f,y),this}getBearing(){return this.transform.bearing}setBearing(f,y){return this.jumpTo({bearing:f},y),this}getPadding(){return this.transform.padding}setPadding(f,y){return this.jumpTo({padding:f},y),this}rotateTo(f,y,w){return this.easeTo({bearing:f,...y},w)}resetNorth(f,y){return this.rotateTo(0,{duration:1e3,...f},y),this}resetNorthPitch(f,y){return this.easeTo({bearing:0,pitch:0,duration:1e3,...f},y),this}snapToNorth(f,y){return Math.abs(this.getBearing())f.aspect?w/(2*Math.tan(.5*f.fovX)*f.aspect):k/(2*Math.tan(.5*f.fovY)*f.aspect)}_cameraForBoundsOnGlobe(f,y,w,k,R,M){const z=f.clone(),V=this._extendCameraOptions(M);z.bearing=k,z.pitch=R;const H=l.cJ.convert(y),Y=l.cJ.convert(w),te=.5*(H.lat+Y.lat),ne=.5*(H.lng+Y.lng),le=l.eO(te,ne),me=l.cg([],le),fe=l.cg([],l.eP([],me,[0,1,0])),Se=l.eP([],fe,me),Me=[fe[0],fe[1],fe[2],0,Se[0],Se[1],Se[2],0,me[0],me[1],me[2],0,0,0,0,1],qe=[le,l.eO(H.lat,H.lng),l.eO(Y.lat,H.lng),l.eO(Y.lat,Y.lng),l.eO(H.lat,Y.lng),l.eO(te,H.lng),l.eO(te,Y.lng),l.eO(H.lat,ne),l.eO(Y.lat,ne)];let Ne=l.eQ.fromPoints(qe.map(Ut=>[l.d$(fe,Ut),l.d$(Se,Ut),l.d$(me,Ut)]));const We=l.bS([],Ne.center,Me);l.eR(We)===0&&l.eS(We,0,0,1),l.cg(We,We),l.dY(We,We,l.cT),z.center=l.eT(We);const ct=z.getWorldToCameraMatrix(),it=l.aZ(new Float64Array(16),ct);Ne=l.eQ.applyTransform(Ne,l.a1([],ct,Me));const pt=this._extendAABB(Ne,z,V,k);if(!pt)return void l.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Ne=pt,l.bS(We,We,ct);const dt=.5*(Ne.max[2]-Ne.min[2]),mt=this._minimumAABBFrustumDistance(z,Ne),xt=l.dY([],[0,0,1],dt),bt=l.dZ(xt,We,xt),Ft=mt+(z.pitch===0?0:l.eU(We,bt)),Lt=z.globeCenterInViewSpace,Mt=l.cQ([],We,[Lt[0],Lt[1],Lt[2]]);l.cg(Mt,Mt),l.dY(Mt,Mt,Ft);const or=l.dZ([],We,Mt);l.bS(or,or,it);const fr=l.bu/l.cT,Cr=l.en(or),qr=l.ca(Math.max(Cr*fr-l.bu,Number.EPSILON),0),qt=Math.min(z.zoomFromMercatorZAdjusted(qr),V.maxZoom);return qt>.5*(l.ek+l.bc)?(z.setProjection({name:"mercator"}),z.zoom=qt,this._cameraForBounds(z,y,w,k,R,M)):{center:z.center,zoom:qt,bearing:k,pitch:R}}_extendAABB(f,y,w,k){const R=.5*((w.padding.left||0)+(w.padding.right||0)),M=.5*((w.padding.top||0)+(w.padding.bottom||0)),z=M,V=R,H=R,Y=M,te=y.width-(V+H),ne=y.height-(z+Y),le=l.cQ([],f.max,f.min),me=Math.min(te/le[0],ne/le[1]),fe=Math.min(y.scaleZoom(y.scale*me),w.maxZoom);if(isNaN(fe))return null;const Se=y.scale/y.zoomScale(fe),Me=new l.eQ([f.min[0]-V*Se,f.min[1]-Y*Se,f.min[2]],[f.max[0]+H*Se,f.max[1]+z*Se,f.max[2]]),qe=(typeof w.offset.x=="number"&&typeof w.offset.y=="number"?new l.P(w.offset.x,w.offset.y):l.P.convert(w.offset)).rotate(-l.aF(k));return Me.center[0]-=qe.x*Se,Me.center[1]+=qe.y*Se,Me}queryTerrainElevation(f,y){const w=this.transform.elevation;return w?(y={exaggerated:!0,...y},w.getAtPoint(l.b$.fromLngLat(f),null,y.exaggerated)):null}_cameraForBounds(f,y,w,k,R,M){if(f.projection.name==="globe")return this._cameraForBoundsOnGlobe(f,y,w,k,R,M);const z=f.clone(),V=this._extendCameraOptions(M);z.bearing=k,z.pitch=R;const H=l.cJ.convert(y),Y=l.cJ.convert(w),te=new l.cJ(H.lng,Y.lat),ne=new l.cJ(Y.lng,H.lat),le=z.project(H),me=z.project(Y),fe=this.queryTerrainElevation(H),Se=this.queryTerrainElevation(Y),Me=this.queryTerrainElevation(te),qe=this.queryTerrainElevation(ne),Ne=[[le.x,le.y,Math.min(fe||0,Se||0,Me||0,qe||0)],[me.x,me.y,Math.max(fe||0,Se||0,Me||0,qe||0)]];let We=l.eQ.fromPoints(Ne);const ct=z.getWorldToCameraMatrix(),it=l.aZ(new Float64Array(16),ct);We=l.eQ.applyTransform(We,ct);const pt=this._extendAABB(We,z,V,k);if(!pt)return void l.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");We=pt;const dt=.5*l.cQ([],We.max,We.min)[2],mt=this._minimumAABBFrustumDistance(z,We),xt=[0,0,1,0];l.cd(xt,xt,ct),l.eV(xt,xt);const bt=l.dY([],xt,mt+dt),Ft=l.dZ([],We.center,bt);l.bS(We.center,We.center,it),l.bS(Ft,Ft,it);const Lt=z.unproject(new l.P(We.center[0],We.center[1])),Mt=l.eW(z.projection,Lt),or=Math.pow(2,Mt),fr=Math.min(z._zoomFromMercatorZ(Ft[2]*z.pixelsPerMeter*or/z.worldSize),V.maxZoom);return z.mercatorFromTransition&&fr<.5*(l.ek+l.bc)?(z.setProjection({name:"globe"}),z.zoom=fr,this._cameraForBounds(z,y,w,k,R,M)):{center:Lt,zoom:fr,bearing:k,pitch:R}}fitBounds(f,y,w){const k=this.cameraForBounds(f,y);return this._fitInternal(k,y,w)}fitScreenCoordinates(f,y,w,k,R){const M=l.P.convert(f),z=l.P.convert(y),V=new l.P(Math.min(M.x,z.x),Math.min(M.y,z.y)),H=new l.P(Math.max(M.x,z.x),Math.max(M.y,z.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(M,z))return this;const Y=this.transform.pointLocation3D(V),te=this.transform.pointLocation3D(H),ne=this.transform.pointLocation3D(new l.P(V.x,H.y)),le=this.transform.pointLocation3D(new l.P(H.x,V.y)),me=[Math.min(Y.lng,te.lng,ne.lng,le.lng),Math.min(Y.lat,te.lat,ne.lat,le.lat)],fe=[Math.max(Y.lng,te.lng,ne.lng,le.lng),Math.max(Y.lat,te.lat,ne.lat,le.lat)],Se=k&&k.pitch?k.pitch:this.getPitch(),Me=this._cameraForBounds(this.transform,me,fe,w,Se,k);return this._fitInternal(Me,k,R)}_fitInternal(f,y,w){return f?(y=Object.assign(f,y)).linear?this.easeTo(y,w):this.flyTo(y,w):this}jumpTo(f,y){this._stop({keepGesture:"ifPointerDown"});const w=f.preloadOnly?this.transform.clone():this.transform;let k=!1,R=!1,M=!1;"zoom"in f&&w.zoom!==+f.zoom&&(k=!0,w.zoom=+f.zoom),f.center!==void 0&&(w.center=l.cJ.convert(f.center)),"bearing"in f&&w.bearing!==+f.bearing&&(R=!0,w.bearing=+f.bearing),"pitch"in f&&w.pitch!==+f.pitch&&(M=!0,w.pitch=+f.pitch),"fov"in f&&(w.fov=+f.fov);const z=typeof f.padding=="number"?this._extendPadding(f.padding):f.padding;if(f.padding!=null&&!w.isPaddingEqual(z))if(f.retainPadding===!1){const V=w.clone();V.padding=z,w.setLocationAtPoint(w.center,V.centerPoint)}else w.padding=z;return f.preloadOnly?(this._preloadTiles(w),this):(this.fire(new l.i("movestart",y)).fire(new l.i("move",y)),k&&this.fire(new l.i("zoomstart",y)).fire(new l.i("zoom",y)).fire(new l.i("zoomend",y)),R&&this.fire(new l.i("rotatestart",y)).fire(new l.i("rotate",y)).fire(new l.i("rotateend",y)),M&&this.fire(new l.i("pitchstart",y)).fire(new l.i("pitch",y)).fire(new l.i("pitchend",y)),this.fire(new l.i("moveend",y)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||l.w(pi),this.transform.getFreeCameraOptions()}setFreeCameraOptions(f,y){const w=this.transform;if(!w.projection.supportsFreeCamera)return l.w(pi),this;this.stop();const k=w.zoom,R=w.pitch,M=w.bearing;w.setFreeCameraOptions(f);const z=k!==w.zoom,V=R!==w.pitch,H=M!==w.bearing;return this.fire(new l.i("movestart",y)).fire(new l.i("move",y)),z&&this.fire(new l.i("zoomstart",y)).fire(new l.i("zoom",y)).fire(new l.i("zoomend",y)),H&&this.fire(new l.i("rotatestart",y)).fire(new l.i("rotate",y)).fire(new l.i("rotateend",y)),V&&this.fire(new l.i("pitchstart",y)).fire(new l.i("pitch",y)).fire(new l.i("pitchend",y)),this.fire(new l.i("moveend",y)),this}easeTo(f,y){this._stop({easeId:f.easeId}),((f={offset:[0,0],duration:500,easing:l.eJ,...f}).animate===!1||this._prefersReducedMotion(f))&&(f.duration=0);const w=f.preloadOnly?this.transform.clone():this.transform,k=this.getZoom(),R=this.getBearing(),M=this.getPitch(),z=this.getPadding(),V=this.getVerticalFieldOfView(),H="zoom"in f?+f.zoom:k,Y="bearing"in f?this._normalizeBearing(f.bearing,R):R,te="pitch"in f?+f.pitch:M,ne="fov"in f?+f.fov:V,le=this._extendPadding(f.padding),me=l.P.convert(f.offset);let fe,Se,Me;if(w.projection.name==="globe"){const Lt=l.b$.fromLngLat(w.center),Mt=me.rotate(-w.angle);Lt.x+=Mt.x/w.worldSize,Lt.y+=Mt.y/w.worldSize;const or=Lt.toLngLat(),fr=l.cJ.convert(f.center||or);this._normalizeCenter(fr),fe=w.centerPoint.add(Mt),Se=new l.P(Lt.x,Lt.y).mult(w.worldSize),Me=new l.P(l.ad(fr.lng),l.ae(fr.lat)).mult(w.worldSize).sub(Se)}else{fe=w.centerPoint.add(me);const Lt=w.pointLocation(fe),Mt=l.cJ.convert(f.center||Lt);this._normalizeCenter(Mt),Se=w.project(Lt),Me=w.project(Mt).sub(Se)}const qe=w.zoomScale(H-k);let Ne,We;f.around&&(Ne=l.cJ.convert(f.around),We=w.locationPoint(Ne));const ct=this._zooming||H!==k,it=this._rotating||R!==Y,pt=this._pitching||te!==M,dt=ne!==V,mt=!w.isPaddingEqual(le),xt=f.retainPadding===!1?w.clone():w,bt=Lt=>Mt=>{if(ct&&(Lt.zoom=l.aw(k,H,Mt)),it&&(Lt.bearing=l.aw(R,Y,Mt)),pt&&(Lt.pitch=l.aw(M,te,Mt)),dt&&(Lt.fov=l.aw(V,ne,Mt)),mt&&(xt.interpolatePadding(z,le,Mt),fe=xt.centerPoint.add(me)),Ne)Lt.setLocationAtPoint(Ne,We);else{const or=Lt.zoomScale(Lt.zoom-k),fr=H>k?Math.min(2,qe):Math.max(.5,qe),Cr=Math.pow(fr,1-Mt),qr=Lt.unproject(Se.add(Me.mult(Mt*Cr)).mult(or));Lt.setLocationAtPoint(Lt.renderWorldCopies?qr.wrap():qr,fe)}return f.preloadOnly||this._fireMoveEvents(y),Lt};if(f.preloadOnly){const Lt=this._emulate(bt,f.duration,w);return this._preloadTiles(Lt),this}const Ft={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=ct,this._rotating=it,this._pitching=pt,this._padding=mt,this._easeId=f.easeId,this._prepareEase(y,f.noMoveStart,Ft),this._ease(bt(w),Lt=>{w.cameraElevationReference==="sea"&&w.recenterOnTerrain(),this._afterEase(y,Lt)},f),this}_prepareEase(f,y,w={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),y||w.moving||this.fire(new l.i("movestart",f)),this._zooming&&!w.zooming&&this.fire(new l.i("zoomstart",f)),this._rotating&&!w.rotating&&this.fire(new l.i("rotatestart",f)),this._pitching&&!w.pitching&&this.fire(new l.i("pitchstart",f))}_fireMoveEvents(f){this.fire(new l.i("move",f)),this._zooming&&this.fire(new l.i("zoom",f)),this._rotating&&this.fire(new l.i("rotate",f)),this._pitching&&this.fire(new l.i("pitch",f))}_afterEase(f,y){if(this._easeId&&y&&this._easeId===y)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const w=this._zooming,k=this._rotating,R=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,w&&this.fire(new l.i("zoomend",f)),k&&this.fire(new l.i("rotateend",f)),R&&this.fire(new l.i("pitchend",f)),this.fire(new l.i("moveend",f))}flyTo(f,y){if(this._prefersReducedMotion(f)){const ur=l.cx(f,["center","zoom","bearing","pitch","fov","around","padding","retainPadding"]);return this.jumpTo(ur,y)}this.stop();const w=(f={offset:[0,0],speed:1.2,curve:1.42,easing:l.eJ,...f}).preloadOnly?this.transform.clone():this.transform,k=this.getZoom(),R=this.getBearing(),M=this.getPitch(),z=this.getPadding(),V=this.getVerticalFieldOfView(),H="zoom"in f?l.bb(+f.zoom,w.minZoom,w.maxZoom):k,Y="bearing"in f?this._normalizeBearing(f.bearing,R):R,te="pitch"in f?+f.pitch:M,ne="fov"in f?+f.fov:V,le=ne!==V,me=this._extendPadding(f.padding),fe=w.zoomScale(H-k),Se=l.P.convert(f.offset);let Me=w.centerPoint.add(Se);const qe=w.pointLocation(Me),Ne=l.cJ.convert(f.center||qe);this._normalizeCenter(Ne);const We=w.project(qe),ct=w.project(Ne).sub(We);let it=f.curve;const pt=Math.max(w.width,w.height),dt=pt/fe,mt=ct.mag();if("minZoom"in f){const ur=l.bb(Math.min(f.minZoom,k,H),w.minZoom,w.maxZoom),Xt=pt/w.zoomScale(ur-k);it=Math.sqrt(Xt/mt*2)}const xt=it*it;function bt(ur){return-Math.asinh((dt*dt-pt*pt+(ur?-1:1)*xt*xt*mt*mt)/(2*(ur?dt:pt)*xt*mt))}function Ft(ur){return(Math.exp(ur)-Math.exp(-ur))/2}function Lt(ur){return(Math.exp(ur)+Math.exp(-ur))/2}const Mt=bt(0);let or=function(ur){return Lt(Mt)/Lt(Mt+it*ur)},fr=function(ur){return pt*((Lt(Mt)*(Ft(Xt=Mt+it*ur)/Lt(Xt))-Ft(Mt))/xt)/mt;var Xt},Cr=(bt(1)-Mt)/it;if(Math.abs(mt)<1e-6||!isFinite(Cr)){if(Math.abs(pt-dt)<1e-6)return this.easeTo(f,y);const ur=dtf.maxDuration&&(f.duration=0);const qr=R!==Y,qt=te!==M,Ut=!w.isPaddingEqual(me),gr=f.retainPadding===!1?w.clone():w,Pr=ur=>Xt=>{const mr=Xt*Cr,tn=1/or(mr);ur.zoom=Xt===1?H:k+ur.scaleZoom(tn),qr&&(ur.bearing=l.aw(R,Y,Xt)),qt&&(ur.pitch=l.aw(M,te,Xt)),le&&(ur.fov=l.aw(V,ne,Xt)),Ut&&(gr.interpolatePadding(z,me,Xt),Me=gr.centerPoint.add(Se));const kr=Xt===1?Ne:ur.unproject(We.add(ct.mult(fr(mr))).mult(tn));return ur.setLocationAtPoint(ur.renderWorldCopies?kr.wrap():kr,Me),ur._updateCameraOnTerrain(),f.preloadOnly||this._fireMoveEvents(y),ur};if(f.preloadOnly){const ur=this._emulate(Pr,f.duration,w);return this._preloadTiles(ur),this}return this._zooming=!0,this._rotating=qr,this._pitching=qt,this._padding=Ut,this._prepareEase(y,!1),this._ease(Pr(w),()=>this._afterEase(y),f),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(f){}_cancelRenderFrame(f){}_stop({easeId:f,keepGesture:y}={}){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const k=this._onEaseEnd;this._onEaseEnd=void 0,k.call(this,f)}const w=this.handlers;return w&&w.stop(y),this}_ease(f,y,w){w.animate===!1||w.duration===0?(f(1),y()):(this._easeStart=l.e.now(),this._easeOptions=w,this._onEaseFrame=f,this._onEaseEnd=y,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const f=Math.min((l.e.now()-this._easeStart)/this._easeOptions.duration,1),y=this._onEaseFrame;y&&y(this._easeOptions.easing(f)),f<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(f,y){f=l.dc(f,-180,180);const w=Math.abs(f-y);return Math.abs(f-360-y)180?-360:w<-180?360:0}_prefersReducedMotion(f){return this._respectPrefersReducedMotion&&l.e.prefersReducedMotion&&!(f&&f.essential)}_emulate(f,y,w){const k=Math.ceil(15*y/1e3),R=[],M=f(w.clone());for(let z=0;z<=k;z++){const V=M(z/k);R.push(V.clone())}return R}_preloadTiles(f,y){}}const D1=/^(https?:|mailto:)/i;class ks{constructor(f={}){this.options=f,l.b4(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(f){const y=this.options&&this.options.compact,w=f._getUIString("AttributionControl.ToggleAttribution");this._map=f,this._container=C("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=C("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",w);const k=C("span","mapboxgl-ctrl-icon",this._compactButton);return k.setAttribute("aria-hidden","true"),k.setAttribute("title",w),this._innerContainer=C("div","mapboxgl-ctrl-attrib-inner",this._container),y&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),y===void 0&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0}_toggleAttribution(){this._container.classList.contains("mapboxgl-compact-show")?(this._container.classList.remove("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","false")):(this._container.classList.add("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","true"))}_updateEditLink(){let f=this._editLink;f||(f=this._editLink=this._container.querySelector(".mapbox-improve-map"));const y=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||l.t.ACCESS_TOKEN}];if(f){const w=y.reduce((k,R,M)=>(R.value&&(k+=`${R.key}=${R.value}${Mk.length-R.length),f=f.filter((k,R)=>{for(let M=R+1;Mfunction(R){const M=new DOMParser().parseFromString(R,"text/html");return Array.from(M.body.querySelectorAll("*")).reverse().forEach(z=>{const V=z.textContent||"";if(z.tagName!=="A")return void z.replaceWith(...z.childNodes);const H=z.getAttribute("href");if(!H||!D1.test(H))return void z.replaceWith(M.createTextNode(V));const Y=M.createElement("a");Y.href=H,Y.textContent=V,Y.rel="noopener nofollow";const te=z.getAttribute("class");te&&(Y.className=te),z.replaceWith(Y)}),M.body.innerHTML}(k)).join(" | ");w!==this._attribHTML&&(this._attribHTML=w,f.length?(this._innerContainer.innerHTML=w,this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null)}_updateCompact(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact","mapboxgl-compact-show")}}class M1{constructor(){l.b4(["_updateLogo","_updateCompact"],this)}onAdd(f){this._map=f,this._container=C("div","mapboxgl-ctrl");const y=C("a","mapboxgl-ctrl-logo");return y.target="_blank",y.rel="noopener nofollow",y.href="https://www.mapbox.com/",y.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),y.setAttribute("rel","noopener nofollow"),this._container.appendChild(y),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact)}getDefaultPosition(){return"bottom-left"}_updateLogo(f){f&&f.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const f=this._map.style._sourceCaches;if(Object.entries(f).length===0)return!0;for(const y in f){const w=f[y].getSource();if(Object.hasOwn(w,"mapbox_logo")&&!w.mapbox_logo)return!1}return!0}_updateCompact(){const f=this._container.children;if(f.length){const y=f[0];this._map.getCanvasContainer().offsetWidth<250?y.classList.add("mapboxgl-compact"):y.classList.remove("mapboxgl-compact")}}}class wc{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(f){const y=++this._id;return this._queue.push({callback:f,id:y,cancelled:!1}),y}remove(f){const y=this._currentlyRunning,w=y?this._queue.concat(y):this._queue;for(const k of w)if(k.id===f)return void(k.cancelled=!0)}run(f=0){const y=this._currentlyRunning=this._queue;this._queue=[];for(const w of y)if(!w.cancelled&&(w.callback(f),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class yR{constructor(f){this.jumpTo(f)}getValue(f){if(f<=this._startTime)return this._start;if(f>=this._endTime)return this._end;const y=l.c5((f-this._startTime)/(this._endTime-this._startTime));return this._start*(1-y)+this._end*y}isEasing(f){return f>=this._startTime&&f<=this._endTime}jumpTo(f){this._startTime=-1/0,this._endTime=-1/0,this._start=f,this._end=f}easeTo(f,y,w){this._start=this.getValue(y),this._end=f,this._startTime=y,this._endTime=y+w}}const bf={"AttributionControl.ToggleAttribution":"Toggle attribution","FullscreenControl.Enter":"Enter fullscreen","FullscreenControl.Exit":"Exit fullscreen","GeolocateControl.FindMyLocation":"Find my location","GeolocateControl.LocationNotAvailable":"Location not available","LogoControl.Title":"Mapbox homepage","Map.Title":"Map","NavigationControl.ResetBearing":"Reset bearing to north","NavigationControl.ZoomIn":"Zoom in","NavigationControl.ZoomOut":"Zoom out","ScrollZoomBlocker.CtrlMessage":"Use ctrl + scroll to zoom the map","ScrollZoomBlocker.CmdMessage":"Use ⌘ + scroll to zoom the map","TouchPanBlocker.Message":"Use two fingers to move the map"};class W2 extends l.i{constructor(f,y,w,k){const{point:R,lngLat:M,originalEvent:z,target:V}=f;super(f.type,{point:R,lngLat:M,originalEvent:z,target:V}),this.preventDefault=()=>{f.preventDefault()},this.id=y,this.interaction=w,this.feature=k}}class Wc{constructor(f){this.map=f,this.interactionsByType=new Map,this.delegatedInteractions=new Map,this.typeById=new Map,this.filters=new Map,this.handleType=this.handleType.bind(this),this.handleMove=this.handleMove.bind(this),this.handleOut=this.handleOut.bind(this),this.hoveredFeatures=new Map,this.prevHoveredFeatures=new Map}add(f,y){if(this.typeById.has(f))throw new Error(`Interaction id "${f}" already exists.`);const w=y.filter;let k=y.type;w&&this.filters.set(f,l.bH(w)),k==="mouseover"&&(k="mouseenter"),k==="mouseout"&&(k="mouseleave");const R=this.interactionsByType.get(k)||new Map;k==="mouseenter"||k==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(f,y)):R.size===0&&this.map.on(k,this.handleType),R.size===0&&this.interactionsByType.set(k,R),R.set(f,y),this.typeById.set(f,k)}get(f){const y=this.typeById.get(f);if(!y)return;const w=this.interactionsByType.get(y);return w?w.get(f):void 0}remove(f){const y=this.typeById.get(f);if(!y)return;this.typeById.delete(f),this.filters.delete(f);const w=this.interactionsByType.get(y);w&&(w.delete(f),y==="mouseenter"||y==="mouseleave"?(this.delegatedInteractions.delete(f),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):w.size===0&&this.map.off(y,this.handleType))}queryTargets(f,y){const w=[];for(const[k,R]of y)R.target&&w.push({targetId:k,target:R.target,filter:this.filters.get(k)});return this.map.style.queryRenderedTargets(f,w,this.map.transform)}handleMove(f){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const y=this.queryTargets(f.point,Array.from(this.delegatedInteractions).reverse());y.length&&(f.type="mouseenter",this.handleType(f,y));const w=new Map;for(const[k,{feature:R}]of this.prevHoveredFeatures)this.hoveredFeatures.has(k)||w.set(R.id,R);w.size&&(f.type="mouseleave",this.handleType(f,Array.from(w.values())))}handleOut(f){const y=Array.from(this.hoveredFeatures.values()).map(({feature:w})=>w);y.length&&(f.type="mouseleave",this.handleType(f,y)),this.hoveredFeatures.clear()}handleType(f,y){const w=f.type==="mouseenter";if(w&&!this.interactionsByType.has(f.type))return void l.w("mouseenter interaction required for mouseleave to work.");const k=Array.from(this.interactionsByType.get(f.type)).reverse(),R=!!y;y=y||this.queryTargets(f.point,k);let M=!1;const z=new Set;for(const V of y){for(const[H,Y]of k){if(!Y.target)continue;const te=V.variants?V.variants[H]:null;if(te){for(const ne of te){if(u2(ne,V,z,H))continue;const le=new l.dU(V,ne),me=Cx(ne,V,H);R&&le.id!==void 0&&(le.state=this.map.getFeatureState(le));const fe=w?this.prevHoveredFeatures.get(me):null,Se=new W2(f,H,Y,le),Me=fe?fe.stop:Y.handler(Se);if(w&&this.hoveredFeatures.set(me,{feature:V,stop:Me}),Me!==!1){M=!0;break}}if(M)break}}if(M)break}if(!M)for(const[V,H]of k){const{handler:Y,target:te}=H;if(!te&&Y(new W2(f,V,H,null))!==!1)break}}}function os(_,f){if(Array.isArray(_)&&Array.isArray(f)){const y=new Set(_),w=new Set(f);return y.size===w.size&&_.every(k=>w.has(k))}return l.Y(_,f)}const K2=/matrix.*\((.+)\)/,xR={center:[0,0],zoom:0,bearing:0,pitch:0,minZoom:-2,maxZoom:22,minPitch:0,maxPitch:85,interactive:!0,scrollZoom:!0,boxZoom:!0,dragRotate:!0,dragPan:!0,keyboard:!0,doubleClickZoom:!0,touchZoomRotate:!0,touchPitch:!0,cooperativeGestures:!1,performanceMetricsCollection:!0,bearingSnap:7,clickTolerance:3,pitchWithRotate:!0,hash:!1,attributionControl:!0,antialias:!1,failIfMajorPerformanceCaveat:!1,preserveDrawingBuffer:!1,trackResize:!0,renderWorldCopies:!0,refreshExpiredTiles:!0,minTileCacheSize:null,maxTileCacheSize:null,localIdeographFontFamily:"sans-serif",localFontFamily:null,fontstackCompositing:"client",transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1,precompilePrograms:!0,scaleFactor:1,emissiveColorPrecision:"approximate"},Y2={showCompass:!0,showZoom:!0,visualizePitch:!1};class cz{constructor(f,y,w=!1){this._clickTolerance=10,this.element=y,this.mouseRotate=new fR({clickTolerance:f.dragRotate._mouseRotate._clickTolerance}),this.map=f,w&&(this.mousePitch=new mR({clickTolerance:f.dragRotate._mousePitch._clickTolerance})),l.b4(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),y.addEventListener("mousedown",this.mousedown),y.addEventListener("touchstart",this.touchstart,{passive:!1}),y.addEventListener("touchmove",this.touchmove),y.addEventListener("touchend",this.touchend),y.addEventListener("touchcancel",this.reset)}down(f,y){this.mouseRotate.mousedown(f,y),this.mousePitch&&this.mousePitch.mousedown(f,y),G()}move(f,y){const w=this.map,k=this.mouseRotate.mousemoveWindow(f,y),R=k&&k.bearingDelta;if(R&&w.setBearing(w.getBearing()+R),this.mousePitch){const M=this.mousePitch.mousemoveWindow(f,y),z=M&&M.pitchDelta;z&&w.setPitch(w.getPitch()+z)}}off(){const f=this.element;f.removeEventListener("mousedown",this.mousedown),f.removeEventListener("touchstart",this.touchstart),f.removeEventListener("touchmove",this.touchmove),f.removeEventListener("touchend",this.touchend),f.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){W(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(f){this.down({...f,button:f.button,type:f.type,ctrlKey:!0,preventDefault:()=>f.preventDefault()},ee(this.element,f)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(f){this.move(f,ee(this.element,f))}mouseup(f){this.mouseRotate.mouseupWindow(f),this.mousePitch&&this.mousePitch.mouseupWindow(f),this.offTemp()}touchstart(f){f.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=ie(this.element,f.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>f.preventDefault()},this._startPos))}touchmove(f){f.targetTouches.length!==1?this.reset():(this._lastPos=ie(this.element,f.targetTouches)[0],this.move({buttons:1,preventDefault:()=>f.preventDefault()},this._lastPos))}touchend(f){f.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)y.width||f.y>y.height;y.locationPoint3D(w).distSqr(f)180;){const w=y.locationPoint3D(_);if(w.x>=0&&w.y>=0&&w.x<=y.width&&w.y<=y.height)break;_.lng>y.center.lng?_.lng-=360:_.lng+=360}return _}const F1={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"},uz=/\s+/,xd={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Ch extends l.E{constructor(f,y){super(),(f instanceof HTMLElement||y)&&(f={element:f,...y}),l.b4(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:w="center",color:k="#3FB1CE",scale:R=1,draggable:M=!1,clickTolerance:z=0,rotation:V=xd.rotation,rotationAlignment:H=xd.rotationAlignment,pitchAlignment:Y=xd.pitchAlignment,occludedOpacity:te=xd.occludedOpacity,altitude:ne=xd.altitude}=f||{};this._anchor=w,this._color=k,this._scale=R,this._draggable=M,this._clickTolerance=z,this._rotation=V,this._rotationAlignment=H,this._pitchAlignment=Y,this._occludedOpacity=te,this._altitude=ne,this._state="inactive",this._isDragging=!1,this._pointerEvents=null,this._updateMoving=()=>this._update(!0),f&&f.element?(this._element=f.element,this._offset=l.P.convert(f&&f.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=l.P.convert(f&&f.offset||[0,-14])),this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label","Map marker"),this._element.hasAttribute("role")||this._element.setAttribute("role","img"),this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",me=>{me.preventDefault()}),this._element.addEventListener("mousedown",me=>{me.preventDefault()});const le=this._element.classList;for(const me in F1)le.remove(`mapboxgl-marker-anchor-${me}`);le.add(`mapboxgl-marker-anchor-${this._anchor}`),f&&f.className&&le.add(...f.className.trim().split(uz)),this._popup=null}_createDefaultMarker(){const f=C("div"),y=L("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},f);this._svgElement=y;const w=L("radialGradient",{id:"shadowGradient"},L("defs",{},y));L("stop",{offset:"10%","stop-opacity":.4},w),L("stop",{offset:"100%","stop-opacity":.05},w);const k=L("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"});return this._shadowElement=k,this._altitude===0&&y.insertBefore(k,y.firstChild),L("path",{fill:this._color,d:"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z"},y),L("path",{opacity:.25,d:"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z"},y),L("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},y),f}addTo(f){return f===this._map||(this.remove(),this._map=f,f.getCanvasContainer().appendChild(this._element),f.on("move",this._updateMoving),f.on("moveend",this._update),f.on("remove",this._clearFadeTimer),f._addMarker(this),this.setDraggable(this._draggable),this._update(),f.on("click",this._onMapClick)),this}remove(){const f=this._map;return f&&(f.off("click",this._onMapClick),f.off("move",this._updateMoving),f.off("moveend",this._update),f.off("mousedown",this._addDragHandler),f.off("touchstart",this._addDragHandler),f.off("mouseup",this._onUp),f.off("touchend",this._onUp),f.off("mousemove",this._onMove),f.off("touchmove",this._onMove),f.off("remove",this._clearFadeTimer),f._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(f){return this._lngLat=l.cJ.convert(f),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(f){if(f===this._altitude)return this;const y=this._altitude;return this._altitude=f||xd.altitude,this._defaultMarker&&y===0!=(this._altitude===0)&&(this._altitude===0?this._svgElement.insertBefore(this._shadowElement,this._svgElement.firstChild):this._shadowElement.remove()),this._update(),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(f){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeAttribute("role"),this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),f){if(!("offset"in f.options)){const k=Math.sqrt(Math.pow(13.5,2)/2);f.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[k,-1*(38.1-13.5+k)],"bottom-right":[-k,-1*(38.1-13.5+k)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=f,f._marker=this,f._altitude=this._altitude,this._lngLat&&this._popup.setLngLat(this._lngLat),this._element.setAttribute("role","button"),this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress),this._element.setAttribute("aria-expanded","false")}return this}_onKeyPress(f){const y=f.code,w=f.charCode||f.keyCode;y!=="Space"&&y!=="Enter"&&w!==32&&w!==13||this.togglePopup()}_onMapClick(f){const y=f.originalEvent.target,w=this._element;this._popup&&(y===w||w.contains(y))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const f=this._popup;return f?(f.isOpen()?(f.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(f.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const f=this._map,y=this._pos;if(!f||!y)return!1;const w=f.unproject(y,this._altitude),k=f.getFreeCameraOptions();if(!k.position)return!1;const R=k.position.toLngLat();return R.distanceTo(w)<.9*R.distanceTo(this._lngLat)}_evaluateOpacity(){const f=this._map;if(!f)return;const y=this._pos;if(!y||y.x<0||y.x>f.transform.width||y.y<0||y.y>f.transform.height)return void this._clearFadeTimer();const w=f.unproject(y,this._altitude);let k;f._showingGlobe()&&l.fd(f.transform,this._lngLat)?k=0:(k=1-f._queryFogOpacity(w),f.transform._terrainEnabled()&&f.style&&f.style.hasTerrain()&&this._behindTerrain()&&(k*=this._occludedOpacity)),this._element.style.opacity=`${k}`;const R=this._element.style.pointerEvents;(this._pointerEvents===null?R==="":R===this._pointerEvents)&&(this._pointerEvents=k>0?"auto":"none",this._element.style.pointerEvents=this._pointerEvents),this._popup&&this._popup._setOpacity(k),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const f=this._pos;if(!f||!this._map)return;const y=this._offset.mult(this._scale);this._element.style.transform=` translate(${f.x}px,${f.y}px) ${F1[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${y.x}px,${y.y}px) `}_calculateXYTransform(){const f=this._pos,y=this._map,w=this.getPitchAlignment();if(!y||!f||w!=="map")return"";if(!y._showingGlobe()){const V=y.getPitch();return V?`rotateX(${V}deg)`:""}const k=l.fe(l.ff(y.transform,this._lngLat)),R=f.sub(l.fg(y.transform)),M=Math.abs(R.x)+Math.abs(R.y);if(M===0)return"";const z=k/M;return`rotateX(${-R.y*z}deg) rotateY(${R.x*z}deg)`}_calculateZTransform(){const f=this._pos,y=this._map;if(!y||!f)return"";let w=0;const k=this.getRotationAlignment();if(k==="map")if(y._showingGlobe()){const R=y.project(new l.cJ(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),M=y.project(new l.cJ(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(R);w=l.fe(Math.atan2(M.y,M.x))-90}else w=-y.getBearing();else if(k==="horizon"){const R=l.ax(4,6,y.getZoom()),M=l.fg(y.transform);M.y+=R*y.transform.height;const z=f.sub(M),V=l.fe(Math.atan2(z.y,z.x));w=(V>90?V-270:V+90)*(1-R)}return w+=this._rotation,w?`rotateZ(${w}deg)`:""}_update(f){cancelAnimationFrame(this._updateFrameId);const y=this._map;y&&(y.transform.renderWorldCopies&&(this._lngLat=O1(this._lngLat,this._pos,y.transform)),this._pos=y.project(this._lngLat,this._altitude),f===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),y._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(y._showingGlobe()||y.style&&y.style.hasTerrain()||y.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(f){return this._offset=l.P.convert(f),this._update(),this}addClassName(f){return this._element.classList.add(f),this}removeClassName(f){return this._element.classList.remove(f),this}toggleClassName(f){return this._element.classList.toggle(f)}_onMove(f){const y=this._map;if(!y)return;const w=this._pointerdownPos,k=this._positionDelta;if(w&&k){if(!this._isDragging){const R=this._clickTolerance||y._clickTolerance;if(f.point.dist(w)`mapboxgl-ctrl-geolocate-${_}`,B0=["waiting","active","active-error","background","background-error"].map(B1),Gx={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0,showUserHeading:!1,showButton:!0,followUserLocation:!0},ls={maxWidth:100,unit:"metric"},Gn={kilometer:"km",meter:"m",mile:"mi",foot:"ft","nautical-mile":"nm"},_R=/\s+/,mm={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",altitude:0},z0=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function z1(_=new l.P(0,0),f="bottom"){if(typeof _=="number"){const y=Math.round(Math.sqrt(.5*Math.pow(_,2)));switch(f){case"top":return new l.P(0,_);case"top-left":return new l.P(y,y);case"top-right":return new l.P(-y,y);case"bottom":return new l.P(0,-_);case"bottom-left":return new l.P(y,-y);case"bottom-right":return new l.P(-y,-y);case"left":return new l.P(_,0);case"right":return new l.P(-_,0)}return new l.P(0,0)}return _ instanceof l.P||Array.isArray(_)?l.P.convert(_):l.P.convert(_[f]||[0,0])}const Hu=typeof document<"u"?document.currentScript:null;return l.fh(Hu&&Hu.src&&l.fi(Hu.src)?"cdn":"other"),{version:l.fa,supported:function(_){return!function(f){return typeof window<"u"&&typeof document<"u"?Object.hasOwn?typeof Worker>"u"?"Web Workers not supported":function(){const y=document.createElement("canvas");y.width=y.height=1;const w=y.getContext("2d");return!!w&&w.getImageData(0,0,1,1).width===y.width}()?function(y){return y?(E===void 0&&(E=T(!0)),E):(v===void 0&&(v=T(!1)),v)}(f)?"":"insufficient WebGL2 support":"insufficient Canvas/getImageData support":"Object.hasOwn not supported":"not a browser"}(_)},setSdkInfo:l.fl,addTileProvider:l.fk,Map:class extends Qd{constructor(_){l.eX.mark(l.fb.create);const f=_;if((_={...xR,..._}).minZoom!=null&&_.maxZoom!=null&&_.minZoom>_.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(_.minPitch!=null&&_.maxPitch!=null&&_.minPitch>_.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(_.minPitch!=null&&_.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(_.maxPitch!=null&&_.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");super(new l.eY(_.minZoom,_.maxZoom,_.minPitch,_.maxPitch,_.renderWorldCopies,null,null),_),this._animationFrameProvider=_.animationFrameProvider,this._repaint=!!_.repaint,this._interactive=_.interactive,this._minTileCacheSize=_.minTileCacheSize,this._maxTileCacheSize=_.maxTileCacheSize,this._failIfMajorPerformanceCaveat=_.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=_.preserveDrawingBuffer,this._antialias=_.antialias,this._trackResize=_.trackResize,this._bearingSnap=_.bearingSnap,this._refreshExpiredTiles=_.refreshExpiredTiles,this._fadeDuration=_.fadeDuration,this._placementAlgorithm=_.placementAlgorithm||"default",this._staticMode=!1,this._isInitialLoad=!0,this._crossSourceCollisions=_.crossSourceCollisions,this._collectResourceTiming=_.collectResourceTiming,this._language=this._parseLanguage(_.language),this._worldview=_.worldview,this._renderTaskQueue=new wc,this._domRenderTaskQueue=new wc,this._controls=[],this._markers=[],this._popups=[],this._mapId=l.aG(),this._locale={...bf,..._.locale},this._clickTolerance=_.clickTolerance,this._cooperativeGestures=_.cooperativeGestures,this._performanceMetricsCollection=_.performanceMetricsCollection,this._tessellationStep=_.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=_.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new yR(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._emissiveColorPrecision=_.emissiveColorPrecision,this._scaleFactor=_.scaleFactor,this._requestManager=new l.eZ(_.transformRequest,_.accessToken,_.testMode);const y=l.e_(_.accessToken||l.t.ACCESS_TOKEN);if(y&&"atlas"in y&&typeof y.atlas=="number"&&(this._tokenExpiration=y.atlas),this._silenceAuthErrors=!!_.testMode,this._contextCreateOptions=_.contextCreateOptions?{..._.contextCreateOptions}:{},typeof _.container=="string"){const w=document.getElementById(_.container);if(!w)throw new Error(`Container '${_.container.toString()}' not found.`);this._container=w}else{if(!(_.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=_.container}if(this._container.childNodes.length>0&&l.w("The map container element should be empty, otherwise the map's interactivity will be negatively impacted. If you want to display a message when WebGL is not supported, use the Mapbox GL Supported plugin instead."),_.maxBounds&&this.setMaxBounds(_.maxBounds),this._spriteFormat="auto",l.b4(["_onWindowOnline","_onWindowResize","_onVisibilityChange","_onMapScroll","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),this.painter===void 0)throw new Error("Failed to initialize WebGL.");if(this.on("move",()=>this._update(!1)),this.on("moveend",()=>this._update(!1)),this.on("zoom",()=>this._update(!0)),this._fullscreenchangeEvent="onfullscreenchange"in document?"fullscreenchange":"webkitfullscreenchange",window.addEventListener("online",this._onWindowOnline,!1),window.addEventListener("resize",this._onWindowResize,!1),window.addEventListener("orientationchange",this._onWindowResize,!1),window.addEventListener(this._fullscreenchangeEvent,this._onWindowResize,!1),window.addEventListener("visibilitychange",this._onVisibilityChange,!1),this.handlers=new H2(this,_),this._localFontFamily=_.localFontFamily,this._localIdeographFontFamily=_.localIdeographFontFamily,this._fontstackCompositing=_.fontstackCompositing,(_.style||!_.testMode)&&this.setStyle(_.style||l.t.DEFAULT_STYLE,{config:_.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,fontstackCompositing:this._fontstackCompositing}),_.projection&&this.setProjection(_.projection),_.hash&&(this._hash=new M2(typeof _.hash=="string"&&_.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){f.center==null&&f.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:_.center,zoom:_.zoom,bearing:_.bearing,pitch:_.pitch});const w=_.bounds;w&&(this.resize(),this.fitBounds(w,{..._.fitBoundsOptions,duration:0}))}this.resize(),_.attributionControl&&this.addControl(new ks({customAttribution:_.customAttribution})),this._logoControl=new M1,this.addControl(this._logoControl,_.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",w=>{this._update(w.dataType==="style"),this.fire(new l.i(`${w.dataType}data`,w))}),this.on("dataloading",w=>{this.fire(new l.i(`${w.dataType}dataloading`,w))}),this._interactions=new Wc(this)}_getMapId(){return this._mapId}addControl(_,f){let y,w;if(typeof f=="string"?y=f:f&&(y=f.position,w=f.offset),y===void 0&&(y=_.getDefaultPosition?_.getDefaultPosition():"top-right"),!_||!_.onAdd)return this.fire(new l.h(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const k=_.onAdd(this);this._controls.push(_),function(M,z,V){const H=V&&V.x!==void 0?`${Math.max(0,V.x)}px`:"",Y=V&&V.y!==void 0?`${Math.max(0,V.y)}px`:"";M.style.marginLeft=z.includes("left")?H:"",M.style.marginRight=z.includes("right")?H:"",M.style.marginTop=z.includes("top")?Y:"",M.style.marginBottom=z.includes("bottom")?Y:""}(k,y,w);const R=this._controlPositions[y];return y.includes("bottom")?R.insertBefore(k,R.firstChild):R.appendChild(k),this}removeControl(_){if(!_||!_.onRemove)return this.fire(new l.h(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const f=this._controls.indexOf(_);return f>-1&&this._controls.splice(f,1),_.onRemove(this),this}hasControl(_){return this._controls.includes(_)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(_){if(this._updateContainerDimensions(),this._containerWidth===this.transform.width&&this._containerHeight===this.transform.height)return this;this._resizeCanvas(this._containerWidth,this._containerHeight),this.transform.resize(this._containerWidth,this._containerHeight),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight));const f=!this._moving;return f&&this.fire(new l.i("movestart",_)).fire(new l.i("move",_)),this.fire(new l.i("resize",_)),f&&this.fire(new l.i("moveend",_)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(_){return this.transform.setMaxBounds(l.eN.convert(_)),this._update()}setMinZoom(_){if((_=_??-2)>=-2&&_<=this.transform.maxZoom)return this.transform.minZoom=_,this._update(),this.getZoom()<_?this.setZoom(_):this.fire(new l.i("zoomstart")).fire(new l.i("zoom")).fire(new l.i("zoomend")),this;throw new Error("minZoom must be between -2 and the current maxZoom, inclusive")}getMinZoom(){return this.transform.minZoom}setMaxZoom(_){if((_=_??22)>=this.transform.minZoom)return this.transform.maxZoom=_,this._update(),this.getZoom()>_?this.setZoom(_):this.fire(new l.i("zoomstart")).fire(new l.i("zoom")).fire(new l.i("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(_){if((_=_??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(_>=0&&_<=this.transform.maxPitch)return this.transform.minPitch=_,this._update(),this.getPitch()<_?this.setPitch(_):this.fire(new l.i("pitchstart")).fire(new l.i("pitch")).fire(new l.i("pitchend")),this;throw new Error("minPitch must be between 0 and the current maxPitch, inclusive")}getMinPitch(){return this.transform.minPitch}setMaxPitch(_){if((_=_??85)>85)throw new Error("maxPitch must be less than or equal to 85");if(_>=this.transform.minPitch)return this.transform.maxPitch=_,this._update(),this.getPitch()>_?this.setPitch(_):this.fire(new l.i("pitchstart")).fire(new l.i("pitch")).fire(new l.i("pitchend")),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(_){return this._scaleFactor=_,this.painter.scaleFactor=_,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(f=>f.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(_){return this.transform.renderWorldCopies=_,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(_){return _==="auto"?navigator.language:Array.isArray(_)?_.length===0?void 0:_.map(f=>f==="auto"?navigator.language:f):_}setLanguage(_){const f=this._parseLanguage(_);if(!this.style||f===this._language)return this;this._language=f,this.style.reloadSources();for(const y of this._controls)y._setLanguage&&y._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(_){return this.style&&_!==this._worldview?(this._worldview=_,this._styleDirty=!0,this.style.setWorldview(_),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(_){return this._lazyInitEmptyStyle(),_?typeof _=="string"&&(_={name:_}):_=null,this._useExplicitProjection=!!_,this._prioritizeAndUpdateProjection(_,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const _=this.transform,f=_.projection.name;let y;f==="globe"&&_.zoom>=l.bc?(_.setMercatorFromTransition(),y=!0):f==="mercator"&&_.zoom=l.bc?this.transform.setMercatorFromTransition():this.transform.setProjection(_),this.style.applyProjectionUpdate();const w=this.transform.getProjection().name==="mercator"&&y!==this.transform.mercatorFromTransition;return(f||w)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(_,f){return this.transform.locationPoint3D(l.cJ.convert(_),f)}unproject(_,f){return this.transform.pointLocation3D(l.P.convert(_),f)}isMoving(){return this._moving||this.handlers&&this.handlers.isMoving()||!1}isZooming(){return this._zooming||this.handlers&&this.handlers.isZooming()||!1}isRotating(){return this._rotating||this.handlers&&this.handlers.isRotating()||!1}_isDragging(){return this.handlers&&this.handlers._isDragging()||!1}_createDelegatedListener(_,f,y){const w=k=>{let R=[];if(Array.isArray(f)){const M=f.filter(z=>this.getLayer(z));R=M.length?this.queryRenderedFeatures(k,{layers:M}):[]}else R=this.queryRenderedFeatures(k,{target:f});return R};if(_==="mouseenter"||_==="mouseover"){let k=!1;return{listener:y,targets:f,delegates:{mousemove:M=>{const z=w(M.point);z.length?k||(k=!0,y.call(this,new Gu(_,this,M.originalEvent,{features:z}))):k=!1},mouseout:()=>{k=!1}}}}if(_==="mouseleave"||_==="mouseout"){let k=!1;return{listener:y,targets:f,delegates:{mousemove:z=>{w(z.point).length?k=!0:k&&(k=!1,y.call(this,new Gu(_,this,z.originalEvent)))},mouseout:z=>{k&&(k=!1,y.call(this,new Gu(_,this,z.originalEvent)))}}}}{const k=R=>{const M=w(R.point);M.length&&(R.features=M,y.call(this,R),delete R.features)};return{listener:y,targets:f,delegates:{[_]:k}}}}on(_,f,y){if(typeof f=="function"||y===void 0)return super.on(_,f);if(typeof f=="string"&&(f=[f]),!this._areTargetsValid(f))return this;const w=this._createDelegatedListener(_,f,y);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[_]=this._delegatedListeners[_]||[],this._delegatedListeners[_].push(w);for(const k in w.delegates)this.on(k,w.delegates[k]);return this}once(_,f,y){if(typeof f=="function"||y===void 0)return super.once(_,f);if(typeof f=="string"&&(f=[f]),!this._areTargetsValid(f))return this;const w=this._createDelegatedListener(_,f,y);for(const k in w.delegates)this.once(k,w.delegates[k]);return this}off(_,f,y){if(typeof f=="function"||y===void 0)return super.off(_,f);if(typeof f=="string"&&(f=[f]),!this._areTargetsValid(f))return this;const w=this._delegatedListeners?this._delegatedListeners[_]:void 0;return w&&(k=>{for(let R=0;R{if(y){const k=typeof y=="string"?y:y instanceof Error?y.message:y.error;l.w(`Unable to perform style diff: ${k}. Rebuilding the style from scratch.`),this._updateStyle(_,f)}else w&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=f.localIdeographFontFamily,this._localFontFamily=f.localFontFamily,this._fontstackCompositing=f.fontstackCompositing,this._updateStyle(_,f))}_getUIString(_){const f=this._locale[_];if(f==null)throw new Error(`Missing UI string '${_}'`);return f}_updateStyle(_,f){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),_){const y={...f};f&&f.config&&(y.initialConfig=f.config,delete y.config),this.style=new Mx(this,y).load(_),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new Mx(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():(l.w("There is no style added to the map."),!1)}_isValidId(_){return _==null?(this.fire(new l.h(new Error("IDs can't be empty."))),!1):l.dN(_)?(this.fire(new l.h(new Error(`IDs can't contain special symbols: "${_}".`))),!1):_!=="__proto__"&&_!=="constructor"&&_!=="prototype"||(this.fire(new l.h(new Error(`IDs can't be "${_}".`))),!1)}_isTargetValid(_){return"featuresetId"in _?this._isValidId("importId"in _?_.importId:_.featuresetId):"layerId"in _&&this._isValidId(_.layerId)}_areTargetsValid(_){if(Array.isArray(_)){for(const f of _)if(!this._isValidId(f))return!1;return!0}return this._isTargetValid(_)}addSource(_,f){return this._isValidId(_)?(this._lazyInitEmptyStyle(),this.style.addSource(_,f),this._update(!0)):this}isSourceLoaded(_){return!!this._isValidId(_)&&!!this.style&&this.style._isSourceCacheLoaded(_)}areTilesLoaded(){return this.style.areTilesLoaded()}removeSource(_){return this._isValidId(_)?(this.style.removeSource(_),this._updateTerrain(),this._update(!0)):this}getSource(_){return this._isValidId(_)?this.style.getOwnSource(_):null}addImage(_,f,{pixelRatio:y=1,sdf:w=!1,stretchX:k,stretchY:R,content:M}={}){this._lazyInitEmptyStyle();const z=l.I.from(_);if(f instanceof HTMLImageElement||ImageBitmap&&f instanceof ImageBitmap){const{width:V,height:H,data:Y}=l.e.getImageData(f);this.style.addImage(z,{data:new l.b({width:V,height:H},Y),pixelRatio:y,stretchX:k,stretchY:R,content:M,sdf:w,version:0,usvg:!1})}else if(f.width===void 0||f.height===void 0)this.fire(new l.h(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));else{const{width:V,height:H}=f,Y=f;this.style.addImage(z,{data:new l.b({width:V,height:H},new Uint8Array(Y.data)),pixelRatio:y,stretchX:k,stretchY:R,content:M,sdf:w,usvg:!1,version:0,userImage:Y}),Y.onAdd&&Y.onAdd(this,_)}}updateImage(_,f){this._lazyInitEmptyStyle();const y=l.I.from(_),w=this.style.getImage(y);if(!w)return void this.fire(new l.h(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const k=f instanceof HTMLImageElement||ImageBitmap&&f instanceof ImageBitmap?l.e.getImageData(f):f,{width:R,height:M,data:z}=k;if(R===void 0||M===void 0)return void this.fire(new l.h(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(R!==(w.usvg?w.icon.usvg_tree.width:w.data.width)||M!==(w.usvg?w.icon.usvg_tree.height:w.data.height))return void this.fire(new l.h(new Error(`The width and height of the updated image (${R}, ${M}) must be that same as the previous version of the image (${w.data.width}, ${w.data.height})`)));const V=!(f instanceof HTMLImageElement||ImageBitmap&&f instanceof ImageBitmap);let H=!1;w.usvg?(w.data=new l.b({width:R,height:M},new Uint8Array(z)),w.usvg=!1,w.icon=void 0,H=!0):w.data.replace(z,V),this.style.updateImage(y,w,H)}hasImage(_){return _?!!this.style&&!!this.style.getImage(l.I.from(_)):(this.fire(new l.h(new Error("Missing required image id"))),!1)}removeImage(_){this.style.removeImage(l.I.from(_))}loadImage(_,f){(async()=>{const y=await this._requestManager.transformRequest(_,l.R.Image),{data:w}=await l.a(y);return w})().then(y=>f(null,y)).catch(f)}listImages(){return this.style.listImages().map(_=>_.name)}addModel(_,f){this._lazyInitEmptyStyle(),this.style.addModel(_,f)}hasModel(_){return _?this.style.hasModel(_):(this.fire(new l.h(new Error("Missing required model id"))),!1)}removeModel(_){this.style.removeModel(_)}listModels(){return this.style.listModels()}addLayer(_,f){return this._isValidId(_.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(_,f),this._update(!0)):this}getSlot(_){const f=this.getLayer(_);return f&&f.slot||null}setSlot(_,f){return this.style.setSlot(_,f),this.style.mergeLayers(),this._update(!0)}addImport(_,f){return this._isValidId(_.id)?(this.style.addImport(_,f).catch(y=>this.fire(new l.h(new Error("Failed to add import",y)))),this):this}updateImport(_,f){return typeof f!="string"&&f.id!==_?(this.removeImport(_),this.addImport(f)):(this.style.updateImport(_,f),this._update(!0))}removeImport(_){const f=this.style._getRasterMaskUser(_,"import");return f?(this.fire(new l.h(new Error(`Import "${_}" cannot be removed while layer "${f}" uses it in "raster-mask-import".`))),this):(this.style.removeImport(_),this)}moveImport(_,f){return this.style.moveImport(_,f),this._update(!0)}moveLayer(_,f){return this._isValidId(_)?(this.style.moveLayer(_,f),this._update(!0)):this}removeLayer(_){if(!this._isValidId(_))return this;const f=this.style._getRasterMaskUser(_,"layer");return f?(this.fire(new l.h(new Error(`Layer "${_}" cannot be removed while layer "${f}" uses it in "raster-mask".`))),this):(this.style.removeLayer(_),this._update(!0))}getLayer(_){if(!this._isValidId(_))return null;const f=this.style.getOwnLayer(_);return f?f.type==="custom"?f.implementation:f.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(_,f,y){return this._isValidId(_)?(this.style.setLayerZoomRange(_,f,y),this._update(!0)):this}setFilter(_,f,y={}){return this._isValidId(_)?(this.style.setFilter(_,f,y),this._update(!0)):this}getFilter(_){return this._isValidId(_)?this.style.getFilter(_):null}setPaintProperty(_,f,y,w={}){return this._isValidId(_)?(this.style.setPaintProperty(_,f,y,w),this._update(!0)):this}getPaintProperty(_,f){return this._isValidId(_)?this.style.getPaintProperty(_,f):null}setLayoutProperty(_,f,y,w={}){return this._isValidId(_)?(this.style.setLayoutProperty(_,f,y,w),this._update(!0)):this}getLayoutProperty(_,f){return this._isValidId(_)?this.style.getLayoutProperty(_,f):null}getLayerProperty(_,f){return this._isValidId(_)?this.style.getLayerProperty(_,f):null}setLayerProperty(_,f,y,w={}){return this._isValidId(_)?(f==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(_,f,y,w),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(_){return this.style.setGlyphsUrl(_),this._update(!0)}getSchema(_){return this.style.getSchema(_)}setSchema(_,f){return this.style.setSchema(_,f),this._update(!0)}getConfig(_){return this.style.getConfig(_)}setConfig(_,f){return this.style.setConfig(_,f),this._update(!0)}getConfigProperty(_,f){return this.style.getConfigProperty(_,f)}setConfigProperty(_,f,y){return this.style.setConfigProperty(_,f,y),this._update(!0)}getFeaturesetDescriptors(_){return this.style.getFeaturesetDescriptors(_)}setLights(_){if(this._lazyInitEmptyStyle(),_&&_.length===1&&_[0].type==="flat"){const f=_[0];f.properties?this.style.setFlatLight(f.properties,f.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(_),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const _=this.style.getLights()||[];return _.length===0&&_.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),_}setLight(_,f={}){return console.log("The `map.setLight` function is deprecated, prefer using `map.setLights` with `flat` light type instead."),this.setLights([{id:"flat",type:"flat",properties:_}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(_){return this._lazyInitEmptyStyle(),!_&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(_),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(_){return this._lazyInitEmptyStyle(),this.style.setFog(_),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(_){return this._lazyInitEmptyStyle(),this.style.setSnow(_),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(_){return this._lazyInitEmptyStyle(),this.style.setRain(_),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(_){return this._lazyInitEmptyStyle(),this.style.setColorTheme(_),this._update(!0)}setImportColorTheme(_,f){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(_,f),this._update(!0)}setCamera(_){return this.style.setCamera(_),this._triggerCameraUpdate(_)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(_){const f=this.transform.nearClipOffset!==_;return this.transform.nearClipOffset=_,this._update(f)}_triggerCameraUpdate(_){return this._update(this.transform.setOrthographicProjectionAtLowPitch(_["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(_){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(l.cJ.convert(_),this.transform):0}setFeatureState(_,f){return _.source&&!this._isValidId(_.source)?this:(this.style.setFeatureState(_,f),this._update())}removeFeatureState(_,f){return _.source&&!this._isValidId(_.source)?this:(this.style.removeFeatureState(_,f),this._update())}getFeatureState(_){return _.source&&!this._isValidId(_.source)?null:this.style.getFeatureState(_)}resetFeatureStates(_){return this.style.resetFeatureStates(_),this._update()}_selectIndoorFloor(_){this.style.indoorManager&&this.style.indoorManager.selectFloor(_)}_setIndoorActiveFloorsVisibility(_){this.style.indoorManager&&this.style.indoorManager.setActiveFloorsVisibility(_)}getIndoorTileOptions(_,f){return this.style&&this.style.isIndoorEnabled()&&this.style.indoorManager?this.style.indoorManager.getIndoorTileOptions(_,f):null}_updateContainerDimensions(){if(!this._container)return;const _=this._container.getBoundingClientRect().width||400,f=this._container.getBoundingClientRect().height||300;let y,w,k,R=this._container;for(;R&&(!w||!k);){const M=window.getComputedStyle(R).transform;M&&M!=="none"&&(y=M.match(K2)[1].split(", "),y[0]&&y[0]!=="0"&&y[0]!=="1"&&(w=y[0]),y[3]&&y[3]!=="0"&&y[3]!=="1"&&(k=y[3])),R=R.parentElement}this._containerWidth=w?Math.abs(_/w):_,this._containerHeight=k?Math.abs(f/k):f}_detectMissingCSS(){window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")!=="rgb(250, 128, 114)"&&l.w("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.")}_setupContainer(){const _=this._container;_.classList.add("mapboxgl-map"),(this._missingCSSCanary=C("div","mapboxgl-canary",_)).style.visibility="hidden",this._detectMissingCSS();const f=this._canvasContainer=C("div","mapboxgl-canvas-container",_);this._canvas=C("canvas","mapboxgl-canvas",f),this._interactive&&(f.classList.add("mapboxgl-interactive"),this._canvas.setAttribute("tabindex","0")),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const y=this._controlContainer=C("div","mapboxgl-control-container",_),w=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(k=>{w[k]=C("div",`mapboxgl-ctrl-${k}`,y)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(_,f){const y=l.e.devicePixelRatio||1;this._canvas.width=y*Math.ceil(_),this._canvas.height=y*Math.ceil(f),this._canvas.style.width=`${_}px`,this._canvas.style.height=`${f}px`}_addMarker(_){this._markers.push(_)}_removeMarker(_){const f=this._markers.indexOf(_);f!==-1&&this._markers.splice(f,1)}_addPopup(_){this._popups.push(_)}_removePopup(_){const f=this._popups.indexOf(_);f!==-1&&this._popups.splice(f,1)}_setupPainter(){const _={...g,failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1},f=this._canvas.getContext("webgl2",_);f?(l.e$(f,!0),this.painter=new rz(f,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview,this._emissiveColorPrecision),this.on("data",y=>{if(y.dataType==="source"){const w=this.transform.elevation?this.transform.elevation._source():null;w&&y.sourceCacheId===w.id&&this.style&&this.style._setLabelPlacementStale(),this.style&&y.sourceCacheId&&this.style._buildingIndex.hasLayerForSourceCache(y.sourceCacheId)&&this.style._requestFullLabelPlacement(),this.painter.setTileLoadedFlag(!0)}})):this.fire(new l.h(new Error("Failed to initialize WebGL")))}_contextLost(_){_.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.style&&this.style.handleContextLost(),this.fire(new l.i("webglcontextlost",{originalEvent:_}))}_contextRestored(_){this._setupPainter(),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight)),this._updateTerrain(),this.style&&(this.style.clearLayers(),this.style.imageManager.destroyAtlasTextures(),this.style.imageManager.imageAtlasCache.clear(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new l.i("webglcontextrestored",{originalEvent:_}))}_onMapScroll(_){if(_.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1}idle(){return!this.isMoving()&&this.loaded()}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}frameReady(){return this.loaded()&&!this._placementDirty}_update(_){return this.style?(this._styleDirty=this._styleDirty||_,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(_){return this._update(),this._renderTaskQueue.add(_)}_cancelRenderFrame(_){this._renderTaskQueue.remove(_)}_requestDomTask(_){!this.loaded()||this.loaded()&&!this.isMoving()?_():this._domRenderTaskQueue.add(_)}_render(_){let f;this.fire(new l.i("renderstart")),++this._frameId;const y=this.painter.context.extTimerQuery,w=l.e.now(),k=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(f=k.createQuery(),k.beginQuery(y.TIME_ELAPSED_EXT,f)),this.painter.context.setDirty(),this.painter.setBaseState(),(this.isMoving()||this.isRotating()||this.isZooming())&&(this._interactionRange[0]=Math.min(this._interactionRange[0],performance.now()),this._interactionRange[1]=Math.max(this._interactionRange[1],performance.now())),this._renderTaskQueue.run(_),this._domRenderTaskQueue.run(_),this._removed)return;this._updateProjectionTransition();const R=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const V=this.transform.zoom,H=this.transform.pitch,Y=l.e.now(),te=new l.au(V,{now:Y,fadeDuration:R,pitch:H,transition:this._loaded?this.style.transition:{duration:0,delay:0},worldview:this._worldview});this.style.update(te)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let M=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),M=this._updateAverageElevation(w),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):M=this._updateAverageElevation(w),this.style){const V=this._staticMode&&!this.style.loaded();this._placementDirty=V||this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,R,this._crossSourceCollisions,this.painter.replacementSource,this._placementAlgorithm)}if(this.style&&this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:R,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming,paintStartTimeStamp:_}),this.fire(new l.i("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,l.eX.mark(l.fb.load),this.fire(new l.i("load"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&this.style.imageManager.hasPatternsInFlight()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),f){const V=l.e.now()-w;k.endQuery(y.TIME_ELAPSED_EXT),setTimeout(()=>{const H=k.getQueryParameter(f,k.QUERY_RESULT)/1e6;k.deleteQuery(f),this.fire(new l.i("gpu-timing-frame",{cpuTime:V,gpuTime:H}))},50)}if(this.listens("gpu-timing-layer")){const V=this.painter.collectGpuTimers();setTimeout(()=>{const H=this.painter.queryGpuTimers(V);this.fire(new l.i("gpu-timing-layer",{layerTimes:H}))},50)}if(this.listens("gpu-timing-deferred-render")){const V=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const H=this.painter.queryGpuTimeDeferredRender(V);this.fire(new l.i("gpu-timing-deferred-render",{gpuTime:H}))},50)}const z=this._sourcesDirty||this._styleDirty||this._placementDirty||M;if(z||this._repaint||this.style&&(this.style.snow||this.style.rain))this.triggerRepaint();else{const V=this.idle();if(V&&(M=this._updateAverageElevation(w,!0)),M)this.triggerRepaint();else{if(this._triggerFrame(!1),V&&(this.fire(new l.i("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const H=this._calculateSpeedIndex();this.fire(new l.i("speedindexcompleted",{speedIndex:H})),this.speedIndexTiming=!1}V&&this.style&&this.style.handleIdle()}}!this._loaded||this._fullyLoaded||z||(this._fullyLoaded=!0,l.eX.mark(l.fb.fullLoad),this._performanceMetricsCollection&&l.f0(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:this.painter.style.hasTerrain(),fogEnabled:!!this.painter.style.getFog(),projection:this.getProjection().name,zoom:this.transform.zoom,renderer:this.painter.context.renderer,vendor:this.painter.context.vendor}),this._authenticate())}_forceMarkerAndPopupUpdate(_){for(const f of this._markers)_&&!this.getRenderWorldCopies()&&(f._lngLat=f._lngLat.wrap()),f._update();for(const f of this._popups)!_||this.getRenderWorldCopies()||f._trackPointer||(f._lngLat=f._lngLat.wrap()),f._update()}_updateAverageElevation(_,f=!1){const y=k=>(this.transform.averageElevation=k,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&y(0);const w=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(w||(f||_-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(_)){const k=this.transform.averageElevation;let R=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(R)?R=0:this._averageElevationLastSampledAt=_;const M=Math.abs(k-R);if(M>1){if(this._isInitialLoad||w)return this._averageElevation.jumpTo(R),y(R);this._averageElevation.easeTo(R,_,300)}else if(M>1e-4)return this._averageElevation.jumpTo(R),y(R)}return!!this._averageElevation.isEasing(_)&&y(this._averageElevation.getValue(_))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const _=this.painter.context.gl;l.e$(_,!1),this._logoControl instanceof M1&&this._logoControl._updateLogo(),_&&_.clear(_.DEPTH_BUFFER_BIT|_.COLOR_BUFFER_BIT|_.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new l.h(new Error("A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/")))}_authenticate(){l.f1(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,_=>{_&&(_.message!==l.f2&&_.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),l.f3(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&l.f4(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&l.f5(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){l.f6(this._requestManager._customAccessToken)}_updateTerrain(){const _=this._isDragging();this.painter.updateTerrain(this.style,_)}_calculateSpeedIndex(){const _=this.painter.canvasCopy(),f=this.painter.getCanvasCopiesAndTimestamps();f.timeStamps.push(performance.now());const y=this.painter.context.gl,w=y.createFramebuffer();function k(R){y.framebufferTexture2D(y.FRAMEBUFFER,y.COLOR_ATTACHMENT0,y.TEXTURE_2D,R,0);const M=new Uint8Array(y.drawingBufferWidth*y.drawingBufferHeight*4);return y.readPixels(0,0,y.drawingBufferWidth,y.drawingBufferHeight,y.RGBA,y.UNSIGNED_BYTE,M),M}return y.bindFramebuffer(y.FRAMEBUFFER,w),this._canvasPixelComparison(k(_),f.canvasCopies.map(k),f.timeStamps)}_canvasPixelComparison(_,f,y){let w=y[1]-y[0];const k=_.length/4;for(let R=0;R{const R=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,R&&this._render(k)}));const y=k=>{const R=!!this._renderNextFrame;this._renderNextFrame=null;try{R&&this._render(k)}finally{this._frame=null}R&&!this._removed&&Promise.resolve().then(()=>this._triggerFrame(!1))};let w=null;this._frame={cancel:()=>{w!==null&&f.cancelAnimationFrame(w)}};try{w=f.requestAnimationFrame(y)}catch(k){throw this._frame=null,k}}_preloadTiles(_){const f=this.style?this.style.getSourceCaches():[];return l.u(f,(y,w)=>y._preloadTiles(_,w),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(_){this._trackResize&&this.resize({originalEvent:_})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(_){this._showTileBoundaries!==_&&(this._showTileBoundaries=_,_&&gc(),this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(_){this._showParseStatus!==_&&(this._showParseStatus=_,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(_){this._showTerrainWireframe!==_&&(this._showTerrainWireframe=_,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(_){this._showLayers2DWireframe!==_&&(this._showLayers2DWireframe=_,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(_){this._showLayers3DWireframe!==_&&(this._showLayers3DWireframe=_,this._update())}get showElevationIdDebug(){return!!this.painter&&this.painter._debugParams.showElevationIdDebug}set showElevationIdDebug(_){this.painter&&this.painter._debugParams.showElevationIdDebug!==_&&(this.painter._debugParams.showElevationIdDebug=_,this.style&&_?this.style._reloadSources():this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(_){this._speedIndexTiming!==_&&(this._speedIndexTiming=_,this._update())}get showPadding(){return!!this._showPadding}set showPadding(_){this._showPadding!==_&&(this._showPadding=_,_&&gc(),this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(_){this._showCollisionBoxes!==_&&(this._showCollisionBoxes=_,_&&gc(),this.style&&_?this.style._reloadSources():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(_){this._showOverdrawInspector!==_&&(this._showOverdrawInspector=_,this._update())}get repaint(){return!!this._repaint}set repaint(_){this._repaint!==_&&(this._repaint=_,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(_){this._vertices=_,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(_){this._showTileAABBs!==_&&(this._showTileAABBs=_,_&&this._update())}_setCacheLimits(_,f){l.fc(_,f)}get version(){return l.fa}},NavigationControl:class{constructor(_={}){this.options={...Y2,..._},this._container=C("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",f=>f.preventDefault()),this.options.showZoom&&(l.b4(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",f=>{this._map&&this._map.zoomIn({},{originalEvent:f})}),C("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",f=>{this._map&&this._map.zoomOut({},{originalEvent:f})}),C("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(l.b4(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",f=>{const y=this._map;y&&(this.options.visualizePitch?y.resetNorthPitch({},{originalEvent:f}):y.resetNorth({},{originalEvent:f}))}),this._compassIcon=C("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const _=this._map;if(!_)return;const f=_.getZoom(),y=f===_.getMaxZoom(),w=f===_.getMinZoom();this._zoomInButton.disabled=y,this._zoomOutButton.disabled=w,this._zoomInButton.setAttribute("aria-disabled",y.toString()),this._zoomOutButton.setAttribute("aria-disabled",w.toString())}_rotateCompassArrow(){const _=this._map;if(!_)return;const f=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(_.transform.pitch*(Math.PI/180)),.5)}) rotateX(${_.transform.pitch}deg) rotateZ(${_.transform.angle*(180/Math.PI)}deg)`:`rotate(${_.transform.angle*(180/Math.PI)}deg)`;_._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=f)})}onAdd(_){return this._map=_,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),_.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&_.on("pitch",this._rotateCompassArrow),_.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new cz(_,this._compass,this.options.visualizePitch)),this._container}onRemove(){const _=this._map;_&&(this._container.remove(),this.options.showZoom&&_.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&_.off("pitch",this._rotateCompassArrow),_.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(_,f){const y=C("button",_,this._container);return y.type="button",y.addEventListener("click",f),y}_setButtonTitle(_,f){if(!this._map)return;const y=this._map._getUIString(`NavigationControl.${f}`);_.setAttribute("aria-label",y),_.firstElementChild&&_.firstElementChild.setAttribute("title",y)}},GeolocateControl:class extends l.E{constructor(_={}){super();const f=navigator.geolocation;this.options={geolocation:f,...Gx,..._},l.b4(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=D2(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(_){return this._map=_,this._container=C("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._clearRequestTimeout(),this._geolocationWatchID!==void 0&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("zoom",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1}_checkGeolocationSupport(_){const f=(y=!!this.options.geolocation)=>{this._supportsGeolocation=y,_(y)};this._supportsGeolocation!==void 0?_(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(y=>f(y.state!=="denied")).catch(()=>f()):f()}_isOutOfMapMaxBounds(_){const f=this._map.getMaxBounds(),y=_.coords;return!!f&&(y.longitudef.getEast()||y.latitudef.getNorth())}_setWatchState(_){this._watchState=_;const f=this._geolocateButton.classList;f.remove(...B0);for(const y of Ph[_])f.add(B1(y))}_setButtonTitle(_){const f=this._map._getUIString(_);this._geolocateButton.setAttribute("aria-label",f),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",f)}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":this._setWatchState("ACTIVE_ERROR");break;case"BACKGROUND":this._setWatchState("BACKGROUND_ERROR")}}_onSuccess(_){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(_))return this._setErrorState(),this.fire(new l.i("outofmaxbounds",_)),this._updateMarker(),void this._finish();if(this._lastKnownPosition=_,this.options.trackUserLocation)switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._setWatchState(this.options.followUserLocation?"ACTIVE_LOCK":"BACKGROUND");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._setWatchState("BACKGROUND")}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(_),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(_),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new l.i("geolocate",{coords:_.coords,timestamp:_.timestamp,..._.toJSON?{toJSON:_.toJSON.bind(_)}:{}})),this._finish()}}_updateCamera(_){const f=new l.cJ(_.coords.longitude,_.coords.latitude),y=_.coords.accuracy,w={bearing:this._map.getBearing(),...this.options.fitBoundsOptions};this._map.fitBounds(f.toBounds(y),w,{geolocateSource:!0})}_updateMarker(_){if(_){const f=new l.cJ(_.coords.longitude,_.coords.latitude);this.options.showAccuracyCircle?this._accuracyCircleMarker.setLngLat(f).addTo(this._map):this._accuracyCircleMarker.remove(),this._userLocationDotMarker.setLngLat(f).addTo(this._map),this._accuracy=_.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const _=this._map.transform,f=l.ca(1,_._center.lat)*_.worldSize,y=Math.ceil(2*this._accuracy*f);this._circleElement.style.width=`${y}px`,this._circleElement.style.height=`${y}px`}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}_updateMarkerRotation(){this._userLocationDotMarker&&typeof this._heading=="number"?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName("mapboxgl-user-location-show-heading")):(this._userLocationDotMarker.removeClassName("mapboxgl-user-location-show-heading"),this._userLocationDotMarker.setRotation(0))}_onError(_){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(_.code===1)this._setWatchState("OFF"),this._geolocateButton.disabled=!0,this._setButtonTitle("GeolocateControl.LocationNotAvailable"),this._geolocationWatchID!==void 0&&this._clearWatch();else{if(_.code===3&&this._noTimeout)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new l.i("error",{code:_.code,message:_.message,PERMISSION_DENIED:_.PERMISSION_DENIED,POSITION_UNAVAILABLE:_.POSITION_UNAVAILABLE,TIMEOUT:_.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const _=this.options.positionOptions.timeout;_&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},_))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(_){this._map!==void 0&&(this._container.addEventListener("contextmenu",f=>f.preventDefault()),this._geolocateButton=C("button","mapboxgl-ctrl-geolocate",this._container),C("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",_===!1?(l.w("Geolocation support is not available so the GeolocateControl will be disabled."),this._geolocateButton.disabled=!0,this._setButtonTitle("GeolocateControl.LocationNotAvailable")):this._setButtonTitle("GeolocateControl.FindMyLocation"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._createUserLocationMarkers(),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.showButton||(this._container.style.display="none"),this.options.trackUserLocation&&this._map.on("movestart",f=>{f.geolocateSource||this._watchState!=="ACTIVE_LOCK"||f.originalEvent&&f.originalEvent.type==="resize"||(this._setWatchState("BACKGROUND"),this.fire(new l.i("trackuserlocationend")))}),this.fire(new l.i("ready")))}_onDeviceOrientation(_){this._userLocationDotMarker&&(_.webkitCompassHeading?this._heading=_.webkitCompassHeading:_.absolute===!0&&(this._heading=-1*_.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return l.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._setWatchState("WAITING_ACTIVE"),this.fire(new l.i("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._setWatchState("OFF"),this.fire(new l.i("trackuserlocationend"));break;case"BACKGROUND":this._setWatchState("ACTIVE_LOCK"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new l.i("trackuserlocationstart"))}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let _;this._geolocateButton.classList.add(B1("waiting")),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(_={maximumAge:6e5,timeout:0},this._noTimeout=!0):(_=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,_),this._startRequestTimeout(),this.options.showUserHeading&&this._addDeviceOrientationListener()}}else this.options.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._startRequestTimeout(),this._timeoutId=window.setTimeout(this._finish,1e4);return!0}setFollowUserLocation(_){return this.options.followUserLocation=_??Gx.followUserLocation,this.options.trackUserLocation&&this._watchState!=="OFF"&&(this.options.followUserLocation?this._watchState!=="BACKGROUND"&&this._watchState!=="BACKGROUND_ERROR"||(this._setWatchState("ACTIVE_LOCK"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new l.i("trackuserlocationstart"))):this._watchState!=="ACTIVE_LOCK"&&this._watchState!=="ACTIVE_ERROR"||(this._setWatchState("BACKGROUND"),this.fire(new l.i("trackuserlocationend")))),this}setShowAccuracyCircle(_){if(this.options.showAccuracyCircle=_??Gx.showAccuracyCircle,!this._accuracyCircleMarker)return this;if(this.options.showAccuracyCircle){if(this.options.showUserLocation&&this._lastKnownPosition){const{longitude:f,latitude:y,accuracy:w}=this._lastKnownPosition.coords;this._accuracy=w,this._accuracyCircleMarker.setLngLat(new l.cJ(f,y)).addTo(this._map),this._updateCircleRadius()}}else this._accuracyCircleMarker.remove();return this}setShowUserHeading(_){return this.options.showUserHeading=_??Gx.showUserHeading,this._setup?(this.options.showUserHeading?this._geolocationWatchID!==void 0&&this._addDeviceOrientationListener():(this._removeDeviceOrientationListener(),this._heading=void 0,this._userLocationDotMarker&&this._updateMarkerRotation()),this):this}setFitBoundsOptions(_){return this.options.fitBoundsOptions=_??Gx.fitBoundsOptions,this}setShowUserLocation(_){return this.options.showUserLocation=_??Gx.showUserLocation,this._setup?(this.options.showUserLocation?(this._userLocationDotMarker||(this._createUserLocationMarkers(),this._map.on("zoom",this._onZoom)),!this._lastKnownPosition||this._watchState!==void 0&&this._watchState==="OFF"||this._updateMarker(this._lastKnownPosition)):(this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this._accuracyCircleMarker&&this._accuracyCircleMarker.remove()),this):this}_addDeviceOrientationListener(){const _=()=>{const y="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(y,this._onDeviceOrientation)},f=DeviceOrientationEvent;typeof(f==null?void 0:f.requestPermission)=="function"?f.requestPermission().then(y=>{y==="granted"?_():l.w("GeolocateControl: permission to use device orientation was denied, so the user heading arrow will not be shown.")}).catch(()=>{l.w("GeolocateControl: could not request device orientation permission. Enable the user heading from a user gesture (click/tap) so the browser can prompt for access.")}):_()}_removeDeviceOrientationListener(){window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation)}_createUserLocationMarkers(){this._dotElement=C("div","mapboxgl-user-location"),this._dotElement.appendChild(C("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(C("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new Ch({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=C("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ch({element:this._circleElement,pitchAlignment:"map"})}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),this._removeDeviceOrientationListener(),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove(B1("waiting")),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:ks,ScaleControl:class{constructor(_={}){this.options={...ls,..._},l.b4(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const _=this.options.maxWidth||100,f=this._map,y=f._containerHeight/2,w=f._containerWidth/2-_/2,k=f.unproject([w,y]),R=f.unproject([w+_,y]),M=k.distanceTo(R);if(this.options.unit==="imperial"){const z=3.2808*M;z>5280?this._setScale(_,z/5280,"mile"):this._setScale(_,z,"foot")}else this.options.unit==="nautical"?this._setScale(_,M/1852,"nautical-mile"):M>=1e3?this._setScale(_,M/1e3,"kilometer"):this._setScale(_,M,"meter")}_setScale(_,f,y){this._map._requestDomTask(()=>{const w=function(R){const M=Math.pow(10,`${Math.floor(R)}`.length-1);let z=R/M;return z=z>=10?10:z>=5?5:z>=3?3:z>=2?2:z>=1?1:function(V){const H=Math.pow(10,Math.ceil(-Math.log(V)/Math.LN10));return Math.round(V*H)/H}(z),M*z}(f),k=w/f;this._container.innerHTML=y!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:y}).format(w):`${w} ${Gn[y]}`,this._container.style.width=_*k+"px"})}onAdd(_){return this._map=_,this._language=_.getLanguage(),this._container=C("div","mapboxgl-ctrl mapboxgl-ctrl-scale",_.getContainer()),this._container.dir="auto",this._map.on("move",this._update),this._update(),this._container}onRemove(){this._container.remove(),this._map.off("move",this._update),this._map=void 0}_setLanguage(_){this._language=_,this._update()}setUnit(_){this.options.unit=_,this._update()}},FullscreenControl:class{constructor(_={}){this._fullscreen=!1,_&&_.container&&(_.container instanceof HTMLElement?this._container=_.container:l.w("Full screen control 'container' must be a DOM element.")),l.b4(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(_){return this._map=_,this._container||(this._container=this._map.getContainer()),this._controlContainer=C("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",l.w("This device does not support fullscreen mode.")),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,document.removeEventListener(this._fullscreenchange,this._changeIcon)}_checkFullscreenSupport(){return!(!document.fullscreenEnabled&&!document.webkitFullscreenEnabled)}_setupUI(){const _=this._fullscreenButton=C("button","mapboxgl-ctrl-fullscreen",this._controlContainer);C("span","mapboxgl-ctrl-icon",_).setAttribute("aria-hidden","true"),_.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const _=this._getTitle();this._fullscreenButton.setAttribute("aria-label",_),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",_)}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_changeIcon(){(document.fullscreenElement||document.webkitFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle())}_onClickFullscreen(){this._isFullscreen()?document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen&&document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen()}},IndoorControl:class{constructor(){l.b4(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(_){return this._map=_,this._container=C("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._map.on("idle",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const _=this._map.style.indoorManager;_.off("selector-update",this._onIndoorUpdate),_.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(_.getControlState()),this._map.off("idle",this._onStyleData)}}_createButton(_,f){const y=C("button",_,this._container);return y.type="button",y.addEventListener("click",f),y}_setButtonTitle(_,f){_.setAttribute("aria-label",f),_.textContent=f}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.off("idle",this._onStyleData),this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(_){if(!_||!_.floors||_.floors.length===0)return this._model=_,void(this._container.style.display="none");const f=this._model;this._model=_,this._container.style.display="inline-block";const y=!f||f.floors.length!==_.floors.length||f.floors.some((w,k)=>w.id!==_.floors[k].id);if(y&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),_.selectedFloorId){if(_.selectedFloorId!==this._lastSelectedFloorId||y){const w=_.floors.findIndex(k=>k.id===_.selectedFloorId);if(w!==-1){const k=_.floors.length;let R,M;k<=5?(R=0,M=k-1):this._visibleFloorStart===0?(R=0,M=3):this._visibleFloorStart>=k-3?(R=k-3-1,M=k-1):(R=this._visibleFloorStart,M=this._visibleFloorStart+3-1),wM&&(this._visibleFloorStart=w-2)}}this._lastSelectedFloorId=_.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const _=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);C("span","mapboxgl-ctrl-icon",_).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||_.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(_);const f=this._model.floors,y=f.length;if(y<=5)return void f.forEach(M=>this._createFloorButton(M));const w=this._visibleFloorStart===0,k=this._visibleFloorStart>=y-3;if(w)this._createFloorButton(f[0]);else{const M=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);C("span","mapboxgl-ctrl-icon",M).setAttribute("aria-hidden","true"),this._container.appendChild(M)}let R=[];if(R=w?f.slice(1,4):k?f.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):f.slice(this._visibleFloorStart,this._visibleFloorStart+3),R.forEach(M=>this._createFloorButton(M)),k)this._createFloorButton(f[y-1]);else{const M=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);C("span","mapboxgl-ctrl-icon",M).setAttribute("aria-hidden","true"),this._container.appendChild(M)}}_createFloorButton(_){const f=this._createButton("mapboxgl-ctrl-level-button",()=>{const R=_.id;this._model&&this._model.selectedFloorId===R&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(R))}),y=(_.name||"").trim(),w=_.zIndex.toString(),k=y?Array.from(y).slice(0,3).join(""):w;this._setButtonTitle(f,k),this._model&&this._model.activeFloorsVisible&&_.id===this._model.selectedFloorId&&f.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(f)}_toggleIndoor(){this._map&&this._map.style&&this._map.style.indoorManager&&this._model&&this._model.activeFloorsVisible&&this._map.style.indoorManager.setActiveFloorsVisibility(!1)}_scrollUp(){if(this._visibleFloorStart>0){this._visibleFloorStart--,this._visibleFloorStart===1&&(this._visibleFloorStart=0);const _=this._model&&this._model.floors||[];if(_.length>3){const f=_.length-3;this._visibleFloorStart===f-1&&(this._visibleFloorStart=f-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const _=this._model.floors.length-3;this._visibleFloorStart<_&&(this._visibleFloorStart++,this._visibleFloorStart===1&&(this._visibleFloorStart=2),this._visibleFloorStart===_-1&&(this._visibleFloorStart=_),this._visibleFloorStart>_&&(this._visibleFloorStart=_),this._render())}}},Popup:class extends l.E{constructor(_){super(),this.options=Object.assign(Object.create(mm),_),this._altitude=this.options.altitude,l.b4(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(_&&_.className?_.className.trim().split(_R):[])}addTo(_){return this._map&&this.remove(),this._map=_,this.options.closeOnClick&&_.on("preclick",this._onClose),this.options.closeOnMove&&_.on("move",this._onClose),_.on("remove",this.remove),this._update(),_._addPopup(this),this._focusFirstElement(),this._trackPointer?(_.on("mousemove",this._onMouseEvent),_.on("mouseup",this._onMouseEvent),_._canvasContainer.classList.add("mapboxgl-track-pointer")):_.on("move",this._update),this.fire(new l.i("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const _=this._map;return _&&(_.off("move",this._update),_.off("move",this._onClose),_.off("preclick",this._onClose),_.off("click",this._onClose),_.off("remove",this.remove),_.off("mousemove",this._onMouseEvent),_.off("mouseup",this._onMouseEvent),_.off("drag",this._onMouseEvent),_._canvasContainer&&_._canvasContainer.classList.remove("mapboxgl-track-pointer"),_._removePopup(this),this._map=void 0),this.fire(new l.i("close")),this}getLngLat(){return this._lngLat}setLngLat(_){this._lngLat=l.cJ.convert(_),this._pos=null,this._trackPointer=!1,this._update();const f=this._map;return f&&(f.on("move",this._update),f.off("mousemove",this._onMouseEvent),f._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(_){return this._altitude=_,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const _=this._map;return _&&(_.off("move",this._update),_.on("mousemove",this._onMouseEvent),_.on("drag",this._onMouseEvent),_._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(_){return this.setDOMContent(document.createTextNode(_))}setHTML(_){const f=document.createDocumentFragment(),y=document.createElement("body");let w;for(y.innerHTML=_;w=y.firstChild,w;)f.appendChild(w);return this.setDOMContent(f)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(_){return this.options.maxWidth=_,this._update(),this}setDOMContent(_){let f=this._content;if(f)for(;f.hasChildNodes();)f.firstChild&&f.removeChild(f.firstChild);else f=this._content=C("div","mapboxgl-popup-content",this._container||void 0);if(f.appendChild(_),this.options.closeButton){const y=this._closeButton=C("button","mapboxgl-popup-close-button",f);y.type="button",y.setAttribute("aria-label","Close popup"),y.innerHTML='',y.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(_){return this._classList.add(_),this._updateClassList(),this}removeClassName(_){return this._classList.delete(_),this._updateClassList(),this}setOffset(_){return this.options.offset=_,this._update(),this}toggleClassName(_){let f;return this._classList.delete(_)?f=!1:(this._classList.add(_),f=!0),this._updateClassList(),f}_onMouseEvent(_){this._update(_.point)}_getAnchor(_){if(this.options.anchor)return this.options.anchor;const f=this._map,y=this._container,w=this._pos;if(!f||!y||!w)return"bottom";const k=y.offsetWidth,R=y.offsetHeight,M=w.xf.transform.width-k/2;if(w.y+_f.transform.height-R){if(M)return"bottom-left";if(z)return"bottom-right"}return M?"left":z?"right":"bottom"}_updateClassList(){const _=this._container;if(!_)return;const f=[...this._classList];f.push("mapboxgl-popup"),this._anchor&&f.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&f.push("mapboxgl-popup-track-pointer"),_.className=f.join(" ")}_update(_){const f=this._map,y=this._content;if(!f||!this._lngLat&&!this._trackPointer||!y)return;let w=this._container;if(w||(w=this._container=C("div","mapboxgl-popup",f.getContainer()),this._tip=C("div","mapboxgl-popup-tip",w),w.appendChild(y)),this.options.maxWidth&&w.style.maxWidth!==this.options.maxWidth&&(w.style.maxWidth=this.options.maxWidth),f.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=O1(this._lngLat,this._pos,f.transform)),!this._trackPointer||_){const k=this._pos=this._trackPointer&&_ instanceof l.P?_:f.project(this._lngLat,this._altitude),R=z1(this.options.offset),M=this._anchor=this._getAnchor(R.y),z=z1(this.options.offset,M),V=k.add(z).round();f._requestDomTask(()=>{this._container&&M&&(this._container.style.transform=`${F1[M]} translate(${V.x}px,${V.y}px)`)})}if(!this._marker&&f._showingGlobe()){const k=l.fd(f.transform,this._lngLat)?0:1;this._setOpacity(k)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const _=this._container.querySelector(z0);_&&_.focus()}_onClose(){this.remove()}_setOpacity(_){this._container&&(this._container.style.opacity=`${_}`),this._content&&(this._content.style.pointerEvents=_?"auto":"none")}},Marker:Ch,Style:Mx,LngLat:l.cJ,LngLatBounds:l.eN,Point:l.P,MercatorCoordinate:l.b$,FreeCameraOptions:l.fj,Evented:l.E,config:l.t,prewarm:function(){l1().acquire(wt)},clearPrewarmedResources:function(){const _=zg;_&&(_.isPreloaded()&&_.numActive()===1?(_.release(wt),zg=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},get accessToken(){return l.t.ACCESS_TOKEN},set accessToken(_){l.fv(_)},get baseApiUrl(){return l.t.API_URL},set baseApiUrl(_){l.fu(_)},get workerCount(){return St.workerCount},set workerCount(_){(function(f){St.workerCount=f})(_)},get maxParallelImageRequests(){return l.t.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(_){l.ft(_)},clearStorage(_){l.fs(_)},get workerUrl(){return rt.workerUrl},set workerUrl(_){rt.workerUrl=_},get workerClass(){return rt.workerClass},set workerClass(_){rt.workerClass=_},get dracoUrl(){return l.fr()},set dracoUrl(_){l.fq(_)},get meshoptUrl(){return l.fp()},set meshoptUrl(_){l.fo(_)},get buildingGenUrl(){return l.fn()},set buildingGenUrl(_){l.fm(_)},setNow:l.e.setNow,restoreNow:l.e.restoreNow}});var p=c;return p})})(CEe);var ynt=CEe.exports;const Rf=ea(ynt),Vle={coming_soon:"#3B82F6",office_exclusive:"#6366F1",temp_off_market:"#D97706",withdrawn:"#64748B",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},qle={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",temp_off_market:"Temporarily Off Market",withdrawn:"Withdrawn",pre_market:"Pre-Market",active:"Active",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"};function xnt(t){return t>=1e6?`$${(t/1e6).toFixed(1)}M`:`$${(t/1e3).toFixed(0)}K`}function _nt({listings:t,isLoading:e}){const r=qa(),n=N.useRef(null),i=N.useRef(null),a=N.useRef([]),[c,d]=N.useState(""),[p,l]=N.useState(!0);return N.useEffect(()=>{(async()=>{l(!0);try{const{data:E}=await Be.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();E!=null&&E.value&&d(E.value)}catch(E){console.error("Error fetching mapbox token:",E)}l(!1)})()},[]),N.useEffect(()=>{if(!n.current||!c||i.current)return;Rf.accessToken=c;const v=t.filter(j=>j.latitude!=null&&j.longitude!=null);let E=[-98.5795,39.8283],T=4;if(v.length>0){const j=v.reduce((C,L)=>C+L.longitude,0)/v.length,P=v.reduce((C,L)=>C+L.latitude,0)/v.length;E=[j,P],T=v.length===1?12:10}return i.current=new Rf.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:T,center:E}),i.current.addControl(new Rf.NavigationControl,"top-right"),()=>{var j;(j=i.current)==null||j.remove(),i.current=null}},[c]),N.useEffect(()=>{if(!i.current||!c)return;a.current.forEach(E=>E.remove()),a.current=[];const v=t.filter(E=>E.latitude!=null&&E.longitude!=null);if(v.forEach(E=>{var $,G,W;const T=Vle[E.status]||"#10B981",j=(($=E.photos)==null?void 0:$.find(Z=>Z.is_primary))||((G=E.photos)==null?void 0:G[0]),C=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${E.slug||E.id}`:`/public/listing/${E.slug||E.id}`,L=document.createElement("div");L.className="cursor-pointer",L.innerHTML=`
`;const O=new Rf.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${j!=null&&j.photo_url?``:""}
${xnt(E.price)}
${E.property_address||""}
${E.city}, ${E.state}
${qle[E.status]||E.status} ${E.bedrooms?`${E.bedrooms} bed`:""} ${E.bathrooms?`${E.bathrooms} bath`:""}
${(W=E.agent)!=null&&W.name?`
Listed by ${E.agent.name}
`:""}
Click to view details →
`),F=new Rf.Marker(L).setLngLat([E.longitude,E.latitude]).setPopup(O).addTo(i.current);a.current.push(F)}),v.length>1){const E=new Rf.LngLatBounds;v.forEach(T=>E.extend([T.longitude,T.latitude])),i.current.fitBounds(E,{padding:60,maxZoom:13})}else v.length===1&&i.current.flyTo({center:[v[0].longitude,v[0].latitude],zoom:12})},[t,c]),N.useEffect(()=>(window.__navigateToPublicListing__=v=>{r(v)},()=>{delete window.__navigateToPublicListing__}),[r]),p||e?s.jsx(Mc,{className:"w-full h-[500px] rounded-lg"}):!c||t.filter(v=>v.latitude!=null&&v.longitude!=null).length===0?null:s.jsxs("div",{className:"space-y-3",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:Object.entries(Vle).map(([v,E])=>s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:E}}),s.jsx("span",{className:"text-xs text-gray-600",children:qle[v]})]},v))}),s.jsx("div",{ref:n,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const OU={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",temp_off_market:"Temporarily Off Market",withdrawn:"Withdrawn",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},vnt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},CS="#0d0d0d",Gle="#1a1a1a",zs="#c9a84c",x_="#f0d78c";function LEe(){const[t,e]=N.useState(""),[r,n]=N.useState(!1),[i,a]=N.useState(!1),[c,d]=N.useState(!1),[p,l]=N.useState(-1),g=N.useRef(null),[v,E]=N.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:T}=Qrt(),j=N.useMemo(()=>{if(!T)return[];const oe=t.trim().toLowerCase(),pe=[...T.cities.map(be=>({label:be.label,value:be.city,type:"city",count:be.count})),...T.neighborhoods.map(be=>({label:be.label,value:be.neighborhood,type:"neighborhood",count:be.count})),...T.zips.map(be=>({label:`ZIP ${be.label}`,value:be.zip,type:"zip",count:be.count}))];return(oe?pe.filter(be=>be.label.toLowerCase().includes(oe)||be.value.toLowerCase().includes(oe)):pe).slice(0,8)},[T,t]);N.useEffect(()=>{const oe=pe=>{g.current&&!g.current.contains(pe.target)&&d(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[]);const{data:P,isLoading:C}=Xrt({city:t||void 0,status:v.status||void 0,propertyType:v.propertyType||void 0,minPrice:v.minPrice?Number(v.minPrice):void 0,maxPrice:v.maxPrice?Number(v.maxPrice):void 0}),L=oe=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(oe),O=()=>{E({status:"",propertyType:"",minPrice:"",maxPrice:""}),e("")},F=t||v.status||v.propertyType||v.minPrice||v.maxPrice,$=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),G=oe=>$?`/${oe.slug||oe.id}`:`/public/listing/${oe.slug||oe.id}`,{featured:W,restListings:Z,luxeCount:Q,cities:ee,activeCount:ie}=N.useMemo(()=>{const oe=P||[],pe=oe.filter(ot=>ot.status==="active"),Le=pe.length>0?pe:oe,be=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[Re,Ie,Te]=be.split("-").map(Number),ge=Math.floor(Date.UTC(Re,Ie-1,Te)/864e5),$e=Le.length>0?Le[ge%Le.length]:void 0,we=oe.filter(ot=>!$e||ot.id!==$e.id),ke=Array.from(new Set(oe.map(ot=>ot.city).filter(Boolean))).slice(0,8),Ae=oe.filter(ot=>(ot.price||0)>=1e6).length,He=pe.length;return{featured:$e,restListings:we,luxeCount:Ae,cities:ke,activeCount:He}},[P]);return s.jsxs(s.Fragment,{children:[s.jsxs(mc,{children:[s.jsx("title",{children:"LevelUp Listings — Curated Homes for Sale"}),s.jsx("meta",{name:"description",content:"A curated collection of exclusive properties from LevelUp real estate agents. Discover luxury homes, coming soon listings, and market-defining architecture."}),s.jsx("link",{rel:"canonical",href:"https://listings.relevelup.com"}),s.jsx("meta",{property:"og:title",content:"LevelUp Listings — Curated Homes for Sale"}),s.jsx("meta",{property:"og:description",content:"A curated collection of exclusive properties from LevelUp real estate agents."}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:url",content:"https://listings.relevelup.com"}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),s.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"LevelUp Listings",url:"https://listings.relevelup.com"})})]}),s.jsxs("div",{className:"min-h-screen text-white",style:{backgroundColor:CS,fontFamily:"'Fira Sans', system-ui, sans-serif"},children:[s.jsx("style",{children:` .lu-serif { font-family: 'DM Serif Display', Georgia, serif; font-weight: 400; letter-spacing: -0.01em; } .lu-eyebrow { font-family: 'Fira Sans', sans-serif; font-weight: 500; letter-spacing: 0.3em; text-transform: uppercase; font-size: 11px; } .lu-gold { color: ${zs}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${zs}, transparent); } .lu-card-hover { transition: transform .6s cubic-bezier(.2,.7,.2,1), box-shadow .6s; } .lu-card-hover:hover { transform: translateY(-6px); } .lu-img-zoom { transition: transform 1.2s cubic-bezier(.2,.7,.2,1); } .group:hover .lu-img-zoom { transform: scale(1.06); } .lu-hero-title { animation: luFadeUp 1.1s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-sub { animation: luFadeUp 1.1s .15s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-search { animation: luFadeUp 1.1s .3s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-stats { animation: luFadeUp 1.1s .45s cubic-bezier(.2,.7,.2,1) both; } @keyframes luFadeUp { from { opacity: 0; transform: translateY(24px); } to { opacity: 1; transform: none; } } .lu-grain::after { content: ''; position: absolute; inset: 0; pointer-events: none; opacity: .18; background-image: url("data:image/svg+xml;utf8,"); } .lu-marquee { display: flex; gap: 3rem; animation: luMarquee 40s linear infinite; } @keyframes luMarquee { to { transform: translateX(-50%); } } .lu-input-dark { background: rgba(255,255,255,0.06) !important; border-color: rgba(201,168,76,0.25) !important; color: #fff !important; } .lu-input-dark::placeholder { color: rgba(255,255,255,0.5) !important; } `}),s.jsxs("header",{className:"sticky top-0 z-50 backdrop-blur-md",style:{backgroundColor:"rgba(13,13,13,0.75)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:[s.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between",children:[s.jsxs(Nn,{to:"/",className:"flex items-center gap-3",children:[s.jsx("img",{src:Ule,alt:"LevelUp",className:"h-7"}),s.jsx("span",{className:"hidden sm:inline-block h-5 w-px",style:{background:"rgba(255,255,255,0.2)"}}),s.jsx("span",{className:"hidden sm:inline lu-eyebrow lu-gold",children:"Listings"})]}),s.jsxs("nav",{className:"hidden md:flex items-center gap-8",children:[s.jsx("a",{href:"#featured",className:"text-sm text-white/80 hover:text-white transition",children:"Featured"}),s.jsx("a",{href:"#collection",className:"text-sm text-white/80 hover:text-white transition",children:"Collection"}),s.jsx("a",{href:"#map",className:"text-sm text-white/80 hover:text-white transition",children:"Map"}),s.jsx(Nn,{to:"/home-value",className:"text-sm text-white/80 hover:text-white transition",children:"Home Value"}),s.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-sm px-4 py-2 rounded-full transition",style:{border:`1px solid ${zs}`,color:zs},children:"About LevelUp"})]}),s.jsx("button",{type:"button",onClick:()=>a(oe=>!oe),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${zs}`,color:zs},"aria-label":"Toggle menu","aria-expanded":i,children:i?s.jsx(Ra,{className:"w-5 h-5"}):s.jsx(nA,{className:"w-5 h-5"})})]}),i&&s.jsx("div",{className:"md:hidden border-t",style:{borderColor:"rgba(201,168,76,0.15)"},children:s.jsxs("nav",{className:"max-w-7xl mx-auto px-6 py-4 flex flex-col gap-1",children:[s.jsx("a",{href:"#featured",onClick:()=>a(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Featured"}),s.jsx("a",{href:"#collection",onClick:()=>a(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Collection"}),s.jsx("a",{href:"#map",onClick:()=>a(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Map"}),s.jsx(Nn,{to:"/home-value",onClick:()=>a(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Home Value"}),s.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",onClick:()=>a(!1),className:"mt-3 text-center text-sm px-4 py-3 rounded-full",style:{border:`1px solid ${zs}`,color:zs},children:"About LevelUp"})]})})]}),s.jsxs("section",{className:"relative overflow-hidden lu-grain",style:{minHeight:"92vh"},children:[s.jsxs("div",{className:"absolute inset-0",children:[s.jsx("img",{src:gnt,alt:"Luxury home at dusk",className:"w-full h-full object-cover",style:{filter:"brightness(0.55) contrast(1.05)"}}),s.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(13,13,13,0.55) 0%, rgba(13,13,13,0.25) 40%, rgba(13,13,13,0.9) 100%)"}})]}),s.jsxs("div",{className:"relative max-w-7xl mx-auto px-6 pt-24 md:pt-32 pb-16 flex flex-col justify-center",style:{minHeight:"92vh"},children:[s.jsxs("div",{className:"max-w-4xl",children:[s.jsxs("div",{className:"lu-hero-title flex items-center gap-3 mb-6",children:[s.jsx("span",{className:"h-px w-10",style:{background:zs}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"The LevelUp Collection"})]}),s.jsxs("h1",{className:"lu-serif lu-hero-title text-white text-5xl sm:text-6xl md:text-7xl lg:text-8xl leading-[1.02] mb-6",children:["Homes with a",s.jsx("br",{}),s.jsx("span",{className:"italic",style:{color:x_},children:"quiet"})," kind of luxury."]}),s.jsx("p",{className:"lu-hero-sub text-white/75 text-lg md:text-xl max-w-2xl mb-10 leading-relaxed",children:"A private, hand-picked collection of properties represented by LevelUp agents — from waterfront estates to architectural landmarks and everything in between."}),s.jsxs("div",{className:"lu-hero-search max-w-3xl",ref:g,children:[s.jsxs("div",{className:"flex items-stretch rounded-full overflow-hidden shadow-2xl relative",style:{background:"rgba(13,13,13,0.7)",border:`1px solid ${zs}`,backdropFilter:"blur(12px)"},children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(ef,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:zs}}),s.jsx(hn,{placeholder:"City, neighborhood, or ZIP",value:t,onChange:oe=>{e(oe.target.value),d(!0),l(-1)},onFocus:()=>d(!0),onKeyDown:oe=>{if(!(!c||j.length===0))if(oe.key==="ArrowDown")oe.preventDefault(),l(pe=>Math.min(pe+1,j.length-1));else if(oe.key==="ArrowUp")oe.preventDefault(),l(pe=>Math.max(pe-1,0));else if(oe.key==="Enter"&&p>=0){oe.preventDefault();const pe=j[p];e(pe.value),d(!1)}else oe.key==="Escape"&&d(!1)},className:"pl-16 h-16 text-base md:text-lg border-0 bg-transparent text-white placeholder:text-white/50 focus-visible:ring-0 rounded-none"})]}),s.jsxs("button",{onClick:()=>n(!r),className:"hidden sm:flex items-center gap-2 px-6 border-l text-sm text-white/80 hover:text-white transition",style:{borderColor:"rgba(201,168,76,0.3)"},children:[s.jsx(_5e,{className:"h-4 w-4"}),"Filters"]}),s.jsxs("button",{className:"px-8 flex items-center gap-2 font-medium transition hover:brightness-110",style:{background:zs,color:CS},onClick:()=>d(!1),children:[s.jsx(ef,{className:"h-5 w-5"}),s.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),c&&j.length>0&&s.jsxs("div",{className:"mt-2 rounded-2xl overflow-hidden shadow-2xl animate-fade-in",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.35)",backdropFilter:"blur(12px)"},children:[s.jsx("div",{className:"px-5 pt-3 pb-2 text-[10px] tracking-[0.2em] uppercase",style:{color:zs},children:"Suggestions"}),s.jsx("ul",{className:"max-h-80 overflow-y-auto",children:j.map((oe,pe)=>s.jsx("li",{children:s.jsxs("button",{type:"button",onMouseEnter:()=>l(pe),onClick:()=>{e(oe.value),d(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:p===pe?"rgba(201,168,76,0.12)":"transparent"},children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[oe.type==="city"&&s.jsx(Va,{className:"h-4 w-4 shrink-0",style:{color:zs}}),oe.type==="neighborhood"&&s.jsx(jl,{className:"h-4 w-4 shrink-0",style:{color:zs}}),oe.type==="zip"&&s.jsx(Do,{className:"h-4 w-4 shrink-0",style:{color:zs}}),s.jsx("span",{className:"text-white/90 truncate",children:oe.label})]}),s.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[oe.count," ",oe.count===1?"listing":"listings"]})]})},`${oe.type}-${oe.value}-${pe}`))})]}),c&&t.trim()&&j.length===0&&s.jsx("div",{className:"mt-2 rounded-2xl px-5 py-4 text-sm text-white/70",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.25)"},children:"No matches yet — try a nearby city or ZIP."}),r&&s.jsxs("div",{className:"mt-4 p-6 rounded-2xl grid sm:grid-cols-2 md:grid-cols-4 gap-4 animate-fade-in",style:{background:"rgba(26,26,26,0.9)",border:"1px solid rgba(201,168,76,0.25)"},children:[s.jsxs("div",{children:[s.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),s.jsxs(Xo,{value:v.status||"all",onValueChange:oe=>E({...v,status:oe==="all"?"":oe}),children:[s.jsx(Mo,{className:"lu-input-dark",children:s.jsx(Qo,{})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"all",children:"Any status"}),Object.entries(OU).map(([oe,pe])=>s.jsx($n,{value:oe,children:pe},oe))]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),s.jsxs(Xo,{value:v.propertyType||"all",onValueChange:oe=>E({...v,propertyType:oe==="all"?"":oe}),children:[s.jsx(Mo,{className:"lu-input-dark",children:s.jsx(Qo,{})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"all",children:"Any type"}),Object.entries(vnt).map(([oe,pe])=>s.jsx($n,{value:oe,children:pe},oe))]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),s.jsx(hn,{type:"number",placeholder:"No min",value:v.minPrice,onChange:oe=>E({...v,minPrice:oe.target.value}),className:"lu-input-dark"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Max Price"}),s.jsx(hn,{type:"number",placeholder:"No max",value:v.maxPrice,onChange:oe=>E({...v,maxPrice:oe.target.value}),className:"lu-input-dark"})]}),F&&s.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:s.jsxs(Jt,{variant:"ghost",size:"sm",onClick:O,className:"text-white/70 hover:text-white gap-1",children:[s.jsx(Ra,{className:"h-4 w-4"})," Clear all"]})})]})]}),s.jsx("div",{className:"lu-hero-stats mt-14 grid grid-cols-3 gap-6 max-w-2xl",children:[{label:"Listings",value:((P==null?void 0:P.length)??0).toString()},{label:"Active Now",value:ie.toString()},{label:"Luxury $1M+",value:Q.toString()}].map(oe=>s.jsxs("div",{children:[s.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:x_},children:oe.value}),s.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:oe.label})]},oe.label))})]}),s.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2 text-white/60",children:[s.jsx("span",{className:"lu-eyebrow",children:"Scroll"}),s.jsx(ad,{className:"h-4 w-4 animate-bounce"})]})]})]}),ee.length>0&&s.jsx("section",{className:"py-8 overflow-hidden",style:{background:Gle,borderTop:"1px solid rgba(201,168,76,0.15)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:s.jsx("div",{className:"lu-marquee whitespace-nowrap",children:[...ee,...ee,...ee].map((oe,pe)=>s.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[oe,s.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:zs}})]},pe))})}),W&&s.jsx("section",{id:"featured",className:"py-20 md:py-28",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[s.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx(va,{className:"h-4 w-4",style:{color:zs}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"Today's Featured Residence"})]}),s.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl",children:["Today's ",s.jsx("span",{className:"italic",style:{color:x_},children:"standout"}),"."]})]}),s.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),s.jsx(Nn,{to:G(W),className:"group block",children:s.jsxs("div",{className:"grid lg:grid-cols-5 gap-6 lg:gap-10 items-stretch",children:[s.jsxs("div",{className:"lg:col-span-3 relative overflow-hidden rounded-2xl aspect-[4/3] bg-black",children:[(()=>{var pe,Le;const oe=((pe=W.photos)==null?void 0:pe.find(be=>be.is_primary))||((Le=W.photos)==null?void 0:Le[0]);return oe?s.jsx("img",{src:oe.photo_url,alt:W.property_address||W.city,className:"w-full h-full object-cover lu-img-zoom"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(Do,{className:"h-16 w-16 text-white/20"})})})(),s.jsx("div",{className:"absolute top-5 left-5 px-4 py-1.5 rounded-full lu-eyebrow",style:{background:zs,color:CS},children:OU[W.status]||"Featured"})]}),s.jsxs("div",{className:"lg:col-span-2 flex flex-col justify-center",children:[s.jsxs("div",{className:"lu-eyebrow text-white/60 mb-4 flex items-center gap-2",children:[s.jsx(Va,{className:"h-3.5 w-3.5",style:{color:zs}}),W.city,W.state?`, ${W.state}`:""]}),W.property_address&&s.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:W.property_address}),s.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:x_},children:L(W.price)}),s.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[W.bedrooms&&s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(tA,{className:"h-4 w-4",style:{color:zs}}),W.bedrooms," bd"]}),W.bathrooms&&s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(ww,{className:"h-4 w-4",style:{color:zs}}),W.bathrooms," ba"]}),W.square_footage&&s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(JW,{className:"h-4 w-4",style:{color:zs}}),W.square_footage.toLocaleString()," sf"]})]}),W.description&&s.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:W.description}),s.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:zs},children:["View Residence ",s.jsx(lo,{className:"h-4 w-4"})]})]})]})})]})}),s.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:Gle},children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[s.jsxs("div",{className:"text-center mb-14",children:[s.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[s.jsx("span",{className:"h-px w-10",style:{background:zs}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),s.jsx("span",{className:"h-px w-10",style:{background:zs}})]}),s.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl mb-4",children:["Every home, ",s.jsx("span",{className:"italic",style:{color:x_},children:"carefully considered"}),"."]}),s.jsx("p",{className:"text-white/60 max-w-2xl mx-auto",children:"Browse the full catalogue of LevelUp-represented properties. Filter, refine, and find the one that feels like yours."})]}),C?s.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((oe,pe)=>s.jsxs("div",{className:"space-y-3",children:[s.jsx(Mc,{className:"aspect-[4/5] bg-white/5"}),s.jsx(Mc,{className:"h-6 w-32 bg-white/5"}),s.jsx(Mc,{className:"h-4 w-full bg-white/5"})]},pe))}):Z.length>0?s.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:Z.map(oe=>{var Le,be,Re,Ie,Te;const pe=((Le=oe.photos)==null?void 0:Le.find(ge=>ge.is_primary))||((be=oe.photos)==null?void 0:be[0]);return s.jsxs(Nn,{to:G(oe),className:"group lu-card-hover block",children:[s.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[pe?s.jsx("img",{src:pe.photo_url,alt:oe.property_address||oe.city,className:"w-full h-full object-cover lu-img-zoom"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(Do,{className:"h-12 w-12 text-white/20"})}),s.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity",style:{background:"linear-gradient(180deg, transparent 40%, rgba(13,13,13,0.85) 100%)"}}),s.jsx("div",{className:"absolute top-4 left-4 px-3 py-1 lu-eyebrow rounded-full",style:{background:"rgba(13,13,13,0.75)",color:zs,border:`1px solid ${zs}`},children:OU[oe.status]}),s.jsxs("div",{className:"absolute bottom-4 left-4 right-4 flex items-center gap-4 text-white/90 text-sm opacity-0 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0 transition-all",children:[oe.bedrooms&&s.jsxs("span",{children:[oe.bedrooms," bd"]}),oe.bathrooms&&s.jsxs("span",{children:[oe.bathrooms," ba"]}),oe.square_footage&&s.jsxs("span",{children:[oe.square_footage.toLocaleString()," sf"]})]})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"lu-eyebrow text-white/50 mb-2 flex items-center gap-2",children:[s.jsx(Va,{className:"h-3 w-3",style:{color:zs}}),oe.city,oe.state?`, ${oe.state}`:""]}),s.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:x_},children:L(oe.price)}),oe.property_address&&s.jsx("p",{className:"text-white/70 text-sm truncate",children:oe.property_address}),((Re=oe.agent)==null?void 0:Re.name)&&s.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[s.jsx(jl,{className:"h-3 w-3"}),oe.agent.name,(((Ie=oe.agent.brokerage)==null?void 0:Ie.name)||oe.agent.brokerage_name)&&s.jsxs("span",{className:"truncate",children:["· ",((Te=oe.agent.brokerage)==null?void 0:Te.name)||oe.agent.brokerage_name]})]})]})]},oe.id)})}):s.jsxs("div",{className:"text-center py-20",children:[s.jsx("div",{className:"w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center",style:{border:`1px solid ${zs}`},children:s.jsx(Do,{className:"h-8 w-8",style:{color:zs}})}),s.jsx("h3",{className:"lu-serif text-2xl mb-2",children:"No listings match yet"}),s.jsx("p",{className:"text-white/60 mb-6",children:"Adjust your search — or check back soon for new arrivals."}),F&&s.jsx(Jt,{onClick:O,style:{background:zs,color:CS},className:"hover:brightness-110",children:"Clear filters"})]})]})}),P&&P.length>0&&s.jsx("section",{id:"map",className:"py-20 md:py-28",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[s.jsx("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-10",children:s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("span",{className:"h-px w-10",style:{background:zs}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"Explore"})]}),s.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl",children:["Every listing, ",s.jsx("span",{className:"italic",style:{color:x_},children:"on the map"}),"."]})]})}),s.jsx("div",{className:"rounded-2xl overflow-hidden",style:{border:"1px solid rgba(201,168,76,0.2)"},children:s.jsx(_nt,{listings:P,isLoading:C})})]})}),s.jsxs("section",{className:"relative py-24 md:py-32 overflow-hidden lu-grain",children:[s.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(ellipse at center, rgba(201,168,76,0.15) 0%, ${CS} 70%)`}}),s.jsxs("div",{className:"relative max-w-4xl mx-auto px-6 text-center",children:[s.jsxs("div",{className:"flex items-center justify-center gap-3 mb-6",children:[s.jsx("span",{className:"h-px w-10",style:{background:zs}}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),s.jsx("span",{className:"h-px w-10",style:{background:zs}})]}),s.jsxs("h2",{className:"lu-serif text-4xl md:text-6xl mb-6 leading-tight",children:["Your listings deserve a",s.jsx("br",{}),s.jsx("span",{className:"italic",style:{color:x_},children:"stage this good"}),"."]}),s.jsx("p",{className:"text-white/70 text-lg mb-10 max-w-2xl mx-auto",children:"Join LevelUp and get every listing published to this collection — with a cinematic microsite, lead capture, and marketing tools that do the heavy lifting."}),s.jsxs("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-3 px-8 py-4 rounded-full font-medium transition hover:brightness-110",style:{background:zs,color:CS},children:["Explore LevelUp",s.jsx(lo,{className:"h-4 w-4"})]})]})]}),s.jsx("footer",{className:"py-14",style:{background:"#080808",borderTop:"1px solid rgba(201,168,76,0.15)"},children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6 flex flex-col md:flex-row items-center justify-between gap-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("img",{src:Ule,alt:"LevelUp",className:"h-6"}),s.jsx("span",{className:"h-4 w-px bg-white/20"}),s.jsx("span",{className:"lu-eyebrow lu-gold",children:"Listings"})]}),s.jsxs("p",{className:"text-white/40 text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),s.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-white/60 hover:text-white text-sm transition",children:"relevelup.com →"})]})})]}),s.jsx(Crt,{}),s.jsx(Prt,{})]})}const bnt=Object.freeze(Object.defineProperty({__proto__:null,default:LEe},Symbol.toStringTag,{value:"Module"})),wnt=N.lazy(()=>Ge(()=>import("./PublicHomeValue-CpMRy4yq.js"),[]));function Snt(){const t=ms(),e=window.location.hostname;if(!(e==="listings.relevelup.com"||e.startsWith("listings.")))return null;const n=t.pathname.slice(1);return!n||n===""?s.jsx(LEe,{}):n==="home-value"||n==="whats-my-home-worth"?s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(wnt,{})}):n.startsWith("public/")?null:s.jsx(aZ,{slugOverride:n})}const Ent=N.lazy(()=>Ge(()=>import("./CommercialMarketplace-CvkDdqEd.js"),[]));function Tnt(){const e=ms().pathname.slice(1);return e?e.startsWith("public/")?null:s.jsx(aZ,{slugOverride:e}):s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"min-h-screen bg-[#0a0d12]"}),children:s.jsx(Ent,{})})}function C5({card:t,variant:e}){const r=t.brokerage_display_name||t.brokerage_logo_url,n=t.team_name||t.team_logo_url;if(!r&&!n)return null;const i={standard:{container:"bg-slate-50 border border-slate-100",text:"text-slate-600",subtext:"text-slate-400"},luxury:{container:"bg-[#1e2636] border border-[#c9a84c]/10",text:"text-[#e2e8f0]",subtext:"text-[#4a5568]"},bold:{container:"bg-gray-50 border border-gray-100",text:"text-[#1a1a2e]",subtext:"text-gray-400"},classic:{container:"bg-white border border-[#d4cfc5] shadow-sm",text:"text-[#1b3a4b]",subtext:"text-[#a0aec0]"}}[e];return s.jsx("div",{className:`rounded-2xl p-4 mb-6 ${i.container}`,children:s.jsxs("div",{className:`flex flex-col items-center gap-3 ${r&&n?"divide-y divide-current/10":""}`,children:[r&&s.jsxs("div",{className:"flex flex-col items-center gap-1.5 w-full",children:[t.brokerage_logo_url&&s.jsx("img",{src:t.brokerage_logo_url,alt:t.brokerage_display_name||"Brokerage",style:{height:`${t.brokerage_logo_size||56}px`},className:"max-w-[280px] object-contain"}),t.brokerage_display_name&&!t.brokerage_logo_url&&s.jsx("p",{className:`text-sm font-medium ${i.text}`,children:t.brokerage_display_name})]}),n&&s.jsxs("div",{className:`flex flex-col items-center gap-1.5 w-full ${r?"pt-3":""}`,children:[t.team_logo_url&&s.jsx("img",{src:t.team_logo_url,alt:t.team_name||"Team",style:{height:`${t.team_logo_size||56}px`},className:"max-w-[280px] object-contain"}),t.team_name&&!t.team_logo_url&&s.jsx("p",{className:`text-sm font-medium ${i.text}`,children:t.team_name})]})]})})}const Ant=t=>jr({queryKey:["agent-card-public",t],queryFn:async()=>{if(!t)throw new Error("No slug provided");const{data:e,error:r}=await Be.from("agent_cards").select("*").eq("slug",t).eq("is_published",!0).single();if(r)throw r;const{data:n}=await Be.from("profiles").select("name, email, phone, brokerage_id").eq("id",e.user_id).single();let i=null;if(n!=null&&n.brokerage_id){const{data:d}=await Be.from("brokerages").select("name").eq("id",n.brokerage_id).single();i=(d==null?void 0:d.name)||null}let a=null;try{const{data:d}=await Be.from("profiles").select("avatar_url").eq("id",e.user_id).single();if(d!=null&&d.avatar_url)a=d.avatar_url;else{const{data:p}=await Be.storage.from("avatars").list(`${e.user_id}`);if(p&&p.length>0){const{data:l}=Be.storage.from("avatars").getPublicUrl(`${e.user_id}/${p[0].name}`);a=`${l.publicUrl}?t=${Date.now()}`}}}catch{}const c={...n||{name:null,email:null,phone:null,brokerage_id:null},email:e.display_email||(n==null?void 0:n.email)||null};return{...e,social_links:e.social_links||[],profile:c,brokerage_name:e.brokerage_display_name||i,avatar_url:a}},enabled:!!t}),SYt=()=>jr({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:t,error:e}=await Be.from("agent_cards").select("*").order("created_at",{ascending:!1});if(e)throw e;return t}}),EYt=t=>jr({queryKey:["agent-card",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Be.from("agent_cards").select("*").eq("user_id",t).maybeSingle();if(r)throw r;return e},enabled:!!t}),TYt=()=>{const t=Ur();return zr({mutationFn:async e=>{const{data:r,error:n}=await Be.from("agent_cards").insert(e).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-cards-admin"]}),t.invalidateQueries({queryKey:["agent-card"]}),lr.success("Agent card created")},onError:e=>lr.error(e.message)})},AYt=()=>{const t=Ur();return zr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Be.from("agent_cards").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["agent-cards-admin"]}),t.invalidateQueries({queryKey:["agent-card"]}),lr.success("Agent card updated")},onError:e=>lr.error(e.message)})},Vs=async(t,e,r,n)=>{const i=new URLSearchParams(window.location.search);await Be.from("agent_card_interactions").insert({card_id:t,interaction_type:e,interaction_detail:r||null,referrer:document.referrer||null,user_agent:navigator.userAgent||null,utm_source:i.get("utm_source")||null,utm_medium:i.get("utm_medium")||null,utm_campaign:i.get("utm_campaign")||null,metadata:{}})},knt=async(t,e)=>{const{error:r}=await Be.from("agent_card_leads").insert({card_id:t,...e});if(r)throw r},kYt=t=>jr({queryKey:["agent-card-analytics",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Be.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",t).order("created_at",{ascending:!1}).limit(500);if(r)throw r;const{data:n,error:i}=await Be.from("agent_card_leads").select("*").eq("card_id",t).order("created_at",{ascending:!1});if(i)throw i;const a=(e==null?void 0:e.filter(p=>p.interaction_type==="card_view").length)||0,c=(e==null?void 0:e.filter(p=>p.interaction_type==="button_click").length)||0,d=(e==null?void 0:e.filter(p=>p.interaction_type==="contact_saved").length)||0;return{views:a,clicks:c,saves:d,leads:n||[],interactions:e||[]}},enabled:!!t});function P5({open:t,onOpenChange:e,cardId:r,type:n,agentName:i}){const[a,c]=N.useState(""),[d,p]=N.useState(""),[l,g]=N.useState(""),[v,E]=N.useState(""),[T,j]=N.useState(""),[P,C]=N.useState(!1),L=async O=>{if(O.preventDefault(),!a.trim()){lr.error("Please enter your name");return}C(!0);try{await knt(r,{lead_type:n,name:a.trim(),email:d.trim()||void 0,phone:l.trim()||void 0,message:T.trim()||void 0,intent:v||void 0}),Vs(r,"lead_submitted",n),Be.functions.invoke("card-lead-notify",{body:{cardId:r,leadType:n,name:a.trim(),email:d.trim()||void 0,phone:l.trim()||void 0,message:T.trim()||void 0,intent:v||void 0}}).catch(F=>console.error("Card lead notify failed:",F)),lr.success(n==="booking"?"Request sent! They'll be in touch soon.":n==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),e(!1),c(""),p(""),g(""),E(""),j("")}catch{lr.error("Something went wrong. Please try again.")}finally{C(!1)}};return s.jsx(gl,{open:t,onOpenChange:e,children:s.jsxs(Jo,{className:"sm:max-w-md rounded-2xl",children:[s.jsxs(Bc,{children:[s.jsx(pc,{children:n==="booking"?"Book a Call":n==="connect"?"Connect with Me":"Refer a Friend"}),s.jsx(sf,{children:n==="booking"?`Let ${i} know you'd like to connect.`:n==="connect"?`Share your info and ${i} will reach out.`:`Know someone who could use ${i}'s help?`})]}),s.jsxs("form",{onSubmit:L,className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"lead-name",children:"Name *"}),s.jsx(hn,{id:"lead-name",value:a,onChange:O=>c(O.target.value),placeholder:"Your name",required:!0})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"lead-phone",children:"Phone"}),s.jsx(hn,{id:"lead-phone",type:"tel",value:l,onChange:O=>g(O.target.value),placeholder:"(555) 123-4567"})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"lead-email",children:"Email"}),s.jsx(hn,{id:"lead-email",type:"email",value:d,onChange:O=>p(O.target.value),placeholder:"you@example.com"})]}),n==="booking"&&s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"lead-intent",children:"I'm looking to..."}),s.jsxs(Xo,{value:v,onValueChange:E,children:[s.jsx(Mo,{children:s.jsx(Qo,{placeholder:"Select one"})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"buy",children:"Buy a home"}),s.jsx($n,{value:"sell",children:"Sell my home"}),s.jsx($n,{value:"both",children:"Buy & Sell"}),s.jsx($n,{value:"other",children:"Something else"})]})]})]}),n!=="connect"&&s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"lead-message",children:n==="referral"?"Tell us about them":"Message (optional)"}),s.jsx(hn,{id:"lead-message",value:T,onChange:O=>j(O.target.value),placeholder:n==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),s.jsx(Jt,{type:"submit",className:"w-full rounded-2xl",disabled:P,children:P?"Sending...":"Submit"})]})]})})}const Int=t=>jr({queryKey:["card-blocks",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Be.from("card_blocks").select("*").eq("card_id",t).eq("is_visible",!0).order("sort_order",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t}),IYt=t=>jr({queryKey:["card-blocks-all",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Be.from("card_blocks").select("*").eq("card_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t}),jYt=()=>{const t=Ur();return zr({mutationFn:async e=>{const{data:r,error:n}=await Be.from("card_blocks").insert(e).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["card-blocks",r.card_id]}),t.invalidateQueries({queryKey:["card-blocks-all",r.card_id]}),lr.success("Block added")},onError:e=>lr.error(e.message)})},CYt=()=>{const t=Ur();return zr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Be.from("card_blocks").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["card-blocks"]}),t.invalidateQueries({queryKey:["card-blocks-all"]}),lr.success("Block updated")},onError:e=>lr.error(e.message)})},PYt=()=>{const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("card_blocks").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["card-blocks"]}),t.invalidateQueries({queryKey:["card-blocks-all"]}),lr.success("Block removed")},onError:e=>lr.error(e.message)})};function jnt(t){const e=t.match(/(?:iframe\.mediadelivery\.net\/embed\/|video\.bunnycdn\.com\/play\/)(\d+)\/([a-f0-9-]+)/i);return e?`https://iframe.mediadelivery.net/embed/${e[1]}/${e[2]}?autoplay=false&responsive=true`:(t.includes("iframe.mediadelivery.net"),t)}function Cnt(t){const e=t.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/);return e?`https://www.youtube.com/embed/${e[1]}`:null}const Pnt={standard:"rounded-2xl overflow-hidden mb-6 bg-slate-100",luxury:"rounded-xl overflow-hidden mb-6 bg-[#1e2636] border border-[#c9a84c]/10",bold:"rounded-2xl overflow-hidden mb-6",classic:"rounded-lg overflow-hidden mb-6 border border-[#d4cfc5] shadow-sm"};function Nnt({block:t,variant:e}){const r=t.config;if(!r.video_url)return null;const n=r.video_url.includes("mediadelivery.net")||r.video_url.includes("bunnycdn.com"),i=Cnt(r.video_url),a=n||!!i,c=n?jnt(r.video_url):i||r.video_url;return s.jsx("div",{className:Pnt[e],children:a?s.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:s.jsx("iframe",{src:c,loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,width:"100%",height:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):s.jsx("video",{src:r.video_url,controls:!0,className:"w-full",preload:"metadata"})})}const Rnt={standard:{container:"mb-6",card:"bg-slate-50 rounded-2xl p-5 border border-slate-100",quote:"text-sm text-slate-600 italic",name:"text-sm font-semibold text-slate-800",role:"text-xs text-slate-500",dot:"bg-primary",dotInactive:"bg-slate-300",nav:"text-slate-400 hover:text-slate-600"},luxury:{container:"mb-6",card:"bg-[#1e2636] rounded-xl p-5 border border-[#c9a84c]/10",quote:"text-sm text-[#a0aec0] italic font-serif",name:"text-sm font-semibold text-white",role:"text-xs text-[#c9a84c]",dot:"bg-[#c9a84c]",dotInactive:"bg-[#2a3040]",nav:"text-[#4a5568] hover:text-[#c9a84c]"},bold:{container:"mb-6",card:"bg-[#fff3e0] rounded-2xl p-5",quote:"text-sm text-[#1a1a2e] font-medium",name:"text-sm font-black text-[#1a1a2e]",role:"text-xs text-[#ff5722] font-bold",dot:"bg-[#ff5722]",dotInactive:"bg-gray-300",nav:"text-gray-400 hover:text-[#ff5722]"},classic:{container:"mb-6",card:"bg-white rounded-lg p-5 border border-[#d4cfc5] shadow-sm",quote:"text-sm text-[#4a5568] italic font-serif",name:"text-sm font-semibold text-[#1b3a4b]",role:"text-xs text-[#5a7a6f]",dot:"bg-[#1b3a4b]",dotInactive:"bg-[#d4cfc5]",nav:"text-[#a0aec0] hover:text-[#1b3a4b]"}};function Lnt({block:t,variant:e}){const n=t.config.testimonials||[],[i,a]=N.useState(0);if(n.length===0)return null;const c=Rnt[e],d=n[i];return s.jsxs("div",{className:c.container,children:[s.jsxs("div",{className:c.card,children:[s.jsx(m5e,{className:"h-4 w-4 mb-2 opacity-30"}),s.jsxs("p",{className:`${c.quote} mb-3`,children:['"',d.quote,'"']}),s.jsxs("div",{children:[s.jsx("p",{className:c.name,children:d.name}),d.role&&s.jsx("p",{className:c.role,children:d.role})]})]}),n.length>1&&s.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[s.jsx("button",{onClick:()=>a(p=>(p-1+n.length)%n.length),className:c.nav,children:s.jsx(bg,{className:"h-4 w-4"})}),s.jsx("div",{className:"flex gap-1.5",children:n.map((p,l)=>s.jsx("div",{className:`h-1.5 w-1.5 rounded-full transition-colors cursor-pointer ${l===i?c.dot:c.dotInactive}`,onClick:()=>a(l)},l))}),s.jsx("button",{onClick:()=>a(p=>(p+1)%n.length),className:c.nav,children:s.jsx(uf,{className:"h-4 w-4"})})]})]})}const Dnt={standard:{container:"flex flex-wrap gap-2 mb-6 justify-center",tag:"px-3 py-1.5 text-xs font-medium rounded-full bg-primary/10 text-primary"},luxury:{container:"flex flex-wrap gap-2 mb-6 justify-center",tag:"px-3 py-1.5 text-xs font-medium rounded-full bg-[#c9a84c]/10 text-[#e8d48b] border border-[#c9a84c]/20"},bold:{container:"flex flex-wrap gap-2 mb-6 justify-center",tag:"px-3 py-1.5 text-xs font-black rounded-full bg-[#1a1a2e] text-white uppercase tracking-wide"},classic:{container:"flex flex-wrap gap-2 mb-6 justify-center",tag:"px-3 py-1.5 text-xs font-medium rounded-md bg-[#1b3a4b]/10 text-[#1b3a4b] border border-[#d4cfc5]"}};function Mnt({block:t,variant:e}){const n=t.config.tags||[];if(n.length===0)return null;const i=Dnt[e];return s.jsx("div",{className:i.container,children:n.map((a,c)=>s.jsx("span",{className:i.tag,children:a},c))})}const Ont={standard:{container:"space-y-2 mb-6",link:"w-full flex items-center justify-between h-12 px-4 rounded-2xl bg-slate-50 hover:bg-slate-100 border border-slate-100 transition-colors text-sm font-medium text-slate-700",icon:"text-primary"},luxury:{container:"space-y-2 mb-6",link:"w-full flex items-center justify-between h-12 px-4 rounded-xl bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/10 transition-colors text-sm font-medium text-[#e2e8f0]",icon:"text-[#c9a84c]"},bold:{container:"space-y-2 mb-6",link:"w-full flex items-center justify-between h-12 px-4 rounded-2xl bg-gray-50 hover:bg-gray-100 transition-colors text-sm font-bold text-[#1a1a2e]",icon:"text-[#ff5722]"},classic:{container:"space-y-2 mb-6",link:"w-full flex items-center justify-between h-12 px-4 rounded-lg bg-white hover:bg-[#f5f1eb] border border-[#d4cfc5] shadow-sm transition-colors text-sm font-medium text-[#1b3a4b]",icon:"text-[#5a7a6f]"}};function Fnt({block:t,cardId:e,variant:r}){const i=t.config.links||[];if(i.length===0)return null;const a=Ont[r];return s.jsx("div",{className:a.container,children:i.map((c,d)=>s.jsxs("a",{href:c.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Vs(e,"button_click",`custom_link_${c.label}`),className:a.link,children:[s.jsx("span",{children:c.label}),s.jsx(rA,{className:`h-4 w-4 ${a.icon}`})]},d))})}const Bnt={instagram:{label:"Instagram",icon:"M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z",color:"#E4405F",hoverBg:"hover:bg-[#E4405F]/10"},facebook:{label:"Facebook",icon:"M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z",color:"#1877F2",hoverBg:"hover:bg-[#1877F2]/10"},linkedin:{label:"LinkedIn",icon:"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z",color:"#0A66C2",hoverBg:"hover:bg-[#0A66C2]/10"},twitter:{label:"X",icon:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z",color:"#000000",hoverBg:"hover:bg-black/10"},youtube:{label:"YouTube",icon:"M23.498 6.186a3.016 3.016 0 00-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 00.502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 002.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 002.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814z M9.545 15.568V8.432L15.818 12z",color:"#FF0000",hoverBg:"hover:bg-[#FF0000]/10"},tiktok:{label:"TikTok",icon:"M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z",color:"#000000",hoverBg:"hover:bg-black/10"},zillow:{label:"Zillow",icon:"M12 0L1 6v12l11 6 11-6V6L12 0zm0 2.18L21 7.5v9L12 21.82 3 16.5v-9L12 2.18z",color:"#006AFF",hoverBg:"hover:bg-[#006AFF]/10"},realtor:{label:"Realtor",icon:"M12 2L2 7v10l10 5 10-5V7L12 2zm0 2.18l8 4v8l-8 4-8-4v-8l8-4z",color:"#D92228",hoverBg:"hover:bg-[#D92228]/10"},spotify:{label:"Spotify",icon:"M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0zm5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.779-.179-.899-.539-.12-.421.18-.78.54-.9 4.56-1.021 8.52-.6 11.64 1.32.42.18.479.659.301 1.02zm1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6-.12-.48.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2zm.12-3.36C15.24 8.4 8.82 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.419 1.56-.299.421-1.02.599-1.559.3z",color:"#1DB954",hoverBg:"hover:bg-[#1DB954]/10"},apple_music:{label:"Apple Music",icon:"M23.994 6.124a9.23 9.23 0 00-.24-2.19c-.317-1.31-1.062-2.31-2.18-3.043A5.022 5.022 0 0019.7.198a10.7 10.7 0 00-1.564-.15C17.637.017 17.14 0 12.002 0h-.004C6.858 0 6.362.017 5.862.047 5.34.08 4.82.13 4.309.325a5.017 5.017 0 00-1.874.826C1.317 2.07.573 3.07.255 4.38A9.234 9.234 0 00.02 6.57C-.013 7.068-.03 7.564 0 12.002v.004c-.03 4.438.013 4.934.047 5.432.033.522.083 1.042.278 1.554a5.017 5.017 0 00.826 1.874c.92 1.118 1.92 1.862 3.23 2.18a9.23 9.23 0 002.19.24c.498.03.994.013 5.432.047h.004c4.438.034 4.934-.013 5.432-.047a9.23 9.23 0 002.19-.24c1.31-.317 2.31-1.062 3.043-2.18a5.022 5.022 0 00.627-1.874c.195-.492.245-1.012.278-1.534.03-.498.047-.994.047-5.432v-.004c.034-4.438-.013-4.934-.047-5.432zM17.42 16.41c0 .612-.15 1.21-.44 1.758a3.58 3.58 0 01-1.207 1.31c-.518.339-1.09.521-1.705.545-.13.005-.26 0-.39-.017a2.617 2.617 0 01-1.653-.772 2.305 2.305 0 01-.668-1.653c-.005-.13 0-.26.017-.39.07-.52.275-.986.602-1.39a2.998 2.998 0 011.218-.94 3.14 3.14 0 011.12-.282c.17-.009.336.002.502.034V9.472L10.2 10.637v7.093c0 .612-.15 1.21-.44 1.758a3.58 3.58 0 01-1.207 1.31c-.518.339-1.09.521-1.705.545-.13.005-.26 0-.39-.017a2.617 2.617 0 01-1.653-.772A2.305 2.305 0 014.137 18.9c-.005-.13 0-.26.017-.39.07-.52.275-.986.602-1.39a2.998 2.998 0 011.218-.94 3.14 3.14 0 011.12-.282c.17-.009.336.002.502.034V8.377c0-.453.066-.903.195-1.34a3.2 3.2 0 01.694-1.204 2.62 2.62 0 011.063-.738c.39-.14.793-.208 1.196-.196l4.84-1.01v10.52z",color:"#FA243C",hoverBg:"hover:bg-[#FA243C]/10"}};function znt({path:t,color:e,size:r=20}){return s.jsx("svg",{viewBox:"0 0 24 24",width:r,height:r,fill:e,children:s.jsx("path",{d:t})})}const $nt={standard:{container:"bg-white rounded-2xl border border-slate-100 p-5 mb-6 shadow-sm",title:"text-sm font-semibold text-slate-800 mb-3",linkClass:"h-11 w-11 rounded-xl bg-slate-50 border border-slate-100 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:shadow-md"},luxury:{container:"bg-zinc-900/50 backdrop-blur rounded-2xl border border-amber-900/20 p-5 mb-6",title:"text-sm font-semibold text-amber-200/80 mb-3",linkClass:"h-11 w-11 rounded-xl bg-zinc-800/80 border border-amber-900/20 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:border-amber-500/40 hover:shadow-md hover:shadow-amber-500/10"},bold:{container:"bg-white/10 backdrop-blur rounded-2xl border border-white/20 p-5 mb-6",title:"text-sm font-semibold text-white/90 mb-3",linkClass:"h-11 w-11 rounded-xl bg-white/10 border border-white/20 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:bg-white/20 hover:shadow-md"},classic:{container:"bg-stone-50 rounded-2xl border border-stone-200 p-5 mb-6",title:"text-sm font-semibold text-stone-800 mb-3",linkClass:"h-11 w-11 rounded-xl bg-white border border-stone-200 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:shadow-md"}};function Unt({block:t,cardId:e,variant:r}){const i=t.config.platforms||[],a=$nt[r];return i.length===0?null:s.jsxs("div",{className:a.container,children:[s.jsx("h3",{className:a.title,children:"Follow Me"}),s.jsx("div",{className:"flex flex-wrap gap-3 justify-center",children:i.map((c,d)=>{const p=Bnt[c.platform.toLowerCase()];return!p||!c.url?null:s.jsx("a",{href:c.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Vs(e,"button_click",`social_${c.platform}`),className:a.linkClass,title:p.label,children:s.jsx(znt,{path:p.icon,color:p.color})},d)})})]})}function N5({cardId:t,variant:e}){const{data:r}=Int(t);if(!r||r.length===0)return null;const n=r.filter(c=>c.block_type==="social_media"&&c.is_visible),i=r.filter(c=>c.block_type!=="social_media"),a=n.length>0?{...n[0],config:{platforms:n.flatMap(c=>c.config.platforms||[])}}:null;return r.findIndex(c=>c.block_type==="social_media"),s.jsxs(s.Fragment,{children:[i.map(c=>{switch(c.block_type){case"video_intro":return s.jsx(Nnt,{block:c,variant:e},c.id);case"testimonials":return s.jsx(Lnt,{block:c,variant:e},c.id);case"specialties":return s.jsx(Mnt,{block:c,variant:e},c.id);case"custom_links":return s.jsx(Fnt,{block:c,cardId:t,variant:e},c.id);default:return null}}),a&&s.jsx(Unt,{block:a,cardId:t,variant:e})]})}async function Vnt(t){try{const e=await fetch(t);if(!e.ok)return null;const r=await e.blob(),n=r.type||"image/jpeg";return new Promise(i=>{const a=new FileReader;a.onloadend=()=>{const d=a.result.split(",")[1];i({base64:d,mimeType:n})},a.onerror=()=>i(null),a.readAsDataURL(r)})}catch{return null}}function qnt(t){const e=t.trim().split(/\s+/);if(e.length<=1)return{first:e[0]||"",last:""};const r=e.pop();return{first:e.join(" "),last:r}}async function R5(t){const{first:e,last:r}=qnt(t.name),n=["BEGIN:VCARD","VERSION:3.0",`FN:${t.name}`,`N:${r};${e};;;`];if(t.phone&&n.push(`TEL;TYPE=CELL:${t.phone}`),t.email&&n.push(`EMAIL;TYPE=INTERNET:${t.email}`),t.brokerage&&n.push(`ORG:${t.brokerage}`),n.push(`URL:${t.cardUrl}`),t.avatarUrl){const d=await Vnt(t.avatarUrl);if(d){const l={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[d.mimeType]||"JPEG";n.push(`PHOTO;ENCODING=b;TYPE=${l}:${d.base64}`)}}n.push("END:VCARD");const i=new Blob([n.join(`\r `)],{type:"text/vcard"}),a=URL.createObjectURL(i),c=document.createElement("a");c.href=a,c.download=`${t.name.replace(/\s+/g,"_")}.vcf`,c.click(),URL.revokeObjectURL(a),lr.success("Contact saved!")}function Gnt({card:t}){var L;const[e,r]=N.useState(!1),[n,i]=N.useState("booking"),a=((L=t.profile)==null?void 0:L.name)||"Agent",c=a.split(" ").map(O=>O[0]).join("").toUpperCase().slice(0,2),d=(O,F)=>{Vs(t.id,"button_click",O),F()},p=()=>d("call",()=>{var O;(O=t.profile)!=null&&O.phone?window.location.href=`tel:${t.profile.phone}`:lr.error("Phone number not available")}),l=()=>d("text",()=>{var O;(O=t.profile)!=null&&O.phone?window.location.href=`sms:${t.profile.phone}`:lr.error("Phone number not available")}),g=()=>d("email",()=>{var O;(O=t.profile)!=null&&O.email?window.location.href=`mailto:${t.profile.email}`:lr.error("Email not available")}),v=()=>{t.booking_url?d("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),Vs(t.id,"button_click","book"))},E=()=>{var O,F;Vs(t.id,"contact_saved"),R5({name:a,phone:(O=t.profile)==null?void 0:O.phone,email:(F=t.profile)==null?void 0:F.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},T=async()=>{Vs(t.id,"share_event");const O=`https://cards.relevelup.com/${t.slug}`,F="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${a}`,text:F,url:O})}catch{}else await navigator.clipboard.writeText(O),lr.success("Link copied!")},j=()=>{i("referral"),r(!0),Vs(t.id,"button_click","refer")},P=()=>{i("connect"),r(!0),Vs(t.id,"button_click","connect")},C={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return s.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-white to-slate-50",children:[s.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[s.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&s.jsxs(tf,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[s.jsx(rf,{src:t.avatar_url||void 0,alt:a}),s.jsx(nf,{className:"text-2xl font-semibold bg-primary text-primary-foreground",children:c})]}),s.jsx("h1",{className:"text-2xl font-bold text-slate-900 mb-0.5",children:a}),t.title&&s.jsx("p",{className:"text-sm font-medium text-primary mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&s.jsx("p",{className:"text-sm font-medium text-slate-500 mb-1",children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&s.jsx("p",{className:"text-xs font-medium text-slate-400 mb-3",children:t.team_name}),t.positioning_statement&&s.jsxs("p",{className:"text-base text-slate-600 italic leading-relaxed max-w-xs mx-auto",children:['"',t.positioning_statement,'"']})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[s.jsxs(Jt,{onClick:p,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[s.jsx(Ui,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),s.jsxs(Jt,{onClick:l,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[s.jsx(ug,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),s.jsxs(Jt,{onClick:g,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[s.jsx(rs,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),s.jsxs(Jt,{onClick:v,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[s.jsx(Cl,{className:"h-5 w-5 mr-2"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&s.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm text-slate-600",children:s.jsxs("div",{className:"text-center flex items-center gap-1",children:[s.jsx(Bd,{className:"h-4 w-4 text-amber-500 fill-amber-500"}),s.jsx("span",{className:"font-bold text-slate-900",children:"5.0"})]})}),t.review_snippet&&s.jsx("div",{className:"bg-slate-50 rounded-2xl p-4 mb-6 border border-slate-100",children:s.jsxs("p",{className:"text-sm text-slate-600 italic text-center",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&s.jsxs("div",{className:"mb-6",children:[s.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-2",children:"About Me"}),s.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:t.bio})]}),s.jsx(C5,{card:t,variant:"standard"}),s.jsx(N5,{cardId:t.id,variant:"standard"}),s.jsxs("div",{className:"space-y-2 mb-6",children:[t.show_save_contact&&s.jsxs(Jt,{variant:"ghost",onClick:E,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx($u,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs(Jt,{variant:"ghost",onClick:()=>{Vs(t.id,"button_click","review"),window.open(t.review_source_url,"_blank")},className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(Bd,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),t.show_refer_friend&&s.jsxs(Jt,{variant:"ghost",onClick:j,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(Dc,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),s.jsxs(Jt,{variant:"ghost",onClick:P,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(I4,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),s.jsxs(Jt,{variant:"ghost",onClick:T,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[s.jsx(RP,{className:"h-4 w-4 mr-3 text-primary"}),"Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&s.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((O,F)=>s.jsx("a",{href:O.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Vs(t.id,"button_click",`social_${O.platform}`),className:"h-10 w-10 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-lg transition-colors",children:C[O.platform.toLowerCase()]||"🔗"},F))}),s.jsx("div",{className:"text-center",children:s.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),s.jsx(P5,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:a})]})}function Hnt({card:t}){var L;const[e,r]=N.useState(!1),[n,i]=N.useState("booking"),a=((L=t.profile)==null?void 0:L.name)||"Agent",c=a.split(" ").map(O=>O[0]).join("").toUpperCase().slice(0,2),d=(O,F)=>{Vs(t.id,"button_click",O),F()},p=()=>d("call",()=>{var O;(O=t.profile)!=null&&O.phone?window.location.href=`tel:${t.profile.phone}`:lr.error("Phone number not available")}),l=()=>d("text",()=>{var O;(O=t.profile)!=null&&O.phone?window.location.href=`sms:${t.profile.phone}`:lr.error("Phone number not available")}),g=()=>d("email",()=>{var O;(O=t.profile)!=null&&O.email?window.location.href=`mailto:${t.profile.email}`:lr.error("Email not available")}),v=()=>{t.booking_url?d("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),Vs(t.id,"button_click","book"))},E=()=>{var O,F;Vs(t.id,"contact_saved"),R5({name:a,phone:(O=t.profile)==null?void 0:O.phone,email:(F=t.profile)==null?void 0:F.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},T=async()=>{Vs(t.id,"share_event");const O=`https://cards.relevelup.com/${t.slug}`,F="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${a}`,text:F,url:O})}catch{}else await navigator.clipboard.writeText(O),lr.success("Link copied!")},j=()=>{i("referral"),r(!0),Vs(t.id,"button_click","refer")},P=()=>{i("connect"),r(!0),Vs(t.id,"button_click","connect")},C={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return s.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-[#0f1419] via-[#1a1f2e] to-[#0f1419]",children:[s.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[s.jsx("div",{className:"w-16 h-0.5 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] mx-auto mb-8"}),s.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&s.jsxs(tf,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[s.jsx(rf,{src:t.avatar_url||void 0,alt:a}),s.jsx(nf,{className:"text-2xl font-serif bg-[#c9a84c]/20 text-[#e8d48b]",children:c})]}),s.jsx("h1",{className:"text-2xl font-serif font-bold text-white tracking-wide mb-0.5",children:a}),t.title&&s.jsx("p",{className:"text-sm font-medium text-[#e8d48b] mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&s.jsx("p",{className:"text-sm font-medium text-[#c9a84c] tracking-widest uppercase mb-1",children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&s.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:t.team_name}),t.positioning_statement&&s.jsxs("p",{className:"text-base text-[#a0aec0] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',t.positioning_statement,'"']})]}),s.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Ui,label:"Call",handler:p},{icon:ug,label:"Text",handler:l},{icon:rs,label:"Email",handler:g}].map(({icon:O,label:F,handler:$})=>s.jsxs("button",{onClick:$,className:"flex flex-col items-center gap-1.5 py-4 bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/20 rounded-xl transition-colors",children:[s.jsx(O,{className:"h-5 w-5 text-[#c9a84c]"}),s.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:F})]},F))}),s.jsxs("button",{onClick:v,className:"w-full h-12 text-base font-semibold rounded-xl mb-6 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] text-[#0f1419] hover:opacity-90 transition-opacity flex items-center justify-center gap-2",children:[s.jsx(Cl,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&s.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm",children:s.jsxs("div",{className:"text-center flex items-center gap-1",children:[s.jsx(Bd,{className:"h-4 w-4 text-[#c9a84c] fill-[#c9a84c]"}),s.jsx("span",{className:"font-bold text-white",children:"5.0"})]})}),t.review_snippet&&s.jsx("div",{className:"bg-[#1e2636] rounded-xl p-4 mb-6 border border-[#c9a84c]/10",children:s.jsxs("p",{className:"text-sm text-[#a0aec0] italic text-center font-serif",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&s.jsxs("div",{className:"mb-6",children:[s.jsx("h2",{className:"text-sm font-semibold text-[#c9a84c] mb-2 tracking-wide uppercase",children:"About"}),s.jsx("p",{className:"text-sm text-[#a0aec0] leading-relaxed",children:t.bio})]}),s.jsx(C5,{card:t,variant:"luxury"}),s.jsx(N5,{cardId:t.id,variant:"luxury"}),s.jsxs("div",{className:"space-y-1 mb-6",children:[t.show_save_contact&&s.jsxs("button",{onClick:E,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx($u,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs("button",{onClick:()=>{Vs(t.id,"button_click","review"),window.open(t.review_source_url,"_blank")},className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(Bd,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),t.show_refer_friend&&s.jsxs("button",{onClick:j,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(Dc,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),s.jsxs("button",{onClick:P,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(I4,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),s.jsxs("button",{onClick:T,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[s.jsx(RP,{className:"h-4 w-4 text-[#c9a84c]"})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&s.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((O,F)=>s.jsx("a",{href:O.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Vs(t.id,"button_click",`social_${O.platform}`),className:"h-10 w-10 rounded-full bg-[#1e2636] border border-[#c9a84c]/20 hover:border-[#c9a84c]/50 flex items-center justify-center text-lg transition-colors",children:C[O.platform.toLowerCase()]||"🔗"},F))}),s.jsx("div",{className:"text-center",children:s.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),s.jsx(P5,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:a})]})}function Wnt({card:t}){var F,$,G,W;const[e,r]=N.useState(!1),[n,i]=N.useState("booking"),a=((F=t.profile)==null?void 0:F.name)||"Agent",c=a.split(" ").map(Z=>Z[0]).join("").toUpperCase().slice(0,2),d={accent:(($=t.bold_theme_colors)==null?void 0:$.accent)||"#ff5722",dark:((G=t.bold_theme_colors)==null?void 0:G.dark)||"#1a1a2e",button:((W=t.bold_theme_colors)==null?void 0:W.button)||"#ff5722"},p=(Z,Q)=>{const ee=parseInt(Z.replace("#",""),16),ie=Math.max(0,(ee>>16)-Q),oe=Math.max(0,(ee>>8&255)-Q),pe=Math.max(0,(ee&255)-Q);return`#${(ie<<16|oe<<8|pe).toString(16).padStart(6,"0")}`};p(d.accent,25),p(d.dark,-20),p(d.button,25);const l=(Z,Q)=>{Vs(t.id,"button_click",Z),Q()},g=()=>l("call",()=>{var Z;(Z=t.profile)!=null&&Z.phone?window.location.href=`tel:${t.profile.phone}`:lr.error("Phone number not available")}),v=()=>l("text",()=>{var Z;(Z=t.profile)!=null&&Z.phone?window.location.href=`sms:${t.profile.phone}`:lr.error("Phone number not available")}),E=()=>l("email",()=>{var Z;(Z=t.profile)!=null&&Z.email?window.location.href=`mailto:${t.profile.email}`:lr.error("Email not available")}),T=()=>{t.booking_url?l("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),Vs(t.id,"button_click","book"))},j=()=>{var Z,Q;Vs(t.id,"contact_saved"),R5({name:a,phone:(Z=t.profile)==null?void 0:Z.phone,email:(Q=t.profile)==null?void 0:Q.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},P=async()=>{Vs(t.id,"share_event");const Z=`https://cards.relevelup.com/${t.slug}`,Q="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${a}`,text:Q,url:Z})}catch{}else await navigator.clipboard.writeText(Z),lr.success("Link copied!")},C=()=>{i("referral"),r(!0),Vs(t.id,"button_click","refer")},L=()=>{i("connect"),r(!0),Vs(t.id,"button_click","connect")},O={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return s.jsxs("div",{className:"min-h-screen",style:{backgroundColor:d.accent},children:[s.jsxs("div",{className:"px-5 pt-10 pb-14 text-center relative",style:{backgroundColor:d.dark},children:[t.show_photo&&s.jsxs(tf,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${d.accent}`},children:[s.jsx(rf,{src:t.avatar_url||void 0,alt:a}),s.jsx(nf,{className:"text-2xl font-black text-white",style:{backgroundColor:d.accent},children:c})]}),s.jsx("h1",{className:"text-3xl font-black text-white tracking-tight mb-0.5",children:a}),t.title&&s.jsx("p",{className:"text-sm font-bold mb-1",style:{color:`${d.accent}cc`},children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&s.jsx("p",{className:"text-sm font-bold uppercase tracking-wider mb-1",style:{color:d.accent},children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&s.jsx("p",{className:"text-xs font-bold text-white/60 uppercase tracking-wider",children:t.team_name})]}),s.jsxs("div",{className:"max-w-md mx-auto px-5 -mt-6",children:[s.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl px-5 py-8",children:[t.positioning_statement&&s.jsx("p",{className:"text-center font-bold text-lg leading-snug mb-6 max-w-xs mx-auto",style:{color:d.dark},children:t.positioning_statement}),s.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Ui,label:"Call",handler:g},{icon:ug,label:"Text",handler:v},{icon:rs,label:"Email",handler:E}].map(({icon:Z,label:Q,handler:ee})=>s.jsxs("button",{onClick:ee,className:"flex flex-col items-center gap-1.5 py-4 text-white rounded-2xl transition-opacity font-bold hover:opacity-85",style:{backgroundColor:d.dark},children:[s.jsx(Z,{className:"h-5 w-5"}),s.jsx("span",{className:"text-xs",children:Q})]},Q))}),s.jsxs("button",{onClick:T,className:"w-full h-14 text-base font-black rounded-2xl mb-6 text-white transition-opacity hover:opacity-90 flex items-center justify-center gap-2 uppercase tracking-wide",style:{backgroundColor:d.button},children:[s.jsx(Cl,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&s.jsx("div",{className:"flex items-center justify-center gap-5 mb-6",children:t.review_snippet&&s.jsxs("div",{className:"text-center flex items-center gap-1",children:[s.jsx(Bd,{className:"h-5 w-5",style:{color:d.accent,fill:d.accent}}),s.jsx("span",{className:"font-black text-2xl",style:{color:d.dark},children:"5.0"})]})}),t.review_snippet&&s.jsx("div",{className:"rounded-2xl p-4 mb-6",style:{backgroundColor:`${d.accent}15`},children:s.jsxs("p",{className:"text-sm font-medium text-center",style:{color:d.dark},children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&s.jsxs("div",{className:"mb-6",children:[s.jsx("h2",{className:"text-xs font-black mb-2 uppercase tracking-wider",style:{color:d.accent},children:"About Me"}),s.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:t.bio})]}),s.jsx(C5,{card:t,variant:"bold"}),s.jsx(N5,{cardId:t.id,variant:"bold"}),s.jsxs("div",{className:"space-y-1 mb-6",children:[t.show_save_contact&&s.jsxs("button",{onClick:j,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:d.dark},children:[s.jsx($u,{className:"h-4 w-4",style:{color:d.accent}})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs("button",{onClick:()=>{Vs(t.id,"button_click","review"),window.open(t.review_source_url,"_blank")},className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:d.dark},children:[s.jsx(Bd,{className:"h-4 w-4",style:{color:d.accent}})," Leave a Review"]}),t.show_refer_friend&&s.jsxs("button",{onClick:C,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:d.dark},children:[s.jsx(Dc,{className:"h-4 w-4",style:{color:d.accent}})," Refer a Friend"]}),s.jsxs("button",{onClick:L,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:d.dark},children:[s.jsx(I4,{className:"h-4 w-4",style:{color:d.accent}})," Connect with Me"]}),s.jsxs("button",{onClick:P,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:d.dark},children:[s.jsx(RP,{className:"h-4 w-4",style:{color:d.accent}})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&s.jsx("div",{className:"flex justify-center gap-4 mb-6",children:t.social_links.slice(0,3).map((Z,Q)=>s.jsx("a",{href:Z.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Vs(t.id,"button_click",`social_${Z.platform}`),className:"h-10 w-10 rounded-full flex items-center justify-center text-lg transition-opacity hover:opacity-85",style:{backgroundColor:d.dark},children:O[Z.platform.toLowerCase()]||"🔗"},Q))})]}),s.jsx("div",{className:"text-center py-6",children:s.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),s.jsx(P5,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:a})]})}function Knt({card:t}){var L;const[e,r]=N.useState(!1),[n,i]=N.useState("booking"),a=((L=t.profile)==null?void 0:L.name)||"Agent",c=a.split(" ").map(O=>O[0]).join("").toUpperCase().slice(0,2),d=(O,F)=>{Vs(t.id,"button_click",O),F()},p=()=>d("call",()=>{var O;(O=t.profile)!=null&&O.phone?window.location.href=`tel:${t.profile.phone}`:lr.error("Phone number not available")}),l=()=>d("text",()=>{var O;(O=t.profile)!=null&&O.phone?window.location.href=`sms:${t.profile.phone}`:lr.error("Phone number not available")}),g=()=>d("email",()=>{var O;(O=t.profile)!=null&&O.email?window.location.href=`mailto:${t.profile.email}`:lr.error("Email not available")}),v=()=>{t.booking_url?d("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),Vs(t.id,"button_click","book"))},E=()=>{var O,F;Vs(t.id,"contact_saved"),R5({name:a,phone:(O=t.profile)==null?void 0:O.phone,email:(F=t.profile)==null?void 0:F.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},T=async()=>{Vs(t.id,"share_event");const O=`https://cards.relevelup.com/${t.slug}`,F="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${a}`,text:F,url:O})}catch{}else await navigator.clipboard.writeText(O),lr.success("Link copied!")},j=()=>{i("referral"),r(!0),Vs(t.id,"button_click","refer")},P=()=>{i("connect"),r(!0),Vs(t.id,"button_click","connect")},C={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return s.jsxs("div",{className:"min-h-screen bg-[#f5f1eb]",children:[s.jsx("div",{className:"bg-[#1b3a4b] h-2"}),s.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[s.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&s.jsxs(tf,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[s.jsx(rf,{src:t.avatar_url||void 0,alt:a}),s.jsx(nf,{className:"text-2xl font-serif bg-[#1b3a4b] text-white",children:c})]}),s.jsx("h1",{className:"text-2xl font-serif font-bold text-[#1b3a4b] mb-0.5",children:a}),t.title&&s.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&s.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&s.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:t.team_name}),t.positioning_statement&&s.jsxs("p",{className:"text-base text-[#4a5568] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',t.positioning_statement,'"']})]}),s.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:Ui,label:"Call",handler:p},{icon:ug,label:"Text",handler:l},{icon:rs,label:"Email",handler:g}].map(({icon:O,label:F,handler:$})=>s.jsxs("button",{onClick:$,className:"flex flex-col items-center gap-1.5 py-4 bg-white hover:bg-[#e8e3db] border border-[#d4cfc5] rounded-lg transition-colors shadow-sm",children:[s.jsx(O,{className:"h-5 w-5 text-[#1b3a4b]"}),s.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:F})]},F))}),s.jsxs("button",{onClick:v,className:"w-full h-12 text-base font-semibold rounded-lg mb-6 bg-[#1b3a4b] hover:bg-[#264d61] text-white transition-colors flex items-center justify-center gap-2 shadow-sm",children:[s.jsx(Cl,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&s.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:s.jsx("div",{className:"flex items-center justify-center gap-6",children:s.jsxs("div",{className:"text-center flex items-center gap-1",children:[s.jsx(Bd,{className:"h-4 w-4 text-[#d4a843] fill-[#d4a843]"}),s.jsx("span",{className:"font-bold text-[#1b3a4b] font-serif",children:"5.0"})]})})}),t.review_snippet&&s.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:s.jsxs("p",{className:"text-sm text-[#4a5568] italic text-center font-serif",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&s.jsxs("div",{className:"mb-6",children:[s.jsx("h2",{className:"text-sm font-semibold text-[#1b3a4b] mb-2 font-serif",children:"About"}),s.jsx("p",{className:"text-sm text-[#4a5568] leading-relaxed",children:t.bio})]}),s.jsx(C5,{card:t,variant:"classic"}),s.jsx(N5,{cardId:t.id,variant:"classic"}),s.jsxs("div",{className:"bg-white rounded-lg border border-[#d4cfc5] shadow-sm divide-y divide-[#e8e3db] mb-6",children:[t.show_save_contact&&s.jsxs("button",{onClick:E,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx($u,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&s.jsxs("button",{onClick:()=>{Vs(t.id,"button_click","review"),window.open(t.review_source_url,"_blank")},className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(Bd,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),t.show_refer_friend&&s.jsxs("button",{onClick:j,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(Dc,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),s.jsxs("button",{onClick:P,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(I4,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),s.jsxs("button",{onClick:T,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[s.jsx(RP,{className:"h-4 w-4 text-[#5a7a6f]"})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&s.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((O,F)=>s.jsx("a",{href:O.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Vs(t.id,"button_click",`social_${O.platform}`),className:"h-10 w-10 rounded-full bg-white border border-[#d4cfc5] hover:bg-[#e8e3db] flex items-center justify-center text-lg transition-colors shadow-sm",children:C[O.platform.toLowerCase()]||"🔗"},F))}),s.jsx("div",{className:"text-center",children:s.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),s.jsx(P5,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:a})]})}function Ynt({card:t}){switch(t.theme){case"luxury":return s.jsx(Hnt,{card:t});case"bold":return s.jsx(Wnt,{card:t});case"classic":return s.jsx(Knt,{card:t});case"standard":default:return s.jsx(Gnt,{card:t})}}function Znt(t){if(!t)return null;try{const e=new URL(t),r=new URL("https://relzejiswnotikjgvjhz.supabase.co").host;return e.protocol!=="https:"||e.host!==r||!e.pathname.includes("/storage/v1/object/public/")?null:e.toString()}catch{return null}}function Xnt(t){return`https://docs.google.com/gview?url=${encodeURIComponent(t)}&embedded=true`}function Qnt(){if(typeof window>"u")return null;const t=Znt(new URLSearchParams(window.location.search).get("oh_disclosure"));return t?s.jsx("div",{className:"sticky top-0 z-50 bg-primary text-primary-foreground shadow-md",children:s.jsxs("div",{className:"mx-auto flex max-w-md items-center justify-between gap-3 px-4 py-2.5",children:[s.jsx("span",{className:"text-sm font-medium",children:"Thanks for visiting the open house!"}),s.jsxs("a",{href:Xnt(t),target:"_blank",rel:"noopener noreferrer",className:"inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-background px-3 py-1.5 text-xs font-semibold text-foreground",children:[s.jsx(lg,{className:"h-3.5 w-3.5"})," See Disclosures"]})]})}):null}function Jnt(){const t=ms();N.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]);const e=t.pathname.slice(1);return!e||e===""?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Agent Cards"}),s.jsx("p",{className:"text-slate-500",children:"Visit a specific agent's card URL to view their digital business card."})]})}):s.jsx(eit,{slug:e})}function eit({slug:t}){return s.jsx(tit,{slug:t})}function tit({slug:t}){var a;const{data:e,isLoading:r,error:n}=Ant(t);if(N.useEffect(()=>{e!=null&&e.id&&Vs(e.id,"card_view")},[e==null?void 0:e.id]),r)return s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:s.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[s.jsxs("div",{className:"flex flex-col items-center gap-4",children:[s.jsx(Mc,{className:"h-28 w-28 rounded-full"}),s.jsx(Mc,{className:"h-6 w-48"}),s.jsx(Mc,{className:"h-4 w-36"})]}),s.jsx(Mc,{className:"h-12 w-full"}),s.jsx(Mc,{className:"h-12 w-full"})]})});if(n||!e)return s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),s.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const i=((a=e.profile)==null?void 0:a.name)||"Agent";return s.jsxs(s.Fragment,{children:[s.jsxs(mc,{children:[s.jsxs("title",{children:[i," | Real Estate Agent"]}),s.jsx("meta",{name:"description",content:e.positioning_statement||`Connect with ${i}, your trusted real estate professional.`}),s.jsx("meta",{property:"og:title",content:`${i} | Real Estate Agent`}),s.jsx("meta",{property:"og:description",content:e.positioning_statement||`Connect with ${i}`}),e.avatar_url&&s.jsx("meta",{property:"og:image",content:e.avatar_url})]}),s.jsx(Qnt,{}),s.jsx(Ynt,{card:e})]})}function rit({presentationId:t,ctaLabel:e,agentName:r,prefillName:n,prefillEmail:i,prefillPhone:a}){const[c,d]=N.useState(n||""),[p,l]=N.useState(i||""),[g,v]=N.useState(a||""),[E,T]=N.useState(""),[j,P]=N.useState(""),[C,L]=N.useState(!1),[O,F]=N.useState(!1),$=async G=>{if(G.preventDefault(),!c.trim()){lr.error("Please enter your name");return}L(!0);try{const{error:W}=await Be.from("smart_presentation_leads").insert({presentation_id:t,name:c.trim(),email:p.trim()||null,phone:g.trim()||null,intent:E||null,message:j.trim()||null});if(W)throw W;try{await Be.rpc("log_presentation_view",{p_presentation_id:t,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}Be.functions.invoke("presentation-lead-notify",{body:{presentationId:t,name:c.trim(),email:p.trim()||void 0,phone:g.trim()||void 0,intent:E||void 0,message:j.trim()||void 0}}).catch(Z=>console.error("Presentation lead notify failed:",Z)),F(!0)}catch{lr.error("Something went wrong. Please try again.")}finally{L(!1)}};return O?s.jsxs("div",{className:"text-center py-8",children:[s.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-4",children:s.jsx(ql,{className:"h-8 w-8 text-emerald-600"})}),s.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),s.jsx("p",{className:"text-gray-500",children:r?`${r} will be in touch soon.`:"We'll be in touch soon."})]}):s.jsxs("form",{onSubmit:$,className:"space-y-4 max-w-md mx-auto",children:[s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"pres-lead-name",children:"Name *"}),s.jsx(hn,{id:"pres-lead-name",value:c,onChange:G=>d(G.target.value),placeholder:"Your name",required:!0})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"pres-lead-phone",children:"Phone"}),s.jsx(hn,{id:"pres-lead-phone",type:"tel",value:g,onChange:G=>v(G.target.value),placeholder:"(555) 123-4567"})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"pres-lead-email",children:"Email"}),s.jsx(hn,{id:"pres-lead-email",type:"email",value:p,onChange:G=>l(G.target.value),placeholder:"you@example.com"})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),s.jsxs(Xo,{value:E,onValueChange:T,children:[s.jsx(Mo,{children:s.jsx(Qo,{placeholder:"Select one"})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"buy",children:"Buy a home"}),s.jsx($n,{value:"sell",children:"Sell my home"}),s.jsx($n,{value:"both",children:"Buy & Sell"}),s.jsx($n,{value:"other",children:"Something else"})]})]})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"pres-lead-message",children:"Message (optional)"}),s.jsx(hn,{id:"pres-lead-message",value:j,onChange:G=>P(G.target.value),placeholder:"Anything you'd like us to know"})]}),s.jsx(Jt,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:C,children:C?"Sending...":e})]})}function nit(){const t=ms();N.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]);const e=t.pathname.slice(1);return!e||e===""?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Smart Presentations"}),s.jsx("p",{className:"text-slate-500",children:"Visit a specific presentation URL to view it."})]})}):s.jsx(iit,{shareToken:e})}function iit({shareToken:t}){var j;const[e,r]=N.useState(null),[n,i]=N.useState(!0),[a,c]=N.useState(0),[d,p]=N.useState(!1);N.useEffect(()=>{l()},[t]);const l=async()=>{const{data:P,error:C}=await Be.from("smart_presentations").select("*").eq("share_token",t).eq("status","published").single();if(C||!P){p(!0),i(!1);return}const{data:L}=await Be.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",P.owner_user_id).single();let O;if(L!=null&&L.brokerage_id){const{data:$}=await Be.from("brokerages").select("name").eq("id",L.brokerage_id).single();O=($==null?void 0:$.name)||void 0}let F=null;if(P.contact_id){const{data:$}=await Be.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",P.contact_id).single();F=$}r({...P,owner_name:L==null?void 0:L.name,owner_email:L==null?void 0:L.email,owner_phone:L==null?void 0:L.phone,owner_avatar:L==null?void 0:L.avatar_url,owner_title:(L==null?void 0:L.title)||void 0,brokerage_name:O,contact_name:F?[F.first_name,F.last_name].filter(Boolean).join(" "):void 0,contact_email:(F==null?void 0:F.email)||void 0,contact_phone:(F==null?void 0:F.phone)||void 0}),i(!1);try{await Be.rpc("log_presentation_view",{p_presentation_id:P.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},g=async()=>{if(e){try{await Be.rpc("log_presentation_view",{p_presentation_id:e.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}e.cta_url&&window.open(e.cta_url,"_blank")}},v=P=>{const C=P.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(C)return`https://www.youtube.com/embed/${C[1]}?rel=0`;if(P.includes("iframe.mediadelivery.net/play/")){const F=P.replace("/play/","/embed/"),$=F.includes("?")?"&":"?";return`${F}${$}responsive=true`}if(P.includes("iframe.mediadelivery.net")){const F=P.includes("?")?"&":"?";return`${P}${F}responsive=true`}const L=P.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(L)return`https://www.loom.com/embed/${L[1]}`;const O=P.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return O?`https://iframe.mediadelivery.net/embed/${O[1]}/${O[2]}?responsive=true`:P};if(n)return s.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:s.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[s.jsx(Mc,{className:"h-12 w-3/4 mx-auto"}),s.jsx(Mc,{className:"h-64 w-full"}),s.jsx(Mc,{className:"h-8 w-1/2 mx-auto"})]})});if(d||!e)return s.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),s.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const E=e.sections.filter(P=>P.is_visible!==!1),T=E[a];return s.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[s.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:s.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:s.jsxs("div",{className:"flex items-center gap-3",children:[e.owner_avatar&&s.jsx("img",{src:e.owner_avatar,alt:e.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),s.jsxs("div",{className:"text-right text-sm",children:[s.jsx("p",{className:"font-semibold text-gray-900",children:e.owner_name}),e.owner_title&&s.jsx("p",{className:"text-gray-500 text-xs",children:e.owner_title}),e.brokerage_name&&!e.owner_title&&s.jsx("p",{className:"text-gray-500 text-xs",children:e.brokerage_name})]})]})})}),s.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[s.jsxs("div",{className:"text-center mb-8",children:[s.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:e.heading||(e.client_name?`Welcome, ${e.client_name}!`:e.title)}),e.property_address&&s.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",s.jsx("strong",{children:e.property_address}),"."]})]}),s.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[s.jsxs("div",{className:"md:col-span-3",children:[T!=null&&T.video_url?s.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:s.jsx("iframe",{src:v(T.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):T!=null&&T.image_url?s.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:s.jsx("img",{src:T.image_url,alt:T.title,className:"w-full h-auto object-cover",loading:"lazy"})}):s.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[s.jsx("span",{className:"text-5xl mb-3",children:T==null?void 0:T.icon}),s.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:T==null?void 0:T.title}),s.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:T==null?void 0:T.description})]}),(T==null?void 0:T.text)&&s.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:T.text}})]}),s.jsx("div",{className:"md:col-span-2 space-y-3",children:E.map((P,C)=>s.jsx("button",{onClick:()=>c(C),className:hr("w-full text-left p-4 rounded-xl border transition-all",a===C?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(C+1).padStart(2,"0"),"."]}),s.jsxs("div",{children:[s.jsx("span",{className:"mr-2",children:P.icon}),s.jsx("span",{className:"font-semibold text-gray-900",children:P.title}),s.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:P.description})]})]})},C))})]}),s.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[e.owner_avatar&&s.jsx("img",{src:e.owner_avatar,alt:e.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),s.jsx("h3",{className:"text-lg font-bold text-gray-900",children:e.owner_name}),e.owner_title&&s.jsx("p",{className:"text-sm text-gray-500",children:e.owner_title}),e.brokerage_name&&s.jsx("p",{className:"text-sm text-gray-500",children:e.brokerage_name}),s.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[e.owner_phone&&s.jsx("a",{href:`tel:${e.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:e.owner_phone}),e.owner_email&&s.jsx("a",{href:`mailto:${e.owner_email}`,className:"hover:text-blue-600 transition-colors",children:e.owner_email})]})]}),e.cta_label&&s.jsxs("div",{className:"text-center mt-8 py-8",children:[s.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(j=e.cta_url)!=null&&j.trim()?s.jsxs(Jt,{size:"lg",onClick:g,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[e.cta_label,s.jsx(rA,{className:"h-5 w-5 ml-2"})]}):s.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:s.jsx(rit,{presentationId:e.id,ctaLabel:e.cta_label,agentName:e.owner_name||void 0,prefillName:e.contact_name,prefillEmail:e.contact_email,prefillPhone:e.contact_phone})})]})]}),s.jsx("footer",{className:"border-t border-gray-100 bg-white mt-12 py-6 text-center text-xs text-gray-400",children:"Powered by LevelUp"})]})}function NYt(){const{user:t}=_i(),e=qs(),{data:r}=_A();return jr({queryKey:["open-houses",e,r==null?void 0:r.teamId,r==null?void 0:r.role],queryFn:async()=>{const{data:n,error:i}=await Be.from("open_houses").select("*").eq("agent_id",e).order("event_date",{ascending:!1});if(i)throw i;let a=n||[];if((r==null?void 0:r.role)==="team_leader"&&r.teamId){const{data:c,error:d}=await Be.rpc("get_team_open_houses",{_user_id:e});if(!d&&c){const p=[...new Set(c.map(v=>v.agent_id))],l={};if(p.length>0){const{data:v}=await Be.from("profiles").select("id, name").in("id",p);v==null||v.forEach(E=>{E.name&&(l[E.id]=E.name)})}const g=c.map(v=>({...v,agent_name:l[v.agent_id]||void 0}));a=[...a,...g]}}return a.sort((c,d)=>d.event_date.localeCompare(c.event_date)),a},enabled:!!t&&!!e})}function RYt(t){const{user:e}=_i();return jr({queryKey:["open-house",t],queryFn:async()=>{const{data:r,error:n}=await Be.from("open_houses").select("*").eq("id",t).single();if(n)throw n;return r},enabled:!!e&&!!t})}function LYt(t){const{user:e}=_i(),r=Ur();return N.useEffect(()=>{if(!t)return;const n=`visitors-${t}-${Math.random().toString(36).slice(2,10)}`,i=Be.channel(n).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${t}`},()=>{r.invalidateQueries({queryKey:["open-house-visitors",t]}),r.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{Be.removeChannel(i)}},[t,r]),jr({queryKey:["open-house-visitors",t],queryFn:async()=>{const{data:n,error:i}=await Be.from("open_house_visitors").select("*").eq("open_house_id",t).order("created_at",{ascending:!1});if(i)throw i;return n},enabled:!!e&&!!t})}function DYt(){const t=Ur(),e=qs();return zr({mutationFn:async r=>{const{data:n,error:i}=await Be.from("open_houses").insert({...r,agent_id:e}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["open-houses"]}),ba({title:"Open house created!"})},onError:r=>{ba({title:"Error",description:r.message,variant:"destructive"})}})}function MYt(){const t=Ur();return zr({mutationFn:async({id:e,...r})=>{const{error:n}=await Be.from("open_houses").update(r).eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-houses"]}),t.invalidateQueries({queryKey:["open-house",r.id]})}})}function OYt(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("open_houses").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["open-houses"]}),ba({title:"Open house deleted"})}})}function DEe(t){return jr({queryKey:["public-open-house",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",t).eq("is_active",!0).single();if(r)throw r;let n=null;if(e.agent_id){const{data:i}=await Be.from("agent_cards").select("slug").eq("user_id",e.agent_id).eq("is_published",!0).maybeSingle();i&&(n=i.slug)}return{...e,agent_card_slug:n}},enabled:!!t})}function FYt(t){const{user:e}=_i();return jr({queryKey:["survey-questions",t],queryFn:async()=>{const{data:r,error:n}=await Be.from("open_house_survey_questions").select("*").eq("open_house_id",t).order("sort_order");if(n)throw n;return r},enabled:!!e&&!!t})}function sit(t){return jr({queryKey:["public-survey-questions",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("open_house_survey_questions").select("*").eq("open_house_id",t).eq("is_active",!0).order("sort_order");if(r)throw r;return e},enabled:!!t})}function ait(){return zr({mutationFn:async t=>{const{error:e}=await Be.from("open_house_survey_responses").insert(t);if(e)throw e}})}function BYt(t){const{user:e}=_i();return jr({queryKey:["survey-responses",t],queryFn:async()=>{const{data:r,error:n}=await Be.from("open_house_survey_questions").select("*").eq("open_house_id",t).order("sort_order");if(n)throw n;const i=(r||[]).map(d=>d.id);if(i.length===0)return{questions:[],responses:[]};const{data:a,error:c}=await Be.from("open_house_survey_responses").select("*").in("question_id",i).order("created_at",{ascending:!1});if(c)throw c;return{questions:r,responses:a||[]}},enabled:!!e&&!!t})}function zYt(){const t=Ur();return zr({mutationFn:async e=>{const{data:r,error:n}=await Be.from("open_house_survey_questions").insert(e).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function $Yt(){const t=Ur();return zr({mutationFn:async({id:e,open_house_id:r,...n})=>{const{error:i}=await Be.from("open_house_survey_questions").update(n).eq("id",e);if(i)throw i},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function UYt(){const t=Ur();return zr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Be.from("open_house_survey_questions").delete().eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["survey-questions",r.open_house_id]})}})}function VYt(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.rpc("seed_default_survey_questions",{_open_house_id:e});if(r)throw r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["survey-questions",r]})}})}function oit(){return zr({mutationFn:async t=>{const e=crypto.randomUUID(),{error:r}=await Be.from("open_house_visitors").insert({...t,id:e});if(r)throw r;return{id:e}}})}function lit(){return zr({mutationFn:async({visitor_id:t,...e})=>{const{error:r}=await Be.from("open_house_visitors").update(e).eq("id",t);if(r)throw r}})}function cit(){return zr({mutationFn:async t=>{await Be.rpc("increment_open_house_scan",{_slug:t})}})}async function MEe(t){const{data:e,error:r}=await Be.from("open_house_rooms").select("*").eq("open_house_id",t).order("sort_order");if(r)throw r;const n=e||[];if(n.length===0)return[];const i=n.map(p=>p.id),{data:a,error:c}=await Be.from("open_house_room_media").select("*").in("room_id",i).order("sort_order");if(c)throw c;const d={};return(a||[]).forEach(p=>{var g;const l=p;(d[g=l.room_id]||(d[g]=[])).push(l)}),n.map(p=>({...p,media:d[p.id]||[]}))}function qYt(t){const{user:e}=_i();return jr({queryKey:["open-house-rooms",t],queryFn:()=>MEe(t),enabled:!!e&&!!t})}function uit(t){return jr({queryKey:["public-open-house-rooms",t],queryFn:()=>MEe(t),enabled:!!t})}function GYt(){const t=Ur();return zr({mutationFn:async e=>{const{data:r,error:n}=await Be.from("open_house_rooms").insert(e).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function HYt(){const t=Ur();return zr({mutationFn:async({id:e,open_house_id:r,...n})=>{const{error:i}=await Be.from("open_house_rooms").update(n).eq("id",e);if(i)throw i},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function WYt(){const t=Ur();return zr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Be.from("open_house_rooms").delete().eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function KYt(){const t=Ur();return zr({mutationFn:async({open_house_id:e,...r})=>{const{data:n,error:i}=await Be.from("open_house_room_media").insert(r).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function YYt(){const t=Ur();return zr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Be.from("open_house_room_media").delete().eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rooms",r.open_house_id]})}})}function ZYt(){const t=Ur();return zr({mutationFn:async({open_house_id:e,orderedIds:r})=>{for(let n=0;n{const n=["open-house-rooms",e];await t.cancelQueries({queryKey:n});const i=t.getQueryData(n);if(i){const a=new Map(i.map(d=>[d.id,d])),c=r.map((d,p)=>({...a.get(d),sort_order:p})).filter(Boolean);t.setQueryData(n,c)}return{prev:i,key:n}},onError:(e,r,n)=>{n!=null&&n.prev&&t.setQueryData(n.key,n.prev)},onSettled:(e,r,n)=>{t.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function XYt(){const t=Ur();return zr({mutationFn:async({open_house_id:e,room_id:r,orderedIds:n})=>{for(let i=0;i{const i=["open-house-rooms",e];await t.cancelQueries({queryKey:i});const a=t.getQueryData(i);return a&&t.setQueryData(i,a.map(c=>{if(c.id!==r)return c;const d=new Map(c.media.map(p=>[p.id,p]));return{...c,media:n.map((p,l)=>{const g=d.get(p);return g?{...g,sort_order:l}:null}).filter(Boolean)}})),{prev:a,key:i}},onError:(e,r,n)=>{n!=null&&n.prev&&t.setQueryData(n.key,n.prev)},onSettled:(e,r,n)=>{t.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function QYt(t){const{user:e}=_i();return jr({queryKey:["open-house-leads",t],queryFn:async()=>{const{data:r,error:n}=await Be.from("open_house_leads").select("*").eq("open_house_id",t).order("created_at",{ascending:!1});if(n)throw n;return r||[]},enabled:!!e&&!!t})}function JYt(){const t=Ur();return zr({mutationFn:async({id:e,status:r,open_house_id:n})=>{const{error:i}=await Be.from("open_house_leads").update({status:r}).eq("id",e);if(i)throw i;return{open_house_id:n}},onSuccess:e=>{t.invalidateQueries({queryKey:["open-house-leads",e.open_house_id]})}})}var dit=Object.defineProperty,kv=(t,e)=>dit(t,"name",{value:e,configurable:!0}),oZ="Switch",[hit,eZt]=Nl(oZ),[fit,lZ]=hit(oZ);function OEe(t){const{__scopeSwitch:e,checked:r,children:n,defaultChecked:i,disabled:a,form:c,name:d,onCheckedChange:p,required:l,value:g="on",internal_do_not_use_render:v}=t,[E,T]=ph({prop:r,defaultProp:i??!1,onChange:p,caller:oZ}),[j,P]=N.useState(null),[C,L]=N.useState(null),[O,F]=N.useState(null),$=j?!!c||!!j.closest("form"):!0,G={checked:E,setChecked:T,disabled:a,control:j,setControl:P,name:d,form:c,value:g,userClick:O,onUserClick:F,required:l,defaultChecked:i,isFormControl:$,bubbleInput:C,setBubbleInput:L};return s.jsx(fit,{scope:e,...G,children:BEe(v)?v(G):n})}kv(OEe,"SwitchProvider");var mit="SwitchTrigger",pit=N.forwardRef(kv(function({__scopeSwitch:e,onClick:r,...n},i){const{control:a,form:c,value:d,disabled:p,checked:l,required:g,setControl:v,setChecked:E,onUserClick:T,isFormControl:j,bubbleInput:P}=lZ(mit,e),C=Jn(i,v),L=N.useRef(l);return N.useEffect(()=>{const O=c?a==null?void 0:a.ownerDocument.getElementById(c):a==null?void 0:a.form;if(O instanceof HTMLFormElement){const F=kv(()=>E(L.current),"reset");return O.addEventListener("reset",F),()=>O.removeEventListener("reset",F)}},[a,c,E]),s.jsx(An.button,{type:"button",role:"switch","aria-checked":l,"aria-required":g,"data-state":cZ(l),"data-disabled":p?"":void 0,disabled:p,value:d,...n,ref:C,onClick:Qr(r,O=>{const F=O.isPropagationStopped();T({requestedChecked:!l,hasConsumerStoppedPropagation:F}),E($=>!$),P&&j&&(F||O.stopPropagation())})})},"SwitchTrigger")),FEe=N.forwardRef(kv(function(e,r){const{__scopeSwitch:n,name:i,checked:a,defaultChecked:c,required:d,disabled:p,value:l,onCheckedChange:g,form:v,...E}=e;return s.jsx(OEe,{__scopeSwitch:n,checked:a,defaultChecked:c,disabled:p,required:d,onCheckedChange:g,name:i,form:v,value:l,internal_do_not_use_render:({isFormControl:T})=>s.jsxs(s.Fragment,{children:[s.jsx(pit,{...E,ref:r,__scopeSwitch:n}),T&&s.jsx(_it,{__scopeSwitch:n})]})})},"Switch")),git="SwitchThumb",yit=N.forwardRef(kv(function(e,r){const{__scopeSwitch:n,...i}=e,a=lZ(git,n);return s.jsx(An.span,{"data-state":cZ(a.checked),"data-disabled":a.disabled?"":void 0,...i,ref:r})},"SwitchThumb")),xit="SwitchBubbleInput",_it=N.forwardRef(kv(function({__scopeSwitch:e,onClick:r,...n},i){const{control:a,userClick:c,checked:d,defaultChecked:p,required:l,disabled:g,name:v,value:E,form:T,bubbleInput:j,setBubbleInput:P}=lZ(xit,e),C=Jn(i,P),L=dA(a),O=N.useRef(!1),F=N.useRef(d),$=N.useRef(c),G=N.useRef(null);N.useEffect(()=>{const Z=j;if(!Z)return;const Q=window.HTMLInputElement.prototype,ie=Object.getOwnPropertyDescriptor(Q,"checked").set;if(!ie)return;const oe=F.current!==d;F.current=d;const pe=c!==null&&c!==$.current;if($.current=c,pe)G.current=oe?null:c,oe&&ie.call(Z,d),Z.dispatchEvent(new Event("click",{bubbles:!c.hasConsumerStoppedPropagation}));else if(oe){const Le=G.current;G.current=null;const be=(Le==null?void 0:Le.requestedChecked)===d;O.current=!0,ie.call(Z,d),Z.dispatchEvent(new Event("click",{bubbles:!(be&&Le.hasConsumerStoppedPropagation)})),O.current=!1}},[j,d,c]);const W=N.useRef(d);return s.jsx(An.input,{type:"checkbox","aria-hidden":!0,defaultChecked:p??W.current,required:l,disabled:g,name:v,value:E,form:T,...n,tabIndex:-1,ref:C,onClick:Qr(r,Z=>{O.current&&Z.stopPropagation()}),style:{...n.style,...L,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function BEe(t){return typeof t=="function"}kv(BEe,"isFunction");function cZ(t){return t?"checked":"unchecked"}kv(cZ,"getState");const TA=N.forwardRef(({className:t,...e},r)=>s.jsx(FEe,{className:hr("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",t),...e,ref:r,children:s.jsx(yit,{className:hr("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));TA.displayName=FEe.displayName;const vit=["Excellent","Good","Neutral","Bad","Very Bad"],bit=[5,4,3,2,1];function wit({questions:t,visitorId:e,onComplete:r,onSkip:n}){const i=ait(),[a,c]=N.useState({}),d=t.filter(E=>E.question_type==="rating"),p=t.filter(E=>E.question_type!=="rating"),l=(E,T)=>{c(j=>({...j,[E]:{rating_value:T}}))},g=(E,T)=>{c(j=>({...j,[E]:{text_value:T}}))},v=async()=>{const E=Object.entries(a).filter(([,T])=>T.rating_value!=null||T.text_value&&T.text_value.trim()).map(([T,j])=>{var P;return{visitor_id:e,question_id:T,rating_value:j.rating_value??null,text_value:((P=j.text_value)==null?void 0:P.trim())||null}});if(E.length>0)try{await i.mutateAsync(E)}catch{}r()};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Quick Feedback"}),s.jsx("button",{onClick:n,className:"text-sm text-slate-400 hover:text-slate-600 underline",children:"Skip"})]}),s.jsx("p",{className:"text-sm text-slate-500 -mt-2",children:"Your feedback helps the agent — totally optional!"}),d.length>0&&s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("div",{className:"flex-1"}),vit.map(E=>s.jsx("div",{className:"w-12 text-center",children:s.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:E})},E))]}),d.map(E=>s.jsxs("div",{className:"flex items-center gap-1 py-1.5 border-b border-slate-100 last:border-0",children:[s.jsx("span",{className:"flex-1 text-sm text-slate-700 pr-2",children:E.question_text}),bit.map(T=>{var j;return s.jsx("div",{className:"w-12 flex justify-center",children:s.jsx("button",{type:"button",onClick:()=>l(E.id,T),className:`w-6 h-6 rounded-full border-2 transition-all ${((j=a[E.id])==null?void 0:j.rating_value)===T?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},T)})]},E.id))]}),p.map(E=>{var T;return s.jsxs("div",{children:[s.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:E.question_text}),s.jsx(df,{value:((T=a[E.id])==null?void 0:T.text_value)||"",onChange:j=>g(E.id,j.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},E.id)}),s.jsx(Jt,{onClick:v,disabled:i.isPending,className:"w-full h-12 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:i.isPending?s.jsx(gh,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function l9(t){return/iframe\.mediadelivery\.net\/embed\//.test(t)}function Sit({rooms:t}){var P;const[e,r]=N.useState(((P=t[0])==null?void 0:P.id)||""),[n,i]=N.useState(null),[a,c]=N.useState(null),d=N.useRef({}),p=t.find(C=>C.id===n)||t[0],l=a!==null?p==null?void 0:p.media[a]:null,g=(p==null?void 0:p.media.length)??0,v=()=>{c(null),i(null)},E=()=>c(C=>C===null||g===0?C:(C-1+g)%g),T=()=>c(C=>C===null||g===0?C:(C+1)%g);N.useEffect(()=>{if(a===null)return;const C=L=>{L.key==="Escape"?v():L.key==="ArrowLeft"?E():L.key==="ArrowRight"&&T()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[a,g]),N.useEffect(()=>{const C=new IntersectionObserver(L=>{const O=L.filter(F=>F.isIntersecting).sort((F,$)=>F.boundingClientRect.top-$.boundingClientRect.top);O[0]&&r(O[0].target.dataset.roomId||"")},{rootMargin:"-90px 0px -55% 0px"});return Object.values(d.current).forEach(L=>L&&C.observe(L)),()=>C.disconnect()},[t]);const j=C=>{r(C);const L=d.current[C];L&&window.scrollTo({top:L.getBoundingClientRect().top+window.scrollY-80,behavior:"smooth"})};return t.length?s.jsxs("div",{className:"hidden md:block",children:[s.jsx("div",{className:"sticky top-0 z-20 -mx-5 px-5 py-3 bg-slate-950/80 backdrop-blur-md border-b border-white/10 overflow-x-auto",children:s.jsx("div",{className:"flex gap-2 min-w-max",children:t.map(C=>s.jsxs("button",{onClick:()=>j(C.id),className:hr("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",e===C.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[C.name,s.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:C.media.length})]},C.id))})}),t.map(C=>s.jsxs("section",{"data-room-id":C.id,ref:L=>{d.current[C.id]=L},className:"mt-10 first:mt-6",children:[s.jsx("h3",{className:"text-2xl font-bold",children:C.name}),C.description&&s.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:C.description}),C.media.length===0?s.jsx("p",{className:"text-white/40 text-sm mt-6 italic",children:"No media yet for this room."}):s.jsx("div",{className:"mt-5 grid grid-cols-2 gap-4",children:C.media.map((L,O)=>s.jsx("button",{onClick:()=>{i(C.id),c(O)},className:hr("relative aspect-[3/2] rounded-xl overflow-hidden bg-white/5 group",O===0&&C.media.length!==2&&"col-span-2 aspect-[16/9]"),children:L.kind==="video"?s.jsxs(s.Fragment,{children:[l9(L.url)?s.jsx("div",{className:"absolute inset-0 bg-slate-900"}):s.jsx("video",{src:L.url,className:"w-full h-full object-cover"}),s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/50 transition",children:s.jsx("div",{className:"w-14 h-14 rounded-full bg-white/90 flex items-center justify-center",children:s.jsx(rj,{className:"h-6 w-6 text-slate-900"})})})]}):s.jsx("img",{src:L.url,alt:C.name,loading:"lazy",className:"w-full h-full object-cover group-hover:scale-[1.03] transition-transform duration-500"})},L.id))})]},C.id)),l&&p&&s.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:v,children:[s.jsxs("div",{className:"absolute top-5 left-1/2 -translate-x-1/2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-xs font-medium",children:[p.name," — ",(a??0)+1," / ",g]}),s.jsx("button",{onClick:C=>{C.stopPropagation(),v()},className:"absolute top-5 right-5 h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 text-white text-xl flex items-center justify-center transition","aria-label":"Close",children:"×"}),g>1&&s.jsx("button",{onClick:C=>{C.stopPropagation(),E()},className:"absolute left-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Previous",children:s.jsx(bg,{className:"h-6 w-6"})}),l.kind==="video"?l9(l.url)?s.jsx("iframe",{src:`${l.url}?autoplay=true`,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full max-w-5xl aspect-video rounded-lg",onClick:C=>C.stopPropagation()},l.url):s.jsx("video",{src:l.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:C=>C.stopPropagation()},l.url):s.jsx("img",{src:l.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:C=>C.stopPropagation()}),g>1&&s.jsx("button",{onClick:C=>{C.stopPropagation(),T()},className:"absolute right-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Next",children:s.jsx(uf,{className:"h-6 w-6"})})]})]}):null}function Eit({rooms:t}){var d;const e=[];t.forEach(p=>{e.push({type:"cover",roomId:p.id,roomName:p.name,description:p.description,mediaCount:p.media.length}),p.media.forEach((l,g)=>{e.push({type:"media",roomId:p.id,roomName:p.name,url:l.url,kind:l.kind,index:g,total:p.media.length})})});const r=N.useRef(null),[n,i]=N.useState(0);N.useEffect(()=>{const p=r.current;if(!p)return;let l=0;const g=()=>{cancelAnimationFrame(l),l=requestAnimationFrame(()=>{const v=Math.round(p.scrollLeft/p.clientWidth);i(v)})};return p.addEventListener("scroll",g,{passive:!0}),()=>{p.removeEventListener("scroll",g),cancelAnimationFrame(l)}},[]);const a=p=>{const l=r.current;l&&l.scrollTo({left:p*l.clientWidth,behavior:"smooth"})};if(!e.length)return null;const c=(d=e[n])==null?void 0:d.roomId;return s.jsxs("div",{className:"md:hidden -mx-5",children:[s.jsx("div",{className:"px-5 py-3 overflow-x-auto sticky top-0 z-20 bg-slate-950/80 backdrop-blur-md border-b border-white/10",children:s.jsx("div",{className:"flex gap-2 min-w-max",children:t.map(p=>{const l=e.findIndex(v=>v.roomId===p.id),g=c===p.id;return s.jsx("button",{onClick:()=>a(l),className:hr("px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition",g?"bg-white text-slate-900":"bg-white/10 text-white/80"),children:p.name},p.id)})})}),s.jsx("div",{ref:r,className:"flex overflow-x-auto snap-x snap-mandatory scroll-smooth no-scrollbar",style:{scrollSnapType:"x mandatory"},children:e.map((p,l)=>s.jsx("div",{className:"shrink-0 w-screen snap-center",children:s.jsxs("div",{className:"w-full aspect-[9/16] max-h-[75vh] bg-slate-900 relative",children:[p.type==="cover"?s.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center p-8 text-center bg-gradient-to-br from-slate-800 to-slate-950",children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-white/40 mb-2",children:"Next room"}),s.jsx("h3",{className:"text-3xl font-bold",children:p.roomName}),p.description&&s.jsx("p",{className:"text-white/70 text-sm mt-3 max-w-xs",children:p.description}),s.jsxs("p",{className:"text-white/40 text-xs mt-5",children:[p.mediaCount," ",p.mediaCount===1?"item":"items"," — swipe to view →"]})]}):p.kind==="video"?l9(p.url)?s.jsx("iframe",{src:p.url,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full h-full"}):s.jsx("video",{src:p.url,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):s.jsx("img",{src:p.url,alt:p.roomName,className:"w-full h-full object-cover"}),p.type==="media"&&s.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-center justify-between pointer-events-none",children:[s.jsx("div",{className:"px-3 py-1 rounded-full bg-black/50 backdrop-blur-sm text-xs text-white font-medium",children:p.roomName}),s.jsxs("div",{className:"px-2.5 py-1 rounded-full bg-black/50 backdrop-blur-sm text-[10px] text-white/80",children:[p.index+1," / ",p.total]})]})]})},l))}),s.jsxs("div",{className:"flex items-center justify-between px-5 mt-3",children:[s.jsxs("button",{onClick:()=>a(Math.max(0,n-1)),disabled:n===0,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:[s.jsx(bg,{className:"h-4 w-4"})," Prev"]}),s.jsxs("span",{className:"text-xs text-white/50",children:[n+1," / ",e.length]}),s.jsxs("button",{onClick:()=>a(Math.min(e.length-1,n+1)),disabled:n===e.length-1,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:["Next ",s.jsx(uf,{className:"h-4 w-4"})]})]})]})}const FU={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:ug},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:Cl},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:lg},offer:{label:"I'm Interested — Let's Talk",title:"Express interest / make an offer",placeholder:"Tell the agent about your interest or any offer thoughts.",icon:Cy}},Tit=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function Ait(t){return t==null||t<=0?null:`$${t.toLocaleString("en-US")}`}function kit({openHouse:t,visitorId:e,visitorName:r,visitorEmail:n,visitorPhone:i,previewMode:a=!1}){var cr;const c=t.profiles,d=((cr=c==null?void 0:c.name)==null?void 0:cr.split(" ").map(ft=>ft[0]).join("").slice(0,2))||"?",p=t.brand_color_override||null,[l,g]=N.useState(null),[v,E]=N.useState(""),[T,j]=N.useState(n||""),[P,C]=N.useState(i||""),[L,O]=N.useState(!1),[F,$]=N.useState(null),[G,W]=N.useState(""),[Z,Q]=N.useState(""),[ee,ie]=N.useState(""),[oe,pe]=N.useState([]),[Le,be]=N.useState(""),[Re,Ie]=N.useState(""),[Te,ge]=N.useState(""),[$e,we]=N.useState(""),ke=Ait(t.price),Ae=t.tour_mode==="rooms",{data:He=[]}=uit(Ae?t.id:void 0),ot=[t.enable_question&&"question",t.enable_showing&&"showing",t.enable_disclosures&&"disclosure",t.enable_offer&&"offer"].filter(Boolean),nt=ft=>{g(ft),E(""),W(""),Q(""),ie(""),pe([]),be(""),Ie(""),ge(""),we("")},tt=()=>{g(null)},vt=ft=>{pe(Kt=>Kt.includes(ft)?Kt.filter(ir=>ir!==ft):[...Kt,ft])},Vt=ft=>ft==="showing"?{preferred_date:G||null,preferred_time:Z||null,alternate_date:ee||null}:ft==="disclosure"?{requested_documents:oe}:ft==="offer"?{offer_amount:Le||null,financing:Re||null,timeline:Te||null,pre_approved:$e||null}:{},Ct=l?l==="showing"?!!G:l==="question"?v.trim().length>0:!0:!1,Bt=async()=>{if(l){if(a){ba({title:"Preview mode",description:"Lead not sent — this is just a preview."}),$(l),setTimeout(()=>{g(null),$(null)},1500);return}O(!0);try{const ft=Vt(l),{error:Kt}=await Be.from("open_house_leads").insert({open_house_id:t.id,visitor_id:e,action_type:l,payload:{message:v.trim()||null,email:T.trim()||null,phone:P.trim()||null,visitor_name:r,...ft}});if(Kt)throw Kt;Be.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:t.id,visitor_id:e,action_type:l,message:v.trim()||null,visitor_name:r,visitor_email:T.trim()||null,visitor_phone:P.trim()||null,extras:ft}}).catch(()=>{}),$(l),ba({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{tt(),$(null)},1400)}catch(ft){ba({title:"Something went wrong",description:ft.message,variant:"destructive"})}finally{O(!1)}}};return s.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[s.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[t.hero_video_url?s.jsx("video",{src:t.hero_video_url,poster:t.hero_video_thumbnail_url||t.photo_url||void 0,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):t.photo_url?s.jsx("img",{src:t.photo_url,alt:t.property_address,className:"w-full h-full object-cover"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),s.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),s.jsxs("div",{className:"max-w-5xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[s.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[s.jsx("h1",{className:"text-2xl font-bold leading-tight",children:t.property_address}),t.city&&s.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[s.jsx(Va,{className:"h-3.5 w-3.5"}),t.city,t.state?`, ${t.state}`:""," ",t.zip]}),ke&&s.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:ke}),s.jsxs("div",{className:"flex flex-wrap gap-4 mt-4 text-sm text-white/80",children:[t.beds!=null&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tA,{className:"h-4 w-4"}),t.beds," bd"]}),t.baths!=null&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ww,{className:"h-4 w-4"}),t.baths," ba"]}),t.sqft!=null&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(JW,{className:"h-4 w-4"}),t.sqft.toLocaleString()," sqft"]})]}),t.property_description?s.jsx("p",{className:"text-white/80 text-sm mt-5 whitespace-pre-wrap leading-relaxed",children:t.property_description}):t.agent_greeting&&s.jsxs("p",{className:"text-white/70 text-sm mt-5 border-l-2 border-white/20 pl-3 italic",children:['"',t.agent_greeting,'"']})]}),c&&s.jsxs("div",{className:"mt-5 flex items-center gap-3 bg-white/5 border border-white/10 rounded-xl p-4",children:[t.team_photo_url?s.jsx("img",{src:t.team_photo_url,alt:c.name||"Team",className:"h-16 w-24 shrink-0 rounded-lg object-cover ring-2 ring-white/20"}):s.jsxs(s.Fragment,{children:[s.jsxs(tf,{className:"h-12 w-12 ring-2 ring-white/20",style:p?{boxShadow:`0 0 0 2px ${p}`}:void 0,children:[s.jsx(rf,{src:c.avatar_url||"",alt:c.name||""}),s.jsx(nf,{className:"bg-white/10 text-white",children:d})]}),t.co_host_name&&s.jsxs(tf,{className:"h-12 w-12 -ml-6 ring-2 ring-slate-950",children:[s.jsx(rf,{src:t.co_host_photo_url||"",alt:t.co_host_name}),s.jsx(nf,{className:"bg-white/10 text-white",children:String(t.co_host_name).split(" ").map(ft=>ft[0]).join("").slice(0,2)})]})]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("p",{className:"font-semibold text-white truncate",children:[c.name,t.co_host_name?` & ${t.co_host_name}`:""]}),(t.brokerage_display_name||c.title)&&s.jsx("p",{className:"text-xs text-white/60 truncate",children:[!t.co_host_name&&c.title,t.brokerage_display_name].filter(Boolean).join(" · ")})]}),(c.phone||c.email)&&s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.phone&&s.jsx("a",{href:`tel:${c.phone}`,"aria-label":`Call ${c.name}`,className:"h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 transition-colors flex items-center justify-center text-white",style:p?{backgroundColor:`${p}33`,color:"white"}:void 0,children:s.jsx(Ui,{className:"h-4 w-4"})}),c.email&&s.jsx("a",{href:`mailto:${c.email}`,"aria-label":`Email ${c.name}`,className:"h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 transition-colors flex items-center justify-center text-white",style:p?{backgroundColor:`${p}33`,color:"white"}:void 0,children:s.jsx(rs,{className:"h-4 w-4"})})]})]}),Ae&&He.length>0&&s.jsxs("div",{className:"mt-8",children:[s.jsx(Sit,{rooms:He}),s.jsx(Eit,{rooms:He})]}),ot.length>0&&s.jsxs("div",{className:"mt-10 pt-6 border-t border-white/10",children:[s.jsx("p",{className:"text-xs uppercase tracking-wider text-white/40 mb-3",children:"Interested in this home?"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:ot.map(ft=>{const Kt=FU[ft],ir=Kt.icon;return s.jsxs("button",{onClick:()=>nt(ft),className:"flex items-center gap-2 px-4 py-2.5 rounded-full border border-white/15 bg-white/5 text-white/90 hover:bg-white/10 hover:border-white/30 transition-colors text-sm",children:[s.jsx(ir,{className:"h-4 w-4",style:p?{color:p}:void 0}),s.jsx("span",{className:"font-medium",children:Kt.label})]},ft)})})]}),s.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),s.jsx(Awe,{open:!!l,onOpenChange:ft=>!ft&&tt(),children:s.jsx(ZK,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:l&&s.jsxs(s.Fragment,{children:[s.jsxs(Iwe,{className:"text-left",children:[s.jsx(jwe,{children:FU[l].title}),s.jsxs(Cwe,{children:[(c==null?void 0:c.name)||"The agent"," will be notified by email."]})]}),F===l?s.jsxs("div",{className:"py-10 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"w-14 h-14 rounded-full bg-green-100 flex items-center justify-center",children:s.jsx(od,{className:"h-7 w-7 text-green-600"})}),s.jsx("p",{className:"font-medium",children:"Message sent!"})]}):s.jsxs("div",{className:"space-y-4 pt-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Email"}),s.jsx(hn,{type:"email",value:T,onChange:ft=>j(ft.target.value),placeholder:"you@example.com",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Phone"}),s.jsx(hn,{type:"tel",value:P,onChange:ft=>C(ft.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),l==="showing"&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Preferred date *"}),s.jsx(hn,{type:"date",value:G,onChange:ft=>W(ft.target.value),className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Preferred time"}),s.jsx(hn,{type:"time",value:Z,onChange:ft=>Q(ft.target.value),className:"mt-1"})]})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Alternate date (optional)"}),s.jsx(hn,{type:"date",value:ee,onChange:ft=>ie(ft.target.value),className:"mt-1"})]})]}),l==="disclosure"&&s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Which documents? (select all that apply)"}),s.jsx("div",{className:"mt-2 space-y-2",children:Tit.map(ft=>s.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[s.jsx(XP,{checked:oe.includes(ft),onCheckedChange:()=>vt(ft)}),s.jsx("span",{children:ft})]},ft))})]}),l==="offer"&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Estimated offer"}),s.jsx(hn,{value:Le,onChange:ft=>be(ft.target.value),placeholder:"$",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Financing"}),s.jsxs(Xo,{value:Re,onValueChange:Ie,children:[s.jsx(Mo,{className:"mt-1",children:s.jsx(Qo,{placeholder:"Select..."})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"Cash",children:"Cash"}),s.jsx($n,{value:"Conventional",children:"Conventional"}),s.jsx($n,{value:"FHA",children:"FHA"}),s.jsx($n,{value:"VA",children:"VA"}),s.jsx($n,{value:"Other",children:"Other"})]})]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Timeline"}),s.jsxs(Xo,{value:Te,onValueChange:ge,children:[s.jsx(Mo,{className:"mt-1",children:s.jsx(Qo,{placeholder:"Select..."})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"ASAP",children:"ASAP"}),s.jsx($n,{value:"30 days",children:"30 days"}),s.jsx($n,{value:"60 days",children:"60 days"}),s.jsx($n,{value:"90+ days",children:"90+ days"})]})]})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Pre-approved?"}),s.jsxs(Xo,{value:$e,onValueChange:we,children:[s.jsx(Mo,{className:"mt-1",children:s.jsx(Qo,{placeholder:"Select..."})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"Yes",children:"Yes"}),s.jsx($n,{value:"No",children:"No"}),s.jsx($n,{value:"In progress",children:"In progress"})]})]})]})]})]}),s.jsxs("div",{children:[s.jsxs(sn,{className:"text-xs",children:["Message",l==="question"?" *":" (optional)"]}),s.jsx(df,{value:v,onChange:ft=>E(ft.target.value),placeholder:FU[l].placeholder,rows:4,className:"mt-1"})]}),s.jsx(Jt,{onClick:Bt,disabled:L||!Ct,className:"w-full h-12 text-white hover:opacity-90",style:p?{backgroundColor:p}:void 0,children:L?s.jsx(gh,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const Iit=Gv({first_name:Us().trim().min(1,"First name is required").max(50),last_name:Us().trim().max(50).optional(),email:Us().trim().email("Please enter a valid email").max(255).optional().or(TF("")),phone:Us().trim().max(20).optional().or(TF(""))}),jit=[{value:"buying",label:"Looking to Buy",emoji:"🏠"},{value:"selling",label:"Thinking of Selling",emoji:"📋"},{value:"browsing",label:"Just Browsing",emoji:"👀"},{value:"neighbor",label:"I'm a Neighbor",emoji:"👋"}];function zEe({slug:t}={}){var li;const e=Sg(),r=t||e.slug,[n]=zv(),i=n.get("kiosk")==="1"||n.get("mode")==="kiosk",a=8,{data:c,isLoading:d,error:p}=DEe(r),l=oit(),g=lit(),v=cit(),E=N.useRef(!1),[T,j]=N.useState("welcome"),[P,C]=N.useState(null),[L,O]=N.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[F,$]=N.useState(""),[G,W]=N.useState(!1),[Z,Q]=N.useState(!1),[ee,ie]=N.useState(""),[oe,pe]=N.useState(""),[Le,be]=N.useState(a),[Re,Ie]=N.useState(!1),[Te,ge]=N.useState(null),$e=c==null?void 0:c.agent_card_slug,we=$e?`https://cards.relevelup.com/${$e}${c!=null&&c.disclosure_pdf_url?`?oh_disclosure=${encodeURIComponent(c.disclosure_pdf_url)}`:""}`:null,ke=T==="done"&&!i&&!!we&&!!(c!=null&&c.auto_forward_to_card);N.useEffect(()=>{if(!ke||Re){ge(null);return}let Lr=c!=null&&c.disclosure_pdf_url?10:3;ge(Lr);const Or=setInterval(()=>{if(Lr-=1,Lr<=0){clearInterval(Or),window.location.href=we;return}ge(Lr)},1e3);return()=>clearInterval(Or)},[ke,Re,we,c==null?void 0:c.disclosure_pdf_url]);const Ae=N.useCallback(()=>{C(null),O({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),$(""),W(!1),Q(!1),ie(""),pe(""),be(a),j(i?"info":"welcome")},[i]),He=N.useCallback((Lr,Or)=>{c!=null&&c.id&&Be.functions.invoke("guestbook-lead-notify",{body:{open_house_id:c.id,visitor_id:Lr,first_name:Or.first_name??L.first_name,last_name:Or.last_name??L.last_name,email:Or.email??L.email,phone:Or.phone??L.phone,visitor_intent:Or.visitor_intent??F,message:Or.message,wants_market_updates:Or.wants_market_updates??G,has_agent:Or.has_agent??Z,working_with_agent_name:Or.working_with_agent_name??ee,visitor_address:Or.visitor_address??L.visitor_address}}).catch(si=>console.error("Guest book lead notify failed:",si))},[c==null?void 0:c.id,L,F,G,Z,ee]);N.useEffect(()=>{if(!i||T!=="done")return;be(a);const Lr=setInterval(()=>{be(Or=>Or<=1?(clearInterval(Lr),Ae(),0):Or-1)},1e3);return()=>clearInterval(Lr)},[i,T,Ae]),N.useEffect(()=>{if(!i)return;j(Or=>Or==="welcome"?"info":Or);let Lr=null;return(async()=>{var Or,si;try{Lr=await((si=(Or=navigator.wakeLock)==null?void 0:Or.request)==null?void 0:si.call(Or,"screen"))}catch{}})(),()=>{var Or;try{(Or=Lr==null?void 0:Lr.release)==null||Or.call(Lr)}catch{}}},[i]);const ot=N.useCallback(()=>{var Or;const Lr=document.documentElement;document.fullscreenElement||(Or=Lr.requestFullscreen||Lr.webkitRequestFullscreen)==null||Or.call(Lr).catch(()=>{})},[]),{data:nt,isLoading:tt}=sit(c==null?void 0:c.id),vt=!!(c!=null&&c.enable_survey),Vt=(c==null?void 0:c.ask_visitor_intent)!==!1,Ct=(c==null?void 0:c.ask_visitor_address)===!0;N.useEffect(()=>{if(!r||!(c!=null&&c.id)||E.current)return;const Lr=`oh_scan_${c.id}`;if(sessionStorage.getItem(Lr)){E.current=!0;return}E.current=!0,sessionStorage.setItem(Lr,"1"),v.mutate(r)},[r,c==null?void 0:c.id]),N.useEffect(()=>{T==="pending_survey"&&(tt||j(vt&&((nt==null?void 0:nt.length)??0)>0?"survey":"done"))},[T,tt,vt,nt]);const Bt=Lr=>{if(!Lr)return"";const[Or,si]=Lr.split(":"),ss=parseInt(Or),ps=ss>=12?"PM":"AM";return`${ss>12?ss-12:ss||12}:${si} ${ps}`},cr=async()=>{pe("");const Lr=Iit.safeParse(L);if(!Lr.success){pe(Lr.error.issues[0].message);return}if(!L.email&&!L.phone){pe("Please provide either an email or phone number");return}const Or=(c==null?void 0:c.kind)==="virtual";let si=null;if(!P&&(c!=null&&c.id))try{const ss=await l.mutateAsync({open_house_id:c.id,first_name:L.first_name.trim(),last_name:L.last_name.trim()||void 0,email:L.email.trim()||void 0,phone:L.phone.trim()||void 0,visitor_address:Ct&&L.visitor_address.trim()?L.visitor_address.trim():void 0,wants_market_updates:G,has_agent:Z,working_with_agent_name:Z&&ee.trim()?ee.trim():void 0,partial_signin:Or?!1:Vt});si=ss.id,C(ss.id)}catch{if(Or){pe("We could not start the virtual tour. Please try again.");return}}if(Or){Vt?j("intent"):(si&&He(si,{}),j("done"));return}if(!Vt){si&&He(si,{}),vt?!tt&&nt&&nt.length>0?j("survey"):j("pending_survey"):j("done");return}j("intent")},ft=async Lr=>{$(Lr);try{let Or=P;if(Or?await g.mutateAsync({visitor_id:Or,visitor_intent:Lr,wants_market_updates:G,has_agent:Z,working_with_agent_name:Z&&ee.trim()?ee.trim():null,partial_signin:!1}):(Or=(await l.mutateAsync({open_house_id:c.id,first_name:L.first_name.trim(),last_name:L.last_name.trim()||void 0,email:L.email.trim()||void 0,phone:L.phone.trim()||void 0,visitor_address:Ct&&L.visitor_address.trim()?L.visitor_address.trim():void 0,visitor_intent:Lr,wants_market_updates:G,has_agent:Z,working_with_agent_name:Z&&ee.trim()?ee.trim():void 0,partial_signin:!1})).id,C(Or)),Or&&He(Or,{visitor_intent:Lr,wants_market_updates:G,has_agent:Z,working_with_agent_name:Z&&ee.trim()?ee.trim():null}),(c==null?void 0:c.kind)==="virtual"){j("done");return}vt?!tt&&nt&&nt.length>0?j("survey"):j("pending_survey"):j("done")}catch{pe("Something went wrong. Please try again.")}};if(d)return s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:s.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})});if(p||!c)return s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center text-white",children:[s.jsx(Do,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Open House Not Found"}),s.jsx("p",{className:"text-white/60",children:"This sign-in page doesn't exist or is no longer active."})]})});const Kt=c.profiles,ir=((li=Kt==null?void 0:Kt.name)==null?void 0:li.split(" ").map(Lr=>Lr[0]).join("").slice(0,2))||"?",Gr=c.event_type==="community",tr=c.kind==="virtual",Qt=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(tr&&(Qt||T==="done"))return!Qt&&!P?s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:s.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})}):s.jsxs(s.Fragment,{children:[s.jsxs(mc,{children:[s.jsxs("title",{children:["Virtual Tour | ",c.property_address]}),s.jsx("meta",{name:"description",content:`Take a virtual tour of ${c.property_address}`}),s.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),Qt&&s.jsx("div",{className:"fixed top-3 left-1/2 -translate-x-1/2 z-[100] bg-amber-500 text-white text-xs font-semibold px-3 py-1.5 rounded-full shadow-lg pointer-events-none",children:"Agent Preview Mode — visitors won't see this"}),s.jsx(kit,{openHouse:c,visitorId:Qt?"preview":P,visitorName:Qt?"Preview Visitor":`${L.first_name} ${L.last_name}`.trim(),visitorEmail:Qt?"":L.email,visitorPhone:Qt?"":L.phone,previewMode:Qt})]});const Vr=`${tr?"Virtual Open House":Gr?"Community Event":"Open House"} — ${c.property_address}`,Fn=[[c.city,c.state].filter(Boolean).join(", "),c.event_date?ds(new Date(c.event_date+"T00:00:00"),"EEE, MMM d"):null,Kt!=null&&Kt.name?`Hosted by ${Kt.name}`:null].filter(Boolean).join(" · "),Ar=c.photo_url||"",Tn=Ar&&Ar.includes("/storage/v1/object/public/")?Ar.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Ar||"https://dashboard.relevelup.com/og-image.png",mn=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${r}`;return s.jsxs(s.Fragment,{children:[s.jsxs(mc,{children:[s.jsx("title",{children:Vr}),s.jsx("meta",{name:"description",content:Fn||`Sign in to ${c.property_address}`}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:title",content:Vr}),s.jsx("meta",{property:"og:description",content:Fn||`Sign in to ${c.property_address}`}),s.jsx("meta",{property:"og:image",content:Tn}),s.jsx("meta",{property:"og:image:width",content:"1200"}),s.jsx("meta",{property:"og:image:height",content:"630"}),s.jsx("meta",{property:"og:url",content:mn}),s.jsx("meta",{property:"og:site_name",content:"ReLevel Up"}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),s.jsx("meta",{name:"twitter:title",content:Vr}),s.jsx("meta",{name:"twitter:description",content:Fn||`Sign in to ${c.property_address}`}),s.jsx("meta",{name:"twitter:image",content:Tn}),s.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-4",children:s.jsxs("div",{className:"w-full max-w-md",children:[s.jsxs("div",{className:"text-center mb-6",children:[s.jsxs(tf,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[s.jsx(rf,{src:(Kt==null?void 0:Kt.avatar_url)||"",alt:(Kt==null?void 0:Kt.name)||""}),s.jsx(nf,{className:"bg-white/10 text-white text-lg",children:ir})]}),s.jsx("p",{className:"text-white/60 text-sm",children:Kt==null?void 0:Kt.name}),(Kt==null?void 0:Kt.title)&&s.jsx("p",{className:"text-white/40 text-xs",children:Kt.title})]}),s.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[c.photo_url&&s.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[s.jsx("img",{src:c.photo_url,alt:c.property_address,className:"w-full h-full object-cover"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),s.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[s.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:c.property_address}),s.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[c.city&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Va,{className:"h-3 w-3"}),c.city,c.state?`, ${c.state}`:""," ",c.zip]}),!tr&&s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Cl,{className:"h-3 w-3"}),ds(new Date(c.event_date+"T00:00:00"),"MMM d, yyyy")]}),c.start_time&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(su,{className:"h-3 w-3"}),Bt(c.start_time),c.end_time?` – ${Bt(c.end_time)}`:""]})]})]})]})]}),!c.photo_url&&s.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:Gr?s.jsx(jl,{className:"h-5 w-5 text-white"}):s.jsx(Do,{className:"h-5 w-5 text-white"})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-white font-bold text-lg leading-tight",children:c.property_address}),s.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-white/60 text-xs",children:[c.city&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Va,{className:"h-3 w-3"}),c.city,c.state?`, ${c.state}`:""," ",c.zip]}),!tr&&s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(Cl,{className:"h-3 w-3"}),ds(new Date(c.event_date+"T00:00:00"),"MMM d, yyyy")]}),c.start_time&&s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(su,{className:"h-3 w-3"}),Bt(c.start_time),c.end_time?` – ${Bt(c.end_time)}`:""]})]})]})]})]})}),s.jsxs("div",{className:"p-6",children:[T==="welcome"&&s.jsxs("div",{className:"text-center space-y-6",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),s.jsx("p",{className:"text-slate-500 text-sm",children:c.agent_greeting||"Please sign in below."})]}),s.jsxs(Jt,{onClick:()=>j("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",s.jsx(lo,{className:"h-5 w-5 ml-2"})]}),s.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),T==="info"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("button",{onClick:()=>j("welcome"),className:"text-slate-400 hover:text-slate-600",children:s.jsx(yv,{className:"h-4 w-4"})}),s.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Your Info"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{className:"text-slate-600 text-xs",children:"First Name *"}),s.jsx(hn,{value:L.first_name,onChange:Lr=>O(Or=>({...Or,first_name:Lr.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-slate-600 text-xs",children:"Last Name"}),s.jsx(hn,{value:L.last_name,onChange:Lr=>O(Or=>({...Or,last_name:Lr.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-slate-600 text-xs",children:"Email"}),s.jsx(hn,{type:"email",value:L.email,onChange:Lr=>O(Or=>({...Or,email:Lr.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-slate-600 text-xs",children:"Phone"}),s.jsx(hn,{type:"tel",value:L.phone,onChange:Lr=>O(Or=>({...Or,phone:Lr.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),Ct&&s.jsxs("div",{children:[s.jsx(sn,{className:"text-slate-600 text-xs",children:"Your Home Address"}),s.jsx(hn,{value:L.visitor_address,onChange:Lr=>O(Or=>({...Or,visitor_address:Lr.target.value})),placeholder:"Street, City, State ZIP",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoComplete:"street-address"})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[s.jsx("input",{type:"checkbox",checked:G,onChange:Lr=>W(Lr.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),s.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),s.jsxs("div",{className:"space-y-2 pt-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xs font-medium text-slate-400",children:Z?"Yes":"No"}),s.jsx(TA,{checked:Z,onCheckedChange:Q})]})]}),Z&&s.jsx(hn,{value:ee,onChange:Lr=>ie(Lr.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),oe&&s.jsx("p",{className:"text-destructive text-sm",children:oe}),s.jsxs(Jt,{onClick:cr,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",s.jsx(lo,{className:"h-5 w-5 ml-2"})]})]}),T==="intent"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("button",{onClick:()=>j("info"),className:"text-slate-400 hover:text-slate-600",children:s.jsx(yv,{className:"h-4 w-4"})}),s.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"What brings you here?"})]}),s.jsx("div",{className:"grid grid-cols-2 gap-3",children:jit.map(Lr=>s.jsxs("button",{onClick:()=>ft(Lr.value),disabled:l.isPending,className:"flex flex-col items-center gap-2 p-5 rounded-xl border-2 border-slate-200 hover:border-slate-900 hover:bg-slate-50 transition-all text-center group",children:[s.jsx("span",{className:"text-2xl",children:Lr.emoji}),s.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Lr.label})]},Lr.value))}),oe&&s.jsx("p",{className:"text-destructive text-sm text-center",children:oe})]}),T==="pending_survey"&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[s.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),s.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),T==="survey"&&P&&nt&&s.jsx(wit,{questions:nt,visitorId:P,onComplete:()=>j("done"),onSkip:()=>j("done")}),T==="done"&&s.jsxs("div",{className:"text-center space-y-4 py-4",children:[s.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:s.jsx(od,{className:"h-8 w-8 text-green-600"})}),s.jsxs("div",{children:[s.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"You're all set!"}),s.jsxs("p",{className:"text-slate-500 text-sm mt-1",children:["Thanks for signing in, ",L.first_name,". ",Gr?"Enjoy the event!":"Enjoy the open house!"]})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 justify-center",children:[(c==null?void 0:c.disclosure_pdf_url)&&s.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(c.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",onClick:()=>Ie(!0),className:"inline-flex items-center justify-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[s.jsx(lg,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),we&&s.jsxs("a",{href:we,className:"inline-flex items-center justify-center gap-2 px-5 py-3 rounded-xl bg-slate-900 hover:bg-slate-800 text-white font-medium text-sm transition-colors",children:[s.jsx(lo,{className:"h-4 w-4"}),"View ",Kt!=null&&Kt.name?`${Kt.name.split(" ")[0]}'s`:"My"," Business Card"]})]}),we&&Te!==null&&!Re&&s.jsxs("p",{className:"text-xs text-slate-400",children:["Opening the business card in ",Te,"s…"," ",s.jsx("button",{type:"button",className:"underline",onClick:()=>Ie(!0),children:"Stay here"})]}),(Kt==null?void 0:Kt.name)&&s.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",s.jsx("strong",{className:"text-slate-600",children:Kt.name})]}),i&&s.jsxs("div",{className:"pt-4 space-y-3",children:[s.jsx(Jt,{onClick:Ae,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),s.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",Le,"s…"]})]})]})]})]}),s.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),i&&s.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[s.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10",children:[s.jsx(w5e,{className:"h-3 w-3"})," Tablet Mode"]}),s.jsx("button",{onClick:ot,className:"inline-flex items-center gap-1 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10 hover:bg-white/20",title:"Enter full screen",children:s.jsx(i5e,{className:"h-3 w-3"})})]})]})})]})}const Cit=Object.freeze(Object.defineProperty({__proto__:null,default:zEe},Symbol.toStringTag,{value:"Module"}));function tZt(t){return jr({queryKey:["open-house-rsvps",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("open_house_rsvps").select("*").eq("open_house_id",t).order("created_at",{ascending:!1});if(r)throw r;return e||[]},enabled:!!t})}function Pit(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("open_house_rsvps").insert({open_house_id:e.open_house_id,first_name:e.first_name,last_name:e.last_name||null,email:e.email||null,phone:e.phone||null,has_agent:e.has_agent??!1,working_with_agent_name:e.working_with_agent_name||null,message:e.message||null});if(r)throw r;return null},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["open-house-rsvps",r.open_house_id]})}})}function rZt(t){const e=Ur();return zr({mutationFn:async r=>{const{error:n}=await Be.from("open_house_rsvps").delete().eq("id",r);if(n)throw n},onSuccess:()=>e.invalidateQueries({queryKey:["open-house-rsvps",t]})})}function nZt(t){const e=Ur();return zr({mutationFn:async({id:r,checkedIn:n})=>{const{error:i}=await Be.from("open_house_rsvps").update({checked_in_at:n?new Date().toISOString():null}).eq("id",r);if(i)throw i},onSuccess:()=>e.invalidateQueries({queryKey:["open-house-rsvps",t]})})}const Nit=Gv({first_name:Us().trim().min(1,"First name is required").max(50),last_name:Us().trim().max(50).optional(),email:Us().trim().email("Please enter a valid email").max(255),phone:Us().trim().max(20).optional().or(TF("")),message:Us().trim().max(500).optional().or(TF(""))}),BU=t=>{if(!t)return"";const[e,r]=t.split(":"),n=parseInt(e,10),i=n>=12?"PM":"AM";return`${n>12?n-12:n||12}:${r} ${i}`},Rit=t=>{if(!t)return null;const[e,r,n]=t.split(/[-/T]/).map(Number);return!e||!r||!n?null:new Date(e,r-1,n)};function $Ee({slug:t}={}){const e=Sg(),r=t||e.slug,{data:n,isLoading:i,error:a}=DEe(r),c=Pit(),[d,p]=N.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[l,g]=N.useState(!1),[v,E]=N.useState(""),[T,j]=N.useState(""),[P,C]=N.useState(!1),L=N.useMemo(()=>Rit(n==null?void 0:n.event_date),[n==null?void 0:n.event_date]),O=N.useMemo(()=>{const Q=n==null?void 0:n.photo_url;return Q?Q.includes("/storage/v1/object/public/")?Q.replace("/object/public/","/render/image/public/")+"?width=1600&quality=80":Q:""},[n]),F=n==null?void 0:n.profiles,$=[n==null?void 0:n.city,n==null?void 0:n.state].filter(Boolean).join(", "),G=async()=>{j("");const Q=Nit.safeParse(d);if(!Q.success){j(Q.error.issues[0].message);return}try{await c.mutateAsync({open_house_id:n.id,first_name:d.first_name.trim(),last_name:d.last_name.trim()||void 0,email:d.email.trim(),phone:d.phone.trim()||void 0,has_agent:l,working_with_agent_name:l&&v.trim()?v.trim():void 0,message:d.message.trim()||void 0}),C(!0)}catch(ee){j((ee==null?void 0:ee.message)||"Something went wrong. Please try again.")}},W=N.useMemo(()=>{if(!n||!L)return"";const Q=be=>String(be).padStart(2,"0"),ee=`${L.getFullYear()}${Q(L.getMonth()+1)}${Q(L.getDate())}`,ie=(n.start_time||"12:00").slice(0,5).replace(":","")+"00",oe=(n.end_time||"14:00").slice(0,5).replace(":","")+"00",pe=encodeURIComponent(`Open House — ${n.property_address}`),Le=encodeURIComponent([n.property_address,$,n.zip].filter(Boolean).join(", "));return`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${pe}&dates=${ee}T${ie}/${ee}T${oe}&location=${Le}`},[n,L,$]);if(i)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22]",children:s.jsx("div",{className:"h-10 w-10 rounded-full border-2 border-white/20 border-t-white animate-spin"})});if(a||!n)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22] p-6 text-center",children:s.jsxs("div",{className:"text-white/80",children:[s.jsx(Do,{className:"h-8 w-8 mx-auto mb-3 opacity-50"}),s.jsx("h1",{className:"text-xl font-semibold mb-1",children:"Open house not found"}),s.jsx("p",{className:"text-sm text-white/50",children:"This RSVP link may have expired."})]})});const Z=`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent([n.property_address,$,n.zip].filter(Boolean).join(", "))}`;return s.jsxs("div",{className:"min-h-screen bg-[#f6f2ee]",children:[s.jsxs(mc,{children:[s.jsx("title",{children:`RSVP — Open House at ${n.property_address}`}),s.jsx("meta",{name:"description",content:`Reserve your spot for the open house at ${n.property_address}${L?` on ${ds(L,"EEEE, MMMM d")}`:""}.`})]}),s.jsxs("header",{className:"relative",children:[s.jsxs("div",{className:"relative h-[46vh] min-h-[320px] w-full overflow-hidden bg-[#1b3a4b]",children:[O&&s.jsx("img",{src:O,alt:n.property_address,className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0f1c22] via-[#0f1c22]/55 to-[#0f1c22]/25"}),s.jsx("div",{className:"absolute inset-x-0 bottom-0 p-6 sm:p-10",children:s.jsxs("div",{className:"mx-auto max-w-3xl",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.35em] text-[#d4b978] mb-3",children:"Open House"}),s.jsx("h1",{className:"font-serif text-3xl sm:text-4xl font-bold text-white leading-tight",children:n.property_address}),$&&s.jsxs("p",{className:"mt-1 text-white/70",children:[$," ",n.zip||""]}),s.jsxs("div",{className:"mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm text-white/85",children:[L&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cl,{className:"h-4 w-4 text-[#d4b978]"}),ds(L,"EEEE, MMMM d, yyyy")]}),n.start_time&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(su,{className:"h-4 w-4 text-[#d4b978]"}),BU(n.start_time),n.end_time?` – ${BU(n.end_time)}`:""]})]})]})})]}),s.jsx("div",{className:"h-1 bg-gradient-to-r from-[#b8975a] via-[#d4b978] to-[#b8975a]"})]}),s.jsxs("main",{className:"mx-auto max-w-3xl px-5 py-8 sm:py-12 space-y-8",children:[(n.price||n.beds||n.baths||n.sqft)&&s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[n.price?s.jsx(RD,{icon:s.jsx(Do,{className:"h-4 w-4"}),label:"Price",value:`$${Number(n.price).toLocaleString()}`}):null,n.beds?s.jsx(RD,{icon:s.jsx(z4e,{className:"h-4 w-4"}),label:"Beds",value:String(n.beds)}):null,n.baths?s.jsx(RD,{icon:s.jsx(ww,{className:"h-4 w-4"}),label:"Baths",value:String(n.baths)}):null,n.sqft?s.jsx(RD,{icon:s.jsx(k4,{className:"h-4 w-4"}),label:"Sq Ft",value:Number(n.sqft).toLocaleString()}):null]}),n.property_description&&s.jsx("p",{className:"text-[15px] leading-relaxed text-[#3a4a51] whitespace-pre-line",children:n.property_description}),s.jsx("section",{id:"rsvp",className:"rounded-2xl bg-white shadow-[0_10px_40px_rgba(15,28,34,0.08)] overflow-hidden",children:P?s.jsxs("div",{className:"p-8 sm:p-12 text-center",children:[s.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-emerald-500/10",children:s.jsx(od,{className:"h-7 w-7 text-emerald-600"})}),s.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"You're on the list!"}),s.jsxs("p",{className:"mt-2 text-[#5b6b72]",children:["We'll see you ",L?ds(L,"EEEE, MMMM d"):"soon",n.start_time?` at ${BU(n.start_time)}`:"",". A confirmation reminder will land in your inbox before the event."]}),s.jsxs("div",{className:"mt-6 flex flex-wrap justify-center gap-3",children:[W&&s.jsx(Jt,{asChild:!0,className:"bg-[#1b3a4b] hover:bg-[#25505f]",children:s.jsxs("a",{href:W,target:"_blank",rel:"noreferrer",children:[s.jsx(rve,{className:"mr-2 h-4 w-4"}),"Add to calendar"]})}),s.jsx(Jt,{asChild:!0,variant:"outline",children:s.jsxs("a",{href:Z,target:"_blank",rel:"noreferrer",children:[s.jsx(Va,{className:"mr-2 h-4 w-4"}),"Get directions"]})})]})]}):s.jsxs("div",{className:"p-6 sm:p-8",children:[s.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"Reserve your spot"}),s.jsx("p",{className:"mt-1 text-sm text-[#5b6b72]",children:"Let us know you're coming and we'll save you a spot and send a reminder."}),s.jsxs("div",{className:"mt-6 grid gap-4 sm:grid-cols-2",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{htmlFor:"rsvp-first",children:"First name *"}),s.jsx(hn,{id:"rsvp-first",value:d.first_name,onChange:Q=>p(ee=>({...ee,first_name:Q.target.value})),className:"h-11"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{htmlFor:"rsvp-last",children:"Last name"}),s.jsx(hn,{id:"rsvp-last",value:d.last_name,onChange:Q=>p(ee=>({...ee,last_name:Q.target.value})),className:"h-11"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{htmlFor:"rsvp-email",children:"Email *"}),s.jsx(hn,{id:"rsvp-email",type:"email",value:d.email,onChange:Q=>p(ee=>({...ee,email:Q.target.value})),className:"h-11"})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{htmlFor:"rsvp-phone",children:"Phone"}),s.jsx(hn,{id:"rsvp-phone",type:"tel",value:d.phone,onChange:Q=>p(ee=>({...ee,phone:Q.target.value})),className:"h-11"})]})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-[#e4dcd3] bg-[#faf7f4] p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-[#1b3a4b]",children:"Are you working with an agent?"}),s.jsx("p",{className:"text-xs text-[#7a888e]",children:"So we can respect your existing representation."})]}),s.jsx(TA,{checked:l,onCheckedChange:g})]}),l&&s.jsx(hn,{value:v,onChange:Q=>E(Q.target.value),placeholder:"Your agent's name (optional)",className:"mt-3 h-10 bg-white"})]}),s.jsxs("div",{className:"mt-4 space-y-1.5",children:[s.jsx(sn,{htmlFor:"rsvp-msg",children:"Anything you'd like us to know?"}),s.jsx(df,{id:"rsvp-msg",rows:3,value:d.message,onChange:Q=>p(ee=>({...ee,message:Q.target.value})),className:"resize-y"})]}),T&&s.jsx("p",{className:"mt-3 text-sm text-destructive",children:T}),s.jsx(Jt,{onClick:G,disabled:c.isPending,className:"mt-6 h-12 w-full bg-gradient-to-r from-[#1b3a4b] to-[#406E71] text-base hover:opacity-95",children:c.isPending?"Reserving…":s.jsxs(s.Fragment,{children:["RSVP for this open house",s.jsx(lo,{className:"ml-2 h-4 w-4"})]})}),s.jsx("p",{className:"mt-3 text-center text-xs text-[#8b979c]",children:"We'll only use your info to follow up about this property."})]})}),(F==null?void 0:F.name)&&s.jsxs("section",{className:"rounded-2xl bg-white/70 border border-[#e4dcd3] p-5 flex items-center gap-4",children:[s.jsxs(tf,{className:"h-14 w-14",children:[s.jsx(rf,{src:F.avatar_url||void 0,alt:F.name}),s.jsx(nf,{children:F.name.slice(0,1)})]}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-[#a08a5f]",children:"Hosted by"}),s.jsx("p",{className:"font-semibold text-[#1b3a4b]",children:F.name}),F.title&&s.jsx("p",{className:"text-sm text-[#5b6b72]",children:F.title}),s.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 text-sm text-[#406E71]",children:[F.phone&&s.jsx("a",{href:`tel:${F.phone}`,children:F.phone}),F.email&&s.jsx("a",{href:`mailto:${F.email}`,className:"truncate",children:F.email})]})]})]}),s.jsx("div",{className:"text-center",children:s.jsxs("a",{href:Z,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-sm text-[#406E71] hover:underline",children:[s.jsx(Va,{className:"h-4 w-4"}),"Get directions to ",n.property_address]})})]})]})}function RD({icon:t,label:e,value:r}){return s.jsxs("div",{className:"rounded-xl bg-white border border-[#e9e2da] px-4 py-3",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-[#9aa5aa]",children:[t,e]}),s.jsx("div",{className:"mt-1 text-lg font-semibold text-[#1b3a4b]",children:r})]})}const Lit=Object.freeze(Object.defineProperty({__proto__:null,default:$Ee},Symbol.toStringTag,{value:"Module"}));function iZt(t){const{user:e}=_i();return jr({queryKey:["cohost-tokens",t],queryFn:async()=>{const{data:r,error:n}=await Be.from("open_house_cohost_tokens").select("*").eq("open_house_id",t).order("created_at",{ascending:!1});if(n)throw n;return r},enabled:!!e&&!!t})}function sZt(){const t=Ur(),{user:e}=_i();return zr({mutationFn:async({openHouseId:r,label:n})=>{const{data:i,error:a}=await Be.from("open_house_cohost_tokens").insert({open_house_id:r,label:n||null,created_by:e.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(a)throw a;return i},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function aZt(){const t=Ur();return zr({mutationFn:async({id:e,openHouseId:r})=>{const{error:n}=await Be.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",e);if(n)throw n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function Dit(t){return jr({queryKey:["cohost-validate",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",t).eq("is_active",!0).single();if(r)throw r;if(e.expires_at&&new Date(e.expires_at)-1&&t.splice(r,1)}const yg=(t,e,r)=>r>e?e:r{};const Iv={},UEe=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t),VEe=t=>typeof t=="object"&&t!==null,qEe=t=>/^0[^.\s]+$/u.test(t);function GEe(t){let e;return()=>(e===void 0&&(e=t()),e)}const Vf=t=>t,eN=(...t)=>t.reduce((e,r)=>n=>r(e(n))),mC=(t,e,r)=>{const n=e-t;return n?(r-t)/n:1};class mZ{constructor(){this.subscriptions=[]}add(e){return fZ(this.subscriptions,e),()=>IF(this.subscriptions,e)}notify(e,r,n){const i=this.subscriptions.length;if(i)if(i===1)this.subscriptions[0](e,r,n);else for(let a=0;at*1e3,Bf=t=>t/1e3,HEe=(t,e)=>e?t*(1e3/e):0,WEe=(t,e,r)=>(((1-3*r+3*e)*t+(3*r-6*e))*t+3*e)*t,Oit=1e-7,Fit=12;function Bit(t,e,r,n,i){let a,c,d=0;do c=e+(r-e)/2,a=WEe(c,n,i)-t,a>0?r=c:e=c;while(Math.abs(a)>Oit&&++dBit(a,0,1,t,r);return a=>a===0||a===1?a:WEe(i(a),e,n)}const KEe=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,YEe=t=>e=>1-t(1-e),ZEe=tN(.33,1.53,.69,.99),pZ=YEe(ZEe),XEe=KEe(pZ),QEe=t=>t>=1?1:(t*=2)<1?.5*pZ(t):.5*(2-Math.pow(2,-10*(t-1))),gZ=t=>1-Math.sin(Math.acos(t)),JEe=YEe(gZ),eTe=KEe(gZ),zit=tN(.42,0,1,1),$it=tN(0,0,.58,1),tTe=tN(.42,0,.58,1),Uit=t=>Array.isArray(t)&&typeof t[0]!="number",rTe=t=>Array.isArray(t)&&typeof t[0]=="number",Vit={linear:Vf,easeIn:zit,easeInOut:tTe,easeOut:$it,circIn:gZ,circInOut:eTe,circOut:JEe,backIn:pZ,backInOut:XEe,backOut:ZEe,anticipate:QEe},qit=t=>typeof t=="string",Hle=t=>{if(rTe(t)){D5(t.length===4);const[e,r,n,i]=t;return tN(e,r,n,i)}else if(qit(t))return Vit[t];return t},LD=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function Git(t){let e=new Set,r=new Set,n=!1,i=!1;const a=new WeakSet;let c={delta:0,timestamp:0,isProcessing:!1};function d(l){a.has(l)&&(p.schedule(l),t()),l(c)}const p={schedule:(l,g=!1,v=!1)=>{const T=v&&n?e:r;return g&&a.add(l),T.add(l),l},cancel:l=>{r.delete(l),a.delete(l)},process:l=>{if(c=l,n){i=!0;return}n=!0;const g=e;e=r,r=g,e.forEach(d),e.clear(),n=!1,i&&(i=!1,p.process(l))}};return p}const Hit=40;function nTe(t,e){let r=!1,n=!0;const i={delta:0,timestamp:0,isProcessing:!1},a=()=>r=!0,c=LD.reduce((F,$)=>(F[$]=Git(a),F),{}),{setup:d,read:p,resolveKeyframes:l,preUpdate:g,update:v,preRender:E,render:T,postRender:j}=c,P=()=>{const F=Iv.useManualTiming,$=F?i.timestamp:performance.now();r=!1,F||(i.delta=n?1e3/60:Math.max(Math.min($-i.timestamp,Hit),1)),i.timestamp=$,i.isProcessing=!0,d.process(i),p.process(i),l.process(i),g.process(i),v.process(i),E.process(i),T.process(i),j.process(i),i.isProcessing=!1,r&&e&&(n=!1,t(P))},C=()=>{r=!0,n=!0,i.isProcessing||t(P)};return{schedule:LD.reduce((F,$)=>{const G=c[$];return F[$]=(W,Z=!1,Q=!1)=>(r||C(),G.schedule(W,Z,Q)),F},{}),cancel:F=>{for(let $=0;$(iO===void 0&&Nd.set(ku.isProcessing||Iv.useManualTiming?ku.timestamp:performance.now()),iO),set:t=>{iO=t,queueMicrotask(Wit)}},iTe=t=>e=>typeof e=="string"&&e.startsWith(t),sTe=iTe("--"),Kit=iTe("var(--"),yZ=t=>Kit(t)?Yit.test(t.split("/*")[0].trim()):!1,Yit=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Wle(t){return typeof t!="string"?!1:t.split("/*")[0].includes("var(--")}const AA={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},pC={...AA,transform:t=>yg(0,1,t)},DD={...AA,default:1},hj=t=>Math.round(t*1e5)/1e5,xZ=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Zit(t){return t==null}const Xit=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,_Z=(t,e)=>r=>!!(typeof r=="string"&&Xit.test(r)&&r.startsWith(t)||e&&!Zit(r)&&Object.prototype.hasOwnProperty.call(r,e)),aTe=(t,e,r)=>n=>{if(typeof n!="string")return n;const[i,a,c,d]=n.match(xZ);return{[t]:parseFloat(i),[e]:parseFloat(a),[r]:parseFloat(c),alpha:d!==void 0?parseFloat(d):1}},Qit=t=>yg(0,255,t),$U={...AA,transform:t=>Math.round(Qit(t))},jb={test:_Z("rgb","red"),parse:aTe("red","green","blue"),transform:({red:t,green:e,blue:r,alpha:n=1})=>"rgba("+$U.transform(t)+", "+$U.transform(e)+", "+$U.transform(r)+", "+hj(pC.transform(n))+")"};function Jit(t){let e="",r="",n="",i="";return t.length>5?(e=t.substring(1,3),r=t.substring(3,5),n=t.substring(5,7),i=t.substring(7,9)):(e=t.substring(1,2),r=t.substring(2,3),n=t.substring(3,4),i=t.substring(4,5),e+=e,r+=r,n+=n,i+=i),{red:parseInt(e,16),green:parseInt(r,16),blue:parseInt(n,16),alpha:i?parseInt(i,16)/255:1}}const c9={test:_Z("#"),parse:Jit,transform:jb.transform},rN=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),my=rN("deg"),sg=rN("%"),Qn=rN("px"),est=rN("vh"),tst=rN("vw"),Kle={...sg,parse:t=>sg.parse(t)/100,transform:t=>sg.transform(t*100)},sE={test:_Z("hsl","hue"),parse:aTe("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:r,alpha:n=1})=>"hsla("+Math.round(t)+", "+sg.transform(hj(e))+", "+sg.transform(hj(r))+", "+hj(pC.transform(n))+")"},cc={test:t=>jb.test(t)||c9.test(t)||sE.test(t),parse:t=>jb.test(t)?jb.parse(t):sE.test(t)?sE.parse(t):c9.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?jb.transform(t):sE.transform(t),getAnimatableNone:t=>{const e=cc.parse(t);return e.alpha=0,cc.transform(e)}},rst=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function nst(t){var e,r;return isNaN(t)&&typeof t=="string"&&(((e=t.match(xZ))==null?void 0:e.length)||0)+(((r=t.match(rst))==null?void 0:r.length)||0)>0}const oTe="number",lTe="color",ist="var",sst="var(",Yle="${}",ast=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function yT(t){const e=t.toString(),r=[],n={color:[],number:[],var:[]},i=[];let a=0;const d=e.replace(ast,p=>(cc.test(p)?(n.color.push(a),i.push(lTe),r.push(cc.parse(p))):p.startsWith(sst)?(n.var.push(a),i.push(ist),r.push(p)):(n.number.push(a),i.push(oTe),r.push(parseFloat(p))),++a,Yle)).split(Yle);return{values:r,split:d,indexes:n,types:i}}function ost(t){return yT(t).values}function cTe({split:t,types:e}){const r=t.length;return n=>{let i="";for(let a=0;atypeof t=="number"?0:cc.test(t)?cc.getAnimatableNone(t):t,ust=(t,e)=>typeof t=="number"?e!=null&&e.trim().endsWith("/")?t:0:cst(t);function dst(t){const e=yT(t);return cTe(e)(e.values.map((n,i)=>ust(n,e.split[i])))}const tp={test:nst,parse:ost,createTransformer:lst,getAnimatableNone:dst};function UU(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+(e-t)*6*r:r<1/2?e:r<2/3?t+(e-t)*(2/3-r)*6:t}function hst({hue:t,saturation:e,lightness:r,alpha:n}){t/=360,e/=100,r/=100;let i=0,a=0,c=0;if(!e)i=a=c=r;else{const d=r<.5?r*(1+e):r+e-r*e,p=2*r-d;i=UU(p,d,t+1/3),a=UU(p,d,t),c=UU(p,d,t-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(c*255),alpha:n}}function jF(t,e){return r=>r>0?e:t}const co=(t,e,r)=>t+(e-t)*r,VU=(t,e,r)=>{const n=t*t,i=r*(e*e-n)+n;return i<0?0:Math.sqrt(i)},fst=[c9,jb,sE],mst=t=>fst.find(e=>e.test(t));function Zle(t){const e=mst(t);if(!e)return!1;let r=e.parse(t);return e===sE&&(r=hst(r)),r}const Xle=(t,e)=>{const r=Zle(t),n=Zle(e);if(!r||!n)return jF(t,e);const i={...r};return a=>(i.red=VU(r.red,n.red,a),i.green=VU(r.green,n.green,a),i.blue=VU(r.blue,n.blue,a),i.alpha=co(r.alpha,n.alpha,a),jb.transform(i))},u9=new Set(["none","hidden"]);function pst(t,e){return u9.has(t)?r=>r<=0?t:e:r=>r>=1?e:t}function gst(t,e){return r=>co(t,e,r)}function vZ(t){return typeof t=="number"?gst:typeof t=="string"?yZ(t)?jF:cc.test(t)?Xle:_st:Array.isArray(t)?uTe:typeof t=="object"?cc.test(t)?Xle:yst:jF}function uTe(t,e){const r=[...t],n=r.length,i=t.map((a,c)=>vZ(a)(a,e[c]));return a=>{for(let c=0;c{for(const a in n)r[a]=n[a](i);return r}}function xst(t,e){const r=[],n={color:0,var:0,number:0};for(let i=0;i{const r=tp.createTransformer(e),n=yT(t),i=yT(e);return n.indexes.var.length===i.indexes.var.length&&n.indexes.color.length===i.indexes.color.length&&n.indexes.number.length>=i.indexes.number.length?u9.has(t)&&!i.values.length||u9.has(e)&&!n.values.length?pst(t,e):eN(uTe(xst(n,i),i.values),r):jF(t,e)};function dTe(t,e,r){return typeof t=="number"&&typeof e=="number"&&typeof r=="number"?co(t,e,r):vZ(t)(t,e)}const vst=t=>{const e=({timestamp:r})=>t(r);return{start:(r=!0)=>uo.update(e,r),stop:()=>jv(e),now:()=>ku.isProcessing?ku.timestamp:Nd.now()}},hTe=(t,e,r=10)=>{let n="";const i=Math.max(Math.round(e/r),2);for(let a=0;a=CF?1/0:e}function bst(t,e=100,r){const n=r({...t,keyframes:[0,e]}),i=Math.min(bZ(n),CF);return{type:"keyframes",ease:a=>n.next(i*a).value/e,duration:Bf(i)}}const Al={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function d9(t,e){return t*Math.sqrt(1-e*e)}const wst=12;function Sst(t,e,r){let n=r;for(let i=1;i{const g=l*c,v=g*t,E=g-r,T=d9(l,c),j=Math.exp(-v);return qU-E/T*j},a=l=>{const v=l*c*t,E=v*r+r,T=Math.pow(c,2)*Math.pow(l,2)*t,j=Math.exp(-v),P=d9(Math.pow(l,2),c);return(-i(l)+qU>0?-1:1)*((E-T)*j)/P}):(i=l=>{const g=Math.exp(-l*t),v=(l-r)*t+1;return-qU+g*v},a=l=>{const g=Math.exp(-l*t),v=(r-l)*(t*t);return g*v});const d=5/t,p=Sst(i,a,d);if(t=Zh(t),isNaN(p))return{stiffness:Al.stiffness,damping:Al.damping,duration:t};{const l=Math.pow(p,2)*n;return{stiffness:l,damping:c*2*Math.sqrt(n*l),duration:t}}}const Tst=["duration","bounce"],Ast=["stiffness","damping","mass"];function Qle(t,e){return e.some(r=>t[r]!==void 0)}function kst(t){let e={velocity:Al.velocity,stiffness:Al.stiffness,damping:Al.damping,mass:Al.mass,isResolvedFromDuration:!1,...t};if(!Qle(t,Ast)&&Qle(t,Tst))if(e.velocity=0,t.visualDuration){const r=t.visualDuration,n=2*Math.PI/(r*1.2),i=n*n,a=2*yg(.05,1,1-(t.bounce||0))*Math.sqrt(i);e={...e,mass:Al.mass,stiffness:i,damping:a}}else{const r=Est({...t,velocity:0});e={...e,...r,mass:Al.mass},e.isResolvedFromDuration=!0}return e}function PF(t=Al.visualDuration,e=Al.bounce){const r=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:n,restDelta:i}=r;const a=r.keyframes[0],c=r.keyframes[r.keyframes.length-1],d={done:!1,value:a},{stiffness:p,damping:l,mass:g,duration:v,velocity:E,isResolvedFromDuration:T}=kst({...r,velocity:-Bf(r.velocity||0)}),j=E||0,P=l/(2*Math.sqrt(p*g)),C=c-a,L=Bf(Math.sqrt(p/g)),O=Math.abs(C)<5;n||(n=O?Al.restSpeed.granular:Al.restSpeed.default),i||(i=O?Al.restDelta.granular:Al.restDelta.default);let F,$,G,W,Z,Q;if(P<1)G=d9(L,P),W=(j+P*L*C)/G,F=ie=>{const oe=Math.exp(-P*L*ie);return c-oe*(W*Math.sin(G*ie)+C*Math.cos(G*ie))},Z=P*L*W+C*G,Q=P*L*C-W*G,$=ie=>Math.exp(-P*L*ie)*(Z*Math.sin(G*ie)+Q*Math.cos(G*ie));else if(P===1){F=oe=>c-Math.exp(-L*oe)*(C+(j+L*C)*oe);const ie=j+L*C;$=oe=>Math.exp(-L*oe)*(L*ie*oe-j)}else{const ie=L*Math.sqrt(P*P-1);F=be=>{const Re=Math.exp(-P*L*be),Ie=Math.min(ie*be,300);return c-Re*((j+P*L*C)*Math.sinh(Ie)+ie*C*Math.cosh(Ie))/ie};const oe=(j+P*L*C)/ie,pe=P*L*oe-C*ie,Le=P*L*C-oe*ie;$=be=>{const Re=Math.exp(-P*L*be),Ie=Math.min(ie*be,300);return Re*(pe*Math.sinh(Ie)+Le*Math.cosh(Ie))}}const ee={calculatedDuration:T&&v||null,velocity:ie=>Zh($(ie)),next:ie=>{if(!T&&P<1){const pe=Math.exp(-P*L*ie),Le=Math.sin(G*ie),be=Math.cos(G*ie),Re=c-pe*(W*Le+C*be),Ie=Zh(pe*(Z*Le+Q*be));return d.done=Math.abs(Ie)<=n&&Math.abs(c-Re)<=i,d.value=d.done?c:Re,d}const oe=F(ie);if(T)d.done=ie>=v;else{const pe=Zh($(ie));d.done=Math.abs(pe)<=n&&Math.abs(c-oe)<=i}return d.value=d.done?c:oe,d},toString:()=>{const ie=Math.min(bZ(ee),CF),oe=hTe(pe=>ee.next(ie*pe).value,ie,30);return ie+"ms "+oe},toTransition:()=>{}};return ee}PF.applyToOptions=t=>{const e=bst(t,100,PF);return t.ease=e.ease,t.duration=Zh(e.duration),t.type="keyframes",t};const Ist=5;function fTe(t,e,r){const n=Math.max(e-Ist,0);return HEe(r-t(n),e-n)}function h9({keyframes:t,velocity:e=0,power:r=.8,timeConstant:n=325,bounceDamping:i=10,bounceStiffness:a=500,modifyTarget:c,min:d,max:p,restDelta:l=.5,restSpeed:g}){const v=t[0],E={done:!1,value:v},T=Q=>d!==void 0&&Qp,j=Q=>d===void 0?p:p===void 0||Math.abs(d-Q)-P*Math.exp(-Q/n),F=Q=>L+O(Q),$=Q=>{const ee=O(Q),ie=F(Q);E.done=Math.abs(ee)<=l,E.value=E.done?L:ie};let G,W;const Z=Q=>{T(E.value)&&(G=Q,W=PF({keyframes:[E.value,j(E.value)],velocity:fTe(F,Q,E.value),damping:i,stiffness:a,restDelta:l,restSpeed:g}))};return Z(0),{calculatedDuration:null,next:Q=>{let ee=!1;return!W&&G===void 0&&(ee=!0,$(Q),Z(Q)),G!==void 0&&Q>=G?W.next(Q-G):(!ee&&$(Q),E)}}}function jst(t,e,r){const n=[],i=r||Iv.mix||dTe,a=t.length-1;for(let c=0;ce[0];if(a===2&&e[0]===e[1])return()=>e[1];const c=t[0]===t[1];t[0]>t[a-1]&&(t=[...t].reverse(),e=[...e].reverse());const d=jst(e,n,i),p=d.length,l=g=>{if(c&&g1)for(;vl(yg(t[0],t[a-1],g)):l}function Pst(t,e){const r=t[t.length-1];for(let n=1;n<=e;n++){const i=mC(0,e,n);t.push(co(r,1,i))}}function Nst(t){const e=[0];return Pst(e,t.length-1),e}function Rst(t,e){return t.map(r=>r*e)}function Lst(t,e){return t.map(()=>e||tTe).splice(0,t.length-1)}function fj({duration:t=300,keyframes:e,times:r,ease:n="easeInOut"}){const i=Uit(n)?n.map(Hle):Hle(n),a={done:!1,value:e[0]},c=Rst(r&&r.length===e.length?r:Nst(e),t),d=Cst(c,e,{ease:Array.isArray(i)?i:Lst(e,i)});return{calculatedDuration:t,next:p=>(a.value=d(p),a.done=p>=t,a)}}const Dst=t=>t!==null;function M5(t,{repeat:e,repeatType:r="loop"},n,i=1){const a=t.filter(Dst),d=i<0||e&&r!=="loop"&&e%2===1?0:a.length-1;return!d||n===void 0?a[d]:n}const Mst={decay:h9,inertia:h9,tween:fj,keyframes:fj,spring:PF};function mTe(t){typeof t.type=="string"&&(t.type=Mst[t.type])}class wZ{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,r){return this.finished.then(e,r)}}const Ost=t=>t/100;class NF extends wZ{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{var n,i;const{motionValue:r}=this.options;r&&r.updatedAt!==Nd.now()&&this.tick(Nd.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(i=(n=this.options).onStop)==null||i.call(n))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;mTe(e);const{type:r=fj,repeat:n=0,repeatDelay:i=0,repeatType:a,velocity:c=0}=e;let{keyframes:d}=e;const p=r||fj;p!==fj&&typeof d[0]!="number"&&(this.mixKeyframes=eN(Ost,dTe(d[0],d[1])),d=[0,100]);const l=p({...e,keyframes:d});a==="mirror"&&(this.mirroredGenerator=p({...e,keyframes:[...d].reverse(),velocity:-c})),l.calculatedDuration===null&&(l.calculatedDuration=bZ(l));const{calculatedDuration:g}=l;this.calculatedDuration=g,this.resolvedDuration=g+i,this.totalDuration=this.resolvedDuration*(n+1)-i,this.generator=l}updateTime(e){const r=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=r}tick(e,r=!1){const{generator:n,totalDuration:i,mixKeyframes:a,mirroredGenerator:c,resolvedDuration:d,calculatedDuration:p}=this;if(this.startTime===null)return n.next(0);const{delay:l=0,keyframes:g,repeat:v,repeatType:E,repeatDelay:T,type:j,onUpdate:P,finalKeyframe:C}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-i/this.speed,this.startTime)),r?this.currentTime=e:this.updateTime(e);const L=this.currentTime-l*(this.playbackSpeed>=0?1:-1),O=this.playbackSpeed>=0?L<0:L>i;this.currentTime=Math.max(L,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=i);let F=this.currentTime,$=n;if(v){const Q=Math.min(this.currentTime,i)/d;let ee=Math.floor(Q),ie=Q%1;!ie&&Q>=1&&(ie=1),ie===1&&ee--,ee=Math.min(ee,v+1),!!(ee%2)&&(E==="reverse"?(ie=1-ie,T&&(ie-=T/d)):E==="mirror"&&($=c)),F=yg(0,1,ie)*d}let G;O?(this.delayState.value=g[0],G=this.delayState):G=$.next(F),a&&!O&&(G.value=a(G.value));let{done:W}=G;!O&&p!==null&&(W=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const Z=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&W);return Z&&j!==h9&&(G.value=M5(g,this.options,C,this.speed)),P&&P(G.value),Z&&this.finish(),G}then(e,r){return this.finished.then(e,r)}get duration(){return Bf(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Bf(e)}get time(){return Bf(this.currentTime)}set time(e){e=Zh(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=e,this.tick(e))}getGeneratorVelocity(){const e=this.currentTime;if(e<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(e);const r=this.generator.next(e).value;return fTe(n=>this.generator.next(n).value,e,r)}get speed(){return this.playbackSpeed}set speed(e){const r=this.playbackSpeed!==e;r&&this.driver&&this.updateTime(Nd.now()),this.playbackSpeed=e,r&&this.driver&&(this.time=Bf(this.currentTime))}play(){var i,a;if(this.isStopped)return;const{driver:e=vst,startTime:r}=this.options;this.driver||(this.driver=e(c=>this.tick(c))),(a=(i=this.options).onPlay)==null||a.call(i);const n=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=n):this.holdTime!==null?this.startTime=n-this.holdTime:this.startTime||(this.startTime=r??n),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Nd.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,r;this.notifyFinished(),this.teardown(),this.state="finished",(r=(e=this.options).onComplete)==null||r.call(e)}cancel(){var e,r;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(r=(e=this.options).onCancel)==null||r.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var r;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(r=this.driver)==null||r.stop(),e.observe(this)}}function Fst(t){for(let e=1;et*180/Math.PI,f9=t=>{const e=Cb(Math.atan2(t[1],t[0]));return m9(e)},Bst={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:f9,rotateZ:f9,skewX:t=>Cb(Math.atan(t[1])),skewY:t=>Cb(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},m9=t=>(t=t%360,t<0&&(t+=360),t),Jle=f9,ece=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),tce=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),zst={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ece,scaleY:tce,scale:t=>(ece(t)+tce(t))/2,rotateX:t=>m9(Cb(Math.atan2(t[6],t[5]))),rotateY:t=>m9(Cb(Math.atan2(-t[2],t[0]))),rotateZ:Jle,rotate:Jle,skewX:t=>Cb(Math.atan(t[4])),skewY:t=>Cb(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function p9(t){return t.includes("scale")?1:0}function g9(t,e){if(!t||t==="none")return p9(e);const r=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,i;if(r)n=zst,i=r;else{const d=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=Bst,i=d}if(!i)return p9(e);const a=n[e],c=i[1].split(",").map(Ust);return typeof a=="function"?a(c):c[a]}const $st=(t,e)=>{const{transform:r="none"}=getComputedStyle(t);return g9(r,e)};function Ust(t){return parseFloat(t.trim())}const kA=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],IA=new Set([...kA,"pathRotation"]),rce=t=>t===AA||t===Qn,Vst=new Set(["x","y","z"]),qst=kA.filter(t=>!Vst.has(t));function Gst(t){const e=[];return qst.forEach(r=>{const n=t.getValue(r);n!==void 0&&(e.push([r,n.get()]),n.set(r.startsWith("scale")?1:0))}),e}const Q_={width:({x:t},{paddingLeft:e="0",paddingRight:r="0",boxSizing:n})=>{const i=t.max-t.min;return n==="border-box"?i:i-parseFloat(e)-parseFloat(r)},height:({y:t},{paddingTop:e="0",paddingBottom:r="0",boxSizing:n})=>{const i=t.max-t.min;return n==="border-box"?i:i-parseFloat(e)-parseFloat(r)},top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>g9(e,"x"),y:(t,{transform:e})=>g9(e,"y")};Q_.translateX=Q_.x;Q_.translateY=Q_.y;const Kb=new Set;let y9=!1,x9=!1,_9=!1;function pTe(){if(x9){const t=Array.from(Kb).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),r=new Map;e.forEach(n=>{const i=Gst(n);i.length&&(r.set(n,i),n.render())}),t.forEach(n=>n.measureInitialState()),e.forEach(n=>{n.render();const i=r.get(n);i&&i.forEach(([a,c])=>{var d;(d=n.getValue(a))==null||d.set(c)})}),t.forEach(n=>n.measureEndState()),t.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}x9=!1,y9=!1,Kb.forEach(t=>t.complete(_9)),Kb.clear()}function gTe(){Kb.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(x9=!0)})}function Hst(){_9=!0,gTe(),pTe(),_9=!1}class SZ{constructor(e,r,n,i,a,c=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=r,this.name=n,this.motionValue=i,this.element=a,this.isAsync=c}scheduleResolve(){this.state="scheduled",this.isAsync?(Kb.add(this),y9||(y9=!0,uo.read(gTe),uo.resolveKeyframes(pTe))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:r,element:n,motionValue:i}=this;if(e[0]===null){const a=i==null?void 0:i.get(),c=e[e.length-1];if(a!==void 0)e[0]=a;else if(n&&r){const d=n.readValue(r,c);d!=null&&(e[0]=d)}e[0]===void 0&&(e[0]=c),i&&a===void 0&&i.set(e[0])}Fst(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Kb.delete(this)}cancel(){this.state==="scheduled"&&(Kb.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Wst=t=>t.startsWith("--");function yTe(t,e,r){Wst(e)?t.style.setProperty(e,r):t.style[e]=r}const Kst={};function xTe(t,e){const r=GEe(t);return()=>Kst[e]??r()}const Yst=xTe(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),_Te=xTe(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),zI=([t,e,r,n])=>`cubic-bezier(${t}, ${e}, ${r}, ${n})`,nce={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:zI([0,.65,.55,1]),circOut:zI([.55,0,1,.45]),backIn:zI([.31,.01,.66,-.59]),backOut:zI([.33,1.53,.69,.99])};function vTe(t,e){if(t)return typeof t=="function"?_Te()?hTe(t,e):"ease-out":rTe(t)?zI(t):Array.isArray(t)?t.map(r=>vTe(r,e)||nce.easeOut):nce[t]}function Zst(t,e,r,{delay:n=0,duration:i=300,repeat:a=0,repeatType:c="loop",ease:d="easeOut",times:p}={},l=void 0){const g={[e]:r};p&&(g.offset=p);const v=vTe(d,i);Array.isArray(v)&&(g.easing=v);const E={delay:n,duration:i,easing:Array.isArray(v)?"linear":v,fill:"both",iterations:a+1,direction:c==="reverse"?"alternate":"normal"};return l&&(E.pseudoElement=l),t.animate(g,E)}function bTe(t){return typeof t=="function"&&"applyToOptions"in t}function Xst({type:t,...e}){return bTe(t)&&_Te()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class wTe extends wZ{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!e)return;const{element:r,name:n,keyframes:i,pseudoElement:a,allowFlatten:c=!1,finalKeyframe:d,onComplete:p}=e;this.isPseudoElement=!!a,this.allowFlatten=c,this.options=e,D5(typeof e.type!="string");const l=Xst(e);this.animation=Zst(r,n,i,l,a),l.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!a){const g=M5(i,this.options,d,this.speed);this.updateMotionValue&&this.updateMotionValue(g),yTe(r,n,g),this.animation.cancel()}p==null||p(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,r;(r=(e=this.animation).finish)==null||r.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var r,n,i;const e=(r=this.options)==null?void 0:r.element;!this.isPseudoElement&&(e!=null&&e.isConnected)&&((i=(n=this.animation).commitStyles)==null||i.call(n))}get duration(){var r,n;const e=((n=(r=this.animation.effect)==null?void 0:r.getComputedTiming)==null?void 0:n.call(r).duration)||0;return Bf(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+Bf(e)}get time(){return Bf(Number(this.animation.currentTime)||0)}set time(e){const r=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Zh(e),r&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(e){this.manualStartTime=this.animation.startTime=e}attachTimeline({timeline:e,rangeStart:r,rangeEnd:n,observe:i}){var a;return this.allowFlatten&&((a=this.animation.effect)==null||a.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&Yst()?(this.animation.timeline=e,r&&(this.animation.rangeStart=r),n&&(this.animation.rangeEnd=n),Vf):i(this)}}const STe={anticipate:QEe,backInOut:XEe,circInOut:eTe};function Qst(t){return t in STe}function Jst(t){typeof t.ease=="string"&&Qst(t.ease)&&(t.ease=STe[t.ease])}const GU=10;class eat extends wTe{constructor(e){Jst(e),mTe(e),super(e),e.startTime!==void 0&&e.autoplay!==!1&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:r,onUpdate:n,onComplete:i,element:a,...c}=this.options;if(!r)return;if(e!==void 0){r.set(e);return}const d=new NF({...c,autoplay:!1}),p=Math.max(GU,Nd.now()-this.startTime),l=yg(0,GU,p-GU),g=d.sample(p).value,{name:v}=this.options;a&&v&&yTe(a,v,g),r.setWithVelocity(d.sample(Math.max(0,p-l)).value,g,l),d.stop()}}const ice=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(tp.test(t)||t==="0")&&!t.startsWith("url("));function tat(t){const e=t[0];if(t.length===1)return!0;for(let r=0;rObject.hasOwnProperty.call(Element.prototype,"animate"));function oat(t){var v;const{motionValue:e,name:r,repeatDelay:n,repeatType:i,damping:a,type:c,keyframes:d}=t,p=(v=e==null?void 0:e.owner)==null?void 0:v.current;if(!(p instanceof HTMLElement)&&!(p instanceof SVGElement))return!1;const{onUpdate:l,transformTemplate:g}=e.owner.getProps();return aat()&&r&&(ETe.has(r)||sat.has(r)&&iat(d))&&(r!=="transform"||!g)&&!l&&!n&&i!=="mirror"&&a!==0&&c!=="inertia"}const lat=40;class cat extends wZ{constructor({autoplay:e=!0,delay:r=0,type:n="keyframes",repeat:i=0,repeatDelay:a=0,repeatType:c="loop",keyframes:d,name:p,motionValue:l,element:g,...v}){var j;super(),this.stop=()=>{var P,C;this._animation&&(this._animation.stop(),(P=this.stopTimeline)==null||P.call(this)),(C=this.keyframeResolver)==null||C.cancel()},this.createdAt=Nd.now();const E={autoplay:e,delay:r,type:n,repeat:i,repeatDelay:a,repeatType:c,name:p,motionValue:l,element:g,...v},T=(g==null?void 0:g.KeyframeResolver)||SZ;this.keyframeResolver=new T(d,(P,C,L)=>this.onKeyframesResolved(P,C,E,!L),p,l,g),(j=this.keyframeResolver)==null||j.scheduleResolve()}onKeyframesResolved(e,r,n,i){var L,O;this.keyframeResolver=void 0;const{name:a,type:c,velocity:d,delay:p,isHandoff:l,onUpdate:g}=n;this.resolvedAt=Nd.now();let v=!0;rat(e,a,c,d)||(v=!1,(Iv.instantAnimations||!p)&&(g==null||g(M5(e,n,r))),e[0]=e[e.length-1],v9(n),n.repeat=0);const T={startTime:i?this.resolvedAt?this.resolvedAt-this.createdAt>lat?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:r,...n,keyframes:e},j=v&&!l&&oat(T),P=(O=(L=T.motionValue)==null?void 0:L.owner)==null?void 0:O.current;let C;if(j)try{C=new eat({...T,element:P})}catch{C=new NF(T)}else C=new NF(T);C.finished.then(()=>{this.notifyFinished()}).catch(Vf),this.pendingTimeline&&(this.stopTimeline=C.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=C}get finished(){return this._animation?this.animation.finished:this._finished}then(e,r){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),Hst()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var e;this._animation&&this.animation.cancel(),(e=this.keyframeResolver)==null||e.cancel()}}function TTe(t,e,r,n=0,i=1){const a=Array.from(t).sort((l,g)=>l.sortNodePosition(g)).indexOf(e),c=t.size,d=(c-1)*n;return typeof r=="function"?r(a,c):i===1?a*n:d-a*n}const sce=30,uat=t=>!isNaN(parseFloat(t));class dat{constructor(e,r={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=n=>{var a;const i=Nd.now();if(this.updatedAt!==i&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(n),this.current!==this.prev&&((a=this.events.change)==null||a.notify(this.current),this.dependents))for(const c of this.dependents)c.dirty()},this.hasAnimated=!1,this.setCurrent(e),this.owner=r.owner}setCurrent(e){this.current=e,this.updatedAt=Nd.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=uat(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,r){this.events[e]||(this.events[e]=new mZ);const n=this.events[e].add(r);return e==="change"?()=>{n(),uo.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,r){this.passiveEffect=e,this.stopPassiveEffect=r}set(e){this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e)}setWithVelocity(e,r,n){this.set(r),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,r=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,r&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=Nd.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>sce)return 0;const r=Math.min(this.updatedAt-this.prevUpdatedAt,sce);return HEe(parseFloat(this.current)-parseFloat(this.prevFrameValue),r)}start(e){return this.stop(),new Promise(r=>{this.hasAnimated=!0,this.animation=e(r),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var e,r;(e=this.dependents)==null||e.clear(),(r=this.events.destroy)==null||r.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function xT(t,e){return new dat(t,e)}function ATe(t,e){if(t!=null&&t.inherit&&e){const{inherit:r,...n}=t;return{...e,...n}}return t}function EZ(t,e){const r=(t==null?void 0:t[e])??(t==null?void 0:t.default)??t;return r!==t?ATe(r,t):r}const hat={type:"spring",stiffness:500,damping:25,restSpeed:10},fat=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),mat={type:"keyframes",duration:.8},pat={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},gat=(t,{keyframes:e})=>e.length>2?mat:IA.has(t)?t.startsWith("scale")?fat(e[1]):hat:pat,yat=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function xat(t){for(const e in t)if(!yat.has(e))return!0;return!1}const TZ=(t,e,r,n={},i,a)=>c=>{const d=EZ(n,t)||{},p=d.delay||n.delay||0;let{elapsed:l=0}=n;l=l-Zh(p);const g={keyframes:Array.isArray(r)?r:[null,r],ease:"easeOut",velocity:e.getVelocity(),...d,delay:-l,onUpdate:E=>{e.set(E),d.onUpdate&&d.onUpdate(E)},onComplete:()=>{c(),d.onComplete&&d.onComplete()},name:t,motionValue:e,element:a?void 0:i};xat(d)||Object.assign(g,gat(t,g)),g.duration&&(g.duration=Zh(g.duration)),g.repeatDelay&&(g.repeatDelay=Zh(g.repeatDelay)),g.from!==void 0&&(g.keyframes[0]=g.from);let v=!1;if((g.type===!1||g.duration===0&&!g.repeatDelay)&&(v9(g),g.delay===0&&(v=!0)),(Iv.instantAnimations||Iv.skipAnimations||i!=null&&i.shouldSkipAnimations||d.skipAnimations)&&(v=!0,v9(g),g.delay=0),g.allowFlatten=!d.type&&!d.ease,v&&!a&&e.get()!==void 0){const E=M5(g.keyframes,d);if(E!==void 0){uo.update(()=>{g.onUpdate(E),g.onComplete()});return}}return d.isSync?new NF(g):new cat(g)},_at=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function vat(t){const e=_at.exec(t);if(!e)return[,];const[,r,n,i]=e;return[`--${r??n}`,i]}function kTe(t,e,r=1){const[n,i]=vat(t);if(!n)return;const a=window.getComputedStyle(e).getPropertyValue(n);if(a){const c=a.trim();return UEe(c)?parseFloat(c):c}return yZ(i)?kTe(i,e,r+1):i}function ace(t){const e=[{},{}];return t==null||t.values.forEach((r,n)=>{e[0][n]=r.get(),e[1][n]=r.getVelocity()}),e}function AZ(t,e,r,n){if(typeof e=="function"){const[i,a]=ace(n);e=e(r!==void 0?r:t.custom,i,a)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[i,a]=ace(n);e=e(r!==void 0?r:t.custom,i,a)}return e}function Yb(t,e,r){const n=t.getProps();return AZ(n,e,r!==void 0?r:n.custom,t)}const ITe=new Set(["width","height","top","left","right","bottom",...kA]),b9=t=>Array.isArray(t);function bat(t,e,r){t.hasValue(e)?t.getValue(e).set(r):t.addValue(e,xT(r))}function wat(t){return b9(t)?t[t.length-1]||0:t}function Sat(t,e){const r=Yb(t,e);let{transitionEnd:n={},transition:i={},...a}=r||{};a={...a,...n};for(const c in a){const d=wat(a[c]);bat(t,c,d)}}const Bu=t=>!!(t&&t.getVelocity);function Eat(t){return!!(Bu(t)&&t.add)}function w9(t,e){const r=t.getValue("willChange");if(Eat(r))return r.add(e);if(!r&&Iv.WillChange){const n=new Iv.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function kZ(t){return t.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}const Tat="framerAppearId",jTe="data-"+kZ(Tat);function CTe(t){return t.props[jTe]}function Aat({protectedKeys:t,needsAnimating:e},r){const n=t.hasOwnProperty(r)&&e[r]!==!0;return e[r]=!1,n}function PTe(t,e,{delay:r=0,transitionOverride:n,type:i}={}){let{transition:a,transitionEnd:c,...d}=e;const p=t.getDefaultTransition();a=a?ATe(a,p):p;const l=a==null?void 0:a.reduceMotion,g=a==null?void 0:a.skipAnimations;n&&(a=n);const v=[],E=i&&t.animationState&&t.animationState.getState()[i],T=a==null?void 0:a.path;T&&T.animateVisualElement(t,d,a,r,v);for(const j in d){const P=t.getValue(j,t.latestValues[j]??null),C=d[j];if(C===void 0||E&&Aat(E,j))continue;const L={delay:r,...EZ(a||{},j)};g&&(L.skipAnimations=!0);const O=P.get();if(O!==void 0&&!P.isAnimating()&&!Array.isArray(C)&&C===O&&!L.velocity){uo.update(()=>P.set(C));continue}let F=!1;if(window.MotionHandoffAnimation){const W=CTe(t);if(W){const Z=window.MotionHandoffAnimation(W,j,uo);Z!==null&&(L.startTime=Z,F=!0)}}w9(t,j);const $=l??t.shouldReduceMotion;P.start(TZ(j,P,C,$&&ITe.has(j)?{type:!1}:L,t,F));const G=P.animation;G&&v.push(G)}if(c){const j=()=>uo.update(()=>{c&&Sat(t,c)});v.length?Promise.all(v).then(j):j()}return v}function S9(t,e,r={}){var p;const n=Yb(t,e,r.type==="exit"?(p=t.presenceContext)==null?void 0:p.custom:void 0);let{transition:i=t.getDefaultTransition()||{}}=n||{};r.transitionOverride&&(i=r.transitionOverride);const a=n?()=>Promise.all(PTe(t,n,r)):()=>Promise.resolve(),c=t.variantChildren&&t.variantChildren.size?(l=0)=>{const{delayChildren:g=0,staggerChildren:v,staggerDirection:E}=i;return kat(t,e,l,g,v,E,r)}:()=>Promise.resolve(),{when:d}=i;if(d){const[l,g]=d==="beforeChildren"?[a,c]:[c,a];return l().then(()=>g())}else return Promise.all([a(),c(r.delay)])}function kat(t,e,r=0,n=0,i=0,a=1,c){const d=[];for(const p of t.variantChildren)p.notify("AnimationStart",e),d.push(S9(p,e,{...c,delay:r+(typeof n=="function"?0:n)+TTe(t.variantChildren,p,n,i,a)}).then(()=>p.notify("AnimationComplete",e)));return Promise.all(d)}function Iat(t,e,r={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const i=e.map(a=>S9(t,a,r));n=Promise.all(i)}else if(typeof e=="string")n=S9(t,e,r);else{const i=typeof e=="function"?Yb(t,e,r.custom):e;n=Promise.all(PTe(t,i,r))}return n.then(()=>{t.notify("AnimationComplete",e)})}const jat={test:t=>t==="auto",parse:t=>t},NTe=t=>e=>e.test(t),RTe=[AA,Qn,sg,my,tst,est,jat],oce=t=>RTe.find(NTe(t));function Cat(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||qEe(t):!0}const Pat=new Set(["brightness","contrast","saturate","opacity"]);function Nat(t){const[e,r]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=r.match(xZ)||[];if(!n)return t;const i=r.replace(n,"");let a=Pat.has(e)?1:0;return n!==r&&(a*=100),e+"("+a+i+")"}const Rat=/\b([a-z-]*)\(.*?\)/gu,E9={...tp,getAnimatableNone:t=>{const e=t.match(Rat);return e?e.map(Nat).join(" "):t}},T9={...tp,getAnimatableNone:t=>{const e=tp.parse(t);return tp.createTransformer(t)(e.map(n=>typeof n=="number"?0:typeof n=="object"?{...n,alpha:1}:n))}},lce={...AA,transform:Math.round},Lat={rotate:my,pathRotation:my,rotateX:my,rotateY:my,rotateZ:my,scale:DD,scaleX:DD,scaleY:DD,scaleZ:DD,skew:my,skewX:my,skewY:my,distance:Qn,translateX:Qn,translateY:Qn,translateZ:Qn,x:Qn,y:Qn,z:Qn,perspective:Qn,transformPerspective:Qn,opacity:pC,originX:Kle,originY:Kle,originZ:Qn},RF={borderWidth:Qn,borderTopWidth:Qn,borderRightWidth:Qn,borderBottomWidth:Qn,borderLeftWidth:Qn,borderRadius:Qn,borderTopLeftRadius:Qn,borderTopRightRadius:Qn,borderBottomRightRadius:Qn,borderBottomLeftRadius:Qn,width:Qn,maxWidth:Qn,height:Qn,maxHeight:Qn,top:Qn,right:Qn,bottom:Qn,left:Qn,inset:Qn,insetBlock:Qn,insetBlockStart:Qn,insetBlockEnd:Qn,insetInline:Qn,insetInlineStart:Qn,insetInlineEnd:Qn,padding:Qn,paddingTop:Qn,paddingRight:Qn,paddingBottom:Qn,paddingLeft:Qn,paddingBlock:Qn,paddingBlockStart:Qn,paddingBlockEnd:Qn,paddingInline:Qn,paddingInlineStart:Qn,paddingInlineEnd:Qn,margin:Qn,marginTop:Qn,marginRight:Qn,marginBottom:Qn,marginLeft:Qn,marginBlock:Qn,marginBlockStart:Qn,marginBlockEnd:Qn,marginInline:Qn,marginInlineStart:Qn,marginInlineEnd:Qn,fontSize:Qn,backgroundPositionX:Qn,backgroundPositionY:Qn,...Lat,zIndex:lce,fillOpacity:pC,strokeOpacity:pC,numOctaves:lce},Dat={...RF,color:cc,backgroundColor:cc,outlineColor:cc,fill:cc,stroke:cc,borderColor:cc,borderTopColor:cc,borderRightColor:cc,borderBottomColor:cc,borderLeftColor:cc,filter:E9,WebkitFilter:E9,mask:T9,WebkitMask:T9},LTe=t=>Dat[t],Mat=new Set([E9,T9]);function DTe(t,e){let r=LTe(t);return Mat.has(r)||(r=tp),r.getAnimatableNone?r.getAnimatableNone(e):void 0}const Oat=new Set(["auto","none","0"]);function Fat(t,e,r){let n=0,i;for(;n{e.getValue(p).set(l)}),this.resolveNoneKeyframes()}}const IZ=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function MTe(t,e,r){if(t==null)return[];if(t instanceof EventTarget)return[t];if(typeof t=="string"){const i=document.querySelectorAll(t);return i?Array.from(i):[]}return Array.from(t).filter(n=>n!=null)}const A9=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function sO(t){return VEe(t)&&"offsetHeight"in t&&!("ownerSVGElement"in t)}const{schedule:jZ}=nTe(queueMicrotask,!1),Rm={x:!1,y:!1};function OTe(){return Rm.x||Rm.y}function zat(t){return t==="x"||t==="y"?Rm[t]?null:(Rm[t]=!0,()=>{Rm[t]=!1}):Rm.x||Rm.y?null:(Rm.x=Rm.y=!0,()=>{Rm.x=Rm.y=!1})}function FTe(t,e){const r=MTe(t),n=new AbortController,i={passive:!0,...e,signal:n.signal};return[r,i,()=>n.abort()]}function $at(t){return!(t.pointerType==="touch"||OTe())}function Uat(t,e,r={}){const[n,i,a]=FTe(t,r);return n.forEach(c=>{let d=!1,p=!1,l;const g=()=>{c.removeEventListener("pointerleave",j)},v=C=>{l&&(l(C),l=void 0),g()},E=C=>{d=!1,window.removeEventListener("pointerup",E),window.removeEventListener("pointercancel",E),p&&(p=!1,v(C))},T=()=>{d=!0,window.addEventListener("pointerup",E,i),window.addEventListener("pointercancel",E,i)},j=C=>{if(C.pointerType!=="touch"){if(d){p=!0;return}v(C)}},P=C=>{if(!$at(C))return;p=!1;const L=e(c,C);typeof L=="function"&&(l=L,c.addEventListener("pointerleave",j,i))};c.addEventListener("pointerenter",P,i),c.addEventListener("pointerdown",T,i)}),a}const BTe=(t,e)=>e?t===e?!0:BTe(t,e.parentElement):!1,CZ=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Vat=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function qat(t){return Vat.has(t.tagName)||t.isContentEditable===!0}const Gat=new Set(["INPUT","SELECT","TEXTAREA"]);function Hat(t){return Gat.has(t.tagName)||t.isContentEditable===!0}const aO=new WeakSet;function cce(t){return e=>{e.key==="Enter"&&t(e)}}function HU(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Wat=(t,e)=>{const r=t.currentTarget;if(!r)return;const n=cce(()=>{if(aO.has(r))return;HU(r,"down");const i=cce(()=>{HU(r,"up")}),a=()=>HU(r,"cancel");r.addEventListener("keyup",i,e),r.addEventListener("blur",a,e)});r.addEventListener("keydown",n,e),r.addEventListener("blur",()=>r.removeEventListener("keydown",n),e)};function uce(t){return CZ(t)&&!OTe()}const dce=new WeakSet;function Kat(t,e,r={}){const[n,i,a]=FTe(t,r),c=d=>{const p=d.currentTarget;if(!uce(d)||dce.has(d))return;aO.add(p),r.stopPropagation&&dce.add(d);const l=e(p,d),g={...i,capture:!0},v=(j,P)=>{window.removeEventListener("pointerup",E,g),window.removeEventListener("pointercancel",T,g),aO.has(p)&&aO.delete(p),uce(j)&&typeof l=="function"&&l(j,{success:P})},E=j=>{v(j,p===window||p===document||r.useGlobalTarget||BTe(p,j.target))},T=j=>{v(j,!1)};window.addEventListener("pointerup",E,g),window.addEventListener("pointercancel",T,g)};return n.forEach(d=>{(r.useGlobalTarget?window:d).addEventListener("pointerdown",c,i),sO(d)&&(d.addEventListener("focus",l=>Wat(l,i)),!qat(d)&&!d.hasAttribute("tabindex")&&(d.tabIndex=0))}),a}function PZ(t){return VEe(t)&&"ownerSVGElement"in t}const oO=new WeakMap;let A_;const zTe=(t,e,r)=>(n,i)=>i&&i[0]?i[0][t+"Size"]:PZ(n)&&"getBBox"in n?n.getBBox()[e]:n[r],Yat=zTe("inline","width","offsetWidth"),Zat=zTe("block","height","offsetHeight");function Xat({target:t,borderBoxSize:e}){var r;(r=oO.get(t))==null||r.forEach(n=>{n(t,{get width(){return Yat(t,e)},get height(){return Zat(t,e)}})})}function Qat(t){t.forEach(Xat)}function Jat(){typeof ResizeObserver>"u"||(A_=new ResizeObserver(Qat))}function eot(t,e){A_||Jat();const r=MTe(t);return r.forEach(n=>{let i=oO.get(n);i||(i=new Set,oO.set(n,i)),i.add(e),A_==null||A_.observe(n)}),()=>{r.forEach(n=>{const i=oO.get(n);i==null||i.delete(e),i!=null&&i.size||A_==null||A_.unobserve(n)})}}const lO=new Set;let aE;function tot(){aE=()=>{const t={get width(){return window.innerWidth},get height(){return window.innerHeight}};lO.forEach(e=>e(t))},window.addEventListener("resize",aE)}function rot(t){return lO.add(t),aE||tot(),()=>{lO.delete(t),!lO.size&&typeof aE=="function"&&(window.removeEventListener("resize",aE),aE=void 0)}}function hce(t,e){return typeof t=="function"?rot(t):eot(t,e)}function not(t){return PZ(t)&&t.tagName==="svg"}const iot=[...RTe,cc,tp],sot=t=>iot.find(NTe(t)),fce=()=>({translate:0,scale:1,origin:0,originPoint:0}),oE=()=>({x:fce(),y:fce()}),mce=()=>({min:0,max:0}),jc=()=>({x:mce(),y:mce()}),aot=new WeakMap;function O5(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function gC(t){return typeof t=="string"||Array.isArray(t)}const NZ=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],RZ=["initial",...NZ];function F5(t){return O5(t.animate)||RZ.some(e=>gC(t[e]))}function $Te(t){return!!(F5(t)||t.variants)}function oot(t,e,r){for(const n in e){const i=e[n],a=r[n];if(Bu(i))t.addValue(n,i);else if(Bu(a))t.addValue(n,xT(i,{owner:t}));else if(a!==i)if(t.hasValue(n)){const c=t.getValue(n);c.liveStyle===!0?c.jump(i):c.hasAnimated||c.set(i)}else{const c=t.getStaticValue(n);t.addValue(n,xT(c!==void 0?c:i,{owner:t}))}}for(const n in r)e[n]===void 0&&t.removeValue(n);return e}const k9={current:null},UTe={current:!1},lot=typeof window<"u";function cot(){if(UTe.current=!0,!!lot)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>k9.current=t.matches;t.addEventListener("change",e),e()}else k9.current=!1}const pce=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let LF={};function VTe(t){LF=t}function uot(){return LF}class dot{scrapeMotionValuesFromProps(e,r,n){return{}}constructor({parent:e,props:r,presenceContext:n,reducedMotionConfig:i,skipAnimations:a,blockInitialAnimation:c,visualState:d},p={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=SZ,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const T=Nd.now();this.renderScheduledAtthis.bindToMotionValue(a,i)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(UTe.current||cot(),this.shouldReduceMotion=k9.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,(n=this.parent)==null||n.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){var e;this.projection&&this.projection.unmount(),jv(this.notifyUpdate),jv(this.render),this.valueSubscriptions.forEach(r=>r()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(e=this.parent)==null||e.removeChild(this);for(const r in this.events)this.events[r].clear();for(const r in this.features){const n=this.features[r];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(e){this.children.add(e),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(e)}removeChild(e){this.children.delete(e),this.enteringChildren&&this.enteringChildren.delete(e)}bindToMotionValue(e,r){if(this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)(),r.accelerate&&ETe.has(e)&&this.current instanceof HTMLElement){const{factory:c,keyframes:d,times:p,ease:l,duration:g}=r.accelerate,v=new wTe({element:this.current,name:e,keyframes:d,times:p,ease:l,duration:Zh(g)}),E=c(v);this.valueSubscriptions.set(e,()=>{E(),v.cancel()});return}const n=IA.has(e);n&&this.onBindTransform&&this.onBindTransform();const i=r.on("change",c=>{this.latestValues[e]=c,this.props.onUpdate&&uo.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let a;typeof window<"u"&&window.MotionCheckAppearSync&&(a=window.MotionCheckAppearSync(this,e,r)),this.valueSubscriptions.set(e,()=>{i(),a&&a()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in LF){const r=LF[e];if(!r)continue;const{isEnabled:n,Feature:i}=r;if(!this.features[e]&&i&&n(this.props)&&(this.features[e]=new i(this)),this.features[e]){const a=this.features[e];a.isMounted?a.update():(a.mount(),a.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):jc()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,r){this.latestValues[e]=r}update(e,r){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=r;for(let n=0;nr.variantChildren.delete(e)}addValue(e,r){const n=this.values.get(e);r!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,r),this.values.set(e,r),this.latestValues[e]=r.get())}removeValue(e){this.values.delete(e);const r=this.valueSubscriptions.get(e);r&&(r(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,r){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return n===void 0&&r!==void 0&&(n=xT(r===null?void 0:r,{owner:this}),this.addValue(e,n)),n}readValue(e,r){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n=="string"&&(UEe(n)||qEe(n))?n=parseFloat(n):!sot(n)&&tp.test(r)&&(n=DTe(e,r)),this.setBaseTarget(e,Bu(n)?n.get():n)),Bu(n)?n.get():n}setBaseTarget(e,r){this.baseTarget[e]=r}getBaseTarget(e){var a;const{initial:r}=this.props;let n;if(typeof r=="string"||typeof r=="object"){const c=AZ(this.props,r,(a=this.presenceContext)==null?void 0:a.custom);c&&(n=c[e])}if(r&&n!==void 0)return n;const i=this.getBaseTargetFromProps(this.props,e);return i!==void 0&&!Bu(i)?i:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,r){return this.events[e]||(this.events[e]=new mZ),this.events[e].add(r)}notify(e,...r){this.events[e]&&this.events[e].notify(...r)}scheduleRenderMicrotask(){jZ.render(this.render)}}class qTe extends dot{constructor(){super(...arguments),this.KeyframeResolver=Bat}sortInstanceNodePosition(e,r){return e.compareDocumentPosition(r)&2?1:-1}getBaseTargetFromProps(e,r){const n=e.style;return n?n[r]:void 0}removeValueFromRenderState(e,{vars:r,style:n}){delete r[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Bu(e)&&(this.childSubscription=e.on("change",r=>{this.current&&(this.current.textContent=`${r}`)}))}}class Kv{constructor(e){this.isMounted=!1,this.node=e}update(){}}function GTe({top:t,left:e,right:r,bottom:n}){return{x:{min:e,max:r},y:{min:t,max:n}}}function hot({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function fot(t,e){if(!e)return t;const r=e({x:t.left,y:t.top}),n=e({x:t.right,y:t.bottom});return{top:r.y,left:r.x,bottom:n.y,right:n.x}}function WU(t){return t===void 0||t===1}function I9({scale:t,scaleX:e,scaleY:r}){return!WU(t)||!WU(e)||!WU(r)}function gb(t){return I9(t)||HTe(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function HTe(t){return gce(t.x)||gce(t.y)}function gce(t){return t&&t!=="0%"}function DF(t,e,r){const n=t-r,i=e*n;return r+i}function yce(t,e,r,n,i){return i!==void 0&&(t=DF(t,i,n)),DF(t,r,n)+e}function j9(t,e=0,r=1,n,i){t.min=yce(t.min,e,r,n,i),t.max=yce(t.max,e,r,n,i)}function WTe(t,{x:e,y:r}){j9(t.x,e.translate,e.scale,e.originPoint),j9(t.y,r.translate,r.scale,r.originPoint)}const xce=.999999999999,_ce=1.0000000000001;function mot(t,e,r,n=!1){var d;const i=r.length;if(!i)return;e.x=e.y=1;let a,c;for(let p=0;pxce&&(e.x=1),e.y<_ce&&e.y>xce&&(e.y=1)}function Gp(t,e){t.min+=e,t.max+=e}function vce(t,e,r,n,i=.5){const a=co(t.min,t.max,i);j9(t,e,r,a,n)}function bce(t,e){return typeof t=="string"?parseFloat(t)/100*(e.max-e.min):t}function cO(t,e,r){const n=r??t;vce(t.x,bce(e.x,n.x),e.scaleX,e.scale,e.originX),vce(t.y,bce(e.y,n.y),e.scaleY,e.scale,e.originY)}function KTe(t,e){return GTe(fot(t.getBoundingClientRect(),e))}function pot(t,e,r){const n=KTe(t,r),{scroll:i}=e;return i&&(Gp(n.x,i.offset.x),Gp(n.y,i.offset.y)),n}const got={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},yot=kA.length;function xot(t,e,r){let n="",i=!0;for(let c=0;c{if(!e.target)return t;if(typeof t=="string")if(Qn.test(t))t=parseFloat(t);else return t;const r=wce(t,e.target.x),n=wce(t,e.target.y);return`${r}% ${n}%`}},_ot={correct:(t,{treeScale:e,projectionDelta:r})=>{const n=t,i=tp.parse(t);if(i.length>5)return n;const a=tp.createTransformer(t),c=typeof i[0]!="number"?1:0,d=r.x.scale*e.x,p=r.y.scale*e.y;i[0+c]/=d,i[1+c]/=p;const l=co(d,p,.5);return typeof i[2+c]=="number"&&(i[2+c]/=l),typeof i[3+c]=="number"&&(i[3+c]/=l),a(i)}},C9={borderRadius:{...lI,applyTo:[...IZ]},borderTopLeftRadius:lI,borderTopRightRadius:lI,borderBottomLeftRadius:lI,borderBottomRightRadius:lI,boxShadow:_ot};function ZTe(t,{layout:e,layoutId:r}){return IA.has(t)||t.startsWith("origin")||(e||r!==void 0)&&(!!C9[t]||t==="opacity")}function DZ(t,e,r){var c;const n=t.style,i=e==null?void 0:e.style,a={};if(!n)return a;for(const d in n)(Bu(n[d])||i&&Bu(i[d])||ZTe(d,t)||((c=r==null?void 0:r.getValue(d))==null?void 0:c.liveStyle)!==void 0)&&(a[d]=n[d]);return a}function vot(t){return window.getComputedStyle(t)}class bot extends qTe{constructor(){super(...arguments),this.type="html",this.renderInstance=YTe}mount(e){D5(!!e.style),super.mount(e)}readValueFromInstance(e,r){var n;if(IA.has(r))return(n=this.projection)!=null&&n.isProjecting?p9(r):$st(e,r);{const i=vot(e),a=(sTe(r)?i.getPropertyValue(r):i[r])||0;return typeof a=="string"?a.trim():a}}measureInstanceViewportBox(e,{transformPagePoint:r}){return KTe(e,r)}build(e,r,n){LZ(e,r,n.transformTemplate)}scrapeMotionValuesFromProps(e,r,n){return DZ(e,r,n)}}const wot={offset:"stroke-dashoffset",array:"stroke-dasharray"},Sot={offset:"strokeDashoffset",array:"strokeDasharray"};function Eot(t,e,r=1,n=0,i=!0){t.pathLength=1;const a=i?wot:Sot;t[a.offset]=`${-n}`,t[a.array]=`${e} ${r}`}const Tot=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function XTe(t,{attrX:e,attrY:r,attrScale:n,pathLength:i,pathSpacing:a=1,pathOffset:c=0,...d},p,l,g){if(LZ(t,d,l),p){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:v,style:E}=t;v.transform&&(E.transform=v.transform,delete v.transform),(E.transform||v.transformOrigin)&&(E.transformOrigin=v.transformOrigin??"50% 50%",delete v.transformOrigin),E.transform&&(E.transformBox=(g==null?void 0:g.transformBox)??"fill-box",delete v.transformBox);for(const T of Tot)v[T]!==void 0&&(E[T]=v[T],delete v[T]);e!==void 0&&(v.x=e),r!==void 0&&(v.y=r),n!==void 0&&(v.scale=n),i!==void 0&&Eot(v,i,a,c,!1)}const QTe=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]),JTe=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Aot(t,e,r,n){YTe(t,e,void 0,n);for(const i in e.attrs)t.setAttribute(QTe.has(i)?i:kZ(i),e.attrs[i])}function eAe(t,e,r){const n=DZ(t,e,r);for(const i in t)if(Bu(t[i])||Bu(e[i])){const a=kA.indexOf(i)!==-1?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i;n[a]=t[i]}return n}class kot extends qTe{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=jc}getBaseTargetFromProps(e,r){return e[r]}readValueFromInstance(e,r){if(IA.has(r)){const n=LTe(r);return n&&n.default||0}return r=QTe.has(r)?r:kZ(r),e.getAttribute(r)}scrapeMotionValuesFromProps(e,r,n){return eAe(e,r,n)}build(e,r,n){XTe(e,r,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,r,n,i){Aot(e,r,n,i)}mount(e){this.isSVGTag=JTe(e.tagName),super.mount(e)}}const Iot=RZ.length;function tAe(t){if(!t)return;if(!t.isControllingVariants){const r=t.parent?tAe(t.parent)||{}:{};return t.props.initial!==void 0&&(r.initial=t.props.initial),r}const e={};for(let r=0;rPromise.all(e.map(({animation:r,options:n})=>Iat(t,r,n)))}function Not(t){let e=Pot(t),r=Sce(),n=!0,i=!1;const a=l=>(g,v)=>{var T;const E=Yb(t,v,l==="exit"?(T=t.presenceContext)==null?void 0:T.custom:void 0);if(E){const{transition:j,transitionEnd:P,...C}=E;g={...g,...C,...P}}return g};function c(l){e=l(t)}function d(l){const{props:g}=t,v=tAe(t.parent)||{},E=[],T=new Set;let j={},P=1/0;for(let L=0;LP&&G,ie=!1;const oe=Array.isArray($)?$:[$];let pe=oe.reduce(a(O),{});W===!1&&(pe={});const{prevResolvedValues:Le={}}=F,be={...Le,...pe},Re=ge=>{ee=!0,T.has(ge)&&(ie=!0,T.delete(ge)),F.needsAnimating[ge]=!0;const $e=t.getValue(ge);$e&&($e.liveStyle=!1)};for(const ge in be){const $e=pe[ge],we=Le[ge];if(j.hasOwnProperty(ge))continue;let ke=!1;b9($e)&&b9(we)?ke=!rAe($e,we)||Q:ke=$e!==we,ke?$e!=null?Re(ge):T.add(ge):$e!==void 0&&T.has(ge)?Re(ge):F.protectedKeys[ge]=!0}F.prevProp=$,F.prevResolvedValues=pe,F.isActive&&(j={...j,...pe}),(n||i)&&t.blockInitialAnimation&&(ee=!1);const Ie=Z&&Q;ee&&(!Ie||ie)&&E.push(...oe.map(ge=>{const $e={type:O};if(typeof ge=="string"&&(n||i)&&!Ie&&t.manuallyAnimateOnMount&&t.parent){const{parent:we}=t,ke=Yb(we,ge);if(we.enteringChildren&&ke){const{delayChildren:Ae}=ke.transition||{};$e.delay=TTe(we.enteringChildren,t,Ae)}}return{animation:ge,options:$e}}))}if(T.size){const L={};if(typeof g.initial!="boolean"){const O=Yb(t,Array.isArray(g.initial)?g.initial[0]:g.initial);O&&O.transition&&(L.transition=O.transition)}T.forEach(O=>{const F=t.getBaseTarget(O),$=t.getValue(O);$&&($.liveStyle=!0),L[O]=F??null}),E.push({animation:L})}let C=!!E.length;return n&&(g.initial===!1||g.initial===g.animate)&&!t.manuallyAnimateOnMount&&(C=!1),n=!1,i=!1,C?e(E):Promise.resolve()}function p(l,g){var E;if(r[l].isActive===g)return Promise.resolve();(E=t.variantChildren)==null||E.forEach(T=>{var j;return(j=T.animationState)==null?void 0:j.setActive(l,g)}),r[l].isActive=g;const v=d(l);for(const T in r)r[T].protectedKeys={};return v}return{animateChanges:d,setActive:p,setAnimateFunction:c,getState:()=>r,reset:()=>{r=Sce(),i=!0}}}function Rot(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!rAe(e,t):!1}function sb(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Sce(){return{animate:sb(!0),whileInView:sb(),whileHover:sb(),whileTap:sb(),whileDrag:sb(),whileFocus:sb(),exit:sb()}}function P9(t,e){t.min=e.min,t.max=e.max}function Tm(t,e){P9(t.x,e.x),P9(t.y,e.y)}function Ece(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}const nAe=1e-4,Lot=1-nAe,Dot=1+nAe,iAe=.01,Mot=0-iAe,Oot=0+iAe;function Rd(t){return t.max-t.min}function Fot(t,e,r){return Math.abs(t-e)<=r}function Tce(t,e,r,n=.5){t.origin=n,t.originPoint=co(e.min,e.max,t.origin),t.scale=Rd(r)/Rd(e),t.translate=co(r.min,r.max,t.origin)-t.originPoint,(t.scale>=Lot&&t.scale<=Dot||isNaN(t.scale))&&(t.scale=1),(t.translate>=Mot&&t.translate<=Oot||isNaN(t.translate))&&(t.translate=0)}function mj(t,e,r,n){Tce(t.x,e.x,r.x,n?n.originX:void 0),Tce(t.y,e.y,r.y,n?n.originY:void 0)}function Ace(t,e,r,n=0){const i=n?co(r.min,r.max,n):r.min;t.min=i+e.min,t.max=t.min+Rd(e)}function Bot(t,e,r,n){Ace(t.x,e.x,r.x,n==null?void 0:n.x),Ace(t.y,e.y,r.y,n==null?void 0:n.y)}function kce(t,e,r,n=0){const i=n?co(r.min,r.max,n):r.min;t.min=e.min-i,t.max=t.min+Rd(e)}function MF(t,e,r,n){kce(t.x,e.x,r.x,n==null?void 0:n.x),kce(t.y,e.y,r.y,n==null?void 0:n.y)}function Ice(t,e,r,n,i){return t-=e,t=DF(t,1/r,n),i!==void 0&&(t=DF(t,1/i,n)),t}function zot(t,e=0,r=1,n=.5,i,a=t,c=t){if(sg.test(e)&&(e=parseFloat(e),e=co(c.min,c.max,e/100)-c.min),typeof e!="number")return;let d=co(a.min,a.max,n);t===a&&(d-=e),t.min=Ice(t.min,e,r,d,i),t.max=Ice(t.max,e,r,d,i)}function jce(t,e,[r,n,i],a,c){zot(t,e[r],e[n],e[i],e.scale,a,c)}const $ot=["x","scaleX","originX"],Uot=["y","scaleY","originY"];function Cce(t,e,r,n){jce(t.x,e,$ot,r?r.x:void 0,n?n.x:void 0),jce(t.y,e,Uot,r?r.y:void 0,n?n.y:void 0)}function Pce(t){return t.translate===0&&t.scale===1}function sAe(t){return Pce(t.x)&&Pce(t.y)}function Nce(t,e){return t.min===e.min&&t.max===e.max}function Vot(t,e){return Nce(t.x,e.x)&&Nce(t.y,e.y)}function Rce(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function aAe(t,e){return Rce(t.x,e.x)&&Rce(t.y,e.y)}function Lce(t){return Rd(t.x)/Rd(t.y)}function Dce(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}function Fp(t){return[t("x"),t("y")]}function qot(t,e,r){let n="";const i=t.x.translate/e.x,a=t.y.translate/e.y,c=(r==null?void 0:r.z)||0;if((i||a||c)&&(n=`translate3d(${i}px, ${a}px, ${c}px) `),(e.x!==1||e.y!==1)&&(n+=`scale(${1/e.x}, ${1/e.y}) `),r){const{transformPerspective:l,rotate:g,pathRotation:v,rotateX:E,rotateY:T,skewX:j,skewY:P}=r;l&&(n=`perspective(${l}px) ${n}`),g&&(n+=`rotate(${g}deg) `),v&&(n+=`rotate(${v}deg) `),E&&(n+=`rotateX(${E}deg) `),T&&(n+=`rotateY(${T}deg) `),j&&(n+=`skewX(${j}deg) `),P&&(n+=`skewY(${P}deg) `)}const d=t.x.scale*e.x,p=t.y.scale*e.y;return(d!==1||p!==1)&&(n+=`scale(${d}, ${p})`),n||"none"}const Got=IZ.length,Mce=t=>typeof t=="string"?parseFloat(t):t,Oce=t=>typeof t=="number"||Qn.test(t);function Hot(t,e,r,n,i,a){i?(t.opacity=co(0,r.opacity??1,Wot(n)),t.opacityExit=co(e.opacity??1,0,Kot(n))):a&&(t.opacity=co(e.opacity??1,r.opacity??1,n));for(let c=0;cne?1:r(mC(t,e,n))}function Yot(t,e,r){const n=Bu(t)?t:xT(t);return n.start(TZ("",n,e,r)),n.animation}function yC(t,e,r,n={passive:!0}){return t.addEventListener(e,r,n),()=>t.removeEventListener(e,r,n)}const Zot=(t,e)=>t.depth-e.depth;class Xot{constructor(){this.children=[],this.isDirty=!1}add(e){fZ(this.children,e),this.isDirty=!0}remove(e){IF(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(Zot),this.isDirty=!1,this.children.forEach(e)}}function Qot(t,e){const r=Nd.now(),n=({timestamp:i})=>{const a=i-r;a>=e&&(jv(n),t(a-e))};return uo.setup(n,!0),()=>jv(n)}function uO(t){return Bu(t)?t.get():t}class Jot{constructor(){this.members=[]}add(e){fZ(this.members,e);for(let r=this.members.length-1;r>=0;r--){const n=this.members[r];if(n===e||n===this.lead||n===this.prevLead)continue;const i=n.instance;(!i||i.isConnected===!1)&&!n.snapshot&&(IF(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(IF(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const r=this.members[this.members.length-1];r&&this.promote(r)}}relegate(e){var r;for(let n=this.members.indexOf(e)-1;n>=0;n--){const i=this.members[n];if(i.isPresent!==!1&&((r=i.instance)==null?void 0:r.isConnected)!==!1)return this.promote(i),!0}return!1}promote(e,r){var i;const n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.updateSnapshot(),e.scheduleRender();const{layoutDependency:a}=n.options,{layoutDependency:c}=e.options;(a===void 0||a!==c)&&(e.resumeFrom=n,r&&(n.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),(i=e.root)!=null&&i.isUpdating&&(e.isLayoutDirty=!0)),e.options.crossfade===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{var r,n,i,a,c;(n=(r=e.options).onExitComplete)==null||n.call(r),(c=(i=e.resumingFrom)==null?void 0:(a=i.options).onExitComplete)==null||c.call(a)})}scheduleRender(){this.members.forEach(e=>e.instance&&e.scheduleRender(!1))}removeLeadSnapshot(){var e;(e=this.lead)!=null&&e.snapshot&&(this.lead.snapshot=void 0)}}const dO={hasAnimatedSinceResize:!0,hasEverUpdated:!1},KU=["","X","Y","Z"],elt=1e3;let tlt=0;function YU(t,e,r,n){const{latestValues:i}=e;i[t]&&(r[t]=i[t],e.setStaticValue(t,0),n&&(n[t]=0))}function lAe(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const r=CTe(e);if(window.MotionHasOptimisedAnimation(r,"transform")){const{layout:i,layoutId:a}=t.options;window.MotionCancelOptimisedAnimation(r,"transform",uo,!(i||a))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&lAe(n)}function cAe({attachResizeListener:t,defaultParent:e,measureScroll:r,checkIsScrollRoot:n,resetTransform:i}){return class{constructor(c={},d=e==null?void 0:e()){this.id=tlt++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(ilt),this.nodes.forEach(ult),this.nodes.forEach(dlt),this.nodes.forEach(slt)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=c,this.root=d?d.root||d:this,this.path=d?[...d.path,d]:[],this.parent=d,this.depth=d?d.depth+1:0;for(let p=0;pthis.root.updateBlockedByResize=!1;uo.read(()=>{v=window.innerWidth}),t(c,()=>{const T=window.innerWidth;T!==v&&(v=T,this.root.updateBlockedByResize=!0,g&&g(),g=Qot(E,250),dO.hasAnimatedSinceResize&&(dO.hasAnimatedSinceResize=!1,this.nodes.forEach($ce)))})}d&&this.root.registerSharedNode(d,this),this.options.animate!==!1&&l&&(d||p)&&this.addEventListener("didUpdate",({delta:g,hasLayoutChanged:v,hasRelativeLayoutChanged:E,layout:T})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const j=this.options.transition||l.getDefaultTransition()||glt,{onLayoutAnimationStart:P,onLayoutAnimationComplete:C}=l.getProps(),L=!this.targetLayout||!aAe(this.targetLayout,T),O=!v&&E;if(this.options.layoutRoot||this.resumeFrom||O||v&&(L||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const F={...EZ(j,"layout"),onPlay:P,onComplete:C};(l.shouldReduceMotion||this.options.layoutRoot)&&(F.delay=0,F.type=!1),this.startAnimation(F),this.setAnimationOrigin(g,O,F.path)}else v||$ce(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=T})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const c=this.getStack();c&&c.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),jv(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(hlt),this.animationId++)}getTransformTemplate(){const{visualElement:c}=this.options;return c&&c.getProps().transformTemplate}willUpdate(c=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&lAe(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let g=0;g{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Rd(this.snapshot.measuredBox.x)&&!Rd(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let p=0;p{const Z=W/1e3,Q=G==null?void 0:G(Z);Q?(E.x.translate=Q.x,E.x.scale=co(c.x.scale,1,Z),E.x.origin=c.x.origin,E.x.originPoint=c.x.originPoint,E.y.translate=Q.y,E.y.scale=co(c.y.scale,1,Z),E.y.origin=c.y.origin,E.y.originPoint=c.y.originPoint):(Uce(E.x,c.x,Z),Uce(E.y,c.y,Z)),this.setTargetDelta(E),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(MF(T,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),mlt(this.relativeTarget,this.relativeTargetOrigin,T,Z),$&&Vot(this.relativeTarget,$)&&(this.isProjectionDirty=!1),$||($=jc()),Tm($,this.relativeTarget)),C&&(this.animationValues=v,Hot(v,g,this.latestValues,Z,F,O)),Q&&Q.rotate!==void 0&&(this.animationValues||(this.animationValues=v),this.animationValues.pathRotation=Q.rotate),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=Z},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(c){var d,p,l;this.notifyListeners("animationStart"),(d=this.currentAnimation)==null||d.stop(),(l=(p=this.resumingFrom)==null?void 0:p.currentAnimation)==null||l.stop(),this.pendingAnimation&&(jv(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=uo.update(()=>{dO.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=xT(0)),this.motionValue.jump(0,!1),this.currentAnimation=Yot(this.motionValue,[0,1e3],{...c,velocity:0,isSync:!0,onUpdate:g=>{this.mixTargetDelta(g),c.onUpdate&&c.onUpdate(g)},onComplete:()=>{c.onComplete&&c.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const c=this.getStack();c&&c.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(elt),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const c=this.getLead();let{targetWithTransforms:d,target:p,layout:l,latestValues:g}=c;if(!(!d||!p||!l)){if(this!==c&&this.layout&&l&&uAe(this.options.animationType,this.layout.layoutBox,l.layoutBox)){p=this.target||jc();const v=Rd(this.layout.layoutBox.x);p.x.min=c.target.x.min,p.x.max=p.x.min+v;const E=Rd(this.layout.layoutBox.y);p.y.min=c.target.y.min,p.y.max=p.y.min+E}Tm(d,p),cO(d,g),mj(this.projectionDeltaWithTransform,this.layoutCorrected,d,g)}}registerSharedNode(c,d){this.sharedNodes.has(c)||this.sharedNodes.set(c,new Jot),this.sharedNodes.get(c).add(d);const l=d.options.initialPromotionConfig;d.promote({transition:l?l.transition:void 0,preserveFollowOpacity:l&&l.shouldPreserveFollowOpacity?l.shouldPreserveFollowOpacity(d):void 0})}isLead(){const c=this.getStack();return c?c.lead===this:!0}getLead(){var d;const{layoutId:c}=this.options;return c?((d=this.getStack())==null?void 0:d.lead)||this:this}getPrevLead(){var d;const{layoutId:c}=this.options;return c?(d=this.getStack())==null?void 0:d.prevLead:void 0}getStack(){const{layoutId:c}=this.options;if(c)return this.root.sharedNodes.get(c)}promote({needsReset:c,transition:d,preserveFollowOpacity:p}={}){const l=this.getStack();l&&l.promote(this,p),c&&(this.projectionDelta=void 0,this.needsReset=!0),d&&this.setOptions({transition:d})}relegate(){const c=this.getStack();return c?c.relegate(this):!1}resetSkewAndRotation(){const{visualElement:c}=this.options;if(!c)return;let d=!1;const{latestValues:p}=c;if((p.z||p.rotate||p.rotateX||p.rotateY||p.rotateZ||p.skewX||p.skewY)&&(d=!0),!d)return;const l={};p.z&&YU("z",c,l,this.animationValues);for(let g=0;g{var d;return(d=c.currentAnimation)==null?void 0:d.stop()}),this.root.nodes.forEach(Bce),this.root.sharedNodes.clear()}}}function rlt(t){t.updateLayout()}function nlt(t){var r;const e=((r=t.resumeFrom)==null?void 0:r.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:i}=t.layout,{animationType:a}=t.options,c=e.source!==t.layout.source;if(a==="size")Fp(v=>{const E=c?e.measuredBox[v]:e.layoutBox[v],T=Rd(E);E.min=n[v].min,E.max=E.min+T});else if(a==="x"||a==="y"){const v=a==="x"?"y":"x";P9(c?e.measuredBox[v]:e.layoutBox[v],n[v])}else uAe(a,e.layoutBox,n)&&Fp(v=>{const E=c?e.measuredBox[v]:e.layoutBox[v],T=Rd(n[v]);E.max=E.min+T,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[v].max=t.relativeTarget[v].min+T)});const d=oE();mj(d,n,e.layoutBox);const p=oE();c?mj(p,t.applyTransform(i,!0),e.measuredBox):mj(p,n,e.layoutBox);const l=!sAe(d);let g=!1;if(!t.resumeFrom){const v=t.getClosestProjectingParent();if(v&&!v.resumeFrom){const{snapshot:E,layout:T}=v;if(E&&T){const j=t.options.layoutAnchor||void 0,P=jc();MF(P,e.layoutBox,E.layoutBox,j);const C=jc();MF(C,n,T.layoutBox,j),aAe(P,C)||(g=!0),v.options.layoutRoot&&(t.relativeTarget=C,t.relativeTargetOrigin=P,t.relativeParent=v)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:p,layoutDelta:d,hasLayoutChanged:l,hasRelativeLayoutChanged:g})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function ilt(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function slt(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function alt(t){t.clearSnapshot()}function Bce(t){t.clearMeasurements()}function olt(t){t.isLayoutDirty=!0,t.updateLayout()}function zce(t){t.isLayoutDirty=!1}function llt(t){t.isAnimationBlocked&&t.layout&&!t.isLayoutDirty&&(t.snapshot=t.layout,t.isLayoutDirty=!0)}function clt(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function $ce(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function ult(t){t.resolveTargetDelta()}function dlt(t){t.calcProjection()}function hlt(t){t.resetSkewAndRotation()}function flt(t){t.removeLeadSnapshot()}function Uce(t,e,r){t.translate=co(e.translate,0,r),t.scale=co(e.scale,1,r),t.origin=e.origin,t.originPoint=e.originPoint}function Vce(t,e,r,n){t.min=co(e.min,r.min,n),t.max=co(e.max,r.max,n)}function mlt(t,e,r,n){Vce(t.x,e.x,r.x,n),Vce(t.y,e.y,r.y,n)}function plt(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const glt={duration:.45,ease:[.4,0,.1,1]},qce=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Gce=qce("applewebkit/")&&!qce("chrome/")?Math.round:Vf;function Hce(t){t.min=Gce(t.min),t.max=Gce(t.max)}function ylt(t){Hce(t.x),Hce(t.y)}function uAe(t,e,r){return t==="position"||t==="preserve-aspect"&&!Fot(Lce(e),Lce(r),.2)}function xlt(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const _lt=cAe({attachResizeListener:(t,e)=>yC(t,"resize",e),measureScroll:()=>{var t,e;return{x:document.documentElement.scrollLeft||((t=document.body)==null?void 0:t.scrollLeft)||0,y:document.documentElement.scrollTop||((e=document.body)==null?void 0:e.scrollTop)||0}},checkIsScrollRoot:()=>!0}),ZU={current:void 0},dAe=cAe({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!ZU.current){const t=new _lt({});t.mount(window),t.setOptions({layoutScroll:!0}),ZU.current=t}return ZU.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),MZ=N.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function Wce(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function vlt(...t){return e=>{let r=!1;const n=t.map(i=>{const a=Wce(i,e);return!r&&typeof a=="function"&&(r=!0),a});if(r)return()=>{for(let i=0;i{const{width:T,height:j,top:P,left:C,right:L,bottom:O,direction:F}=p.current;if(e||a===!1||!d.current||!T||!j)return;const $=F==="rtl",G=r==="left"?$?`right: ${L}`:`left: ${C}`:$?`left: ${C}`:`right: ${L}`,W=n==="bottom"?`bottom: ${O}`:`top: ${P}`;d.current.dataset.motionPopId=c;const Z=document.createElement("style");l&&(Z.nonce=l);const Q=i??document.head;return Q.appendChild(Z),Z.sheet&&Z.sheet.insertRule(` [data-motion-pop-id="${c}"] { position: absolute !important; width: ${T}px !important; height: ${j}px !important; ${G}px !important; ${W}px !important; } `),()=>{var ee;(ee=d.current)==null||ee.removeAttribute("data-motion-pop-id"),Q.contains(Z)&&Q.removeChild(Z)}},[e]),s.jsx(wlt,{isPresent:e,childRef:d,sizeRef:p,pop:a,children:a===!1?t:N.cloneElement(t,{ref:v})})}const Elt=({children:t,initial:e,isPresent:r,onExitComplete:n,custom:i,presenceAffectsLayout:a,mode:c,anchorX:d,anchorY:p,root:l})=>{const g=dZ(Tlt),v=N.useId(),E=N.useRef(r),T=N.useRef(n);hZ(()=>{E.current=r,T.current=n});let j=!0,P=N.useMemo(()=>(j=!1,{id:v,initial:e,isPresent:r,custom:i,onExitComplete:C=>{g.set(C,!0);for(const L of g.values())if(!L)return;n&&n()},register:C=>(g.set(C,!1),()=>{var L;g.delete(C),!E.current&&!g.size&&((L=T.current)==null||L.call(T))})}),[r,g,n]);return a&&j&&(P={...P}),N.useMemo(()=>{g.forEach((C,L)=>g.set(L,!1))},[r]),N.useEffect(()=>{!r&&!g.size&&n&&n()},[r]),t=s.jsx(Slt,{pop:c==="popLayout",isPresent:r,anchorX:d,anchorY:p,root:l,children:t}),s.jsx(L5.Provider,{value:P,children:t})};function Tlt(){return new Map}function hAe(t=!0){const e=N.useContext(L5);if(e===null)return[!0,null];const{isPresent:r,onExitComplete:n,register:i}=e,a=N.useId();N.useEffect(()=>{if(t)return i(a)},[t]);const c=N.useCallback(()=>t&&n&&n(a),[a,n,t]);return!r&&n?[!1,c]:[!0]}const MD=t=>t.key||"";function Kce(t){const e=[];return N.Children.forEach(t,r=>{N.isValidElement(r)&&e.push(r)}),e}const fAe=({children:t,custom:e,initial:r=!0,onExitComplete:n,presenceAffectsLayout:i=!0,mode:a="sync",propagate:c=!1,anchorX:d="left",anchorY:p="top",root:l})=>{const[g,v]=hAe(c),E=N.useMemo(()=>Kce(t),[t]),T=c&&!g?[]:E.map(MD),j=N.useRef(!0),P=N.useRef(E),C=dZ(()=>new Map),L=N.useRef(new Set),[O,F]=N.useState(E),[$,G]=N.useState(E);hZ(()=>{j.current=!1,P.current=E;for(let Q=0;Q<$.length;Q++){const ee=MD($[Q]);T.includes(ee)?(C.delete(ee),L.current.delete(ee)):C.get(ee)!==!0&&C.set(ee,!1)}},[$,T.length,T.join("-")]);const W=[];if(E!==O){let Q=[...E];for(let ee=0;ee<$.length;ee++){const ie=$[ee],oe=MD(ie);T.includes(oe)||(Q.splice(ee,0,ie),W.push(ie))}return a==="wait"&&W.length&&(Q=W),G(Kce(Q)),F(E),null}const{forceRender:Z}=N.useContext(uZ);return s.jsx(s.Fragment,{children:$.map(Q=>{const ee=MD(Q),ie=c&&!g?!1:E===$||T.includes(ee),oe=()=>{if(L.current.has(ee))return;if(C.has(ee))L.current.add(ee),C.set(ee,!0);else return;let pe=!0;C.forEach(Le=>{Le||(pe=!1)}),pe&&(Z==null||Z(),G(P.current),c&&(v==null||v()),n&&n())};return s.jsx(Elt,{isPresent:ie,initial:!j.current||r?void 0:!1,custom:e,presenceAffectsLayout:i,mode:a,root:l,onExitComplete:ie?void 0:oe,anchorX:d,anchorY:p,children:Q},ee)})})},mAe=N.createContext({strict:!1}),Yce={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let Zce=!1;function Alt(){if(Zce)return;const t={};for(const e in Yce)t[e]={isEnabled:r=>Yce[e].some(n=>!!r[n])};VTe(t),Zce=!0}function pAe(){return Alt(),uot()}function klt(t){const e=pAe();for(const r in t)e[r]={...e[r],...t[r]};VTe(e)}const Ilt=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","propagate","ignoreStrict","viewport"]);function OF(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Ilt.has(t)}let gAe=t=>!OF(t);function jlt(t){typeof t=="function"&&(gAe=e=>e.startsWith("on")?!OF(e):t(e))}try{jlt(require("@emotion/is-prop-valid").default)}catch{}function Clt(t,e,r){const n={};for(const i in t)i==="values"&&typeof t.values=="object"||Bu(t[i])||(gAe(i)||r===!0&&OF(i)||!e&&!OF(i)||t.draggable&&i.startsWith("onDrag"))&&(n[i]=t[i]);return n}const B5=N.createContext({});function Plt(t,e){if(F5(t)){const{initial:r,animate:n}=t;return{initial:r===!1||gC(r)?r:void 0,animate:gC(n)?n:void 0}}return t.inherit!==!1?e:{}}function Nlt(t){const{initial:e,animate:r}=Plt(t,N.useContext(B5));return N.useMemo(()=>({initial:e,animate:r}),[Xce(e),Xce(r)])}function Xce(t){return Array.isArray(t)?t.join(" "):t}const OZ=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function yAe(t,e,r){for(const n in e)!Bu(e[n])&&!ZTe(n,r)&&(t[n]=e[n])}function Rlt({transformTemplate:t},e){return N.useMemo(()=>{const r=OZ();return LZ(r,e,t),Object.assign({},r.vars,r.style)},[e])}function Llt(t,e){const r=t.style||{},n={};return yAe(n,r,t),Object.assign(n,Rlt(t,e)),n}function Dlt(t,e){const r={},n=Llt(t,e);return t.drag&&t.dragListener!==!1&&(r.draggable=!1,n.userSelect=n.WebkitUserSelect=n.WebkitTouchCallout="none",n.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(r.tabIndex=0),r.style=n,r}const xAe=()=>({...OZ(),attrs:{}});function Mlt(t,e,r,n){const i=N.useMemo(()=>{const a=xAe();return XTe(a,e,JTe(n),t.transformTemplate,t.style),{...a.attrs,style:{...a.style}}},[e]);if(t.style){const a={};yAe(a,t.style,t),i.style={...a,...i.style}}return i}const Olt=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function FZ(t){return typeof t!="string"||t.includes("-")?!1:!!(Olt.indexOf(t)>-1||/[A-Z]/u.test(t))}function Flt(t,e,r,{latestValues:n},i,a=!1,c){const p=(c??FZ(t)?Mlt:Dlt)(e,n,i,t),l=Clt(e,typeof t=="string",a),g=t!==N.Fragment?{...l,...p,ref:r}:{},{children:v}=e,E=N.useMemo(()=>Bu(v)?v.get():v,[v]);return N.createElement(t,{...g,children:E})}function Blt({scrapeMotionValuesFromProps:t,createRenderState:e},r,n,i){return{latestValues:zlt(r,n,i,t),renderState:e()}}function zlt(t,e,r,n){const i={},a=n(t,{});for(const E in a)i[E]=uO(a[E]);let{initial:c,animate:d}=t;const p=F5(t),l=$Te(t);e&&l&&!p&&t.inherit!==!1&&(c===void 0&&(c=e.initial),d===void 0&&(d=e.animate));let g=r?r.initial===!1:!1;g=g||c===!1;const v=g?d:c;if(v&&typeof v!="boolean"&&!O5(v)){const E=Array.isArray(v)?v:[v];for(let T=0;T(e,r)=>{const n=N.useContext(B5),i=N.useContext(L5),a=()=>Blt(t,e,n,i);return r?a():dZ(a)},$lt=_Ae({scrapeMotionValuesFromProps:DZ,createRenderState:OZ}),Ult=_Ae({scrapeMotionValuesFromProps:eAe,createRenderState:xAe}),Vlt=Symbol.for("motionComponentSymbol");function qlt(t,e,r){const n=N.useRef(r);N.useInsertionEffect(()=>{n.current=r});const i=N.useRef(null);return N.useCallback(a=>{var d;a&&((d=t.onMount)==null||d.call(t,a)),e&&(a?e.mount(a):e.unmount());const c=n.current;if(typeof c=="function")if(a){const p=c(a);typeof p=="function"&&(i.current=p)}else i.current?(i.current(),i.current=null):c(a);else c&&(c.current=a)},[e])}const vAe=N.createContext({});function US(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Glt(t,e,r,n,i,a){var F,$;const{visualElement:c}=N.useContext(B5),d=N.useContext(mAe),p=N.useContext(L5),l=N.useContext(MZ),g=l.reducedMotion,v=l.skipAnimations,E=N.useRef(null),T=N.useRef(!1);n=n||d.renderer,!E.current&&n&&(E.current=n(t,{visualState:e,parent:c,props:r,presenceContext:p,blockInitialAnimation:p?p.initial===!1:!1,reducedMotionConfig:g,skipAnimations:v,isSVG:a}),T.current&&E.current&&(E.current.manuallyAnimateOnMount=!0));const j=E.current,P=N.useContext(vAe);j&&!j.projection&&i&&(j.type==="html"||j.type==="svg")&&Hlt(E.current,r,i,P);const C=N.useRef(!1);N.useInsertionEffect(()=>{j&&C.current&&j.update(r,p)});const L=r[jTe],O=N.useRef(!!L&&typeof window<"u"&&!((F=window.MotionHandoffIsComplete)!=null&&F.call(window,L))&&(($=window.MotionHasOptimisedAnimation)==null?void 0:$.call(window,L)));return hZ(()=>{T.current=!0,j&&(C.current=!0,window.MotionIsMounted=!0,j.updateFeatures(),j.scheduleRenderMicrotask(),O.current&&j.animationState&&j.animationState.animateChanges())}),N.useEffect(()=>{j&&(!O.current&&j.animationState&&j.animationState.animateChanges(),O.current&&(queueMicrotask(()=>{var G;(G=window.MotionHandoffMarkAsComplete)==null||G.call(window,L)}),O.current=!1),j.enteringChildren=void 0)}),j}function Hlt(t,e,r,n){const{layoutId:i,layout:a,drag:c,dragConstraints:d,layoutScroll:p,layoutRoot:l,layoutAnchor:g,layoutCrossfade:v}=e;t.projection=new r(t.latestValues,e["data-framer-portal-id"]?void 0:bAe(t.parent)),t.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!c||d&&US(d),visualElement:t,animationType:typeof a=="string"?a:"both",initialPromotionConfig:n,crossfade:v,layoutScroll:p,layoutRoot:l,layoutAnchor:g})}function bAe(t){if(t)return t.options.allowProjection!==!1?t.projection:bAe(t.parent)}function XU(t,{forwardMotionProps:e=!1,type:r}={},n,i){n&&klt(n);const a=r?r==="svg":FZ(t),c=a?Ult:$lt;function d(l,g){let v;const E={...N.useContext(MZ),...l,layoutId:Wlt(l)},{isStatic:T}=E,j=Nlt(l),P=c(l,T);if(!T&&typeof window<"u"){Klt();const C=Ylt(E);v=C.MeasureLayout,j.visualElement=Glt(t,P,E,i,C.ProjectionNode,a)}return s.jsxs(B5.Provider,{value:j,children:[v&&j.visualElement?s.jsx(v,{visualElement:j.visualElement,...E}):null,Flt(t,l,qlt(P,j.visualElement,g),P,T,e,a)]})}d.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const p=N.forwardRef(d);return p[Vlt]=t,p}function Wlt({layoutId:t}){const e=N.useContext(uZ).id;return e&&t!==void 0?e+"-"+t:t}function Klt(t,e){N.useContext(mAe).strict}function Ylt(t){const e=pAe(),{drag:r,layout:n}=e;if(!r&&!n)return{};const i={...r,...n};return{MeasureLayout:r!=null&&r.isEnabled(t)||n!=null&&n.isEnabled(t)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}function Zlt(t,e){if(typeof Proxy>"u")return XU;const r=new Map,n=(a,c)=>XU(a,c,t,e),i=(a,c)=>n(a,c);return new Proxy(i,{get:(a,c)=>c==="create"?n:(r.has(c)||r.set(c,XU(c,void 0,t,e)),r.get(c))})}const Xlt=(t,e)=>e.isSVG??FZ(t)?new kot(e):new bot(e,{allowProjection:t!==N.Fragment});class Qlt extends Kv{constructor(e){super(e),e.animationState||(e.animationState=Not(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();O5(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:r}=this.node.prevProps||{};e!==r&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let Jlt=0;class ect extends Kv{constructor(){super(...arguments),this.id=Jlt++,this.isExitComplete=!1}update(){var a;if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:r}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;if(e&&n===!1){if(this.isExitComplete){const{initial:c,custom:d}=this.node.getProps();if(typeof c=="string"||typeof c=="object"&&c!==null&&!Array.isArray(c)){const p=Yb(this.node,c,d);if(p){const{transition:l,transitionEnd:g,...v}=p;for(const E in v)(a=this.node.getValue(E))==null||a.jump(v[E])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const i=this.node.animationState.setActive("exit",!e);r&&!e&&i.then(()=>{this.isExitComplete=!0,r(this.id)})}mount(){const{register:e,onExitComplete:r}=this.node.presenceContext||{};r&&r(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const tct={animation:{Feature:Qlt},exit:{Feature:ect}};function nN(t){return{point:{x:t.pageX,y:t.pageY}}}const rct=t=>e=>CZ(e)&&t(e,nN(e));function pj(t,e,r,n){return yC(t,e,rct(r),n)}const wAe=({current:t})=>t?t.ownerDocument.defaultView:null,Qce=(t,e)=>Math.abs(t-e);function nct(t,e){const r=Qce(t.x,e.x),n=Qce(t.y,e.y);return Math.sqrt(r**2+n**2)}const Jce=new Set(["auto","scroll"]);class SAe{constructor(e,r,{transformPagePoint:n,contextWindow:i=window,dragSnapToOrigin:a=!1,distanceThreshold:c=3,element:d}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=j=>{this.handleScroll(j.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=OD(this.lastRawMoveEventInfo,this.transformPagePoint));const j=QU(this.lastMoveEventInfo,this.history),P=this.startEvent!==null,C=nct(j.offset,{x:0,y:0})>=this.distanceThreshold;if(!P&&!C)return;const{point:L}=j,{timestamp:O}=ku;this.history.push({...L,timestamp:O});const{onStart:F,onMove:$}=this.handlers;P||(F&&F(this.lastMoveEvent,j),this.startEvent=this.lastMoveEvent),$&&$(this.lastMoveEvent,j)},this.handlePointerMove=(j,P)=>{this.lastMoveEvent=j,this.lastRawMoveEventInfo=P,this.lastMoveEventInfo=OD(P,this.transformPagePoint),uo.update(this.updatePoint,!0)},this.handlePointerUp=(j,P)=>{this.end();const{onEnd:C,onSessionEnd:L,resumeAnimation:O}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&O&&O(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const F=QU(j.type==="pointercancel"?this.lastMoveEventInfo:OD(P,this.transformPagePoint),this.history);this.startEvent&&C&&C(j,F),L&&L(j,F)},!CZ(e))return;this.dragSnapToOrigin=a,this.handlers=r,this.transformPagePoint=n,this.distanceThreshold=c,this.contextWindow=i||window;const p=nN(e),l=OD(p,this.transformPagePoint),{point:g}=l,{timestamp:v}=ku;this.history=[{...g,timestamp:v}];const{onSessionStart:E}=r;E&&E(e,QU(l,this.history));const T={passive:!0,capture:!0};this.removeListeners=eN(pj(this.contextWindow,"pointermove",this.handlePointerMove,T),pj(this.contextWindow,"pointerup",this.handlePointerUp,T),pj(this.contextWindow,"pointercancel",this.handlePointerUp,T)),d&&this.startScrollTracking(d)}startScrollTracking(e){let r=e.parentElement;for(;r;){const n=getComputedStyle(r);(Jce.has(n.overflowX)||Jce.has(n.overflowY))&&this.scrollPositions.set(r,{x:r.scrollLeft,y:r.scrollTop}),r=r.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(e){const r=this.scrollPositions.get(e);if(!r)return;const n=e===window,i=n?{x:window.scrollX,y:window.scrollY}:{x:e.scrollLeft,y:e.scrollTop},a={x:i.x-r.x,y:i.y-r.y};a.x===0&&a.y===0||(n?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=a.x,this.lastMoveEventInfo.point.y+=a.y):this.history.length>0&&(this.history[0].x-=a.x,this.history[0].y-=a.y),this.scrollPositions.set(e,i),uo.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),jv(this.updatePoint)}}function OD(t,e){return e?{point:e(t.point)}:t}function eue(t,e){return{x:t.x-e.x,y:t.y-e.y}}function QU({point:t},e){return{point:t,delta:eue(t,EAe(e)),offset:eue(t,ict(e)),velocity:sct(e,.1)}}function ict(t){return t[0]}function EAe(t){return t[t.length-1]}function sct(t,e){if(t.length<2)return{x:0,y:0};let r=t.length-1,n=null;const i=EAe(t);for(;r>=0&&(n=t[r],!(i.timestamp-n.timestamp>Zh(e)));)r--;if(!n)return{x:0,y:0};n===t[0]&&t.length>2&&i.timestamp-n.timestamp>Zh(e)*2&&(n=t[1]);const a=Bf(i.timestamp-n.timestamp);if(a===0)return{x:0,y:0};const c={x:(i.x-n.x)/a,y:(i.y-n.y)/a};return c.x===1/0&&(c.x=0),c.y===1/0&&(c.y=0),c}function act(t,{min:e,max:r},n){return e!==void 0&&tr&&(t=n?co(r,t,n.max):Math.min(t,r)),t}function tue(t,e,r){return{min:e!==void 0?t.min+e:void 0,max:r!==void 0?t.max+r-(t.max-t.min):void 0}}function oct(t,{top:e,left:r,bottom:n,right:i}){return{x:tue(t.x,r,i),y:tue(t.y,e,n)}}function rue(t,e){let r=e.min-t.min,n=e.max-t.max;return e.max-e.minn?r=mC(e.min,e.max-n,t.min):n>i&&(r=mC(t.min,t.max-i,e.min)),yg(0,1,r)}function uct(t,e){const r={};return e.min!==void 0&&(r.min=e.min-t.min),e.max!==void 0&&(r.max=e.max-t.min),r}const N9=.35;function dct(t=N9){return t===!1?t=0:t===!0&&(t=N9),{x:nue(t,"left","right"),y:nue(t,"top","bottom")}}function nue(t,e,r){return{min:iue(t,e),max:iue(t,r)}}function iue(t,e){return typeof t=="number"?t:t[e]||0}const hct=new WeakMap;class fct{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=jc(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:r=!1,distanceThreshold:n}={}){const{presenceContext:i}=this.visualElement;if(i&&i.isPresent===!1)return;const a=v=>{r&&this.snapToCursor(nN(v).point),this.stopAnimation()},c=(v,E)=>{const{drag:T,dragPropagation:j,onDragStart:P}=this.getProps();if(T&&!j&&(this.openDragLock&&this.openDragLock(),this.openDragLock=zat(T),!this.openDragLock))return;this.latestPointerEvent=v,this.latestPanInfo=E,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Fp(L=>{let O=this.getAxisMotionValue(L).get()||0;if(sg.test(O)){const{projection:F}=this.visualElement;if(F&&F.layout){const $=F.layout.layoutBox[L];$&&(O=Rd($)*(parseFloat(O)/100))}}this.originPoint[L]=O}),P&&uo.update(()=>P(v,E),!1,!0),w9(this.visualElement,"transform");const{animationState:C}=this.visualElement;C&&C.setActive("whileDrag",!0)},d=(v,E)=>{this.latestPointerEvent=v,this.latestPanInfo=E;const{dragPropagation:T,dragDirectionLock:j,onDirectionLock:P,onDrag:C}=this.getProps();if(!T&&!this.openDragLock)return;const{offset:L}=E;if(j&&this.currentDirection===null){this.currentDirection=pct(L),this.currentDirection!==null&&P&&P(this.currentDirection);return}this.updateAxis("x",E.point,L),this.updateAxis("y",E.point,L),this.visualElement.render(),C&&uo.update(()=>C(v,E),!1,!0)},p=(v,E)=>{this.latestPointerEvent=v,this.latestPanInfo=E,this.stop(v,E),this.latestPointerEvent=null,this.latestPanInfo=null},l=()=>{const{dragSnapToOrigin:v}=this.getProps();(v||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:g}=this.getProps();this.panSession=new SAe(e,{onSessionStart:a,onStart:c,onMove:d,onSessionEnd:p,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:g,distanceThreshold:n,contextWindow:wAe(this.visualElement),element:this.visualElement.current})}stop(e,r){const n=e||this.latestPointerEvent,i=r||this.latestPanInfo,a=this.isDragging;if(this.cancel(),!a||!i||!n)return;const{velocity:c}=i;this.startAnimation(c);const{onDragEnd:d}=this.getProps();d&&uo.postRender(()=>d(n,i))}cancel(){this.isDragging=!1;const{projection:e,animationState:r}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),r&&r.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(e,r,n){const{drag:i}=this.getProps();if(!n||!FD(e,i,this.currentDirection))return;const a=this.getAxisMotionValue(e);let c=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(c=act(c,this.constraints[e],this.elastic[e])),a.set(c)}resolveConstraints(){var a;const{dragConstraints:e,dragElastic:r}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(a=this.visualElement.projection)==null?void 0:a.layout,i=this.constraints;e&&US(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=oct(n.layoutBox,e):this.constraints=!1,this.elastic=dct(r),i!==this.constraints&&!US(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&Fp(c=>{this.constraints!==!1&&this.getAxisMotionValue(c)&&(this.constraints[c]=uct(n.layoutBox[c],this.constraints[c]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:r}=this.getProps();if(!e||!US(e))return!1;const n=e.current,{projection:i}=this.visualElement;if(!i||!i.layout)return!1;i.root&&(i.root.scroll=void 0,i.root.updateScroll());const a=pot(n,i.root,this.visualElement.getTransformPagePoint());let c=lct(i.layout.layoutBox,a);if(r){const d=r(hot(c));this.hasMutatedConstraints=!!d,d&&(c=GTe(d))}return c}startAnimation(e){const{drag:r,dragMomentum:n,dragElastic:i,dragTransition:a,dragSnapToOrigin:c,onDragTransitionEnd:d}=this.getProps(),p=this.constraints||{},l=Fp(g=>{if(!FD(g,r,this.currentDirection))return;let v=p&&p[g]||{};(c===!0||c===g)&&(v={min:0,max:0});const E=i?200:1e6,T=i?40:1e7,j={type:"inertia",velocity:n?e[g]:0,bounceStiffness:E,bounceDamping:T,timeConstant:750,restDelta:1,restSpeed:10,...a,...v};return this.startAxisValueAnimation(g,j)});return Promise.all(l).then(d)}startAxisValueAnimation(e,r){const n=this.getAxisMotionValue(e);return w9(this.visualElement,e),n.start(TZ(e,n,0,r,this.visualElement,!1))}stopAnimation(){Fp(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){const r=`_drag${e.toUpperCase()}`,i=this.visualElement.getProps()[r];return i||this.visualElement.getValue(e,this.visualElement.latestValues[e]??0)}snapToCursor(e){Fp(r=>{const{drag:n}=this.getProps();if(!FD(r,n,this.currentDirection))return;const{projection:i}=this.visualElement,a=this.getAxisMotionValue(r);if(i&&i.layout){const{min:c,max:d}=i.layout.layoutBox[r],p=a.get()||0;a.set(e[r]-co(c,d,.5)+p)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:r}=this.getProps(),{projection:n}=this.visualElement;if(!US(r)||!n||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};Fp(c=>{const d=this.getAxisMotionValue(c);if(d&&this.constraints!==!1){const p=d.get();i[c]=cct({min:p,max:p},this.constraints[c])}});const{transformTemplate:a}=this.visualElement.getProps();this.visualElement.current.style.transform=a?a({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.constraints=!1,this.resolveConstraints(),Fp(c=>{if(!FD(c,e,null))return;const d=this.getAxisMotionValue(c),{min:p,max:l}=this.constraints[c];d.set(co(p,l,i[c]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;hct.set(this.visualElement,this);const e=this.visualElement.current,r=pj(e,"pointerdown",l=>{const{drag:g,dragListener:v=!0}=this.getProps(),E=l.target,T=E!==e&&Hat(E);g&&v&&!T&&this.start(l)});let n;const i=()=>{const{dragConstraints:l}=this.getProps();US(l)&&l.current&&(this.constraints=this.resolveRefConstraints(),n||(n=mct(e,l.current,()=>this.scalePositionWithinConstraints())))},{projection:a}=this.visualElement,c=a.addEventListener("measure",i);a&&!a.layout&&(a.root&&a.root.updateScroll(),a.updateLayout()),uo.read(i);const d=yC(window,"resize",()=>this.scalePositionWithinConstraints()),p=a.addEventListener("didUpdate",({delta:l,hasLayoutChanged:g})=>{this.isDragging&&g&&(Fp(v=>{const E=this.getAxisMotionValue(v);E&&(this.originPoint[v]+=l[v].translate,E.set(E.get()+l[v].translate))}),this.visualElement.render())});return()=>{d(),r(),c(),p&&p(),n&&n()}}getProps(){const e=this.visualElement.getProps(),{drag:r=!1,dragDirectionLock:n=!1,dragPropagation:i=!1,dragConstraints:a=!1,dragElastic:c=N9,dragMomentum:d=!0}=e;return{...e,drag:r,dragDirectionLock:n,dragPropagation:i,dragConstraints:a,dragElastic:c,dragMomentum:d}}}function sue(t){let e=!0;return()=>{if(e){e=!1;return}t()}}function mct(t,e,r){const n=hce(t,sue(r)),i=hce(e,sue(r));return()=>{n(),i()}}function FD(t,e,r){return(e===!0||e===t)&&(r===null||r===t)}function pct(t,e=10){let r=null;return Math.abs(t.y)>e?r="y":Math.abs(t.x)>e&&(r="x"),r}class gct extends Kv{constructor(e){super(e),this.removeGroupControls=Vf,this.removeListeners=Vf,this.controls=new fct(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Vf}update(){const{dragControls:e}=this.node.getProps(),{dragControls:r}=this.node.prevProps||{};e!==r&&(this.removeGroupControls(),e&&(this.removeGroupControls=e.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const JU=t=>(e,r)=>{t&&uo.update(()=>t(e,r),!1,!0)};class yct extends Kv{constructor(){super(...arguments),this.removePointerDownListener=Vf}onPointerDown(e){this.session=new SAe(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:wAe(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:r,onPan:n,onPanEnd:i}=this.node.getProps();return{onSessionStart:JU(e),onStart:JU(r),onMove:JU(n),onEnd:(a,c)=>{delete this.session,i&&uo.postRender(()=>i(a,c))}}}mount(){this.removePointerDownListener=pj(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let eV=!1;class xct extends N.Component{componentDidMount(){const{visualElement:e,layoutGroup:r,switchLayoutGroup:n,layoutId:i}=this.props,{projection:a}=e;a&&(r.group&&r.group.add(a),n&&n.register&&i&&n.register(a),eV&&a.root.didUpdate(),a.addEventListener("animationComplete",()=>{this.safeToRemove()}),a.setOptions({...a.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),dO.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:r,visualElement:n,drag:i,isPresent:a}=this.props,{projection:c}=n;return c&&(c.isPresent=a,e.layoutDependency!==r&&c.setOptions({...c.options,layoutDependency:r}),eV=!0,i||e.layoutDependency!==r||r===void 0||e.isPresent!==a?c.willUpdate():this.safeToRemove(),e.isPresent!==a&&(a?c.promote():c.relegate()||uo.postRender(()=>{const d=c.getStack();(!d||!d.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:e,layoutAnchor:r}=this.props,{projection:n}=e;n&&(n.options.layoutAnchor=r,n.root.didUpdate(),jZ.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:r,switchLayoutGroup:n}=this.props,{projection:i}=e;eV=!0,i&&(i.scheduleCheckAfterUnmount(),r&&r.group&&r.group.remove(i),n&&n.deregister&&n.deregister(i))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function TAe(t){const[e,r]=hAe(),n=N.useContext(uZ);return s.jsx(xct,{...t,layoutGroup:n,switchLayoutGroup:N.useContext(vAe),isPresent:e,safeToRemove:r})}const _ct={pan:{Feature:yct},drag:{Feature:gct,ProjectionNode:dAe,MeasureLayout:TAe}};function aue(t,e,r){const{props:n}=t;t.animationState&&n.whileHover&&t.animationState.setActive("whileHover",r==="Start");const i="onHover"+r,a=n[i];a&&uo.postRender(()=>a(e,nN(e)))}class vct extends Kv{mount(){const{current:e}=this.node;e&&(this.unmount=Uat(e,(r,n)=>(aue(this.node,n,"Start"),i=>aue(this.node,i,"End"))))}unmount(){}}class bct extends Kv{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=eN(yC(this.node.current,"focus",()=>this.onFocus()),yC(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function oue(t,e,r){const{props:n}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&n.whileTap&&t.animationState.setActive("whileTap",r==="Start");const i="onTap"+(r==="End"?"":r),a=n[i];a&&uo.postRender(()=>a(e,nN(e)))}class wct extends Kv{mount(){const{current:e}=this.node;if(!e)return;const{globalTapTarget:r,propagate:n}=this.node.props;this.unmount=Kat(e,(i,a)=>(oue(this.node,a,"Start"),(c,{success:d})=>oue(this.node,c,d?"End":"Cancel")),{useGlobalTarget:r,stopPropagation:(n==null?void 0:n.tap)===!1})}unmount(){}}const R9=new WeakMap,tV=new WeakMap,Sct=t=>{const e=R9.get(t.target);e&&e(t)},Ect=t=>{t.forEach(Sct)};function Tct({root:t,...e}){const r=t||document;tV.has(r)||tV.set(r,{});const n=tV.get(r),i=JSON.stringify(e);return n[i]||(n[i]=new IntersectionObserver(Ect,{root:t,...e})),n[i]}function Act(t,e,r){const n=Tct(e);return R9.set(t,r),n.observe(t),()=>{R9.delete(t),n.unobserve(t)}}const kct={some:0,all:1};class Ict extends Kv{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){var p;(p=this.stopObserver)==null||p.call(this);const{viewport:e={}}=this.node.getProps(),{root:r,margin:n,amount:i="some",once:a}=e,c={root:r?r.current:void 0,rootMargin:n,threshold:typeof i=="number"?i:kct[i]},d=l=>{const{isIntersecting:g}=l;if(this.isInView===g||(this.isInView=g,a&&!g&&this.hasEnteredView))return;g&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",g);const{onViewportEnter:v,onViewportLeave:E}=this.node.getProps(),T=g?v:E;T&&T(l)};this.stopObserver=Act(this.node.current,c,d)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:r}=this.node;["amount","margin","root"].some(jct(e,r))&&this.startObserver()}unmount(){var e;(e=this.stopObserver)==null||e.call(this),this.hasEnteredView=!1,this.isInView=!1}}function jct({viewport:t={}},{viewport:e={}}={}){return r=>t[r]!==e[r]}const Cct={inView:{Feature:Ict},tap:{Feature:wct},focus:{Feature:bct},hover:{Feature:vct}},Pct={layout:{ProjectionNode:dAe,MeasureLayout:TAe}},Nct={...tct,...Cct,..._ct,...Pct},Sr=Zlt(Nct,Xlt);function Rct(t){switch(t){case"buying":return{label:"Buying",emoji:"🏠",color:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30"};case"selling":return{label:"Selling",emoji:"📋",color:"bg-blue-500/15 text-blue-400 border-blue-500/30"};case"neighbor":return{label:"Neighbor",emoji:"👋",color:"bg-amber-500/15 text-amber-400 border-amber-500/30"};case"browsing":return{label:"Browsing",emoji:"👀",color:"bg-slate-500/15 text-slate-300 border-slate-500/30"};default:return{label:"Visitor",emoji:"🙂",color:"bg-slate-500/15 text-slate-300 border-slate-500/30"}}}function lue(t){return t.visitor_intent==="buying"&&!t.has_agent}function Lct({token:t}={}){var T;const e=Sg(),r=t||e.token,{data:n,isLoading:i,isError:a}=Dit(r);Ur();const c=(T=n==null?void 0:n.open_houses)==null?void 0:T.id,{data:d}=jr({queryKey:["cohost-visitors",r,c],queryFn:async()=>{const{data:j,error:P}=await Be.rpc("get_cohost_visitors",{_token:r});if(P)throw P;return j||[]},enabled:!!r&&!!c,refetchInterval:15e3});if(i)return s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center",children:s.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(a||!n)return s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center text-white",children:[s.jsx("h1",{className:"text-xl font-bold mb-2",children:"Link Expired or Invalid"}),s.jsx("p",{className:"text-white/40 text-sm",children:"This co-host link is no longer active. Ask the host for a new one."})]})});const p=n.open_houses,l=(d==null?void 0:d.length)||0,g=(d==null?void 0:d.filter(j=>j.visitor_intent==="buying").length)||0,v=(d==null?void 0:d.filter(lue).length)||0,E=j=>{if(!j)return"";const[P,C]=j.split(":"),L=parseInt(P);return`${L>12?L-12:L||12}:${C} ${L>=12?"PM":"AM"}`};return s.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[s.jsxs("div",{className:"border-b border-white/10 px-4 sm:px-6 py-3 flex items-center justify-between bg-black/30 backdrop-blur-xl",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),s.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),s.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:p.property_address})]}),s.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Dc,{className:"h-4 w-4"}),s.jsx("span",{className:"font-bold text-white",children:l})]}),s.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[s.jsx(sve,{className:"h-4 w-4"}),s.jsx("span",{className:"font-bold text-white",children:v})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Do,{className:"h-4 w-4"}),s.jsx("span",{className:"font-bold text-white",children:g})]})]})]}),s.jsxs("div",{className:"px-4 sm:px-6 py-2 flex items-center gap-4 text-xs text-white/40 border-b border-white/5",children:[s.jsx("span",{children:ds(new Date(p.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),p.start_time&&s.jsxs("span",{children:[E(p.start_time),p.end_time?` – ${E(p.end_time)}`:""]})]}),s.jsx(Eg,{className:"flex-1 p-4 sm:p-6",children:d!=null&&d.length?s.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:s.jsx(fAe,{children:d.map((j,P)=>{var O;const C=Rct(j.visitor_intent),L=lue(j);return s.jsxs(Sr.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:P*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${L?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[s.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center text-lg font-bold shrink-0 ${L?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(O=j.first_name[0])==null?void 0:O.toUpperCase()}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsxs("span",{className:"font-semibold text-white truncate",children:[j.first_name," ",j.last_name||""]}),L&&s.jsx(Js,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),j.has_agent&&s.jsx(Js,{variant:"outline",className:"text-[10px] px-1.5 py-0 border-yellow-500/40 text-yellow-400",children:"⚠️ Has Agent"})]}),s.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.jsxs(Js,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${C.color}`,children:[C.emoji," ",C.label]}),s.jsx("span",{className:"text-white/30 text-xs",children:ds(new Date(j.created_at),"h:mm a")})]})]})]},j.id)})})}):s.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-20",children:[s.jsx("div",{className:"w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mb-4",children:s.jsx(hve,{className:"h-10 w-10 text-white/20"})}),s.jsx("h2",{className:"text-xl font-bold text-white/60 mb-1",children:"Waiting for visitors..."}),s.jsx("p",{className:"text-white/30 text-sm",children:"New sign-ins will appear here in real-time"})]})})]})}function Dct(){const e=ms().pathname.slice(1);if(N.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),e.startsWith("live/")){const r=e.slice(5);if(r)return s.jsx(Lct,{token:r})}if(e.startsWith("rsvp/")){const r=e.slice(5);if(r)return s.jsx($Ee,{slug:r})}return!e||e===""?s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center text-white",children:[s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Guest Book"}),s.jsx("p",{className:"text-white/60",children:"The modern open house sign-in experience."}),s.jsx("p",{className:"text-white/40 text-sm mt-2",children:"Visit a specific open house link to sign in."})]})}):s.jsx(zEe,{slug:e})}function Mct({dealData:t,agentProfile:e,welcomeMessage:r,isWon:n,branding:i}){var l;const a=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,c=(i==null?void 0:i.logo_url)||null,d=(i==null?void 0:i.cover_photo_url)||null,p=(i==null?void 0:i.tagline)||"Your Real Estate Concierge";return s.jsxs("div",{className:"relative overflow-hidden",children:[s.jsxs("div",{className:"relative px-4 pt-10 pb-20",children:[d&&s.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${d})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter-mobile)"}}),s.jsx("div",{className:"absolute inset-0",style:{background:d?"var(--portal-hero-scrim-mobile)":"radial-gradient(ellipse 100% 70% at 50% 0%, hsl(var(--portal-gold) / 0.12), transparent 60%), linear-gradient(180deg, hsl(0 0% 7%), hsl(0 0% 4%))"}}),s.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, hsl(var(--portal-gold)) 1px, transparent 1px)",backgroundSize:"32px 32px"}}),s.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[c&&s.jsx(Sr.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},transition:{duration:.5},className:"mb-6 flex justify-center",children:s.jsx("div",{className:"rounded-xl px-4 py-2.5",style:{background:"hsl(0 0% 100% / 0.06)",backdropFilter:"blur(8px)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:s.jsx("img",{src:c,alt:"Brand",className:"h-9 max-w-[160px] object-contain"})})}),e&&s.jsxs(Sr.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.5,delay:.05},className:"mb-6",children:[e.avatar_url?s.jsx("div",{className:"w-20 h-20 mx-auto mb-3 relative",children:s.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:s.jsx("img",{src:e.avatar_url,alt:e.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):s.jsx("div",{className:"w-20 h-20 mx-auto mb-3 rounded-full flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"var(--portal-hero-accent)"},children:((l=e.name)==null?void 0:l.charAt(0))||"?"}),s.jsx("p",{className:"portal-serif text-lg",style:{color:"var(--portal-hero-ink)"},children:e.name}),s.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"var(--portal-hero-ink-dim)"},children:p})]}),s.jsxs(Sr.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6,delay:.1},children:[s.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.2em] uppercase mb-4",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.25)",color:"var(--portal-hero-accent)"},children:[s.jsx(Do,{className:"w-3 h-3"}),(t==null?void 0:t.deal_type)==="listing"?"Sale":(t==null?void 0:t.deal_type)==="buy-side"?"Purchase":"Transaction",n&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"opacity-50",children:"·"}),"Complete"]})]}),s.jsx("h1",{className:"portal-serif text-[2.5rem] leading-[1.05] mb-3",style:{color:"var(--portal-hero-ink)"},children:(t==null?void 0:t.deal_name)||"Your Transaction"}),s.jsx("div",{className:"portal-hairline w-24 mx-auto mb-4"}),a&&s.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-sm",style:{color:"var(--portal-hero-ink-muted)"},children:[s.jsx(Va,{className:"w-3.5 h-3.5",style:{color:"var(--portal-hero-accent)"}}),s.jsx("span",{children:a})]}),r&&s.jsxs("p",{className:"mt-6 text-sm leading-relaxed max-w-md mx-auto italic portal-serif",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.05rem"},children:["“",r,"”"]})]})]})]}),e&&s.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-10 relative z-10",children:s.jsx("div",{className:"rounded-2xl p-3",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.2)",boxShadow:"var(--portal-shadow-tile)"},children:s.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.phone&&s.jsxs("a",{href:`tel:${e.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[s.jsx(Ui,{className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),e.email&&s.jsxs("a",{href:`mailto:${e.email}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[s.jsx(rs,{className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),e.phone&&s.jsxs("a",{href:`sms:${e.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[s.jsx(nT,{className:"w-4 h-4"}),s.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function AAe({targetCloseDate:t,actualCloseDate:e,clientName:r}){if(e||!t)return null;const n=t.split(/[-/T]/),i=new Date(Number(n[0]),Number(n[1])-1,Number(n[2])),c=hQe(i,new Date);if(mT(i)&&!Uf(i))return null;const d=Uf(i),p=d?"0":String(Math.max(0,c)),l=Math.max(4,Math.min(100,(60-Math.min(60,c))/60*100));return s.jsxs("div",{className:"portal-tile p-8 text-center",children:[s.jsx("p",{className:"portal-eyebrow mb-4",children:d?"The Moment Has Arrived":"Countdown to Closing"}),d?s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"portal-serif text-5xl mb-2",style:{color:"hsl(var(--portal-gold))"},children:"Closing Day"}),s.jsxs("p",{className:"text-sm mt-3",style:{color:"hsl(var(--portal-ink-muted))"},children:["Congratulations",r?`, ${r.split(" ")[0]}`:"","."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-baseline justify-center gap-3",children:[s.jsx(Sr.span,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6},className:"portal-serif tabular-nums leading-none",style:{fontSize:"5.5rem",color:"hsl(var(--portal-gold))",textShadow:"0 0 40px hsl(var(--portal-gold) / 0.4)"},children:p}),s.jsx("span",{className:"portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink-muted))"},children:c===1?"day":"days"})]}),s.jsx("div",{className:"portal-hairline w-16 mx-auto my-4"}),s.jsx("p",{className:"text-xs tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-muted))"},children:"Until you hold the keys"}),s.jsx("div",{className:"mt-6 mx-auto max-w-[260px]",children:s.jsx("div",{className:"h-[2px] rounded-full overflow-hidden",style:{background:"hsl(var(--portal-gold) / 0.15)"},children:s.jsx(Sr.div,{initial:{width:0},animate:{width:`${l}%`},transition:{duration:1.2,ease:"easeOut"},className:"h-full rounded-full",style:{background:"var(--portal-gradient-gold)",boxShadow:"0 0 12px hsl(var(--portal-gold) / 0.6)"}})})})]})]})}function kAe({journeyStages:t,currentIndex:e}){return t.length===0?null:s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"The Journey"}),s.jsx("h2",{className:"portal-serif text-2xl mb-6",style:{color:"hsl(var(--portal-ink))"},children:"Your path to the keys"}),s.jsx("div",{className:"relative",children:t.map((r,n)=>{const i=ne;return s.jsxs(Sr.div,{initial:{opacity:0,x:-6},animate:{opacity:1,x:0},transition:{duration:.35,delay:n*.05},className:"flex items-start gap-4 relative",children:[n{var c,d;if(a.includes("youtube.com/watch")){const p=new URL(a).searchParams.get("v");return p?`https://www.youtube.com/embed/${p}`:null}if(a.includes("youtu.be/")){const p=(c=a.split("youtu.be/")[1])==null?void 0:c.split("?")[0];return p?`https://www.youtube.com/embed/${p}`:null}if(a.includes("loom.com/share/")){const p=(d=a.split("loom.com/share/")[1])==null?void 0:d.split("?")[0];return p?`https://www.loom.com/embed/${p}`:null}return a};return s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Right Now"}),s.jsx("h4",{className:"portal-serif text-3xl mb-2 portal-gold-underline",style:{color:"hsl(var(--portal-ink))"},children:t.label}),s.jsx("p",{className:"text-sm leading-relaxed mt-4",style:{color:"hsl(var(--portal-ink-muted))"},children:t.description}),e&&s.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Note From Your Agent"}),s.jsxs("p",{className:"text-sm leading-relaxed portal-serif italic",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:["“",e,"”"]})]}),r&&s.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"linear-gradient(135deg, hsl(var(--portal-gold) / 0.08), hsl(var(--portal-gold) / 0.02))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"What’s Next"}),s.jsx("p",{className:"text-sm leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:r})]}),n&&s.jsx("div",{className:"mt-5 rounded-xl overflow-hidden aspect-video relative group",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:s.jsx("iframe",{src:i(n)||n,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Next step video"})})]})}function _T(t){const e=t.split(/[-/T]/);if(e.length>=3){const r=Number(e[0]);return r>99?new Date(r,Number(e[1])-1,Number(e[2])):new Date(Number(e[2]),Number(e[0])-1,Number(e[1]))}return new Date(`${t}T12:00:00`)}function lZt(t){const e=t.trim();if(!e)return;const r=e.split(/[-/]/).filter(Boolean);if(r.length<3)return;const n=r.map(p=>Number(p));if(n.some(p=>Number.isNaN(p)))return;n[0];let i,a,c;if(r[0].length===4)[c,i,a]=n,i=i-1;else if([i,a,c]=n,i=i-1,r[2].length===2)c=c<=49?2e3+c:1900+c;else if(r[2].length!==4)return;const d=new Date(c,i,a);if(!(d.getFullYear()!==c||d.getMonth()!==i||d.getDate()!==a))return d}const Oct=[{key:"contract_date",label:"Contract Accepted",icon:jq},{key:"earnest_money_due_date",label:"Earnest Money",icon:Cy},{key:"inspection_date",label:"Inspection",icon:ef},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:lg},{key:"appraisal_date",label:"Appraisal",icon:Do},{key:"loan_approval_date",label:"Loan Approval",icon:lve},{key:"title_docs_due_date",label:"Title & Disclosures",icon:lg},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:Q4e},{key:"target_close_date",label:"Target Close",icon:Cl}];function Fct(t,e){const r=ds(e,"yyyyMMdd");return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:t,dates:`${r}/${r}`,details:"Added from your Client Portal"}).toString()}`}function Bct(t,e){const r=ds(e,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${r} DTEND;VALUE=DATE:${r} SUMMARY:${t} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function jAe({deal:t,portal:e,targetCloseDate:r,contractDate:n,inspectionDate:i,appraisalDate:a,actualCloseDate:c}){const d={...t||{},contract_date:(t==null?void 0:t.contract_date)??n??null,inspection_date:(t==null?void 0:t.inspection_date)??(e==null?void 0:e.inspection_date)??i??null,appraisal_date:(t==null?void 0:t.appraisal_date)??(e==null?void 0:e.appraisal_date)??a??null,target_close_date:(t==null?void 0:t.target_close_date)??r??null},p=(t==null?void 0:t.actual_close_date)??c??null,l=Array.isArray(t==null?void 0:t.completed_key_dates)?t.completed_key_dates:[],g=Oct.map(T=>T.key==="target_close_date"&&p?{...T,label:"Closed",date:p,done:!0}:{...T,date:d[T.key],done:l.includes(T.key)}).filter(T=>!!T.date);if(g.length===0)return null;const v=(T,j,P)=>{const C=_T(j);if(P==="google")window.open(Fct(T,C),"_blank");else{const L=Bct(T,C),O=document.createElement("a");O.href=L,O.download=`${T.replace(/\s+/g,"-").toLowerCase()}.ics`,O.click()}},E=g.filter(T=>T.done).length;return s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),s.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-5 flex-wrap",children:[s.jsx("h2",{className:"portal-serif text-2xl",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),s.jsxs("span",{className:"text-[11px] tracking-[0.18em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[E," of ",g.length," complete"]})]}),s.jsxs("div",{className:"space-y-4 relative",children:[s.jsx("div",{className:"absolute left-[10px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.18)"}}),g.map(({label:T,date:j,done:P,icon:C})=>{const L=_T(j),O=mT(L)&&!Uf(L),F=Uf(L),$=!O&&!F,G=P?"Completed":F?"Today":O?"In progress":"Upcoming";return s.jsxs("div",{className:"flex items-start gap-3 relative",children:[s.jsx("div",{className:"w-[21px] h-[21px] rounded-full mt-0.5 flex-shrink-0 relative z-10 flex items-center justify-center",style:{background:P?"hsl(var(--portal-gold))":F?"hsl(var(--portal-gold) / 0.25)":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.7)",boxShadow:F?"0 0 12px hsl(var(--portal-gold) / 0.5)":"none"},children:P?s.jsx(ql,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):s.jsx(C,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:T}),s.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:P?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:ds(L,"MMM d, yyyy")}),s.jsx("span",{className:"inline-block mt-1 text-[9px] tracking-[0.2em] uppercase px-2 py-0.5 rounded-full",style:{color:P||F?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${P||F?.5:.18})`},children:G})]}),$&&s.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[s.jsx("button",{onClick:()=>v(T,j,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:W=>{W.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:W=>{W.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:s.jsx(rve,{className:"w-3.5 h-3.5"})}),s.jsx("button",{onClick:()=>v(T,j,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},T)})]})]})}function CAe({documents:t}){const e=n=>n<1024?`${n} B`:n<1048576?`${(n/1024).toFixed(0)} KB`:`${(n/1048576).toFixed(1)} MB`,r=async n=>{const{data:i}=await Be.storage.from("deal-files").createSignedUrl(n.storage_path,300);i!=null&&i.signedUrl&&window.open(i.signedUrl,"_blank")};return s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),s.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),s.jsx("div",{className:"space-y-2",children:t.map(n=>s.jsxs("button",{onClick:()=>r(n),className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},onMouseEnter:i=>{i.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.35)"},onMouseLeave:i=>{i.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.08)"},children:[s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:s.jsx(lg,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:n.file_name}),s.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:e(n.file_size)})]}),s.jsx($u,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},n.id))})]})}function PAe({slug:t,wrapper:e}){const r=qa(),[n,i]=N.useState(null),{data:a=[]}=jr({queryKey:["portal-signature-requests",t],enabled:!!t,queryFn:async()=>{const{data:g,error:v}=await Be.functions.invoke("forms-portal-public",{body:{action:"list",slug:t}});return v?[]:(g==null?void 0:g.envelopes)||[]}}),c=a.filter(g=>g.my_turn),d=a.filter(g=>!g.my_turn&&g.status!=="completed");if(!c.length&&!d.length)return null;const p=async g=>{i(g);try{const{data:v,error:E}=await Be.functions.invoke("forms-portal-public",{body:{action:"sign_link",slug:t,envelope_id:g}});if(E||v!=null&&v.error)throw new Error((v==null?void 0:v.error)||"Could not open the document");r(v.path)}catch(v){lr.error((v==null?void 0:v.message)||"Could not open the document")}finally{i(null)}},l=s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Needs you"}),s.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents to sign"}),s.jsxs("div",{className:"space-y-2",children:[c.map(g=>s.jsxs("button",{onClick:()=>p(g.id),disabled:n===g.id,className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left",style:{background:"hsl(var(--portal-gold) / 0.1)",border:"1px solid hsl(var(--portal-gold) / 0.4)"},children:[s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.14)",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:n===g.id?s.jsx(gh,{className:"w-4 h-4 animate-spin",style:{color:"hsl(var(--portal-gold))"}}):s.jsx(l5e,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:g.title}),s.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-gold))"},children:"Tap to review & sign"})]})]},g.id)),d.map(g=>s.jsxs("div",{className:"w-full flex items-center gap-3 p-3 rounded-xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},children:[s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.06)"},children:g.my_status==="signed"?s.jsx(od,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}}):s.jsx(su,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1rem"},children:g.title}),s.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:g.my_status==="signed"?"You signed — waiting on others":"Waiting on another signer"})]})]},g.id))]})]});return e?e(l):l}function NAe({updates:t}){const e=r=>{var n,i;if(r.includes("youtube.com/watch")){const a=new URL(r).searchParams.get("v");return a?`https://www.youtube.com/embed/${a}`:null}if(r.includes("youtu.be/")){const a=(n=r.split("youtu.be/")[1])==null?void 0:n.split("?")[0];return a?`https://www.youtube.com/embed/${a}`:null}if(r.includes("loom.com/share/")){const a=(i=r.split("loom.com/share/")[1])==null?void 0:i.split("?")[0];return a?`https://www.loom.com/embed/${a}`:null}return r};return s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow mb-2",children:"Dispatch"}),s.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Updates from your agent"}),s.jsx("div",{className:"space-y-6",children:t.map((r,n)=>s.jsx("div",{className:n>0?"pt-6":"",style:n>0?{borderTop:"1px solid hsl(var(--portal-gold) / 0.1)"}:void 0,children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5",style:{background:r.is_stage_change?"hsl(var(--portal-gold) / 0.15)":"hsl(var(--portal-surface-3))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:r.is_stage_change?s.jsx(B4e,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):s.jsx(PP,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[s.jsx("h3",{className:"portal-serif",style:{fontSize:n===0?"1.4rem":"1.15rem",color:"hsl(var(--portal-ink))"},children:r.title}),s.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase flex-shrink-0",style:{color:"hsl(var(--portal-ink-dim))"},children:ds(new Date(r.created_at),"MMM d")})]}),r.content&&s.jsx("p",{className:`text-sm mt-2 leading-relaxed ${n===0?"italic portal-serif":""}`,style:{color:"hsl(var(--portal-ink-muted))",fontSize:n===0?"1rem":"0.875rem"},children:n===0?`“${r.content}”`:r.content}),r.video_url&&s.jsx("div",{className:"mt-3 rounded-xl overflow-hidden aspect-video",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:s.jsx("iframe",{src:e(r.video_url)||r.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:r.title})})]})]})},r.id))})]})}const zct=[{value:"lender",label:"Lender"},{value:"inspector",label:"Inspector"},{value:"title_escrow",label:"Title / Escrow"},{value:"insurance",label:"Insurance"},{value:"home_warranty",label:"Home Warranty"},{value:"movers",label:"Movers"},{value:"cleaners",label:"Cleaners"},{value:"handyman",label:"Handyman"},{value:"painter",label:"Painter"},{value:"landscaper",label:"Landscaper"},{value:"photographer",label:"Photographer"},{value:"stager",label:"Stager"},{value:"contractor",label:"Contractor"},{value:"electrician",label:"Electrician"},{value:"plumber",label:"Plumber"},{value:"hvac",label:"HVAC"},{value:"roofer",label:"Roofer"},{value:"pest_control",label:"Pest Control"},{value:"attorney",label:"Attorney"},{value:"accountant",label:"Accountant"},{value:"other",label:"Other"}];function cue(t){var r,n;const e=(r=t.custom_category)==null?void 0:r.trim();return e||((n=zct.find(i=>i.value===t.category))==null?void 0:n.label)||t.category}function uue(t){var r;const e=(r=t.custom_category)==null?void 0:r.trim();return e?`custom:${e.toLowerCase()}`:t.category}const cZt=[{value:"book",label:"Book Now (link)"},{value:"quote",label:"Request Quote (email)"},{value:"call",label:"Call"},{value:"email",label:"Email"},{value:"website",label:"Visit Website"}];function uZt(t){return jr({queryKey:["vendors","brokerage",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Be.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",t).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t})}function dZt(){const t=qs(),{brokerageId:e}=_i();return jr({queryKey:["vendors","library",t,e],queryFn:async()=>{if(!t)return{vendors:[],selections:[]};let r=Be.from("vendors").select("*");e?r=r.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${e})`):r=r.eq("owner_type","agent").eq("owner_user_id",t);const[{data:n,error:i},{data:a,error:c}]=await Promise.all([r.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),Be.from("agent_vendor_selections").select("*").eq("agent_user_id",t)]);if(i)throw i;if(c)throw c;return{vendors:n||[],selections:a||[]}},enabled:!!t})}function hZt(){const t=Ur();return zr({mutationFn:async e=>{if(e.id){const{id:r,created_at:n,...i}=e,{data:a,error:c}=await Be.from("vendors").update(i).eq("id",r).select().single();if(c)throw c;return a}else{const{data:r,error:n}=await Be.from("vendors").insert(e).select().single();if(n)throw n;return r}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function fZt(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("vendors").delete().eq("id",e);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function mZt(){const t=qs(),e=Ur();return zr({mutationFn:async({vendorId:r,isVisible:n})=>{if(!t)throw new Error("No user");const{data:i}=await Be.from("agent_vendor_selections").select("id").eq("agent_user_id",t).eq("vendor_id",r).maybeSingle();if(i){const{error:a}=await Be.from("agent_vendor_selections").update({is_visible:n}).eq("id",i.id);if(a)throw a}else{const{error:a}=await Be.from("agent_vendor_selections").insert({agent_user_id:t,vendor_id:r,is_visible:n});if(a)throw a}},onSuccess:()=>e.invalidateQueries({queryKey:["vendors"]})})}function RAe(t){return jr({queryKey:["portal-vendors",t==null?void 0:t.id,t==null?void 0:t.owner_user_id],queryFn:async()=>{if(!(t!=null&&t.id)||!(t!=null&&t.owner_user_id))return[];const e=t.owner_user_id,{data:r}=await Be.from("profiles").select("brokerage_id").eq("id",e).maybeSingle(),n=r==null?void 0:r.brokerage_id,i=Be.from("vendors").select("*").eq("is_active",!0),a=n?i.or(`and(owner_type.eq.agent,owner_user_id.eq.${e}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${n})`):i.eq("owner_type","agent").eq("owner_user_id",e),[{data:c,error:d},{data:p},{data:l}]=await Promise.all([a.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),Be.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",e),Be.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",t.id)]);if(d)throw d;const g=new Map;(p||[]).forEach(T=>g.set(T.vendor_id,{display_order:T.display_order,is_visible:T.is_visible}));const v=new Map;return(l||[]).forEach(T=>v.set(T.vendor_id,T.is_visible)),(c||[]).filter(T=>{if(v.get(T.id)===!1)return!1;const j=g.get(T.id);return!(j&&j.is_visible===!1&&!T.is_required)}).map(T=>{var j;return{...T,display_order:((j=g.get(T.id))==null?void 0:j.display_order)??T.sort_order??0}}).sort((T,j)=>(T.display_order||0)-(j.display_order||0))},enabled:!!(t!=null&&t.id)&&!!(t!=null&&t.owner_user_id)})}async function due(t){try{await Be.from("vendor_clicks").insert({vendor_id:t.vendorId,portal_id:t.portalId||null,agent_user_id:t.agentUserId||null,action_taken:t.actionTaken||null,user_agent:typeof navigator<"u"?navigator.userAgent.slice(0,500):null})}catch(e){console.warn("vendor click track failed",e)}}function pZt(t,e){return jr({queryKey:["vendor-clicks",t,e],queryFn:async()=>{if(!e)return{};const{data:r}=await Be.from("vendors").select("id").eq(t==="agent"?"owner_user_id":"owner_brokerage_id",e).eq("owner_type",t),n=(r||[]).map(c=>c.id);if(n.length===0)return{};const{data:i}=await Be.from("vendor_clicks").select("vendor_id").in("vendor_id",n),a={};return(i||[]).forEach(c=>{a[c.vendor_id]=(a[c.vendor_id]||0)+1}),a},enabled:!!e})}function LAe({portalId:t,ownerUserId:e,currentStage:r,brandingColor:n,layout:i="list"}){const{data:a=[],isLoading:c}=RAe({id:t,owner_user_id:e});if(c||a.length===0)return null;const d=a.filter(L=>!L.stage_filter||L.stage_filter.length===0||!r?!0:L.stage_filter.includes(r));if(d.length===0)return null;const p=n||"#406E71",l=(L,O)=>{switch(O){case"book":return L.booking_url;case"website":return L.website;case"call":return L.phone?`tel:${L.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return L.email?`mailto:${L.email}`:null}},g=L=>{const O=l(L,L.action_type);due({vendorId:L.id,portalId:t,agentUserId:e,actionTaken:L.action_type}),O&&window.open(O,L.action_type==="call"||L.action_type==="email"||L.action_type==="quote"?"_self":"_blank")},v=L=>{const O=l(L,L.action_type);return[{action:"website",label:"Website",icon:s.jsx(rT,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:s.jsx(rs,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:s.jsx(Ui,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:s.jsx(Cl,{className:"w-3.5 h-3.5"})}].filter($=>$.action!==L.action_type).map($=>{const G=l(L,$.action);return!G||G===O?null:s.jsxs("button",{onClick:()=>{due({vendorId:L.id,portalId:t,agentUserId:e,actionTaken:$.action}),window.open(G,$.action==="call"||$.action==="email"?"_self":"_blank")},className:"inline-flex items-center gap-1 text-slate-500 hover:text-slate-700 hover:underline",title:$.label,children:[$.icon,s.jsx("span",{className:"text-xs",children:$.label})]},$.action)}).filter(Boolean)},E=L=>{switch(L.action_type){case"book":return"Book Now";case"quote":return"Request Quote";case"call":return"Call";case"email":return"Email";case"website":return"Visit Site"}},T=L=>{switch(L.action_type){case"book":return s.jsx(Cl,{className:"w-3.5 h-3.5"});case"call":return s.jsx(Ui,{className:"w-3.5 h-3.5"});case"email":case"quote":return s.jsx(rs,{className:"w-3.5 h-3.5"});case"website":return s.jsx(rT,{className:"w-3.5 h-3.5"})}},j=s.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[s.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{backgroundColor:`${p}15`,color:p},children:s.jsx(va,{className:"w-4 h-4"})}),s.jsxs("div",{children:[s.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),s.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),P=d.some(L=>L.disclosure_text)&&s.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:d.filter(L=>L.disclosure_text).map(L=>s.jsxs("p",{className:"text-[10px] text-slate-400",children:[s.jsxs("span",{className:"font-medium",children:[L.company||L.name,":"]})," ",L.disclosure_text]},L.id))});if(i==="grid")return s.jsxs(wi,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[j,s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:d.map(L=>s.jsxs("div",{className:"group flex flex-col p-4 rounded-xl border border-slate-200/70 bg-white hover:shadow-md hover:-translate-y-0.5 transition-all",children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"w-12 h-12 rounded-lg bg-slate-50 border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:L.logo_url?s.jsx("img",{src:L.logo_url,alt:L.name,className:"w-full h-full object-cover"}):s.jsx("span",{className:"text-base font-semibold text-slate-500",children:(L.company||L.name).charAt(0)})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"font-semibold text-sm text-slate-800 truncate",children:L.company||L.name}),L.company&&L.name&&s.jsx("p",{className:"text-xs text-slate-500 truncate",children:L.name}),s.jsx("span",{className:"inline-block mt-1 text-[10px] font-medium px-1.5 py-0.5 rounded",style:{backgroundColor:`${p}12`,color:p},children:cue(L)})]})]}),L.description&&s.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:L.description}),s.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[s.jsxs(Jt,{size:"sm",onClick:()=>g(L),style:{backgroundColor:p},className:"text-white hover:opacity-90 w-full",children:[T(L),s.jsx("span",{className:"ml-1.5 text-xs",children:E(L)})]}),v(L).length>0&&s.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:v(L)})]})]},L.id))}),P]});const C=d.reduce((L,O)=>((L[uue(O)]=L[uue(O)]||[]).push(O),L),{});return s.jsxs(wi,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[j,s.jsx("div",{className:"space-y-4",children:Object.entries(C).map(([L,O])=>s.jsxs("div",{children:[s.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:cue(O[0])}),s.jsx("div",{className:"space-y-2",children:O.map(F=>s.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-white border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:F.logo_url?s.jsx("img",{src:F.logo_url,alt:F.name,className:"w-full h-full object-cover"}):s.jsx("span",{className:"text-sm font-semibold text-slate-500",children:F.name.charAt(0)})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:F.company||F.name}),F.company&&F.name&&s.jsx("p",{className:"text-xs text-slate-500 truncate",children:F.name}),F.description&&s.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:F.description})]}),s.jsxs(Jt,{size:"sm",onClick:()=>g(F),style:{backgroundColor:p},className:"text-white hover:opacity-90 shrink-0",children:[T(F),s.jsx("span",{className:"ml-1.5 text-xs",children:E(F)})]})]},F.id))})]},L))}),P]})}function $ct(t){const e=window.location.hostname;return e==="localhost"||e.includes("lovable.app")?`${window.location.origin}/portal/${t}/refer`:`https://clients.relevelup.com/${t}/refer`}function Uct(t){if(!t)return null;const e=t.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([\w-]+)/);if(e)return`https://www.youtube.com/embed/${e[1]}`;const r=t.match(/loom\.com\/share\/([\w-]+)/);return r?`https://www.loom.com/embed/${r[1]}`:(t.match(/\.(mp4|webm|mov)(\?|$)/i),t)}function DAe({portalId:t,portalSlug:e,ownerUserId:r,rewardText:n,ctaHeadline:i,agentName:a,clientName:c,reviewUrl:d,hubVideoUrl:p}){const[l,g]=N.useState(!1),v=N.useRef(!1),E=$ct(e);N.useEffect(()=>{v.current||(v.current=!0,Be.from("portal_referral_clicks").insert({portal_id:t,owner_user_id:r,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[t,r]);const T=async W=>{await Be.from("portal_referral_clicks").insert({portal_id:t,owner_user_id:r,click_type:W,user_agent:navigator.userAgent.slice(0,500)})},j=()=>`${c?`Hey, it's ${c}!`:"Hey!"} I just had an amazing experience working with ${a||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${E}`,P=async()=>{await navigator.clipboard.writeText(E),g(!0),T("copy_link"),setTimeout(()=>g(!1),2e3)},C=()=>{T("share_sms");const W=encodeURIComponent(j());window.location.href=`sms:?&body=${W}`},L=()=>{T("share_email");const W=encodeURIComponent("A referral you'll thank me for"),Z=encodeURIComponent(j());window.location.href=`mailto:?subject=${W}&body=${Z}`},O=()=>{T("open_form"),window.open(E,"_blank")},F=i||"Know someone buying or selling?",$=p?Uct(p):null,G=$==null?void 0:$.match(/\.(mp4|webm|mov)(\?|$)/i);return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"bg-gradient-to-br from-emerald-50 via-teal-50 to-cyan-50 rounded-2xl p-6 border border-emerald-100 text-center",children:[s.jsx("div",{className:"text-5xl mb-2",children:"🎉"}),s.jsxs("h3",{className:"text-xl font-bold text-emerald-900 mb-1 font-serif",children:["Welcome Home",c?`, ${c.split(" ")[0]}`:"","!"]}),s.jsx("p",{className:"text-sm text-emerald-700/80",children:"Your transaction is complete. We're so proud to have been part of your journey."})]}),$&&s.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[s.jsx("div",{className:"px-4 pt-4 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(va,{className:"w-4 h-4 text-[#406E71]"}),s.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",a||"your agent"]})]})}),s.jsx("div",{className:"aspect-video bg-slate-900",children:G?s.jsx("video",{src:$,controls:!0,className:"w-full h-full",playsInline:!0}):s.jsx("iframe",{src:$,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),s.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white shadow-xl",children:[s.jsx("div",{className:"absolute inset-0 opacity-[0.07]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"20px 20px"}}),s.jsxs("div",{className:"relative p-6",children:[s.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium mb-3",children:[s.jsx(Jm,{className:"w-3 h-3"}),"Referral Program"]}),s.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:F}),n&&s.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[s.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",n]}),s.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",a||"us"," is sending a friend or family member."]}),s.jsxs("button",{onClick:O,className:"w-full bg-white text-[#2a4c64] font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 shadow-md hover:bg-white/95 active:scale-[0.99] transition-all",children:["Refer a Friend",s.jsx(lo,{className:"w-4 h-4"})]}),s.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[s.jsxs("button",{onClick:C,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[s.jsx(nT,{className:"w-3.5 h-3.5"}),"Text"]}),s.jsxs("button",{onClick:L,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[s.jsx(rs,{className:"w-3.5 h-3.5"}),"Email"]}),s.jsxs("button",{onClick:P,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[l?s.jsx(ql,{className:"w-3.5 h-3.5"}):s.jsx(Cq,{className:"w-3.5 h-3.5"}),l?"Copied":"Copy"]})]})]})]}),d&&s.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",onClick:()=>T("review_click"),className:"block bg-white border border-slate-200 hover:border-amber-300 hover:bg-amber-50/30 rounded-2xl p-4 transition-colors",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"text-2xl",children:"⭐"}),s.jsxs("div",{className:"flex-1",children:[s.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),s.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),s.jsx(lo,{className:"w-4 h-4 text-slate-400"})]})})]})}function Vct(t){return jr({queryKey:["portal-messages",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("portal_messages").select("*").eq("portal_id",t).order("created_at",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t,refetchInterval:3e4})}function qct(){const t=Ur();return zr({mutationFn:async({portalId:e,senderType:r,senderName:n,body:i,deviceFingerprint:a,portalUrl:c})=>{const{data:d,error:p}=await Be.from("portal_messages").insert({portal_id:e,sender_type:r,sender_name:n||null,body:i.trim(),device_fingerprint:a||null,...r==="agent"?{read_at:new Date().toISOString()}:{}}).select().single();if(p)throw p;try{await Be.functions.invoke("portal-message-notify",{body:{message_id:d.id,portal_url:c}})}catch(l){console.error("portal-message-notify failed",l)}return d},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["portal-messages",r.portalId]}),t.invalidateQueries({queryKey:["portal-unread-messages"]}),t.invalidateQueries({queryKey:["portal-conversations"]})}})}function gZt(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("portal_messages").update({read_at:new Date().toISOString()}).eq("portal_id",e).eq("sender_type","client").is("read_at",null);if(r)throw r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["portal-messages",r]}),t.invalidateQueries({queryKey:["portal-unread-messages"]}),t.invalidateQueries({queryKey:["portal-conversations"]})}})}function yZt(){const t=qs();return jr({queryKey:["portal-conversations",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("client_portals").select("id, slug, client_name, client_email, archived_at").eq("owner_user_id",t).is("archived_at",null);if(r)throw r;if(!e||e.length===0)return[];const n=e.map(p=>p.id),i=[],a=100,c=1e3;for(let p=0;p{const l=d.get(p.id)||[];return{portalId:p.id,slug:p.slug,clientName:p.client_name,clientEmail:p.client_email,lastMessage:l.length?l[l.length-1]:null,unreadCount:l.filter(g=>g.sender_type==="client"&&!g.read_at).length,messageCount:l.length}}).sort((p,l)=>{var E,T;const g=((E=p.lastMessage)==null?void 0:E.created_at)||"",v=((T=l.lastMessage)==null?void 0:T.created_at)||"";return g===v?(p.clientName||"").localeCompare(l.clientName||""):v.localeCompare(g)})},enabled:!!t,refetchInterval:3e4})}function MAe({portalId:t,clientName:e,agentName:r,agentAvatar:n,deviceFingerprint:i}){const{data:a,isLoading:c}=Vct(t),d=qct(),[p,l]=N.useState(""),g=`portal_msg_name_${t}`,[v,E]=N.useState(()=>localStorage.getItem(g)||e||""),T=N.useRef(null);N.useEffect(()=>{var C;(C=T.current)==null||C.scrollIntoView({block:"nearest"})},[a==null?void 0:a.length]);const j=async()=>{const C=p.trim();if(!C)return;const L=(v||e||"").trim();if(!L){lr.error("Please add your name first");return}try{localStorage.setItem(g,L),await d.mutateAsync({portalId:t,senderType:"client",senderName:L,body:C,deviceFingerprint:i,portalUrl:window.location.href}),l(""),lr.success("Message sent")}catch(O){lr.error((O==null?void 0:O.message)||"Could not send your message")}},P="hsl(var(--portal-gold))";return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[s.jsx(ug,{className:"w-4 h-4",style:{color:P}}),s.jsx("h2",{className:"portal-serif",style:{fontSize:"1.35rem",color:"hsl(var(--portal-ink))"},children:"Messages"})]}),s.jsx("div",{className:"portal-hairline mb-4"}),s.jsxs("div",{className:"space-y-3 max-h-[340px] overflow-y-auto pr-1",children:[c&&s.jsx("div",{className:"flex justify-center py-6",children:s.jsx(gh,{className:"w-4 h-4 animate-spin",style:{color:P}})}),!c&&(!a||a.length===0)&&s.jsxs("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:["Have a question for ",r||"your agent","? Send a message below — they'll be notified right away."]}),a==null?void 0:a.map(C=>{const L=C.sender_type==="agent";return s.jsx("div",{className:`flex ${L?"justify-start":"justify-end"}`,children:s.jsxs("div",{className:"max-w-[85%] rounded-2xl px-4 py-3",style:{background:L?"hsl(var(--portal-surface-2))":"hsl(var(--portal-gold) / 0.12)",border:`1px solid ${L?"hsl(var(--portal-gold) / 0.12)":"hsl(var(--portal-gold) / 0.28)"}`},children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[L&&n&&s.jsx("img",{src:n,alt:r||"Agent",className:"w-5 h-5 rounded-full object-cover"}),s.jsxs("span",{className:"text-[11px] uppercase tracking-[0.14em]",style:{color:"hsl(var(--portal-ink-dim))"},children:[L?r||"Your agent":C.sender_name||"You"," ·"," ",ds(new Date(C.created_at),"MMM d, h:mm a")]})]}),s.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:C.body})]})},C.id)}),s.jsx("div",{ref:T})]}),s.jsxs("div",{className:"mt-4 space-y-2",children:[!e&&s.jsx("input",{value:v,onChange:C=>E(C.target.value),placeholder:"Your name",className:"w-full rounded-xl px-3 py-2 text-sm outline-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),s.jsx("textarea",{value:p,onChange:C=>l(C.target.value),rows:3,placeholder:`Write a message to ${r||"your agent"}...`,className:"w-full rounded-xl px-3 py-2 text-sm outline-none resize-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),s.jsxs("button",{onClick:j,disabled:d.isPending||!p.trim(),className:"w-full flex items-center justify-center gap-2 rounded-xl py-2.5 text-sm font-medium transition-opacity disabled:opacity-50",style:{background:"hsl(var(--portal-gold) / 0.16)",border:"1px solid hsl(var(--portal-gold) / 0.35)",color:P},children:[d.isPending?s.jsx(gh,{className:"w-4 h-4 animate-spin"}):s.jsx(nF,{className:"w-4 h-4"}),"Send message"]})]})]})}function Gct(t){return t==="buy-side"?"Home Search in Progress":t==="listing"?"Your Home Is On The Market":"Active Phase"}function Hct(t){return t==="buy-side"?"We're actively searching for homes that match your criteria.":t==="listing"?"Your property is now being marketed to potential buyers.":"Your transaction is actively moving forward."}const Wct={Lead:{label:"Getting Started",description:"We're beginning your home journey and preparing the next steps."},Consultation:{label:"Planning Your Move",description:"We're discussing your goals and building a plan for buying or selling."},"Agreement Signed":{label:"Officially Working Together",description:"We've signed the agreement and are moving forward together."},"Under Contract":{label:"Under Contract",description:"Your offer has been accepted and we are now moving through inspections and due diligence."},Closing:{label:"Final Steps to Closing",description:"We're finalizing documents and preparing for closing day."},"Closed Won":{label:"Closing Day",description:"Congratulations! Your transaction is complete. 🎉"}},OAe=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function FAe(t){return OAe.map(e=>{if(e==="Active")return{key:"Active",label:Gct(t),description:Hct(t)};const r=Wct[e];return{key:e,label:r.label,description:r.description}})}function FF(t){if(!t)return 0;const e=OAe.indexOf(t);return e>=0?e:0}function Kct({portal:t,linkedPortal:e,activePortal:r,activeTab:n,onTabChange:i,agentProfile:a,branding:c,updates:d,documents:p}){var Re,Ie,Te;const l=(c==null?void 0:c.cover_photo_url)||null,g=(c==null?void 0:c.logo_url)||null,v=(c==null?void 0:c.tagline)||"Your Real Estate Concierge",E=r==null?void 0:r.deal_pipeline,T=E==null?void 0:E.deal_pipeline_stages,j=T==null?void 0:T.is_won_stage,P=E==null?void 0:E.deal_type,C=r==null?void 0:r.stage_mapping;let L=FAe(P);C&&C.length>0&&(L=C.map((ge,$e)=>{var we,ke;return{key:`custom-${$e}`,label:ge.label||((we=L[$e])==null?void 0:we.label)||`Stage ${$e+1}`,description:ge.description||((ke=L[$e])==null?void 0:ke.description)||"",video_url:ge.video_url||void 0}}));const O=C&&C.length>0?Math.min(FF(T==null?void 0:T.name),L.length-1):FF(T==null?void 0:T.name),F=L[O],$=F==null?void 0:F.video_url,G=j&&r.show_post_close_tips!==!1&&r.referral_enabled!==!1,W=E!=null&&E.property_address?`${E.property_address}, ${E.city||""}, ${E.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,Z=!!e,Q=(Re=t==null?void 0:t.deal_pipeline)==null?void 0:Re.deal_type,ee=(Ie=e==null?void 0:e.deal_pipeline)==null?void 0:Ie.deal_type,ie=ge=>ge==="listing"?"Your Sale":ge==="buy-side"?"Your Purchase":"Transaction",oe=L.length>1?Math.round((O+1)/L.length*100):0,{data:pe=[]}=RAe({id:r==null?void 0:r.id,owner_user_id:r==null?void 0:r.owner_user_id}),Le=pe.some(ge=>!ge.stage_filter||ge.stage_filter.length===0||!(T!=null&&T.name)?!0:ge.stage_filter.includes(T.name)),be=()=>{var ge;(ge=document.getElementById("trusted-vendors"))==null||ge.scrollIntoView({behavior:"smooth",block:"start"})};return s.jsxs("div",{className:"min-h-screen relative",style:{background:"var(--portal-gradient-noir)"},children:[s.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[600px] opacity-70",style:{background:"radial-gradient(ellipse 70% 100% at 50% 0%, hsl(var(--portal-gold) / 0.08), transparent 60%)"}}),s.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-8",children:[s.jsxs(Sr.div,{initial:{opacity:0,y:-6},animate:{opacity:1,y:0},transition:{duration:.4},className:"flex items-center justify-between mb-8",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[g?s.jsx("div",{className:"rounded-lg px-3 py-1.5",style:{background:"hsl(0 0% 100% / 0.04)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:s.jsx("img",{src:g,alt:"Brand",className:"h-8 max-w-[140px] object-contain"})}):s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center portal-serif text-xl",style:{background:"var(--portal-gradient-gold)",color:"hsl(var(--portal-bg))"},children:"✦"}),s.jsxs("div",{children:[s.jsx("p",{className:"portal-eyebrow",children:"Private Client Portal"}),s.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.1rem",color:"hsl(var(--portal-ink))"},children:r!=null&&r.client_name?`Welcome, ${r.client_name.split(" ")[0]}`:"Your transaction"})]})]}),s.jsxs("div",{className:"flex items-center gap-2 text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[s.jsx(Wj,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),s.jsxs(Sr.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.6,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl mb-8",style:{minHeight:380,border:"1px solid hsl(var(--portal-gold) / 0.25)",boxShadow:"var(--portal-shadow-luxe)"},children:[l?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${l})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter)"}}),s.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-scrim)"}})]}):s.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-fallback)"}}),s.jsx("div",{className:"absolute top-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.6), transparent)"}}),s.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-12",children:[s.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[s.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.22em] uppercase mb-6 self-start",style:{background:"hsl(0 0% 0% / 0.28)",backdropFilter:"blur(6px)",border:"1px solid var(--portal-hero-accent)",color:"var(--portal-hero-accent)"},children:[s.jsx(Do,{className:"w-3 h-3"}),P==="listing"?"Sale":P==="buy-side"?"Purchase":"Transaction",j&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),s.jsx("h1",{className:"portal-serif leading-[0.95] mb-4",style:{fontSize:"4.5rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:(E==null?void 0:E.deal_name)||"Your Transaction"}),s.jsx("div",{className:"portal-hairline w-32 mb-5"}),W&&s.jsxs("div",{className:"flex items-center gap-2",style:{color:"var(--portal-hero-ink-muted)",textShadow:"var(--portal-hero-text-shadow)"},children:[s.jsx(Va,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),s.jsx("span",{className:"text-base",children:W})]}),(r==null?void 0:r.welcome_message)&&s.jsxs("p",{className:"mt-6 portal-serif italic leading-relaxed max-w-2xl",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.15rem",textShadow:"var(--portal-hero-text-shadow)"},children:["“",r.welcome_message,"”"]})]}),s.jsxs("div",{className:"flex flex-col items-center justify-center",children:[s.jsx(Yct,{pct:oe}),s.jsx("p",{className:"portal-eyebrow mt-4",style:{color:"var(--portal-hero-accent)"},children:"Journey Progress"}),s.jsxs("p",{className:"portal-serif mt-1",style:{fontSize:"1.1rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:["Stage ",O+1," of ",L.length]})]})]}),s.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.4), transparent)"}})]}),Z&&s.jsx("div",{className:"inline-flex gap-1 rounded-xl p-1 mb-8",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(ge=>{const $e=ge==="primary"?Q:ee,we=n===ge;return s.jsx("button",{onClick:()=>i(ge),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:we?"hsl(var(--portal-surface-3))":"transparent",color:we?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:we?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:ie($e)},ge)})}),s.jsxs(Sr.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.06}}},className:"grid grid-cols-12 gap-5",children:[s.jsx("aside",{className:"col-span-3 space-y-5",children:s.jsxs("div",{className:"sticky top-6 space-y-5",children:[s.jsxs(Lp,{children:[s.jsxs("div",{className:"text-center pt-2 pb-1",children:[a!=null&&a.avatar_url?s.jsx("div",{className:"w-24 h-24 mx-auto relative",children:s.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:s.jsx("img",{src:a.avatar_url,alt:a.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):s.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.4)",color:"hsl(var(--portal-gold))"},children:((Te=a==null?void 0:a.name)==null?void 0:Te.charAt(0))||"?"}),s.jsx("h3",{className:"mt-4 portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink))"},children:a==null?void 0:a.name}),s.jsx("div",{className:"portal-hairline w-12 mx-auto my-2"}),s.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:v})]}),s.jsxs("div",{className:"mt-5 space-y-2",children:[(a==null?void 0:a.phone)&&s.jsx(rV,{href:`tel:${a.phone}`,icon:Ui,label:"Call",sub:a.phone}),(a==null?void 0:a.phone)&&s.jsx(rV,{href:`sms:${a.phone}`,icon:nT,label:"Text message"}),(a==null?void 0:a.email)&&s.jsx(rV,{href:`mailto:${a.email}`,icon:rs,label:"Email",sub:a.email})]})]}),s.jsxs(Lp,{children:[s.jsx("p",{className:"portal-eyebrow mb-4",children:"At a Glance"}),s.jsxs("div",{className:"space-y-4",children:[(E==null?void 0:E.target_close_date)&&s.jsx(nV,{icon:Cl,label:"Target close",value:hue(E.target_close_date)}),(E==null?void 0:E.contract_date)&&s.jsx(nV,{icon:su,label:"Under contract",value:hue(E.contract_date)}),s.jsx(nV,{icon:ad,label:"Progress",value:`${oe}%`})]})]})]})}),s.jsxs("main",{className:"col-span-6 space-y-5",children:[G&&s.jsx(DAe,{portalId:r.id,portalSlug:r.slug,ownerUserId:r.owner_user_id,rewardText:r.referral_reward_text,ctaHeadline:r.referral_cta_headline,agentName:a==null?void 0:a.name,clientName:r.client_name,reviewUrl:r.review_url,hubVideoUrl:r.homeowner_hub_video_url}),s.jsx(AAe,{targetCloseDate:E==null?void 0:E.target_close_date,actualCloseDate:E==null?void 0:E.actual_close_date,clientName:r.client_name}),F&&s.jsx(Lp,{children:s.jsx(IAe,{currentStage:F,nextStepText:r.next_step_text,nextStepVideoUrl:$||r.next_step_video_url})}),s.jsx(Lp,{children:s.jsx(kAe,{journeyStages:L,currentIndex:O})}),d&&d.length>0&&s.jsx(Lp,{children:s.jsx(NAe,{updates:d})}),(r==null?void 0:r.id)&&s.jsx(Lp,{children:s.jsx(MAe,{portalId:r.id,clientName:r.client_name,agentName:a==null?void 0:a.name,agentAvatar:a==null?void 0:a.avatar_url})})]}),s.jsxs("aside",{className:"col-span-3 space-y-5",children:[s.jsx(Lp,{children:s.jsx(jAe,{deal:E,portal:r})}),(r==null?void 0:r.slug)&&s.jsx(PAe,{slug:r.slug,wrapper:ge=>s.jsx(Lp,{children:ge})}),p&&p.length>0&&s.jsx(Lp,{children:s.jsx(CAe,{documents:p})}),Le&&s.jsx(Lp,{children:s.jsxs("button",{onClick:be,className:"w-full flex items-center gap-3 rounded-xl px-3 py-3 transition-all text-left group",style:{background:"hsl(var(--portal-gold) / 0.06)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},onMouseEnter:ge=>{ge.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:ge=>{ge.currentTarget.style.background="hsl(var(--portal-gold) / 0.06)"},children:[s.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},children:s.jsx(mve,{className:"w-4 h-4"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"portal-serif",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:"Trusted Vendors"}),s.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:"My hand-picked network"})]}),s.jsx(ad,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})]})}),s.jsxs("div",{className:"text-center pt-2 space-y-2",children:[s.jsx("div",{className:"portal-hairline w-12 mx-auto"}),s.jsx("p",{className:"text-[10px] tracking-[0.25em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:"Powered by ReLevelUp"})]})]})]}),(r==null?void 0:r.id)&&(r==null?void 0:r.owner_user_id)&&s.jsx("div",{id:"trusted-vendors",className:"mt-8 scroll-mt-10",children:s.jsx(LAe,{portalId:r.id,ownerUserId:r.owner_user_id,currentStage:T==null?void 0:T.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function Lp({children:t}){return s.jsx(Sr.div,{variants:{hidden:{opacity:0,y:10},show:{opacity:1,y:0,transition:{duration:.45,ease:"easeOut"}}},className:"portal-tile p-6",children:t})}function rV({href:t,icon:e,label:r,sub:n}){return s.jsxs("a",{href:t,className:"flex items-center gap-3 rounded-xl px-3 py-2.5 transition-all",style:{background:"hsl(var(--portal-gold) / 0.05)",border:"1px solid hsl(var(--portal-gold) / 0.12)"},onMouseEnter:i=>{i.currentTarget.style.background="hsl(var(--portal-gold) / 0.1)",i.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.3)"},onMouseLeave:i=>{i.currentTarget.style.background="hsl(var(--portal-gold) / 0.05)",i.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.12)"},children:[s.jsx("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},children:s.jsx(e,{className:"w-4 h-4"})}),s.jsxs("div",{className:"min-w-0 text-left",children:[s.jsx("p",{className:"text-sm portal-serif",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:r}),n&&s.jsx("p",{className:"text-[10px] tracking-[0.15em] uppercase truncate mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:n})]})]})}function nV({icon:t,label:e,value:r}){return s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.1)",color:"hsl(var(--portal-gold))"},children:s.jsx(t,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:e}),s.jsx("p",{className:"portal-serif truncate",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:r})]})]})}function Yct({pct:t}){const i=2*Math.PI*78,a=i-t/100*i;return s.jsxs("div",{className:"relative",style:{width:170,height:170},children:[s.jsxs("svg",{width:170,height:170,className:"-rotate-90",children:[s.jsx("defs",{children:s.jsxs("linearGradient",{id:"portal-progress-gold",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[s.jsx("stop",{offset:"0%",stopColor:"var(--portal-hero-accent)"}),s.jsx("stop",{offset:"100%",stopColor:"var(--portal-hero-ink)"})]})}),s.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(0 0% 100% / 0.22)",strokeWidth:2,fill:"none"}),s.jsx(Sr.circle,{cx:170/2,cy:170/2,r:78,stroke:"url(#portal-progress-gold)",strokeWidth:3,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:i},animate:{strokeDashoffset:a},transition:{duration:1.4,ease:"easeOut"},strokeDasharray:i,style:{filter:"drop-shadow(0 0 6px hsl(0 0% 0% / 0.45))"}})]}),s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[s.jsx("span",{className:"portal-serif tabular-nums leading-none",style:{fontSize:"3rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:t}),s.jsx("span",{className:"text-[10px] tracking-[0.25em] uppercase mt-1",style:{color:"var(--portal-hero-ink-dim)",textShadow:"var(--portal-hero-text-shadow)"},children:"percent"})]})]})}function hue(t){const e=t.split(/[-/T]/),r=new Date(Number(e[0]),Number(e[1])-1,Number(e[2]));return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(r)}function Zct({portal:t,dealData:e,agentProfile:r,customQuestions:n,deviceFingerprint:i,onComplete:a}){var C,L;const[c,d]=N.useState({first_name:((C=t.client_name)==null?void 0:C.split(" ")[0])||"",last_name:((L=t.client_name)==null?void 0:L.split(" ").slice(1).join(" "))||"",email:t.client_email||"",phone:t.client_phone||"",preferred_contact_method:"email",client_role:"buyer",notes:"",spouse_first_name:"",spouse_last_name:"",spouse_email:"",spouse_phone:""}),[p,l]=N.useState({}),[g,v]=N.useState(!1),E=zr({mutationFn:async()=>{const{error:O}=await Be.from("portal_onboarding_submissions").insert({portal_id:t.id,first_name:c.first_name,last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,preferred_contact_method:c.preferred_contact_method,client_role:c.client_role,notes:c.notes||null,device_fingerprint:i,custom_answers:Object.keys(p).length>0?p:null,spouse_first_name:g&&c.spouse_first_name||null,spouse_last_name:g&&c.spouse_last_name||null,spouse_email:g&&c.spouse_email||null,spouse_phone:g&&c.spouse_phone||null});if(O)throw O},onSuccess:a,onError:O=>{console.error("[PortalOnboarding] Submit failed:",O),lr.error("Something went wrong. Please try again.")}}),T=e!=null&&e.property_address?`${e.property_address}, ${e.city||""}, ${e.state||""}`:null,j="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",P="mt-1 w-full rounded-xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400";return s.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:s.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[s.jsxs("div",{className:"text-center mb-8",children:[(r==null?void 0:r.avatar_url)&&s.jsx("img",{src:r.avatar_url,alt:r.name,className:"w-16 h-16 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),s.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),T&&s.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[s.jsx(Va,{className:"w-3.5 h-3.5"}),s.jsx("span",{children:T.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),s.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),s.jsxs("form",{onSubmit:O=>{O.preventDefault(),E.mutate()},className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),s.jsx(hn,{required:!0,value:c.first_name,onChange:O=>d(F=>({...F,first_name:O.target.value})),className:j,placeholder:"John"})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),s.jsx(hn,{value:c.last_name,onChange:O=>d(F=>({...F,last_name:O.target.value})),className:j,placeholder:"Doe"})]})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs font-medium text-slate-700",children:"Email"}),s.jsx(hn,{type:"email",value:c.email,onChange:O=>d(F=>({...F,email:O.target.value})),className:j,placeholder:"john@example.com"})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs font-medium text-slate-700",children:"Phone"}),s.jsx(hn,{type:"tel",value:c.phone,onChange:O=>d(F=>({...F,phone:O.target.value})),className:j,placeholder:"(555) 123-4567"})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs font-medium text-slate-700",children:"Preferred Contact Method"}),s.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(O=>s.jsx("button",{type:"button",onClick:()=>d(F=>({...F,preferred_contact_method:O.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c.preferred_contact_method===O.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:O.label},O.value))})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs font-medium text-slate-700",children:"Your Role"}),s.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(O=>s.jsx("button",{type:"button",onClick:()=>d(F=>({...F,client_role:O})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c.client_role===O?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:O.charAt(0).toUpperCase()+O.slice(1)},O))})]}),n.map(O=>s.jsxs("div",{children:[s.jsxs(sn,{className:"text-xs font-medium text-slate-700",children:[O.question_text," ",O.is_required&&"*"]}),O.field_type==="text"&&s.jsx(hn,{required:O.is_required,value:p[O.id]||"",onChange:F=>l($=>({...$,[O.id]:F.target.value})),className:j}),O.field_type==="textarea"&&s.jsx("textarea",{required:O.is_required,value:p[O.id]||"",onChange:F=>l($=>({...$,[O.id]:F.target.value})),className:`${P} min-h-[80px]`}),O.field_type==="dropdown"&&s.jsxs("select",{required:O.is_required,value:p[O.id]||"",onChange:F=>l($=>({...$,[O.id]:F.target.value})),className:`${P} h-10`,children:[s.jsx("option",{value:"",children:"Select..."}),(O.options||[]).map(F=>s.jsx("option",{value:F,children:F},F))]}),O.field_type==="toggle"&&s.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(F=>s.jsx("button",{type:"button",onClick:()=>l($=>({...$,[O.id]:F})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${p[O.id]===F?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:F},F))})]},O.id)),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),s.jsx("textarea",{value:c.notes,onChange:O=>d(F=>({...F,notes:O.target.value})),className:`${P} min-h-[60px]`,placeholder:"Anything you'd like your agent to know..."})]}),t.allow_spouse&&s.jsxs("div",{children:[s.jsx("button",{type:"button",onClick:()=>v(!g),className:"text-sm text-blue-600 hover:text-blue-700 font-medium",children:g?"− Remove spouse/partner":"+ Add spouse/partner"}),g&&s.jsxs("div",{className:"mt-3 p-4 bg-slate-50 rounded-xl border border-slate-200 space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs font-medium text-slate-700",children:"First Name"}),s.jsx(hn,{value:c.spouse_first_name,onChange:O=>d(F=>({...F,spouse_first_name:O.target.value})),className:j})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),s.jsx(hn,{value:c.spouse_last_name,onChange:O=>d(F=>({...F,spouse_last_name:O.target.value})),className:j})]})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs font-medium text-slate-700",children:"Email"}),s.jsx(hn,{type:"email",value:c.spouse_email,onChange:O=>d(F=>({...F,spouse_email:O.target.value})),className:j})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs font-medium text-slate-700",children:"Phone"}),s.jsx(hn,{type:"tel",value:c.spouse_phone,onChange:O=>d(F=>({...F,spouse_phone:O.target.value})),className:j})]})]})]}),s.jsx(Jt,{type:"submit",disabled:E.isPending||!c.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:E.isPending?"Submitting...":"Access My Portal"})]})]})})}function Xct(t,e){const r=(n,i)=>i!=null&&i!==""?i:n!=null&&n!==""?n:null;return{logo_url:r(t==null?void 0:t.logo_url,e==null?void 0:e.logo_url),cover_photo_url:r(t==null?void 0:t.cover_photo_url,e==null?void 0:e.cover_photo_url),brand_color:r(t==null?void 0:t.brand_color,e==null?void 0:e.brand_color),accent_color:r(t==null?void 0:t.accent_color,e==null?void 0:e.accent_color),tagline:r(t==null?void 0:t.tagline,e==null?void 0:e.tagline),welcome_message:r(t==null?void 0:t.welcome_message,e==null?void 0:e.welcome_message),portal_theme:r(t==null?void 0:t.portal_theme,e==null?void 0:e.portal_theme)||"noir"}}function xZt(){const t=qs();return jr({queryKey:["agent-portal-branding",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Be.from("agent_portal_branding").select("*").eq("user_id",t).maybeSingle();if(r)throw r;return e},enabled:!!t})}function Qct(t){return jr({queryKey:["agent-portal-branding-public",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Be.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message, portal_theme").eq("user_id",t).maybeSingle();if(r)throw r;return e},enabled:!!t})}function _Zt(){const t=qs(),e=Ur();return zr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Be.from("agent_portal_branding").upsert({user_id:t,...r},{onConflict:"user_id"}).select().single();if(i)throw i;return n},onSuccess:()=>{e.invalidateQueries({queryKey:["agent-portal-branding",t]}),e.invalidateQueries({queryKey:["agent-portal-branding-public",t]})}})}async function vZt(t,e,r){var d;const n=((d=e.name.split(".").pop())==null?void 0:d.toLowerCase())||"png",i=`${t}/${r}-${Date.now()}.${n}`,{error:a}=await Be.storage.from("portal-branding").upload(i,e,{upsert:!0,cacheControl:"3600"});if(a)throw a;const{data:c}=Be.storage.from("portal-branding").getPublicUrl(i);return c.publicUrl}function Jct(t,e){return jr({queryKey:["client-portal-public",t],queryFn:async()=>{if(!t)return null;const{data:r,error:n}=await Be.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("slug",t).eq("is_enabled",!0).maybeSingle();if(n)throw n;return r},enabled:e})}function eut(t){return jr({queryKey:["client-portal-by-id",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Be.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("id",t).eq("is_enabled",!0).maybeSingle();if(r)throw r;return e},enabled:!!t})}function tut({slug:t}){var $e,we,ke,Ae,He,ot;const[e,r]=N.useState(!1),[n,i]=N.useState("primary"),[a]=N.useState(()=>{const nt=`portal_fp_${t}`;let tt=localStorage.getItem(nt);return tt||(tt=localStorage.getItem("portal_fp"),tt?localStorage.setItem(nt,tt):(tt=crypto.randomUUID(),localStorage.setItem(nt,tt),localStorage.setItem("portal_fp",tt))),tt});N.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:c,isLoading:d,error:p}=Jct(t,!0),l=c==null?void 0:c.linked_portal_id,{data:g}=eut(l),v=($e=c==null?void 0:c.deal_pipeline)==null?void 0:$e.owner_user_id,{data:E}=jr({queryKey:["portal-stages",v],queryFn:async()=>{const{data:nt,error:tt}=await Be.from("deal_pipeline_stages").select("*").eq("owner_user_id",v).order("sort_order",{ascending:!0});if(tt)throw tt;return nt},enabled:!!v}),{data:T}=jr({queryKey:["portal-agent",v],queryFn:async()=>{const{data:nt,error:tt}=await Be.from("profiles").select("id, name, avatar_url, phone, email").eq("id",v).single();if(tt)throw tt;return nt},enabled:!!v}),{data:j}=Qct(v),P=n==="linked"&&g?g:c,C=P==null?void 0:P.id,L=Xct(j,P==null?void 0:P.branding_override),O=L.portal_theme==="azure"?"azure":"noir";N.useEffect(()=>{const nt=`portal-theme-${O}`;return document.body.classList.add(nt),()=>document.body.classList.remove(nt)},[O]);const{data:F}=jr({queryKey:["portal-updates-public",C],queryFn:async()=>{const{data:nt,error:tt}=await Be.from("portal_updates").select("*").eq("portal_id",C).order("created_at",{ascending:!1});if(tt)throw tt;return nt},enabled:!!C}),$=(we=P==null?void 0:P.deal_pipeline)==null?void 0:we.id,{data:G}=jr({queryKey:["portal-documents",$],queryFn:async()=>{const{data:nt,error:tt}=await Be.from("deal_files").select("*").eq("deal_id",$).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(tt)throw tt;return nt},enabled:!!$}),W=c==null?void 0:c.id,Z=W?`portal_onboarded_${W}_${a}`:null,Q=Z?localStorage.getItem(Z)==="1":!1,{data:ee,isLoading:ie}=jr({queryKey:["portal-onboarding-check",W,a],queryFn:async()=>{const{data:nt,error:tt}=await Be.from("portal_onboarding_submissions").select("id").eq("portal_id",W).eq("device_fingerprint",a).maybeSingle();if(tt)throw tt;return nt&&Z&&localStorage.setItem(Z,"1"),nt},enabled:!!W&&!!(c!=null&&c.require_onboarding)&&!Q,staleTime:5*60*1e3}),oe=!!(c!=null&&c.require_onboarding)&&!Q&&!ee&&!e,{data:pe}=jr({queryKey:["portal-custom-questions-public",v],queryFn:async()=>{const{data:nt,error:tt}=await Be.from("portal_custom_questions").select("*").eq("owner_user_id",v).eq("is_active",!0).order("sort_order",{ascending:!0});if(tt)throw tt;return nt},enabled:!!v&&oe}),Le=Q||!!ee||e||!(c!=null&&c.require_onboarding);if(d||c!=null&&c.require_onboarding&&!Q&&ie)return s.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:s.jsx(gh,{className:"w-6 h-6 animate-spin",style:{color:"hsl(var(--portal-gold))"}})});if(p||!c)return s.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",style:{background:"var(--portal-gradient-noir)"},children:s.jsxs("div",{className:"text-center max-w-md",children:[s.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-6",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:s.jsx(Wj,{className:"w-6 h-6",style:{color:"hsl(var(--portal-gold))"}})}),s.jsx("h1",{className:"portal-serif text-4xl mb-3",style:{color:"hsl(var(--portal-ink))"},children:"Portal Not Available"}),s.jsx("div",{className:"portal-hairline mx-auto w-24 mb-4"}),s.jsx("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:"This portal is no longer active or doesn't exist."})]})});if(!Le){const nt=c==null?void 0:c.deal_pipeline;return s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:s.jsx(Zct,{portal:c,dealData:nt,agentProfile:T,customQuestions:pe||[],deviceFingerprint:a,onComplete:()=>{Z&&localStorage.setItem(Z,"1"),r(!0)}})})}const be=(ke=c==null?void 0:c.deal_pipeline)==null?void 0:ke.deal_type,Re=(Ae=g==null?void 0:g.deal_pipeline)==null?void 0:Ae.deal_type,Ie=!!g,Te=nt=>nt==="listing"?"Your Sale":nt==="buy-side"?"Your Purchase":"Transaction",ge=nt=>nt==="listing"?s.jsx(Do,{className:"w-3.5 h-3.5"}):s.jsx(ove,{className:"w-3.5 h-3.5"});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"hidden lg:block",children:s.jsx(Kct,{portal:c,linkedPortal:g,activePortal:P,activeTab:n,onTabChange:i,agentProfile:T,branding:L,updates:F,documents:G})}),s.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[s.jsx(Mct,{dealData:P==null?void 0:P.deal_pipeline,agentProfile:T,welcomeMessage:(P==null?void 0:P.welcome_message)||L.welcome_message,isWon:(ot=(He=P==null?void 0:P.deal_pipeline)==null?void 0:He.deal_pipeline_stages)==null?void 0:ot.is_won_stage,branding:L}),s.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[Ie&&s.jsx("div",{className:"flex gap-1 rounded-xl p-1",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(nt=>{const tt=n===nt,vt=nt==="primary"?be:Re;return s.jsxs("button",{onClick:()=>i(nt),className:"flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all portal-serif",style:{background:tt?"hsl(var(--portal-surface-3))":"transparent",color:tt?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:tt?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[ge(vt),s.jsx("span",{style:{fontSize:"1rem"},children:Te(vt)})]},nt)})}),s.jsx(rut,{portal:P,updates:F,documents:G,agentProfile:T}),C&&s.jsx("div",{className:"rounded-2xl p-5",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.14)"},children:s.jsx(MAe,{portalId:C,clientName:P==null?void 0:P.client_name,agentName:T==null?void 0:T.name,agentAvatar:T==null?void 0:T.avatar_url,deviceFingerprint:a})}),s.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[s.jsx("div",{className:"portal-hairline w-16 mx-auto"}),s.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[s.jsx(Wj,{className:"w-3 h-3"}),s.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase",children:"Secure Client Portal"})]}),T&&s.jsxs("p",{className:"text-xs",style:{color:"hsl(var(--portal-ink-muted))"},children:["Curated by ",s.jsx("span",{className:"portal-serif",style:{color:"hsl(var(--portal-gold))",fontSize:"0.95rem"},children:T.name})]})]})]})]})]})}function rut({portal:t,updates:e,documents:r,agentProfile:n}){const i=t,a=i==null?void 0:i.deal_pipeline,c=a==null?void 0:a.deal_pipeline_stages,d=c==null?void 0:c.is_won_stage,p=a==null?void 0:a.deal_type,l=t.stage_mapping;let g=FAe(p);l&&l.length>0&&(g=l.map((P,C)=>{var L,O;return{key:`custom-${C}`,label:P.label||((L=g[C])==null?void 0:L.label)||`Stage ${C+1}`,description:P.description||((O=g[C])==null?void 0:O.description)||"",video_url:P.video_url||void 0}}));const v=l&&l.length>0?Math.min(FF(c==null?void 0:c.name),g.length-1):FF(c==null?void 0:c.name),E=g[v],T=E==null?void 0:E.video_url,j=d&&t.show_post_close_tips!==!1&&t.referral_enabled!==!1;return s.jsxs(s.Fragment,{children:[j&&s.jsx(DAe,{portalId:t.id,portalSlug:t.slug,ownerUserId:t.owner_user_id,rewardText:t.referral_reward_text,ctaHeadline:t.referral_cta_headline,agentName:n==null?void 0:n.name,clientName:t.client_name,reviewUrl:t.review_url,hubVideoUrl:t.homeowner_hub_video_url}),s.jsx(AAe,{targetCloseDate:a==null?void 0:a.target_close_date,actualCloseDate:a==null?void 0:a.actual_close_date,clientName:t.client_name}),s.jsx(kAe,{journeyStages:g,currentIndex:v}),E&&s.jsx(IAe,{currentStage:E,nextStepText:t.next_step_text,nextStepVideoUrl:T||t.next_step_video_url}),s.jsx(jAe,{deal:a,portal:t}),(t==null?void 0:t.slug)&&s.jsx(PAe,{slug:t.slug}),r&&r.length>0&&s.jsx(CAe,{documents:r}),(t==null?void 0:t.id)&&(t==null?void 0:t.owner_user_id)&&s.jsx(LAe,{portalId:t.id,ownerUserId:t.owner_user_id,currentStage:c==null?void 0:c.name}),e&&e.length>0&&s.jsx(NAe,{updates:e})]})}function BAe({slug:t}){const e=Sg(),r=t||e.slug,[n,i]=N.useState(!1),[a,c]=N.useState(!1),[d,p]=N.useState(""),[l,g]=N.useState(""),[v,E]=N.useState(""),[T,j]=N.useState(""),[P,C]=N.useState(""),[L,O]=N.useState("buying"),[F,$]=N.useState("");N.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:G,isLoading:W,error:Z}=jr({queryKey:["portal-referral-target",r],queryFn:async()=>{if(!r)return null;const{data:ie,error:oe}=await Be.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",r).eq("is_enabled",!0).maybeSingle();if(oe)throw oe;return ie},enabled:!!r}),{data:Q}=jr({queryKey:["portal-referral-agent",G==null?void 0:G.owner_user_id],queryFn:async()=>{const{data:ie}=await Be.from("profiles").select("id, name, avatar_url").eq("id",G.owner_user_id).single();return ie},enabled:!!(G!=null&&G.owner_user_id)}),ee=async ie=>{if(ie.preventDefault(),!G||!v.trim()){lr.error("Please enter your friend's name");return}if(!T.trim()&&!P.trim()){lr.error("Please add at least an email or phone for your friend");return}i(!0);try{const{error:oe}=await Be.from("portal_referrals").insert({portal_id:G.id,owner_user_id:G.owner_user_id,referrer_name:d.trim()||G.client_name||null,referrer_email:l.trim()||null,friend_name:v.trim(),friend_email:T.trim()||null,friend_phone:P.trim()||null,friend_interest:L,friend_message:F.trim()||null});if(oe)throw oe;c(!0)}catch(oe){lr.error(oe.message||"Could not submit referral")}finally{i(!1)}};return W?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:s.jsx(Mc,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):Z||!G||!G.referral_enabled?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:s.jsx("span",{className:"text-2xl",children:"🔒"})}),s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Referral Page Unavailable"}),s.jsx("p",{className:"text-slate-500",children:"This referral link is no longer active."})]})}):a?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-emerald-50 via-teal-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[s.jsx("div",{className:"w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4",children:s.jsx(ql,{className:"w-8 h-8 text-emerald-600"})}),s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2 font-serif",children:"Thank you! 🙏"}),s.jsxs("p",{className:"text-sm text-slate-600 leading-relaxed mb-6",children:["Your referral has been sent to ",(Q==null?void 0:Q.name)||"your agent",". They'll reach out to"," ",s.jsx("span",{className:"font-semibold text-slate-800",children:v})," personally and treat them like family."]}),s.jsxs("button",{onClick:()=>window.history.back(),className:"inline-flex items-center gap-2 text-sm text-[#406E71] hover:text-[#2a4c64] font-medium",children:[s.jsx(yv,{className:"w-4 h-4"}),"Back to your portal"]})]})}):s.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white pb-12",children:[s.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white px-4 pt-10 pb-12 overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),s.jsxs("div",{className:"relative max-w-lg mx-auto text-center",children:[Q!=null&&Q.avatar_url?s.jsx("img",{src:Q.avatar_url,alt:Q.name||"Agent",className:"w-16 h-16 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 object-cover"}):s.jsx("div",{className:"w-16 h-16 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 bg-white/10 flex items-center justify-center",children:s.jsx(Jm,{className:"w-7 h-7 text-white/70"})}),s.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/10 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/90 mb-2",children:[s.jsx(Jm,{className:"w-3 h-3"})," Referral"]}),s.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:G.referral_cta_headline||"Refer a Friend"}),s.jsxs("p",{className:"text-sm text-white/70",children:["Send ",(Q==null?void 0:Q.name)||"your agent"," someone you trust."]}),G.referral_reward_text&&s.jsxs("p",{className:"text-xs text-white/60 mt-2",children:["You'll get: ",s.jsx("span",{className:"text-white font-medium",children:G.referral_reward_text})," when they close."]})]})]}),s.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-6 relative z-10",children:s.jsxs("form",{onSubmit:ee,className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-5 space-y-5",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Tell us about your friend"}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsxs(sn,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx(hn,{id:"friend_name",value:v,onChange:ie=>E(ie.target.value),placeholder:"Jane Smith",required:!0,className:"mt-1"})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),s.jsx(hn,{id:"friend_email",type:"email",value:T,onChange:ie=>j(ie.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),s.jsx(hn,{id:"friend_phone",type:"tel",value:P,onChange:ie=>C(ie.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),s.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-sm",children:"They're interested in..."}),s.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[{v:"buying",l:"Buying"},{v:"selling",l:"Selling"},{v:"both",l:"Both"},{v:"unsure",l:"Not sure"}].map(ie=>s.jsx("button",{type:"button",onClick:()=>O(ie.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${L===ie.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:ie.l},ie.v))})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),s.jsx("textarea",{id:"friend_message",value:F,onChange:ie=>$(ie.target.value),placeholder:"They're moving from Boston in the spring...",rows:3,className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]})]})]}),s.jsxs("div",{className:"border-t pt-4",children:[s.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),s.jsx(hn,{id:"referrer_name",value:d,onChange:ie=>p(ie.target.value),placeholder:G.client_name||"Your name",className:"mt-1"})]}),s.jsxs("div",{children:[s.jsx(sn,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),s.jsx(hn,{id:"referrer_email",type:"email",value:l,onChange:ie=>g(ie.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),s.jsxs("button",{type:"submit",disabled:n,className:"w-full bg-[#406E71] hover:bg-[#345e7a] disabled:opacity-60 text-white font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 transition-colors",children:[n?s.jsx(gh,{className:"w-4 h-4 animate-spin"}):s.jsx(Jm,{className:"w-4 h-4"}),n?"Sending...":"Send Referral"]}),s.jsx("p",{className:"text-[11px] text-center text-slate-400",children:"By submitting, you confirm your friend has agreed to be contacted."})]})})]})}const nut=Object.freeze(Object.defineProperty({__proto__:null,default:BAe},Symbol.toStringTag,{value:"Module"}));function iut(){const e=ms().pathname.slice(1).replace(/\/$/,"");if(N.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>{document.body.classList.remove("client-portal-page")}),[]),!e)return s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Client Portal"}),s.jsx("p",{className:"text-slate-500",children:"Visit your personalized portal link to view your transaction details."})]})});const r=e.match(/^([^/]+)\/refer$/);return r?s.jsx(BAe,{slug:r[1]}):e.includes("/")?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Page Not Found"}),s.jsx("p",{className:"text-slate-500",children:"This portal link doesn't look right."})]})}):s.jsx(tut,{slug:e})}function sut(t){const e=[],r=n=>{n&&!e.includes(n)&&e.push(n)};for(const n of t.filter(Boolean)){r(n);try{const i=new URL(n),a=i.searchParams.get("u");a&&/\/functions\/v1\/trestle-media/i.test(i.pathname)&&r(a)}catch{}}return e}function L9({photos:t,alt:e="",className:r="w-full h-full",imgClassName:n="w-full h-full object-cover",iconClassName:i="w-8 h-8"}){const a=N.useMemo(()=>sut(Array.isArray(t)?t:[]),[t]),[c,d]=N.useState(0);return N.useEffect(()=>{d(0)},[a.join("|")]),!a.length||c>=a.length?s.jsx("div",{className:`${r} bg-muted flex items-center justify-center text-muted-foreground`,children:s.jsx(Do,{className:`${i} opacity-40`})}):s.jsx("div",{className:`${r} overflow-hidden bg-muted`,children:s.jsx("img",{src:a[c],alt:e,className:n,onError:()=>d(p=>p+1)})})}function aut({comp:t,open:e,onClose:r}){var l;const[n,i]=N.useState(0);if(!t)return null;const a=Array.isArray(t.photos)?t.photos.filter(Boolean):[],c=t.soldPrice||t.price,d=t.sqft&&c?Math.round(c/t.sqft):null,p=g=>{if(!g)return null;const[v,E,T]=g.split(/[-/T]/);return v?`${E}/${T}/${v}`:null};return s.jsx(gl,{open:e,onOpenChange:g=>{g||r()},children:s.jsxs(Jo,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[s.jsxs(Bc,{className:"px-6 pt-6 pb-2",children:[s.jsx(pc,{className:"text-xl",children:t.address}),s.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[s.jsx(Va,{className:"w-3.5 h-3.5"}),t.city,", ",t.state," ",t.zip]})]}),a.length>0?s.jsxs("div",{className:"px-6",children:[s.jsx(L9,{photos:a.slice(n),className:"rounded-lg aspect-[16/10]"}),a.length>1&&s.jsx("div",{className:"flex gap-2 mt-2 overflow-x-auto pb-2",children:a.slice(0,24).map((g,v)=>s.jsx("button",{onClick:()=>i(v),className:`flex-none w-20 h-16 rounded overflow-hidden border-2 transition ${v===n?"border-primary":"border-transparent opacity-70 hover:opacity-100"}`,children:s.jsx(L9,{photos:[g],iconClassName:"w-5 h-5"})},v))})]}):s.jsx("div",{className:"px-6",children:s.jsx("div",{className:"rounded-lg bg-muted aspect-[16/10] flex items-center justify-center text-muted-foreground",children:s.jsx(Do,{className:"w-12 h-12 opacity-40"})})}),s.jsxs("div",{className:"px-6 pt-4 flex items-center justify-between flex-wrap gap-2",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-3xl font-bold flex items-center gap-1",children:[s.jsx(Cy,{className:"w-6 h-6 text-muted-foreground"}),(c||0).toLocaleString()]}),d&&s.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",d,"/sqft"]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1",children:[s.jsx(Js,{variant:"outline",children:t.status}),t.daysOnMarket!=null&&s.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.daysOnMarket," DOM"]})]})]}),(t.listDate||t.statusChangeDate||t.soldDate)&&s.jsxs("div",{className:"px-6 pt-4",children:[s.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Timeline"}),s.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[s.jsx(iV,{label:"Active",date:p(t.listDate),active:!0}),s.jsx(iV,{label:"Pending",date:/Pending|Contingent|Under Contract|Backup/i.test(String(t.status||""))?p(t.statusChangeDate):null,active:/Pending|Contingent|Under Contract|Backup/i.test(String(t.status||""))}),s.jsx(iV,{label:"Closed",date:p(t.soldDate)||(/Closed|Sold/i.test(String(t.status||""))?p(t.statusChangeDate):null),active:/Closed|Sold/i.test(String(t.status||""))})]})]}),s.jsxs("div",{className:"px-6 pt-4 grid grid-cols-2 md:grid-cols-4 gap-3",children:[s.jsx(BD,{icon:s.jsx(tA,{className:"w-4 h-4"}),label:"Beds",value:t.bedrooms??"—"}),s.jsx(BD,{icon:s.jsx(ww,{className:"w-4 h-4"}),label:"Baths",value:t.bathrooms??"—"}),s.jsx(BD,{icon:s.jsx(k4,{className:"w-4 h-4"}),label:"SqFt",value:((l=t.sqft)==null?void 0:l.toLocaleString())??"—"}),s.jsx(BD,{icon:s.jsx(Cl,{className:"w-4 h-4"}),label:"Year Built",value:t.yearBuilt??"—"})]}),s.jsxs("div",{className:"px-6 pt-4 grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:[s.jsx(wd,{label:"MLS #",value:t.mlsNumber}),s.jsx(wd,{label:"Property Type",value:t.propertySubType||t.propertyType}),s.jsx(wd,{label:"Lot Size",value:t.lotSize}),s.jsx(wd,{label:"Garage",value:t.garageSpaces}),s.jsx(wd,{label:"Stories",value:t.stories}),s.jsx(wd,{label:"HOA",value:t.hoaFee?`$${t.hoaFee}/${(t.hoaFrequency||"mo").toLowerCase()}`:null}),s.jsx(wd,{label:"Tax (annual)",value:t.taxAmount?`$${t.taxAmount.toLocaleString()}`:null}),s.jsx(wd,{label:"Heating",value:t.heating}),s.jsx(wd,{label:"Cooling",value:t.cooling}),s.jsx(wd,{label:"Parking",value:t.parking}),s.jsx(wd,{label:"Elementary",value:t.elementarySchool}),s.jsx(wd,{label:"Middle",value:t.middleSchool}),s.jsx(wd,{label:"High",value:t.highSchool}),s.jsx(wd,{label:"Listed By",value:t.listAgentFullName}),s.jsx(wd,{label:"Office",value:t.listOfficeName})]}),t.description&&s.jsxs("div",{className:"px-6 pt-4",children:[s.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1",children:"Description"}),s.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:t.description})]}),s.jsx("div",{className:"px-6 py-4"})]})})}function BD({icon:t,label:e,value:r}){return s.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[t,e]}),s.jsx("div",{className:"text-lg font-semibold mt-0.5",children:r})]})}function wd({label:t,value:e}){return e==null||e===""||e===0?null:s.jsxs("div",{className:"flex justify-between border-b border-dashed py-1",children:[s.jsx("span",{className:"text-muted-foreground",children:t}),s.jsx("span",{className:"font-medium text-right ml-3 truncate",children:String(e)})]})}function iV({label:t,date:e,active:r}){return s.jsxs("div",{className:`rounded-lg border p-2 text-center ${r?"bg-primary/5 border-primary/30":"bg-muted/30"}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:t}),s.jsx("div",{className:`text-sm font-medium mt-0.5 ${e?"":"text-muted-foreground/60"}`,children:e||"—"})]})}function zD({to:t,durationMs:e=1400,prefix:r="",suffix:n="",className:i,delayMs:a=0}){const[c,d]=N.useState(0),p=N.useRef(null);return N.useEffect(()=>{if(!Number.isFinite(t))return;let l=0;const g=0,v=T=>1-Math.pow(1-T,3),E=setTimeout(()=>{const T=j=>{l||(l=j);const P=j-l,C=Math.min(1,P/e);d(Math.round(g+(t-g)*v(C))),C<1&&(p.current=requestAnimationFrame(T))};p.current=requestAnimationFrame(T)},a);return()=>{clearTimeout(E),p.current&&cancelAnimationFrame(p.current)}},[t,e,a]),s.jsxs("span",{className:i,children:[r,c.toLocaleString(),n]})}function out({low:t,likely:e,high:r,defaultMortgage:n=0,defaultCommissionPct:i=6,defaultClosingPct:a=1}){const[c,d]=N.useState(e),[p,l]=N.useState(n),[g,v]=N.useState(i),[E,T]=N.useState(a),{commission:j,closing:P,net:C}=N.useMemo(()=>{const F=Math.round(c*g/100),$=Math.round(c*E/100);return{commission:F,closing:$,net:Math.max(0,c-F-$-(p||0))}},[c,g,E,p]),L=F=>`$${F.toLocaleString()}`,O=r>t?(c-t)/(r-t)*100:50;return s.jsxs(wi,{className:"overflow-hidden border-primary/20",children:[s.jsxs("div",{className:"bg-gradient-to-br from-primary/5 to-primary/10 px-6 pt-6 pb-4 border-b border-primary/10",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(iA,{className:"w-4 h-4 text-primary"}),s.jsx("span",{className:"text-xs uppercase tracking-widest font-semibold text-primary",children:"Your Price Story"})]}),s.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"What if you priced it at…"}),s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Drag the price. Watch your estimated walk-away update in real-time."})]}),s.jsxs(Di,{className:"p-6 space-y-6",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-end justify-between mb-3",children:[s.jsx("span",{className:"text-xs text-muted-foreground",children:"List price"}),s.jsx("span",{className:"text-3xl font-bold tabular-nums",children:L(c)})]}),s.jsxs("div",{className:"relative",children:[s.jsx(dj,{value:[c],min:t,max:r,step:1e3,onValueChange:([F])=>d(F)}),s.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[s.jsx("span",{children:L(t)}),s.jsxs("span",{children:["Suggested ",L(e)]}),s.jsx("span",{children:L(r)})]})]}),s.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:s.jsx("div",{className:"h-full bg-gradient-to-r from-emerald-500 via-primary to-amber-500 transition-all",style:{width:`${Math.min(100,Math.max(0,O))}%`}})})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Mortgage payoff"}),s.jsx(hn,{type:"number",inputMode:"numeric",value:p||"",placeholder:"$0",onChange:F=>l(Number(F.target.value)||0)})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Commission %"}),s.jsx(hn,{type:"number",step:"0.25",value:g,onChange:F=>v(Number(F.target.value)||0)})]}),s.jsxs("div",{children:[s.jsx(sn,{className:"text-xs",children:"Closing costs %"}),s.jsx(hn,{type:"number",step:"0.25",value:E,onChange:F=>T(Number(F.target.value)||0)})]})]}),s.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[s.jsxs("div",{className:"px-5 py-4 grid grid-cols-2 gap-y-2 text-sm",children:[s.jsx("span",{className:"text-muted-foreground",children:"Sale price"}),s.jsx("span",{className:"text-right tabular-nums font-medium",children:L(c)}),s.jsxs("span",{className:"text-muted-foreground",children:["Commission (",g,"%)"]}),s.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",L(j)]}),s.jsxs("span",{className:"text-muted-foreground",children:["Closing (",E,"%)"]}),s.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",L(P)]}),p>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-muted-foreground",children:"Mortgage payoff"}),s.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",L(p)]})]})]}),s.jsxs("div",{className:"bg-gradient-to-r from-emerald-500/10 to-primary/10 px-5 py-4 border-t flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(tK,{className:"w-5 h-5 text-emerald-600"}),s.jsx("span",{className:"font-semibold",children:"Your estimated walk-away"})]}),s.jsx("span",{className:"text-2xl font-bold tabular-nums text-emerald-700",children:L(C)})]})]}),s.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"This is a rough estimate to help you think through pricing. Actual proceeds depend on title fees, prorations, repairs, and other items your agent will walk through in detail."})]})]})}function zAe({tokenOverride:t}={}){var Bt,cr,ft,Kt,ir,Gr,tr,Qt,zt,Vr,Jr,Fn;const e=Sg(),r=t??e.token,[n,i]=N.useState(null),[a,c]=N.useState(null),[d,p]=N.useState([]),[l,g]=N.useState(!0),[v,E]=N.useState(""),[T,j]=N.useState(""),[P,C]=N.useState(""),[L,O]=N.useState(!1),[F,$]=N.useState(!1),[G,W]=N.useState(null),[Z,Q]=N.useState(null),[ee,ie]=N.useState(!1),{toast:oe}=c_e();N.useEffect(()=>{r&&(async()=>{const{data:Ar}=await Be.from("cmas").select("*").eq("share_token",r).eq("status","shared").maybeSingle();if(!Ar){g(!1);return}i(Ar);const[{data:Tn},{data:mn}]=await Promise.all([Be.from("cma_comps").select("*").eq("cma_id",Ar.id).order("position"),Be.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",Ar.agent_id).maybeSingle()]);p((Tn||[]).filter(Lr=>Lr.selected)),c(mn);const li=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",li),await Be.from("cma_views").insert({cma_id:Ar.id,visitor_token:li,user_agent:navigator.userAgent}),g(!1)})()},[r]);const pe=async Ar=>{if(!n)return;const Tn=localStorage.getItem("cma_visitor_token")||"";await Be.from("cma_views").insert({cma_id:n.id,visitor_token:Tn,reactions:{[Ar]:!0}}),Be.functions.invoke("cma-reply-notify",{body:{shareToken:r,reaction:Ar,visitorToken:Tn}}).catch(()=>{}),oe({title:"Thanks — your agent just got notified ✨"})},Le=!(n!=null&&n.contact_id),be=async()=>{if(!n||!v.trim())return;if(Le&&(!T.trim()||!P.trim())){oe({title:"Please add your name and email",variant:"destructive"});return}O(!0);const Ar=localStorage.getItem("cma_visitor_token")||"",{data:Tn,error:mn}=await Be.functions.invoke("cma-reply-notify",{body:{shareToken:r,message:v,visitorToken:Ar,viewerName:T.trim()||void 0,viewerEmail:P.trim()||void 0}});if(O(!1),mn||!(Tn!=null&&Tn.success)){oe({title:"Could not send",description:(mn==null?void 0:mn.message)||(Tn==null?void 0:Tn.error),variant:"destructive"});return}E(""),$(!0),oe({title:"Message sent to your agent"})},Re=N.useMemo(()=>{const Ar=d.map(Tn=>{const mn=Tn.snapshot,li=(mn==null?void 0:mn.soldPrice)||(mn==null?void 0:mn.price);return li&&(mn!=null&&mn.sqft)?li/mn.sqft:null}).filter(Tn=>!!Tn).sort((Tn,mn)=>Tn-mn);return Ar.length?Math.round(Ar[Math.floor(Ar.length/2)]):null},[d]);if(l)return s.jsx("div",{className:"min-h-screen flex items-center justify-center",children:s.jsx(gh,{className:"w-8 h-8 animate-spin"})});if(!n)return s.jsx("div",{className:"min-h-screen flex items-center justify-center text-center p-6",children:s.jsxs("div",{children:[s.jsx(Do,{className:"w-12 h-12 mx-auto text-muted-foreground mb-4"}),s.jsx("h1",{className:"text-xl font-semibold",children:"CMA not found"}),s.jsx("p",{className:"text-muted-foreground",children:"This report may have been removed or unpublished."})]})});const Ie=n.subject||{},Te=(Bt=n.settings)==null?void 0:Bt.personalVideo,ge=(cr=Ie.photos)==null?void 0:cr[0],$e=n.contact_first_name?n.contact_first_name:null,we=((a==null?void 0:a.name)||"A").split(" ").map(Ar=>Ar[0]).slice(0,2).join("").toUpperCase(),ke=a!=null&&a.phone?`tel:${String(a.phone).replace(/[^\d+]/g,"")}`:null,Ae=a!=null&&a.email?`mailto:${a.email}`:null,He=a!=null&&a.phone?`sms:${String(a.phone).replace(/[^\d+]/g,"")}`:null,ot=n.price_low??null,nt=n.price_likely??null,tt=n.price_high??null,vt=ot&&nt&&tt,Vt=nt&&Ie.sqft?Math.round(nt/Ie.sqft):null,Ct=Vt&&Re?Math.round((Vt-Re)/Re*100):null;return s.jsxs("div",{className:"min-h-screen bg-background pb-28 md:pb-0",children:[a&&s.jsx("div",{className:"border-b bg-card sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:s.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-6 py-3 flex items-center gap-3",children:[a.avatar_url?s.jsx("img",{src:a.avatar_url,alt:a.name,className:"w-10 h-10 rounded-full object-cover ring-2 ring-primary/20"}):s.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center font-semibold text-primary text-sm",children:we}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"font-semibold leading-tight truncate text-sm",children:a.name}),(a.title||a.brokerage_name)&&s.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-1 truncate",children:[a.brokerage_name&&s.jsx(jl,{className:"w-3 h-3 shrink-0"}),s.jsx("span",{className:"truncate",children:[a.title,a.brokerage_name].filter(Boolean).join(" · ")})]})]}),s.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[ke&&s.jsx(Jt,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:ke,children:[s.jsx(Ui,{className:"w-4 h-4 mr-1"}),"Call"]})}),Ae&&s.jsx(Jt,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs("a",{href:Ae,children:[s.jsx(rs,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),s.jsxs("div",{className:"relative overflow-hidden",children:[ge?s.jsxs("div",{className:"absolute inset-0",children:[s.jsx("img",{src:ge,alt:Ie.address,className:"w-full h-full object-cover scale-110 animate-[kenburns_18s_ease-out_infinite_alternate]",style:{animation:"kenburns 22s ease-in-out infinite alternate"}}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),s.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),s.jsx("div",{className:"relative container mx-auto max-w-6xl px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-24",children:s.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[s.jsxs("div",{className:`${Te!=null&&Te.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[s.jsxs(Js,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[s.jsx(va,{className:"w-3 h-3 mr-1"}),$e?`Prepared for ${$e}`:n.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),s.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:Ie.address}),s.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[s.jsx(Va,{className:"w-4 h-4"}),Ie.city,", ",Ie.state," ",Ie.zip]}),vt&&s.jsxs("div",{className:"mt-8 md:mt-10",children:[s.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-white/60 mb-2",children:"Estimated Value"}),s.jsx("div",{className:"flex items-baseline gap-4 flex-wrap",children:s.jsx("div",{className:"text-5xl md:text-7xl font-bold tabular-nums",children:s.jsx(zD,{to:nt,prefix:"$",durationMs:1600,delayMs:250})})}),s.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[s.jsxs("div",{children:[s.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),s.jsx("span",{className:"tabular-nums font-medium",children:s.jsx(zD,{to:ot,prefix:"$",delayMs:500})})]}),s.jsx("div",{className:"h-8 w-px bg-white/20"}),s.jsxs("div",{children:[s.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Likely"}),s.jsx("span",{className:"tabular-nums font-medium",children:s.jsx(zD,{to:nt,prefix:"$",delayMs:650})})]}),s.jsx("div",{className:"h-8 w-px bg-white/20"}),s.jsxs("div",{children:[s.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),s.jsx("span",{className:"tabular-nums font-medium",children:s.jsx(zD,{to:tt,prefix:"$",delayMs:800})})]})]})]})]}),(Te==null?void 0:Te.url)&&s.jsx("div",{className:"md:col-span-2 animate-scale-in",children:s.jsxs("button",{onClick:()=>ie(!0),className:"group relative w-full aspect-[4/5] md:aspect-[4/5] rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/20 bg-black",children:[Te.thumb?s.jsx("img",{src:Te.thumb,alt:"",className:"w-full h-full object-cover"}):s.jsx("video",{src:Te.url,className:"w-full h-full object-cover",muted:!0,playsInline:!0,preload:"metadata"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-black/10 group-hover:from-black/40 transition-colors"}),s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white",children:[s.jsx("div",{className:"w-16 h-16 md:w-20 md:h-20 rounded-full bg-white/95 text-primary flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform",children:s.jsx(h5e,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),s.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((ft=a==null?void 0:a.name)==null?void 0:ft.split(" ")[0])||"your agent"]})]})]})})]})})]}),ee&&(Te==null?void 0:Te.url)&&s.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>ie(!1),children:s.jsxs("div",{className:"relative w-full max-w-4xl",onClick:Ar=>Ar.stopPropagation(),children:[s.jsx("video",{src:Te.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),s.jsx(Jt,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>ie(!1),children:"Close"})]})}),s.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-8 py-10 md:py-16 space-y-10 md:space-y-14",children:[s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 -mt-20 md:-mt-24 relative z-10",children:[{label:"Beds",value:Ie.bedrooms??"—"},{label:"Baths",value:Ie.bathrooms??"—"},{label:"Sq Ft",value:((Kt=Ie.sqft)==null?void 0:Kt.toLocaleString())??"—"},{label:"Year Built",value:Ie.yearBuilt??"—"}].map((Ar,Tn)=>s.jsx(wi,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${Tn*80}ms`},children:s.jsxs(Di,{className:"p-4 md:p-6 text-center",children:[s.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:Ar.value}),s.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:Ar.label})]})},Tn))}),((Gr=(ir=n.settings)==null?void 0:ir.priceOverride)==null?void 0:Gr.enabled)&&((Qt=(tr=n.settings)==null?void 0:tr.priceOverride)==null?void 0:Qt.note)&&s.jsx(wi,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:s.jsxs(Di,{className:"p-6 md:p-8",children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"A note from your agent"}),s.jsx("p",{className:"text-base md:text-lg leading-relaxed whitespace-pre-wrap text-foreground/90",children:n.settings.priceOverride.note})]})}),vt&&s.jsx(out,{low:ot,likely:nt,high:tt}),Re&&Vt&&s.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[s.jsx(wi,{className:"md:col-span-2",children:s.jsxs(Di,{className:"p-6 md:p-8",children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Why this price"}),s.jsx("h2",{className:"text-2xl md:text-3xl font-bold mb-3",children:"The market is talking."}),s.jsxs("p",{className:"text-muted-foreground leading-relaxed",children:["Based on ",s.jsxs("strong",{className:"text-foreground",children:[d.length," comparable ",d.length===1?"home":"homes"]})," in ",Ie.city,", the median sale rate is ",s.jsxs("strong",{className:"text-foreground",children:["$",Re,"/sqft"]}),". Applied to your home's ",(zt=Ie.sqft)==null?void 0:zt.toLocaleString()," sqft, the comps support a value near ",s.jsxs("strong",{className:"text-foreground",children:["$",(Re*(Ie.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),s.jsx(wi,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:s.jsxs(Di,{className:"p-6 md:p-8 h-full flex flex-col justify-center",children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground mb-1",children:"Your home"}),s.jsxs("div",{className:"text-3xl font-bold tabular-nums",children:["$",Vt,s.jsx("span",{className:"text-base font-normal text-muted-foreground",children:"/sqft"})]}),s.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Neighborhood avg: ",s.jsxs("span",{className:"font-medium text-foreground",children:["$",Re,"/sqft"]})]}),Ct!==null&&Ct!==0&&s.jsxs("p",{className:`text-sm font-medium mt-1 ${Ct>0?"text-emerald-600":"text-rose-600"}`,children:[Ct>0?"▲":"▼"," ",Math.abs(Ct),"% ",Ct>0?"above":"below"," the median"]})]})})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold",children:"Homes like yours"}),s.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"The Comparables"})]}),s.jsxs(Js,{variant:"outline",className:"text-xs",children:[d.length," comps"]})]}),s.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:d.map((Ar,Tn)=>{var Lr;const mn=Ar.snapshot,li=mn.soldPrice||mn.price;return s.jsxs(wi,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${Z===Tn?"ring-2 ring-primary":""}`,style:{animationDelay:`${Tn*60}ms`},onClick:()=>W(Tn),onMouseEnter:()=>Q(Tn),onMouseLeave:()=>Q(null),children:[s.jsxs("div",{className:"relative",children:[s.jsx(L9,{photos:mn.photos,className:"w-full h-44"}),s.jsxs(Js,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",Tn+1]}),s.jsx(Js,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:mn.status})]}),s.jsxs(Di,{className:"p-4",children:[s.jsx("div",{className:"font-semibold leading-tight truncate",children:mn.address}),s.jsxs("div",{className:"text-xs text-muted-foreground",children:[mn.city,", ",mn.state]}),s.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:s.jsxs("span",{className:"text-muted-foreground",children:[mn.bedrooms??"?","bd · ",mn.bathrooms??"?","ba · ",((Lr=mn.sqft)==null?void 0:Lr.toLocaleString())??"?"," sqft"]})}),s.jsxs("div",{className:"flex justify-between items-center mt-3 pt-3 border-t",children:[s.jsxs("span",{className:"text-xl font-bold tabular-nums",children:["$",li==null?void 0:li.toLocaleString()]}),mn.sqft&&li?s.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(li/mn.sqft),"/sqft"]}):null]})]})]},Tn)})})]}),s.jsx(aut,{comp:G!==null?(Vr=d[G])==null?void 0:Vr.snapshot:null,open:G!==null,onClose:()=>W(null)}),s.jsx(wi,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:s.jsxs(Di,{className:"p-6 md:p-8 space-y-5",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-1",children:"Your turn"}),s.jsxs("h2",{className:"text-2xl md:text-3xl font-bold",children:["What do you think",$e?`, ${$e}`:"","?"]}),s.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((Jr=a==null?void 0:a.name)==null?void 0:Jr.split(" ")[0])||"Your agent"," hears you instantly."]})]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:cg,label:"I love this price"},{kind:"fair",icon:S5e,label:"Seems fair"},{kind:"lower",icon:gve,label:"I'd price lower"},{kind:"higher",icon:iA,label:"I'd price higher"},{kind:"ready_to_list",icon:Pq,label:"Ready to list"},{kind:"want_walkthrough",icon:E4,label:"Want a walkthrough"},{kind:"need_time",icon:Cl,label:"Need more time"},{kind:"have_questions",icon:q4e,label:"I have questions"}].map(({kind:Ar,icon:Tn,label:mn})=>s.jsxs(Jt,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>pe(Ar),children:[s.jsx(Tn,{className:"w-4 h-4 mr-2"}),mn]},Ar))}),s.jsxs("div",{className:"pt-4 border-t",children:[s.jsxs("p",{className:"text-sm font-medium mb-2 flex items-center gap-1",children:[s.jsx(nT,{className:"w-4 h-4"}),"Ask your agent a question"]}),F?s.jsxs("div",{className:"rounded-md bg-emerald-50 border border-emerald-200 p-4 text-sm text-emerald-800 animate-fade-in",children:["✓ Sent! ",((Fn=a==null?void 0:a.name)==null?void 0:Fn.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):s.jsxs(s.Fragment,{children:[Le&&s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[s.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:T,onChange:Ar=>j(Ar.target.value)}),s.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:P,onChange:Ar=>C(Ar.target.value)})]}),s.jsx("textarea",{className:"w-full border rounded-md p-3 text-sm min-h-[100px] bg-background",placeholder:"What questions do you have about this analysis?",value:v,onChange:Ar=>E(Ar.target.value)}),s.jsx(Jt,{onClick:be,disabled:!v.trim()||L,className:"mt-2",children:L?"Sending…":"Send to agent"})]})]})]})}),a&&s.jsx(wi,{className:"overflow-hidden border-primary/20",children:s.jsx("div",{className:"bg-gradient-to-br from-primary/10 to-primary/5 p-6 md:p-10",children:s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 items-start",children:[a.avatar_url?s.jsx("img",{src:a.avatar_url,alt:a.name,className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl object-cover ring-4 ring-background shadow-lg"}):s.jsx("div",{className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl bg-primary/20 flex items-center justify-center text-3xl font-bold text-primary ring-4 ring-background shadow-lg",children:we}),s.jsxs("div",{className:"flex-1",children:[s.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground",children:"Prepared by"}),s.jsx("h2",{className:"text-2xl md:text-3xl font-bold mt-1",children:a.name}),(a.title||a.brokerage_name)&&s.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:[a.title,a.brokerage_name].filter(Boolean).join(" · ")}),a.bio&&s.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:a.bio}),s.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[ke&&s.jsx(Jt,{asChild:!0,children:s.jsxs("a",{href:ke,children:[s.jsx(Ui,{className:"w-4 h-4 mr-2"}),a.phone]})}),Ae&&s.jsx(Jt,{variant:"outline",asChild:!0,children:s.jsxs("a",{href:Ae,children:[s.jsx(rs,{className:"w-4 h-4 mr-2"}),"Email"]})}),a.website_url&&s.jsx(Jt,{variant:"outline",asChild:!0,children:s.jsxs("a",{href:a.website_url,target:"_blank",rel:"noreferrer",children:[s.jsx(rT,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),a&&(ke||He||Ae)&&s.jsxs("div",{className:"md:hidden fixed bottom-0 left-0 right-0 bg-card/95 backdrop-blur border-t shadow-2xl z-50 px-3 py-3 flex gap-2",style:{paddingBottom:"calc(0.75rem + env(safe-area-inset-bottom))"},children:[ke&&s.jsx(Jt,{className:"flex-1",asChild:!0,children:s.jsxs("a",{href:ke,children:[s.jsx(Ui,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),He&&s.jsx(Jt,{variant:"outline",className:"flex-1",asChild:!0,children:s.jsxs("a",{href:He,children:[s.jsx(nT,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),Ae&&s.jsx(Jt,{variant:"outline",className:"flex-1",asChild:!0,children:s.jsxs("a",{href:Ae,children:[s.jsx(rs,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}const lut=Object.freeze(Object.defineProperty({__proto__:null,default:zAe},Symbol.toStringTag,{value:"Module"}));function cut(){const e=ms().pathname.slice(1).replace(/\/$/,"");return!e||e.includes("/")?s.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"CMA Portal"}),s.jsx("p",{className:"text-slate-500",children:"Open your CMA link to view your personalized market analysis."})]})}):s.jsx(zAe,{tokenOverride:e})}const D9="levelup_affiliate_ref",uut=30,dut=()=>{const[t]=zv();N.useEffect(()=>{const e=t.get("ref");if(e){const r={code:e.toUpperCase(),timestamp:Date.now()};localStorage.setItem(D9,JSON.stringify(r)),console.log("[Affiliate] Stored referral code:",e)}},[t])},hut=()=>{try{const t=localStorage.getItem(D9);if(!t)return null;const e=JSON.parse(t),r=uut*24*60*60*1e3;return Date.now()-e.timestamp>r?(localStorage.removeItem(D9),console.log("[Affiliate] Referral code expired"),null):e.code}catch{return null}},fue="/assets/levelup-logo-header-_ZX7DvlA.png",fut="/assets/scale-your-team-ku4MPatU.png";function mut({open:t,onOpenChange:e}){return s.jsx(gl,{open:t,onOpenChange:e,children:s.jsxs(Jo,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[s.jsx(Bc,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 bg-[#4a6b6d]/10 rounded-lg",children:s.jsx(jl,{className:"h-5 w-5 text-[#4a6b6d]"})}),s.jsxs("div",{children:[s.jsx(pc,{children:"Schedule a Brokerage Interest Meeting"}),s.jsx(sf,{children:"Learn how LevelUp can empower your entire team"})]})]})}),t&&s.jsx("iframe",{src:"https://booking.relevelup.com/jeremy-collins",className:"w-full border-0 rounded-lg",style:{height:"600px",minHeight:"500px"},title:"Schedule Brokerage Interest Meeting"})]})})}const $Ae="/assets/mission_control-BJ-Kz8rX.png",put="/assets/crm-CsLftmB2.png",gut="/assets/deal_pipeline-XYgypvwv.png",yut="/assets/staging_studio-5iLDjnv0.png",xut="/assets/coaching-CSQEA81I.png",_ut="/assets/marketing_studio-Brx1ZOnN.png",vut=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:$Ae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:put},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:gut},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:yut},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:xut},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:_ut}];function but({slot:t}){return s.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[s.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),s.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),t.src?s.jsx("img",{src:t.src,alt:`LevelUp ${t.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):s.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[s.jsx(va,{className:"h-8 w-8 text-white/40"}),s.jsx("p",{className:"text-sm font-medium text-white/60",children:t.label}),s.jsx("p",{className:"text-xs px-6 text-center text-white/40",children:"Screenshot placeholder"})]}),s.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[s.jsx("span",{className:"font-semibold text-white",children:t.label})," — ",t.caption]})]})}const Ef={individual_agent:{name:"Individual Agent",price:"$39",period:"/month",description:"Perfect for independent agents ready to level up",features:["Full dashboard access","300+ professional templates","Academy training library","Community & networking","Live events & workshops","Social media content","Newsletter resources","Email support"],trial:"7-day free trial"},brokerage_over_25:{name:"Brokerage",subtitle:"Unlimited Agents",price:"$499",period:"/month",description:"Scale your brokerage without limits",features:["Everything in Individual, plus:","Unlimited agents","Brokerage manager dashboard","Exclusive brokerage resources","Team performance analytics","Agent onboarding tools","Resource sharing","Priority support"]}},wut=[{icon:YW,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:A4,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:Cl,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:nT,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:lg,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Jm,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],Sut=[{category:"Marketing Studio",icon:NP,items:["Weekly Reels scripts","Social Post Generator","300+ Canva templates","Marketing Calendar","Postcard Direct Mail","Listing Music Videos","Social Swag drops"]},{category:"Lead Generation",icon:eK,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:n5e,items:["Agent OS CRM","Deal pipeline","Forms & e-signatures","Client portal","Smart follow-up queue","Lead ponds for teams","Google Business reviews"]},{category:"AI & Media",icon:k5e,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:Hj,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:jl,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],Eut=[{icon:Dc,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:va,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Ui,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:U4e,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Va,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Gj,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:cg,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:aF,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],Tut=[{name:"Sarah M.",role:"Top Producer, RE/MAX",quote:"LevelUp completely transformed how I run my business. The templates alone save me hours every week."},{name:"Mike T.",role:"Brokerage Owner",quote:"Onboarding new agents used to take weeks. Now they're productive from day one with all the training resources."},{name:"Jessica L.",role:"Team Lead",quote:"The community is incredible. I've learned more from other agents here than any conference I've attended."}],Aut=()=>{const{user:t,loading:e}=_i(),r=qa(),[n]=zv();N.useEffect(()=>{const Z=window.location.host==="listings.relevelup.com",Q=window.location.pathname==="/";if(Z&&Q){r("/public/listings",{replace:!0});return}},[r]);const[i,a]=N.useState(null),[c,d]=N.useState(null),[p,l]=N.useState(!1),[g,v]=N.useState(""),[E,T]=N.useState(""),[j,P]=N.useState(""),[C,L]=N.useState(!1),[O,F]=N.useState(!1),$=(Z,Q=!1)=>{d({tier:Z,skipTrial:Q}),l(!0)};dut(),N.useEffect(()=>{const Z=window.location.host==="listings.relevelup.com",Q=location.pathname.startsWith("/public/");!e&&t&&!Z&&!Q&&r("/dashboard")},[t,e,r,location.pathname]),N.useEffect(()=>{n.get("canceled")==="true"&&lr.error("Checkout was canceled. Feel free to try again when you're ready!")},[n]);const G=async(Z,Q=!1)=>{if(!g){lr.error("Please enter your email address");return}if(!E.trim()){lr.error("Please enter your full name");return}L(!0),a(Z+(Q?"_direct":""));const ee=hut();try{const{data:ie,error:oe}=await Be.functions.invoke("create-checkout",{body:{tier:Z,email:g,name:E.trim(),couponCode:j.trim()||void 0,skipTrial:Q,referralCode:ee}});if(oe)throw oe;if(ie!=null&&ie.url)window.open(ie.url,"_blank","noopener,noreferrer"),lr.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(ie){console.error("Checkout error:",ie),lr.error(ie.message||"Failed to start checkout. Please try again.")}finally{L(!1),a(null),l(!1),d(null)}},W=()=>{c&&G(c.tier,c.skipTrial)};return e?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#4a6b6d]",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-white border-t-transparent"})}):s.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[s.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:s.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[s.jsx("div",{className:"flex items-center",children:s.jsx("img",{src:fue,alt:"LevelUp",className:"h-8 md:h-10"})}),s.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[s.jsx(Jt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var Z;return(Z=document.getElementById("features"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},children:"Features"}),s.jsx(Jt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var Z;return(Z=document.getElementById("pricing"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),s.jsx(Jt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>r("/brokerage-solutions"),children:"For Brokerages"}),s.jsx(Jt,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>r("/blog"),children:"Blog"}),s.jsx(Jt,{onClick:()=>r("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),s.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[s.jsx("style",{children:` @keyframes hero-float { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-12px); } } @keyframes hero-float-slow { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-8px); } } @keyframes hero-glow { 0%,100% { opacity: 0.55; } 50% { opacity: 0.9; } } `}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),s.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 h-[560px] w-[900px] rounded-full bg-[#4aa8a0]/25 blur-[140px] animate-[hero-glow_7s_ease-in-out_infinite]"}),s.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),s.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),s.jsx("div",{className:"absolute inset-0 opacity-[0.12] bg-[linear-gradient(to_right,rgba(255,255,255,0.5)_1px,transparent_1px),linear-gradient(to_bottom,rgba(255,255,255,0.5)_1px,transparent_1px)] bg-[size:56px_56px] [mask-image:radial-gradient(ellipse_75%_65%_at_50%_35%,black,transparent)]"}),s.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),s.jsxs("div",{className:"container mx-auto px-4 relative",children:[s.jsxs("div",{className:"max-w-5xl mx-auto text-center pt-20 md:pt-28 pb-10 space-y-8",children:[s.jsx("div",{className:"flex justify-center animate-fade-in",children:s.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 backdrop-blur-sm px-4 py-1.5 text-xs md:text-sm font-semibold tracking-wide text-white/85 shadow-lg",children:[s.jsx(va,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"The Agent Operating System — coaching, CRM & marketing in one"]})}),s.jsxs("h1",{className:"text-4xl sm:text-5xl md:text-7xl font-sans font-bold tracking-tight text-white leading-[1.05] animate-fade-in",children:["The tools you need",s.jsx("br",{className:"hidden sm:block"})," to get it done.",s.jsx("span",{className:"block mt-3 bg-gradient-to-r from-[#8fe0d6] via-[#5cc0b6] to-[#e6c878] bg-clip-text text-transparent",children:"The platform to keep it going."})]}),s.jsx("p",{className:"text-base md:text-xl text-white/65 max-w-2xl mx-auto leading-relaxed animate-fade-in",children:"Weekly coaching, a smart CRM, done-for-you marketing and AI tools — everything a modern agent runs on, in one login."}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-2 animate-fade-in",children:[s.jsxs(Jt,{size:"lg",onClick:()=>{var Z;return(Z=document.getElementById("free-trial"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#122c3a] hover:bg-white/90 shadow-[0_0_40px_-8px_rgba(140,220,210,0.6)] transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",s.jsx(lo,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),s.jsx(Jt,{size:"lg",variant:"outline",onClick:()=>{var Z;return(Z=document.getElementById("features"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white/40 text-white bg-white/5 backdrop-blur-sm hover:bg-white hover:text-[#122c3a] rounded-full",children:"See What's Included"})]}),s.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-8 gap-y-3 pt-2 text-sm text-white/55 animate-fade-in",children:[s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(Bd,{className:"h-4 w-4 text-[#e6c878] fill-[#e6c878]"})," Built with agents' direct input"]}),s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(aF,{className:"h-4 w-4 text-[#7fd4cc]"})," New tools added every month"]}),s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx(Wj,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]})]})]}),s.jsxs("div",{className:"relative max-w-5xl mx-auto pb-20 md:pb-28 px-2",children:[s.jsx("div",{className:"absolute inset-x-8 top-10 bottom-0 rounded-[40px] bg-gradient-to-b from-[#4aa8a0]/30 to-transparent blur-2xl","aria-hidden":!0}),s.jsxs("div",{className:"relative animate-[hero-float-slow_8s_ease-in-out_infinite]",children:[s.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/15 bg-[#0d1f29]/80 backdrop-blur-md shadow-[0_40px_80px_-20px_rgba(0,0,0,0.7)]",children:[s.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2.5 border-b border-white/10 bg-white/5",children:[s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),s.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),s.jsx("img",{src:$Ae,alt:"LevelUp Agent Command Center dashboard",className:"w-full h-auto block"})]}),s.jsxs("div",{className:"hidden md:flex absolute -left-10 top-24 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_6s_ease-in-out_infinite]",children:[s.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#4aa8a0]/20",children:s.jsx(iA,{className:"h-5 w-5 text-[#7fd4cc]"})}),s.jsxs("span",{children:[s.jsx("span",{className:"block text-sm font-semibold text-white",children:"Smart Queue ready"}),s.jsx("span",{className:"block text-xs text-white/55",children:"5 follow-ups due today"})]})]}),s.jsxs("div",{className:"hidden md:flex absolute -right-10 top-1/2 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_7s_ease-in-out_infinite_1s]",children:[s.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#e6c878]/15",children:s.jsx(YW,{className:"h-5 w-5 text-[#e6c878]"})}),s.jsxs("span",{children:[s.jsx("span",{className:"block text-sm font-semibold text-white",children:"Weekly Reels delivered"}),s.jsx("span",{className:"block text-xs text-white/55",children:"Fresh scripts every Monday"})]})]}),s.jsxs("div",{className:"hidden md:flex absolute left-8 -bottom-6 items-center gap-3 rounded-2xl border border-white/15 bg-[#122c3a]/90 backdrop-blur-md px-4 py-3 shadow-2xl animate-[hero-float_6.5s_ease-in-out_infinite_0.5s]",children:[s.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-white/10",children:s.jsx(Cl,{className:"h-5 w-5 text-white/80"})}),s.jsxs("span",{children:[s.jsx("span",{className:"block text-sm font-semibold text-white",children:"Coaching booked"}),s.jsx("span",{className:"block text-xs text-white/55",children:"Meet link added automatically"})]})]})]})]})]})]}),s.jsx("section",{className:"py-20 bg-background",children:s.jsx("div",{className:"container mx-auto px-4",children:s.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[s.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),s.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[s.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),s.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),s.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[s.jsxs(Jt,{size:"lg",variant:"outline",onClick:()=>{var Z;return(Z=document.getElementById("brokerage"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[s.jsx(jl,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),s.jsxs(Jt,{size:"lg",onClick:()=>{var Z;return(Z=document.getElementById("pricing"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[s.jsx(nd,{className:"mr-2 h-5 w-5"}),"Individual Membership"]})]})]})})}),s.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:s.jsxs("div",{className:"container mx-auto px-4",children:[s.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[s.jsxs("span",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-semibold mb-5",children:[s.jsx(J4e,{className:"w-4 h-4"}),"40+ tools & counting"]}),s.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:wut.map((Z,Q)=>s.jsxs(wi,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[s.jsxs(Wh,{children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:s.jsx(Z.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),s.jsx(Kh,{className:"text-xl font-sans",children:Z.title})]}),s.jsx(Di,{children:s.jsx("p",{className:"text-muted-foreground leading-relaxed",children:Z.description})})]},Q))}),s.jsxs("div",{className:"mt-14 max-w-6xl mx-auto rounded-3xl bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] p-8 md:p-12 relative overflow-hidden shadow-2xl",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsxs("div",{className:"relative",children:[s.jsxs("div",{className:"text-center mb-10",children:[s.jsx("h3",{className:"text-2xl md:text-3xl font-bold text-white font-sans",children:"...and that's just the beginning"}),s.jsx("p",{className:"text-white/60 mt-2",children:"Dozens of purpose-built tools, all included with membership."})]}),s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-8",children:Sut.map(Z=>s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-white/10",children:s.jsx(Z.icon,{className:"h-4 w-4 text-white"})}),s.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-white/90",children:Z.category})]}),s.jsx("ul",{className:"space-y-2.5",children:Z.items.map(Q=>s.jsxs("li",{className:"flex items-center gap-2.5 text-white/70 text-sm",children:[s.jsx(ql,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),Q]},Q))})]},Z.category))}),s.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[s.jsx(va,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),s.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsxs("div",{className:"container mx-auto px-4 relative",children:[s.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-14",children:[s.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-white/70",children:"See it in action"}),s.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight font-sans",children:"A real platform, not another course"}),s.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto text-lg",children:"This is what members open every morning."})]}),s.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10 max-w-6xl mx-auto",children:vut.map(Z=>s.jsx(but,{slot:Z},Z.key))})]})]}),s.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsxs("div",{className:"container mx-auto px-4 relative",children:[s.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[s.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[s.jsx(va,{className:"w-4 h-4"}),"Included with Membership"]}),s.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",s.jsx("span",{className:"italic",children:"Agent OS"})]}),s.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:Eut.map((Z,Q)=>s.jsxs(wi,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[s.jsxs(Wh,{className:"pb-3",children:[s.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:s.jsx(Z.icon,{className:"w-6 h-6 text-white"})}),s.jsx(Kh,{className:"text-lg font-semibold text-white",children:Z.title})]}),s.jsx(Di,{children:s.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:Z.description})})]},Q))}),s.jsx("div",{className:"text-center mt-12",children:s.jsxs(Jt,{size:"lg",onClick:()=>{var Z;return(Z=document.getElementById("pricing"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"bg-white text-[#4a6b6d] hover:bg-white/90 shadow-xl transition-all hover:scale-105",children:["Get Agent OS with Your Membership",s.jsx(lo,{className:"ml-2 w-5 h-5"})]})})]})]}),s.jsx("section",{id:"brokerage",className:"py-20 bg-[#4a6b6d]/5",children:s.jsx("div",{className:"container mx-auto px-4",children:s.jsx("div",{className:"max-w-6xl mx-auto",children:s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium",children:[s.jsx(jl,{className:"w-4 h-4"}),"For Brokerages"]}),s.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"Give every agent on your team access to world-class training and resources. Track performance, streamline onboarding, and watch your brokerage thrive."}),s.jsx("ul",{className:"space-y-4",children:["Dedicated brokerage manager dashboard","Invite and manage agents with one click","Exclusive brokerage-only resources","Team analytics and performance tracking","Simplified agent onboarding","Share resources across your team"].map((Z,Q)=>s.jsxs("li",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center flex-shrink-0",children:s.jsx(ql,{className:"w-4 h-4 text-[#4a6b6d]"})}),s.jsx("span",{className:"text-foreground",children:Z})]},Q))}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[s.jsxs(Jt,{size:"lg",onClick:()=>{var Z;return(Z=document.getElementById("pricing"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",s.jsx(uf,{className:"ml-2 w-5 h-5"})]}),s.jsxs(Jt,{size:"lg",variant:"outline",onClick:()=>F(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[s.jsx(Cl,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),s.jsx("div",{className:"relative hidden md:block",children:s.jsx("img",{src:fut,alt:"Scale Your Team from 5 to 500 Agents",className:"w-full rounded-3xl shadow-lg"})})]})})})}),s.jsx("section",{className:"py-20 bg-background",children:s.jsxs("div",{className:"container mx-auto px-4",children:[s.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[s.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Agents Love ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"LevelUp"})]}),s.jsx("p",{className:"text-lg text-muted-foreground",children:"See what top producers are saying about the platform."})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto",children:Tut.map((Z,Q)=>s.jsx(wi,{className:"bg-muted/30 border-0",children:s.jsxs(Di,{className:"pt-8",children:[s.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(ee=>s.jsx(Bd,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},ee))}),s.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',Z.quote,'"']}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold",children:Z.name}),s.jsx("p",{className:"text-sm text-muted-foreground",children:Z.role})]})]})},Q))})]})}),s.jsxs("section",{id:"free-trial",className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsx("div",{className:"container mx-auto px-4 relative",children:s.jsxs("div",{className:"max-w-3xl mx-auto text-center space-y-8",children:[s.jsxs("h2",{className:"text-3xl md:text-5xl font-bold text-white",children:["Start Your Free Trial ",s.jsx("span",{className:"italic",children:"Today"})]}),s.jsx("p",{className:"text-lg md:text-xl text-white/80 leading-relaxed",children:"Get instant access to 7 days of trainings, templates, and tools — designed to give you quick wins now and resources you'll keep forever."}),s.jsx("div",{className:"pt-4",children:s.jsxs(Jt,{size:"lg",className:"px-12 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",onClick:()=>$("individual_agent"),children:["Start Free Trial",s.jsx(lo,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),s.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:s.jsxs("div",{className:"container mx-auto px-4",children:[s.jsxs("div",{className:"text-center mb-16",children:[s.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),s.jsx("p",{className:"text-lg text-muted-foreground max-w-2xl mx-auto",children:"Choose the plan that fits your needs. All plans include everything you need to succeed."})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8 max-w-4xl mx-auto",children:[s.jsxs(wi,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[s.jsxs(Wh,{className:"pb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/10 flex items-center justify-center",children:s.jsx(nd,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsx(Kh,{className:"text-xl font-sans",children:Ef.individual_agent.name})]}),s.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[s.jsx("span",{className:"text-5xl font-bold",children:Ef.individual_agent.price}),s.jsx("span",{className:"text-muted-foreground text-lg",children:Ef.individual_agent.period})]}),s.jsx(sC,{className:"text-base mt-2",children:Ef.individual_agent.description}),s.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-green-500/10 text-green-600 text-sm font-medium mt-4",children:[s.jsx(su,{className:"w-4 h-4"}),Ef.individual_agent.trial]})]}),s.jsx(Di,{className:"flex-1 pt-0",children:s.jsx("ul",{className:"space-y-3",children:Ef.individual_agent.features.map((Z,Q)=>s.jsxs("li",{className:"flex items-center gap-3",children:[s.jsx(ql,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),s.jsx("span",{children:Z})]},Q))})}),s.jsxs(IG,{className:"flex flex-col gap-3 pt-4",children:[s.jsx(Jt,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>$("individual_agent"),children:"Start Free Trial"}),s.jsx(Jt,{variant:"outline",className:"w-full rounded-full border-2 border-[#4a6b6d] text-[#4a6b6d] bg-white hover:bg-[#4a6b6d]/5 uppercase text-sm font-medium tracking-wide",onClick:()=>$("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),s.jsxs(wi,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl bg-background",children:[s.jsx("div",{className:"absolute -top-4 left-1/2 -translate-x-1/2 px-6 py-2 bg-[#4a6b6d] text-white text-sm font-semibold rounded-full shadow-lg",children:"Most Popular"}),s.jsxs(Wh,{className:"pb-4 pt-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/20 flex items-center justify-center",children:s.jsx(jl,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsxs("div",{children:[s.jsx(Kh,{className:"text-xl font-sans",children:Ef.brokerage_over_25.name}),s.jsx("span",{className:"text-sm text-muted-foreground",children:Ef.brokerage_over_25.subtitle})]})]}),s.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[s.jsx("span",{className:"text-5xl font-bold",children:Ef.brokerage_over_25.price}),s.jsx("span",{className:"text-muted-foreground text-lg",children:Ef.brokerage_over_25.period})]}),s.jsx(sC,{className:"text-base mt-2",children:Ef.brokerage_over_25.description})]}),s.jsx(Di,{className:"flex-1 pt-0",children:s.jsx("ul",{className:"space-y-3",children:Ef.brokerage_over_25.features.map((Z,Q)=>s.jsxs("li",{className:"flex items-center gap-3",children:[s.jsx(ql,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),s.jsx("span",{children:Z})]},Q))})}),s.jsxs(IG,{className:"pt-4 flex flex-col gap-3",children:[s.jsx(Jt,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>$("brokerage_over_25"),children:"Get Started"}),s.jsxs(Jt,{variant:"link",className:"text-[#4a6b6d]",onClick:()=>r("/brokerage-solutions"),children:["Explore all brokerage management tools ",s.jsx(lo,{className:"ml-1 w-4 h-4"})]})]})]})]})]})}),s.jsx("section",{id:"neutrality",className:"py-20 bg-background",children:s.jsx("div",{className:"container mx-auto px-4",children:s.jsxs("div",{className:"max-w-4xl mx-auto",children:[s.jsxs("div",{className:"text-center mb-12",children:[s.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium mb-4",children:[s.jsx(Wj,{className:"w-4 h-4"}),"Our Commitment"]}),s.jsxs("h2",{className:"text-3xl md:text-4xl font-sans font-bold",children:["LevelUp Brokerage ",s.jsx("span",{className:"italic text-[#4a6b6d]",children:"Neutrality Policy"})]}),s.jsx("p",{className:"text-lg text-muted-foreground mt-4 max-w-2xl mx-auto",children:"We are committed to being a trusted, independent partner for every agent and brokerage."})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[s.jsx(wi,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:s.jsxs(Di,{className:"p-6 flex items-start gap-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:s.jsx(jl,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),s.jsx(wi,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:s.jsxs(Di,{className:"p-6 flex items-start gap-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:s.jsx(xv,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not share member information with any brokerage."})]})}),s.jsx(wi,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:s.jsxs(Di,{className:"p-6 flex items-start gap-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:s.jsx(E5e,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not recruit brokerage partners' agents."})]})}),s.jsx(wi,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:s.jsxs(Di,{className:"p-6 flex items-start gap-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:s.jsx(lg,{className:"w-5 h-5 text-[#4a6b6d]"})}),s.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not use LevelUp events, trainings, webinars, CRM data, or member lists for recruiting purposes."})]})})]})]})})}),s.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 opacity-10",children:s.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),s.jsx("div",{className:"container mx-auto px-4 relative",children:s.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[s.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),s.jsx("p",{className:"text-lg text-white/80 max-w-2xl mx-auto",children:"Join thousands of agents who are closing more deals, saving time, and growing their business with LevelUp."}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[s.jsxs(Jt,{size:"lg",onClick:()=>{var Z;return(Z=document.getElementById("pricing"))==null?void 0:Z.scrollIntoView({behavior:"smooth"})},className:"px-10 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105",children:["Start Your Free Trial",s.jsx(lo,{className:"ml-2 w-5 h-5"})]}),s.jsx(Jt,{size:"lg",onClick:()=>r("/auth"),className:"px-10 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#4a6b6d]",children:"Sign In"})]})]})})]}),s.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:s.jsx("div",{className:"container mx-auto px-4",children:s.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[s.jsx("img",{src:fue,alt:"LevelUp",className:"h-8"}),s.jsxs("p",{className:"text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsx("a",{href:"/brokerage-solutions",className:"text-white/60 hover:text-white transition-colors text-sm",children:"For Brokerages"}),s.jsx("a",{href:"/blog",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Blog"}),s.jsx("a",{href:"/privacy-policy",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Privacy Policy"}),s.jsx("a",{href:"mailto:support@relevelup.com",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Contact Support"})]})]})})}),s.jsx(mut,{open:O,onOpenChange:F}),s.jsx(gl,{open:p,onOpenChange:l,children:s.jsxs(Jo,{className:"sm:max-w-md",children:[s.jsxs(Bc,{children:[s.jsx(pc,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),s.jsx(sf,{children:(c==null?void 0:c.tier)==="individual_agent"&&!(c!=null&&c.skipTrial)?"Start your 7-day free trial":(c==null?void 0:c.tier)==="individual_agent"?"Subscribe to Individual Agent":"Subscribe to Brokerage"})]}),s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("div",{children:[s.jsxs(sn,{htmlFor:"dialog-name",children:["Full Name ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx(hn,{id:"dialog-name",type:"text",placeholder:"John Smith",value:E,onChange:Z=>T(Z.target.value),className:"mt-1",required:!0})]}),s.jsxs("div",{children:[s.jsxs(sn,{htmlFor:"dialog-email",children:["Email Address ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx(hn,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:g,onChange:Z=>v(Z.target.value),className:"mt-1",required:!0})]}),s.jsxs("div",{children:[s.jsxs(sn,{htmlFor:"dialog-coupon",children:["Discount Code ",s.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),s.jsx(hn,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:j,onChange:Z=>P(Z.target.value),className:"mt-1"})]})]}),s.jsx(Jt,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:W,disabled:C,children:C?"Loading...":"Continue to Checkout"})]})})]})},kut="/__l5e/assets-v1/68014836-514e-4076-834c-9b66112cd2a0/levelup-logo-horizontal.png",Iut=Gv({email:Us().email("Invalid email address"),password:Us().min(6,"Password must be at least 6 characters")}),UAe="https://dashboard.relevelup.com",$D="/oauth-connect",jut=`${UAe}/profile?reset=true`,hO="levelupOAuthRouteHistory";function mue(t){return t.startsWith("/")&&!t.startsWith("//")&&!t.includes("://")}function Cut(t){const e=Date.now(),r=15e3;try{const a=[...JSON.parse(sessionStorage.getItem(hO)??"[]").filter(d=>e-d.atd.route));return a.length>=6&&c.has("auth")&&c.has("consent")}catch{return sessionStorage.setItem(hO,JSON.stringify([{route:t,at:e}])),!1}}function Put(){sessionStorage.removeItem(hO)}const pue=()=>{const{signIn:t,user:e,loading:r}=_i(),n=(e==null?void 0:e.id)??null,i=qa(),[a]=zv(),c=a.get("authorization_id")??"",d=a.get("next")??"",[p,l]=N.useState(!1),[g,v]=N.useState({}),[E,T]=N.useState(""),[j,P]=N.useState(!1),[C,L]=N.useState(!1),[O,F]=N.useState(null),[$,G]=N.useState(null),[W,Z]=N.useState(!1),[Q,ee]=N.useState(!1),[ie,oe]=N.useState(()=>{if(a.get("paused")!=="1")return null;let Ie="";try{Ie=sessionStorage.getItem("accountPausedReason")||""}catch{}return Ie?`Your account is paused. ${Ie}`:"Your account is paused. Please contact LevelUp support to reactivate it."}),pe=N.useRef(!1);N.useEffect(()=>{if(c&&/(\.lovable\.app|\.lovableproject\.com)$/.test(window.location.hostname)){const Ie=new URL("/auth",UAe);Ie.searchParams.set("next",`${$D}?authorization_id=${encodeURIComponent(c)}`),window.location.replace(Ie.toString());return}if(c){const Ie=`${$D}?authorization_id=${encodeURIComponent(c)}`;sessionStorage.setItem("redirectAfterLogin",Ie);return}d&&mue(d)&&sessionStorage.setItem("redirectAfterLogin",d)},[c,d]),N.useEffect(()=>{if(r||!n||pe.current)return;const Ie=c?`${$D}?authorization_id=${encodeURIComponent(c)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!mue(Ie)){sessionStorage.removeItem("redirectAfterLogin"),pe.current=!0,i("/dashboard",{replace:!0});return}const Te=Ie.startsWith($D)||Ie.startsWith("/oauth/consent")||Ie.startsWith("/.lovable/oauth/consent");if(Te&&Cut("auth")){F("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}pe.current=!0,Te||(Put(),sessionStorage.removeItem("redirectAfterLogin")),i(Ie,{replace:!0})},[c,r,i,n]);const Le=async Ie=>{Ie.preventDefault(),v({}),oe(null),G(null),Z(!1),l(!0);const Te=new FormData(Ie.currentTarget),ge=Te.get("email"),$e=Te.get("password");try{Iut.parse({email:ge,password:$e}),await t(ge,$e)}catch(we){if(we instanceof tZe){const ke={};we.issues.forEach(Ae=>{Ae.path[0]&&(ke[Ae.path[0]]=Ae.message)}),v(ke)}else if(we instanceof Error&&we.name==="AccountPaused")oe(we.message);else if(ge)try{const{data:ke}=await Be.functions.invoke("account-activation-status",{body:{email:ge}});ke!=null&&ke.needsActivation&&G(ge)}catch{}}finally{l(!1)}},be=async()=>{if($){ee(!0);try{const{data:Ie,error:Te}=await Be.functions.invoke("send-password-reset",{body:{email:$,variant:"activation"}});if(Te)throw Te;if((Ie==null?void 0:Ie.sent)===!1)throw new Error("We couldn't send the activation email. Please try again in a moment or contact support.");Z(!0),lr.success("Activation email sent! Check your inbox.")}catch(Ie){lr.error(Ie instanceof Error?Ie.message:"Failed to send activation email")}finally{ee(!1)}}},Re=async()=>{if(!E){lr.error("Please enter your email address");return}P(!0);try{const{data:Ie,error:Te}=await Be.functions.invoke("send-password-reset",{body:{email:E.trim().toLowerCase(),redirectTo:jut}});if(Te)throw Te;if((Ie==null?void 0:Ie.sent)===!1){lr.error("We couldn't find a LevelUp account for that email. Double-check the address, or email hello@relevelup.com and we'll help.");return}lr.success("Password reset email sent! Check your inbox."),L(!1),T("")}catch(Ie){lr.error(Ie instanceof Error?Ie.message:"Failed to send reset email")}finally{P(!1)}};return s.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]",children:s.jsxs("div",{className:"absolute inset-0 opacity-30",children:[s.jsx("div",{className:"absolute top-0 left-0 w-96 h-96 bg-white/10 rounded-full blur-3xl animate-pulse"}),s.jsx("div",{className:"absolute bottom-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),s.jsx("div",{className:"absolute top-1/2 left-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"2s"}})]})}),s.jsxs("div",{className:"relative z-10 flex flex-col min-h-screen",children:[s.jsx("header",{className:"p-6",children:s.jsxs(Nn,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[s.jsx(yv,{className:"h-4 w-4"}),"Back to Home"]})}),s.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:s.jsxs("div",{className:"w-full max-w-md",children:[s.jsx("div",{className:"flex justify-center mb-8",children:s.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:s.jsx("img",{src:kut,alt:"LevelUp",className:"h-12 w-auto"})})}),s.jsxs(wi,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[s.jsxs(Wh,{className:"space-y-1 text-center pb-4",children:[s.jsx(Kh,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),s.jsx(sC,{className:"text-gray-600",children:O||"Sign in to access your dashboard"})]}),s.jsxs(Di,{children:[ie&&s.jsxs("div",{className:"mb-4 rounded-lg border border-amber-300 bg-amber-50 p-4 text-left",children:[s.jsx("p",{className:"text-sm font-semibold text-amber-900",children:"Account paused"}),s.jsx("p",{className:"mt-1 text-sm text-amber-800",children:ie}),s.jsx("a",{href:"mailto:support@relevelup.com",className:"mt-2 inline-block text-sm font-medium text-amber-900 underline",children:"Contact support"})]}),$&&s.jsxs("div",{className:"mb-4 rounded-lg border border-[#4a6b6d]/30 bg-[#f2f7f7] p-4 text-left",children:[s.jsx("p",{className:"text-sm font-semibold text-[#2a4347]",children:"You haven't set a password yet"}),s.jsx("p",{className:"mt-1 text-sm text-gray-700",children:W?`We just emailed ${$} a link to set your password and sign in. Check your inbox (and spam folder).`:`Your LevelUp account for ${$} is ready — it just needs a password. We'll email you a link to set one.`}),!W&&s.jsx(Jt,{type:"button",onClick:be,disabled:Q,className:"mt-3 bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",children:Q?"Sending...":"Email me a set-password link"})]}),s.jsxs("form",{onSubmit:Le,className:"space-y-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(sn,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),s.jsx(hn,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),g.email&&s.jsx("p",{className:"text-sm text-red-600",children:g.email})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(sn,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),s.jsx(hn,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),g.password&&s.jsx("p",{className:"text-sm text-red-600",children:g.password})]}),s.jsx(Jt,{type:"submit",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg transition-all duration-200 shadow-lg hover:shadow-xl",disabled:p,children:p?"Signing in...":"Sign In"}),s.jsxs(gl,{open:C,onOpenChange:L,children:[s.jsx(Swe,{asChild:!0,children:s.jsx(Jt,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),s.jsxs(Jo,{className:"bg-white",children:[s.jsxs(Bc,{children:[s.jsx(pc,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),s.jsx(sf,{className:"text-gray-600",children:"Enter your email address and we'll send you a link to reset your password."})]}),s.jsxs("div",{className:"space-y-4 pt-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx(sn,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),s.jsx(hn,{id:"reset-email",type:"email",placeholder:"your@email.com",value:E,onChange:Ie=>T(Ie.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),s.jsx(Jt,{onClick:Re,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:j,children:j?"Sending...":"Send Reset Link"})]})]})]})]})]})]}),s.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",s.jsx(Nn,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},BZ=()=>jr({queryKey:["lead-sources"],queryFn:async()=>{const{data:t,error:e}=await Be.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(e)throw e;return t}}),Nut=()=>{const t=Ur(),{user:e}=_i();return zr({mutationFn:async r=>{const{data:n}=await Be.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",r.trim()),i=(n||[]).find(d=>d.name.toLowerCase()===r.trim().toLowerCase()&&!0);if(i)throw new Error(`Lead source "${i.name}" already exists`);const{data:a,error:c}=await Be.from("lead_sources").insert({name:r,owner_user_id:e==null?void 0:e.id,sort_order:100}).select().single();if(c)throw c;return a},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),lr.success("Lead source added")},onError:r=>{lr.error("Failed to add lead source"),console.error(r)}})},bZt=()=>{const t=Ur();return zr({mutationFn:async({id:e,name:r})=>{const{error:n}=await Be.from("lead_sources").update({name:r}).eq("id",e);if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),lr.success("Lead source updated")},onError:e=>{lr.error(e.message||"Failed to update lead source")}})},wZt=()=>{const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("lead_sources").update({is_active:!1}).eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),lr.success("Lead source removed")},onError:e=>{lr.error(e.message||"Failed to remove lead source")}})},VAe=(t,e)=>{const{user:r,isAdmin:n}=_i(),i=n&&e?e:r==null?void 0:r.id;return jr({queryKey:["scorecard-transactions",t,i],queryFn:async()=>{let a=Be.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",i).order("close_date",{ascending:!1});t&&(a=a.gte("close_date",`${t}-01-01`).lte("close_date",`${t}-12-31`));const{data:c,error:d}=await a;if(d)throw d;return c},enabled:!!i})},Rut=t=>{const{user:e,isAdmin:r}=_i(),n=r&&t?t:e==null?void 0:e.id;return jr({queryKey:["scorecard-transactions-all",n],queryFn:async()=>{const{data:i,error:a}=await Be.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",n).order("close_date",{ascending:!1});if(a)throw a;return i},enabled:!!n})},zZ=()=>{const t=Ur(),{user:e}=_i();return zr({mutationFn:async r=>{const{data:n,error:i}=await Be.from("scorecard_transactions").insert({...r,owner_user_id:e.id}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-transactions"]}),t.invalidateQueries({queryKey:["scorecard-transactions-all"]}),lr.success("Transaction added")},onError:r=>{lr.error("Failed to add transaction"),console.error(r)}})},Lut=()=>{const t=Ur();return zr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Be.from("scorecard_transactions").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-transactions"]}),t.invalidateQueries({queryKey:["scorecard-transactions-all"]}),lr.success("Transaction updated")},onError:e=>{lr.error("Failed to update transaction"),console.error(e)}})},Dut=()=>{const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("scorecard_transactions").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-transactions"]}),t.invalidateQueries({queryKey:["scorecard-transactions-all"]}),lr.success("Transaction deleted")},onError:e=>{lr.error("Failed to delete transaction"),console.error(e)}})},Mut=(t,e)=>{const{user:r,isAdmin:n}=_i(),i=n&&e?e:r==null?void 0:r.id;return jr({queryKey:["scorecard-goals",t,i],queryFn:async()=>{const{data:a,error:c}=await Be.from("scorecard_goals").select("*").eq("owner_user_id",i).eq("year",t).maybeSingle();if(c)throw c;return a},enabled:!!i})},Out=()=>{const t=Ur(),{user:e}=_i();return zr({mutationFn:async r=>{const{data:n,error:i}=await Be.from("scorecard_goals").upsert({...r,owner_user_id:e.id},{onConflict:"owner_user_id,year"}).select().single();if(i)throw i;return n},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["scorecard-goals",n.year]}),lr.success("Goals saved")},onError:r=>{lr.error("Failed to save goals"),console.error(r)}})},z5=()=>{const{user:t}=_i();return jr({queryKey:["scorecard-settings",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await Be.from("scorecard_settings").select("*").eq("user_id",t.id).maybeSingle();if(r)throw r;return e},enabled:!!(t!=null&&t.id)})},Fut=()=>{const t=Ur(),{user:e}=_i();return zr({mutationFn:async r=>{const{data:n,error:i}=await Be.from("scorecard_settings").upsert({...r,user_id:e.id},{onConflict:"user_id"}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-settings"]}),lr.success("Settings saved")},onError:r=>{lr.error("Failed to save settings"),console.error(r)}})},But=(t,e)=>{const{data:r,isLoading:n}=VAe(t,e),{data:i,isLoading:a}=Rut(e),{data:c}=z5(),d=(c==null?void 0:c.show_commission)??!0,p=l=>{if(!l||l.length===0)return{totalTransactions:0,buyerCount:0,sellerCount:0,totalVolume:0,averagePrice:0,totalCommission:0,totalNetToAgent:0,topLeadSource:null,transactionsByMonth:[],leadSourceBreakdown:[]};const g=l.filter(G=>G.transaction_type==="buyer").length,v=l.filter(G=>G.transaction_type==="seller").length,E=l.reduce((G,W)=>G+Number(W.sale_price),0),T=l.reduce((G,W)=>G+(Number(W.commission_amount)||0),0),j=l.reduce((G,W)=>{const Z=Number(W.commission_amount)||0;if(!Z)return G;let Q=Z;return W.brokerage_split_pct&&(Q-=Z*(W.brokerage_split_pct/100)),W.team_split_pct&&(Q-=Z*(W.team_split_pct/100)),W.franchise_fee_pct&&(Q-=Z*(W.franchise_fee_pct/100)),W.referral_fee_pct&&(Q-=Z*(W.referral_fee_pct/100)),W.transaction_fee&&(Q-=W.transaction_fee),G+Math.max(0,Q)},0),P={};l.forEach(G=>{var Z;const W=((Z=G.lead_source)==null?void 0:Z.name)||"Unknown";P[W]=(P[W]||0)+1});const C=Object.entries(P).map(([G,W])=>({name:G,count:W})).sort((G,W)=>W.count-G.count),L=C[0]||null,O={};l.forEach(G=>{const W=_T(G.close_date).toLocaleString("default",{month:"short"});O[W]=(O[W]||0)+1});const $=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(G=>({month:G,count:O[G]||0}));return{totalTransactions:l.length,buyerCount:g,sellerCount:v,totalVolume:E,averagePrice:l.length>0?E/l.length:0,totalCommission:d?T:0,totalNetToAgent:d?j:0,topLeadSource:L,transactionsByMonth:$,leadSourceBreakdown:C}};return{yearStats:p(r),lifetimeStats:p(i),isLoading:n||a,showCommission:d}},SZt=()=>{const{isAdmin:t}=_i();return jr({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:e,error:r}=await Be.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(r)throw r;const n=[...new Set(e.map(c=>c.owner_user_id))],{data:i,error:a}=await Be.from("profiles").select("id, name, email").in("id",n);if(a)throw a;return i},enabled:t})},$Z=N.forwardRef(({className:t,...e},r)=>s.jsx("div",{className:"relative w-full overflow-auto",children:s.jsx("table",{ref:r,className:hr("w-full caption-bottom text-sm",t),...e})}));$Z.displayName="Table";const UZ=N.forwardRef(({className:t,...e},r)=>s.jsx("thead",{ref:r,className:hr("[&_tr]:border-b",t),...e}));UZ.displayName="TableHeader";const VZ=N.forwardRef(({className:t,...e},r)=>s.jsx("tbody",{ref:r,className:hr("[&_tr:last-child]:border-0",t),...e}));VZ.displayName="TableBody";const zut=N.forwardRef(({className:t,...e},r)=>s.jsx("tfoot",{ref:r,className:hr("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...e}));zut.displayName="TableFooter";const xC=N.forwardRef(({className:t,...e},r)=>s.jsx("tr",{ref:r,className:hr("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",t),...e}));xC.displayName="TableRow";const Cu=N.forwardRef(({className:t,...e},r)=>s.jsx("th",{ref:r,className:hr("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",t),...e}));Cu.displayName="TableHead";const Pu=N.forwardRef(({className:t,...e},r)=>s.jsx("td",{ref:r,className:hr("p-4 align-middle [&:has([role=checkbox])]:pr-0",t),...e}));Pu.displayName="TableCell";const $ut=N.forwardRef(({className:t,...e},r)=>s.jsx("caption",{ref:r,className:hr("mt-4 text-sm text-muted-foreground",t),...e}));$ut.displayName="TableCaption";const M9="boost";function jw(t,e){typeof window>"u"||window.dispatchEvent(new CustomEvent(M9,{detail:{type:t,requestId:e}}))}function EZt(t){const e=r=>{const n=r.detail;t(typeof n=="string"?{type:n}:n)};return window.addEventListener(M9,e),()=>window.removeEventListener(M9,e)}const TZt=["Idle","Thinking","Listening","Working","Success","Alert","Celebration","Pointing","Wave","Sleeping"],AZt=new Set(["Idle","Thinking","Listening","Working","Sleeping"]),kZt={contact_created:{clip:"Celebration",priority:4},task_completed:{clip:"Celebration",priority:4},lead_received:{clip:"Alert",priority:3},gift_claimed:{clip:"Celebration",priority:5},task_created:{clip:"Success",priority:2},request_success:{clip:"Success",priority:2}},gue={hidden:!1,paused:!1,reduceMotion:!1,muteAnnouncements:!1},qAe=new Map,GAe=t=>`boost:prefs:${t}`;function IZt(t){try{const e=window.localStorage.getItem(GAe(t));if(e)return{...gue,...JSON.parse(e)}}catch{}return qAe.get(t)??gue}function jZt(t,e){qAe.set(t,e);try{window.localStorage.setItem(GAe(t),JSON.stringify(e))}catch{}}let cI=null;function CZt(){var t;if(cI!==null)return cI;try{const e=document.createElement("canvas"),r=e.getContext("webgl2")||e.getContext("webgl");cI=!!r,(t=r==null?void 0:r.getExtension("WEBGL_lose_context"))==null||t.loseContext()}catch{cI=!1}return cI}const qZ=()=>jr({queryKey:["relationship-types"],queryFn:async()=>{const{data:t,error:e}=await Be.from("relationship_types").select("*").order("sort_order");if(e)throw e;return t}}),PZt=()=>{const t=qs(),e=1e3;return jr({queryKey:["innercircle-contacts-lite",t],queryFn:async()=>{const r=[];let n=0;for(;;){const{data:i,error:a}=await Be.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code, birthday, home_anniversary, wedding_anniversary, created_at").eq("owner_user_id",t).order("created_at",{ascending:!1}).range(n,n+e-1);if(a)throw a;const c=i??[];if(r.push(...c),c.length{const e=qs(),r=1e3,n=async i=>{const a=[];let c=0;for(;;){const{data:d,error:p}=await i.range(c,c+r-1);if(p)throw p;const l=d??[];if(a.push(...l),l.length{let i=Be.from("innercircle_contacts").select("*").eq("owner_user_id",e).order("created_at",{ascending:!1}).order("first_name");const a=await n(i);if(a.length===0)return a;const c=a.map(T=>T.id),d=Array.from(new Set(a.map(T=>T.lead_source_id).filter(T=>!!T))),p=(T,j=250)=>{const P=[];for(let C=0;C{const{data:j,error:P}=await Be.from("innercircle_contact_tags").select("id, contact_id, relationship_type_id, relationship_type:relationship_types(*)").in("contact_id",T);if(P)throw P;return j??[]})),Promise.all(p(d).map(async T=>{const{data:j,error:P}=await Be.from("lead_sources").select("id, name").in("id",T);if(P)throw P;return j??[]}))]),v=new Map;l.flat().forEach(T=>{const j=v.get(T.contact_id)??[];j.push(T),v.set(T.contact_id,j)});const E=new Map(g.flat().map(T=>[T.id,T]));return a.map(T=>({...T,lead_source_ref:T.lead_source_id?E.get(T.lead_source_id)??null:null,tags:v.get(T.id)??[]}))},enabled:!!e,staleTime:10*60*1e3})},NZt=t=>jr({queryKey:["innercircle-contact",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",t).maybeSingle();if(r)throw r;return e},enabled:!!t}),RZt=()=>{const t=qs();return jr({queryKey:["innercircle-contact-counts",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(r)throw r;const n={};return e==null||e.forEach(i=>{var a;(a=i.tags)==null||a.forEach(c=>{n[c.relationship_type_id]=(n[c.relationship_type_id]||0)+1})}),n},enabled:!!t})},Uut=()=>{const t=Ur(),e=qs();return zr({mutationFn:async r=>{const{tagIds:n,...i}=r,a={...i,birthday:i.birthday||null,home_anniversary:i.home_anniversary||null,spouse_birthday:i.spouse_birthday||null,owner_user_id:e},{data:c,error:d}=await Be.from("innercircle_contacts").insert(a).select().single();if(d)throw d;if(n&&n.length>0){const{error:p}=await Be.from("innercircle_contact_tags").insert(n.map(l=>({contact_id:c.id,relationship_type_id:l})));if(p)throw p}return c},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),jw("contact_created"),ba({title:"Contact created successfully"})},onError:r=>{ba({title:"Error creating contact",description:r.message,variant:"destructive"})}})},LZt=()=>{const t=Ur();return zr({mutationFn:async({id:e,...r})=>{const{tagIds:n,tags:i,...a}=r,c=["birthday","home_anniversary","spouse_birthday","wedding_anniversary","last_contacted_at","next_touch_date"],d={...a};for(const g of Object.keys(d)){const v=d[g];(v===""||typeof v=="string"&&c.includes(g)&&v.trim()==="")&&(d[g]=null)}const{data:p,error:l}=await Be.from("innercircle_contacts").update(d).eq("id",e).select().single();if(l)throw l;if(n!==void 0&&(await Be.from("innercircle_contact_tags").delete().eq("contact_id",e),n.length>0)){const{error:g}=await Be.from("innercircle_contact_tags").insert(n.map(v=>({contact_id:e,relationship_type_id:v})));if(g)throw g}return p},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),jw("contact_created"),ba({title:"Contact updated successfully"})},onError:e=>{ba({title:"Error updating contact",description:e.message,variant:"destructive"})}})},DZt=()=>{const t=Ur();return zr({mutationFn:async({contactId:e,spouseContactId:r})=>{if(r){const{error:n}=await Be.from("innercircle_contacts").update({spouse_contact_id:r}).eq("id",e);if(n)throw n;const{error:i}=await Be.from("innercircle_contacts").update({spouse_contact_id:e}).eq("id",r);if(i)throw i}else{const{data:n}=await Be.from("innercircle_contacts").select("spouse_contact_id").eq("id",e).single(),i=n==null?void 0:n.spouse_contact_id,{error:a}=await Be.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",e);if(a)throw a;if(i){const{error:c}=await Be.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",i);if(c)throw c}}},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact"]}),t.invalidateQueries({queryKey:["innercircle-contact-spouse"]}),ba({title:"Spouse link updated"})},onError:e=>{ba({title:"Error linking spouse",description:e.message,variant:"destructive"})}})},MZt=()=>{const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("innercircle_contacts").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ba({title:"Contact deleted successfully"})},onError:e=>{ba({title:"Error deleting contact",description:e.message,variant:"destructive"})}})},OZt=()=>{const t=Ur();return zr({mutationFn:async({ids:e,onProgress:r})=>{let i=0;for(let a=0;a{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),t.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})},FZt=()=>jr({queryKey:["action-types"],queryFn:async()=>{const{data:t,error:e}=await Be.from("action_types").select("*").order("sort_order");if(e)throw e;return t}}),BZt=t=>jr({queryKey:["action-scripts",t],queryFn:async()=>{let e=Be.from("action_scripts").select("*, action_type:action_types(*)");const{data:r,error:n}=await e;if(n)throw n;return r}}),zZt=()=>jr({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:t,error:e}=await Be.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(e)throw e;return t}}),$Zt=()=>{const t=Ur(),e=qs();return zr({mutationFn:async({name:r,description:n})=>{const{data:i,error:a}=await Be.from("touchpoint_plans").insert({name:r,description:n,owner_user_id:e,active:!0,is_template:!1}).select().single();if(a)throw a;return i},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),ba({title:"Plan created successfully"})},onError:r=>{ba({title:"Error creating plan",description:r.message,variant:"destructive"})}})},UZt=()=>{const t=Ur(),e=qs();return zr({mutationFn:async({sourcePlanId:r,newName:n})=>{const{data:i,error:a}=await Be.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",r).single();if(a)throw a;if(!i)throw new Error("Source plan not found");const{data:c,error:d}=await Be.from("touchpoint_plans").insert({name:n,description:i.description,owner_user_id:e,active:!0,is_template:!1}).select().single();if(d)throw d;if(i.items&&i.items.length>0){const p=i.items.map(g=>({plan_id:c.id,month_number:g.month_number,action_type_id:g.action_type_id,default_script_id:g.default_script_id,notes:g.notes})),{error:l}=await Be.from("touchpoint_plan_items").insert(p);if(l)throw l}return c},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),ba({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:r=>{ba({title:"Error duplicating plan",description:r.message,variant:"destructive"})}})},VZt=()=>{const t=Ur();return zr({mutationFn:async({id:e,name:r,description:n})=>{const{data:i,error:a}=await Be.from("touchpoint_plans").update({name:r,description:n}).eq("id",e).select().single();if(a)throw a;return i},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),ba({title:"Plan updated successfully"})}})},qZt=()=>{const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("touchpoint_plans").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),ba({title:"Plan deleted successfully"})}})},GZt=()=>{const t=Ur();return zr({mutationFn:async({planId:e,items:r})=>{if(await Be.from("touchpoint_plan_items").delete().eq("plan_id",e),r.length>0){const{error:n}=await Be.from("touchpoint_plan_items").insert(r.map(i=>({plan_id:e,month_number:i.month_number,action_type_id:i.action_type_id,default_script_id:i.default_script_id||null,notes:i.notes})));if(n)throw n}},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),ba({title:"Plan schedule updated"})}})},HZt=()=>{const t=Ur();return zr({mutationFn:async({actionTypeId:e,title:r,scriptBody:n,emailSubject:i,tone:a})=>{const{data:{user:c}}=await Be.auth.getUser(),{data:d,error:p}=await Be.from("action_scripts").insert({action_type_id:e,title:r,script_body:n,email_subject:i||null,tone:a||null,active:!0,user_id:c==null?void 0:c.id}).select().single();if(p)throw p;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["action-scripts"]}),ba({title:"Script created successfully"})},onError:e=>{ba({title:"Error creating script",description:e.message,variant:"destructive"})}})},WZt=()=>{const t=qs();return jr({queryKey:["user-plan-enrollments",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(r)throw r;return e},enabled:!!t})},KZt=()=>{const t=Ur(),e=qs();return zr({mutationFn:async({planId:r,relationshipTypeId:n,active:i})=>{const{data:a}=await Be.from("user_plan_enrollments").select("id").eq("plan_id",r).eq("relationship_type_id",n).maybeSingle();if(a){const{error:c}=await Be.from("user_plan_enrollments").update({active:i}).eq("id",a.id);if(c)throw c}else if(i){const{error:c}=await Be.from("user_plan_enrollments").insert({owner_user_id:e,plan_id:r,relationship_type_id:n,active:!0,start_date:new Date().toISOString().split("T")[0]});if(c)throw c}},onSuccess:()=>{t.invalidateQueries({queryKey:["user-plan-enrollments"]}),ba({title:"Plan enrollment updated"})}})},WAe=(t=7)=>{const e=qs();return jr({queryKey:["contact-touch-logs",e,t],queryFn:async()=>{const r=new Date;r.setDate(r.getDate()-t);const{data:n,error:i}=await Be.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",e).gte("completed_at",r.toISOString()).order("completed_at",{ascending:!1});if(i)throw i;return n},enabled:!!e})},Vut=()=>{const t=qs();return jr({queryKey:["contacts-last-touch",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",t).order("completed_at",{ascending:!1});if(r)throw r;const n={};return e==null||e.forEach(i=>{n[i.contact_id]||(n[i.contact_id]=i.completed_at)}),n},enabled:!!t})},YZt=(t=90)=>{const{data:e}=HAe(),{data:r}=Vut();if(!e||!r)return{contacts:[],count:0};const n=new Date;n.setDate(n.getDate()-t);const i=e.filter(a=>{const c=r[a.id];return c?new Date(c){const t=Ur(),e=qs();return zr({mutationFn:async({contactId:r,actionTypeId:n,scriptUsedId:i,notes:a,completedAt:c})=>{const{data:d,error:p}=await Be.from("contact_touch_logs").insert({owner_user_id:e,contact_id:r,action_type_id:n,script_used_id:i,notes:a,completed_at:c||new Date().toISOString()}).select().single();if(p)throw p;return d},onSuccess:async(r,n)=>{var i,a;t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts-last-touch"]}),t.invalidateQueries({queryKey:["today-actions"]}),t.invalidateQueries({queryKey:["popby-logs"]}),jw("task_completed"),ba({title:"Action completed!"});try{const[c,d]=await Promise.all([Be.from("innercircle_contacts").select("email").eq("id",n.contactId).single(),Be.from("action_types").select("name").eq("id",n.actionTypeId).single()]),p=(i=c.data)==null?void 0:i.email,l=((a=d.data)==null?void 0:a.name)||"Touch";/pop[\s-]?by/i.test(l)&&Be.from("popby_logs").insert({owner_user_id:e,contact_id:n.contactId,notes:n.notes??null,completed_at:n.completedAt||r.completed_at}).then(()=>{t.invalidateQueries({queryKey:["popby-logs"]})}),p&&Be.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:p,touch_type:l,touch_notes:n.notes||null,touch_date:n.completedAt||r.completed_at}}).catch(()=>{})}catch{}}})},KAe="agentos_weekly_touch_goal",yue=20,qut=()=>{if(typeof window>"u")return yue;const t=localStorage.getItem(KAe);if(t){const e=parseInt(t,10);if(!isNaN(e)&&e>0)return e}return yue},XZt=t=>{localStorage.setItem(KAe,t.toString())},QZt=()=>{const{data:t}=WAe(7),e=new Date;e.setHours(0,0,0,0);const r=new Date(e);r.setDate(e.getDate()-e.getDay());const n=(t==null?void 0:t.filter(c=>new Date(c.completed_at)>=r).length)||0;let i=0;if(t&&t.length>0){const c=new Set(t.map(p=>new Date(p.completed_at).toDateString()));let d=new Date(e);for(;c.has(d.toDateString());)i++,d.setDate(d.getDate()-1)}const a=qut();return{actionsThisWeek:n,weeklyGoal:a,streak:i,progress:Math.min(n/a*100,100)}},Gut=()=>{const t=qs();return jr({queryKey:["contact-plan-cycles",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(r)throw r;return e},enabled:!!t})},JZt=()=>{const t=Ur();return qs(),zr({mutationFn:async()=>{var p;const{data:e}=await Be.from("user_plan_enrollments").select("*").eq("active",!0);if(!e||e.length===0)return;const{data:r}=await Be.auth.getUser(),n=(p=r==null?void 0:r.user)==null?void 0:p.id;if(!n)return;const{data:i}=await Be.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",n);if(!i)return;const{data:a}=await Be.from("contact_plan_cycles").select("contact_id, plan_id"),c=new Set((a==null?void 0:a.map(l=>`${l.contact_id}-${l.plan_id}`))||[]),d=[];for(const l of i)for(const g of l.tags||[]){const v=e.find(E=>E.relationship_type_id===g.relationship_type_id);v&&!c.has(`${l.id}-${v.plan_id}`)&&d.push({contact_id:l.id,plan_id:v.plan_id,relationship_type_id:g.relationship_type_id})}if(d.length>0){const{error:l}=await Be.from("contact_plan_cycles").insert(d);if(l)throw l}return d.length},onSuccess:e=>{t.invalidateQueries({queryKey:["contact-plan-cycles"]}),e&&e>0&&ba({title:`${e} contact(s) enrolled in plans`})}})},eXt=()=>{const t=qs(),{data:e}=Gut(),{data:r}=WAe(30);return jr({queryKey:["today-actions",t,e==null?void 0:e.length,r==null?void 0:r.length],queryFn:async()=>{var j;if(!e||e.length===0)return[];const{data:n}=await Be.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),i=new Set((n==null?void 0:n.map(P=>P.contact_id))||[]),a=new Date,c=[],d=new Date(a.getFullYear(),a.getMonth(),1),p=new Set((r==null?void 0:r.filter(P=>new Date(P.completed_at)>=d).map(P=>`${P.contact_id}-${P.action_type_id}`))||[]);for(const P of e){if(!((j=P.plan)!=null&&j.items)||P.plan.items.length===0||!P.contact||i.has(P.contact_id))continue;const C=new Date(P.cycle_start_date),O=Math.floor((a.getTime()-C.getTime())/(30.44*24*60*60*1e3))%12+1,F=P.plan.items.find($=>$.month_number===O);if(F&&F.action_type){const $=`${P.contact_id}-${F.action_type_id}`;if(!p.has($)){const{data:G}=await Be.from("relationship_types").select("name").eq("id",P.relationship_type_id).single();c.push({contact:P.contact,actionType:F.action_type,script:F.default_script||void 0,planName:P.plan.name,relationshipTypeName:(G==null?void 0:G.name)||"",monthNumber:O})}}}const l=5,g=a.getDate(),v=c.sort((P,C)=>P.contact.first_name.localeCompare(C.contact.first_name)),E=(g-1)%Math.max(1,v.length);return[...v.slice(E),...v.slice(0,E)].slice(0,l)},enabled:!!t&&!!e})};var Hut=Object.defineProperty,ox=(t,e)=>Hut(t,"name",{value:e,configurable:!0}),GZ="Popover",[YAe,tXt]=Nl(GZ,[Bv]),HZ=Bv(),[Wut,jA]=YAe(GZ),Kut=ox(t=>{const{__scopePopover:e,children:r,open:n,defaultOpen:i,onOpenChange:a,modal:c=!1}=t,d=HZ(e),p=N.useRef(null),[l,g]=N.useState(!1),[v,E]=N.useState(0),[T,j]=N.useState(0),[P,C]=ph({prop:n,defaultProp:i??!1,onChange:a,caller:GZ});return s.jsx(V4,{...d,children:s.jsx(Wut,{scope:e,contentId:Wl(),titleId:Wl(),descriptionId:Wl(),titlePresent:v>0,descriptionPresent:T>0,setTitleCount:E,setDescriptionCount:j,triggerRef:p,open:P,onOpenChange:C,onOpenToggle:N.useCallback(()=>C(L=>!L),[C]),hasCustomAnchor:l,onCustomAnchorAdd:N.useCallback(()=>g(!0),[]),onCustomAnchorRemove:N.useCallback(()=>g(!1),[]),modal:c,children:r})})},"Popover"),Yut="PopoverTrigger",Zut=N.forwardRef(ox(function(e,r){const{__scopePopover:n,...i}=e,a=jA(Yut,n),c=HZ(n),d=Jn(r,a.triggerRef),p=s.jsx(An.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":WZ(a.open),...i,ref:d,onClick:Qr(e.onClick,a.onOpenToggle)});return a.hasCustomAnchor?p:s.jsx(q4,{asChild:!0,...c,children:p})},"PopoverTrigger")),ZAe="PopoverPortal",[Xut,Qut]=YAe(ZAe,{forceMount:void 0}),Jut=ox(t=>{const{__scopePopover:e,forceMount:r,children:n,container:i}=t,a=jA(ZAe,e);return s.jsx(Xut,{scope:e,forceMount:r,children:s.jsx(zc,{present:r||a.open,children:s.jsx(jP,{asChild:!0,container:i,children:n})})})},"PopoverPortal"),_C="PopoverContent",XAe=N.forwardRef(ox(function(e,r){const n=Qut(_C,e.__scopePopover),{forceMount:i=n.forceMount,...a}=e,c=jA(_C,e.__scopePopover);return s.jsx(zc,{present:i||c.open,children:c.modal?s.jsx(tdt,{...a,ref:r}):s.jsx(rdt,{...a,ref:r})})},"PopoverContent")),edt=sp("PopoverContent.RemoveScroll"),tdt=N.forwardRef(ox(function(e,r){const n=jA(_C,e.__scopePopover),i=N.useRef(null),a=Jn(r,i),c=N.useRef(!1),{nodes:d,registry:p}=P4();return N.useEffect(()=>{const l=i.current;if(l)return L4(l)},[]),s.jsx(DP,{as:edt,allowPinchZoom:!0,shards:N.useMemo(()=>[i,...d.map(l=>({current:l}))],[i,d]),children:s.jsx(QAe,{...e,ref:a,branchNodes:d,branchRegistry:p,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Qr(e.onCloseAutoFocus,l=>{var g;l.preventDefault(),c.current||(g=n.triggerRef.current)==null||g.focus()}),onPointerDownOutside:Qr(e.onPointerDownOutside,l=>{const g=l.detail.originalEvent,v=g.button===0&&g.ctrlKey===!0,E=g.button===2||v;c.current=E},{checkForDefaultPrevented:!1}),onFocusOutside:Qr(e.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),rdt=N.forwardRef(ox(function(e,r){const n=jA(_C,e.__scopePopover),i=N.useRef(!1),a=N.useRef(!1);return s.jsx(QAe,{...e,ref:r,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:c=>{var d,p;(d=e.onCloseAutoFocus)==null||d.call(e,c),c.defaultPrevented||(i.current||(p=n.triggerRef.current)==null||p.focus(),c.preventDefault()),i.current=!1,a.current=!1},onInteractOutside:c=>{var l,g;(l=e.onInteractOutside)==null||l.call(e,c),c.defaultPrevented||(i.current=!0,c.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const d=c.target;((g=n.triggerRef.current)==null?void 0:g.contains(d))&&c.preventDefault(),c.detail.originalEvent.type==="focusin"&&a.current&&c.preventDefault()}})},"PopoverContentNonModal")),QAe=N.forwardRef(ox(function(e,r){const{__scopePopover:n,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:c,disableOutsidePointerEvents:d,onEscapeKeyDown:p,onPointerDownOutside:l,onFocusOutside:g,onInteractOutside:v,"aria-describedby":E,branchNodes:T,branchRegistry:j,...P}=e,C=jA(_C,n),L=HZ(n),[O,F]=N.useState(null),$=Jn(r,F);return N4(O),aA(),s.jsx(C4,{registry:j,children:s.jsx(j4,{asChild:!0,loop:!0,trapped:i,branches:T,onMountAutoFocus:a,onUnmountAutoFocus:c,children:s.jsx(JT,{asChild:!0,disableOutsidePointerEvents:d,onInteractOutside:v,onEscapeKeyDown:p,onPointerDownOutside:l,onFocusOutside:g,onDismiss:()=>C.onOpenChange(!1),deferPointerDownOutside:!0,children:s.jsx(G4,{"data-state":WZ(C.open),role:"dialog",id:C.contentId,"aria-labelledby":C.titlePresent?C.titleId:void 0,"aria-describedby":C.descriptionPresent?JAe(E,C.descriptionId):E,...L,...P,ref:$,style:{...P.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})})},"PopoverContentImpl"));function WZ(t){return t?"open":"closed"}ox(WZ,"getState");function JAe(...t){const e=new Set;for(const r of t)if(typeof r=="string")for(const n of String(r).trim().split(/\s+/))n&&e.add(n);return e.size>0?Array.from(e).join(" "):void 0}ox(JAe,"concatAriaDescribedby");const fO=Kut,mO=Zut,gj=N.forwardRef(({className:t,align:e="center",sideOffset:r=4,...n},i)=>s.jsx(Jut,{children:s.jsx(XAe,{ref:i,align:e,sideOffset:r,className:hr("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...n})}));gj.displayName=XAe.displayName;const ndt=Gv({property_address:Us().min(1,"Property address is required"),city:Us().optional(),state:Us().optional(),zip:Us().optional(),transaction_type:g5(["buyer","seller"]),close_date:Us().min(1,"Close date is required"),sale_price:cj().min(0,"Sale price must be positive"),commission_amount:cj().optional(),lead_source_id:Us().optional(),client_type_id:Us().optional(),contact_id:Us().optional(),notes:Us().optional(),is_win:zZe()});function e2e({open:t,onOpenChange:e,transaction:r}){const[n,i]=N.useState(!1),[a,c]=N.useState(""),[d,p]=N.useState(!1),[l,g]=N.useState(""),v=zZ(),E=Lut(),{data:T}=BZ(),{data:j}=qZ(),{data:P}=HAe(),C=Uut(),L=Nut(),{data:O}=z5(),F=(O==null?void 0:O.show_commission)??!0,$=lY({resolver:uY(ndt),defaultValues:{property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1}});N.useEffect(()=>{r?$.reset({property_address:r.property_address,city:r.city||"",state:r.state||"",zip:r.zip||"",transaction_type:r.transaction_type,close_date:r.close_date,sale_price:Number(r.sale_price),commission_amount:r.commission_amount?Number(r.commission_amount):void 0,lead_source_id:r.lead_source_id||void 0,client_type_id:r.client_type_id||void 0,contact_id:r.contact_id||void 0,notes:r.notes||"",is_win:r.is_win}):$.reset({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1})},[r,$]);const G=async ee=>{const ie={property_address:ee.property_address,transaction_type:ee.transaction_type,close_date:ee.close_date,sale_price:ee.sale_price,is_win:ee.is_win,commission_amount:ee.commission_amount||null,lead_source_id:ee.lead_source_id||null,client_type_id:ee.client_type_id||null,contact_id:ee.contact_id||null,city:ee.city||null,state:ee.state||null,zip:ee.zip||null,notes:ee.notes||null};r?await E.mutateAsync({id:r.id,...ie}):await v.mutateAsync(ie),e(!1)},W=async()=>{if(!a.trim())return;const[ee,...ie]=a.trim().split(" "),oe=ie.join(" ")||null,pe=await C.mutateAsync({first_name:ee,last_name:oe,tagIds:[]});pe&&($.setValue("contact_id",pe.id),c(""),p(!1),i(!1))},Z=async()=>{if(!l.trim())return;const ee=await L.mutateAsync(l.trim());ee&&($.setValue("lead_source_id",ee.id),g(""))},Q=P==null?void 0:P.find(ee=>ee.id===$.watch("contact_id"));return s.jsx(gl,{open:t,onOpenChange:e,children:s.jsxs(Jo,{className:"max-w-lg max-h-[90vh]",children:[s.jsx(Bc,{children:s.jsx(pc,{children:r?"Edit Transaction":"Add Transaction"})}),s.jsx(Eg,{className:"max-h-[70vh] pr-4",children:s.jsx(EY,{...$,children:s.jsxs("form",{onSubmit:$.handleSubmit(G),className:"space-y-4",children:[s.jsx(Cc,{control:$.control,name:"property_address",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Property Address *"}),s.jsx(oc,{children:s.jsx(hn,{placeholder:"123 Main St",...ee})}),s.jsx(Ym,{})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[s.jsx(Cc,{control:$.control,name:"city",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"City"}),s.jsx(oc,{children:s.jsx(hn,{placeholder:"City",...ee})})]})}),s.jsx(Cc,{control:$.control,name:"state",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"State"}),s.jsx(oc,{children:s.jsx(hn,{placeholder:"TX",...ee})})]})}),s.jsx(Cc,{control:$.control,name:"zip",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Zip"}),s.jsx(oc,{children:s.jsx(hn,{placeholder:"75001",...ee})})]})})]}),s.jsx(Cc,{control:$.control,name:"transaction_type",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Transaction Type *"}),s.jsxs(Xo,{onValueChange:ee.onChange,value:ee.value,children:[s.jsx(oc,{children:s.jsx(Mo,{children:s.jsx(Qo,{placeholder:"Select type"})})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"buyer",children:"Buyer"}),s.jsx($n,{value:"seller",children:"Seller"})]})]}),s.jsx(Ym,{})]})}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsx(Cc,{control:$.control,name:"close_date",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Close Date *"}),s.jsx(oc,{children:s.jsx(hn,{type:"date",...ee})}),s.jsx(Ym,{})]})}),s.jsx(Cc,{control:$.control,name:"sale_price",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Sale Price *"}),s.jsx(oc,{children:s.jsx(hn,{type:"number",placeholder:"0",...ee,onChange:ie=>ee.onChange(Number(ie.target.value))})}),s.jsx(Ym,{})]})})]}),F&&s.jsx(Cc,{control:$.control,name:"commission_amount",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Commission"}),s.jsx(oc,{children:s.jsx(hn,{type:"number",placeholder:"0",...ee,value:ee.value??"",onChange:ie=>ee.onChange(ie.target.value?Number(ie.target.value):void 0)})})]})}),s.jsx(Cc,{control:$.control,name:"lead_source_id",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Lead Source"}),s.jsxs(Xo,{onValueChange:ee.onChange,value:ee.value||"",children:[s.jsx(oc,{children:s.jsx(Mo,{children:s.jsx(Qo,{placeholder:"Select source"})})}),s.jsx(Oo,{children:T==null?void 0:T.map(ie=>s.jsx($n,{value:ie.id,children:ie.name},ie.id))})]})]})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(hn,{placeholder:"Add custom source...",value:l,onChange:ee=>g(ee.target.value),className:"flex-1"}),s.jsx(Jt,{type:"button",variant:"outline",size:"icon",onClick:Z,disabled:!l.trim(),children:s.jsx(Py,{className:"h-4 w-4"})})]}),s.jsx(Cc,{control:$.control,name:"client_type_id",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Client Type"}),s.jsxs(Xo,{onValueChange:ee.onChange,value:ee.value||"",children:[s.jsx(oc,{children:s.jsx(Mo,{children:s.jsx(Qo,{placeholder:"Select client type"})})}),s.jsx(Oo,{children:j==null?void 0:j.map(ie=>s.jsx($n,{value:ie.id,children:ie.name},ie.id))})]})]})}),s.jsx(Cc,{control:$.control,name:"contact_id",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Client Contact"}),s.jsxs(fO,{open:n,onOpenChange:i,children:[s.jsx(mO,{asChild:!0,children:s.jsx(oc,{children:s.jsxs(Jt,{variant:"outline",role:"combobox",className:hr("w-full justify-between",!ee.value&&"text-muted-foreground"),children:[Q?`${Q.first_name} ${Q.last_name||""}`.trim():"Select contact",s.jsx(Iq,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),s.jsxs(gj,{className:"w-full p-0",align:"start",children:[s.jsxs(cC,{children:[s.jsx(uC,{placeholder:"Search contacts..."}),s.jsxs(dC,{children:[s.jsx(hC,{children:s.jsxs("div",{className:"p-2 space-y-2",children:[s.jsx("p",{className:"text-sm text-muted-foreground",children:"No contact found."}),!d&&s.jsxs(Jt,{variant:"outline",size:"sm",className:"w-full",onClick:()=>p(!0),children:[s.jsx(Py,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),s.jsx(pT,{children:P==null?void 0:P.map(ie=>s.jsxs(X_,{value:`${ie.first_name} ${ie.last_name||""}`,onSelect:()=>{ee.onChange(ie.id),i(!1)},children:[s.jsx(ql,{className:hr("mr-2 h-4 w-4",ie.id===ee.value?"opacity-100":"opacity-0")}),ie.first_name," ",ie.last_name||""]},ie.id))})]})]}),d&&s.jsxs("div",{className:"p-2 border-t space-y-2",children:[s.jsx(hn,{placeholder:"Enter contact name...",value:a,onChange:ie=>c(ie.target.value)}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Jt,{size:"sm",onClick:W,disabled:!a.trim()||C.isPending,children:"Add Contact"}),s.jsx(Jt,{size:"sm",variant:"outline",onClick:()=>{p(!1),c("")},children:"Cancel"})]})]})]})]})]})}),s.jsx(Cc,{control:$.control,name:"notes",render:({field:ee})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Notes"}),s.jsx(oc,{children:s.jsx(df,{placeholder:"Any notes about this transaction...",...ee})})]})}),s.jsx(Cc,{control:$.control,name:"is_win",render:({field:ee})=>s.jsxs(sc,{className:"flex items-center justify-between rounded-lg border p-3",children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(ac,{children:"Mark as Win 🏆"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),s.jsx(oc,{children:s.jsx(TA,{checked:ee.value,onCheckedChange:ee.onChange})})]})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(Jt,{type:"button",variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsxs(Jt,{type:"submit",disabled:v.isPending||E.isPending,children:[r?"Update":"Add"," Transaction"]})]})]})})})]})})}const sV=768;function idt(){const[t,e]=N.useState(void 0);return N.useEffect(()=>{const r=window.matchMedia(`(max-width: ${sV-1}px)`),n=()=>{e(window.innerWidthr.removeEventListener("change",n)},[]),!!t}function t2e({transactions:t,showCommission:e,isLoading:r,agentNameMap:n,readOnly:i}){const[a,c]=N.useState(null),[d,p]=N.useState(null),[l,g]=N.useState(""),[v,E]=N.useState("all"),[T,j]=N.useState("all"),[P,C]=N.useState("all"),[L,O]=N.useState(!1),F=Dut(),$=zZ(),{data:G}=BZ(),{data:W}=qZ(),Z=idt(),Q=oe=>{const{id:pe,created_at:Le,updated_at:be,lead_source:Re,client_type:Ie,contact:Te,...ge}=oe;$.mutate(ge)},ee=()=>{d&&(F.mutate(d),p(null))},ie=t.filter(oe=>{var Te,ge,$e,we;const pe=l===""||oe.property_address.toLowerCase().includes(l.toLowerCase())||((ge=(Te=oe.contact)==null?void 0:Te.first_name)==null?void 0:ge.toLowerCase().includes(l.toLowerCase()))||((we=($e=oe.contact)==null?void 0:$e.last_name)==null?void 0:we.toLowerCase().includes(l.toLowerCase())),Le=v==="all"||oe.transaction_type===v,be=T==="all"||oe.lead_source_id===T,Re=P==="all"||oe.client_type_id===P,Ie=!L||oe.is_win;return pe&&Le&&be&&Re&&Ie});return r?s.jsx(wi,{children:s.jsx(Di,{className:"p-6 space-y-4",children:[1,2,3].map(oe=>s.jsx(Mc,{className:"h-16 w-full"},oe))})}):s.jsxs(s.Fragment,{children:[s.jsxs(wi,{children:[s.jsx(Wh,{className:"pb-3",children:s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[s.jsxs(Kh,{children:["Transactions (",ie.length,")"]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("div",{className:"relative",children:[s.jsx(ef,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),s.jsx(hn,{placeholder:"Search...",value:l,onChange:oe=>g(oe.target.value),className:"pl-8 w-[150px]"})]}),s.jsxs(Xo,{value:v,onValueChange:E,children:[s.jsx(Mo,{className:"w-[100px]",children:s.jsx(Qo,{placeholder:"Type"})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"all",children:"All Types"}),s.jsx($n,{value:"buyer",children:"Buyer"}),s.jsx($n,{value:"seller",children:"Seller"})]})]}),s.jsxs(Xo,{value:T,onValueChange:j,children:[s.jsx(Mo,{className:"w-[130px]",children:s.jsx(Qo,{placeholder:"Lead Source"})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"all",children:"All Sources"}),G==null?void 0:G.map(oe=>s.jsx($n,{value:oe.id,children:oe.name},oe.id))]})]}),s.jsxs(Jt,{variant:L?"default":"outline",size:"sm",onClick:()=>O(!L),children:[s.jsx(_E,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),s.jsx(Di,{children:ie.length===0?s.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):Z?s.jsx("div",{className:"space-y-3",children:ie.map(oe=>s.jsxs(wi,{className:"p-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"font-medium truncate",children:oe.property_address}),oe.is_win&&s.jsx(_E,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[oe.city,oe.state?`, ${oe.state}`:""]})]}),s.jsx(Js,{variant:oe.transaction_type==="buyer"?"default":"secondary",children:oe.transaction_type})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3 text-sm",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Close Date: "}),Jse(oe.close_date)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Price: "}),Ho(oe.sale_price)]}),e&&oe.commission_amount&&s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),Ho(oe.commission_amount)]}),oe.lead_source&&s.jsxs("div",{children:[s.jsx("span",{className:"text-muted-foreground",children:"Source: "}),oe.lead_source.name]}),oe.contact&&s.jsxs("div",{className:"col-span-2",children:[s.jsx("span",{className:"text-muted-foreground",children:"Client: "}),oe.contact.first_name," ",oe.contact.last_name]}),n&&s.jsxs("div",{className:"col-span-2",children:[s.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),n[oe.owner_user_id]||"Unknown"]})]}),!i&&s.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[s.jsx(Jt,{variant:"ghost",size:"sm",onClick:()=>c(oe),children:s.jsx(Rq,{className:"h-4 w-4"})}),s.jsx(Jt,{variant:"ghost",size:"sm",onClick:()=>Q(oe),children:s.jsx(Cq,{className:"h-4 w-4"})}),s.jsx(Jt,{variant:"ghost",size:"sm",onClick:()=>p(oe.id),children:s.jsx(iF,{className:"h-4 w-4 text-destructive"})})]})]},oe.id))}):s.jsx("div",{className:"overflow-x-auto",children:s.jsxs($Z,{children:[s.jsx(UZ,{children:s.jsxs(xC,{children:[n&&s.jsx(Cu,{children:"Agent"}),s.jsx(Cu,{children:"Property"}),s.jsx(Cu,{children:"Type"}),s.jsx(Cu,{children:"Close Date"}),s.jsx(Cu,{children:"Sale Price"}),e&&s.jsx(Cu,{children:"Commission"}),s.jsx(Cu,{children:"Lead Source"}),s.jsx(Cu,{children:"Client"}),!i&&s.jsx(Cu,{className:"w-[50px]"})]})}),s.jsx(VZ,{children:ie.map(oe=>{var pe;return s.jsxs(xC,{children:[n&&s.jsx(Pu,{className:"font-medium text-sm",children:n[oe.owner_user_id]||"Unknown"}),s.jsx(Pu,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[oe.is_win&&s.jsx(_E,{className:"h-4 w-4 text-yellow-500"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium",children:oe.property_address}),s.jsxs("div",{className:"text-sm text-muted-foreground",children:[oe.city,oe.state?`, ${oe.state}`:""]})]})]})}),s.jsx(Pu,{children:s.jsx(Js,{variant:oe.transaction_type==="buyer"?"default":"secondary",children:oe.transaction_type})}),s.jsx(Pu,{children:Jse(oe.close_date)}),s.jsx(Pu,{children:Ho(oe.sale_price)}),e&&s.jsx(Pu,{children:oe.commission_amount?Ho(oe.commission_amount):"-"}),s.jsx(Pu,{children:((pe=oe.lead_source)==null?void 0:pe.name)||"-"}),s.jsx(Pu,{children:oe.contact?`${oe.contact.first_name} ${oe.contact.last_name||""}`.trim():"-"}),!i&&s.jsx(Pu,{children:s.jsxs(UP,{children:[s.jsx(VP,{asChild:!0,children:s.jsx(Jt,{variant:"ghost",size:"icon",children:s.jsx(G4e,{className:"h-4 w-4"})})}),s.jsxs(xA,{align:"end",children:[s.jsxs(lh,{onClick:()=>c(oe),children:[s.jsx(Rq,{className:"h-4 w-4 mr-2"}),"Edit"]}),s.jsxs(lh,{onClick:()=>Q(oe),children:[s.jsx(Cq,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),s.jsxs(lh,{onClick:()=>p(oe.id),className:"text-destructive",children:[s.jsx(iF,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},oe.id)})})]})})})]}),s.jsx(e2e,{open:!!a,onOpenChange:oe=>!oe&&c(null),transaction:a||void 0}),s.jsx(e0e,{open:!!d,onOpenChange:oe=>!oe&&p(null),children:s.jsxs(lK,{children:[s.jsxs(cK,{children:[s.jsx(dK,{children:"Delete Transaction?"}),s.jsx(hK,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),s.jsxs(uK,{children:[s.jsx(mK,{children:"Cancel"}),s.jsx(fK,{onClick:ee,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}var sdt=Object.defineProperty,lx=(t,e)=>sdt(t,"name",{value:e,configurable:!0}),r2e="Progress",KZ=100,[adt,rXt]=Nl(r2e),[odt,ldt]=adt(r2e),n2e=N.forwardRef(lx(function(e,r){const{__scopeProgress:n,value:i=null,max:a,getValueLabel:c=i2e,...d}=e;(a||a===0)&&!O9(a)&&console.error(s2e(`${a}`,"Progress"));const p=O9(a)?a:KZ;i!==null&&!F9(i,p)&&console.error(a2e(`${i}`,"Progress"));const l=F9(i,p)?i:null,g=vC(l)?c(l,p):void 0;return s.jsx(odt,{scope:n,value:l,max:p,children:s.jsx(An.div,{"aria-valuemax":p,"aria-valuemin":0,"aria-valuenow":vC(l)?l:void 0,"aria-valuetext":g,role:"progressbar","data-state":YZ(l,p),"data-value":l??void 0,"data-max":p,...d,ref:r})})},"Progress")),cdt="ProgressIndicator",udt=N.forwardRef(lx(function(e,r){const{__scopeProgress:n,...i}=e,a=ldt(cdt,n);return s.jsx(An.div,{"data-state":YZ(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...i,ref:r})},"ProgressIndicator"));function i2e(t,e){return`${Math.round(t/e*100)}%`}lx(i2e,"defaultGetValueLabel");function YZ(t,e){return t==null?"indeterminate":t===e?"complete":"loading"}lx(YZ,"getProgressState");function vC(t){return typeof t=="number"}lx(vC,"isNumber");function O9(t){return vC(t)&&!isNaN(t)&&t>0}lx(O9,"isValidMaxNumber");function F9(t,e){return vC(t)&&!isNaN(t)&&t<=e&&t>=0}lx(F9,"isValidValueNumber");function s2e(t,e){return`Invalid prop \`max\` of value \`${t}\` supplied to \`${e}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${KZ}\`.`}lx(s2e,"getInvalidMaxError");function a2e(t,e){return`Invalid prop \`value\` of value \`${t}\` supplied to \`${e}\`. The \`value\` prop must be: - a positive number - less than the value passed to \`max\` (or ${KZ} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}lx(a2e,"getInvalidValueError");const pO=N.forwardRef(({className:t,value:e,...r},n)=>s.jsx(n2e,{ref:n,className:hr("relative h-4 w-full overflow-hidden rounded-full bg-secondary",t),...r,children:s.jsx(udt,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(e||0)}%)`}})}));pO.displayName=n2e.displayName;function ddt({goals:t,stats:e,year:r,showCommission:n}){const i=new Date().getMonth()+1,a=new Date().getFullYear()===r?i:12,c=12-a,d=(E,T)=>{if(!T||T===0)return null;const j=Math.min(E/T*100,100),P=Math.max(T-E,0),C=c>0?P/c:0,L=a/12*100,O=j>=L?"ahead":j>=L*.8?"on-track":"behind";return{percent:j,remaining:P,pace:C,status:O}},p=d(e.totalTransactions,t.transactions_goal),l=d(e.totalVolume,t.volume_goal),g=n?d(e.totalCommission,t.gci_goal):null,v=E=>{switch(E){case"ahead":return s.jsxs(Js,{className:"bg-green-500 text-white",children:[s.jsx(iA,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return s.jsxs(Js,{variant:"secondary",children:[s.jsx(o5e,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return s.jsxs(Js,{variant:"destructive",children:[s.jsx(gve,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!t.transactions_goal&&!t.volume_goal&&!t.gci_goal?null:s.jsxs(wi,{children:[s.jsx(Wh,{className:"pb-3",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(eK,{className:"h-5 w-5 text-primary"}),s.jsxs(Kh,{children:[r," Goals Progress"]})]})}),s.jsx(Di,{children:s.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[t.transactions_goal&&p&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:"Transactions"}),v(p.status)]}),s.jsx(pO,{value:p.percent,className:"h-2"}),s.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[s.jsxs("span",{children:[e.totalTransactions," of ",t.transactions_goal]}),s.jsxs("span",{children:[Math.round(p.percent),"%"]})]}),p.remaining>0&&c>0&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Math.ceil(p.pace),"/month to hit goal"]})]}),t.volume_goal&&l&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:"Volume"}),v(l.status)]}),s.jsx(pO,{value:l.percent,className:"h-2"}),s.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[s.jsxs("span",{children:[Ho(e.totalVolume,!0)," of ",Ho(t.volume_goal,!0)]}),s.jsxs("span",{children:[Math.round(l.percent),"%"]})]}),l.remaining>0&&c>0&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Ho(l.pace,!0),"/month"]})]}),n&&t.gci_goal&&g&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm font-medium",children:"GCI"}),v(g.status)]}),s.jsx(pO,{value:g.percent,className:"h-2"}),s.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[s.jsxs("span",{children:[Ho(e.totalCommission,!0)," of ",Ho(t.gci_goal,!0)]}),s.jsxs("span",{children:[Math.round(g.percent),"%"]})]}),g.remaining>0&&c>0&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Ho(g.pace,!0),"/month"]})]})]})})]})}var hdt=Array.isArray,bh=hdt,fdt=typeof Ou=="object"&&Ou&&Ou.Object===Object&&Ou,o2e=fdt,mdt=o2e,pdt=typeof self=="object"&&self&&self.Object===Object&&self,gdt=mdt||pdt||Function("return this")(),Tg=gdt,ydt=Tg,xdt=ydt.Symbol,iN=xdt,xue=iN,l2e=Object.prototype,_dt=l2e.hasOwnProperty,vdt=l2e.toString,uI=xue?xue.toStringTag:void 0;function bdt(t){var e=_dt.call(t,uI),r=t[uI];try{t[uI]=void 0;var n=!0}catch{}var i=vdt.call(t);return n&&(e?t[uI]=r:delete t[uI]),i}var wdt=bdt,Sdt=Object.prototype,Edt=Sdt.toString;function Tdt(t){return Edt.call(t)}var Adt=Tdt,_ue=iN,kdt=wdt,Idt=Adt,jdt="[object Null]",Cdt="[object Undefined]",vue=_ue?_ue.toStringTag:void 0;function Pdt(t){return t==null?t===void 0?Cdt:jdt:vue&&vue in Object(t)?kdt(t):Idt(t)}var cx=Pdt;function Ndt(t){return t!=null&&typeof t=="object"}var ux=Ndt,Rdt=cx,Ldt=ux,Ddt="[object Symbol]";function Mdt(t){return typeof t=="symbol"||Ldt(t)&&Rdt(t)==Ddt}var CA=Mdt,Odt=bh,Fdt=CA,Bdt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,zdt=/^\w*$/;function $dt(t,e){if(Odt(t))return!1;var r=typeof t;return r=="number"||r=="symbol"||r=="boolean"||t==null||Fdt(t)?!0:zdt.test(t)||!Bdt.test(t)||e!=null&&t in Object(e)}var ZZ=$dt;function Udt(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var Yv=Udt;const PA=ea(Yv);var Vdt=cx,qdt=Yv,Gdt="[object AsyncFunction]",Hdt="[object Function]",Wdt="[object GeneratorFunction]",Kdt="[object Proxy]";function Ydt(t){if(!qdt(t))return!1;var e=Vdt(t);return e==Hdt||e==Wdt||e==Gdt||e==Kdt}var XZ=Ydt;const Wi=ea(XZ);var Zdt=Tg,Xdt=Zdt["__core-js_shared__"],Qdt=Xdt,aV=Qdt,bue=function(){var t=/[^.]+$/.exec(aV&&aV.keys&&aV.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function Jdt(t){return!!bue&&bue in t}var eht=Jdt,tht=Function.prototype,rht=tht.toString;function nht(t){if(t!=null){try{return rht.call(t)}catch{}try{return t+""}catch{}}return""}var c2e=nht,iht=XZ,sht=eht,aht=Yv,oht=c2e,lht=/[\\^$.*+?()[\]{}|]/g,cht=/^\[object .+?Constructor\]$/,uht=Function.prototype,dht=Object.prototype,hht=uht.toString,fht=dht.hasOwnProperty,mht=RegExp("^"+hht.call(fht).replace(lht,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function pht(t){if(!aht(t)||sht(t))return!1;var e=iht(t)?mht:cht;return e.test(oht(t))}var ght=pht;function yht(t,e){return t==null?void 0:t[e]}var xht=yht,_ht=ght,vht=xht;function bht(t,e){var r=vht(t,e);return _ht(r)?r:void 0}var Cw=bht,wht=Cw,Sht=wht(Object,"create"),$5=Sht,wue=$5;function Eht(){this.__data__=wue?wue(null):{},this.size=0}var Tht=Eht;function Aht(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var kht=Aht,Iht=$5,jht="__lodash_hash_undefined__",Cht=Object.prototype,Pht=Cht.hasOwnProperty;function Nht(t){var e=this.__data__;if(Iht){var r=e[t];return r===jht?void 0:r}return Pht.call(e,t)?e[t]:void 0}var Rht=Nht,Lht=$5,Dht=Object.prototype,Mht=Dht.hasOwnProperty;function Oht(t){var e=this.__data__;return Lht?e[t]!==void 0:Mht.call(e,t)}var Fht=Oht,Bht=$5,zht="__lodash_hash_undefined__";function $ht(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=Bht&&e===void 0?zht:e,this}var Uht=$ht,Vht=Tht,qht=kht,Ght=Rht,Hht=Fht,Wht=Uht;function NA(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e-1}var uft=cft,dft=U5;function hft(t,e){var r=this.__data__,n=dft(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}var fft=hft,mft=Zht,pft=ift,gft=oft,yft=uft,xft=fft;function RA(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e0?1:-1},Pb=function(e){return fw(e)&&e.indexOf("%")===e.length-1},gn=function(e){return Fmt(e)&&!sN(e)},Umt=function(e){return fs(e)},Fc=function(e){return gn(e)||fw(e)},Vmt=0,aN=function(e){var r=++Vmt;return"".concat(e||"").concat(r)},Dd=function(e,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!gn(e)&&!fw(e))return n;var a;if(Pb(e)){var c=e.indexOf("%");a=r*parseFloat(e.slice(0,c))/100}else a=+e;return sN(a)&&(a=n),i&&a>r&&(a=r),a},F_=function(e){if(!e)return null;var r=Object.keys(e);return r&&r.length?e[r[0]]:null},qmt=function(e){if(!Array.isArray(e))return!1;for(var r=e.length,n={},i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Xmt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function z9(t){"@babel/helpers - typeof";return z9=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},z9(t)}var jue={click:"onClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",touchcancel:"onTouchCancel",touchend:"onTouchEnd",touchmove:"onTouchMove",touchstart:"onTouchStart",contextmenu:"onContextMenu",dblclick:"onDoubleClick"},My=function(e){return typeof e=="string"?e:e?e.displayName||e.name||"Component":""},Cue=null,lV=null,oX=function t(e){if(e===Cue&&Array.isArray(lV))return lV;var r=[];return N.Children.forEach(e,function(n){fs(n)||(Rmt.isFragment(n)?r=r.concat(t(n.props.children)):r.push(n))}),lV=r,Cue=e,r};function qf(t,e){var r=[],n=[];return Array.isArray(e)?n=e.map(function(i){return My(i)}):n=[My(e)],oX(t).forEach(function(i){var a=Xh(i,"type.displayName")||Xh(i,"type.name");n.indexOf(a)!==-1&&r.push(i)}),r}function Uh(t,e){var r=qf(t,e);return r&&r[0]}var Pue=function(e){if(!e||!e.props)return!1;var r=e.props,n=r.width,i=r.height;return!(!gn(n)||n<=0||!gn(i)||i<=0)},Qmt=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColormatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-url","foreignObject","g","glyph","glyphRef","hkern","image","line","lineGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"],Jmt=function(e){return e&&e.type&&fw(e.type)&&Qmt.indexOf(e.type)>=0},nXt=function(e){return e&&z9(e)==="object"&&"clipDot"in e},ept=function(e,r,n,i){var a,c=(a=oV==null?void 0:oV[i])!==null&&a!==void 0?a:[];return r.startsWith("data-")||!Wi(e)&&(i&&c.includes(r)||Wmt.includes(r))||n&&aX.includes(r)},$i=function(e,r,n){if(!e||typeof e=="function"||typeof e=="boolean")return null;var i=e;if(N.isValidElement(e)&&(i=e.props),!PA(i))return null;var a={};return Object.keys(i).forEach(function(c){var d;ept((d=i)===null||d===void 0?void 0:d[c],c,r,n)&&(a[c]=i[c])}),a},$9=function t(e,r){if(e===r)return!0;var n=N.Children.count(e);if(n!==N.Children.count(r))return!1;if(n===0)return!0;if(n===1)return Nue(Array.isArray(e)?e[0]:e,Array.isArray(r)?r[0]:r);for(var i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function spt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function V9(t){var e=t.children,r=t.width,n=t.height,i=t.viewBox,a=t.className,c=t.style,d=t.title,p=t.desc,l=ipt(t,npt),g=i||{width:r,height:n,x:0,y:0},v=hs("recharts-surface",a);return et.createElement("svg",U9({},$i(l,!0,"svg"),{className:v,width:r,height:n,style:c,viewBox:"".concat(g.x," ").concat(g.y," ").concat(g.width," ").concat(g.height)}),et.createElement("title",null,d),et.createElement("desc",null,p),e)}var apt=["children","className"];function q9(){return q9=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function lpt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var $a=et.forwardRef(function(t,e){var r=t.children,n=t.className,i=opt(t,apt),a=hs("recharts-layer",n);return et.createElement("g",q9({className:a},$i(i,!0),{ref:e}),r)}),rp=function(e,r){for(var n=arguments.length,i=new Array(n>2?n-2:0),a=2;ai?0:i+e),r=r>i?i:r,r<0&&(r+=i),i=e>r?0:r-e>>>0,e>>>=0;for(var a=Array(i);++n=n?t:dpt(t,e,r)}var fpt=hpt,mpt="\\ud800-\\udfff",ppt="\\u0300-\\u036f",gpt="\\ufe20-\\ufe2f",ypt="\\u20d0-\\u20ff",xpt=ppt+gpt+ypt,_pt="\\ufe0e\\ufe0f",vpt="\\u200d",bpt=RegExp("["+vpt+mpt+xpt+_pt+"]");function wpt(t){return bpt.test(t)}var _2e=wpt;function Spt(t){return t.split("")}var Ept=Spt,v2e="\\ud800-\\udfff",Tpt="\\u0300-\\u036f",Apt="\\ufe20-\\ufe2f",kpt="\\u20d0-\\u20ff",Ipt=Tpt+Apt+kpt,jpt="\\ufe0e\\ufe0f",Cpt="["+v2e+"]",G9="["+Ipt+"]",H9="\\ud83c[\\udffb-\\udfff]",Ppt="(?:"+G9+"|"+H9+")",b2e="[^"+v2e+"]",w2e="(?:\\ud83c[\\udde6-\\uddff]){2}",S2e="[\\ud800-\\udbff][\\udc00-\\udfff]",Npt="\\u200d",E2e=Ppt+"?",T2e="["+jpt+"]?",Rpt="(?:"+Npt+"(?:"+[b2e,w2e,S2e].join("|")+")"+T2e+E2e+")*",Lpt=T2e+E2e+Rpt,Dpt="(?:"+[b2e+G9+"?",G9,w2e,S2e,Cpt].join("|")+")",Mpt=RegExp(H9+"(?="+H9+")|"+Dpt+Lpt,"g");function Opt(t){return t.match(Mpt)||[]}var Fpt=Opt,Bpt=Ept,zpt=_2e,$pt=Fpt;function Upt(t){return zpt(t)?$pt(t):Bpt(t)}var Vpt=Upt,qpt=fpt,Gpt=_2e,Hpt=Vpt,Wpt=f2e;function Kpt(t){return function(e){e=Wpt(e);var r=Gpt(e)?Hpt(e):void 0,n=r?r[0]:e.charAt(0),i=r?qpt(r,1).join(""):e.slice(1);return n[t]()+i}}var Ypt=Kpt,Zpt=Ypt,Xpt=Zpt("toUpperCase"),Qpt=Xpt;const rB=ea(Qpt);function bo(t){return function(){return t}}const A2e=Math.cos,$F=Math.sin,cp=Math.sqrt,UF=Math.PI,nB=2*UF,W9=Math.PI,K9=2*W9,yb=1e-6,Jpt=K9-yb;function k2e(t){this._+=t[0];for(let e=1,r=t.length;e=0))throw new Error(`invalid digits: ${t}`);if(e>15)return k2e;const r=10**e;return function(n){this._+=n[0];for(let i=1,a=n.length;iyb)if(!(Math.abs(v*p-l*g)>yb)||!a)this._append`L${this._x1=e},${this._y1=r}`;else{let T=n-c,j=i-d,P=p*p+l*l,C=T*T+j*j,L=Math.sqrt(P),O=Math.sqrt(E),F=a*Math.tan((W9-Math.acos((P+E-C)/(2*L*O)))/2),$=F/O,G=F/L;Math.abs($-1)>yb&&this._append`L${e+$*g},${r+$*v}`,this._append`A${a},${a},0,0,${+(v*T>g*j)},${this._x1=e+G*p},${this._y1=r+G*l}`}}arc(e,r,n,i,a,c){if(e=+e,r=+r,n=+n,c=!!c,n<0)throw new Error(`negative radius: ${n}`);let d=n*Math.cos(i),p=n*Math.sin(i),l=e+d,g=r+p,v=1^c,E=c?i-a:a-i;this._x1===null?this._append`M${l},${g}`:(Math.abs(this._x1-l)>yb||Math.abs(this._y1-g)>yb)&&this._append`L${l},${g}`,n&&(E<0&&(E=E%K9+K9),E>Jpt?this._append`A${n},${n},0,1,${v},${e-d},${r-p}A${n},${n},0,1,${v},${this._x1=l},${this._y1=g}`:E>yb&&this._append`A${n},${n},0,${+(E>=W9)},${v},${this._x1=e+n*Math.cos(a)},${this._y1=r+n*Math.sin(a)}`)}rect(e,r,n,i){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+r}h${n=+n}v${+i}h${-n}Z`}toString(){return this._}}function lX(t){let e=3;return t.digits=function(r){if(!arguments.length)return e;if(r==null)e=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);e=n}return t},()=>new tgt(e)}function cX(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function I2e(t){this._context=t}I2e.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e);break}}};function iB(t){return new I2e(t)}function j2e(t){return t[0]}function C2e(t){return t[1]}function P2e(t,e){var r=bo(!0),n=null,i=iB,a=null,c=lX(d);t=typeof t=="function"?t:t===void 0?j2e:bo(t),e=typeof e=="function"?e:e===void 0?C2e:bo(e);function d(p){var l,g=(p=cX(p)).length,v,E=!1,T;for(n==null&&(a=i(T=c())),l=0;l<=g;++l)!(l=T;--j)d.point(F[j],$[j]);d.lineEnd(),d.areaEnd()}L&&(F[E]=+t(C,E,v),$[E]=+e(C,E,v),d.point(n?+n(C,E,v):F[E],r?+r(C,E,v):$[E]))}if(O)return d=null,O+""||null}function g(){return P2e().defined(i).curve(c).context(a)}return l.x=function(v){return arguments.length?(t=typeof v=="function"?v:bo(+v),n=null,l):t},l.x0=function(v){return arguments.length?(t=typeof v=="function"?v:bo(+v),l):t},l.x1=function(v){return arguments.length?(n=v==null?null:typeof v=="function"?v:bo(+v),l):n},l.y=function(v){return arguments.length?(e=typeof v=="function"?v:bo(+v),r=null,l):e},l.y0=function(v){return arguments.length?(e=typeof v=="function"?v:bo(+v),l):e},l.y1=function(v){return arguments.length?(r=v==null?null:typeof v=="function"?v:bo(+v),l):r},l.lineX0=l.lineY0=function(){return g().x(t).y(e)},l.lineY1=function(){return g().x(t).y(r)},l.lineX1=function(){return g().x(n).y(e)},l.defined=function(v){return arguments.length?(i=typeof v=="function"?v:bo(!!v),l):i},l.curve=function(v){return arguments.length?(c=v,a!=null&&(d=c(a)),l):c},l.context=function(v){return arguments.length?(v==null?a=d=null:d=c(a=v),l):a},l}class N2e{constructor(e,r){this._context=e,this._x=r}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,r){switch(e=+e,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,r,e,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,e,this._y0,e,r);break}}this._x0=e,this._y0=r}}function rgt(t){return new N2e(t,!0)}function ngt(t){return new N2e(t,!1)}const uX={draw(t,e){const r=cp(e/UF);t.moveTo(r,0),t.arc(0,0,r,0,nB)}},igt={draw(t,e){const r=cp(e/5)/2;t.moveTo(-3*r,-r),t.lineTo(-r,-r),t.lineTo(-r,-3*r),t.lineTo(r,-3*r),t.lineTo(r,-r),t.lineTo(3*r,-r),t.lineTo(3*r,r),t.lineTo(r,r),t.lineTo(r,3*r),t.lineTo(-r,3*r),t.lineTo(-r,r),t.lineTo(-3*r,r),t.closePath()}},R2e=cp(1/3),sgt=R2e*2,agt={draw(t,e){const r=cp(e/sgt),n=r*R2e;t.moveTo(0,-r),t.lineTo(n,0),t.lineTo(0,r),t.lineTo(-n,0),t.closePath()}},ogt={draw(t,e){const r=cp(e),n=-r/2;t.rect(n,n,r,r)}},lgt=.8908130915292852,L2e=$F(UF/10)/$F(7*UF/10),cgt=$F(nB/10)*L2e,ugt=-A2e(nB/10)*L2e,dgt={draw(t,e){const r=cp(e*lgt),n=cgt*r,i=ugt*r;t.moveTo(0,-r),t.lineTo(n,i);for(let a=1;a<5;++a){const c=nB*a/5,d=A2e(c),p=$F(c);t.lineTo(p*r,-d*r),t.lineTo(d*n-p*i,p*n+d*i)}t.closePath()}},cV=cp(3),hgt={draw(t,e){const r=-cp(e/(cV*3));t.moveTo(0,r*2),t.lineTo(-cV*r,-r),t.lineTo(cV*r,-r),t.closePath()}},Tf=-.5,Af=cp(3)/2,Y9=1/cp(12),fgt=(Y9/2+1)*3,mgt={draw(t,e){const r=cp(e/fgt),n=r/2,i=r*Y9,a=n,c=r*Y9+r,d=-a,p=c;t.moveTo(n,i),t.lineTo(a,c),t.lineTo(d,p),t.lineTo(Tf*n-Af*i,Af*n+Tf*i),t.lineTo(Tf*a-Af*c,Af*a+Tf*c),t.lineTo(Tf*d-Af*p,Af*d+Tf*p),t.lineTo(Tf*n+Af*i,Tf*i-Af*n),t.lineTo(Tf*a+Af*c,Tf*c-Af*a),t.lineTo(Tf*d+Af*p,Tf*p-Af*d),t.closePath()}};function pgt(t,e){let r=null,n=lX(i);t=typeof t=="function"?t:bo(t||uX),e=typeof e=="function"?e:bo(e===void 0?64:+e);function i(){let a;if(r||(r=a=n()),t.apply(this,arguments).draw(r,+e.apply(this,arguments)),a)return r=null,a+""||null}return i.type=function(a){return arguments.length?(t=typeof a=="function"?a:bo(a),i):t},i.size=function(a){return arguments.length?(e=typeof a=="function"?a:bo(+a),i):e},i.context=function(a){return arguments.length?(r=a??null,i):r},i}function VF(){}function qF(t,e,r){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+r)/6)}function D2e(t){this._context=t}D2e.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:qF(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:qF(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function ggt(t){return new D2e(t)}function M2e(t){this._context=t}M2e.prototype={areaStart:VF,areaEnd:VF,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:qF(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function ygt(t){return new M2e(t)}function O2e(t){this._context=t}O2e.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+t)/6,n=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:qF(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function xgt(t){return new O2e(t)}function F2e(t){this._context=t}F2e.prototype={areaStart:VF,areaEnd:VF,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))}};function _gt(t){return new F2e(t)}function Lue(t){return t<0?-1:1}function Due(t,e,r){var n=t._x1-t._x0,i=e-t._x1,a=(t._y1-t._y0)/(n||i<0&&-0),c=(r-t._y1)/(i||n<0&&-0),d=(a*i+c*n)/(n+i);return(Lue(a)+Lue(c))*Math.min(Math.abs(a),Math.abs(c),.5*Math.abs(d))||0}function Mue(t,e){var r=t._x1-t._x0;return r?(3*(t._y1-t._y0)/r-e)/2:e}function uV(t,e,r){var n=t._x0,i=t._y0,a=t._x1,c=t._y1,d=(a-n)/3;t._context.bezierCurveTo(n+d,i+d*e,a-d,c-d*r,a,c)}function GF(t){this._context=t}GF.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:uV(this,this._t0,Mue(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(t,e){var r=NaN;if(t=+t,e=+e,!(t===this._x1&&e===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,uV(this,Mue(this,r=Due(this,t,e)),r);break;default:uV(this,this._t0,r=Due(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=r}}};function B2e(t){this._context=new z2e(t)}(B2e.prototype=Object.create(GF.prototype)).point=function(t,e){GF.prototype.point.call(this,e,t)};function z2e(t){this._context=t}z2e.prototype={moveTo:function(t,e){this._context.moveTo(e,t)},closePath:function(){this._context.closePath()},lineTo:function(t,e){this._context.lineTo(e,t)},bezierCurveTo:function(t,e,r,n,i,a){this._context.bezierCurveTo(e,t,n,r,a,i)}};function vgt(t){return new GF(t)}function bgt(t){return new B2e(t)}function $2e(t){this._context=t}$2e.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var t=this._x,e=this._y,r=t.length;if(r)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),r===2)this._context.lineTo(t[1],e[1]);else for(var n=Oue(t),i=Oue(e),a=0,c=1;c=0;--e)i[e]=(c[e]-i[e+1])/a[e];for(a[r-1]=(t[r]+i[r-1])/2,e=0;e=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var r=this._x*(1-this._t)+t*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,e)}break}}this._x=t,this._y=e}};function Sgt(t){return new sB(t,.5)}function Egt(t){return new sB(t,0)}function Tgt(t){return new sB(t,1)}function vT(t,e){if((c=t.length)>1)for(var r=1,n,i,a=t[e[0]],c,d=a.length;r=0;)r[e]=e;return r}function Agt(t,e){return t[e]}function kgt(t){const e=[];return e.key=t,e}function Igt(){var t=bo([]),e=Z9,r=vT,n=Agt;function i(a){var c=Array.from(t.apply(this,arguments),kgt),d,p=c.length,l=-1,g;for(const v of a)for(d=0,++l;d0){for(var r,n,i=0,a=t[0].length,c;i0){for(var r=0,n=t[e[0]],i,a=n.length;r0)||!((a=(i=t[e[0]]).length)>0))){for(var r=0,n=1,i,a,c;n=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Ogt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var U2e={symbolCircle:uX,symbolCross:igt,symbolDiamond:agt,symbolSquare:ogt,symbolStar:dgt,symbolTriangle:hgt,symbolWye:mgt},Fgt=Math.PI/180,Bgt=function(e){var r="symbol".concat(rB(e));return U2e[r]||uX},zgt=function(e,r,n){if(r==="area")return e;switch(n){case"cross":return 5*e*e/9;case"diamond":return .5*e*e/Math.sqrt(3);case"square":return e*e;case"star":{var i=18*Fgt;return 1.25*e*e*(Math.tan(i)-Math.tan(i*2)*Math.pow(Math.tan(i),2))}case"triangle":return Math.sqrt(3)*e*e/4;case"wye":return(21-10*Math.sqrt(3))*e*e/8;default:return Math.PI*e*e/4}},$gt=function(e,r){U2e["symbol".concat(rB(e))]=r},dX=function(e){var r=e.type,n=r===void 0?"circle":r,i=e.size,a=i===void 0?64:i,c=e.sizeType,d=c===void 0?"area":c,p=Mgt(e,Ngt),l=Bue(Bue({},p),{},{type:n,size:a,sizeType:d}),g=function(){var C=Bgt(n),L=pgt().type(C).size(zgt(a,d,n));return L()},v=l.className,E=l.cx,T=l.cy,j=$i(l,!0);return E===+E&&T===+T&&a===+a?et.createElement("path",X9({},j,{className:hs("recharts-symbols",v),transform:"translate(".concat(E,", ").concat(T,")"),d:g()})):null};dX.registerSymbol=$gt;function bT(t){"@babel/helpers - typeof";return bT=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},bT(t)}function Q9(){return Q9=Object.assign?Object.assign.bind():function(t){for(var e=1;e`);var O=T.inactive?l:T.color;return et.createElement("li",Q9({className:C,style:v,key:"legend-item-".concat(j)},mw(n.props,T,j)),et.createElement(V9,{width:c,height:c,viewBox:g,style:E},n.renderIcon(T)),et.createElement("span",{className:"recharts-legend-item-text",style:{color:O}},P?P(L,T,j):L))})}},{key:"render",value:function(){var n=this.props,i=n.payload,a=n.layout,c=n.align;if(!i||!i.length)return null;var d={padding:0,margin:0,textAlign:a==="horizontal"?c:"left"};return et.createElement("ul",{className:"recharts-default-legend",style:d},this.renderItems())}}])}(N.PureComponent);wC(hX,"displayName","Legend");wC(hX,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var Xgt=V5;function Qgt(){this.__data__=new Xgt,this.size=0}var Jgt=Qgt;function eyt(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}var tyt=eyt;function ryt(t){return this.__data__.get(t)}var nyt=ryt;function iyt(t){return this.__data__.has(t)}var syt=iyt,ayt=V5,oyt=JZ,lyt=eX,cyt=200;function uyt(t,e){var r=this.__data__;if(r instanceof ayt){var n=r.__data__;if(!oyt||n.lengthd))return!1;var l=a.get(t),g=a.get(e);if(l&&g)return l==e&&g==t;var v=-1,E=!0,T=r&Nyt?new Iyt:void 0;for(a.set(t,e),a.set(e,t);++v-1&&t%1==0&&t-1&&t%1==0&&t<=Mxt}var gX=Oxt,Fxt=cx,Bxt=gX,zxt=ux,$xt="[object Arguments]",Uxt="[object Array]",Vxt="[object Boolean]",qxt="[object Date]",Gxt="[object Error]",Hxt="[object Function]",Wxt="[object Map]",Kxt="[object Number]",Yxt="[object Object]",Zxt="[object RegExp]",Xxt="[object Set]",Qxt="[object String]",Jxt="[object WeakMap]",e_t="[object ArrayBuffer]",t_t="[object DataView]",r_t="[object Float32Array]",n_t="[object Float64Array]",i_t="[object Int8Array]",s_t="[object Int16Array]",a_t="[object Int32Array]",o_t="[object Uint8Array]",l_t="[object Uint8ClampedArray]",c_t="[object Uint16Array]",u_t="[object Uint32Array]",No={};No[r_t]=No[n_t]=No[i_t]=No[s_t]=No[a_t]=No[o_t]=No[l_t]=No[c_t]=No[u_t]=!0;No[$xt]=No[Uxt]=No[e_t]=No[Vxt]=No[t_t]=No[qxt]=No[Gxt]=No[Hxt]=No[Wxt]=No[Kxt]=No[Yxt]=No[Zxt]=No[Xxt]=No[Qxt]=No[Jxt]=!1;function d_t(t){return zxt(t)&&Bxt(t.length)&&!!No[Fxt(t)]}var h_t=d_t;function f_t(t){return function(e){return t(e)}}var J2e=f_t,YF={exports:{}};YF.exports;(function(t,e){var r=o2e,n=e&&!e.nodeType&&e,i=n&&!0&&t&&!t.nodeType&&t,a=i&&i.exports===n,c=a&&r.process,d=function(){try{var p=i&&i.require&&i.require("util").types;return p||c&&c.binding&&c.binding("util")}catch{}}();t.exports=d})(YF,YF.exports);var m_t=YF.exports,p_t=h_t,g_t=J2e,Hue=m_t,Wue=Hue&&Hue.isTypedArray,y_t=Wue?g_t(Wue):p_t,eke=y_t,x_t=bxt,__t=mX,v_t=bh,b_t=Q2e,w_t=pX,S_t=eke,E_t=Object.prototype,T_t=E_t.hasOwnProperty;function A_t(t,e){var r=v_t(t),n=!r&&__t(t),i=!r&&!n&&b_t(t),a=!r&&!n&&!i&&S_t(t),c=r||n||i||a,d=c?x_t(t.length,String):[],p=d.length;for(var l in t)(e||T_t.call(t,l))&&!(c&&(l=="length"||i&&(l=="offset"||l=="parent")||a&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||w_t(l,p)))&&d.push(l);return d}var k_t=A_t,I_t=Object.prototype;function j_t(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||I_t;return t===r}var C_t=j_t;function P_t(t,e){return function(r){return t(e(r))}}var tke=P_t,N_t=tke,R_t=N_t(Object.keys,Object),L_t=R_t,D_t=C_t,M_t=L_t,O_t=Object.prototype,F_t=O_t.hasOwnProperty;function B_t(t){if(!D_t(t))return M_t(t);var e=[];for(var r in Object(t))F_t.call(t,r)&&r!="constructor"&&e.push(r);return e}var z_t=B_t,$_t=XZ,U_t=gX;function V_t(t){return t!=null&&U_t(t.length)&&!$_t(t)}var oN=V_t,q_t=k_t,G_t=z_t,H_t=oN;function W_t(t){return H_t(t)?q_t(t):G_t(t)}var aB=W_t,K_t=cxt,Y_t=_xt,Z_t=aB;function X_t(t){return K_t(t,Z_t,Y_t)}var Q_t=X_t,Kue=Q_t,J_t=1,evt=Object.prototype,tvt=evt.hasOwnProperty;function rvt(t,e,r,n,i,a){var c=r&J_t,d=Kue(t),p=d.length,l=Kue(e),g=l.length;if(p!=g&&!c)return!1;for(var v=p;v--;){var E=d[v];if(!(c?E in e:tvt.call(e,E)))return!1}var T=a.get(t),j=a.get(e);if(T&&j)return T==e&&j==t;var P=!0;a.set(t,e),a.set(e,t);for(var C=c;++v-1}var ebt=J0t;function tbt(t,e,r){for(var n=-1,i=t==null?0:t.length;++n=gbt){var l=e?null:mbt(t);if(l)return pbt(l);c=!1,i=fbt,p=new ubt}else p=e?[]:d;e:for(;++n=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Nbt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function Rbt(t){return t.value}function Lbt(t,e){if(et.isValidElement(t))return et.cloneElement(t,e);if(typeof t=="function")return et.createElement(t,e);e.ref;var r=Pbt(e,Sbt);return et.createElement(hX,r)}var ude=1,IE=function(t){function e(){var r;Ebt(this,e);for(var n=arguments.length,i=new Array(n),a=0;aude||Math.abs(i.height-this.lastBoundingBox.height)>ude)&&(this.lastBoundingBox.width=i.width,this.lastBoundingBox.height=i.height,n&&n(i)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,n&&n(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?oy({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var i=this.props,a=i.layout,c=i.align,d=i.verticalAlign,p=i.margin,l=i.chartWidth,g=i.chartHeight,v,E;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(c==="center"&&a==="vertical"){var T=this.getBBoxSnapshot();v={left:((l||0)-T.width)/2}}else v=c==="right"?{right:p&&p.right||0}:{left:p&&p.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(d==="middle"){var j=this.getBBoxSnapshot();E={top:((g||0)-j.height)/2}}else E=d==="bottom"?{bottom:p&&p.bottom||0}:{top:p&&p.top||0};return oy(oy({},v),E)}},{key:"render",value:function(){var n=this,i=this.props,a=i.content,c=i.width,d=i.height,p=i.wrapperStyle,l=i.payloadUniqBy,g=i.payload,v=oy(oy({position:"absolute",width:c||"auto",height:d||"auto"},this.getDefaultPosition(p)),p);return et.createElement("div",{className:"recharts-legend-wrapper",style:v,ref:function(T){n.wrapperNode=T}},Lbt(a,oy(oy({},this.props),{},{payload:lke(g,l,Rbt)})))}}],[{key:"getWithHeight",value:function(n,i){var a=oy(oy({},this.defaultProps),n.props),c=a.layout;return c==="vertical"&&gn(n.props.height)?{height:n.props.height}:c==="horizontal"?{width:n.props.width||i}:null}}])}(N.PureComponent);oB(IE,"displayName","Legend");oB(IE,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var dde=iN,Dbt=mX,Mbt=bh,hde=dde?dde.isConcatSpreadable:void 0;function Obt(t){return Mbt(t)||Dbt(t)||!!(hde&&t&&t[hde])}var Fbt=Obt,Bbt=Z2e,zbt=Fbt;function dke(t,e,r,n,i){var a=-1,c=t.length;for(r||(r=zbt),i||(i=[]);++a0&&r(d)?e>1?dke(d,e-1,r,n,i):Bbt(i,d):n||(i[i.length]=d)}return i}var hke=dke;function $bt(t){return function(e,r,n){for(var i=-1,a=Object(e),c=n(e),d=c.length;d--;){var p=c[t?d:++i];if(r(a[p],p,a)===!1)break}return e}}var Ubt=$bt,Vbt=Ubt,qbt=Vbt(),Gbt=qbt,Hbt=Gbt,Wbt=aB;function Kbt(t,e){return t&&Hbt(t,e,Wbt)}var fke=Kbt,Ybt=oN;function Zbt(t,e){return function(r,n){if(r==null)return r;if(!Ybt(r))return t(r,n);for(var i=r.length,a=e?i:-1,c=Object(r);(e?a--:++ae||a&&c&&p&&!d&&!l||n&&c&&p||!r&&p||!i)return 1;if(!n&&!a&&!l&&t=d)return p;var l=r[n];return p*(l=="desc"?-1:1)}}return t.index-e.index}var uwt=cwt,mV=rX,dwt=nX,hwt=Ag,fwt=mke,mwt=swt,pwt=J2e,gwt=uwt,ywt=OA,xwt=bh;function _wt(t,e,r){e.length?e=mV(e,function(a){return xwt(a)?function(c){return dwt(c,a.length===1?a[0]:a)}:a}):e=[ywt];var n=-1;e=mV(e,pwt(hwt));var i=fwt(t,function(a,c,d){var p=mV(e,function(l){return l(a)});return{criteria:p,index:++n,value:a}});return mwt(i,function(a,c){return gwt(a,c,r)})}var vwt=_wt;function bwt(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var wwt=bwt,Swt=wwt,mde=Math.max;function Ewt(t,e,r){return e=mde(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,a=mde(n.length-e,0),c=Array(a);++i0){if(++e>=Lwt)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}var Fwt=Owt,Bwt=Rwt,zwt=Fwt,$wt=zwt(Bwt),Uwt=$wt,Vwt=OA,qwt=Twt,Gwt=Uwt;function Hwt(t,e){return Gwt(qwt(t,e,Vwt),t+"")}var Wwt=Hwt,Kwt=QZ,Ywt=oN,Zwt=pX,Xwt=Yv;function Qwt(t,e,r){if(!Xwt(r))return!1;var n=typeof e;return(n=="number"?Ywt(r)&&Zwt(e,r.length):n=="string"&&e in r)?Kwt(r[e],t):!1}var lB=Qwt,Jwt=hke,e1t=vwt,t1t=Wwt,gde=lB,r1t=t1t(function(t,e){if(t==null)return[];var r=e.length;return r>1&&gde(t,e[0],e[1])?e=[]:r>2&&gde(e[0],e[1],e[2])&&(e=[e[0]]),e1t(t,Jwt(e,1),[])}),n1t=r1t;const _X=ea(n1t);function SC(t){"@babel/helpers - typeof";return SC=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},SC(t)}function a7(){return a7=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r=e.x),"".concat(dI,"-left"),gn(r)&&e&&gn(e.x)&&r=e.y),"".concat(dI,"-top"),gn(n)&&e&&gn(e.y)&&nP?Math.max(g,p[n]):Math.max(v,p[n])}function x1t(t){var e=t.translateX,r=t.translateY,n=t.useTranslate3d;return{transform:n?"translate3d(".concat(e,"px, ").concat(r,"px, 0)"):"translate(".concat(e,"px, ").concat(r,"px)")}}function _1t(t){var e=t.allowEscapeViewBox,r=t.coordinate,n=t.offsetTopLeft,i=t.position,a=t.reverseDirection,c=t.tooltipBox,d=t.useTranslate3d,p=t.viewBox,l,g,v;return c.height>0&&c.width>0&&r?(g=_de({allowEscapeViewBox:e,coordinate:r,key:"x",offsetTopLeft:n,position:i,reverseDirection:a,tooltipDimension:c.width,viewBox:p,viewBoxDimension:p.width}),v=_de({allowEscapeViewBox:e,coordinate:r,key:"y",offsetTopLeft:n,position:i,reverseDirection:a,tooltipDimension:c.height,viewBox:p,viewBoxDimension:p.height}),l=x1t({translateX:g,translateY:v,useTranslate3d:d})):l=g1t,{cssProperties:l,cssClasses:y1t({translateX:g,translateY:v,coordinate:r})}}function ST(t){"@babel/helpers - typeof";return ST=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ST(t)}function vde(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function bde(t){for(var e=1;ewde||Math.abs(n.height-this.state.lastBoundingBox.height)>wde)&&this.setState({lastBoundingBox:{width:n.width,height:n.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var n,i;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==this.state.dismissedAtCoordinate.x||((i=this.props.coordinate)===null||i===void 0?void 0:i.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var n=this,i=this.props,a=i.active,c=i.allowEscapeViewBox,d=i.animationDuration,p=i.animationEasing,l=i.children,g=i.coordinate,v=i.hasPayload,E=i.isAnimationActive,T=i.offset,j=i.position,P=i.reverseDirection,C=i.useTranslate3d,L=i.viewBox,O=i.wrapperStyle,F=_1t({allowEscapeViewBox:c,coordinate:g,offsetTopLeft:T,position:j,reverseDirection:P,tooltipBox:this.state.lastBoundingBox,useTranslate3d:C,viewBox:L}),$=F.cssClasses,G=F.cssProperties,W=bde(bde({transition:E&&a?"transform ".concat(d,"ms ").concat(p):void 0},G),{},{pointerEvents:"none",visibility:!this.state.dismissed&&a&&v?"visible":"hidden",position:"absolute",top:0,left:0},O);return et.createElement("div",{tabIndex:-1,className:$,style:W,ref:function(Q){n.wrapperNode=Q}},l)}}])}(N.PureComponent),j1t=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},FA={isSsr:j1t()};function ET(t){"@babel/helpers - typeof";return ET=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ET(t)}function Sde(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function Ede(t){for(var e=1;e0;return et.createElement(I1t,{allowEscapeViewBox:c,animationDuration:d,animationEasing:p,isAnimationActive:E,active:a,coordinate:g,hasPayload:W,offset:T,position:C,reverseDirection:L,useTranslate3d:O,viewBox:F,wrapperStyle:$},B1t(l,Ede(Ede({},this.props),{},{payload:G})))}}])}(N.PureComponent);vX(zm,"displayName","Tooltip");vX(zm,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!FA.isSsr,itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,viewBox:{x:0,y:0,height:0,width:0},wrapperStyle:{}});var z1t=Tg,$1t=function(){return z1t.Date.now()},U1t=$1t,V1t=/\s/;function q1t(t){for(var e=t.length;e--&&V1t.test(t.charAt(e)););return e}var G1t=q1t,H1t=G1t,W1t=/^\s+/;function K1t(t){return t&&t.slice(0,H1t(t)+1).replace(W1t,"")}var Y1t=K1t,Z1t=Y1t,Tde=Yv,X1t=CA,Ade=NaN,Q1t=/^[-+]0x[0-9a-f]+$/i,J1t=/^0b[01]+$/i,eSt=/^0o[0-7]+$/i,tSt=parseInt;function rSt(t){if(typeof t=="number")return t;if(X1t(t))return Ade;if(Tde(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=Tde(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=Z1t(t);var r=J1t.test(t);return r||eSt.test(t)?tSt(t.slice(2),r?2:8):Q1t.test(t)?Ade:+t}var vke=rSt,nSt=Yv,gV=U1t,kde=vke,iSt="Expected a function",sSt=Math.max,aSt=Math.min;function oSt(t,e,r){var n,i,a,c,d,p,l=0,g=!1,v=!1,E=!0;if(typeof t!="function")throw new TypeError(iSt);e=kde(e)||0,nSt(r)&&(g=!!r.leading,v="maxWait"in r,a=v?sSt(kde(r.maxWait)||0,e):a,E="trailing"in r?!!r.trailing:E);function T(W){var Z=n,Q=i;return n=i=void 0,l=W,c=t.apply(Q,Z),c}function j(W){return l=W,d=setTimeout(L,e),g?T(W):c}function P(W){var Z=W-p,Q=W-l,ee=e-Z;return v?aSt(ee,a-Q):ee}function C(W){var Z=W-p,Q=W-l;return p===void 0||Z>=e||Z<0||v&&Q>=a}function L(){var W=gV();if(C(W))return O(W);d=setTimeout(L,P(W))}function O(W){return d=void 0,E&&n?T(W):(n=i=void 0,c)}function F(){d!==void 0&&clearTimeout(d),l=0,n=p=i=d=void 0}function $(){return d===void 0?c:O(gV())}function G(){var W=gV(),Z=C(W);if(n=arguments,i=this,p=W,Z){if(d===void 0)return j(p);if(v)return clearTimeout(d),d=setTimeout(L,e),T(p)}return d===void 0&&(d=setTimeout(L,e)),c}return G.cancel=F,G.flush=$,G}var lSt=oSt,cSt=lSt,uSt=Yv,dSt="Expected a function";function hSt(t,e,r){var n=!0,i=!0;if(typeof t!="function")throw new TypeError(dSt);return uSt(r)&&(n="leading"in r?!!r.leading:n,i="trailing"in r?!!r.trailing:i),cSt(t,e,{leading:n,maxWait:e,trailing:i})}var fSt=hSt;const bke=ea(fSt);function TC(t){"@babel/helpers - typeof";return TC=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},TC(t)}function Ide(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function GD(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&(Le=bke(Le,P,{trailing:!0,leading:!1}));var be=new ResizeObserver(Le),Re=G.current.getBoundingClientRect(),Ie=Re.width,Te=Re.height;return oe(Ie,Te),be.observe(G.current),function(){be.disconnect()}},[oe,P]);var pe=N.useMemo(function(){var Le=ee.containerWidth,be=ee.containerHeight;if(Le<0||be<0)return null;rp(Pb(c)||Pb(p),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,c,p),rp(!r||r>0,"The aspect(%s) must be greater than zero.",r);var Re=Pb(c)?Le:c,Ie=Pb(p)?be:p;r&&r>0&&(Re?Ie=Re/r:Ie&&(Re=Ie*r),E&&Ie>E&&(Ie=E)),rp(Re>0||Ie>0,`The width(%s) and height(%s) of chart should be greater than 0, please check the style of container, or the props width(%s) and height(%s), or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the height and width.`,Re,Ie,c,p,g,v,r);var Te=!Array.isArray(T)&&My(T.type).endsWith("Chart");return et.Children.map(T,function(ge){return et.isValidElement(ge)?N.cloneElement(ge,GD({width:Re,height:Ie},Te?{style:GD({height:"100%",width:"100%",maxHeight:Ie,maxWidth:Re},ge.props.style)}:{})):ge})},[r,T,p,E,v,g,ee,c]);return et.createElement("div",{id:C?"".concat(C):void 0,className:hs("recharts-responsive-container",L),style:GD(GD({},$),{},{width:c,height:p,minWidth:g,minHeight:v,maxHeight:E}),ref:G},pe)}),cB=function(e){return null};cB.displayName="Cell";function AC(t){"@babel/helpers - typeof";return AC=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},AC(t)}function Cde(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function d7(t){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||FA.isSsr)return{width:0,height:0};var n=kSt(r),i=JSON.stringify({text:e,copyStyle:n});if(PS.widthCache[i])return PS.widthCache[i];try{var a=document.getElementById(Pde);a||(a=document.createElement("span"),a.setAttribute("id",Pde),a.setAttribute("aria-hidden","true"),document.body.appendChild(a));var c=d7(d7({},ASt),n);Object.assign(a.style,c),a.textContent="".concat(e);var d=a.getBoundingClientRect(),p={width:d.width,height:d.height};return PS.widthCache[i]=p,++PS.cacheCount>TSt&&(PS.cacheCount=0,PS.widthCache={}),p}catch{return{width:0,height:0}}},ISt=function(e){return{top:e.top+window.scrollY-document.documentElement.clientTop,left:e.left+window.scrollX-document.documentElement.clientLeft}};function kC(t){"@babel/helpers - typeof";return kC=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},kC(t)}function JF(t,e){return NSt(t)||PSt(t,e)||CSt(t,e)||jSt()}function jSt(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function CSt(t,e){if(t){if(typeof t=="string")return Nde(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Nde(t,e)}}function Nde(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function HSt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function Fde(t,e){return ZSt(t)||YSt(t,e)||KSt(t,e)||WSt()}function WSt(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function KSt(t,e){if(t){if(typeof t=="string")return Bde(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Bde(t,e)}}function Bde(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&arguments[0]!==void 0?arguments[0]:[];return Re.reduce(function(Ie,Te){var ge=Te.word,$e=Te.width,we=Ie[Ie.length-1];if(we&&(i==null||a||we.width+$e+nTe.width?Ie:Te})};if(!g)return T;for(var P="…",C=function(Re){var Ie=v.slice(0,Re),Te=Tke({breakAll:l,style:p,children:Ie+P}).wordsWithComputedWidth,ge=E(Te),$e=ge.length>c||j(ge).width>Number(i);return[$e,ge]},L=0,O=v.length-1,F=0,$;L<=O&&F<=v.length-1;){var G=Math.floor((L+O)/2),W=G-1,Z=C(W),Q=Fde(Z,2),ee=Q[0],ie=Q[1],oe=C(G),pe=Fde(oe,1),Le=pe[0];if(!ee&&!Le&&(L=G+1),ee&&Le&&(O=G-1),!ee&&Le){$=ie;break}F++}return $||T},zde=function(e){var r=fs(e)?[]:e.toString().split(Eke);return[{words:r}]},QSt=function(e){var r=e.width,n=e.scaleToFit,i=e.children,a=e.style,c=e.breakAll,d=e.maxLines;if((r||n)&&!FA.isSsr){var p,l,g=Tke({breakAll:c,children:i,style:a});if(g){var v=g.wordsWithComputedWidth,E=g.spaceWidth;p=v,l=E}else return zde(i);return XSt({breakAll:c,children:i,maxLines:d,style:a},p,l,r,n)}return zde(i)},$de="#808080",pw=function(e){var r=e.x,n=r===void 0?0:r,i=e.y,a=i===void 0?0:i,c=e.lineHeight,d=c===void 0?"1em":c,p=e.capHeight,l=p===void 0?"0.71em":p,g=e.scaleToFit,v=g===void 0?!1:g,E=e.textAnchor,T=E===void 0?"start":E,j=e.verticalAnchor,P=j===void 0?"end":j,C=e.fill,L=C===void 0?$de:C,O=Ode(e,qSt),F=N.useMemo(function(){return QSt({breakAll:O.breakAll,children:O.children,maxLines:O.maxLines,scaleToFit:v,style:O.style,width:O.width})},[O.breakAll,O.children,O.maxLines,v,O.style,O.width]),$=O.dx,G=O.dy,W=O.angle,Z=O.className,Q=O.breakAll,ee=Ode(O,GSt);if(!Fc(n)||!Fc(a))return null;var ie=n+(gn($)?$:0),oe=a+(gn(G)?G:0),pe;switch(P){case"start":pe=yV("calc(".concat(l,")"));break;case"middle":pe=yV("calc(".concat((F.length-1)/2," * -").concat(d," + (").concat(l," / 2))"));break;default:pe=yV("calc(".concat(F.length-1," * -").concat(d,")"));break}var Le=[];if(v){var be=F[0].width,Re=O.width;Le.push("scale(".concat((gn(Re)?Re/be:1)/be,")"))}return W&&Le.push("rotate(".concat(W,", ").concat(ie,", ").concat(oe,")")),Le.length&&(ee.transform=Le.join(" ")),et.createElement("text",h7({},$i(ee,!0),{x:ie,y:oe,className:hs("recharts-text",Z),textAnchor:T,fill:L.includes("url")?$de:L}),F.map(function(Ie,Te){var ge=Ie.words.join(Q?"":" ");return et.createElement("tspan",{x:ie,dy:Te===0?pe:d,key:"".concat(ge,"-").concat(Te)},ge)}))};function dv(t,e){return t==null||e==null?NaN:te?1:t>=e?0:NaN}function JSt(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function bX(t){let e,r,n;t.length!==2?(e=dv,r=(d,p)=>dv(t(d),p),n=(d,p)=>t(d)-p):(e=t===dv||t===JSt?t:eEt,r=t,n=t);function i(d,p,l=0,g=d.length){if(l>>1;r(d[v],p)<0?l=v+1:g=v}while(l>>1;r(d[v],p)<=0?l=v+1:g=v}while(ll&&n(d[v-1],p)>-n(d[v],p)?v-1:v}return{left:i,center:c,right:a}}function eEt(){return 0}function Ake(t){return t===null?NaN:+t}function*tEt(t,e){for(let r of t)r!=null&&(r=+r)>=r&&(yield r)}const rEt=bX(dv),lN=rEt.right;bX(Ake).center;class Ude extends Map{constructor(e,r=sEt){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),e!=null)for(const[n,i]of e)this.set(n,i)}get(e){return super.get(Vde(this,e))}has(e){return super.has(Vde(this,e))}set(e,r){return super.set(nEt(this,e),r)}delete(e){return super.delete(iEt(this,e))}}function Vde({_intern:t,_key:e},r){const n=e(r);return t.has(n)?t.get(n):r}function nEt({_intern:t,_key:e},r){const n=e(r);return t.has(n)?t.get(n):(t.set(n,r),r)}function iEt({_intern:t,_key:e},r){const n=e(r);return t.has(n)&&(r=t.get(n),t.delete(n)),r}function sEt(t){return t!==null&&typeof t=="object"?t.valueOf():t}function aEt(t=dv){if(t===dv)return kke;if(typeof t!="function")throw new TypeError("compare is not a function");return(e,r)=>{const n=t(e,r);return n||n===0?n:(t(r,r)===0)-(t(e,e)===0)}}function kke(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(te?1:0)}const oEt=Math.sqrt(50),lEt=Math.sqrt(10),cEt=Math.sqrt(2);function e3(t,e,r){const n=(e-t)/Math.max(0,r),i=Math.floor(Math.log10(n)),a=n/Math.pow(10,i),c=a>=oEt?10:a>=lEt?5:a>=cEt?2:1;let d,p,l;return i<0?(l=Math.pow(10,-i)/c,d=Math.round(t*l),p=Math.round(e*l),d/le&&--p,l=-l):(l=Math.pow(10,i)*c,d=Math.round(t/l),p=Math.round(e/l),d*le&&--p),p0))return[];if(t===e)return[t];const n=e=i))return[];const d=a-i+1,p=new Array(d);if(n)if(c<0)for(let l=0;l=n)&&(r=n);return r}function Gde(t,e){let r;for(const n of t)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function Ike(t,e,r=0,n=1/0,i){if(e=Math.floor(e),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(t.length-1,n)),!(r<=e&&e<=n))return t;for(i=i===void 0?kke:aEt(i);n>r;){if(n-r>600){const p=n-r+1,l=e-r+1,g=Math.log(p),v=.5*Math.exp(2*g/3),E=.5*Math.sqrt(g*v*(p-v)/p)*(l-p/2<0?-1:1),T=Math.max(r,Math.floor(e-l*v/p+E)),j=Math.min(n,Math.floor(e+(p-l)*v/p+E));Ike(t,e,T,j,i)}const a=t[e];let c=r,d=n;for(hI(t,r,e),i(t[n],a)>0&&hI(t,r,n);c0;)--d}i(t[r],a)===0?hI(t,r,d):(++d,hI(t,d,n)),d<=e&&(r=d+1),e<=d&&(n=d-1)}return t}function hI(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function uEt(t,e,r){if(t=Float64Array.from(tEt(t)),!(!(n=t.length)||isNaN(e=+e))){if(e<=0||n<2)return Gde(t);if(e>=1)return qde(t);var n,i=(n-1)*e,a=Math.floor(i),c=qde(Ike(t,a).subarray(0,a+1)),d=Gde(t.subarray(a+1));return c+(d-c)*(i-a)}}function dEt(t,e,r=Ake){if(!(!(n=t.length)||isNaN(e=+e))){if(e<=0||n<2)return+r(t[0],0,t);if(e>=1)return+r(t[n-1],n-1,t);var n,i=(n-1)*e,a=Math.floor(i),c=+r(t[a],a,t),d=+r(t[a+1],a+1,t);return c+(d-c)*(i-a)}}function hEt(t,e,r){t=+t,e=+e,r=(i=arguments.length)<2?(e=t,t=0,1):i<3?1:+r;for(var n=-1,i=Math.max(0,Math.ceil((e-t)/r))|0,a=new Array(i);++n>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):r===8?WD(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):r===4?WD(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=mEt.exec(t))?new uh(e[1],e[2],e[3],1):(e=pEt.exec(t))?new uh(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=gEt.exec(t))?WD(e[1],e[2],e[3],e[4]):(e=yEt.exec(t))?WD(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=xEt.exec(t))?Qde(e[1],e[2]/100,e[3]/100,1):(e=_Et.exec(t))?Qde(e[1],e[2]/100,e[3]/100,e[4]):Hde.hasOwnProperty(t)?Yde(Hde[t]):t==="transparent"?new uh(NaN,NaN,NaN,0):null}function Yde(t){return new uh(t>>16&255,t>>8&255,t&255,1)}function WD(t,e,r,n){return n<=0&&(t=e=r=NaN),new uh(t,e,r,n)}function wEt(t){return t instanceof cN||(t=PC(t)),t?(t=t.rgb(),new uh(t.r,t.g,t.b,t.opacity)):new uh}function y7(t,e,r,n){return arguments.length===1?wEt(t):new uh(t,e,r,n??1)}function uh(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}SX(uh,y7,Cke(cN,{brighter(t){return t=t==null?t3:Math.pow(t3,t),new uh(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?jC:Math.pow(jC,t),new uh(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new uh(Zb(this.r),Zb(this.g),Zb(this.b),r3(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Zde,formatHex:Zde,formatHex8:SEt,formatRgb:Xde,toString:Xde}));function Zde(){return`#${Nb(this.r)}${Nb(this.g)}${Nb(this.b)}`}function SEt(){return`#${Nb(this.r)}${Nb(this.g)}${Nb(this.b)}${Nb((isNaN(this.opacity)?1:this.opacity)*255)}`}function Xde(){const t=r3(this.opacity);return`${t===1?"rgb(":"rgba("}${Zb(this.r)}, ${Zb(this.g)}, ${Zb(this.b)}${t===1?")":`, ${t})`}`}function r3(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Zb(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Nb(t){return t=Zb(t),(t<16?"0":"")+t.toString(16)}function Qde(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new Hm(t,e,r,n)}function Pke(t){if(t instanceof Hm)return new Hm(t.h,t.s,t.l,t.opacity);if(t instanceof cN||(t=PC(t)),!t)return new Hm;if(t instanceof Hm)return t;t=t.rgb();var e=t.r/255,r=t.g/255,n=t.b/255,i=Math.min(e,r,n),a=Math.max(e,r,n),c=NaN,d=a-i,p=(a+i)/2;return d?(e===a?c=(r-n)/d+(r0&&p<1?0:c,new Hm(c,d,p,t.opacity)}function EEt(t,e,r,n){return arguments.length===1?Pke(t):new Hm(t,e,r,n??1)}function Hm(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}SX(Hm,EEt,Cke(cN,{brighter(t){return t=t==null?t3:Math.pow(t3,t),new Hm(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?jC:Math.pow(jC,t),new Hm(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*e,i=2*r-n;return new uh(xV(t>=240?t-240:t+120,i,n),xV(t,i,n),xV(t<120?t+240:t-120,i,n),this.opacity)},clamp(){return new Hm(Jde(this.h),KD(this.s),KD(this.l),r3(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=r3(this.opacity);return`${t===1?"hsl(":"hsla("}${Jde(this.h)}, ${KD(this.s)*100}%, ${KD(this.l)*100}%${t===1?")":`, ${t})`}`}}));function Jde(t){return t=(t||0)%360,t<0?t+360:t}function KD(t){return Math.max(0,Math.min(1,t||0))}function xV(t,e,r){return(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)*255}const EX=t=>()=>t;function TEt(t,e){return function(r){return t+r*e}}function AEt(t,e,r){return t=Math.pow(t,r),e=Math.pow(e,r)-t,r=1/r,function(n){return Math.pow(t+n*e,r)}}function kEt(t){return(t=+t)==1?Nke:function(e,r){return r-e?AEt(e,r,t):EX(isNaN(e)?r:e)}}function Nke(t,e){var r=e-t;return r?TEt(t,r):EX(isNaN(t)?e:t)}const ehe=function t(e){var r=kEt(e);function n(i,a){var c=r((i=y7(i)).r,(a=y7(a)).r),d=r(i.g,a.g),p=r(i.b,a.b),l=Nke(i.opacity,a.opacity);return function(g){return i.r=c(g),i.g=d(g),i.b=p(g),i.opacity=l(g),i+""}}return n.gamma=t,n}(1);function IEt(t,e){e||(e=[]);var r=t?Math.min(e.length,t.length):0,n=e.slice(),i;return function(a){for(i=0;ir&&(a=e.slice(r,a),d[c]?d[c]+=a:d[++c]=a),(n=n[0])===(i=i[0])?d[c]?d[c]+=i:d[++c]=i:(d[++c]=null,p.push({i:c,x:n3(n,i)})),r=_V.lastIndex;return re&&(r=t,t=e,e=r),function(n){return Math.max(t,Math.min(e,n))}}function BEt(t,e,r){var n=t[0],i=t[1],a=e[0],c=e[1];return i2?zEt:BEt,p=l=null,v}function v(E){return E==null||isNaN(E=+E)?a:(p||(p=d(t.map(n),e,r)))(n(c(E)))}return v.invert=function(E){return c(i((l||(l=d(e,t.map(n),n3)))(E)))},v.domain=function(E){return arguments.length?(t=Array.from(E,i3),g()):t.slice()},v.range=function(E){return arguments.length?(e=Array.from(E),g()):e.slice()},v.rangeRound=function(E){return e=Array.from(E),r=TX,g()},v.clamp=function(E){return arguments.length?(c=E?!0:Md,g()):c!==Md},v.interpolate=function(E){return arguments.length?(r=E,g()):r},v.unknown=function(E){return arguments.length?(a=E,v):a},function(E,T){return n=E,i=T,g()}}function AX(){return uB()(Md,Md)}function $Et(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function s3(t,e){if(!isFinite(t)||t===0)return null;var r=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"),n=t.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+t.slice(r+1)]}function TT(t){return t=s3(Math.abs(t)),t?t[1]:NaN}function UEt(t,e){return function(r,n){for(var i=r.length,a=[],c=0,d=t[0],p=0;i>0&&d>0&&(p+d+1>n&&(d=Math.max(1,n-p)),a.push(r.substring(i-=d,i+d)),!((p+=d+1)>n));)d=t[c=(c+1)%t.length];return a.reverse().join(e)}}function VEt(t){return function(e){return e.replace(/[0-9]/g,function(r){return t[+r]})}}var qEt=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function NC(t){if(!(e=qEt.exec(t)))throw new Error("invalid format: "+t);var e;return new kX({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}NC.prototype=kX.prototype;function kX(t){this.fill=t.fill===void 0?" ":t.fill+"",this.align=t.align===void 0?">":t.align+"",this.sign=t.sign===void 0?"-":t.sign+"",this.symbol=t.symbol===void 0?"":t.symbol+"",this.zero=!!t.zero,this.width=t.width===void 0?void 0:+t.width,this.comma=!!t.comma,this.precision=t.precision===void 0?void 0:+t.precision,this.trim=!!t.trim,this.type=t.type===void 0?"":t.type+""}kX.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function GEt(t){e:for(var e=t.length,r=1,n=-1,i;r0&&(n=0);break}return n>0?t.slice(0,n)+t.slice(i+1):t}var a3;function HEt(t,e){var r=s3(t,e);if(!r)return a3=void 0,t.toPrecision(e);var n=r[0],i=r[1],a=i-(a3=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,c=n.length;return a===c?n:a>c?n+new Array(a-c+1).join("0"):a>0?n.slice(0,a)+"."+n.slice(a):"0."+new Array(1-a).join("0")+s3(t,Math.max(0,e+a-1))[0]}function rhe(t,e){var r=s3(t,e);if(!r)return t+"";var n=r[0],i=r[1];return i<0?"0."+new Array(-i).join("0")+n:n.length>i+1?n.slice(0,i+1)+"."+n.slice(i+1):n+new Array(i-n.length+2).join("0")}const nhe={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:$Et,e:(t,e)=>t.toExponential(e),f:(t,e)=>t.toFixed(e),g:(t,e)=>t.toPrecision(e),o:t=>Math.round(t).toString(8),p:(t,e)=>rhe(t*100,e),r:rhe,s:HEt,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function ihe(t){return t}var she=Array.prototype.map,ahe=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function WEt(t){var e=t.grouping===void 0||t.thousands===void 0?ihe:UEt(she.call(t.grouping,Number),t.thousands+""),r=t.currency===void 0?"":t.currency[0]+"",n=t.currency===void 0?"":t.currency[1]+"",i=t.decimal===void 0?".":t.decimal+"",a=t.numerals===void 0?ihe:VEt(she.call(t.numerals,String)),c=t.percent===void 0?"%":t.percent+"",d=t.minus===void 0?"−":t.minus+"",p=t.nan===void 0?"NaN":t.nan+"";function l(v,E){v=NC(v);var T=v.fill,j=v.align,P=v.sign,C=v.symbol,L=v.zero,O=v.width,F=v.comma,$=v.precision,G=v.trim,W=v.type;W==="n"?(F=!0,W="g"):nhe[W]||($===void 0&&($=12),G=!0,W="g"),(L||T==="0"&&j==="=")&&(L=!0,T="0",j="=");var Z=(E&&E.prefix!==void 0?E.prefix:"")+(C==="$"?r:C==="#"&&/[boxX]/.test(W)?"0"+W.toLowerCase():""),Q=(C==="$"?n:/[%p]/.test(W)?c:"")+(E&&E.suffix!==void 0?E.suffix:""),ee=nhe[W],ie=/[defgprs%]/.test(W);$=$===void 0?6:/[gprs]/.test(W)?Math.max(1,Math.min(21,$)):Math.max(0,Math.min(20,$));function oe(pe){var Le=Z,be=Q,Re,Ie,Te;if(W==="c")be=ee(pe)+be,pe="";else{pe=+pe;var ge=pe<0||1/pe<0;if(pe=isNaN(pe)?p:ee(Math.abs(pe),$),G&&(pe=GEt(pe)),ge&&+pe==0&&P!=="+"&&(ge=!1),Le=(ge?P==="("?P:d:P==="-"||P==="("?"":P)+Le,be=(W==="s"&&!isNaN(pe)&&a3!==void 0?ahe[8+a3/3]:"")+be+(ge&&P==="("?")":""),ie){for(Re=-1,Ie=pe.length;++ReTe||Te>57){be=(Te===46?i+pe.slice(Re+1):pe.slice(Re))+be,pe=pe.slice(0,Re);break}}}F&&!L&&(pe=e(pe,1/0));var $e=Le.length+pe.length+be.length,we=$e>1)+Le+pe+be+we.slice($e);break;default:pe=we+Le+pe+be;break}return a(pe)}return oe.toString=function(){return v+""},oe}function g(v,E){var T=Math.max(-8,Math.min(8,Math.floor(TT(E)/3)))*3,j=Math.pow(10,-T),P=l((v=NC(v),v.type="f",v),{suffix:ahe[8+T/3]});return function(C){return P(j*C)}}return{format:l,formatPrefix:g}}var YD,IX,Rke;KEt({thousands:",",grouping:[3],currency:["$",""]});function KEt(t){return YD=WEt(t),IX=YD.format,Rke=YD.formatPrefix,YD}function YEt(t){return Math.max(0,-TT(Math.abs(t)))}function ZEt(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(TT(e)/3)))*3-TT(Math.abs(t)))}function XEt(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,TT(e)-TT(t))+1}function Lke(t,e,r,n){var i=p7(t,e,r),a;switch(n=NC(n??",f"),n.type){case"s":{var c=Math.max(Math.abs(t),Math.abs(e));return n.precision==null&&!isNaN(a=ZEt(i,c))&&(n.precision=a),Rke(n,c)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(a=XEt(i,Math.max(Math.abs(t),Math.abs(e))))&&(n.precision=a-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(a=YEt(i))&&(n.precision=a-(n.type==="%")*2);break}}return IX(n)}function Zv(t){var e=t.domain;return t.ticks=function(r){var n=e();return f7(n[0],n[n.length-1],r??10)},t.tickFormat=function(r,n){var i=e();return Lke(i[0],i[i.length-1],r??10,n)},t.nice=function(r){r==null&&(r=10);var n=e(),i=0,a=n.length-1,c=n[i],d=n[a],p,l,g=10;for(d0;){if(l=m7(c,d,r),l===p)return n[i]=c,n[a]=d,e(n);if(l>0)c=Math.floor(c/l)*l,d=Math.ceil(d/l)*l;else if(l<0)c=Math.ceil(c*l)/l,d=Math.floor(d*l)/l;else break;p=l}return t},t}function o3(){var t=AX();return t.copy=function(){return uN(t,o3())},Jf.apply(t,arguments),Zv(t)}function Dke(t){var e;function r(n){return n==null||isNaN(n=+n)?e:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(t=Array.from(n,i3),r):t.slice()},r.unknown=function(n){return arguments.length?(e=n,r):e},r.copy=function(){return Dke(t).unknown(e)},t=arguments.length?Array.from(t,i3):[0,1],Zv(r)}function Mke(t,e){t=t.slice();var r=0,n=t.length-1,i=t[r],a=t[n],c;return aMath.pow(t,e)}function rTt(t){return t===Math.E?Math.log:t===10&&Math.log10||t===2&&Math.log2||(t=Math.log(t),e=>Math.log(e)/t)}function che(t){return(e,r)=>-t(-e,r)}function jX(t){const e=t(ohe,lhe),r=e.domain;let n=10,i,a;function c(){return i=rTt(n),a=tTt(n),r()[0]<0?(i=che(i),a=che(a),t(QEt,JEt)):t(ohe,lhe),e}return e.base=function(d){return arguments.length?(n=+d,c()):n},e.domain=function(d){return arguments.length?(r(d),c()):r()},e.ticks=d=>{const p=r();let l=p[0],g=p[p.length-1];const v=g0){for(;E<=T;++E)for(j=1;jg)break;L.push(P)}}else for(;E<=T;++E)for(j=n-1;j>=1;--j)if(P=E>0?j/a(-E):j*a(E),!(Pg)break;L.push(P)}L.length*2{if(d==null&&(d=10),p==null&&(p=n===10?"s":","),typeof p!="function"&&(!(n%1)&&(p=NC(p)).precision==null&&(p.trim=!0),p=IX(p)),d===1/0)return p;const l=Math.max(1,n*d/e.ticks().length);return g=>{let v=g/a(Math.round(i(g)));return v*nr(Mke(r(),{floor:d=>a(Math.floor(i(d))),ceil:d=>a(Math.ceil(i(d)))})),e}function Oke(){const t=jX(uB()).domain([1,10]);return t.copy=()=>uN(t,Oke()).base(t.base()),Jf.apply(t,arguments),t}function uhe(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function dhe(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function CX(t){var e=1,r=t(uhe(e),dhe(e));return r.constant=function(n){return arguments.length?t(uhe(e=+n),dhe(e)):e},Zv(r)}function Fke(){var t=CX(uB());return t.copy=function(){return uN(t,Fke()).constant(t.constant())},Jf.apply(t,arguments)}function hhe(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function nTt(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function iTt(t){return t<0?-t*t:t*t}function PX(t){var e=t(Md,Md),r=1;function n(){return r===1?t(Md,Md):r===.5?t(nTt,iTt):t(hhe(r),hhe(1/r))}return e.exponent=function(i){return arguments.length?(r=+i,n()):r},Zv(e)}function NX(){var t=PX(uB());return t.copy=function(){return uN(t,NX()).exponent(t.exponent())},Jf.apply(t,arguments),t}function sTt(){return NX.apply(null,arguments).exponent(.5)}function fhe(t){return Math.sign(t)*t*t}function aTt(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function Bke(){var t=AX(),e=[0,1],r=!1,n;function i(a){var c=aTt(t(a));return isNaN(c)?n:r?Math.round(c):c}return i.invert=function(a){return t.invert(fhe(a))},i.domain=function(a){return arguments.length?(t.domain(a),i):t.domain()},i.range=function(a){return arguments.length?(t.range((e=Array.from(a,i3)).map(fhe)),i):e.slice()},i.rangeRound=function(a){return i.range(a).round(!0)},i.round=function(a){return arguments.length?(r=!!a,i):r},i.clamp=function(a){return arguments.length?(t.clamp(a),i):t.clamp()},i.unknown=function(a){return arguments.length?(n=a,i):n},i.copy=function(){return Bke(t.domain(),e).round(r).clamp(t.clamp()).unknown(n)},Jf.apply(i,arguments),Zv(i)}function zke(){var t=[],e=[],r=[],n;function i(){var c=0,d=Math.max(1,e.length);for(r=new Array(d-1);++c0?r[d-1]:t[0],d=r?[n[r-1],e]:[n[l-1],n[l]]},c.unknown=function(p){return arguments.length&&(a=p),c},c.thresholds=function(){return n.slice()},c.copy=function(){return $ke().domain([t,e]).range(i).unknown(a)},Jf.apply(Zv(c),arguments)}function Uke(){var t=[.5],e=[0,1],r,n=1;function i(a){return a!=null&&a<=a?e[lN(t,a,0,n)]:r}return i.domain=function(a){return arguments.length?(t=Array.from(a),n=Math.min(t.length,e.length-1),i):t.slice()},i.range=function(a){return arguments.length?(e=Array.from(a),n=Math.min(t.length,e.length-1),i):e.slice()},i.invertExtent=function(a){var c=e.indexOf(a);return[t[c-1],t[c]]},i.unknown=function(a){return arguments.length?(r=a,i):r},i.copy=function(){return Uke().domain(t).range(e).unknown(r)},Jf.apply(i,arguments)}const vV=new Date,bV=new Date;function $c(t,e,r,n){function i(a){return t(a=arguments.length===0?new Date:new Date(+a)),a}return i.floor=a=>(t(a=new Date(+a)),a),i.ceil=a=>(t(a=new Date(a-1)),e(a,1),t(a),a),i.round=a=>{const c=i(a),d=i.ceil(a);return a-c(e(a=new Date(+a),c==null?1:Math.floor(c)),a),i.range=(a,c,d)=>{const p=[];if(a=i.ceil(a),d=d==null?1:Math.floor(d),!(a0))return p;let l;do p.push(l=new Date(+a)),e(a,d),t(a);while(l$c(c=>{if(c>=c)for(;t(c),!a(c);)c.setTime(c-1)},(c,d)=>{if(c>=c)if(d<0)for(;++d<=0;)for(;e(c,-1),!a(c););else for(;--d>=0;)for(;e(c,1),!a(c););}),r&&(i.count=(a,c)=>(vV.setTime(+a),bV.setTime(+c),t(vV),t(bV),Math.floor(r(vV,bV))),i.every=a=>(a=Math.floor(a),!isFinite(a)||!(a>0)?null:a>1?i.filter(n?c=>n(c)%a===0:c=>i.count(0,c)%a===0):i)),i}const l3=$c(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);l3.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?$c(e=>{e.setTime(Math.floor(e/t)*t)},(e,r)=>{e.setTime(+e+r*t)},(e,r)=>(r-e)/t):l3);l3.range;const Ay=1e3,zf=Ay*60,ky=zf*60,Zy=ky*24,RX=Zy*7,mhe=Zy*30,wV=Zy*365,Rb=$c(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*Ay)},(t,e)=>(e-t)/Ay,t=>t.getUTCSeconds());Rb.range;const LX=$c(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Ay)},(t,e)=>{t.setTime(+t+e*zf)},(t,e)=>(e-t)/zf,t=>t.getMinutes());LX.range;const DX=$c(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*zf)},(t,e)=>(e-t)/zf,t=>t.getUTCMinutes());DX.range;const MX=$c(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Ay-t.getMinutes()*zf)},(t,e)=>{t.setTime(+t+e*ky)},(t,e)=>(e-t)/ky,t=>t.getHours());MX.range;const OX=$c(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*ky)},(t,e)=>(e-t)/ky,t=>t.getUTCHours());OX.range;const dN=$c(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*zf)/Zy,t=>t.getDate()-1);dN.range;const dB=$c(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Zy,t=>t.getUTCDate()-1);dB.range;const Vke=$c(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Zy,t=>Math.floor(t/Zy));Vke.range;function Pw(t){return $c(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(e,r)=>{e.setDate(e.getDate()+r*7)},(e,r)=>(r-e-(r.getTimezoneOffset()-e.getTimezoneOffset())*zf)/RX)}const hB=Pw(0),c3=Pw(1),oTt=Pw(2),lTt=Pw(3),AT=Pw(4),cTt=Pw(5),uTt=Pw(6);hB.range;c3.range;oTt.range;lTt.range;AT.range;cTt.range;uTt.range;function Nw(t){return $c(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCDate(e.getUTCDate()+r*7)},(e,r)=>(r-e)/RX)}const fB=Nw(0),u3=Nw(1),dTt=Nw(2),hTt=Nw(3),kT=Nw(4),fTt=Nw(5),mTt=Nw(6);fB.range;u3.range;dTt.range;hTt.range;kT.range;fTt.range;mTt.range;const FX=$c(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth());FX.range;const BX=$c(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth());BX.range;const Xy=$c(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());Xy.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:$c(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,r)=>{e.setFullYear(e.getFullYear()+r*t)});Xy.range;const Qy=$c(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());Qy.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:$c(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCFullYear(e.getUTCFullYear()+r*t)});Qy.range;function qke(t,e,r,n,i,a){const c=[[Rb,1,Ay],[Rb,5,5*Ay],[Rb,15,15*Ay],[Rb,30,30*Ay],[a,1,zf],[a,5,5*zf],[a,15,15*zf],[a,30,30*zf],[i,1,ky],[i,3,3*ky],[i,6,6*ky],[i,12,12*ky],[n,1,Zy],[n,2,2*Zy],[r,1,RX],[e,1,mhe],[e,3,3*mhe],[t,1,wV]];function d(l,g,v){const E=gC).right(c,E);if(T===c.length)return t.every(p7(l/wV,g/wV,v));if(T===0)return l3.every(Math.max(p7(l,g,v),1));const[j,P]=c[E/c[T-1][2]53)return null;"w"in ft||(ft.w=1),"Z"in ft?(ir=EV(fI(ft.y,0,1)),Gr=ir.getUTCDay(),ir=Gr>4||Gr===0?u3.ceil(ir):u3(ir),ir=dB.offset(ir,(ft.V-1)*7),ft.y=ir.getUTCFullYear(),ft.m=ir.getUTCMonth(),ft.d=ir.getUTCDate()+(ft.w+6)%7):(ir=SV(fI(ft.y,0,1)),Gr=ir.getDay(),ir=Gr>4||Gr===0?c3.ceil(ir):c3(ir),ir=dN.offset(ir,(ft.V-1)*7),ft.y=ir.getFullYear(),ft.m=ir.getMonth(),ft.d=ir.getDate()+(ft.w+6)%7)}else("W"in ft||"U"in ft)&&("w"in ft||(ft.w="u"in ft?ft.u%7:"W"in ft?1:0),Gr="Z"in ft?EV(fI(ft.y,0,1)).getUTCDay():SV(fI(ft.y,0,1)).getDay(),ft.m=0,ft.d="W"in ft?(ft.w+6)%7+ft.W*7-(Gr+5)%7:ft.w+ft.U*7-(Gr+6)%7);return"Z"in ft?(ft.H+=ft.Z/100|0,ft.M+=ft.Z%100,EV(ft)):SV(ft)}}function Q(Ct,Bt,cr,ft){for(var Kt=0,ir=Bt.length,Gr=cr.length,tr,Qt;Kt=Gr)return-1;if(tr=Bt.charCodeAt(Kt++),tr===37){if(tr=Bt.charAt(Kt++),Qt=G[tr in phe?Bt.charAt(Kt++):tr],!Qt||(ft=Qt(Ct,cr,ft))<0)return-1}else if(tr!=cr.charCodeAt(ft++))return-1}return ft}function ee(Ct,Bt,cr){var ft=l.exec(Bt.slice(cr));return ft?(Ct.p=g.get(ft[0].toLowerCase()),cr+ft[0].length):-1}function ie(Ct,Bt,cr){var ft=T.exec(Bt.slice(cr));return ft?(Ct.w=j.get(ft[0].toLowerCase()),cr+ft[0].length):-1}function oe(Ct,Bt,cr){var ft=v.exec(Bt.slice(cr));return ft?(Ct.w=E.get(ft[0].toLowerCase()),cr+ft[0].length):-1}function pe(Ct,Bt,cr){var ft=L.exec(Bt.slice(cr));return ft?(Ct.m=O.get(ft[0].toLowerCase()),cr+ft[0].length):-1}function Le(Ct,Bt,cr){var ft=P.exec(Bt.slice(cr));return ft?(Ct.m=C.get(ft[0].toLowerCase()),cr+ft[0].length):-1}function be(Ct,Bt,cr){return Q(Ct,e,Bt,cr)}function Re(Ct,Bt,cr){return Q(Ct,r,Bt,cr)}function Ie(Ct,Bt,cr){return Q(Ct,n,Bt,cr)}function Te(Ct){return c[Ct.getDay()]}function ge(Ct){return a[Ct.getDay()]}function $e(Ct){return p[Ct.getMonth()]}function we(Ct){return d[Ct.getMonth()]}function ke(Ct){return i[+(Ct.getHours()>=12)]}function Ae(Ct){return 1+~~(Ct.getMonth()/3)}function He(Ct){return c[Ct.getUTCDay()]}function ot(Ct){return a[Ct.getUTCDay()]}function nt(Ct){return p[Ct.getUTCMonth()]}function tt(Ct){return d[Ct.getUTCMonth()]}function vt(Ct){return i[+(Ct.getUTCHours()>=12)]}function Vt(Ct){return 1+~~(Ct.getUTCMonth()/3)}return{format:function(Ct){var Bt=W(Ct+="",F);return Bt.toString=function(){return Ct},Bt},parse:function(Ct){var Bt=Z(Ct+="",!1);return Bt.toString=function(){return Ct},Bt},utcFormat:function(Ct){var Bt=W(Ct+="",$);return Bt.toString=function(){return Ct},Bt},utcParse:function(Ct){var Bt=Z(Ct+="",!0);return Bt.toString=function(){return Ct},Bt}}}var phe={"-":"",_:" ",0:"0"},lu=/^\s*\d+/,vTt=/^%/,bTt=/[\\^$*+?|[\]().{}]/g;function fa(t,e,r){var n=t<0?"-":"",i=(n?-t:t)+"",a=i.length;return n+(a[e.toLowerCase(),r]))}function STt(t,e,r){var n=lu.exec(e.slice(r,r+1));return n?(t.w=+n[0],r+n[0].length):-1}function ETt(t,e,r){var n=lu.exec(e.slice(r,r+1));return n?(t.u=+n[0],r+n[0].length):-1}function TTt(t,e,r){var n=lu.exec(e.slice(r,r+2));return n?(t.U=+n[0],r+n[0].length):-1}function ATt(t,e,r){var n=lu.exec(e.slice(r,r+2));return n?(t.V=+n[0],r+n[0].length):-1}function kTt(t,e,r){var n=lu.exec(e.slice(r,r+2));return n?(t.W=+n[0],r+n[0].length):-1}function ghe(t,e,r){var n=lu.exec(e.slice(r,r+4));return n?(t.y=+n[0],r+n[0].length):-1}function yhe(t,e,r){var n=lu.exec(e.slice(r,r+2));return n?(t.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function ITt(t,e,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(r,r+6));return n?(t.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function jTt(t,e,r){var n=lu.exec(e.slice(r,r+1));return n?(t.q=n[0]*3-3,r+n[0].length):-1}function CTt(t,e,r){var n=lu.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function xhe(t,e,r){var n=lu.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function PTt(t,e,r){var n=lu.exec(e.slice(r,r+3));return n?(t.m=0,t.d=+n[0],r+n[0].length):-1}function _he(t,e,r){var n=lu.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function NTt(t,e,r){var n=lu.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function RTt(t,e,r){var n=lu.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function LTt(t,e,r){var n=lu.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function DTt(t,e,r){var n=lu.exec(e.slice(r,r+6));return n?(t.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function MTt(t,e,r){var n=vTt.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function OTt(t,e,r){var n=lu.exec(e.slice(r));return n?(t.Q=+n[0],r+n[0].length):-1}function FTt(t,e,r){var n=lu.exec(e.slice(r));return n?(t.s=+n[0],r+n[0].length):-1}function vhe(t,e){return fa(t.getDate(),e,2)}function BTt(t,e){return fa(t.getHours(),e,2)}function zTt(t,e){return fa(t.getHours()%12||12,e,2)}function $Tt(t,e){return fa(1+dN.count(Xy(t),t),e,3)}function Gke(t,e){return fa(t.getMilliseconds(),e,3)}function UTt(t,e){return Gke(t,e)+"000"}function VTt(t,e){return fa(t.getMonth()+1,e,2)}function qTt(t,e){return fa(t.getMinutes(),e,2)}function GTt(t,e){return fa(t.getSeconds(),e,2)}function HTt(t){var e=t.getDay();return e===0?7:e}function WTt(t,e){return fa(hB.count(Xy(t)-1,t),e,2)}function Hke(t){var e=t.getDay();return e>=4||e===0?AT(t):AT.ceil(t)}function KTt(t,e){return t=Hke(t),fa(AT.count(Xy(t),t)+(Xy(t).getDay()===4),e,2)}function YTt(t){return t.getDay()}function ZTt(t,e){return fa(c3.count(Xy(t)-1,t),e,2)}function XTt(t,e){return fa(t.getFullYear()%100,e,2)}function QTt(t,e){return t=Hke(t),fa(t.getFullYear()%100,e,2)}function JTt(t,e){return fa(t.getFullYear()%1e4,e,4)}function eAt(t,e){var r=t.getDay();return t=r>=4||r===0?AT(t):AT.ceil(t),fa(t.getFullYear()%1e4,e,4)}function tAt(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+fa(e/60|0,"0",2)+fa(e%60,"0",2)}function bhe(t,e){return fa(t.getUTCDate(),e,2)}function rAt(t,e){return fa(t.getUTCHours(),e,2)}function nAt(t,e){return fa(t.getUTCHours()%12||12,e,2)}function iAt(t,e){return fa(1+dB.count(Qy(t),t),e,3)}function Wke(t,e){return fa(t.getUTCMilliseconds(),e,3)}function sAt(t,e){return Wke(t,e)+"000"}function aAt(t,e){return fa(t.getUTCMonth()+1,e,2)}function oAt(t,e){return fa(t.getUTCMinutes(),e,2)}function lAt(t,e){return fa(t.getUTCSeconds(),e,2)}function cAt(t){var e=t.getUTCDay();return e===0?7:e}function uAt(t,e){return fa(fB.count(Qy(t)-1,t),e,2)}function Kke(t){var e=t.getUTCDay();return e>=4||e===0?kT(t):kT.ceil(t)}function dAt(t,e){return t=Kke(t),fa(kT.count(Qy(t),t)+(Qy(t).getUTCDay()===4),e,2)}function hAt(t){return t.getUTCDay()}function fAt(t,e){return fa(u3.count(Qy(t)-1,t),e,2)}function mAt(t,e){return fa(t.getUTCFullYear()%100,e,2)}function pAt(t,e){return t=Kke(t),fa(t.getUTCFullYear()%100,e,2)}function gAt(t,e){return fa(t.getUTCFullYear()%1e4,e,4)}function yAt(t,e){var r=t.getUTCDay();return t=r>=4||r===0?kT(t):kT.ceil(t),fa(t.getUTCFullYear()%1e4,e,4)}function xAt(){return"+0000"}function whe(){return"%"}function She(t){return+t}function Ehe(t){return Math.floor(+t/1e3)}var NS,Yke,Zke;_At({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function _At(t){return NS=_Tt(t),Yke=NS.format,NS.parse,Zke=NS.utcFormat,NS.utcParse,NS}function vAt(t){return new Date(t)}function bAt(t){return t instanceof Date?+t:+new Date(+t)}function zX(t,e,r,n,i,a,c,d,p,l){var g=AX(),v=g.invert,E=g.domain,T=l(".%L"),j=l(":%S"),P=l("%I:%M"),C=l("%I %p"),L=l("%a %d"),O=l("%b %d"),F=l("%B"),$=l("%Y");function G(W){return(p(W)e(i/(t.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(i,a)=>uEt(t,a/n))},r.copy=function(){return eIe(e).domain(t)},dx.apply(r,arguments)}function pB(){var t=0,e=.5,r=1,n=1,i,a,c,d,p,l=Md,g,v=!1,E;function T(P){return isNaN(P=+P)?E:(P=.5+((P=+g(P))-a)*(n*Pe}var iIe=IAt,jAt=gB,CAt=iIe,PAt=OA;function NAt(t){return t&&t.length?jAt(t,PAt,CAt):void 0}var RAt=NAt;const yB=ea(RAt);function LAt(t,e){return tt.e^a.s<0?1:-1;for(n=a.d.length,i=t.d.length,e=0,r=nt.d[e]^a.s<0?1:-1;return n===i?0:n>i^a.s<0?1:-1};Yn.decimalPlaces=Yn.dp=function(){var t=this,e=t.d.length-1,r=(e-t.e)*Ro;if(e=t.d[e],e)for(;e%10==0;e/=10)r--;return r<0?0:r};Yn.dividedBy=Yn.div=function(t){return Oy(this,new this.constructor(t))};Yn.dividedToIntegerBy=Yn.idiv=function(t){var e=this,r=e.constructor;return ho(Oy(e,new r(t),0,1),r.precision)};Yn.equals=Yn.eq=function(t){return!this.cmp(t)};Yn.exponent=function(){return fc(this)};Yn.greaterThan=Yn.gt=function(t){return this.cmp(t)>0};Yn.greaterThanOrEqualTo=Yn.gte=function(t){return this.cmp(t)>=0};Yn.isInteger=Yn.isint=function(){return this.e>this.d.length-2};Yn.isNegative=Yn.isneg=function(){return this.s<0};Yn.isPositive=Yn.ispos=function(){return this.s>0};Yn.isZero=function(){return this.s===0};Yn.lessThan=Yn.lt=function(t){return this.cmp(t)<0};Yn.lessThanOrEqualTo=Yn.lte=function(t){return this.cmp(t)<1};Yn.logarithm=Yn.log=function(t){var e,r=this,n=r.constructor,i=n.precision,a=i+5;if(t===void 0)t=new n(10);else if(t=new n(t),t.s<1||t.eq(Gh))throw Error(Wf+"NaN");if(r.s<1)throw Error(Wf+(r.s?"NaN":"-Infinity"));return r.eq(Gh)?new n(0):(Zo=!1,e=Oy(RC(r,a),RC(t,a),a),Zo=!0,ho(e,i))};Yn.minus=Yn.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?cIe(e,t):oIe(e,(t.s=-t.s,t))};Yn.modulo=Yn.mod=function(t){var e,r=this,n=r.constructor,i=n.precision;if(t=new n(t),!t.s)throw Error(Wf+"NaN");return r.s?(Zo=!1,e=Oy(r,t,0,1).times(t),Zo=!0,r.minus(e)):ho(new n(r),i)};Yn.naturalExponential=Yn.exp=function(){return lIe(this)};Yn.naturalLogarithm=Yn.ln=function(){return RC(this)};Yn.negated=Yn.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};Yn.plus=Yn.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?oIe(e,t):cIe(e,(t.s=-t.s,t))};Yn.precision=Yn.sd=function(t){var e,r,n,i=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(Xb+t);if(e=fc(i)+1,n=i.d.length-1,r=n*Ro+1,n=i.d[n],n){for(;n%10==0;n/=10)r--;for(n=i.d[0];n>=10;n/=10)r++}return t&&e>r?e:r};Yn.squareRoot=Yn.sqrt=function(){var t,e,r,n,i,a,c,d=this,p=d.constructor;if(d.s<1){if(!d.s)return new p(0);throw Error(Wf+"NaN")}for(t=fc(d),Zo=!1,i=Math.sqrt(+d),i==0||i==1/0?(e=Qp(d.d),(e.length+t)%2==0&&(e+="0"),i=Math.sqrt(e),t=$A((t+1)/2)-(t<0||t%2),i==1/0?e="5e"+t:(e=i.toExponential(),e=e.slice(0,e.indexOf("e")+1)+t),n=new p(e)):n=new p(i.toString()),r=p.precision,i=c=r+3;;)if(a=n,n=a.plus(Oy(d,a,c+2)).times(.5),Qp(a.d).slice(0,c)===(e=Qp(n.d)).slice(0,c)){if(e=e.slice(c-3,c+1),i==c&&e=="4999"){if(ho(a,r+1,0),a.times(a).eq(d)){n=a;break}}else if(e!="9999")break;c+=4}return Zo=!0,ho(n,r)};Yn.times=Yn.mul=function(t){var e,r,n,i,a,c,d,p,l,g=this,v=g.constructor,E=g.d,T=(t=new v(t)).d;if(!g.s||!t.s)return new v(0);for(t.s*=g.s,r=g.e+t.e,p=E.length,l=T.length,p=0;){for(e=0,i=p+n;i>n;)d=a[i]+T[n]*E[i-n-1]+e,a[i--]=d%Jc|0,e=d/Jc|0;a[i]=(a[i]+e)%Jc|0}for(;!a[--c];)a.pop();return e?++r:a.shift(),t.d=a,t.e=r,Zo?ho(t,v.precision):t};Yn.toDecimalPlaces=Yn.todp=function(t,e){var r=this,n=r.constructor;return r=new n(r),t===void 0?r:(xg(t,0,zA),e===void 0?e=n.rounding:xg(e,0,8),ho(r,t+fc(r)+1,e))};Yn.toExponential=function(t,e){var r,n=this,i=n.constructor;return t===void 0?r=gw(n,!0):(xg(t,0,zA),e===void 0?e=i.rounding:xg(e,0,8),n=ho(new i(n),t+1,e),r=gw(n,!0,t+1)),r};Yn.toFixed=function(t,e){var r,n,i=this,a=i.constructor;return t===void 0?gw(i):(xg(t,0,zA),e===void 0?e=a.rounding:xg(e,0,8),n=ho(new a(i),t+fc(i)+1,e),r=gw(n.abs(),!1,t+fc(n)+1),i.isneg()&&!i.isZero()?"-"+r:r)};Yn.toInteger=Yn.toint=function(){var t=this,e=t.constructor;return ho(new e(t),fc(t)+1,e.rounding)};Yn.toNumber=function(){return+this};Yn.toPower=Yn.pow=function(t){var e,r,n,i,a,c,d=this,p=d.constructor,l=12,g=+(t=new p(t));if(!t.s)return new p(Gh);if(d=new p(d),!d.s){if(t.s<1)throw Error(Wf+"Infinity");return d}if(d.eq(Gh))return d;if(n=p.precision,t.eq(Gh))return ho(d,n);if(e=t.e,r=t.d.length-1,c=e>=r,a=d.s,c){if((r=g<0?-g:g)<=aIe){for(i=new p(Gh),e=Math.ceil(n/Ro+4),Zo=!1;r%2&&(i=i.times(d),khe(i.d,e)),r=$A(r/2),r!==0;)d=d.times(d),khe(d.d,e);return Zo=!0,t.s<0?new p(Gh).div(i):ho(i,n)}}else if(a<0)throw Error(Wf+"NaN");return a=a<0&&t.d[Math.max(e,r)]&1?-1:1,d.s=1,Zo=!1,i=t.times(RC(d,n+l)),Zo=!0,i=lIe(i),i.s=a,i};Yn.toPrecision=function(t,e){var r,n,i=this,a=i.constructor;return t===void 0?(r=fc(i),n=gw(i,r<=a.toExpNeg||r>=a.toExpPos)):(xg(t,1,zA),e===void 0?e=a.rounding:xg(e,0,8),i=ho(new a(i),t,e),r=fc(i),n=gw(i,t<=r||r<=a.toExpNeg,t)),n};Yn.toSignificantDigits=Yn.tosd=function(t,e){var r=this,n=r.constructor;return t===void 0?(t=n.precision,e=n.rounding):(xg(t,1,zA),e===void 0?e=n.rounding:xg(e,0,8)),ho(new n(r),t,e)};Yn.toString=Yn.valueOf=Yn.val=Yn.toJSON=Yn[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=fc(t),r=t.constructor;return gw(t,e<=r.toExpNeg||e>=r.toExpPos)};function oIe(t,e){var r,n,i,a,c,d,p,l,g=t.constructor,v=g.precision;if(!t.s||!e.s)return e.s||(e=new g(t)),Zo?ho(e,v):e;if(p=t.d,l=e.d,c=t.e,i=e.e,p=p.slice(),a=c-i,a){for(a<0?(n=p,a=-a,d=l.length):(n=l,i=c,d=p.length),c=Math.ceil(v/Ro),d=c>d?c+1:d+1,a>d&&(a=d,n.length=1),n.reverse();a--;)n.push(0);n.reverse()}for(d=p.length,a=l.length,d-a<0&&(a=d,n=l,l=p,p=n),r=0;a;)r=(p[--a]=p[a]+l[a]+r)/Jc|0,p[a]%=Jc;for(r&&(p.unshift(r),++i),d=p.length;p[--d]==0;)p.pop();return e.d=p,e.e=i,Zo?ho(e,v):e}function xg(t,e,r){if(t!==~~t||tr)throw Error(Xb+t)}function Qp(t){var e,r,n,i=t.length-1,a="",c=t[0];if(i>0){for(a+=c,e=1;ec?1:-1;else for(d=p=0;di[d]?1:-1;break}return p}function r(n,i,a){for(var c=0;a--;)n[a]-=c,c=n[a]1;)n.shift()}return function(n,i,a,c){var d,p,l,g,v,E,T,j,P,C,L,O,F,$,G,W,Z,Q,ee=n.constructor,ie=n.s==i.s?1:-1,oe=n.d,pe=i.d;if(!n.s)return new ee(n);if(!i.s)throw Error(Wf+"Division by zero");for(p=n.e-i.e,Z=pe.length,G=oe.length,T=new ee(ie),j=T.d=[],l=0;pe[l]==(oe[l]||0);)++l;if(pe[l]>(oe[l]||0)&&--p,a==null?O=a=ee.precision:c?O=a+(fc(n)-fc(i))+1:O=a,O<0)return new ee(0);if(O=O/Ro+2|0,l=0,Z==1)for(g=0,pe=pe[0],O++;(l1&&(pe=t(pe,g),oe=t(oe,g),Z=pe.length,G=oe.length),$=Z,P=oe.slice(0,Z),C=P.length;C=Jc/2&&++W;do g=0,d=e(pe,P,Z,C),d<0?(L=P[0],Z!=C&&(L=L*Jc+(P[1]||0)),g=L/W|0,g>1?(g>=Jc&&(g=Jc-1),v=t(pe,g),E=v.length,C=P.length,d=e(v,P,E,C),d==1&&(g--,r(v,Z16)throw Error(VX+fc(t));if(!t.s)return new g(Gh);for(Zo=!1,d=v,c=new g(.03125);t.abs().gte(.1);)t=t.times(c),l+=5;for(n=Math.log(_b(2,l))/Math.LN10*2+5|0,d+=n,r=i=a=new g(Gh),g.precision=d;;){if(i=ho(i.times(t),d),r=r.times(++p),c=a.plus(Oy(i,r,d)),Qp(c.d).slice(0,d)===Qp(a.d).slice(0,d)){for(;l--;)a=ho(a.times(a),d);return g.precision=v,e==null?(Zo=!0,ho(a,v)):a}a=c}}function fc(t){for(var e=t.e*Ro,r=t.d[0];r>=10;r/=10)e++;return e}function TV(t,e,r){if(e>t.LN10.sd())throw Zo=!0,r&&(t.precision=r),Error(Wf+"LN10 precision limit exceeded");return ho(new t(t.LN10),e)}function N_(t){for(var e="";t--;)e+="0";return e}function RC(t,e){var r,n,i,a,c,d,p,l,g,v=1,E=10,T=t,j=T.d,P=T.constructor,C=P.precision;if(T.s<1)throw Error(Wf+(T.s?"NaN":"-Infinity"));if(T.eq(Gh))return new P(0);if(e==null?(Zo=!1,l=C):l=e,T.eq(10))return e==null&&(Zo=!0),TV(P,l);if(l+=E,P.precision=l,r=Qp(j),n=r.charAt(0),a=fc(T),Math.abs(a)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)T=T.times(t),r=Qp(T.d),n=r.charAt(0),v++;a=fc(T),n>1?(T=new P("0."+r),a++):T=new P(n+"."+r.slice(1))}else return p=TV(P,l+2,C).times(a+""),T=RC(new P(n+"."+r.slice(1)),l-E).plus(p),P.precision=C,e==null?(Zo=!0,ho(T,C)):T;for(d=c=T=Oy(T.minus(Gh),T.plus(Gh),l),g=ho(T.times(T),l),i=3;;){if(c=ho(c.times(g),l),p=d.plus(Oy(c,new P(i),l)),Qp(p.d).slice(0,l)===Qp(d.d).slice(0,l))return d=d.times(2),a!==0&&(d=d.plus(TV(P,l+2,C).times(a+""))),d=Oy(d,new P(v),l),P.precision=C,e==null?(Zo=!0,ho(d,C)):d;d=p,i+=2}}function Ahe(t,e){var r,n,i;for((r=e.indexOf("."))>-1&&(e=e.replace(".","")),(n=e.search(/e/i))>0?(r<0&&(r=n),r+=+e.slice(n+1),e=e.substring(0,n)):r<0&&(r=e.length),n=0;e.charCodeAt(n)===48;)++n;for(i=e.length;e.charCodeAt(i-1)===48;)--i;if(e=e.slice(n,i),e){if(i-=n,r=r-n-1,t.e=$A(r/Ro),t.d=[],n=(r+1)%Ro,r<0&&(n+=Ro),nd3||t.e<-d3))throw Error(VX+r)}else t.s=0,t.e=0,t.d=[0];return t}function ho(t,e,r){var n,i,a,c,d,p,l,g,v=t.d;for(c=1,a=v[0];a>=10;a/=10)c++;if(n=e-c,n<0)n+=Ro,i=e,l=v[g=0];else{if(g=Math.ceil((n+1)/Ro),a=v.length,g>=a)return t;for(l=a=v[g],c=1;a>=10;a/=10)c++;n%=Ro,i=n-Ro+c}if(r!==void 0&&(a=_b(10,c-i-1),d=l/a%10|0,p=e<0||v[g+1]!==void 0||l%a,p=r<4?(d||p)&&(r==0||r==(t.s<0?3:2)):d>5||d==5&&(r==4||p||r==6&&(n>0?i>0?l/_b(10,c-i):0:v[g-1])%10&1||r==(t.s<0?8:7))),e<1||!v[0])return p?(a=fc(t),v.length=1,e=e-a-1,v[0]=_b(10,(Ro-e%Ro)%Ro),t.e=$A(-e/Ro)||0):(v.length=1,v[0]=t.e=t.s=0),t;if(n==0?(v.length=g,a=1,g--):(v.length=g+1,a=_b(10,Ro-n),v[g]=i>0?(l/_b(10,c-i)%_b(10,i)|0)*a:0),p)for(;;)if(g==0){(v[0]+=a)==Jc&&(v[0]=1,++t.e);break}else{if(v[g]+=a,v[g]!=Jc)break;v[g--]=0,a=1}for(n=v.length;v[--n]===0;)v.pop();if(Zo&&(t.e>d3||t.e<-d3))throw Error(VX+fc(t));return t}function cIe(t,e){var r,n,i,a,c,d,p,l,g,v,E=t.constructor,T=E.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new E(t),Zo?ho(e,T):e;if(p=t.d,v=e.d,n=e.e,l=t.e,p=p.slice(),c=l-n,c){for(g=c<0,g?(r=p,c=-c,d=v.length):(r=v,n=l,d=p.length),i=Math.max(Math.ceil(T/Ro),d)+2,c>i&&(c=i,r.length=1),r.reverse(),i=c;i--;)r.push(0);r.reverse()}else{for(i=p.length,d=v.length,g=i0;--i)p[d++]=0;for(i=v.length;i>c;){if(p[--i]0?a=a.charAt(0)+"."+a.slice(1)+N_(n):c>1&&(a=a.charAt(0)+"."+a.slice(1)),a=a+(i<0?"e":"e+")+i):i<0?(a="0."+N_(-i-1)+a,r&&(n=r-c)>0&&(a+=N_(n))):i>=c?(a+=N_(i+1-c),r&&(n=r-i-1)>0&&(a=a+"."+N_(n))):((n=i+1)0&&(i+1===c&&(a+="."),a+=N_(n))),t.s<0?"-"+a:a}function khe(t,e){if(t.length>e)return t.length=e,!0}function uIe(t){var e,r,n;function i(a){var c=this;if(!(c instanceof i))return new i(a);if(c.constructor=i,a instanceof i){c.s=a.s,c.e=a.e,c.d=(a=a.d)?a.slice():a;return}if(typeof a=="number"){if(a*0!==0)throw Error(Xb+a);if(a>0)c.s=1;else if(a<0)a=-a,c.s=-1;else{c.s=0,c.e=0,c.d=[0];return}if(a===~~a&&a<1e7){c.e=0,c.d=[a];return}return Ahe(c,a.toString())}else if(typeof a!="string")throw Error(Xb+a);if(a.charCodeAt(0)===45?(a=a.slice(1),c.s=-1):c.s=1,t2t.test(a))Ahe(c,a);else throw Error(Xb+a)}if(i.prototype=Yn,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=uIe,i.config=i.set=r2t,t===void 0&&(t={}),t)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],e=0;e=i[e+1]&&n<=i[e+2])this[r]=n;else throw Error(Xb+r+": "+n);if((n=t[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(Xb+r+": "+n);return this}var qX=uIe(e2t);Gh=new qX(1);const Ja=qX;function n2t(t){return o2t(t)||a2t(t)||s2t(t)||i2t()}function i2t(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function s2t(t,e){if(t){if(typeof t=="string")return v7(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return v7(t,e)}}function a2t(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function o2t(t){if(Array.isArray(t))return v7(t)}function v7(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=e?r.apply(void 0,i):t(e-c,Ihe(function(){for(var d=arguments.length,p=new Array(d),l=0;lt.length)&&(e=t.length);for(var r=0,n=new Array(e);r"u"||!(Symbol.iterator in Object(t)))){var r=[],n=!0,i=!1,a=void 0;try{for(var c=t[Symbol.iterator](),d;!(n=(d=c.next()).done)&&(r.push(d.value),!(e&&r.length===e));n=!0);}catch(p){i=!0,a=p}finally{try{!n&&c.return!=null&&c.return()}finally{if(i)throw a}}return r}}function w2t(t){if(Array.isArray(t))return t}function pIe(t){var e=LC(t,2),r=e[0],n=e[1],i=r,a=n;return r>n&&(i=n,a=r),[i,a]}function gIe(t,e,r){if(t.lte(0))return new Ja(0);var n=bB.getDigitCount(t.toNumber()),i=new Ja(10).pow(n),a=t.div(i),c=n!==1?.05:.1,d=new Ja(Math.ceil(a.div(c).toNumber())).add(r).mul(c),p=d.mul(i);return e?p:new Ja(Math.ceil(p))}function S2t(t,e,r){var n=1,i=new Ja(t);if(!i.isint()&&r){var a=Math.abs(t);a<1?(n=new Ja(10).pow(bB.getDigitCount(t)-1),i=new Ja(Math.floor(i.div(n).toNumber())).mul(n)):a>1&&(i=new Ja(Math.floor(t)))}else t===0?i=new Ja(Math.floor((e-1)/2)):r||(i=new Ja(Math.floor(t)));var c=Math.floor((e-1)/2),d=d2t(u2t(function(p){return i.add(new Ja(p-c).mul(n)).toNumber()}),b7);return d(0,e)}function yIe(t,e,r,n){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((e-t)/(r-1)))return{step:new Ja(0),tickMin:new Ja(0),tickMax:new Ja(0)};var a=gIe(new Ja(e).sub(t).div(r-1),n,i),c;t<=0&&e>=0?c=new Ja(0):(c=new Ja(t).add(e).div(2),c=c.sub(new Ja(c).mod(a)));var d=Math.ceil(c.sub(t).div(a).toNumber()),p=Math.ceil(new Ja(e).sub(c).div(a).toNumber()),l=d+p+1;return l>r?yIe(t,e,r,n,i+1):(l0?p+(r-l):p,d=e>0?d:d+(r-l)),{step:a,tickMin:c.sub(new Ja(d).mul(a)),tickMax:c.add(new Ja(p).mul(a))})}function E2t(t){var e=LC(t,2),r=e[0],n=e[1],i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,c=Math.max(i,2),d=pIe([r,n]),p=LC(d,2),l=p[0],g=p[1];if(l===-1/0||g===1/0){var v=g===1/0?[l].concat(S7(b7(0,i-1).map(function(){return 1/0}))):[].concat(S7(b7(0,i-1).map(function(){return-1/0})),[g]);return r>n?w7(v):v}if(l===g)return S2t(l,i,a);var E=yIe(l,g,c,a),T=E.step,j=E.tickMin,P=E.tickMax,C=bB.rangeStep(j,P.add(new Ja(.1).mul(T)),T);return r>n?w7(C):C}function T2t(t,e){var r=LC(t,2),n=r[0],i=r[1],a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,c=pIe([n,i]),d=LC(c,2),p=d[0],l=d[1];if(p===-1/0||l===1/0)return[n,i];if(p===l)return[p];var g=Math.max(e,2),v=gIe(new Ja(l).sub(p).div(g-1),a,0),E=[].concat(S7(bB.rangeStep(new Ja(p),new Ja(l).sub(new Ja(.99).mul(v)),v)),[l]);return n>i?w7(E):E}var A2t=fIe(E2t),k2t=fIe(T2t),I2t="Invariant failed";function yw(t,e){throw new Error(I2t)}var j2t=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function IT(t){"@babel/helpers - typeof";return IT=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},IT(t)}function h3(){return h3=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function M2t(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function O2t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function F2t(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r1&&arguments[1]!==void 0?arguments[1]:[],i=arguments.length>2?arguments[2]:void 0,a=arguments.length>3?arguments[3]:void 0,c=-1,d=(r=n==null?void 0:n.length)!==null&&r!==void 0?r:0;if(d<=1)return 0;if(a&&a.axisType==="angleAxis"&&Math.abs(Math.abs(a.range[1]-a.range[0])-360)<=1e-6)for(var p=a.range,l=0;l0?i[l-1].coordinate:i[d-1].coordinate,v=i[l].coordinate,E=l>=d-1?i[0].coordinate:i[l+1].coordinate,T=void 0;if(Ld(v-g)!==Ld(E-v)){var j=[];if(Ld(E-v)===Ld(p[1]-p[0])){T=E;var P=v+p[1]-p[0];j[0]=Math.min(P,(P+g)/2),j[1]=Math.max(P,(P+g)/2)}else{T=g;var C=E+p[1]-p[0];j[0]=Math.min(v,(C+v)/2),j[1]=Math.max(v,(C+v)/2)}var L=[Math.min(v,(T+v)/2),Math.max(v,(T+v)/2)];if(e>L[0]&&e<=L[1]||e>=j[0]&&e<=j[1]){c=i[l].index;break}}else{var O=Math.min(g,E),F=Math.max(g,E);if(e>(O+v)/2&&e<=(F+v)/2){c=i[l].index;break}}}else for(var $=0;$0&&$(n[$].coordinate+n[$-1].coordinate)/2&&e<=(n[$].coordinate+n[$+1].coordinate)/2||$===d-1&&e>(n[$].coordinate+n[$-1].coordinate)/2){c=n[$].index;break}return c},GX=function(e){var r,n=e,i=n.type.displayName,a=(r=e.type)!==null&&r!==void 0&&r.defaultProps?Il(Il({},e.type.defaultProps),e.props):e.props,c=a.stroke,d=a.fill,p;switch(i){case"Line":p=c;break;case"Area":case"Radar":p=c&&c!=="none"?c:d;break;default:p=d;break}return p},tkt=function(e){var r=e.barSize,n=e.totalSize,i=e.stackGroups,a=i===void 0?{}:i;if(!a)return{};for(var c={},d=Object.keys(a),p=0,l=d.length;p=0});if(L&&L.length){var O=L[0].type.defaultProps,F=O!==void 0?Il(Il({},O),L[0].props):L[0].props,$=F.barSize,G=F[C];c[G]||(c[G]=[]);var W=fs($)?r:$;c[G].push({item:L[0],stackList:L.slice(1),barSize:fs(W)?void 0:Dd(W,n,0)})}}return c},rkt=function(e){var r=e.barGap,n=e.barCategoryGap,i=e.bandSize,a=e.sizeList,c=a===void 0?[]:a,d=e.maxBarSize,p=c.length;if(p<1)return null;var l=Dd(r,i,0,!0),g,v=[];if(c[0].barSize===+c[0].barSize){var E=!1,T=i/p,j=c.reduce(function($,G){return $+G.barSize||0},0);j+=(p-1)*l,j>=i&&(j-=(p-1)*l,l=0),j>=i&&T>0&&(E=!0,T*=.9,j=p*T);var P=(i-j)/2>>0,C={offset:P-l,size:0};g=c.reduce(function($,G){var W={item:G.item,position:{offset:C.offset+C.size+l,size:E?T:G.barSize}},Z=[].concat(Phe($),[W]);return C=Z[Z.length-1].position,G.stackList&&G.stackList.length&&G.stackList.forEach(function(Q){Z.push({item:Q,position:C})}),Z},v)}else{var L=Dd(n,i,0,!0);i-2*L-(p-1)*l<=0&&(l=0);var O=(i-2*L-(p-1)*l)/p;O>1&&(O>>=0);var F=d===+d?Math.min(O,d):O;g=c.reduce(function($,G,W){var Z=[].concat(Phe($),[{item:G.item,position:{offset:L+(O+l)*W+(O-F)/2,size:F}}]);return G.stackList&&G.stackList.length&&G.stackList.forEach(function(Q){Z.push({item:Q,position:Z[Z.length-1].position})}),Z},v)}return g},nkt=function(e,r,n,i){var a=n.children,c=n.width,d=n.margin,p=c-(d.left||0)-(d.right||0),l=bIe({children:a,legendWidth:p});if(l){var g=i||{},v=g.width,E=g.height,T=l.align,j=l.verticalAlign,P=l.layout;if((P==="vertical"||P==="horizontal"&&j==="middle")&&T!=="center"&&gn(e[T]))return Il(Il({},e),{},CE({},T,e[T]+(v||0)));if((P==="horizontal"||P==="vertical"&&T==="center")&&j!=="middle"&&gn(e[j]))return Il(Il({},e),{},CE({},j,e[j]+(E||0)))}return e},ikt=function(e,r,n){return fs(r)?!0:e==="horizontal"?r==="yAxis":e==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},wIe=function(e,r,n,i,a){var c=r.props.children,d=qf(c,wB).filter(function(l){return ikt(i,a,l.props.direction)});if(d&&d.length){var p=d.map(function(l){return l.props.dataKey});return e.reduce(function(l,g){var v=Mu(g,n);if(fs(v))return l;var E=Array.isArray(v)?[xB(v),yB(v)]:[v,v],T=p.reduce(function(j,P){var C=Mu(g,P,0),L=E[0]-Math.abs(Array.isArray(C)?C[0]:C),O=E[1]+Math.abs(Array.isArray(C)?C[1]:C);return[Math.min(L,j[0]),Math.max(O,j[1])]},[1/0,-1/0]);return[Math.min(T[0],l[0]),Math.max(T[1],l[1])]},[1/0,-1/0])}return null},skt=function(e,r,n,i,a){var c=r.map(function(d){return wIe(e,d,n,a,i)}).filter(function(d){return!fs(d)});return c&&c.length?c.reduce(function(d,p){return[Math.min(d[0],p[0]),Math.max(d[1],p[1])]},[1/0,-1/0]):null},SIe=function(e,r,n,i,a){var c=r.map(function(p){var l=p.props.dataKey;return n==="number"&&l&&wIe(e,p,l,i)||_j(e,l,n,a)});if(n==="number")return c.reduce(function(p,l){return[Math.min(p[0],l[0]),Math.max(p[1],l[1])]},[1/0,-1/0]);var d={};return c.reduce(function(p,l){for(var g=0,v=l.length;g=2?Ld(d[0]-d[1])*2*l:l,r&&(e.ticks||e.niceTicks)){var g=(e.ticks||e.niceTicks).map(function(v){var E=a?a.indexOf(v):v;return{coordinate:i(E)+l,value:v,offset:l}});return g.filter(function(v){return!sN(v.coordinate)})}return e.isCategorical&&e.categoricalDomain?e.categoricalDomain.map(function(v,E){return{coordinate:i(v)+l,value:v,index:E,offset:l}}):i.ticks&&!n?i.ticks(e.tickCount).map(function(v){return{coordinate:i(v)+l,value:v,offset:l}}):i.domain().map(function(v,E){return{coordinate:i(v)+l,value:a?a[v]:v,index:E,offset:l}})},AV=new WeakMap,ZD=function(e,r){if(typeof r!="function")return e;AV.has(e)||AV.set(e,new WeakMap);var n=AV.get(e);if(n.has(r))return n.get(r);var i=function(){e.apply(void 0,arguments),r.apply(void 0,arguments)};return n.set(r,i),i},AIe=function(e,r,n){var i=e.scale,a=e.type,c=e.layout,d=e.axisType;if(i==="auto")return c==="radial"&&d==="radiusAxis"?{scale:IC(),realScaleType:"band"}:c==="radial"&&d==="angleAxis"?{scale:o3(),realScaleType:"linear"}:a==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:xj(),realScaleType:"point"}:a==="category"?{scale:IC(),realScaleType:"band"}:{scale:o3(),realScaleType:"linear"};if(fw(i)){var p="scale".concat(rB(i));return{scale:(The[p]||xj)(),realScaleType:The[p]?p:"point"}}return Wi(i)?{scale:i}:{scale:xj(),realScaleType:"point"}},Rhe=1e-4,kIe=function(e){var r=e.domain();if(!(!r||r.length<=2)){var n=r.length,i=e.range(),a=Math.min(i[0],i[1])-Rhe,c=Math.max(i[0],i[1])+Rhe,d=e(r[0]),p=e(r[n-1]);(dc||pc)&&e.domain([r[0],r[n-1]])}},akt=function(e,r){if(!e)return null;for(var n=0,i=e.length;ni)&&(a[1]=i),a[0]>i&&(a[0]=i),a[1]=0?(e[d][n][0]=a,e[d][n][1]=a+p,a=e[d][n][1]):(e[d][n][0]=c,e[d][n][1]=c+p,c=e[d][n][1])}},ckt=function(e){var r=e.length;if(!(r<=0))for(var n=0,i=e[0].length;n=0?(e[c][n][0]=a,e[c][n][1]=a+d,a=e[c][n][1]):(e[c][n][0]=0,e[c][n][1]=0)}},ukt={sign:lkt,expand:jgt,none:vT,silhouette:Cgt,wiggle:Pgt,positive:ckt},dkt=function(e,r,n){var i=r.map(function(d){return d.props.dataKey}),a=ukt[n],c=Igt().keys(i).value(function(d,p){return+Mu(d,p,0)}).order(Z9).offset(a);return c(e)},hkt=function(e,r,n,i,a,c){if(!e)return null;var d=c?r.reverse():r,p={},l=d.reduce(function(v,E){var T,j=(T=E.type)!==null&&T!==void 0&&T.defaultProps?Il(Il({},E.type.defaultProps),E.props):E.props,P=j.stackId,C=j.hide;if(C)return v;var L=j[n],O=v[L]||{hasStack:!1,stackGroups:{}};if(Fc(P)){var F=O.stackGroups[P]||{numericAxisId:n,cateAxisId:i,items:[]};F.items.push(E),O.hasStack=!0,O.stackGroups[P]=F}else O.stackGroups[aN("_stackId_")]={numericAxisId:n,cateAxisId:i,items:[E]};return Il(Il({},v),{},CE({},L,O))},p),g={};return Object.keys(l).reduce(function(v,E){var T=l[E];if(T.hasStack){var j={};T.stackGroups=Object.keys(T.stackGroups).reduce(function(P,C){var L=T.stackGroups[C];return Il(Il({},P),{},CE({},C,{numericAxisId:n,cateAxisId:i,items:L.items,stackedData:dkt(e,L.items,a)}))},j)}return Il(Il({},v),{},CE({},E,T))},g)},IIe=function(e,r){var n=r.realScaleType,i=r.type,a=r.tickCount,c=r.originalDomain,d=r.allowDecimals,p=n||r.scale;if(p!=="auto"&&p!=="linear")return null;if(a&&i==="number"&&c&&(c[0]==="auto"||c[1]==="auto")){var l=e.domain();if(!l.length)return null;var g=A2t(l,a,d);return e.domain([xB(g),yB(g)]),{niceTicks:g}}if(a&&i==="number"){var v=e.domain(),E=k2t(v,a,d);return{niceTicks:E}}return null};function iXt(t){var e=t.axis,r=t.ticks,n=t.bandSize,i=t.entry,a=t.index,c=t.dataKey;if(e.type==="category"){if(!e.allowDuplicatedCategory&&e.dataKey&&!fs(i[e.dataKey])){var d=BF(r,"value",i[e.dataKey]);if(d)return d.coordinate+n/2}return r[a]?r[a].coordinate+n/2:null}var p=Mu(i,fs(c)?e.dataKey:c);return fs(p)?null:e.scale(p)}var Lhe=function(e){var r=e.axis,n=e.ticks,i=e.offset,a=e.bandSize,c=e.entry,d=e.index;if(r.type==="category")return n[d]?n[d].coordinate+i:null;var p=Mu(c,r.dataKey,r.domain[d]);return fs(p)?null:r.scale(p)-a/2+i},fkt=function(e){var r=e.numericAxis,n=r.scale.domain();if(r.type==="number"){var i=Math.min(n[0],n[1]),a=Math.max(n[0],n[1]);return i<=0&&a>=0?0:a<0?a:i}return n[0]},mkt=function(e,r){var n,i=(n=e.type)!==null&&n!==void 0&&n.defaultProps?Il(Il({},e.type.defaultProps),e.props):e.props,a=i.stackId;if(Fc(a)){var c=r[a];if(c){var d=c.items.indexOf(e);return d>=0?c.stackedData[d]:null}}return null},pkt=function(e){return e.reduce(function(r,n){return[xB(n.concat([r[0]]).filter(gn)),yB(n.concat([r[1]]).filter(gn))]},[1/0,-1/0])},jIe=function(e,r,n){return Object.keys(e).reduce(function(i,a){var c=e[a],d=c.stackedData,p=d.reduce(function(l,g){var v=pkt(g.slice(r,n+1));return[Math.min(l[0],v[0]),Math.max(l[1],v[1])]},[1/0,-1/0]);return[Math.min(p[0],i[0]),Math.max(p[1],i[1])]},[1/0,-1/0]).map(function(i){return i===1/0||i===-1/0?0:i})},Dhe=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Mhe=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,k7=function(e,r,n){if(Wi(e))return e(r,n);if(!Array.isArray(e))return r;var i=[];if(gn(e[0]))i[0]=n?e[0]:Math.min(e[0],r[0]);else if(Dhe.test(e[0])){var a=+Dhe.exec(e[0])[1];i[0]=r[0]-a}else Wi(e[0])?i[0]=e[0](r[0]):i[0]=r[0];if(gn(e[1]))i[1]=n?e[1]:Math.max(e[1],r[1]);else if(Mhe.test(e[1])){var c=+Mhe.exec(e[1])[1];i[1]=r[1]+c}else Wi(e[1])?i[1]=e[1](r[1]):i[1]=r[1];return i},m3=function(e,r,n){if(e&&e.scale&&e.scale.bandwidth){var i=e.scale.bandwidth();if(!n||i>0)return i}if(e&&r&&r.length>=2){for(var a=_X(r,function(v){return v.coordinate}),c=1/0,d=1,p=a.length;dt.length)&&(e=t.length);for(var r=0,n=new Array(e);r2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(e-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},Ekt=function(e,r,n,i,a){var c=e.width,d=e.height,p=e.startAngle,l=e.endAngle,g=Dd(e.cx,c,c/2),v=Dd(e.cy,d,d/2),E=NIe(c,d,n),T=Dd(e.innerRadius,E,0),j=Dd(e.outerRadius,E,E*.8),P=Object.keys(r);return P.reduce(function(C,L){var O=r[L],F=O.domain,$=O.reversed,G;if(fs(O.range))i==="angleAxis"?G=[p,l]:i==="radiusAxis"&&(G=[T,j]),$&&(G=[G[1],G[0]]);else{G=O.range;var W=G,Z=xkt(W,2);p=Z[0],l=Z[1]}var Q=AIe(O,a),ee=Q.realScaleType,ie=Q.scale;ie.domain(F).range(G),kIe(ie);var oe=IIe(ie,xy(xy({},O),{},{realScaleType:ee})),pe=xy(xy(xy({},O),oe),{},{range:G,radius:j,realScaleType:ee,scale:ie,cx:g,cy:v,innerRadius:T,outerRadius:j,startAngle:p,endAngle:l});return xy(xy({},C),{},PIe({},L,pe))},{})},Tkt=function(e,r){var n=e.x,i=e.y,a=r.x,c=r.y;return Math.sqrt(Math.pow(n-a,2)+Math.pow(i-c,2))},Akt=function(e,r){var n=e.x,i=e.y,a=r.cx,c=r.cy,d=Tkt({x:n,y:i},{x:a,y:c});if(d<=0)return{radius:d};var p=(n-a)/d,l=Math.acos(p);return i>c&&(l=2*Math.PI-l),{radius:d,angle:Skt(l),angleInRadian:l}},kkt=function(e){var r=e.startAngle,n=e.endAngle,i=Math.floor(r/360),a=Math.floor(n/360),c=Math.min(i,a);return{startAngle:r-c*360,endAngle:n-c*360}},Ikt=function(e,r){var n=r.startAngle,i=r.endAngle,a=Math.floor(n/360),c=Math.floor(i/360),d=Math.min(a,c);return e+d*360},zhe=function(e,r){var n=e.x,i=e.y,a=Akt({x:n,y:i},r),c=a.radius,d=a.angle,p=r.innerRadius,l=r.outerRadius;if(cl)return!1;if(c===0)return!0;var g=kkt(r),v=g.startAngle,E=g.endAngle,T=d,j;if(v<=E){for(;T>E;)T-=360;for(;T=v&&T<=E}else{for(;T>v;)T-=360;for(;T=E&&T<=v}return j?xy(xy({},r),{},{radius:c,angle:Ikt(T,r)}):null},RIe=function(e){return!N.isValidElement(e)&&!Wi(e)&&typeof e!="boolean"?e.className:""};function FC(t){"@babel/helpers - typeof";return FC=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},FC(t)}var jkt=["offset"];function Ckt(t){return Lkt(t)||Rkt(t)||Nkt(t)||Pkt()}function Pkt(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Nkt(t,e){if(t){if(typeof t=="string")return I7(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return I7(t,e)}}function Rkt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function Lkt(t){if(Array.isArray(t))return I7(t)}function I7(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Mkt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function $he(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function kc(t){for(var e=1;e=0?1:-1,F,$;i==="insideStart"?(F=T+O*c,$=P):i==="insideEnd"?(F=j-O*c,$=!P):i==="end"&&(F=j+O*c,$=P),$=L<=0?$:!$;var G=To(l,g,C,F),W=To(l,g,C,F+($?1:-1)*359),Z="M".concat(G.x,",").concat(G.y,` A`).concat(C,",").concat(C,",0,1,").concat($?0:1,`, `).concat(W.x,",").concat(W.y),Q=fs(e.id)?aN("recharts-radial-line-"):e.id;return et.createElement("text",BC({},n,{dominantBaseline:"central",className:hs("recharts-radial-bar-label",d)}),et.createElement("defs",null,et.createElement("path",{id:Q,d:Z})),et.createElement("textPath",{xlinkHref:"#".concat(Q)},r))},Vkt=function(e){var r=e.viewBox,n=e.offset,i=e.position,a=r,c=a.cx,d=a.cy,p=a.innerRadius,l=a.outerRadius,g=a.startAngle,v=a.endAngle,E=(g+v)/2;if(i==="outside"){var T=To(c,d,l+n,E),j=T.x,P=T.y;return{x:j,y:P,textAnchor:j>=c?"start":"end",verticalAnchor:"middle"}}if(i==="center")return{x:c,y:d,textAnchor:"middle",verticalAnchor:"middle"};if(i==="centerTop")return{x:c,y:d,textAnchor:"middle",verticalAnchor:"start"};if(i==="centerBottom")return{x:c,y:d,textAnchor:"middle",verticalAnchor:"end"};var C=(p+l)/2,L=To(c,d,C,E),O=L.x,F=L.y;return{x:O,y:F,textAnchor:"middle",verticalAnchor:"middle"}},qkt=function(e){var r=e.viewBox,n=e.parentViewBox,i=e.offset,a=e.position,c=r,d=c.x,p=c.y,l=c.width,g=c.height,v=g>=0?1:-1,E=v*i,T=v>0?"end":"start",j=v>0?"start":"end",P=l>=0?1:-1,C=P*i,L=P>0?"end":"start",O=P>0?"start":"end";if(a==="top"){var F={x:d+l/2,y:p-v*i,textAnchor:"middle",verticalAnchor:T};return kc(kc({},F),n?{height:Math.max(p-n.y,0),width:l}:{})}if(a==="bottom"){var $={x:d+l/2,y:p+g+E,textAnchor:"middle",verticalAnchor:j};return kc(kc({},$),n?{height:Math.max(n.y+n.height-(p+g),0),width:l}:{})}if(a==="left"){var G={x:d-C,y:p+g/2,textAnchor:L,verticalAnchor:"middle"};return kc(kc({},G),n?{width:Math.max(G.x-n.x,0),height:g}:{})}if(a==="right"){var W={x:d+l+C,y:p+g/2,textAnchor:O,verticalAnchor:"middle"};return kc(kc({},W),n?{width:Math.max(n.x+n.width-W.x,0),height:g}:{})}var Z=n?{width:l,height:g}:{};return a==="insideLeft"?kc({x:d+C,y:p+g/2,textAnchor:O,verticalAnchor:"middle"},Z):a==="insideRight"?kc({x:d+l-C,y:p+g/2,textAnchor:L,verticalAnchor:"middle"},Z):a==="insideTop"?kc({x:d+l/2,y:p+E,textAnchor:"middle",verticalAnchor:j},Z):a==="insideBottom"?kc({x:d+l/2,y:p+g-E,textAnchor:"middle",verticalAnchor:T},Z):a==="insideTopLeft"?kc({x:d+C,y:p+E,textAnchor:O,verticalAnchor:j},Z):a==="insideTopRight"?kc({x:d+l-C,y:p+E,textAnchor:L,verticalAnchor:j},Z):a==="insideBottomLeft"?kc({x:d+C,y:p+g-E,textAnchor:O,verticalAnchor:T},Z):a==="insideBottomRight"?kc({x:d+l-C,y:p+g-E,textAnchor:L,verticalAnchor:T},Z):PA(a)&&(gn(a.x)||Pb(a.x))&&(gn(a.y)||Pb(a.y))?kc({x:d+Dd(a.x,l),y:p+Dd(a.y,g),textAnchor:"end",verticalAnchor:"end"},Z):kc({x:d+l/2,y:p+g/2,textAnchor:"middle",verticalAnchor:"middle"},Z)},Gkt=function(e){return"cx"in e&&gn(e.cx)};function nu(t){var e=t.offset,r=e===void 0?5:e,n=Dkt(t,jkt),i=kc({offset:r},n),a=i.viewBox,c=i.position,d=i.value,p=i.children,l=i.content,g=i.className,v=g===void 0?"":g,E=i.textBreakAll;if(!a||fs(d)&&fs(p)&&!N.isValidElement(l)&&!Wi(l))return null;if(N.isValidElement(l))return N.cloneElement(l,i);var T;if(Wi(l)){if(T=N.createElement(l,i),N.isValidElement(T))return T}else T=zkt(i);var j=Gkt(a),P=$i(i,!0);if(j&&(c==="insideStart"||c==="insideEnd"||c==="end"))return Ukt(i,T,P);var C=j?Vkt(i):qkt(i);return et.createElement(pw,BC({className:hs("recharts-label",v)},P,C,{breakAll:E}),T)}nu.displayName="Label";var LIe=function(e){var r=e.cx,n=e.cy,i=e.angle,a=e.startAngle,c=e.endAngle,d=e.r,p=e.radius,l=e.innerRadius,g=e.outerRadius,v=e.x,E=e.y,T=e.top,j=e.left,P=e.width,C=e.height,L=e.clockWise,O=e.labelViewBox;if(O)return O;if(gn(P)&&gn(C)){if(gn(v)&&gn(E))return{x:v,y:E,width:P,height:C};if(gn(T)&&gn(j))return{x:T,y:j,width:P,height:C}}return gn(v)&&gn(E)?{x:v,y:E,width:0,height:0}:gn(r)&&gn(n)?{cx:r,cy:n,startAngle:a||i||0,endAngle:c||i||0,innerRadius:l||0,outerRadius:g||p||d||0,clockWise:L}:e.viewBox?e.viewBox:{}},Hkt=function(e,r){return e?e===!0?et.createElement(nu,{key:"label-implicit",viewBox:r}):Fc(e)?et.createElement(nu,{key:"label-implicit",viewBox:r,value:e}):N.isValidElement(e)?e.type===nu?N.cloneElement(e,{key:"label-implicit",viewBox:r}):et.createElement(nu,{key:"label-implicit",content:e,viewBox:r}):Wi(e)?et.createElement(nu,{key:"label-implicit",content:e,viewBox:r}):PA(e)?et.createElement(nu,BC({viewBox:r},e,{key:"label-implicit"})):null:null},Wkt=function(e,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!e||!e.children&&n&&!e.label)return null;var i=e.children,a=LIe(e),c=qf(i,nu).map(function(p,l){return N.cloneElement(p,{viewBox:r||a,key:"label-".concat(l)})});if(!n)return c;var d=Hkt(e.label,r||a);return[d].concat(Ckt(c))};nu.parseViewBox=LIe;nu.renderCallByParent=Wkt;function Kkt(t){var e=t==null?0:t.length;return e?t[e-1]:void 0}var Ykt=Kkt;const Zkt=ea(Ykt);function zC(t){"@babel/helpers - typeof";return zC=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},zC(t)}var Xkt=["valueAccessor"],Qkt=["data","dataKey","clockWise","id","textBreakAll"];function Jkt(t){return nIt(t)||rIt(t)||tIt(t)||eIt()}function eIt(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function tIt(t,e){if(t){if(typeof t=="string")return j7(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return j7(t,e)}}function rIt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function nIt(t){if(Array.isArray(t))return j7(t)}function j7(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function oIt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var lIt=function(e){return Array.isArray(e.value)?Zkt(e.value):e.value};function hv(t){var e=t.valueAccessor,r=e===void 0?lIt:e,n=qhe(t,Xkt),i=n.data,a=n.dataKey,c=n.clockWise,d=n.id,p=n.textBreakAll,l=qhe(n,Qkt);return!i||!i.length?null:et.createElement($a,{className:"recharts-label-list"},i.map(function(g,v){var E=fs(a)?r(g,v):Mu(g&&g.payload,a),T=fs(d)?{}:{id:"".concat(d,"-").concat(v)};return et.createElement(nu,g3({},$i(g,!0),l,T,{parentViewBox:g.parentViewBox,value:E,textBreakAll:p,viewBox:nu.parseViewBox(fs(c)?g:Vhe(Vhe({},g),{},{clockWise:c})),key:"label-".concat(v),index:v}))}))}hv.displayName="LabelList";function cIt(t,e){return t?t===!0?et.createElement(hv,{key:"labelList-implicit",data:e}):et.isValidElement(t)||Wi(t)?et.createElement(hv,{key:"labelList-implicit",data:e,content:t}):PA(t)?et.createElement(hv,g3({data:e},t,{key:"labelList-implicit"})):null:null}function uIt(t,e){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&r&&!t.label)return null;var n=t.children,i=qf(n,hv).map(function(c,d){return N.cloneElement(c,{data:e,key:"labelList-".concat(d)})});if(!r)return i;var a=cIt(t.label,e);return[a].concat(Jkt(i))}hv.renderCallByParent=uIt;function $C(t){"@babel/helpers - typeof";return $C=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},$C(t)}function C7(){return C7=Object.assign?Object.assign.bind():function(t){for(var e=1;e180),",").concat(+(c>l),`, `).concat(v.x,",").concat(v.y,` `);if(i>0){var T=To(r,n,i,c),j=To(r,n,i,l);E+="L ".concat(j.x,",").concat(j.y,` A `).concat(i,",").concat(i,`,0, `).concat(+(Math.abs(p)>180),",").concat(+(c<=l),`, `).concat(T.x,",").concat(T.y," Z")}else E+="L ".concat(r,",").concat(n," Z");return E},pIt=function(e){var r=e.cx,n=e.cy,i=e.innerRadius,a=e.outerRadius,c=e.cornerRadius,d=e.forceCornerRadius,p=e.cornerIsExternal,l=e.startAngle,g=e.endAngle,v=Ld(g-l),E=XD({cx:r,cy:n,radius:a,angle:l,sign:v,cornerRadius:c,cornerIsExternal:p}),T=E.circleTangency,j=E.lineTangency,P=E.theta,C=XD({cx:r,cy:n,radius:a,angle:g,sign:-v,cornerRadius:c,cornerIsExternal:p}),L=C.circleTangency,O=C.lineTangency,F=C.theta,$=p?Math.abs(l-g):Math.abs(l-g)-P-F;if($<0)return d?"M ".concat(j.x,",").concat(j.y,` a`).concat(c,",").concat(c,",0,0,1,").concat(c*2,`,0 a`).concat(c,",").concat(c,",0,0,1,").concat(-c*2,`,0 `):DIe({cx:r,cy:n,innerRadius:i,outerRadius:a,startAngle:l,endAngle:g});var G="M ".concat(j.x,",").concat(j.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(v<0),",").concat(T.x,",").concat(T.y,` A`).concat(a,",").concat(a,",0,").concat(+($>180),",").concat(+(v<0),",").concat(L.x,",").concat(L.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(v<0),",").concat(O.x,",").concat(O.y,` `);if(i>0){var W=XD({cx:r,cy:n,radius:i,angle:l,sign:v,isExternal:!0,cornerRadius:c,cornerIsExternal:p}),Z=W.circleTangency,Q=W.lineTangency,ee=W.theta,ie=XD({cx:r,cy:n,radius:i,angle:g,sign:-v,isExternal:!0,cornerRadius:c,cornerIsExternal:p}),oe=ie.circleTangency,pe=ie.lineTangency,Le=ie.theta,be=p?Math.abs(l-g):Math.abs(l-g)-ee-Le;if(be<0&&c===0)return"".concat(G,"L").concat(r,",").concat(n,"Z");G+="L".concat(pe.x,",").concat(pe.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(v<0),",").concat(oe.x,",").concat(oe.y,` A`).concat(i,",").concat(i,",0,").concat(+(be>180),",").concat(+(v>0),",").concat(Z.x,",").concat(Z.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(v<0),",").concat(Q.x,",").concat(Q.y,"Z")}else G+="L".concat(r,",").concat(n,"Z");return G},gIt={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},MIe=function(e){var r=Hhe(Hhe({},gIt),e),n=r.cx,i=r.cy,a=r.innerRadius,c=r.outerRadius,d=r.cornerRadius,p=r.forceCornerRadius,l=r.cornerIsExternal,g=r.startAngle,v=r.endAngle,E=r.className;if(c0&&Math.abs(g-v)<360?C=pIt({cx:n,cy:i,innerRadius:a,outerRadius:c,cornerRadius:Math.min(P,j/2),forceCornerRadius:p,cornerIsExternal:l,startAngle:g,endAngle:v}):C=DIe({cx:n,cy:i,innerRadius:a,outerRadius:c,startAngle:g,endAngle:v}),et.createElement("path",C7({},$i(r,!0),{className:T,d:C,role:"img"}))};function UC(t){"@babel/helpers - typeof";return UC=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},UC(t)}function P7(){return P7=Object.assign?Object.assign.bind():function(t){for(var e=1;ejIt.call(t,e));function Rw(t,e){return t===e||!t&&!e&&t!==t&&e!==e}const NIt="__v",RIt="__o",LIt="_owner",DIt=64,{getOwnPropertyDescriptor:R7,keys:y3}=Object,{propertyIsEnumerable:gO}=Object.prototype,MIt=R7(Object.getPrototypeOf(Int8Array.prototype),Symbol.toStringTag).get;function OIt(t,e){return t.byteLength===e.byteLength&&x3(new Uint8Array(t),new Uint8Array(e))}function FIt(t,e,r){let n=t.length;if(e.length!==n)return!1;for(;n-- >0;)if(!r.equals(t[n],e[n],n,n,t,e,r))return!1;return!0}function BIt(t,e){return t.byteLength===e.byteLength&&x3(new Uint8Array(t.buffer,t.byteOffset,t.byteLength),new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}function zIt(t,e){return Rw(t.getTime(),e.getTime())}function $It(t,e,r){if(t.name!==e.name||t.message!==e.message||t.stack!==e.stack)return!1;const n=t.cause,i=e.cause;if(n!==i&&!r.equals(n,i,"cause","cause",t,e,r))return!1;const a=t.errors,c=e.errors;if(a!==c&&!r.equals(a,c,"errors","errors",t,e,r))return!1;const d=y3(t),p=y3(e);let l=d.length;if(!l&&!p.length)return!0;let g=0,v;for(;l-- >0;)if(v=d[l],!(v==="cause"||v==="errors")){if(v!==p[l]&&!gO.call(e,v)||!r.equals(t[v],e[v],v,v,t,e,r))return!1;++g}const E=p.length-g;return!E||E===(gO.call(e,"cause")?1:0)+(gO.call(e,"errors")?1:0)}function UIt(t,e){return t===e}function VIt(t,e,r){return t.name===e.name&&t.message===e.message&&t.stack===e.stack&&VS(t,e,r)}function Xhe(t,e,r){const n=t.size;if(n!==e.size)return!1;if(!n)return!0;const i=new Array(n),a=t.entries();let c,d,p=0;for(;(c=a.next())&&!c.done;){const l=e.entries();let g=!1,v=0;for(;(d=l.next())&&!d.done;){if(i[v]){v++;continue}const E=c.value,T=d.value;if(r.equals(E[0],T[0],p,v,t,e,r)&&r.equals(E[1],T[1],E[0],T[0],t,e,r)){g=i[v]=!0;break}v++}if(!g)return!1;p++}return!0}const qIt=Rw;function GIt(t,e,r){const n=y3(t),i=y3(e);let a=n.length;if(i.length!==a)return!1;const c=a<=DIt;let d;for(;a-- >0;)if(d=n[a],!zIe(t,e,d)&&(d!==i[a]&&!(c?i.includes(d):gO.call(e,d))||!r.equals(t[d],e[d],d,d,t,e,r)))return!1;return!0}function VS(t,e,r){const n=Zhe(t);let i=n.length;if(Zhe(e).length!==i)return!1;let a,c,d;for(;i-- >0;)if(a=n[i],!zIe(t,e,a)&&(!PIt(e,a)||!r.equals(t[a],e[a],a,a,t,e,r))||(c=R7(t,a),d=R7(e,a),(c||d)&&(!c||!d||c.configurable!==d.configurable||c.enumerable!==d.enumerable||c.writable!==d.writable)))return!1;return!0}function HIt(t,e){return Rw(t.valueOf(),e.valueOf())}function WIt(t,e){return t.source===e.source&&t.flags===e.flags}function Qhe(t,e,r){const n=t.size;if(n!==e.size)return!1;if(!n)return!0;const i=new Array(n),a=t.values();let c,d;for(;(c=a.next())&&!c.done;){const p=e.values();let l=!1,g=0;for(;(d=p.next())&&!d.done;){if(!i[g]&&r.equals(c.value,d.value,c.value,d.value,t,e,r)){l=i[g]=!0;break}g++}if(!l)return!1}return!0}function x3(t,e){let r=t.length;if(e.length!==r||t.byteOffset!==e.byteOffset)return!1;const n=MIt.call(t);if(n==="Float64Array"||n==="Float32Array"||n==="Float16Array"){for(;r-- >0;)if(t[r]!==e[r]&&(t[r]===t[r]||e[r]===e[r]))return!1;return!0}for(;r-- >0;)if(t[r]!==e[r])return!1;return!0}function KIt(t,e){return t.href===e.href?!0:t.protocol===e.protocol&&t.username===e.username&&t.password===e.password&&t.host===e.host&&t.pathname===e.pathname&&t.hash===e.hash&&YIt(t.searchParams,e.searchParams)}function YIt(t,e){const r=t.toString(),n=e.toString();return r===n||Jhe(r)===Jhe(n)}function Jhe(t){return t.split("&").sort().join("&")}function zIe(t,e,r){return(r===LIt||r===RIt||r===NIt)&&!!(t.$$typeof||e.$$typeof)}const ZIt="[object ArrayBuffer]",XIt="[object Arguments]",QIt="[object Boolean]",JIt="[object DataView]",ejt="[object Date]",tjt="[object Error]",rjt="[object Map]",njt="[object Number]",ijt="[object Object]",sjt="[object RegExp]",ajt="[object Set]",ojt="[object String]",ljt={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},cjt="[object URL]",ujt=Object.prototype.toString;function djt({areArrayBuffersEqual:t,areArraysEqual:e,areDataViewsEqual:r,areDatesEqual:n,areErrorsEqual:i,areFunctionsEqual:a,areMapsEqual:c,areNumbersEqual:d,areObjectsEqual:p,arePrimitiveWrappersEqual:l,areRegExpsEqual:g,areSetsEqual:v,areTypedArraysEqual:E,areUrlsEqual:T,unknownTagComparators:j}){return function(C,L,O){if(C===L)return!0;if(C==null||L==null)return!1;const F=typeof C;if(F!==typeof L)return!1;if(F!=="object")return F==="number"?d(C,L,O):F==="function"?a(C,L,O):!1;const $=C.constructor;if($!==L.constructor)return!1;if($===Object)return p(C,L,O);if(Array.isArray(C))return e(C,L,O);if($===Date)return n(C,L,O);if($===RegExp)return g(C,L,O);if($===Map)return c(C,L,O);if($===Set)return v(C,L,O);if($==null)return p(C,L,O);const G=ujt.call(C);if(G===ejt)return n(C,L,O);if(G===sjt)return g(C,L,O);if(G===rjt)return c(C,L,O);if(G===ajt)return v(C,L,O);if(G===ijt)return typeof C.then!="function"&&typeof L.then!="function"&&p(C,L,O);if(G===cjt)return T(C,L,O);if(G===tjt)return i(C,L,O);if(G===XIt)return p(C,L,O);if(ljt[G])return E(C,L,O);if(G===ZIt)return t(C,L,O);if(G===JIt)return r(C,L,O);if(G===QIt||G===njt||G===ojt)return l(C,L,O);if(j){let W=j[G];if(!W){const Z=CIt(C);Z&&(W=j[Z])}if(W)return W(C,L,O)}return!1}}function hjt({circular:t,createCustomConfig:e,strict:r}){let n={areArrayBuffersEqual:OIt,areArraysEqual:r?VS:FIt,areDataViewsEqual:BIt,areDatesEqual:zIt,areErrorsEqual:r?VIt:$It,areFunctionsEqual:UIt,areMapsEqual:r?kV(Xhe,VS):Xhe,areNumbersEqual:qIt,areObjectsEqual:r?VS:GIt,arePrimitiveWrappersEqual:HIt,areRegExpsEqual:WIt,areSetsEqual:r?kV(Qhe,VS):Qhe,areTypedArraysEqual:r?kV(x3,VS):x3,areUrlsEqual:KIt,unknownTagComparators:void 0};if(e&&(n=Object.assign({},n,e(n))),t){const i=xI(n.areArraysEqual),a=xI(n.areErrorsEqual),c=xI(n.areMapsEqual),d=xI(n.areObjectsEqual),p=xI(n.areSetsEqual);n=Object.assign({},n,{areArraysEqual:i,areErrorsEqual:a,areMapsEqual:c,areObjectsEqual:d,areSetsEqual:p})}return n}function fjt(t){return function(e,r,n,i,a,c,d){return t(e,r,d)}}function mjt({circular:t,comparator:e,createState:r,equals:n,strict:i}){if(r)return function(d,p){const{cache:l=t?new WeakMap:void 0,meta:g}=r();return e(d,p,{cache:l,equals:n,meta:g,strict:i})};if(t)return function(d,p){return e(d,p,{cache:new WeakMap,equals:n,meta:void 0,strict:i})};const a={cache:void 0,equals:n,meta:void 0,strict:i};return function(d,p){return e(d,p,a)}}const pjt=Qv();Qv({strict:!0});Qv({circular:!0});Qv({circular:!0,strict:!0});Qv({createInternalComparator:()=>Rw});Qv({strict:!0,createInternalComparator:()=>Rw});Qv({circular:!0,createInternalComparator:()=>Rw});Qv({circular:!0,createInternalComparator:()=>Rw,strict:!0});function Qv(t={}){const{circular:e=!1,createInternalComparator:r,createState:n,strict:i=!1}=t,a=hjt(t),c=djt(a),d=r?r(c):fjt(c);return mjt({circular:e,comparator:c,createState:n,equals:d,strict:i})}function gjt(t){typeof requestAnimationFrame<"u"&&requestAnimationFrame(t)}function efe(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function i(a){r<0&&(r=a),a-r>e?(t(a),r=-1):gjt(i)};requestAnimationFrame(n)}function L7(t){"@babel/helpers - typeof";return L7=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},L7(t)}function yjt(t){return bjt(t)||vjt(t)||_jt(t)||xjt()}function xjt(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _jt(t,e){if(t){if(typeof t=="string")return tfe(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return tfe(t,e)}}function tfe(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r1?1:L<0?0:L},P=function(L){for(var O=L>1?1:L,F=O,$=0;$<8;++$){var G=v(F)-O,W=T(F);if(Math.abs(G-O)<_3||W<_3)return E(F);F=j(F-G/W)}return E(F)};return P.isStepper=!1,P},Ojt=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=e.stiff,n=r===void 0?100:r,i=e.damping,a=i===void 0?8:i,c=e.dt,d=c===void 0?17:c,p=function(g,v,E){var T=-(g-v)*n,j=E*a,P=E+(T-j)*d/1e3,C=E*d/1e3+g;return Math.abs(C-v)<_3&&Math.abs(P)<_3?[v,0]:[C,P]};return p.isStepper=!0,p.dt=d,p},Fjt=function(){for(var e=arguments.length,r=new Array(e),n=0;nt.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Qjt(t,e){if(t==null)return{};var r={},n=Object.keys(t),i,a;for(a=0;a=0)&&(r[i]=t[i]);return r}function IV(t){return rCt(t)||tCt(t)||eCt(t)||Jjt()}function Jjt(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function eCt(t,e){if(t){if(typeof t=="string")return B7(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return B7(t,e)}}function tCt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function rCt(t){if(Array.isArray(t))return B7(t)}function B7(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function b3(t){return b3=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},b3(t)}var Jy=function(t){oCt(r,t);var e=lCt(r);function r(n,i){var a;nCt(this,r),a=e.call(this,n,i);var c=a.props,d=c.isActive,p=c.attributeName,l=c.from,g=c.to,v=c.steps,E=c.children,T=c.duration;if(a.handleStyleChange=a.handleStyleChange.bind(U7(a)),a.changeStyle=a.changeStyle.bind(U7(a)),!d||T<=0)return a.state={style:{}},typeof E=="function"&&(a.state={style:g}),$7(a);if(v&&v.length)a.state={style:v[0].style};else if(l){if(typeof E=="function")return a.state={style:l},$7(a);a.state={style:p?$I({},p,l):l}}else a.state={style:{}};return a}return sCt(r,[{key:"componentDidMount",value:function(){var i=this.props,a=i.isActive,c=i.canBegin;this.mounted=!0,!(!a||!c)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(i){var a=this.props,c=a.isActive,d=a.canBegin,p=a.attributeName,l=a.shouldReAnimate,g=a.to,v=a.from,E=this.state.style;if(d){if(!c){var T={style:p?$I({},p,g):g};this.state&&E&&(p&&E[p]!==g||!p&&E!==g)&&this.setState(T);return}if(!(pjt(i.to,g)&&i.canBegin&&i.isActive)){var j=!i.canBegin||!i.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var P=j||l?v:i.to;if(this.state&&E){var C={style:p?$I({},p,P):P};(p&&E[p]!==P||!p&&E!==P)&&this.setState(C)}this.runAnimation(Am(Am({},this.props),{},{from:P,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var i=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),i&&i()}},{key:"handleStyleChange",value:function(i){this.changeStyle(i)}},{key:"changeStyle",value:function(i){this.mounted&&this.setState({style:i})}},{key:"runJSAnimation",value:function(i){var a=this,c=i.from,d=i.to,p=i.duration,l=i.easing,g=i.begin,v=i.onAnimationEnd,E=i.onAnimationStart,T=Yjt(c,d,Fjt(l),p,this.changeStyle),j=function(){a.stopJSAnimation=T()};this.manager.start([E,g,j,p,v])}},{key:"runStepAnimation",value:function(i){var a=this,c=i.steps,d=i.begin,p=i.onAnimationStart,l=c[0],g=l.style,v=l.duration,E=v===void 0?0:v,T=function(P,C,L){if(L===0)return P;var O=C.duration,F=C.easing,$=F===void 0?"ease":F,G=C.style,W=C.properties,Z=C.onAnimationEnd,Q=L>0?c[L-1]:C,ee=W||Object.keys(G);if(typeof $=="function"||$==="spring")return[].concat(IV(P),[a.runJSAnimation.bind(a,{from:Q.style,to:G,duration:O,easing:$}),O]);var ie=ife(ee,O,$),oe=Am(Am(Am({},Q.style),G),{},{transition:ie});return[].concat(IV(P),[oe,O,Z]).filter(Ajt)};return this.manager.start([p].concat(IV(c.reduce(T,[g,Math.max(E,d)])),[i.onAnimationEnd]))}},{key:"runAnimation",value:function(i){this.manager||(this.manager=wjt());var a=i.begin,c=i.duration,d=i.attributeName,p=i.to,l=i.easing,g=i.onAnimationStart,v=i.onAnimationEnd,E=i.steps,T=i.children,j=this.manager;if(this.unSubscribe=j.subscribe(this.handleStyleChange),typeof l=="function"||typeof T=="function"||l==="spring"){this.runJSAnimation(i);return}if(E.length>1){this.runStepAnimation(i);return}var P=d?$I({},d,p):p,C=ife(Object.keys(P),c,l);j.start([g,a,Am(Am({},P),{},{transition:C}),c,v])}},{key:"render",value:function(){var i=this.props,a=i.children;i.begin;var c=i.duration;i.attributeName,i.easing;var d=i.isActive;i.steps,i.from,i.to,i.canBegin,i.onAnimationEnd,i.shouldReAnimate,i.onAnimationReStart;var p=Xjt(i,Zjt),l=N.Children.count(a),g=this.state.style;if(typeof a=="function")return a(g);if(!d||l===0||c<=0)return a;var v=function(T){var j=T.props,P=j.style,C=P===void 0?{}:P,L=j.className,O=N.cloneElement(T,Am(Am({},p),{},{style:Am(Am({},C),g),className:L}));return O};return l===1?v(N.Children.only(a)):et.createElement("div",null,N.Children.map(a,function(E){return v(E)}))}}]),r}(N.PureComponent);Jy.displayName="Animate";Jy.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};Jy.propTypes={from:Ca.oneOfType([Ca.object,Ca.string]),to:Ca.oneOfType([Ca.object,Ca.string]),attributeName:Ca.string,duration:Ca.number,begin:Ca.number,easing:Ca.oneOfType([Ca.string,Ca.func]),steps:Ca.arrayOf(Ca.shape({duration:Ca.number.isRequired,style:Ca.object.isRequired,easing:Ca.oneOfType([Ca.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),Ca.func]),properties:Ca.arrayOf("string"),onAnimationEnd:Ca.func})),children:Ca.oneOfType([Ca.node,Ca.func]),isActive:Ca.bool,canBegin:Ca.bool,onAnimationEnd:Ca.func,shouldReAnimate:Ca.bool,onAnimationStart:Ca.func,onAnimationReStart:Ca.func};function GC(t){"@babel/helpers - typeof";return GC=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},GC(t)}function w3(){return w3=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0?1:-1,p=n>=0?1:-1,l=i>=0&&n>=0||i<0&&n<0?1:0,g;if(c>0&&a instanceof Array){for(var v=[0,0,0,0],E=0,T=4;Ec?c:a[E];g="M".concat(e,",").concat(r+d*v[0]),v[0]>0&&(g+="A ".concat(v[0],",").concat(v[0],",0,0,").concat(l,",").concat(e+p*v[0],",").concat(r)),g+="L ".concat(e+n-p*v[1],",").concat(r),v[1]>0&&(g+="A ".concat(v[1],",").concat(v[1],",0,0,").concat(l,`, `).concat(e+n,",").concat(r+d*v[1])),g+="L ".concat(e+n,",").concat(r+i-d*v[2]),v[2]>0&&(g+="A ".concat(v[2],",").concat(v[2],",0,0,").concat(l,`, `).concat(e+n-p*v[2],",").concat(r+i)),g+="L ".concat(e+p*v[3],",").concat(r+i),v[3]>0&&(g+="A ".concat(v[3],",").concat(v[3],",0,0,").concat(l,`, `).concat(e,",").concat(r+i-d*v[3])),g+="Z"}else if(c>0&&a===+a&&a>0){var j=Math.min(c,a);g="M ".concat(e,",").concat(r+d*j,` A `).concat(j,",").concat(j,",0,0,").concat(l,",").concat(e+p*j,",").concat(r,` L `).concat(e+n-p*j,",").concat(r,` A `).concat(j,",").concat(j,",0,0,").concat(l,",").concat(e+n,",").concat(r+d*j,` L `).concat(e+n,",").concat(r+i-d*j,` A `).concat(j,",").concat(j,",0,0,").concat(l,",").concat(e+n-p*j,",").concat(r+i,` L `).concat(e+p*j,",").concat(r+i,` A `).concat(j,",").concat(j,",0,0,").concat(l,",").concat(e,",").concat(r+i-d*j," Z")}else g="M ".concat(e,",").concat(r," h ").concat(n," v ").concat(i," h ").concat(-n," Z");return g},xCt=function(e,r){if(!e||!r)return!1;var n=e.x,i=e.y,a=r.x,c=r.y,d=r.width,p=r.height;if(Math.abs(d)>0&&Math.abs(p)>0){var l=Math.min(a,a+d),g=Math.max(a,a+d),v=Math.min(c,c+p),E=Math.max(c,c+p);return n>=l&&n<=g&&i>=v&&i<=E}return!1},_Ct={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},HX=function(e){var r=hfe(hfe({},_Ct),e),n=N.useRef(),i=N.useState(-1),a=uCt(i,2),c=a[0],d=a[1];N.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var $=n.current.getTotalLength();$&&d($)}catch{}},[]);var p=r.x,l=r.y,g=r.width,v=r.height,E=r.radius,T=r.className,j=r.animationEasing,P=r.animationDuration,C=r.animationBegin,L=r.isAnimationActive,O=r.isUpdateAnimationActive;if(p!==+p||l!==+l||g!==+g||v!==+v||g===0||v===0)return null;var F=hs("recharts-rectangle",T);return O?et.createElement(Jy,{canBegin:c>0,from:{width:g,height:v,x:p,y:l},to:{width:g,height:v,x:p,y:l},duration:P,animationEasing:j,isActive:O},function($){var G=$.width,W=$.height,Z=$.x,Q=$.y;return et.createElement(Jy,{canBegin:c>0,from:"0px ".concat(c===-1?1:c,"px"),to:"".concat(c,"px 0px"),attributeName:"strokeDasharray",begin:C,duration:P,isActive:L,easing:j},et.createElement("path",w3({},$i(r,!0),{className:F,d:ffe(Z,Q,G,W,E),ref:n})))}):et.createElement("path",w3({},$i(r,!0),{className:F,d:ffe(p,l,g,v,E)}))},vCt=["points","className","baseLinePoints","connectNulls"];function cE(){return cE=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function wCt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function mfe(t){return ACt(t)||TCt(t)||ECt(t)||SCt()}function SCt(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ECt(t,e){if(t){if(typeof t=="string")return V7(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return V7(t,e)}}function TCt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function ACt(t){if(Array.isArray(t))return V7(t)}function V7(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return e.forEach(function(n){pfe(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),pfe(e[0])&&r[r.length-1].push(e[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},bj=function(e,r){var n=kCt(e);r&&(n=[n.reduce(function(a,c){return[].concat(mfe(a),mfe(c))},[])]);var i=n.map(function(a){return a.reduce(function(c,d,p){return"".concat(c).concat(p===0?"M":"L").concat(d.x,",").concat(d.y)},"")}).join("");return n.length===1?"".concat(i,"Z"):i},ICt=function(e,r,n){var i=bj(e,n);return"".concat(i.slice(-1)==="Z"?i.slice(0,-1):i,"L").concat(bj(r.reverse(),n).slice(1))},jCt=function(e){var r=e.points,n=e.className,i=e.baseLinePoints,a=e.connectNulls,c=bCt(e,vCt);if(!r||!r.length)return null;var d=hs("recharts-polygon",n);if(i&&i.length){var p=c.stroke&&c.stroke!=="none",l=ICt(r,i,a);return et.createElement("g",{className:d},et.createElement("path",cE({},$i(c,!0),{fill:l.slice(-1)==="Z"?c.fill:"none",stroke:"none",d:l})),p?et.createElement("path",cE({},$i(c,!0),{fill:"none",d:bj(r,a)})):null,p?et.createElement("path",cE({},$i(c,!0),{fill:"none",d:bj(i,a)})):null)}var g=bj(r,a);return et.createElement("path",cE({},$i(c,!0),{fill:g.slice(-1)==="Z"?c.fill:"none",className:d,d:g}))};function q7(){return q7=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function MCt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var OCt=function(e,r,n,i,a,c){return"M".concat(e,",").concat(a,"v").concat(i,"M").concat(c,",").concat(r,"h").concat(n)},FCt=function(e){var r=e.x,n=r===void 0?0:r,i=e.y,a=i===void 0?0:i,c=e.top,d=c===void 0?0:c,p=e.left,l=p===void 0?0:p,g=e.width,v=g===void 0?0:g,E=e.height,T=E===void 0?0:E,j=e.className,P=DCt(e,CCt),C=PCt({x:n,y:a,top:d,left:l,width:v,height:T},P);return!gn(n)||!gn(a)||!gn(v)||!gn(T)||!gn(d)||!gn(l)?null:et.createElement("path",G7({},$i(C,!0),{className:hs("recharts-cross",j),d:OCt(n,a,v,T,d,l)}))},BCt=gB,zCt=iIe,$Ct=Ag;function UCt(t,e){return t&&t.length?BCt(t,$Ct(e),zCt):void 0}var VCt=UCt;const qCt=ea(VCt);var GCt=gB,HCt=Ag,WCt=sIe;function KCt(t,e){return t&&t.length?GCt(t,HCt(e),WCt):void 0}var YCt=KCt;const ZCt=ea(YCt);var XCt=["cx","cy","angle","ticks","axisLine"],QCt=["ticks","tick","angle","tickFormatter","stroke"];function CT(t){"@babel/helpers - typeof";return CT=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},CT(t)}function wj(){return wj=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function JCt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function ePt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function _fe(t,e){for(var r=0;rwfe?c=i==="outer"?"start":"end":a<-wfe?c=i==="outer"?"end":"start":c="middle",c}},{key:"renderAxisLine",value:function(){var n=this.props,i=n.cx,a=n.cy,c=n.radius,d=n.axisLine,p=n.axisLineType,l=lb(lb({},$i(this.props,!1)),{},{fill:"none"},$i(d,!1));if(p==="circle")return et.createElement(WX,wb({className:"recharts-polar-angle-axis-line"},l,{cx:i,cy:a,r:c}));var g=this.props.ticks,v=g.map(function(E){return To(i,a,c,E.coordinate)});return et.createElement(jCt,wb({className:"recharts-polar-angle-axis-line"},l,{points:v}))}},{key:"renderTicks",value:function(){var n=this,i=this.props,a=i.ticks,c=i.tick,d=i.tickLine,p=i.tickFormatter,l=i.stroke,g=$i(this.props,!1),v=$i(c,!1),E=lb(lb({},g),{},{fill:"none"},$i(d,!1)),T=a.map(function(j,P){var C=n.getTickLineCoord(j),L=n.getTickTextAnchor(j),O=lb(lb(lb({textAnchor:L},g),{},{stroke:"none",fill:l},v),{},{index:P,payload:j,x:C.x2,y:C.y2});return et.createElement($a,wb({className:hs("recharts-polar-angle-axis-tick",RIe(c)),key:"tick-".concat(j.coordinate)},mw(n.props,j,P)),d&&et.createElement("line",wb({className:"recharts-polar-angle-axis-tick-line"},E,C)),c&&e.renderTickItem(c,O,p?p(j.value,P):j.value))});return et.createElement($a,{className:"recharts-polar-angle-axis-ticks"},T)}},{key:"render",value:function(){var n=this.props,i=n.ticks,a=n.radius,c=n.axisLine;return a<=0||!i||!i.length?null:et.createElement($a,{className:hs("recharts-polar-angle-axis",this.props.className)},c&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,i,a){var c;return et.isValidElement(n)?c=et.cloneElement(n,i):Wi(n)?c=n(i):c=et.createElement(pw,wb({},i,{className:"recharts-polar-angle-axis-tick-value"}),a),c}}])}(N.PureComponent);TB(AB,"displayName","PolarAngleAxis");TB(AB,"axisType","angleAxis");TB(AB,"defaultProps",{type:"category",angleAxisId:0,scale:"auto",cx:0,cy:0,orientation:"outer",axisLine:!0,tickLine:!0,tickSize:8,tick:!0,hide:!1,allowDuplicatedCategory:!0});var pPt=tke,gPt=pPt(Object.getPrototypeOf,Object),yPt=gPt,xPt=cx,_Pt=yPt,vPt=ux,bPt="[object Object]",wPt=Function.prototype,SPt=Object.prototype,XIe=wPt.toString,EPt=SPt.hasOwnProperty,TPt=XIe.call(Object);function APt(t){if(!vPt(t)||xPt(t)!=bPt)return!1;var e=_Pt(t);if(e===null)return!0;var r=EPt.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&XIe.call(r)==TPt}var kPt=APt;const IPt=ea(kPt);var jPt=cx,CPt=ux,PPt="[object Boolean]";function NPt(t){return t===!0||t===!1||CPt(t)&&jPt(t)==PPt}var RPt=NPt;const LPt=ea(RPt);function WC(t){"@babel/helpers - typeof";return WC=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},WC(t)}function T3(){return T3=Object.assign?Object.assign.bind():function(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r0,from:{upperWidth:0,lowerWidth:0,height:E,x:p,y:l},to:{upperWidth:g,lowerWidth:v,height:E,x:p,y:l},duration:P,animationEasing:j,isActive:L},function(F){var $=F.upperWidth,G=F.lowerWidth,W=F.height,Z=F.x,Q=F.y;return et.createElement(Jy,{canBegin:c>0,from:"0px ".concat(c===-1?1:c,"px"),to:"".concat(c,"px 0px"),attributeName:"strokeDasharray",begin:C,duration:P,easing:j},et.createElement("path",T3({},$i(r,!0),{className:O,d:Afe(Z,Q,$,G,W),ref:n})))}):et.createElement("g",null,et.createElement("path",T3({},$i(r,!0),{className:O,d:Afe(p,l,g,v,E)})))},GPt=["option","shapeType","propTransformer","activeClassName","isActive"];function KC(t){"@babel/helpers - typeof";return KC=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},KC(t)}function HPt(t,e){if(t==null)return{};var r=WPt(t,e),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function WPt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function kfe(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function A3(t){for(var e=1;e0?Xh(F,"paddingAngle",0):0;if(G){var Z=P_(G.endAngle-G.startAngle,F.endAngle-F.startAngle),Q=vo(vo({},F),{},{startAngle:O+W,endAngle:O+Z(P)+W});C.push(Q),O=Q.endAngle}else{var ee=F.endAngle,ie=F.startAngle,oe=P_(0,ee-ie),pe=oe(P),Le=vo(vo({},F),{},{startAngle:O+W,endAngle:O+pe+W});C.push(Le),O=Le.endAngle}}),et.createElement($a,null,n.renderSectorsStatically(C))})}},{key:"attachKeyboardHandlers",value:function(n){var i=this;n.onkeydown=function(a){if(!a.altKey)switch(a.key){case"ArrowLeft":{var c=++i.state.sectorToFocus%i.sectorRefs.length;i.sectorRefs[c].focus(),i.setState({sectorToFocus:c});break}case"ArrowRight":{var d=--i.state.sectorToFocus<0?i.sectorRefs.length-1:i.state.sectorToFocus%i.sectorRefs.length;i.sectorRefs[d].focus(),i.setState({sectorToFocus:d});break}case"Escape":{i.sectorRefs[i.state.sectorToFocus].blur(),i.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var n=this.props,i=n.sectors,a=n.isAnimationActive,c=this.state.prevSectors;return a&&i&&i.length&&(!c||!_B(c,i))?this.renderSectorsWithAnimation():this.renderSectorsStatically(i)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,i=this.props,a=i.hide,c=i.sectors,d=i.className,p=i.label,l=i.cx,g=i.cy,v=i.innerRadius,E=i.outerRadius,T=i.isAnimationActive,j=this.state.isAnimationFinished;if(a||!c||!c.length||!gn(l)||!gn(g)||!gn(v)||!gn(E))return null;var P=hs("recharts-pie",d);return et.createElement($a,{tabIndex:this.props.rootTabIndex,className:P,ref:function(L){n.pieRef=L}},this.renderSectors(),p&&this.renderLabels(c),nu.renderCallByParent(this.props,null,!1),(!T||j)&&hv.renderCallByParent(this.props,c,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,i){return i.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==i.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:i.curSectors,isAnimationFinished:!0}:n.sectors!==i.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,i){return n>i?"start":n=360?O:O-1)*p,$=C-O*T-F,G=i.reduce(function(Q,ee){var ie=Mu(ee,L,0);return Q+(gn(ie)?ie:0)},0),W;if(G>0){var Z;W=i.map(function(Q,ee){var ie=Mu(Q,L,0),oe=Mu(Q,g,ee),pe=(gn(ie)?ie:0)/G,Le;ee?Le=Z.endAngle+Ld(P)*p*(ie!==0?1:0):Le=c;var be=Le+Ld(P)*((ie!==0?T:0)+pe*$),Re=(Le+be)/2,Ie=(j.innerRadius+j.outerRadius)/2,Te=[{name:oe,value:ie,payload:Q,dataKey:L,type:E}],ge=To(j.cx,j.cy,Ie,Re);return Z=vo(vo(vo({percent:pe,cornerRadius:a,name:oe,tooltipPayload:Te,midAngle:Re,middleRadius:Ie,tooltipPosition:ge},Q),j),{},{value:Mu(Q,L),startAngle:Le,endAngle:be,payload:Q,paddingAngle:Ld(P)*p}),Z})}return vo(vo({},j),{},{sectors:W,data:i})});var mNt=Math.ceil,pNt=Math.max;function gNt(t,e,r,n){for(var i=-1,a=pNt(mNt((e-t)/(r||1)),0),c=Array(a);a--;)c[n?a:++i]=t,t+=r;return c}var yNt=gNt,xNt=vke,Pfe=1/0,_Nt=17976931348623157e292;function vNt(t){if(!t)return t===0?t:0;if(t=xNt(t),t===Pfe||t===-Pfe){var e=t<0?-1:1;return e*_Nt}return t===t?t:0}var tje=vNt,bNt=yNt,wNt=lB,jV=tje;function SNt(t){return function(e,r,n){return n&&typeof n!="number"&&wNt(e,r,n)&&(r=n=void 0),e=jV(e),r===void 0?(r=e,e=0):r=jV(r),n=n===void 0?e0&&n.handleDrag(i.changedTouches[0])}),Bh(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var i=n.props,a=i.endIndex,c=i.onDragEnd,d=i.startIndex;c==null||c({endIndex:a,startIndex:d})}),n.detachDragEndListener()}),Bh(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),Bh(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),Bh(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),Bh(n,"handleSlideDragStart",function(i){var a=Mfe(i)?i.changedTouches[0]:i;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:a.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}return ONt(e,t),RNt(e,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var i=n.startX,a=n.endX,c=this.state.scaleValues,d=this.props,p=d.gap,l=d.data,g=l.length-1,v=Math.min(i,a),E=Math.max(i,a),T=e.getIndexInRange(c,v),j=e.getIndexInRange(c,E);return{startIndex:T-T%p,endIndex:j===g?g:j-j%p}}},{key:"getTextOfTick",value:function(n){var i=this.props,a=i.data,c=i.tickFormatter,d=i.dataKey,p=Mu(a[n],d,n);return Wi(c)?c(p,n):p}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(n){var i=this.state,a=i.slideMoveStartX,c=i.startX,d=i.endX,p=this.props,l=p.x,g=p.width,v=p.travellerWidth,E=p.startIndex,T=p.endIndex,j=p.onChange,P=n.pageX-a;P>0?P=Math.min(P,l+g-v-d,l+g-v-c):P<0&&(P=Math.max(P,l-c,l-d));var C=this.getIndex({startX:c+P,endX:d+P});(C.startIndex!==E||C.endIndex!==T)&&j&&j(C),this.setState({startX:c+P,endX:d+P,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,i){var a=Mfe(i)?i.changedTouches[0]:i;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:a.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var i=this.state,a=i.brushMoveStartX,c=i.movingTravellerId,d=i.endX,p=i.startX,l=this.state[c],g=this.props,v=g.x,E=g.width,T=g.travellerWidth,j=g.onChange,P=g.gap,C=g.data,L={startX:this.state.startX,endX:this.state.endX},O=n.pageX-a;O>0?O=Math.min(O,v+E-T-l):O<0&&(O=Math.max(O,v-l)),L[c]=l+O;var F=this.getIndex(L),$=F.startIndex,G=F.endIndex,W=function(){var Q=C.length-1;return c==="startX"&&(d>p?$%P===0:G%P===0)||dp?G%P===0:$%P===0)||d>p&&G===Q};this.setState(Bh(Bh({},c,l+O),"brushMoveStartX",n.pageX),function(){j&&W()&&j(F)})}},{key:"handleTravellerMoveKeyboard",value:function(n,i){var a=this,c=this.state,d=c.scaleValues,p=c.startX,l=c.endX,g=this.state[i],v=d.indexOf(g);if(v!==-1){var E=v+n;if(!(E===-1||E>=d.length)){var T=d[E];i==="startX"&&T>=l||i==="endX"&&T<=p||this.setState(Bh({},i,T),function(){a.props.onChange(a.getIndex({startX:a.state.startX,endX:a.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,i=n.x,a=n.y,c=n.width,d=n.height,p=n.fill,l=n.stroke;return et.createElement("rect",{stroke:l,fill:p,x:i,y:a,width:c,height:d})}},{key:"renderPanorama",value:function(){var n=this.props,i=n.x,a=n.y,c=n.width,d=n.height,p=n.data,l=n.children,g=n.padding,v=N.Children.only(l);return v?et.cloneElement(v,{x:i,y:a,width:c,height:d,margin:g,compact:!0,data:p}):null}},{key:"renderTravellerLayer",value:function(n,i){var a,c,d=this,p=this.props,l=p.y,g=p.travellerWidth,v=p.height,E=p.traveller,T=p.ariaLabel,j=p.data,P=p.startIndex,C=p.endIndex,L=Math.max(n,this.props.x),O=CV(CV({},$i(this.props,!1)),{},{x:L,y:l,width:g,height:v}),F=T||"Min value: ".concat((a=j[P])===null||a===void 0?void 0:a.name,", Max value: ").concat((c=j[C])===null||c===void 0?void 0:c.name);return et.createElement($a,{tabIndex:0,role:"slider","aria-label":F,"aria-valuenow":n,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[i],onTouchStart:this.travellerDragStartHandlers[i],onKeyDown:function(G){["ArrowLeft","ArrowRight"].includes(G.key)&&(G.preventDefault(),G.stopPropagation(),d.handleTravellerMoveKeyboard(G.key==="ArrowRight"?1:-1,i))},onFocus:function(){d.setState({isTravellerFocused:!0})},onBlur:function(){d.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},e.renderTraveller(E,O))}},{key:"renderSlide",value:function(n,i){var a=this.props,c=a.y,d=a.height,p=a.stroke,l=a.travellerWidth,g=Math.min(n,i)+l,v=Math.max(Math.abs(i-n)-l,0);return et.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:p,fillOpacity:.2,x:g,y:c,width:v,height:d})}},{key:"renderText",value:function(){var n=this.props,i=n.startIndex,a=n.endIndex,c=n.y,d=n.height,p=n.travellerWidth,l=n.stroke,g=this.state,v=g.startX,E=g.endX,T=5,j={pointerEvents:"none",fill:l};return et.createElement($a,{className:"recharts-brush-texts"},et.createElement(pw,j3({textAnchor:"end",verticalAnchor:"middle",x:Math.min(v,E)-T,y:c+d/2},j),this.getTextOfTick(i)),et.createElement(pw,j3({textAnchor:"start",verticalAnchor:"middle",x:Math.max(v,E)+p+T,y:c+d/2},j),this.getTextOfTick(a)))}},{key:"render",value:function(){var n=this.props,i=n.data,a=n.className,c=n.children,d=n.x,p=n.y,l=n.width,g=n.height,v=n.alwaysShowText,E=this.state,T=E.startX,j=E.endX,P=E.isTextActive,C=E.isSlideMoving,L=E.isTravellerMoving,O=E.isTravellerFocused;if(!i||!i.length||!gn(d)||!gn(p)||!gn(l)||!gn(g)||l<=0||g<=0)return null;var F=hs("recharts-brush",a),$=et.Children.count(c)===1,G=PNt("userSelect","none");return et.createElement($a,{className:F,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:G},this.renderBackground(),$&&this.renderPanorama(),this.renderSlide(T,j),this.renderTravellerLayer(T,"startX"),this.renderTravellerLayer(j,"endX"),(P||C||L||O||v)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var i=n.x,a=n.y,c=n.width,d=n.height,p=n.stroke,l=Math.floor(a+d/2)-1;return et.createElement(et.Fragment,null,et.createElement("rect",{x:i,y:a,width:c,height:d,fill:p,stroke:"none"}),et.createElement("line",{x1:i+1,y1:l,x2:i+c-1,y2:l,fill:"none",stroke:"#fff"}),et.createElement("line",{x1:i+1,y1:l+2,x2:i+c-1,y2:l+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,i){var a;return et.isValidElement(n)?a=et.cloneElement(n,i):Wi(n)?a=n(i):a=e.renderDefaultTraveller(i),a}},{key:"getDerivedStateFromProps",value:function(n,i){var a=n.data,c=n.width,d=n.x,p=n.travellerWidth,l=n.updateId,g=n.startIndex,v=n.endIndex;if(a!==i.prevData||l!==i.prevUpdateId)return CV({prevData:a,prevTravellerWidth:p,prevUpdateId:l,prevX:d,prevWidth:c},a&&a.length?BNt({data:a,width:c,x:d,travellerWidth:p,startIndex:g,endIndex:v}):{scale:null,scaleValues:null});if(i.scale&&(c!==i.prevWidth||d!==i.prevX||p!==i.prevTravellerWidth)){i.scale.range([d,d+c-p]);var E=i.scale.domain().map(function(T){return i.scale(T)});return{prevData:a,prevTravellerWidth:p,prevUpdateId:l,prevX:d,prevWidth:c,startX:i.scale(n.startIndex),endX:i.scale(n.endIndex),scaleValues:E}}return null}},{key:"getIndexInRange",value:function(n,i){for(var a=n.length,c=0,d=a-1;d-c>1;){var p=Math.floor((c+d)/2);n[p]>i?d=p:c=p}return i>=n[d]?d:c}}])}(N.PureComponent);Bh(LT,"displayName","Brush");Bh(LT,"defaultProps",{height:40,travellerWidth:5,gap:1,fill:"#fff",stroke:"#666",padding:{top:1,right:1,bottom:1,left:1},leaveTimeOut:1e3,alwaysShowText:!1});var zNt=xX;function $Nt(t,e){var r;return zNt(t,function(n,i,a){return r=e(n,i,a),!r}),!!r}var UNt=$Nt,VNt=W2e,qNt=Ag,GNt=UNt,HNt=bh,WNt=lB;function KNt(t,e,r){var n=HNt(t)?VNt:GNt;return r&&WNt(t,e,r)&&(e=void 0),n(t,qNt(e))}var YNt=KNt;const ZNt=ea(YNt);var og=function(e,r){var n=e.alwaysShow,i=e.ifOverflow;return n&&(i="extendDomain"),i===r},Ofe=pke;function XNt(t,e,r){e=="__proto__"&&Ofe?Ofe(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var QNt=XNt,JNt=QNt,eRt=fke,tRt=Ag;function rRt(t,e){var r={};return e=tRt(e),eRt(t,function(n,i,a){JNt(r,i,e(n,i,a))}),r}var nRt=rRt;const iRt=ea(nRt);function sRt(t,e){for(var r=-1,n=t==null?0:t.length;++r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function wRt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function SRt(t,e){var r=t.x,n=t.y,i=bRt(t,yRt),a="".concat(r),c=parseInt(a,10),d="".concat(n),p=parseInt(d,10),l="".concat(e.height||i.height),g=parseInt(l,10),v="".concat(e.width||i.width),E=parseInt(v,10);return _I(_I(_I(_I(_I({},e),i),c?{x:c}:{}),p?{y:p}:{}),{},{height:g,width:E,name:e.name,radius:e.radius})}function Bfe(t){return et.createElement(QIe,Z7({shapeType:"rectangle",propTransformer:SRt,activeClassName:"recharts-active-bar"},t))}var ERt=function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(n,i){if(typeof e=="number")return e;var a=gn(n)||Umt(n);return a?e(n,i):(a||yw(),r)}},TRt=["value","background"],aje;function DT(t){"@babel/helpers - typeof";return DT=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},DT(t)}function ARt(t,e){if(t==null)return{};var r=kRt(t,e),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function kRt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function P3(){return P3=Object.assign?Object.assign.bind():function(t){for(var e=1;e0&&Math.abs(Re)0&&Math.abs(be)0&&(Le=Math.min((ot||0)-(be[nt-1]||0),Le))}),Number.isFinite(Le)){var Re=Le/pe,Ie=P.layout==="vertical"?n.height:n.width;if(P.padding==="gap"&&(Z=Re*Ie/2),P.padding==="no-gap"){var Te=Dd(e.barCategoryGap,Re*Ie),ge=Re*Ie/2;Z=ge-Te-(ge-Te)/Ie*Te}}}i==="xAxis"?Q=[n.left+(F.left||0)+(Z||0),n.left+n.width-(F.right||0)-(Z||0)]:i==="yAxis"?Q=p==="horizontal"?[n.top+n.height-(F.bottom||0),n.top+(F.top||0)]:[n.top+(F.top||0)+(Z||0),n.top+n.height-(F.bottom||0)-(Z||0)]:Q=P.range,G&&(Q=[Q[1],Q[0]]);var $e=AIe(P,a,E),we=$e.scale,ke=$e.realScaleType;we.domain(L).range(Q),kIe(we);var Ae=IIe(we,$m($m({},P),{},{realScaleType:ke}));i==="xAxis"?(oe=C==="top"&&!$||C==="bottom"&&$,ee=n.left,ie=v[W]-oe*P.height):i==="yAxis"&&(oe=C==="left"&&!$||C==="right"&&$,ee=v[W]-oe*P.width,ie=n.top);var He=$m($m($m({},P),Ae),{},{realScaleType:ke,x:ee,y:ie,scale:we,width:i==="xAxis"?n.width:P.width,height:i==="yAxis"?n.height:P.height});return He.bandSize=m3(He,Ae),!P.hide&&i==="xAxis"?v[W]+=(oe?-1:1)*He.height:P.hide||(v[W]+=(oe?-1:1)*He.width),$m($m({},T),{},jB({},j,He))},{})},uje=function(e,r){var n=e.x,i=e.y,a=r.x,c=r.y;return{x:Math.min(n,a),y:Math.min(i,c),width:Math.abs(a-n),height:Math.abs(c-i)}},BRt=function(e){var r=e.x1,n=e.y1,i=e.x2,a=e.y2;return uje({x:r,y:n},{x:i,y:a})},dje=function(){function t(e){DRt(this,t),this.scale=e}return MRt(t,[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=n.bandAware,a=n.position;if(r!==void 0){if(a)switch(a){case"start":return this.scale(r);case"middle":{var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+c}case"end":{var d=this.bandwidth?this.bandwidth():0;return this.scale(r)+d}default:return this.scale(r)}if(i){var p=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+p}return this.scale(r)}}},{key:"isInRange",value:function(r){var n=this.range(),i=n[0],a=n[n.length-1];return i<=a?r>=i&&r<=a:r>=a&&r<=i}}],[{key:"create",value:function(r){return new t(r)}}])}();jB(dje,"EPS",1e-4);var KX=function(e){var r=Object.keys(e).reduce(function(n,i){return $m($m({},n),{},jB({},i,dje.create(e[i])))},{});return $m($m({},r),{},{apply:function(i){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},c=a.bandAware,d=a.position;return iRt(i,function(p,l){return r[l].apply(p,{bandAware:c,position:d})})},isInRange:function(i){return sje(i,function(a,c){return r[c].isInRange(a)})}})};function zRt(t){return(t%180+180)%180}var $Rt=function(e){var r=e.width,n=e.height,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,a=zRt(i),c=a*Math.PI/180,d=Math.atan(n/r),p=c>d&&c-1?i[a?e[c]:c]:void 0}}var HRt=GRt,WRt=tje;function KRt(t){var e=WRt(t),r=e%1;return e===e?r?e-r:e:0}var YRt=KRt,ZRt=oke,XRt=Ag,QRt=YRt,JRt=Math.max;function eLt(t,e,r){var n=t==null?0:t.length;if(!n)return-1;var i=r==null?0:QRt(r);return i<0&&(i=JRt(n+i,0)),ZRt(t,XRt(e),i)}var tLt=eLt,rLt=HRt,nLt=tLt,iLt=rLt(nLt),sLt=iLt;const aLt=ea(sLt);var oLt=Kft(function(t){return{x:t.left,y:t.top,width:t.width,height:t.height}},function(t){return["l",t.left,"t",t.top,"w",t.width,"h",t.height].join("")}),YX=N.createContext(void 0),ZX=N.createContext(void 0),hje=N.createContext(void 0),fje=N.createContext({}),mje=N.createContext(void 0),pje=N.createContext(0),gje=N.createContext(0),qfe=function(e){var r=e.state,n=r.xAxisMap,i=r.yAxisMap,a=r.offset,c=e.clipPathId,d=e.children,p=e.width,l=e.height,g=oLt(a);return et.createElement(YX.Provider,{value:n},et.createElement(ZX.Provider,{value:i},et.createElement(fje.Provider,{value:a},et.createElement(hje.Provider,{value:g},et.createElement(mje.Provider,{value:c},et.createElement(pje.Provider,{value:l},et.createElement(gje.Provider,{value:p},d)))))))},lLt=function(){return N.useContext(mje)},yje=function(e){var r=N.useContext(YX);r==null&&yw();var n=r[e];return n==null&&yw(),n},cLt=function(){var e=N.useContext(YX);return F_(e)},uLt=function(){var e=N.useContext(ZX),r=aLt(e,function(n){return sje(n.domain,Number.isFinite)});return r||F_(e)},xje=function(e){var r=N.useContext(ZX);r==null&&yw();var n=r[e];return n==null&&yw(),n},dLt=function(){var e=N.useContext(hje);return e},hLt=function(){return N.useContext(fje)},XX=function(){return N.useContext(gje)},QX=function(){return N.useContext(pje)};function MT(t){"@babel/helpers - typeof";return MT=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},MT(t)}function fLt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function mLt(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);rt*i)return!1;var a=r();return t*(e-t*a/2-n)>=0&&t*(e+t*a/2-i)<=0}function YLt(t,e){return Tje(t,e+1)}function ZLt(t,e,r,n,i){for(var a=(n||[]).slice(),c=e.start,d=e.end,p=0,l=1,g=c,v=function(){var j=n==null?void 0:n[p];if(j===void 0)return{v:Tje(n,l)};var P=p,C,L=function(){return C===void 0&&(C=r(j,P)),C},O=j.coordinate,F=p===0||M3(t,O,L,g,d);F||(p=0,g=c,l+=1),F&&(g=O+t*(L()/2+i),p+=l)},E;l<=a.length;)if(E=v(),E)return E.v;return[]}function JC(t){"@babel/helpers - typeof";return JC=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},JC(t)}function Qfe(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function ed(t){for(var e=1;e0?T.coordinate-C*t:T.coordinate})}else a[E]=T=ed(ed({},T),{},{tickCoord:T.coordinate});var L=M3(t,T.tickCoord,P,d,p);L&&(p=T.tickCoord-t*(P()/2+i),a[E]=ed(ed({},T),{},{isShow:!0}))},g=c-1;g>=0;g--)l(g);return a}function tDt(t,e,r,n,i,a){var c=(n||[]).slice(),d=c.length,p=e.start,l=e.end;if(a){var g=n[d-1],v=r(g,d-1),E=t*(g.coordinate+t*v/2-l);c[d-1]=g=ed(ed({},g),{},{tickCoord:E>0?g.coordinate-E*t:g.coordinate});var T=M3(t,g.tickCoord,function(){return v},p,l);T&&(l=g.tickCoord-t*(v/2+i),c[d-1]=ed(ed({},g),{},{isShow:!0}))}for(var j=a?d-1:d,P=function(O){var F=c[O],$,G=function(){return $===void 0&&($=r(F,O)),$};if(O===0){var W=t*(F.coordinate-t*G()/2-p);c[O]=F=ed(ed({},F),{},{tickCoord:W<0?F.coordinate-W*t:F.coordinate})}else c[O]=F=ed(ed({},F),{},{tickCoord:F.coordinate});var Z=M3(t,F.tickCoord,G,p,l);Z&&(p=F.tickCoord+t*(G()/2+i),c[O]=ed(ed({},F),{},{isShow:!0}))},C=0;C=2?Ld(i[1].coordinate-i[0].coordinate):1,L=KLt(a,C,T);return p==="equidistantPreserveStart"?ZLt(C,L,P,i,c):(p==="preserveStart"||p==="preserveStartEnd"?E=tDt(C,L,P,i,c,p==="preserveStartEnd"):E=eDt(C,L,P,i,c),E.filter(function(O){return O.isShow}))}var rDt=["viewBox"],nDt=["viewBox"],iDt=["ticks"];function BT(t){"@babel/helpers - typeof";return BT=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},BT(t)}function dE(){return dE=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function sDt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function aDt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function eme(t,e){for(var r=0;r0?p(this.props):p(T)),c<=0||d<=0||!j||!j.length?null:et.createElement($a,{className:hs("recharts-cartesian-axis",l),ref:function(C){n.layerReference=C}},a&&this.renderAxisLine(),this.renderTicks(j,this.state.fontSize,this.state.letterSpacing),nu.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,i,a){var c,d=hs(i.className,"recharts-cartesian-axis-tick-value");return et.isValidElement(n)?c=et.cloneElement(n,Ac(Ac({},i),{},{className:d})):Wi(n)?c=n(Ac(Ac({},i),{},{className:d})):c=et.createElement(pw,dE({},i,{className:"recharts-cartesian-axis-tick-value"}),a),c}}])}(N.Component);rQ(UA,"displayName","CartesianAxis");rQ(UA,"defaultProps",{x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd"});var fDt=["x1","y1","x2","y2","key"],mDt=["offset"];function xw(t){"@babel/helpers - typeof";return xw=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},xw(t)}function tme(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function rd(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function xDt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}var _Dt=function(e){var r=e.fill;if(!r||r==="none")return null;var n=e.fillOpacity,i=e.x,a=e.y,c=e.width,d=e.height,p=e.ry;return et.createElement("rect",{x:i,y:a,ry:p,width:c,height:d,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function Ije(t,e){var r;if(et.isValidElement(t))r=et.cloneElement(t,e);else if(Wi(t))r=t(e);else{var n=e.x1,i=e.y1,a=e.x2,c=e.y2,d=e.key,p=rme(e,fDt),l=$i(p,!1);l.offset;var g=rme(l,mDt);r=et.createElement("line",Lb({},g,{x1:n,y1:i,x2:a,y2:c,fill:"none",key:d}))}return r}function vDt(t){var e=t.x,r=t.width,n=t.horizontal,i=n===void 0?!0:n,a=t.horizontalPoints;if(!i||!a||!a.length)return null;var c=a.map(function(d,p){var l=rd(rd({},t),{},{x1:e,y1:d,x2:e+r,y2:d,key:"line-".concat(p),index:p});return Ije(i,l)});return et.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function bDt(t){var e=t.y,r=t.height,n=t.vertical,i=n===void 0?!0:n,a=t.verticalPoints;if(!i||!a||!a.length)return null;var c=a.map(function(d,p){var l=rd(rd({},t),{},{x1:d,y1:e,x2:d,y2:e+r,key:"line-".concat(p),index:p});return Ije(i,l)});return et.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function wDt(t){var e=t.horizontalFill,r=t.fillOpacity,n=t.x,i=t.y,a=t.width,c=t.height,d=t.horizontalPoints,p=t.horizontal,l=p===void 0?!0:p;if(!l||!e||!e.length)return null;var g=d.map(function(E){return Math.round(E+i-i)}).sort(function(E,T){return E-T});i!==g[0]&&g.unshift(0);var v=g.map(function(E,T){var j=!g[T+1],P=j?i+c-E:g[T+1]-E;if(P<=0)return null;var C=T%e.length;return et.createElement("rect",{key:"react-".concat(T),y:E,x:n,height:P,width:a,stroke:"none",fill:e[C],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return et.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},v)}function SDt(t){var e=t.vertical,r=e===void 0?!0:e,n=t.verticalFill,i=t.fillOpacity,a=t.x,c=t.y,d=t.width,p=t.height,l=t.verticalPoints;if(!r||!n||!n.length)return null;var g=l.map(function(E){return Math.round(E+a-a)}).sort(function(E,T){return E-T});a!==g[0]&&g.unshift(0);var v=g.map(function(E,T){var j=!g[T+1],P=j?a+d-E:g[T+1]-E;if(P<=0)return null;var C=T%n.length;return et.createElement("rect",{key:"react-".concat(T),x:E,y:c,width:P,height:p,stroke:"none",fill:n[C],fillOpacity:i,className:"recharts-cartesian-grid-bg"})});return et.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},v)}var EDt=function(e,r){var n=e.xAxis,i=e.width,a=e.height,c=e.offset;return TIe(tQ(rd(rd(rd({},UA.defaultProps),n),{},{ticks:Iy(n,!0),viewBox:{x:0,y:0,width:i,height:a}})),c.left,c.left+c.width,r)},TDt=function(e,r){var n=e.yAxis,i=e.width,a=e.height,c=e.offset;return TIe(tQ(rd(rd(rd({},UA.defaultProps),n),{},{ticks:Iy(n,!0),viewBox:{x:0,y:0,width:i,height:a}})),c.top,c.top+c.height,r)},RS={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function jje(t){var e,r,n,i,a,c,d=XX(),p=QX(),l=hLt(),g=rd(rd({},t),{},{stroke:(e=t.stroke)!==null&&e!==void 0?e:RS.stroke,fill:(r=t.fill)!==null&&r!==void 0?r:RS.fill,horizontal:(n=t.horizontal)!==null&&n!==void 0?n:RS.horizontal,horizontalFill:(i=t.horizontalFill)!==null&&i!==void 0?i:RS.horizontalFill,vertical:(a=t.vertical)!==null&&a!==void 0?a:RS.vertical,verticalFill:(c=t.verticalFill)!==null&&c!==void 0?c:RS.verticalFill,x:gn(t.x)?t.x:l.left,y:gn(t.y)?t.y:l.top,width:gn(t.width)?t.width:l.width,height:gn(t.height)?t.height:l.height}),v=g.x,E=g.y,T=g.width,j=g.height,P=g.syncWithTicks,C=g.horizontalValues,L=g.verticalValues,O=cLt(),F=uLt();if(!gn(T)||T<=0||!gn(j)||j<=0||!gn(v)||v!==+v||!gn(E)||E!==+E)return null;var $=g.verticalCoordinatesGenerator||EDt,G=g.horizontalCoordinatesGenerator||TDt,W=g.horizontalPoints,Z=g.verticalPoints;if((!W||!W.length)&&Wi(G)){var Q=C&&C.length,ee=G({yAxis:F?rd(rd({},F),{},{ticks:Q?C:F.ticks}):void 0,width:d,height:p,offset:l},Q?!0:P);rp(Array.isArray(ee),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(xw(ee),"]")),Array.isArray(ee)&&(W=ee)}if((!Z||!Z.length)&&Wi($)){var ie=L&&L.length,oe=$({xAxis:O?rd(rd({},O),{},{ticks:ie?L:O.ticks}):void 0,width:d,height:p,offset:l},ie?!0:P);rp(Array.isArray(oe),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(xw(oe),"]")),Array.isArray(oe)&&(Z=oe)}return et.createElement("g",{className:"recharts-cartesian-grid"},et.createElement(_Dt,{fill:g.fill,fillOpacity:g.fillOpacity,x:g.x,y:g.y,width:g.width,height:g.height,ry:g.ry}),et.createElement(vDt,Lb({},g,{offset:l,horizontalPoints:W,xAxis:O,yAxis:F})),et.createElement(bDt,Lb({},g,{offset:l,verticalPoints:Z,xAxis:O,yAxis:F})),et.createElement(wDt,Lb({},g,{horizontalPoints:W})),et.createElement(SDt,Lb({},g,{verticalPoints:Z})))}jje.displayName="CartesianGrid";function zT(t){"@babel/helpers - typeof";return zT=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},zT(t)}function ADt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function kDt(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function fMt(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function mMt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function pMt(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r0?c:e&&e.length&&gn(i)&&gn(a)?e.slice(i,a+1):[]};function Vje(t){return t==="number"?[0,"auto"]:void 0}var fH=function(e,r,n,i){var a=e.graphicalItems,c=e.tooltipAxis,d=MB(r,e);return n<0||!a||!a.length||n>=d.length?null:a.reduce(function(p,l){var g,v=(g=l.props.data)!==null&&g!==void 0?g:r;v&&e.dataStartIndex+e.dataEndIndex!==0&&e.dataEndIndex-e.dataStartIndex>=n&&(v=v.slice(e.dataStartIndex,e.dataEndIndex+1));var E;if(c.dataKey&&!c.allowDuplicatedCategory){var T=v===void 0?d:v;E=BF(T,c.dataKey,i)}else E=v&&v[n]||d[n];return E?[].concat(VT(p),[CIe(l,E)]):p},[])},lme=function(e,r,n,i){var a=i||{x:e.chartX,y:e.chartY},c=kMt(a,n),d=e.orderedTooltipTicks,p=e.tooltipAxis,l=e.tooltipTicks,g=ekt(c,d,l,p);if(g>=0&&l){var v=l[g]&&l[g].value,E=fH(e,r,g,v),T=IMt(n,d,g,a);return{activeTooltipIndex:g,activeLabel:v,activePayload:E,activeCoordinate:T}}return null},jMt=function(e,r){var n=r.axes,i=r.graphicalItems,a=r.axisType,c=r.axisIdKey,d=r.stackGroups,p=r.dataStartIndex,l=r.dataEndIndex,g=e.layout,v=e.children,E=e.stackOffset,T=EIe(g,a);return n.reduce(function(j,P){var C,L=P.type.defaultProps!==void 0?Ir(Ir({},P.type.defaultProps),P.props):P.props,O=L.type,F=L.dataKey,$=L.allowDataOverflow,G=L.allowDuplicatedCategory,W=L.scale,Z=L.ticks,Q=L.includeHidden,ee=L[c];if(j[ee])return j;var ie=MB(e.data,{graphicalItems:i.filter(function(Ae){var He,ot=c in Ae.props?Ae.props[c]:(He=Ae.type.defaultProps)===null||He===void 0?void 0:He[c];return ot===ee}),dataStartIndex:p,dataEndIndex:l}),oe=ie.length,pe,Le,be;tMt(L.domain,$,O)&&(pe=k7(L.domain,null,$),T&&(O==="number"||W!=="auto")&&(be=_j(ie,F,"category")));var Re=Vje(O);if(!pe||pe.length===0){var Ie,Te=(Ie=L.domain)!==null&&Ie!==void 0?Ie:Re;if(F){if(pe=_j(ie,F,O),O==="category"&&T){var ge=qmt(pe);G&&ge?(Le=pe,pe=I3(0,oe)):G||(pe=Ohe(Te,pe,P).reduce(function(Ae,He){return Ae.indexOf(He)>=0?Ae:[].concat(VT(Ae),[He])},[]))}else if(O==="category")G?pe=pe.filter(function(Ae){return Ae!==""&&!fs(Ae)}):pe=Ohe(Te,pe,P).reduce(function(Ae,He){return Ae.indexOf(He)>=0||He===""||fs(He)?Ae:[].concat(VT(Ae),[He])},[]);else if(O==="number"){var $e=skt(ie,i.filter(function(Ae){var He,ot,nt=c in Ae.props?Ae.props[c]:(He=Ae.type.defaultProps)===null||He===void 0?void 0:He[c],tt="hide"in Ae.props?Ae.props.hide:(ot=Ae.type.defaultProps)===null||ot===void 0?void 0:ot.hide;return nt===ee&&(Q||!tt)}),F,a,g);$e&&(pe=$e)}T&&(O==="number"||W!=="auto")&&(be=_j(ie,F,"category"))}else T?pe=I3(0,oe):d&&d[ee]&&d[ee].hasStack&&O==="number"?pe=E==="expand"?[0,1]:jIe(d[ee].stackGroups,p,l):pe=SIe(ie,i.filter(function(Ae){var He=c in Ae.props?Ae.props[c]:Ae.type.defaultProps[c],ot="hide"in Ae.props?Ae.props.hide:Ae.type.defaultProps.hide;return He===ee&&(Q||!ot)}),O,g,!0);if(O==="number")pe=uH(v,pe,ee,a,Z),Te&&(pe=k7(Te,pe,$));else if(O==="category"&&Te){var we=Te,ke=pe.every(function(Ae){return we.indexOf(Ae)>=0});ke&&(pe=we)}}return Ir(Ir({},j),{},Li({},ee,Ir(Ir({},L),{},{axisType:a,domain:pe,categoricalDomain:be,duplicateDomain:Le,originalDomain:(C=L.domain)!==null&&C!==void 0?C:Re,isCategorical:T,layout:g})))},{})},CMt=function(e,r){var n=r.graphicalItems,i=r.Axis,a=r.axisType,c=r.axisIdKey,d=r.stackGroups,p=r.dataStartIndex,l=r.dataEndIndex,g=e.layout,v=e.children,E=MB(e.data,{graphicalItems:n,dataStartIndex:p,dataEndIndex:l}),T=E.length,j=EIe(g,a),P=-1;return n.reduce(function(C,L){var O=L.type.defaultProps!==void 0?Ir(Ir({},L.type.defaultProps),L.props):L.props,F=O[c],$=Vje("number");if(!C[F]){P++;var G;return j?G=I3(0,T):d&&d[F]&&d[F].hasStack?(G=jIe(d[F].stackGroups,p,l),G=uH(v,G,F,a)):(G=k7($,SIe(E,n.filter(function(W){var Z,Q,ee=c in W.props?W.props[c]:(Z=W.type.defaultProps)===null||Z===void 0?void 0:Z[c],ie="hide"in W.props?W.props.hide:(Q=W.type.defaultProps)===null||Q===void 0?void 0:Q.hide;return ee===F&&!ie}),"number",g),i.defaultProps.allowDataOverflow),G=uH(v,G,F,a)),Ir(Ir({},C),{},Li({},F,Ir(Ir({axisType:a},i.defaultProps),{},{hide:!0,orientation:Xh(TMt,"".concat(a,".").concat(P%2),null),domain:G,originalDomain:$,isCategorical:j,layout:g})))}return C},{})},PMt=function(e,r){var n=r.axisType,i=n===void 0?"xAxis":n,a=r.AxisComp,c=r.graphicalItems,d=r.stackGroups,p=r.dataStartIndex,l=r.dataEndIndex,g=e.children,v="".concat(i,"Id"),E=qf(g,a),T={};return E&&E.length?T=jMt(e,{axes:E,graphicalItems:c,axisType:i,axisIdKey:v,stackGroups:d,dataStartIndex:p,dataEndIndex:l}):c&&c.length&&(T=CMt(e,{Axis:a,graphicalItems:c,axisType:i,axisIdKey:v,stackGroups:d,dataStartIndex:p,dataEndIndex:l})),T},NMt=function(e){var r=F_(e),n=Iy(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:_X(n,function(i){return i.coordinate}),tooltipAxis:r,tooltipAxisBandSize:m3(r,n)}},cme=function(e){var r=e.children,n=e.defaultShowTooltip,i=Uh(r,LT),a=0,c=0;return e.data&&e.data.length!==0&&(c=e.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(a=i.props.startIndex),i.props.endIndex>=0&&(c=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:a,dataEndIndex:c,activeTooltipIndex:-1,isTooltipActive:!!n}},RMt=function(e){return!e||!e.length?!1:e.some(function(r){var n=My(r&&r.type);return n&&n.indexOf("Bar")>=0})},ume=function(e){return e==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:e==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:e==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},LMt=function(e,r){var n=e.props,i=e.graphicalItems,a=e.xAxisMap,c=a===void 0?{}:a,d=e.yAxisMap,p=d===void 0?{}:d,l=n.width,g=n.height,v=n.children,E=n.margin||{},T=Uh(v,LT),j=Uh(v,IE),P=Object.keys(p).reduce(function(G,W){var Z=p[W],Q=Z.orientation;return!Z.mirror&&!Z.hide?Ir(Ir({},G),{},Li({},Q,G[Q]+Z.width)):G},{left:E.left||0,right:E.right||0}),C=Object.keys(c).reduce(function(G,W){var Z=c[W],Q=Z.orientation;return!Z.mirror&&!Z.hide?Ir(Ir({},G),{},Li({},Q,Xh(G,"".concat(Q))+Z.height)):G},{top:E.top||0,bottom:E.bottom||0}),L=Ir(Ir({},C),P),O=L.bottom;T&&(L.bottom+=T.props.height||LT.defaultProps.height),j&&r&&(L=nkt(L,i,n,r));var F=l-L.left-L.right,$=g-L.top-L.bottom;return Ir(Ir({brushBottom:O},L),{},{width:Math.max(F,0),height:Math.max($,0)})},DMt=function(e,r){if(r==="xAxis")return e[r].width;if(r==="yAxis")return e[r].height},qje=function(e){var r=e.chartName,n=e.GraphicalChild,i=e.defaultTooltipEventType,a=i===void 0?"axis":i,c=e.validateTooltipEventTypes,d=c===void 0?["axis"]:c,p=e.axisComponents,l=e.legendContent,g=e.formatAxisMap,v=e.defaultProps,E=function(L,O){var F=O.graphicalItems,$=O.stackGroups,G=O.offset,W=O.updateId,Z=O.dataStartIndex,Q=O.dataEndIndex,ee=L.barSize,ie=L.layout,oe=L.barGap,pe=L.barCategoryGap,Le=L.maxBarSize,be=ume(ie),Re=be.numericAxisName,Ie=be.cateAxisName,Te=RMt(F),ge=[];return F.forEach(function($e,we){var ke=MB(L.data,{graphicalItems:[$e],dataStartIndex:Z,dataEndIndex:Q}),Ae=$e.type.defaultProps!==void 0?Ir(Ir({},$e.type.defaultProps),$e.props):$e.props,He=Ae.dataKey,ot=Ae.maxBarSize,nt=Ae["".concat(Re,"Id")],tt=Ae["".concat(Ie,"Id")],vt={},Vt=p.reduce(function(Fn,Ar){var Tn=O["".concat(Ar.axisType,"Map")],mn=Ae["".concat(Ar.axisType,"Id")];Tn&&Tn[mn]||Ar.axisType==="zAxis"||yw();var li=Tn[mn];return Ir(Ir({},Fn),{},Li(Li({},Ar.axisType,li),"".concat(Ar.axisType,"Ticks"),Iy(li)))},vt),Ct=Vt[Ie],Bt=Vt["".concat(Ie,"Ticks")],cr=$&&$[nt]&&$[nt].hasStack&&mkt($e,$[nt].stackGroups),ft=My($e.type).indexOf("Bar")>=0,Kt=m3(Ct,Bt),ir=[],Gr=Te&&tkt({barSize:ee,stackGroups:$,totalSize:DMt(Vt,Ie)});if(ft){var tr,Qt,zt=fs(ot)?Le:ot,Vr=(tr=(Qt=m3(Ct,Bt,!0))!==null&&Qt!==void 0?Qt:zt)!==null&&tr!==void 0?tr:0;ir=rkt({barGap:oe,barCategoryGap:pe,bandSize:Vr!==Kt?Vr:Kt,sizeList:Gr[tt],maxBarSize:zt}),Vr!==Kt&&(ir=ir.map(function(Fn){return Ir(Ir({},Fn),{},{position:Ir(Ir({},Fn.position),{},{offset:Fn.position.offset-Vr/2})})}))}var Jr=$e&&$e.type&&$e.type.getComposedData;Jr&&ge.push({props:Ir(Ir({},Jr(Ir(Ir({},Vt),{},{displayedData:ke,props:L,dataKey:He,item:$e,bandSize:Kt,barPosition:ir,offset:G,stackedData:cr,layout:ie,dataStartIndex:Z,dataEndIndex:Q}))),{},Li(Li(Li({key:$e.key||"item-".concat(we)},Re,Vt[Re]),Ie,Vt[Ie]),"animationId",W)),childIndex:rpt($e,L.children),item:$e})}),ge},T=function(L,O){var F=L.props,$=L.dataStartIndex,G=L.dataEndIndex,W=L.updateId;if(!Pue({props:F}))return null;var Z=F.children,Q=F.layout,ee=F.stackOffset,ie=F.data,oe=F.reverseStackOrder,pe=ume(Q),Le=pe.numericAxisName,be=pe.cateAxisName,Re=qf(Z,n),Ie=hkt(ie,Re,"".concat(Le,"Id"),"".concat(be,"Id"),ee,oe),Te=p.reduce(function(Ae,He){var ot="".concat(He.axisType,"Map");return Ir(Ir({},Ae),{},Li({},ot,PMt(F,Ir(Ir({},He),{},{graphicalItems:Re,stackGroups:He.axisType===Le&&Ie,dataStartIndex:$,dataEndIndex:G}))))},{}),ge=LMt(Ir(Ir({},Te),{},{props:F,graphicalItems:Re}),O==null?void 0:O.legendBBox);Object.keys(Te).forEach(function(Ae){Te[Ae]=g(F,Te[Ae],ge,Ae.replace("Map",""),r)});var $e=Te["".concat(be,"Map")],we=NMt($e),ke=E(F,Ir(Ir({},Te),{},{dataStartIndex:$,dataEndIndex:G,updateId:W,graphicalItems:Re,stackGroups:Ie,offset:ge}));return Ir(Ir({formattedGraphicalItems:ke,graphicalItems:Re,offset:ge,stackGroups:Ie},we),Te)},j=function(C){function L(O){var F,$,G;return mMt(this,L),G=yMt(this,L,[O]),Li(G,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Li(G,"accessibilityManager",new eMt),Li(G,"handleLegendBBoxUpdate",function(W){if(W){var Z=G.state,Q=Z.dataStartIndex,ee=Z.dataEndIndex,ie=Z.updateId;G.setState(Ir({legendBBox:W},T({props:G.props,dataStartIndex:Q,dataEndIndex:ee,updateId:ie},Ir(Ir({},G.state),{},{legendBBox:W}))))}}),Li(G,"handleReceiveSyncEvent",function(W,Z,Q){if(G.props.syncId===W){if(Q===G.eventEmitterSymbol&&typeof G.props.syncMethod!="function")return;G.applySyncEvent(Z)}}),Li(G,"handleBrushChange",function(W){var Z=W.startIndex,Q=W.endIndex;if(Z!==G.state.dataStartIndex||Q!==G.state.dataEndIndex){var ee=G.state.updateId;G.setState(function(){return Ir({dataStartIndex:Z,dataEndIndex:Q},T({props:G.props,dataStartIndex:Z,dataEndIndex:Q,updateId:ee},G.state))}),G.triggerSyncEvent({dataStartIndex:Z,dataEndIndex:Q})}}),Li(G,"handleMouseEnter",function(W){var Z=G.getMouseInfo(W);if(Z){var Q=Ir(Ir({},Z),{},{isTooltipActive:!0});G.setState(Q),G.triggerSyncEvent(Q);var ee=G.props.onMouseEnter;Wi(ee)&&ee(Q,W)}}),Li(G,"triggeredAfterMouseMove",function(W){var Z=G.getMouseInfo(W),Q=Z?Ir(Ir({},Z),{},{isTooltipActive:!0}):{isTooltipActive:!1};G.setState(Q),G.triggerSyncEvent(Q);var ee=G.props.onMouseMove;Wi(ee)&&ee(Q,W)}),Li(G,"handleItemMouseEnter",function(W){G.setState(function(){return{isTooltipActive:!0,activeItem:W,activePayload:W.tooltipPayload,activeCoordinate:W.tooltipPosition||{x:W.cx,y:W.cy}}})}),Li(G,"handleItemMouseLeave",function(){G.setState(function(){return{isTooltipActive:!1}})}),Li(G,"handleMouseMove",function(W){W.persist(),G.throttleTriggeredAfterMouseMove(W)}),Li(G,"handleMouseLeave",function(W){G.throttleTriggeredAfterMouseMove.cancel();var Z={isTooltipActive:!1};G.setState(Z),G.triggerSyncEvent(Z);var Q=G.props.onMouseLeave;Wi(Q)&&Q(Z,W)}),Li(G,"handleOuterEvent",function(W){var Z=tpt(W),Q=Xh(G.props,"".concat(Z));if(Z&&Wi(Q)){var ee,ie;/.*touch.*/i.test(Z)?ie=G.getMouseInfo(W.changedTouches[0]):ie=G.getMouseInfo(W),Q((ee=ie)!==null&&ee!==void 0?ee:{},W)}}),Li(G,"handleClick",function(W){var Z=G.getMouseInfo(W);if(Z){var Q=Ir(Ir({},Z),{},{isTooltipActive:!0});G.setState(Q),G.triggerSyncEvent(Q);var ee=G.props.onClick;Wi(ee)&&ee(Q,W)}}),Li(G,"handleMouseDown",function(W){var Z=G.props.onMouseDown;if(Wi(Z)){var Q=G.getMouseInfo(W);Z(Q,W)}}),Li(G,"handleMouseUp",function(W){var Z=G.props.onMouseUp;if(Wi(Z)){var Q=G.getMouseInfo(W);Z(Q,W)}}),Li(G,"handleTouchMove",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.throttleTriggeredAfterMouseMove(W.changedTouches[0])}),Li(G,"handleTouchStart",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.handleMouseDown(W.changedTouches[0])}),Li(G,"handleTouchEnd",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.handleMouseUp(W.changedTouches[0])}),Li(G,"handleDoubleClick",function(W){var Z=G.props.onDoubleClick;if(Wi(Z)){var Q=G.getMouseInfo(W);Z(Q,W)}}),Li(G,"handleContextMenu",function(W){var Z=G.props.onContextMenu;if(Wi(Z)){var Q=G.getMouseInfo(W);Z(Q,W)}}),Li(G,"triggerSyncEvent",function(W){G.props.syncId!==void 0&&NV.emit(RV,G.props.syncId,W,G.eventEmitterSymbol)}),Li(G,"applySyncEvent",function(W){var Z=G.props,Q=Z.layout,ee=Z.syncMethod,ie=G.state.updateId,oe=W.dataStartIndex,pe=W.dataEndIndex;if(W.dataStartIndex!==void 0||W.dataEndIndex!==void 0)G.setState(Ir({dataStartIndex:oe,dataEndIndex:pe},T({props:G.props,dataStartIndex:oe,dataEndIndex:pe,updateId:ie},G.state)));else if(W.activeTooltipIndex!==void 0){var Le=W.chartX,be=W.chartY,Re=W.activeTooltipIndex,Ie=G.state,Te=Ie.offset,ge=Ie.tooltipTicks;if(!Te)return;if(typeof ee=="function")Re=ee(ge,W);else if(ee==="value"){Re=-1;for(var $e=0;$e=0){var cr,ft;if(Le.dataKey&&!Le.allowDuplicatedCategory){var Kt=typeof Le.dataKey=="function"?Bt:"payload.".concat(Le.dataKey.toString());cr=BF($e,Kt,Re),ft=we&&ke&&BF(ke,Kt,Re)}else cr=$e==null?void 0:$e[be],ft=we&&ke&&ke[be];if(tt||nt){var ir=W.props.activeIndex!==void 0?W.props.activeIndex:be;return[N.cloneElement(W,Ir(Ir(Ir({},ee.props),Vt),{},{activeIndex:ir})),null,null]}if(!fs(cr))return[Ct].concat(VT(G.renderActivePoints({item:ee,activePoint:cr,basePoint:ft,childIndex:be,isRange:we})))}else{var Gr,tr=(Gr=G.getItemByXY(G.state.activeCoordinate))!==null&&Gr!==void 0?Gr:{graphicalItem:Ct},Qt=tr.graphicalItem,zt=Qt.item,Vr=zt===void 0?W:zt,Jr=Qt.childIndex,Fn=Ir(Ir(Ir({},ee.props),Vt),{},{activeIndex:Jr});return[N.cloneElement(Vr,Fn),null,null]}return we?[Ct,null,null]:[Ct,null]}),Li(G,"renderCustomized",function(W,Z,Q){return N.cloneElement(W,Ir(Ir({key:"recharts-customized-".concat(Q)},G.props),G.state))}),Li(G,"renderMap",{CartesianGrid:{handler:eM,once:!0},ReferenceArea:{handler:G.renderReferenceElement},ReferenceLine:{handler:eM},ReferenceDot:{handler:G.renderReferenceElement},XAxis:{handler:eM},YAxis:{handler:eM},Brush:{handler:G.renderBrush,once:!0},Bar:{handler:G.renderGraphicChild},Line:{handler:G.renderGraphicChild},Area:{handler:G.renderGraphicChild},Radar:{handler:G.renderGraphicChild},RadialBar:{handler:G.renderGraphicChild},Scatter:{handler:G.renderGraphicChild},Pie:{handler:G.renderGraphicChild},Funnel:{handler:G.renderGraphicChild},Tooltip:{handler:G.renderCursor,once:!0},PolarGrid:{handler:G.renderPolarGrid,once:!0},PolarAngleAxis:{handler:G.renderPolarAxis},PolarRadiusAxis:{handler:G.renderPolarAxis},Customized:{handler:G.renderCustomized}}),G.clipPathId="".concat((F=O.id)!==null&&F!==void 0?F:aN("recharts"),"-clip"),G.throttleTriggeredAfterMouseMove=bke(G.triggeredAfterMouseMove,($=O.throttleDelay)!==null&&$!==void 0?$:1e3/60),G.state={},G}return vMt(L,C),gMt(L,[{key:"componentDidMount",value:function(){var F,$;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(F=this.props.margin.left)!==null&&F!==void 0?F:0,top:($=this.props.margin.top)!==null&&$!==void 0?$:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var F=this.props,$=F.children,G=F.data,W=F.height,Z=F.layout,Q=Uh($,zm);if(Q){var ee=Q.props.defaultIndex;if(!(typeof ee!="number"||ee<0||ee>this.state.tooltipTicks.length-1)){var ie=this.state.tooltipTicks[ee]&&this.state.tooltipTicks[ee].value,oe=fH(this.state,G,ee,ie),pe=this.state.tooltipTicks[ee].coordinate,Le=(this.state.offset.top+W)/2,be=Z==="horizontal",Re=be?{x:pe,y:Le}:{y:pe,x:Le},Ie=this.state.formattedGraphicalItems.find(function(ge){var $e=ge.item;return $e.type.name==="Scatter"});Ie&&(Re=Ir(Ir({},Re),Ie.props.points[ee].tooltipPosition),oe=Ie.props.points[ee].tooltipPayload);var Te={activeTooltipIndex:ee,isTooltipActive:!0,activeLabel:ie,activePayload:oe,activeCoordinate:Re};this.setState(Te),this.renderCursor(Q),this.accessibilityManager.setIndex(ee)}}}},{key:"getSnapshotBeforeUpdate",value:function(F,$){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==$.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==F.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==F.margin){var G,W;this.accessibilityManager.setDetails({offset:{left:(G=this.props.margin.left)!==null&&G!==void 0?G:0,top:(W=this.props.margin.top)!==null&&W!==void 0?W:0}})}return null}},{key:"componentDidUpdate",value:function(F){$9([Uh(F.children,zm)],[Uh(this.props.children,zm)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var F=Uh(this.props.children,zm);if(F&&typeof F.props.shared=="boolean"){var $=F.props.shared?"axis":"item";return d.indexOf($)>=0?$:a}return a}},{key:"getMouseInfo",value:function(F){if(!this.container)return null;var $=this.container,G=$.getBoundingClientRect(),W=ISt(G),Z={chartX:Math.round(F.pageX-W.left),chartY:Math.round(F.pageY-W.top)},Q=G.width/$.offsetWidth||1,ee=this.inRange(Z.chartX,Z.chartY,Q);if(!ee)return null;var ie=this.state,oe=ie.xAxisMap,pe=ie.yAxisMap,Le=this.getTooltipEventType(),be=lme(this.state,this.props.data,this.props.layout,ee);if(Le!=="axis"&&oe&&pe){var Re=F_(oe).scale,Ie=F_(pe).scale,Te=Re&&Re.invert?Re.invert(Z.chartX):null,ge=Ie&&Ie.invert?Ie.invert(Z.chartY):null;return Ir(Ir({},Z),{},{xValue:Te,yValue:ge},be)}return be?Ir(Ir({},Z),be):null}},{key:"inRange",value:function(F,$){var G=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,W=this.props.layout,Z=F/G,Q=$/G;if(W==="horizontal"||W==="vertical"){var ee=this.state.offset,ie=Z>=ee.left&&Z<=ee.left+ee.width&&Q>=ee.top&&Q<=ee.top+ee.height;return ie?{x:Z,y:Q}:null}var oe=this.state,pe=oe.angleAxisMap,Le=oe.radiusAxisMap;if(pe&&Le){var be=F_(pe);return zhe({x:Z,y:Q},be)}return null}},{key:"parseEventsOfWrapper",value:function(){var F=this.props.children,$=this.getTooltipEventType(),G=Uh(F,zm),W={};G&&$==="axis"&&(G.props.trigger==="click"?W={onClick:this.handleClick}:W={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var Z=zF(this.props,this.handleOuterEvent);return Ir(Ir({},Z),W)}},{key:"addListener",value:function(){NV.on(RV,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){NV.removeListener(RV,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(F,$,G){for(var W=this.state.formattedGraphicalItems,Z=0,Q=W.length;Z");return t}const Wje=N.forwardRef(({id:t,className:e,children:r,config:n,...i},a)=>{const c=N.useId(),d=`chart-${t||c.replace(/:/g,"")}`;return s.jsx(Gje.Provider,{value:{config:n},children:s.jsxs("div",{"data-chart":d,ref:a,className:hr("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",e),...i,children:[s.jsx(BMt,{id:d,config:n}),s.jsx(u7,{children:r})]})})});Wje.displayName="Chart";const BMt=({id:t,config:e})=>{const r=Object.entries(e).filter(([n,i])=>i.theme||i.color);return r.length?s.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(FMt).map(([n,i])=>` ${i} [data-chart=${t}] { ${r.map(([a,c])=>{var p;const d=((p=c.theme)==null?void 0:p[n])||c.color;return d?` --color-${a}: ${d};`:null}).join(` `)} } `).join(` `)}}):null},Kje=N.forwardRef(({active:t,payload:e,className:r,indicator:n="dot",hideLabel:i=!1,hideIndicator:a=!1,label:c,labelFormatter:d,labelClassName:p,formatter:l,color:g,nameKey:v,labelKey:E},T)=>{const{config:j}=Hje(),P=N.useMemo(()=>{var G;if(i||!(e!=null&&e.length))return null;const[L]=e,O=`${E||L.dataKey||L.name||"value"}`,F=mH(j,L,O),$=!E&&typeof c=="string"?((G=j[c])==null?void 0:G.label)||c:F==null?void 0:F.label;return d?s.jsx("div",{className:hr("font-medium",p),children:d($,e)}):$?s.jsx("div",{className:hr("font-medium",p),children:$}):null},[c,d,e,i,p,j,E]);if(!t||!(e!=null&&e.length))return null;const C=e.length===1&&n!=="dot";return s.jsxs("div",{ref:T,className:hr("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",r),children:[C?null:P,s.jsx("div",{className:"grid gap-1.5",children:e.map((L,O)=>{const F=`${v||L.name||L.dataKey||"value"}`,$=mH(j,L,F),G=g||L.payload.fill||L.color;return s.jsx("div",{className:hr("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",n==="dot"&&"items-center"),children:l&&(L==null?void 0:L.value)!==void 0&&L.name?l(L.value,L.name,L,O,L.payload):s.jsxs(s.Fragment,{children:[$!=null&&$.icon?s.jsx($.icon,{}):!a&&s.jsx("div",{className:hr("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":n==="dot","w-1":n==="line","w-0 border-[1.5px] border-dashed bg-transparent":n==="dashed","my-0.5":C&&n==="dashed"}),style:{"--color-bg":G,"--color-border":G}}),s.jsxs("div",{className:hr("flex flex-1 justify-between leading-none",C?"items-end":"items-center"),children:[s.jsxs("div",{className:"grid gap-1.5",children:[C?P:null,s.jsx("span",{className:"text-muted-foreground",children:($==null?void 0:$.label)||L.name})]}),L.value&&s.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:L.value.toLocaleString()})]})]})},L.dataKey)})})]})});Kje.displayName="ChartTooltip";const zMt=N.forwardRef(({className:t,hideIcon:e=!1,payload:r,verticalAlign:n="bottom",nameKey:i},a)=>{const{config:c}=Hje();return r!=null&&r.length?s.jsx("div",{ref:a,className:hr("flex items-center justify-center gap-4",n==="top"?"pb-3":"pt-3",t),children:r.map(d=>{const p=`${i||d.dataKey||"value"}`,l=mH(c,d,p);return s.jsxs("div",{className:hr("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[l!=null&&l.icon&&!e?s.jsx(l.icon,{}):s.jsx("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:d.color}}),l==null?void 0:l.label]},d.value)})}):null});zMt.displayName="ChartLegend";function mH(t,e,r){if(typeof e!="object"||e===null)return;const n="payload"in e&&typeof e.payload=="object"&&e.payload!==null?e.payload:void 0;let i=r;return r in e&&typeof e[r]=="string"?i=e[r]:n&&r in n&&typeof n[r]=="string"&&(i=n[r]),i in t?t[i]:t[r]}const tM=["hsl(var(--primary))","hsl(var(--secondary))","hsl(210, 70%, 50%)","hsl(170, 60%, 45%)","hsl(280, 60%, 55%)","hsl(30, 70%, 50%)","hsl(340, 65%, 55%)","hsl(200, 65%, 50%)"];function Yje({stats:t,year:e}){const r=t.transactionsByMonth.some(i=>i.count>0),n=t.leadSourceBreakdown.length>0;return!r&&!n?s.jsx(wi,{children:s.jsx(Di,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):s.jsxs("div",{className:"grid gap-6",children:[r&&s.jsxs(wi,{className:"overflow-hidden",children:[s.jsx(Wh,{children:s.jsx(Kh,{className:"text-base",children:"Transactions by Month"})}),s.jsx(Di,{className:"overflow-hidden",children:s.jsx(Wje,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:s.jsx(u7,{width:"100%",height:"100%",children:s.jsxs(MMt,{data:t.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[s.jsx(jje,{strokeDasharray:"3 3",className:"stroke-muted"}),s.jsx(LB,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),s.jsx(DB,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),s.jsx(zm,{content:s.jsx(Kje,{})}),s.jsx(Lw,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),n&&s.jsxs(wi,{children:[s.jsx(Wh,{children:s.jsx(Kh,{className:"text-base",children:"Lead Sources"})}),s.jsxs(Di,{children:[s.jsx("div",{className:"h-[250px]",children:s.jsx(u7,{width:"100%",height:"100%",children:s.jsxs(OMt,{children:[s.jsx(hx,{data:t.leadSourceBreakdown,dataKey:"count",nameKey:"name",cx:"50%",cy:"50%",outerRadius:80,label:({name:i,percent:a})=>a>.05?`${i} (${(a*100).toFixed(0)}%)`:"",labelLine:!1,children:t.leadSourceBreakdown.map((i,a)=>s.jsx(cB,{fill:tM[a%tM.length]},`cell-${a}`))}),s.jsx(zm,{formatter:(i,a)=>[`${i} deals`,a]})]})})}),s.jsx("div",{className:"flex flex-wrap gap-2 mt-2 justify-center",children:t.leadSourceBreakdown.slice(0,6).map((i,a)=>s.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[s.jsx("div",{className:"w-3 h-3 rounded-sm",style:{backgroundColor:tM[a%tM.length]}}),s.jsx("span",{className:"text-muted-foreground",children:i.name})]},i.name))})]})]})]})}const $Mt=eA("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),Zje=N.forwardRef(({className:t,variant:e,...r},n)=>s.jsx("div",{ref:n,role:"alert",className:hr($Mt({variant:e}),t),...r}));Zje.displayName="Alert";const UMt=N.forwardRef(({className:t,...e},r)=>s.jsx("h5",{ref:r,className:hr("mb-1 font-medium leading-none tracking-tight",t),...e}));UMt.displayName="AlertTitle";const Xje=N.forwardRef(({className:t,...e},r)=>s.jsx("div",{ref:r,className:hr("text-sm [&_p]:leading-relaxed",t),...e}));Xje.displayName="AlertDescription";function VMt(t){if(!t||!t.trim())return null;const e=t.trim(),r=["yyyy-MM-dd","M/d/yyyy","MM/dd/yyyy","M-d-yyyy","MM-dd-yyyy","MM/dd/yy","M/d/yy"];for(const n of r)try{const i=het(e,n,new Date);if(ZG(i))return ds(i,"yyyy-MM-dd")}catch{}try{const n=new Date(e);if(ZG(n))return ds(n,"yyyy-MM-dd")}catch{}return null}const qMt=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function GMt({open:t,onOpenChange:e}){const[r,n]=N.useState([]),[i,a]=N.useState(!1),[c,d]=N.useState(0),{data:p}=BZ(),{data:l}=qZ(),g=zZ(),v=()=>{const L=qMt.join(","),O=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),F=`${L} ${O}`,$=new Blob([F],{type:"text/csv"}),G=URL.createObjectURL($),W=document.createElement("a");W.href=G,W.download="transaction-import-template.csv",W.click(),URL.revokeObjectURL(G)},E=L=>{const O=L.split(` `).filter($=>$.trim());if(O.length<2)return[];const F=O[0].split(",").map($=>$.trim().toLowerCase().replace(/['"]/g,""));return O.slice(1).map(($,G)=>{var Te,ge,$e,we;const W=[];let Z="",Q=!1;for(const ke of $)ke==='"'?Q=!Q:ke===","&&!Q?(W.push(Z.trim()),Z=""):Z+=ke;W.push(Z.trim());const ee=ke=>{var He;const Ae=F.indexOf(ke);return Ae>=0?(He=W[Ae])==null?void 0:He.replace(/^["']|["']$/g,"").trim():""},ie=(Te=ee("transaction_type"))==null?void 0:Te.toLowerCase(),oe=(ge=ee("sale_price"))==null?void 0:ge.replace(/[$,]/g,""),pe=($e=ee("commission_amount"))==null?void 0:$e.replace(/[$,]/g,""),Le=(we=ee("is_win"))==null?void 0:we.toLowerCase(),be=ee("close_date"),Re=VMt(be);let Ie;return ee("property_address")?["buyer","seller"].includes(ie)?Re?(!oe||isNaN(Number(oe)))&&(Ie="Invalid sale price"):Ie=`Invalid date format: "${be}" - use MM/DD/YYYY or YYYY-MM-DD`:Ie='Transaction type must be "buyer" or "seller"':Ie="Missing property address",{property_address:ee("property_address"),city:ee("city"),state:ee("state"),zip:ee("zip"),transaction_type:ie==="seller"?"seller":"buyer",close_date:Re||"",sale_price:Number(oe)||0,commission_amount:pe?Number(pe):null,lead_source_name:ee("lead_source"),client_type_name:ee("client_type"),is_win:["yes","true","1"].includes(Le),notes:ee("notes"),error:Ie}})},T=L=>{var $;const O=($=L.target.files)==null?void 0:$[0];if(!O)return;const F=new FileReader;F.onload=G=>{var Q;const W=(Q=G.target)==null?void 0:Q.result,Z=E(W);n(Z)},F.readAsText(O)},j=async()=>{const L=r.filter($=>!$.error);if(L.length===0){lr.error("No valid transactions to import");return}a(!0),d(0);let O=0,F=0;for(let $=0;$Q.name.toLowerCase()===G.lead_source_name.toLowerCase()),Z=l==null?void 0:l.find(Q=>Q.name.toLowerCase()===G.client_type_name.toLowerCase());await g.mutateAsync({property_address:G.property_address,city:G.city||null,state:G.state||null,zip:G.zip||null,transaction_type:G.transaction_type,close_date:G.close_date,sale_price:G.sale_price,commission_amount:G.commission_amount,lead_source_id:(W==null?void 0:W.id)||null,client_type_id:(Z==null?void 0:Z.id)||null,contact_id:null,notes:G.notes||null,is_win:G.is_win}),O++}catch(W){F++,console.error("Failed to import transaction:",W)}d(Math.round(($+1)/L.length*100))}a(!1),O>0&&lr.success(`Imported ${O} transaction${O>1?"s":""}`),F>0&&lr.error(`Failed to import ${F} transaction${F>1?"s":""}`),n([]),e(!1)},P=r.filter(L=>!L.error).length,C=r.filter(L=>L.error).length;return s.jsx(gl,{open:t,onOpenChange:e,children:s.jsxs(Jo,{className:"max-w-2xl max-h-[90vh]",children:[s.jsxs(Bc,{children:[s.jsx(pc,{children:"Import Transactions"}),s.jsx(sf,{children:"Upload a CSV file with your past transactions"})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-muted/50",children:[s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Download Template"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Get a CSV template with the correct format"})]}),s.jsxs(Jt,{variant:"outline",onClick:v,children:[s.jsx($u,{className:"h-4 w-4 mr-2"}),"Template"]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(sn,{htmlFor:"csv-file",children:"Upload CSV File"}),s.jsx(hn,{id:"csv-file",type:"file",accept:".csv",onChange:T})]}),r.length>0&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Js,{variant:"outline",children:[r.length," rows found"]}),P>0&&s.jsxs(Js,{className:"bg-green-500 text-white",children:[s.jsx(ql,{className:"h-3 w-3 mr-1"}),P," valid"]}),C>0&&s.jsxs(Js,{variant:"destructive",children:[s.jsx(nve,{className:"h-3 w-3 mr-1"}),C," errors"]})]}),s.jsx(Eg,{className:"h-[200px] border rounded-lg",children:s.jsxs("div",{className:"p-2 space-y-2",children:[r.slice(0,10).map((L,O)=>s.jsxs("div",{className:`p-2 rounded text-sm ${L.error?"bg-destructive/10":"bg-muted/50"}`,children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"font-medium",children:L.property_address||"(no address)"}),s.jsx(Js,{variant:L.transaction_type==="buyer"?"default":"secondary",children:L.transaction_type})]}),s.jsxs("div",{className:"text-muted-foreground",children:[L.close_date," • $",L.sale_price.toLocaleString()]}),L.error&&s.jsx(Zje,{variant:"destructive",className:"mt-1 py-1",children:s.jsx(Xje,{className:"text-xs",children:L.error})})]},O)),r.length>10&&s.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",r.length-10," more"]})]})}),i&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:s.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${c}%`}})}),s.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",c,"%"]})]})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[s.jsx(Jt,{variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsxs(Jt,{onClick:j,disabled:P===0||i,children:[s.jsx(Lq,{className:"h-4 w-4 mr-2"}),"Import ",P," Transaction",P!==1?"s":""]})]})]})]})})}const HMt=Gv({transactions_goal:cj().min(0).optional(),volume_goal:cj().min(0).optional(),gci_goal:cj().min(0).optional()});function WMt({open:t,onOpenChange:e,year:r,existingGoals:n}){const i=Out(),{data:a}=z5(),c=(a==null?void 0:a.show_commission)??!0,d=lY({resolver:uY(HMt),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});N.useEffect(()=>{n?d.reset({transactions_goal:n.transactions_goal??void 0,volume_goal:n.volume_goal?Number(n.volume_goal):void 0,gci_goal:n.gci_goal?Number(n.gci_goal):void 0}):d.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[n,d,t]);const p=async l=>{await i.mutateAsync({year:r,transactions_goal:l.transactions_goal??null,volume_goal:l.volume_goal??null,gci_goal:c?l.gci_goal??null:null}),e(!1)};return s.jsx(gl,{open:t,onOpenChange:e,children:s.jsxs(Jo,{className:"max-w-md",children:[s.jsxs(Bc,{children:[s.jsxs(pc,{children:[r," Goals"]}),s.jsx(sf,{children:"Set your annual targets to track your progress throughout the year."})]}),s.jsx(EY,{...d,children:s.jsxs("form",{onSubmit:d.handleSubmit(p),className:"space-y-4",children:[s.jsx(Cc,{control:d.control,name:"transactions_goal",render:({field:l})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Transactions Goal"}),s.jsx(oc,{children:s.jsx(hn,{type:"number",placeholder:"e.g., 24",...l,value:l.value??"",onChange:g=>l.onChange(g.target.value?Number(g.target.value):void 0)})}),s.jsx(rO,{children:"Total number of deals you want to close"}),s.jsx(Ym,{})]})}),s.jsx(Cc,{control:d.control,name:"volume_goal",render:({field:l})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"Volume Goal ($)"}),s.jsx(oc,{children:s.jsx(hn,{type:"number",placeholder:"e.g., 5000000",...l,value:l.value??"",onChange:g=>l.onChange(g.target.value?Number(g.target.value):void 0)})}),s.jsx(rO,{children:"Total sales volume you want to achieve"}),s.jsx(Ym,{})]})}),c&&s.jsx(Cc,{control:d.control,name:"gci_goal",render:({field:l})=>s.jsxs(sc,{children:[s.jsx(ac,{children:"GCI Goal ($)"}),s.jsx(oc,{children:s.jsx(hn,{type:"number",placeholder:"e.g., 150000",...l,value:l.value??"",onChange:g=>l.onChange(g.target.value?Number(g.target.value):void 0)})}),s.jsx(rO,{children:"Gross commission income target"}),s.jsx(Ym,{})]})}),s.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[s.jsx(Jt,{type:"button",variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsx(Jt,{type:"submit",disabled:i.isPending,children:"Save Goals"})]})]})})]})})}function Qje({transactions:t,isLoading:e}){const r=N.useRef(null),n=N.useRef(null),i=N.useRef([]),a=N.useRef(null),{isAdmin:c}=_i(),[d,p]=N.useState(""),[l,g]=N.useState(!0),[v,E]=N.useState(0),[T,j]=N.useState(!1),P=t.filter(L=>L.latitude!=null&&L.longitude!=null),C=t.filter(L=>L.latitude==null||L.longitude==null);return N.useEffect(()=>{(async()=>{g(!0);try{const{data:O}=await Be.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();O!=null&&O.value&&p(O.value)}catch(O){console.error("Error fetching mapbox token:",O)}g(!1)})()},[]),N.useEffect(()=>{if(!d||C.length===0||T)return;(async()=>{var F;j(!0);let O=0;for(const $ of C){const G=[$.property_address,$.city,$.state,$.zip].filter(Boolean).join(", ");if(G)try{const Z=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(G)}.json?access_token=${d}&limit=1`)).json();if((F=Z.features)!=null&&F[0]){const[Q,ee]=Z.features[0].center;await Be.from("scorecard_transactions").update({latitude:ee,longitude:Q}).eq("id",$.id),$.latitude=ee,$.longitude=Q,O++}}catch(W){console.error("Geocode error:",W)}}E(O),j(!1)})()},[d,t]),N.useEffect(()=>{if(!r.current||!d||n.current)return;Rf.accessToken=d;const L=t.filter($=>$.latitude!=null&&$.longitude!=null);let O=[-98.5795,39.8283],F=4;if(L.length>0){const $=L.reduce((W,Z)=>W+Z.longitude,0)/L.length,G=L.reduce((W,Z)=>W+Z.latitude,0)/L.length;O=[$,G],F=L.length===1?12:10}return n.current=new Rf.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:F,center:O}),n.current.addControl(new Rf.NavigationControl,"top-right"),()=>{var $;($=n.current)==null||$.remove(),n.current=null}},[d]),N.useEffect(()=>{var O;if(!n.current||!d)return;i.current.forEach(F=>F.remove()),i.current=[],(O=a.current)==null||O.remove();const L=t.filter(F=>F.latitude!=null&&F.longitude!=null);if(L.forEach(F=>{var ee;const $=F.transaction_type==="buyer",G=$?"#3B82F6":"#10B981",W=document.createElement("div");W.className="cursor-pointer",W.innerHTML=`
${$?'':''}
`;const Z=new Rf.Popup({offset:25,closeButton:!0}).setHTML(`
${F.property_address}
${F.city?`
${F.city}${F.state?", "+F.state:""} ${F.zip||""}
`:""}
${$?"Buyer":"Seller"} $${Number(F.sale_price).toLocaleString()}
Closed: ${_T(F.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(ee=F.lead_source)!=null&&ee.name?" · "+F.lead_source.name:""}
${F.contact?`
Client: ${F.contact.first_name} ${F.contact.last_name||""}
`:""}
`),Q=new Rf.Marker(W).setLngLat([F.longitude,F.latitude]).setPopup(Z).addTo(n.current);i.current.push(Q)}),L.length>1){const F=new Rf.LngLatBounds;L.forEach($=>F.extend([$.longitude,$.latitude])),n.current.fitBounds(F,{padding:60,maxZoom:13})}else L.length===1&&n.current.flyTo({center:[L[0].longitude,L[0].latitude],zoom:12})},[t,d,T]),l||e?s.jsx(wi,{children:s.jsx(Di,{className:"flex items-center justify-center h-[50vh]",children:s.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):d?t.length===0?s.jsx(wi,{children:s.jsxs(Di,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[s.jsx(Va,{className:"h-12 w-12 text-muted-foreground"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold",children:"No Transactions Yet"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Add transactions to see them plotted on the map."})]})]})}):s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#3B82F6"}}),s.jsx("span",{children:"Buyer"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#10B981"}}),s.jsx("span",{children:"Seller"})]}),s.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[P.length," of ",t.length," mapped",T&&" · Geocoding..."]})]}),s.jsx("div",{ref:r,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):s.jsx(wi,{children:s.jsxs(Di,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[s.jsx(nve,{className:"h-12 w-12 text-muted-foreground"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:c?"Set up your Mapbox token in the Popby Map to enable maps across the platform.":"The map feature has not been configured yet. Please contact your administrator."})]})]})})}const Jje=()=>{const{data:t}=_A();return jr({queryKey:["team-scorecard-members",t==null?void 0:t.teamId],queryFn:async()=>{const{data:e,error:r}=await Be.from("team_members").select("user_id").eq("team_id",t.teamId);if(r)throw r;const n=e.map(c=>c.user_id),{data:i,error:a}=await Be.from("profiles").select("id, name, email, avatar_url").in("id",n);if(a)throw a;return i||[]},enabled:!!(t!=null&&t.teamId)&&(t==null?void 0:t.role)==="team_leader"})},KMt=t=>{const{data:e}=_A(),{data:r}=Jje();return jr({queryKey:["team-scorecard-transactions",e==null?void 0:e.teamId,t],queryFn:async()=>{const n=r.map(d=>d.id);let i=Be.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",n).order("close_date",{ascending:!1});t&&(i=i.gte("close_date",`${t}-01-01`).lte("close_date",`${t}-12-31`));const{data:a,error:c}=await i;if(c)throw c;return a},enabled:!!r&&r.length>0})};function YMt(t,e){const r=e.filter(a=>a.owner_user_id===t.id),n=r.reduce((a,c)=>a+Number(c.sale_price),0),i=r.reduce((a,c)=>a+(Number(c.commission_amount)||0),0);return{member:t,totalTransactions:r.length,buyerCount:r.filter(a=>a.transaction_type==="buyer").length,sellerCount:r.filter(a=>a.transaction_type==="seller").length,totalVolume:n,averagePrice:r.length>0?n/r.length:0,totalGCI:i}}function ZMt(t,e){return t?t.split(" ").map(r=>r[0]).join("").toUpperCase().slice(0,2):e[0].toUpperCase()}function XMt({year:t}){var E;const{data:e,isLoading:r}=Jje(),{data:n,isLoading:i}=KMt(t),a=qa(),c=r||i,{aggregate:d,memberStats:p,topPerformer:l,agentNameMap:g,teamChartStats:v}=N.useMemo(()=>{if(!e||!n)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const T=e.map(ie=>YMt(ie,n));T.sort((ie,oe)=>oe.totalVolume-ie.totalVolume);const j={};e.forEach(ie=>{j[ie.id]=ie.name||ie.email});const P=n.length,C=n.reduce((ie,oe)=>ie+Number(oe.sale_price),0),L=n.reduce((ie,oe)=>ie+(Number(oe.commission_amount)||0),0),O=n.filter(ie=>ie.transaction_type==="buyer").length,F=n.filter(ie=>ie.transaction_type==="seller").length,$={};n.forEach(ie=>{var pe;const oe=((pe=ie.lead_source)==null?void 0:pe.name)||"Unknown";$[oe]=($[oe]||0)+1});const G=Object.entries($).sort((ie,oe)=>oe[1]-ie[1])[0],W={};n.forEach(ie=>{const oe=_T(ie.close_date).toLocaleString("default",{month:"short"});W[oe]=(W[oe]||0)+1});const Q=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(ie=>({month:ie,count:W[ie]||0})),ee=Object.entries($).map(([ie,oe])=>({name:ie,count:oe})).sort((ie,oe)=>oe.count-ie.count);return{aggregate:{totalTxns:P,buyerCount:O,sellerCount:F,totalVolume:C,avgPrice:P>0?C/P:0,totalGCI:L,topSource:G?{name:G[0],count:G[1]}:null,memberCount:e.length},memberStats:T,topPerformer:T[0]||null,agentNameMap:j,teamChartStats:{transactionsByMonth:Q,leadSourceBreakdown:ee}}},[e,n]);return c?s.jsxs("div",{className:"space-y-6",children:[s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(T=>s.jsx(Mc,{className:"h-24"},T))}),s.jsx(Mc,{className:"h-64"})]}):!d||p.length===0?s.jsx(wi,{className:"py-12",children:s.jsxs(Di,{className:"text-center space-y-2",children:[s.jsx(Dc,{className:"h-10 w-10 mx-auto text-muted-foreground"}),s.jsx("h3",{className:"text-lg font-semibold",children:"No Team Data"}),s.jsxs("p",{className:"text-muted-foreground",children:["No scorecard transactions found for your team members in ",t,"."]})]})}):s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Dc,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Members"})]}),s.jsx("p",{className:"text-2xl font-bold",children:d.memberCount})]})}),s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Do,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Team Transactions"})]}),s.jsx("p",{className:"text-2xl font-bold",children:d.totalTxns}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[d.buyerCount,"B / ",d.sellerCount,"S"]})]})}),s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Cy,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Team Volume"})]}),s.jsx("p",{className:"text-2xl font-bold",children:Ho(d.totalVolume,!0)})]})}),s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(iA,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),s.jsx("p",{className:"text-2xl font-bold",children:Ho(d.avgPrice,!0)})]})}),s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Cy,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Team GCI"})]}),s.jsx("p",{className:"text-2xl font-bold",children:Ho(d.totalGCI,!0)})]})}),s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(_E,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),s.jsx("p",{className:"text-lg font-bold truncate",children:((E=d.topSource)==null?void 0:E.name)||"-"}),d.topSource&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:[d.topSource.count," deals"]})]})})]}),l&&l.totalTransactions>0&&s.jsx(wi,{className:"border-primary/30 bg-primary/5",children:s.jsxs(Di,{className:"pt-4 flex items-center gap-4",children:[s.jsx("div",{className:"flex items-center justify-center h-10 w-10 rounded-full bg-primary/10",children:s.jsx(sF,{className:"h-5 w-5 text-primary"})}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("p",{className:"text-sm font-medium text-muted-foreground",children:["Top Performer — ",t]}),s.jsx("p",{className:"text-lg font-bold",children:l.member.name||l.member.email})]}),s.jsxs("div",{className:"text-right",children:[s.jsxs("p",{className:"text-sm text-muted-foreground",children:[l.totalTransactions," deals"]}),s.jsx("p",{className:"font-semibold",children:Ho(l.totalVolume,!0)})]})]})}),s.jsxs(wi,{children:[s.jsx(Wh,{children:s.jsx(Kh,{className:"text-lg",children:"Member Performance"})}),s.jsx(Di,{children:s.jsx("div",{className:"overflow-x-auto",children:s.jsxs($Z,{children:[s.jsx(UZ,{children:s.jsxs(xC,{children:[s.jsx(Cu,{children:"Agent"}),s.jsx(Cu,{className:"text-center",children:"Transactions"}),s.jsx(Cu,{className:"text-center",children:"B / S"}),s.jsx(Cu,{className:"text-right",children:"Volume"}),s.jsx(Cu,{className:"text-right",children:"Avg Price"}),s.jsx(Cu,{className:"text-right",children:"GCI"}),s.jsx(Cu,{className:"text-right"})]})}),s.jsx(VZ,{children:p.map((T,j)=>s.jsxs(xC,{children:[s.jsx(Pu,{children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("div",{className:"relative",children:[j===0&&T.totalTransactions>0&&s.jsx(sF,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),s.jsxs(tf,{className:"h-8 w-8",children:[s.jsx(rf,{src:T.member.avatar_url||void 0}),s.jsx(nf,{className:"text-xs",children:ZMt(T.member.name,T.member.email)})]})]}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium text-sm",children:T.member.name||T.member.email}),T.member.name&&s.jsx("p",{className:"text-xs text-muted-foreground",children:T.member.email})]})]})}),s.jsx(Pu,{className:"text-center font-semibold",children:T.totalTransactions}),s.jsxs(Pu,{className:"text-center text-sm",children:[T.buyerCount," / ",T.sellerCount]}),s.jsx(Pu,{className:"text-right font-medium",children:Ho(T.totalVolume,!0)}),s.jsx(Pu,{className:"text-right text-sm",children:Ho(T.averagePrice,!0)}),s.jsx(Pu,{className:"text-right font-medium",children:Ho(T.totalGCI,!0)}),s.jsx(Pu,{className:"text-right",children:s.jsx(Jt,{variant:"ghost",size:"sm",onClick:()=>a(`/mission-control/scorecard/${T.member.id}`),children:s.jsx(E4,{className:"h-4 w-4"})})})]},T.member.id))})]})})})]}),s.jsxs(XY,{defaultValue:"transactions",className:"space-y-4",children:[s.jsxs(k5,{children:[s.jsxs(Dy,{value:"transactions",children:[s.jsx(Nq,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),s.jsxs(Dy,{value:"charts",children:[s.jsx(Gj,{className:"h-4 w-4 mr-1"}),"Charts"]}),s.jsxs(Dy,{value:"map",children:[s.jsx(Va,{className:"h-4 w-4 mr-1"}),"Map"]})]}),s.jsx(uv,{value:"transactions",children:s.jsx(t2e,{transactions:n||[],showCommission:!0,isLoading:i,agentNameMap:g,readOnly:!0})}),s.jsx(uv,{value:"charts",children:v&&s.jsx(Yje,{stats:v,year:t})}),s.jsx(uv,{value:"map",children:s.jsx(Qje,{transactions:n||[],isLoading:i})})]})]})}const xO=new Date().getFullYear(),dme=Array.from({length:10},(t,e)=>xO-e),rM="all";function QMt(){var oe;const[t,e]=N.useState(xO),r=t===null?rM:String(t),n=pe=>e(pe===rM?null:Number(pe)),[i,a]=N.useState(!1),[c,d]=N.useState(!1),[p,l]=N.useState(!1),[g,v]=N.useState(!1),[E,T]=N.useState("my"),{data:j}=_A(),P=(j==null?void 0:j.role)==="team_leader",{data:C,isLoading:L}=VAe(t??void 0),{yearStats:O,lifetimeStats:F,showCommission:$}=But(t??void 0),{data:G,isLoading:W}=Mut(t??xO),{data:Z}=z5(),Q=Fut(),ee=()=>{if(!C||C.length===0)return;const pe=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...$?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],Le=C.map(ge=>{var $e,we;return[ge.property_address,ge.city||"",ge.state||"",ge.zip||"",ge.transaction_type,ge.close_date,ge.sale_price,...$?[ge.commission_amount||""]:[],(($e=ge.lead_source)==null?void 0:$e.name)||"",((we=ge.client_type)==null?void 0:we.name)||"",ge.contact?`${ge.contact.first_name} ${ge.contact.last_name||""}`.trim():"",ge.is_win?"Yes":"No",ge.notes||""]}),be=[pe,...Le].map(ge=>ge.map($e=>`"${String($e).replace(/"/g,'""')}"`).join(",")).join(` `),Re=new Blob([be],{type:"text/csv"}),Ie=URL.createObjectURL(Re),Te=document.createElement("a");Te.href=Ie,Te.download=t===null?"transactions-all.csv":`transactions-${t}.csv`,Te.click(),URL.revokeObjectURL(Ie)},ie=!C||C.length===0;return s.jsxs(gT,{title:"Scorecard",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),P&&s.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[s.jsx(Jt,{variant:E==="my"?"default":"ghost",size:"sm",onClick:()=>T("my"),className:"h-8",children:"My Scorecard"}),s.jsxs(Jt,{variant:E==="team"?"default":"ghost",size:"sm",onClick:()=>T("team"),className:"h-8",children:[s.jsx(Dc,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),E==="team"&&P?s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Team Performance"}),s.jsx("p",{className:"text-muted-foreground text-sm",children:"Aggregate stats and member comparison"})]}),s.jsxs(Xo,{value:r,onValueChange:n,children:[s.jsx(Mo,{className:"w-[140px]",children:s.jsx(Qo,{})}),s.jsxs(Oo,{children:[s.jsx($n,{value:rM,children:"All Years"}),dme.map(pe=>s.jsx($n,{value:String(pe),children:pe},pe))]})]})]}),s.jsx(XMt,{year:t??void 0})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),s.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(Xo,{value:r,onValueChange:n,children:[s.jsx(Mo,{className:"w-[140px]",children:s.jsx(Qo,{})}),s.jsxs(Oo,{children:[s.jsx($n,{value:rM,children:"All Years"}),dme.map(pe=>s.jsx($n,{value:String(pe),children:pe},pe))]})]}),s.jsx(Jt,{variant:"outline",size:"icon",onClick:()=>v(!g),children:s.jsx(XW,{className:"h-4 w-4"})})]})]}),g&&s.jsxs(wi,{children:[s.jsx(Wh,{className:"pb-3",children:s.jsx(Kh,{className:"text-lg",children:"Settings"})}),s.jsx(Di,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsx(sn,{children:"Show Commission"}),s.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),s.jsx(TA,{checked:(Z==null?void 0:Z.show_commission)??!0,onCheckedChange:pe=>Q.mutate({show_commission:pe})})]})})]}),ie&&!L?s.jsx(wi,{className:"py-12",children:s.jsxs(Di,{className:"text-center space-y-4",children:[s.jsx("div",{className:"w-16 h-16 mx-auto rounded-full bg-primary/10 flex items-center justify-center",children:s.jsx(Gj,{className:"h-8 w-8 text-primary"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold",children:"Start Tracking Your Success"}),s.jsx("p",{className:"text-muted-foreground max-w-md mx-auto mt-1",children:"Add your past transactions to see your performance metrics, track your goals, and celebrate your wins."})]}),s.jsxs("div",{className:"flex flex-wrap justify-center gap-2 pt-2",children:[s.jsxs(Jt,{onClick:()=>a(!0),children:[s.jsx(Py,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),s.jsxs(Jt,{variant:"outline",onClick:()=>d(!0),children:[s.jsx(Lq,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]}),s.jsxs("div",{className:"pt-4 border-t mt-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Need help formatting your data?"}),s.jsx(Jt,{variant:"link",className:"h-auto p-0",asChild:!0,children:s.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[s.jsx($u,{className:"h-4 w-4 mr-2"}),"Download CSV Template"]})})]})]})}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs(Jt,{onClick:()=>a(!0),children:[s.jsx(Py,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),s.jsxs(Jt,{variant:"outline",onClick:()=>l(!0),children:[s.jsx(eK,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),s.jsxs(Jt,{variant:"outline",onClick:()=>d(!0),children:[s.jsx(Lq,{className:"h-4 w-4 mr-2"}),"Import"]}),s.jsxs(Jt,{variant:"outline",onClick:ee,disabled:ie,children:[s.jsx($u,{className:"h-4 w-4 mr-2"}),"Export"]}),s.jsx(Jt,{variant:"ghost",size:"sm",asChild:!0,children:s.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[s.jsx($u,{className:"h-4 w-4 mr-2"}),"CSV Template"]})})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Do,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),s.jsx("p",{className:"text-2xl font-bold",children:O.totalTransactions}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[F.totalTransactions," lifetime"]})]})}),s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Dc,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),s.jsxs("p",{className:"text-2xl font-bold",children:[O.buyerCount,"/",O.sellerCount]}),s.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Cy,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),s.jsx("p",{className:"text-2xl font-bold",children:Ho(O.totalVolume,!0)}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ho(F.totalVolume,!0)," lifetime"]})]})}),s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(iA,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),s.jsx("p",{className:"text-2xl font-bold",children:Ho(O.averagePrice,!0)})]})}),s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(_E,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),s.jsx("p",{className:"text-lg font-bold truncate",children:((oe=O.topLeadSource)==null?void 0:oe.name)||"-"}),O.topLeadSource&&s.jsxs("p",{className:"text-xs text-muted-foreground",children:[O.topLeadSource.count," deals"]})]})}),$&&s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[s.jsx(Cy,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),s.jsx("p",{className:"text-2xl font-bold",children:Ho(O.totalCommission,!0)}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ho(F.totalCommission,!0)," lifetime"]})]})}),$&&O.totalNetToAgent>0&&O.totalNetToAgent!==O.totalCommission&&s.jsx(wi,{children:s.jsxs(Di,{className:"pt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-teal-600 dark:text-teal-400 mb-1",children:[s.jsx(Cy,{className:"h-4 w-4"}),s.jsx("span",{className:"text-xs font-medium",children:"Net to Agent"})]}),s.jsx("p",{className:"text-2xl font-bold text-teal-600 dark:text-teal-400",children:Ho(O.totalNetToAgent,!0)}),s.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ho(F.totalNetToAgent,!0)," lifetime"]})]})})]}),t!==null&&G&&s.jsx(ddt,{goals:G,stats:O,year:t,showCommission:$}),s.jsxs(XY,{defaultValue:"transactions",className:"space-y-4",children:[s.jsxs(k5,{children:[s.jsx(Dy,{value:"transactions",children:"Transactions"}),s.jsx(Dy,{value:"charts",children:"Charts"}),s.jsxs(Dy,{value:"map",children:[s.jsx(Va,{className:"h-4 w-4 mr-1"}),"Map"]})]}),s.jsx(uv,{value:"transactions",children:s.jsx(t2e,{transactions:C||[],showCommission:$,isLoading:L})}),s.jsx(uv,{value:"charts",children:s.jsx(Yje,{stats:O,year:t??void 0})}),s.jsx(uv,{value:"map",children:s.jsx(Qje,{transactions:C||[],isLoading:L})})]})]})]})]}),s.jsx(e2e,{open:i,onOpenChange:a}),s.jsx(GMt,{open:c,onOpenChange:d}),s.jsx(WMt,{open:p,onOpenChange:l,year:t??xO,existingGoals:G})]})}function JMt(){const t=qs();return jr({queryKey:["deal-tasks",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Be.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name), stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e},enabled:!!t})}function sXt(t){const e=qs();return jr({queryKey:["deal-tasks","deal",t,e],queryFn:async()=>{if(!e||!t)return[];const{data:r,error:n}=await Be.from("deal_tasks").select(` *, stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",e).eq("deal_id",t).order("sort_order",{ascending:!0});if(n)throw n;return r},enabled:!!e&&!!t})}function eOt(){const t=qs(),e=Ur();return zr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Be.from("deal_tasks").insert({owner_user_id:t,title:r.title,description:r.description||null,deal_id:r.deal_id||null,contact_id:r.contact_id||null,stage_id:r.stage_id||null,priority:r.priority||"medium",status:r.status||"todo",due_date:r.due_date||null,sort_order:r.sort_order||0}).select().single();if(i)throw i;return n},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-tasks"]})}})}function tOt(){const t=Ur();return zr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Be.from("deal_tasks").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-tasks"]}),r.status==="done"&&jw("task_completed")}})}function rOt(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("deal_tasks").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function nQ(){const t=Ur();return zr({mutationFn:async({id:e,status:r})=>{const{data:n,error:i}=await Be.from("deal_tasks").update({status:r,completed_at:r==="done"?new Date().toISOString():null}).eq("id",e).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-tasks"]}),r.status==="done"&&jw("task_completed")}})}function aXt(){const t=Ur();return zr({mutationFn:async e=>{if(e.length===0)return;const{error:r}=await Be.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",e);if(r)throw r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-tasks"]}),r.length>0&&jw("task_completed")}})}function nOt(t){const e=qs();return jr({queryKey:["deal-task-templates",e,t],queryFn:async()=>{if(!e)return[];let r=Be.from("deal_task_templates").select("*").eq("owner_user_id",e).order("sort_order",{ascending:!0});t&&(r=r.eq("stage_id",t));const{data:n,error:i}=await r;if(i)throw i;return n},enabled:!!e})}function iOt(){const t=qs(),e=Ur();return zr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Be.from("deal_task_templates").insert({owner_user_id:t,stage_id:r.stage_id,title:r.title,description:r.description||null,priority:r.priority||"medium",default_due_offset_days:r.default_due_offset_days||null,sort_order:r.sort_order||0}).select().single();if(i)throw i;return n},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-task-templates"]})}})}function sOt(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("deal_task_templates").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function oXt(){const t=qs(),e=Ur();return zr({mutationFn:async({dealId:r,stageId:n})=>{if(!t)throw new Error("Not authenticated");const{data:i,error:a}=await Be.from("deal_task_templates").select("*").eq("owner_user_id",t).eq("stage_id",n).order("sort_order");if(a)throw a;if(!i||i.length===0)return[];const{data:c}=await Be.from("deal_tasks").select("title, stage_id").eq("deal_id",r).eq("stage_id",n),d=new Set((c||[]).map(v=>v.title)),p=i.filter(v=>!d.has(v.title)).map((v,E)=>({owner_user_id:t,deal_id:r,stage_id:n,title:v.title,description:v.description,priority:v.priority,due_date:v.default_due_offset_days?new Date(Date.now()+v.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:E,status:"todo"}));if(p.length===0)return[];const{data:l,error:g}=await Be.from("deal_tasks").insert(p).select();if(g)throw g;return l},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-tasks"]})}})}function vI(t){const e=t.expected_commission,r=Number(t.bonus_amount)||0;if(!e)return r>0?r:null;if((t.commission_calc_method||"standard")==="referral_first"){let a=e;t.referral_fee_pct&&(a-=e*(t.referral_fee_pct/100));let c=a;return t.brokerage_split_pct&&(c-=a*(t.brokerage_split_pct/100)),t.team_split_pct&&(c-=e*(t.team_split_pct/100)),t.franchise_fee_pct&&(c-=e*(t.franchise_fee_pct/100)),t.transaction_fee&&(c-=t.transaction_fee),Math.max(0,c)+r}let i=e;return t.brokerage_split_pct&&(i-=e*(t.brokerage_split_pct/100)),t.team_split_pct&&(i-=e*(t.team_split_pct/100)),t.franchise_fee_pct&&(i-=e*(t.franchise_fee_pct/100)),t.referral_fee_pct&&(i-=e*(t.referral_fee_pct/100)),t.transaction_fee&&(i-=t.transaction_fee),Math.max(0,i)+r}function aOt(){const t=qs();return jr({queryKey:["deal-pipeline-stages",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Be.from("deal_pipeline_stages").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e},enabled:!!t})}function lXt(){const t=qs(),e=Ur();return zr({mutationFn:async()=>{if(!t)throw new Error("Not authenticated");const{error:r}=await Be.rpc("initialize_deal_pipeline_stages",{p_user_id:t});if(r)throw r},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function oOt(){const t=qs();return jr({queryKey:["deal-pipeline-deals",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Be.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at) `).eq("owner_user_id",t).order("updated_at",{ascending:!1});if(r)throw r;return e},enabled:!!t})}function cXt(){const t=qs(),e=Ur();return zr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Be.from("deal_pipeline").insert({deal_name:r.deal_name,deal_type:r.deal_type,stage_id:r.stage_id||null,contact_id:r.contact_id||null,listing_id:r.listing_id||null,property_address:r.property_address||null,city:r.city||null,state:r.state||null,zip_code:r.zip_code||null,expected_price:r.expected_price||null,expected_commission:r.expected_commission||null,commission_percentage:r.commission_percentage||3,target_close_date:r.target_close_date||null,contract_date:r.contract_date||null,listing_date:r.listing_date||null,priority:r.priority||"medium",probability:r.probability||50,notes:r.notes||null,owner_user_id:t}).select().single();if(i)throw i;return await Be.from("deal_activities").insert([{deal_id:n.id,activity_type:"system",title:"Deal created",description:`Deal "${r.deal_name}" was created`}]),n},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-pipeline-deals"]}),e.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function uXt(){const t=Ur();return zr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Be.from("deal_pipeline").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function dXt(){const t=Ur();return zr({mutationFn:async({dealId:e,stageId:r,stageName:n})=>{const{data:i}=await Be.from("deal_pipeline_stages").select("default_probability").eq("id",r).maybeSingle(),a={stage_id:r};typeof(i==null?void 0:i.default_probability)=="number"&&(a.probability=i.default_probability);const{data:c,error:d}=await Be.from("deal_pipeline").update(a).eq("id",e).select().single();if(d)throw d;return await Be.from("deal_activities").insert({deal_id:e,activity_type:"stage_change",title:`Moved to ${n}`,metadata:{new_stage_id:r,new_stage_name:n}}),c},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-activities"]})}})}function hXt(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("deal_pipeline").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function fXt(t){return jr({queryKey:["deal-activities",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("deal_activities").select("*").eq("deal_id",t).order("created_at",{ascending:!1});if(r)throw r;return e},enabled:!!t})}function mXt(){const t=Ur();return zr({mutationFn:async e=>{const{data:r,error:n}=await Be.from("deal_activities").insert([{deal_id:e.deal_id,activity_type:e.activity_type,title:e.title,description:e.description||null}]).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-activities",r.deal_id]})}})}function pXt(t){return jr({queryKey:["deal-checklist",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("deal_checklist_items").select("*").eq("deal_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e},enabled:!!t})}function gXt(){const t=Ur();return zr({mutationFn:async({id:e,is_completed:r,deal_id:n})=>{const{data:i,error:a}=await Be.from("deal_checklist_items").update({is_completed:r,completed_at:r?new Date().toISOString():null}).eq("id",e).select().single();if(a)throw a;return i},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-checklist",r.deal_id]})}})}function yXt(){const t=Ur();return zr({mutationFn:async e=>{const{data:r,error:n}=await Be.from("deal_checklist_items").insert([{deal_id:e.deal_id,title:e.title,description:e.description||null,due_date:e.due_date||null,sort_order:e.sort_order||0}]).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-checklist",r.deal_id]})}})}function xXt(){const t=qs();return jr({queryKey:["deal-pipeline-stats",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Be.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",t);if(r)throw r;const n=(e==null?void 0:e.filter(d=>{var p,l,g;return!((p=d.deal_pipeline_stages)!=null&&p.is_won_stage)&&!((l=d.deal_pipeline_stages)!=null&&l.is_lost_stage)&&((g=d.deal_pipeline_stages)==null?void 0:g.name)!=="Cancelled"}))||[],i=(e==null?void 0:e.filter(d=>{var p;return(p=d.deal_pipeline_stages)==null?void 0:p.is_won_stage}))||[],a=new Date().getFullYear(),c=i.filter(d=>{const p=d.actual_close_date;return p?new Date(p).getFullYear()===a:!0});return{totalDeals:(e==null?void 0:e.length)||0,activeDeals:n.length,wonDeals:i.length,pipelineValue:n.reduce((d,p)=>d+(p.expected_price||0),0),expectedCommission:n.reduce((d,p)=>d+(p.expected_commission||0)+(p.bonus_amount||0),0),expectedNetToAgent:n.reduce((d,p)=>d+(vI(p)||0),0),wonValue:i.reduce((d,p)=>d+(p.expected_price||0),0),weightedGCI:n.reduce((d,p)=>{const l=(p.probability??50)/100;return d+((p.expected_commission||0)+(p.bonus_amount||0))*l},0),weightedNet:n.reduce((d,p)=>{const l=(p.probability??50)/100;return d+(vI(p)||0)*l},0),ytdWonDeals:c.length,ytdWonGCI:c.reduce((d,p)=>d+(p.expected_commission||0)+(p.bonus_amount||0),0),ytdWonNet:c.reduce((d,p)=>d+(vI(p)||0),0),projectedAnnualNet:c.reduce((d,p)=>d+(vI(p)||0),0)+n.reduce((d,p)=>{const l=(p.probability??50)/100;return d+(vI(p)||0)*l},0)}},enabled:!!t})}function _Xt(t){const e=qs();return jr({queryKey:["deal-by-listing",t,e],queryFn:async()=>{if(!e||!t)return null;const{data:r,error:n}=await Be.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",e).eq("listing_id",t).maybeSingle();if(n)throw n;return r},enabled:!!e&&!!t})}function vXt(){const t=Ur();return zr({mutationFn:async({dealId:e,listingId:r})=>{const{data:n,error:i}=await Be.from("deal_pipeline").update({listing_id:r}).eq("id",e).select().single();if(i)throw i;return await Be.from("deal_activities").insert({deal_id:e,activity_type:"system",title:"Linked to Listing Exchange",description:"This deal is now synced with Listing Exchange",metadata:{listing_id:r}}),n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-by-listing",r.listingId]})}})}function bXt(){const t=Ur();return zr({mutationFn:async({dealId:e,listingId:r})=>{const{data:n,error:i}=await Be.from("deal_pipeline").update({listing_id:null}).eq("id",e).select().single();if(i)throw i;return{data:n,listingId:r}},onSuccess:e=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-by-listing",e.listingId]})}})}var zi=function(){return zi=Object.assign||function(e){for(var r,n=1,i=arguments.length;n1&&(p||!l),v=e>1&&(l||!p),E=function(){n&&a(n)},T=function(){i&&a(i)};return s.jsx(zOt,{displayMonth:t.displayMonth,hideNext:g,hidePrevious:v,nextMonth:i,previousMonth:n,onPreviousClick:E,onNextClick:T})}function $Ot(t){var e,r=Ao(),n=r.classNames,i=r.disableNavigation,a=r.styles,c=r.captionLayout,d=r.components,p=(e=d==null?void 0:d.CaptionLabel)!==null&&e!==void 0?e:rCe,l;return i?l=s.jsx(p,{id:t.id,displayMonth:t.displayMonth}):c==="dropdown"?l=s.jsx(hme,{displayMonth:t.displayMonth,id:t.id}):c==="dropdown-buttons"?l=s.jsxs(s.Fragment,{children:[s.jsx(hme,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),s.jsx(fme,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id})]}):l=s.jsxs(s.Fragment,{children:[s.jsx(p,{id:t.id,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),s.jsx(fme,{displayMonth:t.displayMonth,id:t.id})]}),s.jsx("div",{className:n.caption,style:a.caption,children:l})}function UOt(t){var e=Ao(),r=e.footer,n=e.styles,i=e.classNames.tfoot;return r?s.jsx("tfoot",{className:i,style:n.tfoot,children:s.jsx("tr",{children:s.jsx("td",{colSpan:8,children:r})})}):s.jsx(s.Fragment,{})}function VOt(t,e,r){for(var n=r?Ky(new Date):ld(new Date,{locale:t,weekStartsOn:e}),i=[],a=0;a<7;a++){var c=tu(n,a);i.push(c)}return i}function qOt(){var t=Ao(),e=t.classNames,r=t.styles,n=t.showWeekNumber,i=t.locale,a=t.weekStartsOn,c=t.ISOWeek,d=t.formatters.formatWeekdayName,p=t.labels.labelWeekday,l=VOt(i,a,c);return s.jsxs("tr",{style:r.head_row,className:e.head_row,children:[n&&s.jsx("td",{style:r.head_cell,className:e.head_cell}),l.map(function(g,v){return s.jsx("th",{scope:"col",className:e.head_cell,style:r.head_cell,"aria-label":p(g,{locale:i}),children:d(g,{locale:i})},v)})]})}function GOt(){var t,e=Ao(),r=e.classNames,n=e.styles,i=e.components,a=(t=i==null?void 0:i.HeadRow)!==null&&t!==void 0?t:qOt;return s.jsx("thead",{style:n.head,className:r.head,children:s.jsx(a,{})})}function HOt(t){var e=Ao(),r=e.locale,n=e.formatters.formatDay;return s.jsx(s.Fragment,{children:n(t.date,{locale:r})})}var iQ=N.createContext(void 0);function WOt(t){if(!hN(t.initialProps)){var e={selected:void 0,modifiers:{disabled:[]}};return s.jsx(iQ.Provider,{value:e,children:t.children})}return s.jsx(KOt,{initialProps:t.initialProps,children:t.children})}function KOt(t){var e=t.initialProps,r=t.children,n=e.selected,i=e.min,a=e.max,c=function(l,g,v){var E,T;(E=e.onDayClick)===null||E===void 0||E.call(e,l,g,v);var j=!!(g.selected&&i&&(n==null?void 0:n.length)===i);if(!j){var P=!!(!g.selected&&a&&(n==null?void 0:n.length)===a);if(!P){var C=n?eCe([],n):[];if(g.selected){var L=C.findIndex(function(O){return Fu(l,O)});C.splice(L,1)}else C.push(l);(T=e.onSelect)===null||T===void 0||T.call(e,C,l,g,v)}}},d={disabled:[]};n&&d.disabled.push(function(l){var g=a&&n.length>a-1,v=n.some(function(E){return Fu(E,l)});return!!(g&&!v)});var p={selected:n,onDayClick:c,modifiers:d};return s.jsx(iQ.Provider,{value:p,children:r})}function sQ(){var t=N.useContext(iQ);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function YOt(t,e){var r=e||{},n=r.from,i=r.to;return n&&i?Fu(i,t)&&Fu(n,t)?void 0:Fu(i,t)?{from:i,to:void 0}:Fu(n,t)?void 0:lC(n,t)?{from:t,to:i}:{from:n,to:t}:i?lC(t,i)?{from:i,to:t}:{from:t,to:i}:n?OY(t,n)?{from:t,to:n}:{from:n,to:t}:{from:t,to:void 0}}var aQ=N.createContext(void 0);function ZOt(t){if(!fN(t.initialProps)){var e={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return s.jsx(aQ.Provider,{value:e,children:t.children})}return s.jsx(XOt,{initialProps:t.initialProps,children:t.children})}function XOt(t){var e=t.initialProps,r=t.children,n=e.selected,i=n||{},a=i.from,c=i.to,d=e.min,p=e.max,l=function(T,j,P){var C,L;(C=e.onDayClick)===null||C===void 0||C.call(e,T,j,P);var O=YOt(T,n);(L=e.onSelect)===null||L===void 0||L.call(e,O,T,j,P)},g={range_start:[],range_end:[],range_middle:[],disabled:[]};if(a?(g.range_start=[a],c?(g.range_end=[c],Fu(a,c)||(g.range_middle=[{after:a,before:c}])):g.range_end=[a]):c&&(g.range_start=[c],g.range_end=[c]),d&&(a&&!c&&g.disabled.push({after:TU(a,d-1),before:tu(a,d-1)}),a&&c&&g.disabled.push({after:a,before:tu(a,d-1)}),!a&&c&&g.disabled.push({after:TU(c,d-1),before:tu(c,d-1)})),p){if(a&&!c&&(g.disabled.push({before:tu(a,-p+1)}),g.disabled.push({after:tu(a,p-1)})),a&&c){var v=Zm(c,a)+1,E=p-v;g.disabled.push({before:TU(a,E)}),g.disabled.push({after:tu(c,E)})}!a&&c&&(g.disabled.push({before:tu(c,-p+1)}),g.disabled.push({after:tu(c,p-1)}))}return s.jsx(aQ.Provider,{value:{selected:n,onDayClick:l,modifiers:g},children:r})}function oQ(){var t=N.useContext(aQ);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function _O(t){return Array.isArray(t)?eCe([],t):t!==void 0?[t]:[]}function QOt(t){var e={};return Object.entries(t).forEach(function(r){var n=r[0],i=r[1];e[n]=_O(i)}),e}var op;(function(t){t.Outside="outside",t.Disabled="disabled",t.Selected="selected",t.Hidden="hidden",t.Today="today",t.RangeStart="range_start",t.RangeEnd="range_end",t.RangeMiddle="range_middle"})(op||(op={}));var JOt=op.Selected,ly=op.Disabled,eFt=op.Hidden,tFt=op.Today,DV=op.RangeEnd,MV=op.RangeMiddle,OV=op.RangeStart,rFt=op.Outside;function nFt(t,e,r){var n,i=(n={},n[JOt]=_O(t.selected),n[ly]=_O(t.disabled),n[eFt]=_O(t.hidden),n[tFt]=[t.today],n[DV]=[],n[MV]=[],n[OV]=[],n[rFt]=[],n);return t.fromDate&&i[ly].push({before:t.fromDate}),t.toDate&&i[ly].push({after:t.toDate}),hN(t)?i[ly]=i[ly].concat(e.modifiers[ly]):fN(t)&&(i[ly]=i[ly].concat(r.modifiers[ly]),i[OV]=r.modifiers[OV],i[MV]=r.modifiers[MV],i[DV]=r.modifiers[DV]),i}var sCe=N.createContext(void 0);function iFt(t){var e=Ao(),r=sQ(),n=oQ(),i=nFt(e,r,n),a=QOt(e.modifiers),c=zi(zi({},i),a);return s.jsx(sCe.Provider,{value:c,children:t.children})}function aCe(){var t=N.useContext(sCe);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function sFt(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function aFt(t){return!!(t&&typeof t=="object"&&"from"in t)}function oFt(t){return!!(t&&typeof t=="object"&&"after"in t)}function lFt(t){return!!(t&&typeof t=="object"&&"before"in t)}function cFt(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function uFt(t,e){var r,n=e.from,i=e.to;if(n&&i){var a=Zm(i,n)<0;a&&(r=[i,n],n=r[0],i=r[1]);var c=Zm(t,n)>=0&&Zm(i,t)>=0;return c}return i?Fu(i,t):n?Fu(n,t):!1}function dFt(t){return RY(t)}function hFt(t){return Array.isArray(t)&&t.every(RY)}function fFt(t,e){return e.some(function(r){if(typeof r=="boolean")return r;if(dFt(r))return Fu(t,r);if(hFt(r))return r.includes(t);if(aFt(r))return uFt(t,r);if(cFt(r))return r.dayOfWeek.includes(t.getDay());if(sFt(r)){var n=Zm(r.before,t),i=Zm(r.after,t),a=n>0,c=i<0,d=lC(r.before,r.after);return d?c&&a:a||c}return oFt(r)?Zm(t,r.after)>0:lFt(r)?Zm(r.before,t)>0:typeof r=="function"?r(t):!1})}function lQ(t,e,r){var n=Object.keys(e).reduce(function(a,c){var d=e[c];return fFt(t,d)&&a.push(c),a},[]),i={};return n.forEach(function(a){return i[a]=!0}),r&&!w5(t,r)&&(i.outside=!0),i}function mFt(t,e){for(var r=Fd(t[0]),n=KP(t[t.length-1]),i,a,c=r;c<=n;){var d=lQ(c,e),p=!d.disabled&&!d.hidden;if(!p){c=tu(c,1);continue}if(d.selected)return c;d.today&&!a&&(a=c),i||(i=c),c=tu(c,1)}return a||i}var pFt=365;function oCe(t,e){var r=e.moveBy,n=e.direction,i=e.context,a=e.modifiers,c=e.retry,d=c===void 0?{count:0,lastFocused:t}:c,p=i.weekStartsOn,l=i.fromDate,g=i.toDate,v=i.locale,E={day:tu,week:YG,month:af,year:lQe,startOfWeek:function(C){return i.ISOWeek?Ky(C):ld(C,{locale:v,weekStartsOn:p})},endOfWeek:function(C){return i.ISOWeek?xSe(C):v5(C,{locale:v,weekStartsOn:p})}},T=E[r](t,n==="after"?1:-1);n==="before"&&l?T=cQe([l,T]):n==="after"&&g&&(T=uQe([g,T]));var j=!0;if(a){var P=lQ(T,a);j=!P.disabled&&!P.hidden}return j?T:d.count>pFt?d.lastFocused:oCe(T,{moveBy:r,direction:n,context:i,modifiers:a,retry:zi(zi({},d),{count:d.count+1})})}var lCe=N.createContext(void 0);function gFt(t){var e=mN(),r=aCe(),n=N.useState(),i=n[0],a=n[1],c=N.useState(),d=c[0],p=c[1],l=mFt(e.displayMonths,r),g=i??(d&&e.isDateDisplayed(d))?d:l,v=function(){p(i),a(void 0)},E=function(C){a(C)},T=Ao(),j=function(C,L){if(i){var O=oCe(i,{moveBy:C,direction:L,context:T,modifiers:r});Fu(i,O)||(e.goToDate(O,i),E(O))}},P={focusedDay:i,focusTarget:g,blur:v,focus:E,focusDayAfter:function(){return j("day","after")},focusDayBefore:function(){return j("day","before")},focusWeekAfter:function(){return j("week","after")},focusWeekBefore:function(){return j("week","before")},focusMonthBefore:function(){return j("month","before")},focusMonthAfter:function(){return j("month","after")},focusYearBefore:function(){return j("year","before")},focusYearAfter:function(){return j("year","after")},focusStartOfWeek:function(){return j("startOfWeek","before")},focusEndOfWeek:function(){return j("endOfWeek","after")}};return s.jsx(lCe.Provider,{value:P,children:t.children})}function cQ(){var t=N.useContext(lCe);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function yFt(t,e){var r=aCe(),n=lQ(t,r,e);return n}var uQ=N.createContext(void 0);function xFt(t){if(!OB(t.initialProps)){var e={selected:void 0};return s.jsx(uQ.Provider,{value:e,children:t.children})}return s.jsx(_Ft,{initialProps:t.initialProps,children:t.children})}function _Ft(t){var e=t.initialProps,r=t.children,n=function(a,c,d){var p,l,g;if((p=e.onDayClick)===null||p===void 0||p.call(e,a,c,d),c.selected&&!e.required){(l=e.onSelect)===null||l===void 0||l.call(e,void 0,a,c,d);return}(g=e.onSelect)===null||g===void 0||g.call(e,a,a,c,d)},i={selected:e.selected,onDayClick:n};return s.jsx(uQ.Provider,{value:i,children:r})}function cCe(){var t=N.useContext(uQ);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function vFt(t,e){var r=Ao(),n=cCe(),i=sQ(),a=oQ(),c=cQ(),d=c.focusDayAfter,p=c.focusDayBefore,l=c.focusWeekAfter,g=c.focusWeekBefore,v=c.blur,E=c.focus,T=c.focusMonthBefore,j=c.focusMonthAfter,P=c.focusYearBefore,C=c.focusYearAfter,L=c.focusStartOfWeek,O=c.focusEndOfWeek,F=function(Te){var ge,$e,we,ke;OB(r)?(ge=n.onDayClick)===null||ge===void 0||ge.call(n,t,e,Te):hN(r)?($e=i.onDayClick)===null||$e===void 0||$e.call(i,t,e,Te):fN(r)?(we=a.onDayClick)===null||we===void 0||we.call(a,t,e,Te):(ke=r.onDayClick)===null||ke===void 0||ke.call(r,t,e,Te)},$=function(Te){var ge;E(t),(ge=r.onDayFocus)===null||ge===void 0||ge.call(r,t,e,Te)},G=function(Te){var ge;v(),(ge=r.onDayBlur)===null||ge===void 0||ge.call(r,t,e,Te)},W=function(Te){var ge;(ge=r.onDayMouseEnter)===null||ge===void 0||ge.call(r,t,e,Te)},Z=function(Te){var ge;(ge=r.onDayMouseLeave)===null||ge===void 0||ge.call(r,t,e,Te)},Q=function(Te){var ge;(ge=r.onDayPointerEnter)===null||ge===void 0||ge.call(r,t,e,Te)},ee=function(Te){var ge;(ge=r.onDayPointerLeave)===null||ge===void 0||ge.call(r,t,e,Te)},ie=function(Te){var ge;(ge=r.onDayTouchCancel)===null||ge===void 0||ge.call(r,t,e,Te)},oe=function(Te){var ge;(ge=r.onDayTouchEnd)===null||ge===void 0||ge.call(r,t,e,Te)},pe=function(Te){var ge;(ge=r.onDayTouchMove)===null||ge===void 0||ge.call(r,t,e,Te)},Le=function(Te){var ge;(ge=r.onDayTouchStart)===null||ge===void 0||ge.call(r,t,e,Te)},be=function(Te){var ge;(ge=r.onDayKeyUp)===null||ge===void 0||ge.call(r,t,e,Te)},Re=function(Te){var ge;switch(Te.key){case"ArrowLeft":Te.preventDefault(),Te.stopPropagation(),r.dir==="rtl"?d():p();break;case"ArrowRight":Te.preventDefault(),Te.stopPropagation(),r.dir==="rtl"?p():d();break;case"ArrowDown":Te.preventDefault(),Te.stopPropagation(),l();break;case"ArrowUp":Te.preventDefault(),Te.stopPropagation(),g();break;case"PageUp":Te.preventDefault(),Te.stopPropagation(),Te.shiftKey?P():T();break;case"PageDown":Te.preventDefault(),Te.stopPropagation(),Te.shiftKey?C():j();break;case"Home":Te.preventDefault(),Te.stopPropagation(),L();break;case"End":Te.preventDefault(),Te.stopPropagation(),O();break}(ge=r.onDayKeyDown)===null||ge===void 0||ge.call(r,t,e,Te)},Ie={onClick:F,onFocus:$,onBlur:G,onKeyDown:Re,onKeyUp:be,onMouseEnter:W,onMouseLeave:Z,onPointerEnter:Q,onPointerLeave:ee,onTouchCancel:ie,onTouchEnd:oe,onTouchMove:pe,onTouchStart:Le};return Ie}function bFt(){var t=Ao(),e=cCe(),r=sQ(),n=oQ(),i=OB(t)?e.selected:hN(t)?r.selected:fN(t)?n.selected:void 0;return i}function wFt(t){return Object.values(op).includes(t)}function SFt(t,e){var r=[t.classNames.day];return Object.keys(e).forEach(function(n){var i=t.modifiersClassNames[n];if(i)r.push(i);else if(wFt(n)){var a=t.classNames["day_".concat(n)];a&&r.push(a)}}),r}function EFt(t,e){var r=zi({},t.styles.day);return Object.keys(e).forEach(function(n){var i;r=zi(zi({},r),(i=t.modifiersStyles)===null||i===void 0?void 0:i[n])}),r}function TFt(t,e,r){var n,i,a,c=Ao(),d=cQ(),p=yFt(t,e),l=vFt(t,p),g=bFt(),v=!!(c.onDayClick||c.mode!=="default");N.useEffect(function(){var W;p.outside||d.focusedDay&&v&&Fu(d.focusedDay,t)&&((W=r.current)===null||W===void 0||W.focus())},[d.focusedDay,t,r,v,p.outside]);var E=SFt(c,p).join(" "),T=EFt(c,p),j=!!(p.outside&&!c.showOutsideDays||p.hidden),P=(a=(i=c.components)===null||i===void 0?void 0:i.DayContent)!==null&&a!==void 0?a:HOt,C=s.jsx(P,{date:t,displayMonth:e,activeModifiers:p}),L={style:T,className:E,children:C,role:"gridcell"},O=d.focusTarget&&Fu(d.focusTarget,t)&&!p.outside,F=d.focusedDay&&Fu(d.focusedDay,t),$=zi(zi(zi({},L),(n={disabled:p.disabled,role:"gridcell"},n["aria-selected"]=p.selected,n.tabIndex=F||O?0:-1,n)),l),G={isButton:v,isHidden:j,activeModifiers:p,selectedDays:g,buttonProps:$,divProps:L};return G}function AFt(t){var e=N.useRef(null),r=TFt(t.date,t.displayMonth,e);return r.isHidden?s.jsx("div",{role:"gridcell"}):r.isButton?s.jsx($3,zi({name:"day",ref:e},r.buttonProps)):s.jsx("div",zi({},r.divProps))}function kFt(t){var e=t.number,r=t.dates,n=Ao(),i=n.onWeekNumberClick,a=n.styles,c=n.classNames,d=n.locale,p=n.labels.labelWeekNumber,l=n.formatters.formatWeekNumber,g=l(Number(e),{locale:d});if(!i)return s.jsx("span",{className:c.weeknumber,style:a.weeknumber,children:g});var v=p(Number(e),{locale:d}),E=function(T){i(e,r,T)};return s.jsx($3,{name:"week-number","aria-label":v,className:c.weeknumber,style:a.weeknumber,onClick:E,children:g})}function IFt(t){var e,r,n=Ao(),i=n.styles,a=n.classNames,c=n.showWeekNumber,d=n.components,p=(e=d==null?void 0:d.Day)!==null&&e!==void 0?e:AFt,l=(r=d==null?void 0:d.WeekNumber)!==null&&r!==void 0?r:kFt,g;return c&&(g=s.jsx("td",{className:a.cell,style:i.cell,children:s.jsx(l,{number:t.weekNumber,dates:t.dates})})),s.jsxs("tr",{className:a.row,style:i.row,children:[g,t.dates.map(function(v){return s.jsx("td",{className:a.cell,style:i.cell,role:"presentation",children:s.jsx(p,{displayMonth:t.displayMonth,date:v})},pJe(v))})]})}function mme(t,e,r){for(var n=r!=null&&r.ISOWeek?xSe(e):v5(e,r),i=r!=null&&r.ISOWeek?Ky(t):ld(t,r),a=Zm(n,i),c=[],d=0;d<=a;d++)c.push(tu(i,d));var p=c.reduce(function(l,g){var v=r!=null&&r.ISOWeek?LY(g):MY(g,r),E=l.find(function(T){return T.weekNumber===v});return E?(E.dates.push(g),l):(l.push({weekNumber:v,dates:[g]}),l)},[]);return p}function jFt(t,e){var r=mme(Fd(t),KP(t),e);if(e!=null&&e.useFixedWeeks){var n=yJe(t,e);if(n<6){var i=r[r.length-1],a=i.dates[i.dates.length-1],c=YG(a,6-n),d=mme(YG(a,1),c,e);r.push.apply(r,d)}}return r}function CFt(t){var e,r,n,i=Ao(),a=i.locale,c=i.classNames,d=i.styles,p=i.hideHead,l=i.fixedWeeks,g=i.components,v=i.weekStartsOn,E=i.firstWeekContainsDate,T=i.ISOWeek,j=jFt(t.displayMonth,{useFixedWeeks:!!l,ISOWeek:T,locale:a,weekStartsOn:v,firstWeekContainsDate:E}),P=(e=g==null?void 0:g.Head)!==null&&e!==void 0?e:GOt,C=(r=g==null?void 0:g.Row)!==null&&r!==void 0?r:IFt,L=(n=g==null?void 0:g.Footer)!==null&&n!==void 0?n:UOt;return s.jsxs("table",{id:t.id,className:c.table,style:d.table,role:"grid","aria-labelledby":t["aria-labelledby"],children:[!p&&s.jsx(P,{}),s.jsx("tbody",{className:c.tbody,style:d.tbody,children:j.map(function(O){return s.jsx(C,{displayMonth:t.displayMonth,dates:O.dates,weekNumber:O.weekNumber},O.weekNumber)})}),s.jsx(L,{displayMonth:t.displayMonth})]})}function PFt(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var NFt=PFt()?N.useLayoutEffect:N.useEffect,FV=!1,RFt=0;function pme(){return"react-day-picker-".concat(++RFt)}function LFt(t){var e,r=t??(FV?pme():null),n=N.useState(r),i=n[0],a=n[1];return NFt(function(){i===null&&a(pme())},[]),N.useEffect(function(){FV===!1&&(FV=!0)},[]),(e=t??i)!==null&&e!==void 0?e:void 0}function DFt(t){var e,r,n=Ao(),i=n.dir,a=n.classNames,c=n.styles,d=n.components,p=mN().displayMonths,l=LFt(n.id?"".concat(n.id,"-").concat(t.displayIndex):void 0),g=n.id?"".concat(n.id,"-grid-").concat(t.displayIndex):void 0,v=[a.month],E=c.month,T=t.displayIndex===0,j=t.displayIndex===p.length-1,P=!T&&!j;i==="rtl"&&(e=[T,j],j=e[0],T=e[1]),T&&(v.push(a.caption_start),E=zi(zi({},E),c.caption_start)),j&&(v.push(a.caption_end),E=zi(zi({},E),c.caption_end)),P&&(v.push(a.caption_between),E=zi(zi({},E),c.caption_between));var C=(r=d==null?void 0:d.Caption)!==null&&r!==void 0?r:$Ot;return s.jsxs("div",{className:v.join(" "),style:E,children:[s.jsx(C,{id:l,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),s.jsx(CFt,{id:g,"aria-labelledby":l,displayMonth:t.displayMonth})]},t.displayIndex)}function MFt(t){var e=Ao(),r=e.classNames,n=e.styles;return s.jsx("div",{className:r.months,style:n.months,children:t.children})}function OFt(t){var e,r,n=t.initialProps,i=Ao(),a=cQ(),c=mN(),d=N.useState(!1),p=d[0],l=d[1];N.useEffect(function(){i.initialFocus&&a.focusTarget&&(p||(a.focus(a.focusTarget),l(!0)))},[i.initialFocus,p,a.focus,a.focusTarget,a]);var g=[i.classNames.root,i.className];i.numberOfMonths>1&&g.push(i.classNames.multiple_months),i.showWeekNumber&&g.push(i.classNames.with_weeknumber);var v=zi(zi({},i.styles.root),i.style),E=Object.keys(n).filter(function(j){return j.startsWith("data-")}).reduce(function(j,P){var C;return zi(zi({},j),(C={},C[P]=n[P],C))},{}),T=(r=(e=n.components)===null||e===void 0?void 0:e.Months)!==null&&r!==void 0?r:MFt;return s.jsx("div",zi({className:g.join(" "),style:v,dir:i.dir,id:i.id,nonce:n.nonce,title:n.title,lang:n.lang},E,{children:s.jsx(T,{children:c.displayMonths.map(function(j,P){return s.jsx(DFt,{displayIndex:P,displayMonth:j},P)})})}))}function FFt(t){var e=t.children,r=lOt(t,["children"]);return s.jsx(kOt,{initialProps:r,children:s.jsx(OOt,{children:s.jsx(xFt,{initialProps:r,children:s.jsx(WOt,{initialProps:r,children:s.jsx(ZOt,{initialProps:r,children:s.jsx(iFt,{children:s.jsx(gFt,{children:e})})})})})})})}function BFt(t){return s.jsx(FFt,zi({},t,{children:s.jsx(OFt,{initialProps:t})}))}function uCe({className:t,classNames:e,showOutsideDays:r=!0,captionLayout:n,...i}){const a=n==="dropdown"?"dropdown-buttons":n;return s.jsx(BFt,{showOutsideDays:r,captionLayout:a,className:hr("p-3",t),classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center min-h-8",caption_label:"text-sm font-medium",caption_dropdowns:"flex gap-2 items-center justify-center px-9 [&_[aria-hidden=true]]:hidden",vhidden:"sr-only",nav:"space-x-1 flex items-center",nav_button:hr(Yj({variant:"outline"}),"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-y-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:"h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",day:hr(Yj({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",dropdown:"h-8 rounded-md border border-input bg-background px-2 py-1 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",...e},components:{IconLeft:({...c})=>s.jsx(bg,{className:"h-4 w-4"}),IconRight:({...c})=>s.jsx(uf,{className:"h-4 w-4"})},...i})}uCe.displayName="Calendar";function dCe({open:t,onOpenChange:e,editTask:r,defaultDealId:n,defaultStageId:i}){var Le;const a=eOt(),c=tOt(),{data:d}=oOt(),p=qs(),{data:l}=jr({queryKey:["contacts-for-tasks",p],queryFn:async()=>{if(!p)return[];const be=[],Re=1e3;for(let Ie=0;;Ie+=Re){const{data:Te,error:ge}=await Be.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",p).order("first_name").order("id").range(Ie,Ie+Re-1);if(ge)throw ge;if(be.push(...Te||[]),!Te||Te.length{r?(v(r.title),T(r.description||""),P(r.deal_id||"none"),L(r.contact_id||"none"),F(r.priority),G(r.status),Z(r.due_date?jd(r.due_date):void 0)):(v(""),T(""),P(n||"none"),L("none"),F("medium"),G("todo"),Z(void 0))},[r,t,n]);const pe=async()=>{if(!g.trim()){lr.error("Task title is required");return}try{const be={title:g.trim(),description:E.trim()||null,deal_id:j==="none"?null:j,contact_id:C==="none"?null:C,stage_id:i||null,priority:O,status:$,due_date:W?ds(W,"yyyy-MM-dd"):null};r?(await c.mutateAsync({id:r.id,...be}),lr.success("Task updated")):(await a.mutateAsync(be),jw("task_created"),lr.success("Task created")),e(!1)}catch{lr.error("Failed to save task")}};return s.jsx(gl,{open:t,onOpenChange:e,children:s.jsxs(Jo,{className:"sm:max-w-[480px]",children:[s.jsx(Bc,{children:s.jsx(pc,{children:r?"Edit Task":"New Task"})}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx(sn,{children:"Title *"}),s.jsx(hn,{value:g,onChange:be=>v(be.target.value),placeholder:"e.g., Send inspection report"})]}),s.jsxs("div",{children:[s.jsx(sn,{children:"Description"}),s.jsx(df,{value:E,onChange:be=>T(be.target.value),placeholder:"Optional details...",rows:2})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx(sn,{children:"Priority"}),s.jsxs(Xo,{value:O,onValueChange:be=>F(be),children:[s.jsx(Mo,{children:s.jsx(Qo,{})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"low",children:"🟢 Low"}),s.jsx($n,{value:"medium",children:"🟡 Medium"}),s.jsx($n,{value:"high",children:"🟠 High"}),s.jsx($n,{value:"urgent",children:"🔴 Urgent"})]})]})]}),s.jsxs("div",{children:[s.jsx(sn,{children:"Status"}),s.jsxs(Xo,{value:$,onValueChange:be=>G(be),children:[s.jsx(Mo,{children:s.jsx(Qo,{})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"todo",children:"To Do"}),s.jsx($n,{value:"in_progress",children:"In Progress"}),s.jsx($n,{value:"done",children:"Done"})]})]})]})]}),s.jsxs("div",{children:[s.jsx(sn,{children:"Due Date"}),s.jsxs(fO,{children:[s.jsx(mO,{asChild:!0,children:s.jsxs(Jt,{variant:"outline",className:hr("w-full justify-start text-left font-normal",!W&&"text-muted-foreground"),children:[s.jsx(Cl,{className:"mr-2 h-4 w-4"}),W?ds(W,"PPP"):"Pick a date"]})}),s.jsx(gj,{className:"w-auto p-0",align:"start",children:s.jsx(uCe,{mode:"single",selected:W,onSelect:Z,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),s.jsxs("div",{children:[s.jsx(sn,{children:"Link to Deal"}),s.jsxs(fO,{open:Q,onOpenChange:ee,children:[s.jsx(mO,{asChild:!0,children:s.jsxs(Jt,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[s.jsxs("span",{className:"flex items-center gap-2 truncate",children:[s.jsx(jl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),j!=="none"?((Le=d==null?void 0:d.find(be=>be.id===j))==null?void 0:Le.deal_name)||"Select deal":"No Deal"]}),s.jsx(Iq,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),s.jsx(gj,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:s.jsxs(cC,{children:[s.jsx(uC,{placeholder:"Search deals..."}),s.jsxs(dC,{children:[s.jsx(hC,{children:"No deals found."}),s.jsxs(pT,{children:[s.jsxs(X_,{value:"no-deal",onSelect:()=>{P("none"),ee(!1)},children:[s.jsx(ql,{className:hr("mr-2 h-4 w-4",j==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),d==null?void 0:d.map(be=>s.jsxs(X_,{value:be.deal_name,onSelect:()=>{P(be.id),ee(!1)},children:[s.jsx(ql,{className:hr("mr-2 h-4 w-4",j===be.id?"opacity-100":"opacity-0")}),be.deal_name]},be.id))]})]})]})})]})]}),s.jsxs("div",{children:[s.jsx(sn,{children:"Link to Contact"}),s.jsxs(fO,{open:ie,onOpenChange:oe,children:[s.jsx(mO,{asChild:!0,children:s.jsxs(Jt,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[s.jsxs("span",{className:"flex items-center gap-2 truncate",children:[s.jsx(nd,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),C!=="none"?(()=>{const be=l==null?void 0:l.find(Re=>Re.id===C);return be?`${be.first_name} ${be.last_name}`:"Select contact"})():"No Contact"]}),s.jsx(Iq,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),s.jsx(gj,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:s.jsxs(cC,{children:[s.jsx(uC,{placeholder:"Search contacts..."}),s.jsxs(dC,{children:[s.jsx(hC,{children:"No contacts found."}),s.jsxs(pT,{children:[s.jsxs(X_,{value:"no-contact",onSelect:()=>{L("none"),oe(!1)},children:[s.jsx(ql,{className:hr("mr-2 h-4 w-4",C==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),l==null?void 0:l.map(be=>s.jsxs(X_,{value:`${be.first_name??""} ${be.last_name??""} ${be.id}`,onSelect:()=>{L(be.id),oe(!1)},children:[s.jsx(ql,{className:hr("mr-2 h-4 w-4",C===be.id?"opacity-100":"opacity-0")}),be.first_name," ",be.last_name]},be.id))]})]})]})})]})]}),s.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[s.jsx(Jt,{variant:"outline",onClick:()=>e(!1),children:"Cancel"}),s.jsx(Jt,{onClick:pe,disabled:a.isPending||c.isPending,children:r?"Save Changes":"Create Task"})]})]})]})})}const zFt={urgent:{label:"Urgent",color:"bg-red-500/10 text-red-600 border-red-200",dot:"🔴"},high:{label:"High",color:"bg-orange-500/10 text-orange-600 border-orange-200",dot:"🟠"},medium:{label:"Medium",color:"bg-amber-500/10 text-amber-600 border-amber-200",dot:"🟡"},low:{label:"Low",color:"bg-emerald-500/10 text-emerald-600 border-emerald-200",dot:"🟢"}};function $Ft({tasks:t}){const e=nQ(),r=rOt(),n=qa(),[i,a]=N.useState(null),c=async g=>{const v=g.status==="done"?"todo":"done";try{await e.mutateAsync({id:g.id,status:v})}catch{lr.error("Failed to update task")}},d=async g=>{try{await r.mutateAsync(g),lr.success("Task deleted")}catch{lr.error("Failed to delete task")}};if(t.length===0)return s.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[s.jsx(od,{className:"h-12 w-12 text-muted-foreground/30 mb-3"}),s.jsx("p",{className:"text-muted-foreground font-medium",children:"No tasks found"}),s.jsx("p",{className:"text-muted-foreground/60 text-sm",children:"Create a new task to get started"})]});const p=new Map,l=[];return t.forEach(g=>{if(g.deal){const v=p.get(g.deal.id)||{dealName:g.deal.deal_name,tasks:[]};v.tasks.push(g),p.set(g.deal.id,v)}else l.push(g)}),s.jsxs("div",{className:"space-y-4",children:[l.length>0&&s.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[s.jsx("div",{className:"bg-muted/30 px-4 py-2 border-b",children:s.jsx("h3",{className:"font-medium text-sm text-muted-foreground",children:"General Tasks"})}),l.map(g=>s.jsx(gme,{task:g,onToggle:c,onDelete:d,onEdit:a,onNavigateDeal:v=>n(`/mission-control/pipeline?deal=${v}`)},g.id))]}),Array.from(p.entries()).map(([g,v])=>s.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[s.jsxs("button",{onClick:()=>n(`/mission-control/pipeline?deal=${g}`),className:"w-full bg-muted/30 px-4 py-2 border-b flex items-center gap-2 hover:bg-muted/50 transition-colors text-left",children:[s.jsx(jl,{className:"h-3.5 w-3.5 text-muted-foreground"}),s.jsx("h3",{className:"font-medium text-sm",children:v.dealName}),s.jsxs(Js,{variant:"secondary",className:"ml-auto text-xs",children:[v.tasks.filter(E=>E.status==="done").length,"/",v.tasks.length]}),s.jsx(uf,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),v.tasks.map(E=>s.jsx(gme,{task:E,onToggle:c,onDelete:d,onEdit:a,onNavigateDeal:T=>n(`/mission-control/pipeline?deal=${T}`)},E.id))]},g)),i&&s.jsx(dCe,{open:!!i,onOpenChange:()=>a(null),editTask:i})]})}function gme({task:t,onToggle:e,onDelete:r,onEdit:n,onNavigateDeal:i}){const a=t.status==="done",c=!a&&t.due_date&&mT(jd(t.due_date))&&!Uf(jd(t.due_date)),d=!a&&t.due_date&&Uf(jd(t.due_date)),p=zFt[t.priority];return s.jsxs("div",{className:hr("flex items-center gap-3 px-4 py-3 border-b last:border-b-0 group hover:bg-muted/30 transition-colors",a&&"opacity-60"),children:[s.jsx("button",{onClick:()=>e(t),className:"shrink-0",children:a?s.jsx(od,{className:"h-5 w-5 text-emerald-500"}):s.jsx(tT,{className:"h-5 w-5 text-muted-foreground hover:text-primary transition-colors"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:hr("text-sm font-medium truncate",a&&"line-through text-muted-foreground"),children:t.title}),s.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[t.stage&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full font-medium",style:{backgroundColor:t.stage.color+"20",color:t.stage.color},children:t.stage.name}),t.contact&&s.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[s.jsx(nd,{className:"h-2.5 w-2.5"}),t.contact.first_name," ",t.contact.last_name]})]})]}),s.jsxs(Js,{variant:"outline",className:hr("text-[10px] shrink-0",p.color),children:[p.dot," ",p.label]}),t.due_date&&s.jsxs("span",{className:hr("text-xs shrink-0 flex items-center gap-1",c&&"text-destructive font-medium",d&&"text-amber-600 font-medium",!c&&!d&&"text-muted-foreground"),children:[s.jsx(su,{className:"h-3 w-3"}),ds(jd(t.due_date),"MMM d")]}),s.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[s.jsx("button",{onClick:()=>n(t),className:"p-1 hover:bg-muted rounded",children:s.jsx(Rq,{className:"h-3.5 w-3.5 text-muted-foreground"})}),s.jsx("button",{onClick:()=>r(t.id),className:"p-1 hover:bg-destructive/10 rounded",children:s.jsx(iF,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const UFt=[{status:"todo",label:"To Do",icon:tT,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:YW,color:"border-t-blue-500"},{status:"done",label:"Done",icon:od,color:"border-t-emerald-500"}],VFt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function qFt({tasks:t}){const e=nQ(),r=N.useMemo(()=>{const a={todo:[],in_progress:[],done:[]};return t.forEach(c=>a[c.status].push(c)),a},[t]),n=(a,c)=>{a.dataTransfer.setData("taskId",c)},i=async(a,c)=>{a.preventDefault();const d=a.dataTransfer.getData("taskId");if(!d)return;const p=t.find(l=>l.id===d);if(!(!p||p.status===c))try{await e.mutateAsync({id:d,status:c})}catch{lr.error("Failed to move task")}};return s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:UFt.map(a=>s.jsxs("div",{className:hr("border rounded-lg border-t-4 bg-muted/20",a.color),onDragOver:c=>c.preventDefault(),onDrop:c=>i(c,a.status),children:[s.jsxs("div",{className:"px-4 py-3 flex items-center gap-2",children:[s.jsx(a.icon,{className:"h-4 w-4 text-muted-foreground"}),s.jsx("h3",{className:"font-semibold text-sm",children:a.label}),s.jsx(Js,{variant:"secondary",className:"ml-auto text-xs",children:r[a.status].length})]}),s.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[r[a.status].map(c=>s.jsx(GFt,{task:c,onDragStart:n},c.id)),r[a.status].length===0&&s.jsx("p",{className:"text-xs text-muted-foreground text-center py-8",children:"Drag tasks here"})]})]},a.status))})}function GFt({task:t,onDragStart:e}){const r=t.status==="done",n=!r&&t.due_date&&mT(jd(t.due_date))&&!Uf(jd(t.due_date)),i=!r&&t.due_date&&Uf(jd(t.due_date));return s.jsx("div",{draggable:!0,onDragStart:a=>e(a,t.id),className:hr("bg-background border rounded-lg p-3 cursor-grab active:cursor-grabbing shadow-sm hover:shadow-md transition-shadow",n&&"border-destructive/50"),children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"text-xs mt-0.5",children:VFt[t.priority]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:hr("text-sm font-medium",r&&"line-through text-muted-foreground"),children:t.title}),s.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[t.deal&&s.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[s.jsx(jl,{className:"h-2.5 w-2.5"}),t.deal.deal_name]}),t.contact&&s.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[s.jsx(nd,{className:"h-2.5 w-2.5"}),t.contact.first_name," ",t.contact.last_name]})]}),t.due_date&&s.jsxs("div",{className:hr("text-[10px] mt-1.5 flex items-center gap-1",n&&"text-destructive font-medium",i&&"text-amber-600 font-medium",!n&&!i&&"text-muted-foreground"),children:[s.jsx(su,{className:"h-2.5 w-2.5"}),n?"Overdue — ":i?"Due today — ":"",ds(jd(t.due_date),"MMM d")]}),t.stage&&s.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium mt-1.5",style:{backgroundColor:t.stage.color+"20",color:t.stage.color},children:t.stage.name})]})]})})}const yme={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function HFt({tasks:t}){const[e,r]=N.useState(new Date),n=nQ(),i=Fd(e),a=KP(e),c=ld(i),d=v5(a),p=_Qe({start:c,end:d}),l=N.useMemo(()=>{const E=new Map;return t.forEach(T=>{if(!T.due_date)return;const j=T.due_date,P=E.get(j)||[];P.push(T),E.set(j,P)}),E},[t]),g=N.useMemo(()=>t.filter(E=>!E.due_date),[t]),v=async E=>{const T=E.status==="done"?"todo":"done";try{await n.mutateAsync({id:E.id,status:T})}catch{lr.error("Failed to update task")}};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx(Jt,{variant:"ghost",size:"icon",onClick:()=>r(Ret(e,1)),children:s.jsx(bg,{className:"h-4 w-4"})}),s.jsx("h3",{className:"font-semibold",children:ds(e,"MMMM yyyy")}),s.jsx(Jt,{variant:"ghost",size:"icon",onClick:()=>r(af(e,1)),children:s.jsx(uf,{className:"h-4 w-4"})})]}),s.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(E=>s.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:E},E))}),s.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:p.map(E=>{const T=ds(E,"yyyy-MM-dd"),j=l.get(T)||[],P=w5(E,e),C=Uf(E);return s.jsxs("div",{className:hr("border-r border-b min-h-[100px] p-1",!P&&"bg-muted/30",C&&"bg-primary/5"),children:[s.jsx("div",{className:hr("text-xs font-medium mb-1 text-right px-1",!P&&"text-muted-foreground/40",C&&"text-primary font-bold"),children:ds(E,"d")}),s.jsxs("div",{className:"space-y-0.5",children:[j.slice(0,3).map(L=>s.jsxs("button",{onClick:()=>v(L),className:hr("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",L.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[L.status==="done"?s.jsx(od,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):s.jsx(tT,{className:"h-2.5 w-2.5 shrink-0"}),s.jsxs("span",{className:"truncate",children:[yme[L.priority]," ",L.title]})]},L.id)),j.length>3&&s.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",j.length-3," more"]})]})]},T)})}),g.length>0&&s.jsxs("div",{className:"border rounded-lg p-3",children:[s.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",g.length,")"]}),s.jsx("div",{className:"space-y-1",children:g.map(E=>s.jsxs("button",{onClick:()=>v(E),className:hr("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",E.status==="done"&&"opacity-50 line-through"),children:[E.status==="done"?s.jsx(od,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):s.jsx(tT,{className:"h-3.5 w-3.5 shrink-0"}),s.jsxs("span",{className:"truncate",children:[yme[E.priority]," ",E.title]}),E.deal&&s.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",E.deal.deal_name]})]},E.id))})]})]})}const WFt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function KFt({open:t,onOpenChange:e,stages:r}){var L;const[n,i]=N.useState(((L=r[0])==null?void 0:L.id)||""),{data:a,isLoading:c}=nOt(n||void 0),d=iOt(),p=sOt(),[l,g]=N.useState(""),[v,E]=N.useState("medium"),[T,j]=N.useState(""),P=async()=>{if(!(!l.trim()||!n))try{await d.mutateAsync({stage_id:n,title:l.trim(),priority:v,default_due_offset_days:T?parseInt(T):null,sort_order:((a==null?void 0:a.length)||0)+1}),g(""),j(""),lr.success("Template added")}catch{lr.error("Failed to add template")}},C=async O=>{try{await p.mutateAsync(O),lr.success("Template deleted")}catch{lr.error("Failed to delete template")}};return s.jsx(gl,{open:t,onOpenChange:e,children:s.jsxs(Jo,{className:"sm:max-w-[560px]",children:[s.jsx(Bc,{children:s.jsxs(pc,{className:"flex items-center gap-2",children:[s.jsx(K4e,{className:"h-5 w-5"}),"Task Templates by Stage"]})}),s.jsx("p",{className:"text-sm text-muted-foreground -mt-2",children:"Create default tasks that auto-populate when a deal enters a stage."}),s.jsxs("div",{children:[s.jsx(sn,{children:"Pipeline Stage"}),s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:r.filter(O=>!O.is_won_stage&&!O.is_lost_stage).map(O=>s.jsx("button",{onClick:()=>i(O.id),className:hr("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",n===O.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:O.name},O.id))})]}),s.jsx(Eg,{className:"max-h-[250px]",children:s.jsxs("div",{className:"space-y-1.5",children:[a==null?void 0:a.map((O,F)=>s.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border rounded-lg group",children:[s.jsx("span",{className:"text-xs",children:WFt[O.priority]}),s.jsx("span",{className:"text-sm flex-1 truncate",children:O.title}),O.default_due_offset_days&&s.jsxs(Js,{variant:"outline",className:"text-[10px]",children:["+",O.default_due_offset_days,"d"]}),s.jsx("button",{onClick:()=>C(O.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:s.jsx(iF,{className:"h-3.5 w-3.5 text-destructive"})})]},O.id)),(a==null?void 0:a.length)===0&&n&&s.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),n&&s.jsxs("div",{className:"space-y-3 border-t pt-3",children:[s.jsx(sn,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(hn,{placeholder:"Task title...",value:l,onChange:O=>g(O.target.value),className:"flex-1",onKeyDown:O=>O.key==="Enter"&&P()}),s.jsxs(Xo,{value:v,onValueChange:O=>E(O),children:[s.jsx(Mo,{className:"w-[100px]",children:s.jsx(Qo,{})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"low",children:"🟢 Low"}),s.jsx($n,{value:"medium",children:"🟡 Med"}),s.jsx($n,{value:"high",children:"🟠 High"}),s.jsx($n,{value:"urgent",children:"🔴 Urgent"})]})]})]}),s.jsxs("div",{className:"flex gap-2 items-end",children:[s.jsxs("div",{className:"flex-1",children:[s.jsx(sn,{className:"text-xs",children:"Due offset (days from entering stage)"}),s.jsx(hn,{type:"number",placeholder:"e.g., 7",value:T,onChange:O=>j(O.target.value)})]}),s.jsxs(Jt,{onClick:P,disabled:!l.trim()||d.isPending,children:[s.jsx(Py,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function YFt(){const{data:t,isLoading:e}=JMt(),{data:r}=aOt(),[n,i]=N.useState("list"),[a,c]=N.useState(""),[d,p]=N.useState("active"),[l,g]=N.useState("all"),[v,E]=N.useState("all"),[T,j]=N.useState(!1),[P,C]=N.useState(!1),L=N.useMemo(()=>{if(!t)return[];const $=new Map;return t.forEach(G=>{G.deal&&$.set(G.deal.id,G.deal.deal_name)}),Array.from($,([G,W])=>({id:G,name:W}))},[t]),O=N.useMemo(()=>t?t.filter($=>{var ie,oe,pe,Le;const G=a.toLowerCase(),W=!G||$.title.toLowerCase().includes(G)||((oe=(ie=$.deal)==null?void 0:ie.deal_name)==null?void 0:oe.toLowerCase().includes(G))||`${((pe=$.contact)==null?void 0:pe.first_name)||""} ${((Le=$.contact)==null?void 0:Le.last_name)||""}`.toLowerCase().includes(G),Z=d==="all"||d==="active"&&$.status!=="done"||d==="todo"&&$.status==="todo"||d==="in_progress"&&$.status==="in_progress"||d==="done"&&$.status==="done"||d==="overdue"&&$.status!=="done"&&$.due_date&&mT(jd($.due_date))&&!Uf(jd($.due_date)),Q=l==="all"||$.priority===l,ee=v==="all"||v==="no_deal"&&!$.deal_id||$.deal_id===v;return W&&Z&&Q&&ee}):[],[t,a,d,l,v]),F=N.useMemo(()=>{if(!t)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const $=t.filter(G=>G.status!=="done");return{total:$.length,overdue:$.filter(G=>G.due_date&&mT(jd(G.due_date))&&!Uf(jd(G.due_date))).length,dueToday:$.filter(G=>G.due_date&&Uf(jd(G.due_date))).length,dueThisWeek:$.filter(G=>G.due_date&&get(jd(G.due_date))).length,completed:t.filter(G=>G.status==="done").length}},[t]);return s.jsx(gT,{children:s.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[s.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),s.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Jt,{variant:"outline",size:"sm",onClick:()=>C(!0),children:[s.jsx(Y4e,{className:"h-4 w-4 mr-1"}),"Templates"]}),s.jsxs(Jt,{size:"sm",onClick:()=>j(!0),children:[s.jsx(Py,{className:"h-4 w-4 mr-1"}),"New Task"]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[s.jsxs("button",{onClick:()=>p("active"),className:`p-3 rounded-lg border text-left transition-colors ${d==="active"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs font-medium",children:[s.jsx(Nq,{className:"h-3.5 w-3.5"}),"Active"]}),s.jsx("p",{className:"text-xl font-bold mt-1",children:F.total})]}),s.jsxs("button",{onClick:()=>p("overdue"),className:`p-3 rounded-lg border text-left transition-colors ${d==="overdue"?"border-destructive bg-destructive/5":"hover:bg-muted/50"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 text-destructive text-xs font-medium",children:[s.jsx(LP,{className:"h-3.5 w-3.5"}),"Overdue"]}),s.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:F.overdue})]}),s.jsxs("button",{onClick:()=>{p("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs font-medium",children:[s.jsx(su,{className:"h-3.5 w-3.5"}),"Due Today"]}),s.jsx("p",{className:"text-xl font-bold mt-1",children:F.dueToday})]}),s.jsxs("button",{onClick:()=>{p("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 text-blue-600 text-xs font-medium",children:[s.jsx(ig,{className:"h-3.5 w-3.5"}),"This Week"]}),s.jsx("p",{className:"text-xl font-bold mt-1",children:F.dueThisWeek})]}),s.jsxs("button",{onClick:()=>p("done"),className:`p-3 rounded-lg border text-left transition-colors ${d==="done"?"border-emerald-500 bg-emerald-500/5":"hover:bg-muted/50"}`,children:[s.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 text-xs font-medium",children:[s.jsx(od,{className:"h-3.5 w-3.5"}),"Completed"]}),s.jsx("p",{className:"text-xl font-bold mt-1",children:F.completed})]})]}),s.jsxs("div",{className:"flex flex-col md:flex-row gap-3 items-start md:items-center",children:[s.jsxs("div",{className:"relative flex-1 max-w-sm",children:[s.jsx(ef,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),s.jsx(hn,{placeholder:"Search tasks...",value:a,onChange:$=>c($.target.value),className:"pl-9"})]}),s.jsxs(Xo,{value:l,onValueChange:g,children:[s.jsx(Mo,{className:"w-[130px]",children:s.jsx(Qo,{placeholder:"Priority"})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"all",children:"All Priorities"}),s.jsx($n,{value:"urgent",children:"🔴 Urgent"}),s.jsx($n,{value:"high",children:"🟠 High"}),s.jsx($n,{value:"medium",children:"🟡 Medium"}),s.jsx($n,{value:"low",children:"🟢 Low"})]})]}),s.jsxs(Xo,{value:v,onValueChange:E,children:[s.jsx(Mo,{className:"w-[160px]",children:s.jsx(Qo,{placeholder:"Deal"})}),s.jsxs(Oo,{children:[s.jsx($n,{value:"all",children:"All Deals"}),s.jsx($n,{value:"no_deal",children:"No Deal"}),L.map($=>s.jsx($n,{value:$.id,children:$.name},$.id))]})]}),s.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[s.jsx("button",{onClick:()=>i("list"),className:`p-1.5 rounded-md transition-colors ${n==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:s.jsx(Nq,{className:"h-4 w-4"})}),s.jsx("button",{onClick:()=>i("kanban"),className:`p-1.5 rounded-md transition-colors ${n==="kanban"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:s.jsx(ZW,{className:"h-4 w-4"})}),s.jsx("button",{onClick:()=>i("calendar"),className:`p-1.5 rounded-md transition-colors ${n==="calendar"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:s.jsx(ig,{className:"h-4 w-4"})})]})]}),e?s.jsx("div",{className:"flex items-center justify-center py-20",children:s.jsx("div",{className:"animate-spin h-8 w-8 border-2 border-primary border-t-transparent rounded-full"})}):s.jsxs(s.Fragment,{children:[n==="list"&&s.jsx($Ft,{tasks:O}),n==="kanban"&&s.jsx(qFt,{tasks:O}),n==="calendar"&&s.jsx(HFt,{tasks:O})]}),s.jsx(dCe,{open:T,onOpenChange:j}),s.jsx(KFt,{open:P,onOpenChange:C,stages:r||[]})]})})}const wXt={pending_payment:"Pending Payment",order_submitted:"Order Submitted",awaiting_proof_approval:"Awaiting Proof Approval",proof_approved:"Proof Approved",processing:"Processing",in_production:"In Production",shipped:"Shipped",completed:"Completed",cancelled:"Cancelled",refunded:"Refunded"},SXt={pending_payment:"bg-yellow-100 text-yellow-800",order_submitted:"bg-blue-100 text-blue-800",awaiting_proof_approval:"bg-orange-100 text-orange-800",proof_approved:"bg-green-100 text-green-800",processing:"bg-purple-100 text-purple-800",in_production:"bg-indigo-100 text-indigo-800",shipped:"bg-cyan-100 text-cyan-800",completed:"bg-green-200 text-green-900",cancelled:"bg-red-100 text-red-800",refunded:"bg-gray-100 text-gray-800"};function ZFt(t=!0){return jr({queryKey:["marketplace-categories",t],queryFn:async()=>{let e=Be.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});t&&(e=e.eq("is_active",!0));const{data:r,error:n}=await e;if(n)throw n;return r}})}function EXt(){const t=Ur();return zr({mutationFn:async e=>{const{data:r,error:n}=await Be.from("marketplace_categories").insert([e]).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),lr.success("Category created successfully")},onError:e=>{lr.error("Failed to create category: "+e.message)}})}function TXt(){const t=Ur();return zr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Be.from("marketplace_categories").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),lr.success("Category updated successfully")},onError:e=>{lr.error("Failed to update category: "+e.message)}})}function AXt(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("marketplace_categories").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),lr.success("Category deleted successfully")},onError:e=>{lr.error("Failed to delete category: "+e.message)}})}function XFt(t,e=!0){return jr({queryKey:["marketplace-products",t,e],queryFn:async()=>{let r=Be.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).order("sort_order",{ascending:!0});t&&(r=r.eq("category_id",t)),e&&(r=r.eq("is_active",!0));const{data:n,error:i}=await r;if(i)throw i;return n}})}function kXt(t){return jr({queryKey:["marketplace-product",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",t).single();if(r)throw r;return e},enabled:!!t})}function IXt(){const t=Ur();return zr({mutationFn:async e=>{const{data:r,error:n}=await Be.from("marketplace_products").insert([e]).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-products"]}),lr.success("Product created successfully")},onError:e=>{lr.error("Failed to create product: "+e.message)}})}function jXt(){const t=Ur();return zr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Be.from("marketplace_products").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",r.id]}),lr.success("Product updated successfully")},onError:e=>{lr.error("Failed to update product: "+e.message)}})}function CXt(){const t=Ur();return zr({mutationFn:async e=>{const{error:r}=await Be.from("marketplace_products").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-products"]}),lr.success("Product deleted successfully")},onError:e=>{lr.error("Failed to delete product: "+e.message)}})}function PXt(){const t=Ur();return zr({mutationFn:async e=>{const{data:r,error:n}=await Be.from("marketplace_product_images").insert([e]).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",r.product_id]})}})}function NXt(){const t=Ur();return zr({mutationFn:async({id:e,productId:r})=>{const{error:n}=await Be.from("marketplace_product_images").delete().eq("id",e);if(n)throw n;return r},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",e]}),lr.success("Image deleted successfully")},onError:e=>{lr.error("Failed to delete image: "+e.message)}})}function RXt(){const t=Ur();return zr({mutationFn:async({imageId:e,productId:r})=>{const{error:n}=await Be.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",r);if(n)throw n;const{error:i}=await Be.from("marketplace_product_images").update({is_primary:!0}).eq("id",e);if(i)throw i;return r},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",e]}),lr.success("Primary image updated")},onError:e=>{lr.error("Failed to set primary image: "+e.message)}})}function LXt(){const t=Ur();return zr({mutationFn:async e=>{const{data:r,error:n}=await Be.from("marketplace_product_variants").insert([e]).select().single();if(n)throw n;return r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",r.product_id]}),lr.success("Variant added successfully")}})}function DXt(){const t=Ur();return zr({mutationFn:async({id:e,productId:r})=>{const{error:n}=await Be.from("marketplace_product_variants").delete().eq("id",e);if(n)throw n;return r},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",e]}),lr.success("Variant deleted successfully")}})}function MXt(){const t=Ur();return zr({mutationFn:async({productId:e,videoUrl:r})=>{await Be.from("marketplace_product_videos").delete().eq("product_id",e);const{data:n,error:i}=await Be.from("marketplace_product_videos").insert({product_id:e,video_url:r}).select().single();if(i)throw i;return n},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["marketplace-products"]}),t.invalidateQueries({queryKey:["marketplace-product",r.productId]}),lr.success("Video updated successfully")}})}function OXt(t){const{isAdmin:e}=_i();return jr({queryKey:["marketplace-orders",t,e],queryFn:async()=>{let r=Be.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:n,error:i}=await r;if(i)throw i;if(e&&n){const a=[...new Set(n.map(p=>p.user_id))],{data:c}=await Be.from("profiles").select("id, name, email").in("id",a),d=new Map((c==null?void 0:c.map(p=>[p.id,p]))||[]);return n.map(p=>({...p,user:d.get(p.user_id)}))}return n}})}function FXt(){const{user:t}=_i();return jr({queryKey:["my-marketplace-orders",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await Be.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("user_id",t.id).order("created_at",{ascending:!1});if(r)throw r;return e},enabled:!!(t!=null&&t.id)})}function BXt(t){return jr({queryKey:["marketplace-order",t],queryFn:async()=>{const{data:e,error:r}=await Be.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",t).single();if(r)throw r;return e},enabled:!!t})}function zXt(){const t=Ur(),{user:e}=_i();return zr({mutationFn:async({orderId:r,status:n,notes:i,trackingNumber:a,trackingUrl:c,previousStatus:d})=>{const p={status:n};a!==void 0&&(p.tracking_number=a),c!==void 0&&(p.tracking_url=c);const{error:l}=await Be.from("marketplace_orders").update(p).eq("id",r);if(l)throw l;const{error:g}=await Be.from("marketplace_order_status_history").insert({order_id:r,status:n,notes:i,created_by:e==null?void 0:e.id});if(g)throw g;if(["shipped","in_production","processing","completed"].includes(n)&&n!==d)try{await Be.functions.invoke("marketplace-order-notify",{body:{orderId:r,notificationType:n==="shipped"?"shipped":"status_update",newStatus:n,trackingNumber:a,trackingUrl:c}})}catch(E){console.error("Failed to send notification email:",E)}},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["marketplace-orders"]}),t.invalidateQueries({queryKey:["marketplace-order",n.orderId]}),t.invalidateQueries({queryKey:["my-marketplace-orders"]}),lr.success("Order status updated")},onError:r=>{lr.error("Failed to update order: "+r.message)}})}function $Xt(){const t=Ur();return zr({mutationFn:async({itemId:e,proofUrl:r,proofNotes:n,orderId:i})=>{const{error:a}=await Be.from("marketplace_order_items").update({proof_url:r,proof_notes:n,proof_status:"pending"}).eq("id",e);if(a)throw a;await Be.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",i);try{await Be.functions.invoke("marketplace-order-notify",{body:{orderId:i,notificationType:"proof_ready"}})}catch(c){console.error("Failed to send proof notification:",c)}return i},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-orders"]}),t.invalidateQueries({queryKey:["marketplace-order",e]}),t.invalidateQueries({queryKey:["my-marketplace-orders"]}),lr.success("Proof uploaded & customer notified")}})}function UXt(){const t=Ur();return zr({mutationFn:async({itemId:e,orderId:r})=>{const{error:n}=await Be.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",e);if(n)throw n;return r},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-orders"]}),t.invalidateQueries({queryKey:["marketplace-order",e]}),t.invalidateQueries({queryKey:["my-marketplace-orders"]}),lr.success("Proof approved")}})}function VXt(){const t=Ur();return zr({mutationFn:async({itemId:e,orderId:r,reason:n})=>{const{error:i}=await Be.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:n}).eq("id",e);if(i)throw i;return r},onSuccess:e=>{t.invalidateQueries({queryKey:["marketplace-orders"]}),t.invalidateQueries({queryKey:["marketplace-order",e]}),t.invalidateQueries({queryKey:["my-marketplace-orders"]}),lr.success("Proof rejected - please upload a new proof")}})}function QFt(){const t=qa(),[e,r]=N.useState(null),{data:n,isLoading:i}=XFt(e||void 0,!0),{data:a,isLoading:c}=ZFt(!0),{cartItems:d}=JSe(),p=d.reduce((g,v)=>g+v.quantity,0),l=g=>{t(`/marketplace/${g.id}`)};return i||c?s.jsx(gT,{title:"Marketplace",children:s.jsxs("div",{className:"space-y-6",children:[s.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(g=>s.jsx(Mc,{className:"h-10 w-24 flex-shrink-0"},g))}),s.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:[1,2,3,4].map(g=>s.jsx(Mc,{className:"h-72 w-full"},g))})]})}):s.jsx(gT,{title:"Marketplace",children:s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),s.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),s.jsxs(Jt,{variant:"outline",onClick:()=>t("/marketplace/cart"),className:"relative",children:[s.jsx(fve,{className:"h-4 w-4 mr-2"}),"Cart",p>0&&s.jsx(Js,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:p})]})]}),a&&a.length>0&&s.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[s.jsx(Jt,{variant:e===null?"default":"outline",size:"sm",onClick:()=>r(null),children:"All"}),a.map(g=>s.jsx(Jt,{variant:e===g.id?"default":"outline",size:"sm",onClick:()=>r(g.id),children:g.name},g.id))]}),n&&n.length>0?s.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:n.map(g=>{var v;return s.jsxs(wi,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>l(g),children:[s.jsxs("div",{className:"aspect-square bg-muted relative",children:[g.images&&g.images.length>0?s.jsx("img",{src:((v=g.images.find(E=>E.is_primary))==null?void 0:v.image_url)||g.images[0].image_url,alt:g.name,className:"w-full h-full object-cover"}):s.jsx("div",{className:"flex items-center justify-center h-full",children:s.jsx(Kse,{className:"h-12 w-12 text-muted-foreground"})}),g.category&&s.jsx(Js,{className:"absolute top-2 left-2",variant:"secondary",children:g.category.name})]}),s.jsxs(Di,{className:"p-4",children:[s.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:g.name}),g.description&&s.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:g.description}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("span",{className:"font-bold text-lg",children:["$",Number(g.base_price).toFixed(2)]}),g.variants&&g.variants.length>0&&s.jsxs("span",{className:"text-xs text-muted-foreground",children:[g.variants.length," options"]})]})]})]},g.id)})}):s.jsxs("div",{className:"text-center py-12",children:[s.jsx(Kse,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),s.jsx("p",{className:"text-muted-foreground",children:"No products available yet."})]})]})})}const pN={home_anniversary:{title:["Happy Home","Anniversary"],icon:"🏡",emojis:["🏡","✨","🎉","❤️","🎊","🏠"],defaultMessage:"Wishing you many more wonderful years of memories in your beautiful home. Thank you for letting me be part of your journey."},wedding_anniversary:{title:["Happy","Anniversary"],icon:"💍",emojis:["💍","💐","❤️","🥂","💕","✨"],defaultMessage:"Wishing you both a wonderful anniversary filled with love, laughter, and cherished memories. Here's to many more years together!"},just_listed:{title:["Just","Listed!"],icon:"🏠",emojis:["🏠","📋","🔑","⭐","🎯","✨"],defaultMessage:"Exciting news — this beautiful property just hit the market! Contact me for a private showing."},just_sold:{title:["Just","Sold!"],icon:"🎉",emojis:["🎉","🏡","🔑","🥂","🎊","💰"],defaultMessage:"Another successful closing! Congratulations to the new homeowners. It was a pleasure making this happen."},congratulations:{title:["Congratulations!",""],icon:"🏆",emojis:["🎉","🥳","🏆","⭐","🎊","✨"],defaultMessage:"What an incredible milestone! I'm so happy for you. Wishing you all the best in this exciting new chapter."},birthday:{title:["Happy","Birthday!"],icon:"🎂",emojis:["🎂","🎈","🎁","🥳","🎉","🧁"],defaultMessage:"Wishing you the happiest of birthdays! May this year bring you joy, laughter, and everything you've been dreaming of."},holiday:{title:["Happy","Holidays!"],icon:"🎄",emojis:["🎄","❄️","🎁","⭐","🕯️","🎅"],defaultMessage:"Wishing you and your family a season filled with warmth, joy, and cherished moments. Happy Holidays!"},thank_you:{title:["Thank","You!"],icon:"💐",emojis:["💐","🙏","❤️","⭐","✨","🤝"],defaultMessage:"Thank you so much for your trust and confidence. It truly means the world to me. I'm always here for you!"},thinking_of_you:{title:["Thinking","Of You"],icon:"💭",emojis:["💭","❤️","🌸","☀️","🦋","💫"],defaultMessage:"Just wanted to reach out and let you know I'm thinking of you. I hope you're doing well — don't hesitate to reach out anytime!"}};function bI({delay:t,x:e,y:r,size:n}){return s.jsx(Sr.div,{className:"absolute rounded-full bg-slate-300/30 dark:bg-slate-500/20",style:{left:e,top:r,width:n,height:n},animate:{y:[0,-20,0],opacity:[.3,.7,.3],scale:[1,1.2,1]},transition:{duration:4,delay:t,repeat:1/0,ease:"easeInOut"}})}function JFt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:a,agentName:c,agentPhotoUrl:d,agentPhone:p,agentEmail:l,agentBrokerage:g,propertyPhotoUrl:v,videoUrl:E}=t,T=pN[e];return s.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-blue-50/30 to-white dark:from-slate-950 dark:to-slate-900 flex items-center justify-center p-4 overflow-hidden relative",children:[s.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[s.jsx(Sr.div,{className:"absolute -top-20 -right-20 w-72 h-72 rounded-full bg-gradient-to-br from-blue-100/40 to-slate-100/20 blur-3xl",animate:{scale:[1,1.1,1],rotate:[0,5,0]},transition:{duration:8,repeat:1/0,ease:"easeInOut"}}),s.jsx(Sr.div,{className:"absolute -bottom-20 -left-20 w-64 h-64 rounded-full bg-gradient-to-tr from-slate-200/30 to-blue-100/20 blur-3xl",animate:{scale:[1,1.15,1],rotate:[0,-5,0]},transition:{duration:10,repeat:1/0,ease:"easeInOut"}}),s.jsx(bI,{delay:0,x:"15%",y:"20%",size:8}),s.jsx(bI,{delay:1,x:"80%",y:"30%",size:6}),s.jsx(bI,{delay:2,x:"60%",y:"70%",size:10}),s.jsx(bI,{delay:.5,x:"25%",y:"80%",size:7}),s.jsx(bI,{delay:1.5,x:"70%",y:"15%",size:5})]}),s.jsxs(Sr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,ease:"easeOut"},children:[s.jsxs(Sr.div,{className:"bg-white/80 dark:bg-slate-900/80 backdrop-blur-xl rounded-3xl shadow-[0_20px_60px_-15px_rgba(0,0,0,0.1)] overflow-hidden border border-slate-200/60 dark:border-slate-700/50",initial:{scale:.95},animate:{scale:1},transition:{duration:.6,delay:.2},children:[s.jsx("div",{className:"relative h-2 bg-gradient-to-r from-slate-200 via-blue-300 to-slate-200 dark:from-slate-700 dark:via-blue-500 dark:to-slate-700 overflow-hidden",children:s.jsx(Sr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}})}),s.jsxs("div",{className:"px-8 py-10 text-center",children:[s.jsxs(Sr.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-slate-100 to-blue-50 dark:from-slate-800 dark:to-slate-700 flex items-center justify-center shadow-lg relative",initial:{scale:0,rotate:-10},animate:{scale:1,rotate:0},transition:{duration:.5,delay:.4,type:"spring",stiffness:200},children:[s.jsx(Sr.div,{className:"absolute inset-0 rounded-2xl border-2 border-slate-200/50 dark:border-slate-600/50",animate:{scale:[1,1.15,1],opacity:[.5,0,.5]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut"}}),s.jsx("span",{className:"text-4xl",children:T.icon})]}),e==="home_anniversary"&&i!==null&&i>0&&s.jsx(Sr.div,{className:"inline-block mb-4",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:s.jsxs("span",{className:"text-sm font-semibold tracking-[0.25em] uppercase text-blue-400 dark:text-blue-300",children:[i," ",i===1?"Year":"Years"]})}),s.jsx(Sr.h1,{className:"text-4xl font-light text-slate-800 dark:text-slate-100 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:T.title[0]}),T.title[1]&&s.jsx(Sr.h2,{className:"text-4xl font-bold text-slate-800 dark:text-slate-100 mb-8 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:T.title[1]}),s.jsxs(Sr.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,delay:1},children:[s.jsx("p",{className:"text-xl font-medium text-slate-700 dark:text-slate-200 mb-1",children:r}),n&&s.jsx("p",{className:"text-sm text-slate-400 dark:text-slate-500 mb-6",children:n})]}),s.jsx(Sr.div,{className:"h-px bg-gradient-to-r from-transparent via-slate-300 dark:via-slate-600 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"80%"},transition:{duration:.8,delay:1.1},style:{margin:"0 auto 1.5rem"}}),v&&s.jsx(Sr.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:s.jsx("img",{src:v,alt:"Property",className:"w-full h-48 object-cover"})}),E&&s.jsx(Sr.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:s.jsx("iframe",{src:`${E}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),s.jsx(Sr.p,{className:"text-sm text-slate-500 dark:text-slate-400 leading-relaxed max-w-xs mx-auto mb-8 italic",initial:{opacity:0},animate:{opacity:1},transition:{duration:.6,delay:1.3},children:a||T.defaultMessage}),s.jsxs(Sr.div,{className:"border-t border-slate-100 dark:border-slate-800 pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.5,delay:1.5},children:[s.jsxs("div",{className:"flex items-center justify-center gap-3",children:[d?s.jsx(Sr.img,{src:d,alt:c,className:"h-12 w-12 rounded-full object-cover ring-2 ring-slate-200 dark:ring-slate-700 shadow-md",whileHover:{scale:1.1}}):s.jsx("div",{className:"h-12 w-12 rounded-full bg-gradient-to-br from-slate-200 to-blue-100 dark:from-slate-700 dark:to-slate-600 flex items-center justify-center shadow-md",children:s.jsx("span",{className:"text-sm font-semibold text-slate-600 dark:text-slate-300",children:c.charAt(0)})}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:c}),g&&s.jsx("p",{className:"text-xs text-slate-400 dark:text-slate-500",children:g})]})]}),s.jsxs("div",{className:"flex items-center justify-center gap-3 mt-4",children:[p&&s.jsxs(Sr.a,{href:`tel:${p}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(Ui,{className:"h-3.5 w-3.5"})," Call"]}),l&&s.jsxs(Sr.a,{href:`mailto:${l}`,className:"flex items-center gap-1.5 px-4 py-2 rounded-full bg-slate-100 dark:bg-slate-800 text-xs font-medium text-slate-600 dark:text-slate-300 hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors shadow-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(rs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),s.jsx(Sr.p,{className:"text-center text-[10px] text-slate-400 dark:text-slate-600 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function BV({delay:t,x:e,y:r,color:n,size:i}){return s.jsx(Sr.div,{className:`absolute rounded-full blur-2xl ${n}`,style:{left:e,top:r,width:i,height:i},animate:{scale:[1,1.4,1],opacity:[.2,.5,.2]},transition:{duration:5,delay:t,repeat:1/0,ease:"easeInOut"}})}function wI({delay:t,x:e,y:r}){return s.jsx(Sr.div,{className:"absolute text-white/30 text-lg",style:{left:e,top:r},animate:{opacity:[0,1,0],scale:[.5,1,.5],rotate:[0,180,360]},transition:{duration:3,delay:t,repeat:1/0,ease:"easeInOut"},children:"✦"})}const xme={home_anniversary:{bg:"from-violet-950 via-purple-900 to-fuchsia-950",orbs:["bg-violet-500/30","bg-fuchsia-500/25","bg-purple-400/20"]},birthday:{bg:"from-pink-950 via-rose-900 to-fuchsia-950",orbs:["bg-pink-500/30","bg-rose-500/25","bg-fuchsia-400/20"]},just_sold:{bg:"from-emerald-950 via-teal-900 to-cyan-950",orbs:["bg-emerald-500/30","bg-teal-500/25","bg-cyan-400/20"]},just_listed:{bg:"from-amber-950 via-orange-900 to-yellow-950",orbs:["bg-amber-500/30","bg-orange-500/25","bg-yellow-400/20"]},thank_you:{bg:"from-rose-950 via-pink-900 to-red-950",orbs:["bg-rose-500/30","bg-pink-500/25","bg-red-400/20"]},congratulations:{bg:"from-yellow-950 via-amber-900 to-orange-950",orbs:["bg-yellow-500/30","bg-amber-500/25","bg-orange-400/20"]},holiday:{bg:"from-red-950 via-rose-900 to-emerald-950",orbs:["bg-red-500/30","bg-green-500/25","bg-rose-400/20"]},thinking_of_you:{bg:"from-indigo-950 via-violet-900 to-purple-950",orbs:["bg-indigo-500/30","bg-violet-500/25","bg-purple-400/20"]}};function e3t(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:a,agentName:c,agentPhotoUrl:d,agentPhone:p,agentEmail:l,agentBrokerage:g,propertyPhotoUrl:v,videoUrl:E}=t,T=pN[e],j=xme[e]||xme.home_anniversary;return s.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${j.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[s.jsx(BV,{delay:0,x:"10%",y:"10%",color:j.orbs[0],size:200}),s.jsx(BV,{delay:1,x:"70%",y:"60%",color:j.orbs[1],size:180}),s.jsx(BV,{delay:2,x:"50%",y:"20%",color:j.orbs[2],size:150}),s.jsx(wI,{delay:0,x:"20%",y:"25%"}),s.jsx(wI,{delay:.8,x:"75%",y:"15%"}),s.jsx(wI,{delay:1.6,x:"85%",y:"65%"}),s.jsx(wI,{delay:2.4,x:"10%",y:"75%"}),s.jsx(wI,{delay:.4,x:"45%",y:"85%"}),s.jsxs(Sr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.7,ease:"easeOut"},children:[s.jsxs(Sr.div,{className:"relative rounded-3xl overflow-hidden",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[s.jsx(Sr.div,{className:"absolute -inset-[1px] rounded-3xl bg-gradient-to-r from-violet-500 via-fuchsia-500 to-violet-500 opacity-50",animate:{backgroundPosition:["0% 50%","100% 50%","0% 50%"]},transition:{duration:4,repeat:1/0,ease:"linear"},style:{backgroundSize:"200% 200%"}}),s.jsxs("div",{className:"relative bg-white/5 backdrop-blur-xl border border-white/10 rounded-3xl px-8 py-10 text-center m-[1px]",children:[s.jsxs(Sr.div,{className:"mx-auto mb-6 h-20 w-20 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-2xl shadow-violet-500/40 relative",initial:{scale:0,rotate:-20},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:200},children:[s.jsx(Sr.div,{className:"absolute inset-0 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500",animate:{scale:[1,1.3,1],opacity:[.6,0,.6]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),s.jsx("span",{className:"text-4xl relative z-10",children:T.icon})]}),e==="home_anniversary"&&i!==null&&i>0&&s.jsxs(Sr.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/10 border border-white/15 backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[s.jsx(Sr.span,{className:"text-3xl font-black text-white",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.8},children:i}),s.jsx("span",{className:"text-xs font-semibold text-violet-200 uppercase tracking-widest",children:i===1?"Year":"Years"})]}),s.jsx(Sr.h1,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-violet-200 via-white to-fuchsia-200 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:T.title[0]}),T.title[1]&&s.jsx(Sr.h2,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-fuchsia-300 via-violet-200 to-purple-300 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:T.title[1]}),s.jsx(Sr.div,{className:"text-3xl mb-4",initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},transition:{duration:.4,delay:1,type:"spring",stiffness:300},children:T.emojis.slice(0,3).join("")}),s.jsxs(Sr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[s.jsx("p",{className:"text-xl font-semibold text-white/90 mb-1",children:r}),n&&s.jsxs("p",{className:"text-sm text-violet-300/70 mb-6 flex items-center justify-center gap-1.5",children:[s.jsx(Do,{className:"h-3.5 w-3.5"}),n]})]}),v&&s.jsx(Sr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:s.jsx("img",{src:v,alt:"Property",className:"w-full h-48 object-cover"})}),E&&s.jsx(Sr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:s.jsx("iframe",{src:`${E}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),s.jsx(Sr.div,{className:"bg-white/5 rounded-2xl p-5 border border-white/10 mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:s.jsx("p",{className:"text-sm text-violet-100/80 leading-relaxed",children:a||T.defaultMessage})}),s.jsxs(Sr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[s.jsxs("div",{className:"flex items-center justify-center gap-3",children:[d?s.jsx(Sr.img,{src:d,alt:c,className:"h-12 w-12 rounded-xl object-cover ring-2 ring-violet-500/40 shadow-lg",whileHover:{scale:1.1}}):s.jsx("div",{className:"h-12 w-12 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-lg",children:s.jsx("span",{className:"text-sm font-bold text-white",children:c.charAt(0)})}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-sm font-bold text-white",children:c}),g&&s.jsx("p",{className:"text-xs text-violet-300/60",children:g})]})]}),s.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[p&&s.jsxs(Sr.a,{href:`tel:${p}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(Ui,{className:"h-3.5 w-3.5"})," Call Me"]}),l&&s.jsxs(Sr.a,{href:`mailto:${l}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r from-violet-500/30 to-fuchsia-500/30 text-xs font-semibold text-white hover:from-violet-500/50 hover:to-fuchsia-500/50 transition-all border border-white/15 shadow-lg",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(rs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),s.jsx(Sr.p,{className:"text-center text-[10px] text-violet-400/40 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function t3t({emoji:t,delay:e,x:r,duration:n}){return s.jsx(Sr.div,{className:"absolute text-2xl pointer-events-none",style:{left:r,bottom:-20},animate:{y:[0,-600],opacity:[0,1,1,0],x:[0,15,-10,5],rotate:[0,20,-15,10]},transition:{duration:n,delay:e,repeat:1/0,ease:"easeOut"},children:t})}const _me={home_anniversary:{bg:"from-amber-50 via-orange-50 to-rose-50",header:"from-amber-400 via-orange-400 to-rose-400",accent:"text-amber-900",text:"text-amber-800"},birthday:{bg:"from-pink-50 via-rose-50 to-fuchsia-50",header:"from-pink-400 via-rose-400 to-fuchsia-400",accent:"text-pink-900",text:"text-pink-800"},just_sold:{bg:"from-emerald-50 via-teal-50 to-cyan-50",header:"from-emerald-400 via-teal-400 to-cyan-400",accent:"text-emerald-900",text:"text-emerald-800"},just_listed:{bg:"from-sky-50 via-blue-50 to-indigo-50",header:"from-sky-400 via-blue-400 to-indigo-400",accent:"text-blue-900",text:"text-blue-800"},thank_you:{bg:"from-rose-50 via-pink-50 to-red-50",header:"from-rose-400 via-pink-400 to-red-400",accent:"text-rose-900",text:"text-rose-800"},congratulations:{bg:"from-yellow-50 via-amber-50 to-orange-50",header:"from-yellow-400 via-amber-400 to-orange-400",accent:"text-amber-900",text:"text-amber-800"},holiday:{bg:"from-red-50 via-green-50 to-emerald-50",header:"from-red-500 via-green-500 to-emerald-500",accent:"text-green-900",text:"text-green-800"},thinking_of_you:{bg:"from-violet-50 via-purple-50 to-indigo-50",header:"from-violet-400 via-purple-400 to-indigo-400",accent:"text-violet-900",text:"text-violet-800"}};function r3t(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:a,agentName:c,agentPhotoUrl:d,agentPhone:p,agentEmail:l,agentBrokerage:g,propertyPhotoUrl:v,videoUrl:E}=t,T=pN[e],j=_me[e]||_me.home_anniversary;return s.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${j.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[T.emojis.map((P,C)=>s.jsx(t3t,{emoji:P,delay:C*1.2,x:`${15+C*14}%`,duration:5+C%3},C)),s.jsx(Sr.div,{className:"absolute top-1/4 left-1/2 -translate-x-1/2 w-96 h-96 bg-gradient-to-r from-amber-200/30 to-rose-200/30 rounded-full blur-[100px]",animate:{scale:[1,1.2,1],opacity:[.3,.5,.3]},transition:{duration:6,repeat:1/0,ease:"easeInOut"}}),s.jsxs(Sr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.7},children:[s.jsxs(Sr.div,{className:"bg-white rounded-3xl shadow-[0_20px_60px_-15px_rgba(251,146,60,0.2)] overflow-hidden border border-amber-100",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[s.jsxs(Sr.div,{className:`h-28 bg-gradient-to-r ${j.header} relative overflow-hidden`,children:[s.jsx(Sr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:3,repeat:1/0,repeatDelay:2,ease:"easeInOut"}}),s.jsx(Sr.div,{className:"absolute top-3 left-10 text-5xl",animate:{rotate:[0,10,-5,0],y:[0,-3,0]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:T.emojis[0]}),s.jsx(Sr.div,{className:"absolute top-2 right-14 text-3xl",animate:{scale:[1,1.3,1],rotate:[0,15,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut",delay:.5},children:T.emojis[1]}),s.jsx(Sr.div,{className:"absolute bottom-2 left-1/2 -translate-x-1/2 text-3xl",animate:{y:[0,-5,0],scale:[1,1.1,1]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut",delay:1},children:T.emojis[2]})]}),s.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[s.jsx(Sr.div,{className:"mx-auto mb-4 h-20 w-20 rounded-full bg-white shadow-xl flex items-center justify-center border-4 border-white relative",initial:{scale:0},animate:{scale:1},transition:{delay:.4,type:"spring",stiffness:300},children:s.jsx(Sr.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:s.jsx("span",{className:"text-3xl",children:T.icon})})}),e==="home_anniversary"&&i!==null&&i>0&&s.jsx(Sr.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:s.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${j.accent}`,children:[s.jsx(Sr.span,{className:"text-5xl font-black",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.8},children:i}),s.jsx("span",{className:"text-sm font-semibold",children:i===1?"year":"wonderful years"})]})}),s.jsxs(Sr.h1,{className:`text-3xl font-bold ${j.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[T.title.join(" ")," ",T.emojis[4]]}),s.jsxs(Sr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[s.jsx("p",{className:`text-lg font-semibold ${j.text} mb-1`,children:r}),n&&s.jsxs("p",{className:`text-sm ${j.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[s.jsx(Va,{className:"h-3 w-3"}),n]})]}),v&&s.jsx(Sr.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:s.jsx("img",{src:v,alt:"Property",className:"w-full h-48 object-cover"})}),E&&s.jsx(Sr.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:s.jsx("iframe",{src:`${E}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),s.jsx(Sr.div,{className:"bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-5 mb-6 border border-amber-100 shadow-inner",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:s.jsxs("p",{className:`text-sm ${j.text} leading-relaxed italic`,children:['"',a||T.defaultMessage,'"']})}),s.jsxs(Sr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[s.jsxs("div",{className:"flex items-center gap-3 justify-center",children:[d?s.jsx(Sr.img,{src:d,alt:c,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):s.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${j.header} flex items-center justify-center shadow-md`,children:s.jsx("span",{className:"text-sm font-bold text-white",children:c.charAt(0)})}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:`text-sm font-bold ${j.accent}`,children:c}),g&&s.jsx("p",{className:`text-xs ${j.text} opacity-60`,children:g})]})]}),s.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[p&&s.jsxs(Sr.a,{href:`tel:${p}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${j.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(Ui,{className:"h-3.5 w-3.5"})," Call"]}),l&&s.jsxs(Sr.a,{href:`mailto:${l}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${j.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(rs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),s.jsx(Sr.p,{className:"text-center text-[10px] text-amber-400 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function nM({delay:t,x:e,y:r,size:n,color:i}){return s.jsx(Sr.div,{className:`absolute rounded-full ${i} blur-3xl`,style:{left:e,top:r,width:n,height:n},animate:{scale:[1,1.3,1],opacity:[.4,.7,.4],x:[0,20,-10,0],y:[0,-15,10,0]},transition:{duration:8,delay:t,repeat:1/0,ease:"easeInOut"}})}function zV({delay:t,x:e,y:r,size:n}){return s.jsx(Sr.div,{className:"absolute rounded-full border border-white/10",style:{left:e,top:r,width:n,height:n},animate:{scale:[1,1.2,1],opacity:[.1,.3,.1],rotate:[0,180,360]},transition:{duration:12,delay:t,repeat:1/0,ease:"linear"}})}const vme={home_anniversary:{mesh:["bg-sky-400/40","bg-indigo-500/30","bg-violet-400/25"],accent:"text-sky-200",glow:"shadow-sky-500/20"},birthday:{mesh:["bg-pink-400/40","bg-fuchsia-500/30","bg-purple-400/25"],accent:"text-pink-200",glow:"shadow-pink-500/20"},just_sold:{mesh:["bg-emerald-400/40","bg-teal-500/30","bg-cyan-400/25"],accent:"text-emerald-200",glow:"shadow-emerald-500/20"},just_listed:{mesh:["bg-amber-400/40","bg-orange-500/30","bg-yellow-400/25"],accent:"text-amber-200",glow:"shadow-amber-500/20"},thank_you:{mesh:["bg-rose-400/40","bg-pink-500/30","bg-red-400/25"],accent:"text-rose-200",glow:"shadow-rose-500/20"},congratulations:{mesh:["bg-yellow-400/40","bg-amber-500/30","bg-orange-400/25"],accent:"text-yellow-200",glow:"shadow-yellow-500/20"},holiday:{mesh:["bg-red-400/40","bg-emerald-500/30","bg-green-400/25"],accent:"text-red-200",glow:"shadow-red-500/20"},thinking_of_you:{mesh:["bg-violet-400/40","bg-indigo-500/30","bg-blue-400/25"],accent:"text-violet-200",glow:"shadow-violet-500/20"}};function n3t(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:a,agentName:c,agentPhotoUrl:d,agentPhone:p,agentEmail:l,agentBrokerage:g,propertyPhotoUrl:v,videoUrl:E}=t,T=pN[e],j=vme[e]||vme.home_anniversary;return s.jsxs("div",{className:"min-h-screen bg-slate-950 flex items-center justify-center p-4 overflow-hidden relative",children:[s.jsx(nM,{delay:0,x:"5%",y:"10%",size:300,color:j.mesh[0]}),s.jsx(nM,{delay:2,x:"60%",y:"50%",size:250,color:j.mesh[1]}),s.jsx(nM,{delay:4,x:"30%",y:"70%",size:200,color:j.mesh[2]}),s.jsx(nM,{delay:1,x:"80%",y:"15%",size:180,color:j.mesh[0]}),s.jsx(zV,{delay:0,x:"15%",y:"20%",size:100}),s.jsx(zV,{delay:3,x:"70%",y:"60%",size:140}),s.jsx(zV,{delay:6,x:"40%",y:"10%",size:80}),s.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`}}),s.jsxs(Sr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.8,ease:[.16,1,.3,1]},children:[s.jsxs(Sr.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${j.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[s.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:s.jsx(Sr.div,{className:"absolute inset-0 bg-gradient-to-r from-transparent via-white/60 to-transparent",animate:{x:["-100%","200%"]},transition:{duration:4,repeat:1/0,repeatDelay:3,ease:"easeInOut"}})}),s.jsxs("div",{className:"px-8 py-10 text-center",children:[s.jsxs(Sr.div,{className:"mx-auto mb-6 h-24 w-24 rounded-3xl bg-white/[0.08] backdrop-blur-xl border border-white/[0.15] flex items-center justify-center relative",initial:{scale:0,rotate:-15},animate:{scale:1,rotate:0},transition:{duration:.6,delay:.4,type:"spring",stiffness:180},children:[s.jsx(Sr.div,{className:"absolute -inset-1 rounded-3xl border border-white/[0.08]",animate:{scale:[1,1.1,1],opacity:[.3,0,.3]},transition:{duration:3,repeat:1/0,ease:"easeInOut"}}),s.jsx(Sr.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:T.icon})]}),e==="home_anniversary"&&i!==null&&i>0&&s.jsxs(Sr.div,{className:"inline-flex items-center gap-2 mb-5 px-5 py-2 rounded-full bg-white/[0.06] border border-white/[0.1] backdrop-blur-sm",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:[s.jsx(Sr.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:i}),s.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${j.accent}`,children:i===1?"Year":"Years"})]}),s.jsx(Sr.h1,{className:"text-4xl font-extralight text-white/90 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.7},children:T.title[0]}),T.title[1]&&s.jsx(Sr.h2,{className:"text-4xl font-bold text-white mb-6 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.85},children:T.title[1]}),s.jsxs(Sr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[s.jsx("p",{className:"text-xl font-medium text-white/80 mb-1",children:r}),n&&s.jsxs("p",{className:"text-sm text-white/30 mb-6 flex items-center justify-center gap-1.5",children:[s.jsx(Va,{className:"h-3 w-3"})," ",n]})]}),s.jsx(Sr.div,{className:"h-px bg-gradient-to-r from-transparent via-white/15 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"70%"},transition:{duration:1,delay:1.1},style:{margin:"0 auto 1.5rem"}}),v&&s.jsx(Sr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:s.jsx("img",{src:v,alt:"Property",className:"w-full h-48 object-cover"})}),E&&s.jsx(Sr.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:s.jsx("iframe",{src:`${E}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),s.jsx(Sr.div,{className:"bg-white/[0.04] rounded-2xl p-5 border border-white/[0.08] mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:s.jsxs("p",{className:"text-sm text-white/60 leading-relaxed italic",children:['"',a||T.defaultMessage,'"']})}),s.jsxs(Sr.div,{className:"border-t border-white/[0.06] pt-6",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[s.jsxs("div",{className:"flex items-center justify-center gap-3",children:[d?s.jsx(Sr.img,{src:d,alt:c,className:"h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10",whileHover:{scale:1.08}}):s.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white/[0.08] border border-white/[0.1] flex items-center justify-center",children:s.jsx("span",{className:"text-sm font-semibold text-white/60",children:c.charAt(0)})}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-sm font-semibold text-white/80",children:c}),g&&s.jsx("p",{className:"text-xs text-white/30",children:g})]})]}),s.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[p&&s.jsxs(Sr.a,{href:`tel:${p}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(Ui,{className:"h-3.5 w-3.5"})," Call"]}),l&&s.jsxs(Sr.a,{href:`mailto:${l}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/70 hover:bg-white/[0.12] transition-colors backdrop-blur-sm",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(rs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),s.jsx(Sr.p,{className:"text-center text-[10px] text-white/20 mt-4",initial:{opacity:0},animate:{opacity:1},transition:{delay:2},children:"Powered by LevelUp"})]})]})}function $V({delay:t,x:e,angle:r,color:n}){return s.jsx(Sr.div,{className:`absolute h-[400px] w-[1px] ${n} origin-top`,style:{left:e,top:"-10%",transform:`rotate(${r}deg)`},animate:{opacity:[0,.4,0],scaleY:[.5,1,.5]},transition:{duration:6,delay:t,repeat:1/0,ease:"easeInOut"}})}function iM({delay:t,x:e}){return s.jsx(Sr.div,{className:"absolute w-1 h-1 rounded-full bg-amber-400/60",style:{left:e,bottom:"20%"},animate:{y:[0,-200,-400],x:[0,15,-10],opacity:[0,.8,0],scale:[0,1.5,0]},transition:{duration:4,delay:t,repeat:1/0,ease:"easeOut"}})}const bme={home_anniversary:{gradient:"from-slate-950 via-blue-950 to-slate-950",accent:"from-blue-400 to-cyan-300",stripe:"bg-blue-400/20"},birthday:{gradient:"from-slate-950 via-rose-950 to-slate-950",accent:"from-rose-400 to-pink-300",stripe:"bg-rose-400/20"},just_sold:{gradient:"from-slate-950 via-emerald-950 to-slate-950",accent:"from-emerald-400 to-green-300",stripe:"bg-emerald-400/20"},just_listed:{gradient:"from-slate-950 via-amber-950 to-slate-950",accent:"from-amber-400 to-yellow-300",stripe:"bg-amber-400/20"},thank_you:{gradient:"from-slate-950 via-pink-950 to-slate-950",accent:"from-pink-400 to-rose-300",stripe:"bg-pink-400/20"},congratulations:{gradient:"from-slate-950 via-yellow-950 to-slate-950",accent:"from-yellow-400 to-amber-300",stripe:"bg-yellow-400/20"},holiday:{gradient:"from-slate-950 via-red-950 to-slate-950",accent:"from-red-400 to-green-400",stripe:"bg-red-400/20"},thinking_of_you:{gradient:"from-slate-950 via-purple-950 to-slate-950",accent:"from-purple-400 to-violet-300",stripe:"bg-purple-400/20"}};function i3t(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:a,agentName:c,agentPhotoUrl:d,agentPhone:p,agentEmail:l,agentBrokerage:g,propertyPhotoUrl:v,videoUrl:E}=t,T=pN[e],j=bme[e]||bme.home_anniversary;return s.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${j.gradient} flex items-center justify-center p-4 overflow-hidden relative`,children:[s.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.04)_0%,transparent_60%)]"}),s.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom,rgba(0,0,0,0.6)_0%,transparent_60%)]"}),s.jsx($V,{delay:0,x:"20%",angle:15,color:j.stripe}),s.jsx($V,{delay:2,x:"75%",angle:-12,color:j.stripe}),s.jsx($V,{delay:4,x:"50%",angle:5,color:j.stripe}),s.jsx(iM,{delay:0,x:"30%"}),s.jsx(iM,{delay:1.5,x:"60%"}),s.jsx(iM,{delay:3,x:"45%"}),s.jsx(iM,{delay:.7,x:"75%"}),s.jsx("div",{className:"absolute inset-0 opacity-[0.015] mix-blend-overlay",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 512 512' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.7' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`}}),s.jsxs(Sr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[s.jsx(Sr.div,{className:"relative overflow-hidden",initial:{y:50},animate:{y:0},transition:{duration:.8,delay:.3,ease:[.16,1,.3,1]},children:s.jsxs("div",{className:"px-8 py-12 text-center",children:[s.jsx(Sr.div,{className:"mx-auto mb-8 relative",initial:{scale:0},animate:{scale:1},transition:{duration:.8,delay:.5,type:"spring",stiffness:100},children:s.jsx(Sr.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${j.accent} flex items-center justify-center shadow-2xl`,animate:{boxShadow:["0 0 40px rgba(255,255,255,0.05)","0 0 80px rgba(255,255,255,0.1)","0 0 40px rgba(255,255,255,0.05)"]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:s.jsx("span",{className:"text-4xl",children:T.icon})})}),e==="home_anniversary"&&i!==null&&i>0&&s.jsxs(Sr.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[s.jsx(Sr.span,{className:`text-6xl font-black bg-gradient-to-r ${j.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:i}),s.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:i===1?"Year":"Years"})]}),s.jsx("div",{className:"overflow-hidden mb-2",children:s.jsx(Sr.h1,{className:"text-5xl font-thin text-white/90 tracking-wide",initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.8,ease:[.16,1,.3,1]},children:T.title[0]})}),T.title[1]&&s.jsx("div",{className:"overflow-hidden mb-8",children:s.jsx(Sr.h2,{className:`text-5xl font-black bg-gradient-to-r ${j.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:T.title[1]})}),s.jsxs(Sr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.1,duration:.6},children:[s.jsx("p",{className:"text-lg font-light text-white/70 tracking-wide",children:r}),n&&s.jsxs("p",{className:"text-xs text-white/25 mt-1 flex items-center justify-center gap-1",children:[s.jsx(Va,{className:"h-3 w-3"})," ",n]})]}),s.jsxs(Sr.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[s.jsx(Sr.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-r from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"right"}}),s.jsx(Sr.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),s.jsx(Sr.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-l from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"left"}})]}),v&&s.jsxs(Sr.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.3,duration:.6},children:[s.jsx("img",{src:v,alt:"Property",className:"w-full h-48 object-cover"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-950/30 to-transparent pointer-events-none"})]}),E&&s.jsx(Sr.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.35,duration:.6},children:s.jsx("iframe",{src:`${E}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),s.jsx(Sr.p,{className:"text-sm text-white/40 leading-relaxed max-w-xs mx-auto mb-10 font-light",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.4,duration:.8},children:a||T.defaultMessage}),s.jsxs(Sr.div,{className:"pt-6 border-t border-white/[0.04]",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{delay:1.6,duration:.6},children:[s.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[d?s.jsx(Sr.img,{src:d,alt:c,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):s.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${j.accent} flex items-center justify-center shadow-xl`,children:s.jsx("span",{className:"text-sm font-bold text-slate-900",children:c.charAt(0)})}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-sm font-medium text-white/70",children:c}),g&&s.jsx("p",{className:"text-[11px] text-white/25",children:g})]})]}),s.jsxs("div",{className:"flex items-center justify-center gap-2",children:[p&&s.jsxs(Sr.a,{href:`tel:${p}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${j.accent} text-xs font-semibold text-slate-900 shadow-lg`,whileHover:{scale:1.05,boxShadow:"0 10px 40px rgba(255,255,255,0.15)"},whileTap:{scale:.95},children:[s.jsx(Ui,{className:"h-3.5 w-3.5"})," Call"]}),l&&s.jsxs(Sr.a,{href:`mailto:${l}`,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-white/[0.06] border border-white/[0.1] text-xs font-medium text-white/60 hover:bg-white/[0.12] transition-colors",whileHover:{scale:1.05},whileTap:{scale:.95},children:[s.jsx(rs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),s.jsx(Sr.p,{className:"text-center text-[10px] text-white/10 mt-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:2.2},children:"Powered by LevelUp"})]})]})}function hCe(){const{shareToken:t}=Sg(),{data:e,isLoading:r,error:n}=jr({queryKey:["public-sendable-card",t],queryFn:async()=>{const{data:c,error:d}=await Be.from("sendable_cards").select("*").eq("share_token",t).single();if(d)throw d;return c},enabled:!!t});if(N.useEffect(()=>{if(!e)return;const c=(e.recipient_name||"").trim().split(/\s+/)[0],p={home_anniversary:"Happy Home Anniversary",birthday:"Happy Birthday",wedding_anniversary:"Happy Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",holiday:"Happy Holidays",thank_you:"Thank You",thinking_of_you:"Thinking of You"}[e.card_type]||"A card for you";document.title=c?`${p}, ${c}!`:`${p}!`},[e]),N.useEffect(()=>{t&&Be.rpc("log_sendable_card_view",{p_share_token:t}).then(({error:c})=>{c&&console.error("Error tracking view:",c)})},[t]),r)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:s.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[s.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),s.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(n||!e)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),s.jsx("p",{className:"text-muted-foreground",children:"This card may have been removed or the link is invalid."})]})});const i=e.home_anniversary_date?Math.floor((Date.now()-_T(e.home_anniversary_date).getTime())/(365.25*24*60*60*1e3)):null,a={cardType:e.card_type||"home_anniversary",recipientName:e.recipient_name,propertyAddress:e.property_address,anniversaryYears:i,customMessage:e.custom_message,agentName:e.agent_name,agentPhotoUrl:e.agent_photo_url,agentPhone:e.agent_phone,agentEmail:e.agent_email,agentBrokerage:e.agent_brokerage,propertyPhotoUrl:e.property_photo_url,videoUrl:e.video_url||null};switch(e.template){case"bold":return s.jsx(e3t,{...a});case"warm":return s.jsx(r3t,{...a});case"glass":return s.jsx(n3t,{...a});case"cinematic":return s.jsx(i3t,{...a});case"elegant":default:return s.jsx(JFt,{...a})}}const s3t=Object.freeze(Object.defineProperty({__proto__:null,default:hCe},Symbol.toStringTag,{value:"Module"})),fCe=()=>{const t=ms();return N.useEffect(()=>{if(/[?&]authorization_id=/.test(t.search)||t.pathname.startsWith("/oauth")){window.location.replace(`https://dashboard.relevelup.com/oauth-connect${t.search}`);return}console.error("404 Error: User attempted to access non-existent route:",t.pathname)},[t.pathname,t.search]),s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),s.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),s.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})};function a3t(){return N.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),s.jsxs(kb,{children:[s.jsx(Ce,{path:"/c/:shareToken",element:s.jsx(hCe,{})}),s.jsx(Ce,{path:"*",element:s.jsx(fCe,{})})]})}function o3t(t,e){return e?t.find(r=>r.id===e)??null:null}const UV={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"},l3t=["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","America/Anchorage","Pacific/Honolulu","Europe/London","Europe/Paris","Asia/Dubai","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];function c3t(t,e,r){const[n,i,a]=t.split("-").map(Number),[c,d]=e.split(":").map(Number),p=Date.UTC(n,i-1,a,c,d),l=new Intl.DateTimeFormat("en-US",{timeZone:r,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),g=Object.fromEntries(l.formatToParts(new Date(p)).filter(E=>E.type!=="literal").map(E=>[E.type,E.value])),v=Date.UTC(Number(g.year),Number(g.month)-1,Number(g.day),Number(g.hour)%24,Number(g.minute));return p+(p-v)}function VV(t){var e;try{return((e=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"short"}).formatToParts(new Date).find(n=>n.type==="timeZoneName"))==null?void 0:e.value)||t}catch{return t}}function mCe({slugOverride:t}){const e=Sg(),r=t||e.slug,[n]=zv(),i=n.get("type"),[a,c]=N.useState("types"),[d,p]=N.useState(null),[l,g]=N.useState(null),[v,E]=N.useState(null),[T,j]=N.useState(new Date),[P,C]=N.useState({name:"",email:"",phone:"",message:""}),[L,O]=N.useState(!1),[F,$]=N.useState(null),[G,W]=N.useState(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"America/New_York"}catch{return"America/New_York"}}),{data:Z,isLoading:Q}=jr({queryKey:["public-booking-settings",r],queryFn:async()=>{const{data:Ae,error:He}=await Be.from("agent_booking_settings").select("*").eq("slug",r).eq("is_active",!0).single();if(He)throw He;return Ae},enabled:!!r}),{data:ee}=jr({queryKey:["public-booking-profile",Z==null?void 0:Z.user_id],queryFn:async()=>{const{data:Ae,error:He}=await Be.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",Z.user_id).single();if(He)throw He;return Ae},enabled:!!(Z!=null&&Z.user_id)}),{data:ie=[]}=jr({queryKey:["public-booking-types",Z==null?void 0:Z.user_id],queryFn:async()=>{const{data:Ae,error:He}=await Be.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",Z.user_id).eq("is_active",!0).eq("is_coaching_only",!1).order("sort_order");if(He)throw He;return Ae},enabled:!!(Z!=null&&Z.user_id)});N.useEffect(()=>{if(!i||d||ie.length===0)return;const Ae=o3t(ie,i);Ae&&(p(Ae),c("date"))},[i,ie,d]);const oe=ds(T,"yyyy-MM"),{data:pe={},isFetching:Le}=jr({queryKey:["public-availability-map",r,d==null?void 0:d.id,oe],enabled:!!r&&!!d,staleTime:6e4,queryFn:async()=>{const Ae=new Date(T.getFullYear(),T.getMonth(),1),He=Ev(new Date),ot=lC(He,Ae)?He:Ae,nt=new Date(T.getFullYear(),T.getMonth()+1,0),tt=Math.max(1,Math.round((nt.getTime()-ot.getTime())/864e5)+1),{data:vt,error:Vt}=await Be.functions.invoke("agent-booking",{body:{action:"availability",slug:r,booking_type_id:d.id,start:ds(ot,"yyyy-MM-dd"),days:Math.min(tt,90)}});if(Vt)throw Vt;if(vt!=null&&vt.error)throw new Error(vt.error);return(vt==null?void 0:vt.availability)||{}}}),be=Ae=>{const He=Ev(new Date),ot=tu(He,(Z==null?void 0:Z.max_advance_days)||30);return OY(Ae,He)||lC(Ae,ot)?!1:(pe[ds(Ae,"yyyy-MM-dd")]||[]).length>0},Re=N.useMemo(()=>l?pe[ds(l,"yyyy-MM-dd")]||[]:[],[l,pe]),Ie=N.useMemo(()=>{const Ae=T.getFullYear(),He=T.getMonth(),ot=new Date(Ae,He,1),nt=new Date(Ae,He+1,0),tt=ot.getDay(),vt=[];for(let Vt=0;Vt{var Ae,He;if(!(!d||!l||!v||!P.name||!Z)){O(!0);try{const ot=ds(l,"yyyy-MM-dd"),{data:nt,error:tt}=await Be.functions.invoke("agent-booking",{body:{action:"create",slug:r,booking_type_id:d.id,date:ot,time:v,guest_name:P.name,guest_email:P.email||null,guest_phone:P.phone||null,guest_message:P.message||null,guest_timezone:G}});if(tt){let Ct=tt.message;try{const Bt=await((He=(Ae=tt.context)==null?void 0:Ae.json)==null?void 0:He.call(Ae));Bt!=null&&Bt.error&&(Ct=Bt.error)}catch{}throw new Error(Ct)}if(nt!=null&&nt.error)throw new Error(nt.error);const vt=(nt==null?void 0:nt.end_time)||v,Vt=nt!=null&&nt.manage_token?`${window.location.origin}/booking/manage/${nt.manage_token}`:null;$(Vt),Be.functions.invoke("booking-notify",{body:{agentUserId:Z.user_id,guestName:P.name,guestEmail:P.email||null,guestPhone:P.phone||null,guestMessage:P.message||null,bookingTypeName:d.name,bookingDate:ot,startTime:v,endTime:vt,durationMinutes:d.duration_minutes,meetingLink:Z.meeting_link||null,manageUrl:Vt}}).catch(Ct=>console.error("Booking notify error:",Ct)),c("confirmed")}catch(ot){lr.error("Failed to book: "+ot.message)}finally{O(!1)}}},ge=Ae=>{const[He,ot]=Ae.split(":").map(Number),nt=He>=12?"PM":"AM";return`${He%12||12}:${ot.toString().padStart(2,"0")} ${nt}`},$e=(Z==null?void 0:Z.timezone)||"America/New_York",we=G!==$e,ke=(Ae,He)=>{if(!we)return ge(He);try{return new Intl.DateTimeFormat("en-US",{timeZone:G,hour:"numeric",minute:"2-digit"}).format(new Date(c3t(Ae,He,$e)))}catch{return ge(He)}};return Q?s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center",children:s.jsxs("div",{className:"flex flex-col items-center gap-3",children:[s.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[#406E71] border-t-transparent"}),s.jsx("p",{className:"text-sm text-slate-500",children:"Loading booking page..."})]})}):Z?s.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8]",children:[s.jsx("div",{className:"h-1.5 bg-gradient-to-r from-[#406E71] via-[#5a9a9d] to-[#2a4c64]"}),s.jsxs("div",{className:"max-w-lg mx-auto px-4 py-6 sm:py-10",children:[s.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden mb-6",children:[s.jsx("div",{className:"relative bg-gradient-to-r from-[#406E71] to-[#2a4c64] px-6 pt-6 pb-12",children:s.jsxs("div",{className:"absolute inset-0 opacity-10",children:[s.jsx("div",{className:"absolute top-2 right-8 w-20 h-20 rounded-full border-2 border-white/30"}),s.jsx("div",{className:"absolute bottom-4 left-12 w-10 h-10 rounded-full border border-white/20"})]})}),s.jsx("div",{className:"relative -mt-10 px-6",children:s.jsxs("div",{className:"flex items-end gap-4",children:[ee!=null&&ee.avatar_url?s.jsx("img",{src:ee.avatar_url,alt:(ee==null?void 0:ee.name)||"Agent",className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl object-cover border-4 border-white shadow-md"}):s.jsx("div",{className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl bg-gradient-to-br from-[#406E71] to-[#2a4c64] border-4 border-white shadow-md flex items-center justify-center",children:s.jsx(nd,{className:"h-10 w-10 text-white"})}),s.jsxs("div",{className:"pb-1.5",children:[s.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-slate-800 leading-tight",children:(ee==null?void 0:ee.name)||"Agent"}),(ee==null?void 0:ee.title)&&s.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:ee.title})]})]})}),s.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(ee==null?void 0:ee.phone)&&s.jsxs("a",{href:`tel:${ee.phone}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#406E71]/8 hover:bg-[#406E71]/15 text-[#406E71] text-xs font-medium transition-colors",children:[s.jsx(Ui,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"hidden sm:inline",children:ee.phone}),s.jsx("span",{className:"sm:hidden",children:"Call"})]}),(ee==null?void 0:ee.email)&&s.jsxs("a",{href:`mailto:${ee.email}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#2a4c64]/8 hover:bg-[#2a4c64]/15 text-[#2a4c64] text-xs font-medium transition-colors",children:[s.jsx(rs,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"hidden sm:inline",children:ee.email}),s.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),s.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:s.jsxs("div",{className:"p-5 sm:p-6",children:[a==="types"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),s.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),s.jsx("div",{className:"space-y-2.5",children:ie.map(Ae=>s.jsx("button",{onClick:()=>{p(Ae),c("date")},className:"w-full text-left group",children:s.jsx("div",{className:"relative rounded-xl border border-slate-150 p-4 transition-all duration-200 hover:shadow-md hover:border-[#406E71]/30 hover:-translate-y-0.5 active:translate-y-0",style:{borderLeftWidth:"3px",borderLeftColor:Ae.color},children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[s.jsx("span",{className:"text-2xl shrink-0 mt-0.5",children:UV[Ae.icon]||"📅"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:"font-semibold text-sm text-slate-800 group-hover:text-[#406E71] transition-colors",children:Ae.name}),Ae.description&&s.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:Ae.description})]})]}),s.jsxs("div",{className:"shrink-0 flex items-center gap-1 px-2.5 py-1 rounded-full bg-slate-100 text-slate-600 text-xs font-medium",children:[s.jsx(su,{className:"h-3 w-3"}),Ae.duration_minutes,"m"]})]})})},Ae.id))})]}),a==="date"&&d&&s.jsxs("div",{className:"space-y-5",children:[s.jsxs("button",{onClick:()=>{c("types"),g(null),E(null)},className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[s.jsx(yv,{className:"h-3.5 w-3.5"})," Back to meeting types"]}),s.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl border",style:{borderColor:d.color+"40",backgroundColor:d.color+"08"},children:[s.jsx("span",{className:"text-xl",children:UV[d.icon]||"📅"}),s.jsx("div",{className:"flex-1 min-w-0",children:s.jsx("p",{className:"font-semibold text-sm text-slate-800",children:d.name})}),s.jsxs("div",{className:"flex items-center gap-1 text-xs text-slate-500 font-medium",children:[s.jsx(su,{className:"h-3 w-3"}),d.duration_minutes," min"]})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:ds(T,"MMMM yyyy")}),s.jsxs("div",{className:"flex gap-1",children:[s.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>j(new Date(T.getFullYear(),T.getMonth()-1)),children:s.jsx(bg,{className:"h-4 w-4"})}),s.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>j(new Date(T.getFullYear(),T.getMonth()+1)),children:s.jsx(uf,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"grid grid-cols-7 gap-0.5 text-center",children:[["Su","Mo","Tu","We","Th","Fr","Sa"].map(Ae=>s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:Ae},Ae)),Ie.map((Ae,He)=>{if(!Ae)return s.jsx("div",{},`pad-${He}`);const ot=be(Ae),nt=l&&Fu(Ae,l),tt=Fu(Ae,new Date);return s.jsx("button",{disabled:!ot,onClick:()=>{g(Ae),E(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${nt?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":ot?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${tt&&!nt?"ring-1 ring-[#406E71]/40":""}`,children:Ae.getDate()},Ae.toISOString())})]})]}),l&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ig,{className:"h-4 w-4 text-[#406E71]"}),s.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:ds(l,"EEEE, MMMM d")})]}),s.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl bg-slate-50 border border-slate-100 px-3 py-2",children:[s.jsx("span",{className:"text-[11px] text-slate-500",children:"Times shown in your timezone"}),s.jsx("select",{value:G,onChange:Ae=>W(Ae.target.value),className:"text-[11px] font-medium text-slate-700 bg-transparent focus:outline-none cursor-pointer",children:Array.from(new Set([G,$e,...l3t])).map(Ae=>s.jsxs("option",{value:Ae,children:[Ae.replace(/_/g," ")," (",VV(Ae),")"]},Ae))})]}),Le&&Re.length===0?s.jsxs("div",{className:"text-center py-8 space-y-2",children:[s.jsx(gh,{className:"h-6 w-6 text-slate-300 mx-auto animate-spin"}),s.jsx("p",{className:"text-sm text-slate-400",children:"Checking live availability…"})]}):Re.length===0?s.jsxs("div",{className:"text-center py-8 space-y-2",children:[s.jsx(su,{className:"h-8 w-8 text-slate-300 mx-auto"}),s.jsx("p",{className:"text-sm text-slate-400",children:"No available times on this day"}),s.jsx("p",{className:"text-xs text-slate-400",children:"Try selecting a different date"})]}):s.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-52 overflow-y-auto pr-1 custom-scrollbar",children:Re.map(Ae=>{const He=v===Ae;return s.jsx("button",{onClick:()=>E(Ae),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${He?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-[1.02]":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10 hover:text-[#406E71] border border-slate-150"}`,children:ke(ds(l,"yyyy-MM-dd"),Ae)},Ae)})}),v&&s.jsx(Jt,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg",onClick:()=>c("form"),children:"Continue to Details"})]})]}),a==="form"&&d&&l&&v&&s.jsxs("div",{className:"space-y-5",children:[s.jsxs("button",{onClick:()=>c("date"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[s.jsx(yv,{className:"h-3.5 w-3.5"})," Back"]}),s.jsxs("div",{className:"rounded-xl bg-gradient-to-r from-[#406E71]/5 to-[#2a4c64]/5 border border-[#406E71]/15 p-4 space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-lg",children:UV[d.icon]||"📅"}),s.jsx("p",{className:"font-semibold text-sm text-slate-800",children:d.name})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-600",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ig,{className:"h-3.5 w-3.5 text-[#406E71]"}),ds(l,"EEE, MMM d, yyyy")]}),s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(su,{className:"h-3.5 w-3.5 text-[#406E71]"}),ke(ds(l,"yyyy-MM-dd"),v)," (",VV(G),") · ",d.duration_minutes," min"]})]})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),s.jsx(hn,{value:P.name,onChange:Ae=>C({...P,name:Ae.target.value}),placeholder:"Jane Smith",className:"h-11 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{className:"text-xs font-semibold text-slate-700",children:"Email"}),s.jsxs("div",{className:"relative",children:[s.jsx(rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),s.jsx(hn,{type:"email",value:P.email,onChange:Ae=>C({...P,email:Ae.target.value}),placeholder:"jane@email.com",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),s.jsxs("div",{className:"relative",children:[s.jsx(Ui,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),s.jsx(hn,{type:"tel",value:P.phone,onChange:Ae=>C({...P,phone:Ae.target.value}),placeholder:"(555) 123-4567",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]})]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(sn,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),s.jsx(df,{value:P.message,onChange:Ae=>C({...P,message:Ae.target.value}),placeholder:"Anything you'd like the agent to know ahead of time?",rows:3,className:"rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20 resize-none"})]})]}),s.jsx(Jt,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg disabled:opacity-60",onClick:Te,disabled:!P.name||L,children:L?s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"}),"Booking..."]}):"Confirm Booking"})]}),a==="confirmed"&&s.jsxs("div",{className:"text-center space-y-5 py-6",children:[s.jsxs("div",{className:"relative mx-auto w-20 h-20",children:[s.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping opacity-30"}),s.jsx("div",{className:"relative w-20 h-20 rounded-full bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-200",children:s.jsx(od,{className:"h-10 w-10 text-white"})})]}),s.jsxs("div",{children:[s.jsx("h2",{className:"text-2xl font-bold text-slate-800",children:"You're booked!"}),s.jsxs("p",{className:"text-slate-500 mt-1.5",children:[d==null?void 0:d.name," with ",(ee==null?void 0:ee.name)||"your agent"]})]}),s.jsx("div",{className:"inline-flex items-center gap-3 px-5 py-3 rounded-xl bg-slate-50 border border-slate-100",children:s.jsxs("div",{className:"text-left text-sm",children:[s.jsx("p",{className:"font-semibold text-slate-800",children:l&&ds(l,"EEEE, MMMM d, yyyy")}),s.jsxs("p",{className:"text-slate-500",children:[l&&v?`${ke(ds(l,"yyyy-MM-dd"),v)} (${VV(G)})`:""," · ",d==null?void 0:d.duration_minutes," min"]})]})}),s.jsx("p",{className:"text-sm text-slate-400 max-w-xs mx-auto",children:"A confirmation with meeting details will be sent to you shortly."}),F&&s.jsx("div",{className:"pt-1",children:s.jsx("a",{href:F,className:"inline-flex items-center gap-1.5 text-xs font-semibold text-[#406E71] underline underline-offset-4",children:"Reschedule or cancel this meeting"})}),((ee==null?void 0:ee.phone)||(ee==null?void 0:ee.email))&&s.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[s.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wider font-semibold",children:"Contact"}),s.jsxs("div",{className:"flex gap-3",children:[(ee==null?void 0:ee.phone)&&s.jsxs("a",{href:`tel:${ee.phone}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#406E71]/10 text-[#406E71] text-xs font-medium hover:bg-[#406E71]/20 transition-colors",children:[s.jsx(Ui,{className:"h-3.5 w-3.5"})," Call"]}),(ee==null?void 0:ee.email)&&s.jsxs("a",{href:`mailto:${ee.email}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#2a4c64]/10 text-[#2a4c64] text-xs font-medium hover:bg-[#2a4c64]/20 transition-colors",children:[s.jsx(rs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]})}),s.jsx("p",{className:"text-center text-[10px] text-slate-300 mt-6 font-medium tracking-wide uppercase",children:"Powered by LevelUp"})]})]}):s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center p-4",children:s.jsxs("div",{className:"max-w-sm w-full text-center space-y-4",children:[s.jsx("div",{className:"mx-auto w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center",children:s.jsx(ig,{className:"h-8 w-8 text-slate-400"})}),s.jsx("h2",{className:"text-lg font-semibold text-slate-700",children:"Page Not Available"}),s.jsx("p",{className:"text-sm text-slate-500",children:"This booking page doesn't exist or is currently inactive."})]})})}const u3t=Object.freeze(Object.defineProperty({__proto__:null,default:mCe},Symbol.toStringTag,{value:"Module"}));function d3t(){const e=ms().pathname.slice(1).split("/")[0];return N.useEffect(()=>{document.body.classList.add("booking-page");const r=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(a=>{document.querySelectorAll(a).forEach(c=>{c.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("booking-page"),n.forEach(clearTimeout)}},[]),e?s.jsx(mCe,{slugOverride:e}):s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-950 dark:to-slate-900 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Scheduler"}),s.jsx("p",{className:"text-muted-foreground",children:"Visit a specific agent's booking URL to schedule a meeting."})]})})}const h3t="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",f3t="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",m3t="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",p3t="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",g3t="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",y3t="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",qV={"minimal-mono":{key:"minimal-mono",label:"Minimal Mono",description:"Clean paper white, restrained.",bg:"#f7f7f5",surface:"#ffffff",border:"#e6e5e0",text:"#111111",textMuted:"#6b6b6b",accent:"#111111",accentText:"#ffffff",headingFont:'"Fraunces", ui-serif, Georgia, serif',bodyFont:'"Inter", system-ui, sans-serif',swatch:["#f7f7f5","#111111","#6b6b6b","#e6e5e0"],defaultCover:y3t},"warm-coastal":{key:"warm-coastal",label:"Warm Coastal",description:"Sand and soft teal.",bg:"linear-gradient(180deg,#faf6ef 0%,#f2ece1 100%)",surface:"#ffffff",border:"#e6dfd1",text:"#2b2a26",textMuted:"#7a746a",accent:"#2f7a7d",accentText:"#ffffff",headingFont:'"Cormorant Garamond", ui-serif, Georgia, serif',bodyFont:'"Karla", system-ui, sans-serif',swatch:["#faf6ef","#2f7a7d","#c9b99a","#2b2a26"],defaultCover:h3t},"deep-luxe":{key:"deep-luxe",label:"Deep Luxe",description:"Charcoal with gold.",bg:"linear-gradient(180deg,#161616 0%,#0d0d0d 100%)",surface:"#1e1e1e",border:"#2c2c2c",text:"#f5f0e0",textMuted:"#a49a80",accent:"#c9a84c",accentText:"#111111",headingFont:'"Instrument Serif", ui-serif, Georgia, serif',bodyFont:'"Work Sans", system-ui, sans-serif',swatch:["#0d0d0d","#c9a84c","#f5f0e0","#2c2c2c"],defaultCover:f3t},sunset:{key:"sunset",label:"Sunset",description:"Peach into magenta.",bg:"linear-gradient(160deg,#ffe4d1 0%,#ffc9b0 40%,#f2a1c5 100%)",surface:"#ffffff",border:"#f6d5ce",text:"#2a1a2f",textMuted:"#7a5a70",accent:"#d84a7a",accentText:"#ffffff",headingFont:'"Sora", system-ui, sans-serif',bodyFont:'"Manrope", system-ui, sans-serif',swatch:["#ffe4d1","#ffc9b0","#f2a1c5","#d84a7a"],defaultCover:m3t},editorial:{key:"editorial",label:"Editorial",description:"Ink black on paper white.",bg:"#f5f3ee",surface:"#ffffff",border:"#d9d6ce",text:"#0d0d0d",textMuted:"#5a564d",accent:"#0d0d0d",accentText:"#f5f3ee",headingFont:'"DM Serif Display", ui-serif, Georgia, serif',bodyFont:'"Fira Sans", system-ui, sans-serif',swatch:["#f5f3ee","#0d0d0d","#d9d6ce","#5a564d"],defaultCover:p3t},playful:{key:"playful",label:"Playful",description:"Blush and lavender.",bg:"linear-gradient(180deg,#fdf3f7 0%,#efe5ff 100%)",surface:"#ffffff",border:"#ecd7e6",text:"#3a2450",textMuted:"#7c6a94",accent:"#9b72cf",accentText:"#ffffff",headingFont:'"Outfit", system-ui, sans-serif',bodyFont:'"Figtree", system-ui, sans-serif',swatch:["#fdf3f7","#efe5ff","#c9a0dc","#9b72cf"],defaultCover:g3t}},qXt=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function x3t(t){return t&&t in qV?qV[t]:qV["minimal-mono"]}function _3t(t,e){const r=e||t.accent;return{background:t.bg,color:t.text,fontFamily:t.bodyFont,"--c-bg":t.bg,"--c-surface":t.surface,"--c-border":t.border,"--c-text":t.text,"--c-text-muted":t.textMuted,"--c-accent":r,"--c-accent-text":t.accentText,"--c-heading-font":t.headingFont,"--c-body-font":t.bodyFont}}function pCe({slugOverride:t}={}){var Da;const{slug:e}=Sg(),r=t||e,[n]=zv(),i=n.get("t"),[a,c]=N.useState(!0),[d,p]=N.useState(null),[l,g]=N.useState(null),v=N.useRef(null),E=N.useRef(null),[T,j]=N.useState(null),[P,C]=N.useState(null),[L,O]=N.useState(!1),[F,$]=N.useState(!1),[G,W]=N.useState(0),[Z,Q]=N.useState(!1),[ee,ie]=N.useState(""),[oe,pe]=N.useState(""),[Le,be]=N.useState(""),[Re,Ie]=N.useState(""),[Te,ge]=N.useState(""),[$e,we]=N.useState(""),[ke,Ae]=N.useState(""),[He,ot]=N.useState(""),[nt,tt]=N.useState(""),[vt,Vt]=N.useState(""),[Ct,Bt]=N.useState(""),[cr,ft]=N.useState(""),[Kt,ir]=N.useState(""),[Gr,tr]=N.useState([]),[Qt,zt]=N.useState([]),[Vr,Jr]=N.useState(""),[Fn,Ar]=N.useState(""),[Tn,mn]=N.useState(""),[li,Lr]=N.useState([]);N.useEffect(()=>{Or()},[r,i]);const Or=async()=>{if(!r)return;c(!0);const{data:pn,error:Vi}=await Be.from("contact_intake_pages").select("*").eq("slug",r).eq("is_active",!0).maybeSingle();if(Vi||!pn){Q(!0),c(!1);return}g(pn),E.current=pn;const{data:Yi}=await Be.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",pn.user_id).single();if(Yi){let nn;if(Yi.brokerage_id){const{data:yt}=await Be.from("brokerages").select("name").eq("id",Yi.brokerage_id).single();nn=(yt==null?void 0:yt.name)||void 0}let Ke=Yi.avatar_url||null;if(!Ke){const{data:yt}=Be.storage.from("avatars").getPublicUrl(`${pn.user_id}/avatar.jpg`);yt!=null&&yt.publicUrl&&(Ke=`${yt.publicUrl}?t=${Date.now()}`)}const at={...Yi,avatar_url:Ke,brokerage_name:nn};p(at),v.current=at}if(i)try{console.log("[ConnectPage] Resolving token:",i,"for page:",pn.id);const{data:nn,error:Ke}=await Be.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:i,page_id:pn.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:nn,resolveErr:Ke}),!Ke&&(nn!=null&&nn.contact_id)){C(nn.contact_id);const at=nn.contact;at&&(j(at),ie(at.first_name||""),pe(at.last_name||""),be(at.email||""),Ie(at.phone||""),ge(at.address||""),we(at.city||""),Ae(at.state||""),ot(at.zip||""),tt(at.birthday||""),Vt(at.home_anniversary||""))}}catch(nn){console.error("Failed to resolve token:",nn)}c(!1)},si=async()=>{var pn,Vi;if(!ee.trim()){lr.error("Please enter your first name");return}if(!r){lr.error("Invalid page. Please refresh.");return}$(!0);try{let Yi=(pn=E.current)==null?void 0:pn.id,nn=(Vi=E.current)==null?void 0:Vi.user_id;if(!Yi||!nn){const{data:yt}=await Be.from("contact_intake_pages").select("id, user_id").eq("slug",r).eq("is_active",!0).maybeSingle();if(!yt){lr.error("This page is no longer active. Please contact the agent directly."),$(!1);return}Yi=yt.id,nn=yt.user_id}const Ke={intake_page_id:Yi,agent_user_id:nn,existing_contact_id:P,first_name:ee.trim(),last_name:oe.trim()||null,email:Le.trim()||null,phone:Re.trim()||null,address:Te.trim()||null,city:$e.trim()||null,state:ke.trim()||null,zip:He.trim()||null,birthday:nt||null,home_anniversary:vt||null,real_estate_interest:Ct||null,message:cr.trim()||null,life_events:{spouse_name:Kt.trim()||null,kids:Gr.filter(yt=>yt.name.trim()),pets:Qt.filter(yt=>yt.name.trim()),favorite_spots:Vr.trim()||null,dream_neighborhood:Fn.trim()||null,wedding_anniversary:Tn||null},referrals:li.filter(yt=>yt.name.trim()&&yt.contact.trim())},{error:at}=await Be.from("contact_intake_submissions").insert(Ke);if(console.log("[ConnectPage] Insert result:",{error:at}),at)throw at;i&&await Be.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",i);try{const yt=[ee.trim(),oe.trim()].filter(Boolean).join(" ");await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/connect-page-notify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentUserId:nn,contactName:yt,contactEmail:Le.trim()||null,contactPhone:Re.trim()||null,slug:r})})}catch(yt){console.warn("Connect page notification failed (non-blocking):",yt)}O(!0)}catch(Yi){console.error(Yi),lr.error("Something went wrong. Please try again.")}finally{$(!1)}};if(a)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:s.jsx(gh,{className:"h-8 w-8 animate-spin text-slate-400"})});if(Z)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:s.jsxs("div",{className:"text-center space-y-3",children:[s.jsx("h1",{className:"text-2xl font-semibold text-slate-700",children:"Page Not Found"}),s.jsx("p",{className:"text-slate-500",children:"This connect page doesn't exist or is no longer active."})]})});if(L)return s.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50 p-4",children:[s.jsx(mc,{children:s.jsxs("title",{children:["Thank You | ",d==null?void 0:d.name]})}),s.jsxs(Sr.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"max-w-md w-full text-center space-y-6 p-8",children:[s.jsx(Sr.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",delay:.2},className:"mx-auto w-20 h-20 rounded-full bg-emerald-100 flex items-center justify-center",children:s.jsx(od,{className:"h-10 w-10 text-emerald-600"})}),s.jsx("h1",{className:"text-3xl font-bold text-slate-800",children:"Thank You!"}),s.jsxs("p",{className:"text-lg text-slate-600",children:[d==null?void 0:d.name," has received your info and will be in touch soon."]}),s.jsxs("div",{className:"flex items-center justify-center gap-1 text-sm text-slate-400 pt-4",children:[s.jsx(cg,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const ss=!!i&&!!T,ps=(l==null?void 0:l.show_little_things)??!0,Mi=[{title:ss?"Confirm Your Info":"Let's Get Connected",fields:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"First Name *"}),s.jsx("input",{type:"text",value:ee,onChange:pn=>ie(pn.target.value),placeholder:"Jane",className:"connect-input",required:!0})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Last Name"}),s.jsx("input",{type:"text",value:oe,onChange:pn=>pe(pn.target.value),placeholder:"Smith",className:"connect-input"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Email"}),s.jsx("input",{type:"email",value:Le,onChange:pn=>be(pn.target.value),placeholder:"jane@email.com",className:"connect-input"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Phone"}),s.jsx("input",{type:"tel",value:Re,onChange:pn=>Ie(pn.target.value),placeholder:"(555) 123-4567",className:"connect-input"})]})]})},{title:"A Little More About You",fields:s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Street Address"}),s.jsx("input",{type:"text",value:Te,onChange:pn=>ge(pn.target.value),placeholder:"123 Main St",className:"connect-input"})]}),s.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[s.jsxs("div",{className:"col-span-2",children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"City"}),s.jsx("input",{type:"text",value:$e,onChange:pn=>we(pn.target.value),placeholder:"Austin",className:"connect-input"})]}),s.jsxs("div",{className:"col-span-1",children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"State"}),s.jsx("input",{type:"text",value:ke,onChange:pn=>Ae(pn.target.value),placeholder:"TX",maxLength:2,className:"connect-input"})]}),s.jsxs("div",{className:"col-span-2",children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Zip"}),s.jsx("input",{type:"text",value:He,onChange:pn=>ot(pn.target.value),placeholder:"78701",className:"connect-input"})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),s.jsx("input",{type:"date",value:nt,onChange:pn=>tt(pn.target.value),className:"connect-input"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Home Anniversary"}),s.jsx("input",{type:"date",value:vt,onChange:pn=>Vt(pn.target.value),className:"connect-input"})]})]})]})},...ps?[{title:"The Little Things",subtitle:"Optional — helps me remember what matters to you.",fields:s.jsxs("div",{className:"space-y-5",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Spouse / partner's name"}),s.jsx("input",{type:"text",value:Kt,onChange:pn=>ir(pn.target.value),placeholder:"Alex",className:"connect-input"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),s.jsx("input",{type:"date",value:Tn,onChange:pn=>mn(pn.target.value),className:"connect-input"})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Kids"}),s.jsxs("button",{type:"button",onClick:()=>tr(pn=>[...pn,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[s.jsx(Py,{className:"h-3 w-3"})," Add"]})]}),s.jsxs("div",{className:"space-y-2",children:[Gr.length===0&&s.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Gr.map((pn,Vi)=>s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx("input",{type:"text",value:pn.name,onChange:Yi=>tr(nn=>nn.map((Ke,at)=>at===Vi?{...Ke,name:Yi.target.value}:Ke)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),s.jsx("input",{type:"text",value:pn.age,onChange:Yi=>tr(nn=>nn.map((Ke,at)=>at===Vi?{...Ke,age:Yi.target.value}:Ke)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),s.jsx("button",{type:"button",onClick:()=>tr(Yi=>Yi.filter((nn,Ke)=>Ke!==Vi)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:s.jsx(Ra,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Vi))]})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Pets"}),s.jsxs("button",{type:"button",onClick:()=>zt(pn=>[...pn,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[s.jsx(Py,{className:"h-3 w-3"})," Add"]})]}),s.jsxs("div",{className:"space-y-2",children:[Qt.length===0&&s.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Qt.map((pn,Vi)=>s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx("input",{type:"text",value:pn.name,onChange:Yi=>zt(nn=>nn.map((Ke,at)=>at===Vi?{...Ke,name:Yi.target.value}:Ke)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),s.jsx("input",{type:"text",value:pn.kind,onChange:Yi=>zt(nn=>nn.map((Ke,at)=>at===Vi?{...Ke,kind:Yi.target.value}:Ke)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),s.jsx("button",{type:"button",onClick:()=>zt(Yi=>Yi.filter((nn,Ke)=>Ke!==Vi)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:s.jsx(Ra,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Vi))]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Favorite local spots"}),s.jsx("input",{type:"text",value:Vr,onChange:pn=>Jr(pn.target.value),placeholder:"That coffee shop on Main, Town Lake…",className:"connect-input"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Dream neighborhood"}),s.jsx("input",{type:"text",value:Fn,onChange:pn=>Ar(pn.target.value),placeholder:"Where you'd love to live someday",className:"connect-input"})]}),s.jsxs("div",{className:"rounded-xl p-4",style:{background:"color-mix(in srgb, var(--c-accent) 8%, transparent)"},children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium",style:{color:"var(--c-text)"},children:"Know someone who'd love an agent like me?"}),s.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"Refer a friend — up to 3."})]}),li.length<3&&s.jsxs("button",{type:"button",onClick:()=>Lr(pn=>[...pn,{name:"",contact:""}]),className:"text-xs inline-flex items-center gap-1 px-2 py-1 rounded-md",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:[s.jsx(Py,{className:"h-3 w-3"})," Add"]})]}),s.jsx("div",{className:"space-y-2",children:li.map((pn,Vi)=>s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx("input",{type:"text",value:pn.name,onChange:Yi=>Lr(nn=>nn.map((Ke,at)=>at===Vi?{...Ke,name:Yi.target.value}:Ke)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),s.jsx("input",{type:"text",value:pn.contact,onChange:Yi=>Lr(nn=>nn.map((Ke,at)=>at===Vi?{...Ke,contact:Yi.target.value}:Ke)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),s.jsx("button",{type:"button",onClick:()=>Lr(Yi=>Yi.filter((nn,Ke)=>Ke!==Vi)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:s.jsx(Ra,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Vi))})]})]})}]:[],{title:"One Last Thing",fields:s.jsxs("div",{className:"space-y-5",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-slate-600 mb-3",children:["Are you thinking about making a move anytime soon? ",s.jsx("span",{className:"text-slate-400 font-normal",children:"(totally optional)"})]}),s.jsx("div",{className:"grid grid-cols-2 gap-3",children:[{value:"buying",label:"🏠 Buying",desc:"Looking for a home"},{value:"selling",label:"📋 Selling",desc:"Thinking of selling"},{value:"both",label:"🔄 Both",desc:"Buy & sell"},{value:"not_now",label:"😊 Not right now",desc:"Just staying connected"}].map(pn=>s.jsxs("button",{type:"button",onClick:()=>Bt(Ct===pn.value?"":pn.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Ct===pn.value?"border-blue-500 bg-blue-50 shadow-sm":"border-slate-200 bg-white hover:border-slate-300"}`,children:[s.jsx("span",{className:"block text-sm font-medium text-slate-800",children:pn.label}),s.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:pn.desc})]},pn.value))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:["Anything else you'd like to share? ",s.jsx("span",{className:"text-slate-400 font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:cr,onChange:pn=>ft(pn.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],gs=Mi.length,ma=x3t(l==null?void 0:l.theme),Ki=_3t(ma,(l==null?void 0:l.accent_color)||null),Hr=(l==null?void 0:l.cover_image_url)||ma.defaultCover,ci=(l==null?void 0:l.headline)||"Let's stay connected",mo=(l==null?void 0:l.subheadline)||(d!=null&&d.brokerage_name?`${d==null?void 0:d.name} · ${d.brokerage_name}`:(d==null?void 0:d.name)||""),_r=["deep-luxe"].includes((l==null?void 0:l.theme)||"");return s.jsxs("div",{className:"min-h-screen connect-shell",style:Ki,children:[s.jsxs(mc,{children:[s.jsxs("title",{children:["Connect with ",(d==null?void 0:d.name)||"Agent"]}),s.jsx("meta",{name:"description",content:`${ci} — ${(d==null?void 0:d.name)||"your agent"}`}),Hr&&s.jsx("meta",{property:"og:image",content:Hr}),s.jsx("meta",{property:"og:title",content:`Connect with ${(d==null?void 0:d.name)||"me"}`}),s.jsx("meta",{property:"og:description",content:ci}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),s.jsx("style",{children:` .connect-shell { font-family: var(--c-body-font); color: var(--c-text); } .connect-shell h1, .connect-shell h2 { font-family: var(--c-heading-font); } .connect-input { width: 100%; padding: 0.75rem 1rem; border-radius: 0.75rem; border: 1px solid var(--c-border); background: var(--c-surface); color: var(--c-text); font-family: var(--c-body-font); font-size: 0.95rem; transition: border-color 150ms, box-shadow 150ms; } .connect-input::placeholder { color: var(--c-text-muted); opacity: 0.7; } .connect-input:focus { outline: none; border-color: var(--c-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c-accent) 25%, transparent); } `}),s.jsxs("div",{className:"relative w-full overflow-hidden",style:{height:"clamp(200px, 30vh, 320px)"},children:[s.jsx(Sr.img,{src:Hr,alt:"",initial:{scale:1.08},animate:{scale:1},transition:{duration:1.4,ease:"easeOut"},className:"absolute inset-0 w-full h-full object-cover"}),s.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,0) 20%, rgba(0,0,0,0.55) 100%)"}}),s.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-6 pb-16 text-center",children:[s.jsx(Sr.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:ma.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:ci}),mo&&s.jsx(Sr.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:mo})]})]}),s.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[s.jsxs(Sr.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.25},className:"text-center mb-6",children:[d!=null&&d.avatar_url?s.jsx("img",{src:d.avatar_url,alt:d.name,className:"w-24 h-24 rounded-full object-cover mx-auto shadow-xl",style:{border:"4px solid var(--c-surface)"}}):s.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center shadow-xl",style:{background:ma.accent,color:ma.accentText,border:"4px solid var(--c-surface)"},children:s.jsx("span",{className:"text-3xl font-bold",children:((Da=d==null?void 0:d.name)==null?void 0:Da.charAt(0))||"?"})}),(d==null?void 0:d.title)&&s.jsx("p",{className:"text-sm mt-3",style:{color:"var(--c-text-muted)"},children:d.title}),((d==null?void 0:d.phone)||(d==null?void 0:d.email))&&s.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[(d==null?void 0:d.phone)&&s.jsx("a",{href:`tel:${d.phone}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Call agent",children:s.jsx(Ui,{className:"h-4 w-4"})}),(d==null?void 0:d.email)&&s.jsx("a",{href:`mailto:${d.email}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Email agent",children:s.jsx(rs,{className:"h-4 w-4"})})]})]}),s.jsx(Sr.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.35},className:"text-center mb-6 px-2 leading-relaxed text-sm",style:{color:"var(--c-text-muted)"},children:(l==null?void 0:l.welcome_message)||"I'd love to stay in touch — just a few quick details."}),s.jsx("div",{className:"flex gap-1.5 mb-6 px-2",children:Array.from({length:gs}).map((pn,Vi)=>s.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:Vi<=G?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},Vi))}),s.jsxs(Sr.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.4},className:"rounded-2xl p-6 sm:p-8",style:{background:"var(--c-surface)",border:"1px solid var(--c-border)",boxShadow:_r?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[s.jsx(fAe,{mode:"wait",children:s.jsxs(Sr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[s.jsxs("div",{className:"mb-6",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(va,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),s.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:Mi[G].title})]}),Mi[G].subtitle&&s.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:Mi[G].subtitle})]}),Mi[G].fields]},G)}),s.jsxs("div",{className:"flex justify-between mt-8",children:[G>0?s.jsx("button",{type:"button",onClick:()=>W(pn=>pn-1),className:"px-5 py-2.5 text-sm font-medium transition-opacity hover:opacity-70",style:{color:"var(--c-text-muted)"},children:"Back"}):s.jsx("div",{}),G{if(G===0&&!ee.trim()){lr.error("Please enter your first name");return}W(pn=>pn+1)},className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:"Continue"}):s.jsx("button",{type:"button",onClick:()=>si(),disabled:F,className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm disabled:opacity-50 flex items-center gap-2",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:F?s.jsxs(s.Fragment,{children:[s.jsx(gh,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),G>0&&GW(pn=>pn+1),className:"text-xs transition-opacity hover:opacity-80",style:{color:"var(--c-text-muted)"},children:"Skip this step"})})]}),s.jsx("div",{className:"text-center mt-8",children:s.jsxs("div",{className:"flex items-center justify-center gap-1 text-xs",style:{color:"var(--c-text-muted)"},children:[s.jsx(cg,{className:"h-3 w-3"}),s.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const v3t=Object.freeze(Object.defineProperty({__proto__:null,default:pCe},Symbol.toStringTag,{value:"Module"}));function b3t(){const e=ms().pathname.slice(1);return N.useEffect(()=>{document.body.classList.add("connect-page");const r=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(a=>{document.querySelectorAll(a).forEach(c=>{c.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("connect-page"),n.forEach(clearTimeout)}},[]),!e||e===""?s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),s.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),s.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):s.jsx(pCe,{slugOverride:e})}function w3t(t){try{const e=document.createElement("canvas"),r=e.width=Math.min(t.naturalWidth,64),n=e.height=Math.min(t.naturalHeight,64),i=e.getContext("2d");if(!i)return!0;i.drawImage(t,0,0,r,n);const a=i.getImageData(0,0,r,n).data,c=[[0,0],[r-1,0],[0,n-1],[r-1,n-1],[Math.floor(r/2),0],[Math.floor(r/2),n-1],[0,Math.floor(n/2)],[r-1,Math.floor(n/2)]];for(const[d,p]of c)if(a[(p*r+d)*4+3]<250)return!0;return!1}catch{return!0}}const S3t={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function E3t({page:t,fields:e,answers:r,setAnswers:n,onSubmit:i,isSubmitting:a,renderField:c}){const d=t.accent_color||"#E8B84A",p=t.primary_color||"#0F1B3D",l=S3t[t.heading_font||"playfair"],g=t.eyebrow||null,v=t.headline_accent||null,E=Array.isArray(t.trust_pills)?t.trust_pills:[],T=e,j=T.length>5;return s.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:p},children:[t.hero_image_url?s.jsx("img",{src:t.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):s.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${p}, #000)`}}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),s.jsx("div",{className:"relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-screen md:min-h-[760px] flex items-center",children:s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[s.jsxs("div",{className:"lg:col-span-3 text-white",children:[t.logo_url&&s.jsx(T3t,{src:t.logo_url}),g&&s.jsx("p",{className:"text-xs md:text-sm font-semibold tracking-[0.22em] text-white/80 mb-4 uppercase",children:g}),s.jsxs("h1",{className:"font-bold leading-[1.04] mb-5 text-4xl sm:text-5xl md:text-6xl lg:text-[68px]",style:{fontFamily:l,letterSpacing:"-0.015em"},children:[t.hero_headline,v&&s.jsxs(s.Fragment,{children:[" ",s.jsx("span",{style:{color:d,fontStyle:"italic"},children:v})]})]}),t.hero_subtext&&s.jsx("p",{className:"text-base md:text-lg text-white/85 leading-relaxed max-w-xl",children:t.hero_subtext}),t.agent_name&&s.jsxs("div",{className:"mt-8 flex items-center gap-3",children:[t.agent_photo_url&&s.jsx("img",{src:t.agent_photo_url,alt:t.agent_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/30"}),s.jsxs("div",{className:"text-white/90",children:[s.jsx("p",{className:"font-semibold text-sm",children:t.agent_name}),s.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/70 mt-0.5",children:[t.agent_phone&&s.jsxs("a",{href:`tel:${t.agent_phone}`,className:"flex items-center gap-1 hover:text-white",children:[s.jsx(Ui,{className:"h-3 w-3"})," ",t.agent_phone]}),t.agent_email&&s.jsxs("a",{href:`mailto:${t.agent_email}`,className:"flex items-center gap-1 hover:text-white",children:[s.jsx(rs,{className:"h-3 w-3"})," ",t.agent_email]})]})]})]})]}),s.jsx("div",{className:"lg:col-span-2",children:s.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6",children:[s.jsxs("form",{className:"space-y-3",onSubmit:i,children:[s.jsx("div",{className:j?"space-y-3 max-h-[52vh] overflow-y-auto pr-1 -mr-1":"space-y-3",children:T.map(P=>s.jsxs("div",{children:[s.jsxs(sn,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[P.label,P.is_required&&s.jsx("span",{className:"ml-1",style:{color:d},children:"*"})]}),s.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900 [&_span]:text-white/90 [&_button[role=checkbox]]:border-white/60 [&_button[role=checkbox]]:bg-white/20 [&_button[role=checkbox][data-state=checked]]:bg-white [&_button[role=checkbox][data-state=checked]]:text-neutral-900",children:c(P,r,n,p)})]},P.id))}),s.jsx("button",{type:"submit",disabled:a,className:"w-full px-6 py-3.5 rounded-lg font-bold text-neutral-900 text-base md:text-lg shadow-lg hover:brightness-110 active:brightness-95 transition-all disabled:opacity-60 mt-2",style:{backgroundColor:d},children:a?"Submitting...":t.cta_text||"Get Started"})]}),E.length>0&&s.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:E.map((P,C)=>s.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[s.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:d}}),P]},C))})]})})]})})]})}function T3t({src:t}){const[e,r]=N.useState(null),n=s.jsx("img",{src:t,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:i=>r(w3t(i.currentTarget)),onError:()=>r(!0)});return e===!1?s.jsx("span",{className:"inline-flex items-center rounded-md bg-white/90 backdrop-blur px-3 py-2 mb-6 shadow-sm",children:n}):s.jsx("div",{className:"mb-6 inline-block drop-shadow-md",children:n})}const wme={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function A3t({page:t,fields:e,answers:r,setAnswers:n,onSubmit:i,isSubmitting:a,renderField:c,activePath:d,setActivePath:p}){const l=N.useRef(null),[g,v]=N.useState(!1),E=t.primary_color||"#406E71",T=t.accent_color||"#2a4c64",j=t.settings||{},P=wme[t.heading_font]||wme.playfair,C=Array.isArray(t.trust_pills)?t.trust_pills:[],L={buyerLabel:j.buyer_button_label||"I'm a Buyer",buyerSub:j.buyer_button_subtext||"Find the right home, at the right price",sellerLabel:j.seller_button_label||"I'm a Seller",sellerSub:j.seller_button_subtext||"Get a free, no-obligation home evaluation",buyerTitle:j.buyer_form_title||"Tell me what you’re looking for",buyerSubtitle:j.buyer_form_subtext||"A few quick questions and I’ll send you matching homes.",sellerTitle:j.seller_form_title||"Get your free home evaluation",sellerSubtitle:j.seller_form_subtext||"Tell me about your home and I’ll prepare your value report.",buyerCta:j.buyer_submit_label||"Send me homes",sellerCta:j.seller_submit_label||"Get my home value"},O=N.useMemo(()=>{const W=e.filter(ee=>(ee.field_group||"default")==="buyer"),Z=e.filter(ee=>(ee.field_group||"default")==="seller"),Q=e.filter(ee=>(ee.field_group||"default")==="default");return{buyer:W.length?[...Q,...W]:[...Q],seller:Z.length?[...Q,...Z]:[...Q]}},[e]),F=d?O[d]:[];N.useEffect(()=>{d&&l.current&&l.current.scrollIntoView({behavior:"smooth",block:"start"})},[d]);const $=F.filter(W=>W.is_required&&!r[W.label]),G=W=>{W.preventDefault(),v(!0),!($.length>0)&&i(W)};return s.jsxs("div",{className:"min-h-screen bg-neutral-950",children:[s.jsxs("section",{className:"relative min-h-[78vh] flex items-center overflow-hidden",children:[s.jsx("div",{className:"absolute inset-0",style:{background:t.hero_image_url?`url(${t.hero_image_url}) center/cover no-repeat`:`linear-gradient(135deg, ${E}, ${T})`}}),s.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,.72) 0%, rgba(0,0,0,.42) 38%, rgba(0,0,0,.82) 100%)"}}),s.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40",style:{background:"linear-gradient(180deg, transparent, #0a0a0a)"}}),s.jsxs("div",{className:"relative w-full max-w-6xl mx-auto px-5 py-20 text-center",children:[t.logo_url&&s.jsx("img",{src:t.logo_url,alt:"",className:"h-11 w-auto mx-auto mb-8 drop-shadow-lg"}),t.eyebrow&&s.jsx("p",{className:"text-[11px] md:text-xs uppercase tracking-[0.32em] text-white/70 mb-5",children:t.eyebrow}),s.jsxs("h1",{className:"text-white text-4xl md:text-6xl lg:text-7xl leading-[1.05] tracking-tight",style:{fontFamily:P},children:[t.hero_headline,t.headline_accent&&s.jsxs(s.Fragment,{children:[" ",s.jsx("em",{className:"italic",style:{color:"#fff",opacity:.85},children:t.headline_accent})]})]}),t.hero_subtext&&s.jsx("p",{className:"mt-5 text-base md:text-lg text-white/80 max-w-2xl mx-auto leading-relaxed",children:t.hero_subtext}),s.jsxs("div",{className:"mt-12 grid gap-4 sm:grid-cols-2 max-w-3xl mx-auto",children:[s.jsx(Sme,{active:d==="buyer",icon:s.jsx(ove,{className:"h-5 w-5"}),label:L.buyerLabel,sub:L.buyerSub,color:E,onClick:()=>{v(!1),p("buyer")}}),s.jsx(Sme,{active:d==="seller",icon:s.jsx(Do,{className:"h-5 w-5"}),label:L.sellerLabel,sub:L.sellerSub,color:T,onClick:()=>{v(!1),p("seller")}})]}),C.length>0&&s.jsx("div",{className:"mt-9 flex flex-wrap items-center justify-center gap-2",children:C.map(W=>s.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-white/20 bg-white/10 px-3.5 py-1.5 text-[11px] font-medium text-white/85 backdrop-blur",children:[s.jsx(QW,{className:"h-3 w-3"})," ",W]},W))})]})]}),s.jsx("section",{ref:l,className:"relative bg-neutral-950 px-5 pb-20 pt-2 scroll-mt-4",children:s.jsxs("div",{className:"max-w-3xl mx-auto",children:[d?s.jsxs("div",{className:"-mt-14 rounded-3xl border border-white/10 bg-white shadow-[0_40px_80px_-30px_rgba(0,0,0,.8)] overflow-hidden",children:[s.jsxs("div",{className:"px-6 md:px-9 py-6",style:{background:`linear-gradient(120deg, ${d==="buyer"?E:T}, ${d==="buyer"?T:E})`},children:[s.jsxs("button",{type:"button",onClick:()=>p(null),className:"inline-flex items-center gap-1.5 text-[11px] uppercase tracking-widest text-white/75 hover:text-white transition-colors",children:[s.jsx(yv,{className:"h-3 w-3"})," Change"]}),s.jsx("h2",{className:"mt-3 text-2xl md:text-3xl text-white leading-tight",style:{fontFamily:P},children:d==="buyer"?L.buyerTitle:L.sellerTitle}),s.jsx("p",{className:"mt-1.5 text-sm text-white/80",children:d==="buyer"?L.buyerSubtitle:L.sellerSubtitle})]}),s.jsxs("form",{onSubmit:G,className:"px-6 md:px-9 py-7 space-y-4",children:[F.length===0&&s.jsx("p",{className:"text-sm text-neutral-500",children:"This form has no questions yet."}),F.map(W=>s.jsxs("div",{children:[s.jsxs(sn,{className:"text-[13px] font-medium text-neutral-700",children:[W.label,W.is_required&&s.jsx("span",{className:"ml-1",style:{color:E},children:"*"})]}),c(W,r,n,E)]},W.id)),g&&$.length>0&&s.jsxs("p",{className:"text-sm text-red-600",children:["Please fill in: ",$.map(W=>W.label).join(", ")]}),s.jsxs(Jt,{type:"submit",disabled:a,className:"w-full h-12 text-white text-base rounded-xl shadow-lg hover:opacity-95",style:{backgroundColor:d==="buyer"?E:T},children:[a?"Sending…":d==="buyer"?L.buyerCta:L.sellerCta,!a&&s.jsx(lo,{className:"h-4 w-4 ml-2"})]})]})]}):s.jsx("p",{className:"text-center text-white/45 text-sm py-10",children:"Choose an option above to get started."}),t.agent_name&&s.jsxs("div",{className:"mt-10 flex items-center justify-center gap-4 rounded-2xl border border-white/10 bg-white/[0.04] px-6 py-5 backdrop-blur",children:[t.agent_photo_url&&s.jsx("img",{src:t.agent_photo_url,alt:t.agent_name,className:"h-14 w-14 rounded-full object-cover ring-2 ring-white/20"}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-white font-medium",children:t.agent_name}),s.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/65",children:[t.agent_phone&&s.jsxs("a",{href:`tel:${t.agent_phone}`,className:"inline-flex items-center gap-1 hover:text-white",children:[s.jsx(Ui,{className:"h-3 w-3"})," ",t.agent_phone]}),t.agent_email&&s.jsxs("a",{href:`mailto:${t.agent_email}`,className:"inline-flex items-center gap-1 hover:text-white",children:[s.jsx(rs,{className:"h-3 w-3"})," ",t.agent_email]})]})]})]})]})})]})}function Sme({active:t,icon:e,label:r,sub:n,color:i,onClick:a}){return s.jsxs("button",{type:"button",onClick:a,className:`group relative overflow-hidden rounded-2xl border px-6 py-7 text-left transition-all duration-300 backdrop-blur-xl ${t?"border-white/60 bg-white/95 shadow-2xl -translate-y-0.5":"border-white/20 bg-white/10 hover:bg-white/20 hover:-translate-y-0.5"}`,children:[s.jsx("span",{className:"inline-flex h-11 w-11 items-center justify-center rounded-full",style:{backgroundColor:t?i:"rgba(255,255,255,.18)",color:"#fff"},children:e}),s.jsx("span",{className:`mt-4 block text-xl font-semibold ${t?"":"text-white"}`,style:t?{color:i}:void 0,children:r}),s.jsx("span",{className:`mt-1 block text-sm ${t?"text-neutral-600":"text-white/70"}`,children:n}),s.jsx(lo,{className:`absolute right-5 top-7 h-4 w-4 transition-transform group-hover:translate-x-1 ${t?"":"text-white/60"}`,style:t?{color:i}:void 0})]})}function k3t(t){const e=Math.max(0,Math.floor(t/1e3));return{d:Math.floor(e/86400),h:Math.floor(e%86400/3600),m:Math.floor(e%3600/60),s:e%60}}function I3t(t,e,r){const n=new Date(e),i=new Date(n.getTime()+60*60*1e3),a=d=>d.toISOString().replace(/[-:]|\.\d{3}/g,""),c=new URL("https://www.google.com/calendar/render");return c.searchParams.set("action","TEMPLATE"),c.searchParams.set("text",t),c.searchParams.set("dates",`${a(n)}/${a(i)}`),r&&c.searchParams.set("location",r),c.toString()}function j3t(t,e,r){const n=new Date(e),i=new Date(n.getTime()+60*60*1e3),a=d=>d.toISOString().replace(/[-:]|\.\d{3}/g,""),c=["BEGIN:VCALENDAR","VERSION:2.0","BEGIN:VEVENT",`UID:${Date.now()}@levelup`,`DTSTAMP:${a(new Date)}`,`DTSTART:${a(n)}`,`DTEND:${a(i)}`,`SUMMARY:${t}`,r?`LOCATION:${r}`:"","END:VEVENT","END:VCALENDAR"].filter(Boolean).join(`\r `);return`data:text/calendar;charset=utf-8,${encodeURIComponent(c)}`}function C3t({startsAt:t,locationName:e,address:r,title:n,accent:i}){const[a,c]=N.useState(Date.now());N.useEffect(()=>{const T=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval(T)},[]);const d=new Date(t).getTime();if(!Number.isFinite(d))return null;const p=k3t(d-a),l=d-a<=0,g=new Date(t).toLocaleString("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"}),v=[e,r].filter(Boolean).join(" · "),E=r?`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(r)}`:null;return s.jsx("section",{className:"max-w-5xl mx-auto px-4 py-10",children:s.jsx("div",{className:"rounded-2xl border bg-white/80 backdrop-blur p-6 md:p-8 shadow-sm",children:s.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("div",{className:"text-xs uppercase tracking-wider font-medium",style:{color:i},children:l?"Just happened":"Event starts in"}),l?s.jsx("p",{className:"text-sm text-muted-foreground",children:"Missed this one? Submit the form and we'll let you know about the next one."}):s.jsx("div",{className:"flex items-baseline gap-3",children:[{v:p.d,l:"days"},{v:p.h,l:"hrs"},{v:p.m,l:"min"},{v:p.s,l:"sec"}].map(T=>s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"text-3xl md:text-4xl font-bold tabular-nums",style:{color:i},children:String(T.v).padStart(2,"0")}),s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:T.l})]},T.l))}),s.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 pt-2 text-sm text-neutral-700",children:[s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(su,{className:"h-3.5 w-3.5"})," ",g]}),v&&s.jsxs("a",{href:E||"#",target:E?"_blank":void 0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 hover:underline",children:[s.jsx(Va,{className:"h-3.5 w-3.5"})," ",v]})]})]}),!l&&s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("a",{href:I3t(n,t,v||null),target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[s.jsx(Cl,{className:"h-4 w-4"})," Add to Google"]}),s.jsxs("a",{href:j3t(n,t,v||null),download:`${n.replace(/\W+/g,"-").toLowerCase()}.ics`,className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[s.jsx(Cl,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function P3t(){try{const t="_lp_sid";let e=sessionStorage.getItem(t);return e||(e=crypto.randomUUID?crypto.randomUUID():`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,sessionStorage.setItem(t,e)),e}catch{return`s_${Date.now()}`}}function gCe({slugOverride:t}){var Le;const{slug:e}=Sg(),r=t||e,[n,i]=N.useState(!1),[a,c]=N.useState({}),[d,p]=N.useState(null),[l,g]=N.useState(0),[v,E]=N.useState(!1),[T,j]=N.useState(""),[P]=N.useState(()=>Date.now()),C=N.useState(()=>P3t())[0],{data:L,isLoading:O}=jr({queryKey:["public-landing-page",r],queryFn:async()=>{const{data:be,error:Re}=await Be.from("landing_pages").select("*").eq("slug",r).eq("is_published",!0).single();if(Re)throw Re;return be},enabled:!!r}),{data:F=[]}=jr({queryKey:["public-landing-page-fields",L==null?void 0:L.id],queryFn:async()=>{const{data:be,error:Re}=await Be.from("landing_page_fields").select("*").eq("page_id",L.id).order("sort_order");if(Re)throw Re;return be},enabled:!!(L!=null&&L.id)});N.useEffect(()=>{L!=null&&L.id&&Be.from("landing_pages").update({view_count:(L.view_count||0)+1}).eq("id",L.id).then(()=>{})},[L==null?void 0:L.id]),N.useEffect(()=>{if(!(L!=null&&L.id))return;const be=new URLSearchParams(window.location.search);Be.functions.invoke("landing-page-track",{body:{page_id:L.id,event_type:"view",session_id:C,utm_source:be.get("utm_source"),utm_medium:be.get("utm_medium"),utm_campaign:be.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[L==null?void 0:L.id,C]);const $=zr({mutationFn:async()=>{const be=F.find(He=>He.field_type==="text"&&He.label.toLowerCase().includes("name")),Re=F.find(He=>He.field_type==="email"),Ie=F.find(He=>He.field_type==="phone"),Te=be?String(a[be.label]||""):null,ge=Re?String(a[Re.label]||""):null,$e=Ie?String(a[Ie.label]||""):null,we=new URLSearchParams(window.location.search),{data:ke,error:Ae}=await Be.functions.invoke("landing-page-submit",{body:{page_id:L.id,answers:JSON.parse(JSON.stringify(d?{"I am a":d==="buyer"?"Buyer":"Seller",...a}:a)),contact_name:Te,contact_email:ge,contact_phone:$e,session_id:C,honeypot:T,rendered_at:P,utm_source:we.get("utm_source"),utm_medium:we.get("utm_medium"),utm_campaign:we.get("utm_campaign"),referrer:document.referrer||null}});if(Ae)throw Ae;return ke},onSuccess:be=>{i(!0),be!=null&&be.redirect_url&&setTimeout(()=>{window.location.href=be.redirect_url},1500)}}),G=be=>{be.preventDefault(),!((L==null?void 0:L.page_type)!=="buyer_seller"&&F.filter(Ie=>Ie.is_required&&!a[Ie.label]).length>0)&&$.mutate()};if(O)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-gray-400 border-t-transparent"})});if(!L)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold text-gray-700",children:"Page Not Found"}),s.jsx("p",{className:"text-gray-500 mt-2",children:"This page doesn't exist or is no longer available."})]})});const W=L.primary_color||"#406E71",Z=L.accent_color||"#2a4c64",Q=L,ee=L.page_type==="lead_magnet",ie=L.page_type==="just_listed"||L.page_type==="just_sold",oe=Array.isArray(Q.property_photos)?Q.property_photos:[],pe=Q.lead_magnet_file_url||Q.lead_magnet_external_url;if(n)return s.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${W}, ${Z})`},children:s.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[s.jsx(od,{className:"h-16 w-16 mx-auto mb-4",style:{color:W}}),s.jsx("h2",{className:"text-2xl font-bold mb-2",children:ee?"Your download is ready!":"Submitted!"}),s.jsx("p",{className:"text-gray-600",children:L.success_message}),ee&&pe&&s.jsxs("a",{href:pe,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 mt-6 px-6 py-3 rounded-lg text-white font-semibold transition-transform hover:scale-105",style:{backgroundColor:W},children:[s.jsx($u,{className:"h-5 w-5"}),"Download ",Q.lead_magnet_file_name||"Your File"]}),L.agent_name&&s.jsxs("div",{className:"mt-6 pt-4 border-t",children:[s.jsx("p",{className:"text-sm text-gray-500",children:"Contact"}),s.jsx("p",{className:"font-semibold",children:L.agent_name}),L.agent_phone&&s.jsxs("a",{href:`tel:${L.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:W},children:[s.jsx(Ui,{className:"h-3 w-3"})," ",L.agent_phone]}),L.agent_email&&s.jsxs("a",{href:`mailto:${L.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:W},children:[s.jsx(rs,{className:"h-3 w-3"})," ",L.agent_email]})]})]})});if(ie){const be=Re=>{const Ie=parseFloat(Re.replace(/[^0-9.]/g,""));return isNaN(Ie)?Re:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ie)};return s.jsxs("div",{className:"min-h-screen bg-gray-50",children:[v&&oe.length>0&&s.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>E(!1),children:[s.jsx("button",{onClick:()=>E(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:s.jsx(Ra,{className:"h-8 w-8"})}),s.jsx("button",{onClick:Re=>{Re.stopPropagation(),g(Ie=>Ie===0?oe.length-1:Ie-1)},className:"absolute left-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/20 text-white rounded-full p-3 transition-colors z-10",children:s.jsx(bg,{className:"h-6 w-6"})}),s.jsx("img",{src:oe[l],alt:`Property photo ${l+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:Re=>Re.stopPropagation()}),s.jsx("button",{onClick:Re=>{Re.stopPropagation(),g(Ie=>Ie===oe.length-1?0:Ie+1)},className:"absolute right-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/20 text-white rounded-full p-3 transition-colors z-10",children:s.jsx(uf,{className:"h-6 w-6"})}),s.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 text-white/70 text-sm",children:[l+1," / ",oe.length]})]}),oe.length>0&&s.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 pt-6",children:[s.jsx("div",{className:"absolute top-10 left-8 z-10 px-4 py-1.5 rounded-full text-white font-bold text-sm uppercase tracking-wider shadow-lg",style:{backgroundColor:Q.property_status==="just_sold"?"#e74c3c":W},children:Q.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),oe.length===1?s.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{g(0),E(!0)},children:[s.jsx("img",{src:oe[0],alt:"Property",className:"w-full h-[50vh] object-cover group-hover:scale-105 transition-transform duration-500"}),s.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white px-3 py-1.5 rounded-lg text-sm flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[s.jsx(Zse,{className:"h-4 w-4"})," View"]})]}):oe.length===2?s.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:oe.slice(0,2).map((Re,Ie)=>s.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{g(Ie),E(!0)},children:s.jsx("img",{src:Re,alt:`Property ${Ie+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},Ie))}):s.jsxs("div",{className:"grid grid-cols-4 gap-2 rounded-2xl overflow-hidden",style:{height:"55vh"},children:[s.jsx("div",{className:"col-span-2 row-span-2 cursor-pointer group relative",onClick:()=>{g(0),E(!0)},children:s.jsx("img",{src:oe[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),oe.slice(1,5).map((Re,Ie)=>s.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{g(Ie+1),E(!0)},children:[s.jsx("img",{src:Re,alt:`Property ${Ie+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),Ie===3&&oe.length>5&&s.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",oe.length-5," more"]})]},Ie))]}),oe.length>2&&s.jsxs("button",{onClick:()=>{g(0),E(!0)},className:"absolute bottom-4 right-8 bg-white shadow-lg hover:shadow-xl text-gray-800 px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-shadow",children:[s.jsx(Zse,{className:"h-4 w-4"})," View all ",oe.length," photos"]})]}),oe.length===0&&s.jsx("div",{className:"relative py-16 px-4",style:{background:L.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${L.hero_image_url}) center/cover`:`linear-gradient(135deg, ${W}, ${Z})`},children:s.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[L.logo_url&&s.jsx("img",{src:L.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),s.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:L.hero_headline}),L.hero_subtext&&s.jsx("p",{className:"mt-3 text-lg opacity-90",children:L.hero_subtext})]})}),s.jsx("div",{className:"max-w-4xl mx-auto px-4 py-8",children:s.jsxs("div",{className:"grid md:grid-cols-5 gap-6",children:[s.jsx("div",{className:"md:col-span-3 space-y-6",children:s.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[Q.property_price&&s.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:W},children:be(Q.property_price)}),Q.property_address&&s.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[s.jsx(Va,{className:"h-5 w-5 shrink-0"})," ",Q.property_address]}),s.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[Q.property_beds&&s.jsxs("div",{className:"text-center",children:[s.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[s.jsx(tA,{className:"h-5 w-5",style:{color:W}})," ",Q.property_beds]}),s.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),Q.property_baths&&s.jsxs("div",{className:"text-center",children:[s.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[s.jsx(ww,{className:"h-5 w-5",style:{color:W}})," ",Q.property_baths]}),s.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),Q.property_sqft&&s.jsxs("div",{className:"text-center",children:[s.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[s.jsx(k4,{className:"h-5 w-5",style:{color:W}})," ",Number(Q.property_sqft).toLocaleString()]}),s.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),Q.property_description&&s.jsxs("div",{children:[s.jsx("h3",{className:"font-semibold text-gray-800 mb-2",children:"About This Property"}),s.jsx("p",{className:"text-gray-600 leading-relaxed whitespace-pre-line",children:Q.property_description})]})]})}),s.jsx("div",{className:"md:col-span-2",children:s.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 sticky top-6",children:[s.jsx("h2",{className:"text-lg font-bold mb-1",style:{color:W},children:Q.property_status==="just_sold"?"Want results like this?":"Interested in this property?"}),s.jsx("p",{className:"text-gray-500 text-sm mb-4",children:"Fill out the form and I'll be in touch!"}),L.agent_name&&s.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[L.agent_photo_url&&s.jsx("img",{src:L.agent_photo_url,alt:L.agent_name,className:"h-12 w-12 rounded-full object-cover"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold text-sm",children:L.agent_name}),s.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[L.agent_phone&&s.jsxs("a",{href:`tel:${L.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[s.jsx(Ui,{className:"h-3 w-3"})," ",L.agent_phone]}),L.agent_email&&s.jsxs("a",{href:`mailto:${L.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[s.jsx(rs,{className:"h-3 w-3"})," ",L.agent_email]})]})]})]}),s.jsxs("form",{onSubmit:G,className:"space-y-3",children:[F.map(Re=>s.jsxs("div",{children:[s.jsxs(sn,{className:"text-xs font-medium",children:[Re.label,Re.is_required&&s.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),sM(Re,a,c)]},Re.id)),s.jsx(Jt,{type:"submit",className:"w-full text-white",style:{backgroundColor:W},disabled:$.isPending,children:$.isPending?"Submitting...":"Submit"}),$.isError&&s.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),s.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return L.page_type==="buyer_seller"?s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:T,onChange:be=>j(be.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),s.jsx(A3t,{page:L,fields:F,answers:a,setAnswers:c,onSubmit:G,isSubmitting:$.isPending,renderField:sM,activePath:d,setActivePath:p}),$.isError&&s.jsx("p",{className:"text-center text-sm text-red-500 pb-8 bg-neutral-950",children:"Something went wrong. Please try again."}),s.jsx("div",{className:"text-center py-6 text-xs text-white/30 bg-neutral-950",children:"Powered by LevelUp"})]}):L.theme_style!=="classic"&&!ee?s.jsxs("div",{className:"min-h-screen bg-neutral-50",children:[s.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:T,onChange:be=>j(be.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),s.jsx(E3t,{page:L,fields:F,answers:a,setAnswers:c,onSubmit:G,isSubmitting:$.isPending,renderField:sM}),L.page_type==="event_registration"&&((Le=L.settings)==null?void 0:Le.event_starts_at)&&s.jsx(C3t,{startsAt:L.settings.event_starts_at,locationName:L.settings.event_location_name,address:L.settings.event_address,title:L.hero_headline||L.title,accent:L.accent_color||L.primary_color||"#406E71"}),$.isError&&s.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),s.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):s.jsxs("div",{className:"min-h-screen bg-gray-50",children:[s.jsx("div",{className:"relative py-16 px-4",style:{background:L.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${L.hero_image_url}) center/cover`:`linear-gradient(135deg, ${W}, ${Z})`},children:s.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[L.logo_url&&s.jsx("img",{src:L.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),s.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:L.hero_headline}),L.hero_subtext&&s.jsx("p",{className:"mt-3 text-lg opacity-90",children:L.hero_subtext}),ee&&Q.lead_magnet_file_name&&s.jsxs("div",{className:"mt-6 inline-flex items-center gap-2 bg-white/20 backdrop-blur px-4 py-2 rounded-full text-sm",children:[s.jsx($u,{className:"h-4 w-4"}),"Free Download: ",Q.lead_magnet_file_name]})]})}),s.jsx("div",{className:"max-w-2xl mx-auto px-4 -mt-8",children:s.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[ee&&s.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),L.agent_name&&s.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[L.agent_photo_url&&s.jsx("img",{src:L.agent_photo_url,alt:L.agent_name,className:"h-12 w-12 rounded-full object-cover"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-semibold",children:L.agent_name}),s.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[L.agent_phone&&s.jsxs("a",{href:`tel:${L.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[s.jsx(Ui,{className:"h-3 w-3"})," ",L.agent_phone]}),L.agent_email&&s.jsxs("a",{href:`mailto:${L.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[s.jsx(rs,{className:"h-3 w-3"})," ",L.agent_email]})]})]})]}),s.jsxs("form",{onSubmit:G,className:"space-y-4",children:[F.map(be=>s.jsxs("div",{children:[s.jsxs(sn,{className:"text-sm font-medium",children:[be.label,be.is_required&&s.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),sM(be,a,c)]},be.id)),s.jsx(Jt,{type:"submit",className:"w-full text-white",style:{backgroundColor:W},disabled:$.isPending,children:$.isPending?"Submitting...":ee?"Get My Free Download":"Submit"}),$.isError&&s.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})}),s.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}function sM(t,e,r,n){const i=e[t.label]||"",a=Array.isArray(t.options)?t.options:[];switch(t.field_type){case"text":case"email":case"phone":return s.jsx(hn,{type:t.field_type==="email"?"email":t.field_type==="phone"?"tel":"text",value:String(i),onChange:c=>r(d=>({...d,[t.label]:c.target.value})),placeholder:t.placeholder||"",className:"mt-1"});case"textarea":return s.jsx(df,{value:String(i),onChange:c=>r(d=>({...d,[t.label]:c.target.value})),placeholder:t.placeholder||"",rows:3,className:"mt-1"});case"select":return s.jsxs(Xo,{value:String(i),onValueChange:c=>r(d=>({...d,[t.label]:c})),children:[s.jsx(Mo,{className:"mt-1",children:s.jsx(Qo,{placeholder:"Select..."})}),s.jsx(Oo,{children:a.map(c=>s.jsx($n,{value:c,children:c},c))})]});case"multiselect":return s.jsx("div",{className:"mt-1 space-y-2",children:a.map(c=>{const d=Array.isArray(i)?i:[];return s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx(XP,{checked:d.includes(c),onCheckedChange:p=>{const l=p?[...d,c]:d.filter(g=>g!==c);r(g=>({...g,[t.label]:l}))}}),s.jsx("span",{className:"text-sm",children:c})]},c)})});case"toggle":return s.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[s.jsx(TA,{checked:!!i,onCheckedChange:c=>r(d=>({...d,[t.label]:c?"Yes":"No"}))}),s.jsx("span",{className:"text-sm text-gray-600",children:i?"Yes":"No"})]});default:return s.jsx(hn,{value:String(i),onChange:c=>r(d=>({...d,[t.label]:c.target.value})),className:"mt-1"})}}const N3t=Object.freeze(Object.defineProperty({__proto__:null,default:gCe},Symbol.toStringTag,{value:"Module"}));function R3t(){const e=ms().pathname.slice(1).split("/")[0];return N.useEffect(()=>{document.body.classList.add("landing-page-public");const r=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(a=>{document.querySelectorAll(a).forEach(c=>{c.style.display="none"})})};r();const n=[setTimeout(r,500),setTimeout(r,1500),setTimeout(r,3e3),setTimeout(r,5e3)];return()=>{document.body.classList.remove("landing-page-public"),n.forEach(clearTimeout)}},[]),e?s.jsx(gCe,{slugOverride:e}):s.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Pages"}),s.jsx("p",{className:"text-gray-500",children:"Visit a specific page URL to view content."})]})})}const L3t=[{type:"hero",enabled:!0},{type:"featured_listings",enabled:!0},{type:"new_listings",enabled:!1},{type:"open_houses",enabled:!1},{type:"my_listings",enabled:!1},{type:"city_pages",enabled:!1},{type:"featured_areas",enabled:!0},{type:"about",enabled:!0},{type:"testimonials",enabled:!0},{type:"cta_banner",enabled:!0}],GXt={hero:"Hero Section",featured_listings:"Featured Listings",featured_areas:"Featured Areas",about:"About Me",testimonials:"Testimonials",agent_reviews:"Live Client Reviews",cta_banner:"Call To Action",new_listings:"New Listings Carousel",open_houses:"Open Houses Carousel",my_listings:"My Listings Carousel",city_pages:"City Pages Grid",property_types:"Property Types Gallery",advantages:"Advantages / Why Choose Us",rate_my_agent:"RateMyAgent Reviews",lifestyle_gallery:"Lifestyle Gallery",market_pulse:"Market Pulse",concierge_services:"Concierge Services",credentials:"Credentials & Clientele",land_use_guide:"Land Use Guide",land_valuation_cta:"Land Valuation CTA",acreage_showcase:"Acreage Showcase",featured_video:"Featured Video",schedule_cta:"Schedule a Consultation"},HXt={hero:"Full-screen background image with headline, subtitle, and search bar",featured_listings:"Grid of highlighted properties from the MLS",featured_areas:"Spotlight regions or neighborhoods that link to property search",about:"Agent photo, bio, and credentials section",testimonials:"Client reviews carousel with quotes",agent_reviews:"Real reviews you selected in the LevelUp Reviews app, updated automatically",cta_banner:"Call-to-action block to drive contact and search engagement",new_listings:"Horizontal carousel of newest listings, filterable by city",open_houses:"Horizontal carousel of open house listings, filterable by city",my_listings:"Showcase the agent's own active listings in a carousel",city_pages:"Grid of your city landing pages with photos and links",property_types:"Visual gallery of property categories (Ranch, Farm, Land, etc.)",advantages:"Feature cards highlighting your expertise and unique value",rate_my_agent:"Verified client reviews carousel powered by RateMyAgent",lifestyle_gallery:"Cinematic photo grid showcasing luxury living — pools, views, interiors",market_pulse:"Sleek market stats dashboard with avg price, days on market, inventory",concierge_services:"White-glove services showcase — staging, design, moving coordination",credentials:"Affiliation logos and specialty positioning (e.g. luxury and sports & entertainment divisions)",land_use_guide:"Interactive land use cards — Agriculture, Hunting, Equestrian, Recreational",land_valuation_cta:`"What's Your Land Worth?" — bold call-to-action for landowners`,acreage_showcase:"Large visual cards emphasizing lot size with aerial imagery",featured_video:"Embedded YouTube or Bunny video section for cinematic storytelling",schedule_cta:"Prominent booking section that sends visitors to your online scheduling calendar"},Eme={basic:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","agent_reviews","rate_my_agent","featured_video","schedule_cta","cta_banner"],luxury:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","agent_reviews","rate_my_agent","cta_banner","lifestyle_gallery","market_pulse","concierge_services","credentials","featured_video","schedule_cta"],"land-ranch":["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","agent_reviews","rate_my_agent","cta_banner","property_types","advantages","land_use_guide","land_valuation_cta","acreage_showcase","featured_video","schedule_cta"]};function WXt(t){return Eme[t]||Eme.basic}function D3t(t){const e=t.theme_config||{};return{themeTier:t.theme_tier||"basic",brandColor:t.brand_color||"#0f172a",accentColor:t.accent_color||"#3b82f6",fontFamily:t.font_family||"Inter",heroImageUrl:t.hero_image_url||null,homepageModules:Array.isArray(t.homepage_modules)&&t.homepage_modules.length?t.homepage_modules.map(r=>typeof r=="string"?{type:r,enabled:!0}:{enabled:!0,...r}):L3t,testimonials:Array.isArray(t.testimonials)?t.testimonials:[],featuredListingIds:t.featured_listing_ids||[],searchCities:Array.isArray(e.searchCities)?e.searchCities:[],searchZipCodes:Array.isArray(e.searchZipCodes)?e.searchZipCodes:[],searchCounties:Array.isArray(e.searchCounties)?e.searchCounties:[],searchSubdivisions:Array.isArray(e.searchSubdivisions)?e.searchSubdivisions:[],referralMode:e.referralMode===!0,referralPrimaryLabel:e.referralPrimaryLabel||void 0,referralPrimaryUrl:e.referralPrimaryUrl||void 0,referralSecondaryLabel:e.referralSecondaryLabel||void 0,referralSecondaryUrl:e.referralSecondaryUrl||void 0,divisionLogos:Array.isArray(e.divisionLogos)?e.divisionLogos:[],focusPages:Array.isArray(e.focusPages)?e.focusPages:[],headerLogoSize:["small","medium","large","xl"].includes(e.headerLogoSize)?e.headerLogoSize:"medium"}}const KXt=[{value:"small",label:"Small",hint:"Discreet — about 36px tall"},{value:"medium",label:"Standard",hint:"Default — about 48px tall"},{value:"large",label:"Large",hint:"Prominent — about 60px tall"},{value:"xl",label:"Extra large",hint:"Fills the header — about 68px tall"}],M3t={small:"h-8 sm:h-9 max-w-[140px]",medium:"h-10 sm:h-12 max-w-[180px]",large:"h-12 sm:h-[60px] max-w-[240px]",xl:"h-14 sm:h-[68px] max-w-[320px]"},O3t={small:"h-10 max-w-[160px]",medium:"h-12 max-w-[200px]",large:"h-16 max-w-[260px]",xl:"h-20 max-w-[320px]"};function dQ(t){return t==="small"||t==="large"||t==="xl"?t:"medium"}function F3t(t){return M3t[dQ(t)]}function B3t(t){return O3t[dQ(t)]}const z3t=new Set(["localhost","tile-portal.lovable.app","id-preview--b4ed24ae-0b44-4f4d-8676-c620f649ed8a.lovable.app","dashboard.relevelup.com","guestbook.relevelup.com","pages.relevelup.com","listings.relevelup.com"]);function $3t(t){const e=t.toLowerCase().replace(/:\d+$/,"");return!!(z3t.has(e)||e.endsWith(".lovable.app")||e.endsWith(".lovableproject.com")||e.endsWith(".lovable.dev"))}function yCe(){return new URLSearchParams(window.location.search).get("previewSlug")}function U3t(){const t=yCe();if(t)return t;const r=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return r?r[1]:null}function V3t(){const t=U3t(),e=!!yCe(),r=window.location.hostname,n=t?null:l_e(r),i=!t&&!$3t(r)&&r.includes(".")&&!o_e(r),a=t||n||(i?r:null),{data:c,isLoading:d,error:p}=jr({queryKey:["lead-site",a,i,e],queryFn:async()=>{var G;if(!a)return null;const g=Be.from("lead_sites").select("*"),v=e?g:g.eq("is_active",!0);let E;if(t)E=await v.eq("subdomain_slug",t).maybeSingle();else if(n)E=await v.ilike("custom_domain",n).maybeSingle();else if(i)E=await v.ilike("custom_domain",r).maybeSingle();else return null;const{data:T,error:j}=E;if(j)throw j;if(!T)return null;const{data:P}=await Be.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url, google_business_url, zillow_profile_url, realtor_profile_url, specialties").eq("id",T.agent_id).single();let C=null;if(T.show_team_logo)if(T.team_logo_url)C=T.team_logo_url;else{const{data:W}=await Be.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",T.agent_id).limit(1).maybeSingle();W&&((G=W.teams)!=null&&G.avatar_url)&&(C=W.teams.avatar_url)}const L=T.theme_config||{},O=W=>typeof W=="string"&&W.trim()?W.trim():null,F={id:T.id,agentId:T.agent_id,subdomainSlug:T.subdomain_slug,customDomain:T.custom_domain||null,mlsProviderId:T.mls_provider_id,siteTitle:T.site_title,siteTagline:T.site_tagline,leadRegistrationMode:T.lead_registration_mode||"disabled",registrationTriggerCount:T.registration_trigger_count??1,themeConfig:T.theme_config||{},themeTier:T.theme_tier||"basic",planTier:T.plan_tier||"paid",ownerType:T.owner_type||"agent",orgTier:T.org_tier||"essential",brokerageId:T.brokerage_id||null,teamId:T.team_id||null,orgName:T.org_name||null,orgLogoUrl:T.org_logo_url||null,orgLogoDarkUrl:T.org_logo_dark_url||null,orgProfile:T.org_profile||{},brandColor:T.brand_color||void 0,accentColor:T.accent_color||void 0,mlsServiceCities:Array.isArray(T.mls_service_cities)?T.mls_service_cities:[],isActive:T.is_active,brokerageLegalName:T.brokerage_legal_name||null,brokerageLicenseNumber:T.brokerage_license_number||null,agentLicenseNumber:T.agent_license_number||null,licenseState:T.license_state||null,mlsDisclaimerText:T.mls_disclaimer_text||null,mlsLogoUrl:T.mls_logo_url||null,equalHousingEnabled:T.equal_housing_enabled??!0,faviconUrl:T.favicon_url||null,ogImageUrl:T.og_image_url||null,showTeamLogo:T.show_team_logo??!1,teamLogoUrl:C,headerLogoSize:dQ(L.headerLogoSize),valuationLabel:O(L.valuationLabel),noMlsMode:T.no_mls_mode===!0,bookingUrl:T.booking_url||null,pageSubtitles:T.page_subtitles||{},agent:P?{id:P.id,full_name:P.name||"",avatar_url:O(L.agentHeadshotUrl)||P.avatar_url,email:P.email,phone:P.phone,title:O(L.agentTitle)||P.title,bio:O(L.agentBio)||P.bio,areas_served:P.areas_served||null,years_experience:P.years_experience??null,instagram_url:P.instagram_url||null,facebook_url:P.facebook_url||null,linkedin_url:P.linkedin_url||null,google_business_url:P.google_business_url||null,zillow_profile_url:P.zillow_profile_url||null,realtor_profile_url:P.realtor_profile_url||null,specialties:P.specialties||null}:void 0,testimonials:Array.isArray(T.testimonials)?T.testimonials.filter(W=>W&&typeof W=="object"&&W.text).map(W=>({name:String(W.name||"Client"),text:String(W.text),rating:typeof W.rating=="number"?W.rating:5,location:W.location?String(W.location):void 0})):[],seoMetaTitle:T.seo_meta_title||null,seoMetaDescription:T.seo_meta_description||null,googleSearchConsoleVerification:T.google_search_console_verification||null},$=D3t(T);return{siteConfig:F,themeConfig:$}},enabled:!!a,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1}),l=n||(i?r:null);return{siteConfig:(c==null?void 0:c.siteConfig)??null,themeConfig:(c==null?void 0:c.themeConfig)??null,isLoading:d,error:p,slug:t??(c==null?void 0:c.siteConfig.subdomainSlug)??null,customDomain:l}}async function q3t(t,e){try{await Be.functions.invoke("lead-site-notify",{body:{lead:e,lead_site_id:t}})}catch(r){console.warn("Lead notification failed:",r)}}function xCe(t){const e=`ls_identity_${t}`;try{const r=localStorage.getItem(e);if(r&&/^[0-9a-f-]{36}$/i.test(r))return r;const n=crypto.randomUUID();return localStorage.setItem(e,n),n}catch{return crypto.randomUUID()}}const G3t=Gv({lead_site_id:Us().uuid(),name:Us().trim().min(1).max(160),email:Us().trim().email().max(255),phone:Us().max(40).nullable().optional(),message:Us().max(5e3).nullable().optional(),source_page:Us().max(2e3).nullable().optional(),lead_type:Us().max(100),metadata:XZe(Us(),HG()).nullable().optional()});async function rP(t){const e=G3t.safeParse(t);if(!e.success)return{error:new Error("Please check your name, email, and message.")};const{error:r}=await Be.rpc("submit_identified_website_lead",{_site_id:e.data.lead_site_id,_token:xCe(e.data.lead_site_id),_lead:e.data});return{error:r}}async function YXt(t,e,r){const{error:n}=await Be.rpc("record_identified_property_view",{_site_id:t,_token:xCe(t),_mls_number:e,_address:(r==null?void 0:r.propertyAddress)||null,_photo:(r==null?void 0:r.photoUrl)||null});n&&console.warn("Property activity could not be recorded:",n.message)}function ZXt(t,e,r,n,i){return t!=="disabled"&&!e&&!r&&n>i}const _Ce=N.createContext(null);function VA(){const t=N.useContext(_Ce);if(!t)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return t}function aM({siteConfig:t,children:e}){const[r,n]=N.useState(null),[i,a]=N.useState(null),[c,d]=N.useState(!0);N.useEffect(()=>{let v=!0,E=0;const T=async C=>{var F;const L=++E;let{data:O}=await Be.from("lead_site_consumer_profiles").select("id, name, phone, contact_id").eq("user_id",C.id).eq("lead_site_id",t.id).maybeSingle();if(O&&!O.contact_id||!O&&((F=C.user_metadata)==null?void 0:F.consumer_site_id)===t.id){const{data:$}=await Be.from("lead_site_consumer_profiles").upsert({user_id:C.id,lead_site_id:t.id,name:(O==null?void 0:O.name)||C.user_metadata.full_name||"Website visitor",phone:(O==null?void 0:O.phone)||C.user_metadata.consumer_phone||null},{onConflict:"user_id,lead_site_id"}).select("id,name,phone").single();O=$}!v||L!==E||(a(O?{...O,email:C.email||""}:null),d(!1))},{data:{subscription:j}}=Be.auth.onAuthStateChange((C,L)=>{const O=(L==null?void 0:L.user)??null;n(O),O?window.setTimeout(()=>void T(O),0):(E+=1,a(null),d(!1))}),P=window.setTimeout(()=>{v&&(console.warn("Lead site auth initialization timed out."),d(!1))},8e3);return()=>{v=!1,window.clearTimeout(P),j.unsubscribe()}},[t.id]),N.useEffect(()=>{const v=new URL(window.location.href),E=v.searchParams.get("signin");E&&(v.searchParams.delete("signin"),window.history.replaceState({},"",v.pathname+v.search+v.hash),Be.auth.verifyOtp({type:"email",token_hash:E}).then(({error:T})=>{T&&console.warn("Sign-in link could not be used (it may already be used or expired).",T.message)}))},[]);const p=N.useCallback(async v=>{const E=v.email.toLowerCase().trim(),{data:T,error:j}=await Be.functions.invoke("consumer-auth-link",{body:{site_id:t.id,email:E,name:v.name.trim(),phone:v.phone.trim(),mode:"signup",redirect_to:window.location.href}});if(j)throw j;let P=!1;if(T!=null&&T.token_hash){const{error:C}=await Be.auth.verifyOtp({type:"email",token_hash:T.token_hash});C?console.error("Instant sign-in after registration failed:",C):P=!0}{const{error:C}=await rP({lead_site_id:t.id,name:v.name.trim(),email:E,phone:v.phone.trim(),message:P?"Created a website account (signed in)":"Requested a website account; email verification pending",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,verification_pending:!P}});if(C)throw C;q3t(t.id,{name:v.name.trim(),email:E,phone:v.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}return{instant:P,existing:(T==null?void 0:T.new_account)===!1}},[t.id]),l=N.useCallback(async(v,E)=>{const T=v.toLowerCase().trim(),{data:j,error:P}=await Be.functions.invoke("consumer-auth-link",{body:{site_id:t.id,email:T,mode:"signin",redirect_to:window.location.href}});if(P)throw P;let C=!1;if(j!=null&&j.token_hash){const{error:L}=await Be.auth.verifyOtp({type:"email",token_hash:j.token_hash});L||(C=!0,rP({lead_site_id:t.id,email:T,message:"Created a website account (signed in)",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,verification_pending:!1}}).catch(()=>{}))}return{instant:C}},[t.id]),g=N.useCallback(async()=>{await Be.auth.signOut(),n(null),a(null)},[]);return s.jsx(_Ce.Provider,{value:{user:r,profile:i,isLoading:c,signUp:p,signIn:l,signOut:g},children:e})}const vCe=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),bCe=new Set(["tomlois"]);function Cv(t,e){var r;return t?(e==null?void 0:e.referralMode)===!0||((r=t.themeConfig)==null?void 0:r.referralMode)===!0||t.noMlsMode===!0||vCe.has(t.id||"")||bCe.has((t.subdomainSlug||"").toLowerCase())||!t.mlsProviderId:!1}function H3t(t,e){var r;return t?((r=t.themeConfig)==null?void 0:r.referralMode)===!0||vCe.has(t.id||"")||bCe.has((t.subdomainSlug||"").toLowerCase()):!1}function XXt(t,e){return H3t(t)?"referral":Cv(t,e)?"direct":"idx"}function QXt(t){return`Contact ${t.split(" ")[0]||"Me"}`}const W3t="free_luxury",K3t="free_beta";function wCe(t){const e=t==null?void 0:t.planTier;return e===W3t||e===K3t}const JXt={idx_search:{title:"MLS / IDX Home Search",description:"Let visitors search every active MLS listing in your market, with saved searches and instant alerts."},mls_listings:{title:"MLS Listing Feeds",description:"Automatically feature live MLS listings, new listings and sold comps on your homepage and city pages."},cma_reports:{title:"Professional Home Value Reports",description:"Build branded home value reports (CMAs) with live MLS comps and share them with sellers."},custom_domain:{title:"Custom Branded Domain",description:"Point your own web address at your site instead of the free subdomain."},ai_content:{title:"AI Content Creation",description:"Auto-written blog posts, city guides and monthly market updates published to your site."}},qA="#c9a96e",Y3t="Schedule a Free Consultation",Z3t={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function Fy({bookingUrl:t,label:e=Y3t,className:r="",variant:n="solid",color:i=qA,size:a="md",onDark:c=!0,source:d}){if(!t)return null;const p=`inline-flex items-center justify-center gap-2.5 font-semibold tracking-[0.18em] uppercase rounded-full transition-all duration-300 ${Z3t[a]}`,l=n==="solid"?{backgroundColor:i,color:"#0d0b0a",boxShadow:`0 10px 30px -12px ${i}`}:{borderColor:i,color:i,borderWidth:1};return s.jsxs("a",{href:t,target:"_blank",rel:"noopener noreferrer","data-schedule-source":d,className:`${p} ${n==="solid"?"hover:brightness-110":`border hover:bg-[${i}]/10`} ${n==="outline"&&!c?"bg-white/0":""} ${r}`,style:l,children:[s.jsx(KW,{className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{children:e})]})}function eQt({bookingUrl:t,agentName:e,accentColor:r=qA,config:n={},luxury:i=!0}){const a=n.bookingUrl||t;if(!a)return null;const c=n.eyebrow||"No Cost. No Obligation.",d=n.sectionTitle||"Schedule a Free Consultation",p=n.subtitle||`Pick a time that works for you and ${e.split(" ")[0]} will personally call you for a free 30-minute real estate consultation.`,l=n.buttonLabel||"Book My Free Consultation",g=[{icon:su,title:n.point1Title||"30 Minutes",text:n.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:d5e,title:n.point2Title||"A Personal Call",text:n.point2Text||`${e.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:od,title:n.point3Title||"Real Answers",text:n.point3Text||"Pricing, strategy, and next steps for buying or selling — free of charge."}],v=i?"bg-[#12100e]":"bg-gray-950";return s.jsxs("section",{className:`relative py-24 ${v} overflow-hidden`,children:[s.jsx("div",{className:"absolute inset-0 opacity-[0.07] pointer-events-none",style:{background:`radial-gradient(circle at 50% 0%, ${r}, transparent 60%)`}}),s.jsx("div",{className:"relative max-w-5xl mx-auto px-6 text-center",children:s.jsxs(Sr.div,{initial:{opacity:0,y:24},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{duration:.7},children:[s.jsxs("div",{className:"flex items-center justify-center gap-4 mb-5",children:[s.jsx("div",{className:"h-px w-12 bg-white/10"}),s.jsx("span",{className:"text-[11px] tracking-[0.4em] uppercase",style:{color:r},children:c}),s.jsx("div",{className:"h-px w-12 bg-white/10"})]}),s.jsx("h2",{className:"text-3xl md:text-5xl text-white tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:d}),s.jsx("p",{className:"text-white/50 mt-5 text-lg max-w-2xl mx-auto leading-relaxed",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:p}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-14 text-left",children:g.map((E,T)=>s.jsxs("div",{className:"border border-white/10 bg-white/[0.03] p-6",children:[s.jsx(E.icon,{className:"h-5 w-5 mb-4",style:{color:r}}),s.jsx("p",{className:"text-white text-sm tracking-[0.15em] uppercase mb-2",children:E.title}),s.jsx("p",{className:"text-white/45 text-sm leading-relaxed",children:E.text})]},T))}),s.jsxs("div",{className:"mt-12 flex flex-col items-center gap-4",children:[s.jsx(Fy,{bookingUrl:a,label:l,size:"lg",color:r,source:"home_section"}),s.jsx("p",{className:"text-white/30 text-xs tracking-[0.2em] uppercase",children:"Opens in a new tab · Free 30-minute consultation"})]})]})})]})}function tQt({bookingUrl:t,accentColor:e=qA,headline:r="Prefer to talk it through?",subtext:n="Book a free 30-minute consultation at a time that works for you.",dark:i=!0,className:a="",source:c}){return t?s.jsxs("div",{className:`flex flex-col sm:flex-row sm:items-center sm:justify-between gap-5 p-6 md:p-8 border ${i?"border-white/10 bg-white/[0.03]":"border-gray-200 bg-gray-50 rounded-2xl"} ${a}`,children:[s.jsxs("div",{children:[s.jsx("p",{className:`text-lg ${i?"text-white":"text-gray-900"}`,style:{fontFamily:"'Playfair Display', Georgia, serif"},children:r}),s.jsx("p",{className:`text-sm mt-1 ${i?"text-white/45":"text-gray-600"}`,children:n})]}),s.jsx(Fy,{bookingUrl:t,label:"Schedule Now",color:e,size:"sm",className:"flex-shrink-0",source:c})]}):null}function X3t({bookingUrl:t,accentColor:e=qA}){const[r,n]=N.useState(!1),[i,a]=N.useState(!1);if(N.useEffect(()=>{sessionStorage.getItem("schedule-cta-dismissed")==="1"&&a(!0);const d=()=>n(window.scrollY>260);return d(),window.addEventListener("scroll",d,{passive:!0}),()=>window.removeEventListener("scroll",d)},[]),!t||i)return null;const c=()=>{sessionStorage.setItem("schedule-cta-dismissed","1"),a(!0)};return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`md:hidden fixed inset-x-0 bottom-0 z-[60] transition-transform duration-300 ${r?"translate-y-0":"translate-y-full"}`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:s.jsxs("div",{className:"bg-[#0d0b0a]/95 backdrop-blur-lg border-t border-white/10 px-4 py-3 flex items-center gap-3",children:[s.jsxs("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"flex-1 inline-flex items-center justify-center gap-2 rounded-full py-3 text-[11px] font-semibold tracking-[0.18em] uppercase",style:{backgroundColor:e,color:"#0d0b0a"},children:[s.jsx(KW,{className:"h-4 w-4"}),"Schedule Free Consultation"]}),s.jsx("button",{onClick:c,"aria-label":"Dismiss",className:"p-2 text-white/40 hover:text-white",children:s.jsx(Ra,{className:"h-4 w-4"})})]})}),s.jsx("div",{className:`hidden md:flex fixed bottom-6 left-6 z-[60] items-center gap-2 transition-all duration-300 ${r?"opacity-100 translate-y-0":"opacity-0 translate-y-4 pointer-events-none"}`,children:s.jsx(Fy,{bookingUrl:t,label:"Schedule a Free Consultation",size:"sm",color:e,source:"sticky"})})]})}function Q3t({bookingUrl:t,agentName:e}){return N.useEffect(()=>{if(t){const r=setTimeout(()=>window.location.replace(t),400);return()=>clearTimeout(r)}},[t]),s.jsx("div",{className:"min-h-[70vh] flex items-center justify-center bg-[#0d0b0a] px-6 text-center",children:s.jsxs("div",{children:[s.jsx(KW,{className:"h-8 w-8 mx-auto mb-6",style:{color:qA}}),s.jsx("h1",{className:"text-3xl md:text-4xl text-white tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:"Free 30-Minute Real Estate Consultation"}),s.jsx("p",{className:"text-white/45 mt-4",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:t?`Taking you to ${e}'s booking calendar…`:"Online booking is not available yet — please use the contact page."}),t&&s.jsx("div",{className:"mt-8",children:s.jsx(Fy,{bookingUrl:t,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}const hQ=` id, slug, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, description, video_link, mls_link, co_agent_name, co_agent_brokerage, co_agent_phone, co_agent_email, co_agent_photo_url, photos:listing_photos(id, photo_url, is_primary, sort_order) `;function FB(t){return jr({queryKey:["lead-site-exchange-listings",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:e,error:r}=await Be.from("listings").select(hQ).eq("agent_id",t).eq("show_on_lead_site",!0).eq("is_approved",!0).not("status","in","(sold,temp_off_market,withdrawn)").order("created_at",{ascending:!1});if(r)throw r;return e||[]}})}function fQ(t){return jr({queryKey:["lead-site-sold-listings",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:e,error:r}=await Be.from("listings").select(hQ).eq("agent_id",t).eq("show_on_lead_site",!0).eq("is_approved",!0).eq("status","sold").order("created_at",{ascending:!1});if(r)throw r;return e||[]}})}function rQt(t,e){return jr({queryKey:["lead-site-exchange-listing",t,e],enabled:!!t&&!!e,queryFn:async()=>{const r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e);let n=Be.from("listings").select(hQ).eq("agent_id",t).eq("show_on_lead_site",!0).eq("is_approved",!0);n=r?n.eq("id",e):n.eq("slug",e);const{data:i,error:a}=await n.maybeSingle();if(a)throw a;return i??null}})}function nQt(t){var e;return(e=t==null?void 0:t.photos)!=null&&e.length?[...t.photos].sort((r,n)=>Number(n.is_primary)-Number(r.is_primary)||(r.sort_order??0)-(n.sort_order??0)).map(r=>r.photo_url):[]}function iQt(t){return t?`$${t.toLocaleString()}`:"Price upon request"}const J3t="b4e0faa0-5246-4b05-8545-18596e7ff784",e4t=Gv({name:Us().trim().min(1,"Please enter your name.").max(160),email:Us().trim().email("Please enter a valid email.").max(255),phone:Us().trim().max(40),interest:g5(["Buying a home","Selling a home","Buying and selling","eXp Ready program","Other"]),preferredTime:Us().trim().max(200),message:Us().trim().max(4e3)});async function sQt(t,e){const r=e4t.parse(e),n={name:r.name,email:r.email,phone:r.phone||null,message:[`Interested in: ${r.interest}`,`Preferred contact time: ${r.preferredTime||"Not specified"}`,r.message&&`Message: ${r.message}`].filter(Boolean).join(` `),lead_type:"consultation",source_page:"/schedule"},{error:i}=await rP({lead_site_id:t,...n,metadata:{interest:r.interest,preferred_contact_time:r.preferredTime}});if(i)throw i;try{const{data:a,error:c}=await Be.functions.invoke("lead-site-notify",{body:{lead_site_id:t,lead:n}});return{emailSent:!c&&(a==null?void 0:a.success)===!0&&(a==null?void 0:a.sent)===1}}catch{return{emailSent:!1}}}const t4t="/__l5e/assets-v1/7e98e197-8135-428c-969f-07023434dec8/btb-emblem-white.webp",r4t={url:t4t},n4t="/assets/hero-Bp0n5rUQ.jpg",i4t="/assets/construction-DRPJW-Zl.jpg",s4t="/assets/design-DQodobBx.jpg",a4t="/assets/realestate-C0vC4CaI.jpg",o4t="/assets/lexington-BXiMdbEn.jpg",Vm={hero:n4t,construction:i4t,design:s4t,realestate:a4t,lexington:o4t},ru={legal:"Building The Bluegrass Realty",phone:"(859) 201-2101",phoneHref:"tel:+18592012101",address:"3320 Clay Mills Rd",cityLine:"Lexington, KY 40503",logoWhite:`https://tile-portal.lovable.app${r4t.url}`,facebook:"https://www.facebook.com/buildingthebluegrass",instagram:"https://www.instagram.com/buildingthebluegrass"},cl="https://www.buildingthebluegrass.com/wp-content/uploads/",pH=[{name:"Joey Svec",role:"CEO & Principal Broker",photo:cl+"fx-gs.jpeg",group:"Leadership",licensed:!0},{name:"Maria Gillette",role:"Principal of Real Estate & REALTOR®",photo:cl+"maria.jpeg",group:"Leadership",licensed:!0},{name:"Brad Boaz",role:"Landscape Architect & Planner",photo:cl+"BradBoaz.jpeg",group:"Construction & Design"},{name:"Elizabeth Powell",role:"Senior Associate Designer",photo:cl+"Elizabeth-headshot.jpg",group:"Construction & Design"},{name:"Jeff Moore",role:"Project Manager",photo:cl+"Jeff_Moore_Headshot_BW_Square-400x400.jpg",group:"Construction & Design"},{name:"Michael Wilbanks",role:"Project Manager",photo:cl+"Mike-headshot.jpg",group:"Construction & Design"},{name:"Noah Storkson",role:"Foreman",photo:cl+"Noah-headshot.jpg",group:"Construction & Design"},{name:"Jane Carter",role:"Estimator & Procurement Specialist",photo:cl+"Jane-Headshot.jpg",group:"Construction & Design"},{name:"Kristi White",role:"REALTOR®",photo:cl+"White_Kristi_BW-scaled-e1725038078208.jpg",group:"Real Estate",licensed:!0},{name:"Mary Grenet",role:"REALTOR®",photo:cl+"Grenet_Mary_BW-scaled-e1725037952355.jpg",group:"Real Estate",licensed:!0},{name:"Jim Cottle",role:"REALTOR®",photo:cl+"rsz_1jim-e1695063749369.jpg",group:"Real Estate",licensed:!0},{name:"Allison Haas",role:"REALTOR®",photo:cl+"allison.jpeg",group:"Real Estate",licensed:!0},{name:"Chris Haas",role:"REALTOR®",photo:cl+"chris.jpeg",group:"Real Estate",licensed:!0},{name:"Randi Mjos",role:"REALTOR®",photo:cl+"LMP_8523-scaled-e1695063828144.jpg",group:"Real Estate",licensed:!0},{name:"Cindi Baston",role:"REALTOR®",photo:cl+"Cindi-Baston-BW-scaled-e1725038818587.jpg",group:"Real Estate",licensed:!0},{name:"Valeria Kaidanov",role:"REALTOR®",photo:cl+"Valeria-headshot-.jpg",group:"Real Estate",licensed:!0},{name:"Joshua Cromwell",role:"REALTOR®",photo:cl+"Joshua-Cromwell_BW-scaled-e1725038396105.jpg",group:"Real Estate",licensed:!0},{name:"Monica Suetholz",role:"REALTOR®",photo:cl+"fx-gs5.jpeg",group:"Real Estate",licensed:!0},{name:"Angela Piech",role:"REALTOR®",photo:cl+"Angela-Piech-headshot.jpeg",group:"Real Estate",licensed:!0},{name:"Shannon Foster",role:"REALTOR®",photo:cl+"Shannon-headshot.jpg",group:"Real Estate",licensed:!0},{name:"Hampton Johnson",role:"REALTOR®",photo:cl+"Hampton-Johnson-BW.webp",group:"Real Estate",licensed:!0},{name:"Jodie Fite",role:"Accounting",photo:cl+"jodie-e1695063894957.png",group:"Operations"},{name:"Samantha Elliot",role:"Executive Assistant & Bookkeeper",photo:cl+"Sam-headshot.jpg",group:"Operations"}],gN=[{name:"Lexington",county:"Fayette County",blurb:"The heart of the Bluegrass — historic neighborhoods, a lively downtown, the University of Kentucky and horse country minutes away."},{name:"Nicholasville",county:"Jessamine County",blurb:"Just south of Lexington in Jessamine County, with established neighborhoods and new construction."},{name:"Georgetown",county:"Scott County",blurb:"A historic downtown in Scott County with easy access to I-75 and Lexington."},{name:"Versailles",county:"Woodford County",blurb:"Woodford County charm surrounded by farmland and the Kentucky River."},{name:"Winchester",county:"Clark County",blurb:"Clark County’s small-town character east of Lexington."},{name:"Richmond",county:"Madison County",blurb:"Madison County, home to Eastern Kentucky University."}],qT=t=>`/homes-for-sale-in-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,Tme=[{key:"buy",label:"Buy a home"},{key:"sell",label:"Sell my home"},{key:"value",label:"What’s my home worth?"},{key:"relocate",label:"Relocating to the Bluegrass"},{key:"explore",label:"Just exploring"}],SCe="https://wsrv.nl/",l4t=["cdn.photos.sparkplatform.com","images.unsplash.com","cdn.repliers.io","cdn.repliers.com","relzejiswnotikjgvjhz.supabase.co","supabase.co"],c4t={thumb:200,card:600,hero:1200,full:1920},u4t={thumb:70,card:75,hero:80,full:82};function aQt(t,e={}){return""}function d4t(t){if(!t||t.startsWith("data:")||t.startsWith("blob:")||t.startsWith(SCe)||t.includes("/functions/v1/mlsgrid-media")||t.includes("/functions/v1/trestle-media"))return!1;try{const e=new URL(t);return l4t.some(r=>e.hostname===r||e.hostname.endsWith("."+r))}catch{return!1}}function h4t(t,e={}){if(!t)return"";if(!d4t(t))return t;const r=e.variant??"card",n=e.width??c4t[r],i=e.quality??u4t[r],a=t.replace(/^https?:\/\//,""),c=new URLSearchParams({url:a,w:String(n),q:String(i),output:"webp"});return e.height&&c.set("h",String(e.height)),e.fit&&c.set("fit",e.fit),`${SCe}?${c.toString()}`}function PE({siteConfig:t,accentColor:e,sectionTitle:r,cities:n,count:i=12,mode:a,luxuryMode:c=!1}){const d=qa(),p=N.useRef(null),[l,g]=N.useState(!1),[v,E]=N.useState(!1),{data:T=[],isLoading:j}=jr({queryKey:["lead-site-carousel",t.id,a,n,i,t.agentId],queryFn:async()=>{const F="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/lead-site-search",$={leadSiteId:t.id,pageSize:i,propertyType:"Residential"},G=Q=>{const ee=(Q.propertyType||"").toLowerCase().replace(/\s+/g,"");return ee?ee.startsWith("residential")||ee.startsWith("singlefamily")||ee.startsWith("condo")||ee.startsWith("townhouse")||ee.startsWith("townhome")||ee.startsWith("multifamily")||ee.startsWith("manufactured"):!0},W=async Q=>{const ee=await fetch(F,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify(Q),signal:AbortSignal.timeout(15e3)});return ee.ok?((await ee.json()).listings||[]).filter(G).slice(0,i):[]};if(n){const Q=n.split(",").map(ee=>ee.trim()).filter(Boolean);Q.length>0&&($.filterCities=Q)}return a==="open_houses"&&($.openHousesOnly=!0),a==="my_listings"&&($.agentListings=!0,$.agentId=t.agentId),a==="new_listings"&&($.sortBy="newest"),await W($)},staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1,refetchOnMount:!1}),P=()=>{const F=p.current;F&&(g(F.scrollLeft>10),E(F.scrollLeft{const F=p.current;if(F)return P(),F.addEventListener("scroll",P,{passive:!0}),window.addEventListener("resize",P),()=>{F.removeEventListener("scroll",P),window.removeEventListener("resize",P)}},[T]);const C=F=>{const $=p.current;if(!$)return;const G=340;$.scrollBy({left:F==="left"?-G*2:G*2,behavior:"smooth"})},L={new_listings:"New on the Market",open_houses:"Open Houses",my_listings:"My Active Listings"},O={new_listings:"The latest properties just listed",open_houses:"Tour these homes in person",my_listings:"Properties I'm currently representing"};return j?s.jsx("section",{className:`py-16 md:py-20 overflow-hidden ${c?"bg-[#0d0b0a]":""}`,children:s.jsxs("div",{className:"max-w-[1400px] mx-auto px-6",children:[s.jsxs("div",{className:"text-center mb-10",children:[s.jsx("div",{className:`h-4 w-20 rounded mx-auto mb-3 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),s.jsx("div",{className:`h-8 w-72 rounded mx-auto mb-2 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),s.jsx("div",{className:`h-4 w-56 rounded mx-auto animate-pulse ${c?"bg-white/5":"bg-gray-200"}`})]}),s.jsx("div",{className:"flex gap-5",children:[1,2,3,4].map(F=>s.jsxs("div",{className:`min-w-[320px] rounded-2xl overflow-hidden ${c?"bg-white/5":"bg-gray-100"}`,children:[s.jsx("div",{className:`h-56 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),s.jsxs("div",{className:"p-5 space-y-3",children:[s.jsx("div",{className:`h-5 rounded w-24 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`}),s.jsx("div",{className:`h-4 rounded w-40 animate-pulse ${c?"bg-white/5":"bg-gray-200"}`})]})]},F))})]})}):T.length?s.jsx("section",{className:`py-16 md:py-20 overflow-hidden ${c?"bg-[#0d0b0a]":""}`,children:s.jsxs("div",{className:"max-w-[1400px] mx-auto px-6",children:[s.jsxs("div",{className:"flex items-end justify-between mb-10",children:[s.jsxs("div",{children:[s.jsx(Sr.p,{initial:{opacity:0,y:10},whileInView:{opacity:1,y:0},viewport:{once:!0},className:`text-sm tracking-[0.2em] uppercase font-semibold mb-2 ${c?"tracking-[0.4em]":""}`,style:{color:e},children:a==="open_houses"?"Open Houses":a==="my_listings"?"My Listings":"Just Listed"}),s.jsx(Sr.h2,{initial:{opacity:0,y:15},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{delay:.05},className:`text-3xl md:text-4xl tracking-tight ${c?"text-white":"text-gray-900 font-bold"}`,style:c?{fontFamily:"'Playfair Display', Georgia, serif"}:{},children:r||L[a]}),s.jsx(Sr.p,{initial:{opacity:0},whileInView:{opacity:1},viewport:{once:!0},transition:{delay:.1},className:`mt-1.5 ${c?"text-white/40":"text-gray-500"}`,children:O[a]})]}),s.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[s.jsx("button",{onClick:()=>C("left"),disabled:!l,className:`p-3 rounded-full border transition-all disabled:opacity-30 disabled:cursor-not-allowed ${c?"border-white/10 text-white/50 hover:border-white/30":"border-gray-200 text-gray-600 hover:bg-gray-50 hover:border-gray-300"}`,children:s.jsx(bg,{className:"h-5 w-5"})}),s.jsx("button",{onClick:()=>C("right"),disabled:!v,className:`p-3 rounded-full border transition-all disabled:opacity-30 disabled:cursor-not-allowed ${c?"border-white/10 text-white/50 hover:border-white/30":"border-gray-200 text-gray-600 hover:bg-gray-50 hover:border-gray-300"}`,children:s.jsx(uf,{className:"h-5 w-5"})})]})]}),s.jsxs("div",{className:"relative -mx-6",children:[s.jsxs("div",{ref:p,className:"flex gap-5 overflow-x-auto scrollbar-hide px-6 snap-x snap-mandatory",style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:[T.map((F,$)=>{var G,W,Z,Q;return s.jsx(Sr.div,{initial:{opacity:0,y:20},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{duration:.4,delay:$*.05},onClick:()=>d(`/listing/${F.mlsNumber}`),className:"group min-w-[300px] sm:min-w-[320px] max-w-[340px] flex-shrink-0 snap-start cursor-pointer",children:s.jsxs("div",{className:`overflow-hidden h-full flex flex-col ${c?"bg-[#161312] hover:bg-[#1a1715] transition-all duration-500":"bg-white rounded-2xl shadow-[0_2px_20px_-4px_rgba(0,0,0,0.08)] hover:shadow-[0_8px_40px_-8px_rgba(0,0,0,0.15)] transition-all duration-500"}`,children:[s.jsxs("div",{className:"relative h-56 overflow-hidden",children:[s.jsx("img",{src:h4t(((G=F.photos)==null?void 0:G[0])||"https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=600&q=75",{variant:"card"}),alt:F.address,className:"w-full h-full object-cover group-hover:scale-[1.06] transition-transform duration-700 ease-out",loading:"lazy",decoding:"async"}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent"}),s.jsx("div",{className:"absolute top-3 left-3 px-3 py-1 rounded-full text-[11px] font-bold tracking-wide uppercase text-white backdrop-blur-md",style:{backgroundColor:`${e}cc`},children:a==="open_houses"?"Open House":F.status||"Active"}),s.jsx("div",{className:"absolute bottom-3 left-3",children:s.jsxs("p",{className:"text-2xl font-bold text-white drop-shadow-lg",children:["$",(W=F.price)==null?void 0:W.toLocaleString()]})}),((Z=F.photos)==null?void 0:Z.length)>1&&s.jsxs("div",{className:"absolute bottom-3 right-3 px-2.5 py-1 bg-black/40 backdrop-blur-sm rounded-full text-[11px] text-white font-medium",children:[F.photos.length," photos"]})]}),s.jsxs("div",{className:"p-4 flex-1 flex flex-col",children:[s.jsx("p",{className:`font-semibold text-[15px] leading-snug mb-1 truncate ${c?"text-white/80":"text-gray-900"}`,children:F.address}),s.jsxs("p",{className:`text-sm mb-3 truncate ${c?"text-white/30":"text-gray-500"}`,children:[F.city,", ",F.state," ",F.zip]}),s.jsxs("div",{className:`flex items-center gap-4 mt-auto pt-3 border-t ${c?"border-white/5":"border-gray-100"}`,children:[s.jsxs("div",{className:`flex items-center gap-1.5 ${c?"text-white/30":"text-gray-600"}`,children:[s.jsx(tA,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"text-sm font-medium",children:F.bedrooms})]}),s.jsxs("div",{className:`flex items-center gap-1.5 ${c?"text-white/30":"text-gray-600"}`,children:[s.jsx(ww,{className:"h-3.5 w-3.5"}),s.jsx("span",{className:"text-sm font-medium",children:F.bathrooms})]}),s.jsxs("div",{className:`flex items-center gap-1.5 ${c?"text-white/30":"text-gray-600"}`,children:[s.jsx(s5e,{className:"h-3.5 w-3.5"}),s.jsxs("span",{className:"text-sm font-medium",children:[(Q=F.sqft)==null?void 0:Q.toLocaleString()," sqft"]})]})]})]})]})},F.mlsNumber)}),s.jsx(Sr.div,{initial:{opacity:0},whileInView:{opacity:1},viewport:{once:!0},onClick:()=>d(a==="open_houses"?"/search?openHouses=1":"/search"),className:"min-w-[200px] flex-shrink-0 snap-start cursor-pointer flex items-center justify-center",children:s.jsxs("div",{className:"text-center group",children:[s.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center mx-auto mb-3 transition-transform group-hover:scale-110",style:{backgroundColor:`${e}15`},children:s.jsx(lo,{className:"h-6 w-6",style:{color:e}})}),s.jsx("p",{className:`text-sm font-semibold transition-colors ${c?"text-white/50 group-hover:text-white":"text-gray-700 group-hover:text-gray-900"}`,children:"View All"})]})})]}),s.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-12 bg-gradient-to-l pointer-events-none md:hidden ${c?"from-[#0d0b0a]":"from-white"} to-transparent`})]})]})}):null}function GA(){N.useEffect(()=>{const t=document.querySelectorAll(".btb-reveal:not(.is-in)"),e=new IntersectionObserver(r=>r.forEach(n=>{n.isIntersecting&&(n.target.classList.add("is-in"),e.unobserve(n.target))}),{threshold:.12});return t.forEach(r=>e.observe(r)),()=>e.disconnect()})}const Ame=[{label:"Buy",to:"/buy",children:[{label:"Search All Homes",to:"/search"},{label:"Buying With Us",to:"/buy"},{label:"Land & Farms",to:"/search?propertyType=Land"},{label:"My Saved Homes",to:"/dashboard"}]},{label:"Sell",to:"/sell",children:[{label:"Selling With Us",to:"/sell"},{label:"What’s My Home Worth?",to:"/sell#value"}]},{label:"Communities",to:"/communities",children:[...gN.map(t=>({label:t.name,to:qT(t.name)})),{label:"All Communities",to:"/communities"}]},{label:"Agents",to:"/team"},{label:"Journal",to:"/blog"},{label:"About",to:"/about",children:[{label:"Our Story",to:"/about"},{label:"Our Team",to:"/team"},{label:"Join the Team",to:"/join"},{label:"Contact",to:"/contact"}]}];function f4t({children:t}){const{pathname:e}=ms(),r=e==="/",[n,i]=N.useState(!1),[a,c]=N.useState(!1);N.useEffect(()=>{const p=()=>i(window.scrollY>40);return p(),window.addEventListener("scroll",p,{passive:!0}),()=>window.removeEventListener("scroll",p)},[]),N.useEffect(()=>c(!1),[e]);const d=r&&!n&&!a;return s.jsxs("div",{className:"btb-site min-h-screen",children:[s.jsxs("header",{className:`fixed inset-x-0 top-0 z-50 transition-colors duration-300 ${d?"btb-light":"btb-bg-ink shadow-sm"}`,children:[s.jsxs("div",{className:`mx-auto flex max-w-[1400px] items-center justify-between px-5 lg:px-10 ${d?"h-24":"h-[72px]"} transition-all`,children:[s.jsxs(Nn,{to:"/",className:"flex items-center gap-3","aria-label":"Building The Bluegrass home",children:[s.jsx("img",{src:ru.logoWhite,alt:"",className:"h-11 w-11 object-contain"}),s.jsx("span",{className:"btb-serif text-xl leading-none hidden sm:block",children:"Building The Bluegrass"})]}),s.jsx("nav",{className:"hidden xl:flex items-center gap-8","aria-label":"Main",children:Ame.map(p=>s.jsxs("div",{className:"group relative",children:[s.jsxs(Nn,{to:p.to,className:"flex items-center gap-1 text-[0.8rem] tracking-[0.14em] uppercase py-6 opacity-90 hover:opacity-100",children:[p.label,p.children&&s.jsx(ad,{className:"h-3 w-3"})]}),p.children&&s.jsx("div",{className:"invisible opacity-0 group-hover:visible group-hover:opacity-100 group-focus-within:visible group-focus-within:opacity-100 transition absolute left-0 top-full min-w-[220px] btb-bg-paper btb-ink border btb-line py-3",children:p.children.map(l=>s.jsx(Nn,{to:l.to,className:"block px-5 py-2.5 text-sm hover:btb-accent",children:l.label},l.label))})]},p.label))}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("a",{href:ru.phoneHref,className:"hidden md:flex items-center gap-2 text-sm opacity-90",children:[s.jsx(Ui,{className:"h-4 w-4"}),ru.phone]}),s.jsxs(Nn,{to:"/search",className:"btb-btn btb-btn-light !py-3 !px-4",children:[s.jsx(ef,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Search Homes"})]}),s.jsx("button",{className:"xl:hidden p-2",onClick:()=>c(!a),"aria-label":a?"Close menu":"Open menu","aria-expanded":a,children:a?s.jsx(Ra,{className:"h-6 w-6"}):s.jsx(nA,{className:"h-6 w-6"})})]})]}),a&&s.jsxs("div",{className:"xl:hidden btb-bg-ink border-t btb-line-light max-h-[80vh] overflow-y-auto px-6 py-6 space-y-5",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsx(Nn,{to:"/search",className:"btb-btn btb-btn-light justify-center",children:"Search Homes"}),s.jsx(Nn,{to:"/contact",className:"btb-btn btb-btn-ghost justify-center",children:"Contact"})]}),Ame.map(p=>s.jsxs("div",{children:[s.jsx(Nn,{to:p.to,className:"btb-serif text-2xl block",children:p.label}),p.children&&s.jsx("div",{className:"mt-2 pl-1 space-y-1.5",children:p.children.map(l=>s.jsx(Nn,{to:l.to,className:"block text-sm opacity-75",children:l.label},l.label))})]},p.label)),s.jsxs("a",{href:ru.phoneHref,className:"flex items-center gap-2 text-sm",children:[s.jsx(Ui,{className:"h-4 w-4"}),ru.phone]})]})]}),s.jsx("main",{className:r?"":"pt-[72px]",children:t}),s.jsx(m4t,{})]})}function m4t(){return s.jsxs("footer",{className:"btb-bg-ink",children:[s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-12 md:grid-cols-12",children:[s.jsxs("div",{className:"md:col-span-5",children:[s.jsx("img",{src:ru.logoWhite,alt:"Building The Bluegrass",className:"h-16 w-16 object-contain mb-6"}),s.jsx("p",{className:"btb-serif text-3xl leading-tight max-w-sm",children:"Home, the Bluegrass way."}),s.jsxs("p",{className:"mt-6 text-sm opacity-70 leading-relaxed",children:[ru.address,s.jsx("br",{}),ru.cityLine,s.jsx("br",{}),s.jsx("a",{href:ru.phoneHref,children:ru.phone})]})]}),[["Real Estate",[["Search Homes","/search"],["Buy","/buy"],["Sell","/sell"],["Home Value","/sell#value"]]],["Explore",[...gN.slice(0,3).map(t=>[t.name,qT(t.name)]),["All Communities","/communities"],["Journal","/blog"]]],["Company",[["Our Story","/about"],["Our Team","/team"],["Join the Team","/join"],["Contact","/contact"]]]].map(([t,e])=>s.jsxs("div",{className:"md:col-span-2",children:[s.jsx("p",{className:"btb-eyebrow opacity-60 mb-5",children:t}),s.jsx("ul",{className:"space-y-3 text-sm",children:e.map(([r,n])=>s.jsx("li",{children:s.jsx(Nn,{to:n,className:"opacity-85 hover:opacity-100",children:r})},r))})]},t)),s.jsxs("div",{className:"md:col-span-1",children:[s.jsx("p",{className:"btb-eyebrow opacity-60 mb-5",children:"Follow"}),s.jsxs("ul",{className:"space-y-3 text-sm",children:[s.jsx("li",{children:s.jsx("a",{href:ru.facebook,target:"_blank",rel:"noreferrer",children:"Facebook"})}),s.jsx("li",{children:s.jsx("a",{href:ru.instagram,target:"_blank",rel:"noreferrer",children:"Instagram"})})]})]})]}),s.jsx("div",{className:"border-t btb-line-light",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-6 text-xs opacity-60 flex flex-col md:flex-row gap-3 justify-between",children:[s.jsxs("p",{children:["© ",new Date().getFullYear()," ",ru.legal,". All rights reserved. Equal Housing Opportunity."]}),s.jsx("p",{children:"Listing data provided courtesy of Imagine MLS. Information deemed reliable but not guaranteed."})]})})]})}function vO({compact:t=!1}){const e=qa(),[r,n]=N.useState(""),[i,a]=N.useState(""),[c,d]=N.useState(""),p=l=>{l.preventDefault();const g=new URLSearchParams;r.trim()&&g.set("q",r.trim()),i&&g.set("maxPrice",i),c&&g.set("beds",c),e(`/search?${g.toString()}`)};return s.jsxs("form",{onSubmit:p,className:`btb-bg-paper btb-ink grid gap-0 md:grid-cols-[1fr_180px_140px_auto] ${t?"":"shadow-2xl"}`,role:"search",children:[s.jsxs("label",{className:"px-6 py-4 border-b md:border-b-0 md:border-r btb-line",children:[s.jsx("span",{className:"btb-eyebrow btb-soft block mb-1",children:"Location"}),s.jsx("input",{value:r,onChange:l=>n(l.target.value),placeholder:"City, neighborhood, address or MLS #",className:"w-full bg-transparent outline-none text-base"})]}),s.jsxs("label",{className:"px-6 py-4 border-b md:border-b-0 md:border-r btb-line",children:[s.jsx("span",{className:"btb-eyebrow btb-soft block mb-1",children:"Max price"}),s.jsxs("select",{value:i,onChange:l=>a(l.target.value),className:"w-full bg-transparent outline-none",children:[s.jsx("option",{value:"",children:"Any"}),[3e5,45e4,6e5,8e5,1e6,15e5].map(l=>s.jsxs("option",{value:l,children:["$",(l/1e3).toLocaleString(),"k"]},l))]})]}),s.jsxs("label",{className:"px-6 py-4 border-b md:border-b-0 md:border-r btb-line",children:[s.jsx("span",{className:"btb-eyebrow btb-soft block mb-1",children:"Beds"}),s.jsxs("select",{value:c,onChange:l=>d(l.target.value),className:"w-full bg-transparent outline-none",children:[s.jsx("option",{value:"",children:"Any"}),[1,2,3,4,5].map(l=>s.jsxs("option",{value:l,children:[l,"+"]},l))]})]}),s.jsxs("button",{type:"submit",className:"btb-btn justify-center !py-5",children:[s.jsx(ef,{className:"h-4 w-4"}),"Search"]})]})}function yN({eyebrow:t,title:e,intro:r,image:n}){return s.jsxs("section",{className:"relative h-[62vh] min-h-[440px] overflow-hidden btb-light",children:[s.jsx("img",{src:n,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),s.jsxs("div",{className:"relative mx-auto flex h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pb-16",children:[s.jsx("p",{className:"btb-eyebrow mb-5 opacity-90",children:t}),s.jsx("h1",{className:"btb-serif text-5xl md:text-7xl max-w-4xl leading-[1.02]",children:e}),s.jsx("p",{className:"mt-6 max-w-xl text-lg opacity-90",children:r})]})]})}function Jv({title:t,description:e}){return s.jsxs(mc,{children:[s.jsx("title",{children:t}),s.jsx("meta",{name:"description",content:e}),s.jsx("meta",{property:"og:title",content:t}),s.jsx("meta",{property:"og:description",content:e})]})}function e0({siteConfig:t,defaultIntent:e="explore",heading:r="What are you imagining?"}){var j;const{pathname:n}=ms(),[i,a]=N.useState(e),[c,d]=N.useState({name:"",email:"",phone:"",message:""}),[p,l]=N.useState("idle"),[g,v]=N.useState(""),E=((j=Tme.find(P=>P.key===i))==null?void 0:j.label)||"Explore my options",T=async P=>{if(P.preventDefault(),v(""),!c.name.trim()||!c.email.trim()){v("Please add your name and email.");return}l("sending");const{error:C}=await rP({lead_site_id:t.id,name:c.name.trim(),email:c.email.trim(),phone:c.phone.trim()||null,message:`[${E}] ${c.message.trim()}`.trim(),source_page:n,lead_type:i==="sell"||i==="value"?"seller":i==="buy"?"buyer":"contact",metadata:{intent:i,intent_label:E,division:"real_estate"}});if(C){l("error"),v(C.message||"Something went wrong. Please try again or call us.");return}l("sent")};return s.jsx("section",{id:"inquire",className:"btb-bg-stone",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-32 grid gap-14 lg:grid-cols-2",children:[s.jsxs("div",{className:"btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Start a conversation"}),s.jsx("h2",{className:"btb-serif text-5xl md:text-6xl leading-[1.05]",children:r}),s.jsx("p",{className:"mt-6 btb-soft text-lg max-w-md",children:"Tell us where you are in the journey. A Building The Bluegrass agent will follow up personally — no pressure, just good advice."}),s.jsx("div",{className:"mt-10 flex flex-wrap gap-2",role:"radiogroup","aria-label":"What can we help with?",children:Tme.map(P=>s.jsx("button",{type:"button",role:"radio","aria-checked":i===P.key,onClick:()=>a(P.key),className:`px-4 py-2.5 text-sm border transition ${i===P.key?"btb-bg-ink border-transparent":"btb-line hover:btb-bg-paper"}`,children:P.label},P.key))})]}),p==="sent"?s.jsxs("div",{className:"btb-bg-paper p-10 md:p-14 flex flex-col justify-center",role:"status",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-4",children:"Received"}),s.jsxs("p",{className:"btb-serif text-4xl",children:["Thank you, ",c.name.split(" ")[0],"."]}),s.jsxs("p",{className:"mt-4 btb-soft",children:["Your note about “",E.toLowerCase(),"” is with our team. For anything urgent, call ",ru.phone,"."]})]}):s.jsxs("form",{onSubmit:T,className:"btb-bg-paper p-8 md:p-12 space-y-6",noValidate:!0,children:[s.jsxs("div",{className:"grid gap-6 sm:grid-cols-2",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Name *"}),s.jsx("input",{className:"btb-input",value:c.name,onChange:P=>d({...c,name:P.target.value}),autoComplete:"name",required:!0})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Phone"}),s.jsx("input",{className:"btb-input",value:c.phone,onChange:P=>d({...c,phone:P.target.value}),autoComplete:"tel",type:"tel"})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Email *"}),s.jsx("input",{className:"btb-input",type:"email",value:c.email,onChange:P=>d({...c,email:P.target.value}),autoComplete:"email",required:!0})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Tell us a little more"}),s.jsx("textarea",{className:"btb-input min-h-[110px] resize-none",value:c.message,onChange:P=>d({...c,message:P.target.value}),placeholder:i==="sell"||i==="value"?"Property address and timing…":"Neighborhoods, price range, timing…"})]}),g&&s.jsx("p",{className:"text-sm text-destructive",role:"alert",children:g}),s.jsx("button",{type:"submit",disabled:p==="sending",className:"btb-btn w-full justify-center",children:p==="sending"?"Sending…":s.jsxs(s.Fragment,{children:["Send to our team ",s.jsx(lo,{className:"h-4 w-4"})]})})]})]})})}function p4t({siteConfig:t}){GA();const[e,r]=N.useState(0),n=pH.filter(a=>a.group==="Leadership"),i=pH.filter(a=>a.group==="Real Estate").slice(0,6);return s.jsxs(s.Fragment,{children:[s.jsx(Jv,{title:"Building The Bluegrass Realty | Lexington, KY Homes for Sale",description:"Search every home for sale in Lexington and Central Kentucky. Boutique real estate service for buyers and sellers from Building The Bluegrass Realty."}),s.jsxs("section",{className:"relative h-[92svh] md:h-[100svh] min-h-[600px] overflow-hidden btb-light",children:[s.jsx("img",{src:Vm.hero,alt:"Kentucky farmhouse at sunset (temporary placeholder image)",width:1920,height:1088,fetchPriority:"high",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),s.jsxs("div",{className:"relative mx-auto flex h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pb-10 md:pb-14",children:[s.jsx("p",{className:"btb-eyebrow mb-6 opacity-90",children:"Building The Bluegrass Realty · Lexington, Kentucky"}),s.jsxs("h1",{className:"btb-serif text-[2.9rem] leading-[0.98] sm:text-7xl lg:text-[7.5rem] max-w-5xl",children:["Find your place",s.jsx("br",{}),s.jsx("em",{className:"font-normal",children:"in the Bluegrass."})]}),s.jsx("p",{className:"mt-7 max-w-xl text-lg opacity-90",children:"Boutique real estate for Lexington and Central Kentucky — every home on the market, and agents who know these communities by heart."}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[s.jsx(Nn,{to:"/search",className:"btb-btn btb-btn-light",children:"Search Homes"}),s.jsx(Nn,{to:"/sell#value",className:"btb-btn btb-btn-ghost",children:"What’s My Home Worth?"})]}),s.jsx("div",{className:"mt-14 hidden md:block",children:s.jsx(vO,{})}),s.jsxs("div",{className:"mt-4 hidden md:flex flex-wrap gap-x-6 gap-y-2 text-sm opacity-85",children:[["Lexington","Nicholasville","Georgetown","Versailles"].map(a=>s.jsx(Nn,{to:qT(a),className:"hover:underline",children:a},a)),s.jsx(Nn,{to:"/search?propertyType=Land",className:"hover:underline",children:"Land & Lots"})]})]})]}),s.jsx("section",{className:"md:hidden px-5 py-8 btb-bg-ink",children:s.jsx(vO,{compact:!0})}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-36 grid gap-12 lg:grid-cols-12 items-center",children:[s.jsx("div",{className:"lg:col-span-6 btb-reveal btb-img-zoom overflow-hidden aspect-[4/5]",children:s.jsx("img",{src:Vm.design,alt:"Warm, light-filled kitchen (temporary placeholder image)",loading:"lazy",width:1200,height:1504,className:"h-full w-full object-cover"})}),s.jsxs("div",{className:"lg:col-span-5 lg:col-start-8 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-6",children:"A boutique brokerage"}),s.jsxs("h2",{className:"btb-serif text-5xl md:text-6xl leading-[1.04]",children:["Local knowledge.",s.jsx("br",{}),"A more personal experience."]}),s.jsx("p",{className:"mt-8 btb-soft text-lg leading-relaxed",children:"With more than 100 years of combined experience, our REALTORS® treat every client as if they are our only client — thoughtful pricing, honest guidance and steady negotiation from the first showing to the closing table."}),s.jsx("p",{className:"mt-5 btb-soft leading-relaxed",children:"Our vision is simple: be your trusted property professional through relationships and excellence in service."}),s.jsx(Nn,{to:"/about",className:"btb-link mt-10 inline-block",children:"Our story"})]})]}),s.jsxs("section",{id:"paths",className:"btb-bg-ink",children:[s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pt-24 pb-10",children:[s.jsx("p",{className:"btb-eyebrow opacity-60 mb-5",children:"How we can help"}),s.jsx("h2",{className:"btb-serif text-5xl md:text-6xl max-w-3xl leading-[1.05]",children:"Wherever you are in the move, start here."})]}),s.jsx("div",{className:"grid md:grid-cols-3",children:[{k:"Buy",h:"Find the place for your next chapter.",b:"Search every listing across Central Kentucky, save favorites, get alerts and tour with an agent who knows the neighborhood.",to:"/buy",img:Vm.realestate,cta:"Start your search"},{k:"Sell",h:"Present your home at its best.",b:"Thoughtful pricing, strong presentation and a marketing plan built to bring the right buyer to your door.",to:"/sell",img:Vm.design,cta:"Talk about selling"},{k:"Communities",h:"Get to know the Bluegrass.",b:"Local guides, market snapshots and live homes for sale in Lexington and the towns around it.",to:"/communities",img:Vm.lexington,cta:"Explore communities"}].map((a,c)=>s.jsxs(Nn,{to:a.to,className:"group relative block h-[78vh] min-h-[520px] overflow-hidden btb-img-zoom btb-light",children:[s.jsx("img",{src:a.img,alt:"",loading:"lazy",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 btb-hero-shade"}),s.jsxs("div",{className:"relative flex h-full flex-col justify-between p-8 md:p-10",children:[s.jsxs("span",{className:"btb-eyebrow opacity-80",children:["0",c+1," — ",a.k]}),s.jsxs("div",{children:[s.jsx("h3",{className:"btb-serif text-4xl leading-tight",children:a.h}),s.jsx("p",{className:"mt-4 opacity-85 max-w-sm",children:a.b}),s.jsxs("span",{className:"btb-link mt-8 inline-flex items-center gap-2",children:[a.cta," ",s.jsx(Q_e,{className:"h-4 w-4"})]})]})]})]},a.k))})]}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-32 grid gap-10 md:grid-cols-12 items-end",children:[s.jsxs("div",{className:"md:col-span-7 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"The Journal"}),s.jsx("h2",{className:"btb-serif text-5xl md:text-6xl leading-[1.05]",children:"Market notes, neighborhood stories and advice from our agents."})]}),s.jsxs("div",{className:"md:col-span-4 md:col-start-9 btb-reveal",children:[s.jsx("p",{className:"btb-soft text-lg",children:"What’s selling, where prices are heading and what to know before you make a move in Central Kentucky."}),s.jsx(Nn,{to:"/blog",className:"btb-link mt-8 inline-block",children:"Read the Journal"})]})]}),s.jsx("section",{className:"btb-bg-paper border-y btb-line",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-10 lg:grid-cols-12 items-center",children:[s.jsxs("div",{className:"lg:col-span-5 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Homes across the Bluegrass"}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05]",children:"Explore every home on the market."}),s.jsx("p",{className:"mt-6 btb-soft text-lg",children:"Search live listings from Lexington to the surrounding counties — save favorites, set alerts, and request a showing with our agents."}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[s.jsx(Nn,{to:"/search",className:"btb-btn",children:"Explore all homes"}),s.jsx(Nn,{to:"/search?propertyType=Land",className:"btb-btn btb-btn-ghost",children:"Land & Lots"})]})]}),s.jsx("div",{className:"lg:col-span-6 lg:col-start-7 btb-reveal",children:s.jsx(vO,{compact:!0})})]})}),s.jsx("section",{className:"btb-bg-paper py-6",children:s.jsxs("div",{children:[s.jsx(PE,{siteConfig:t,accentColor:"#406E71",mode:"new_listings",sectionTitle:"Just Listed in the Bluegrass",count:12}),s.jsx(PE,{siteConfig:t,accentColor:"#406E71",mode:"open_houses",sectionTitle:"Upcoming Open Houses",count:12})]})}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-36 grid gap-12 lg:grid-cols-12",children:[s.jsxs("div",{className:"lg:col-span-5 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Discover the Bluegrass"}),s.jsx("h2",{className:"btb-serif text-5xl leading-[1.05]",children:"Places we know by heart."}),s.jsx("div",{className:"mt-10 border-t btb-line",children:gN.map((a,c)=>s.jsxs("div",{className:"border-b btb-line",children:[s.jsxs("button",{className:"flex w-full items-center justify-between py-5 text-left",onClick:()=>r(c),"aria-expanded":e===c,children:[s.jsx("span",{className:"btb-serif text-3xl",children:a.name}),s.jsx(ad,{className:`h-5 w-5 transition ${e===c?"rotate-180":""}`})]}),e===c&&s.jsxs("div",{className:"pb-6",children:[s.jsx("p",{className:"btb-soft",children:a.blurb}),s.jsxs("div",{className:"mt-4 flex gap-6",children:[s.jsxs(Nn,{to:qT(a.name),className:"btb-link",children:["Homes in ",a.name]}),s.jsx("a",{href:"#inquire",className:"btb-link",children:"Ask an agent"})]})]})]},a.name))})]}),s.jsx("div",{className:"lg:col-span-6 lg:col-start-7 overflow-hidden min-h-[420px] btb-reveal",children:s.jsx("img",{src:Vm.lexington,alt:"Bluegrass horse farm (temporary placeholder image)",loading:"lazy",className:"h-full w-full object-cover"})})]}),s.jsx("section",{className:"btb-bg-green",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 md:py-32",children:[s.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6 mb-14",children:[s.jsxs("div",{children:[s.jsx("p",{className:"btb-eyebrow opacity-70 mb-5",children:"The people behind the possibilities"}),s.jsx("h2",{className:"btb-serif text-5xl md:text-6xl max-w-2xl leading-[1.05]",children:"REALTORS® who know the Bluegrass."})]}),s.jsx(Nn,{to:"/team",className:"btb-link",children:"Meet our agents"})]}),s.jsx("div",{className:"grid gap-10 md:grid-cols-2 mb-14",children:n.map(a=>s.jsxs("div",{className:"flex gap-6 items-end btb-reveal",children:[s.jsx("img",{src:a.photo,alt:a.name,loading:"lazy",className:"w-40 h-52 object-cover object-top grayscale"}),s.jsxs("div",{children:[s.jsx("p",{className:"btb-serif text-3xl",children:a.name}),s.jsx("p",{className:"opacity-75 text-sm mt-1",children:a.role}),s.jsx("p",{className:"btb-eyebrow mt-3 opacity-60",children:"Brokerage leadership"})]})]},a.name))}),s.jsx("div",{className:"grid grid-cols-3 md:grid-cols-6 gap-4",children:i.map(a=>s.jsxs("div",{children:[s.jsx("img",{src:a.photo,alt:a.name,loading:"lazy",className:"aspect-[3/4] w-full object-cover object-top grayscale"}),s.jsx("p",{className:"mt-2 text-sm",children:a.name}),s.jsx("p",{className:"text-xs opacity-65",children:a.role})]},a.name))})]})}),s.jsx(e0,{siteConfig:t})]})}function ECe({steps:t}){return s.jsx("div",{className:"grid gap-px md:grid-cols-4 btb-bg-stone",children:t.map(([e,r],n)=>s.jsxs("div",{className:"btb-bg p-8 btb-reveal",children:[s.jsx("p",{className:"btb-serif text-5xl btb-accent",children:n+1}),s.jsx("p",{className:"mt-4 btb-serif text-2xl",children:e}),s.jsx("p",{className:"mt-2 btb-soft text-sm",children:r})]},e))})}function g4t(){return s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pb-24",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-8",children:"Popular communities"}),s.jsx("div",{className:"flex flex-wrap gap-3",children:gN.map(t=>s.jsx(Nn,{to:qT(t.name),className:"px-5 py-3 border btb-line hover:btb-bg-paper btb-serif text-xl",children:t.name},t.name))})]})}function y4t({siteConfig:t}){return GA(),s.jsxs(s.Fragment,{children:[s.jsx(Jv,{title:"Buy a Home in Lexington, KY | Building The Bluegrass Realty",description:"Search homes, land and new construction in Lexington and Central Kentucky with a boutique team of local REALTORS®."}),s.jsx(yN,{eyebrow:"Buy",title:"Find the place for your next chapter.",intro:"Every home on the market across Central Kentucky, and an agent who will tell you honestly what each one is — and isn’t.",image:Vm.realestate}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 -mt-10 relative z-10",children:s.jsx(vO,{})}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-8",children:"How buying with us works"}),s.jsx(ECe,{steps:[["Plan","Your goals, budget, timing and must-haves."],["Search","Live MLS listings, saved favorites and instant alerts."],["Tour & offer","Private showings and a strong, well-priced offer."],["Close","Inspections, appraisal and closing day, handled."]]})]}),s.jsx(g4t,{}),s.jsx(e0,{siteConfig:t,defaultIntent:"buy",heading:"Let’s find your place."})]})}function x4t({siteConfig:t}){return GA(),s.jsxs(s.Fragment,{children:[s.jsx(Jv,{title:"Sell Your Home in Lexington, KY | Building The Bluegrass Realty",description:"Pricing, presentation and marketing that bring the right buyer. Request a free home value from Building The Bluegrass Realty."}),s.jsx(yN,{eyebrow:"Sell",title:"Present your home at its best.",intro:"Thoughtful pricing, beautiful presentation and steady negotiation — with a boutique team that treats your sale like it’s our only one.",image:Vm.design}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-8",children:"How selling with us works"}),s.jsx(ECe,{steps:[["Price","A clear, local market analysis of your home."],["Prepare","Practical advice on what’s worth fixing, and what isn’t."],["Market","Professional photography, MLS and targeted promotion."],["Negotiate","Offers, inspections and closing, handled for you."]]})]}),s.jsx("div",{id:"value",className:"scroll-mt-24",children:s.jsx(e0,{siteConfig:t,defaultIntent:"value",heading:"What’s your home worth?"})})]})}function _4t({siteConfig:t}){return GA(),s.jsxs(s.Fragment,{children:[s.jsx(Jv,{title:"Our Story | Building The Bluegrass",description:"A Lexington real estate brokerage built on relationships, service and faith — giving 10% of all profits to charity."}),s.jsx(yN,{eyebrow:"Our story",title:"To be your trusted property professional.",intro:"A Lexington brokerage built to be the local expert through relationships, with excellence in service to our clients.",image:Vm.lexington}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-px md:grid-cols-3 btb-bg-stone",children:[["We Connect","Passions and gifts to serve clients through a trustworthy, fulfilling and educational experience."],["We Believe","Leadership provides the opportunity to serve others; whoever brings blessings will be enriched."],["We Give","Time and resources to others, giving 10% of all profits to charities."]].map(([e,r])=>s.jsxs("div",{className:"btb-bg p-10 btb-reveal",children:[s.jsx("p",{className:"btb-serif text-4xl",children:e}),s.jsx("p",{className:"mt-4 btb-soft leading-relaxed",children:r})]},e))}),s.jsxs("section",{className:"mx-auto max-w-3xl px-5 pb-24 btb-reveal",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-6",children:"Foundational principles"}),s.jsx("div",{className:"space-y-10",children:[["Relationship","Matthew 6:28–34","A vertical relationship needs to be established before we can make a horizontal impact — serving clients and having true relationships with others."],["Worth","Genesis 1:27 & Ephesians 3:6","Rather than chasing a leaderboard, we ask where you find your worth — made in God’s image, with Him all things are possible."],["Revenue","Malachi 3:8–12","Finances are a tool to strengthen the Kingdom. We give a 10 percent tithe first, and stay faithful to that principle."],["Generational","Exodus 20:5–6","Building a stable, influential company for the community, meant to last for generations to come."]].map(([e,r,n])=>s.jsxs("div",{className:"border-t btb-line pt-6",children:[s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("h3",{className:"btb-serif text-3xl",children:e}),s.jsx("span",{className:"btb-soft text-sm italic",children:r})]}),s.jsx("p",{className:"mt-3 btb-soft leading-relaxed",children:n})]},e))})]}),s.jsx(e0,{siteConfig:t})]})}function v4t({siteConfig:t}){GA();const e=["Leadership","Real Estate","Operations"];return s.jsxs(s.Fragment,{children:[s.jsx(Jv,{title:"Our Team | Building The Bluegrass",description:"Meet the REALTORS® and staff of Building The Bluegrass in Lexington, KY."}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pt-20 pb-6",children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Our team"}),s.jsx("h1",{className:"btb-serif text-6xl md:text-7xl max-w-3xl leading-[1.02]",children:"The people behind the possibilities."})]}),e.map(r=>s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-14",children:[s.jsxs("div",{className:"flex items-baseline justify-between border-b btb-line pb-4 mb-10",children:[s.jsx("h2",{className:"btb-serif text-4xl",children:r}),r==="Real Estate"&&s.jsx("span",{className:"btb-eyebrow btb-soft",children:"Licensed REALTORS®"})]}),s.jsx("div",{className:`grid gap-8 ${r==="Leadership"?"sm:grid-cols-2 lg:grid-cols-3":"grid-cols-2 sm:grid-cols-3 lg:grid-cols-5"}`,children:pH.filter(n=>n.group===r).map(n=>s.jsxs("div",{className:"btb-reveal",children:[s.jsx("div",{className:"overflow-hidden aspect-[3/4]",children:s.jsx("img",{src:n.photo,alt:n.name,loading:"lazy",className:"h-full w-full object-cover object-top grayscale hover:grayscale-0 transition duration-700"})}),s.jsx("p",{className:`btb-serif mt-4 ${r==="Leadership"?"text-3xl":"text-2xl"}`,children:n.name}),s.jsx("p",{className:"btb-soft text-sm",children:n.role})]},n.name))})]},r)),s.jsx(e0,{siteConfig:t})]})}function b4t({siteConfig:t}){return s.jsxs(s.Fragment,{children:[s.jsx(Jv,{title:"Join the Team | Building The Bluegrass",description:"Real estate careers at Building The Bluegrass in Lexington, KY."}),s.jsx(yN,{eyebrow:"Join the team",title:"Build a career with purpose.",intro:"REALTORS® who want to serve clients well, grow together and give back to the community.",image:Vm.construction}),s.jsx(e0,{siteConfig:t,defaultIntent:"explore",heading:"Tell us about yourself."})]})}function w4t({siteConfig:t}){return GA(),s.jsxs(s.Fragment,{children:[s.jsx(Jv,{title:"Central Kentucky Communities | Building The Bluegrass",description:"Local guides to Lexington, Nicholasville, Georgetown, Versailles, Winchester and Richmond with live homes for sale."}),s.jsx(yN,{eyebrow:"Communities",title:"Discover the Bluegrass.",intro:"Guides to the places our agents know and serve — market snapshots, local favorites and live homes for sale.",image:Vm.lexington}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-px md:grid-cols-3 btb-bg-stone",children:gN.map(e=>s.jsxs("div",{className:"btb-bg p-10 btb-reveal",children:[s.jsx("h2",{className:"btb-serif text-4xl",children:e.name}),s.jsx("p",{className:"mt-4 btb-soft",children:e.blurb}),s.jsx("p",{className:"btb-eyebrow btb-soft mt-2",children:e.county}),s.jsxs(Nn,{to:qT(e.name),className:"btb-link mt-6 inline-block",children:["Homes in ",e.name]})]},e.name))}),s.jsx(e0,{siteConfig:t,defaultIntent:"buy"})]})}function S4t({siteConfig:t}){const[e]=zv();return s.jsxs(s.Fragment,{children:[s.jsx(Jv,{title:"Contact | Building The Bluegrass",description:"Contact Building The Bluegrass at 3320 Clay Mills Rd, Lexington, KY 40503 — (859) 201-2101."}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pt-20 pb-4 grid gap-10 md:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"btb-eyebrow btb-accent mb-5",children:"Contact"}),s.jsx("h1",{className:"btb-serif text-6xl md:text-7xl leading-[1.02]",children:"Let’s talk."})]}),s.jsxs("div",{className:"md:pt-10 btb-soft text-lg space-y-2",children:[s.jsxs("p",{children:[ru.address,s.jsx("br",{}),ru.cityLine]}),s.jsx("p",{children:s.jsx("a",{href:ru.phoneHref,className:"btb-ink",children:ru.phone})})]})]}),s.jsx(e0,{siteConfig:t,defaultIntent:e.get("intent")||"explore"})]})}function __({children:t}){const e=N.useRef(null);return s.jsx("div",{ref:e,className:"btb-bg-paper min-h-[70vh]",children:t})}function mQ(t){return jr({queryKey:["org-site-roster",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:e,error:r}=await Be.rpc("get_org_site_roster",{p_site_id:t});if(r)throw r;return e||[]}})}function oQt(t,e=!1){return jr({queryKey:["org-site-listings",t,e],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:r,error:n}=await Be.rpc("get_org_site_listings",{p_site_id:t,p_sold:e});if(n)throw n;return r||[]}})}function lQt(t){return t?`$${Math.round(t).toLocaleString()}`:"Price upon request"}const E4t="/assets/hero-kv4I0DLE.jpg",T4t="/assets/lexington-DDS8S5Ti.jpg",A4t="/assets/georgetown-CDefc5Gd.jpg",k4t="/assets/winchester-BRay9GI-.jpg",I4t="/assets/interior-BGPkmSFt.jpg",iu={hero:E4t,lexington:T4t,georgetown:A4t,winchester:k4t,interior:I4t},Cd={name:"RE/MAX Creative Realty",phone:"(859) 422-2000",phoneHref:"tel:+18594222000",tollFree:"(800) 860-7468",founded:1987,broker:"Sarith “Sari” Lawrence, Principal Broker"},GV=t=>`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(t)}`,nP=[{key:"lexington",name:"Lexington",address:"2808 Palumbo Dr, Unit 100",cityLine:"Lexington, KY 40509",hours:"Mon–Fri · 8:30am–5:30pm",image:"lexington",note:"Our main office on the corner of Man o’ War and Palumbo, just off I-75 at exit 108.",map:GV("2808 Palumbo Dr Unit 100, Lexington, KY 40509")},{key:"georgetown",name:"Georgetown",address:"128 Edwards Ave",cityLine:"Georgetown, KY 40324",hours:"Flexible hours — call ahead",image:"georgetown",note:"Serving Scott County and the I-75 corridor north of Lexington.",map:GV("128 Edwards Ave, Georgetown, KY 40324")},{key:"winchester",name:"Winchester",address:"804 Bypass Rd",cityLine:"Winchester, KY 40391",hours:"By appointment — call ahead",image:"winchester",note:"Home base for Clark County and the eastern Bluegrass.",map:GV("804 Bypass Rd, Winchester, KY 40391")}],U3=[{name:"Lexington",county:"Fayette County",image:"lexington",blurb:"Historic neighborhoods, a lively downtown, the University of Kentucky and horse farms minutes away."},{name:"Georgetown",county:"Scott County",image:"georgetown",blurb:"A walkable historic downtown, Georgetown College and an easy I-75 commute."},{name:"Winchester",county:"Clark County",image:"winchester",blurb:"Small-town character, rolling farmland and room to breathe east of Lexington."},{name:"Nicholasville",county:"Jessamine County",image:"interior",blurb:"Established neighborhoods and new construction just south of Lexington."},{name:"Versailles",county:"Woodford County",image:"hero",blurb:"Horse country charm along the Kentucky River."},{name:"Richmond",county:"Madison County",image:"winchester",blurb:"Home to Eastern Kentucky University and growing neighborhoods."},{name:"Frankfort",county:"Franklin County",image:"georgetown",blurb:"Kentucky’s capital city, with historic homes and river views."},{name:"Lawrenceburg",county:"Anderson County",image:"hero",blurb:"Bourbon country living with a close-knit feel."}],iP=t=>`/homes-for-sale-in-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`,HV=[{key:"buy",label:"Buy a home"},{key:"sell",label:"Sell my home"},{key:"value",label:"What’s my home worth?"},{key:"relocate",label:"Moving to Kentucky"},{key:"join",label:"Join RE/MAX Creative"}];function TCe(t){const e=(t||"").replace(/\D/g,""),r=e.length===11&&e.startsWith("1")?e.slice(1):e;return r.length!==10?null:{phone:`(${r.slice(0,3)}) ${r.slice(3,6)}-${r.slice(6)}`,phoneHref:`tel:+1${r}`}}const If=t=>typeof t=="string"&&t.trim()?t.trim():null;function ACe(t){const e=t.ownerType==="brokerage"?"brokerage":t.ownerType==="team"?"team":"agent";if(e==="brokerage")return{mode:e,name:Cd.name,first:Cd.name,phone:Cd.phone,phoneHref:Cd.phoneHref,email:null,photo:null,title:"Real estate brokerage",bio:null};const r=t.themeConfig||{},n=t.agent||{},i=If((t.siteTitle||"").split("|")[0]),a=e==="team"?If(t.orgName)||i||"Our Team":If(n.full_name)||i||"Your Agent",c=TCe(If(r.agentPhone)||n.phone)||{phone:Cd.phone,phoneHref:Cd.phoneHref};return{mode:e,name:a,first:e==="agent"?a.split(/\s+/)[0]:a,...c,email:If(r.agentEmail)||If(n.email),photo:If(r.agentHeadshotUrl)||If(n.avatar_url),title:If(r.agentTitle)||If(n.title)||(e==="team"?"Real estate team":"REALTOR®"),bio:If(r.agentBio)||If(n.bio)}}const j4t="/__l5e/assets-v1/46dc71ce-4743-4cc2-b8f2-7899c82a15ba/remax-balloon-mark.webp",NE={url:j4t},gH="Lexington, Georgetown, Winchester, Nicholasville, Versailles, Richmond";function BB(){N.useEffect(()=>{const t=document.querySelectorAll(".rmc-reveal:not(.is-in)"),e=new IntersectionObserver(r=>r.forEach(n=>{n.isIntersecting&&(n.target.classList.add("is-in"),e.unobserve(n.target))}),{threshold:.1});return t.forEach(r=>e.observe(r)),()=>e.disconnect()})}function Pv({title:t,description:e}){return s.jsxs(mc,{children:[s.jsx("title",{children:t}),s.jsx("meta",{name:"description",content:e}),s.jsx("meta",{property:"og:title",content:t}),s.jsx("meta",{property:"og:description",content:e})]})}const kCe=N.createContext(ACe({ownerType:"brokerage"})),kg=()=>N.useContext(kCe);function ICe({light:t=!0}){const e=kg();return e.mode!=="brokerage"?s.jsxs("span",{className:"flex items-center gap-3",children:[s.jsx("img",{src:NE.url,alt:"","aria-hidden":!0,className:"block h-10 w-auto shrink-0 drop-shadow"}),s.jsxs("span",{className:"leading-none",children:[s.jsx("span",{className:`block text-lg md:text-xl font-bold tracking-tight ${t?"":"rmc-blue"}`,children:e.name}),s.jsxs("span",{className:"block text-[0.6rem] tracking-[0.28em] uppercase opacity-80 mt-1",children:["RE",s.jsx("span",{className:"rmc-red",children:"/"}),"MAX Creative Realty"]})]})]}):s.jsxs("span",{className:"flex items-center gap-3",children:[s.jsx("img",{src:NE.url,alt:"","aria-hidden":!0,className:"block h-10 w-auto shrink-0 drop-shadow"}),s.jsxs("span",{className:"leading-none",children:[s.jsxs("span",{className:`block text-xl font-bold tracking-tight ${t?"":"rmc-blue"}`,children:["RE",s.jsx("span",{className:"rmc-red",children:"/"}),"MAX"]}),s.jsx("span",{className:"block text-[0.62rem] tracking-[0.32em] uppercase opacity-80 mt-1",children:"Creative Realty"})]})]})}const kme=[{label:"Buy",to:"/buy",children:[{label:"Search All Homes",to:"/search"},{label:"Buying With Us",to:"/buy"},{label:"Farms & Land",to:"/search?propertyType=Land"},{label:"My Saved Homes",to:"/dashboard"}]},{label:"Sell",to:"/sell",children:[{label:"Selling With Us",to:"/sell"},{label:"What’s My Home Worth?",to:"/sell#inquire"}]},{label:"Communities",to:"/communities",children:[...U3.slice(0,6).map(t=>({label:t.name,to:iP(t.name)})),{label:"All Communities",to:"/communities"}]},{label:"Agents",to:"/agents"},{label:"Offices",to:"/offices"},{label:"About",to:"/about",children:[{label:"Our Story",to:"/about"},{label:"Join Our Team",to:"/join"},{label:"Market Blog",to:"/blog"},{label:"Contact",to:"/contact"}]}];function C4t(t){return t==="brokerage"?kme:kme.map(e=>e.label==="About"?{...e,children:e.children.filter(r=>r.to!=="/join")}:e).filter(e=>t==="team"||e.label!=="Agents").map(e=>e.label==="Agents"?{...e,label:"Our Team"}:e)}function P4t({children:t,siteConfig:e}){const r=N.useMemo(()=>ACe(e),[e]),n=C4t(r.mode),{pathname:i}=ms(),a=i==="/",[c,d]=N.useState(!1),[p,l]=N.useState(!1);N.useEffect(()=>{const v=()=>d(window.scrollY>40);return v(),window.addEventListener("scroll",v,{passive:!0}),()=>window.removeEventListener("scroll",v)},[]),N.useEffect(()=>l(!1),[i]);const g=a&&!c&&!p;return s.jsx(kCe.Provider,{value:r,children:s.jsxs("div",{className:"rmc-site min-h-screen",children:[s.jsxs("header",{className:`fixed inset-x-0 top-0 z-50 transition-all duration-300 ${g?"rmc-light":"rmc-bg-navy shadow-lg"}`,children:[!g&&s.jsx("div",{className:"rmc-stripe"}),s.jsxs("div",{className:`mx-auto flex max-w-[1400px] items-center justify-between px-5 lg:px-10 ${g?"h-24":"h-[72px]"} transition-all`,children:[s.jsx(Nn,{to:"/","aria-label":`${r.name} home`,children:s.jsx(ICe,{})}),s.jsx("nav",{className:"hidden xl:flex items-center gap-7","aria-label":"Main",children:n.map(v=>s.jsxs("div",{className:"group relative",children:[s.jsxs(Nn,{to:v.to,className:"flex items-center gap-1 text-[0.8rem] font-semibold tracking-[0.12em] uppercase py-6 opacity-90 hover:opacity-100",children:[v.label,v.children&&s.jsx(ad,{className:"h-3 w-3"})]}),v.children&&s.jsx("div",{className:"invisible opacity-0 group-hover:visible group-hover:opacity-100 group-focus-within:visible group-focus-within:opacity-100 transition absolute left-0 top-full min-w-[230px] rmc-card py-3 text-[hsl(var(--rmc-ink))]",children:v.children.map(E=>s.jsx(Nn,{to:E.to,className:"block px-5 py-2.5 text-sm hover:rmc-red",children:E.label},E.label))})]},v.label))}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("a",{href:r.phoneHref,className:"hidden md:flex items-center gap-2 text-sm font-semibold",children:[s.jsx(Ui,{className:"h-4 w-4"}),r.phone]}),s.jsxs(Nn,{to:"/search",className:"rmc-btn !py-3 !px-4",children:[s.jsx(ef,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Search"})]}),s.jsx("button",{className:"xl:hidden p-2",onClick:()=>l(!p),"aria-label":p?"Close menu":"Open menu","aria-expanded":p,children:p?s.jsx(Ra,{className:"h-6 w-6"}):s.jsx(nA,{className:"h-6 w-6"})})]})]}),p&&s.jsxs("div",{className:"xl:hidden rmc-bg-navy border-t rmc-line-light max-h-[80vh] overflow-y-auto px-6 py-6 space-y-5",children:[n.map(v=>s.jsxs("div",{children:[s.jsx(Nn,{to:v.to,className:"rmc-display text-2xl block",children:v.label}),v.children&&s.jsx("div",{className:"mt-2 space-y-1.5",children:v.children.map(E=>s.jsx(Nn,{to:E.to,className:"block text-sm opacity-75",children:E.label},E.label))})]},v.label)),s.jsxs("a",{href:r.phoneHref,className:"flex items-center gap-2 text-sm",children:[s.jsx(Ui,{className:"h-4 w-4"}),r.phone]})]})]}),s.jsx("main",{className:a?"":"pt-[76px]",children:t}),s.jsx(N4t,{})]})})}function N4t(){const t=kg();return s.jsxs("footer",{className:"rmc-bg-navy",children:[s.jsx("div",{className:"rmc-stripe"}),s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-16 grid gap-12 lg:grid-cols-12",children:[s.jsxs("div",{className:"lg:col-span-4",children:[s.jsx(ICe,{}),s.jsx("p",{className:"rmc-display text-3xl mt-6 max-w-xs leading-tight",children:t.mode==="brokerage"?s.jsxs(s.Fragment,{children:["Central Kentucky’s original RE/MAX — since ",Cd.founded,"."]}):s.jsx(s.Fragment,{children:"Your Bluegrass home, handled with care."})}),t.email&&s.jsxs("a",{href:`mailto:${t.email}`,className:"mt-3 flex items-center gap-2 text-sm opacity-85",children:[s.jsx(rs,{className:"h-4 w-4"}),t.email]}),s.jsxs("a",{href:t.phoneHref,className:"mt-6 inline-flex items-center gap-2 font-semibold",children:[s.jsx(Ui,{className:"h-4 w-4"}),t.phone]})]}),s.jsx("div",{className:"lg:col-span-5 grid gap-8 sm:grid-cols-3",children:nP.map(e=>s.jsxs("div",{className:"text-sm",children:[s.jsx("p",{className:"rmc-eyebrow opacity-60 mb-3",children:e.name}),s.jsxs("p",{className:"opacity-85 leading-relaxed",children:[e.address,s.jsx("br",{}),e.cityLine]}),s.jsx("a",{href:e.map,target:"_blank",rel:"noreferrer",className:"mt-2 inline-block text-xs underline opacity-70",children:"Directions"})]},e.key))}),s.jsxs("div",{className:"lg:col-span-3 grid grid-cols-2 gap-6 text-sm",children:[s.jsx("ul",{className:"space-y-2.5",children:[["Search Homes","/search"],["Buy","/buy"],["Sell","/sell"],["Communities","/communities"]].map(([e,r])=>s.jsx("li",{children:s.jsx(Nn,{to:r,className:"opacity-85 hover:opacity-100",children:e})},e))}),s.jsx("ul",{className:"space-y-2.5",children:(t.mode==="brokerage"?[["Our Agents","/agents"],["Offices","/offices"],["Join Us","/join"],["Contact","/contact"]]:[[t.mode==="team"?"Our Team":"About",t.mode==="team"?"/agents":"/about"],["Offices","/offices"],["Blog","/blog"],["Contact","/contact"]]).map(([e,r])=>s.jsx("li",{children:s.jsx(Nn,{to:r,className:"opacity-85 hover:opacity-100",children:e})},e))})]})]}),s.jsx("div",{className:"border-t rmc-line-light",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-6 text-xs opacity-60 space-y-1.5",children:[s.jsxs("p",{children:["© ",new Date().getFullYear()," ",t.mode==="brokerage"?"":`${t.name} · `,"RE/MAX Creative Realty. Each office independently owned and operated. ",Cd.broker,". Equal Housing Opportunity."]}),s.jsx("p",{children:"Listing data courtesy of Imagine MLS. Information deemed reliable but not guaranteed."})]})})]})}function R4t(){const t=qa(),[e,r]=N.useState(""),[n,i]=N.useState(""),[a,c]=N.useState(""),d=p=>{p.preventDefault();const l=new URLSearchParams;e.trim()&&l.set("q",e.trim()),n&&l.set("maxPrice",n),a&&l.set("beds",a),t(`/search?${l.toString()}`)};return s.jsxs("form",{onSubmit:d,role:"search",className:"rmc-card text-[hsl(var(--rmc-ink))] p-2 grid gap-1 md:grid-cols-[1fr_170px_120px_auto] md:rounded-full",children:[s.jsxs("label",{className:"px-5 py-2.5",children:[s.jsx("span",{className:"rmc-eyebrow rmc-soft block !text-[0.62rem]",children:"Where"}),s.jsx("input",{value:e,onChange:p=>r(p.target.value),placeholder:"City, ZIP, address or MLS #",className:"w-full bg-transparent outline-none"})]}),s.jsxs("label",{className:"px-5 py-2.5 md:border-l rmc-line",children:[s.jsx("span",{className:"rmc-eyebrow rmc-soft block !text-[0.62rem]",children:"Max price"}),s.jsxs("select",{value:n,onChange:p=>i(p.target.value),className:"w-full bg-transparent outline-none",children:[s.jsx("option",{value:"",children:"Any"}),[25e4,4e5,6e5,8e5,1e6,2e6].map(p=>s.jsxs("option",{value:p,children:["$",(p/1e3).toLocaleString(),"k"]},p))]})]}),s.jsxs("label",{className:"px-5 py-2.5 md:border-l rmc-line",children:[s.jsx("span",{className:"rmc-eyebrow rmc-soft block !text-[0.62rem]",children:"Beds"}),s.jsxs("select",{value:a,onChange:p=>c(p.target.value),className:"w-full bg-transparent outline-none",children:[s.jsx("option",{value:"",children:"Any"}),[1,2,3,4,5].map(p=>s.jsxs("option",{value:p,children:[p,"+"]},p))]})]}),s.jsxs("button",{type:"submit",className:"rmc-btn justify-center",children:[s.jsx(ef,{className:"h-4 w-4"}),"Search"]})]})}function _w({eyebrow:t,title:e,intro:r,image:n}){return s.jsxs("section",{className:"relative h-[56vh] min-h-[420px] overflow-hidden rmc-light",children:[s.jsx("img",{src:n,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),s.jsxs("div",{className:"relative mx-auto flex h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pb-14",children:[s.jsx("p",{className:"rmc-eyebrow mb-4",children:t}),s.jsx("h1",{className:"rmc-display text-5xl md:text-7xl max-w-4xl leading-[1.02]",children:e}),s.jsx("p",{className:"mt-5 max-w-xl text-lg opacity-90",children:r})]})]})}function bO({eyebrow:t,title:e,intro:r,center:n=!1}){return s.jsxs("div",{className:`rmc-reveal mb-12 ${n?"text-center mx-auto max-w-2xl":"max-w-2xl"}`,children:[s.jsx("p",{className:"rmc-eyebrow rmc-red mb-4",children:t}),s.jsx("h2",{className:"rmc-display text-4xl md:text-6xl leading-[1.05]",children:e}),r&&s.jsx("p",{className:"mt-5 rmc-soft text-lg",children:r})]})}function Nv({siteConfig:t,defaultIntent:e="buy",heading:r="How can we help you move?"}){var O;const n=kg(),i=n.mode==="brokerage"?HV:HV.filter(F=>F.key!=="join"),{pathname:a}=ms(),[c,d]=N.useState(e),[p,l]=N.useState("lexington"),[g,v]=N.useState({name:"",email:"",phone:"",message:""}),[E,T]=N.useState("idle"),[j,P]=N.useState(""),C=((O=HV.find(F=>F.key===c))==null?void 0:O.label)||"General question",L=async F=>{var W;if(F.preventDefault(),P(""),!g.name.trim()||!g.email.trim()){P("Please add your name and email.");return}T("sending");const $=(W=nP.find(Z=>Z.key===p))==null?void 0:W.name,{error:G}=await rP({lead_site_id:t.id,name:g.name.trim(),email:g.email.trim(),phone:g.phone.trim()||null,message:`[${C}${n.mode==="brokerage"?` · ${$} office`:""}] ${g.message.trim()}`.trim(),source_page:a,lead_type:c==="sell"||c==="value"?"seller":c==="buy"||c==="relocate"?"buyer":"contact",metadata:{intent:c,intent_label:C,office:p}});if(G){T("error"),P(G.message||`Something went wrong. Please call ${n.phone}.`);return}T("sent")};return s.jsx("section",{id:"inquire",className:"rmc-bg-mist",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-14 lg:grid-cols-2 items-center",children:[s.jsxs("div",{className:"rmc-reveal",children:[s.jsx("p",{className:"rmc-eyebrow rmc-red mb-4",children:"Talk to a local expert"}),s.jsx("h2",{className:"rmc-display text-5xl md:text-6xl leading-[1.05]",children:r}),s.jsx("p",{className:"mt-5 rmc-soft text-lg max-w-md",children:n.mode==="agent"?"Tell me what you need and I’ll reach out personally — usually the same day.":n.mode==="team"?"Tell us what you need and someone from our team will reach out — usually the same day.":"Tell us what you need and the right agent from the nearest office will reach out — usually the same day."}),s.jsx("div",{className:"mt-8 flex flex-wrap gap-2",role:"radiogroup","aria-label":"What can we help with?",children:i.map(F=>s.jsx("button",{type:"button",role:"radio","aria-checked":c===F.key,onClick:()=>d(F.key),className:`px-4 py-2.5 rounded-full text-sm font-medium border transition ${c===F.key?"rmc-bg-blue border-transparent":"rmc-line rmc-bg-paper"}`,children:F.label},F.key))})]}),E==="sent"?s.jsxs("div",{className:"rmc-card p-12",role:"status",children:[s.jsx("p",{className:"rmc-eyebrow rmc-red mb-3",children:"Got it"}),s.jsxs("p",{className:"rmc-display text-4xl",children:["Thank you, ",g.name.split(" ")[0],"!"]}),s.jsxs("p",{className:"mt-4 rmc-soft",children:[n.mode==="brokerage"?"A RE/MAX Creative agent":n.mode==="agent"?n.first:"Our team"," will follow up shortly. Need us now? Call ",n.phone,"."]})]}):s.jsxs("form",{onSubmit:L,className:"rmc-card p-8 md:p-10 space-y-4",noValidate:!0,children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx("input",{className:"rmc-input",placeholder:"Name *","aria-label":"Name",value:g.name,onChange:F=>v({...g,name:F.target.value}),autoComplete:"name"}),s.jsx("input",{className:"rmc-input",placeholder:"Phone","aria-label":"Phone",type:"tel",value:g.phone,onChange:F=>v({...g,phone:F.target.value}),autoComplete:"tel"})]}),s.jsx("input",{className:"rmc-input",placeholder:"Email *","aria-label":"Email",type:"email",value:g.email,onChange:F=>v({...g,email:F.target.value}),autoComplete:"email"}),n.mode==="brokerage"&&s.jsx("select",{className:"rmc-input","aria-label":"Nearest office",value:p,onChange:F=>l(F.target.value),children:nP.map(F=>s.jsxs("option",{value:F.key,children:[F.name," office"]},F.key))}),s.jsx("textarea",{className:"rmc-input min-h-[110px] resize-none",placeholder:c==="sell"||c==="value"?"Property address and timing…":"Areas, price range, timing…","aria-label":"Message",value:g.message,onChange:F=>v({...g,message:F.target.value})}),j&&s.jsx("p",{className:"text-sm text-destructive",role:"alert",children:j}),s.jsx("button",{type:"submit",disabled:E==="sending",className:"rmc-btn w-full justify-center",children:E==="sending"?"Sending…":s.jsxs(s.Fragment,{children:["Send message ",s.jsx(lo,{className:"h-4 w-4"})]})})]})]})})}function jCe(t){return(t||"?").split(/\s+/).map(e=>e[0]).slice(0,2).join("").toUpperCase()}function V3({a:t}){var r;const e=t.agent_site_slug?`https://${t.agent_site_slug}.thelocalmove.com`:null;return s.jsxs("div",{className:"rmc-card overflow-hidden group flex flex-col",children:[s.jsxs("div",{className:"aspect-[4/5] rmc-bg-mist overflow-hidden rmc-zoom relative",children:[t.avatar_url?s.jsx("img",{src:t.avatar_url,alt:t.full_name||"",loading:"lazy",className:"h-full w-full object-cover"}):s.jsx("div",{className:"h-full w-full flex items-center justify-center rmc-display text-5xl rmc-blue",children:jCe(t.full_name)}),t.team_name&&s.jsx("span",{className:"absolute left-3 top-3 rounded-full rmc-bg-navy px-3 py-1 text-[0.65rem] font-semibold uppercase tracking-wider",children:t.team_name})]}),s.jsxs("div",{className:"p-5 flex-1 flex flex-col",children:[s.jsx("p",{className:"font-semibold text-lg leading-tight",children:t.full_name}),s.jsx("p",{className:"text-sm rmc-soft mt-0.5",children:t.title||"REALTOR®"}),s.jsxs("div",{className:"mt-4 space-y-1.5 text-sm",children:[t.phone&&s.jsxs("a",{href:`tel:${t.phone.replace(/[^\d+]/g,"")}`,className:"flex items-center gap-2 hover:rmc-red",children:[s.jsx(Ui,{className:"h-3.5 w-3.5"}),((r=TCe(t.phone))==null?void 0:r.phone)||t.phone]}),t.email&&s.jsxs("a",{href:`mailto:${t.email}`,className:"flex items-center gap-2 hover:rmc-red truncate",children:[s.jsx(rs,{className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"truncate",children:t.email})]})]}),e&&s.jsxs("a",{href:e,target:"_blank",rel:"noreferrer",className:"mt-auto pt-4 inline-flex items-center gap-1 text-xs font-semibold uppercase tracking-wider rmc-blue",children:["Visit website ",s.jsx(Q_e,{className:"h-3.5 w-3.5"})]})]})]})}function CCe({roster:t}){const e=kg(),r=(e.bio||"").split(/\n\s*\n/).map(n=>n.trim()).filter(Boolean);return e.mode==="team"?s.jsx("section",{className:"rmc-bg-paper",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6",children:[s.jsx(bO,{eyebrow:"Meet the team",title:`The ${e.name}.`,intro:r[0]||"Local experts who share the work — so you always have someone ready to help."}),s.jsxs(Nn,{to:"/agents",className:"rmc-btn mb-12",children:["Meet everyone ",s.jsx(lo,{className:"h-4 w-4"})]})]}),t.length>0&&s.jsx("div",{className:"grid gap-5 grid-cols-2 md:grid-cols-4",children:t.slice(0,8).map(n=>s.jsx(V3,{a:n},n.user_id))})]})}):s.jsx("section",{className:"rmc-bg-paper",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24 grid gap-12 lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)] items-center",children:[s.jsxs("div",{className:"rmc-reveal relative",children:[s.jsx("div",{className:"aspect-[4/5] overflow-hidden rounded-[1.5rem] rmc-bg-mist",children:e.photo?s.jsx("img",{src:e.photo,alt:e.name,loading:"lazy",className:"h-full w-full object-cover"}):s.jsx("div",{className:"h-full w-full flex items-center justify-center rmc-display text-7xl rmc-blue",children:jCe(e.name)})}),s.jsx("img",{src:NE.url,alt:"","aria-hidden":!0,className:"absolute -right-4 -bottom-6 h-24 w-auto drop-shadow-lg"})]}),s.jsxs("div",{className:"rmc-reveal",children:[s.jsxs("p",{className:"rmc-eyebrow rmc-red mb-4",children:["Meet ",e.first]}),s.jsx("h2",{className:"rmc-display text-4xl md:text-6xl leading-[1.05]",children:e.name}),s.jsxs("p",{className:"mt-2 rmc-soft",children:[e.title," · RE/MAX Creative Realty"]}),s.jsx("div",{className:"mt-6 space-y-4 text-lg rmc-soft max-w-2xl",children:(r.length?r.slice(0,2):["I help Central Kentucky buyers and sellers move with clarity and confidence — with local market knowledge and the reach of RE/MAX behind every move."]).map((n,i)=>s.jsx("p",{children:n},i))}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[s.jsxs("a",{href:e.phoneHref,className:"rmc-btn",children:[s.jsx(Ui,{className:"h-4 w-4"}),e.phone]}),e.email&&s.jsxs("a",{href:`mailto:${e.email}`,className:"rmc-btn rmc-btn-blue",children:[s.jsx(rs,{className:"h-4 w-4"}),"Email ",e.first]}),s.jsxs(Nn,{to:"/about",className:"rmc-btn rmc-btn-ghost",children:["My story ",s.jsx(lo,{className:"h-4 w-4"})]})]})]})]})})}function L4t({siteConfig:t}){var c;BB();const e=kg(),r=e.mode==="brokerage",{data:n=[]}=mQ(e.mode==="agent"?null:t.id),i=(r?n.filter(d=>d.avatar_url):n).slice(0,8),a=((c=t.themeConfig)==null?void 0:c.heroImageUrl)||iu.hero;return s.jsxs(s.Fragment,{children:[s.jsx(Pv,{title:r?"RE/MAX Creative Realty | Lexington, Georgetown & Winchester KY Homes for Sale":`${e.name} | RE/MAX Creative Realty | Central Kentucky Homes for Sale`,description:r?"Search every Central Kentucky home for sale. RE/MAX Creative Realty has served the Bluegrass since 1987 with offices in Lexington, Georgetown and Winchester.":`Search every Central Kentucky home for sale with ${e.name} of RE/MAX Creative Realty.`}),s.jsxs("section",{className:"relative h-[100svh] min-h-[640px] overflow-hidden rmc-light",children:[s.jsx("img",{src:r?iu.hero:a,alt:"Kentucky horse farm at sunrise",width:1920,height:1088,fetchPriority:"high",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),s.jsx("img",{src:NE.url,alt:"","aria-hidden":!0,className:"rmc-balloon hidden md:block right-[9%] top-[22%] h-28 w-auto drop-shadow-lg"}),s.jsx("img",{src:NE.url,alt:"","aria-hidden":!0,className:"rmc-balloon hidden md:block right-[21%] top-[36%] h-14 w-auto opacity-80 drop-shadow",style:{animationDelay:"-3s"}}),s.jsxs("div",{className:"relative mx-auto flex h-full max-w-[1400px] flex-col justify-end px-5 lg:px-10 pb-12 md:pb-16",children:[s.jsx("p",{className:"rmc-eyebrow mb-5",children:r?"Lexington · Georgetown · Winchester":`${e.name} · RE/MAX Creative Realty`}),s.jsxs("h1",{className:"rmc-display text-[3rem] leading-[0.98] sm:text-7xl lg:text-[7rem] max-w-5xl",children:["Your Bluegrass home ",s.jsx("em",{className:"rmc-red not-italic",children:"starts here."})]}),s.jsx("p",{className:"mt-6 max-w-xl text-lg opacity-90",children:r?"Central Kentucky’s original RE/MAX. Three offices, 70+ local REALTORS®, and every home on the market — searchable right here.":e.mode==="team"?"Local REALTORS® who work together for you — and every home on the market, searchable right here.":`Local guidance from ${e.first}, backed by RE/MAX Creative Realty — and every home on the market, searchable right here.`}),s.jsx("div",{className:"mt-10 max-w-4xl",children:s.jsx(R4t,{})}),s.jsx("div",{className:"mt-5 flex flex-wrap gap-x-5 gap-y-2 text-sm opacity-90",children:U3.slice(0,6).map(d=>s.jsx(Nn,{to:iP(d.name),className:"hover:underline",children:d.name},d.name))})]})]}),r&&s.jsx("section",{className:"rmc-bg-blue",children:s.jsx("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-12 grid grid-cols-2 md:grid-cols-4 gap-8",children:[[_E,`Since ${Cd.founded}`,"Serving Central Kentucky"],[Dc,n.length?`${n.length}+`:"70+","Local REALTORS®"],[jl,"3","Offices in the Bluegrass"],[Do,"8+","Counties we cover"]].map(([d,p,l])=>s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(d,{className:"h-8 w-8 opacity-80 shrink-0"}),s.jsxs("div",{children:[s.jsx("p",{className:"rmc-display text-4xl leading-none",children:p}),s.jsx("p",{className:"text-sm opacity-80 mt-1",children:l})]})]},l))})}),!r&&s.jsx(CCe,{siteConfig:t,roster:n}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsx(bO,{eyebrow:"Fresh on the market",title:"Just listed in Central Kentucky.",intro:"Live from Imagine MLS — updated throughout the day."}),s.jsxs("div",{className:"space-y-6",children:[e.mode==="agent"&&s.jsx(PE,{siteConfig:t,accentColor:"#003DA5",mode:"my_listings",sectionTitle:`${e.first}’s Listings`,count:12}),s.jsx(PE,{siteConfig:t,accentColor:"#DC1C2E",cities:gH,mode:"new_listings",sectionTitle:"Newest Listings",count:12}),s.jsx(PE,{siteConfig:t,accentColor:"#003DA5",cities:gH,mode:"open_houses",sectionTitle:"Open Houses This Week",count:12})]}),s.jsx("div",{className:"mt-10",children:s.jsxs(Nn,{to:"/search",className:"rmc-btn rmc-btn-blue",children:["See every home ",s.jsx(lo,{className:"h-4 w-4"})]})})]}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pb-24 grid gap-6 md:grid-cols-2",children:[{to:"/buy",img:iu.interior,eyebrow:"Buying",title:"Find the one.",copy:"Search like an insider with saved searches, instant alerts and an agent who knows every street."},{to:"/sell",img:iu.lexington,eyebrow:"Selling",title:"Sell for more.",copy:"Pricing backed by live MLS data, marketing with the reach of the RE/MAX network."}].map(d=>s.jsxs(Nn,{to:d.to,className:"rmc-reveal relative overflow-hidden rounded-[1.5rem] h-[440px] rmc-zoom rmc-light group",children:[s.jsx("img",{src:d.img,alt:"",loading:"lazy",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),s.jsxs("div",{className:"absolute bottom-0 p-8 md:p-10",children:[s.jsx("p",{className:"rmc-eyebrow mb-3",children:d.eyebrow}),s.jsx("p",{className:"rmc-display text-5xl",children:d.title}),s.jsx("p",{className:"mt-3 max-w-sm opacity-90",children:d.copy}),s.jsxs("span",{className:"mt-5 inline-flex items-center gap-2 text-sm font-semibold uppercase tracking-wider",children:["Learn more ",s.jsx(lo,{className:"h-4 w-4 transition group-hover:translate-x-1"})]})]})]},d.to))}),s.jsx("section",{className:"rmc-bg-navy",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsxs("div",{className:"rmc-reveal mb-12 max-w-2xl",children:[s.jsx("p",{className:"rmc-eyebrow rmc-red mb-4",children:r?"Three offices":"RE/MAX Creative offices"}),s.jsx("h2",{className:"rmc-display text-4xl md:text-6xl",children:"Close to home, wherever home is."})]}),s.jsx("div",{className:"grid gap-6 md:grid-cols-3",children:nP.map(d=>s.jsxs("div",{className:"rmc-reveal rounded-[1.25rem] overflow-hidden bg-[hsl(var(--rmc-cream)/0.06)] border rmc-line-light",children:[s.jsx("div",{className:"h-48 overflow-hidden rmc-zoom",children:s.jsx("img",{src:iu[d.image],alt:"",loading:"lazy",className:"h-full w-full object-cover"})}),s.jsxs("div",{className:"p-6",children:[s.jsx("p",{className:"rmc-display text-3xl",children:d.name}),s.jsxs("p",{className:"mt-3 text-sm opacity-85 flex gap-2",children:[s.jsx(Va,{className:"h-4 w-4 shrink-0 mt-0.5"}),d.address,", ",d.cityLine]}),s.jsxs("p",{className:"mt-2 text-sm opacity-70 flex gap-2",children:[s.jsx(su,{className:"h-4 w-4 shrink-0 mt-0.5"}),d.hours]}),s.jsxs("div",{className:"mt-5 flex gap-3",children:[s.jsx("a",{href:d.map,target:"_blank",rel:"noreferrer",className:"rmc-btn !py-2.5 !px-4 !text-[0.7rem]",children:"Directions"}),s.jsx("a",{href:Cd.phoneHref,className:"rmc-btn rmc-btn-ghost !py-2.5 !px-4 !text-[0.7rem]",children:"Call"})]})]})]},d.key))})]})}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsx(bO,{eyebrow:"Explore the Bluegrass",title:"Communities we call home."}),s.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-4",children:U3.slice(0,4).map((d,p)=>s.jsxs(Nn,{to:iP(d.name),className:`rmc-reveal relative overflow-hidden rounded-[1.25rem] rmc-zoom rmc-light ${p===0?"lg:col-span-2 lg:row-span-2 h-[300px] lg:h-full min-h-[300px]":"h-[300px]"}`,children:[s.jsx("img",{src:iu[d.image],alt:"",loading:"lazy",className:"absolute inset-0 h-full w-full object-cover"}),s.jsx("div",{className:"absolute inset-0 rmc-hero-shade"}),s.jsxs("div",{className:"absolute bottom-0 p-6",children:[s.jsx("p",{className:"rmc-eyebrow opacity-80",children:d.county}),s.jsx("p",{className:"rmc-display text-4xl",children:d.name})]})]},d.name))}),s.jsx("div",{className:"mt-8",children:s.jsxs(Nn,{to:"/communities",className:"rmc-btn rmc-btn-blue",children:["All communities ",s.jsx(lo,{className:"h-4 w-4"})]})})]}),r&&i.length>0&&s.jsx("section",{className:"rmc-bg-paper",children:s.jsxs("div",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-24",children:[s.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-6",children:[s.jsx(bO,{eyebrow:"Our people",title:"Meet a few of our agents."}),s.jsxs(Nn,{to:"/agents",className:"rmc-btn mb-12",children:["All ",n.length," agents ",s.jsx(lo,{className:"h-4 w-4"})]})]}),s.jsx("div",{className:"grid gap-5 grid-cols-2 md:grid-cols-4",children:i.map(d=>s.jsx(V3,{a:d},d.user_id))})]})}),r&&s.jsxs("section",{className:"relative overflow-hidden rmc-bg-blue",children:[s.jsx("img",{src:NE.url,alt:"","aria-hidden":!0,className:"rmc-balloon left-[6%] top-10 h-32 w-auto opacity-30"}),s.jsxs("div",{className:"relative mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-8 md:grid-cols-[1fr_auto] items-center",children:[s.jsxs("div",{children:[s.jsx("p",{className:"rmc-eyebrow mb-3 opacity-80",children:"Careers"}),s.jsx("p",{className:"rmc-display text-4xl md:text-5xl max-w-2xl",children:"Grow your business with the most recognized name in real estate."})]}),s.jsxs(Nn,{to:"/join",className:"rmc-btn",children:["Join our team ",s.jsx(lo,{className:"h-4 w-4"})]})]})]}),s.jsx(Nv,{siteConfig:t})]})}function D4t({siteConfig:t}){const e=kg(),{data:r=[],isLoading:n}=mQ(e.mode==="agent"?null:t.id),[i,a]=N.useState(""),[c,d]=N.useState(""),p=N.useMemo(()=>r.filter(l=>{const g=(l.full_name||"").toLowerCase();return!(i&&!g.includes(i.toLowerCase())&&!(l.team_name||"").toLowerCase().includes(i.toLowerCase())||c&&!(g.split(" ").pop()||"").startsWith(c.toLowerCase()))}),[r,i,c]);return e.mode==="agent"?s.jsx(Oi,{to:"/about",replace:!0}):e.mode==="team"?s.jsxs(s.Fragment,{children:[s.jsx(Pv,{title:`Our Team | ${e.name}`,description:`Meet the REALTORS® of ${e.name}, RE/MAX Creative Realty.`}),s.jsx(_w,{eyebrow:"Our team",title:`Meet the ${e.name}.`,intro:"Local REALTORS® who work together for you.",image:iu.lexington}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-14",children:[s.jsx("p",{className:"text-sm rmc-soft",children:n?"Loading team…":`${r.length} team member${r.length===1?"":"s"}`}),s.jsx("div",{className:"mt-6 grid gap-5 grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:r.map(l=>s.jsx(V3,{a:l},l.user_id))})]}),s.jsx(Nv,{siteConfig:t,heading:"Talk to our team."})]}):s.jsxs(s.Fragment,{children:[s.jsx(Pv,{title:"Our Agents | RE/MAX Creative Realty",description:"Find a RE/MAX Creative Realty REALTOR® in Lexington, Georgetown or Winchester, Kentucky."}),s.jsx(_w,{eyebrow:"Agent directory",title:"Find your agent.",intro:`${r.length||"70+"} REALTORS® across Lexington, Georgetown and Winchester.`,image:iu.lexington}),s.jsxs("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-14",children:[s.jsxs("div",{className:"rmc-card p-4 flex flex-col md:flex-row gap-4 md:items-center",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx(ef,{className:"h-4 w-4 absolute left-4 top-1/2 -translate-y-1/2 rmc-soft"}),s.jsx("input",{className:"rmc-input !pl-11",placeholder:"Search by name or team",value:i,onChange:l=>a(l.target.value),"aria-label":"Search agents"})]}),s.jsx("div",{className:"flex flex-wrap gap-1","aria-label":"Filter by last name",children:["",..."ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")].map(l=>s.jsx("button",{onClick:()=>d(l),className:`h-8 min-w-8 px-2 rounded-full text-xs font-semibold ${c===l?"rmc-bg-blue":"hover:rmc-bg-mist"}`,children:l||"All"},l||"all"))})]}),s.jsx("p",{className:"mt-6 text-sm rmc-soft",children:n?"Loading agents…":`${p.length} agent${p.length===1?"":"s"}`}),s.jsx("div",{className:"mt-6 grid gap-5 grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:p.map(l=>s.jsx(V3,{a:l},l.user_id))})]}),s.jsx(Nv,{siteConfig:t,heading:"Not sure who to call?"})]})}function M4t({siteConfig:t}){return s.jsxs(s.Fragment,{children:[s.jsx(Pv,{title:"Offices | RE/MAX Creative Realty",description:"Visit RE/MAX Creative Realty in Lexington, Georgetown or Winchester, Kentucky."}),s.jsx(_w,{eyebrow:"Visit us",title:"Three offices. One team.",intro:`Call any office at ${Cd.phone}.`,image:iu.georgetown}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 space-y-10",children:nP.map((e,r)=>s.jsxs("div",{className:`rmc-card overflow-hidden grid md:grid-cols-2 ${r%2?"md:[&>*:first-child]:order-2":""}`,children:[s.jsx("div",{className:"h-72 md:h-auto overflow-hidden",children:s.jsx("img",{src:iu[e.image],alt:"",loading:"lazy",className:"h-full w-full object-cover"})}),s.jsxs("div",{className:"p-10 md:p-14",children:[s.jsx("p",{className:"rmc-eyebrow rmc-red mb-3",children:r===0?"Main office":"Branch office"}),s.jsx("h2",{className:"rmc-display text-5xl",children:e.name}),s.jsx("p",{className:"mt-4 rmc-soft",children:e.note}),s.jsxs("div",{className:"mt-6 space-y-2 text-sm",children:[s.jsxs("p",{className:"flex gap-2",children:[s.jsx(Va,{className:"h-4 w-4 rmc-blue mt-0.5"}),e.address,", ",e.cityLine]}),s.jsxs("p",{className:"flex gap-2",children:[s.jsx(su,{className:"h-4 w-4 rmc-blue mt-0.5"}),e.hours]}),s.jsxs("p",{className:"flex gap-2",children:[s.jsx(Ui,{className:"h-4 w-4 rmc-blue mt-0.5"}),s.jsx("a",{href:Cd.phoneHref,children:Cd.phone})]})]}),s.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[s.jsx("a",{href:e.map,target:"_blank",rel:"noreferrer",className:"rmc-btn",children:"Get directions"}),s.jsxs(Nn,{to:iP(e.name),className:"rmc-btn rmc-btn-blue",children:["Homes in ",e.name]})]})]})]},e.key))}),s.jsx(Nv,{siteConfig:t})]})}function O4t({siteConfig:t}){return BB(),s.jsxs(s.Fragment,{children:[s.jsx(Pv,{title:"Central Kentucky Communities | RE/MAX Creative Realty",description:"Explore homes for sale in Lexington, Georgetown, Winchester, Nicholasville, Versailles, Richmond, Frankfort and Lawrenceburg."}),s.jsx(_w,{eyebrow:"Communities",title:"Explore the Bluegrass.",intro:"Neighborhood guides, market snapshots and every listing in the towns we serve.",image:iu.hero}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-6 sm:grid-cols-2 lg:grid-cols-3",children:U3.map(e=>s.jsxs(Nn,{to:iP(e.name),className:"rmc-reveal rmc-card overflow-hidden group",children:[s.jsx("div",{className:"h-56 overflow-hidden rmc-zoom",children:s.jsx("img",{src:iu[e.image],alt:"",loading:"lazy",className:"h-full w-full object-cover"})}),s.jsxs("div",{className:"p-6",children:[s.jsx("p",{className:"rmc-eyebrow rmc-red",children:e.county}),s.jsx("p",{className:"rmc-display text-3xl mt-1",children:e.name}),s.jsx("p",{className:"mt-2 text-sm rmc-soft",children:e.blurb}),s.jsxs("span",{className:"mt-4 inline-flex items-center gap-1 text-xs font-semibold uppercase tracking-wider rmc-blue",children:["Homes for sale ",s.jsx(lo,{className:"h-3.5 w-3.5 transition group-hover:translate-x-1"})]})]})]},e.name))}),s.jsx(Nv,{siteConfig:t,defaultIntent:"relocate",heading:"Moving to Central Kentucky?"})]})}function zB({siteConfig:t,seo:e,hero:r,points:n,intent:i,heading:a,children:c}){BB();const d=kg(),p=d.mode==="brokerage"?"RE/MAX Creative Realty":`${d.name} | RE/MAX Creative Realty`;return s.jsxs(s.Fragment,{children:[s.jsx(Pv,{title:e[0].replace("RE/MAX Creative Realty",p),description:e[1]}),s.jsx(_w,{...r}),s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 py-20 grid gap-6 md:grid-cols-3",children:n.map(([l,g],v)=>s.jsxs("div",{className:"rmc-reveal rmc-card p-8",children:[s.jsx("span",{className:`inline-flex h-10 w-10 items-center justify-center rounded-full text-sm font-bold ${v%2?"rmc-bg-blue":"bg-[hsl(var(--rmc-red))] text-[hsl(var(--rmc-paper))]"}`,children:v+1}),s.jsx("p",{className:"rmc-display text-2xl mt-5",children:l}),s.jsx("p",{className:"mt-2 rmc-soft text-sm leading-relaxed",children:g})]},l))}),c,s.jsx(Nv,{siteConfig:t,defaultIntent:i,heading:a})]})}function F4t({siteConfig:t}){return s.jsx(zB,{siteConfig:t,intent:"buy",heading:"Ready to start looking?",seo:["Buy a Home in Central Kentucky | RE/MAX Creative Realty","Search every Central Kentucky listing and buy with a local RE/MAX Creative agent."],hero:{eyebrow:"Buying",title:"Find the one.",intro:"Every MLS listing, instant alerts and an agent who knows the neighborhood.",image:iu.interior},points:[["Search everything","Every home listed in Imagine MLS, updated throughout the day, with saved searches and alerts."],["Local guidance","Schools, commutes, farms and neighborhoods — from agents who live here."],["Negotiate with confidence","Offer strategy and a QSC service guarantee from the first showing to closing."]],children:s.jsx("section",{className:"mx-auto max-w-[1400px] px-5 lg:px-10 pb-20",children:s.jsx(PE,{siteConfig:t,accentColor:"#DC1C2E",cities:gH,mode:"new_listings",sectionTitle:"Newest Listings",count:12})})})}function B4t({siteConfig:t}){return s.jsx(zB,{siteConfig:t,intent:"value",heading:"What’s your home worth?",seo:["Sell Your Home in Central Kentucky | RE/MAX Creative Realty","Get a free home value and sell with RE/MAX Creative Realty."],hero:{eyebrow:"Selling",title:"Sell smarter. Net more.",intro:"Pricing from live MLS data, and marketing with the reach of the RE/MAX network.",image:iu.winchester},points:[["Price it right","A comparative market analysis built on today’s sales, not last quarter’s headlines."],["Market it everywhere","Professional photography, MLS syndication and the global RE/MAX network."],["Close with care","Offer review, negotiation and a team that sees every detail through to closing."]]})}function z4t({siteConfig:t}){var n;const e=kg(),{data:r=[]}=mQ(e.mode==="team"?t.id:null);if(BB(),e.mode!=="brokerage"){const i=(e.bio||"").split(/\n\s*\n/).map(a=>a.trim()).filter(Boolean);return s.jsxs(s.Fragment,{children:[s.jsx(Pv,{title:`About ${e.name} | RE/MAX Creative Realty`,description:`Get to know ${e.name} of RE/MAX Creative Realty, serving Central Kentucky.`}),s.jsx(_w,{eyebrow:e.mode==="team"?"About the team":`About ${e.first}`,title:e.name,intro:`${e.title} · RE/MAX Creative Realty`,image:((n=t.themeConfig)==null?void 0:n.heroImageUrl)||iu.hero}),s.jsx(CCe,{siteConfig:t,roster:r}),i.length>2&&e.mode==="agent"&&s.jsx("section",{className:"mx-auto max-w-3xl px-5 lg:px-10 pb-20 space-y-4 text-lg rmc-soft",children:i.slice(2).map((a,c)=>s.jsx("p",{children:a},c))}),s.jsx(Nv,{siteConfig:t,heading:"Let’s talk."})]})}return s.jsx(zB,{siteConfig:t,intent:"buy",heading:"Let’s talk.",seo:["About RE/MAX Creative Realty | Lexington, KY","Central Kentucky’s original RE/MAX brokerage, serving the Bluegrass since 1987."],hero:{eyebrow:"Our story",title:`Rooted in the Bluegrass since ${Cd.founded}.`,intro:"Central Kentucky’s original RE/MAX firm — three offices and 70+ REALTORS® ready to work for you.",image:iu.hero},points:[["Local since 1987","For more than 35 years we have helped families buy, sell and invest across Central Kentucky."],["Quality Service Certified","Our agents earn the QSC designation and put their service guarantee in writing."],["Giving back","Our agents support Children’s Miracle Network, Habitat for Humanity, CASA and many more causes close to home."]]})}function $4t({siteConfig:t}){return kg().mode!=="brokerage"?s.jsx(Oi,{to:"/contact",replace:!0}):s.jsx(zB,{siteConfig:t,intent:"join",heading:"Let’s talk about your career.",seo:["Join RE/MAX Creative Realty | Real Estate Careers in Kentucky","Grow your real estate career with Central Kentucky’s original RE/MAX brokerage."],hero:{eyebrow:"Careers",title:"Build your business here.",intro:"The most recognized brand in real estate, with local leadership in your corner.",image:iu.georgetown},points:[["A global brand","The RE/MAX balloon opens doors — and referrals — around the world."],["Three offices","Work from Lexington, Georgetown or Winchester with real support staff."],["Modern tools","Your own IDX website, CRM, marketing and video tools through LevelUp."]]})}function U4t({siteConfig:t}){const e=kg(),r=e.mode==="brokerage";return s.jsxs(s.Fragment,{children:[s.jsx(Pv,{title:`Contact ${e.name}`,description:`Call ${e.phone} or send a message to ${e.name}.`}),s.jsx(_w,{eyebrow:"Contact",title:e.mode==="agent"?"Let’s talk.":"We’re here to help.",intro:r?`Call ${e.phone} · toll-free ${Cd.tollFree}`:`Call ${e.phone}${e.email?` · ${e.email}`:""}`,image:iu.lexington}),s.jsx(Nv,{siteConfig:t,heading:"Send us a message."})]})}function V4t({children:t}){return s.jsx("div",{className:"rmc-bg-paper min-h-[70vh]",children:t})}function pQ({open:t,mode:e,siteConfig:r,onComplete:n,onSkip:i,theme:a="default",accentColor:c}){var $e;const{signUp:d,signIn:p}=VA(),[l,g]=N.useState(!1),[v,E]=N.useState(""),[T,j]=N.useState(""),[P,C]=N.useState(""),[L,O]=N.useState(!1),[F,$]=N.useState(""),[G,W]=N.useState(!1),[Z,Q]=N.useState(!1),[ee,ie]=N.useState(!1),oe=e==="required",pe=a==="luxury",Le=c||(pe?"#c9a96e":"#2563eb"),be=(($e=r.agent)==null?void 0:$e.full_name)||"the agent",Re={borderColor:`${Le}66`,"--tw-ring-color":`${Le}66`},Ie=async we=>{if(we.preventDefault(),$(""),!T.trim()||!l&&!P.trim()){$("Email and phone number are required.");return}if(!l&&!v.trim()){$("Name is required.");return}const ke=P.replace(/\D/g,"");if(!l&&ke.length<7){$("Please enter a valid phone number.");return}O(!0);try{const Ae=l?await p(T,P):await d({name:v,email:T,phone:P});Ae!=null&&Ae.instant?Q(!0):(ie(!l&&!!(Ae!=null&&Ae.existing)),W(!0))}catch(Ae){const He=String((Ae==null?void 0:Ae.message)||"").toLowerCase();He.includes("rate")||He.includes("429")||He.includes("too many")?$("We just sent you a link — please check your inbox (and spam) or try again in a minute."):He.includes("email")&&He.includes("valid")?$("Please double-check your email address and try again."):$("We couldn't complete that just now. Please check your email address and try again.")}finally{O(!1)}},Te="w-full",ge=pe?Re:void 0;return s.jsx(gl,{open:t,onOpenChange:oe?void 0:we=>{we||i()},children:s.jsxs(Jo,{className:"sm:max-w-md bg-background text-foreground",onPointerDownOutside:oe?we=>we.preventDefault():void 0,onEscapeKeyDown:oe?we=>we.preventDefault():void 0,children:[s.jsxs(Bc,{children:[s.jsx(pc,{className:"text-xl",style:pe?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:l?"Welcome Back":oe?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),s.jsx(sf,{children:l?"Receive a secure sign-in link by email. No password needed.":`Create a free account to save favorites, get alerts, and connect with ${be}.`})]}),Z?s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsxs("p",{className:"text-sm text-foreground",children:["You're all set",v.trim()?`, ${v.trim().split(" ")[0]}`:"","! Your account is active and you're signed in — everything you view and save is now connected to your account."]}),s.jsx(Jt,{className:"w-full",onClick:n,children:"Start browsing"})]}):G?s.jsxs("div",{className:"space-y-4 py-4",children:[s.jsx("p",{className:"text-sm text-foreground",children:ee?"Welcome back! Looks like you already have an account with us. We've sent a secure sign-in link to your inbox so you can jump right back in.":"Check your email for a secure sign-in link to finish. Your property activity stays connected on this browser."}),s.jsx(Jt,{className:"w-full",onClick:n,children:"Continue browsing"})]}):s.jsxs("form",{onSubmit:Ie,className:"space-y-3 mt-2",children:[!l&&s.jsx(hn,{type:"text",required:!0,placeholder:"Your name",value:v,onChange:we=>E(we.target.value),className:Te,style:ge}),s.jsx(hn,{type:"email",required:!0,placeholder:"Email address",value:T,onChange:we=>j(we.target.value),className:Te,style:ge}),!l&&s.jsx("div",{children:s.jsx(hn,{type:"tel",required:!0,placeholder:"Phone number",value:P,onChange:we=>C(we.target.value),className:Te,style:ge})}),F&&s.jsx("p",{className:"text-destructive text-sm",children:F}),s.jsx(Jt,{type:"submit",disabled:L,className:"w-full",children:L?l?"Sending link...":"Creating account...":l?"Email Sign-In Link":"Create Account"}),s.jsx(Jt,{variant:"ghost",type:"button",onClick:()=>{g(!l),$("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",children:l?"Don't have an account? Sign up":"Already have an account? Sign in"}),!oe&&!l&&s.jsx(Jt,{variant:"ghost",type:"button",onClick:i,className:"w-full text-muted-foreground",children:"Skip for now"})]}),s.jsx("p",{className:"text-xs text-center mt-1 text-muted-foreground",children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}const PCe=[{tab:"saved",label:"Saved Homes",icon:cg},{tab:"searches",label:"Saved Searches & Alerts",icon:ef},{tab:"viewed",label:"Recently Viewed",icon:E4},{tab:"profile",label:"Profile & Preferences",icon:XW}];function NCe(t,e){const r=t!=null&&t.name&&t.name!=="Website visitor"?t.name:"",n=(t==null?void 0:t.email)||e||"",i=r.split(" ")[0]||n.split("@")[0]||"Account",a=(r?r.split(" ").map(c=>c[0]).slice(0,2).join(""):n[0]||"A").toUpperCase();return{name:r||i,first:i,email:n,initials:a}}function gQ({triggerClassName:t,avatarClassName:e,showSaved:r=!0,savedClassName:n}){const{user:i,profile:a,signOut:c}=VA(),d=qa();if(!i)return null;const p=NCe(a,i.email);return s.jsxs("div",{className:"flex items-center gap-1",children:[r&&s.jsxs(Nn,{to:"/account?tab=saved",className:n,"aria-label":"Saved homes",children:[s.jsx(cg,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),s.jsxs(UP,{modal:!1,children:[s.jsxs(VP,{className:t,"aria-label":"Your account",children:[s.jsx("span",{className:e??"flex h-7 w-7 items-center justify-center rounded-full bg-primary text-xs font-semibold text-primary-foreground",children:p.initials}),s.jsx("span",{className:"hidden max-w-[8rem] truncate lg:inline",children:p.first}),s.jsx(ad,{className:"h-3.5 w-3.5 opacity-70"})]}),s.jsxs(xA,{align:"end",className:"z-[80] w-64",children:[s.jsxs(bwe,{className:"font-normal",children:[s.jsx("p",{className:"text-xs text-muted-foreground",children:"Signed in as"}),s.jsx("p",{className:"truncate text-sm font-semibold",children:p.name}),p.email&&s.jsx("p",{className:"truncate text-xs text-muted-foreground",children:p.email})]}),s.jsx(iC,{}),PCe.map(({tab:l,label:g,icon:v})=>s.jsxs(lh,{onSelect:()=>d(`/account?tab=${l}`),className:"cursor-pointer gap-2",children:[s.jsx(v,{className:"h-4 w-4"}),g]},l)),s.jsx(iC,{}),s.jsxs(lh,{onSelect:async()=>{await c(),d("/")},className:"cursor-pointer gap-2",children:[s.jsx(T4,{className:"h-4 w-4"}),"Sign Out"]})]})]})]})}function yQ({onNavigate:t,dark:e}){const{user:r,profile:n,signOut:i}=VA(),a=qa();if(!r)return null;const c=NCe(n,r.email),d=`flex w-full items-center gap-2 rounded-lg px-3 py-2.5 text-left text-sm font-medium ${e?"text-white/80 hover:bg-white/10":"text-gray-600 hover:bg-gray-50"}`;return s.jsxs("div",{className:`mt-3 rounded-xl border p-2 ${e?"border-white/15":"border-gray-200"}`,children:[s.jsxs("div",{className:"flex items-center gap-3 px-2 py-2",children:[s.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-full bg-primary text-sm font-semibold text-primary-foreground",children:c.initials}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("p",{className:`truncate text-sm font-semibold ${e?"text-white":"text-gray-900"}`,children:c.name}),c.email&&s.jsx("p",{className:`truncate text-xs ${e?"text-white/50":"text-gray-500"}`,children:c.email})]})]}),PCe.map(({tab:p,label:l,icon:g})=>s.jsxs("button",{className:d,onClick:()=>{a(`/account?tab=${p}`),t()},children:[s.jsx(g,{className:"h-4 w-4"}),l]},p)),s.jsxs("button",{className:d,onClick:async()=>{await i(),t(),a("/")},children:[s.jsx(T4,{className:"h-4 w-4"}),"Sign Out"]})]})}function xQ(t,e){const r=(e||"").trim(),n=(t||"").trim(),i=n.split(/\s+[|–—-]\s+/)[0].trim();return i&&i.length<=40?r&&i.toLowerCase()===r.toLowerCase()?`${r} Real Estate`:i:r?`${r} Real Estate`:n||"Real Estate"}function q4t(t,e){const r=xQ(t,e),n=(e||"").trim(),i=[n,n?`${n} Realtor`:"",(t||"").trim()].map(a=>a.trim()).filter(a=>a&&a.toLowerCase()!==r.toLowerCase());return Array.from(new Set(i))}function _Q({siteConfig:t,pagePath:e}){const r=t.agent;if(!r)return null;const n=t.customDomain?`https://${t.customDomain}`:`https://${t.subdomainSlug}.thelocalmove.com`,i=t.id==="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109",a=!Cv(t),d=(r.areas_served||"").split(/,|;|\|/).map(Q=>Q.trim()).filter(Boolean),p=d[0]||"",[l,g]=p.split(/,\s*/),v=(r.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],E=[...new Set(v.map(Q=>Q.toUpperCase()))],T=t.testimonials||[],j=T.length?{"@type":"AggregateRating",ratingValue:(T.reduce((Q,ee)=>Q+(ee.rating||5),0)/T.length).toFixed(1),reviewCount:T.length,bestRating:5,worstRating:1}:void 0,P=[r.google_business_url,r.zillow_profile_url,r.realtor_profile_url,r.linkedin_url,r.facebook_url,r.instagram_url].filter(Boolean),C=(r.specialties||"").split(/,|;|\n/).map(Q=>Q.trim()).filter(Boolean),L={"@context":"https://schema.org","@type":["RealEstateAgent","LocalBusiness"],"@id":`${n}/#agent`,name:r.full_name,url:n,image:r.avatar_url||t.ogImageUrl||void 0,logo:t.ogImageUrl||r.avatar_url||void 0,email:r.email,telephone:r.phone||void 0,jobTitle:i?"Personal Real Estate Advisor":r.title||"Real Estate Agent",description:r.bio||`${r.full_name} is a trusted local real estate professional${p?` serving ${p}`:""}.`,priceRange:"$$",...P.length&&{sameAs:P},...t.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:t.brokerageLegalName,...t.brokerageLicenseNumber&&{identifier:t.brokerageLicenseNumber}}},...t.agentLicenseNumber&&{identifier:t.agentLicenseNumber},...l&&{address:{"@type":"PostalAddress",addressLocality:l,...g&&{addressRegion:g},addressCountry:"US"}},...d.length&&{areaServed:d.map(Q=>{const[ee,ie]=Q.split(/,\s*/);return{"@type":"City",name:ee,...ie&&{containedInPlace:{"@type":"State",name:ie}}}})},...j&&{aggregateRating:j},...T.length&&{review:T.slice(0,10).map(Q=>({"@type":"Review",author:{"@type":"Person",name:Q.name},reviewBody:Q.text,reviewRating:{"@type":"Rating",ratingValue:Q.rating||5,bestRating:5,worstRating:1},...Q.location&&{locationCreated:{"@type":"Place",name:Q.location}}}))}},O={"@context":"https://schema.org","@type":"Person","@id":`${n}/#person`,name:r.full_name,jobTitle:i?"Personal Real Estate Advisor":r.title||"Real Estate Agent",description:r.bio||void 0,image:r.avatar_url||void 0,url:n,email:r.email,telephone:r.phone||void 0,...i&&{email:"Tom@TomLois.com",telephone:"520-271-2716",address:{"@type":"PostalAddress",addressLocality:"Columbia",addressRegion:"Missouri",addressCountry:"US"}},...P.length&&{sameAs:P},knowsAbout:[...new Set([...C,"Residential Real Estate","Home Buying","Home Selling",...d.map(Q=>`${Q} Real Estate`)])].filter(Boolean).slice(0,25),...C.length&&{makesOffer:C.slice(0,12).map(Q=>({"@type":"Offer",itemOffered:{"@type":"Service",name:Q,serviceType:"Real Estate Service"}}))},...E.length&&{hasCredential:E.map(Q=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:Q}))},...t.brokerageLegalName&&{worksFor:{"@type":"Organization",name:t.brokerageLegalName}}},F=xQ(t.siteTitle,r.full_name),$=q4t(t.siteTitle,r.full_name),G={"@context":"https://schema.org","@type":"WebSite","@id":`${n}/#website`,name:F,...$.length?{alternateName:$}:{},url:n,publisher:{"@id":`${n}/#agent`},...a&&{potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${n}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}}},W=[...a?[{name:"Search Homes",description:`Browse all current MLS listings${p?` in ${p}`:""}.`,path:"/search"}]:[],{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},...a?[{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"}]:[],{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${r.full_name}${t.brokerageLegalName?` and ${t.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${r.full_name} for buying, selling, or relocation help.`,path:"/contact"}],Z={"@context":"https://schema.org","@type":"ItemList","@id":`${n}/#nav`,name:"Main Navigation",itemListElement:W.map((Q,ee)=>({"@type":"SiteNavigationElement",position:ee+1,name:Q.name,description:Q.description,url:`${n}${Q.path}`}))};return s.jsxs(mc,{children:[s.jsx("script",{type:"application/ld+json",children:JSON.stringify(L)}),s.jsx("script",{type:"application/ld+json",children:JSON.stringify(O)}),s.jsx("script",{type:"application/ld+json",children:JSON.stringify(G)}),s.jsx("script",{type:"application/ld+json",children:JSON.stringify(Z)})]})}function cQt({items:t,siteConfig:e}){const r=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug}.thelocalmove.com`,n={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:t.map((i,a)=>({"@type":"ListItem",position:a+1,name:i.name,item:`${r}${i.path}`}))};return s.jsx(mc,{children:s.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function uQt({listing:t,siteConfig:e}){var i;const r=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug}.thelocalmove.com`,n={"@context":"https://schema.org","@type":"SingleFamilyResidence",name:`${t.address}, ${t.city}, ${t.state} ${t.zip}`,url:`${r}/listing/${t.mlsNumber}`,image:((i=t.photos)==null?void 0:i[0])||void 0,numberOfRooms:t.bedrooms,numberOfBathroomsTotal:t.bathrooms,floorSize:t.sqft?{"@type":"QuantitativeValue",value:t.sqft,unitCode:"FTK"}:void 0,address:{"@type":"PostalAddress",streetAddress:t.address,addressLocality:t.city,addressRegion:t.state,postalCode:t.zip},...t.latitude&&t.longitude&&{geo:{"@type":"GeoCoordinates",latitude:t.latitude,longitude:t.longitude}},offers:{"@type":"Offer",price:t.price,priceCurrency:"USD",availability:t.status==="Active"?"https://schema.org/InStock":"https://schema.org/SoldOut"},...t.yearBuilt&&{yearBuilt:t.yearBuilt}};return s.jsx(mc,{children:s.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function G4t({faqs:t}){if(!t.length)return null;const e={"@context":"https://schema.org","@type":"FAQPage",mainEntity:t.map(r=>({"@type":"Question",name:r.question,acceptedAnswer:{"@type":"Answer",text:r.answer}}))};return s.jsx(mc,{children:s.jsx("script",{type:"application/ld+json",children:JSON.stringify(e)})})}function dQt({title:t,description:e,publishedAt:r,modifiedAt:n,imageUrl:i,slug:a,siteConfig:c}){const d=c.customDomain?`https://${c.customDomain}`:`https://${c.subdomainSlug}.thelocalmove.com`,p=c.agent,l={"@context":"https://schema.org","@type":"Article",headline:t,description:e,url:`${d}/blog/${a}`,datePublished:r,dateModified:n||r,...i&&{image:i},author:p?{"@type":"Person",name:p.full_name,url:d}:void 0,publisher:{"@type":"Organization",name:c.siteTitle||(p==null?void 0:p.full_name)||"Agent",url:d}};return s.jsx(mc,{children:s.jsx("script",{type:"application/ld+json",children:JSON.stringify(l)})})}function hQt({videoId:t,title:e,description:r,thumbnailUrl:n,uploadDate:i,durationSeconds:a}){const c=a&&a>0?a:null,d=c?`PT${Math.floor(c/3600)?`${Math.floor(c/3600)}H`:""}${Math.floor(c%3600/60)}M${c%60}S`:void 0,p={"@context":"https://schema.org","@type":"VideoObject",name:e,description:r,thumbnailUrl:n||`https://i.ytimg.com/vi/${t}/maxresdefault.jpg`,...i&&{uploadDate:i},...d&&{duration:d},embedUrl:`https://www.youtube.com/embed/${t}`,contentUrl:`https://www.youtube.com/watch?v=${t}`};return s.jsx(mc,{children:s.jsx("script",{type:"application/ld+json",children:JSON.stringify(p)})})}const H4t="Home Valuation";function W4t(t){return(t.valuationLabel||"").trim()||H4t}function K4t(t){return t.split(" ").map(e=>e.length>1&&e===e.toUpperCase()?e:e.toLowerCase()).join(" ")}function vQ({siteConfig:t}){var C;const e=ms(),r=t.agent,n=/faq|frequently-asked/i.test(e.pathname);if(!r||!n)return null;const i=r.full_name,a=t.brokerageLegalName||"their brokerage",c=r.areas_served||"the local market",d=((C=c.split(/,|;|\|/)[0])==null?void 0:C.trim())||"the local area",p=r.years_experience,l=r.phone||"",g=r.email,v=t.agentLicenseNumber,E=!Cv(t),T=(r.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],j=[...new Set(T.map(L=>L.toUpperCase()))],P=[{question:`Who is ${i}?`,answer:`${i} is a ${r.title||"REALTOR®"} with ${a}${p?`, with ${p}+ years of local real estate experience`:""} serving ${c}. ${r.bio||""}`.trim()},{question:`What areas does ${i} serve?`,answer:`${i} serves ${c} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${i.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${i}?`,answer:`You can reach ${i} by ${l?`phone at ${l}, `:""}email at ${g}, or by booking a consultation directly through this website.`},...j.length?[{question:`What real estate designations does ${i} hold?`,answer:`${i} holds the following professional designations: ${j.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...v?[{question:`Is ${i} a licensed real estate agent?`,answer:`Yes, ${i} is a fully licensed real estate professional (License #${v}) with ${a}.`}]:[],...E?[{question:`How do I search for homes for sale in ${d}?`,answer:`Use the property search on this site to view current MLS listings in ${d}. You can filter by price, bedrooms, neighborhood, and more, and save searches to receive email alerts when new homes match your criteria.`}]:[],{question:`What is the home buying process like in ${d}?`,answer:E?`${i} guides buyers through every step: getting pre-approved, searching MLS listings, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${i.split(" ")[0]} for a buyer consultation.`:`${i} guides buyers through every step: getting pre-approved, identifying suitable properties, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${i.split(" ")[0]} for a buyer consultation.`},{question:`How do I find out what my home is worth in ${d}?`,answer:`Request a free, no-obligation ${K4t(W4t(t))} from ${i}. ${i.split(" ")[0]} reviews recent local sales and current market conditions in ${d} to give you a realistic picture of your home's value.`}];return s.jsx(G4t,{faqs:P})}const Ime="ls_visitor_geo",Y4t=1e3*60*60,WV="lu_lc_attrib_v1",Z4t=1e3*60*60*24*90;function X4t(t){return t==="/"?"home":t==="/search"?"search":t==="/sell"?"sell":t==="/blog"?"blog":t.startsWith("/listing/")?"listing":t.startsWith("/homes-for-sale-in-")?"city":t.startsWith("/homes-in-")?"subdivision":t==="/dashboard"?"dashboard":"other"}function Q4t(t,e){switch(e){case"home":return"Home";case"search":return"Search";case"sell":return"Sell Your Home";case"blog":return"Blog";case"listing":return`Listing ${t.split("/listing/")[1]||""}`;case"city":return t.replace("/homes-for-sale-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"subdivision":return t.replace("/homes-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"dashboard":return"My Dashboard";default:return t}}async function J4t(){try{const t=localStorage.getItem(Ime);if(t){const e=JSON.parse(t);if(Date.now()-e.ts{a.current||(a.current=!0,J4t().then(c=>{i.current=c}))},[]),N.useEffect(()=>{if(!(t!=null&&t.id))return;const c=r.pathname;if(c===n.current)return;n.current=c;const d=X4t(c),p=Q4t(c,d),l=localStorage.getItem(`ls_visitor_fp_${t.id}`)||null,g=i.current;(async()=>{const E=new URLSearchParams(r.search),T=E.get("luc");if(T&&/^[0-9a-f-]{36}$/i.test(T)){try{localStorage.setItem(WV,JSON.stringify({contact_id:T,ts:Date.now()}))}catch{}return T}const j=E.get("lc");if(j&&/^[0-9a-f-]{36}$/i.test(j)){const{data:P}=await Be.from("listing_email_recipients").select("contact_id").eq("id",j).maybeSingle(),C=P==null?void 0:P.contact_id;if(C){try{localStorage.setItem(WV,JSON.stringify({contact_id:C,ts:Date.now()}))}catch{}return C}}try{const P=localStorage.getItem(WV);if(P){const C=JSON.parse(P);if(C!=null&&C.contact_id&&Date.now()-(C.ts||0){Be.from("lead_site_page_views").insert({lead_site_id:t.id,page_type:d,page_path:c,page_title:p,visitor_fingerprint:l,auth_user_id:e||null,contact_id:E,visitor_city:(g==null?void 0:g.city)||null,visitor_region:(g==null?void 0:g.region)||null,visitor_country:(g==null?void 0:g.country)||null,visitor_lat:(g==null?void 0:g.lat)||null,visitor_lng:(g==null?void 0:g.lng)||null}).then(({error:T})=>{T&&console.error("[PageTracking] insert failed:",T.message)})})},[r.pathname,r.search,t==null?void 0:t.id,e])}const e5t=3e4;function wQ(t,e){const r=ms(),n=N.useRef(null),i=N.useRef(null),a=N.useRef(0),c=r.pathname,d=t5t(c),p=r5t(c,d),l=d==="listing"&&c.split("/listing/")[1]||null;N.useEffect(()=>{if(!(t!=null&&t.id)||!e)return;d==="listing"&&(a.current+=1);const g=localStorage.getItem(`ls_visitor_fp_${t.id}`)||null,v=async()=>{const{data:E,error:T}=await Be.from("lead_site_active_visitors").upsert({lead_site_id:t.id,auth_user_id:e,visitor_fingerprint:g,current_page_path:c,current_page_title:p,current_mls_number:l,last_seen_at:new Date().toISOString(),listing_views_count:a.current},{onConflict:"lead_site_id,session_key"}).select("id, notified_agent").single();!T&&E&&(n.current=E.id,a.current>=2&&!E.notified_agent&&Be.functions.invoke("lead-site-presence-notify",{body:{visitor_id:E.id,lead_site_id:t.id}}).catch(()=>{}))};return v(),i.current&&clearInterval(i.current),i.current=setInterval(v,e5t),()=>{i.current&&clearInterval(i.current)}},[t==null?void 0:t.id,e,c]),N.useEffect(()=>{if(!(t!=null&&t.id)||!e)return;const g=()=>{n.current&&Be.from("lead_site_active_visitors").delete().eq("id",n.current).then(()=>{})};return window.addEventListener("beforeunload",g),()=>window.removeEventListener("beforeunload",g)},[t==null?void 0:t.id,e])}function t5t(t){return t==="/"?"home":t==="/search"?"search":t.startsWith("/listing/")?"listing":t.startsWith("/homes-for-sale-in-")?"city":t.startsWith("/homes-in-")?"subdivision":"other"}function r5t(t,e){switch(e){case"home":return"Home";case"search":return"Search";case"listing":return`Listing ${t.split("/listing/")[1]||""}`;case"city":return t.replace("/homes-for-sale-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");case"subdivision":return t.replace("/homes-in-","").split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ");default:return t}}const yn=Number.isFinite||function(t){return typeof t=="number"&&isFinite(t)},n5t=Number.isSafeInteger||function(t){return typeof t=="number"&&Math.abs(t)<=i5t},i5t=Number.MAX_SAFE_INTEGER||9007199254740991;let Kn=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),Wt=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",t.UNKNOWN="unknown",t}({}),Ee=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});function s5t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var KV={exports:{}},jme;function a5t(){return jme||(jme=1,function(t,e){(function(r){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,a=/(?:\/|^)\.(?=\/)/g,c=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,d={buildAbsoluteURL:function(p,l,g){if(g=g||{},p=p.trim(),l=l.trim(),!l){if(!g.alwaysNormalize)return p;var v=d.parseURL(p);if(!v)throw new Error("Error trying to parse base URL.");return v.path=d.normalizePath(v.path),d.buildURLFromParts(v)}var E=d.parseURL(l);if(!E)throw new Error("Error trying to parse relative URL.");if(E.scheme)return g.alwaysNormalize?(E.path=d.normalizePath(E.path),d.buildURLFromParts(E)):l;var T=d.parseURL(p);if(!T)throw new Error("Error trying to parse base URL.");if(!T.netLoc&&T.path&&T.path[0]!=="/"){var j=i.exec(T.path);T.netLoc=j[1],T.path=j[2]}T.netLoc&&!T.path&&(T.path="/");var P={scheme:T.scheme,netLoc:E.netLoc,path:null,params:E.params,query:E.query,fragment:E.fragment};if(!E.netLoc&&(P.netLoc=T.netLoc,E.path[0]!=="/"))if(!E.path)P.path=T.path,E.params||(P.params=T.params,E.query||(P.query=T.query));else{var C=T.path,L=C.substring(0,C.lastIndexOf("/")+1)+E.path;P.path=d.normalizePath(L)}return P.path===null&&(P.path=g.alwaysNormalize?d.normalizePath(E.path):E.path),d.buildURLFromParts(P)},parseURL:function(p){var l=n.exec(p);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(p){for(p=p.split("").reverse().join("").replace(a,"");p.length!==(p=p.replace(c,"")).length;);return p.split("").reverse().join("")},buildURLFromParts:function(p){return p.scheme+p.netLoc+p.path+p.params+p.query+p.fragment}};t.exports=d})()}(KV)),KV.exports}var SQ=a5t();class EQ{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}let ts=function(t){return t.MANIFEST="manifest",t.LEVEL="level",t.AUDIO_TRACK="audioTrack",t.SUBTITLE_TRACK="subtitleTrack",t.MEDIA_FRAGMENT="media-fragment",t.KEY="key",t.STEERING_MANIFEST="steering-manifest",t.SERVER_CERTIFICATE="server-certificate",t.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",t}({}),On=function(t){return t.MAIN="main",t.AUDIO="audio",t.SUBTITLE="subtitle",t}({});var ro={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class RCe{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,l5t(this,"stats")}setByteRange(e,r){const n=e.split("@",2);let i;n.length===1?i=(r==null?void 0:r.byteRangeEndOffset)||0:i=parseInt(n[1]),this._byteRange=[i,parseInt(n[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[ro.AUDIO]:null,[ro.VIDEO]:null,[ro.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new EQ),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=SQ.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ro.AUDIO]=null,e[ro.VIDEO]=null,e[ro.AUDIOVIDEO]=null,this.url=null}}function Ko(t){return t.sn!=="initSegment"}function UI(t,e){return t.sn===(e==null?void 0:e.sn)&&t.level===e.level}function yH(t,e){return t.sn===(e==null?void 0:e.sn)&&t.level===e.level&&t.cc===e.cc}class oM extends RCe{constructor(e,r){super(r),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],r=this.byteRange[1];if(yn(e)&&yn(r))return r-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:r}=this;if(!r||r.NONE)return null;if(r.identity)this._decryptdata||(this._decryptdata=r.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const n=Object.keys(r);if(n.length===1){const i=this._decryptdata=r[n[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,r))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=yn(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var r;const n=Object.keys(this.levelkeys),i=n.length;if(i>1||i===1&&(r=this.levelkeys[n[0]])!=null&&r.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!yn(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return Ko(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const r=this.levelkeys;if(r){var n;const i=r[e];i&&!((n=this._decryptdata)!=null&&n.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,r))}}abortRequests(){var e,r;(e=this.loader)==null||e.abort(),(r=this.keyLoader)==null||r.abort()}setElementaryStreamInfo(e,r,n,i,a,c=!1){const{elementaryStreams:d}=this,p=d[e];if(!p){d[e]={startPTS:r,endPTS:n,startDTS:i,endDTS:a,partial:c};return}p.startPTS=Math.min(p.startPTS,r),p.endPTS=Math.max(p.endPTS,n),p.startDTS=Math.min(p.startDTS,i),p.endDTS=Math.max(p.endDTS,a)}}class o5t extends RCe{constructor(e,r,n,i,a){super(n),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=r,this.index=i;const c=e.enumeratedString("BYTERANGE");c&&this.setByteRange(c,a),a&&(this.fragOffset=a.fragOffset+a.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===On.SUBTITLE&&this.stats.loading.end>0)}}function LCe(t,e){const r=Object.getPrototypeOf(t);if(r){const n=Object.getOwnPropertyDescriptor(r,e);return n||LCe(r,e)}}function l5t(t,e){const r=LCe(t,e);r&&(r.enumerable=!0,Object.defineProperty(t,e,r))}function c5t(t,e,r){return(e=h5t(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function La(){return La=Object.assign?Object.assign.bind():function(t){for(var e=1;e499)}function aP(t){return t===0&&navigator.onLine===!1}function OCe(t,e){return e>0&&t.loadError>0&&t.loadErrorTime!==0&&self.performance.now()-t.loadErrorTime>e}class LS{constructor(e,r=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=r,this.totalWeight_=n}sample(e,r){const n=Math.pow(this.alpha_,e);this.estimate_=r*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class m5t{constructor(e,r,n,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new LS(e),this.fast_=new LS(r),this.defaultTTFB_=i,this.ttfb_=new LS(e)}update(e,r){const{slow_:n,fast_:i,ttfb_:a}=this;n.halfLife!==e&&(this.slow_=new LS(e,n.getEstimate(),n.getTotalWeight())),i.halfLife!==r&&(this.fast_=new LS(r,i.getEstimate(),i.getTotalWeight())),a.halfLife!==e&&(this.ttfb_=new LS(e,a.getEstimate(),a.getTotalWeight()))}sample(e,r){if(r<=0)return;const n=Math.min(this.minDelayMs_,r/1e5),i=8*r,a=Math.max(e,n)/1e3,c=i/a;this.fast_.sample(a,c),this.slow_.sample(a,c)}sampleTTFB(e){const r=e/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(r,2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class ff{constructor(e,r){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const n=`[${e}]:`;this.trace=R_,this.debug=r.debug.bind(null,n),this.log=r.log.bind(null,n),this.warn=r.warn.bind(null,n),this.info=r.info.bind(null,n),this.error=r.error.bind(null,n)}}const R_=function(){},p5t={trace:R_,debug:R_,log:R_,warn:R_,info:R_,error:R_};function xH(){return La({},p5t)}function g5t(t,e){const r=self.console[t];return r?r.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):R_}function Rme(t,e,r){return e[t]?e[t].bind(e):g5t(t,r)}const _H=xH();function y5t(t,e,r){const n=xH();if(typeof console=="object"&&t===!0||typeof t=="object"){const i=["debug","log","info","warn","error"];i.forEach(a=>{n[a]=Rme(a,t,r)});try{n.log(`Debug logs enabled for "${e}" in hls.js version 1.7.4`)}catch{return xH()}i.forEach(a=>{_H[a]=Rme(a,t)})}else La(_H,n);return n}const la=_H;function Rv(t=!0){return typeof self>"u"?void 0:(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function x5t(t){return typeof self<"u"&&t===self.ManagedMediaSource}function FCe(t,e){const r=Object.keys(t),n=Object.keys(e),i=r.length,a=n.length;return!i||!a||i===a&&!r.some(c=>n.indexOf(c)===-1)}function _5t(t){return btoa(String.fromCharCode(...t))}function UB(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}const v5t="utf-16",YV="utf-16be",Lme="utf-16le",wO="utf-8";function b5t(t,e={}){let r;UB(t)?r=new DataView(t):r=new DataView(t.buffer,t.byteOffset,t.byteLength);let n=0,{encoding:i}=e;if(!i){const l=r.getUint8(0),g=r.getUint8(1);l==239&&g==187&&r.getUint8(2)==191?(i=wO,n=3):l==254&&g==255?(i=YV,n=2):l==255&&g==254?(i=Lme,n=2):i=wO}if(typeof TextDecoder<"u")return new TextDecoder(i).decode(r);const{byteLength:a}=r,c=i!==YV;let d="",p;for(;n=194&&p<=223)if(n+1=128&&l<=191?(p=(p&31)<<6|l&63,n+=2):n++}else n++;else if(p>=224&&p<=239)if(n+2<=a-1){const l=r.getUint8(n+1),g=r.getUint8(n+2);l>=128&&l<=191&&g>=128&&g<=191?(p=(p&15)<<12|(l&63)<<6|g&63,n+=3):n++}else n++;else if(p>=240&&p<=244)if(n+3<=a-1){const l=r.getUint8(n+1),g=r.getUint8(n+2),v=r.getUint8(n+3);l>=128&&l<=191&&g>=128&&g<=191&&v>=128&&v<=191?(p=(p&7)<<18|(l&63)<<12|(g&63)<<6|v&63,n+=4):n++}else n++;else n++;break;case YV:case v5t:case Lme:p=r.getUint16(n,c),n+=2;break}d+=String.fromCodePoint(p)}return d}function w5t(t){const e=typeof t=="string"?new URL(t):t;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}function BCe(t,e){if(t<0)return-BCe(-t,e);const r=Math.pow(10,e);if(Math.abs(t*r%1-.5){const i=(r+Math.random()*16)%16|0;return r=Math.floor(r/16),(n=="x"?i:i&3|8).toString(16)})}}}function AQ(t,e){return e+10<=t.length&&t[e]===73&&t[e+1]===68&&t[e+2]===51&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function VB(t,e){let r=0;return r=(t[e]&127)<<21,r|=(t[e+1]&127)<<14,r|=(t[e+2]&127)<<7,r|=t[e+3]&127,r}function E5t(t,e){return AQ(t,e)&&VB(t,e+6)+10<=t.length-e}function $Ce(t,e){return e+10<=t.length&&t[e]===51&&t[e+1]===68&&t[e+2]===73&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function oP(t,e){const r=e;let n=0;for(;AQ(t,e);){n+=10;const i=VB(t,e+6);n+=i,$Ce(t,e+10)&&(n+=10),e+=n}if(n>0)return t.subarray(r,r+n)}function T5t(t){return UB(t)?t:t.byteOffset==0&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function ZV(t,e=0,r=1/0){return A5t(t,e,r,Uint8Array)}function A5t(t,e,r,n){const i=k5t(t);let a=1;"BYTES_PER_ELEMENT"in n&&(a=n.BYTES_PER_ELEMENT);const c=I5t(t)?t.byteOffset:0,d=(c+t.byteLength)/a,p=(c+e)/a,l=Math.floor(Math.max(0,Math.min(p,d)));return new n(i,l,Math.floor(Math.min(l+Math.max(r,0),d))-l)}function k5t(t){return UB(t)?t:t.buffer}function I5t(t){return t&&UB(t.buffer)&&t.byteLength!==void 0&&t.byteOffset!==void 0}function Qh(t,e=!1){const r=e?t.indexOf(0):t.length,n=b5t(new DataView(t.buffer,t.byteOffset,r),{encoding:wO});return e?n:n.replace(/\0/g,"")}function j5t(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null},r=3;if(t.size<2)return;if(t.data[0]!==r){console.log("Ignore frame with unrecognized character encoding");return}const n=t.data.subarray(1).indexOf(0);if(n===-1)return;const i=Qh(ZV(t.data,1,n)),a=t.data[2+n],c=t.data.subarray(3+n).indexOf(0);if(c===-1)return;const d=Qh(ZV(t.data,3+n,c));let p;return i==="-->"?p=Qh(ZV(t.data,4+n+c)):p=T5t(t.data.subarray(4+n+c)),e.mimeType=i,e.pictureType=a,e.description=d,e.data=p,e}function C5t(t){if(t.size<2)return;const e=Qh(t.data,!0),r=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:r.buffer}}function P5t(t){if(t.size<2)return;if(t.type==="TXXX"){let r=1;const{data:n}=t,i=Qh(n.subarray(r),!0);r+=i.length+1;const a=Qh(n.subarray(r));return{key:t.type,info:i,data:a}}const e=Qh(t.data.subarray(1));return{key:t.type,info:"",data:e}}function N5t(t){if(t.type==="WXXX"){if(t.size<2)return;let r=1;const n=Qh(t.data.subarray(r),!0);r+=n.length+1;const i=Qh(t.data.subarray(r));return{key:t.type,info:n,data:i}}const e=Qh(t.data);return{key:t.type,info:"",data:e}}function R5t(t){return t.type==="PRIV"?C5t(t):t.type[0]==="W"?N5t(t):t.type==="APIC"?j5t(t):P5t(t)}function L5t(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=VB(t,4),n=10;return{type:e,size:r,data:t.subarray(n,n+r)}}const lM=10,D5t=10;function UCe(t){let e=0;const r=[];for(;AQ(t,e);){const n=VB(t,e+6);t[e+5]>>6&1&&(e+=lM),e+=lM;const i=e+n;for(;e+D5te.charCodeAt(0))}function np(t){return String.fromCharCode.apply(null,t)}const Bp=Math.pow(2,32)-1,Ai={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},GCe={video:1,audio:2,id3:3,text:4};function HCe(t,e){const r=t[e]<<8|t[e+1];return r<0?65536+r:r}function Mn(t,e){const r=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return r<0?4294967296+r:r}function Dme(t,e){let r=Mn(t,e);return r*=Math.pow(2,32),r+=Mn(t,e+4),r}function cM(t,e){let r="";for(let n=e;n>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=r&255}function Mme(t,e,r){const n=e.byteOffset-t.byteOffset-8,i=8+r,a=e.byteLength+8-i;a<8||(Ul(t,n,i),Ul(t,n+i,a),Ul(t,n+i+4,Ai.free))}function bH(t,e){return[t.byteOffset-e-8,t.byteOffset-e+t.byteLength]}function WCe(t,e){e.sort((d,p)=>d[0]-p[0]);const r=e.reduce((d,[p,l])=>d+l-p,0),n=new Uint8Array(t.byteLength-r);let i=0,a=0;for(let d=0;de.reduce((p,[l,g])=>g<=d?p+g-l:p,0)}}function O5t(t){const e=Ci(t,["moov"]);if(e.length!==1||Ci(t,["moof"]).length)return null;const r=t.byteOffset,n=[],i=[];let a=!1;const c=Ci(e[0],["trak"]);for(let T=0;T0;if(l.length){({result:E,dropped:T,droppedBefore:j}=WCe(t,l)),Ul(E,c.byteOffset-d-8,c.byteLength+8-T);for(let P=0;P8&&Mn(t,n+4)===Ai[e])return!0;n=i>1?n+i:r}return!1}function Ci(t,e){const r=[];return e.length&&KCe(t,e,0,0,t.byteLength,r),r}function KCe(t,e,r,n,i,a){const c=e[r];if((c==null?void 0:c.length)!==4)return;const d=c.charCodeAt(0),p=c.charCodeAt(1),l=c.charCodeAt(2),g=c.charCodeAt(3),v=e.length-1;for(let E=n;E1?E+j:i;if(T&&t[E+4]===d&&t[E+5]===p&&t[E+6]===l&&t[E+7]===g){const C=Math.min(P,i);r===v?a.push(t.subarray(E+8,C)):KCe(t,e,r+1,E+8,C,a)}E=P}}function z5t(t){const e=[],r=t[0];let n=8;const i=Mn(t,n);n+=4;let a=0,c=0;r===0?(a=Mn(t,n),c=Mn(t,n+4),n+=8):(a=Dme(t,n),c=Dme(t,n+8),n+=16),n+=2;let d=t.length+c;const p=HCe(t,n);n+=2;for(let l=0;l>>31===1)return la.warn("SIDX has hierarchical references (not supported)"),null;const j=Mn(t,g);g+=4,e.push({referenceSize:E,subsegmentDuration:j,info:{duration:j/i,start:d,end:d+E-1}}),d+=E,g+=4,n=g}return{earliestPresentationTime:a,timescale:i,version:r,referencesCount:p,references:e}}function YCe(t){const e=[],r=Ci(t,["moov","trak"]);for(let i=0;i{const a=Mn(i,4),c=e[a];c&&(c.default={duration:Mn(i,12),sampleSize:Mn(i,16),flags:Mn(i,20)})}),e}function $5t(t){const e=t.subarray(8),r=e.subarray(86),n=np(e.subarray(4,8));let i=n,a;const c=n==="enca"||n==="encv";if(c){const l=Ci(e,[n])[0].subarray(n==="enca"?28:78);Ci(l,["sinf"]).forEach(v=>{const E=Ci(v,["schm"])[0];if(E){const T=np(E.subarray(4,8));if(T==="cbcs"||T==="cenc"){const j=Ci(v,["frma"])[0];j&&(i=np(j))}}})}const d=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const p=Ci(r,["avcC"])[0];p&&p.length>3&&(i+="."+dM(p[1])+dM(p[2])+dM(p[3]),a=uM(d==="avc1"?"dva1":"dvav",r));break}case"mp4a":{const p=Ci(e,[n])[0],l=Ci(p.subarray(28),["esds"])[0];if(l&&l.length>7){let g=4;if(l[g++]!==3)break;g=XV(l,g),g+=2;const v=l[g++];if(v&128&&(g+=2),v&64&&(g+=l[g++]),l[g++]!==4)break;g=XV(l,g);const E=l[g++];if(E===64)i+="."+dM(E);else break;if(g+=12,l[g++]!==5)break;g=XV(l,g);const T=l[g++];let j=(T&248)>>3;j===31&&(j+=1+((T&7)<<3)+((l[g]&224)>>5)),i+="."+j}break}case"hvc1":case"hev1":{const p=Ci(r,["hvcC"])[0];if(p&&p.length>12){const l=p[1],g=["","A","B","C"][l>>6],v=l&31,E=Mn(p,2),T=(l&32)>>5?"H":"L",j=p[12],P=p.subarray(6,12);i+="."+g+v,i+="."+U5t(E).toString(16).toUpperCase(),i+="."+T+j;let C="";for(let L=P.length;L--;){const O=P[L];(O||C)&&(C="."+O.toString(16).toUpperCase()+C)}i+=C}a=uM(d=="hev1"?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=uM(i,r)||i;break}case"vp09":{const p=Ci(r,["vpcC"])[0];if(p&&p.length>6){const l=p[4],g=p[5],v=p[6]>>4&15;i+="."+zp(l)+"."+zp(g)+"."+zp(v)}break}case"av01":{const p=Ci(r,["av1C"])[0];if(p&&p.length>2){const l=p[1]>>>5,g=p[1]&31,v=p[2]>>>7?"H":"M",E=(p[2]&64)>>6,T=(p[2]&32)>>5,j=l===2&&E?T?12:10:E?10:8,P=(p[2]&16)>>4,C=(p[2]&8)>>3,L=(p[2]&4)>>2,O=p[2]&3;i+="."+l+"."+zp(g)+v+"."+zp(j)+"."+P+"."+C+L+O+"."+zp(1)+"."+zp(1)+"."+zp(1)+"."+0,a=uM("dav1",r)}break}}return{codec:i,encrypted:c,supplemental:a}}function uM(t,e){const r=Ci(e,["dvvC"]),n=r.length?r[0]:Ci(e,["dvcC"])[0];if(n){const i=n[2]>>1&127,a=n[2]<<5&32|n[3]>>3&31;return t+"."+zp(i)+"."+zp(a)}}function U5t(t){let e=0;for(let r=0;r<32;r++)e|=(t>>r&1)<<31-r;return e>>>0}function XV(t,e){const r=e+5;for(;t[e++]&128&&e{const a=n.subarray(8,24);a.some(c=>c!==0)||(la.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${lc(a)} -> ${lc(r)}`),n.set(r,8))})}function q5t(t){const e=[];return ZCe(t,r=>e.push(r.subarray(8,24))),e}function ZCe(t,e){Ci(t,["moov","trak"]).forEach(n=>{const i=Ci(n,["mdia","minf","stbl","stsd"])[0];if(!i)return;const a=i.subarray(8);let c=Ci(a,["enca"]);const d=c.length>0;d||(c=Ci(a,["encv"])),c.forEach(p=>{const l=d?p.subarray(28):p.subarray(78);Ci(l,["sinf"]).forEach(v=>{const E=XCe(v);E&&e(E,d)})})})}function XCe(t){const e=Ci(t,["schm"])[0];if(e){const r=np(e.subarray(4,8));if(r==="cbcs"||r==="cenc"){const n=Ci(t,["schi","tenc"])[0];if(n)return n}}}let Ome;function G5t(t){return typeof TextDecoder>"u"?Qh(t):(Ome||(Ome=new TextDecoder("utf-8"))).decode(t).replace(/\0/g,"")}function H5t(t){const e=t.byteLength,r=[];for(let n=0;n1?n+a:e;if(i&&t[n+4]===109&&t[n+5]===111&&t[n+6]===111&&t[n+7]===102){const d=Math.min(c,e);for(let p=n+8;p1?p+g:d;if(l&&t[p+4]===116&&t[p+5]===114&&t[p+6]===97&&t[p+7]===102){const E=Math.min(v,d);let T,j;const P=[];for(let C=p+8;C1?C+O:E;if(L&&t[C+4]===116){const $=Math.min(F,E);t[C+5]===102&&t[C+6]===104&&t[C+7]===100?j||(j=t.subarray(C+8,$)):t[C+5]===102&&t[C+6]===100&&t[C+7]===116?T||(T=t.subarray(C+8,$)):t[C+5]===114&&t[C+6]===117&&t[C+7]===110&&P.push(t.subarray(C+8,$))}C=F}r.push({moofOffset:t.byteOffset+n,tfdt:T,tfhd:j,truns:P})}p=v}}n=c}return r}function W5t(t,e,r,n,i=!0){return QCe(t,e,n,i)}function K5t(t,e,r,n,i=!1){const a=[],c=e.samples,d=QCe(c,r,n,i,{isHEVCFlavor:xN(e.codec),samples:a,timeOffset:t,timescale:e.timescale,trackId:e.id});return{samples:a,sampleData:{includeSampleDetails:i,tracks:d}}}function QCe(t,e,r,n,i){const a={};let c=!1;const d=H5t(t),p=t.byteLength;for(let v=0;v0){let si=Ct;do{const ss=t[si]===0?t[si+1]<<16|t[si+2]<<8|t[si+3]:Mn(t,si);si+=4;const ps=t[si],Mi=Fn?ps>>1&63:ps&31;(Fn?Mi===39||Mi===40:Mi===6)&&lP(t.subarray(si,si+ss),Ar,Vr,i.samples),si+=ss}while(sip)break;zt=Lr+1,li+=8}}if($&&(i.timeOffset=Vr),tr!==-1&&Qt<=p&&O.keyFrameIndex===void 0&&(O.keyFrameIndex=tr,O.keyFrameStart=Kt+tr*Z),zt){(!yn(O.ptsMin)||KtO.ptsMax)&&(O.ptsMax=mn)}const Tn=Z*$e;be=Kt+Tn,Re+=Tn;continue}let Bt,cr;n&&(Bt=[],cr={sampleOffset:Ct,samples:Bt,defaultSampleDurationOffset:Q},Ct<=p&&O.trun.push(cr));let ft;for(let Kt=0;Kt<$e;Kt++){let ir;ot?(n&&(ir=ge.byteOffset-t.byteOffset+Vt),Ie=Mn(ge,Vt),Vt+=4):Ie=Z,nt?(ft=Mn(ge,Vt),Vt+=4):ft=ee;let Gr,tr;tt&&(tr=ge[Vt+1]&1?1:0,n&&(Gr={isNonSync:tr,dependsOn:(ge[Vt]&3)===1?1:2}),Vt+=4);let Qt=0;if(vt&&(Qt=ge[0]===0?Mn(ge,Vt):vH(ge,Vt),Vt+=4),$){let zt=Ct,Vr=0;for(;VrO.ptsMax)&&(O.ptsMax=zt+Ie),Bt&&(Bt[Kt]={cts:Qt,duration:Ie,flags:Gr,size:ft})}be+=Ie,Re+=Ie}!Re&&Z&&(Re+=Z*$e)}O.duration+=Re,O.duration&&(c=!0)}if(!c){let v=1/0,E=0;const T=Ci(t,["sidx"]);for(let j=0;jL+O.info.duration||0,0);E=Math.max(E,C+P.earliestPresentationTime/P.timescale)}}E&&yn(E)&&Object.keys(a).forEach(j=>{a[j].duration||(a[j].duration=E*a[j].timescale-a[j].start)})}return a}function Y5t(t){const e={valid:null,remainder:null},r=Ci(t,["moof"]);if(r.length<2)return e.remainder=t,e;const n=r[r.length-1];return e.valid=t.slice(0,n.byteOffset-8),e.remainder=t.slice(n.byteOffset-8),e}function Kf(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function Z5t(t,e){const r=[],n=e.samples,i=e.timescale,a=e.id;let c=!1;return Ci(n,["moof"]).map(p=>{const l=p.byteOffset-8;Ci(p,["traf"]).map(v=>{const E=Ci(v,["tfdt"]).map(T=>{const j=T[0];let P=Mn(T,4);return j===1&&(P*=Math.pow(2,32),P+=Mn(T,8)),P/i})[0];return E!==void 0&&(t=E),Ci(v,["tfhd"]).map(T=>{const j=Mn(T,4),P=Mn(T,0)&16777215,C=(P&1)!==0;let L=0;const O=(P&2)!==0,F=(P&8)!==0;let $=0;const G=(P&16)!==0;let W=0;const Z=(P&32)!==0,Q=!C&&(P&131072)!==0;let ee=8;j===a&&(C?(L=Mn(T,ee),ee+=4,L*=Math.pow(2,32),L+=Mn(T,ee),ee+=4):Q&&(L=l),O&&(ee+=4),F&&($=Mn(T,ee),ee+=4),G&&(W=Mn(T,ee),ee+=4),Z&&(ee+=4),e.type==="video"&&(c=xN(e.codec)),Ci(v,["trun"]).map(ie=>{const oe=ie[0],pe=Mn(ie,0)&16777215,Le=(pe&1)!==0;let be=0;const Re=(pe&4)!==0,Ie=(pe&256)!==0;let Te=0;const ge=(pe&512)!==0;let $e=0;const we=(pe&1024)!==0,ke=(pe&2048)!==0;let Ae=0;const He=Mn(ie,4);let ot=8;Le&&(be=Mn(ie,ot),ot+=4),Re&&(ot+=4);let nt=L+be;for(let tt=0;tt>1&63;return r===39||r===40}else return(e&31)===6}function lP(t,e,r,n){const i=ePe(t);let a=0;a+=e;let c=0,d=0,p=0;for(;a=i.length)break;p=i[a++],c+=p}while(p===255);d=0;do{if(a>=i.length)break;p=i[a++],d+=p}while(p===255);const l=i.length-a;let g=a;if(dl){la.error(`Malformed SEI payload. ${d} is too small, only ${l} bytes left to parse.`);break}if(c===4){if(i[g++]===181){const E=HCe(i,g);if(g+=2,E===49){const T=Mn(i,g);if(g+=4,T===1195456820){const j=i[g++];if(j===3){const P=i[g++],C=31&P,L=64&P,O=L?2+C*3:0,F=new Uint8Array(O);if(L){F[0]=P;for(let $=1;$16){const v=[];for(let j=0;j<16;j++){const P=i[g++].toString(16);v.push(P.length==1?"0"+P:P),(j===3||j===5||j===7||j===9)&&v.push("-")}const E=d-16,T=new Uint8Array(E);for(let j=0;j>24&255,a[1]=n>>16&255,a[2]=n>>8&255,a[3]=n&255,a.set(t,4),i=0,n=8;i0?(a=new Uint8Array(4),e.length>0&&new DataView(a.buffer).setUint32(0,e.length,!1)):a=new Uint8Array;const c=new Uint8Array(4);return r.byteLength>0&&new DataView(c.buffer).setUint32(0,r.byteLength,!1),Q5t([112,115,115,104],new Uint8Array([n,0,0,0]),t,a,i,c,r)}function tPe(t){const e=[];if(t instanceof ArrayBuffer){const r=t.byteLength;let n=0;for(;n+32>3===2)if(a===32){const c=new Uint8Array(16);for(let d=0;d<16;d++)c[d]=parseInt(String.fromCharCode(t[r+d*2],t[r+d*2+1]),16);e.push(c)}else a===16&&e.push(t.subarray(r,r+16));r+=a}return e}function tBt(t){const e=t.getUint32(0),r=t.byteOffset,n=t.byteLength;if(n>>24;if(a!==0&&a!==1)return{offset:r,size:e};const c=t.buffer,d=lc(new Uint8Array(c,r+12,16));let p=null,l=null,g=0;if(a===0)g=28;else{const E=t.getUint32(28);if(!E||n<32+E*16)return{offset:r,size:e};p=[];for(let T=0;T-1||/iPhone|iPad|iPod/.test(HA)}function aBt(){return/Android/.test(HA)}const GT={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function jQ(t,e){const r=GT[e];return!!r&&!!r[t.slice(0,4)]}function cP(t,e,r=!0){return!t.split(",").some(n=>!CQ(n,e,r))}function CQ(t,e,r=!0){var n;const i=Rv(r);return(n=i==null?void 0:i.isTypeSupported(uP(t,e)))!=null?n:!1}function uP(t,e){return`${e}/mp4;codecs=${t}`}function Fme(t){if(t){const e=t.substring(0,4);return GT.video[e]}return 2}function G3(t){const e=nPe();return t.split(",").reduce((r,n)=>{const a=e&&xN(n)?9:GT.video[n];return a?(a*2+r)/(r?3:2):(GT.audio[n]+r)/(r?2:1)},0)}const t8={};function oBt(t,e=!0){if(t8[t])return t8[t];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let i=0;ioBt(r.toLowerCase(),e))}function cBt(t,e){const r=[];if(t){const n=t.split(",");for(let i=0;i4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t)!==-1)&&(Bme(t,"audio")||Bme(t,"video")))return t;if(e){const r=e.split(",");if(r.length>1){if(t){for(let n=r.length;n--;)if(r[n].substring(0,4)===t.substring(0,4))return r[n]}return r[0]}}return e||t}function Bme(t,e){return jQ(t,e)&&CQ(t,e)}function uBt(t){const e=t.split(",");for(let r=0;r2&&n[0]==="avc1"&&(e[r]=`avc1.${parseInt(n[1]).toString(16)}${("000"+parseInt(n[2]).toString(16)).slice(-4)}`)}return e.join(",")}function dBt(t){if(t.startsWith("av01.")){const e=t.split("."),r=["0","111","01","01","01","0"];for(let n=e.length;n>4&&n<10;n++)e[n]=r[n-4];return e.join(".")}return t}function zme(t){const e=Rv(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function wH(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const hBt={supported:!0,powerEfficient:!0,smooth:!0},fBt={supported:!1,smooth:!1,powerEfficient:!1},iPe={supported:!0,configurations:[],decodingInfoResults:[hBt]};function sPe(t,e){return{supported:!1,configurations:e,decodingInfoResults:[fBt],error:t}}function mBt(t,e,r,n,i,a){const c=t.videoCodec,d=t.audioCodec?t.audioGroups:null,p=a==null?void 0:a.audioCodec,l=a==null?void 0:a.channels,g=l?parseInt(l):p?1/0:2;let v=null;if(d!=null&&d.length)try{d.length===1&&d[0]?v=e.groups[d[0]].channels:v=d.reduce((E,T)=>{if(T){const j=e.groups[T];if(!j)throw new Error(`Audio track group ${T} not found`);Object.keys(j.channels).forEach(P=>{E[P]=(E[P]||0)+j.channels[P]})}return E},{2:0})}catch{return!0}return c!==void 0&&(c.split(",").some(E=>xN(E))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(n,30)||t.videoRange!=="SDR"&&t.videoRange!==r||t.bitrate>Math.max(i,8e6))||!!v&&yn(g)&&Object.keys(v).some(E=>parseInt(E)>g)}function aPe(t,e,r,n={}){const i=t.videoCodec;if(!i&&!t.audioCodec||!r)return Promise.resolve(iPe);const a=[],c=pBt(t),d=c.length,p=gBt(t,e,d>0),l=p.length;for(let g=d||1*l||1;g--;){const v={type:"media-source"};if(d&&(v.video=c[g%d]),l){v.audio=p[g%l];const E=v.audio.bitrate;v.video&&E&&(v.video.bitrate-=E)}a.push(v)}if(i){const g=navigator.userAgent;if(i.split(",").some(v=>xN(v))&&nPe())return Promise.resolve(sPe(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${g})`),a))}return Promise.all(a.map(g=>{const v=yBt(g);return n[v]||(n[v]=r.decodingInfo(g))})).then(g=>({supported:!g.some(v=>!v.supported),configurations:a,decodingInfoResults:g})).catch(g=>({supported:!1,configurations:a,decodingInfoResults:[],error:g}))}function pBt(t){var e;const r=(e=t.videoCodec)==null?void 0:e.split(","),n=lPe(t),i=t.width||640,a=t.height||480,c=t.frameRate||30,d=t.videoRange.toLowerCase();return r?r.map(p=>{const l={contentType:uP(dBt(p),"video"),width:i,height:a,bitrate:n,framerate:c};return d!=="sdr"&&(l.transferFunction=d),l}):[]}function gBt(t,e,r){var n;const i=(n=t.audioCodec)==null?void 0:n.split(","),a=lPe(t);return i&&t.audioGroups?t.audioGroups.reduce((c,d)=>{var p;const l=d?(p=e.groups[d])==null?void 0:p.tracks:null;return l?l.reduce((g,v)=>{if(v.groupId===d){const E=parseFloat(v.channels||"");i.forEach(T=>{const j={contentType:uP(T,"audio"),bitrate:r?oPe(T,a):a};E&&(j.channels=""+E),g.push(j)})}return g},c):c},[]):[]}function oPe(t,e){if(e<=1)return 1;let r=128e3;return t==="ec-3"?r=768e3:t==="ac-3"&&(r=64e4),Math.min(e/2,r)}function lPe(t){return Math.ceil(Math.max(t.bitrate*.9,t.averageBitrate)/1e3)*1e3||1}function yBt(t){let e="";const{audio:r,video:n}=t;if(n){const i=wH(n.contentType);e+=`${i}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(r){const i=wH(r.contentType);e+=`${n?"_":""}${i}_c${r.channels}`}return e}function fv(t,e,r){const n=encodeURIComponent(e),i=`${n}=${encodeURIComponent(r)}`;let a=!1;const c=[];t.search.substring(1).split("&").forEach(d=>{d===n||d.startsWith(n+"=")?a||(c.push(i),a=!0):d&&c.push(d)}),a||c.push(i),t.search=c.join("&")}const SH=["NONE","TYPE-0","TYPE-1",null];function xBt(t){return SH.indexOf(t)>-1}const W3=["SDR","PQ","HLG"];function _Bt(t){return!!t&&W3.indexOf(t)>-1}var EO={No:"",Yes:"YES",v2:"v2"};function $me(t){const{canSkipUntil:e,canSkipDateRanges:r,age:n}=t,i=n!!n).map(n=>n.substring(0,4)).join(","),"supplemental"in e){var r;this.supplemental=e.supplemental;const n=(r=e.supplemental)==null?void 0:r.videoCodec;n&&n!==e.videoCodec&&(this.codecSet+=`,${n.substring(0,4)}`)}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Vme(this._audioGroups,e)}hasSubtitleGroup(e){return Vme(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,r){if(r){if(e==="audio"){let n=this._audioGroups;n||(n=this._audioGroups=[]),n.indexOf(r)===-1&&n.push(r)}else if(e==="text"){let n=this._subtitleGroups;n||(n=this._subtitleGroups=[]),n.indexOf(r)===-1&&n.push(r)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Vme(t,e){return!e||!t?!1:t.indexOf(e)!==-1}function vBt(){if(typeof matchMedia=="function"){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return t.matches===!0}return!1}function bBt(t,e){let r=!1,n=[];if(t&&(r=t!=="SDR",n=[t]),e){n=e.allowedVideoRanges||W3.slice(0);const i=n.join("")!=="SDR"&&!e.videoCodec;r=e.preferHDR!==void 0?e.preferHDR:i&&vBt(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}const wBt=t=>{const e=new WeakSet;return(r,n)=>{if(t&&(n=t(r,n)),typeof n=="object"&&n!==null){if(e.has(n))return;e.add(n)}return n}},fo=(t,e)=>JSON.stringify(t,wBt(e));function SBt(t,e,r,n,i){const a=Object.keys(t),c=n==null?void 0:n.channels,d=n==null?void 0:n.audioCodec,p=i==null?void 0:i.videoCodec,l=c&&parseInt(c)===2;let g=!1,v=!1,E=1/0,T=1/0,j=1/0,P=1/0,C=0,L=[];const{preferHDR:O,allowedVideoRanges:F}=bBt(e,i);for(let Q=a.length;Q--;){const ee=t[a[Q]];g||(g=ee.channels[2]>0),E=Math.min(E,ee.minHeight),T=Math.min(T,ee.minFramerate),j=Math.min(j,ee.minBitrate),F.filter(oe=>ee.videoRanges[oe]>0).length>0&&(v=!0)}E=yn(E)?E:0,T=yn(T)?T:0;const $=Math.max(1080,E),G=Math.max(30,T);j=yn(j)?j:r,r=Math.max(j,r),v||(e=void 0);const W=a.length>1;return{codecSet:a.reduce((Q,ee)=>{const ie=t[ee];if(ee===Q)return Q;if(L=v?F.filter(oe=>ie.videoRanges[oe]>0):[],W){if(ie.minBitrate>r)return Dp(ee,`min bitrate of ${ie.minBitrate} > current estimate of ${r}`),Q;if(!ie.hasDefaultAudio)return Dp(ee,"no renditions with default or auto-select sound found"),Q;if(d&&ee.indexOf(d.substring(0,4))%5!==0)return Dp(ee,`audio codec preference "${d}" not found`),Q;if(c&&!l){if(!ie.channels[c])return Dp(ee,`no renditions with ${c} channel sound found (channels options: ${Object.keys(ie.channels)})`),Q}else if((!d||l)&&g&&ie.channels[2]===0)return Dp(ee,"no renditions with stereo sound found"),Q;if(ie.minHeight>$)return Dp(ee,`min resolution of ${ie.minHeight} > maximum of ${$}`),Q;if(ie.minFramerate>G)return Dp(ee,`min framerate of ${ie.minFramerate} > maximum of ${G}`),Q;if(!L.some(oe=>ie.videoRanges[oe]>0))return Dp(ee,`no variants with VIDEO-RANGE of ${fo(L)} found`),Q;if(p&&ee.indexOf(p.substring(0,4))%5!==0)return Dp(ee,`video codec preference "${p}" not found`),Q;if(ie.maxScore=G3(Q)||ie.fragmentError>t[Q].fragmentError)?Q:(P=ie.minIndex,C=ie.maxScore,ee)},void 0),videoRanges:L,preferHDR:O,minFramerate:T,minBitrate:j,minIndex:P}}function Dp(t,e){la.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function cPe(t){return t.reduce((e,r)=>{let n=e.groups[r.groupId];n||(n=e.groups[r.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),n.tracks.push(r);const i=r.channels||"2";return n.channels[i]=(n.channels[i]||0)+1,n.hasDefault=n.hasDefault||r.default,n.hasAutoSelect=n.hasAutoSelect||r.autoselect,n.hasDefault&&(e.hasDefaultAudio=!0),n.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function EBt(t,e,r,n){return t.slice(r,n+1).reduce((i,a,c)=>{if(!a.codecSet)return i;const d=a.audioGroups;let p=i[a.codecSet];p||(i[a.codecSet]=p={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:c,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!d,fragmentError:0}),p.minBitrate=Math.min(p.minBitrate,a.bitrate);const l=Math.min(a.height,a.width);return p.minHeight=Math.min(p.minHeight,l),p.minFramerate=Math.min(p.minFramerate,a.frameRate),p.minIndex=Math.min(p.minIndex,c),p.maxScore=Math.max(p.maxScore,a.score),p.fragmentError+=a.fragmentError,p.videoRanges[a.videoRange]=(p.videoRanges[a.videoRange]||0)+1,d&&d.forEach(g=>{if(!g)return;const v=e.groups[g];v&&(p.hasDefaultAudio=p.hasDefaultAudio||e.hasDefaultAudio?v.hasDefault:v.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(v.channels).forEach(E=>{p.channels[E]=(p.channels[E]||0)+v.channels[E]}))}),i},{})}function qme(t){if(!t)return t;const{lang:e,assocLang:r,characteristics:n,channels:i,audioCodec:a}=t;return{lang:e,assocLang:r,characteristics:n,channels:i,audioCodec:a}}function Jp(t,e,r){if("attrs"in t){const n=e.indexOf(t);if(n!==-1)return n}for(let n=0;nn.indexOf(i)===-1)}function vb(t,e){const{audioCodec:r,channels:n}=t;return(r===void 0||(e.audioCodec||"").substring(0,4)===r.substring(0,4))&&(n===void 0||n===(e.channels||"2"))}function kBt(t,e,r,n,i){const a=e[n],d=e.reduce((E,T,j)=>{const P=T.uri;return(E[P]||(E[P]=[])).push(j),E},{})[a.uri];d.length>1&&(n=Math.max.apply(Math,d));const p=a.videoRange,l=a.frameRate,g=a.codecSet.substring(0,4),v=Gme(e,n,E=>{if(E.videoRange!==p||E.frameRate!==l||E.codecSet.substring(0,4)!==g)return!1;const T=E.audioGroups,j=r.filter(P=>hP(P.groupId,T));return Jp(t,j,i)>-1});return v>-1?v:Gme(e,n,E=>{const T=E.audioGroups,j=r.filter(P=>hP(P.groupId,T));return Jp(t,j,i)>-1})}function Gme(t,e,r){for(let n=e;n>-1;n--)if(r(t[n]))return n;for(let n=e+1;n{var n;const{fragCurrent:i,partCurrent:a,hls:c}=this;if(!c)return;const{autoLevelEnabled:d,media:p}=c;if(!i||!p)return;const l=performance.now(),g=a?a.stats:i.stats,v=a?a.duration:i.duration,E=l-g.loading.start,T=c.minAutoLevel,j=i.level,P=this._nextAutoLevel;if(g.aborted||g.loaded&&g.loaded===g.total||j<=T){this.clearTimer(),this._nextAutoLevel=-1;return}if(!d)return;const C=P>-1&&P!==j,L=!!r||C;if(!L&&(p.paused||!p.playbackRate||!p.readyState))return;const O=c.mainForwardBufferInfo;if(!L&&O===null)return;const F=this.bwEstimator.getEstimateTTFB(),$=Math.abs(p.playbackRate);if(E<=Math.max(F,1e3*(v/($*2))))return;const G=O?O.len/$:0,W=g.loading.first?g.loading.first-g.loading.start:-1,Z=g.loaded&&W>-1,Q=this.getBwEstimate(),ee=c.levels,ie=ee[j],oe=Math.max(g.loaded,Math.round(v*(i.bitrate||ie.averageBitrate)/8));let pe=Z?E-W:E;pe<1&&Z&&(pe=Math.min(E,g.loaded*8/Q));const Le=Z?g.loaded*1e3/pe:0,be=F/1e3,Re=Le?(oe-g.loaded)/Le:oe*8/Q+be;if(Re<=G)return;const Ie=Le?Le*8:Q,Te=((n=(r==null?void 0:r.details)||c.latestLevelDetails)==null?void 0:n.live)===!0,ge=c.config.abrBandWidthUpFactor;let $e=Number.POSITIVE_INFINITY,we;for(we=j-1;we>T;we--){const ot=ee[we].maxBitrate,nt=!ee[we].details||Te;if($e=this.getTimeToLoadFrag(be,Ie,v*ot,nt),$e=Re||$e>v*10)return;Z?this.bwEstimator.sample(E-Math.min(F,W),g.loaded):this.bwEstimator.sampleTTFB(E);const ke=ee[we].maxBitrate;this.getBwEstimate()*ge>ke&&(this.firstAutoFloor=Math.min(we,c.firstLevel),this.resetEstimator(ke));const Ae=this.findBestLevel(ke,T,we,0,G,1,1);Ae>-1&&(we=Ae),this.warn(`Fragment ${i.sn}${a?" part "+a.index:""} of level ${j} is loading too slowly; Fragment duration: ${i.duration.toFixed(3)} Time to underbuffer: ${G.toFixed(3)} s Estimated load time for current fragment: ${Re.toFixed(3)} s Estimated load time for down switch fragment: ${$e.toFixed(3)} s TTFB estimate: ${W|0} ms Current BW estimate: ${yn(Q)?Q|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${we} @ ${ke|0} bps`),c.nextLoadLevel=c.nextAutoLevel=we,this.clearTimer();const He=()=>{this.clearTimer();const ot=this.hls;if(this.fragCurrent===i&&ot.loadLevel===we&&we>0){const nt=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${we>0?"and switching down":""} Fragment duration: ${i.duration.toFixed(3)} s Time to underbuffer: ${nt.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,we>T){let tt=this.findBestLevel(ot.levels[T].bitrate,T,we,0,nt,1,1);tt===-1&&(tt=T),ot.nextLoadLevel=ot.nextAutoLevel=tt,this.firstAutoFloor=Math.min(tt,ot.firstLevel),this.resetEstimator(ot.levels[tt].bitrate)}}};C||Re>$e*2?He():this.timer=self.setInterval(He,$e*1e3),c.trigger(Ee.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:a,stats:g})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const e=this.hls.config;return new m5t(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const e=this.hls;e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.FRAG_LOADING,this.onFragLoading,this),e.on(Ee.FRAG_LOADED,this.onFragLoaded,this),e.on(Ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Ee.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Ee.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.FRAG_LOADING,this.onFragLoading,this),e.off(Ee.FRAG_LOADED,this.onFragLoaded,this),e.off(Ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Ee.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Ee.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,r){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,r){const n=r.frag;if(!this.ignoreFragment(n)){if(!n.bitrateTest){var i;this.fragCurrent=n,this.partCurrent=(i=r.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,r){this.clearTimer()}onError(e,r){if(!r.fatal)switch(r.details){case Wt.BUFFER_ADD_CODEC_ERROR:case Wt.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Wt.FRAG_LOAD_TIMEOUT:{const n=r.frag,{fragCurrent:i,partCurrent:a}=this;if(n&&yH(n,i)){const c=performance.now(),d=a?a.stats:n.stats,p=c-d.loading.start,l=d.loading.first?d.loading.first-d.loading.start:-1;if(d.loaded&&l>-1){const v=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(p-Math.min(v,l),d.loaded)}else this.bwEstimator.sampleTTFB(p)}break}}}getTimeToLoadFrag(e,r,n,i){const a=e+n/r,c=i?e+this.lastLevelLoadSec:0;return a+c}onLevelLoaded(e,r){const n=this.hls.config,{loading:i}=r.stats,a=i.end-i.first;yn(a)&&(this.lastLevelLoadSec=a/1e3),r.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(r.levelInfo)}onFragLoaded(e,r){var n;const{frag:i,part:a}=r,c=a?a.stats:i.stats;if(i.type===On.MAIN&&this.bwEstimator.sampleTTFB(c.loading.first-c.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(n=this.hls)!=null&&n.config.abrMaxWithRealBitrate){const d=a?a.duration:i.duration,p=this.hls.levels[i.level],l=(p.loaded?p.loaded.bytes:0)+c.loaded,g=(p.loaded?p.loaded.duration:0)+d;p.loaded={bytes:l,duration:g},p.realBitrate=Math.round(8*l/g)}if(i.bitrateTest){const d={stats:c,frag:i,part:a,id:i.type};this.onFragBuffered(Ee.FRAG_BUFFERED,d),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}onFragBuffered(e,r){const{frag:n,part:i}=r,a=i!=null&&i.stats.loaded?i.stats:n.stats;if(a.aborted||this.ignoreFragment(n))return;const d=((n.bitrate||0)>=1e5?a.parsing.end:a.loading.end)-a.loading.start-Math.min(a.loading.first-a.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(d,a.loaded),a.bwEstimate=this.getBwEstimate(),n.bitrateTest?this.bitrateTestDelay=d/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==On.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:e}=this;if(!e)return 0;const{maxAutoLevel:r,minAutoLevel:n}=e,i=this.getBwEstimate(),a=this.getStarvationDelay(),c=e.config.maxStarvationDelay,d=this.findBestLevel(i,n,r,a/2,c,1,1);if(d>-1)return d;const p=e.firstLevel,l=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,g=Math.min(Math.max(p,n),r,l);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${p} clamped to ${g}`),g}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const e=this.forcedAutoLevel,n=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!n||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const a=n&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const c=this.hls.levels;if(c.length>Math.max(e,a)&&c[e].loadError<=c[a].loadError)return e}return this._nextAutoLevel=a,this.nextAutoLevelKey=this.getAutoLevelKey(),a}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:r,hls:n}=this;if(!n)return-1;if(n.levels.length<=1)return n.loadLevel;const{maxAutoLevel:i,config:a,minAutoLevel:c}=n,d=r?r.duration:e?e.duration:0,p=this.getBwEstimate(),l=this.getStarvationDelay();let g=a.abrBandWidthFactor,v=a.abrBandWidthUpFactor;if(l){const C=this.findBestLevel(p,c,i,l,0,g,v);if(C>=0)return this.rebufferNotice=-1,C}let E=d?Math.min(d,a.maxStarvationDelay):a.maxStarvationDelay;if(!l){const C=this.bitrateTestDelay;C&&(E=(d?Math.min(d,a.maxLoadingDelay):a.maxLoadingDelay)-C,this.info(`bitrate test took ${Math.round(1e3*C)}ms, set first fragment max fetchDuration to ${Math.round(1e3*E)} ms`),g=v=1)}const T=this.findBestLevel(p,c,i,l,E,g,v);if(this.rebufferNotice!==T&&(this.rebufferNotice=T,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${T}`)),T>-1)return T;const j=n.levels[c],P=n.loadLevelObj;return P&&(j==null?void 0:j.bitrate)=r;Te--){var Ie;const ge=j[Te],$e=Te>T;if(!ge)continue;if(O.useMediaCapabilities&&!ge.supportedResult&&!ge.supportedPromise){const tt=navigator.mediaCapabilities;typeof(tt==null?void 0:tt.decodingInfo)=="function"&&mBt(ge,oe,Z,Q,e,ee)?(ge.supportedPromise=aPe(ge,oe,tt,this.supportedCache),ge.supportedPromise.then(vt=>{if(!this.hls)return;ge.supportedResult=vt;const Vt=this.hls.levels,Ct=Vt.indexOf(ge);vt.error?this.warn(`MediaCapabilities decodingInfo error: "${vt.error}" for level ${Ct} ${fo(vt)}`):vt.supported?vt.decodingInfoResults.some(Bt=>Bt.smooth===!1||Bt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ct} not smooth or powerEfficient: ${fo(vt)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ct} ${fo(vt)}`),Ct>-1&&Vt.length>1&&(this.log(`Removing unsupported level ${Ct}`),this.hls.removeLevel(Ct),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(vt=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${vt}`)})):ge.supportedResult=iPe}if((W&&ge.codecSet!==W||Z&&ge.videoRange!==Z||$e&&Q>ge.frameRate||!$e&&Q>0&&Qtt.smooth===!1))&&(!G||Te!==pe)){Re.push(Te);continue}const we=ge.details,ke=(v?we==null?void 0:we.partTarget:we==null?void 0:we.averagetargetduration)||Le||1;let Ae;$e?Ae=d*e:Ae=c*e;const He=Le&&i>=Le*2&&a===0?ge.averageBitrate:ge.maxBitrate,ot=this.getTimeToLoadFrag(be,Ae,He*ke,!we||we.live);if(Ae>=He&&(Te===l||ge.loadError===0&&ge.fragmentError===0||OCe(ge,O.errorPenaltyExpireMs))&&(ot<=be||!yn(ot)||$&&!this.bitrateTestDelay||ot${Te} adjustedbw(${Math.round(Ae)})-bitrate=${Math.round(Ae-He)} ttfb:${be.toFixed(1)} avgDuration:${ke.toFixed(1)} maxFetchDuration:${E.toFixed(1)} fetchDuration:${ot.toFixed(1)} firstSelection:${G} codecSet:${ge.codecSet} videoRange:${ge.videoRange} hls.loadLevel:${C}`)),G&&(this.firstSelection=Te),Te}}return-1}set nextAutoLevel(e){const r=this.deriveNextAutoLevel(e);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}deriveNextAutoLevel(e){if(!this.hls)return-1;const{maxAutoLevel:r,minAutoLevel:n}=this.hls;return Math.min(Math.max(e,n),r)}}class jBt{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,r,n){if(this.queues===null||this.tracks===null)return;const i=this.queues[r];i.push(e),i.length===1&&!n&&this.executeNext(r)}appendBlocker(e){return new Promise(r=>{const n={label:"async-blocker",execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(n,e)})}prependBlocker(e){return new Promise(r=>{if(this.queues){const n={label:"async-blocker-prepend",execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(n)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var r;const n=(r=e[0])==null?void 0:r.label;n==="async-blocker"||n==="async-blocker-prepend"?(e[0].execute(),e.splice(0,1)):n==="block-audio"&&e.splice(0,1)})}insertNext(e,r){this.queues!==null&&this.queues[r].splice(1,0,...e)}unblockAudio(){var e;this.queues!==null&&((e=this.current("audio"))==null?void 0:e.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(e=>e.label==="block-audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const r=this.queues[e];if(r.length){const i=r[0];try{i.execute()}catch(a){var n;if(i.onError(a),this.queues===null||this.tracks===null)return;const c=(n=this.tracks[e])==null?void 0:n.buffer;c!=null&&c.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var r;return((r=this.queues)==null?void 0:r[e][0])||null}toString(){const{queues:e,tracks:r}=this;return e===null||r===null?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(e){var r,n;return(r=this.queues)!=null&&r[e]||(n=this.tracks)!=null&&n[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var r;const n=(r=this.tracks)==null?void 0:r[e],i=n==null?void 0:n.buffer;return i?`SourceBuffer${i.updating?" updating":""}${n.ended?" ended":""}${n.ending?" ending":""}`:"none"}listOps(e){var r;return((r=this.queues)==null?void 0:r[e].map(n=>n.label).join(", "))||""}}const dPe={search:function(t,e){let r=0,n=t.length-1,i=null,a=null;for(;r<=n;){i=(r+n)/2|0,a=t[i];const c=e(a);if(c>0)r=i+1;else if(c<0)n=i-1;else return a}return null}};function CBt(t,e,r){if(e===null||!Array.isArray(t)||!t.length||!yn(e))return null;const n=t[0].programDateTime;if(e<(n||0))return null;const i=t[t.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let a=0;a0&&d<15e-7&&(r+=15e-7),a&&t.level!==a.level&&a.end<=t.end&&(a=e[2+t.sn-e[0].sn]||null)}else r===0&&e[0].start===0&&(a=e[0]);if(a&&((!t||t.level===a.level)&&Hme(r,n,a)===0||PBt(a,t,Math.min(i,n))))return a;const c=dPe.search(e,Hme.bind(null,r,n));return c&&(c!==t||!a)?c:a}function PBt(t,e,r){if((e==null?void 0:e.start)===0&&e.level0){const n=e.tagList.reduce((i,a)=>(a[0]==="INF"&&(i+=parseFloat(a[1])),i),r);return t.start<=n}return!1}function Hme(t=0,e=0,r){if(r.start<=t&&r.start+r.duration>t)return 0;const n=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=t?1:r.start-n>t&&r.start?-1:0}function NBt(t,e,r){const n=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>t}function hPe(t,e,r){if(t&&t.startCC<=e&&t.endCC>=e){let n=t.fragments;const{fragmentHint:i}=t;i&&(n=n.concat(i));let a;return dPe.search(n,c=>c.cce?-1:(a=c,c.end<=r?1:c.start>r?-1:0)),a||null}return null}function fPe(t,e){return e===t.endSN&&t.fragmentHint?t.fragmentHint:t.fragments[1+e-t.startSN]||null}var ju={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Zc={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class RBt extends ff{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Ee.ERROR,this.onError,this),e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Ee.ERROR,this.onError,this),e.off(Ee.ERROR,this.onErrorOut,this),e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===On.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const r=this.hls,n=r.currentLevel;return(e=r.loadLevelObj)!=null&&e.details||n===-1?r.loadLevel:n}variantHasKey(e,r){if(e){var n;if((n=e.details)!=null&&n.hasKey(r))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(c=>i.indexOf(c.groupId)>=0).some(c=>{var d;return(d=c.details)==null?void 0:d.hasKey(r)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,r){var n;if(r.fatal)return;const i=this.hls,a=r.context;switch(r.details){case Wt.FRAG_LOAD_ERROR:case Wt.FRAG_LOAD_TIMEOUT:case Wt.KEY_LOAD_ERROR:case Wt.KEY_LOAD_TIMEOUT:r.errorAction=this.getFragRetryOrSwitchAction(r);return;case Wt.FRAG_PARSING_ERROR:if((n=r.frag)!=null&&n.gap){r.errorAction=Ej();return}case Wt.FRAG_GAP:case Wt.FRAG_DECRYPT_ERROR:{r.errorAction=this.getFragRetryOrSwitchAction(r),r.errorAction.action=ju.SendAlternateToPenaltyBox;return}case Wt.PLAYLIST_UNCHANGED_ERROR:case Wt.LEVEL_EMPTY_ERROR:case Wt.LEVEL_PARSING_ERROR:{var c;const d=r.parent===On.MAIN?r.level:i.loadLevel;r.details===Wt.LEVEL_EMPTY_ERROR&&((c=r.context)!=null&&(c=c.levelDetails)!=null&&c.live)?r.errorAction=this.getPlaylistRetryOrSwitchAction(r,d):(r.levelRetry=!1,r.errorAction=this.getLevelSwitchAction(r,d))}return;case Wt.LEVEL_LOAD_ERROR:case Wt.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(r.errorAction=this.getPlaylistRetryOrSwitchAction(r,a.level));return;case Wt.AUDIO_TRACK_LOAD_ERROR:case Wt.AUDIO_TRACK_LOAD_TIMEOUT:case Wt.SUBTITLE_LOAD_ERROR:case Wt.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const d=i.loadLevelObj;if(d&&(a.type===ts.AUDIO_TRACK&&d.hasAudioGroup(a.groupId)||a.type===ts.SUBTITLE_TRACK&&d.hasSubtitleGroup(a.groupId))){r.errorAction=this.getPlaylistRetryOrSwitchAction(r,i.loadLevel),r.errorAction.action=ju.SendAlternateToPenaltyBox,r.errorAction.flags=Zc.MoveAllAlternatesMatchingHost;return}}return;case Wt.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:r.errorAction={action:ju.SendAlternateToPenaltyBox,flags:Zc.MoveAllAlternatesMatchingHDCP};return;case Wt.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Wt.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Wt.KEY_SYSTEM_NO_SESSION:r.errorAction={action:ju.SendAlternateToPenaltyBox,flags:Zc.MoveAllAlternatesMatchingKey};return;case Wt.BUFFER_ADD_CODEC_ERROR:case Wt.REMUX_ALLOC_ERROR:case Wt.BUFFER_APPEND_ERROR:r.errorAction||(r.errorAction=this.getLevelSwitchAction(r,r.level));return;case Wt.MEDIA_SOURCE_REQUIRES_RESET:r.errorAction||(r.errorAction=this.getLevelSwitchAction(r,r.level)),r.errorAction.flags|=Zc.ResetMediaSource|Zc.SwitchToSDR;return;case Wt.INTERNAL_EXCEPTION:case Wt.BUFFER_APPENDING_ERROR:case Wt.BUFFER_APPEND_NO_PROGRESS:case Wt.BUFFER_FULL_ERROR:case Wt.LEVEL_SWITCH_ERROR:case Wt.BUFFER_STALLED_ERROR:case Wt.BUFFER_SEEK_OVER_HOLE:case Wt.BUFFER_NUDGE_ON_STALL:r.errorAction=Ej();return}r.type===Kn.KEY_SYSTEM_ERROR&&(r.levelRetry=!1,r.errorAction=Ej())}getPlaylistRetryOrSwitchAction(e,r){const n=this.hls,i=Pme(n.config.playlistLoadPolicy,e),a=this.playlistError++;if(sP(i,a,q3(e),e.response))return{action:ju.RetryRequest,flags:Zc.None,retryConfig:i,retryCount:a};const d=this.getLevelSwitchAction(e,r);return i&&(d.retryConfig=i,d.retryCount=a),d}getFragRetryOrSwitchAction(e){const r=this.hls,n=this.getVariantLevelIndex(e.frag),i=r.levels[n],{fragLoadPolicy:a,keyLoadPolicy:c}=r.config,d=Pme(DCe(e)?c:a,e),p=r.levels.reduce((g,v)=>g+v.fragmentError,0);if(i&&(e.details!==Wt.FRAG_GAP&&i.fragmentError++,!MCe(e)&&sP(d,p,q3(e),e.response)))return{action:ju.RetryRequest,flags:Zc.None,retryConfig:d,retryCount:p};const l=this.getLevelSwitchAction(e,n);return d&&(l.retryConfig=d,l.retryCount=p),l}getLevelSwitchAction(e,r){const n=this.hls;r==null&&(r=n.loadLevel);const i=this.hls.levels[r];if(i){var a,c;const l=e.details;i.loadError++,i.loadErrorTime=self.performance.now(),l===Wt.BUFFER_APPEND_ERROR&&i.fragmentError++;let g=-1;const{levels:v,loadLevel:E,minAutoLevel:T,maxAutoLevel:j}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);const P=(a=e.frag)==null?void 0:a.type,L=(P===On.AUDIO&&l===Wt.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&Wme(e))&&v.some(({audioCodec:W})=>i.audioCodec!==W),F=e.sourceBufferName==="video"&&Wme(e)&&v.some(({codecSet:W,audioCodec:Z})=>i.codecSet!==W&&i.audioCodec===Z),{type:$,groupId:G}=(c=e.context)!=null?c:{};for(let W=v.length;W--;){const Z=(W+E)%v.length;if(Z!==E&&Z>=T&&Z<=j&&(v[Z].loadError===0||OCe(v[Z],n.config.errorPenaltyExpireMs))){var d,p;const Q=v[Z];if(l===Wt.FRAG_GAP&&P===On.MAIN&&e.frag){const ee=v[Z].details;if(ee){const ie=HT(e.frag,ee.fragments,e.frag.start);if(ie!=null&&ie.gap)continue}}else{if($===ts.AUDIO_TRACK&&Q.hasAudioGroup(G)||$===ts.SUBTITLE_TRACK&&Q.hasSubtitleGroup(G))continue;if(P===On.AUDIO&&(d=i.audioGroups)!=null&&d.some(ee=>Q.hasAudioGroup(ee))||P===On.SUBTITLE&&(p=i.subtitleGroups)!=null&&p.some(ee=>Q.hasSubtitleGroup(ee))||L&&i.audioCodec===Q.audioCodec||F&&i.codecSet===Q.codecSet||!L&&i.audioCodec!==Q.audioCodec)continue}g=Z;break}}if(g>-1&&n.loadLevel!==g)return e.levelRetry=!0,this.playlistError=0,{action:ju.SendAlternateToPenaltyBox,flags:Zc.None,nextAutoLevel:g}}return{action:ju.SendAlternateToPenaltyBox,flags:Zc.MoveAllAlternatesMatchingHost}}onErrorOut(e,r){var n,i;switch((n=r.errorAction)==null?void 0:n.action){case ju.DoNothing:break;case ju.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(r),!r.errorAction.resolved&&r.details!==Wt.FRAG_GAP&&r.details!==Wt.PLAYLIST_UNCHANGED_ERROR&&!mPe(r)&&(r.fatal=!0);break}if((((i=r.errorAction)==null?void 0:i.flags)||0)&Zc.ResetMediaSource&&this.hls.recoverMediaError(),r.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const r=this.hls,n=e.errorAction;if(!n)return;let i=n.nextAutoLevel;if(n.flags===Zc.None)this.switchLevel(e,i);else if(n.flags&Zc.SwitchToSDR){const d=this.hls.levels,p=d.length;for(let l=p;l--;)d[l].videoRange!=="SDR"?(d[l].fragmentError++,d[l].loadError++):i===void 0&&(i=l)}else if(n.flags&Zc.MoveAllAlternatesMatchingHDCP){const d=this.getVariantLevelIndex(e.frag),p=r.levels[d],l=p==null?void 0:p.attrs["HDCP-LEVEL"];n.hdcpLevel=l;const g=l==="NONE";l&&!g?(r.maxHdcpLevel=SH[SH.indexOf(l)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${r.maxHdcpLevel}" or lower`)):(g&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),n.flags|=Zc.MoveAllAlternatesMatchingKey)}if(n.flags&Zc.MoveAllAlternatesMatchingKey){const d=e.decryptdata;if(d){const p=this.hls.levels,l=p.length;for(let v=l;v--;)if(this.variantHasKey(p[v],d)){var a,c;this.log(`Banned key found in level ${v} (${p[v].bitrate}bps) or audio group "${(a=p[v].audioGroups)==null?void 0:a.join(",")}" (${(c=e.frag)==null?void 0:c.type} fragment) ${lc(d.keyId||[])}`),p[v].fragmentError++,p[v].loadError++,this.log(`Removing level ${v} with key error (${e.error})`),this.hls.removeLevel(v)}const g=e.frag;if(this.hls.levels.lengthe.endSN||r>0||r===0&&n>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(r=>{let n=r.decryptdata;return n||(r.setKeyFormat(e.keyFormat),n=r.decryptdata),!!n&&e.matches(n)})}get hasProgramDateTime(){return this.fragments.length?yn(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||pPe}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const r=this.lastPartIndex;if(r!==-1){for(let n=e.length;n--;)if(e[n].index>r)return e[n].index;return r}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.advancedDateTime!==void 0&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}get partsExpired(){return this.live&&this.partTarget&&this.advancedDateTime!==void 0&&this.misses<3?this.age>(this.partHoldBack||this.partTarget*3)*1.5:!1}}const Kme={length:0,start:()=>0,end:()=>0};class xi{static isBuffered(e,r){if(e){const n=xi.getBuffered(e);for(let i=n.length;i--;)if(r>=n.start(i)&&r<=n.end(i))return!0}return!1}static bufferedRanges(e){if(e){const r=xi.getBuffered(e);return xi.timeRangesToArray(r)}return[]}static timeRangesToArray(e){const r=[];for(let n=0;n1&&e.sort((g,v)=>g.start-v.start||v.end-g.end);let i=-1,a=[];if(n)for(let g=0;g=e[g].start&&r<=e[g].end&&(i=g);const v=a.length;if(v){const E=a[v-1].end;e[g].start-EE&&(a[v-1].end=e[g].end):a.push(e[g])}else a.push(e[g])}else a=e;let c=0,d,p=r,l=r;for(let g=0;g=v&&r<=E&&(i=g),r+n>=v&&r{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=n=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=n=>{const{media:i,mediaSource:a}=this;n&&this.log("Media source opened"),!(!i||!a)&&(da(a,"sourceopen",this._onMediaSourceOpen),da(i,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Ee.MEDIA_ATTACHED,{media:i,mediaSource:a}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){if(this.isMediaSourceReplaced()){const{currentSrc:p}=this.media,l=p&&p!==this._objectUrl?p:this.mediaSrc;this.warn(`MediaSource closed after media element switched to another source (${this._objectUrl} > ${l}) - detaching media`),this.hls.detachMedia();return}const n=this.media.error,{appendError:i,appendErrors:a}=this;let c=!1;!i&&n&&(c=Math.max(++a.audio,++a.video,++a.audiovideo)>=this.hls.config.appendErrorMaxRetry);const d=new Error(`MediaSource closed while media attached${Xme(c,n)}`);this.warn(d),this.hls.trigger(Ee.ERROR,La({fatal:c},i,{type:Kn.MEDIA_ERROR,details:Wt.MEDIA_SOURCE_REQUIRES_RESET,error:d}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:n,_objectUrl:i}=this;n!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${n})`)},this._onMediaError=()=>{const{media:n}=this;if(n){var i,a;this.log(`Media error (code: ${(i=n.error)==null?void 0:i.code}): ${(a=n.error)==null?void 0:a.message}`)}},this.hls=e,this.fragmentTracker=r,this.appendSource=x5t(Rv(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){const{hls:e}=this;e.on(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Ee.BUFFER_RESET,this.onBufferReset,this),e.on(Ee.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Ee.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Ee.BUFFER_EOS,this.onBufferEos,this),e.on(Ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Ee.FRAG_PARSED,this.onFragParsed,this),e.on(Ee.FRAG_CHANGED,this.onFragChanged,this),e.on(Ee.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Ee.BUFFER_RESET,this.onBufferReset,this),e.off(Ee.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Ee.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Ee.BUFFER_EOS,this.onBufferEos,this),e.off(Ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Ee.FRAG_PARSED,this.onFragParsed,this),e.off(Ee.FRAG_CHANGED,this.onFragChanged,this),e.off(Ee.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:r}=this;if(!e)return null;const n={};if(this.operationQueue){const a=this.isUpdating();a||this.operationQueue.removeBlockers();const c=this.isQueued();(a||c)&&this.warn(`Transfering MediaSource with${c?" operations in queue":""}${a?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return i&&!this.sourceBufferCount&&i.mediaSource===r?La(n,i.tracks):this.sourceBuffers.forEach(a=>{const[c]=a;c&&(n[c]=La({},this.tracks[c]),this.removeBuffer(c)),a[0]=a[1]=null}),{media:e,mediaSource:r,tracks:n}}initTracks(){const e={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,r){var n;let i=2;(r.audio&&!r.video||!r.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(n=this.transferData)!=null&&n.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,r){const n=this.media=r.media;this.transferData=this.overrides=void 0;const i=Rv(this.appendSource);if(i){const c=!!r.mediaSource;(c||r.overrides)&&(this.transferData=r,this.overrides=r.overrides);const d=this.mediaSource=r.mediaSource||new i;if(this.assignMediaSource(d),c)this._objectUrl=n.src,this.attachTransferred();else{var a;const p=this._objectUrl=self.URL.createObjectURL(d),l=this.hls.config,g=l.emeEnabled&&n.mediaKeys?(a=l.emeController)==null?void 0:a.CDMCleanupPromise:null;g?g.then(()=>{this.hls&&this.setSource(n,d,p)}).catch(()=>{}):this.setSource(n,d,p)}_a(n,"emptied",this._onMediaEmptied),_a(n,"error",this._onMediaError),this.appendSource&&_a(n,"seeking",this._onStartStreaming)}}setSource(e,r,n){if(this.appendSource)try{e.removeAttribute("src");const i=self.ManagedMediaSource;e.disableRemotePlayback=e.disableRemotePlayback||i&&r instanceof i,Zme(e),BBt(e,n),e.load()}catch{e.src=n}else e.src=n}assignMediaSource(e){var r,n;this.log(`${((r=this.transferData)==null?void 0:r.mediaSource)===e?"transferred":"created"} media source: ${(n=e.constructor)==null?void 0:n.name}`),_a(e,"sourceopen",this._onMediaSourceOpen),_a(e,"sourceended",this._onMediaSourceEnded),_a(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(_a(e,"startstreaming",this._onStartStreaming),_a(e,"endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,r=this.transferData;if(!r||!e)return;const n=this.tracks,i=r.tracks,a=i?Object.keys(i):null,c=a?a.length:0,d=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&a&&c){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${fo(n,(p,l)=>p==="initSegment"?void 0:l)}; transfer tracks: ${fo(i,(p,l)=>p==="initSegment"?void 0:l)}}`),!FCe(i,n)){r.mediaSource=null,r.tracks=void 0;const p=e.currentTime,l=this.details,g=Math.max(p,(l==null?void 0:l.fragments[0].start)||0);if(g-p>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${p} -> ${g}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(n)}") start time: ${g} currentTime: ${p}`),this.onMediaDetaching(Ee.MEDIA_DETACHING,{}),this.onMediaAttaching(Ee.MEDIA_ATTACHING,r),e.currentTime=g;return}this.transferData=void 0,a.forEach(p=>{const l=p,g=i[l];if(g){const v=g.buffer;if(v){const E=this.fragmentTracker,T=g.id;if(E.hasFragments(T)||E.hasParts(T)){const C=xi.getBuffered(v);E.detectEvictedFragments(l,C,T,null,null,!0)}const j=r8(l),P=[l,v];this.sourceBuffers[j]=P,v.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,g)}}}),d(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),d()}get mediaSourceOpenOrEnded(){var e;const r=(e=this.mediaSource)==null?void 0:e.readyState;return r==="open"||r==="ended"}onMediaDetaching(e,r){const n=!!r.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:a,_objectUrl:c}=this;if(a){if(this.log(`media source ${n?"transferring":"detaching"}`),n)this.sourceBuffers.forEach(([d])=>{d&&this.removeBuffer(d)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const d=a.readyState==="open";try{const p=a.sourceBuffers;for(let l=p.length;l--;)d&&p[l].abort(),a.removeSourceBuffer(p[l]);d&&a.endOfStream()}catch(p){this.warn(`onMediaDetaching: ${p.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}da(a,"sourceopen",this._onMediaSourceOpen),da(a,"sourceended",this._onMediaSourceEnded),da(a,"sourceclose",this._onMediaSourceClose),this.appendSource&&(da(a,"startstreaming",this._onStartStreaming),da(a,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(da(i,"emptied",this._onMediaEmptied),da(i,"error",this._onMediaError),da(i,"seeking",this._onStartStreaming),n||(c&&self.URL.revokeObjectURL(c),this.mediaSrc===c&&!this.isMediaSourceReplaced(c)?(i.removeAttribute("src"),this.appendSource&&Zme(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var r;const n=(r=this.tracks[e])==null?void 0:r.buffer;if(this.removeBuffer(e),n)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(n)}catch(a){this.warn(`onBufferReset ${e}`,a)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[r8(e)]=[null,null];const r=this.tracks[e];r&&(this.clearBufferAppendTimeoutId(r),r.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new jBt(this.tracks)}onBufferCodecs(e,r){var n;const i=this.tracks,a=Object.keys(r);this.log(`BUFFER_CODECS: "${a}" (current SB count ${this.sourceBufferCount})`);const c="audiovideo"in r&&(i.audio||i.video)||i.audiovideo&&("audio"in r||"video"in r),d=!c&&this.sourceBufferCount&&this.media&&a.some(p=>!i[p]);if(c||d){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${a}" SourceBuffers`);return}a.forEach(p=>{var l,g;const v=r[p],{id:E,codec:T,levelCodec:j,container:P,metadata:C,supplemental:L}=v;let O=i[p];const F=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[p],$=F!=null&&F.buffer?F:O,G=($==null?void 0:$.pendingCodec)||($==null?void 0:$.codec),W=$==null?void 0:$.levelCodec;O||(O=i[p]={buffer:void 0,listeners:[],codec:T,supplemental:L,container:P,levelCodec:j,metadata:C,id:E});const Z=SO(G,W),Q=Z==null?void 0:Z.replace(Yme,"$1");let ee=SO(T,j);const ie=(g=ee)==null?void 0:g.replace(Yme,"$1");ee&&Z&&Q!==ie&&(p.slice(0,5)==="audio"&&(ee=H3(ee,this.appendSource)),this.log(`switching codec ${G} to ${ee}`),ee!==(O.pendingCodec||O.codec)&&(O.pendingCodec=ee),O.container=P,this.appendChangeType(p,P,ee))}),(this.tracksReady||this.sourceBufferCount)&&(r.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!r.video&&((n=r.audio)==null?void 0:n.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,r)=>{const n=this.tracks[r];return e[r]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},e},{})}appendChangeType(e,r,n){const i=`${r};codecs=${n}`,a={label:`change-type=${i}`,execute:()=>{const c=this.tracks[e];if(c){const d=c.buffer;d!=null&&d.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),d.changeType(i),c.codec=n,c.container=r)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:c=>{this.warn(`Failed to change ${e} SourceBuffer type`,c)}};this.append(a,e,this.isPending(this.tracks[e]))}blockAudio(e){var r;const n=e.start,i=n+e.duration*.05;if(((r=this.fragmentTracker.getAppendedFrag(n,On.MAIN))==null?void 0:r.gap)===!0)return;const c={label:"block-audio",execute:()=>{var d,p;(this.lastVideoAppendEnd>i||xi.isBuffered((d=this.tracks.video)==null?void 0:d.buffer,i)||((p=this.fragmentTracker.getAppendedFrag(i,On.MAIN))==null?void 0:p.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:d=>{this.warn("Error executing block-audio operation",d)}};this.append(c,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,r){const{tracks:n}=this,{data:i,type:a,parent:c,frag:d,part:p,chunkMeta:l,offset:g}=r,v=l.buffering[a],E=Ko(d)&&!p&&!d.gap&&!l.partial&&!l.iframe;let T=null,j=!1;const{sn:P,cc:C}=d,L=self.performance.now();v.start=L;const O=d.stats.buffering,F=p?p.stats.buffering:null;O.start===0&&(O.start=L),(F==null?void 0:F.start)===0&&(F.start=L);const $=n.audio;let G=!1;a==="audio"&&($==null?void 0:$.container)==="audio/mpeg"&&(G=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const W=n.video,Z=W==null?void 0:W.buffer;if(Z&&P!=="initSegment"&&g!==void 0){const ie=$==null?void 0:$.buffer,oe=p||d;if(a==="audio"&&c!=="main"&&!(W.ending||W.ended)&&ie&&xi.getBuffered(ie).length){const Le=oe.start+oe.duration*.05,be=xi.getBuffered(Z),Re=this.currentOp("video");!be.length&&!Re?this.blockAudio(oe):!xi.isBuffered(Z,Le)&&this.lastVideoAppendEndoe.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const Q=(p||d).start,ee={label:`append-${a}`,execute:()=>{var ie;v.executeStart=self.performance.now();const oe=(ie=this.tracks[a])==null?void 0:ie.buffer;oe&&(E&&(T=xi.timeRangesToArray(xi.getBuffered(oe)),j=Jme(n8(T,d),d)),G?this.updateTimestampOffset(oe,Q,.1,a,P,C):g!==void 0&&yn(g)&&this.updateTimestampOffset(oe,g,1e-6,a,P,C)),this.appendExecutor(i,a)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[a]);const ie=self.performance.now();v.executeEnd=v.end=ie,O.first===0&&(O.first=ie),(F==null?void 0:F.first)===0&&(F.first=ie);const oe={};if(this.sourceBuffers.forEach(([pe,Le])=>{pe&&(oe[pe]=xi.getBuffered(Le))}),E){const pe=this.getFragmentAppendProgress(d),Le=oe[a];if(Le&&T){const be=xi.timeRangesToArray(Le),Re=n8(be,d);pe.progressed||(pe.progressed=Re-n8(T,d)>MBt);const Ie=j&&Jme(Re,d);pe.fullyBuffered[a]=(pe.fullyBuffered[a]===void 0||pe.fullyBuffered[a])&&Ie}}this.hls.trigger(Ee.BUFFER_APPENDED,{type:a,frag:d,part:p,chunkMeta:l,parent:c,timeRanges:oe})},onError:ie=>{var oe;this.clearBufferAppendTimeoutId(this.tracks[a]);const pe=ie.code===DOMException.QUOTA_EXCEEDED_ERR||ie.name=="QuotaExceededError"||"quota"in ie;if(pe&&!this._quotaEvictionPending[a]){const Ie=this.getBackBufferEvictionTarget(a,i.byteLength,d.type);if(Ie>0){this._quotaEvictionPending[a]=!0,this.log(`QuotaExceededError on "${a}" append sn: ${P} - evicting back buffer to ${Ie.toFixed(3)}s and retrying`);const Te=this.getFlushOp(a,0,Ie),ge=this.getClearEvictionPendingOp(a);this.insertNext([Te,ee,ge],a);return}this.warn(`QuotaExceededError on "${a}" sn: ${P} - no back buffer available to evict`)}E&&(this.getFragmentAppendProgress(d).errored=!0);const Le={type:Kn.MEDIA_ERROR,parent:c,details:Wt.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:d,part:p,chunkMeta:l,error:ie,err:ie,fatal:!1},be=(oe=this.media)==null?void 0:oe.error;if(ie.name===gPe&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))Le.errorAction=Ej(!0);else{var Re;pe&&(Le.details=Wt.BUFFER_FULL_ERROR);const Ie=++this.appendErrors[a],Te=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${Ie}/${Te+1} times to append segment in "${a}" sourceBuffer with error: ${ie.message}`),Ie>=Te&&(Le.fatal=!pe);const ge=(Re=this.mediaSource)==null?void 0:Re.readyState;(ge==="ended"||ge==="closed"||be)&&!this.isMediaSourceReplaced()&&(this.warn(`MediaSource readyState "${ge}" during SourceBuffer${Xme(Le.fatal,be)}`),Le.details=Wt.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=Le,this.hls.trigger(Ee.ERROR,Le),pe&&this.hls&&this.trimBuffers(d.start,1)}};this.log(`queuing "${a}" append sn: ${P}${p?" p: "+p.index:""} of ${c} playlist ${d.level} cc: ${C} offset: ${g} bytes: ${i.byteLength}`),this.append(ee,a,this.isPending(this.tracks[a]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,r,n){return this.log(`queuing "${e}" remove ${r}-${n}`),{label:"remove",execute:()=>{this.removeExecutor(e,r,n)},onStart:()=>{},onComplete:()=>{var i;const a=(i=this.tracks[e])==null?void 0:i.buffer;this.log(`Remove request ${r}-${n} from ${e} Source Buffer complete > buffer: ${a?Y3(xi.getBuffered(a)):"(detached)"}`),this.hls.trigger(Ee.BUFFER_FLUSHED,{type:e,start:r,end:n})},onError:i=>{this.warn(`Failed to remove ${r}-${n} from "${e}" SourceBuffer`,i),this.hls.trigger(Ee.BUFFER_FLUSHED,{type:e,start:0,end:0,error:i})}}}onBufferFlushing(e,r){const{type:n,startOffset:i,endOffset:a}=r;(!n||n==="audio")&&this.unblockAudio(),n?this.append(this.getFlushOp(n,i,a),n):this.sourceBuffers.forEach(([c])=>{c&&this.append(this.getFlushOp(c,i,a),c)})}onFragParsed(e,r){const{frag:n,part:i,chunkMeta:a}=r,c=[],d=i?i.elementaryStreams:n.elementaryStreams;d[ro.AUDIOVIDEO]?c.push("audiovideo"):(d[ro.AUDIO]&&c.push("audio"),d[ro.VIDEO]&&c.push("video"));const p=()=>{const l=self.performance.now();n.stats.buffering.end=l,i&&(i.stats.buffering.end=l);const g=i?i.stats:n.stats;this.checkAppendProgress(n,i,a,c),this.hls&&(this.hls.trigger(Ee.FRAG_BUFFERED,{frag:n,part:i,stats:g,id:n.type,chunkMeta:a}),!i&&n.gap&&g.retry&&this.log(`Nothing buffered for ${n.type} level: ${n.level} sn: ${n.sn} retries ${g.retry}`))};c.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${n.type} ${n.level} ${i?`part: ${i.index} of `:""}sn: ${n.sn}`),this.blockBuffers(p,c).catch(l=>{this.warn(`Fragment buffered callback ${l.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,r){var n,i;const a=(n=this.hls)==null?void 0:n.config;if(!a)return;const{backBufferLength:c,frontBufferFlushThreshold:d}=a;this.trimBuffers(d,c,r.frag,r.previousFrag);const p=r.frag.elementaryStreams,{appendErrors:l}=this,g=(i=this.appendError)==null?void 0:i.sourceBufferName;Object.keys(p).forEach(v=>{p[v]&&(l[v]=0,v===g&&(this.appendError=void 0),v==="audio"||v==="video"?(l.audiovideo=0,g==="audiovideo"&&(this.appendError=void 0)):(l.audio=0,l.video=0,g!=="audiovideo"&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const r=this.tracks[e];if(r)return!r.ended||r.ending}return!1})}onBufferEos(e,r){var n;this.sourceBuffers.forEach(([a])=>{if(a){const c=this.tracks[a];(!r.type||r.type===a)&&(c.ending=!0,c.ended||(c.ended=!0,this.log(`${a} buffer reached EOS`)))}});const i=((n=this.overrides)==null?void 0:n.endOfStream)!==!1;this.allTracksEnding?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{if(this.tracksEnded(),!this.allTracksEnding){this.log("EOS cancelled");return}const{mediaSource:a}=this;if((a==null?void 0:a.readyState)!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(Ee.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(Ee.BUFFERED_TO_END,void 0))):r.type==="video"&&this.unblockAudio()}get allTracksEnding(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var r;return e&&!((r=this.tracks[e])!=null&&r.ended)})}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const r=this.tracks[e];r&&(r.ending=!1)}})}onLevelUpdated(e,{details:r}){r.fragments.length&&(this.details=r,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,r){if(r.details===Wt.BUFFER_APPEND_ERROR&&r.frag){var n;const i=(n=r.errorAction)==null?void 0:n.nextAutoLevel;yn(i)&&i!==r.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,r,n){const{media:i}=this;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,n,r):0}getFragmentAppendProgress(e){var r;const n=Qme(e);let i=this.fragmentAppendProgress[n];return((r=i)==null?void 0:r.stats)!==e.stats&&(i={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[n]=i),i}checkAppendProgress(e,r,n,i){if(r||!Ko(e)||e.gap||n.iframe||n.partial)return;const a=Qme(e),c=this.fragmentAppendProgress[a];delete this.fragmentAppendProgress[a];const d=e.stats.buffering;if(d.start&&!d.first)return;const p=(c==null?void 0:c.stats)===e.stats?c:void 0;if(p!=null&&p.errored)return;const l=i.length>0&&i.every(T=>(p==null?void 0:p.fullyBuffered[T])===!0);if(p!=null&&p.progressed||l){delete this.appendsWithoutProgress[a];return}if(!p&&i.length===0)return;const g=(this.appendsWithoutProgress[a]||0)+1,v=this.hls;g>=v.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[a]:this.appendsWithoutProgress[a]=g,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${g} time${g>1?"s":""} without buffered range growth`),v.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:n,parent:e.type,appendsWithoutProgress:g,error:new Error(`Fragment append did not increase buffered coverage (${g})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(e,r,n,i){const{hls:a,details:c,media:d}=this;if(!d||c===null||!this.sourceBufferCount)return;const p=a.config,l=d.currentTime,g=c.levelTargetDuration;r=c.live&&p.liveBackBufferLength!==null?p.liveBackBufferLength:r;let v=-1/0;if(yn(r)&&r>=0){const E=Math.max(r,g);v=Math.floor(l/g)*g-E}if(n){const E=this.getLoopBackBufferFlushEnd(n,i??null);E>0&&(v=Math.max(v,E))}if(v>0&&this.flushBackBuffer(l,g,v),yn(e)&&e>0){const E=Math.max(p.maxBufferLength,e),T=Math.max(E,g),j=Math.floor(l/g)*g+T;this.flushFrontBuffer(l,g,j)}}getLoopBackBufferFlushEnd(e,r){var n;const{media:i}=this;if(((n=this.hls)==null?void 0:n.config.loopBackBufferFlush)===!1||!(i!=null&&i.loop)||!r||e.level<=r.level)return 0;const{video:a,audiovideo:c}=e.elementaryStreams;if(a!=null&&a.partial||c!=null&&c.partial)return 0;const d=this.getEarliestElementaryStreamStart(e)-DBt;return d<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${d.toFixed(3)}]`),d)}getEarliestElementaryStreamStart(e){const{audio:r,video:n,audiovideo:i}=e.elementaryStreams;let a=e.start;return i?a=Math.min(a,i.startDTS):(r&&(a=Math.min(a,r.startDTS)),n&&(a=Math.min(a,n.startDTS))),a}flushBackBuffer(e,r,n){this.sourceBuffers.forEach(([i,a])=>{if(a){const l=xi.getBuffered(a);if(l.length>0&&n>l.start(0)){var c,d,p;this.hls.trigger(Ee.BACK_BUFFER_REACHED,{bufferEnd:n});const g=this.tracks[i];if((c=this.details)!=null&&c.live)this.hls.trigger(Ee.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(g!=null&&g.ended&&!((d=this.media)!=null&&d.loop&&((p=this.hls)==null?void 0:p.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(Ee.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:i})}}})}flushFrontBuffer(e,r,n){this.sourceBuffers.forEach(([i,a])=>{if(a){const c=xi.getBuffered(a),d=c.length;if(d<2)return;const p=c.start(d-1),l=c.end(d-1);if(n>p||e>=p&&e<=l)return;this.hls.trigger(Ee.BUFFER_FLUSHING,{startOffset:p,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:r,mediaSource:n}=this;if(!r||!this.media||(n==null?void 0:n.readyState)!=="open")return null;const i=r.edge;if(r.live&&this.hls.config.liveDurationInfinity){if(r.fragments.length&&n.setLiveSeekableRange){const l=Math.max(0,r.fragmentStart),g=Math.max(l,i);return{duration:1/0,start:l,end:g}}return{duration:1/0}}const a=(e=this.overrides)==null?void 0:e.duration;if(a)return yn(a)?{duration:a}:null;const c=this.media.duration,d=yn(n.duration)?n.duration:0;return i>d&&i>c||!yn(c)?{duration:i}:null}updateMediaSource({duration:e,start:r,end:n}){const i=this.mediaSource;!i||!this.media||i.readyState!=="open"||(i.duration!==e&&(yn(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),r!==void 0&&n!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${r}-${n}.`),i.setLiveSeekableRange(r,n)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:r,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${r} codec events expected: ${e}) ${fo(n)}`),this.tracksReady){var i;const a=(i=this.transferData)==null?void 0:i.tracks;a&&Object.keys(a).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([r,n])=>{if(r){const i=this.tracks[r];e[r]={buffer:n,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(Ee.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([r])=>{this.executeNext(r)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:r,mediaSource:n}=this;if(!n)throw new Error("createSourceBuffers called when mediaSource was null");for(const a in e){const c=a,d=e[c];if(this.isPending(d)){const p=this.getTrackCodec(d,c),l=`${d.container};codecs=${p}`;d.codec=p,this.log(`creating sourceBuffer(${l})${this.currentOp(c)?" Queued":""} ${fo(d)}`);try{const g=n.addSourceBuffer(l),v=r8(c),E=[c,g];r[v]=E,d.buffer=g}catch(g){var i;this.error(`error while trying to add sourceBuffer: ${g.message}`),this.shiftAndExecuteNext(c),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[c],this.hls.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:g,sourceBufferName:c,mimeType:l,parent:d.id});return}this.trackSourceBuffer(c,d)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,r){const n=e.supplemental;let i=e.codec;n&&(r==="video"||r==="audiovideo")&&cP(n,"video")&&(i=cBt(i,n));const a=SO(i,e.levelCodec);return a?r.slice(0,5)==="audio"?H3(a,this.appendSource):a:""}trackSourceBuffer(e,r){const n=r.buffer;if(!n)return;const i=this.getTrackCodec(r,e);this.tracks[e]={buffer:n,codec:i,container:r.container,levelCodec:r.levelCodec,supplemental:r.supplemental,metadata:r.metadata,id:r.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(a,c)=>{const d=c.removedRanges;d!=null&&d.length&&(this.log(`${a} buffer removed ${Y3(d)}`),this.hls.trigger(Ee.BUFFER_FLUSHED,{type:a,start:d.start(0),end:d.end(d.length-1)}))})}get mediaSrc(){var e;const r=this.media;return r?(r.src?r:((e=r.querySelector)==null?void 0:e.call(r,"source"))||r).src:void 0}isMediaSourceReplaced(e=this._objectUrl){var r;if(!e)return!1;const n=(r=this.media)==null?void 0:r.currentSrc,i=this.mediaSrc;return!!n&&n!==e||!!i&&i!==e}onSBUpdateStart(e){const r=this.currentOp(e);r&&r.onStart()}onSBUpdateEnd(e){var r,n;if(((r=this.mediaSource)==null?void 0:r.readyState)==="closed"){this.resetBuffer(e);return}const i=this.currentOp(e);if(!i)return;if(i.onComplete(),(n=this.tracks[e])==null||(n=n.buffer)==null?void 0:n.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,r){var n;const i=(n=this.mediaSource)==null?void 0:n.readyState,a=new Error(`${e} SourceBuffer error. MediaSource readyState: ${i}`);a.name=yPe,this.error(`${a.message}`,r),this.hls.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:a,fatal:!1});const c=this.currentOp(e);c&&c.onError(a)}updateTimestampOffset(e,r,n,i,a,c){const d=r-e.timestampOffset;Math.abs(d)>=n&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${r} (sn: ${a} cc: ${c})`),e.timestampOffset=r)}removeExecutor(e,r,n){const{media:i,mediaSource:a}=this,c=this.tracks[e],d=c==null?void 0:c.buffer;if(!i||!a||!d)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);const p=yn(i.duration)?i.duration:1/0,l=yn(a.duration)?a.duration:1/0,g=Math.max(0,r);if(g>=l){var v;(v=this.currentOp(e))==null||v.onComplete(),this.shiftAndExecuteNext(e);return}const E=Math.min(n,p,l);if(E>g&&(!c.ending||c.ended))c.ended=!1,this.log(`Removing [${g},${E}] from the ${e} SourceBuffer`),d.remove(g,E);else throw new Error(`Cannot remove ${E<=g?`invalid range (${g} >= ${E}) `:""}from the ${e} SourceBuffer${c.ending?" while track ending":""}`)}appendExecutor(e,r){const n=this.tracks[r],i=n==null?void 0:n.buffer;if(!i)throw new OBt(`Attempting to append to the ${r} SourceBuffer, but it does not exist`);if(n.ending=!1,n.ended=!1,this.hls.config.appendTimeout!==1/0){const a=this.calculateAppendTimeoutTime(i);n.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(r,i,a),a)}i.appendBuffer(e)}appendTimeoutHandler(e,r,n){this.log(`Received timeout after ${n}ms for append on ${e} source buffer. Aborting and triggering error.`);try{r.abort()}catch{this.log(`Failed to abort append on ${e} source buffer after timeout.`)}const i=this.currentOp(e);i&&i.onError(new Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let r=pPe;this.details&&(r=this.details.levelTargetDuration);let n=2*r*1e3;if(this.media===null)return n;const i=xi.bufferInfo(e,this.media.currentTime,0);return i.len?(n=Math.max(i.len*1e3,n),Math.max(this.hls.config.appendTimeout,n)):n}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(r=>{this.warn(`SourceBuffer blocked callback ${r}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(r){this.warn(`Callback run without blocking ${this.operationQueue} ${r}`)}}isUpdating(){return this.sourceBuffers.some(([e,r])=>e&&r.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return((e=this.currentOp("audio"))==null?void 0:e.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}blockBuffers(e,r=this.sourceBufferTypes){if(!r.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:n}=this,a=r.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:r.map(c=>this.appendBlocker(c));return Promise.all(a).then(c=>{n===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(r=>{var n;const i=(n=this.tracks[r])==null?void 0:n.buffer;!i||i.updating||r==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(r)})}append(e,r,n){this.operationQueue&&this.operationQueue.append(e,r,n)}insertNext(e,r){this.operationQueue&&this.operationQueue.insertNext(e,r)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,r)=>e+(this.isPending(this.tracks[r])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[r])=>e+(r?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,r,n){const i=this.tracks[e];if(!i)return;const a=i.buffer;if(!a)return;const c=n.bind(this,e);i.listeners.push({event:r,listener:c}),_a(a,r,c)}removeBufferListeners(e){const r=this.tracks[e];if(!r)return;const n=r.buffer;n&&(r.listeners.forEach(i=>{da(n,i.event,i.listener)}),r.listeners.length=0)}}function Zme(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(r=>{t.removeChild(r)})}function BBt(t,e){const r=self.document.createElement("source");r.type="video/mp4",r.src=e,t.appendChild(r)}function r8(t){return t==="audio"?1:0}function Xme(t,e){return`${t?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function Qme(t){return`${t.type}_${t.sn}_${t.level}`}function n8(t,e){const{start:r,end:n}=e;let i=0;for(let a=0;a=n)break;const d=Math.max(r,c.start),p=Math.min(n,c.end);p>d&&(i+=p-d)}return i}function Jme(t,e){return e.duration-t<=.05}var wo={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class zBt{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Ee.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Ee.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,r){const n=this.activePartLists[r];if(n)for(let i=n.length;i--;){const a=n[i];if(!a)break;if(a.start<=e&&e<=a.end&&a.loaded)return a}return this.getBufferedFrag(e,r)}getBufferedFrag(e,r){return this.getFragAtPos(e,r,!0)}getFragAtPos(e,r,n){const{fragments:i}=this,a=Object.keys(i);for(let c=a.length;c--;){const d=i[a[c]];if((d==null?void 0:d.body.type)===r&&(!n||d.buffered)){const p=d.body;if(p.start<=e&&e<=p.end)return p}}return null}detectEvictedFragments(e,r,n,i,a,c){this.timeRanges&&(this.timeRanges[e]=r);const d=(a==null?void 0:a.fragment.sn)||-1;Object.keys(this.fragments).forEach(p=>{const l=this.fragments[p];if(!l||!this.hls)return;const g=l.body;if(d>=g.sn)return;if(!l.buffered&&(!l.loaded||c)){g.type===n&&this.removeFragment(g);return}const v=l.range[e];if(v){if(v.time.length===0){this.removeFragment(g);return}if(v.time.some(E=>{const T=!this.isTimeBuffered(E.startPTS,E.endPTS,r);return T&&this.removeFragment(g),T}),i&&i!==g&&Sj()){const E=i.endPTS,T=g.startPTS;if(E&&T&&l.range.video){const j=T-E;j<0&&j>-.1&&(this.removeFragment(g),this.hls.trigger(Ee.BUFFER_FLUSHING,{startOffset:E+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){const r=this.timeRanges,{frag:n,part:i,id:a}=e;if(!r||!Ko(n))return;const c=DS(n),d=this.fragments[c];if(!d||d.buffered&&n.gap)return;const p=!n.relurl;Object.keys(r).forEach(g=>{const v=n.elementaryStreams[g];if(!v)return;const E=r[g],T=p||v.partial===!0;d.range[g]=this.getBufferedTimes(n,i,T,E),this.detectEvictedFragments(g,E,a,n,i)}),d.loaded=null;const l=Object.keys(d.range);if(l.length){if(this.bufferedEnd(d,n),hM(d)||this.removeParts(n.sn-1,n.type),!i){const g=Math.min(.004,n.duration);l.some(v=>{var E;const T=(E=d.range[v])==null?void 0:E.time,j=T.length===0||T.length===1&&T[0].endPTS-T[0].startPTSi.fragment.sn>=e))}fragBuffered(e,r){const n=DS(e);let i=this.fragments[n];return!i&&r&&(i=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e)),i}getBufferedTimes(e,r,n,i){const a={time:[],partial:n},c=e.start,d=e.end,p=e.minEndPTS||d,l=e.maxStartPTS||c;for(let g=0;g=v&&p<=E){a.time.push({startPTS:Math.max(c,i.start(g)),endPTS:Math.min(d,i.end(g))});break}else if(cv){const T=Math.max(c,i.start(g)),j=Math.min(d,i.end(g));j>T&&(a.partial=!0,a.time.push({startPTS:T,endPTS:j}))}else if(d<=v)break}return a}getPartialFragment(e){let r=null,n,i,a,c=0;const{bufferPadding:d,fragments:p}=this;return Object.keys(p).forEach(l=>{const g=p[l];g&&hM(g)&&(i=g.body.start-d,a=g.body.end+d,e>=i&&e<=a&&(n=Math.min(e-i,a-e),c<=n&&(r=g.body,c=n)))}),r}isEndListAppended(e){const r=this.endListFragments[e];return r!==void 0&&(r.buffered||hM(r))}getState(e){const r=DS(e),n=this.fragments[r];return n?n.buffered?hM(n)?wo.PARTIAL:wo.OK:wo.APPENDING:wo.NOT_LOADED}isTimeBuffered(e,r,n){let i,a;for(let c=0;c=i&&r<=a)return!0;if(r<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,r){if(!Ko(r.frag)||r.frag.bitrateTest)return;const n=r.frag,i=r.part?null:r,a=DS(n);this.fragments[a]={body:n,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,r){const{frag:n,part:i,timeRanges:a}=r;if(!Ko(n))return;const c=n.type;if(i){let d=this.activePartLists[c];d||(this.activePartLists[c]=d=[]),d.push(i)}this.timeRanges=a}onFragBuffered(e,r){this.detectPartialFragments(r)}hasFragment(e){const r=DS(e);return!!this.fragments[r]}hasFragments(e){const{fragments:r}=this,n=Object.keys(r);if(!e)return n.length>0;for(let i=n.length;i--;){const a=r[n[i]];if((a==null?void 0:a.body.type)===e)return!0}return!1}hasParts(e){var r;return!!((r=this.activePartLists[e])!=null&&r.length)}getBackBufferEvictionEnd(e,r,n){const{fragments:i}=this;let a=0,c=0;const d=Object.keys(i);for(let p=0;p=n))return c}return c>0?c:0}removeFragmentsInRange(e,r,n,i,a){i&&!this.hasGaps||Object.keys(this.fragments).forEach(c=>{const d=this.fragments[c];if(!d)return;const p=d.body;p.type!==n||i&&!p.gap||p.starte&&(d.buffered||a)&&this.removeFragment(p)})}removeFragment(e){const r=DS(e);e.clearElementaryStreamInfo();const n=this.activePartLists[e.type];if(n){const i=e.sn;this.activePartLists[e.type]=epe(n,a=>a.fragment.sn!==i)}delete this.fragments[r],e.endList&&delete this.endListFragments[e.type]}gapFragments(){return this.hasGaps?Object.keys(this.fragments).map(e=>{var r;return(r=this.fragments[e])==null?void 0:r.body}).filter(e=>!!(e!=null&&e.gap)):[]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const r=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;r&&r.forEach(n=>n.clearElementaryStreamInfo())}}function hM(t){var e,r,n,i;return t.buffered&&!!(t.body.gap||(e=t.range.video)!=null&&e.partial||(r=t.range.audio)!=null&&r.partial||(n=t.range.audiovideo)!=null&&n.partial||(i=t.range.subs)!=null&&i.partial)}function DS(t){return`${t.type}_${t.level}_${t.sn}`}function epe(t,e){return t.filter(r=>{const n=e(r);return n||r.clearElementaryStreamInfo(),n})}var Lv={cbc:0,ctr:1};class $Bt{constructor(e,r,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=r,this.aesMode=n}decrypt(e,r){switch(this.aesMode){case Lv.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},r,e);case Lv.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},r,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function UBt(t){const e=t.byteLength,r=e&&new DataView(t.buffer).getUint8(e-1);return r?t.slice(0,e-r):t}class VBt{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const r=new DataView(e),n=new Uint32Array(4);for(let i=0;i<4;i++)n[i]=r.getUint32(i*4);return n}initTable(){const e=this.sBox,r=this.invSBox,n=this.subMix,i=n[0],a=n[1],c=n[2],d=n[3],p=this.invSubMix,l=p[0],g=p[1],v=p[2],E=p[3],T=new Uint32Array(256);let j=0,P=0,C=0;for(C=0;C<256;C++)C<128?T[C]=C<<1:T[C]=C<<1^283;for(C=0;C<256;C++){let L=P^P<<1^P<<2^P<<3^P<<4;L=L>>>8^L&255^99,e[j]=L,r[L]=j;const O=T[j],F=T[O],$=T[F];let G=T[L]*257^L*16843008;i[j]=G<<24|G>>>8,a[j]=G<<16|G>>>16,c[j]=G<<8|G>>>24,d[j]=G,G=$*16843009^F*65537^O*257^j*16843008,l[L]=G<<24|G>>>8,g[L]=G<<16|G>>>16,v[L]=G<<8|G>>>24,E[L]=G,j?(j=O^T[T[T[$^O]]],P^=T[T[P]]):j=P=1}}expandKey(e){const r=this.uint8ArrayToUint32Array_(e);let n=!0,i=0;for(;i=n.length?n:n.slice(i.start,i.end):UBt(n)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,r,n,i,a){return this.decryptRange=a,this.useSoftware||a?new Promise((c,d)=>{const p=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(p,r,n,i);const l=this.flush();l?c(l.buffer):d(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),r,n,i)}softwareDecrypt(e,r,n,i){const{currentIV:a,currentResult:c,remainderData:d}=this;if(i!==Lv.cbc||r.byteLength!==16)return la.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),d&&(e=Kf(d,e),this.remainderData=null);const p=this.getValidChunk(e);if(!p.length)return null;a&&(n=a);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new VBt),l.expandKey(r);const g=c;return this.currentResult=l.decrypt(p.buffer,0,n),this.currentIV=p.slice(-16).buffer,g||null}webCryptoDecrypt(e,r,n,i){if(this.key!==r||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,r,n,i));this.key=r,this.fastAesKey=new qBt(this.subtle,r,i)}return this.fastAesKey.expandKey().then(a=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new $Bt(this.subtle,new Uint8Array(n),i).decrypt(e.buffer,a)):Promise.reject(new Error("web crypto not initialized"))).catch(a=>(la.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${a.name}: ${a.message}`),this.onWebCryptoError(e,r,n,i)))}onWebCryptoError(e,r,n,i){const a=this.enableSoftwareAES;if(a){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,r,n,i);const c=this.flush();if(c)return c.buffer}throw new Error("WebCrypto"+(a?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let r=e;const n=e.length-e.length%HBt;return n!==e.length&&(r=e.slice(0,n),this.remainderData=e.slice(n)),r}logOnce(e){this.logEnabled&&(la.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const tpe=Math.pow(2,17);class rpe{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,r,n,i){const a=e.url;if(!a)return Promise.reject(new $p({type:Kn.NETWORK_ERROR,details:Wt.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${a?"part list":"url"}`),networkDetails:null}));this.abort();const c=this.config,d=c.fLoader,p=c.loader;return new Promise((l,g)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(C=>C[0]==="GAP")){g(ipe(e));return}else e.gap=!1;const v=this.loader=d?new d(c):new p(c),E=npe(e,null,r);e.loader=v;const T=Nme(c.fragLoadPolicy.default),j={loadPolicy:T,timeout:T.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:tpe};v.stats.retry=e.stats.retry,e.stats=v.stats;const P={onSuccess:(C,L,O,F)=>{this.resetLoader(e,v);let $=C.data;O.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array($.slice(0,16)),$=$.slice(16)),l({frag:e,part:null,payload:$,networkDetails:F})},onError:(C,L,O,F)=>{this.resetLoader(e,v),g(new $p({type:Kn.NETWORK_ERROR,details:Wt.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Hn({url:a,data:void 0},C),error:new Error(`HTTP Error ${C.code} ${C.text}`),networkDetails:O,stats:F}))},onAbort:(C,L,O)=>{this.resetLoader(e,v),g(new $p({type:Kn.NETWORK_ERROR,details:Wt.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:O,stats:C}))},onTimeout:(C,L,O)=>{this.resetLoader(e,v),g(new $p({type:Kn.NETWORK_ERROR,details:Wt.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${j.timeout}ms`),networkDetails:O,stats:C}))}};if(n){const C=this.gateProgress(n,i);P.onProgress=(L,O,F,$)=>C({frag:e,part:null,payload:F,networkDetails:$})}v.load(E,j,P)})}gateProgress(e,r){let n=e;if(r){const i=[];let a=!1;r.then(()=>{a=!0,i.forEach(c=>e(c)),i.length=0}).catch(()=>{}),n=c=>{a?e(c):i.push(c)}}return n}loadPart(e,r,n){this.abort();const i=this.config,a=i.fLoader,c=i.loader;return new Promise((d,p)=>{if(this.loader&&this.loader.destroy(),e.gap||r.gap){p(ipe(e,r));return}const l=this.loader=a?new a(i):new c(i),g=npe(e,r);e.loader=l;const v=Nme(i.fragLoadPolicy.default),E={loadPolicy:v,timeout:v.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:tpe};r.stats=l.stats,l.load(g,E,{onSuccess:(T,j,P,C)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,r);const L={frag:e,part:r,payload:T.data,networkDetails:C};n(L),d(L)},onError:(T,j,P,C)=>{this.resetLoader(e,l),p(new $p({type:Kn.NETWORK_ERROR,details:Wt.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:r,response:Hn({url:g.url,data:void 0},T),error:new Error(`HTTP Error ${T.code} ${T.text}`),networkDetails:P,stats:C}))},onAbort:(T,j,P)=>{e.stats.aborted=r.stats.aborted,this.resetLoader(e,l),p(new $p({type:Kn.NETWORK_ERROR,details:Wt.INTERNAL_ABORTED,fatal:!1,frag:e,part:r,error:new Error("Aborted"),networkDetails:P,stats:T}))},onTimeout:(T,j,P)=>{this.resetLoader(e,l),p(new $p({type:Kn.NETWORK_ERROR,details:Wt.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:r,error:new Error(`Timeout after ${E.timeout}ms`),networkDetails:P,stats:T}))}})})}updateStatsFromPart(e,r){const n=e.stats,i=r.stats,a=i.total;if(n.loaded+=i.loaded,a){const p=Math.round(e.duration/r.duration),l=Math.min(Math.round(n.loaded/a),p),v=(p-l)*Math.round(n.loaded/l);n.total=n.loaded+v}else n.total=Math.max(n.loaded,n.total);const c=n.loading,d=i.loading;c.start?c.first+=d.first-d.start:(c.start=d.start,c.first=d.first),c.end=d.end}resetLoader(e,r){e.loader=null,e.url=null,this.loader===r&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),r.destroy()}}function npe(t,e=null,r){const n=e||t,i={type:ts.MEDIA_FRAGMENT,frag:t,part:e,responseType:"arraybuffer",url:n.url,headers:{},rangeStart:0,rangeEnd:0},a=Z3(t,e,r);return a.resetIV&&(i.resetIV=!0),a.byteRange&&(i.rangeStart=a.byteRange.start,i.rangeEnd=a.byteRange.end),i}function Z3(t,e=null,r){const n={},i=e||t,a=i.byteRangeStartOffset,c=i.byteRangeEndOffset;if(yn(a)&&yn(c)){var d;if((t.sn==="initSegment"||r)&&WBt((d=t.decryptdata)==null?void 0:d.method)){let p=Math.floor(a/16)*16;const l=Math.ceil(c/16)*16;n.decryptRange={start:a-p,end:c-p},p>=16&&(n.resetIV=!0,p=p-16),n.byteRange={start:p,end:l}}else n.byteRange={start:a,end:c}}return n}function ipe(t,e){const r=new Error(`GAP ${t.gap?"tag":"attribute"} found`),n={type:Kn.MEDIA_ERROR,details:Wt.FRAG_GAP,fatal:!1,frag:t,error:r,networkDetails:null};return e&&(n.part=e),(e||t).stats.aborted=!0,new $p(n)}function WBt(t){return t==="AES-128"||t==="AES-256"}class $p extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class xPe extends ff{constructor(e,r){super(e,r),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class NQ{constructor(e,r,n,i=0,a=-1,c=!1,d,p,l){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=fM(),this.buffering={audio:fM(),video:fM(),audiovideo:fM()},this.level=e,this.sn=r,this.id=n,this.size=i,this.part=a,this.partial=c,this.duration=d||0,this.decryptRange=l,this.iframe=p||!1}}function fM(){return{start:0,executeStart:0,executeEnd:0,end:0}}const EH=/\{\$([a-zA-Z0-9-_]+)\}/g;function spe(t){return EH.lastIndex=0,EH.test(t)}function RQ(t,e){if(t.variableList!==null||t.hasVariableRefs){const r=t.variableList;return e.replace(EH,n=>{const i=n.substring(2,n.length-1),a=r==null?void 0:r[i];return a===void 0?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),n):a})}return e}function ape(t,e,r){let n=t.variableList;n||(t.variableList=n={});let i,a;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const c=new self.URL(r).searchParams;if(c.has(i))a=c.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${r}"`)}catch(c){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${c.message}`))}}else i=e.NAME,a=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=a||""}function KBt(t,e,r){const n=e.IMPORT;if(r&&n in r){let i=t.variableList;i||(t.variableList=i={}),i[n]=r[n]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}const YBt=/^(\d+)x(\d+)$/,ope=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Vo{constructor(e,r){typeof e=="string"&&(e=Vo.parseAttrList(e,r)),La(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const r=parseInt(this[e],10);return r>Number.MAX_SAFE_INTEGER?1/0:r}hexadecimalInteger(e){if(this[e]){let r=(this[e]||"0x").slice(2);r=(r.length&1?"0":"")+r;const n=new Uint8Array(r.length/2);for(let i=0;iNumber.MAX_SAFE_INTEGER?1/0:r}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,r){const n=this[e];return n?parseFloat(n):r}enumeratedString(e){return this[e]}enumeratedStringList(e,r){const n=this[e];return(n?n.split(/[ ,]+/):[]).reduce((i,a)=>(i[a.toLowerCase()]=!0,i),r)}bool(e){return this[e]==="YES"}decimalResolution(e){const r=YBt.exec(this[e]);if(r!==null)return{width:parseInt(r[1],10),height:parseInt(r[2],10)}}static parseAttrList(e,r){let n;const i={},a='"';for(ope.lastIndex=0;(n=ope.exec(e))!==null;){const c=n[1].trim();let d=n[2];const p=d.indexOf(a)===0&&d.lastIndexOf(a)===d.length-1;let l=!1;if(p)d=d.slice(1,-1);else switch(c){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(r&&(p||l))d=RQ(r,d);else if(!l&&!p)switch(c){case"CLOSED-CAPTIONS":if(d==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":la.warn(`${e}: attribute ${c} is missing quotes`)}i[c]=d}return i}}const ZBt="com.apple.hls.interstitial";function XBt(t){return t!=="ID"&&t!=="CLASS"&&t!=="CUE"&&t!=="START-DATE"&&t!=="DURATION"&&t!=="END-DATE"&&t!=="END-ON-NEXT"}function QBt(t){return t==="SCTE35-OUT"||t==="SCTE35-IN"||t==="SCTE35-CMD"}class _Pe{constructor(e,r,n=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(r==null?void 0:r.tagAnchor)||null,this.tagOrder=(i=r==null?void 0:r.tagOrder)!=null?i:n,r){const a=r.attr;for(const c in a)if(Object.prototype.hasOwnProperty.call(e,c)&&e[c]!==a[c]){la.warn(`DATERANGE tag attribute: "${c}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=c;break}e=La(new Vo({}),a,e)}if(this.attr=e,r?(this._startDate=r._startDate,this._cue=r._cue,this._endDate=r._endDate,this._dateAtEnd=r._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){const a=(r==null?void 0:r.endDate)||new Date(e["END-DATE"]);yn(a.getTime())&&(this._endDate=a)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(la.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const r=this.duration;return r!==null?this._dateAtEnd=new Date(this._startDate.getTime()+r*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(yn(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===ZBt}get isValid(){return!!this.id&&!this._badValueForSameId&&yn(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:yn(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}}function X3(t,e){return t.length===e.length?!t.some((r,n)=>r!==e[n]):!1}function lpe(t,e){return!t&&!e?!0:!t||!e?!1:X3(t,e)}function RE(t){return t==="AES-128"||t==="AES-256"||t==="AES-256-CTR"}function LQ(t){switch(t){case"AES-128":case"AES-256":return Lv.cbc;case"AES-256-CTR":return Lv.ctr;default:throw new Error(`invalid full segment method ${t}`)}}function TH(t){return Uint8Array.from(unescape(encodeURIComponent(t)),e=>e.charCodeAt(0))}function JBt(t){const e=TH(t).subarray(0,16),r=new Uint8Array(16);return r.set(e,16-e.length),r}function vPe(t){const e=function(n,i,a){const c=n[i];n[i]=n[a],n[a]=c};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function bPe(t){const e=t.split(":");let r=null;if(e[0]==="data"&&e.length===2){const n=e[1].split(";"),i=n[n.length-1].split(",");if(i.length===2){const a=i[0]==="base64",c=i[1];a?(n.splice(-1,1),r=IQ(c)):r=JBt(c)}}return r}const Q3=typeof self<"u"?self:void 0;var So={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Lu={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function mM(t){switch(t){case Lu.FAIRPLAY:return So.FAIRPLAY;case Lu.PLAYREADY:return So.PLAYREADY;case Lu.WIDEVINE:return So.WIDEVINE;case Lu.CLEARKEY:return So.CLEARKEY}}var wPe={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function i8(t){switch(t){case So.FAIRPLAY:return Lu.FAIRPLAY;case So.PLAYREADY:return Lu.PLAYREADY;case So.WIDEVINE:return Lu.WIDEVINE;case So.CLEARKEY:return Lu.CLEARKEY}}function SI(t){const{drmSystems:e,widevineLicenseUrl:r}=t,n=e?[So.FAIRPLAY,So.WIDEVINE,So.PLAYREADY,So.CLEARKEY].filter(i=>!!e[i]):[];return!n[So.WIDEVINE]&&r&&n.push(So.WIDEVINE),n}const SPe=function(t){return Q3!=null&&(t=Q3.navigator)!=null&&t.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function ezt(t,e,r,n){let i;switch(t){case So.FAIRPLAY:i=["cenc","sinf"];break;case So.WIDEVINE:case So.PLAYREADY:i=["cenc"];break;case So.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return tzt(i,e,r,n)}function tzt(t,e,r,n){return[{initDataTypes:t,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:e.map(a=>({contentType:`audio/mp4; codecs=${a}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:r.map(a=>({contentType:`video/mp4; codecs=${a}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}function rzt(t){var e;return!!t&&(t.sessionType==="persistent-license"||!!((e=t.sessionTypes)!=null&&e.some(r=>r==="persistent-license")))}function DQ(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=np(e),n=r.substring(r.indexOf("<"),r.length),c=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(c){const d=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(d){const p=IQ(d).subarray(0,16);return vPe(p),p}}return null}let MS={};class By{static clearKeyUriToKeyIdMap(){MS={}}static setKeyIdForUri(e,r){MS[e]=r}static addKeyIdForUri(e){const r=Object.keys(MS).length%Number.MAX_SAFE_INTEGER,n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,r),MS[e]=n,n}constructor(e,r,n,i=[1],a=null,c){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=r,this.keyFormat=n,this.keyFormatVersions=i,this.iv=a,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!RE(e),c!=null&&c.startsWith("0x")&&(this.keyId=new Uint8Array(qCe(c)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&X3(e.keyFormatVersions,this.keyFormatVersions)&&lpe(e.iv,this.iv)&&lpe(e.keyId,this.keyId)}isSupported(){if(this.method){if(RE(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Lu.FAIRPLAY:case Lu.WIDEVINE:case Lu.PLAYREADY:case Lu.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,r){var n;if(!this.encrypted||!this.uri)return null;if(RE(this.method)){let c=this.iv;return c||(typeof e!="number"&&(la.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),c=izt(e)),new By(this.method,this.uri,"identity",this.keyFormatVersions,c)}if(this.keyId){const c=MS[this.uri];if(c&&!X3(this.keyId,c)&&By.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=bPe(this.uri);if(i)switch(this.keyFormat){case Lu.WIDEVINE:if(this.pssh=i,!this.keyId){const c=tPe(i.buffer).filter(d=>d.systemId===wPe.WIDEVINE);if(c.length){var a;const d=c[0];this.keyId=(a=d.kids)!=null&&a.length?d.kids[0]:null}}this.keyId||(this.keyId=cpe(r));break;case Lu.PLAYREADY:{const c=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=J5t(c,null,i),this.keyId=DQ(i);break}default:{let c=i.subarray(0,16);if(c.length!==16){const d=new Uint8Array(16);d.set(c,16-c.length),c=d}this.keyId=c;break}}if(((n=this.keyId)==null?void 0:n.byteLength)!==16){let c;c=nzt(r),c||(c=cpe(r),c||(c=MS[this.uri])),c&&(this.keyId=c,By.setKeyIdForUri(this.uri,c))}return this}}function nzt(t){const e=t==null?void 0:t[Lu.WIDEVINE];return e?e.keyId:null}function cpe(t){const e=t==null?void 0:t[Lu.PLAYREADY];if(e){const r=bPe(e.uri);if(r)return DQ(r)}return null}function izt(t){const e=new Uint8Array(16);for(let r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e}const upe=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,dpe=/#EXT-X-MEDIA:(.*)/g,szt=/^#EXT(?:INF|-X-TARGETDURATION):/m,s8=new RegExp([/#EXTINF:\s*(\d+(?:\.\d*)?|\.\d+)?(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),azt=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class eg{static findGroup(e,r){for(let n=0;n0&&a.length({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:c.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let p=0;for(dpe.lastIndex=0;(i=dpe.exec(e))!==null;){const l=new Vo(i[1],n),g=l.TYPE;if(g){const v=d[g],E=a[g]||[];a[g]=E;const T=l.LANGUAGE,j=l["ASSOC-LANGUAGE"],P=l.CHANNELS,C=l.CHARACTERISTICS,L=l["INSTREAM-ID"],O={attrs:l,bitrate:0,id:p++,groupId:l["GROUP-ID"]||"",name:l.NAME||T||"",type:g,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:T,url:l.URI?eg.resolve(l.URI,r):""};if(j&&(O.assocLang=j),P&&(O.channels=P),C&&(O.characteristics=C),L&&(O.instreamId=L),v!=null&&v.length){const F=eg.findGroup(v,O.groupId)||v[0];gpe(O,F,"audioCodec"),gpe(O,F,"textCodec")}E.push(O)}}return a}static parseLevelPlaylist(e,r,n,i,a,c){var d;const p={url:r},l=new LBt(r),g=l.fragments,v=[];let E=null,T=0,j=0,P=0,C=0,L=0,O=null,F=new oM(i,p),$,G,W,Z=-1,Q=!1,ee=null,ie;if(s8.lastIndex=0,l.m3u8=e,l.hasVariableRefs=spe(e),((d=s8.exec(e))==null?void 0:d[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;($=s8.exec(e))!==null;){Q&&(Q=!1,F=new oM(i,p),F.playlistOffset=P,F.setStart(P),F.sn=T,F.cc=C,L&&(F.bitrate=L),F.level=n,E&&(F.initSegment=E,E.rawProgramDateTime&&(F.rawProgramDateTime=E.rawProgramDateTime,E.rawProgramDateTime=null),ee&&(F.setByteRange(ee),ee=null)));const Re=$[1];if(Re){F.duration=parseFloat(Re);const Ie=(" "+$[2]).slice(1);F.title=Ie||null,F.tagList.push(Ie?["INF",Re,Ie]:["INF",Re])}else if($[3]){if(yn(F.duration)){var oe;F.playlistOffset=P,F.setStart(P),W&&xpe(F,W,l),F.sn=T,F.level=n,F.cc=C;const Ie=(" "+$[3]).slice(1);F.relurl=RQ(l,Ie),AH(F,O,v),O=F,P+=F.duration,T++,j=0;const Te=F.byteRange;if(Te.length===2&&(F.bitrate=(Te[1]-Te[0])*8/F.duration|0),l.iframesOnly&&Te[0]&&((oe=E)==null?void 0:oe.cc)!==C){const ge=new oM(i,p);ge.relurl=F.relurl,ge.setByteRange(`${Math.min(Te[0],7*188)}@0`),ge.level=n,ge.sn="initSegment",W&&(ge.levelkeys=W,W.identity&&(ge._decryptdata=W.identity.getDecryptData(0))),E=ge,F.initSegment=E}g.push(F),Q=!0}}else{if($=$[0].match(azt),!$){la.warn("No matches on slow regex match for level playlist!");continue}for(G=1;G<$.length&&$[G]===void 0;G++);const Ie=(" "+$[G]).slice(1),Te=(" "+$[G+1]).slice(1),ge=$[G+2]?(" "+$[G+2]).slice(1):null;switch(Ie){case"BYTERANGE":O?F.setByteRange(Te,O):F.setByteRange(Te);break;case"PROGRAM-DATE-TIME":F.rawProgramDateTime=Te,F.tagList.push(["PROGRAM-DATE-TIME",Te]),Z===-1&&(Z=g.length);break;case"PLAYLIST-TYPE":l.type&&cy(l,Ie,$),l.type=Te.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?cy(l,Ie,$):O!==null&&czt(l,Ie,$),l.startSN=parseInt(Te),T=l.startSN+l.skippedSegments;break;case"SKIP":{l.skippedSegments&&cy(l,Ie,$);const $e=new Vo(Te,l),we=$e.decimalInteger("SKIPPED-SEGMENTS");if(yn(we)){l.skippedSegments+=we;for(let Ae=we;Ae--;)g.push(null);T+=we}const ke=$e.enumeratedString("RECENTLY-REMOVED-DATERANGES");ke&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(ke.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&cy(l,Ie,$),l.targetduration=Math.max(parseInt(Te),1);break;case"VERSION":l.version!==null&&cy(l,Ie,$),l.version=parseInt(Te);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":l.iframesOnly=!0;break;case"ENDLIST":l.live||cy(l,Ie,$),l.live=!1;break;case"#":(Te||ge)&&F.tagList.push(ge?[Te,ge]:[Te]);break;case"DISCONTINUITY":C++,F.tagList.push(["DIS"]);break;case"GAP":F.gap=!0,F.tagList.push([Ie]);break;case"BITRATE":F.tagList.push([Ie,Te]),L=parseInt(Te)*1e3,yn(L)?F.bitrate=L:L=0;break;case"DATERANGE":{const $e=new Vo(Te,l),we=new _Pe($e,l.dateRanges[$e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,we.isValid||l.skippedSegments?l.dateRanges[we.id]=we:la.log(`Ignoring invalid DATERANGE tag: ${we.invalidReason}: ${Te}`),F.tagList.push(["EXT-X-DATERANGE",Te]);break}case"DEFINE":{{const $e=new Vo(Te,l);"IMPORT"in $e?KBt(l,$e,c):ape(l,$e,r)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0&&cy(l,Ie,$),l.startCC=C=parseInt(Te),g.forEach($e=>$e&&($e.cc=C));break;case"KEY":{const $e=fpe(Te,r,l);if($e.isSupported()){if($e.method==="NONE"){W=void 0;break}W||(W={});const we=W[$e.keyFormat];we!=null&&we.matches($e)||(we&&(W=La({},W)),W[$e.keyFormat]=$e)}else la.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${Te}"`);break}case"START":l.startTimeOffset=mpe(Te);break;case"MAP":{const $e=new Vo(Te,l);if(F.duration){const we=new oM(i,p);ype(we,$e,n,W),E=we,F.initSegment=E,E.rawProgramDateTime&&!F.rawProgramDateTime&&(F.rawProgramDateTime=E.rawProgramDateTime)}else{const we=F.byteRangeEndOffset;if(we){const ke=F.byteRangeStartOffset;ee=`${we-ke}@${ke}`}else ee=null;ype(F,$e,n,W),E=F,Q=!0}E.cc=C;break}case"SERVER-CONTROL":{ie&&cy(l,Ie,$),ie=new Vo(Te),l.canBlockReload=ie.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=ie.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&ie.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=ie.optionalFloat("PART-HOLD-BACK",0),l.holdBack=ie.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&cy(l,Ie,$);const $e=new Vo(Te);l.partTarget=$e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let $e=l.partList;$e||($e=l.partList=[]);const we=j>0?$e[$e.length-1]:void 0,ke=j++,Ae=new Vo(Te,l),He=new o5t(Ae,F,p,ke,we);$e.push(He),F.duration+=He.duration;break}case"PRELOAD-HINT":{const $e=new Vo(Te,l);l.preloadHint=$e;break}case"RENDITION-REPORT":{const $e=new Vo(Te,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push($e);break}default:la.warn(`line parsed but not handled: ${$}`);break}}}O&&!O.relurl?(g.pop(),P-=O.duration,l.partList&&(l.fragmentHint=O)):l.partList&&(AH(F,O,v),F.cc=C,l.fragmentHint=F,W&&xpe(F,W,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const pe=g.length,Le=g[0],be=g[pe-1];if(P+=l.skippedSegments*l.targetduration,P>0&&pe&&be){l.averagetargetduration=P/pe;const Re=be.sn;l.endSN=Re!=="initSegment"?Re:0,l.live||(be.endList=!0),Z>0&&(lzt(g,Z,Z>pe-1?F:null),Le&&v.unshift(Le))}return l.fragmentHint&&(P+=l.fragmentHint.duration),l.totalduration=P,v.length&&l.dateRangeTagCount&&Le&&EPe(v,l),l.endCC=C,l}}function hpe(t,e,r,n,i,a){var c;if(e===void 0)return null;const d=RQ(n,e),p={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:eg.resolve(d,r)},l=t.decimalResolution("RESOLUTION");l&&(p.width=l.width,p.height=l.height),ppe(t.CODECS,p);const g=t["SUPPLEMENTAL-CODECS"];return g&&(p.supplemental={},ppe(g,p.supplemental)),(c=p.unknownCodecs)!=null&&c.length||i.push(p),a&&(p.iframes=!0),p}function EPe(t,e){let r=t.length;if(!r)if(e.hasProgramDateTime){const d=e.fragments[e.fragments.length-1];t.push(d),r++}else return;const n=t[r-1],i=e.live?1/0:e.totalduration,a=Object.keys(e.dateRanges);for(let d=a.length;d--;){const p=e.dateRanges[a[d]],l=p.startDate.getTime();p.tagAnchor=n.ref;for(let g=r;g--;){var c;if(((c=t[g])==null?void 0:c.sn)=d||n===0){var c;const p=(((c=r[n+1])==null?void 0:c.start)||i)-a.start;if(e<=d+p*1e3){const l=a.sn-t.startSN,g=t.fragments;if(l>=0&&lr.length){const v=r[n+1]||g[g.length-1],E=Math.min(v.sn-t.startSN,g.length-1);for(let T=E;T>l;T--){const j=g[T].programDateTime;if(e>=j&&en);["video","audio","text","image"].forEach(n=>{const i=r.filter(a=>jQ(a,n));i.length&&(e[`${n}Codec`]=i.map(a=>a.split("/")[0]).join(","),r=r.filter(a=>i.indexOf(a)===-1))}),e.unknownCodecs=r}function gpe(t,e,r){const n=e[r];n&&(t[r]=n)}function lzt(t,e,r){if(r||(r=t[e]),!!r)for(let n=e;n--;){const i=t[n];if(!i)return;i.programDateTime=r.programDateTime-i.duration*1e3,r=i}}function AH(t,e,r){t.rawProgramDateTime?r.push(t):e!=null&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function ype(t,e,r,n){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=r,t.sn="initSegment",n&&(t.levelkeys=n),t.initSegment=null}function xpe(t,e,r){t.levelkeys=e;const{encryptedFragments:n}=r;(!n.length||n[n.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&n.push(t)}function cy(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${r[0]})`)}function czt(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${r[0]})`)}function a8(t,e){const r=e.startPTS;if(yn(r)){let n=0,i;e.sn>t.sn?(n=r-t.start,i=t):(n=t.start-r,i=e),i.duration!==n&&i.setDuration(n)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration):e.setStart(Math.max(t.start-e.duration,0))}function TPe(t,e,r,n,i,a,c,d){n-r<=0&&(d.warn("Fragment should have a positive duration",e),n=r+e.duration,a=i+e.duration);let l=r,g=n;const v=e.startPTS,E=e.endPTS;if(yn(v)){const j=Math.abs(v-r);t&&j>t.totalduration?d.warn(`media timestamps and playlist times differ by ${j}s for level ${e.level} ${t.url}`):yn(e.deltaPTS)?e.deltaPTS=Math.max(j,e.deltaPTS):e.deltaPTS=j,l=Math.max(r,v),r=Math.min(r,v),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,g=Math.min(n,E),n=Math.max(n,E),a=e.endDTS!==void 0?Math.max(a,e.endDTS):a}const T=r-e.start;return e.start!==0&&e.setStart(r),e.setDuration(n-e.start),e.startPTS=r,e.maxStartPTS=l,e.startDTS=i,e.endPTS=n,e.minEndPTS=g,e.endDTS=a,APe(t,e,T)}function APe(t,e,r){var n;const i=e.sn;if(!t||i(((n=t.fragmentHint)==null?void 0:n.sn)||t.endSN))return 0;let a;const c=i-t.startSN,d=t.fragments;for(d[c]=e,a=c;a>0;a--)a8(d[a],d[a-1]);for(a=c;a=0;g--){const v=i[g].initSegment;if(v){n=v;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let a;fzt(t,e,(g,v,E,T)=>{if(v.cc!==g.cc&&(g.cc>v.cc||e.skippedSegments)){const j=g.cc-v.cc;for(let P=E;P{var v;g&&(!g.initSegment||g.initSegment.relurl===((v=n)==null?void 0:v.relurl))&&(g.initSegment=n)}),e.skippedSegments){if(e.deltaUpdateFailed=c.some(g=>!g),e.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let g=e.skippedSegments;g--;)c.shift();e.startSN=c[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=dzt(t.dateRanges,e,r));const g=t.fragments.filter(v=>v.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let v=1;vt.endSN&&c[0].cc{v.cc+=g}),e.endCC+=g}if(!e.startCC){var p;const g=TO(t,e.startSN-1);e.startCC=(p=g==null?void 0:g.cc)!=null?p:c[0].cc}if(hzt(t.partList,e.partList,(g,v)=>{v.elementaryStreams=g.elementaryStreams,v.stats=g.stats,v.gap=g.gap||v.gap}),a){const g=e.iframesOnly&&a.type===On.MAIN;TPe(e,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,g,r)}else kPe(t,e);c.length&&(e.totalduration=e.edge-c[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const g=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=g),e.driftEndTime=l,e.driftEnd=g}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=t.requestScheduled)}function dzt(t,e,r){const{dateRanges:n,recentlyRemovedDateranges:i}=e,a=La({},t);i&&i.forEach(p=>{delete a[p]});const d=Object.keys(a).length;return d?(Object.keys(n).forEach(p=>{const l=a[p],g=new _Pe(n[p].attr,l);g.isValid?(a[p]=g,l||(g.tagOrder+=d)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${fo(n[p].attr)}"`)}),a):n}function hzt(t,e,r){if(t&&e){let n=0;for(let i=0,a=t.length;i=0;let d=0;if(c&&ie){const a=n[n.length-1].duration*1e3;a>0&&a{var n;(n=e.details)==null||n.fragments.forEach(i=>{i.level=r,i.initSegment&&(i.initSegment.level=r)})})}function pzt(t,e){return t!==e&&e?bpe(t)!==bpe(e):!1}function bpe(t){return t.replace(/\?[^?]*$/,"")}function Tj(t,e){for(let n=0,i=t.length;nt.startCC)}function wpe(t,e){const r=t.start+e;t.setStart(r)}function PPe(t,e){const r=e.fragments;for(let n=0,i=r.length;n!!E)[0],c=Tj(n,a.cc)||n[Math.floor(n.length/2)]);const p=a.programDateTime,l=c.programDateTime;if(!p||!l)return;const g=(l-p)/1e3;if(Math.abs(g)>Math.max(60,t.totalduration)){r.log(`Cannot align playlists using PDT without overlap (${Math.abs(g)} > ${t.totalduration})`);return}const v=g-(c.start-a.start);r.log(`Aligning playlists using PDT (diff: ${v})`),PPe(v,t)}const Tr={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class MQ extends xPe{constructor(e,r,n,i,a){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Tr.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:c,fragCurrent:d,media:p,mediaBuffer:l,state:g}=this,v=p?p.currentTime:0,E=xi.bufferInfo(l||p,v,c.maxBufferHole),T=E.len;if(this.log(`Media seeking to ${v}, state: ${g}, ${T?"in":"out of"} buffer`),this.state===Tr.ENDED)this.resetLoadingState();else if(d){const C=c.maxFragLookUpTolerance,L=d.start-C,O=d.start+d.duration+C;if(!T||OE.end){const F=vO;(F||$)&&(d.loader&&($||!this.isFragmentNearlyDownloaded(d))?(this.log(`Cancelling fragment load for seek (sn: ${d.sn}) - ${F?"backward":"forward"} seek`),d.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(p){var j;(j=this.hls)!=null&&j.hasEnoughToStart&&!T&&v!==this.startPosition&&this.fragmentTracker.removeFragmentsInRange(v,1/0,this.playlistType,!0);const C=this.lastCurrentTime;if(v>C&&(this.lastCurrentTime=v),!this.loadingParts){const L=Math.max(E.end,v),O=this.shouldLoadParts(this.getLevelDetails(),L);O&&(this.log(`LL-Part loading ON after seeking to ${v} with buffer @${L}`),this.loadingParts=O)}}const P=!xi.isBuffered(p,v);(!this.hls.hasEnoughToStart||P)&&(this.log(`Setting ${P?"startPosition":"nextLoadPosition"} to ${v} for seek without enough to start`),this.nextLoadPosition=v,P?this.startPosition=v:this.lastCurrentTime=v),T<1&&this.state===Tr.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.nextLoadPosition=this.lastCurrentTime=0},this.playlistType=a,this.hls=e,this.fragmentLoader=new rpe(e.config),this.initFragmentLoader=new rpe(e.config),this.keyLoader=n,this.fragmentTracker=r,this.config=e.config,this.decrypter=new PQ(e.config)}registerListeners(){const{hls:e}=this;e.on(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Ee.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Ee.ERROR,this.onError,this)}doTick(){}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&e.seeking===!1&&(this.lastCurrentTime=e.currentTime)}startLoad(e){}stopLoad(){if(this.state===Tr.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Tr.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:r}=this;if(r===-1&&e){const n=this.getLevelDetails();return n!=null&&n.live?(this.hls.liveSyncPosition||n.fragmentStart)+this.timelineOffset:e}return r}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,r){if(r.live||!this.media)return!1;const n=e.end||0,i=this.config.timelineOffset||0;if(n<=i)return!1;const a=e.buffered;this.config.maxBufferHole&&a&&a.length>1&&(e=xi.bufferedInfo(a,e.start,0));const c=e.nextStart;if(c&&c>i&&ca.addAsGap(d)),this.stopLoad()}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.nextLoadPosition=0,this.startPosition=-1,this.startFragRequested=!1}onError(e,r){}onManifestLoaded(e,r){this.startTimeOffset=r.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Tr.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,r,n){this.startFragRequested=!0,this._loadFragForPlayback(e,r,n)}_loadFragForPlayback(e,r,n){const i=a=>{const c=a.frag;if(this.fragContextChanged(c)){this.warn(`${c.type} sn: ${c.sn}${a.part?" part: "+a.part.index:""} of ${this.fragInfo(c,!1,a.part)} was dropped during download.`),this.fragmentTracker.removeFragment(c);return}const d=++c.stats.chunkCount;this.log(`load progress ${c.type} sn: ${c.sn}${a.part?" part: "+a.part.index:""} of ${this.fragInfo(c,!1,a.part)} chunk: ${d}`),this._handleFragmentLoadProgress(a)};this._doFragLoad(e,r,n,i).then(a=>{if(!a)return;const c=this.state,d=a.frag;if(this.fragContextChanged(d)){(c===Tr.FRAG_LOADING||!this.fragCurrent&&c===Tr.PARSING)&&(this.fragmentTracker.removeFragment(d),this.state=Tr.IDLE);return}"payload"in a&&(this.log(`Loaded ${d.type} sn: ${d.sn} of ${this.playlistLabel()} ${d.level} (bytes ${d.stats.loaded})`),this.hls.trigger(Ee.FRAG_LOADED,a)),this._handleFragmentLoadComplete(a)}).catch(a=>{this.state===Tr.STOPPED||this.state===Tr.ERROR||(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${(a==null?void 0:a.message)||a}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var r;const{fragmentTracker:n}=this;if(n.getState(e)===wo.APPENDING){const a=e.type,c=this.getFwdBufferInfo(this.mediaBuffer,a),d=Math.max(e.duration,c?c.len:this.config.maxBufferLength),p=this.backtrackFragment;((p?e.sn-p.sn:0)===1||this.reduceMaxBufferLength(d,e.duration))&&n.removeFragment(e)}else((r=this.mediaBuffer)==null?void 0:r.buffered.length)===0?n.removeAllFragments():n.hasParts(e.type)&&(n.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),n.getState(e)===wo.PARTIAL&&n.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const r=this.fragmentTracker,n=e.fragments[e.fragments.length-1];if(n.endList&&!r.isEndListAppended(this.playlistType)){const i=r.getPartialFragment(n.end);i&&(r.removeFragment(i),r.fragBuffered(n,!0))}r.detectPartialFragments({frag:n,part:null,stats:n.stats,id:n.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const r=e.details;return(r==null?void 0:r.live)&&r.type!=="EVENT"&&r.advancedDateTime!==void 0&&(r.expired||this.loadingParts&&r.partsExpired||r.misses<3&&r.partEnd<=this.getLoadPosition())}flushMainBuffer(e,r,n=null){if(!(e-r))return;const i={startOffset:e,endOffset:r,type:n};this.hls.trigger(Ee.BUFFER_FLUSHING,i)}_loadInitSegment(e){const{hls:r}=this;return this.initFragmentLoader.abort(),r.trigger(Ee.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(n=>{var i;const a=n.frag;if(!this.levels||!yH(a,(i=this.fragCurrent)==null?void 0:i.initSegment))throw new $p({type:Kn.NETWORK_ERROR,details:Wt.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:a,networkDetails:null});return n}).then(n=>{const{frag:i,payload:a}=n,c=i.decryptdata;if(a&&a.byteLength>0&&c!=null&&c.key&&c.iv&&RE(c.method)){const d=self.performance.now(),{decryptRange:p}=Z3(i,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(a),c.key.buffer,c.iv.buffer,LQ(c.method),p).catch(l=>{throw r.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:i}),this.fragmentLoader.abort(),l}).then(l=>{const g=self.performance.now();return r.trigger(Ee.FRAG_DECRYPTED,{frag:i,part:null,payload:l,stats:{tstart:d,tdecrypt:g}}),n.payload=l,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)})}completeInitSegmentLoad(e){const r=e.frag.stats;e.frag.data=new Uint8Array(e.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){const{initSegment:r}=e;if(!this.bitrateTest&&Ko(e)&&r&&!r.data){var n;return(r.encrypted&&!((n=r.decryptdata)!=null&&n.key)?this.keyLoader.load(r).then(()=>this._loadInitSegment(r)):this._loadInitSegment(r)).catch(a=>{throw this.state===Tr.STOPPED||this.state===Tr.ERROR||("data"in a&&(this.fragmentLoader.abort(),this.handleFragLoadError(a,e)),this.resetFragmentLoading(e)),a})}}unhandledEncryptionError(e,r){var n,i;const a=e.tracks;if(a&&!r.encrypted&&((n=a.audio)!=null&&n.encrypted||(i=a.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const c=this.media,d=new Error(`Encrypted track with no key in ${this.fragInfo(r)} (media ${c?"attached mediaKeys: "+c.mediaKeys:"detached"})`);return this.warn(d.message),!c||c.mediaKeys?!1:(this.hls.trigger(Ee.ERROR,{type:Kn.KEY_SYSTEM_ERROR,details:Wt.KEY_SYSTEM_NO_KEYS,fatal:!1,error:d,frag:r}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:r}=this;return!e||!yH(e,r)}fragBufferedComplete(e,r){const n=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${r?" part: "+r.index:""} of ${this.fragInfo(e,!1,r)} > buffer:${n?Y3(xi.getBuffered(n)):"(detached)"})`),Ko(e)){var i;if(e.type!==On.SUBTITLE){const c=e.elementaryStreams;if(!Object.keys(c).some(d=>!!c[d])){this.state=Tr.IDLE;return}}const a=(i=this.levels)==null?void 0:i[e.level];a!=null&&a.fragmentError&&(r||this.fragmentTracker.getState(e)!==wo.PARTIAL)&&(this.log(`Resetting level fragment error count of ${a.fragmentError} on frag buffered`),a.fragmentError=0,e.stats.retry=0)}this.state=Tr.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:r}=this;if(!r)return;const n=e.frag,{part:i,partsLoaded:a}=e,c=!a||a.length===0||a.some(l=>!l),{decryptRange:d}=Z3(n,i),p=new NQ(n.level,n.sn,n.stats.chunkCount+1,0,i?i.index:-1,!c,n.duration,this.iframesOnly,d);this.log(`load complete ${n.type} sn: ${n.sn}${i?" part: "+i.index:""} of ${this.fragInfo(n,!1,i)}`),r.flush(p)}_handleFragmentLoadProgress(e){}loadKeyFor(e,r,n){var i;let a=null;return e.encrypted&&!((i=e.decryptdata)!=null&&i.key)?(this.log(`Loading key for ${e.sn} of [${r.startSN}-${r.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Tr.KEY_LOADING,a=this.keyLoader.load(e,n).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(Ee.KEY_LOADED,c),this.state===Tr.KEY_LOADING&&(this.state=Tr.IDLE),c}),this.hls.trigger(Ee.KEY_LOADING,{frag:e})):e.encrypted||(a=this.keyLoader.loadClear(e,r.encryptedFragments,this.startFragRequested),a&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)),a}_doFragLoad(e,r,n=null,i){this.fragCurrent=e;const a=r.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);const c=this.fragPrevious;if(!UI(e,c)){const T=this.shouldLoadParts(r.details,e.end);T!==this.loadingParts&&(this.log(`LL-Part loading ${T?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${e.sn}`),this.loadingParts=T)}if(n=Math.max(e.start,n||0),this.loadingParts){const T=a.partList;if(T&&i){n>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const j=this.getNextPart(T,e,n);if(j>-1){const P=T[j];if(e=this.fragCurrent=P.fragment,!UI(e,c)&&!this.shouldLoadParts(r.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,P)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(P,r.details))return Promise.resolve(null);const C=this.loadKeyFor(e,a);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${P.index} (${j}/${T.length-1}) of ${this.fragInfo(e,!1,P)} cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${n}${P.byteRange.length?` range:${P.byteRange.join("-")}`:""}`),this.nextLoadPosition=P.start+P.duration,this.state=Tr.FRAG_LOADING;let L;const O=this.loadInitSegmentIfNeeded(e);if(C||O){const F=!!C;L=Promise.all([C,O]).then(([$])=>F&&(!$||this.fragContextChanged($.frag))?null:this.doFragPartsLoad(e,P,r,i)).catch($=>this.handleFragLoadError($,e))}else L=this.doFragPartsLoad(e,P,r,i).catch(F=>this.handleFragLoadError(F,e));return this.hls.trigger(Ee.FRAG_LOADING,{frag:e,part:P,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):L}else if(!e.url||this.loadedEndOfParts(T,n))return Promise.resolve(null)}}if(this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${n} Check buffer at sn: ${e.sn} loaded parts: ${(d=a.partList)==null?void 0:d.filter(T=>T.loaded).map(T=>`[${T.start}-${T.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,r.details))return Promise.resolve(null);const p=this.loadInitSegmentIfNeeded(e),l=this.loadKeyFor(e,a,p);if(this.fragContextChanged(e)){var g;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(g=this.fragCurrent)==null?void 0:g.relurl}`),p==null||p.catch(()=>null),l==null||l.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${n}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),yn(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Tr.FRAG_LOADING;const v=this.config.progressive&&e.type!==On.SUBTITLE;let E;return v&&l?E=l.then(T=>!T||this.fragContextChanged(T.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,i,p)).catch(T=>this.handleFragLoadError(T,e)):E=Promise.all([this.fragmentLoader.load(e,this.iframesOnly,v?i:void 0,v?p:void 0),l,p]).then(([T])=>(!v&&i&&i(T),T)).catch(T=>this.handleFragLoadError(T,e)),this.hls.trigger(Ee.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([E,p]).then(([T])=>T)}doFragPartsLoad(e,r,n,i){return new Promise((a,c)=>{var d;const p=[],l=(d=n.details)==null?void 0:d.partList,g=v=>{this.fragmentLoader.loadPart(e,v,i).then(E=>{p[v.index]=E;const T=E.part;this.hls.trigger(Ee.FRAG_LOADED,E);const j=vpe(n.details,e.sn,v.index+1)||jPe(l,e.sn,v.index+1);if(j)g(j);else return a({frag:e,part:T,partsLoaded:p})}).catch(c)};g(r)})}handleFragLoadError(e,r){if("data"in e){const n=e.data;n.details===Wt.INTERNAL_ABORTED?this.handleFragLoadAborted(r,n.part):n.type===Kn.KEY_SYSTEM_ERROR&&!n.fatal&&(r.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(r)),n.frag!==r?(n.frag&&this.warn(`${n.details} error cascading from ${this.fragInfo(n.frag,!1,n.part)} to ${this.fragInfo(r,!1)}`),this.hls.trigger(Ee.ERROR,Hn(Hn({},n),{},{frag:r}))):this.hls.trigger(Ee.ERROR,n)}else this.hls.trigger(Ee.ERROR,{type:Kn.OTHER_ERROR,details:Wt.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const r=this.getCurrentContext(e);if(!r||this.state!==Tr.PARSING){!this.fragCurrent&&this.state!==Tr.STOPPED&&this.state!==Tr.ERROR&&(this.state=Tr.IDLE);return}const{frag:n,part:i,level:a}=r,c=self.performance.now();n.stats.parsing.end=c,i&&(i.stats.parsing.end=c);const d=this.getLevelDetails(),l=d&&n.sn>d.endSN||this.shouldLoadParts(d,n.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${n.end}`),this.loadingParts=l),this.updateLevelTiming(n,i,a,e)}shouldLoadParts(e,r){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var n;const i=e.partList[0],a=i.end+(((n=e.fragmentHint)==null?void 0:n.duration)||0);if(r>=a&&this.playhead>i.start-i.fragment.duration)return!0}}return!1}getCurrentContext(e){const{levels:r,fragCurrent:n}=this,{level:i,sn:a,part:c}=e;if(!(r!=null&&r[i]))return this.warn(`Levels object was unset while buffering fragment ${a} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const d=r[i],p=d.details,l=c>-1?vpe(p,a,c):null,g=l?l.fragment:TO(p,a,n);return g?(n&&n!==g&&(g.stats=n.stats),{frag:g,part:l,level:d}):null}bufferFragmentData(e,r,n,i,a){if(this.state!==Tr.PARSING)return;Ko(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r);const{data1:c,data2:d}=e;let p=c;if(d&&(p=Kf(c,d)),!p.length)return;const l=this.initPTS[r.cc],g=l?-l.baseTime/l.timescale:void 0,v={type:e.type,frag:r,part:n,chunkMeta:i,offset:g,parent:r.type,data:p};if(this.hls.trigger(Ee.BUFFER_APPENDING,v),e.dropped&&e.independent&&!n){if(a)return;this.flushBufferGap(r)}}flushBufferGap(e){const r=this.media;if(!r)return;if(!xi.isBuffered(r,r.currentTime)){this.flushMainBuffer(0,e.start);return}const n=r.currentTime,i=xi.bufferInfo(r,n,0),a=e.duration,c=Math.min(this.config.maxFragLookUpTolerance*2,a*.25),d=Math.max(Math.min(e.start-c,i.end-c),n+c);e.start-d>c&&this.flushMainBuffer(d,e.start)}getFwdBufferInfo(e,r){var n;const i=this.playhead,c=this.lastCurrentTime>i||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,r,c)}getFwdBufferInfoAtPos(e,r,n,i){const a=xi.bufferInfo(e,r,i);if(a.len===0&&a.nextStart!==void 0){const c=this.fragmentTracker.getBufferedFrag(r,n);if(c&&(a.nextStart<=c.end||c.gap)){const d=Math.max(Math.min(a.nextStart,c.end)-r,i);return xi.bufferInfo(e,r,d)}}return a}getMaxBufferLength(e){const{config:r}=this;let n;return e?n=Math.max(8*r.maxBufferSize/e,r.maxBufferLength):n=r.maxBufferLength,Math.min(n,r.maxMaxBufferLength)}exceedsMaxBuffer(e,r,n){const i=e.nextStart;if(i&&n.start>i){const a=e.buffered;if(a){let c=e.len;const d=e.bufferedIndex;for(let p=a.length-1;p>d;p--)a[p].start=r}}return!1}reduceMaxBufferLength(e,r){const n=this.config,i=Math.max(Math.min(e-r,n.maxBufferLength),r/2),a=Math.max(e-r*3,n.maxMaxBufferLength/2,i);return a>=i?(n.maxMaxBufferLength=a,this.warn(`Reduce max buffer length to ${a}s`),!0):!1}getAppendedFrag(e){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(e,r){const n=r.fragments,i=n.length;if(!i)return null;const{config:a}=this,c=r.fragmentStart,d=a.lowLatencyMode&&!!r.partList;let p=null;if(r.live){const v=a.initialLiveManifestSize;if(i=c?(C=T,L=T===E?"config":"next load start"):j?(C=j,L="live edge"):(C=e,L="buffer pos"),C1))}getNextFragmentLoopLoading(e,r,n,i,a){let c=null;if(e.gap&&(c=this.getNextFragment(this.nextLoadPosition,r),c&&!c.gap&&n.nextStart)){const d=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,i,0);if(d!==null&&n.len+d.len>=a){const p=c.sn;return this.loopSn!==p&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${p}`),this.loopSn=p),null}}return this.loopSn=void 0,c}get primaryPrefetch(){if(e4(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,r){if(!e)return e;if(e4(this.config)&&("type"in e?e:e.fragment).type!==On.SUBTITLE){const n=this.hls.interstitialsManager,i=n==null?void 0:n.bufferingItem;if(i){const a=i.event;if(a){if(!a.appendInPlace&&(Math.abs(e.start-i.start)>1||i.start===0))return null}else if(e.end<=i.start&&(r==null?void 0:r.live)===!1||e.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||e.start-i.end>1))return null}if(NPe(e,n==null?void 0:n.playerQueue,this.playhead))return null}return e}getNextPart(e,r,n){let i=-1,a=!1,c=!0;for(let p=0,l=e.length;p-1&&n ${d.fragment.sn})`),i}loadedEndOfParts(e,r){let n;for(let i=e.length;i--;){if(n=e[i],!n.loaded)return!1;if(r>n.start)return!0}return!1}getInitialLiveFragment(e){const r=e.fragments,n=this.fragPrevious;let i=null;if(n){if(e.hasProgramDateTime&&(i=CBt(r,n.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`)),!i){const a=n.sn+1;if(a>=e.startSN&&a<=e.endSN){const c=r[a-e.startSN];n.cc===c.cc&&(i=c,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=hPe(e,n.cc,n.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const a=this.hls.liveSyncPosition;a!==null&&(i=this.getFragmentAtPosition(a,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,r,n){const{config:i}=this;let{fragPrevious:a}=this,{fragments:c,endSN:d}=n;const{fragmentHint:p}=n,{maxFragLookUpTolerance:l}=i,g=n.partList,v=!!(this.loadingParts&&g!=null&&g.length&&p);v&&!this.bitrateTest&&g[g.length-1].fragment.sn===p.sn&&(c=c.concat(p),d=p.sn),a&&this.fragmentTracker.getState(a)===wo.NOT_LOADED&&(a=null);let E;if(er-l||(T=this.media)!=null&&T.paused||this.loadingParts||!this.startFragRequested?0:l;E=HT(a,c,e,P)}else E=c[c.length-1];if(E){const j=E.sn,P=j-n.startSN,C=this.fragmentTracker.getState(E);if((C===wo.OK||C===wo.PARTIAL&&E.gap)&&(a=E),UI(E,a)&&(!v||g[0].fragment.sn>j||!n.live||!g.some(L=>L.fragment.sn===j&&!L.loaded&&!L.gap))){const L=c[P+1];E.sn${e.startSN} fragments: ${i}`),p}return a}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,r){let n=this.startPosition;n=0&&(n=this.nextLoadPosition),n}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var r;const n=(r=this.media)==null?void 0:r.currentTime;return yn(n)?n:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==On.MAIN)return!1;const r=this.getLevelDetails();return r?r.iframesOnly:(e=this.levelLastLoaded)==null?void 0:e.iframes}handleFragLoadAborted(e,r){this.transmuxer&&e.type===this.playlistType&&Ko(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${r?" part "+r.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.state!==Tr.STOPPED&&(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Tr.FRAG_LOADING_WAITING_RETRY)&&(this.state=Tr.IDLE)}onFragmentOrKeyLoadError(e,r){if(r.chunkMeta&&!r.frag){const O=this.getCurrentContext(r.chunkMeta);O&&(r.frag=O.frag)}const{frag:n,part:i}=r;if(!n||!this.levels||n.type!==e)return;if(this.fragContextChanged(n)){var a;this.warn(`Frag load error must match current frag to retry ${n.relurl} > ${(a=this.fragCurrent)==null?void 0:a.relurl}`);return}const c=r.details===Wt.FRAG_GAP;c&&this.fragmentTracker.addAsGap(n);const d=r.errorAction;if(!d){this.state=Tr.ERROR;return}const{action:p,flags:l,retryCount:g=0,retryConfig:v}=d,E=!!v,T=E&&p===ju.RetryRequest,j=E&&!d.resolved&&l&Zc.MoveAllAlternatesMatchingHost,P=this.hls.latestLevelDetails,C=P==null?void 0:P.live;if(!T&&j&&Ko(n)&&C&&n.sn=r||n&&!aP(0))&&(n&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Tr.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Tr.PARSING||this.state===Tr.PARSED){const r=e.frag,n=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,n),a=i&&i.len>.5;a&&this.reduceMaxBufferLength(i.len,(r==null?void 0:r.duration)||10);const c=!a;return c?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${n} buffer`):i.nextStart&&r&&i.nextStart>r.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,n===On.AUDIO?n:void 0),r&&(this.fragmentTracker.removeFragment(r),this.nextLoadPosition=r.start),this.resetLoadingState(),c}return!1}resetFragmentErrors(e){e===On.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Tr.STOPPED&&(this.state=Tr.IDLE)}afterBufferFlushed(e,r){if(!e)return;const n=xi.getBuffered(e);this.fragmentTracker.detectEvictedFragments(r,n,this.playlistType),this.state===Tr.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Tr.STOPPED&&(this.state=Tr.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.getLevelDetails();e!=null&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,r,n,i){const a=n.details;if(!a){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${r?" part: "+r.index:""} of ${this.fragInfo(e,!1,r)}`),!Object.keys(e.elementaryStreams).reduce((v,E)=>{const T=e.elementaryStreams[E];if(T){const j=T.endPTS-T.startPTS;if(j<=0)return this.warn(`Could not parse fragment ${e.sn} ${E} duration reliably (${j})`),v||!1;let P=0;return i.partial?r&&i.part===0&&(P=r.start-T.startPTS,e.startPTS=e.maxStartPTS=T.startPTS,e.startDTS=T.startDTS,e.start!==0&&e.setStart(T.startPTS),APe(a,e,P)):P=TPe(a,e,T.startPTS,T.endPTS,T.startDTS,T.endDTS,this.iframesOnly,this),this.hls.trigger(Ee.LEVEL_PTS_UPDATED,{details:a,level:n,drift:P,type:E,frag:e,part:r,start:T.startPTS,end:T.endPTS}),!0}return v},!1)){var d,p,l,g;const v=((d=this.transmuxer)==null?void 0:d.error)===null,E=((p=this.transmuxer)==null?void 0:p.error)!=null,T=((l=(g=this.levels)==null?void 0:g.length)!=null?l:0)>1;if((n.fragmentError===0||v&&(n.fragmentError<2||e.endList)||E&&T)&&this.treatAsGap(e,n),v){const j=new Error(`Found no media in ${this.playlistLabel()} ${e.level} ${r?`part: ${r.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(j.message),this.hls.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.FRAG_PARSING_ERROR,fatal:!1,error:j,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Tr.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${r?" part: "+r.index:""} of ${this.fragInfo(e,!1,r)}`),this.hls.trigger(Ee.FRAG_PARSED,{frag:e,part:r,chunkMeta:i})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,r=!0,n){var i,a;return`${e.type} playlist ${e.level} (${n?"part":"frag"}:[${(i=r&&!n?e.startPTS:(n||e).start)!=null?i:NaN}-${(a=r&&!n?e.endPTS:(n||e).end)!=null?a:NaN}]${n&&e.type==="main"?"INDEPENDENT="+(n.independent?"YES":"NO"):""})`}treatAsGap(e,r){r&&r.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){var r;const n=(r=e.loader)==null?void 0:r.stats;if(!n||n.total<=0)return!1;const i=n.loading.first>0,c=(n.total-n.loaded)*8/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&c<=.15}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const r=this._state;r!==e&&(this._state=e,this.log(`${r}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,r){let n=0;const{hls:i,media:a,config:c,levels:d,playlistType:p}=this,l=this.getLevelDetails();if(a&&!a.paused&&d){var g;const T=p===On.AUDIO?oPe(e.audioCodec,128e3):e.maxBitrate,j=1+i.ttfbEstimate/1e3,P=i.bandwidthEstimate*c.abrBandWidthUpFactor,C=l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||((g=this.fragCurrent)==null?void 0:g.duration)||6;n=j+T*C/P,e.details||(n+=j)}const v=this.playhead,E=!(l!=null&&l.live)||r.end-v>n*1.5;return{fetchdelay:n,okToFlushForwardBuffer:E}}scheduleTrackSwitch(e,r,n){const{media:i,playlistType:a}=this;if(!i||!e)return;const c=n?this.getBufferedFrag(this.playhead+r):null;if(c){const p=this.followingBufferedFrag(c);if(p){var d;this.abortCurrentFrag();const l=p.maxStartPTS?p.maxStartPTS:p.start,g=p.duration,v=Math.max(c.end,l+Math.min(Math.max(g-this.config.maxFragLookUpTolerance,g*(this.couldBacktrack?.5:.125)),g*(this.couldBacktrack?.75:.25)));if((((d=this.getLevelDetails())==null?void 0:d.fragmentStart)||0)>v)return;const T=a===On.MAIN?null:"audio";this.flushMainBuffer(v,Number.POSITIVE_INFINITY,T),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:e,playlistType:r}=this;if(!e)return;const n=this.getAppendedFrag(this.playhead);if(n&&n.start>1){const i=r===On.AUDIO;this.flushMainBuffer(0,n.start-(i?0:1),i?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){var e;const r=this.fragCurrent;switch(this.fragCurrent=null,r&&(r.abortRequests(),this.fragmentTracker.removeFragment(r)),this.state){case Tr.KEY_LOADING:case Tr.FRAG_LOADING:case Tr.FRAG_LOADING_WAITING_RETRY:case Tr.PARSING:case Tr.PARSED:this.state=Tr.IDLE;break}this.nextLoadPosition=(e=this.hls)!=null&&e.hasEnoughToStart?this.playhead:this.lastCurrentTime}checkFragPlaying(){const e=this.media;let r=null;if(e&&e.readyState>1&&e.seeking===!1){const n=e.currentTime;if(xi.isBuffered(e,n)?r=this.getAppendedFrag(n):xi.isBuffered(e,n+.1)&&(r=this.getAppendedFrag(n+.1)),r&&(this.backtrackFragment=void 0,!UI(r,this.fragPlaying)))return this.fragPlaying=r,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:e,media:r,hls:n,config:i,playlistType:a}=this;if(r!=null&&r.readyState&&e&&n&&i){const c=this.getBufferOutput(),d=this.getFwdBufferInfo(c,a);if(!d)return;const p=a===On.AUDIO?n.nextAudioTrack:n.nextLoadLevel,l=e[p],{fetchdelay:g,okToFlushForwardBuffer:v}=this.calculateOptimalSwitchPoint(l,d);this.scheduleTrackSwitch(d,g,v)}this.tickImmediate()}}function NPe(t,e,r){if(e)for(let n=e.length;n--;){const i=e[n].interstitial,a=i.startTime,c=Math.min(a+i.duration,i.resumeTime);if(i.appendInPlace&&(t.start>=a&&t.end<=c||r>t.start&&t.end>a&&t.start>2&15;if(c>12){const C=new Error(`invalid ADTS sampling index:${c}`);t.emit(Ee.ERROR,Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.FRAG_PARSING_ERROR,fatal:!0,error:C,reason:C.message});return}const d=(a>>6&3)+1,p=e[r+3]>>6&3|(a&1)<<2,l=i[c];let g=c;(d===5||d===29)&&(g-=3);let v;const E=(g&14)>>1,T=(g&1)<<7|p<<3;let j=0;if(d===1&&c>=6){j=5;const C=c-3;v=[j<<3|E,T|(C&14)>>1,(C&1)<<7|8,0]}else v=[d<<3|E,T];const P="mp4a.40."+(j||d);return la.log(`manifest codec:${n}, parsed codec:${P}, channels:${p}, rate:${l} (ADTS object type:${d} sampling index:${c} esds config:[${v.join(",")}])`),{config:v,samplerate:l,channelCount:p,codec:P,parsedCodec:P,manifestCodec:n}}function LPe(t,e){return t[e]===255&&(t[e+1]&246)===240}function DPe(t,e){return t[e+1]&1?7:9}function FQ(t,e){return(t[e+3]&3)<<11|t[e+4]<<3|(t[e+5]&224)>>>5}function kzt(t,e){return e+5=t.length)return!1;const n=FQ(t,e);if(n<=r)return!1;const i=e+n;return i===t.length||t4(t,i)}return!1}function MPe(t,e,r,n,i){if(!t.samplerate){const a=Azt(e,r,n,i);if(!a)return;La(t,a)}}function OPe(t){return 1024*9e4/t}function Czt(t,e){const r=DPe(t,e);if(e+r<=t.length){const n=FQ(t,e)-r;if(n>0)return{headerLength:r,frameLength:n}}}function FPe(t,e,r,n,i){const a=OPe(t.samplerate),c=n+i*a,d=Czt(e,r);let p;if(d){const{frameLength:v,headerLength:E}=d,T=E+v,j=Math.max(0,r+T-e.length);j?(p=new Uint8Array(T-E),p.set(e.subarray(r+E,e.length),0)):p=e.subarray(r+E,r+T);const P={unit:p,pts:c};return j||t.samples.push(P),{sample:P,length:T,missing:j}}const l=e.length-r;return p=new Uint8Array(l),p.set(e.subarray(r,e.length),0),{sample:{unit:p,pts:c},length:l,missing:-1}}let Pd=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Hp(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class BQ{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,r,n,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,r){return!1}appendFrame(e,r,n){}demux(e,r){this.cachedData&&(e=Kf(this.cachedData,e),this.cachedData=null);let n=oP(e,0),i=n?n.length:0,a;const c=this._audioTrack,d=this._id3Track,p=n?kQ(n):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&yn(p))&&(this.basePTS=Pzt(p,r,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),n&&n.length>0&&d.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Pd.audioId3,duration:Number.POSITIVE_INFINITY});i{if(yn(t))return t*90;const n=r?r.baseTime*9e4/r.timescale:0;return e*9e4+n},Nzt=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Rzt=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Lzt=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Dzt=[0,1,1,4];function BPe(t,e,r,n,i){if(r+24>e.length)return;const a=zPe(e,r);if(a&&r+a.frameLength<=e.length){const c=a.samplesPerFrame*9e4/a.sampleRate,d=n+i*c,p={unit:e.subarray(r,r+a.frameLength),pts:d,dts:d};return t.config=[],t.channelCount=a.channelCount,t.samplerate=a.sampleRate,t.samples.push(p),{sample:p,length:a.frameLength,missing:0}}}function zPe(t,e){const r=t[e+1]>>3&3,n=t[e+1]>>1&3,i=t[e+2]>>4&15,a=t[e+2]>>2&3;if(r!==1&&i!==0&&i!==15&&a!==3){const c=t[e+2]>>1&1,d=t[e+3]>>6,p=r===3?3-n:n===3?3:4,l=Nzt[p*14+i-1]*1e3,v=Rzt[(r===3?0:r===2?1:2)*3+a],E=d===3?1:2,T=Lzt[r][n],j=Dzt[n],P=T*8*j,C=Math.floor(T*l/v+c)*j,L=Sj();return!!L&&L<=87&&n===2&&l>=224e3&&d===0&&(t[e+3]=t[e+3]|128),{sampleRate:v,channelCount:E,frameLength:C,samplesPerFrame:P}}}function zQ(t,e){return t[e]===255&&(t[e+1]&224)===224&&(t[e+1]&6)!==0}function $Pe(t,e){return e+1{const p=new Uint8Array(d);i.set(p,16),this.decrypter.isSync()||this.decryptAacSamples(e,r+1,n)}).catch(n)}decryptAacSamples(e,r,n){for(;;r++){if(r>=e.length){n();return}if(!(e[r].unit.length<32)&&(this.decryptAacSample(e,r,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const r=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(r);let i=0;for(let a=32;a{a.data=this.getAvcDecryptedUnit(c,p),this.decrypter.isSync()||this.decryptAvcSamples(e,r,n+1,i)}).catch(i)}decryptAvcSamples(e,r,n,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;r++,n=0){if(r>=e.length){i();return}const a=e[r].units;for(;!(n>=a.length);n++){const c=a[n];if(!(c.data.length<=48||c.type!==1&&c.type!==5)&&(this.decryptAvcSample(e,r,n,i,c),!this.decrypter.isSync()))return}}}}class Ozt extends BQ{constructor(e,r){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=r}resetInitSegment(e,r,n,i){super.resetInitSegment(e,r,n,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,r){if(!e)return!1;const n=oP(e,0);let i=(n==null?void 0:n.length)||0;if(UPe(e,i))return!1;for(let a=e.length;i{a.decryptAacSamples(i.audioTrack.samples,0,()=>{c(i)})})}}const qPe=(t,e)=>{let r=0,n=5;e+=n;const i=new Uint32Array(1),a=new Uint32Array(1),c=new Uint8Array(1);for(;n>0;){c[0]=t[e];const d=Math.min(n,8),p=8-d;a[0]=4278190080>>>24+p<>p,r=r?r<e.length||e[r]!==11||e[r+1]!==119)return-1;const a=e[r+4]>>6;if(a>=3)return-1;const d=[48e3,44100,32e3][a],p=e[r+4]&63,g=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][p*3+a]*2;if(r+g>e.length)return-1;const v=e[r+6]>>5;let E=0;v===2?E+=2:(v&1&&v!==1&&(E+=2),v&4&&(E+=2));const T=(e[r+6]<<8|e[r+7])>>12-E&1,P=[2,1,2,3,3,4,4,5][v]+T,C=e[r+5]>>3,L=e[r+5]&7,O=new Uint8Array([a<<6|C<<1|L>>2,(L&3)<<6|v<<3|T<<2|p>>4,p<<4&224]),F=1536/d*9e4,$=n+i*F,G=e.subarray(r,r+g);return t.config=O,t.channelCount=P,t.samplerate=d,t.samples.push({unit:G,pts:$}),g}class Bzt extends BQ{resetInitSegment(e,r,n,i){super.resetInitSegment(e,r,n,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const r=oP(e,0);let n=(r==null?void 0:r.length)||0;if(r&&e[n]===11&&e[n+1]===119&&kQ(r)!==void 0&&qPe(e,n)<=16)return!1;for(let i=e.length;n{const c=X5t(a);if(zzt.test(c.schemeIdUri)){const d=Epe(c,r);let p=c.eventDuration===4294967295?Number.POSITIVE_INFINITY:c.eventDuration/c.timeScale;p<=.001&&(p=Number.POSITIVE_INFINITY);const l=c.payload;n.samples.push({data:l,len:l.byteLength,dts:d,pts:d,type:Pd.emsg,duration:p})}else if(this.config.enableEmsgKLVMetadata){const d=this.config.emsgKLVSchemaUri||Pd.misbklv;if(c.schemeIdUri.startsWith(d)){const p=Epe(c,r);n.samples.push({data:c.payload,len:c.payload.byteLength,dts:p,pts:p,type:Pd.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return n}demuxSampleAes(e,r,n){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}function Epe(t,e){return yn(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}const Uzt=1,Vzt=2,qzt=3,EI=-1;class HPe{constructor(){this.VideoSample=null}createVideoSample(e,r,n){return{key:e,frame:!1,pts:r,dts:n,units:[],length:0}}getLastNalUnit(e){var r;let n=this.VideoSample,i;if((!n||n.units.length===0)&&(n=e[e.length-1]),(r=n)!=null&&r.units){const a=n.units;i=a[a.length-1]}return i}pushAccessUnit(e,r){if(e.units.length&&e.frame){if(e.pts===void 0){const n=r.samples,i=n.length;if(i){const a=n[i-1];e.pts=a.pts,e.dts=a.dts}else{r.dropped++;return}}r.samples.push(e)}}parseNALu(e,r,n){const i=r.byteLength;if(i===0)return[];const a=e.naluState||0,c=a===EI?0:a,d=[];let p=0,l=0,g=-1,v=0;for(a===EI&&(g=0,v=this.getNALuType(r,0),l=1);l0&&r[T-1]===0;)T--;const j=E-T+(T===0?c:0);if(j=0)d.push({data:r.subarray(g,T),type:v});else{const O=this.getLastNalUnit(e.samples);O&&(T>0?O.data=Kf(O.data,r.subarray(0,T)):L>0&&(O.data=O.data.subarray(0,O.data.byteLength-L)),O.state=0)}if(l0&&r[E-1]===0;)E--;p=i-E+(E===0?c:0)}if(g>=0)d.push({data:r.subarray(g),type:v,state:p});else if(d.length===0&&p!==EI){const E=this.getLastNalUnit(e.samples);E&&(E.data=Kf(E.data,r),E.state=p)}return e.naluState=p,d}}class Aj{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,r=this.bytesAvailable,n=e.byteLength-r,i=new Uint8Array(4),a=Math.min(4,r);if(a===0)throw new Error("no bytes available");i.set(e.subarray(n,n+a)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=a*8,this.bytesAvailable-=a}skipBits(e){let r;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,r=e>>3,e-=r<<3,this.bytesAvailable-=r,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let r=Math.min(this.bitsAvailable,e);const n=this.word>>>32-r;if(e>32&&la.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=r,this.bitsAvailable>0)this.word<<=r;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return r=e-r,r>0&&this.bitsAvailable?n<>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}}class Gzt extends HPe{parsePES(e,r,n,i,a){const c=a.iframe,d=this.parseNALu(e,n.data,i);let p=this.VideoSample,l,g=!1;n.data=null,p&&d.length&&!e.audFound&&(this.pushAccessUnit(p,e),p=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),d.forEach(v=>{var E,T;switch(v.type){case 1:{if(c)break;let L=!1;l=!0;const O=v.data;if(g&&O.length>4){const F=this.readSliceType(O);(F===2||F===4||F===7||F===9)&&(L=!0)}if(L){var j;(j=p)!=null&&j.frame&&!p.key&&(this.pushAccessUnit(p,e),p=this.VideoSample=null)}p||(p=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),p.frame=!0,p.key=L;break}case 5:l=!0,(E=p)!=null&&E.frame&&!p.key&&(this.pushAccessUnit(p,e),p=this.VideoSample=null),p||(p=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),p.key=!0,p.frame=!0;break;case 6:{if(c)break;l=!0,lP(v.data,1,n.pts,r.samples);break}case 7:{var P,C;l=!0,g=!0;const L=v.data,O=this.readSPS(L);if(!e.sps||e.width!==O.width||e.height!==O.height||((P=e.pixelRatio)==null?void 0:P[0])!==O.pixelRatio[0]||((C=e.pixelRatio)==null?void 0:C[1])!==O.pixelRatio[1]){e.width=O.width,e.height=O.height,e.pixelRatio=O.pixelRatio,e.sps=[L];const F=L.subarray(1,4);let $="avc1.";for(let G=0;G<3;G++){let W=F[G].toString(16);W.length<2&&(W="0"+W),$+=W}e.codec=$}break}case 8:l=!0,e.pps=[v.data];break;case 9:l=!0,e.audFound=!0,(T=p)!=null&&T.frame&&(this.pushAccessUnit(p,e),p=null),p||(p=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;case 12:l=!0;break;default:l=!1;break}p&&l&&p.units.push(v)}),i&&p&&(this.pushAccessUnit(p,e),this.VideoSample=null)}getNALuType(e,r){return e[r]&31}readSliceType(e){const r=new Aj(e);return r.readUByte(),r.readUEG(),r.readUEG()}skipScalingList(e,r){let n=8,i=8,a;for(let c=0;c(c=this.VideoSample=this.createVideoSample(g,n.pts,n.dts),c);a.forEach((g,v)=>{var E,T;if(this.startsNewAccessUnit(c,e,g,v)){this.pushAccessUnit(c,e);const P=g.type>=16&&g.type<=23;c=l(P),p=!1}switch(g.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:c||(c=l(!1)),c.frame=!0,d=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(d=!0,p){var j;(j=c)!=null&&j.frame&&!c.key&&(this.pushAccessUnit(c,e),c=this.VideoSample=null)}c||(c=l(!0)),c.key=!0,c.frame=!0;break;case 19:case 20:d=!0,(E=c)!=null&&E.frame&&!c.key&&(this.pushAccessUnit(c,e),c=this.VideoSample=null),c||(c=l(!0)),c.key=!0,c.frame=!0;break;case 39:d=!0,lP(g.data,2,n.pts,r.samples);break;case 32:d=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=La(e.params,this.readVPS(g.data)),this.initVPS=g.data),e.vps=[g.data];break;case 33:if(d=!0,p=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],g.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const P=this.readSPS(g.data);e.width=P.width,e.height=P.height,e.pixelRatio=P.pixelRatio,e.codec=P.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const C in P.params)e.params[C]=P.params[C]}this.pushParameterSet(e.sps,g.data,e.vps),c||(c=l(!1));break;case 34:if(d=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const P=this.readPPS(g.data);for(const C in P)e.params[C]=P[C]}this.pushParameterSet(e.pps,g.data,e.vps)}break;case 35:d=!0,e.audFound=!0,(T=c)!=null&&T.frame&&(this.pushAccessUnit(c,e),c=null),c||(c=l(!1));break;default:d=!1;break}c&&d&&c.units.push(g)}),i&&c&&(this.pushAccessUnit(c,e),this.VideoSample=null)}pushParameterSet(e,r,n){(n&&n[0]===this.initVPS||!n&&!e.length)&&e.push(r)}startsNewAccessUnit(e,r,n,i){if(!e)return!1;if(!r.audFound&&i===0)return!0;if(!e.frame)return!1;const{type:a,data:c}=n;return a>=32&&a<=35||a===39||a>=41&&a<=44||a>=48&&a<=55?!0:a<=31&&c.length>2&&(c[2]&128)!==0}getNALuType(e,r){return(e[r]&126)>>>1}ebsp2rbsp(e){const r=new Uint8Array(e.byteLength);let n=0;for(let i=0;i=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(r[n]=e[i],n++);return new Uint8Array(r.buffer,0,n)}pushAccessUnit(e,r){super.pushAccessUnit(e,r),this.initVPS&&(this.initVPS=null)}readVPS(e){const r=new Aj(e);r.readUByte(),r.readUByte(),r.readBits(4),r.skipBits(2),r.readBits(6);const n=r.readBits(3),i=r.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:i}}readSPS(e){const r=new Aj(this.ebsp2rbsp(e));r.readUByte(),r.readUByte(),r.readBits(4);const n=r.readBits(3);r.readBoolean();const i=r.readBits(2),a=r.readBoolean(),c=r.readBits(5),d=r.readUByte(),p=r.readUByte(),l=r.readUByte(),g=r.readUByte(),v=r.readUByte(),E=r.readUByte(),T=r.readUByte(),j=r.readUByte(),P=r.readUByte(),C=r.readUByte(),L=r.readUByte(),O=[],F=[];for(let tr=0;tr0)for(let tr=n;tr<8;tr++)r.readBits(2);for(let tr=0;tr1&&r.readEG();for(let Fn=0;Fn0&&Ar<16?(Ae=Tn[Ar-1],He=mn[Ar-1]):Ar===255&&(Ae=r.readBits(16),He=r.readBits(16))}if(r.readBoolean()&&r.readBoolean(),r.readBoolean()&&(r.readBits(3),r.readBoolean(),r.readBoolean()&&(r.readUByte(),r.readUByte(),r.readUByte())),r.readBoolean()&&(r.readUEG(),r.readUEG()),r.readBoolean(),r.readBoolean(),r.readBoolean(),vt=r.readBoolean(),vt&&(r.skipUEG(),r.skipUEG(),r.skipUEG(),r.skipUEG()),r.readBoolean()&&(nt=r.readBits(32),tt=r.readBits(32),r.readBoolean()&&r.readUEG(),r.readBoolean())){const mn=r.readBoolean(),li=r.readBoolean();let Lr=!1;(mn||li)&&(Lr=r.readBoolean(),Lr&&(r.readUByte(),r.readBits(5),r.readBoolean(),r.readBits(5)),r.readBits(4),r.readBits(4),Lr&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let Or=0;Or<=n;Or++){ot=r.readBoolean();const si=ot||r.readBoolean();let ss=!1;si?r.readEG():ss=r.readBoolean();const ps=ss?1:r.readUEG()+1;if(mn)for(let Mi=0;Mi>tr&1)<<31-tr)>>>0;let ir=Kt.toString(16);return c===1&&ir==="2"&&(ir="6"),{codecString:`hvc1.${cr}${c}.${ir}.${a?"H":"L"}${L}.B0`,params:{general_tier_flag:a,general_profile_idc:c,general_profile_space:i,general_profile_compatibility_flags:[d,p,l,g],general_constraint_indicator_flags:[v,E,T,j,P,C],general_level_idc:L,bit_depth:pe+8,bit_depth_luma_minus8:pe,bit_depth_chroma_minus8:Le,min_spatial_segmentation_idc:ke,chroma_format_idc:$,frame_rate:{fixed:ot,fps:tt/nt}},width:Ct,height:Bt,pixelRatio:[Ae,He]}}readPPS(e){const r=new Aj(this.ebsp2rbsp(e));r.readUByte(),r.readUByte(),r.skipUEG(),r.skipUEG(),r.skipBits(2),r.skipBits(3),r.skipBits(2),r.skipUEG(),r.skipUEG(),r.skipEG(),r.skipBits(2),r.readBoolean()&&r.skipUEG(),r.skipEG(),r.skipEG(),r.skipBits(4);const i=r.readBoolean(),a=r.readBoolean();let c=1;return a&&i?c=0:a?c=3:i&&(c=2),{parallelismType:c}}matchSPS(e,r){return np(e).substring(3)===np(r).substring(3)}}const nc=188;class vy{constructor(e,r,n,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=r,this.typeSupported=n,this.logger=i,this.videoParser=null}static probe(e,r){const n=vy.syncOffset(e);return n>0&&r.warn(`MPEG2-TS detected but first sync word found @ offset ${n}`),n!==-1}static syncOffset(e){const r=e.length;let n=Math.min(nc*5,r-nc)+1,i=0;for(;i1&&(c===0&&d>2||p+nc>n))return c}else{if(d)return-1;break}i++}return-1}static createTrack(e,r){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:GCe[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?r:void 0}}resetInitSegment(e,r,n,i,a,c){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=vy.createTrack("video"),this._videoTrack.duration=i,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new Yzt(this.logger):null,this._audioTrack=vy.createTrack("audio",i),this._id3Track=vy.createTrack("id3"),this._txtTrack=vy.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n,e&&this.demux(e,0,c,(a==null?void 0:a.method)==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:r,_id3Track:n}=this;e&&(e.pesData=null),r&&(r.pesData=null),n&&(n.pesData=null),this.videoParser=null,this.aacOverFlow=null,this.remainderData=null}demux(e,r,n,i=!1,a=!1){i||(this.sampleAes=null);let c;const d=this._videoTrack,p=this.videoIntegrityChecker,l=this._audioTrack,g=this._id3Track,v=this._txtTrack,E=n.iframe;let T=d.pid,j=d.pesData,P=l.pid,C=g.pid,L=this._klvPid,O=l.pesData,F=g.pesData,$=null,G=null,W=this.pmtParsed,Z=this._pmtId,Q=e.length;if(this.remainderData&&(e=Kf(this.remainderData,e),Q=e.length,this.remainderData=null),Q>4;let Ie;if(Re>1){if(Ie=pe+5+e[pe+4],Ie===pe+nc)continue}else Ie=pe+4;switch(be){case T:Le&&(j&&!(p!=null&&p.isCorrupted)&&(c=cb(j,this.logger))&&(this.readyVideoParser(d.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(d,v,c,!1,n)),j={data:[],size:0},p==null||p.reset(T)),p==null||p.handlePacket(e.subarray(pe)),j&&(j.data.push(e.subarray(Ie,pe+nc)),j.size+=pe+nc-Ie);break;case P:if(E)break;if(Le){if(O&&(c=cb(O,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,c,n);break;case"mp3":this.parseMPEGPES(l,c);break;case"ac3":this.parseAC3PES(l,c);break}O={data:[],size:0}}O&&(O.data.push(e.subarray(Ie,pe+nc)),O.size+=pe+nc-Ie);break;case C:if(E)break;Le&&(F&&(c=cb(F,this.logger))&&this.parseID3PES(g,c),F={data:[],size:0}),F&&(F.data.push(e.subarray(Ie,pe+nc)),F.size+=pe+nc-Ie);break;case L:if(E)break;Le&&($&&(c=cb($,this.logger))&&this.parseKlvPES(g,c),$={data:[],size:0}),$&&($.data.push(e.subarray(Ie,pe+nc)),$.size+=pe+nc-Ie);break;case 0:Le&&(Ie+=e[Ie]+1),Z=this._pmtId=Wzt(e,Ie);break;case Z:{Le&&(Ie+=e[Ie]+1);const Te=Kzt(e,Ie,this.typeSupported,i,this.observer,this.logger,this.config,n);T=Te.videoPid,T>0&&(d.pid=T,d.segmentCodec=Te.segmentVideoCodec),P=Te.audioPid,P>0&&(l.pid=P,l.segmentCodec=Te.segmentAudioCodec),C=Te.id3Pid,C>0&&(g.pid=C),L=Te.klvPid,L>0&&(this._klvPid=L),G!==null&&!W&&(this.logger.warn(`MPEG-TS PMT found at ${pe} after unknown PID '${G}'. Backtracking to sync byte @${ee} to parse all TS packets.`),G=null,pe=ee-188),W=this.pmtParsed=!0;break}case 17:case 8191:break;default:G=be;break}}else ie++;ie>0&&kH(this.observer,new Error(`Found ${ie} TS packet/s that do not start with 0x47`),n,void 0,this.logger),d.pesData=j,l.pesData=O,g.pesData=F;const oe={audioTrack:l,videoTrack:d,id3Track:g,textTrack:v};return a&&this.extractRemainingSamples(oe,n),oe}flush(e,r){const{remainderData:n}=this;this.remainderData=null;let i;return n?i=this.demux(n,0,r,!1,!0):i={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i,r),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(e,r){const{audioTrack:n,videoTrack:i,id3Track:a,textTrack:c}=e,d=i.pesData,p=n.pesData,l=a.pesData,g=this.videoIntegrityChecker;let v;if(d&&!(g!=null&&g.isCorrupted)&&(v=cb(d,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,c,v,!0,r),i.pesData=null)):i.pesData=d,p&&(v=cb(p,this.logger))){switch(n.segmentCodec){case"aac":this.parseAACPES(n,v,r);break;case"mp3":this.parseMPEGPES(n,v);break;case"ac3":this.parseAC3PES(n,v);break}n.pesData=null}else p!=null&&p.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),n.pesData=p;l&&(v=cb(l,this.logger))?(this.parseID3PES(a,v),a.pesData=null):a.pesData=l}demuxSampleAes(e,r,n,i){const a=this.demux(e,n,i,!0,!this.config.progressive),c=this.sampleAes=new VPe(this.observer,this.config,r);return this.decrypt(a,c)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Gzt:e==="hevc"&&(this.videoParser=new Hzt))}decrypt(e,r){return new Promise(n=>{const{audioTrack:i,videoTrack:a}=e;i.samples&&i.segmentCodec==="aac"?r.decryptAacSamples(i.samples,0,()=>{a.samples?r.decryptAvcSamples(a.samples,0,0,()=>{n(e)}):n(e)}):a.samples&&r.decryptAvcSamples(a.samples,0,0,()=>{n(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,r,n){let i=0;const a=this.aacOverFlow;let c=r.data;if(a){this.aacOverFlow=null;const E=a.missing,T=a.sample.unit.byteLength;if(E===-1)c=Kf(a.sample.unit,c);else{const j=T-E;a.sample.unit.set(c.subarray(0,E),j),e.samples.push(a.sample),i=a.missing}}let d,p;for(d=i,p=c.length;d0;)d+=p}}parseID3PES(e,r){if(r.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=La({},r,{type:this._videoTrack?Pd.emsg:Pd.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}parseKlvPES(e,r){var n;const i=(n=r.pts)!=null?n:r.dts;if(i===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}const a=r.data;if(a.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let c=0;for(;ca.length)break;const p=c;if(c+=16,c>=a.length)break;const l=a[c];c+=1;let g=0;if(l&128){const j=l&127;if(j===0||j>4||c+j>a.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let P=0;Pa.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const v=c+g,E=a.subarray(p,v),T={data:E,len:E.byteLength,pts:i,dts:(d=r.dts)!=null?d:i,type:Pd.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(T),c=v}}}function r4(t,e){return((t[e+1]&31)<<8)+t[e+2]}function Wzt(t,e){return(t[e+10]&31)<<8|t[e+11]}function Kzt(t,e,r,n,i,a,c,d){const p={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},l=(t[e+1]&15)<<8|t[e+2],g=e+3+l-4,v=(t[e+10]&15)<<8|t[e+11];for(e+=12+v;e0){let j=e+5,P=T;for(;P>2;){switch(t[j]){case 106:p.audioPid===-1&&(r.ac3!==!0?a.log("AC-3 audio found, not supported in this browser for now"):(p.audioPid=E,p.segmentAudioCodec="ac3"));break;case 5:p.klvPid===-1&&c.enableEmsgKLVMetadata&&(p.klvPid=E,a.log(`KLV metadata PID found: ${E}`));break}const L=t[j+1]+2;j+=L,P-=L}}break;case 194:case 135:return kH(i,new Error("Unsupported EC-3 in M2TS found"),d,void 0,a),p;case 36:p.videoPid===-1&&(p.videoPid=E,p.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"));break}e+=T+5}return p}function kH(t,e,r,n,i){i.warn(`parsing error: ${e.message}`),t.emit(Ee.ERROR,Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,chunkMeta:r,error:e,reason:e.message})}function l8(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function cb(t,e){let r=0,n,i,a,c,d;const p=t.data;if(!t||t.size===0)return null;for(;p[0].length<19&&p.length>1;)p[0]=Kf(p[0],p[1]),p.splice(1,1);if(n=p[0],(n[0]<<16)+(n[1]<<8)+n[2]===1){if(i=(n[4]<<8)+n[5],i&&i>t.size-6)return null;const g=n[7];g&192&&(c=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,g&64?(d=(n[14]&14)*536870912+(n[15]&255)*4194304+(n[16]&254)*16384+(n[17]&255)*128+(n[18]&254)/2,c-d>60*9e4&&(e.warn(`${Math.round((c-d)/9e4)}s delta between PTS and DTS, align them`),c=d)):d=c),a=n[8];let v=a+9;if(t.size<=v)return null;t.size-=v;const E=new Uint8Array(t.size);for(let T=0,j=p.length;TP){v-=P;continue}else n=n.subarray(v),P-=v,v=0;E.set(n,r),r+=P}return i&&(i-=a+3),{data:E,pts:c,dts:d,len:i}}return null}class Yzt{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return this.integrityState!=="ok"}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;const r=r4(e,0);if(r!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${r}`);return}const n=(e[3]&48)>>4;if(n===0)return;const i=e[3]&15,a=this.lastContinuityCounter;this.lastContinuityCounter=i;const c=(n&1)!=0;if((n&2)!=0&&e[4]!=0&&(e[5]&128)!=0||a<0)return;const l=c?a+1&15:a;if(i!==l){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${r}', CC=${i}, Expected-CC=${l} Last-CC=${a}`),this.integrityState="cc-failed";return}if(e[1]&128){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${r}'`),this.integrityState="tei-bit";return}}}class Zzt{static getSilentFrame(e,r){switch(e){case"mp4a.40.2":if(r===1)return new Uint8Array([0,200,0,128,35,128]);if(r===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(r===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(r===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(r===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(r===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(r===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(r===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(r===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}var n4;const Xzt={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},c8=new Uint8Array([0,0,0,0,0,0,0,0]),Qzt=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Jzt=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e$t=new Uint8Array([0,0,0,0,0,0,0,0]),TI=new Uint8Array([0,0,0,0,0,0,0,1]),Tpe=new Uint8Array([105,115,111,109]),t$t=new Uint8Array([97,118,99,49]),r$t=new Uint8Array([0,0,0,1]);class bn{static box(e,...r){let n=8,i=r.length;const a=i;for(;i--;)n+=r[i].byteLength;const c=new Uint8Array(n);for(Ul(c,0,n),Ul(c,4,e),i=0,n=8;i>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return bn.box(Ai.mdia,bn.mdhd(e.timescale||0,e.duration||0),bn.hdlr(e.type),bn.minf(e))}static mfhd(e){return bn.box(Ai.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?bn.box(Ai.minf,bn.box(Ai.smhd,e$t),bn.DINF,bn.stbl(e)):bn.box(Ai.minf,bn.box(Ai.vmhd,Jzt),bn.DINF,bn.stbl(e))}static moof(e,r,n){return bn.box(Ai.moof,bn.mfhd(e),bn.traf(n,r))}static moov(e){let r=e.length;const n=[];for(;r--;)n[r]=bn.trak(e[r]);return bn.box.apply(null,[Ai.moov,bn.mvhd(e[0].timescale||0,e[0].duration||0)].concat(n).concat(bn.mvex(e)))}static mvex(e){let r=e.length;const n=[];for(;r--;)n[r]=bn.trex(e[r]);return bn.box.apply(null,[Ai.mvex,...n])}static mvhd(e,r){r*=e;const n=Math.floor(r/(Bp+1)),i=Math.floor(r%(Bp+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return bn.box(Ai.mvhd,a)}static sdtp(e){const r=e.samples||[],n=new Uint8Array(4+r.length);let i,a;for(i=0;i>>8&255),r.push(c&255),r=r.concat(Array.prototype.slice.call(a));for(i=0;i>>8&255),n.push(c&255),n=n.concat(Array.prototype.slice.call(a));const d=bn.box(Ai.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),p=e.width,l=e.height,g=e.pixelRatio[0],v=e.pixelRatio[1];return bn.box(Ai.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,p>>8&255,p&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,bn.box(Ai.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),bn.box(Ai.pasp,new Uint8Array([g>>24,g>>16&255,g>>8&255,g&255,v>>24,v>>16&255,v>>8&255,v&255])))}static esds(e){const r=e.config,n=r.length;return new Uint8Array([0,0,0,0,3,23+n,0,1,0,4,15+n,64,21,0,0,0,0,0,0,0,0,0,0,0,5,n,...r,6,1,2])}static audioStsd(e){const r=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,r>>8&255,r&255,0,0])}static mp4a(e){return bn.box(Ai.mp4a,bn.audioStsd(e),bn.box(Ai.esds,bn.esds(e)))}static mp3(e){return bn.box(Ai[".mp3"],bn.audioStsd(e))}static ac3(e){return bn.box(Ai["ac-3"],bn.audioStsd(e),bn.box(Ai.dac3,e.config))}static stsd(e){const{segmentCodec:r}=e;if(e.type==="audio"){if(r==="aac")return bn.box(Ai.stsd,TI,bn.mp4a(e));if(r==="ac3"&&e.config)return bn.box(Ai.stsd,TI,bn.ac3(e));if(r==="mp3"&&e.codec==="mp3")return bn.box(Ai.stsd,TI,bn.mp3(e))}else if(e.pps&&e.sps){if(r==="avc")return bn.box(Ai.stsd,TI,bn.avc1(e));if(r==="hevc"&&e.vps)return bn.box(Ai.stsd,TI,bn.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${r}/${e.codec})`)}static tkhd(e){const r=e.id,n=(e.duration||0)*(e.timescale||0),i=e.width||0,a=e.height||0,c=Math.floor(n/(Bp+1)),d=Math.floor(n%(Bp+1));return bn.box(Ai.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,r&255,0,0,0,0,c>>24,c>>16&255,c>>8&255,c&255,d>>24,d>>16&255,d>>8&255,d&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,a>>8&255,a&255,0,0]))}static traf(e,r){const n=bn.sdtp(e),i=e.id,a=Math.floor(r/(Bp+1)),c=Math.floor(r%(Bp+1));return bn.box(Ai.traf,bn.box(Ai.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),bn.box(Ai.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,c>>24,c>>16&255,c>>8&255,c&255])),bn.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,bn.box(Ai.trak,bn.tkhd(e),bn.mdia(e))}static trex(e){const r=e.id;return bn.box(Ai.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,r){const n=e.samples||[],i=n.length,a=12+16*i,c=new Uint8Array(a);let d,p,l,g,v,E;for(r+=8+a,c.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255],0),d=0;d>>24&255,l>>>16&255,l>>>8&255,l&255,g>>>24&255,g>>>16&255,g>>>8&255,g&255,v.isLeading<<2|v.dependsOn,v.isDependedOn<<6|v.hasRedundancy<<4|v.paddingValue<<1|v.isNonSync,v.degradPrio&61440,v.degradPrio&15,E>>>24&255,E>>>16&255,E>>>8&255,E&255],12+16*d);return bn.box(Ai.trun,c)}static initSegment(e){const r=bn.moov(e);return Kf(bn.FTYP,r)}static hvc1(e){const r=e.params,n=[e.vps,e.sps,e.pps],i=4,a=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),i-1|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),n.length]);let c=a.length;for(let j=0;j>8,n[j][P].length&255]),c),c+=2,d.set(n[j][P],c),c+=n[j][P].length}const l=bn.box(Ai.hvcC,d),g=e.width,v=e.height,E=e.pixelRatio[0],T=e.pixelRatio[1];return bn.box(Ai.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,g>>8&255,g&255,v>>8&255,v&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,bn.box(Ai.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),bn.box(Ai.pasp,new Uint8Array([E>>24,E>>16&255,E>>8&255,E&255,T>>24,T>>16&255,T>>8&255,T&255])))}}n4=bn;bn.FTYP=n4.box(Ai.ftyp,Tpe,r$t,Tpe,t$t);bn.DINF=n4.box(Ai.dinf,n4.box(Ai.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));const WPe=9e4;function $Q(t,e,r=1,n=!1){const i=t*e*r;return n?Math.round(i):i}function n$t(t,e,r=1,n=!1){return $Q(t,e,1/r,n)}function AI(t,e=!1){return $Q(t,1e3,1/WPe,e)}function i$t(t,e=1){return $Q(t,WPe,1/e)}function Ape(t){const{baseTime:e,timescale:r,trackId:n}=t;return`${e/r} (${e}/${r}) trackId: ${n}`}const s$t=10*1e3,a$t=1024,o$t=1152,l$t=1536,IH=8589934592;function kpe(t,e,r,n){return{duration:e,size:r,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1,paddingValue:0}}}class AO extends ff{constructor(e,r,n,i){super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=r,this.typeSupported=n,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const r=this._initPTS;(!r||!e||e.trackId!==r.trackId||e.baseTime!==r.baseTime||e.timescale!==r.timescale)&&this.log(`Reset initPTS: ${r&&Ape(r)} > ${e&&Ape(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let r=!1;const n=e[0].pts,i=e.reduce((a,c)=>{let d=c.pts,p=d-a;return p<-4294967296&&(r=!0,d=zh(d,n),p=d-a),p>0?a:d},n);return r&&this.debug("PTS rollover detected"),i}remux(e,r,n,i,a,c,d,p,l){let g,v,E,T,j,P,C=a,L=a;const F=!l.iframe&&e.pid>-1,$=r.pid>-1,G=r.samples.length,W=e.samples.length>0,Z=d&&G>0||G>1;if((!F||W)&&(!$||Z)||this.ISGenerated||d){if(this.ISGenerated){var ee,ie,oe,pe;const Ie=this.videoTrackConfig;(Ie&&(r.width!==Ie.width||r.height!==Ie.height||((ee=r.pixelRatio)==null?void 0:ee[0])!==((ie=Ie.pixelRatio)==null?void 0:ie[0])||((oe=r.pixelRatio)==null?void 0:oe[1])!==((pe=Ie.pixelRatio)==null?void 0:pe[1]))||!Ie&&Z||this.nextAudioTs===null&&W)&&this.resetInitSegment()}this.ISGenerated||(E=this.generateIS(e,r,a,c));const Le=this.isVideoContiguous;let be=-1,Re;if(Z&&(be=c$t(r.samples),!Le&&this.config.forceKeyFrameOnDiscontinuity))if(P=!0,be>0){this.warn(`Dropped ${be} out of ${G} video samples due to a missing keyframe`);const Ie=this.getVideoStartPts(r.samples);r.samples=r.samples.slice(be),r.dropped+=be,L+=(r.samples[0].pts-Ie)/r.inputTimeScale,Re=L}else be===-1&&(this.warn(`No keyframe found out of ${G} video samples`),P=!1);if(this.ISGenerated){if(W&&Z&&a){const Ie=this.getVideoStartPts(r.samples),ge=(zh(e.samples[0].pts,Ie)-Ie)/r.inputTimeScale;C+=Math.max(0,ge),L+=Math.max(0,-ge)}if(W){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),E=this.generateIS(e,r,a,c)),v=this.remuxAudio(e,C,this.isAudioContiguous,c,$||Z||p===On.AUDIO?L:void 0,l),Z){const Ie=v?v.endPTS-v.startPTS:0;r.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),E=this.generateIS(e,r,a,c)),g=this.remuxVideo(r,L,Le,Ie,l)}}else Z&&(g=this.remuxVideo(r,L,Le,0,l));g&&(g.firstKeyFrame=be,g.independent=be!==-1,g.firstKeyFramePTS=Re)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(j=KPe(n,a,this._initPTS,this._initDTS)),i.samples.length&&(T=YPe(i,a,this._initPTS))),{audio:v,video:g,initSegment:E,independent:P,text:T,id3:j}}computeInitPts(e,r,n,i){const a=Math.round(n*r);let c=zh(e,a);if(c0?ke-1:ke].dts&&(F=!0)}F&&d.sort(function(ke,Ae){const He=ke.dts-Ae.dts,ot=ke.pts-Ae.pts;return He||ot}),P=d[0].dts,C=d[d.length-1].dts;const G=C-P,W=G?Math.round(G/(l-1)):j||e.inputTimeScale/30;if(n){const ke=P-$,Ae=ke>W,He=ke<-1;if((Ae||He)&&(Ae?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${AI(ke,!0)} ms (${ke}dts) hole between fragments detected at ${r.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${AI(-ke,!0)} ms (${ke}dts) overlapping between fragments detected at ${r.toFixed(3)}`),!He||$>=d[0].pts||Sj())){P=$;const ot=d[0].pts-ke;if(Ae)d[0].dts=P,d[0].pts=ot;else{let nt=!0;for(let tt=0;ttot&&nt);tt++){const vt=d[tt].pts;if(d[tt].dts-=ke,d[tt].pts-=ke,tt0?Ae.dts-d[ke-1].dts:W;if(nt=ke>0?Ae.pts-d[ke-1].pts:W,vt.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ct=Math.floor(vt.maxBufferHole*c),Bt=(i?L+i*c:this.nextAudioTs+v)-Ae.pts;Bt>Ct?(j=Bt-Vt,j<0?j=Vt:pe=!0,this.log(`It is approximately ${Bt/90} ms to the next segment; using duration ${j/90} ms for the last video frame.`)):j=Vt}else j=Vt}let tt=Math.round(Ae.pts-Ae.dts);if(Le=Math.min(Le,j),Re=Math.max(Re,j),be=Math.min(be,nt),Ie=Math.max(Ie,nt),!n&&ke===0&&tt>j){const vt=Math.round(tt/W)*W;vt-tt===1&&(this.log(`pad first CTS ${tt} -> ${vt} of sn: ${a.sn}`),tt=vt)}p.push(kpe(Ae.key,j,ot,tt))}if(p.length){const ke=Sj();if(ke){if(ke<70){const Ae=p[0].flags;Ae.dependsOn=2,Ae.isNonSync=0}}else if(nBt()&&Ie-be0&&(i&&Math.abs($-(O+F))<9e3||Math.abs(zh(C[0].pts,$)-(O+F))<20*v),C.forEach(function(Te){Te.pts=zh(Te.pts,$)}),!n||O<0){const Te=C.length;if(C=C.filter(ge=>ge.pts>=0),Te!==C.length&&this.warn(`Removed ${C.length-Te} of ${Te} samples (initPTS ${F} / ${d})`),!C.length)return;a===0?O=0:i&&!P?O=Math.max(0,$-F):O=C[0].pts-F}if(e.segmentCodec==="aac"){const Te=this.config.maxAudioFramesDrift;for(let ge=0,$e=O+F;ge=Te*v&&He0){Q+=L;try{Z=new Uint8Array(Q)}catch(He){this.observer.emit(Ee.ERROR,Ee.ERROR,{type:Kn.MUX_ERROR,details:Wt.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:c,error:He,bytes:Q,reason:`fail allocating audio mdat ${Q}`});return}T||(Ul(Z,0,Q),Ul(Z,4,Ai.mdat))}else return;Z&&Z.set(we,L);const Ae=we.byteLength;L+=Ae,j.push(kpe(!0,g,Ae,0)),W=ke}const ie=j.length;if(!ie)return;const oe=j[j.length-1];O=W-F,this.nextAudioTs=O+l*oe.duration;const pe=T?new Uint8Array(0):bn.moof(e.sequenceNumber++,G/l,La({},e,{samples:j}));e.samples=[];const Le=(G-F)/d,be=this.nextAudioTs/d,Ie={data1:pe,data2:Z,startPTS:Le,endPTS:be,startDTS:Le,endDTS:be,type:"audio",hasAudio:!0,hasVideo:!1,nb:ie};return this.isAudioContiguous=!0,Ie}}function zh(t,e){let r;if(e===null)return t;for(e4294967296;)t+=r;return t}function c$t(t){for(let e=0;ec.pts-d.pts);const a=t.samples;return t.samples=[],{samples:a}}class u$t extends ff{constructor(e,r,n,i){super("passthrough-remuxer",i),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;const r=this.initPTS;r&&e&&r.baseTime===e.baseTime&&r.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,r,n,i){this.audioCodec=r,this.videoCodec=n,this.decryptdata=i,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,r,n){this.videoOnlyRemux=!1;let{audioCodec:i,videoCodec:a}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:c,video:d}=this.initData=n||YCe(e);if(r)V5t(e,r);else{const l=c||d;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}c&&(i=Ipe(c,ro.AUDIO,this)),d&&(a=Ipe(d,ro.VIDEO,this));const p={};c&&d?p.audiovideo={container:"video/mp4",codec:i+","+a,supplemental:d.supplemental,encrypted:d.encrypted,initSegment:e,id:"main"}:c?p.audio={container:"audio/mp4",codec:i,encrypted:c.encrypted,initSegment:e,id:"audio"}:d?p.video={container:"video/mp4",codec:a,supplemental:d.supplemental,encrypted:d.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=p}remux(e,r,n,i,a,c,d,p,l,g,v){var E,T;let{initPTS:j,lastEndTime:P}=this;const C={audio:void 0,video:void 0,text:void 0,id3:n,initSegment:void 0};yn(P)||(P=this.lastEndTime=a||0);const L=r.samples;if(!L.length)return C;const O=this.pendingInitSegment;O&&(this.pendingInitSegment=void 0,this.generateInitSegment(O,this.decryptdata,g));const F={initPTS:void 0,timescale:void 0,trackId:void 0};let $=this.initData;if((E=$)!=null&&E.length||(this.generateInitSegment(L),$=this.initData),!((T=$)!=null&&T.length))return this.warn("Failed to generate initSegment."),C;if(l.iframe&&$.audio&&$.video){var G;const Qt=(G=this.initTracks)==null||(G=G.audiovideo)==null?void 0:G.initSegment,zt=Qt?O5t(Qt):null;if(zt){var W;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(zt,this.decryptdata),(W=this.initData)!=null&&W.length&&($=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(F.tracks=this.initTracks,C.initSegment=F,this.emitInitSegment=!1);const Z=l.iframe,Q=v&&(!Z||v.includeSampleDetails)?v.tracks:W5t(L,$,l,this,Z),ee=$.audio?Q[$.audio.id]:null,ie=$.video?Q[$.video.id]:null,oe=!!$.audio,pe=!!$.video;let Le="";oe&&(Le+="audio"),pe&&(Le+="video");const be=pM(ie,1/0),Re=pM(ee,1/0),Ie=pM(ie,0,!0),Te=pM(ee,0,!0);let ge=a,$e=0;ie&&ee&&$.audio&&(Re>Ie||be>Te)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${be}-${Ie} a: ${Re}-${Te}}`,ie,ee);const we=!!ee&&(!ie||!j&&Re=1&&$.video&&l.iframe){const{trun:Qt,start:zt}=ie,Vr=Qt.length===1,Jr=Qt.length?Vr?Qt[0].samples:Qt[0].samples.concat(...Qt.slice(1).map(Fn=>Fn.samples)):[];if(Jr.length){const Fn=Qt[0];let Ar=Fn;for(let si=Qt.length;si--;)if(Qt[si].samples.length){Ar=Qt[si];break}const Tn=Ar.lastSampleDurationOffset,{defaultSampleDurationOffset:mn}=Fn,li=Math.abs(l.duration-(Ie-be))>.05,Lr=Jr.lengthgs+ma.size,0):void 0,ss=li?l.duration:Ie-be,ps=h$t(Jr,ss*$.video.timescale,Tn,mn),Mi=F5t(L,$.video.id,Jr.length,si,ps);Mi?(Ae=Mi,ot=d$t(zt,Jr)):this.warn(`IFrame remux skipped (sn ${l.sn}); using native sample duration`),$e=Mi&&ps?ss:Ie-be}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${Qt.length})`),$e=Ie-be}else $e=we?Te-Re:Ie-be;if(this.videoOnlyRemux&&Ae===L)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${l.sn})`),C;const nt=ke.timescale,tt=ke.start-a*nt,vt=we?$.audio.id:$.video.id;if(ge=ke.start/nt,!(!!j&&l.id>1)&&(c||!j)&&(f$t(j,ge,a,$e)||nt!==j.timescale)){let Qt=!1;const zt=we?"audio":"video";if(j){const Vr=a!==0?ge/a:1+ge/1;Qt=ge>=0&&Math.abs(1-Vr)<.001,this.log(`${zt} timestamps in track ${vt} at playlist time: ${c?"":"~"}${a} maps to ${ge} with initPTS: ${j.baseTime/j.timescale} (${tt/nt-j.baseTime/j.timescale}s diff) (${Le}) drift estimate: ${Vr} ${Qt?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}Qt||(this.log(`Found initPTS in ${zt} track ${vt} at playlist time: ${a} offset: ${ge-a} (${tt}/${nt})`),j=null,F.initPTS=tt,F.timescale=nt,F.trackId=vt)}j?(F.initPTS=j.baseTime,F.timescale=j.timescale,F.trackId=j.trackId):((!F.timescale||F.trackId===void 0||F.initPTS===void 0)&&(this.warn("Could not set initPTS"),F.initPTS=ge,F.timescale=1,F.trackId=-1),this.initPTS=j={baseTime:F.initPTS,timescale:F.timescale,trackId:F.trackId});const Ct=ge-j.baseTime/j.timescale,Bt=Ct+$e,cr=pe&&(ke==null?void 0:ke.ptsMin)!==void 0?ke.ptsMin/ke.timescale-j.baseTime/j.timescale:Ct,ft=ot!==void 0&&ie?ot/ie.timescale-j.baseTime/j.timescale:pe&&ke!=null&&ke.ptsMax?ke.ptsMax/ke.timescale-j.baseTime/j.timescale:Bt;$e>0?this.lastEndTime=Bt:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const Kt=($.audio?$.audio.encrypted:!1)||($.video?$.video.encrypted:!1),ir={data1:Ae,data2:He,startPTS:cr,startDTS:Ct,endPTS:ft,endDTS:Bt,type:Le,hasAudio:oe,hasVideo:pe,nb:1,dropped:0,encrypted:Kt};C.audio=oe&&!pe?ir:void 0,C.video=pe?ir:void 0;const Gr=this.isVideoContiguous,tr=ie==null?void 0:ie.sampleCount;if(tr){const Qt=ie.keyFrameIndex,zt=Qt!==-1;ir.nb=tr,ir.dropped=Qt===0||Gr?0:zt?Qt:tr,ir.independent=zt,ir.firstKeyFrame=Qt,zt&&ie.keyFrameStart&&(ir.firstKeyFramePTS=(ie.keyFrameStart-j.baseTime)/j.timescale),Gr||(C.independent=zt),this.isVideoContiguous||(this.isVideoContiguous=zt),ir.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${Qt}/${tr} dropped: ${ir.dropped} start: ${ir.firstKeyFramePTS||"NA"}`)}return C.initSegment=F,C.id3=KPe(n,a,j,j),i.samples.length&&(C.text=YPe(i,a,j)),C}}function pM(t,e,r=!1){return(t==null?void 0:t.start)!==void 0?(t.start+(r?t.duration:0))/t.timescale:e}function d$t(t,e){let r=t,n=t;for(let i=0;i=i}function Ipe(t,e,r){const n=t.codec;return n&&n.length>4?n:e===ro.AUDIO?n==="ec-3"||n==="ac-3"||n==="alac"?n:n==="fLaC"||n==="Opus"?H3(n,!1):(r.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"):n==="mjpg"?n:(r.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1")}let L_;try{L_=self.performance.now.bind(self.performance)}catch{L_=Date.now}const kO=[{demux:$zt,remux:u$t},{demux:vy,remux:AO},{demux:Ozt,remux:AO},{demux:Bzt,remux:AO}];kO.splice(2,0,{demux:Fzt,remux:AO});class jpe{constructor(e,r,n,i,a,c){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=r,this.config=n,this.id=a,this.logger=c}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,r,n,i){if(!this.observer)return gM(n);const a=n.transmuxing;a.executeStart=L_();const c=new Uint8Array(e),{currentTransmuxState:d,transmuxConfig:p}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:g,trackSwitch:v,accurateTimeOffset:E,timeOffset:T,initSegmentChange:j}=i||d,{audioCodec:P,videoCodec:C,defaultInitPts:L,duration:O,initSegmentData:F}=p,$=m$t(c,r);if($&&RE($.method)){const Q=this.getDecrypter(),ee=LQ($.method);return this.asyncResult=!0,this.decryptionPromise=Q.decrypt(c,$.key.buffer,$.iv.buffer,ee,n.decryptRange).then(ie=>{const oe=this.push(ie,null,n);return this.decryptionPromise=null,oe}),this.decryptionPromise}const G=this.needsProbing(g,v);if(G){const Q=n.iframe&&F&&vy.probe(F,this.logger)?F:c,ee=this.configureTransmuxer(Q);if(ee)return this.logger.warn(`[transmuxer] ${ee.message}`),this.observer.emit(Ee.ERROR,Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.FRAG_PARSING_ERROR,fatal:!1,error:ee,reason:ee.message}),a.executeEnd=L_(),gM(n)}(g||v||j||G)&&this.resetInitSegment(F,P,C,O,r,n),(g||j||G)&&this.resetInitialTimestamp(L),l||this.resetContiguity();const W=this.transmux(c,$,T,E,n);this.asyncResult=mP(W);const Z=this.currentTransmuxState;return Z.contiguous=!0,Z.discontinuity=!1,Z.trackSwitch=!1,a.executeEnd=L_(),W}flush(e){const r=e.transmuxing;r.executeStart=L_();const{decrypter:n,currentTransmuxState:i,decryptionPromise:a}=this;if(a)return this.asyncResult=!0,a.then(()=>this.flush(e));const c=[],{timeOffset:d}=i;if(n){const v=n.flush();v&&c.push(this.push(v.buffer,null,e))}const{demuxer:p,remuxer:l}=this;if(!p||!l){r.executeEnd=L_();const v=[gM(e)];return this.asyncResult?Promise.resolve(v):v}const g=p.flush(d,e);return mP(g)?(this.asyncResult=!0,g.then(v=>(this.flushRemux(c,v,e),c))):(this.flushRemux(c,g,e),this.asyncResult?Promise.resolve(c):c)}flushRemux(e,r,n){if(!this.remuxer)return;const{audioTrack:i,videoTrack:a,id3Track:c,textTrack:d}=r,{accurateTimeOffset:p,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?" part: "+n.part:""} of ${this.id} playlist ${n.level}`);const g=this.remuxer.remux(i,a,c,d,l,p,!0,this.id,n,r.initData,r.sampleData);e.push({remuxResult:g,chunkMeta:n}),n.transmuxing.executeEnd=L_()}resetInitialTimestamp(e){const{demuxer:r,remuxer:n}=this;!r||!n||(r.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:r}=this;!e||!r||(e.resetContiguity(),r.resetNextTimestamp())}resetInitSegment(e,r,n,i,a,c){const{demuxer:d,remuxer:p}=this;!d||!p||(d.resetInitSegment(e,r,n,i,a,c),p.resetInitSegment(e,r,n,a))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,r,n,i,a){let c;return(r==null?void 0:r.method)==="SAMPLE-AES"?c=this.transmuxSampleAes(e,r,n,i,a):c=this.transmuxUnencrypted(e,n,i,a),c}transmuxUnencrypted(e,r,n,i){const{demuxer:a,remuxer:c}=this;if(!a||!c)return gM(i);const d=a.demux(e,r,i,!1,!this.config.progressive),{audioTrack:p,videoTrack:l,id3Track:g,textTrack:v}=d;return{remuxResult:c.remux(p,l,g,v,r,n,!1,this.id,i,d.initData,d.sampleData),chunkMeta:i}}transmuxSampleAes(e,r,n,i,a){return this.demuxer?this.demuxer.demuxSampleAes(e,r,n,a).then(c=>({remuxResult:this.remuxer.remux(c.audioTrack,c.videoTrack,c.id3Track,c.textTrack,n,i,!1,this.id,a,c.initData,c.sampleData),chunkMeta:a})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){const{config:r,observer:n,typeSupported:i}=this;if(!n)return;let a;try{for(let v=0,E=kO.length;v0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(r=e),r}const gM=t=>({remuxResult:{},chunkMeta:t});function mP(t){return"then"in t&&t.then instanceof Function}class p$t{constructor(e,r,n,i,a){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=r,this.initSegmentData=n,this.duration=i,this.defaultInitPts=a||null}}class g$t{constructor(e,r,n,i,a,c){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=r,this.accurateTimeOffset=n,this.trackSwitch=i,this.timeOffset=a,this.initSegmentChange=c}}let Cpe=0;class ZPe{constructor(e,r,n,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Cpe++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=p=>{const l=p.data,g=this.hls;if(!(!g||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var v;const E=(v=this.workerContext)==null?void 0:v.objectURL;E&&self.URL.revokeObjectURL(E);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{g.logger[l.data.logType]&&g.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,g.trigger(l.event,l.data);break}}},this.onWorkerError=p=>{if(!this.hls)return;const l=new Error(`${p.message} (${p.filename}:${p.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Ee.ERROR,{type:Kn.OTHER_ERROR,details:Wt.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const a=e.config;this.hls=e,this.id=r,this.useWorker=!!a.enableWorker,this.onTransmuxComplete=n,this.onFlush=i;const c=(p,l)=>{l=l||{},l.frag=this.frag||void 0,p===Ee.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(p,l)};this.observer=new OQ,this.observer.on(Ee.FRAG_DECRYPTED,c),this.observer.on(Ee.ERROR,c);const d=zme(a.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const p=this.hls.logger;if(a.workerPath||wzt()){try{a.workerPath?(p.log(`loading Web Worker ${a.workerPath} for "${r}"`),this.workerContext=Ezt(a.workerPath)):(p.log(`injecting Web Worker for "${r}"`),this.workerContext=Szt());const{worker:g}=this.workerContext;g.addEventListener("message",this.onWorkerMessage),g.addEventListener("error",this.onWorkerError),g.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:d,id:r,config:fo(a)})}catch(g){p.warn(`Error setting up "${r}" Web Worker, fallback to inline`,g),this.terminateWorker(),this.error=null,this.transmuxer=new jpe(this.observer,d,a,"",r,e.logger)}return}}this.transmuxer=new jpe(this.observer,d,a,"",r,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Cpe++;const r=this.hls.config,n=zme(r.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:n,id:this.id,config:fo(r)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Tzt(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const r=this.transmuxer;r&&(r.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,r,n,i,a,c,d,p,l,g){var v,E;l.transmuxing.start=self.performance.now();const{instanceNo:T,transmuxer:j}=this,P=c?c.start:a.start,C=a.decryptdata,L=this.frag,O=L?a.cc!==L.cc:!0,F=L?l.level!==L.level:!0,$=L?l.sn-L.sn:-1,G=this.part?l.part-this.part.index:-1,W=$===0&&l.id>1&&l.id===(L==null?void 0:L.stats.chunkCount),Z=!F&&($===1||$===0&&(G===1||W&&G<=0)),Q=self.performance.now();(F||$||a.stats.parsing.start===0)&&(a.stats.parsing.start=Q),c&&(G||!Z)&&(c.stats.parsing.start=Q);const ee=!(L&&((v=a.initSegment)==null?void 0:v.url)===((E=L.initSegment)==null?void 0:E.url)),ie=new g$t(O,Z,p,F,P,ee);if(!Z||O||ee){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${a.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id} playlist: ${l.level} id: ${l.id} discontinuity: ${O} trackSwitch: ${F} contiguous: ${Z} accurateTimeOffset: ${p} timeOffset: ${P} initSegmentChange: ${ee}`);const oe=new p$t(n,i,r,d,g);this.configureTransmuxer(oe)}if(this.frag=a,this.part=c,this.workerContext)this.workerContext.worker.postMessage({instanceNo:T,cmd:"demux",data:e,decryptdata:C,chunkMeta:l,state:ie},e instanceof ArrayBuffer?[e]:[]);else if(j){const oe=j.push(e,C,l,ie);mP(oe)?oe.then(pe=>{this.handleTransmuxComplete(pe)}).catch(pe=>{this.transmuxerError(pe,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(oe)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:r,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(n){const i=n.flush(e);mP(i)?i.then(a=>{this.handleFlushResult(a,e)}).catch(a=>{this.transmuxerError(a,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,r,n){this.hls&&(this.error=e,this.hls.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.FRAG_PARSING_ERROR,chunkMeta:r,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,r){e.forEach(n=>{this.handleTransmuxComplete(n)}),this.onFlush(r)}configureTransmuxer(e){const{instanceNo:r,transmuxer:n}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:r,cmd:"configure",config:e}):n&&n.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Ppe=100;class y$t extends MQ{constructor(e,r,n){super(e,r,n,"audio-stream-controller",On.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Ee.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Ee.BUFFER_RESET,this.onBufferReset,this),e.on(Ee.BUFFER_CREATED,this.onBufferCreated,this),e.on(Ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Ee.FRAG_LOADING,this.onFragLoading,this),e.on(Ee.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(Ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Ee.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Ee.BUFFER_RESET,this.onBufferReset,this),e.off(Ee.BUFFER_CREATED,this.onBufferCreated,this),e.off(Ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Ee.FRAG_LOADING,this.onFragLoading,this),e.off(Ee.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,r){const{frag:n,id:i,initPTS:a,timescale:c,trackId:d,timestampOffsets:p}=r;if(i===On.MAIN){const l=n.cc,g=this.fragCurrent;if(this.initPTS=p,this.log(`InitPTS for cc: ${l} found from main: ${a/c} (${a}/${c}) trackId: ${d}`),this.mainAnchor=n,this.state===Tr.WAITING_INIT_PTS){const v=this.waitingData;(!v&&!this.loadingParts||v&&v.frag.cc!==l)&&this.syncWithAnchor(n,v==null?void 0:v.frag)}else!this.hls.hasEnoughToStart&&g&&g.cc!==l?(g.abortRequests(),this.syncWithAnchor(n,g)):this.state===Tr.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&((e=this.switchingTrack)==null?void 0:e.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,r){var n;const i=((n=this.mainFragLoading)==null?void 0:n.frag)||null;if(r&&(i==null?void 0:i.cc)===r.cc)return;const a=(i||e).cc,c=this.getLevelDetails(),d=this.getLoadPosition(),p=hPe(c,a,d);p&&this.fragmentTracker.getState(p)!==wo.OK&&(this.log(`Syncing with main frag at ${p.start} cc ${p.cc}`),this.startFragRequested=!1,this.nextLoadPosition=p.start,this.resetLoadingState(),this.state===Tr.IDLE&&this.doTickIdle())}startLoad(e,r){if(!this.levels){this.startPosition=e,this.state=Tr.STOPPED;return}const n=this.lastCurrentTime;this.stopLoad(),this.setInterval(Ppe),n>0&&e===-1&&!r&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n),this.state=Tr.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=r?-1:e,!r&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case Tr.IDLE:this.doTickIdle();break;case Tr.WAITING_TRACK:{const{levels:e,trackId:r}=this,n=e==null?void 0:e[r],i=n==null?void 0:n.details;if(i&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(i))break;this.state=Tr.WAITING_INIT_PTS}break}case Tr.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Tr.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:r,part:n,cache:i,complete:a}=e,c=this.mainAnchor;if(this.initPTS[r.cc]!==void 0){this.waitingData=null,this.state=Tr.FRAG_LOADING;const d=i.flush().buffer,p={frag:r,part:n,payload:d,networkDetails:null};this._handleFragmentLoadProgress(p),a&&super._handleFragmentLoadComplete(p)}else c&&c.cc!==e.frag.cc&&this.syncWithAnchor(c,e.frag)}else this.state=Tr.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){var e;const{hls:r,levels:n,media:i,trackId:a}=this,c=r.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!c.startFragPrefetch)||!(n!=null&&n[a]))return;const d=n[a],p=d.details;if(!p||this.waitForLive(d)||this.waitForCdnTuneIn(p)){this.state=Tr.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ro.AUDIO));const g=this.getFwdBufferInfo();if(g===null)return;if(!this.switchingTrack&&this._streamEnded(g,p)){r.trigger(Ee.BUFFER_EOS,{type:"audio"}),this.state=Tr.ENDED;return}const v=g.len,E=r.maxBufferLength,T=p.fragments,j=T[0].start,P=this.getLoadPosition(),C=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?P:g.end;if(this.switchingTrack&&i){const F=P;p.PTSKnown&&F=this.timelineOffset&&(g.end>j||g.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${F} -> ${j} + 0.05`),i.currentTime=j+.05)}if(v>=E&&!this.switchingTrack&&CO.end){const $=this.fragmentTracker.getFragAtPos(C,On.MAIN);$&&$.end>O.end&&(O=$,this.mainFragLoading={frag:$,targetBufferTime:null})}if(L.start>O.end)return}this.loadFragment(L,d,C)}onMediaDetaching(e,r){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,r)}onAudioTracksUpdated(e,{audioTracks:r}){this.resetTransmuxer(),this.levels=r.map(n=>new dP(n))}onAudioTrackSwitching(e,r){const n=!!r.url;this.trackId=r.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),n?(this.switchingTrack=r,r.flushImmediate||(this.nextTrackId=r.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(r),this.state!==Tr.STOPPED&&(this.setInterval(Ppe),this.state=Tr.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=r,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,r){this.mainDetails=r.details;const n=this.cachedTrackLoadedData;n&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(Ee.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(e,r){var n;const{levels:i}=this,{details:a,id:c,groupId:d,track:p}=r;if(!i){this.warn(`Audio tracks reset while loading track ${c} "${p.name}" of "${d}"`);return}const l=this.mainDetails;if(!l||a.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=r,this.state!==Tr.STOPPED&&(this.state=Tr.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${c} "${p.name}" of "${d}" loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`);const g=i[c];let v=0;if(a.live||(n=g.details)!=null&&n.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;if(g.details){var E;v=this.alignPlaylists(a,g.details,(E=this.levelLastLoaded)==null?void 0:E.details)}a.alignedSliding||(J3(l,a,this),v=a.fragmentStart)}g.details=a,this.levelLastLoaded=g,this.startFragRequested||this.setStartPosition(l,v),this.hls.trigger(Ee.AUDIO_TRACK_UPDATED,{details:a,id:c,groupId:r.groupId}),this.state===Tr.WAITING_TRACK&&!this.waitForCdnTuneIn(a)&&(this.state=Tr.IDLE),this.tick()}_handleFragmentLoadProgress(e){var r;const n=e.frag,{part:i,payload:a}=e,{config:c,trackId:d,levels:p}=this;if(!p){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const l=p[d];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const g=l.details;if(!g){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const v=c.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let E=this.transmuxer;E||(E=this.transmuxer=new ZPe(this.hls,On.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const T=this.initPTS[n.cc],j=(r=n.initSegment)==null?void 0:r.data;if(T!==void 0){const C=i?i.index:-1,L=C!==-1,O=new NQ(n.level,n.sn,n.stats.chunkCount,a.byteLength,C,L,n.duration);E.push(a,j,v,"",n,i,g.totalduration,!1,O,T)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${g.startSN} ,${g.endSN}],track ${d}`);const{cache:P}=this.waitingData=this.waitingData||{frag:n,part:i,cache:new RPe,complete:!1};P.push(new Uint8Array(a)),this.state!==Tr.STOPPED&&(this.state=Tr.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,r){this.bufferFlushed=this.flushing=!1;const n=r.tracks.audio;n&&(this.mediaBuffer=n.buffer||null)}onFragLoading(e,r){!this.audioOnly&&r.frag.type===On.MAIN&&Ko(r.frag)&&(this.mainFragLoading=r,this.state===Tr.IDLE&&this.tick())}onFragBuffered(e,r){const{frag:n,part:i}=r;if(n.type!==On.AUDIO){!this.audioOnly&&n.type===On.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Ko(n)){const a=this.switchingTrack;a&&(this.bufferedTrack=a)}this.fragBufferedComplete(n,i),this.media&&this.tick()}getFwdBufferInfo(){const e=this.getBufferOutput();return super.getFwdBufferInfo(e,On.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const{fragPlaying:n,switchingTrack:i}=this,a=!n||n.level!==(e==null?void 0:e.level);return a&&e&&this.cleanupBackBuffer(),i&&(a||(n==null?void 0:n.level)===i.id)&&this.completeAudioSwitch(i),!0}onError(e,r){var n;if(r.fatal){this.state=Tr.ERROR;return}switch(r.details){case Wt.FRAG_GAP:case Wt.FRAG_PARSING_ERROR:case Wt.FRAG_DECRYPT_ERROR:case Wt.FRAG_LOAD_ERROR:case Wt.FRAG_LOAD_TIMEOUT:case Wt.KEY_LOAD_ERROR:case Wt.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(On.AUDIO,r);break;case Wt.AUDIO_TRACK_LOAD_ERROR:case Wt.AUDIO_TRACK_LOAD_TIMEOUT:case Wt.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Tr.WAITING_TRACK&&((n=r.context)==null?void 0:n.type)===ts.AUDIO_TRACK&&(this.state=Tr.IDLE);break;case Wt.BUFFER_APPEND_NO_PROGRESS:if(r.parent!=="audio")return;r.frag&&(r.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${r.frag.sn} of track ${r.frag.level} as a gap after ${r.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(r.frag));break;case Wt.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(On.AUDIO,r);break;case Wt.BUFFER_ADD_CODEC_ERROR:case Wt.BUFFER_APPEND_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case Wt.BUFFER_FULL_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Wt.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onBufferFlushing(e,{type:r}){r!==ro.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:r}){if(r!==ro.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Tr.ENDED&&(this.state=Tr.IDLE);const n=this.getBufferOutput();n&&(this.afterBufferFlushed(n,r),this.tick())}}_handleTransmuxComplete(e){var r;const n="audio",{hls:i}=this,{remuxResult:a,chunkMeta:c}=e,d=this.getCurrentContext(c);if(!d){this.resetWhenMissingContext(c);return}const{frag:p,part:l,level:g}=d,{details:v}=g,{audio:E,text:T,id3:j,initSegment:P}=a;if(this.fragContextChanged(p)||!v){this.fragmentTracker.removeFragment(p),P!=null&&P.tracks&&this.resetTransmuxer();return}if(this.state=Tr.PARSING,E&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:C}=this,L=C.nextAudioTrackBufferFlushForwardOffset,O=Math.max(this.getLoadPosition()+L,(l||p).start);super.flushMainBuffer(O,Number.POSITIVE_INFINITY,On.AUDIO)}if(P!=null&&P.tracks){const C=p.initSegment||p;if(this.unhandledEncryptionError(P,p))return;this._bufferInitSegment(g,P.tracks,C,c),i.trigger(Ee.FRAG_PARSING_INIT_SEGMENT,{frag:C,id:n,tracks:P.tracks})}if(E){const{startPTS:C,endPTS:L,startDTS:O,endDTS:F}=E;l&&(l.elementaryStreams[ro.AUDIO]={startPTS:C,endPTS:L,startDTS:O,endDTS:F}),p.setElementaryStreamInfo(ro.AUDIO,C,L,O,F),this.bufferFragmentData(E,p,l,c)}if(j!=null&&(r=j.samples)!=null&&r.length){const C=La({id:n,frag:p,details:v},j);i.trigger(Ee.FRAG_PARSING_METADATA,C)}if(T){const C=La({id:n,frag:p,details:v},T);i.trigger(Ee.FRAG_PARSING_USERDATA,C)}}_bufferInitSegment(e,r,n,i){if(this.state!==Tr.PARSING||(r.video&&delete r.video,r.audiovideo&&delete r.audiovideo,!r.audio))return;const a=r.audio;a.id=On.AUDIO;const c=e.audioCodec;this.log(`Init audio buffer, container:${a.container}, codecs[level/parsed]=[${c}/${a.codec}]`),(c==null?void 0:c.split(",").length)===1&&(a.levelCodec=c),this.hls.trigger(Ee.BUFFER_CODECS,r);const d=a.initSegment;if(d!=null&&d.byteLength){const p={type:"audio",frag:n,part:null,chunkMeta:i,parent:n.type,data:d};this.hls.trigger(Ee.BUFFER_APPENDING,p)}this.tickImmediate()}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===wo.NOT_LOADED||i===wo.PARTIAL){var a;if((a=r.details)!=null&&a.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Tr.WAITING_INIT_PTS;const c=this.mainDetails;c&&c.fragmentStart!==r.details.fragmentStart&&J3(c,r.details,this)}else super.loadFragment(e,r,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){const{name:r,lang:n,assocLang:i,characteristics:a,audioCodec:c,channels:d}=this.bufferedTrack;Qb({name:r,lang:n,assocLang:i,characteristics:a,audioCodec:c,channels:d},e,vb)||(K3(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:r}=this;this.bufferedTrack=e,this.switchingTrack=null,r.trigger(Ee.AUDIO_TRACK_SWITCHED,Hn({},e))}get nextAudioTrack(){return this.nextTrackId}}class UQ extends ff{constructor(e,r){super(r,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,r,n){const i=r==null?void 0:r.renditionReports;if(i){let a=-1;for(let c=0;c=0&&g>r.partTarget&&(p+=1)}const l=n&&$me(n);return new Ume(d,p>=0?p:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,r){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,r){if(r)try{return r.addDirectives(e)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}return e}playlistLoaded(e,r,n){const{details:i,stats:a}=r,c=i.fragments,d=self.performance.now(),p=a.loading.first?Math.max(0,Math.floor(d-a.loading.first)):0;i.advancedDateTime=Date.now()-p;const l=this.hls.config.timelineOffset;if(l!==i.appliedTimelineOffset){const v=Math.max(l||0,0);i.appliedTimelineOffset=v,c.forEach(E=>{E==null||E.setStart(E.playlistOffset+v)})}if(i.live||n!=null&&n.live){var g;const v="levelInfo"in r?r.levelInfo:r.track;i.reloaded(n);const E=(g=c[c.length-1])==null?void 0:g.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const G=new Error(`${E} playlist ${v.id} hit max allowed unchanged reloads.`);this.warn(G);const{networkDetails:W,context:Z}=r;this.hls.trigger(Ee.ERROR,{type:Kn.NETWORK_ERROR,details:Wt.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:G,reason:G.message,level:r.level,parent:E,context:Z,networkDetails:W,stats:a});return}if(n){uzt(n,i,this);const G=i.playlistParsingError;if(G){this.warn(G);const W=this.hls;if(!W.config.ignorePlaylistParsingErrors){const{networkDetails:Z}=r;W.trigger(Ee.ERROR,{type:Kn.NETWORK_ERROR,details:Wt.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:G,reason:G.message,level:r.level,parent:E,networkDetails:Z,stats:a});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=a.loading.start);const T=this.hls.mainForwardBufferInfo,j=T?T.end-T.len:0,P=(i.edge-j)*1e3,C=IPe(i,P);i.requestScheduled+C0){if(pe>i.targetduration*3)this.log(`Playlist last advanced ${oe.toFixed(2)}s ago. Omitting segment and part directives.`),F=void 0,$=void 0;else if(n!=null&&n.tuneInGoal&&pe-i.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${Le} with playlist age: ${i.age}`),Le=0;else{const be=Math.floor(Le/i.targetduration);if(F+=be,$!==void 0){const Re=Math.round(Le%i.targetduration/i.partTarget);$+=Re}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${oe.toFixed(2)}s goal: ${Le} skip sn ${be} to part ${$}`)}i.tuneInGoal=Le}if(O=this.getDeliveryDirectives(i,r.deliveryDirectives,F,$),G||!ie){i.requestScheduled=d,this.loadingPlaylist(v,O);return}}else(i.canBlockReload||i.canSkipUntil)&&(O=this.getDeliveryDirectives(i,r.deliveryDirectives,F,$));O&&F!==void 0&&i.canBlockReload&&(i.requestScheduled=a.loading.first+Math.max(C-p*2,C/2)),this.scheduleLoading(v,O,i)}else this.clearTimer()}scheduleLoading(e,r,n){const i=n||e.details;if(!i){this.loadingPlaylist(e,r);return}const a=self.performance.now(),c=i.requestScheduled;if(a>=c&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(e,r),this.loadingSync=!1;return}const d=Math.max(c-a,0);this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(d)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,r),d)}getDeliveryDirectives(e,r,n,i){let a=$me(e);return r!=null&&r.skip&&e.deltaUpdateFailed&&(n=r.msn,i=r.part,a=EO.No),new Ume(n,i,a)}checkRetry(e){const r=e.details,n=q3(e),i=e.errorAction,{action:a,retryCount:c=0,retryConfig:d}=i||{},p=!!i&&!!d&&(a===ju.RetryRequest||!i.resolved&&a===ju.SendAlternateToPenaltyBox);if(p){var l;if(c>=d.maxNumRetry)return!1;if(n&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${c+1}/${d.maxNumRetry} after "${r}" without delivery-directives`),this.loadPlaylist();else{var g;const v=aP((g=e.response)==null?void 0:g.code);if(this.clearTimer(),v)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const E=TQ(d,c);this.warn(`Retrying playlist loading ${c+1}/${d.maxNumRetry} after "${r}" in ${E}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),E)}}e.levelRetry=!0,i.resolved=!0}return p}checkOfflineStatus(){this.clearTimer(),aP(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function XPe(t,e){if(t.length!==e.length)return!1;for(let r=0;rt[i]!==e[i])}class x$t extends UQ{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(Ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Ee.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(Ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Ee.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Ee.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,r){this.tracks=r.audioTracks||[]}onAudioTrackLoaded(e,r){const{id:n,groupId:i,details:a}=r,c=this.tracksInGroup[n];if(!c||c.groupId!==i){this.warn(`Audio track with id:${n} and group:${i} not found in active group ${c==null?void 0:c.groupId}`);return}const d=c.details;c.details=r.details,this.log(`Audio track ${n} "${c.name}" lang:${c.lang} group:${i} loaded [${a.startSN}-${a.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,d)}onLevelLoading(e,r){this.switchLevel(r.level)}onLevelSwitching(e,r){this.switchLevel(r.level)}switchLevel(e){const r=this.hls.levels[e];if(!r)return;const n=r.audioGroups||null,i=this.groupIds;let a=this.currentTrack;if(!n||(i==null?void 0:i.length)!==(n==null?void 0:n.length)||n!=null&&n.some(d=>(i==null?void 0:i.indexOf(d))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const d=this.tracks.filter(E=>hP(E.groupId,n));if(d.length)this.selectDefaultTrack&&!d.some(E=>E.default)&&(this.selectDefaultTrack=!1),d.forEach((E,T)=>{E.id=T});else if(!a&&!this.tracksInGroup.length)return;this.tracksInGroup=d;const p=this.hls.config.audioPreference;if(!a&&p){const E=Jp(p,d,vb);if(E>-1)a=d[E];else{const T=Jp(p,this.tracks);a=this.tracks[T]}}let l=this.findTrackId(a);l===-1&&a&&(l=this.findTrackId(null));const g={audioTracks:d};this.log(`Updating audio tracks, ${d.length} track(s) found in group(s): ${n==null?void 0:n.join(",")}`),this.hls.trigger(Ee.AUDIO_TRACKS_UPDATED,g);const v=this.trackId;if(l!==-1&&v===-1)this.setAudioTrack(l);else if(d.length&&v===-1){var c;const E=new Error(`No audio track selected for current audio group-ID(s): ${(c=this.groupIds)==null?void 0:c.join(",")} track count: ${d.length}`);this.warn(E.message),this.hls.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:E})}}}onError(e,r){r.fatal||!r.context||r.context.type===ts.AUDIO_TRACK&&r.context.id===this.trackId&&hP(r.context.groupId,this.groupIds)&&this.checkRetry(r)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){const r=this.hls;if(r.config.audioPreference=e,e){const n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){const i=this.currentTrack;if(i&&Qb(e,i,vb))return i;const a=Jp(e,this.tracksInGroup,vb);if(a>-1){const c=this.tracksInGroup[a];return this.setAudioTrack(a,"flushImmediate"in e&&e.flushImmediate),c}else if(i){let c=r.loadLevel;c===-1&&(c=r.firstAutoLevel);const d=kBt(e,r.levels,n,c,vb);if(d===-1)return null;r.nextLoadLevel=d}if(e.channels||e.audioCodec){const c=Jp(e,n);if(c>-1)return n[c]}}}return null}setAudioTrack(e,r=!0){const n=this.tracksInGroup;if(e<0||e>=n.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,a=n[e],c=a.details&&!a.details.live;if(e===this.trackId&&a===i&&c||(this.log(`Switching to audio-track ${e} "${a.name}" lang:${a.lang} group:${a.groupId} channels:${a.channels}`),this.trackId=e,this.currentTrack=a,this.hls.trigger(Ee.AUDIO_TRACK_SWITCHING,Hn(Hn({},a),{},{flushImmediate:r})),c))return;const d=this.switchParams(a.url,i==null?void 0:i.details,a.details);this.loadPlaylist(d)}findTrackId(e){const r=this.tracksInGroup;for(let n=0;n1&&this.detectPlayerSize())}onManifestParsed(e,r){this.restrictedLevels=[],r.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls){if((this.timer||this.observer)&&(yn(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){const e=this.hls.levels;e.length>1&&e.some(r=>!!r.videoCodec)&&this.startCapping()}}}onBufferCodecs(e,r){r.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}const e=this.hls.levels;if(e.length>1){const r=this.hls,n=this.getMaxLevel(e.length-1);n!==this.autoLevelCapping&&r.logger.log(`Setting autoLevelCapping to ${n}: ${e[n].height}p@${e[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),r.autoLevelCapping=n,r.autoLevelEnabled&&r.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=r.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;const r=this.hls.levels;if(!r.length)return-1;const n=r.filter((i,a)=>this.isLevelAllowed(i)&&a<=e);return this.observer||(this.clientRect=null),VQ.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}observe(){const e=self.ResizeObserver;e&&(this.observer=new e(r=>{var n;const i=(n=r[0])==null?void 0:n.contentRect;i&&(this.clientRect=i,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||!((e=this.hls)!=null&&e.config.capLevelToPlayerSize)||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,r={width:0,height:0};if(e){const n=e.getBoundingClientRect();r.width=n.width,r.height=n.height,!r.width&&!r.height&&(r.width=n.right-n.left||e.width||0,r.height=n.bottom-n.top||e.height||0)}return this.clientRect=r,r}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;const{ignoreDevicePixelRatio:r,maxDevicePixelRatio:n}=this.hls.config;if(!r)try{e=self.devicePixelRatio}catch{}return Math.min(e,n)}isLevelAllowed(e){return!this.restrictedLevels.some(n=>e.bitrate===n.bitrate&&e.width===n.width&&e.height===n.height)}static getMaxLevelByMediaSize(e,r,n){if(!(e!=null&&e.length))return-1;const i=(d,p)=>p?d.width!==p.width||d.height!==p.height:!0;let a=e.length-1;const c=Math.max(r,n);for(let d=0;d=c||p.height>=c)&&i(p,e[d+1])){a=d;break}}return a}}var yh=class jH{constructor(e,r){Array.isArray(e)&&(e=e.map(n=>n instanceof jH?n:new jH(n))),this.value=e,this.params=r}};const _$t="Dict";function v$t(t){return Array.isArray(t)?JSON.stringify(t):t instanceof Map?"Map{}":t instanceof Set?"Set{}":typeof t=="object"?JSON.stringify(t):String(t)}function b$t(t,e,r,n){return new Error(`failed to ${t} "${v$t(e)}" as ${r}`,{cause:n})}const Npe="Bare Item",w$t="Boolean",S$t="Byte Sequence",E$t="Decimal",T$t="Integer";function A$t(t){return t<-999999999999999||99999999999999912)throw _g(t,E$t);const r=e.toString();return r.includes(".")?r:`${r}.0`}function D$t(t){if(I$t.test(t))throw _g(t,k$t);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function M$t(t){return t.description||t.toString().slice(7,-1)}function Rpe(t){const e=M$t(t);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw _g(e,j$t);return e}function CH(t){switch(typeof t){case"number":if(!yn(t))throw _g(t,Npe);return Number.isInteger(t)?JPe(t):L$t(t);case"string":return D$t(t);case"symbol":return Rpe(t);case"boolean":return P$t(t);case"object":if(t instanceof Date)return R$t(t);if(t instanceof Uint8Array)return N$t(t);if(t instanceof QPe)return Rpe(t);default:throw _g(t,Npe)}}function PH(t){if(/^[a-z*][a-z0-9\-_.*]*$/.test(t)===!1)throw _g(t,C$t);return t}function qQ(t){return t==null?"":Object.entries(t).map(([e,r])=>r===!0?`;${PH(e)}`:`;${PH(e)}=${CH(r)}`).join("")}function eNe(t){return t instanceof yh?`${CH(t.value)}${qQ(t.params)}`:CH(t)}function O$t(t){return`(${t.value.map(eNe).join(" ")})${qQ(t.params)}`}function F$t(t,e={whitespace:!0}){if(typeof t!="object"||t==null)throw _g(t,_$t);const r=t instanceof Map?t.entries():Object.entries(t),n=e!=null&&e.whitespace?" ":"";return Array.from(r).map(([i,a])=>{a instanceof yh||(a=new yh(a));let c=PH(i);return a.value===!0?c+=qQ(a.params):(c+="=",Array.isArray(a.value)?c+=O$t(a):c+=eNe(a)),c}).join(`,${n}`)}function tNe(t,e){return F$t(t,e)}const B$t=["url"],z$t=["version","eventTargets","sid","transmissionMode"],$$t=["customData","headers"],Lpe=t=>t instanceof yh?new yh(Math.round(t.value),t.params):Math.round(t),u8=t=>Array.isArray(t)?t.map(Lpe):Lpe(t),NH=(t,e)=>Array.isArray(t)?t.map(r=>NH(r,e)):t instanceof yh&&typeof t.value=="string"?new yh(NH(t.value,e),t.params):(e.baseUrl&&(t=S5t(t,w5t(e.baseUrl))),e.version===1?encodeURIComponent(t):t),Dpe=t=>t instanceof yh?new yh(Math.round(t.value/100)*100,t.params):Math.round(t/100)*100,yM=t=>Array.isArray(t)?t.map(Dpe):Dpe(t),U$t=(t,e)=>{let r=t;return e.version>=2&&(t instanceof yh&&typeof t.value=="string"?r=new yh([t]):typeof t=="string"&&(r=[t])),NH(r,e)},V$t={br:u8,d:u8,bl:yM,dl:yM,mtp:yM,nor:U$t,rtp:yM,tb:u8},gP=2,rNe="bc",q$t="ps",nNe="pr",G$t="e",Mpe="t",H$t="c",iNe="b",GQ="rr",sNe="ce",xM={BITRATE_CHANGE:rNe,ERROR:G$t,RESPONSE_RECEIVED:GQ,CUSTOM_EVENT:sNe},aNe=new Map([[q$t,"sta"],[nNe,"pr"],[H$t,"cid"],[iNe,"bg"],[rNe,"br"]]),HQ="event",WQ="request",oNe=["cen","e","h","ts"],lNe=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],W$t=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function KQ(t){return W$t.test(t)}const K$t=new Set(lNe);function cNe(t){return K$t.has(t)||KQ(t)}const uNe=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Y$t=new Set(uNe);function dNe(t){return Y$t.has(t)}const Z$t=new Set(oNe);function X$t(t){return cNe(t)||dNe(t)||Z$t.has(t)}const Q$t=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),qB=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],J$t=new Set(qB);function e6t(t){return J$t.has(t)||KQ(t)}const t6t=new Set(["ot","sf","st","e","sta"]);function r6t(t){return t6t.has(t)}function n6t(t){return typeof t=="number"?yn(t):t!=null&&t!==""&&t!==!1}const i6t={[HQ]:X$t,[WQ]:cNe};function hNe(t,e){if(Array.isArray(t)){let r;return e&&(r=t.find(n=>{var i;return((i=n.params)==null?void 0:i.ot)===e})),r||(r=t[0]),hNe(r)}return t instanceof yh?t.value:t}function s6t(t){const e={};for(const[n,i]of Object.entries(t)){if(i==null){e[n]=i;continue}if(n==="nor"){const a=(Array.isArray(i)?i:[i])[0];if(a instanceof yh){var r;e.nor=a.value,(r=a.params)!=null&&r.r&&(e.nrr=a.params.r)}else e.nor=a}else Q$t.has(n)?e[n]=hNe(i,t.ot):e[n]=i}return e}function fNe(t,e={}){const r={};if(t==null||typeof t!="object")return r;const n=e.version||t.v||gP,i=e.reportingMode||WQ,a=n===1?s6t(t):t,c=n===1?e6t:i6t[i];let d=Object.keys(a).filter(c);a.e&&a.e!==GQ&&(d=d.filter(T=>!dNe(T)));const p=e.filter;typeof p=="function"&&(d=d.filter(p));const l=i===HQ;if(l){const T=a.e;!d.includes("e")&&T!=null&&d.push("e"),d.includes("ts")||d.push("ts"),!d.includes("cen")&&a.cen!=null&&T===sNe&&d.push("cen");const j=T?aNe.get(T):void 0;j&&a[j]!=null&&!d.includes(j)&&d.push(j)}if(d.length===0)return r;n>1&&!d.includes("v")&&d.push("v");const g={version:n,reportingMode:i,baseUrl:e.baseUrl};d.sort();for(const T of d){var v,E;let j=a[T];const P=(v=(E=e.formatters)==null?void 0:E[T])!=null?v:V$t[T];if(typeof P=="function"&&(j=P(j,g)),T==="v"){if(n===1)continue;j=n}if(T==="pr"&&j===1&&!(l&&a.e===nNe))continue;l&&T==="ts"&&!yn(j)&&(j=Date.now());const C=l&&j===!1&&T==="bg"&&a.e===iNe;!n6t(j)&&!C||(r6t(T)&&typeof j=="string"&&(j=new QPe(j)),r[T]=j)}return r}const uy="CMCD-Object",nh="CMCD-Request",OS="CMCD-Session",km="CMCD-Status",a6t={REQUEST:nh},o6t={ab:uy,br:uy,d:uy,lab:uy,lb:uy,ot:uy,tab:uy,tb:uy,tpb:uy,bl:nh,cs:nh,dfa:nh,dl:nh,ltc:nh,mtp:nh,nor:nh,nrr:nh,pb:nh,sn:nh,sta:nh,su:nh,tbl:nh,cid:OS,msd:OS,sf:OS,sid:OS,st:OS,v:OS,bg:km,bs:km,bsa:km,bsd:km,bsda:km,cdn:km,ec:km,nr:km,pr:km,pt:km,rtp:km};function l6t(t){return Object.keys(t).reduce((e,r)=>{var n;return(n=t[r])==null||n.forEach(i=>e[i]=r),e},{})}function c6t(t,e){const r={};if(!t)return r;const n=Object.keys(t),i=e?l6t(e):{};for(const c of n){var a;const d=o6t[c]||i[c]||a6t.REQUEST,p=(a=r[d])!=null?a:r[d]={};p[c]=t[c]}return r}function u6t(t,e){const r={},n=c6t(t,e);for(const[i,a]of Object.entries(n)){const c=tNe(a,{whitespace:!1});c&&(r[i]=c)}return r}const Ope="CMCD";function mNe(t){return tNe(t,{whitespace:!1})}function d6t(t,e={}){return t?mNe(fNe(t,e)):""}const h6t=30,RH=[...qB,...lNe,...uNe,...oNe].filter((t,e,r)=>r.indexOf(t)===e),f6t="application/cmcd",m6t=1,Eu={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Im={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},YQ="query",pNe="headers";function Fpe(t,e,r){var n;const i=new Set((n=e.enabledKeys)!=null?n:[]);return{version:e.version||gP,reportingMode:t,filter:a=>i.has(a),baseUrl:r}}function p6t(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let r=0;rt,gNe=Array.from(aNe,([t,e])=>e==="br"?{event:t,field:e,equal:(r,n)=>r===void 0||n===void 0?r===n:p6t(r,n),snapshot:r=>r.slice()}:{event:t,field:e,equal:g6t,snapshot:y6t}),x6t=new Map(gNe.map(t=>[t.event,t]));function _6t(t){const{url:e}=t,r=$B(t,B$t);return fetch(e,r)}function v6t(t){const{version:e=gP,eventTargets:r=[],sid:n=zCe(),transmissionMode:i=YQ}=t,a=$B(t,z$t);return Hn(Hn({},a),{},{version:e,transmissionMode:i,sid:n,eventTargets:r.reduce((c,d)=>{var p,l,g;return d!=null&&d.url&&(p=d.events)!=null&&p.length&&c.push({version:d.version||gP,enabledKeys:((l=d.enabledKeys)==null?void 0:l.slice())||[],url:d.url,events:d.events.slice(),interval:(g=d.interval)!=null?g:h6t,batchSize:d.batchSize||1}),c},[])})}var b6t=class{constructor(t,e=_6t){var r;this.timeOrigin=performance.timeOrigin||((r=performance.timing)==null?void 0:r.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=v6t(t),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(const n of this.config.eventTargets)this.eventTargets.set(n,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((t,e)=>{if(this.disarmInterval(t),e.interval===0||!e.events.includes(Mpe))return;const r=()=>{this.recordTargetEvent(t,e,Mpe),this.processEventTargets()};t.intervalId=setInterval(r,e.interval*1e3),r()})}stop(t=!1){t&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(t){t.sid&&t.sid!==this.data.sid&&this.resetSession(),t.msd&&!isNaN(t.msd)&&(this.msd=t.msd),this.data=Hn(Hn(Hn({},this.data),t),{},{msd:void 0});for(const e of gNe)e.field in t&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(t,e={}){const r=x6t.get(t);if(r){const n=r.field,i=e[n];i!==void 0&&La(this.data,{[n]:i});const a=this.data[n];if(a===void 0||r.equal(a,this.lastEmitted[n]))return;La(this.lastEmitted,{[n]:r.snapshot(a)})}this.eventTargets.forEach((n,i)=>{this.recordTargetEvent(n,i,t,e)}),this.processEventTargets()}recordTargetEvent(t,e,r,n={}){var i;if(!e.events.includes(r))return;const a=Hn(Hn(Hn({},this.data),n),{},{e:r,ts:(i=n.ts)!=null?i:Date.now(),sn:t.sn++});!isNaN(this.msd)&&!t.msdSent&&(a.msd=this.msd,t.msdSent=!0),t.queue.push(a)}recordResponseReceived(t,e={}){var r,n,i;const{request:a}=t,c=(r=e.url)!=null?r:a==null?void 0:a.url;if(!c)return;const d=new URL(c);d.searchParams.delete(Ope);const p={url:d.toString(),rc:t.status},l=t.resourceTiming;l&&(l.startTime!=null&&(p.ts=Math.round(this.timeOrigin+l.startTime),l.responseStart!=null&&(p.ttfb=Math.round(l.responseStart-l.startTime))),l.duration!=null&&(p.ttlb=Math.round(l.duration)));const g=(n=(i=a.customData)==null?void 0:i.cmcd)!=null?n:{};this.recordEvent(GQ,Hn(Hn(Hn({},g),p),e))}applyRequestReport(t){var e;return(e=this.createRequestReport(t))!=null?e:t}isRequestReportingEnabled(){var t;return!!((t=this.config.enabledKeys)!=null&&t.length)}createRequestReport(t,e){var r;const{customData:n={},headers:i={}}=t,a=$B(t,$$t),c=Hn(Hn({},a),{},{headers:Hn({},i),customData:Hn(Hn({},n),{},{cmcd:{}})});if(!((r=this.config.enabledKeys)!=null&&r.length)||!c.url)return c;const d=new URL(c.url),p=Hn(Hn(Hn({},this.data),e),{},{sn:this.requestTarget.sn++}),l=Fpe(WQ,this.config,c.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(p.msd=this.msd,this.requestTarget.msdSent=!0);const g=c.customData.cmcd=fNe(p,l);switch(this.config.transmissionMode){case YQ:const v=mNe(g);v&&(d.searchParams.set(Ope,v),c.url=d.toString());break;case pNe:La(c.headers,u6t(g,l.customHeaderMap));break}return c}processEventTargets(t=!1){let e=!1;this.eventTargets.forEach((r,n)=>{const{queue:i}=r;if(!i.length||i.length{r.queue.unshift(...c)}),e||(e=i.length>0)}),e&&this.processEventTargets()}async sendEventReport(t,e){const r=Fpe(HQ,t),{status:n}=await this.requester({url:t.url,method:"POST",headers:{"Content-Type":f6t},body:e.map(i=>d6t(i,r)).join(` `)+` `});if(n===410)this.disposeEventTarget(t);else if(n===429||n>499&&n<600)throw new Error(`Event report failed with status ${n}`)}disarmInterval(t){clearInterval(t.intervalId),t.intervalId=void 0}disposeEventTarget(t){const e=this.eventTargets.get(t);e&&(this.disarmInterval(e),this.eventTargets.delete(t))}resetSession(){this.eventTargets.forEach(t=>t.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const w6t={HLS:"h"},d8={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function S6t(t,e){return new yh(t,e)}new Set(qB);new Set(RH);const E6t=["includeKeys"];function Bpe(t){return Object.keys(t).every(KQ)}class T6t{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(Im.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Im.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Im.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Im.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Im.SEEKING)},this.onSeeked=()=>{var i;this.initialized&&(i=this.media)!=null&&i.paused&&this.setPlayerState(Im.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=i=>{try{this.apply(i,{ot:Eu.MANIFEST,su:!this.initialized})}catch(a){this.hls.logger.warn("Could not generate manifest CMCD data.",a)}},this.applyFragmentData=i=>{try{const{frag:d,part:p}=i,l=this.hls.levels[d.level],g=this.getObjectType(d,l),v={d:(p||d).duration*1e3,ot:g};if(g===Eu.VIDEO||g===Eu.AUDIO||g===Eu.MUXED||g==null&&(d.type==="main"||d.type==="audio")){var a;const T=l.bitrate/1e3;v.br=[T];const{cmcd:j}=this.config,P=(a=j==null?void 0:j.rtpSafetyFactor)!=null?a:5;if(v.rtp=Math.round(T*P/100)*100,g===Eu.MUXED||g==null&&d.type==="main"){const O=this.getTopBandwidth()/1e3;yn(O)&&(v.tb=[O]);const F=this.getLowestBandwidth()/1e3;yn(F)&&(v.lb=[F])}const C=this.getBufferLength(d);if(yn(C)){var c;v.bl=[C];const O=((c=this.media)==null?void 0:c.playbackRate)||1;v.dl=Math.round(C/O/100)*100}this.playheadLevel&&(v.pb=[this.playheadLevel.bitrate/1e3]);const L=this.hls.maxAutoLevel;if(L>=0){const O=this.hls.levels[L];O&&(v.tpb=[O.bitrate/1e3])}}const E=p?this.getNextPart(p):this.getNextFrag(d);E!=null&&E.url&&E.url!==d.url&&(E.byteRange.length>0?v.nor=[S6t(E.url,{r:`${E.byteRange[0]}-${E.byteRange[1]}`})]:v.nor=[E.url]),this.apply(i,v)}catch(d){this.hls.logger.warn("Could not generate segment CMCD data.",d)}},this.recordFragmentResponse=(i,a,c)=>{var d;const{cmcd:p}=this.config,l=p==null||(d=p.eventTargets)==null?void 0:d.some(g=>{var v;return(v=g.events)==null?void 0:v.includes(xM.RESPONSE_RECEIVED)});if(!(!this.reporter||!(c.loading.first>0)||!l))try{this.reporter.recordResponseReceived({request:{url:i},status:a.code,resourceTiming:{startTime:c.loading.start,responseStart:c.loading.first,duration:c.loading.end-c.loading.start,encodedBodySize:c.total}})}catch(g){this.hls.logger.warn("Could not record fragment response CMCD data.",g)}},this.hls=e;const r=this.config=e.config,{cmcd:n}=r;n!=null&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,r;const{cmcd:n}=this.config;if(n==null)return;const i=n.version||m6t;if(this.reporter=new b6t({sid:n.sessionId||this.hls.sessionId,cid:n.contentId,version:i,transmissionMode:n.useHeaders===!0?pNe:YQ,enabledKeys:(e=n.includeKeys)!=null?e:[...i>=gP?RH:qB],eventTargets:((r=n.eventTargets)!=null?r:[]).map(a=>{let{includeKeys:c}=a,d=$B(a,E6t);return Hn(Hn({},d),{},{enabledKeys:c??RH})})},n.loader),this.reporter.update({sf:w6t.HLS,sta:this.playerState}),n.reporterCallback){const a=this.reporter,c={updateCustomData:d=>{Bpe(d)&&a.update(d)},recordCustomEvent:(d,p={})=>{Bpe(p)&&a.recordEvent(xM.CUSTOM_EVENT,Hn({cen:d},p))}};n.reporterCallback(c)}this.reporter.start()}registerListeners(){const e=this.hls;e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Ee.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Ee.MEDIA_ENDED,this.onMediaEnded,this),e.on(Ee.ERROR,this.onError,this),e.on(Ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Ee.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(Ee.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(Ee.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const e=this.hls;e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Ee.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Ee.MEDIA_ENDED,this.onMediaEnded,this),e.off(Ee.ERROR,this.onError,this),e.off(Ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Ee.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(Ee.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(Ee.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,r){const n=this.media=r.media;this.setPlayerState(this.media.autoplay?Im.STARTING:Im.PRELOADING),_a(n,"waiting",this.onWaiting),_a(n,"play",this.onPlay),_a(n,"playing",this.onPlaying),_a(n,"pause",this.onPause),_a(n,"seeking",this.onSeeking),_a(n,"seeked",this.onSeeked),_a(n,"ratechange",this.onRateChange)}onMediaDetached(){const e=this.media;e&&(da(e,"waiting",this.onWaiting),da(e,"play",this.onPlay),da(e,"playing",this.onPlaying),da(e,"pause",this.onPause),da(e,"seeking",this.onSeeking),da(e,"seeked",this.onSeeked),da(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,r){this.setPlayerState(Im.ENDED)}onManifestLoading(e,r){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Im.PRELOADING)}onError(e,r){r.fatal&&(this.setPlayerState(Im.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(xM.ERROR,{ec:[r.details]}))}onLevelSwitching(e,r){var n;if(!this.reporter)return;const i={br:[r.bitrate/1e3]},a=(n=r.details)==null?void 0:n.fragments[0];a&&(i.ot=this.getObjectType(a,r)),this.reporter.recordEvent(xM.BITRATE_CHANGE,i)}onLevelSwitched(e,r){const n=this.hls.levels[r.level];n&&(this.playheadLevel=n)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){const e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?d8.LOW_LATENCY:d8.LIVE:d8.VOD}apply(e,r={}){var n;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(n=this.media)==null?void 0:n.playbackRate,st:this.getStreamType()});const i=r.ot===Eu.INIT||r.ot===Eu.VIDEO||r.ot===Eu.MUXED;this.starved&&i&&(r.bs=!0,r.su=!0,this.starved=!1),r.su==null&&(r.su=this.buffering);const a=this.reporter.createRequestReport({url:e.url,headers:e.headers},r);e.url=a.url,e.headers=a.headers}getNextFrag(e){var r;const n=(r=this.hls.levels[e.level])==null?void 0:r.details;if(n){const i=e.sn-n.startSN;return n.fragments[i+1]}}getNextPart(e){var r;const{index:n,fragment:i}=e,a=(r=this.hls.levels[i.level])==null||(r=r.details)==null?void 0:r.partList;if(a){const{sn:c}=i;for(let d=a.length-1;d>=0;d--){const p=a[d];if(p.index===n&&p.fragment.sn===c)return a[d+1]}}}getObjectType(e,r){const{type:n}=e;if(n==="subtitle")return Eu.TIMED_TEXT;if(e.sn==="initSegment")return Eu.INIT;if(n==="audio")return Eu.AUDIO;if(n==="main"){if(e.hasStreams){const i=e.elementaryStreams;if(i.audiovideo)return Eu.MUXED;if(i.video)return Eu.VIDEO;if(i.audio)return Eu.AUDIO}if(r){const{audioCodec:i,videoCodec:a}=r;if(!this.hls.audioTracks.length){if(i&&a)return Eu.MUXED;if(i)return Eu.AUDIO}if(a)return Eu.VIDEO}}}getTopBandwidth(){let e=0;const r=this.hls,n=r.maxAutoLevel,i=n>-1?n+1:r.levels.length;return r.levels.slice(0,i).forEach(c=>{c.bitrate>e&&(e=c.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0;const r=this.hls,n=r.maxAutoLevel,i=n>-1?n+1:r.levels.length;return r.levels.slice(0,i).forEach(c=>{c.bitrate{l(g,v,E,T),n(c.url,g,v)}}))}}}}const A6t=3e5;class k6t extends ff{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Ee.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Ee.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,r)=>(e.indexOf(r.pathwayId)===-1&&e.push(r.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const r=this.levels;r&&(this.levels=r.filter(n=>n!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,r){const{contentSteering:n}=r;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,r){this.audioTracks=r.audioTracks,this.subtitleTracks=r.subtitleTracks}onError(e,r){const{errorAction:n}=r;if((n==null?void 0:n.action)===ju.SendAlternateToPenaltyBox&&n.flags&Zc.MoveAllAlternatesMatchingHost){const i=this.levels;let a=this._pathwayPriority,c=this.pathwayId;if(r.context){const{groupId:d,pathwayId:p,type:l}=r.context;d&&i?c=this.getPathwayForGroupId(d,l,c):p&&(c=p)}c in this.penalizedPathways||(this.penalizedPathways[c]=performance.now()),!a&&i&&(a=this.pathways()),a&&a.length>1&&(this.updatePathwayPriority(a),n.resolved=this.pathwayId!==c,!n.resolved&&(r.details!==Wt.BUFFER_APPEND_ERROR||r.fatal)&&this.warn(`Could not resolve ${r.details} ("${r.error.message}") with content-steering for Pathway: ${c} levels: ${i&&i.length} priorities: ${fo(a)} penalized: ${fo(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let r=this.getLevelsForPathway(this.pathwayId);if(r.length===0){const n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),r=this.getLevelsForPathway(n),this.pathwayId=n}return r.length!==e.length&&this.log(`Found ${r.length}/${e.length} levels in Pathway "${this.pathwayId}"`),r}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(r=>e===r.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let r;const n=this.penalizedPathways,i=performance.now();Object.keys(n).forEach(a=>{i-n[a]>A6t&&delete n[a]});for(let a=0;a0){this.log(`Setting Pathway to "${c}"`),this.pathwayId=c,CPe(r),this.hls.trigger(Ee.LEVELS_UPDATED,{levels:r});const l=this.hls.levels[d];p&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==p.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==p.bitrate&&this.log(`Unstable Pathways change from bitrate ${p.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=d);break}}}getPathwayForGroupId(e,r,n){const i=this.getLevelsForPathway(n).concat(this.levels||[]);for(let a=0;a{const{ID:c,"BASE-ID":d,"URI-REPLACEMENT":p}=a;if(r.some(g=>g.pathwayId===c))return;const l=this.getLevelsForPathway(d).map(g=>{const v=new Vo(g.attrs);v["PATHWAY-ID"]=c;const E=v.AUDIO&&`${v.AUDIO}_clone_${c}`,T=v.SUBTITLES&&`${v.SUBTITLES}_clone_${c}`;E&&(n[v.AUDIO]=E,v.AUDIO=E),T&&(i[v.SUBTITLES]=T,v.SUBTITLES=T);const j=yNe(g.uri,v["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",p),P=new dP({attrs:v,audioCodec:g.audioCodec,bitrate:g.bitrate,height:g.height,name:g.name,url:j,videoCodec:g.videoCodec,width:g.width});if(g.audioGroups)for(let C=1;C{this.log(`Loaded steering manifest: "${i}"`);const j=g.data;if((j==null?void 0:j.VERSION)!==1){this.log(`Steering VERSION ${j.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=j.TTL;const{"RELOAD-URI":P,"PATHWAY-CLONES":C,"PATHWAY-PRIORITY":L}=j;if(P)try{this.uri=new self.URL(P,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${P}`);return}this.scheduleRefresh(this.uri||E.url),C&&this.clonePathways(C);const O={steeringManifest:j,url:i.toString()};this.hls.trigger(Ee.STEERING_MANIFEST_LOADED,O),L&&this.updatePathwayPriority(L)},onError:(g,v,E,T)=>{if(this.log(`Error loading steering manifest: ${g.code} ${g.text} (${v.url})`),this.stopLoad(),g.code===410){this.enabled=!1,this.log(`Steering manifest ${v.url} no longer available`);return}let j=this.timeToLoad*1e3;if(g.code===429){const P=this.loader;if(typeof(P==null?void 0:P.getResponseHeader)=="function"){const C=P.getResponseHeader("Retry-After");C&&(j=parseFloat(C)*1e3)}this.log(`Steering manifest ${v.url} rate limited`);return}this.scheduleRefresh(this.uri||v.url,j)},onTimeout:(g,v,E)=>{this.log(`Timeout loading steering manifest (${v.url})`),this.scheduleRefresh(this.uri||v.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(a,p,l)}scheduleRefresh(e,r=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var n;const i=(n=this.hls)==null?void 0:n.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},r)}}function zpe(t,e,r,n){t&&Object.keys(e).forEach(i=>{const a=t.filter(c=>c.groupId===i).map(c=>{const d=La({},c);return d.details=void 0,d.attrs=new Vo(d.attrs),d.url=d.attrs.URI=yNe(c.url,c.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),d.groupId=d.attrs["GROUP-ID"]=e[i],d.attrs["PATHWAY-ID"]=n,d});t.push(...a)})}function yNe(t,e,r,n){if(e){const{[r]:d}=n;if(d){const p=d[e];if(p)return p}}const{HOST:i,PARAMS:a}=n,c=new self.URL(t);return i&&(c.hostname=i),a&&Object.keys(a).sort().forEach(d=>{d&&fv(c,d,a[d])}),c.href}class I6t{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new OQ,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((e,r)=>{this.emitter.on("error",r),this.emitter.on("resolved",e)})}reset(){this.emitter.removeAllListeners();const e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}class Cm extends Error{constructor(e,r){super(r),this.data=void 0,e.error||(e.error=new Error(r)),this.data=e,e.err=e.error}}class yP extends ff{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysChain=yP.CDMCleanupPromise||Promise.resolve(),this.onMediaEncrypted=r=>{const{initDataType:n,initData:i}=r,a=`"${r.type}" event: init data type: "${n}"`;if(this.log(a),i!==null){if(!this.keyFormatPromise){let c=Object.keys(this.keySystemAccessPromises);c.length||(c=SI(this.config));const d=c.map(i8).filter(p=>!!p);this.keyFormatPromise=this.getKeyFormatPromise(d)}this.keyFormatPromise.then(c=>{let d;const p=mM(c),l=this.activeLevelKeys();if(p===So.FAIRPLAY&&n==="sinf")try{const j=np(new Uint8Array(i)),P=IQ(JSON.parse(j).sinf),C=XCe(P);if(!C)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");d=new Uint8Array(C.subarray(8,24))}catch(j){this.warn(`${a} Failed to parse sinf: ${j}`);return}else if(p===So.PLAYREADY)d=DQ(new Uint8Array(i));else if(p===So.WIDEVINE){const j=tPe(i).filter(P=>P.systemId===wPe.WIDEVINE);if(j.length){var g;const P=j[0];d=(g=P.kids)!=null&&g.length?P.kids[0]:null}}let v;if(d){const j=lc(d);for(let P=0;Pthis.handleError(c))}},this.onWaitingForKey=r=>{this.log(`"${r.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:e}=this;e&&(e.on(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ee.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Ee.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ee.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Ee.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));const r=this.hls.levels,n=(c,d,p)=>!!c&&p.indexOf(c)===d,i=r.map(c=>c.audioCodec).filter(n),a=r.map(c=>c.videoCodec).filter(n);return i.length+a.length===0&&a.push("avc1.42e01e"),new Promise((c,d)=>{const p=l=>{const g=l.shift();this.getMediaKeysPromise(g,i,a).then(v=>c({keySystem:g,mediaKeys:v})).catch(v=>{l.length?p(l):v instanceof Cm?d(v):d(new Cm({type:Kn.KEY_SYSTEM_ERROR,details:Wt.KEY_SYSTEM_NO_ACCESS,error:v,fatal:!0},v.message))})};p(e)})}requestMediaKeySystemAccess(e,r){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${n}`;return SPe===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return n(e,r)}getMediaKeysPromise(e,r,n){var i;const a=ezt(e,r,n,this.config.drmSystemOptions||{});let c=this.keySystemAccessPromises[e],d=(i=c)==null?void 0:i.keySystemAccess;if(!d){this.log(`Requesting encrypted media "${e}" key-system access with config: ${fo(a)}`),d=this.requestMediaKeySystemAccess(e,a);const p=c=this.keySystemAccessPromises[e]={keySystemAccess:d};return d.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),d.then(l=>{this.throwIfDestroyed(),this.log(`Access for key-system "${l.keySystem}" obtained`);const g=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const v=p.mediaKeys=l.createMediaKeys().then(E=>(this.log(`Media-keys created for "${e}"`),p.createdMediaKeys=E,g.then(T=>T?this.setMediaKeysServerCertificate(E,e,T):E)));return v.catch(E=>{this.error(`Failed to create media-keys for "${e}"}: ${E}`)}),v})}return d.then(()=>c.mediaKeys)}getMediaKeySessionContext(e,r,n,i){const{mediaKeySessions:a}=this,c=` key-session "${e}" keyId: ${lc(n.keyId||[])} keyUri: ${n.uri} for "${i}"`;for(let l=0;l({keySystem:e,hasMediaKeys:!!this.keySystemAccessPromises[e].createdMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>i8(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:r,mediaKeys:n})=>this.attemptSetMediaKeys(r,n))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:r})=>{const n=i8(r);if(!n)throw new Error(`Unable to find format for key-system "${r}"`);return n})}selectKeySystemFormat(e){const r=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)),this.keyFormatPromise}getKeyFormatPromise(e){const r=SI(this.config),n=e.map(mM).filter(i=>!!i&&r.indexOf(i)!==-1);return this.selectKeySystem(n)}loadClear(e,r,n){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(r.length)for(let i=0,a=r.length;i{if(!this.hls)return;c.setKeyFormat(d);const p=mM(d);if(p)return this.getKeySystemAccess([p])})}if(this.config.requireKeySystemAccessOnStart){const i=SI(this.config);if(i.length)return this.getKeySystemAccess(i)}}return null}getKeyStatus(e){const{mediaKeySessions:r}=this;for(let n=0;n(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,r,n){const i=this.getSessionForKey(e,r);return i.catch(a=>this.handleError(a,n)),i.then(a=>e)}getSessionForKey(e,r){const n=this.findContextForKey(e);if(n!==void 0)return Promise.resolve(n);const i=e.uri,a=this.sessionSetupByUri[i];let c;a===void 0?c=this.resolveSessionForKey(e,r):c=a.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,r))),this.sessionSetupByUri[i]=c;const d=()=>{this.sessionSetupByUri[i]===c&&delete this.sessionSetupByUri[i]};return c.then(d,d),c}findContextForKey(e){const{mediaKeySessions:r}=this;for(let n=r.length;n--;){const i=r[n];if(h8(e,i))return i}}resolveSessionForKey(e,r){return this.getKeySystemForKeyPromise(e).then(({keySystem:n,mediaKeys:i})=>{this.throwIfDestroyed();for(let a=this.mediaKeySessions.length;a--;){const c=this.mediaKeySessions[a];if(h8(e,c))return c;const d=this.getUsableKeyPromise(c,e,r);if(d)return d}return this.attemptSetMediaKeys(n,i).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(n,i,e,r))).then(a=>{this.throwIfDestroyed();const c=e.scheme||"cenc",d=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(a,e,c,d,r)})})}getUsableKeyPromise(e,r,n){const i=e.keyRequests[r.uri];if(i)return this.log(`Waiting for usable key (${n} keyId: ${P6t(r)} format: "${r.keyFormat}" URI: ${r.uri})`),i.useable.then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,r){if(this.hls)if(e instanceof Cm){r&&(e.data.frag=r);const n=e.data.decryptdata;this.error(`${e.message}${n?` (${lc(n.keyId||[])})`:""}`),this.hls.trigger(Ee.ERROR,e.data)}else this.error(e.message),this.hls.trigger(Ee.ERROR,{type:Kn.KEY_SYSTEM_ERROR,details:Wt.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0,reason:`${e.name}: ${e.message}`})}getKeySystemForKeyPromise(e){const r=mM(e.keyFormat),n=r?[r]:SI(this.config);return this.attemptKeySystemAccess(n)}getKeySystemSelectionPromise(e){if(e.length||(e=SI(this.config)),e.length===0)throw new Cm({type:Kn.KEY_SYSTEM_ERROR,details:Wt.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${fo({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){const e=this.activeKeys,r=(e.previous||[]).map(n=>n.decryptdata);return e.audio&&r.unshift(e.audio.decryptdata),e.main&&r.unshift(e.main.decryptdata),r}queueSetMediaKeys(e){const r=this.setMediaKeysChain.then(e);return this.setMediaKeysChain=r.catch(n=>{this.log(`setMediaKeys failed: ${n}`)}),r}attemptSetMediaKeys(e,r){return this.mediaKeys===r?Promise.resolve():(this.log(`Setting media-keys for "${e}"`),this.mediaKeys=r,this.queueSetMediaKeys(()=>this.media?this.media.setMediaKeys(r):new Promise((n,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=r,this.media.setMediaKeys(r).then(n).catch(i)}})).then(()=>{this.log(`Media-keys set for "${e}"`)},n=>{throw this.mediaKeys===r&&(this.mediaKeys=null),n}))}filterInitData(e,r,n,i,a){var c;const d=(c=this.config.drmSystems)==null||(c=c[e.keySystem])==null?void 0:c.generateRequest;if(d)try{const l=d.call(this.hls,n,i,La({},e,{decryptdata:r,reason:a}),a);if(!l)throw new Error("Invalid response from configured generateRequest filter");r.scheme=l.initDataType?l.initDataType:"cenc";const g=l.initData?l.initData:null;return r.pssh=g?new Uint8Array(g):null,l}catch(l){var p;if(this.warn(l.message),(p=this.hls)!=null&&p.config.debug)throw l}return{initDataType:n,initData:i}}generateRequestWithPreferredKeySession(e,r,n,i,a){const c=this.getUsableKeyPromise(e,r,a);if(c)return c;const d=this.filterInitData(e,r,n,i,a);if(d&&(i=d.initData?d.initData:null,n=d.initDataType),i===null)return a.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${a}"`)):(this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(e));const p=r.uri,l=new I6t;e.keyRequests[p]=l;const g=E=>{const T=e.mediaKeysSession;if(!T){const C=new Error("invalid state");l.errored=C;return}const{messageType:j,message:P}=E;l.status=j,this.log(`"${j}" message event for session "${T.sessionId}" message size: ${P.byteLength}`),j==="license-request"||j==="license-renewal"?this.renewLicense(e,r,P).catch(C=>{l.errored=C,l.hasListeners||this.handleError(C),this.removeSession(e)}):j==="license-release"?e.keySystem===So.FAIRPLAY&&this.updateKeySession(e,r,TH("acknowledged")).then(()=>this.removeSession(e)).catch(C=>this.handleError(C)):this.warn(`unhandled media key message type "${j}"`)};return l.onmessage=g,_a(e.mediaKeysSession,"message",g),this.generateRequest(e,r,n,i,a,!1)}generateRequest(e,r,n,i,a,c){if(c){const T=this.filterInitData(e,r,n,i,a);T&&(i=T.initData?T.initData:i,n=T.initDataType)}const d=r.uri,p=e.keyRequests[d],l=lc(r.keyId||[]),g=T=>{let j;T.startsWith("usable")?p.resolve():T==="internal-error"||T==="output-restricted"||T==="output-downscaled"?j=$pe(T,r):T==="expired"?j=new Error(`key expired (keyId: ${l})`):T==="released"?j=new Error("key released"):T==="status-pending"||this.warn(`unhandled key status change "${T}" (keyId: ${l})`),j&&(p.errored=j,p.hasListeners||this.handleError(j))},v=T=>{if(!e.mediaKeysSession){const G=new Error("invalid state");p.errored=G;return}const P=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(P).some(G=>P[G]!=="status-pending"))return;const L=this.activeLevelKeys();for(let G=0;Gthis.handleError(Z));break}}let F=P[l];if(F)g(F);else{var $;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),($=e.keyStatusTimeouts)[l]||($[l]=self.setTimeout(()=>{var W;if(!e.mediaKeysSession)return;const Z=this.getKeyStatus(r);if(Z&&Z!=="status-pending"){var Q;return this.log(`No status for keyId ${l} in key-session "${(Q=e.mediaKeysSession)==null?void 0:Q.sessionId}". Using session key-status ${Z} from other session.`),g(Z)}this.log(`key status for ${l} in key-session "${(W=e.mediaKeysSession)==null?void 0:W.sessionId}" timed out after 1000ms`),F="internal-error",g(F)},1e3)),this.log(`No status for keyId ${l} (${fo(P)}).`)}};p.onkeystatuseschange=v,_a(e.mediaKeysSession,"keystatuseschange",v);const E=p.useable;return this.log(`Generating key-session request for "${a}" keyId: ${l} URI: ${d} (init data type: ${n} length: ${i.byteLength})`),p.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(n,i).then(()=>{var T;p.status="generated",this.log(`Request generated for key-session "${(T=e.mediaKeysSession)==null?void 0:T.sessionId}" keyId: ${l} URI: ${d}`)}).catch(T=>{throw this.log(`mediaKeysSession.generateRequest failed: ${T}`),new Cm({type:Kn.KEY_SYSTEM_ERROR,details:Wt.KEY_SYSTEM_NO_SESSION,error:T,decryptdata:r,fatal:!1},`Error generating key-session request: ${T}`)}).then(()=>E).catch(T=>{var j;this.log(`mediaKeysSession.generateRequest failed: ${T}`);const P=(j=T.data)==null?void 0:j.details;return(P===Wt.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||P===Wt.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(C=>e.keyStatuses[C]==="usable")?(this.handleError(T),e):this.removeSession(e).then(()=>{throw T})}).then(()=>e)}getKeyStatuses(e){const r={},n=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((i,a)=>{if(typeof a=="string"&&typeof i=="object"){const p=a;a=i,i=p}const c="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(e.keySystem===So.PLAYREADY&&c.length===16){const p=lc(c);r[p]=i,vPe(c)}const d=lc(c);this.log(`key status change "${i}" for keyStatuses keyId: ${d} key-session "${n}"`),r[d]=i}),r}fetchServerCertificate(e){const r=this.config,n=r.loader,i=new n(r),a=C6t(e,r);return a?(this.log(`Fetching server certificate for "${e}"`),new Promise((c,d)=>{const p={type:ts.SERVER_CERTIFICATE,responseType:"arraybuffer",url:a},l=r.certLoadPolicy.default,g={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},v={onSuccess:(E,T,j,P)=>{c(E.data)},onError:(E,T,j,P)=>{d(new Cm({type:Kn.KEY_SYSTEM_ERROR,details:Wt.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:j,response:Hn({url:p.url,data:void 0},E)},`"${e}" certificate request failed (${a}). Status: ${E.code} (${E.text})`))},onTimeout:(E,T,j)=>{d(new Cm({type:Kn.KEY_SYSTEM_ERROR,details:Wt.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:j,response:{url:p.url,data:void 0}},`"${e}" certificate request timed out (${a})`))},onAbort:(E,T,j)=>{d(new Error("aborted"))}};i.load(p,g,v)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,r,n){return new Promise((i,a)=>{e.setServerCertificate(n).then(c=>{this.log(`setServerCertificate ${c?"success":"not supported by CDM"} (${n.byteLength}) on "${r}"`),i(e)}).catch(c=>{a(new Cm({type:Kn.KEY_SYSTEM_ERROR,details:Wt.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:c,fatal:!0},c.message))})})}renewLicense(e,r,n){return this.requestLicense(e,r,new Uint8Array(n)).then(i=>this.updateKeySession(e,r,new Uint8Array(i)).catch(a=>{throw new Cm({type:Kn.KEY_SYSTEM_ERROR,details:Wt.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:r,error:a,fatal:!1},a.message)}))}unpackPlayReadyKeyMessage(e,r){const n=np(new Uint16Array(r.buffer));if(!n.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),r;const i=new DOMParser().parseFromString(n,"application/xml"),a=i.querySelectorAll("HttpHeader");if(a.length>0){let g;for(let v=0,E=a.length;v in key message");return TH(atob(l))}setupLicenseXHR(e,r,n,i,a){const c=this.config.licenseXhrSetup;return c?Promise.resolve().then(()=>(this.throwIfDestroyed(),c.call(this.hls,e,r,Hn(Hn({},n),{},{decryptdata:i}),a))).catch(d=>{if(!n.mediaKeysSession)throw d;return e.open("POST",r,!0),c.call(this.hls,e,r,Hn(Hn({},n),{},{decryptdata:i}),a)}).then(d=>(e.readyState||e.open("POST",r,!0),{xhr:e,licenseChallenge:d||a})):(e.open("POST",r,!0),Promise.resolve({xhr:e,licenseChallenge:a}))}requestLicense(e,r,n){return new Promise((i,a)=>{const c=j6t(e.keySystem,this.config);if(!c)return a(new Error(`no license server URL configured for key-system "${e.keySystem}"`));const d=e.keyRequests[r.uri];if(!d)return a(new Error("License emitter removed"));this.log(`Sending license request to URL: ${c}`);const p=this.config.keyLoadPolicy.default,l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(l.readyState===4)if(l.status===200){d.requestErrors=[];let g=l.response;this.log(`License received ${g instanceof ArrayBuffer?g.byteLength:g}`);const v=this.config.licenseResponseCallback;if(v)try{g=v.call(this.hls,l,c,Hn(Hn({},e),{},{decryptdata:r}))}catch(E){this.error(E)}i(g)}else{const g=p.errorRetry,v=g?g.maxNumRetry:0;if(d.requestErrors.push({status:l.status,message:l.statusText}),d.requestErrors.length>v||l.status>=400&&l.status<500)a(new Cm({type:Kn.KEY_SYSTEM_ERROR,details:Wt.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:r,fatal:!0,networkDetails:l,response:{url:c,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${c}). Status: ${l.status} (${l.statusText})`));else{const E=v-d.requestErrors.length;this.warn(`Retrying license request, ${E} attempts left`),this.requestLicense(e,r,n).then(i,a)}}},d.licenseXhr&&d.licenseXhr.readyState!==XMLHttpRequest.DONE&&d.licenseXhr.abort(),d.licenseXhr=l,this.setupLicenseXHR(l,c,e,r,n).then(({xhr:g,licenseChallenge:v})=>{e.keySystem==So.PLAYREADY&&(v=this.unpackPlayReadyKeyMessage(g,v)),g.send(v)}).catch(a)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,_a(n,"encrypted",this.onMediaEncrypted),_a(n,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=n.mediaKeys}onMediaDetached(){const e=this.media;e&&(da(e,"encrypted",this.onMediaEncrypted),da(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(e=!1){this.keyFormatPromise=null,e||(this.keySystemAccessPromises={}),this.activeKeys={},this.sessionSetupByUri={};const r=this.mediaResolved;if(r&&r(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const n=this.media,i=e&&this.config.reuseKeySessions,a=i?[]:this.mediaKeySessions.slice();i||(this.mediaKeySessions=[],By.clearKeyUriToKeyIdMap()),e||(this.mediaKeys=null);const c=a.length,d=n&&!e?this.queueSetMediaKeys(()=>n.setMediaKeys(null)).catch(p=>{this.log(`Could not clear media keys: ${p}`),this.hls&&this.hls.trigger(Ee.ERROR,{type:Kn.OTHER_ERROR,details:Wt.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${p}`)})}):Promise.resolve();yP.CDMCleanupPromise=Promise.all(a.map(p=>this.removeSession(p)).concat(d)).catch(p=>{this.log(`Could not close sessions and clear media keys: ${p}`),this.hls&&this.hls.trigger(Ee.ERROR,{type:Kn.OTHER_ERROR,details:Wt.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${p}`)})}).then(()=>{c&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){var e;const r=(e=this.hls)==null||(e=e.media)==null?void 0:e.mediaKeys,n=!!r&&Object.keys(this.keySystemAccessPromises).some(i=>{var a;return i!==So.FAIRPLAY&&((a=this.keySystemAccessPromises[i])==null?void 0:a.createdMediaKeys)===r});this._clear(n),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:r}){if(!(!r||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=r.reduce((i,a)=>(i.indexOf(a.keyFormat)===-1&&i.push(a.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n),this.keyFormatPromise.catch(()=>{})}}removeSession(e){const{mediaKeysSession:r}=e;if(r){this.log(`Remove licenses and keys and close session "${r.sessionId}"`),Object.keys(e.keyRequests).forEach(d=>{const p=e.keyRequests[d];p.onmessage&&r.removeEventListener("message",p.onmessage),p.onkeystatuseschange&&r.removeEventListener("keystatuseschange",p.onkeystatuseschange),p.reset(),e.keyRequests[d]=void 0}),e.mediaKeysSession=void 0;const n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);const{keyStatusTimeouts:i}=e;i&&Object.keys(i).forEach(d=>self.clearTimeout(i[d]));const{drmSystemOptions:a}=this.config;return(rzt(a)?new Promise((d,p)=>{self.setTimeout(()=>p(new Error("MediaKeySession.remove() timeout")),8e3),r.remove().then(d).catch(p)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(Ee.ERROR,{type:Kn.OTHER_ERROR,details:Wt.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>r.close()).then(()=>r.closed).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(Ee.ERROR,{type:Kn.OTHER_ERROR,details:Wt.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}yP.CDMCleanupPromise=void 0;function j6t(t,e){const{drmSystems:r,widevineLicenseUrl:n}=e,i=r==null?void 0:r[t];if(i)return i.licenseUrl;if(t===So.WIDEVINE&&n)return n}function C6t(t,e){const{drmSystems:r}=e,n=r==null?void 0:r[t];if(n)return n.serverCertificateUrl}function P6t(t){if(t.keyFormat===Lu.FAIRPLAY)return t.uri;if(t.keyId===null)throw new Error("keyId is null");return lc(t.keyId)}function h8(t,e){const r=t.keyId,n=e.mediaKeysSession;if(r&&n){const i=e.mediaKeysSession.keyStatuses;if(i.size)return i.has(r)?i.get(r):e.keyStatuses[lc(r)]}}function $pe(t,e){const r=t==="output-restricted",n=r?Wt.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Wt.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Cm({type:Kn.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:e},r?"HDCP level output restricted":`key status changed to "${t}"`)}class N6t{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Ee.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Ee.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,r){const n=this.hls.config;if(n.capLevelOnFPSDrop){const i=r.media instanceof self.HTMLVideoElement?r.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,r,n){const i=performance.now();if(r){if(this.lastTime){const a=i-this.lastTime,c=n-this.lastDroppedFrames,d=r-this.lastDecodedFrames,p=1e3*c/a,l=this.hls;if(l.trigger(Ee.FPS_DROP,{currentDropped:c,currentDecoded:d,totalDroppedFrames:n}),p>0&&c>l.config.fpsDroppedMonitoringThreshold*d){let g=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+g),g>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=g)&&(g=g-1,l.trigger(Ee.FPS_DROP_LEVEL_CAPPING,{level:g,droppedLevel:l.currentLevel}),l.autoLevelCapping=g,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=n,this.lastDecodedFrames=r}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const r=e.getVideoPlaybackQuality();this.checkFPS(e,r.totalVideoFrames,r.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}var ZQ=function(){if(Q3!=null&&Q3.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function r(d,p){if(typeof p!="string"||!Array.isArray(d))return!1;const l=p.toLowerCase();return~d.indexOf(l)?l:!1}function n(d){return r(t,d)}function i(d){return r(e,d)}function a(d,...p){let l=1;for(;l100)throw new Error("Position must be between 0 and 100.");W=ie,this.hasBeenReset=!0}})),Object.defineProperty(g,"positionAlign",a({},v,{get:function(){return Z},set:function(ie){const oe=i(ie);if(!oe)throw new SyntaxError("An invalid or illegal string was specified.");Z=oe,this.hasBeenReset=!0}})),Object.defineProperty(g,"size",a({},v,{get:function(){return Q},set:function(ie){if(ie<0||ie>100)throw new Error("Size must be between 0 and 100.");Q=ie,this.hasBeenReset=!0}})),Object.defineProperty(g,"align",a({},v,{get:function(){return ee},set:function(ie){const oe=i(ie);if(!oe)throw new SyntaxError("An invalid or illegal string was specified.");ee=oe,this.hasBeenReset=!0}})),g.displayState=void 0}return c.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},c}();class R6t{decode(e,r){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function xNe(t){function e(n,i,a,c){return(n|0)*3600+(i|0)*60+(a|0)+parseFloat(c||0)}const r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?e(r[2],r[3],0,r[4]):e(r[1],r[2],r[3],r[4]):null}class L6t{constructor(){this.values=Object.create(null)}set(e,r){!this.get(e)&&r!==""&&(this.values[e]=r)}get(e,r,n){return n?this.has(e)?this.values[e]:r[n]:this.has(e)?this.values[e]:r}has(e){return e in this.values}alt(e,r,n){for(let i=0;i=0&&n<=100)return this.set(e,n),!0}return!1}}function _Ne(t,e,r,n){const i=n?t.split(n):[t];for(const a in i){if(typeof i[a]!="string")continue;const c=i[a].split(r);if(c.length!==2)continue;const d=c[0],p=c[1];e(d,p)}}const LH=new ZQ(0,0,""),_M=LH.align==="middle"?"middle":"center";function D6t(t,e,r){const n=t;function i(){const d=xNe(t);if(d===null)throw new Error("Malformed timestamp: "+n);return t=t.replace(/^[^\sa-zA-Z-]+/,""),d}function a(d,p){const l=new L6t;_Ne(d,function(E,T){let j;switch(E){case"region":for(let P=r.length-1;P>=0;P--)if(r[P].id===T){l.set(E,r[P].region);break}break;case"vertical":l.alt(E,T,["rl","lr"]);break;case"line":j=T.split(","),l.integer(E,j[0]),l.percent(E,j[0])&&l.set("snapToLines",!1),l.alt(E,j[0],["auto"]),j.length===2&&l.alt("lineAlign",j[1],["start",_M,"end"]);break;case"position":j=T.split(","),l.percent(E,j[0]),j.length===2&&l.alt("positionAlign",j[1],["start",_M,"end","line-left","line-right","auto"]);break;case"size":l.percent(E,T);break;case"align":l.alt(E,T,["start",_M,"end","left","right"]);break}},/:/,/\s/),p.region=l.get("region",null),p.vertical=l.get("vertical","");let g=l.get("line","auto");g==="auto"&&LH.line===-1&&(g=-1),p.line=g,p.lineAlign=l.get("lineAlign","start"),p.snapToLines=l.get("snapToLines",!0),p.size=l.get("size",100),p.align=l.get("align",_M);let v=l.get("position","auto");v==="auto"&&LH.position===50&&(v=p.align==="start"||p.align==="left"?0:p.align==="end"||p.align==="right"?100:50),p.position=v}function c(){t=t.replace(/^\s+/,"")}if(c(),e.startTime=i(),c(),t.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+n);t=t.slice(3),c(),e.endTime=i(),c(),a(t,e)}function vNe(t){return t.replace(//gi,` `)}class M6t{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new R6t,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const r=this;e&&(r.buffer+=r.decoder.decode(e,{stream:!0}));function n(){let a=r.buffer,c=0;for(a=vNe(a);c")===-1){r.cue.id=a;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{D6t(a,r.cue,r.regionList)}catch{r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":{const d=a.indexOf("-->")!==-1;if(!a||d&&(c=!0)){r.oncue&&r.cue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}if(r.cue===null)continue;r.cue.text&&(r.cue.text+=` `),r.cue.text+=a}continue;case"BADCUE":a||(r.state="ID")}}}catch{r.state==="CUETEXT"&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state=r.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=` `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(r){e.onparsingerror&&e.onparsingerror(r)}return e.onflush&&e.onflush(),this}}function kj(t){let e=5381,r=t.length;for(;r;)e=e*33^t.charCodeAt(--r);return(e>>>0).toString()}const O6t=/\r\n|\n\r|\n|\r/g,Upe="Missing initPTS for VTT ",F6t=function(e){let r=parseInt(e.slice(-3));const n=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),a=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!yn(r)||!yn(n)||!yn(i)||!yn(a))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return r+=1e3*n,r+=60*1e3*i,r+=60*60*1e3*a,r};function XQ(t,e,r){return kj(t.toString())+kj(e.toString())+kj(r)}function B6t(t,e,r,n,i,a,c){const d=new M6t,p=Qh(new Uint8Array(t)).trim().replace(O6t,` `).split(` `),l=[],g=e?i$t(e.baseTime,e.timescale):0;let v="00:00.000",E=0,T=0,j=!1,P,C=!0;d.oncue=function(L){const O=r[n];let F=r.ccOffset;const $=(E-g)/9e4;if(j){if(O!=null&&O.new&&(F=r.ccOffset=O.start),$){if(!e){P=new Error(Upe+"MPEGTS");return}F=$-r.presentationOffset}}else if(e)F=-e.baseTime/e.timescale;else{P=new Error(Upe+"without X-TIMESTAMP-MAP");return}const G=L.endTime-L.startTime,W=zh((L.startTime+F-T)*9e4,i*9e4)/9e4;L.startTime=Math.max(W,0),L.endTime=Math.max(W+G,0);const Z=L.text.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");L.text=decodeURIComponent(encodeURIComponent(Z)),L.id?n&&(L.id=`hlsjscc${n}_${L.id}`):L.id=XQ(L.startTime,L.endTime,Z.trim()),L.endTime>0&&l.push(L)},d.onparsingerror=function(L){P=L},d.onflush=function(){if(P){c(P);return}a(l)},p.forEach(L=>{if(C)if(L.startsWith("X-TIMESTAMP-MAP=")){C=!1,j=!0,L.slice(16).split(",").forEach(O=>{O.startsWith("LOCAL:")?v=O.slice(6):O.startsWith("MPEGTS:")&&(E=parseInt(O.slice(7)))});try{T=F6t(v)/1e3}catch(O){P=O}return}else L===""&&(C=!1);d.parse(L+` `)}),d.flush()}const DH="stpp.ttml.im1t",bNe=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,wNe=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,z6t={left:"start",center:"center",right:"end",start:"start",end:"end"};function Vpe(t,e,r,n){const i=Ci(new Uint8Array(t),["mdat"]);if(i.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const a=i.map(d=>Qh(d)),c=n$t(e.baseTime,1,e.timescale);try{a.forEach(d=>r($6t(d,c)))}catch(d){n(d)}}function $6t(t,e){const i=new DOMParser().parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const a={frameRate:30,subFrameRate:1,tickRate:1},c=Object.keys(a).reduce((E,T)=>(E[T]=i.getAttribute(`ttp:${T}`)||a[T],E),{}),d=(i.getAttribute("ttp:frameRateMultiplier")||"").trim().split(/\s+/).map(Number);d.length===2&&d[0]>0&&d[1]>0&&(c.frameRate=Number(c.frameRate)*d[0]/d[1]),!i.getAttribute("ttp:tickRate")&&i.getAttribute("ttp:frameRate")&&(c.tickRate=Number(c.frameRate)*Number(c.subFrameRate));const p=i.getAttribute("xml:space")!=="preserve",l=qpe(f8(i,"styling","style")),g=qpe(f8(i,"layout","region")),v=f8(i,"body","[begin]");return[].map.call(v,E=>{const T=U6t(E,p);if(!T||!E.hasAttribute("begin"))return null;const j=p8(E.getAttribute("begin"),c),P=p8(E.getAttribute("dur"),c);let C=p8(E.getAttribute("end"),c);if(j===null)throw Gpe(E);if(C===null){if(P===null)throw Gpe(E);C=j+P}const L=new ZQ(j-e,C-e,T);L.id=XQ(L.startTime,L.endTime,L.text);const O=g[E.getAttribute("region")],F=l[E.getAttribute("style")],$=V6t(O,F,l),{textAlign:G}=$;if(G){const W=z6t[G];W&&(L.lineAlign=W),L.align=G}return La(L,$),L}).filter(E=>E!==null)}function f8(t,e,r){const n=t.getElementsByTagName(e)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function qpe(t){return t.reduce((e,r)=>{const n=r.getAttribute("xml:id");return n&&(e[n]=r),e},{})}function U6t(t,e){const r=SNe(t,e);return e?r.split(` `).map(n=>n.replace(/ {2,}/g," ").trim()).join(` `):r}function SNe(t,e){return[].slice.call(t.childNodes).reduce((r,n,i)=>{var a;return n.nodeName==="br"&&i?r+` `:(a=n.childNodes)!=null&&a.length?r+SNe(n,e):r+(e?n.textContent.replace(/\s+/g," "):n.textContent)},"")}function V6t(t,e,r){const n="http://www.w3.org/ns/ttml#styling";let i=null;const a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],c=t!=null&&t.hasAttribute("style")?t.getAttribute("style"):null;return c&&r.hasOwnProperty(c)&&(i=r[c]),a.reduce((d,p)=>{const l=m8(e,n,p)||m8(t,n,p)||m8(i,n,p);return l&&(d[p]=l),d},{})}function m8(t,e,r){return t&&t.hasAttributeNS(e,r)?t.getAttributeNS(e,r):null}function Gpe(t){return new Error(`Could not parse ttml timestamp ${t}`)}function p8(t,e){if(!t)return null;if(bNe.test(t))return q6t(t,e);let r=xNe(t);return r===null&&wNe.test(t)&&(r=G6t(t,e)),r}function q6t(t,e){const r=bNe.exec(t),n=(r[4]|0)+(r[5]|0)/e.subFrameRate;return(r[1]|0)*3600+(r[2]|0)*60+(r[3]|0)+n/e.frameRate}function G6t(t,e){const r=wNe.exec(t),n=Number(r[1]);switch(r[2]){case"h":return n*3600;case"m":return n*60;case"ms":return n/1e3;case"f":return n/e.frameRate;case"t":return n/e.tickRate}return n}function QQ(t,e,r,n="",i="disabled"){const a=t.ownerDocument.createElement("track");return a.kind=e,a.label=r,n&&(a.srclang=n),a.src="data:,WEBVTT",a.track.mode=i,t.appendChild(a),a}function H6t(t){return t.forced&&sBt()?"forced":t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function MH(t,e){const r=t.mode;if(r==="disabled"&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(n){la.debug(`[texttrack-utils]: ${n}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(i){la.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}r==="disabled"&&(t.mode=r)}function OH(t,e,r,n){const i=t.mode;if(i==="disabled"&&(t.mode="hidden"),t.cues&&t.cues.length>0){const a=K6t(t.cues,e,r);for(let c=0;ct[r].endTime)return-1;let n=0,i=r,a;for(;n<=i;)if(a=Math.floor((i+n)/2),et[a].startTime&&n-1)for(let a=i,c=t.length;a=e&&d.endTime<=r)n.push(d);else if(d.startTime>r)return n}return n}class Y6t extends UQ{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let r=-1,n=!1;if(this.currentTrack){var i;const d=(i=this.currentTrack.trackNode)==null?void 0:i.track.mode;d==="showing"?(r=this.trackId,n=!0):d==="hidden"&&(r=this.trackId)}if(!n)for(let d=0;d-1){var c;this._subtitleDisplay=((c=this.tracksInGroup[r].trackNode)==null?void 0:c.track.mode)==="showing"}this.setSubtitleTrack(r,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(Ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Ee.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(Ee.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Ee.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(n=>{n.trackNode||(n.trackNode=QQ(this.media,H6t(n),n.name,n.lang))});const r=(e=this.currentTrack)==null||(e=e.trackNode)==null?void 0:e.track;(r==null?void 0:r.mode)==="disabled"&&(r.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,r){const n=r.media;this.media=n;let i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(n.textTracks&&"onchange"in n.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):n.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,r){const n=this.media;if(!n)return;const i=!!r.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!i&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(a=>{const c=a.trackNode;c&&(c.track.mode="hidden",c.remove(),a.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,r){this.tracks=r.subtitleTracks}onSubtitleTrackLoaded(e,r){const{id:n,groupId:i,details:a}=r,c=this.tracksInGroup[n];if(!c||c.groupId!==i){this.warn(`Subtitle track with id:${n} and group:${i} not found in active group ${c==null?void 0:c.groupId}`);return}const d=c.details;c.details=r.details,this.log(`Subtitle track ${n} "${c.name}" lang:${c.lang} group:${i} loaded [${a.startSN}-${a.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,d)}onLevelLoading(e,r){this.switchLevel(r.level)}onLevelSwitching(e,r){this.switchLevel(r.level)}switchLevel(e){const r=this.hls.levels[e];if(!r)return;const n=r.subtitleGroups||null,i=this.groupIds;let a=this.currentTrack;if(!n||(i==null?void 0:i.length)!==(n==null?void 0:n.length)||n!=null&&n.some(c=>(i==null?void 0:i.indexOf(c))===-1)){this.groupIds=n;const c=[];if(this.tracks.forEach(g=>{(g.textCodec===DH?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!n||n.indexOf(g.groupId)>-1?(g.id=c.length,c.push(g)):g.trackNode&&(g.trackNode.remove(),g.trackNode=void 0))}),c.length===this.tracksInGroup.length){let g=!1;for(let v=0;vg.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=c,this.trackId=-1,this.currentTrack=null;const d=this.hls.config.subtitlePreference;if(!a&&d){this.selectDefaultTrack=!1;const g=Jp(d,c);if(g>-1)a=c[g];else{const v=Jp(d,this.tracks);a=this.tracks[v]}}let p=this.findTrackId(a);p===-1&&a&&(p=this.findTrackId(null));const l={subtitleTracks:c};this.log(`Updating subtitle tracks, ${c.length} track(s) found in "${n==null?void 0:n.join(",")}" group-id`),this.hls.trigger(Ee.SUBTITLE_TRACKS_UPDATED,l),this.setSubtitleTrack(p),this.createTracksInGroup()}}findTrackId(e){const r=this.tracksInGroup,n=this.selectDefaultTrack;for(let i=0;i-1){const a=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),a}else{if(n)return null;{const a=Jp(e,r);if(a>-1)return r[a]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,r){super.loadingPlaylist(e,r);const n=e.id,i=e.groupId,a=this.getUrlWithDirectives(e.url,r),c=e.details,d=c==null?void 0:c.age;this.log(`Loading subtitle ${n} "${e.name}" lang:${e.lang} group:${i}${(r==null?void 0:r.msn)!==void 0?" at sn "+r.msn+" part "+r.part:""}${d&&c.live?" age "+d.toFixed(1)+(c.type&&" "+c.type||""):""} ${a}`),this.hls.trigger(Ee.SUBTITLE_TRACK_LOADING,{url:a,id:n,groupId:i,deliveryDirectives:r||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const e=this.currentTrack;this.tracksInGroup.forEach(r=>{if(r.trackNode){const n=r===e?this._subtitleDisplay?"showing":"hidden":"disabled",i=r.trackNode.track;i.mode!==n&&(i.mode=n)}})}setSubtitleTrack(e,r=!1){const n=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=n.length||!yn(e)){this.warn(`Invalid subtitle track id: ${e}`);return}const i=this.currentTrack,a=n[e]||null;if(this.trackId=e,this.currentTrack=a,r&&this.toggleTrackModes(),!a){i&&this.hls.trigger(Ee.SUBTITLE_TRACK_SWITCH,{id:e});return}const c=!!a.details&&!a.details.live;if(a===i&&c)return;this.log(`Switching to subtitle-track ${e}`+(a?` "${a.name}" lang:${a.lang} group:${a.groupId}`:""));const{id:d,groupId:p="",name:l,type:g,url:v}=a;this.hls.trigger(Ee.SUBTITLE_TRACK_SWITCH,{id:d,groupId:p,name:l,type:g,url:v});const E=this.switchParams(a.url,i==null?void 0:i.details,a.details);this.loadPlaylist(E)}}const IO=2,Z6t=100;class X6t extends xPe{constructor(e,r){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var n;(n=this.media)!=null&&n.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var n;this.ended=((n=this.media)==null?void 0:n.currentTime)||1,this.hls.trigger(Ee.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=r,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ee.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ee.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,r){this.setInterval(Z6t),this.mediaSource=r.mediaSource;const n=this.media=r.media;_a(n,"playing",this.onMediaPlaying),_a(n,"waiting",this.onMediaWaiting),_a(n,"ended",this.onMediaEnded)}onMediaDetaching(e,r){this.clearInterval();const{media:n}=this;n&&(da(n,"playing",this.onMediaPlaying),da(n,"waiting",this.onMediaWaiting),da(n,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,r){this.buffered=r.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;const r=((e=this.hls)==null?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,r):r}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const r=this.getCurrentTime();this.media.currentTimer&&this.nudgeOnVideoHole(e,r)),this.waiting===0&&this.stallResolved(e);return}if(l||p){p&&this.stallResolved(e);return}if(g){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&c.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Ee.MEDIA_ENDED,{stalled:!1}));return}if(!xi.getBuffered(c).length){this.skipRetry=this.nudgeRetry=0;return}const v=xi.bufferInfo(c,e,0),E=this.fragmentTracker;E&&this.hls&&Kpe(v,e,E,this.hls);const T=v.nextStart||0;if(d&&E&&this.hls){const W=Hpe(this.hls.inFlightFragments,e),Z=v.len>IO,Q=!T||W||T-e>IO&&!E.getPartialFragment(e);if(Z||Q)return;this.moved=!1}const j=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&E){if(!(v.len>0)&&!T)return;const Z=Math.max(T,v.start||0)-e,ee=!!(j!=null&&j.live)?j.targetduration*2:IO,ie=VI(e,E);if(Z>0&&(Z<=ee||ie)){c.paused||this._trySkipBufferHole(ie);return}}const P=a.detectStallWithCurrentTimeMs,C=self.performance.now(),L=this.waiting;let O=this.stalled;if(O===null)if(L>0&&C-L=P||L&&this.moved)&&this.hls){var $;if((($=this.mediaSource)==null?void 0:$.readyState)==="ended"&&!(j!=null&&j.live)&&Math.abs(e-((j==null?void 0:j.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(Ee.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(v),!this.media||!this.hls)return;if(c.currentTime!==e){const W=e;e=c.currentTime,this.moved=!0,this.log(`currentTime changed ${W} > ${e}`);return}}const G=xi.bufferInfo(c,e,a.maxBufferHole);this._tryFixBufferStall(G,F,e)}stallResolved(e){const r=this.stalled;if(r&&this.hls&&(this.stalled=null,this.stallReported)){const n=self.performance.now()-r;this.log(`playback not stuck anymore @${e}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Ee.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,r){var n;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&i&&i.length>1&&e>i.end(0)){const a=xi.bufferedInfo(xi.timeRangesToArray(this.buffered.audio),e,0);if(a.len>1&&r>=a.start){const c=xi.timeRangesToArray(i),d=xi.bufferedInfo(c,r,0).bufferedIndex;if(d>-1&&dd)&&g-l<1&&e-l<2){const v=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${g} buffered index: ${p}`);this.warn(v.message),this.media.currentTime+=1e-6;let E=VI(e,this.fragmentTracker);E&&"fragment"in E?E=E.fragment:E||(E=void 0);const T=xi.bufferInfo(this.media,e,0);this.hls.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:v,reason:v.message,frag:E,buffer:T.len,bufferInfo:T})}}}}}_tryFixBufferStall(e,r,n){var i,a;const{fragmentTracker:c,media:d}=this,p=(i=this.hls)==null?void 0:i.config;if(!d||!c||!p)return;const l=(a=this.hls)==null?void 0:a.latestLevelDetails,g=VI(n,c);if((g||l!=null&&l.live&&n1&&e.len>p.maxBufferHole||e.nextStart&&(e.nextStart-np.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,r){const n=this.fragmentTracker,i=e.nextStart;if(n&&i){const a=n.getFragAtPos(r,On.MAIN),c=n.getFragAtPos(i,On.MAIN);if(a&&c)return c.sn-a.sn<2}return!1}_reportStall(e){const{hls:r,media:n,stallReported:i,stalled:a}=this;if(!i&&a!==null&&n&&r){this.stallReported=!0;const c=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${fo(e)})`);this.warn(c.message),r.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.BUFFER_STALLED_ERROR,fatal:!1,error:c,buffer:e.len,bufferInfo:e,stalled:{start:a}})}}_trySkipBufferHole(e){const{fragmentTracker:r,media:n,hls:i}=this,a=i==null?void 0:i.config;if(!n||!r||!a)return 0;const c=n.currentTime,d=xi.bufferInfo(n,c,0);Kpe(d,c,r,i);const p=c0&&d.len<1&&n.readyState<3,E=p-c;if(E>0&&(g||v)){if(E>a.maxBufferHole){let L=!1;if(c===0){const O=r.getAppendedFrag(0,On.MAIN);O&&p0)$+=W;else{F=!0;break}}if(F)return 0}}const{nudgeMaxRetry:T,skipBufferHolePadding:j}=a,P=++this.skipRetry>T,C=Math.max(p,c)+j;if(P||(this.warn(`skipping hole, adjusting currentTime from ${c} to ${C}`),this.moved=!0,n.currentTime=C),!(e!=null&&e.gap)||P){const L=new Error(P?`Playhead still not moving after seeking over buffer hole from ${c} to ${C} after ${a.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${c} to ${C}`),O={type:Kn.MEDIA_ERROR,details:Wt.BUFFER_SEEK_OVER_HOLE,fatal:P,error:L,reason:L.message,buffer:d.len,bufferInfo:d};e&&("fragment"in e?O.part=e:O.frag=e),i.trigger(Ee.ERROR,O)}return C}}return 0}_tryNudgeBuffer(e){const{hls:r,media:n,nudgeRetry:i}=this,a=r==null?void 0:r.config;if(!n||!a)return 0;const c=n.currentTime;if(this.nudgeRetry++,i"u"))return self.VTTCue||self.TextTrackCue}function g8(t,e,r,n,i){let a=new t(e,r,"");try{a.value=n,i&&(a.type=i)}catch{a=new t(e,r,fo(i?Hn({type:i},n):n))}return a}const vM=(()=>{const t=FH();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class J6t{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(Ee.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Ee.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Ee.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Ee.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,r){this.media=r.media}onMediaAttached(){var e;const r=(e=this.hls)==null?void 0:e.latestLevelDetails;r&&this.updateDateRangeCues(r)}onMediaDetaching(e,r){this.media=null,!r.transferMedia&&(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return QQ(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,r){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:n,enableID3MetadataCues:i}=this.hls.config;if(!n&&!i)return;const{samples:a}=r;this.id3Track||(this.id3Track=this.createTrack(this.media));const c=FH();if(c)for(let d=0;dvM&&(v=vM),v-g<=0&&(v=g+Q6t);for(let T=0;Tg.type===Pd.audioId3&&p:i==="video"?l=g=>g.type===Pd.emsg&&d:l=g=>g.type===Pd.audioId3&&p||g.type===Pd.emsg&&d,OH(a.track,r,n,l)}}onLevelUpdated(e,{details:r}){this.updateDateRangeCues(r,!0)}onLevelPtsUpdated(e,r){Math.abs(r.drift)>.01&&this.updateDateRangeCues(r.details)}updateDateRangeCues(e,r){if(!this.hls||!this.media)return;const{assetPlayerId:n,timelineOffset:i,enableDateRangeMetadataCues:a,interstitialsController:c}=this.hls.config;if(!a)return;const d=FH();if(n&&i&&!c){const{fragmentStart:P,fragmentEnd:C}=e;let L=this.assetCue;L?(L.startTime=P,L.endTime=C):d&&(L=this.assetCue=g8(d,P,C,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),L&&(L.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(L),L.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:p}=this,{dateRanges:l}=e,g=Object.keys(l);let v=this.dateRangeCuesAppended;if(p&&r){var E;if((E=p.track.cues)!=null&&E.length){const P=Object.keys(v).filter(C=>g.indexOf(C)===-1);for(let C=P.length;C--;){var T;const L=P[C],O=(T=v[L])==null?void 0:T.cues;delete v[L],O&&Object.keys(O).forEach(F=>{const $=O[F];if($){$.removeEventListener("enter",this.onEventCueEnter);try{p.track.removeCue($)}catch{}}})}}else v=this.dateRangeCuesAppended={}}const j=e.fragments[e.fragments.length-1];if(!(g.length===0||!yn(j==null?void 0:j.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let P=0;P{if(pe!==L.id){const Le=l[pe];if(Le.class===L.class&&Le.startDate>L.startDate&&(!oe||L.startDate.01&&(pe.startTime=O,pe.endTime=W);else if(d){let Le=L.attr[oe];QBt(oe)&&(Le=qCe(Le));const Re=g8(d,O,W,{key:oe,data:Le},Pd.dateRange);Re&&(Re.id=C,this.id3Track.track.addCue(Re),$[oe]=Re,c&&(oe==="X-ASSET-LIST"||oe==="X-ASSET-URL")&&Re.addEventListener("enter",this.onEventCueEnter))}}v[C]={cues:$,dateRange:L,durationKnown:G}}}}}function ENe(){return self.SourceBuffer||self.WebKitSourceBuffer}function TNe(){if(!Rv())return!1;const e=ENe();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function eUt(){if(!TNe())return!1;const t=Rv();return typeof(t==null?void 0:t.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(uP(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(uP(e,"audio"))))}function tUt(){var t;const e=ENe();return typeof(e==null||(t=e.prototype)==null?void 0:t.changeType)=="function"}var jm={DISABLED:0,SWITCHING:1,SWITCHED:2};const rUt=100;class ANe extends MQ{constructor(e,r,n){super(e,r,n,"stream-controller",On.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=jm.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,a=i?i.currentTime:null;if(a===null||!yn(a)||(this.log(`Media seeked to ${a}`),!this.getBufferedFrag(a)))return;const c=this.getFwdBufferInfoAtPos(i,a,On.MAIN,0);if(!c||c.len===0){this.log(`Main buffer empty at ${a} on "seeked" event: ${c&&c.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Ee.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(Ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Ee.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Ee.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Ee.BUFFER_CREATED,this.onBufferCreated,this),e.on(Ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Ee.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Ee.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Ee.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Ee.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Ee.BUFFER_CREATED,this.onBufferCreated,this),e.off(Ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Ee.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,r){if(this.levels){const{lastCurrentTime:n,hls:i}=this;if(this.stopLoad(),this.setInterval(rUt),this.level=-1,!this.startFragRequested){let a=i.startLevel;a===-1&&(i.config.testBandwidth&&this.levels.length>1?(a=0,this.bitrateTest=!0):a=i.firstAutoLevel),i.nextLoadLevel=a,this.level=i.loadLevel,this._hasEnoughToStart=!!r}n>0&&e===-1&&!r&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${n}`),e=n),this.state=Tr.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=r?-1:e,!r&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=Tr.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Tr.WAITING_LEVEL:{const{levels:e,level:r}=this,n=e==null?void 0:e[r],i=n==null?void 0:n.details;if(i&&(!i.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(i))break;this.state=Tr.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Tr.IDLE;break}break}case Tr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Tr.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:r,levels:n,media:i}=this;if(r===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const a=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(n!=null&&n[a]))return;const c=n[a],d=this.getMainFwdBufferInfo();if(d===null)return;const p=this.getLevelDetails();if(p&&this._streamEnded(d,p)&&this.altAudio!==jm.SWITCHING){const P={type:this.targetBufferType()};this.hls.trigger(Ee.BUFFER_EOS,P),this.state=Tr.ENDED;return}if(!this.buffering)return;e.loadLevel!==a&&e.manualLevel===-1&&this.log(`Adapting to level ${a} from level ${this.level}`),this.level=e.nextLoadLevel=a;const l=c.details;if(!l||this.state===Tr.WAITING_LEVEL||this.waitForLive(c)){this.level=a,this.state=Tr.WAITING_LEVEL,this.startFragRequested=!1;return}const g=d.len,v=this.getMaxBufferLength(c.maxBitrate);if(g>=v)return;this.backtrackFragment&&this.backtrackFragment.start>d.end&&(this.backtrackFragment=void 0);const E=this.backtrackFragment?this.backtrackFragment.start:d.end;let T=this.getNextFragment(E,l);if(this.couldBacktrack&&!this.fragPrevious&&T&&Ko(T)&&this.fragmentTracker.getState(T)!==wo.OK){var j;const C=((j=this.backtrackFragment)!=null?j:T).sn-l.startSN,L=l.fragments[C-1];L&&T.cc===L.cc&&(T=L,this.fragmentTracker.removeFragment(L))}else this.backtrackFragment&&d.len&&(this.backtrackFragment=void 0);if(T&&this.isLoopLoading(T,E)){if(!T.gap){const C=this.audioOnly&&!this.altAudio?ro.AUDIO:ro.VIDEO,L=(C===ro.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;L&&this.afterBufferFlushed(L,C)}T=this.getNextFragmentLoopLoading(T,l,d,On.MAIN,v)}T&&(this.exceedsMaxBuffer(d,v,T)||this.loadFragment(T,c,E))}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);i===wo.NOT_LOADED||i===wo.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,r)):super.loadFragment(e,r,n):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==jm.DISABLED){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===jm.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){const e=this.fragPlaying;if(!this.checkFragPlaying())return!1;const n=this.fragPlaying;if(n){const i=n.level;this.hls.trigger(Ee.FRAG_CHANGED,{frag:n,previousFrag:e}),(e==null?void 0:e.level)!==i&&this.hls.trigger(Ee.LEVEL_SWITCHED,{level:i})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,r){super.flushMainBuffer(e,r,this.targetBufferType())}targetBufferType(){return this.altAudio===jm.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,r){super.onMediaAttached(e,r);const n=r.media;_a(n,"playing",this.onMediaPlaying),_a(n,"seeked",this.onMediaSeeked)}onMediaDetaching(e,r){const{media:n}=this;n&&(da(n,"playing",this.onMediaPlaying),da(n,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,r),!r.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Ee.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=jm.DISABLED,this.audioOnly=!1}onManifestParsed(e,r){let n=!1,i=!1;for(let a=0;a{if(j>=d.startCC)return!0;delete this.initPTS[j]}),this.tick()}synchronizeToLiveEdge(e){const{config:r,media:n}=this;if(!n)return;const i=this.hls.liveSyncPosition,a=this.playhead,c=e.fragmentStart,d=e.edge,p=a>=c-r.maxFragLookUpTolerance&&a<=d;if(i!==null&&n.duration>i&&(a{this.hls&&this.hls.trigger(Ee.AUDIO_TRACK_SWITCHED,r)}),n.trigger(Ee.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}n.trigger(Ee.AUDIO_TRACK_SWITCHED,r)}}onAudioTrackSwitched(e,r){const n=K3(r.url,this.hls);if(n){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=n?jm.SWITCHED:jm.DISABLED,this.tick()}onBufferCreated(e,r){const n=r.tracks;let i,a,c=!1;for(const d in n){const p=n[d];if(p.id==="main"){if(a=d,i=p,d==="video"){const l=n[d];l&&(this.videoBuffer=l.buffer)}}else c=!0}c&&i?(this.log(`Alternate track found, use ${a}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,r){const{frag:n,part:i}=r,a=n.type===On.MAIN;if(a){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Tr.PARSED&&(this.state=Tr.IDLE);return}let p=!1;if(Ko(n)&&(p=!!n.gap&&!n.tagList.some(l=>l[0]==="GAP")),this.fragBufferedComplete(n,i),p){var c;n.stats.retry++;const l=(c=this.levels)==null?void 0:c[n.level];l&&l.fragmentError++}}const d=this.media;d&&(!this._hasEnoughToStart&&xi.getBuffered(d).length&&(this.seekToStartPos(),this._hasEnoughToStart=!0),a&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,r){var n;if(r.fatal){this.state=Tr.ERROR;return}switch(r.details){case Wt.FRAG_GAP:case Wt.FRAG_PARSING_ERROR:case Wt.FRAG_DECRYPT_ERROR:case Wt.FRAG_LOAD_ERROR:case Wt.FRAG_LOAD_TIMEOUT:case Wt.KEY_LOAD_ERROR:case Wt.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(On.MAIN,r);break;case Wt.LEVEL_LOAD_ERROR:case Wt.LEVEL_LOAD_TIMEOUT:case Wt.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Tr.WAITING_LEVEL&&((n=r.context)==null?void 0:n.type)===ts.LEVEL&&(this.state=Tr.IDLE);break;case Wt.BUFFER_APPEND_NO_PROGRESS:if(r.parent!=="main")return;r.frag&&(r.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${r.frag.sn} of level ${r.frag.level} as a gap after ${r.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(r.frag));break;case Wt.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(On.MAIN,r);break;case Wt.BUFFER_ADD_CODEC_ERROR:case Wt.BUFFER_APPEND_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&this.resetLoadingState();break;case Wt.BUFFER_FULL_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case Wt.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onFragLoadEmergencyAborted(){this.state=Tr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:r}){if(r!==ro.AUDIO||!this.altAudio){const n=(r===ro.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;n&&(this.afterBufferFlushed(n,r),this.tick())}}onLevelsUpdated(e,r){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=r.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const r=e.currentTime;let n=this.startPosition;if(n>=0&&r0&&(p{const{hls:i}=this,a=n==null?void 0:n.frag;if(!a||this.fragContextChanged(a))return;r.fragmentError=0,this.state=Tr.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const c=a.stats;c.parsing.start=c.parsing.end=c.buffering.start=c.buffering.end=self.performance.now(),i.trigger(Ee.FRAG_LOADED,n),a.bitrateTest=!1}).catch(n=>{this.state===Tr.STOPPED||this.state===Tr.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const r=this.playlistType,{hls:n}=this,{remuxResult:i,chunkMeta:a}=e,c=this.getCurrentContext(a);if(!c){this.resetWhenMissingContext(a);return}const{frag:d,part:p,level:l}=c,{video:g,text:v,id3:E,initSegment:T}=i,{details:j}=l,P=this.altAudio?void 0:i.audio;if(this.fragContextChanged(d)){this.fragmentTracker.removeFragment(d);return}if(this.state=Tr.PARSING,T){const C=T.tracks;if(C){const $=d.initSegment||d;if(this.unhandledEncryptionError(T,d))return;this._bufferInitSegment(l,C,$,a),n.trigger(Ee.FRAG_PARSING_INIT_SEGMENT,{frag:$,id:r,tracks:C})}const L=T.initPTS,O=T.timescale,F=this.initPTS[d.cc];if(yn(L)&&(!F||F.baseTime!==L||F.timescale!==O)){const $=T.trackId;this.initPTS[d.cc]={baseTime:L,timescale:O,trackId:$};const G=this.initPTS.slice(0);n.trigger(Ee.INIT_PTS_FOUND,{timestampOffsets:G,frag:d,id:r,initPTS:L,timescale:O,trackId:$})}}if(g&&j){P&&g.type==="audiovideo"&&this.logMuxedErr(d);const C=j.fragments[d.sn-1-j.startSN],L=d.sn===j.startSN,O=!C||d.cc>C.cc;if(i.independent!==!1){const{startPTS:F,endPTS:$,startDTS:G,endDTS:W}=g;if(p)p.elementaryStreams[g.type]={startPTS:F,endPTS:$,startDTS:G,endDTS:W};else if(g.firstKeyFrame&&g.independent&&a.id===1&&!O&&(this.couldBacktrack=!0),g.dropped&&g.independent){const Z=this.getMainFwdBufferInfo(),Q=(Z?Z.end:this.getLoadPosition())+this.config.maxBufferHole,ee=g.firstKeyFramePTS?g.firstKeyFramePTS:F;if(!L&&QIO&&(d.gap=!0);d.setElementaryStreamInfo(g.type,F,$,G,W),this.backtrackFragment&&(this.backtrackFragment=d),this.bufferFragmentData(g,d,p,a,L||O)}else if(L||O)d.gap=!0;else{this.backtrack(d);return}}if(P){const{startPTS:C,endPTS:L,startDTS:O,endDTS:F}=P;p&&(p.elementaryStreams[ro.AUDIO]={startPTS:C,endPTS:L,startDTS:O,endDTS:F}),d.setElementaryStreamInfo(ro.AUDIO,C,L,O,F),this.bufferFragmentData(P,d,p,a)}if(j&&E!=null&&E.samples.length){const C={id:r,frag:d,details:j,samples:E.samples};n.trigger(Ee.FRAG_PARSING_METADATA,C)}if(j&&v){const C={id:r,frag:d,details:j,samples:v.samples};n.trigger(Ee.FRAG_PARSING_USERDATA,C)}}logMuxedErr(e){this.warn(`${Ko(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,r,n,i){if(this.state!==Tr.PARSING)return;this.audioOnly=!!r.audio&&!r.video,this.altAudio&&!this.audioOnly&&(delete r.audio,r.audiovideo&&this.logMuxedErr(n));const{audio:a,video:c,audiovideo:d}=r;if(a){const l=e.audioCodec;let g=SO(a.codec,l);if(g==="mp4a"&&(g="mp4a.40.5"),this.audioCodecSwitch){g&&(g.indexOf("mp4a.40.5")!==-1?g="mp4a.40.2":g="mp4a.40.5");const v=a.metadata;v&&"channelCount"in v&&(v.channelCount||1)!==1&&!iBt()&&(g="mp4a.40.5")}g&&g.indexOf("mp4a.40.5")!==-1&&aBt()&&a.container!=="audio/mpeg"&&(g="mp4a.40.2",this.log(`Android: force audio codec to ${g}`)),l&&l!==g&&this.log(`Swapping manifest audio codec "${l}" for "${g}"`),a.levelCodec=g,a.id=On.MAIN,this.log(`Init audio buffer, container:${a.container}, codecs[selected/level/parsed]=[${g||""}/${l||""}/${a.codec}]`),delete r.audiovideo}if(c){c.levelCodec=e.videoCodec,c.id=On.MAIN;const l=c.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":c.codec="hvc1.1.6.L120.90";break;case"av01":c.codec="av01.0.04M.08";break;case"avc1":c.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${c.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${c.codec!==l?" parsed-corrected="+c.codec:""}${c.supplemental?" supplemental="+c.supplemental:""}`),delete r.audiovideo}d&&(this.iframesOnly&&this.logMuxedErr(n),this.log(`Init audiovideo buffer, container:${d.container}, codecs[level/parsed]=[${e.codecs}/${d.codec}]`),delete r.video,delete r.audio);const p=Object.keys(r);if(p.length){if(this.hls.trigger(Ee.BUFFER_CODECS,r),!this.hls)return;p.forEach(l=>{const v=r[l].initSegment;v!=null&&v.byteLength&&this.hls.trigger(Ee.BUFFER_APPENDING,{type:l,data:v,frag:n,part:null,chunkMeta:i,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.getBufferOutput();return this.getFwdBufferInfo(e,On.MAIN)}get maxBufferLength(){const{levels:e,level:r}=this,n=e==null?void 0:e[r];return n?this.getMaxBufferLength(n.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Tr.IDLE}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const r=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return yn(r)?this.getAppendedFrag(r):null}get currentProgramDateTime(){var e;const r=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(yn(r)){const n=this.getLevelDetails(),i=this.currentFrag||(n?HT(null,n.fragments,r):null);if(i){const a=i.programDateTime;if(a!==null){const c=a+(r-i.start)*1e3;return new Date(c)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class kNe extends ANe{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const r=this.media;r!=null&&r.seeking&&(r.currentTime=r.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,r){if(!this.hls)return;const{seekOnAppend:n}=r,i=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=e,this.state){case Tr.STOPPED:case Tr.ENDED:case Tr.ERROR:this.state=Tr.IDLE}this.state===Tr.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,r]):this.nextOp=[i,r],this.hls.off(Ee.BUFFERED_TO_END,this.onBufferedToEnd);const a=this.media;n&&a&&this.seekTo(i)&&(this.currentOp=[i,r],this.nextOp=void 0,this.flushPipeline(i,!0))}seekTo(e){const r=this.media;if(r){var n;const i=(n=this.getLevelDetails())==null?void 0:n.edge,a=i!==void 0?i:r.duration;if(e>=a&&(e=a-.01),xi.bufferInfo(r,e,0).len>0&&this.getBufferedAt(e))return r.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,On.MAIN)}cacheSet(e,r){if(!this.hls)return;e.data=r;const n=this.cached;n.push(e),this.cachedSize+=r.buffer.byteLength;const i=this.hls.config.iframeCacheLimit;for(;this.cachedSize>i&&n.length>1;){const a=n.shift();if(a.data)this.cachedSize-=a.data.byteLength,a.data=void 0;else{this.cached=n.filter(c=>!!c.data),this.cachedSize=n.reduce((c,{data:d})=>d?d.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){const r=e.frag,{part:n,payload:i}=e;this.cacheFragmentData&&!n&&i!=null&&i.byteLength&&!r.data&&Ko(r)&&this.cacheSet(r,new Uint8Array(i.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);if((i===wo.NOT_LOADED||i===wo.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,r,n)}canReplayCached(e){var r;if(!this.cacheFragmentData||!((r=e.data)!=null&&r.byteLength))return!1;const n=e.decryptdata;return(n==null?void 0:n.keyFormat)!=="identity"||!!n.key}replayCachedFragment(e){const r=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${r.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;const n=e.stats=new EQ;n.loading.start=n.loading.first=n.loading.end=self.performance.now(),n.loaded=n.total=r.byteLength,n.chunkCount=1,this.state=Tr.FRAG_LOADING;const i={frag:e,part:null,payload:r,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(Ee.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)}fragBufferedComplete(e,r){super.fragBufferedComplete(e,r);const{currentOp:n,nextOp:i}=this;this.currentOp=this.nextOp=void 0,this.state=Tr.STOPPED,n!=null&&n[1].seekOnAppend&&(this.flushPipeline(n[0],!i),this.seekTo(n[0])||this.log(`Could not seek to ${n[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?Y3(xi.getBuffered(this.media)):"none"}`)),i&&this.loadMediaAt.apply(this,i)}flushPipeline(e,r){if(r){const n=this.media;if(n){const i=xi.bufferInfo(n,e,0),a=i.len?i.nextStart:0;a&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,On.MAIN),this.flushMainBuffer(a,1/0))}this.hls.once(Ee.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(Ee.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const e=this.hls;e.nextLoadLevel=e.startLevel===-1?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,r,n){const i=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,r,n||i||void 0)}getMainFwdBufferInfo(){const e=this.playhead,r=this.getBufferedAt(e);if(r){const n=r.duration;return{len:n,start:e,end:e+n,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){const e=this.playhead,r=this.fragmentTracker.getBufferedFrag(e,On.MAIN);return!!(r!=null&&r.endList)}}class nUt extends kNe{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var r;const n=(r=this._img)==null?void 0:r.src;n&&self.URL.revokeObjectURL(n),this._img=e}loadMediaAt(e){if(!this.hls)return;const r=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=r,this.startPosition=e,this.state){case Tr.STOPPED:case Tr.ENDED:case Tr.ERROR:this.state=Tr.IDLE}if(this.state===Tr.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===Tr.IDLE){const n=this.getBufferedAt(e);n&&(this.fragCurrent=n,this.updateImage(n,null))}}else{const n=this.fragCurrent;(!n||e>=n.start&&e{if(!this.hls)return;const g=this.hls.levels[e.level];g!=null&&g.fragmentError&&(g.fragmentError=0,e.stats.retry=0);const v=self.performance.now(),E=r?r.stats:e.stats;E.buffering.end=e.stats.buffering.end=v,this.hls.trigger(Ee.FRAG_BUFFERED,{frag:e,part:r,stats:E,id:e.type,chunkMeta:n})},a.onerror=()=>{this.handleError("Image decode error",e,r,n)};const p=a.src;p&&self.URL.revokeObjectURL(p);const l=new Blob([i],{type:"image/jpeg"});a.src=self.URL.createObjectURL(l)}else this.state=Tr.STOPPED,this.processQueued()}processQueued(){const e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,r,n,i){if(!this.hls)return;const a=new Error(e);this.hls.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.FRAG_PARSING_ERROR,chunkMeta:i,frag:r,part:n,fatal:!1,error:a,err:a})}_bufferInitSegment(){}bufferFragmentData(e,r,n,i){super.bufferFragmentData(e,r,n,i,!0);const a=Ci(new Uint8Array(e.data1),["mdat"]);if(a.length===0){this.handleError("Could not find I-Frame mdat",r,n,i);return}const c=r;this.cacheSet(c,a[0]),this.updateImage(c,n,i)}fragBufferedComplete(e,r){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,r),this.processQueued()}checkFragPlaying(){var e;const r=(e=this.fragPrevious)==null?void 0:e.start;if(r!==void 0){const n=this.getAppendedFrag(r);if(n&&!UI(n,this.fragPlaying))return this.fragPlaying=n,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const iUt=10,sUt="Image I-Frame player does not accept HTMLMediaElements",Ype={seekOnAppend:!0};let bM,y8;class aUt extends ff{constructor(e,r){super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,bM||(bM=oUt(r)),y8||(y8=lUt(bM)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(Ee.MANIFEST_LOADING,this.clearAsset,this),e.on(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Ee.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(Ee.MANIFEST_LOADING,this.clearAsset,this),e.off(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Ee.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,r){this.stats=r.stats,this.variableList=r.variableList}onLevelsUpdated(e,{levels:r}){var n;const i=(n=this.hls)==null?void 0:n.pathwayPriority;r.length&&i&&this.iframeInstances.forEach(a=>{a.pathwayPriority=i})}onInitPtsFound(e,{id:r,timestampOffsets:n}){r===On.MAIN&&(this.initPTS=n)}onFragBuffered(e,r){var n;const i=this.hls;i&&i.hasEnoughToStart&&(((n=i.mainForwardBufferInfo)==null?void 0:n.len)||0)>iUt&&this.iframeInstances.forEach(a=>{if(!a.loadingEnabled){var c;a.startLoad(((c=this.hls)==null||(c=c.media)==null?void 0:c.currentTime)||0)}})}createIFramePlayer(e){var r;return this.createInstance(bM,(r=this.hls)==null?void 0:r.iframeVariants,e)}createImageIFramePlayer(e){var r;const n=(r=this.hls)==null?void 0:r.iframeVariants.filter(i=>i.imageCodec);return this.createInstance(y8,n,e,"image-")}createInstance(e,r,n,i){const{hls:a}=this;if(!a)return null;const{url:c,userConfig:d,latestLevelDetails:p,loadLevelObj:l,loadLevel:g,bandwidthEstimate:v,sessionId:E}=a,{stats:T,variableList:j}=this;if(!(r!=null&&r.length)||!T||!c)return null;const P=`${i||""}iframe-player-${this.instanceCounter++}`,C=a.levels,L=l||C[g],O=uPe(L,d.videoPreference),F=(L==null?void 0:L.pathwayId)||".",$=Hn(Hn({},d),{},{loggerId:P,primarySessionId:E,videoPreference:O,abrEwmaDefaultEstimate:v,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},n),G=new e($,c,this.initPTS,p);return this.iframeInstances=this.iframeInstances.filter(W=>!W.url),this.iframeInstances.push(G),G.trigger(Ee.MANIFEST_LOADED,{levels:r,contentSteering:{uri:"",pathwayId:F},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:T,networkDetails:null,url:c,variableList:j}),G}}function oUt(t){return class extends t{constructor(r,n,i,a){r.streamController||(r.streamController=kNe),super(r),this._url=n,this.streamController.setInitPts(i),this.streamController.initDetails=a}loadSource(){}loadMediaAt(r,n=Ype){if(r<0)return;const i=Hn(Hn({},Ype),n);this.loadingEnabled||this.startLoad(r),this.streamController.loadMediaAt(r,i)}}}function lUt(t){return class extends t{constructor(r,n,i,a){r.cmcdController=void 0,r.emeController=void 0,r.streamController||(r.streamController=nUt),r.capLevelController=void 0,r.bufferController=void 0,super(r,n,i,a)}attachImage(r){this.streamController.image=r}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(sUt)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(r){if(r<0)return null;this.loadingEnabled||this.startLoad(r),this.streamController.loadMediaAt(r)}}}const mv=.025;let i4=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function cUt(t,e,r){return`${t.identifier}-${r+1}-${kj(e)}`}class uUt{constructor(e,r){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=r,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var r;if(e>0&&e>=this.assetList.length)return!0;const n=this.playoutLimit;return e<=0||isNaN(n)?!1:n===0?!0:(((r=this.assetList[e])==null?void 0:r.startOffset)||0)>n}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const r=this.dateRange.tagAnchor;if(r)return Zpe(r,e)?jO(e,r):e}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const r=this.dateRange.startTime,n=jO(r,e);return r-n<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,r=yn(e)?e:this.duration;return this.cumulativeDuration+r}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const r=this.resumeAnchor;if(r)return Zpe(r,e)?jO(e,r):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return dUt(this)}}function jO(t,e){return t-e.startt.start-mv&&e":t.cue.post?"":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`}function qS(t){const e=t.timelineStart,r=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+r).toFixed(2)}]`}class hUt{constructor(e,r,n,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(Ee.PLAYOUT_LIMIT_REACHED,{})};const a=this.hls=new e(r);this.interstitial=n,this.assetItem=i;const c=()=>{this.hasDetails=!0};a.once(Ee.LEVEL_LOADED,c),a.once(Ee.AUDIO_TRACK_LOADED,c),a.once(Ee.SUBTITLE_TRACK_LOADED,c),a.on(Ee.MEDIA_ATTACHING,(d,{media:p})=>{this.removeMediaListeners(),this.mediaAttached=p,this.interstitial.playoutLimit&&(p.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&a.on(Ee.BUFFER_APPENDED,()=>{const g=this.bufferedEnd;this.reachedPlayout(g)&&(this._bufferedEosTime=g,a.trigger(Ee.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let r=this.assetItem.uri;try{r=INe(r,e.config.primarySessionId||"").href}catch{}e.loadSource(r)}}bufferedInPlaceToEnd(e,r){var n;if(!this.appendInPlace)return!1;if((n=this.hls)!=null&&n.bufferedToEnd)return!0;if(!e)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),a=this.timelineOffset+(r||0),c=xi.bufferInfo(e,a,.02);return this.getAssetTime(c.end)>=i-.02}reachedPlayout(e){const n=this.interstitial.playoutLimit;return this.startOffset+e>=n}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const r=xi.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(r.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const r=this.interstitial.playoutLimit;if(r){const n=r-this.startOffset;if(n>0&&n1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const r=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,e-r),n)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var r;this.loadSource(),(r=this.hls)==null||r.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const r=n=>delete n.details;e.levels.forEach(r),e.allAudioTracks.forEach(r),e.allSubtitleTracks.forEach(r),this.hasDetails=!1}}on(e,r,n){var i;(i=this.hls)==null||i.on(e,r)}once(e,r,n){var i;(i=this.hls)==null||i.once(e,r)}off(e,r,n){var i;(i=this.hls)==null||i.off(e,r)}toString(){var e;return`HlsAssetPlayer: ${qS(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const _8=.033;class fUt extends ff{constructor(e,r){super("interstitials-sched",r),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,r){return this.events?this.events.reduce((n,i)=>e<=i.startOffset&&r>i.startOffset?(delete i.error,n+1):n,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,r){if(e.event)return this.findEventIndex(e.event.identifier);let n=-1;e.nextEvent?n=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(n=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[n]||(r===void 0&&(r=e.start),n=this.findItemIndexAtTime(r));n>=0&&(a=i[n])!=null&&a.event;){var a;n--}return n}findItemIndexAtTime(e,r){const n=this.items;if(n)for(let i=0;ic&&e1)for(let a=0;ad&&(rp.indexOf(g.identifier)===-1):[];d.length&&d.sort((g,v)=>{const E=g.cue.pre,T=g.cue.post,j=v.cue.pre,P=v.cue.post;if(E&&!j)return-1;if(j&&!E||T&&!P)return 1;if(P&&!T)return-1;if(!E&&!j&&!T&&!P){const C=g.startTime,L=v.startTime;if(C!==L)return C-L}return g.dateRange.tagOrder-v.dateRange.tagOrder}),this.events=d,l.forEach(g=>{this.removeEvent(g)}),this.updateSchedule(e,l,n)}updateSchedule(e,r=[],n=0,i=!1){const a=this.events||[];if(a.length||r.length||this.length<2){const c=this.items,d=this.parseSchedule(a,e,n);(i||r.length||(c==null?void 0:c.length)!==d.length||d.some((l,g)=>Math.abs(l.playout.start-c[g].playout.start)>.005||Math.abs(l.playout.end-c[g].playout.end)>.005))&&(this.items=d,this.onScheduleUpdate(r,c))}}parseDateRanges(e,r,n){const i=[],a=Object.keys(e);for(let c=0;c!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,r);let l=0,g=0;if(e.forEach((v,E)=>{const T=v.cue.pre,j=v.cue.post,P=e[E-1]||null,C=v.appendInPlace,L=j?c:v.startOffset,O=v.duration,F=v.timelineOccupancy===i4.Range?O:0,$=T&&a.live?n+(v.resumeOffset||0):0,G=$||v.resumptionOffset,W=(P==null?void 0:P.startTime)===L,Z=L+v.cumulativeDuration;let Q=C?Z+O:L+G;if(T||!j&&L<=0){const ie=g;g+=F,v.timelineStart=Z;const oe=d;d+=O,i.push({event:v,start:Z,end:Q,playout:{start:oe,end:d},integrated:{start:ie,end:g}})}else if(L<=c){if(!W){const pe=L-l;if(pe>_8){const Le=l,be=g;g+=pe;const Re=d;d+=pe;const Ie={previousEvent:e[E-1]||null,nextEvent:v,start:Le,end:Le+pe,playout:{start:Re,end:d},integrated:{start:be,end:g}};i.push(Ie)}else pe>0&&P&&(P.cumulativeDuration+=pe,i[i.length-1].end=L)}j&&(Q=Z),v.timelineStart=Z;const ie=g;g+=F;const oe=d;d+=O,i.push({event:v,start:Z,end:Q,playout:{start:oe,end:d},integrated:{start:ie,end:g}})}else return;const ee=$||v.resumeTime;j||ee>c?l=c:!T&&Q&&v.appendInPlaceStarted&&ee-Q>_8?l=Q:l=ee}),l{const l=d.cue.pre,g=d.cue.post,v=l?0:g?i:d.startTime;this.updateAssetDurations(d),c===v?d.cumulativeDuration=a:(a=0,c=v),!g&&d.snapOptions.in&&(d.resumeAnchor=HT(null,n.fragments,d.startOffset+d.resumptionOffset,0,0)||void 0),d.appendInPlace&&!d.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(d,r)||(d.appendInPlace=!1)),!d.appendInPlace&&p+1mv?(this.log(`"${e.identifier}" resumption ${n} not aligned with estimated timeline end ${i}`),!1):!Object.keys(r).some(c=>{const d=r[c].details,p=d.edge;if(n>=p)return this.log(`"${e.identifier}" resumption ${n} past ${c} playlist end ${p}`),!1;const l=HT(null,d.fragments,n);if(!l)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${c} playlist (${d.fragStart}-${d.fragmentEnd})`),!0;const g=c==="audio"?.175:0;return Math.abs(l.start-n){const C=E.data,L=C==null?void 0:C.ASSETS;if(!Array.isArray(L)){const O=this.assignAssetListError(e,Wt.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),j.url,T,P);this.hls.trigger(Ee.ERROR,O);return}e.assetListResponse=C,this.hls.trigger(Ee.ASSET_LIST_LOADED,{event:e,assetListResponse:C,networkDetails:P})},onError:(E,T,j,P)=>{const C=this.assignAssetListError(e,Wt.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${E.code} ${E.text} (${T.url})`),T.url,P,j);this.hls.trigger(Ee.ERROR,C)},onTimeout:(E,T,j)=>{const P=this.assignAssetListError(e,Wt.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${T.url})`),T.url,E,j);this.hls.trigger(Ee.ERROR,P)}};return d.load(p,g,v),this.hls.trigger(Ee.ASSET_LIST_LOADING,{event:e}),d}assignAssetListError(e,r,n,i,a,c){return e.error=n,{type:Kn.NETWORK_ERROR,details:r,fatal:!1,interstitial:e,url:i,error:n,networkDetails:c,stats:a}}}function Xpe(t){var e;t==null||(e=t.play())==null||e.catch(()=>{})}function ub(t,e){return`[${t}] Advancing timeline position to ${e}`}class pUt extends ff{constructor(e,r){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled||!this.schedule)return;const i=n-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const c=i<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=n,this.bufferedPos=n;const d=this.playingItem;if(!d){this.checkBuffer();return}if(c&&this.schedule.resetErrorsInRange(n,n-i)&&this.updateSchedule(!0),this.checkBuffer(),c&&n=d.end){var p;const T=this.findItemIndex(d);let j=this.schedule.findItemIndexAtTime(n);if(j===-1&&(j=T+(c?-1:1),this.log(`seeked ${c?"back ":""}to position not covered by schedule ${n} (resolving from ${T} to ${j})`)),!this.isInterstitial(d)&&(p=this.media)!=null&&p.paused&&(this.shouldPlay=!1),!c&&j>T){const P=this.schedule.findJumpRestrictedIndex(T+1,j);if(P>T){this.setSchedulePosition(P);return}}this.setSchedulePosition(j);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(d)){const T=d.event.assetList[0];T&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(n,T))}return}const g=l.timelineStart,v=l.duration||0;if(c&&n=g+v){var E;(E=d.event)!=null&&E.appendInPlace&&(this.clearAssetPlayers(d.event,d),this.flushFrontBuffer(n)),this.setScheduleToAssetAtTime(n,l)}},this.onTimeupdate=()=>{const n=this.currentTime;if(n===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),n>this.timelinePos)this.timelinePos=n,n>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(n>=i.end){this.timelinePos=i.end;const d=this.findItemIndex(i);this.setSchedulePosition(d+1)}const a=this.playingAsset;if(!a)return;const c=a.timelineStart+(a.duration||0);n>=c&&this.setScheduleToAssetAtTime(n,a)},this.onScheduleUpdate=(n,i)=>{const a=this.schedule;if(!a)return;const c=this.playingItem,d=a.events||[],p=a.items||[],l=a.durations,g=n.map(C=>C.identifier),v=!!(d.length||g.length);(v||i)&&this.log(`INTERSTITIALS_UPDATED (${d.length}): ${d} Schedule: ${p.map(C=>rh(C))} pos: ${this.timelinePos}`),g.length&&this.log(`Removed events ${g}`);let E=null,T=null;c&&(E=this.updateItem(c,this.timelinePos),this.itemsMatch(c,E)?this.playingItem=E:this.waitingItem=null);const j=this.waitingItem;j&&(this.waitingItem=this.updateItem(j),!this.waitingItem&&!c&&(this.log(`INTERSTITIAL_ENDED unresolved ${rh(j)}`),this.hls.trigger(Ee.INTERSTITIAL_ENDED,{event:j.event,schedule:p.slice(0),scheduleIndex:-1})));const P=this.bufferingItem;if(P&&(T=this.updateItem(P,this.bufferedPos),this.itemsMatch(P,T)?this.bufferingItem=T:P.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(P.event,null))),n.forEach(C=>{C.assetList.forEach(L=>{this.clearAssetPlayer(L.identifier,null)})}),this.playerQueue.forEach(C=>{if(C.interstitial.appendInPlace){const L=C.assetItem.timelineStart,O=C.timelineOffset-L;if(O)try{C.timelineOffset=L}catch(F){Math.abs(O)>mv&&this.warn(`${F} ("${C.assetId}" ${C.timelineOffset}->${L})`)}}}),v||i){if(this.hls.trigger(Ee.INTERSTITIALS_UPDATED,{events:d.slice(0),schedule:p.slice(0),durations:l,removedIds:g}),this.isInterstitial(c)&&g.indexOf(c.event.identifier)>-1){this.warn(`Interstitial "${c.event.identifier}" removed while playing`),this.primaryFallback(c.event);return}c&&this.trimInPlace(E,c),P&&T!==E&&this.trimInPlace(T,P),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=r,this.assetListLoader=new mUt(e),this.schedule=new fUt(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Ee.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(Ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Ee.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(Ee.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(Ee.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(Ee.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Ee.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(Ee.MEDIA_ENDED,this.onMediaEnded,this),e.on(Ee.ERROR,this.onError,this),e.on(Ee.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Ee.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Ee.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(Ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Ee.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(Ee.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(Ee.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(Ee.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Ee.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Ee.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Ee.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(Ee.MEDIA_ENDED,this.onMediaEnded,this),e.off(Ee.ERROR,this.onError,this),e.off(Ee.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){da(e,"play",this.onPlay),da(e,"pause",this.onPause),da(e,"seeking",this.onSeeking),da(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,r){const n=this.media=r.media;_a(n,"seeking",this.onSeeking),_a(n,"timeupdate",this.onTimeupdate),_a(n,"play",this.onPlay),_a(n,"pause",this.onPause)}onMediaAttached(e,r){const n=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!i){this.clearScheduleState();const a=this.findItemIndex(n);this.setSchedulePosition(a)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,r){const n=!!r.transferMedia,i=this.media;if(this.media=null,!n&&(i&&this.removeMediaListeners(i),this.detachedData)){const a=this.getBufferingPlayer();a&&(this.log(`Removing schedule state for detachedData and ${a}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,a.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,r=()=>e.bufferingItem||e.waitingItem,n=v=>v&&e.getAssetPlayer(v.identifier),i=(v,E,T,j,P)=>{if(v){let C=v[E].start;const L=v.event;if(L){if(E==="playout"||L.timelineOccupancy!==i4.Point){const O=n(T);(O==null?void 0:O.interstitial)===L&&(C+=O.assetItem.startOffset+O[P])}}else{const O=j==="bufferedPos"?c():e[j];C+=O-v.start}return C}return 0},a=(v,E)=>{var T;if(v!==0&&E!=="primary"&&(T=e.schedule)!=null&&T.length){var j;const P=e.schedule.findItemIndexAtTime(v),C=(j=e.schedule.items)==null?void 0:j[P];if(C){const L=C[E].start-C.start;return v+L}}return v},c=()=>{const v=e.bufferedPos;return v===Number.MAX_VALUE?d("primary"):Math.max(v,0)},d=v=>{var E,T;return(E=e.primaryDetails)!=null&&E.live?e.primaryDetails.edge:((T=e.schedule)==null?void 0:T.durations[v])||0},p=(v,E)=>{var T,j;const P=e.effectivePlayingItem;if(P!=null&&(T=P.event)!=null&&T.restrictions.skip||!e.schedule)return;e.log(`seek to ${v} "${E}"`);const C=e.effectivePlayingItem,L=e.schedule.findItemIndexAtTime(v,E),O=(j=e.schedule.items)==null?void 0:j[L],F=e.getBufferingPlayer(),$=F==null?void 0:F.interstitial,G=$==null?void 0:$.appendInPlace,W=C&&e.itemsMatch(C,O);if(C&&(G||W)){const Z=n(e.playingAsset),Q=(Z==null?void 0:Z.media)||e.primaryMedia;if(Q){const ee=E==="primary"?Q.currentTime:i(C,E,e.playingAsset,"timelinePos","currentTime"),ie=v-ee,oe=(G?ee:Q.currentTime)+ie;if(oe>=0&&(!Z||G||oe<=Z.duration)){Q.currentTime=oe;return}}}if(O){let Z=v;if(E!=="primary"){const ee=O[E].start,ie=v-ee;Z=O.start+ie}const Q=!e.isInterstitial(O);if((!e.isInterstitial(C)||C.event.appendInPlace)&&(Q||O.event.appendInPlace)){const ee=e.media||(G?F==null?void 0:F.media:null);ee&&(ee.currentTime=Z)}else if(C){const ee=e.findItemIndex(C);if(L>ee){const oe=e.schedule.findJumpRestrictedIndex(ee+1,L);if(oe>ee){e.setSchedulePosition(oe);return}}let ie=0;if(Q)e.timelinePos=Z,e.checkBuffer();else{const oe=O.event.assetList,pe=v-(O[E]||O).start;for(let Le=oe.length;Le--;){const be=oe[Le];if(be.duration&&pe>=be.startOffset&&pe{const v=e.effectivePlayingItem;if(e.isInterstitial(v))return v;const E=r();return e.isInterstitial(E)?E:null},g={get bufferedEnd(){const v=r(),E=e.bufferingItem;if(E&&E===v){var T;return i(E,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-E.playout.start||((T=e.bufferingAsset)==null?void 0:T.startOffset)||0}return 0},get currentTime(){const v=l(),E=e.effectivePlayingItem;return E&&E===v?i(E,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-E.playout.start:0},set currentTime(v){const E=l(),T=e.effectivePlayingItem;T&&T===E&&p(v+T.playout.start,"playout")},get duration(){const v=l();return v?v.playout.end-v.playout.start:0},get assetPlayers(){var v;const E=(v=l())==null?void 0:v.event.assetList;return E?E.map(T=>e.getAssetPlayer(T.identifier)):[]},get playingIndex(){var v;const E=(v=l())==null?void 0:v.event;return E&&e.effectivePlayingAsset?E.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var v;return((v=e.schedule)==null||(v=v.events)==null?void 0:v.slice(0))||[]},get schedule(){var v;return((v=e.schedule)==null||(v=v.items)==null?void 0:v.slice(0))||[]},get interstitialPlayer(){return l()?g:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return r()},get bufferingIndex(){const v=r();return e.findItemIndex(v)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const v=e.effectivePlayingItem;return e.findItemIndex(v)},primary:{get bufferedEnd(){return c()},get currentTime(){const v=e.timelinePos;return v>0?v:0},set currentTime(v){p(v,"primary")},get duration(){return d("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return i(r(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(v){p(v,"integrated")},get duration(){return d("integrated")},get seekableStart(){return a(e.seekableStart,"integrated")}},skip:()=>{const v=e.effectivePlayingItem,E=v==null?void 0:v.event;if(E&&!E.restrictions.skip){const T=e.findItemIndex(v);if(E.appendInPlace){const j=v.playout.start+v.event.duration;p(j+.001,"playout")}else e.advanceAfterAssetEnded(E,T,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const r=this.playingItem,n=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!r||!n?!1:this.findItemIndex(r)===n.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,r;if(this.mediaSelection===null)return;const n=this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&!n.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const a=(r=i)==null?void 0:r.currentTime;if(!(a===void 0||!yn(a)))return a}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,r){const n=this.getAssetPlayer(e);n&&this.transferMediaFromPlayer(n,r)}transferMediaFromPlayer(e,r){const n=e.interstitial.appendInPlace,i=e.media;if(n&&i===this.primaryMedia){if(this.bufferingAsset=null,(!r||this.isInterstitial(r)&&!r.event.appendInPlace)&&r&&i){this.detachedData={media:i};return}const a=e.transferMedia();this.log(`transfer MediaSource from ${e} ${fo(a)}`),this.detachedData=a}else r&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,r){var n,i;if(e.media===r)return;let a=null;const c=this.hls,d=e!==c,p=d&&e.interstitial.appendInPlace,l=(n=this.detachedData)==null?void 0:n.mediaSource;let g;if(c.media)p&&(a=c.transferMedia(),this.detachedData=a),g="Primary";else{const j=this.getBufferingPlayer();j?(a=j.transferMedia(),this.detachedData=a,g=`${j}`):l?g="detached MediaSource":g="detached media"}if(!a){if(l)a=this.detachedData,this.log(`using detachedData: MediaSource ${fo(a)}`);else if(!this.detachedData||c.media===r){const j=this.playerQueue;j.length>1&&j.forEach(P=>{if(d&&P.interstitial.appendInPlace!==p){const C=P.interstitial;this.clearInterstitial(P.interstitial,null),C.appendInPlace=!1,C.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${C}`)}}),this.hls.detachMedia(),this.detachedData={media:r}}}const v=a&&"mediaSource"in a&&((i=a.mediaSource)==null?void 0:i.readyState)!=="closed";if(this.log(`${v?"transfering MediaSource":"attaching media"} to ${d?e:"Primary"} from ${g} (media.currentTime: ${r.currentTime})`),!v&&!d){e.attachMedia(r);return}const E=v&&a?Hn({},a):{media:r},T=this.schedule;if(T&&d){const j=e.assetId===T.assetIdAtEnd;E.overrides={duration:T.duration,endOfStream:j||e.appendInPlace===!1}}if(!v&&p){const j=e,P=j.assetItem.timelineStart;if(P){const C=j.hls,L=Math.max(this.timelinePos-P,Number.EPSILON);C.startPosition!==L&&(this.log(`Set ${j} startPosition: ${L}`),C.config.startPosition=L,C.loadingEnabled&&C.startLoad(L))}}e.attachMedia(E)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,r=e==null?void 0:e.events,n=this.hls;if(!r||this.playbackDisabled||!this.media||!n)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,a=this.effectivePlayingItem;if(i===-1){if(!n.loadingEnabled){this.log("waiting for startLoad( )");return}const c=n.startPosition;if(this.timelinePos=c,r.length===0)this.setSchedulePosition(0);else if(r[0].cue.pre){this.log(ub("checkStart (preroll)",c));const d=e.findEventIndex(r[0].identifier);this.setSchedulePosition(d)}else if(c>=0||!this.primaryLive){this.log(ub("checkStart",c));const d=this.timelinePos=c>0?c:0,p=e.findItemIndexAtTime(d);this.setSchedulePosition(p)}else n.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(a&&!this.playingItem){this.log(ub("checkStart (playing item)",a.start));const c=e.findItemIndex(a);this.setSchedulePosition(c)}}advanceAssetBuffering(e,r){const n=e.event,i=n.findAssetIndex(r),a=x8(n,i);if(!n.isAssetPastPlayoutLimit(a))this.bufferedToEvent(e,a);else if(this.schedule){var c;const d=this.getNextItemIndex(e,!0),p=(c=this.schedule.items)==null?void 0:c[d];p&&this.bufferedToItem(p)}}livePrerollResumption(e,r){if(e.cue.pre&&this.primaryLive&&!yn(e.resumeOffset)&&this.hls){const n=this.getLiveStartPos();if(r){const i=this.getBufferingPlayer(),a=i!=null&&i.interstitial.cue.pre?i.remaining:0;return n+a}return n}}getNextItemIndex(e,r){if(this.schedule){const n=this.livePrerollResumption(e.event,r);if(n!==void 0)return this.log(`find next item index @${n}`),this.schedule.findItemIndexAtTime(n)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,r,n){const i=x8(e,n);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const a=this.schedule.items;if(a){const c=a[r],d=c.event?this.getNextItemIndex(c):r+1,p=a.length;if(d>=p){this.setSchedulePosition(-1);return}const l=e.resumeTime;this.timelinePos=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${r} (${a&&rh(a)}) pos: ${this.timelinePos}`);const c=this.waitingItem||this.playingItem,d=this.playingLastItem;if(this.isInterstitial(c)){const v=c.event,E=this.playingAsset,T=E==null?void 0:E.identifier,j=T?this.getAssetPlayer(T):null;if(j&&T&&(!this.eventItemsMatch(c,a)||r!==void 0&&T!==v.assetList[r].identifier)){var p;const P=v.findAssetIndex(E);if(this.log(`INTERSTITIAL_ASSET_ENDED ${P+1}/${v.assetList.length} ${qS(E)}`),this.endedAsset=E,this.playingAsset=null,this.hls.trigger(Ee.INTERSTITIAL_ASSET_ENDED,{asset:E,assetListIndex:P,event:v,schedule:i.slice(0),scheduleIndex:e,player:j}),c!==this.playingItem){this.itemsMatch(c,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(v,this.findItemIndex(this.playingItem),P);return}this.retreiveMediaSource(T,a),j.media&&!((p=this.detachedData)!=null&&p.mediaSource)&&j.detachMedia()}if(!this.eventItemsMatch(c,a)&&(this.endedItem=c,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${v} ${rh(c)}`),v.hasPlayed=!0,this.hls.trigger(Ee.INTERSTITIAL_ENDED,{event:v,schedule:i.slice(0),scheduleIndex:e}),v.cue.once&&this.hls)){var l;this.updateSchedule();const P=(l=this.schedule)==null?void 0:l.items;if(a&&P){const C=this.findItemIndex(a),L=this.livePrerollResumption(v);if(L!==void 0){let O=L;const F=this.getNextItemIndex(c);if(!this.isInterstitial(i[F])){var g;const $=(g=this.primaryDetails)==null?void 0:g.fragments;if(v.snapOptions.in&&$){const G=HT(null,$,L);G&&(O=Math.min(Math.max(i[F].start,jO(O,G)),i[F].end))}}if(this.log(ub("live join (preroll)",O)),this.timelinePos=O,F!==C&&(F||F===0)){this.advanceSchedule(F,P,void 0,c,d);return}}this.advanceSchedule(C,P,r,c,d)}return}}this.advanceSchedule(e,i,r,c,d)}advanceSchedule(e,r,n,i,a){const c=this.schedule;if(!c)return;const d=r[e]||null,p=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(g=>{const v=g.interstitial,E=c.findEventIndex(v.identifier);(Ee+1)&&this.clearInterstitial(v,d)}),this.isInterstitial(d)){this.timelinePos=Math.min(Math.max(this.timelinePos,d.start),d.end);const g=d.event;if(n===void 0){n=g.cue.pre?0:c.findAssetIndex(g,this.timelinePos);const j=x8(g,n-1);if(g.isAssetPastPlayoutLimit(j)||g.appendInPlace&&this.timelinePos===d.end){this.advanceAfterAssetEnded(g,e,n);return}n=j}const v=this.waitingItem;this.assetsBuffered(d,p)||this.setBufferingItem(d);let E=this.preloadAssets(g,n);if(this.eventItemsMatch(d,v||i)||(this.waitingItem=d,this.log(`INTERSTITIAL_STARTED ${rh(d)} ${g.appendInPlace?"append in place":""}`),g.hasPlayed=!1,this.hls.trigger(Ee.INTERSTITIAL_STARTED,{event:g,schedule:r.slice(0),scheduleIndex:e})),!g.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${g}`);return}if(g.assetListLoader&&(g.assetListLoader.destroy(),g.assetListLoader=void 0),!p){this.log(`Waiting for attachMedia to start Interstitial ${g}`);return}this.waitingItem=this.endedItem=null,this.playingItem=d;const T=g.assetList[n];if(!T){this.advanceAfterAssetEnded(g,e,n||0);return}if(E||(E=this.getAssetPlayer(T.identifier)),E===null||E.destroyed){const j=g.assetList.length;this.warn(`asset ${n+1}/${j} player destroyed ${g}`),E=this.createAssetPlayer(g,T,n),E.loadSource()}if(!this.eventItemsMatch(d,this.bufferingItem)&&g.appendInPlace&&this.isAssetBuffered(T))return;this.startAssetPlayer(E,n,r,e,p),this.shouldPlay&&Xpe(E.media)}else d?(this.resumePrimary(d,e,i),this.shouldPlay&&Xpe(this.hls.media)):a&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(c.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,r,n){var i,a;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${rh(e)}`);let c=this.timelinePos;if((i=this.detachedData)!=null&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(c):((c=e.end||cl&&!n){const g=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${i} [${p}-${l}]) snapping to liveSync ${g}`),g||p}}}return this.log(`primary resumption itemStart: ${i}`),i}getLiveStartPos(){var e;const r=this.hls.startPosition,n=this.hls.liveSyncPosition||0,i=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;return r===-1||n&&n-r=e.timelineStart+(e.duration||0)}attachPrimary(e,r,n){r?this.setBufferingItem(r):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const a=this.hls;a.media?this.checkBuffer():(this.transferMediaTo(a,i),n&&this.startLoadingPrimaryAt(e,n)),n||(this.log(ub("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,n))}startLoadingPrimaryAt(e,r){const n=this.hls,{loadingEnabled:i,bufferingEnabled:a,startPosition:c}=n,d=n.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${c} skip seek: ${r} has enough ${d} loadingEnabled: ${i} bufferingEnabled: ${a}`),!r&&d||!i||Math.abs(c-e)>.1){const p=this.primaryDetails;if(p!=null&&p.live&&e+.5>=p.edge){const l=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${l?rh(l):null}`),n.pauseBuffering(),this.bufferPastEdge=!0;return}n.startLoad(e,r)}else a||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(Ee.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Ee.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,r){if(r.level===-1||!this.schedule)return;const n=this.hls.levels[r.level];if(!n.details)return;const i=Hn(Hn({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=i;const a=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,a===-1?0:a),!!this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){const d=this.primaryDetails,p=this.bufferedPos;if(d!=null&&d.live&&p+.5i&&(i.setAudioOption(r)||i.setAudioOption(n)))}onSubtitleTrackSwitch(e,r){const n=qme(r);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(r)||r.id!==-1&&i.setSubtitleOption(n)))}onBufferCodecs(e,r){const n=r.tracks;n&&(this.requiredTracks=n)}onBufferAppended(e,r){this.checkBuffer()}onBufferFlushed(e,r){const n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const r=this.schedule.events;if(this.bufferedPos.25){e.event.assetList.forEach((a,c)=>{e.event.isAssetPastPlayoutLimit(c)&&this.clearAssetPlayer(a.identifier,null)});const n=e.end+.25,i=xi.bufferInfo(this.primaryMedia,n,0);(i.end>n||(i.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${rh(e)} (was ${rh(r)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}itemsMatch(e,r){return!!r&&(e===r||e.event&&r.event&&this.eventItemsMatch(e,r)||!e.event&&!r.event&&this.findItemIndex(e)===this.findItemIndex(r))}eventItemsMatch(e,r){var n;return!!r&&(e===r||e.event.identifier===((n=r.event)==null?void 0:n.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var r;const n=(r=this.schedule.items)==null?void 0:r[this.findEventIndex(e)];if(this.isInterstitial(n)&&n.event.identifier===e)return n}}findItemIndex(e,r){return e&&this.schedule?this.schedule.findItemIndex(e,r):-1}updateSchedule(e=!1){var r,n;const i=this.mediaSelection;if(!i)return;const a=((r=this.hls)==null?void 0:r.liveSyncPosition)||0;(n=this.schedule)==null||n.updateSchedule(i,[],a,e)}checkBuffer(e){var r;const n=(r=this.schedule)==null?void 0:r.items;if(!n)return;const i=xi.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,n,e)}updateBufferedPos(e,r,n){const i=this.schedule,a=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(r.length===1&&this.itemsMatch(r[0],a)){this.bufferedPos=e;return}const c=this.playingItem,d=this.findItemIndex(c);let p=i.findItemIndexAtTime(e);if(this.bufferedPos=a.end||(l=E.event)!=null&&l.appendInPlace&&e+.01>=E.start)&&(p=v),this.isInterstitial(a)){const T=a.event;if(v-d>1&&T.appendInPlace===!1||T.assetList.length===0&&T.assetListLoader)return}if(this.bufferedPos=e,p>g&&p>d)this.bufferedToItem(E);else{const T=this.primaryDetails;this.primaryLive&&T&&e>T.edge-T.targetduration&&E.start{const a=this.getAssetPlayer(i.identifier);return!(a!=null&&a.bufferedInPlaceToEnd(r))})}setBufferingItem(e){const r=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,r)&&n){const{items:i,events:a}=n;if(!i||!a)return r;const c=this.isInterstitial(e),d=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const p=d?d.remaining:r?r.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${rh(e)}`+(r?` (${p.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(c){const l=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((g,v)=>{const E=this.getAssetPlayer(g.identifier);E&&(v===l&&E.loadSource(),E.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(Ee.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:a.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return r}bufferedToItem(e,r=0){const n=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,r);else if(n!==null){this.bufferingAsset=null;const i=this.getPrimaryResumption(e,this.findItemIndex(e),!0),a=this.bufferedPos=Math.max(i,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),c=this.detachedData;if(c)c.mediaSource?this.attachPrimary(a,e,!0):this.startLoadingPrimaryAt(a);else{const d=this.playingItem,p=this.isInterstitial(d)&&d.event.appendInPlace;this.startLoadingPrimaryAt(a,p)}}}}bufferedToEvent(e,r){const n=e.event,i=n.assetList.length===0&&!n.assetListLoader,a=n.cue.once;if(i||!a){const c=this.preloadAssets(n,r);if(c!=null&&c.interstitial.appendInPlace){const d=this.primaryMedia;d&&this.bufferAssetPlayer(c,d)}}}preloadAssets(e,r){const n=e.assetUrl,i=e.assetList.length,a=i===0&&!e.assetListLoader,c=e.cue.once;if(a){const p=e.timelineStart,l=this.playingItem,g=this.getBufferingPlayer();if(e.appendInPlace){var d;!this.isInterstitial(l)&&(l==null||(d=l.nextEvent)==null?void 0:d.identifier)===e.identifier&&this.flushFrontBuffer(p+.25)}let v,E=0;if((!g||g.interstitial.cue.pre)&&this.primaryLive&&(E=this.getLiveStartPos(),g&&(E+=g.remaining)),E&&!(e.cue.pre||e.cue.post)){const j=E-p;j>0&&(v=Math.round(j*1e3)/1e3)}if(this.log(`Load interstitial asset ${r+1}/${n?1:i} ${e}${E?` live-start: ${E} start-offset: ${v} (timeline-start: ${p})`:""}`),n)return this.createAsset(e,0,0,p,e.duration,n);const T=this.assetListLoader.loadAssetList(e,v);T&&(e.assetListLoader=T)}else if(!c&&i){for(let l=r;l=n.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(r).forEach(a=>{this.hls.trigger(Ee.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:a})})}getAssetPlayerQueueIndex(e){const r=this.playerQueue;for(let n=0;n=0){const G=r.duration;G&&${if($.live){const Z=new Error(`Interstitials MUST be VOD assets ${e}`),Q={fatal:!0,type:Kn.OTHER_ERROR,details:Wt.INTERSTITIAL_ASSET_ITEM_ERROR,error:Z},ee=this.findEventIndex(e.identifier);this.handleAssetItemError(Q,e,ee,n,Z.message);return}const G=$.edge-$.fragmentStart,W=r.duration;(P||W===null||G>W)&&(P=!1,this.log(`Interstitial asset "${v}" duration change ${W} > ${G}`),r.duration=G,this.updateSchedule())};j.on(Ee.LEVEL_UPDATED,($,{details:G})=>C(G)),j.on(Ee.LEVEL_PTS_UPDATED,($,{details:G})=>C(G)),j.on(Ee.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const L=($,G)=>{const W=this.getAssetPlayer(v);if(W&&G.tracks){W.off(Ee.BUFFER_CODECS,L),W.tracks=G.tracks;const Z=this.primaryMedia;this.bufferingAsset===W.assetItem&&Z&&!W.media&&this.bufferAssetPlayer(W,Z)}};j.on(Ee.BUFFER_CODECS,L);const O=()=>{const $=this.getAssetPlayer(v);if(this.log(`buffered to end of asset ${$}`),!$||!this.schedule)return;const G=this.getEventItem(e.identifier);G&&this.advanceAssetBuffering(G,$.assetItem)};j.on(Ee.BUFFERED_TO_END,O);const F=$=>()=>{if(!this.getAssetPlayer(v)||!this.schedule)return;this.shouldPlay=!0;const W=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,W,$)};return j.once(Ee.MEDIA_ENDED,F(n)),j.once(Ee.PLAYOUT_LIMIT_REACHED,F(1/0)),j.on(Ee.ERROR,($,G)=>{if(!this.schedule)return;const W=this.getAssetPlayer(v);if(G.details===Wt.BUFFER_STALLED_ERROR){if(W!=null&&W.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(G.details===Wt.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(G,e,this.findEventIndex(e.identifier),n,`Asset player error ${G.error} ${e}`)}),j.on(Ee.DESTROYING,()=>{if(!this.getAssetPlayer(v)||!this.schedule)return;const G=new Error(`Asset player destroyed unexpectedly ${v}`),W={fatal:!0,type:Kn.OTHER_ERROR,details:Wt.INTERSTITIAL_ASSET_ITEM_ERROR,error:G};this.handleAssetItemError(W,e,this.findEventIndex(e.identifier),n,G.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${qS(r)}`),this.hls.trigger(Ee.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:r,assetListIndex:n,event:e,player:j}),j}clearInterstitial(e,r){this.clearAssetPlayers(e,r),e.reset()}clearAssetPlayers(e,r){e.assetList.forEach(n=>{this.clearAssetPlayer(n.identifier,r)})}resetAssetPlayer(e){const r=this.getAssetPlayerQueueIndex(e);if(r!==-1){this.log(`reset asset player "${e}" after error`);const n=this.playerQueue[r];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(e,r){const n=this.getAssetPlayerQueueIndex(e);if(n!==-1){const i=this.playerQueue[n];this.log(`clear ${i} toSegment: ${r&&rh(r)}`),this.transferMediaFromPlayer(i,r),this.playerQueue.splice(n,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,r,n,i,a){const{interstitial:c,assetItem:d,assetId:p}=e,l=c.assetList.length,g=this.playingAsset;this.endedAsset=null,this.playingAsset=d,(g==null?void 0:g.identifier)!==p&&(g&&(this.clearAssetPlayer(g.identifier,n[i]),delete g.error),this.log(`INTERSTITIAL_ASSET_STARTED ${r+1}/${l} ${qS(d)}`),this.hls.trigger(Ee.INTERSTITIAL_ASSET_STARTED,{asset:d,assetListIndex:r,event:c,schedule:n.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,a)}bufferAssetPlayer(e,r){var n;if(!this.schedule)return;const{interstitial:i,assetItem:a}=e,c=this.getEventItem(i.identifier);if(!c)return;if(e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=a,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(c,a);return}const d=this.getBufferingPlayer();if(d===e)return;const p=i.appendInPlace;if(p&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;const l=(d==null?void 0:d.tracks)||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(p&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(l&&!FCe(l,e.tracks)){const g=new Error(`Asset ${qS(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(l)}')`),v={fatal:!0,type:Kn.OTHER_ERROR,details:Wt.INTERSTITIAL_ASSET_ITEM_ERROR,error:g},E=i.findAssetIndex(a);this.handleAssetItemError(v,i,this.findEventIndex(i.identifier),E,g.message);return}}this.transferMediaTo(e,r)}handleInPlaceStall(e){const r=this.schedule,n=this.primaryMedia;if(!r||!n)return;const i=n.currentTime,a=r.findAssetIndex(e,i),c=e.assetList[a];if(c){const d=this.getAssetPlayer(c.identifier);if(d){const p=d.currentTime||i-c.timelineStart,l=d.duration-p;if(this.warn(`Stalled at ${p} of ${p+l} in ${d} ${e} (media.currentTime: ${i})`),p&&(l/n.playbackRate<.5||d.bufferedInPlaceToEnd(n,d.currentTime))&&d.hls){const g=r.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,g,a)}}}}advanceInPlace(e){const r=this.primaryMedia;if(r&&r.currentTimee?(this.log(n),r.currentTime=e):this.log(`Cannot ${n}`)}}handleAssetItemError(e,r,n,i,a){if(e.details===Wt.BUFFER_STALLED_ERROR)return;const c=r.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${c&&qS(c)} ${e.error}`),!this.schedule)return;const d=(c==null?void 0:c.identifier)||"",p=this.getAssetPlayerQueueIndex(d),l=this.playerQueue[p]||null,g=this.schedule.items,v=La({},e,{fatal:!1,errorAction:Ej(!0),asset:c,assetListIndex:i,event:r,schedule:g,scheduleIndex:n,player:l});if(this.hls.trigger(Ee.INTERSTITIAL_ASSET_ERROR,v),!e.fatal)return;const E=this.playingAsset,T=this.bufferingAsset,j=new Error(a);if(c&&(this.clearAssetPlayer(d,null),c.error=j),!r.assetList.some(P=>!P.error))r.error=j;else for(let P=i;P{const C=parseFloat(j.DURATION);this.createAsset(a,P,g,p+g,C,j.URI),g+=C}),a.duration=g,this.log(`Loaded asset-list with duration: ${g} (was: ${l}) ${a}`);const v=this.waitingItem,E=(v==null?void 0:v.event.identifier)===c;this.updateSchedule();const T=(i=this.bufferingItem)==null?void 0:i.event;if(E){const j=this.findEventIndex(c),P=this.getEventItem(c);if(P){if(!this.playingItem&&this.timelinePos>P.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==j){a.error=new Error(`Interstitial ${d.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${a}`),this.log(a.error.message),this.updateSchedule(!0),this.primaryFallback(a);return}this.setBufferingItem(P)}this.setSchedulePosition(j)}else if((T==null?void 0:T.identifier)===c){const j=a.assetList[0];if(j){const P=this.getAssetPlayer(j.identifier);if(T.appendInPlace){const C=this.primaryMedia;P&&C&&this.bufferAssetPlayer(P,C)}else P&&P.loadSource()}}}onError(e,r){if(this.schedule)switch(r.details){case Wt.ASSET_LIST_PARSING_ERROR:case Wt.ASSET_LIST_LOAD_ERROR:case Wt.ASSET_LIST_LOAD_TIMEOUT:{const n=r.interstitial;n&&(this.updateSchedule(!0),this.primaryFallback(n));break}case Wt.BUFFER_STALLED_ERROR:{const n=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&n.event.appendInPlace){this.handleInPlaceStall(n.event);return}const i=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${i==null?void 0:i.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}class gUt{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var r;const{media:n}=this,i=this.levelDetails;if(!n||!i||!this.hls)return;this.currentTime=n.currentTime;const a=this.hls.config,c=this.computeLatency();if(c===null)return;this._latency=c;const{lowLatencyMode:d,maxLiveSyncPlaybackRate:p}=a;if(!d||p===1||!i.live)return;const l=this.targetLatency;if(l===null)return;const g=c-l,v=Math.min(this.maxLatency,l+i.targetduration),E=g.05&&this.forwardBufferLength>1&&!T){const j=Math.min(2,Math.max(1,p)),P=Math.round(2/(1+Math.exp(-.75*g-this.edgeStalled))*20)/20,C=Math.min(j,Math.max(1,P));this.changeMediaPlaybackRate(n,C)}else n.playbackRate!==1&&n.playbackRate!==0&&this.changeMediaPlaybackRate(n,1)},this.hls=e,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var e;const r=(e=this.hls)==null?void 0:e.config;if(!r)return 0;if(r.liveMaxLatencyDuration!==void 0)return r.liveMaxLatencyDuration;const n=this.levelDetails;return n?r.liveMaxLatencyDurationCount*n.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||!this.hls)return null;const r=this.hls.config,{holdBack:n,partHoldBack:i,targetduration:a}=e,{liveSyncDuration:c,liveSyncDurationCount:d,lowLatencyMode:p}=r,l=this.hls.userConfig;let g=p&&i||n;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||g===0)&&(g=c!==void 0?c:d*a);const v=a;return g+Math.min(this.stallCount*r.liveSyncOnStallIncrease,v)}set targetLatency(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const e=this.estimateLiveEdge(),r=this.targetLatency;if(e===null||r===null||!this.hls)return null;const n=this.levelDetails;if(n===null)return null;const i=n.edge,a=e-r-this.edgeStalled,c=i-n.totalduration,d=i-(this.hls.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(c,a),d)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null||!this.hls)return 0;const r=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-r,0)}get forwardBufferLength(){const{media:e}=this,r=this.levelDetails;if(!e||!r)return 0;const n=e.buffered.length;return(n?e.buffered.end(n-1):r.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Ee.ERROR,this.onError,this),e.on(Ee.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Ee.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Ee.ERROR,this.onError,this),e.off(Ee.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(e,r){this.media=r.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:r}){r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(e,r){var n;const i=this.hls,a=this.media||r.event.appendInPlace&&(i==null||(n=i.interstitialsManager)==null?void 0:n.playerQueue.reduce((c,d)=>c||d.media,null));i&&a&&a.playbackRate>1&&a.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(a,1)}onError(e,r){var n;r.details===Wt.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,r){var n,i;e.playbackRate!==r&&((n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${r}`),e.playbackRate=r)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const Qpe=500,yUt=1e-6;class xUt extends MQ{constructor(e,r,n){super(e,r,n,"subtitle-stream-controller",On.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Ee.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Ee.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Ee.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Ee.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Ee.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Ee.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,r){this.stopLoad(),this.state=Tr.IDLE,this.setInterval(Qpe),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=r?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,r){this.tracksBuffered=[],super.onMediaDetaching(e,r)}onLevelLoaded(e,r){this.mainDetails=r.details}onSubtitleFragProcessed(e,r){var n,i;const{frag:a,part:c,success:d}=r;if(!d)return;const p=(n=this.tracksBuffered)[i=a.level]||(n[i]=[]);if(!p)return;let l;const g=(c||a).start;for(let E=0;E=p[E].start&&g<=p[E].end){l=p[E];break}const v=g+(c||a).duration;if(l?l.end=v:(l={start:g,end:v},p.push(l)),!c||v>=a.end-yUt){const E=this.fragmentTracker.fragBuffered(a);c&&E&&(E.range.subs={time:[{startPTS:a.start,endPTS:v}],partial:!0}),Ko(a)&&!this.fragContextChanged(a)&&(this.fragPrevious=a),this.fragBufferedComplete(a,c),this.media&&this.tickImmediate()}}onBufferFlushing(e,r){const{startOffset:n,endOffset:i}=r;if(n===0&&i!==Number.POSITIVE_INFINITY){const a=i-1;if(a<=0)return;r.endOffsetSubtitles=Math.max(0,a),this.tracksBuffered.forEach(c=>{if(c)for(let d=0;dnew dP(n));return}this.tracksBuffered=[],this.levels=r.map(n=>new dP(n)),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,On.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,r){var n;if(this.currentTrackId=r.id,this.abortCurrentFrag(),!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];if(!(i!=null&&i.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==Tr.STOPPED&&this.setInterval(Qpe)}onSubtitleTrackLoaded(e,r){var n;const{currentTrackId:i,levels:a}=this,{details:c,id:d}=r;if(!a){this.warn(`Subtitle tracks were reset while loading level ${d}`);return}const p=a[d];if(d>=a.length||!p)return;this.log(`Subtitle track ${d} loaded [${c.startSN},${c.endSN}]${c.lastPartSn?`[part-${c.lastPartSn}-${c.lastPartIndex}]`:""},duration:${c.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const l=this.mainDetails;let g=0;if(c.live||(n=p.details)!=null&&n.live){if(c.deltaUpdateFailed)return;if(!l){this.startFragRequested=!1;return}if(p.details){var v;g=this.alignPlaylists(c,p.details,(v=this.levelLastLoaded)==null?void 0:v.details)}c.alignedSliding||(J3(l,c,this),g=c.fragmentStart)}p.details=c,this.levelLastLoaded=p,l&&!this.startFragRequested&&this.setStartPosition(l,g),d===i&&(this.hls.trigger(Ee.SUBTITLE_TRACK_UPDATED,{details:c,id:d,groupId:r.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){const{frag:r,part:n,payload:i}=e;!n||!(i!=null&&i.byteLength)||!this.shouldDecrypt(r)||this.decryptPayload(i,r,n)}_handleFragmentLoadComplete(e){const{frag:r,payload:n}=e;this.fragContextChanged(r)||!(n!=null&&n.byteLength)||!this.shouldDecrypt(r)||this.decryptPayload(n,r,null)}shouldDecrypt(e){const r=e.decryptdata;return!!(r!=null&&r.key&&r.iv&&RE(r.method))}decryptPayload(e,r,n){const i=r.decryptdata,a=performance.now();this.decrypter.decrypt(new Uint8Array(e),i.key.buffer,i.iv.buffer,LQ(i.method)).then(c=>{this.fragContextChanged(r)||this.hls.trigger(Ee.FRAG_DECRYPTED,{frag:r,part:n,payload:c,stats:{tstart:a,tdecrypt:performance.now()}})}).catch(c=>{this.hls.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:r,part:n}),n||(this.warn(`${c.name}: ${c.message}`),this.state=Tr.IDLE)})}doTick(){if(this.state===Tr.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:n,levels:i}=this,a=i[n],c=a==null?void 0:a.details;if(!c||this.waitForLive(a)||this.waitForCdnTuneIn(c)){this.startFragRequested=!1;return}const{config:d}=this,p=this.playhead,l=xi.bufferedInfo(this.tracksBuffered[n]||[],p,d.maxBufferHole),{end:g,len:v}=l,E=Math.max(this.hls.maxBufferLength+c.levelTargetDuration,((e=this.hls.mainForwardBufferInfo)==null?void 0:e.len)||0);if(v>E||v&&!this.buffering)return;let T=this.getNextFragment(g,c);if(!T)return;if(Ko(T)){var r;if(T.end===l.end)return;const j=T.sn-c.startSN,P=c.fragments[j-1];T.cc===(P==null?void 0:P.cc)&&!((r=c.partList)!=null&&r.length)&&this.fragmentTracker.getState(P)===wo.NOT_LOADED&&(T=P)}this.loadFragment(T,a,g)}}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);(i===wo.NOT_LOADED||i===wo.PARTIAL)&&super.loadFragment(e,r,n)}get mediaBufferTimeRanges(){return new _Ut(this.tracksBuffered[this.currentTrackId]||[])}}class _Ut{constructor(e){this.buffered=void 0;const r=(n,i,a)=>{if(i=i>>>0,i>a-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${a})`);return e[i][n]};this.buffered={get length(){return e.length},end(n){return r("end",n,e.length)},start(n){return r("start",n,e.length)}}}}const vUt={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},jNe=t=>String.fromCharCode(vUt[t]||t),Lm=15,Pm=42,bUt={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},wUt={17:2,18:4,21:6,22:8,23:10,19:13,20:15},SUt={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},EUt={25:2,26:4,29:6,30:8,31:10,27:13,28:15},TUt=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class AUt{constructor(){this.time=null,this.verboseLevel=0}log(e,r){if(this.verboseLevel>=e){const n=typeof r=="function"?r():r;la.log(`${this.time} [${e}] ${n}`)}}}const db=function(e){const r=[];for(let n=0;n=Pm&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Pm-1)}moveCursor(e){const r=Math.min(this.pos+e,Pm);if(e>1)for(let n=this.pos+1;n=144&&this.backSpace();const r=jNe(e);if(this.pos>=Pm){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+r+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1)}clearFromPos(e){let r;for(r=e;r"pacData = "+fo(e));let r=e.row-1;if(this.nrRollUpRows&&r"bkgData = "+fo(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(e,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const r=[];let n="",i=-1;for(let a=0;a0&&(e?n="["+r.join(" | ")+"]":n=r.join(` `)),n}getTextAndFormat(){return this.rows}}class jUt{constructor(e,r,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new v8(n),this.nonDisplayedMemory=new v8(n),this.lastOutputScreen=new v8(n),this.currRollUpRow=this.displayedMemory.rows[Lm-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Lm-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let n=0;nr+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const r={flash:!1};if(r.underline=e%2===1,r.italics=e>=46,r.italics)r.foreground="white";else{const n=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];r.foreground=i[n]}this.logger.log(2,"MIDROW: "+fo(r)),this.writeScreen.setPen(r)}outputDataUpdate(e=!1){const r=this.logger.time;r!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=r:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,r,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:r),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Jpe{constructor(e,r,n){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=PUt(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new AUt,this.field=e,this.outputFilters=[null,r,n]}getHandler(e){return this.outputFilters[e]}setHandler(e,r){var n;this.outputFilters[e]=r,(n=this.channels[e])==null||n.setHandler(r)}getChannel(e){let r=this.channels[e];return r||(r=this.channels[e]=new jUt(this.field+e-1,this.outputFilters[e],this.logger)),r}addData(e,r){this.logger.time=e;for(let n=0;n"["+db([r[n],r[n+1]])+"] -> ("+db([i,a])+")");const p=this.cmdHistory;if(i>=16&&i<=31){if(CUt(i,a,p)){wM(null,null,p),this.logger.log(3,()=>"Repeated command ("+db([i,a])+") is dropped");continue}wM(i,a,this.cmdHistory),c=this.parseCmd(i,a),c||(c=this.parseMidrow(i,a)),c||(c=this.parsePAC(i,a)),c||(c=this.parseBackgroundAttributes(i,a))}else wM(null,null,p);if(!c&&(d=this.parseChars(i,a),d)){const g=this.currentChannel;g&&g>0?this.getChannel(g).insertChars(d):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!c&&!d&&this.logger.log(2,()=>"Couldn't parse cleaned data "+db([i,a])+" orig: "+db([r[n],r[n+1]]))}}parseCmd(e,r){const n=(e===20||e===28||e===21||e===29)&&r>=32&&r<=47,i=(e===23||e===31)&&r>=33&&r<=35;if(!(n||i))return!1;const a=e===20||e===21||e===23?1:2,c=this.getChannel(a);return e===20||e===21||e===28||e===29?r===32?c.ccRCL():r===33?c.ccBS():r===34?c.ccAOF():r===35?c.ccAON():r===36?c.ccDER():r===37?c.ccRU(2):r===38?c.ccRU(3):r===39?c.ccRU(4):r===40?c.ccFON():r===41?c.ccRDC():r===42?c.ccTR():r===43?c.ccRTD():r===44?c.ccEDM():r===45?c.ccCR():r===46?c.ccENM():r===47&&c.ccEOC():c.ccTO(r-32),this.currentChannel=a,!0}parseMidrow(e,r){let n=0;if((e===17||e===25)&&r>=32&&r<=47){if(e===17?n=1:n=2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[n];return i?(i.ccMIDROW(r),this.logger.log(3,()=>"MIDROW ("+db([e,r])+")"),!0):!1}return!1}parsePAC(e,r){let n;const i=(e>=17&&e<=23||e>=25&&e<=31)&&r>=64&&r<=127,a=(e===16||e===24)&&r>=64&&r<=95;if(!(i||a))return!1;const c=e<=23?1:2;return r>=64&&r<=95?n=c===1?bUt[e]:SUt[e]:n=c===1?wUt[e]:EUt[e],this.getChannel(c).setPAC(this.interpretPAC(n,r)),this.currentChannel=c,!0}interpretPAC(e,r){let n;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return r>95?n=r-96:n=r-64,i.underline=(n&1)===1,n<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((n-16)/2)*4,i}parseChars(e,r){let n,i=null,a=null;if(e>=25?(n=2,a=e-8):(n=1,a=e),a>=17&&a<=19){let c;a===17?c=r+80:a===18?c=r+112:c=r+144,this.logger.log(2,()=>"Special char '"+jNe(c)+"' in channel "+n),i=[c]}else e>=32&&e<=127&&(i=r===0?[e]:[e,r]);return i&&this.logger.log(3,()=>"Char codes = "+db(i).join(",")),i}parseBackgroundAttributes(e,r){const n=(e===16||e===24)&&r>=32&&r<=47,i=(e===23||e===31)&&r>=45&&r<=47;if(!(n||i))return!1;let a;const c={};e===16||e===24?(a=Math.floor((r-32)/2),c.background=TUt[a],r%2===1&&(c.background=c.background+"_semi")):r===45?c.background="transparent":(c.foreground="black",r===47&&(c.underline=!0));const d=e<=23?1:2;return this.getChannel(d).setBkgData(c),!0}reset(){for(let e=0;ee)&&(this.startTime=e),this.endTime=r,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class NUt{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ege(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Ee.FRAG_LOADING,this.onFragLoading,this),e.on(Ee.FRAG_LOADED,this.onFragLoaded,this),e.on(Ee.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Ee.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Ee.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Ee.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Ee.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Ee.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Ee.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Ee.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Ee.FRAG_LOADING,this.onFragLoading,this),e.off(Ee.FRAG_LOADED,this.onFragLoaded,this),e.off(Ee.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Ee.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Ee.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Ee.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Ee.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Ee.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new SM(this,"textTrack1"),r=new SM(this,"textTrack2"),n=new SM(this,"textTrack3"),i=new SM(this,"textTrack4");this.cea608Parser1=new Jpe(1,e,r),this.cea608Parser2=new Jpe(3,n,i)}addCues(e,r,n,i,a){let c=!1;for(let p=a.length;p--;){const l=a[p],g=RUt(l[0],l[1],r,n);if(g>=0&&(l[0]=Math.min(l[0],r),l[1]=Math.max(l[1],n),c=!0,g/(n-r)>.5))return}if(c||a.push([r,n]),this.config.renderTextTracksNatively){const p=this.cueCache[e];if(p){const l=this.Cues.newCue(null,r,n,i);l.length&&p.push.apply(p,l)}else{const l=this.captionsTracks[e].track;this.Cues.newCue(l,r,n,i)}}else{var d;const p=this.Cues.newCue(null,r,n,i),l=(d=this.captionsProperties[e])==null?void 0:d.media;this.hls.trigger(Ee.CUES_PARSED,{type:"captions",cues:p,track:e,closedCaptions:l})}}onInitPtsFound(e,{id:r,timestampOffsets:n}){const{unparsedFrags:i}=this;r===On.MAIN&&(this.initPTS=n),i.length&&(this.unparsedFrags=[],i.forEach(a=>{this.initPTS[a.frag.cc]?this.onFragLoaded(Ee.FRAG_LOADED,a):this.hls.trigger(Ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:a.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:r,captionsTracks:n,cueCache:i,media:a}=this,{label:c,languageCode:d}=r[e];a&&(i[e]=[],n[e]=QQ(a,"captions",c,d,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const r=this.captionsProperties[e];if(!r)return;const n=r.label,i={_id:e,label:n,kind:"captions",default:r.media?!!r.media.default:!1,closedCaptions:r.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(Ee.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}onMediaAttaching(e,r){this.media=r.media}onMediaDetaching(e,r){const n=!!r.transferMedia;if(this.media=null,!n){if(this.config.renderTextTracksNatively){const{captionsTracks:i,cueCache:a}=this;for(const c in i)i[c].remove(),delete a[c]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ege(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,r){const n=r.subtitleTracks||[];if(n.length&&!this.config.renderTextTracksNatively&&!XPe(this.tracks,n)){const i=n.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger(Ee.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:i})}this.tracks=n}onManifestLoaded(e,r){this.config.enableCEA708Captions&&r.captions&&r.captions.forEach(n=>{const i=/(?:CC|SERVICE)([1-4])/.exec(n.instreamId);if(!i)return;const a=`textTrack${i[1]}`,c=this.captionsProperties[a];c&&(c.label=n.name,n.lang&&(c.languageCode=n.lang),c.media=n)})}closedCaptionsForLevel(e){const r=this.hls.levels[e.level];return r==null?void 0:r.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,r){if(this.enabled&&r.frag.type===On.MAIN){var n,i;const{cea608Parser1:a,cea608Parser2:c,lastSn:d}=this,{cc:p,sn:l}=r.frag,g=(n=(i=r.part)==null?void 0:i.index)!=null?n:-1;a&&c&&(l!==d+1||l===d&&g!==this.lastPartIndex+1||p!==this.lastCc)&&(a.reset(),c.reset()),this.lastCc=p,this.lastSn=l,this.lastPartIndex=g}}onFragLoaded(e,r){const{frag:n,payload:i}=r;if(n.level{this._appendCues(c,r.level),a.trigger(Ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r,part:i})},c=>{a.logger.log(`Cannot parse IMSC1 (sn: ${r.sn} @${r.start}): ${c}`),a.trigger(Ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,part:i,error:c})})}_parseVTTs(e){var r;const{frag:n,payload:i}=e,a="part"in e?e.part:null,{initPTS:c,unparsedFrags:d}=this,p=c.length-1;if(!c[n.cc]&&p===-1){d.push(e);return}const l=this.hls,g=(r=n.initSegment)==null?void 0:r.data,v=g?Kf(g,new Uint8Array(i)).buffer:i;B6t(v,this.initPTS[n.cc],this.vttCCs,n.cc,(a&&!g?a:n).start,E=>{this._appendCues(E,n.level),l.trigger(Ee.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n,part:a})},E=>{const T=E.message.startsWith("Missing initPTS");if(l.logger.log(`${T?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${n.sn} @${n.start}): ${E}`),T){d.push(e);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(e);l.trigger(Ee.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:a,error:E})})}_fallbackToIMSC1(e){const{frag:r,payload:n}=e,i=this.tracks[r.level];i.textCodec||Vpe(n,this.initPTS[r.cc],()=>{i.textCodec=DH,this._parseIMSC1(e)},()=>{i.textCodec="wvtt"})}_appendCues(e,r){const n=this.hls;if(this.config.renderTextTracksNatively){var i;const a=(i=this.tracks[r].trackNode)==null?void 0:i.track;if(!a||a.mode==="disabled")return;e.forEach(c=>MH(a,c))}else{const a=this.tracks[r];if(!a)return;const c=a.default?"default":"subtitles"+r;n.trigger(Ee.CUES_PARSED,{type:"subtitles",cues:e,track:c,subtitleTrack:a})}}onFragDecrypted(e,r){const{frag:n}=r;n.type===On.SUBTITLE&&this.onFragLoaded(Ee.FRAG_LOADED,r)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,r){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:n,samples:i}=r;if(!(n.type===On.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let a=0;a{var l;const g=(l=c[p])==null?void 0:l.track;if(g){const v=d[p];for(let E=0;EOH(p[g].track,n,i)),Object.keys(l).forEach(g=>{const v=l[g];for(let E=v.length;E--;){const T=v[E];T.startTime>=n&&T.endTime<=i&&v.splice(E,1)}})}this.config.renderTextTracksNatively&&n===0&&a!==void 0&&this.tracks.forEach(p=>{var l;const g=(l=p.trackNode)==null?void 0:l.track;g&&OH(g,n,a)})}}extractCea608Data(e){const r=[[],[]],n=e[0]&31;let i=2;for(let a=0;a=16?p--:p++;const T=vNe(l.trim()),j=XQ(e,r,T);t!=null&&(v=t.cues)!=null&&v.getCueById(j)||(c=new g(e,r,T),c.id=j,c.line=E+1,c.align="left",c.position=10+Math.min(80,Math.floor(p*8/32)*10),i.push(c))}return t&&i.length&&(i.sort((E,T)=>E.line==="auto"||T.line==="auto"?0:E.line>8&&T.line>8?T.line-E.line:E.line-T.line),i.forEach(E=>MH(t,E))),i}};class PNe{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new EQ}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,r,n){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=e,this.config=r,this.callbacks=n,this.loadInternal()}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,r=this.stats.retry;if(sP(e,r,!0))this.retry(e);else{var n;la.warn(`timeout while loading ${(n=this.context)==null?void 0:n.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){const{context:r,stats:n}=this;this.retryDelay=TQ(e,n.retry),n.retry++,la.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${r==null?void 0:r.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}function MUt(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const OUt=/(\d+)-(\d+)\/(\d+)/;class tge extends PNe{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||$Ut}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:e,context:r,stats:n}=this;if(!e||!r)return;n.loading.first=0,n.loaded=0,n.aborted=!1,this.controller=new self.AbortController;const i=FUt(r,this.controller.signal),a=r.responseType==="arraybuffer",c=a?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:p}=e.loadPolicy;this.request=this.fetchSetup(r,i),self.clearTimeout(this.requestTimeout),e.timeout=d&&yn(d)?d:p,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(mP(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(g=>{var v;this.response=g;const E=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=p,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},p-(E-n.loading.start)),!g.ok){const{status:j,statusText:P}=g;throw new UUt(P||"fetch, bad network response",j,g)}n.loading.first=E,n.total=zUt(g.headers)||n.total;const T=(v=this.callbacks)==null?void 0:v.onProgress;return T&&yn(e.highWaterMark)?this.loadProgressively(g,n,r,e.highWaterMark,T):a?g.arrayBuffer():r.responseType==="json"?g.json():g.text()}).then(g=>{var v,E;const T=this.response;if(!T)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const j=g[c];j&&(n.loaded=n.total=j);const P={url:T.url,data:g,code:T.status},C=(v=this.callbacks)==null?void 0:v.onProgress;C&&!yn(e.highWaterMark)&&C(n,r,g,T),(E=this.callbacks)==null||E.onSuccess(P,n,r,T)}).catch(g=>{if(self.clearTimeout(this.requestTimeout),n.aborted)return;const v=g&&g.code||0,E=g?g.message:null,T=e.loadPolicy.errorRetry,j=n.retry,P={url:r.url,data:void 0,code:v};if(sP(T,j,!1,P))this.retry(T);else{var C;la.error(`${v} while loading ${r.url}`),(C=this.callbacks)==null||C.onError({code:v,text:E},r,g?g.details:null,n)}})}getCacheAge(){let e=null;if(this.response){const r=this.response.headers.get("age");e=r?parseFloat(r):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,r,n,i=0,a){const c=new RPe,d=e.body.getReader(),p=()=>d.read().then(l=>{if(l.done)return c.dataLength&&a(r,n,c.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const g=l.value,v=g.length;return r.loaded+=v,v=i&&a(r,n,c.flush().buffer,e)):a(r,n,g.buffer,e),p()}).catch(()=>Promise.reject());return p()}}function FUt(t,e){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(La({},t.headers))};return t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),r}function BUt(t){const e=OUt.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function zUt(t){const e=t.get("Content-Range");if(e){const n=BUt(e);if(yn(n))return n}const r=t.get("Content-Length");if(r)return parseInt(r)}function $Ut(t,e){return new self.Request(t.url,e)}class UUt extends Error{constructor(e,r,n){super(e),this.code=void 0,this.details=void 0,this.code=r,this.details=n}}const VUt=(t,e,r)=>Math.max(e,Math.min(t,r)),qUt=/^age:\s*[\d.]+\s*$/im;class NNe extends PNe{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:e,context:r}=this;if(!e||!r)return;const n=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const a=this.xhrSetup;a?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return a.call(this,n,r.url,r)}).catch(c=>{if(!(this.loader!==n||this.stats.aborted))return n.open("GET",r.url,!0),a.call(this,n,r.url,r)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,r,e)}).catch(c=>{var d;(d=this.callbacks)==null||d.onError({code:n.status,text:c.message},r,n,i)}):this.openAndSendXhr(n,r,e)}openAndSendXhr(e,r,n){e.readyState||e.open("GET",r.url,!0);const i=r.headers,{maxTimeToFirstByteMs:a,maxLoadTimeMs:c}=n.loadPolicy;if(i)for(const d in i)e.setRequestHeader(d,i[d]);r.rangeEnd&&e.setRequestHeader("Range",`bytes=${r.rangeStart}-${r.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=r.responseType,self.clearTimeout(this.requestTimeout),n.timeout=a&&yn(a)?a:c,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){const{context:e,loader:r,stats:n}=this;if(!e||!r)return;const i=r.readyState,a=this.config;if(!n.aborted&&i>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),a.timeout!==a.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),a.timeout=a.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),r.onreadystatechange=null,r.onprogress=null;const l=r.status,g=r.responseType==="text"?r.responseText:null;if(l>=200&&l<300){const j=g??r.response;if(j!=null){var c,d;n.loading.end=Math.max(self.performance.now(),n.loading.first);const P=r.responseType==="arraybuffer"?j.byteLength:j.length;n.loaded=n.total=P,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);const C=(c=this.callbacks)==null?void 0:c.onProgress;C&&C(n,e,j,r);const L={url:r.responseURL,data:j,code:l};e.rangeEnd&&P!==e.rangeEnd-e.rangeStart&&la.warn(`Payload length ${P} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(d=this.callbacks)==null||d.onSuccess(L,n,e,r);return}}const v=a.loadPolicy.errorRetry,E=n.retry,T={url:e.url,data:void 0,code:l};if(sP(v,E,!1,T))this.retry(v);else{var p;la.error(`${l} while loading ${e.url}`),(p=this.callbacks)==null||p.onError({code:l,text:r.statusText},e,r,n)}}}loadprogress(e){const r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total)}getCacheAge(){let e=null;if(this.loader&&qUt.test(this.loader.getAllResponseHeaders())){const r=this.loader.getResponseHeader("age");e=r?parseFloat(r):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const GUt={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},HUt=Hn(Hn({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:NNe,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:SPe,requireKeySystemAccessOnStart:!1,reuseKeySessions:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2*1024*1024,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:GUt},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:ANe,abrController:IBt,bufferController:FBt,capLevelController:VQ,errorController:RBt,fpsController:N6t,id3TrackController:J6t,gapController:X6t,latencyController:gUt},WUt()),{},{subtitleStreamController:xUt,subtitleTrackController:Y6t,timelineController:NUt,audioStreamController:y$t,audioTrackController:x$t,emeController:yP,cmcdController:T6t,contentSteeringController:k6t,iframeController:aUt,interstitialsController:pUt});function WUt(){return{cueHandler:DUt,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function KUt(t,e,r){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(e.liveMaxUnchangedPlaylistRefresh!==void 0){const c=e.liveMaxUnchangedPlaylistRefresh,d=VUt(c,2,1/0);d!==c&&r.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${c} to ${d}.`),e.liveMaxUnchangedPlaylistRefresh=d}const n=zH(t),i=["manifest","level","frag"],a=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(c=>{const d=`${c==="level"?"playlist":c}LoadPolicy`,p=e[d]===void 0,l=[];a.forEach(g=>{const v=`${c}Loading${g}`,E=e[v];if(E!==void 0&&p){l.push(v);const T=n[d].default;switch(e[d]={default:T},g){case"TimeOut":T.maxLoadTimeMs=E,T.maxTimeToFirstByteMs=E;break;case"MaxRetry":T.errorRetry.maxNumRetry=E,T.timeoutRetry.maxNumRetry=E;break;case"RetryDelay":T.errorRetry.retryDelayMs=E,T.timeoutRetry.retryDelayMs=E;break;case"MaxRetryTimeout":T.errorRetry.maxRetryDelayMs=E,T.timeoutRetry.maxRetryDelayMs=E;break}}}),l.length&&r.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${d}": ${fo(e[d])}`)}),Hn(Hn({},n),e)}function zH(t){return t&&typeof t=="object"?Array.isArray(t)?t.map(zH):Object.keys(t).reduce((e,r)=>(e[r]=zH(t[r]),e),{}):t}function YUt(t,e){const r=t.loader;r!==tge&&r!==NNe?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):MUt()&&(t.loader=tge,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}class ZUt extends UQ{constructor(e,r){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=r,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Ee.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Ee.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Ee.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Ee.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Ee.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Ee.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Ee.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(r=>{r.loadError=0,r.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,r){this.resetLevels()}onManifestLoaded(e,r){const n=this.hls.config.preferManagedMediaSource,i=[],a={},c={};let d=!1,p=!1,l=!1,g=!1;r.levels.forEach(v=>{const E=v.attrs,T=rge(v,n),{audioCodec:j,videoCodec:P,imageCodec:C,width:L,height:O}=v;if(!T){this.log(`Some or all CODECS not supported "${E.CODECS}"`);return}d||(d=!!(L&&O)),p||(p=!!P),l||(l=!!j),g||(g=!!C);const{CODECS:F,"FRAME-RATE":$,"HDCP-LEVEL":G,"PATHWAY-ID":W,RESOLUTION:Z,"VIDEO-RANGE":Q}=E,ie=`${`${W||"."}-`}${v.bitrate}-${Z}-${$}-${F}-${Q}-${G}`;if(a[ie])if(a[ie].uri!==v.url&&!v.attrs["PATHWAY-ID"]){const oe=c[ie]+=1;v.attrs["PATHWAY-ID"]=new Array(oe+1).join(".");const pe=this.createLevel(v);a[ie]=pe,i.push(pe)}else v.iframes||(a[ie].addGroupId("audio",E.AUDIO),a[ie].addGroupId("text",E.SUBTITLES));else{const oe=this.createLevel(v);a[ie]=oe,c[ie]=1,i.push(oe)}}),this.filterAndSortMediaOptions(i,r,d,p,l,g)}createLevel(e){const r=new dP(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!LNe(n.videoCodec,this.hls.config.preferManagedMediaSource)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(i.message),r.supportedResult=sPe(i,[])}return r}filterAndSortMediaOptions(e,r,n,i,a,c){var d;let p=[],l=[],g=e;const v=((d=r.stats)==null?void 0:d.parsing)||{},E=this.hls.config.preferManagedMediaSource;if((n||i)&&a&&(g=g.filter(({videoCodec:G,videoRange:W,width:Z,height:Q})=>(!!G||!!(Z&&Q))&&_Bt(W))),i&&c&&(g=g.filter(G=>!G.imageCodec)),g.length===0){Promise.resolve().then(()=>{if(this.hls){let G="no level with compatible codecs found in manifest",W=G;r.levels.length&&(W=`one or more CODECS in variant not supported: ${fo(r.levels.map(Q=>Q.attrs.CODECS).filter((Q,ee,ie)=>ie.indexOf(Q)===ee))}`,this.warn(W),G+=` (${W})`);const Z=new Error(G);this.hls.trigger(Ee.ERROR,{type:Kn.MEDIA_ERROR,details:Wt.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:r.url,error:Z,reason:W})}}),v.end=performance.now();return}r.audioTracks&&(p=r.audioTracks.filter(G=>!G.audioCodec||RNe(G.audioCodec,E)),nge(p)),r.subtitles&&(l=r.subtitles,nge(l));const T=g.slice(0);g.sort((G,W)=>{if(G.attrs["HDCP-LEVEL"]!==W.attrs["HDCP-LEVEL"])return(G.attrs["HDCP-LEVEL"]||"")>(W.attrs["HDCP-LEVEL"]||"")?1:-1;if(n&&G.height!==W.height)return G.height-W.height;if(G.frameRate!==W.frameRate)return G.frameRate-W.frameRate;if(G.videoRange!==W.videoRange)return W3.indexOf(G.videoRange)-W3.indexOf(W.videoRange);if(G.videoCodec!==W.videoCodec){const Z=Fme(G.videoCodec),Q=Fme(W.videoCodec);if(Z!==Q)return Q-Z}if(G.uri===W.uri&&G.codecSet!==W.codecSet){const Z=G3(G.codecSet),Q=G3(W.codecSet);if(Z!==Q)return Q-Z}return G.averageBitrate!==W.averageBitrate?G.averageBitrate-W.averageBitrate:0});let j=T[0];if(this.steering&&(g=this.steering.filterParsedLevels(g),g.length!==T.length)){for(let G=0;GZ&&Z===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=Q)}break}const C=r.iframeVariants.filter(G=>rge(G,E));this._iframeVariants=C;const L=a&&!i,O=this.hls.config,F=!!(O.audioStreamController&&O.audioTrackController),$={levels:g,audioTracks:p,subtitleTracks:l,iframeVariants:C,sessionData:r.sessionData,sessionKeys:r.sessionKeys,firstLevel:this._firstLevel,stats:r.stats,audio:a,video:i,altAudio:F&&!L&&p.some(G=>!!G.url)};v.end=performance.now(),this.hls.trigger(Ee.MANIFEST_PARSED,$)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const r=this._levels;if(r.length===0)return;if(e<0||e>=r.length){const g=new Error("invalid level idx"),v=e<0;if(this.hls.trigger(Ee.ERROR,{type:Kn.OTHER_ERROR,details:Wt.LEVEL_SWITCH_ERROR,level:e,fatal:v,error:g,reason:g.message}),v)return;e=Math.min(e,r.length-1)}const n=this.currentLevelIndex,i=this.currentLevel,a=i?i.attrs["PATHWAY-ID"]:void 0,c=r[e],d=c.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=c,n===e&&i&&a===d)return;this.log(`Switching to level ${e} (${c.height?c.height+"p ":""}${c.videoRange?c.videoRange+" ":""}${c.codecSet?c.codecSet+" ":""}@${c.bitrate})${d?" with Pathway "+d:""} from level ${n}${a?" with Pathway "+a:""}`);const p={level:e,attrs:c.attrs,details:c.details,bitrate:c.bitrate,averageBitrate:c.averageBitrate,maxBitrate:c.maxBitrate,realBitrate:c.realBitrate,width:c.width,height:c.height,codecSet:c.codecSet,audioCodec:c.audioCodec,videoCodec:c.videoCodec,audioGroups:c.audioGroups,subtitleGroups:c.subtitleGroups,loaded:c.loaded,loadError:c.loadError,fragmentError:c.fragmentError,name:c.name,id:c.id,uri:c.uri,url:c.url,urlId:0,audioGroupIds:c.audioGroupIds,textGroupIds:c.textGroupIds};this.hls.trigger(Ee.LEVEL_SWITCHING,p);const l=c.details;if(!l||l.live){const g=this.switchParams(c.uri,i==null?void 0:i.details,l);this.loadPlaylist(g)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const r=this.steering.pathways(),n=e.filter(i=>r.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${r}`);return}this.steering.pathwayPriority=n}}onError(e,r){r.fatal||!r.context||r.context.type===ts.LEVEL&&r.context.level===this.level&&this.checkRetry(r)}onFragBuffered(e,{frag:r}){if(r.type===On.MAIN){const n=r.elementaryStreams;if(!Object.keys(n).some(a=>!!n[a]))return;const i=this._levels[r.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,r){var n;const{level:i,details:a}=r,c=r.levelInfo;if(!c){var d;this.warn(`Invalid level index ${i}`),(d=r.deliveryDirectives)!=null&&d.skip&&(a.deltaUpdateFailed=!0);return}if(c===this.currentLevel||r.withoutMultiVariant){c.fragmentError===0&&(c.loadError=0);let p=c.details;p===r.details&&p.advanced&&(p=void 0),this.playlistLoaded(i,r,p)}else(n=r.deliveryDirectives)!=null&&n.skip&&(a.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,r){super.loadingPlaylist(e,r);const n=this.getUrlWithDirectives(e.uri,r),i=this.currentLevelIndex,a=e.attrs["PATHWAY-ID"],c=e.details,d=c==null?void 0:c.age;this.log(`Loading level index ${i}${(r==null?void 0:r.msn)!==void 0?" at sn "+r.msn+" part "+r.part:""}${a?" Pathway "+a:""}${d&&c.live?" age "+d.toFixed(1)+(c.type&&" "+c.type||""):""} ${n}`),this.hls.trigger(Ee.LEVEL_LOADING,{url:n,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){const r=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==r&&e!==-1){const i=this.hls.config.abrSwitchInterval;if(i>0){const a=performance.now(),c=a-this.lastABRSwitchTime,d=i*1e3;if(this.lastABRSwitchTime>-1&&c ${e} (${Math.round(c)}ms < ${d}ms / ${i}s)`);return}this.lastABRSwitchTime=a,this.log(`Allowing ABR level switch: ${r} -> ${e} (${Math.round(c)}ms >= ${d}ms / ${i}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var r;if(this._levels.length===1)return;const n=this._levels.filter((a,c)=>c!==e?!0:(this.steering&&this.steering.removeLevel(a),a===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,a.details&&a.details.fragments.forEach(d=>d.level=-1)),!1));CPe(n),this._levels=n,this.currentLevelIndex>-1&&(r=this.currentLevel)!=null&&r.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=n.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(Ee.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:r}){this._levels=r}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:r,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(Ee.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}function RNe(t,e){return cP(t,"audio",e)}function LNe(t,e){return cP(t,"video",e)}function rge(t,e){let{audioCodec:r,videoCodec:n}=t;r&&(t.audioCodec=r=H3(r,e)||void 0),n&&(n=t.videoCodec=uBt(n));const{unknownCodecs:i}=t;return!((i==null?void 0:i.length)||0||r&&!RNe(r,e)||n&&!LNe(n,e))}function nge(t){const e={};t.forEach(r=>{const n=r.groupId||"";r.id=e[n]=e[n]||0,e[n]++})}class XUt extends ff{constructor(e,r){super("key-loader",r),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(const n in this.keyLoaderInfo){const i=this.keyLoaderInfo[n].loader;if(i){var r;if(e&&e!==((r=i.context)==null?void 0:r.frag.type))return;i.abort()}}}destroy(){for(const e in this.keyLoaderInfo){const r=this.keyLoaderInfo[e].loader;r&&r.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,r,n){return this.emeController?this.emeController.loadClear(e,r,n):null}load(e,r){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(n=>this.loadInternal(e,r,n)):this.loadInternal(e,r)}loadInternal(e,r,n){n&&e.setKeyFormat(n);const i=e.decryptdata;if(!i){const c=new Error(n?`Expected frag.decryptdata to be defined after setting format ${n}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(v_(e,Wt.KEY_LOAD_ERROR,c))}const a=e;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return i.keyFormat==="identity"?this.loadKeyHTTP(a):r?r.then(()=>this.loadKeyEME(a)):this.loadKeyEME(a);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(a);default:return Promise.reject(v_(e,Wt.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=e.initSegment)!=null&&r.data){const n=q5t(e.initSegment.data);if(n.length){let i=n[0];const a=e.decryptdata.uri;if(i.some(c=>c!==0))this.log(`Using keyId found in init segment ${lc(i)} keyUri: ${a}`),By.setKeyIdForUri(a,i);else{const c=By.addKeyIdForUri(a);this.log(`Patching empty keyId with ${lc(c)} keyUri: ${a}`),i=c}e.decryptdata.keyId=i}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(v_(e,Wt.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){const r=e.decryptdata,n=r.uri;if(!n)return Promise.reject(v_(e,Wt.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const i=this.keyLoaderInfo[n];if(i){if(i.decryptdata.key)return r.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then(l=>(r.key=i.decryptdata.key,Hn(Hn({},l),{},{frag:e})))}this.log(`Loading${r.keyId?" keyId: "+lc(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`);const a=this.config,c=a.loader,d=new c(a);e.keyLoader=d;const p=this.keyLoaderInfo[n]={decryptdata:r,keyLoadPromise:null,loader:d};return p.keyLoadPromise=new Promise((l,g)=>{const v={type:ts.KEY,keyInfo:p,frag:e,responseType:"arraybuffer",url:n},E=a.keyLoadPolicy.default,T={loadPolicy:E,timeout:E.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},j={onSuccess:(P,C,L,O)=>{const{frag:F,keyInfo:$,url:G}=L;if(!F.decryptdata||$!==this.keyLoaderInfo[G])return this.resetLoader(L),g(v_(F,Wt.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),O));$.decryptdata.key=F.decryptdata.key=new Uint8Array(P.data),F.keyLoader=$.loader=$.keyLoadPromise=null,l({frag:F,keyInfo:$})},onError:(P,C,L,O)=>{this.resetLoader(C),g(v_(e,Wt.KEY_LOAD_ERROR,new Error(`HTTP Error ${P.code} loading key ${P.text}`),L,Hn({url:n,data:void 0},P)))},onTimeout:(P,C,L)=>{this.resetLoader(C),g(v_(e,Wt.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),L))},onAbort:(P,C,L)=>{this.resetLoader(C),g(v_(e,Wt.INTERNAL_ABORTED,new Error("key loading aborted"),L))}};d.load(v,T,j)})}resetLoader(e){const{frag:r,keyInfo:n,url:i}=e,a=n.loader;r.keyLoader===a&&(r.keyLoader=n.loader=n.keyLoadPromise=null),delete this.keyLoaderInfo[i],a&&a.destroy()}}function v_(t,e=Wt.KEY_LOAD_ERROR,r,n,i){return new $p({type:Kn.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:i,error:r,networkDetails:n||null})}function ige(t){const{type:e}=t;switch(e){case ts.AUDIO_TRACK:return On.AUDIO;case ts.SUBTITLE_TRACK:return On.SUBTITLE;default:return On.MAIN}}function b8(t,e){let r=t.url;return(r===void 0||r.indexOf("data:")===0)&&(r=e.url),r}class QUt{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Ee.LEVEL_LOADING,this.onLevelLoading,this),e.on(Ee.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Ee.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Ee.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(Ee.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Ee.LEVEL_LOADING,this.onLevelLoading,this),e.off(Ee.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Ee.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Ee.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const r=this.hls.config,n=r.pLoader,i=r.loader,a=n||i,c=new a(r);return this.loaders[e.type]=c,c}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const r=this.loaders[e];r&&r.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,r){const{url:n}=r;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ts.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,r){const{id:n,level:i,pathwayId:a,url:c,deliveryDirectives:d,levelInfo:p}=r;this.load({id:n,level:i,pathwayId:a,responseType:"text",type:ts.LEVEL,url:c,deliveryDirectives:d,levelOrTrack:p})}onAudioTrackLoading(e,r){const{id:n,groupId:i,url:a,deliveryDirectives:c,track:d}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:ts.AUDIO_TRACK,url:a,deliveryDirectives:c,levelOrTrack:d})}onSubtitleTrackLoading(e,r){const{id:n,groupId:i,url:a,deliveryDirectives:c,track:d}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:ts.SUBTITLE_TRACK,url:a,deliveryDirectives:c,levelOrTrack:d})}onLevelsUpdated(e,r){const n=this.loaders[ts.LEVEL];if(n){const i=n.context;i&&!r.levels.some(a=>a===i.levelOrTrack)&&(n.abort(),delete this.loaders[ts.LEVEL])}}load(e){var r;const n=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,g=i.context;if((g==null?void 0:g.levelOrTrack)===e.levelOrTrack&&(g.url===e.url||g.deliveryDirectives&&!e.deliveryDirectives)){g.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${g.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let a;if(e.type===ts.MANIFEST?a=n.manifestLoadPolicy.default:a=La({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),yn((r=e.deliveryDirectives)==null?void 0:r.part)){let l;if(e.type===ts.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===ts.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===ts.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const g=l.partTarget,v=l.targetduration;if(g&&v){const E=Math.max(g*3,v*.8)*1e3;a=La({},a,{maxTimeToFirstByteMs:Math.min(E,a.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(E,a.maxTimeToFirstByteMs)})}}}const c=a.errorRetry||a.timeoutRetry||{},d={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:c.maxNumRetry||0,retryDelay:c.retryDelayMs||0,maxRetryDelay:c.maxRetryDelayMs||0},p={onSuccess:(l,g,v,E)=>{const T=this.getInternalLoader(v);this.resetInternalLoader(v.type);const j=l.data;g.parsing.start=performance.now(),eg.isMediaPlaylist(j)||v.type!==ts.MANIFEST?this.handleTrackOrLevelPlaylist(l,g,v,E||null,T):this.handleMasterPlaylist(l,g,v,E)},onError:(l,g,v,E)=>{this.handleNetworkError(g,v,!1,l,E)},onTimeout:(l,g,v)=>{this.handleNetworkError(g,v,!0,void 0,l)}};i.load(e,d,p)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:r},forceStartLoad:n}=this.hls;(e||n)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${r}`),this.hls.startLoad(r))}handleMasterPlaylist(e,r,n,i){const a=this.hls,c=e.data,d=b8(e,n),p=eg.parseMasterPlaylist(c,d);if(p.playlistParsingError){r.parsing.end=performance.now(),this.handleManifestParsingError(e,n,p.playlistParsingError,i,r);return}const{contentSteering:l,levels:g,iframeVariants:v,sessionData:E,sessionKeys:T,startTimeOffset:j,variableList:P}=p;this.variableList=P,g.forEach(F=>{const{unknownCodecs:$}=F;if($){const{preferManagedMediaSource:G}=this.hls.config;let{audioCodec:W,videoCodec:Z}=F;for(let Q=$.length;Q--;){const ee=$[Q];cP(ee,"audio",G)?(F.audioCodec=W=W?`${W},${ee}`:ee,GT.audio[W.substring(0,4)]=2,$.splice(Q,1)):cP(ee,"video",G)&&(F.videoCodec=Z=Z?`${Z},${ee}`:ee,GT.video[Z.substring(0,4)]=2,$.splice(Q,1))}}});const{AUDIO:C=[],SUBTITLES:L,"CLOSED-CAPTIONS":O}=eg.parseMasterPlaylistMedia(c,d,p);C.length&&!C.some($=>!$.url)&&g[0].audioCodec&&!g[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),C.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Vo({}),bitrate:0,url:""})),a.trigger(Ee.MANIFEST_LOADED,{levels:g,audioTracks:C,subtitles:L,iframeVariants:v,captions:O,contentSteering:l,url:d,stats:r,networkDetails:i,sessionData:E,sessionKeys:T,startTimeOffset:j,variableList:P})}handleTrackOrLevelPlaylist(e,r,n,i,a){const c=this.hls,{id:d,level:p,type:l}=n,g=b8(e,n),v=yn(p)?p:yn(d)?d:0,E=ige(n),T=eg.parseLevelPlaylist(e.data,g,v,E,0,this.variableList);if(l===ts.MANIFEST){const j={attrs:new Vo({}),bitrate:0,details:T,name:"",url:g};T.requestScheduled=r.loading.start+IPe(T,0),c.trigger(Ee.MANIFEST_LOADED,{levels:[j],audioTracks:[],iframeVariants:[],url:g,stats:r,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}r.parsing.end=performance.now(),n.levelDetails=T,this.handlePlaylistLoaded(T,e,r,n,i,a)}handleManifestParsingError(e,r,n,i,a){this.hls.trigger(Ee.ERROR,{type:Kn.NETWORK_ERROR,details:Wt.MANIFEST_PARSING_ERROR,fatal:r.type===ts.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:r,networkDetails:i,stats:a})}handleNetworkError(e,r,n=!1,i,a){let c=`A network ${n?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===ts.LEVEL?c+=`: ${e.level} id: ${e.id}`:(e.type===ts.AUDIO_TRACK||e.type===ts.SUBTITLE_TRACK)&&(c+=` id: ${e.id} group-id: "${e.groupId}"`);const d=new Error(c);this.hls.logger.warn(`[playlist-loader]: ${c}`);let p=Wt.UNKNOWN,l=!1;const g=this.getInternalLoader(e);switch(e.type){case ts.MANIFEST:p=n?Wt.MANIFEST_LOAD_TIMEOUT:Wt.MANIFEST_LOAD_ERROR,l=!0;break;case ts.LEVEL:p=n?Wt.LEVEL_LOAD_TIMEOUT:Wt.LEVEL_LOAD_ERROR,l=!1;break;case ts.AUDIO_TRACK:p=n?Wt.AUDIO_TRACK_LOAD_TIMEOUT:Wt.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ts.SUBTITLE_TRACK:p=n?Wt.SUBTITLE_TRACK_LOAD_TIMEOUT:Wt.SUBTITLE_LOAD_ERROR,l=!1;break}g&&this.resetInternalLoader(e.type);const v={type:Kn.NETWORK_ERROR,details:p,fatal:l,url:e.url,loader:g,context:e,error:d,networkDetails:r,stats:a};if(i){let E=e.url;r&&"url"in r&&(E=r.url),v.response=Hn({url:E,data:void 0},i)}this.hls.trigger(Ee.ERROR,v)}handlePlaylistLoaded(e,r,n,i,a,c){const d=this.hls,{type:p,level:l,levelOrTrack:g,id:v,groupId:E,deliveryDirectives:T}=i,j=b8(r,i),P=ige(i);let C=typeof i.level=="number"&&P===On.MAIN?l:void 0;g&&"iframes"in g&&g.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);const L=e.playlistParsingError;if(L){if(this.hls.logger.warn(`${L} ${e.url}`),!d.config.ignorePlaylistParsingErrors){d.trigger(Ee.ERROR,{type:Kn.NETWORK_ERROR,details:Wt.LEVEL_PARSING_ERROR,fatal:!1,url:j,error:L,reason:L.message,response:r,context:i,level:C,parent:P,networkDetails:a,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){const O=e.playlistParsingError=new Error("No Segments found in Playlist");d.trigger(Ee.ERROR,{type:Kn.NETWORK_ERROR,details:Wt.LEVEL_EMPTY_ERROR,fatal:!1,url:j,error:O,reason:O.message,response:r,context:i,level:C,parent:P,networkDetails:a,stats:n});return}switch(e.live&&c&&(c.getCacheAge&&(e.ageHeader=c.getCacheAge()||0),(!c.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),p){case ts.MANIFEST:case ts.LEVEL:if(C){if(!g)C=0;else if(g!==d.levels[C]){const O=d.levels.indexOf(g);O>-1&&(C=O)}}d.trigger(Ee.LEVEL_LOADED,{details:e,levelInfo:g||d.levels[0],level:C||0,id:v||0,stats:n,networkDetails:a,deliveryDirectives:T,withoutMultiVariant:p===ts.MANIFEST,context:i});break;case ts.AUDIO_TRACK:d.trigger(Ee.AUDIO_TRACK_LOADED,{details:e,track:g,id:v||0,groupId:E||"",stats:n,networkDetails:a,deliveryDirectives:T,context:i});break;case ts.SUBTITLE_TRACK:d.trigger(Ee.SUBTITLE_TRACK_LOADED,{details:e,track:g,id:v||0,groupId:E||"",stats:n,networkDetails:a,deliveryDirectives:T,context:i});break}}}class qm{static get version(){return fP}static isMSESupported(){return TNe()}static isSupported(){return eUt()}static getMediaSource(){return Rv()}static get Events(){return Ee}static get MetadataSchema(){return Pd}static get ErrorTypes(){return Kn}static get ErrorDetails(){return Wt}static get DefaultConfig(){return qm.defaultConfig?qm.defaultConfig:HUt}static set DefaultConfig(e){qm.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new OQ,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const r=this.logger=y5t(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),n=this.config=KUt(qm.DefaultConfig,e,r);this.userConfig=e,n.progressive&&YUt(n,r);const{streamController:i,abrController:a,bufferController:c,capLevelController:d,errorController:p,fpsController:l,id3TrackController:g,iframeController:v,gapController:E}=n,T=new p(this),j=this.abrController=new a(this),P=new zBt(this),C=n.interstitialsController,L=C?this.interstitialsController=new C(this,qm):null,O=c?this.bufferController=new c(this,P):null,F=d?this.capLevelController=new d(this):null,$=l?new l(this):null,G=n.cmcdController,W=G?this.cmcdController=new G(this):null,Z=new QUt(this),Q=n.contentSteeringController,ee=Q?new Q(this):null,ie=this.levelController=new ZUt(this,ee),oe=g?new g(this):void 0,pe=new XUt(this.config,this.logger),Le=this.streamController=new i(this,P,pe),be=this.gapController=E?new E(this,P):void 0;F&&F.setStreamController(Le);const Re=[Z,ie,Le];L&&Re.splice(1,0,L),ee&&Re.splice(1,0,ee),this.networkControllers=Re;const Ie=[j];O&&Ie.push(O),be&&Ie.push(be),F&&Ie.push(F),$&&($.setStreamController(Le),Ie.push($)),oe&&Ie.push(oe),Ie.push(P),this.audioTrackController=this.createController(n.audioTrackController,Re);const Te=n.audioStreamController;Te&&Re.push(this.audioStreamController=new Te(this,P,pe)),this.subtitleTrackController=this.createController(n.subtitleTrackController,Re);const ge=n.subtitleStreamController;ge&&Re.push(this.subtititleStreamController=new ge(this,P,pe)),this.createController(n.timelineController,Ie),pe.emeController=this.emeController=this.createController(n.emeController,Ie),W&&Ie.push(W),this.latencyController=this.createController(n.latencyController,Ie),this.coreComponents=Ie,this.iframeController=v?new v(this,qm):void 0,Re.push(T);const $e=T.onErrorOut;typeof $e=="function"&&this.on(Ee.ERROR,$e,T),this.on(Ee.MANIFEST_LOADED,Z.onManifestLoaded,Z)}createController(e,r){if(e){const n=new e(this);return r&&r.push(n),n}return null}on(e,r,n=this){this._emitter.on(e,r,n)}once(e,r,n=this){this._emitter.once(e,r,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,r,n=this,i){this._emitter.off(e,r,n,i)}listeners(e){return this._emitter.listeners(e)}emit(e,r,n){return this._emitter.emit(e,r,n)}trigger(e,r){if(this.config.debug)return this.emit(e,e,r);try{return this.emit(e,e,r)}catch(n){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;const i=e===Ee.ERROR;this.trigger(Ee.ERROR,{type:Kn.OTHER_ERROR,details:Wt.INTERNAL_EXCEPTION,fatal:i,event:e,error:n}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(Ee.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(r=>r.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(r=>r.destroy()),this.coreComponents.length=0,this.iframeController=void 0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const a=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(Ee.ERROR,{type:Kn.OTHER_ERROR,details:Wt.ATTACH_MEDIA_ERROR,fatal:!0,error:a});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const r="media"in e,n=r?e.media:e,i=r?e:{media:n};this._media=n,this.trigger(Ee.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia");const e={};this.trigger(Ee.MEDIA_DETACHING,e),this._media=null,this.trigger(Ee.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;const r=((e=this.bufferController)==null?void 0:e.transferMedia())||null,n={transferMedia:r};return this.trigger(Ee.MEDIA_DETACHING,n),this.trigger(Ee.MEDIA_DETACHED,n),r}loadSource(e){var r;this.stopLoad();const n=this.media,i=this._url,a=this._url=SQ.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${a}`),n&&i&&(i!==a||(r=this.bufferController)!=null&&r.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(n)),this.trigger(Ee.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,r){this.logger.log(`startLoad(${e+(r?", ":"")})`),this.started=!0,this.resumeBuffering();for(let n=0;n{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[On.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[On.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[On.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,r=this.started,n=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),r&&(n?this.startLoad(n):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=zCe()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const r=this.capLevelController,n=!!e;r&&n!==this.config.capLevelToPlayerSize&&(n?r.startCapping():(r.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=n)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){xBt(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:r}}=this;if(!e)return 0;const n=e.length;for(let i=0;i=r)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:r,maxHdcpLevel:n}=this;let i;if(r===-1&&e!=null&&e.length?i=e.length-1:i=r,n)for(let a=i;a--;){const c=e[a].attrs["HDCP-LEVEL"];if(c&&c<=n)return a}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return((e=this.audioStreamController)==null?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var r;return((r=this.audioTrackController)==null?void 0:r.setAudioOption(e))||null}setSubtitleOption(e){var r;return((r=this.subtitleTrackController)==null?void 0:r.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const r=this.audioTrackController;r&&(r.audioTrack=e)}get nextAudioTrack(){var e,r;return(e=(r=this.audioStreamController)==null?void 0:r.nextAudioTrack)!=null?e:-1}set nextAudioTrack(e){const{audioTrackController:r}=this;r&&(r.nextAudioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const r=this.subtitleTrackController;r&&(r.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const r=this.subtitleTrackController;r&&(r.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,r;return(e=(r=this.latencyController)==null?void 0:r.liveSyncPosition)!=null?e:null}get latency(){var e;return((e=this.latencyController)==null?void 0:e.latency)||0}get maxLatency(){var e;return((e=this.latencyController)==null?void 0:e.maxLatency)||0}get targetLatency(){var e;return((e=this.latencyController)==null?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return((e=this.latencyController)==null?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){const e=this.levelController.iframeVariants;return e||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,r=this.allAudioTracks){const n=cPe(r);return aPe(e,n,navigator.mediaCapabilities)}}qm.defaultConfig=void 0;const JUt=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function qI(t){return!!t&&JUt.test(t)&&!/\.mp4($|\?)/i.test(t)}function eVt(t){const e=t.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return e?{libraryId:e[1],videoId:e[2]}:null}function tVt(t,e){if(!t)return null;const r=eVt(t);if(r){const n=new URLSearchParams({autoplay:e!=null&&e.autoplay?"true":"false",muted:e!=null&&e.muted?"true":"false",loop:e!=null&&e.loop?"true":"false",preload:"true",responsive:"true",playsinline:"true"});return`https://player.mediadelivery.net/embed/${r.libraryId}/${r.videoId}?${n.toString()}`}return/player\.mediadelivery\.net\/embed\//i.test(t)?t:/iframe\.mediadelivery\.net\/(?:play|embed)\//i.test(t)?t.replace("iframe.mediadelivery.net/play/","player.mediadelivery.net/embed/").replace("iframe.mediadelivery.net/embed/","player.mediadelivery.net/embed/"):t}function rVt(t){const e=t.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return e?e[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const sge=N.forwardRef(function({sourceUrl:e,thumbnailUrl:r,autoPlay:n,muted:i,loop:a,playsInline:c=!0,...d},p){const l=N.useRef(null),[g,v]=N.useState(null),E=N.useMemo(()=>tVt(e,{autoplay:!!n,muted:!!i,loop:!!a}),[e,n,i,a]);N.useEffect(()=>{let j=!1;if(!e){v(null);return}if(!qI(e)){v(e);return}if(!E){v(null);return}return v(null),fetch(E).then(async P=>{if(!P.ok)throw new Error(`Failed to load Bunny embed (${P.status})`);const C=await P.text();return rVt(C)}).then(P=>{j||v(P)}).catch(()=>{j||v(null)}),()=>{j=!0}},[E,e]),N.useEffect(()=>{const j=l.current;if(!j||!g)return;let P=null;const C=()=>{if(!n)return;const O=j.play();O&&O.catch(()=>{})};if(j.muted=!!i,j.loop=!!a,g.endsWith(".m3u8")){if(j.canPlayType("application/vnd.apple.mpegurl")){j.src=g;const O=()=>C();return j.addEventListener("loadedmetadata",O),()=>{j.removeEventListener("loadedmetadata",O),j.removeAttribute("src"),j.load()}}return qm.isSupported()?(P=new qm({enableWorker:!0,lowLatencyMode:!0}),P.loadSource(g),P.attachMedia(j),P.on(qm.Events.MANIFEST_PARSED,C),()=>{P==null||P.destroy(),j.removeAttribute("src"),j.load()}):void 0}j.src=g;const L=()=>C();return j.addEventListener("loadedmetadata",L),()=>{j.removeEventListener("loadedmetadata",L),j.removeAttribute("src"),j.load()}},[n,a,i,g]),N.useEffect(()=>{const j=l.current;if(j){if(j.muted=!!i,j.loop=!!a,n&&g){const P=j.play();P&&P.catch(()=>{});return}j.pause()}},[n,a,i,g]);const T=j=>{if(l.current=j,typeof p=="function"){p(j);return}p&&(p.current=j)};return s.jsx("video",{ref:T,poster:r||void 0,autoPlay:n,muted:i,loop:a,playsInline:c,preload:"metadata",...d})}),nVt={portrait:{sm:{w:130,h:231},md:{w:170,h:302},lg:{w:210,h:373}},landscape:{sm:{w:178,h:100},md:{w:220,h:124},lg:{w:270,h:152}}};function iVt(){try{let t=localStorage.getItem("vg_visitor_token");return t||(t=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",t)),t}catch{return null}}function age(t,e){return!t||t.length===0?!1:t.some(r=>r?r===e?!0:r.endsWith("*")?e.startsWith(r.slice(0,-1)):e.startsWith(r):!1)}function sVt({config:t,appSlug:e="video_greeter",preview:r=!1,embedded:n=!1}){const[i,a]=N.useState(!1),[c,d]=N.useState(!1),[p,l]=N.useState(!0),[g,v]=N.useState(!1),[E,T]=N.useState("portrait"),[j,P]=N.useState(!1),[C,L]=N.useState(!1),[O,F]=N.useState({name:"",email:"",phone:""}),[$,G]=N.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),W=N.useRef(null),Z=N.useRef(null),Q=N.useRef(!1),ee=async(tr,Qt)=>{if(!r)try{await Be.from("widget_events").insert({user_id:t.user_id,app_slug:e,event_type:tr,visitor_token:iVt(),page_url:typeof window<"u"?window.location.href:null,metadata:Qt||{}})}catch{}};N.useEffect(()=>{if(g)return;const tr=typeof window<"u"?window.location.pathname:"/",Qt=t.targeting||{mode:"all"};if(Qt.mode==="include"&&!age(Qt.include,tr)||Qt.mode==="exclude"&&age(Qt.exclude,tr))return;const zt=t.trigger||{type:"immediate"};if(zt.type==="immediate"||r){a(!0);return}if(zt.type==="delay"){const Vr=(zt.value||3)*1e3,Jr=setTimeout(()=>a(!0),Vr);return()=>clearTimeout(Jr)}if(zt.type==="scroll"){const Vr=(zt.value||25)/100,Jr=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=Vr&&(a(!0),window.removeEventListener("scroll",Jr))};return window.addEventListener("scroll",Jr,{passive:!0}),()=>window.removeEventListener("scroll",Jr)}if(zt.type==="exit_intent"){const Vr=Jr=>{Jr.clientY<=0&&a(!0)};return document.addEventListener("mouseleave",Vr),()=>document.removeEventListener("mouseleave",Vr)}},[g,t.targeting,t.trigger,r]),N.useEffect(()=>{i&&!Q.current&&(Q.current=!0,ee("impression"))},[i]),N.useEffect(()=>{if(c&&Z.current&&!qI(t.video_url)){Z.current.currentTime=0,Z.current.muted=!1,l(!1);const tr=Z.current.play();tr&&tr.catch(()=>{})}else c&&qI(t.video_url)&&l(!1)},[c,t.video_url]),N.useEffect(()=>{if(!t.thumbnail_url)return;let tr=!1;const Qt=new Image;return Qt.onload=()=>{tr||T(Qt.naturalWidth>Qt.naturalHeight?"landscape":"portrait")},Qt.src=t.thumbnail_url,()=>{tr=!0}},[t.thumbnail_url]),N.useEffect(()=>{const tr=()=>{G({width:window.innerWidth,height:window.innerHeight})};return tr(),window.addEventListener("resize",tr),()=>window.removeEventListener("resize",tr)},[]);const ie=()=>{d(!0),ee("expand")},oe=tr=>{tr.stopPropagation(),v(!0),d(!1)},pe=tr=>{ee("cta_click",{cta_id:tr.id,label:tr.label,url:tr.url})},Le=async tr=>{if(tr.preventDefault(),r){P(!0);return}if(!(!O.email||!O.name)){L(!0);try{const{error:Qt}=await Be.functions.invoke("submit-widget-lead",{body:{user_id:t.user_id,app_slug:e,name:O.name,email:O.email,phone:O.phone||void 0,page_url:window.location.href}});if(Qt)throw Qt;ee("lead_capture",{email:O.email}),P(!0)}catch(Qt){console.error("lead submit failed",Qt)}finally{L(!1)}}};if(!i||g||!t.video_url&&!t.video_embed_url)return null;const be=nVt[E][t.size||"md"],Re=n?"absolute left-2 bottom-2":r?t.position==="bottom-right"?"absolute right-4 bottom-4":"absolute left-4 bottom-4":t.position==="bottom-right"?"fixed right-4 bottom-4 md:right-6 md:bottom-6":"fixed left-4 bottom-4 md:left-6 md:bottom-6",Ie=t.shape==="circle"?"rounded-full":"rounded-2xl",Te=r?E==="landscape"?"w-[280px]":"w-[220px]":E==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",ge=E==="landscape"?"aspect-video":"aspect-[9/16]",$e=t.agent||{},we=t.lead_form_fields||["name","email","phone"],ke=!!(t.show_socials&&($e.instagram_url||$e.facebook_url||$e.linkedin_url)),Ae=108+(t.ctas||[]).length*48+(t.lead_form_enabled&&!j?72+we.length*42:0)+(j?40:0)+(ke?34:0),He=Math.max(300,$.height-32),ot=Math.max(220,$.width-32),nt=Math.max(150,He-Ae),tt=Math.floor(E==="landscape"?nt*(16/9):nt*(9/16)),vt=E==="landscape"?Math.max(220,Math.min(420,ot,tt)):Math.max(180,Math.min(340,ot,tt)),Vt=n?"bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col":`${Te} max-h-[calc(100dvh-2rem)] bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col`,Ct=n?{width:`${vt}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Bt=n?"p-3 space-y-2.5":"p-4 space-y-3",cr=n?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",ft=n?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",Kt=n?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",ir=n?"w-full px-3 py-1.5 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400":"w-full px-3 py-2 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400",Gr=n?"w-full flex items-center justify-center gap-2 px-3 py-2 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60":"w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60";return s.jsx("div",{"data-vg-widget":!0,"data-expanded":c?"true":"false",className:`${Re} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:c?s.jsxs("div",{className:Vt,style:Ct,children:[s.jsxs("div",{className:`relative bg-black ${ge}`,children:[qI(t.video_url)?s.jsx(sge,{ref:Z,sourceUrl:t.video_url,thumbnailUrl:t.thumbnail_url,autoPlay:!0,muted:p,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:tr=>{const{videoWidth:Qt,videoHeight:zt}=tr.currentTarget;Qt&&zt&&T(Qt>zt?"landscape":"portrait")},onEnded:()=>ee("watch_complete")},`expanded-${t.video_url}-${t.thumbnail_url||"no-thumb"}-${c?"on":"off"}`):s.jsx("video",{ref:Z,src:t.video_url||void 0,poster:t.thumbnail_url||void 0,autoPlay:!0,playsInline:!0,controls:!1,className:"w-full h-full object-cover",onEnded:()=>ee("watch_complete"),onLoadedMetadata:tr=>{const{videoWidth:Qt,videoHeight:zt}=tr.currentTarget;Qt&&zt&&T(Qt>zt?"landscape":"portrait")}}),s.jsx("button",{onClick:()=>{Z.current&&(Z.current.muted=!Z.current.muted,l(Z.current.muted))},className:"absolute bottom-3 right-3 w-9 h-9 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur",children:p?s.jsx(A5e,{className:"w-4 h-4"}):s.jsx(T5e,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>d(!1),className:"absolute top-3 right-3 w-8 h-8 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur","aria-label":"Minimize",children:s.jsx(Ra,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:Bt,children:[s.jsxs("div",{className:"flex items-center gap-3",children:[$e.avatar_url&&s.jsx("img",{src:$e.avatar_url,alt:$e.name||"",className:cr}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:ft,children:t.greeting_title||"Glad you're here!"}),t.greeting_subtitle&&s.jsx("p",{className:Kt,children:t.greeting_subtitle})]})]}),(t.ctas||[]).length>0&&s.jsx("div",{className:"space-y-2",children:(t.ctas||[]).map(tr=>{var Qt;return s.jsxs("a",{href:tr.url,target:(Qt=tr.url)!=null&&Qt.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>pe(tr),className:`flex items-center justify-between gap-2 ${n?"px-3 py-2":"px-3.5 py-2.5"} rounded-xl text-sm font-semibold transition-colors ${tr.style==="secondary"?"bg-gray-100 text-gray-900 hover:bg-gray-200":"bg-gray-900 text-white hover:bg-gray-800"}`,children:[s.jsx("span",{children:tr.label}),s.jsx(rA,{className:"w-3.5 h-3.5 opacity-60"})]},tr.id)})}),t.lead_form_enabled&&!j&&s.jsxs("form",{onSubmit:Le,className:"space-y-2 pt-1",children:[we.includes("name")&&s.jsx("input",{type:"text",placeholder:"Name",required:!0,value:O.name,onChange:tr=>F({...O,name:tr.target.value}),className:ir}),we.includes("email")&&s.jsx("input",{type:"email",placeholder:"Email",required:!0,value:O.email,onChange:tr=>F({...O,email:tr.target.value}),className:ir}),we.includes("phone")&&s.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:O.phone,onChange:tr=>F({...O,phone:tr.target.value}),className:ir}),s.jsxs("button",{type:"submit",disabled:C,className:Gr,children:[s.jsx(nF,{className:"w-3.5 h-3.5"}),C?"Sending...":"Send"]})]}),j&&s.jsx("p",{className:"text-sm text-emerald-600 font-medium text-center py-2",children:"Thanks! I'll be in touch shortly."}),t.show_socials&&($e.instagram_url||$e.facebook_url||$e.linkedin_url)&&s.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[$e.instagram_url&&s.jsx("a",{href:$e.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>ee("cta_click",{social:"instagram"}),children:s.jsx(ave,{className:"w-4 h-4"})}),$e.facebook_url&&s.jsx("a",{href:$e.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>ee("cta_click",{social:"facebook"}),children:s.jsx(ive,{className:"w-4 h-4"})}),$e.linkedin_url&&s.jsx("a",{href:$e.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>ee("cta_click",{social:"linkedin"}),children:s.jsx(uve,{className:"w-4 h-4"})})]})]})]}):s.jsxs("div",{className:"relative animate-in fade-in slide-in-from-bottom-4 duration-500",children:[s.jsxs("button",{onClick:ie,className:`relative ${Ie} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:be.w,height:be.h},"aria-label":"Play video greeting",children:[qI(t.video_url)?s.jsx(sge,{ref:W,sourceUrl:t.video_url,thumbnailUrl:t.thumbnail_url,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-cover pointer-events-none",onLoadedMetadata:tr=>{const{videoWidth:Qt,videoHeight:zt}=tr.currentTarget;Qt&&zt&&T(Qt>zt?"landscape":"portrait")}},`collapsed-${t.video_url}-${t.thumbnail_url||"no-thumb"}`):s.jsx("video",{ref:W,src:t.video_url||void 0,poster:t.thumbnail_url||void 0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover",onLoadedMetadata:tr=>{const{videoWidth:Qt,videoHeight:zt}=tr.currentTarget;Qt&&zt&&T(Qt>zt?"landscape":"portrait")}}),s.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none"}),s.jsx("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 w-12 h-12 rounded-full bg-white/95 flex items-center justify-center shadow-lg pointer-events-none",children:s.jsx("svg",{viewBox:"0 0 24 24",className:"w-6 h-6 text-black ml-0.5",fill:"currentColor",children:s.jsx("path",{d:"M8 5v14l11-7z"})})}),s.jsx("span",{className:"absolute top-2 right-2 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider bg-red-500 text-white rounded-full animate-pulse",children:"Live"})]}),s.jsx("button",{onClick:oe,className:"absolute -top-2 -right-2 w-7 h-7 rounded-full bg-black/80 text-white shadow-lg hover:bg-black flex items-center justify-center","aria-label":"Close",children:s.jsx(Ra,{className:"w-3.5 h-3.5"})})]})})}function JQ({slug:t}){const[e,r]=N.useState(null);return N.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:a}=await Be.rpc("get_public_video_greeter_config",{_slug:t});!n&&!a&&i&&r(i)})(),()=>{n=!0}},[t]),e?s.jsx(sVt,{config:e}):null}const DNe="eip_last_shown",oge="eip_visitor_token";function aVt(){try{let t=localStorage.getItem(oge);return t||(t=crypto.randomUUID(),localStorage.setItem(oge,t)),t}catch{return}}function oVt(t){try{const e=Number(localStorage.getItem(DNe)||0);return e?Date.now()-e>t*24*60*60*1e3:!0}catch{return!0}}function lVt(t){if(!t||t.mode==="all")return!0;const e=window.location.pathname,n=(t.mode==="include"?t.include||[]:t.exclude||[]).some(i=>e.startsWith(i));return t.mode==="include"?n:!n}function cVt({config:t,preview:e=!1,forceOpen:r=!1}){const[n,i]=N.useState(r),[a,c]=N.useState(!1),[d,p]=N.useState(!1),[l,g]=N.useState({name:"",email:"",phone:""}),v=N.useRef(!1),E=N.useRef(!1),T=async(W,Z={})=>{if(!e)try{await Be.from("widget_events").insert({user_id:t.user_id,app_slug:"exit_intent",event_type:W,visitor_token:aVt(),page_url:window.location.href,metadata:Z})}catch{}};N.useEffect(()=>{if(e||!lVt(t.targeting)||!oVt(t.frequency_days))return;const W=/Mobi|Android/i.test(navigator.userAgent),Z={low:5,medium:15,high:30}[t.trigger_sensitivity]||15,Q=pe=>{if(!v.current){v.current=!0,i(!0);try{localStorage.setItem(DNe,String(Date.now()))}catch{}T("impression",{reason:pe})}},ee=pe=>{pe.clientY<=Z&&Q("mouse_leave")},ie=()=>{t.enable_mobile_back&&W&&Q("back_button")};if(t.enable_mobile_back&&W){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",ie)}else document.addEventListener("mouseleave",ee);let oe;return t.enable_time_fallback&&(oe=window.setTimeout(()=>Q("time_fallback"),Math.max(5,t.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",ee),window.removeEventListener("popstate",ie),oe&&window.clearTimeout(oe)}},[t,e]),N.useEffect(()=>{n&&!E.current&&!e&&!v.current&&(E.current=!0)},[n,e]);const j=()=>{i(!1),e||T("close")},P=async W=>{if(W.preventDefault(),e){c(!0);return}if(!(!l.email||!l.name)){p(!0);try{const{error:Z}=await Be.functions.invoke("submit-widget-lead",{body:{user_id:t.user_id,app_slug:"exit_intent",name:l.name,email:l.email,phone:l.phone||void 0,page_url:window.location.href}});if(Z)throw Z;T("lead_capture",{email:l.email}),c(!0),t.cta_url&&setTimeout(()=>{window.location.href=t.cta_url},1200)}catch(Z){console.error("exit intent submit failed",Z)}finally{p(!1)}}};if(!n)return null;const C=t.form_fields||["name","email"],L=t.agent||{},O=[L.first_name,L.last_name].filter(Boolean).join(" "),F=t.use_agent_photo&&L.avatar_url||t.image_url,$=t.theme_color||"#f97316",G=e?"absolute inset-0 flex items-center justify-center p-4 z-10":"fixed inset-0 z-[80] flex items-center justify-center p-4";return s.jsx("div",{className:G,style:{background:e?"transparent":"rgba(0,0,0,0.6)"},children:s.jsxs("div",{className:"relative w-full max-w-md bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:W=>W.stopPropagation(),children:[s.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${$}, ${w8($,-25)})`}}),s.jsx("button",{onClick:j,className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full bg-background/80 backdrop-blur hover:bg-background flex items-center justify-center text-muted-foreground hover:text-foreground transition","aria-label":"Close",children:s.jsx(Ra,{className:"w-4 h-4"})}),s.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[F&&s.jsx("img",{src:F,alt:O||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${$}33`,"--tw-ring-color":$}}),s.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${$}1A`,color:$},children:[s.jsx(va,{className:"w-3 h-3"}),t.offer_label]})]}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:t.headline}),s.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:t.subheadline})]}),a?s.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${$}10`,color:$},children:[s.jsx("div",{className:"text-3xl",children:"🎉"}),s.jsx("p",{className:"text-sm font-medium",style:{color:$},children:t.success_message})]}):t.form_enabled?s.jsxs("form",{onSubmit:P,className:"space-y-2.5",children:[C.includes("name")&&s.jsx("input",{type:"text",placeholder:"Your name",value:l.name,onChange:W=>g({...l,name:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":$},required:!0}),C.includes("email")&&s.jsx("input",{type:"email",placeholder:"you@email.com",value:l.email,onChange:W=>g({...l,email:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":$},required:!0}),C.includes("phone")&&s.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:l.phone,onChange:W=>g({...l,phone:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":$}}),s.jsx("button",{type:"submit",disabled:d,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60",style:{background:`linear-gradient(135deg, ${$}, ${w8($,-20)})`},children:d?"Sending...":t.cta_label}),s.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We respect your inbox. Unsubscribe anytime."})]}):s.jsx("a",{href:t.cta_url||"#",onClick:()=>T("cta_click",{url:t.cta_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 transition",style:{background:`linear-gradient(135deg, ${$}, ${w8($,-20)})`},children:t.cta_label}),O&&s.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",O]})]})]})})}function w8(t,e){try{const r=parseInt(t.slice(1),16),n=e<0?0:255,i=Math.abs(e)/100,a=r>>16,c=r>>8&255,d=r&255,p=Math.round((n-a)*i)+a,l=Math.round((n-c)*i)+c,g=Math.round((n-d)*i)+d;return"#"+(16777216+(p<<16)+(l<<8)+g).toString(16).slice(1)}catch{return t}}function eJ({slug:t}){const[e,r]=N.useState(null);return N.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:a}=await Be.rpc("get_public_exit_intent_config",{_slug:t});!n&&!a&&i&&r(i)})(),()=>{n=!0}},[t]),e?s.jsx(cVt,{config:e}):null}const lge="lm_dismissed",cge="lm_visitor_token";function uVt(){try{let t=localStorage.getItem(cge);return t||(t=crypto.randomUUID(),localStorage.setItem(cge,t)),t}catch{return}}function dVt(t){if(!t||t.mode==="all")return!0;const e=window.location.pathname,n=(t.mode==="include"?t.include||[]:t.exclude||[]).some(i=>e.startsWith(i));return t.mode==="include"?n:!n}function hVt({config:t,preview:e=!1}){const[r,n]=N.useState(!1),[i,a]=N.useState(!1),[c,d]=N.useState(!1),[p,l]=N.useState(!1),[g,v]=N.useState({name:"",email:"",phone:""}),E=N.useRef(!1),T=async(F,$={})=>{if(!e)try{await Be.from("widget_events").insert({user_id:t.user_id,app_slug:"lead_magnet",event_type:F,visitor_token:uVt(),page_url:window.location.href,metadata:$})}catch{}};N.useEffect(()=>{if(e){n(!0);return}if(!dVt(t.targeting))return;try{if(sessionStorage.getItem(lge))return}catch{}const F=()=>{E.current||(E.current=!0,n(!0),T("impression"))};if(t.trigger_type==="immediate")F();else if(t.trigger_type==="delay"){const $=window.setTimeout(F,Math.max(0,t.trigger_value)*1e3);return()=>window.clearTimeout($)}else if(t.trigger_type==="scroll"){const $=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(t.trigger_value||30)&&F()};return window.addEventListener("scroll",$,{passive:!0}),()=>window.removeEventListener("scroll",$)}},[t,e]);const j=()=>{n(!1);try{sessionStorage.setItem(lge,"1")}catch{}e||T("close")},P=async F=>{if(F.preventDefault(),e){d(!0);return}if(!(!g.email||!g.name)){l(!0);try{const{error:$}=await Be.functions.invoke("submit-widget-lead",{body:{user_id:t.user_id,app_slug:"lead_magnet",name:g.name,email:g.email,phone:g.phone||void 0,page_url:window.location.href}});if($)throw $;T("lead_capture",{email:g.email}),d(!0),(t.delivery_method==="instant"||t.delivery_method==="both")&&t.download_url&&setTimeout(()=>{const G=document.createElement("a");G.href=t.download_url,G.target="_blank",G.rel="noopener",G.download="",document.body.appendChild(G),G.click(),G.remove()},600)}catch($){console.error("lead magnet submit failed",$)}finally{l(!1)}}};if(!r)return null;const C=t.theme_color||"#2563eb",L=e?t.position==="bottom-left"?"absolute left-4 bottom-4":"absolute right-4 bottom-4":t.position==="bottom-left"?"fixed left-4 bottom-4 md:left-6 md:bottom-6":"fixed right-4 bottom-4 md:right-6 md:bottom-6";if(t.display_style==="bar")return s.jsxs("div",{className:e?"absolute left-0 right-0 bottom-0 z-10":"fixed left-0 right-0 bottom-0 z-[75]",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[s.jsx("div",{className:"text-white shadow-2xl",style:{background:`linear-gradient(90deg, ${C}, ${kI(C,-20)})`},children:s.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-3 flex items-center gap-3 flex-wrap",children:[s.jsx(Jm,{className:"w-5 h-5 shrink-0"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm font-semibold truncate",children:t.title}),s.jsx("p",{className:"text-xs text-white/80 truncate",children:t.description})]}),s.jsx("button",{onClick:()=>{a(!0),T("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:C},children:t.download_label}),s.jsx("button",{onClick:j,className:"text-white/80 hover:text-white","aria-label":"Close",children:s.jsx(Ra,{className:"w-4 h-4"})})]})}),i&&O()]});if(!i)return s.jsxs(s.Fragment,{children:[s.jsxs("button",{onClick:()=>{a(!0),T("expand")},className:`${L} z-[75] group flex items-center gap-3 pl-3 pr-4 py-3 rounded-2xl shadow-2xl hover:shadow-3xl transition-all hover:scale-[1.03] animate-in fade-in slide-in-from-bottom-4 duration-500`,style:{background:`linear-gradient(135deg, ${C}, ${kI(C,-20)})`,paddingBottom:"env(safe-area-inset-bottom)"},children:[s.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center text-white",children:s.jsx(eT,{className:"w-5 h-5"})}),s.jsxs("div",{className:"text-left text-white",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider opacity-90 font-semibold",children:t.badge_label}),s.jsx("div",{className:"text-sm font-bold leading-tight max-w-[180px] truncate",children:t.title})]}),s.jsx("button",{onClick:F=>{F.stopPropagation(),j()},className:"ml-1 w-6 h-6 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white","aria-label":"Close",children:s.jsx(Ra,{className:"w-3 h-3"})})]}),i&&O()]});return O();function O(){const F=t.form_fields||["name","email"],$=t.agent||{},G=[$.first_name,$.last_name].filter(Boolean).join(" ");return s.jsx("div",{className:e?"absolute inset-0 flex items-center justify-center p-4 z-20":"fixed inset-0 z-[85] flex items-center justify-center p-4",style:{background:e?"transparent":"rgba(0,0,0,0.6)"},onClick:()=>a(!1),children:s.jsxs("div",{className:"relative w-full max-w-lg bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:W=>W.stopPropagation(),children:[s.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${C}, ${kI(C,-25)})`},children:[t.cover_image_url?s.jsx("img",{src:t.cover_image_url,alt:t.title,className:"w-full h-full object-cover opacity-90"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(lg,{className:"w-20 h-20 text-white/40"})}),s.jsxs("div",{className:"absolute top-3 left-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-white shadow",style:{color:C},children:[s.jsx(Jm,{className:"w-3 h-3"}),t.badge_label]}),s.jsx("button",{onClick:()=>a(!1),className:"absolute top-3 right-3 w-8 h-8 rounded-full bg-white/95 hover:bg-white flex items-center justify-center text-foreground/70 hover:text-foreground transition","aria-label":"Close",children:s.jsx(Ra,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:t.title}),s.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:t.description})]}),c?s.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${C}10`},children:[s.jsx($u,{className:"w-8 h-8 mx-auto",style:{color:C}}),s.jsx("p",{className:"text-sm font-medium",style:{color:C},children:t.success_message}),t.download_url&&s.jsx("a",{href:t.download_url,target:"_blank",rel:"noopener",className:"inline-block mt-2 text-xs underline",style:{color:C},children:"Click here if download didn't start"})]}):t.form_enabled?s.jsxs("form",{onSubmit:P,className:"space-y-2.5",children:[F.includes("name")&&s.jsx("input",{type:"text",placeholder:"Your name",value:g.name,onChange:W=>v({...g,name:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":C},required:!0}),F.includes("email")&&s.jsx("input",{type:"email",placeholder:"you@email.com",value:g.email,onChange:W=>v({...g,email:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":C},required:!0}),F.includes("phone")&&s.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:g.phone,onChange:W=>v({...g,phone:W.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":C}}),s.jsxs("button",{type:"submit",disabled:p,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60 inline-flex items-center justify-center gap-2",style:{background:`linear-gradient(135deg, ${C}, ${kI(C,-20)})`},children:[s.jsx($u,{className:"w-4 h-4"}),p?"Sending...":t.download_label]}),s.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We'll email you a copy too. No spam — promise."})]}):s.jsx("a",{href:t.download_url||"#",target:"_blank",rel:"noopener",onClick:()=>T("cta_click",{url:t.download_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg",style:{background:`linear-gradient(135deg, ${C}, ${kI(C,-20)})`},children:t.download_label}),G&&s.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",G]})]})]})})}}function kI(t,e){try{const r=parseInt(t.slice(1),16),n=e<0?0:255,i=Math.abs(e)/100,a=r>>16,c=r>>8&255,d=r&255,p=Math.round((n-a)*i)+a,l=Math.round((n-c)*i)+c,g=Math.round((n-d)*i)+d;return"#"+(16777216+(p<<16)+(l<<8)+g).toString(16).slice(1)}catch{return t}}function tJ({slug:t}){const[e,r]=N.useState(null);return N.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:a}=await Be.rpc("get_public_lead_magnet_config",{_slug:t});!n&&!a&&i&&r(i)})(),()=>{n=!0}},[t]),e?s.jsx(hVt,{config:e}):null}function rJ({siteConfig:t,className:e="",iconClassName:r=""}){var a;const n=((a=t==null?void 0:t.themeConfig)==null?void 0:a.socialLinks)||null;if(!n)return null;const i=[{key:"facebook",url:n.facebook,Icon:ive,label:"Facebook"},{key:"instagram",url:n.instagram,Icon:ave,label:"Instagram"},{key:"linkedin",url:n.linkedin,Icon:uve,label:"LinkedIn"},{key:"youtube",url:n.youtube,Icon:I5e,label:"YouTube"}].filter(c=>!!c.url);return i.length?s.jsx("div",{className:`flex items-center gap-3 ${e}`,children:i.map(({key:c,url:d,Icon:p,label:l})=>s.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer","aria-label":l,className:`inline-flex items-center justify-center h-9 w-9 rounded-full border border-current/20 opacity-70 hover:opacity-100 transition-opacity ${r}`,children:s.jsx(p,{className:"h-4 w-4"})},c))}):null}const fVt="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109";function mVt({children:t,siteConfig:e}){var Or,si,ss,ps,Mi,gs,ma,Ki;const r=ms(),n=qa(),[i,a]=N.useState(!1),[c,d]=N.useState(!1);N.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&d(!0)},[]);const[p,l]=N.useState(!1),[g,v]=N.useState([]),[E,T]=N.useState([]),[j,P]=N.useState([]),[C,L]=N.useState(null),O=N.useRef(null),F=N.useRef(null),{user:$,profile:G,signOut:W}=VA();bQ(e,$==null?void 0:$.id),wQ(e,$==null?void 0:$.id);const Z=((Or=e.agent)==null?void 0:Or.full_name)||"Agent",Q=e.siteTitle||`${Z} Real Estate`,ee=r.pathname==="/search",ie=r.pathname==="/",oe=e.leadRegistrationMode!=="disabled",pe=e.id===fVt;N.useEffect(()=>{(async()=>{const{data:ci}=await Be.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",e.id).eq("is_published",!0).order("sort_order",{ascending:!0});v(ci||[])})()},[e.id]),N.useEffect(()=>{(async()=>{const{data:ci}=await Be.from("lead_site_menu_items").select("*").eq("site_id",e.id).order("sort_order",{ascending:!0});P(ci||[]),T((ci||[]).filter(mo=>mo.is_visible!==!1))})()},[e.id]),N.useEffect(()=>{const Hr=ci=>{O.current&&!O.current.contains(ci.target)&&l(!1),F.current&&!F.current.contains(ci.target)&&L(null)};return document.addEventListener("mousedown",Hr),()=>document.removeEventListener("mousedown",Hr)},[]);const Le=Cv(e),be=e==null?void 0:e.bookingUrl,{data:Re}=FB(Le?e.agentId:null),Ie=((Re==null?void 0:Re.length)??0)>0,{data:Te}=fQ(e.agentId),ge=((Te==null?void 0:Te.length)??0)>0,$e=E.filter(Hr=>{const ci=String(Hr.target_url||"").toLowerCase().replace(/\/+$/,""),mo=String(Hr.label||"").toLowerCase();return!(Le&&(ci==="/search"||ci.startsWith("/search?")||mo.includes("search"))||ci==="/listings"&&Le&&!Ie||ci==="/sold"&&!ge)}),we=Le&&Ie&&$e.length>0&&!$e.some(Hr=>String(Hr.target_url||"").toLowerCase().startsWith("/listings"))?[...$e,{id:"__my-listings",label:"My Listings",target_url:"/listings",parent_id:null,is_visible:!0}]:$e,ke=we.length>0,Ae=[{to:"/",label:"Home"},...Le?[]:[{to:"/search",label:"Search"}],...Le&&Ie?[{to:"/listings",label:"My Listings"}]:[],...ge?[{to:"/sold",label:"Sold"}]:[],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],He=we.filter(Hr=>!Hr.parent_id),ot=Hr=>we.filter(ci=>ci.parent_id===Hr),nt=j.filter(Hr=>!Hr.parent_id),tt=new Set([...nt,...He].filter(Hr=>String(Hr.target_url||"").trim()!=="").map(Hr=>String(Hr.target_url).toLowerCase().replace(/\/+$/,"")||"/")),vt=new Set([...nt,...He].map(Hr=>String(Hr.label||"").trim().toLowerCase())),Ct=["/","/search","/about","/contact","/sell","/blog"].some(Hr=>tt.has(Hr)),Bt=Ct?[]:Ae.filter(Hr=>!tt.has(Hr.to.toLowerCase())&&!vt.has(Hr.label.toLowerCase())),cr=Ct?He.filter(Hr=>Hr.is_visible!==!1&&String(Hr.target_url||"").trim()!=="").map(Hr=>({to:String(Hr.target_url),label:String(Hr.label||"").trim()||"Link"})):Bt,ft=nt.find(Hr=>Hr.item_type==="cities"),Kt=String((ft==null?void 0:ft.label)||"Cities").trim()||"Cities",ir=g.length>0&&!pe,Gr=ir&&!ft,tr=Hr=>`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${Hr?ie?"bg-white/15 text-white":"bg-gray-100 text-gray-900":ie?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,Qt=r.pathname.startsWith("/homes-for-sale-in-"),zt=Hr=>s.jsxs("div",{ref:O,className:"relative",children:[s.jsxs("button",{onClick:()=>l(!p),className:`flex items-center gap-1 ${tr(Qt)}`,children:[Hr," ",s.jsx(ad,{className:`h-3.5 w-3.5 transition-transform ${p?"rotate-180":""}`})]}),p&&s.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:g.map(ci=>s.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${ci.city_slug}`),l(!1)},className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors",children:ci.city_name},ci.city_slug))})]},"__cities"),Vr=Hr=>s.jsxs("div",{children:[s.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${ie?"text-white/40":"text-gray-400"}`,children:Hr}),g.map(ci=>s.jsx(Nn,{to:`/homes-for-sale-in-${ci.city_slug}`,onClick:()=>a(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===`/homes-for-sale-in-${ci.city_slug}`?ie?"bg-white/15 text-white":"bg-gray-100 text-gray-900":ie?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:ci.city_name},ci.city_slug))]},"__cities-mobile"),Jr=ie?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",Fn=e.seoMetaTitle||e.siteTitle||`${Z} - Real Estate`,Ar=e.seoMetaDescription||e.siteTagline||`Browse homes and listings with ${Z}`,Tn=e.ogImageUrl||((si=e.agent)==null?void 0:si.avatar_url)||"",mn=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`,li=xQ(e.siteTitle,Z),Lr=(e.googleSearchConsoleVerification||"").trim().replace(/^google-site-verification[=:]\s*/i,"").replace(/^content=/i,"").replace(/^["']|["']$/g,"");return s.jsxs("div",{className:`flex flex-col ${ee?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[s.jsx(_Q,{siteConfig:e,pagePath:r.pathname}),(!pe||r.pathname==="/p/frequently-asked-questions")&&s.jsx(vQ,{siteConfig:e}),s.jsxs(mc,{children:[s.jsx("title",{children:Fn}),s.jsx("meta",{name:"description",content:Ar}),Lr&&s.jsx("meta",{name:"google-site-verification",content:Lr}),s.jsx("meta",{property:"og:site_name",content:li}),s.jsx("meta",{property:"og:title",content:Fn}),s.jsx("meta",{property:"og:description",content:Ar}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:url",content:mn+r.pathname}),Tn&&s.jsx("meta",{property:"og:image",content:Tn}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),s.jsx("meta",{name:"twitter:title",content:Fn}),s.jsx("meta",{name:"twitter:description",content:Ar}),Tn&&s.jsx("meta",{name:"twitter:image",content:Tn}),e.faviconUrl&&s.jsx("link",{rel:"icon",href:e.faviconUrl,type:"image/png"}),s.jsx("link",{rel:"canonical",href:`${mn}${r.pathname}`}),e.subdomainSlug==="matthogg"&&s.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),s.jsxs("header",{className:`${ie?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${Jr}`,children:[s.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:s.jsxs("div",{className:"flex items-center justify-between h-20",children:[s.jsxs(Nn,{to:"/",className:"flex items-center gap-3",children:[e.showTeamLogo&&e.teamLogoUrl?s.jsx("img",{src:e.teamLogoUrl,alt:`${Q} logo`,className:`${F3t(e.headerLogoSize)} w-auto object-contain`}):(ss=e.agent)!=null&&ss.avatar_url?s.jsx("img",{src:e.agent.avatar_url,alt:Z,className:"h-10 w-10 rounded-full object-cover ring-2 ring-white/20"}):null,s.jsx("div",{children:s.jsx("span",{className:"font-bold text-lg leading-none tracking-tight",children:Q})})]}),s.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[e.bookingUrl&&!pe&&s.jsx(Fy,{bookingUrl:e.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),Bt.map(Hr=>s.jsx(Nn,{to:Hr.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname===Hr.to?ie?"bg-white/15 text-white":"bg-gray-100 text-gray-900":ie?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:Hr.label},Hr.to)),ke&&He.map(Hr=>{if(Hr.item_type==="cities")return ir?zt(String(Hr.label||"Cities")):null;if(Hr.item_type==="dropdown"){const ci=ot(Hr.id);return s.jsxs("div",{ref:F,className:"relative",children:[s.jsxs("button",{onClick:()=>L(C===Hr.id?null:Hr.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${ie?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[Hr.label," ",s.jsx(ad,{className:`h-3.5 w-3.5 transition-transform ${C===Hr.id?"rotate-180":""}`})]}),C===Hr.id&&ci.length>0&&s.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:ci.map(mo=>s.jsx(EM,{item:mo,onClick:()=>L(null),className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors block"},mo.id))})]},Hr.id)}return s.jsx(EM,{item:Hr,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${ie?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},Hr.id)}),Gr&&zt(Kt),!pe&&($?s.jsx("div",{className:"ml-2",children:s.jsx(gQ,{savedClassName:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${ie?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,triggerClassName:`flex items-center gap-1.5 rounded-full py-1 pl-1 pr-2.5 text-sm font-medium outline-none transition-colors ${ie?"bg-white/10 text-white hover:bg-white/20":"bg-gray-100 text-gray-800 hover:bg-gray-200"}`})}):oe?s.jsx("button",{onClick:()=>d(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${ie?"bg-white/15 text-white hover:bg-white/25":"bg-blue-600 text-white hover:bg-blue-700"}`,children:"Sign In"}):null)]}),s.jsx("button",{onClick:()=>a(!i),"aria-label":i?"Close menu":"Open menu","aria-expanded":i,className:`md:hidden p-2 rounded-lg ${ie?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:i?s.jsx(Ra,{className:"h-5 w-5"}):s.jsx(nA,{className:"h-5 w-5"})})]})}),i&&s.jsx("div",{className:`md:hidden border-t ${ie?"border-white/10 bg-black/95 backdrop-blur":"border-gray-100 bg-white"} max-h-[calc(100vh-5rem)] overflow-y-auto overscroll-contain`,children:s.jsxs("div",{className:"px-4 py-3 space-y-1 pb-8",children:[e.bookingUrl&&!pe&&s.jsx(Fy,{bookingUrl:e.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),Bt.map(Hr=>s.jsx(Nn,{to:Hr.to,onClick:()=>a(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===Hr.to?ie?"bg-white/15 text-white":"bg-gray-100 text-gray-900":ie?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Hr.label},Hr.to)),ke&&He.map(Hr=>{if(Hr.item_type==="cities")return ir?Vr(String(Hr.label||"Cities")):null;if(Hr.item_type==="dropdown"){const ci=ot(Hr.id);return s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${ie?"text-white/40":"text-gray-400"}`,children:Hr.label}),ci.map(mo=>s.jsx(EM,{item:mo,onClick:()=>a(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${ie?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},mo.id))]},Hr.id)}return s.jsx(EM,{item:Hr,onClick:()=>a(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${ie?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},Hr.id)}),Gr&&Vr(Kt),!pe&&($?s.jsx(yQ,{dark:ie,onNavigate:()=>a(!1)}):oe?s.jsx("button",{onClick:()=>{d(!0),a(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${ie?"text-white/70 hover:bg-white/10":"text-blue-600 hover:bg-blue-50"}`,children:"Sign In / Register"}):null)]})})]}),s.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:t}),!ee&&s.jsx("footer",{className:"bg-gray-950 text-gray-400",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-16",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[((ps=e.agent)==null?void 0:ps.avatar_url)&&s.jsx("img",{src:e.agent.avatar_url,alt:Z,className:"h-16 w-16 rounded-2xl object-cover ring-2 ring-white/10"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-bold text-white text-lg tracking-tight",children:Z}),s.jsx("p",{className:"text-sm text-gray-400",children:pe?"Personal Real Estate Advisor":((Mi=e.agent)==null?void 0:Mi.title)||"Real Estate Professional"})]})]}),((gs=e.agent)==null?void 0:gs.phone)&&s.jsx("p",{className:"text-sm mt-3",children:s.jsxs("a",{href:`tel:${e.agent.phone}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[s.jsx(Ui,{className:"h-3.5 w-3.5"})," ",e.agent.phone]})}),((ma=e.agent)==null?void 0:ma.email)&&s.jsx("p",{className:"text-sm mt-1",children:s.jsxs("a",{href:`mailto:${e.agent.email}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[s.jsx(rs,{className:"h-3.5 w-3.5"})," ",e.agent.email]})}),s.jsx(rJ,{siteConfig:e,className:"mt-4"}),pe&&s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-sm mt-4",children:"Helping you find the right real estate agent, wherever you need one."}),s.jsx("p",{className:"text-sm mt-2",children:"Columbia, Missouri"})]})]}),s.jsxs("div",{children:[s.jsx("h2",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),s.jsxs("ul",{className:"space-y-3 text-sm",children:[(pe?[{to:"/p/how-it-works",label:"How It Works"},{to:"/p/about-tom",label:"About Tom"},{to:"/p/who-i-help",label:"Who I Help"},{to:"/p/frequently-asked-questions",label:"Frequently Asked Questions"},{to:"/p/call-tom-first",label:"Call Tom First"}]:cr).map(Hr=>s.jsx("li",{children:/^https?:\/\//i.test(Hr.to)?s.jsx("a",{href:Hr.to,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:Hr.label}):s.jsx(Nn,{to:Hr.to,className:"hover:text-white transition-colors",children:Hr.label})},Hr.to)),be&&!pe&&s.jsx("li",{children:s.jsx("a",{href:be,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]}),g.length>0&&!pe&&s.jsxs(s.Fragment,{children:[s.jsx("h2",{className:"font-semibold text-white mt-8 mb-4 text-sm tracking-wider uppercase",children:"Local Areas"}),s.jsx("ul",{className:"space-y-3 text-sm",children:g.map(Hr=>s.jsx("li",{children:s.jsx(Nn,{to:`/homes-for-sale-in-${Hr.city_slug}`,className:"hover:text-white transition-colors",children:Hr.city_name})},Hr.city_slug))})]})]}),s.jsxs("div",{children:[s.jsx("h2",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),s.jsx("p",{className:"text-sm text-gray-400 leading-relaxed mb-4",children:pe?"Helping you find the right real estate agent, wherever you need one.":Le?"Have a real estate question or need a trusted connection? Get in touch today.":"Ready to find your dream home? Get in touch today for a personalized consultation."}),s.jsx(Nn,{to:pe?"/p/call-tom-first":"/contact",className:"inline-block px-5 py-2.5 bg-white text-gray-900 text-sm font-semibold rounded-lg hover:bg-gray-100 transition-colors",children:pe?"Call Tom First":"Contact Me"})]})]}),s.jsxs("div",{className:"mt-14 pt-6 border-t border-gray-800/50",children:[e.showTeamLogo&&e.teamLogoUrl&&s.jsx("div",{className:"flex items-center justify-center mb-6",children:s.jsx("img",{src:e.teamLogoUrl,alt:`${Q} logo`,className:`${B3t(e.headerLogoSize)} w-auto object-contain`})}),e.brokerageLegalName&&s.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-gray-400 mb-3",children:[s.jsxs("span",{children:[Z," · ",e.brokerageLegalName]}),e.agentLicenseNumber&&s.jsx("span",{children:e.agentLicenseNumber}),e.brokerageLicenseNumber&&s.jsxs("span",{children:["Brokerage #",e.brokerageLicenseNumber]})]}),e.mlsDisclaimerText&&s.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[e.mlsLogoUrl&&s.jsx("img",{src:e.mlsLogoUrl,alt:"MLS",className:"h-8 w-auto flex-shrink-0 mt-0.5"}),s.jsx("p",{className:"text-[11px] text-gray-400 leading-relaxed max-w-3xl text-center",children:e.mlsDisclaimerText})]}),s.jsxs("div",{className:"flex items-center justify-center gap-4 text-xs text-gray-400",children:[e.equalHousingEnabled&&s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-5 w-5 text-gray-400",children:s.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),s.jsx("span",{children:"Equal Housing Opportunity"})]}),s.jsxs("span",{children:["© ",new Date().getFullYear()," ",Z,". Powered by LevelUp."]})]})]})]})}),!ee&&!pe&&((Ki=e.agent)==null?void 0:Ki.avatar_url)&&s.jsx(pVt,{agent:e.agent,bookingUrl:be}),c&&s.jsx(pQ,{open:c,mode:"optional",siteConfig:e,onComplete:()=>d(!1),onSkip:()=>d(!1)}),s.jsx(JQ,{slug:e.subdomainSlug}),s.jsx(eJ,{slug:e.subdomainSlug}),!pe&&s.jsx(tJ,{slug:e.subdomainSlug})]})}function pVt({agent:t,bookingUrl:e}){var a;const[r,n]=N.useState(!1),i=qa();return t?s.jsx("div",{className:`fixed right-6 z-40 ${e?"bottom-24 md:bottom-6":"bottom-6"}`,children:r?s.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl border border-gray-200 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[s.jsxs("div",{className:"p-5",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[s.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-gray-100"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-bold text-gray-900 text-sm",children:t.full_name}),s.jsx("p",{className:"text-xs text-gray-600",children:t.title||"Real Estate Professional"})]})]}),s.jsx("p",{className:"text-xs text-gray-600 mb-4",children:"Have questions about a property or the area? I'm here to help!"}),s.jsxs("div",{className:"space-y-2",children:[t.phone&&s.jsxs("a",{href:`tel:${t.phone}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[s.jsx(Ui,{className:"h-4 w-4 text-gray-400"}),t.phone]}),t.email&&s.jsxs("a",{href:`mailto:${t.email}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[s.jsx(rs,{className:"h-4 w-4 text-gray-400"}),"Email Me"]}),s.jsx("button",{onClick:()=>{n(!1),i("/contact")},className:"w-full px-3 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl transition-colors",children:"Ask a Question"}),e&&s.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:"block text-center w-full px-3 py-2.5 bg-gray-900 hover:bg-gray-800 text-white text-sm font-semibold rounded-xl transition-colors",children:"Schedule a Call"})]})]}),s.jsx("button",{onClick:()=>n(!1),className:"absolute top-3 right-3 p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100",children:s.jsx(Ra,{className:"h-4 w-4"})})]}):s.jsxs("button",{onClick:()=>n(!0),className:"group flex items-center gap-3 bg-white pl-1.5 pr-5 py-1.5 rounded-full shadow-xl border border-gray-200 hover:shadow-2xl transition-all hover:scale-105",children:[s.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-10 w-10 rounded-full object-cover ring-2 ring-blue-100"}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-xs font-bold text-gray-900 leading-none",children:(a=t.full_name)==null?void 0:a.split(" ")[0]}),s.jsx("p",{className:"text-[10px] text-blue-600 font-medium mt-0.5",children:"Chat with me →"})]})]})}):null}function EM({item:t,className:e,onClick:r}){const n=t.target_url||"#";return/^(https?:)?\/\//i.test(n)||/^(mailto:|tel:)/i.test(n)?s.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:e,onClick:r,children:t.label}):s.jsx(Nn,{to:n,className:e,onClick:r,children:t.label})}const gVt=new Set(["danicapatton"]);function MNe(t){if(!t)return!1;const e=t.themeConfig||{};return e.expReady===!1?!1:e.expReady===!0||gVt.has(t.subdomainSlug)}const yVt="/exp-ready",xVt="eXp Ready",uge={california:"California DRE License",ca:"California DRE License"};function $H(t){const e=(t||"").trim();if(!e)return"Real Estate License";const r=e.toLowerCase();return uge[r]?uge[r]:`${e.replace(/\b\w/g,i=>i.toUpperCase())} Real Estate License`}function dge(t){if(t)return t.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function _Vt({children:t,siteConfig:e}){var cr,ft,Kt,ir,Gr,tr,Qt;const r=ms(),n=qa(),[i,a]=N.useState(!1),[c,d]=N.useState(!1);N.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&d(!0)},[]);const[p,l]=N.useState(!1),[g,v]=N.useState(!1),[E,T]=N.useState([]),[j,P]=N.useState(!1),C=N.useRef(null),L=N.useRef(null),{user:O,profile:F,signOut:$}=VA();bQ(e,O==null?void 0:O.id),wQ(e,O==null?void 0:O.id);const G=((cr=e.agent)==null?void 0:cr.full_name)||"Agent",W=dge(e.agentLicenseNumber),Z=dge(e.brokerageLicenseNumber),Q=e.siteTitle||`${G} Real Estate`,ee=zt=>{if(!zt)return zt;const Vr=G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Jr=new RegExp(`^\\s*${Vr}\\s*[|\\-–—:]\\s*`,"i");return zt.replace(Jr,"").trim()},ie=Q&&Q!==`${G} Real Estate`?Q:null,oe=ie?ee(ie):null,pe=oe&&oe.toLowerCase()!==G.toLowerCase()?oe:null,Le=r.pathname==="/search",be=r.pathname==="/",Re=e.leadRegistrationMode!=="disabled",Ie="#c9a96e",Te=e.bookingUrl;N.useEffect(()=>{const zt=()=>P(window.scrollY>80);return window.addEventListener("scroll",zt,{passive:!0}),()=>window.removeEventListener("scroll",zt)},[]),N.useEffect(()=>{(async()=>{const{data:Vr}=await Be.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",e.id).eq("is_published",!0).order("sort_order",{ascending:!0});T(Vr||[])})()},[e.id]),N.useEffect(()=>{const zt=Vr=>{C.current&&!C.current.contains(Vr.target)&&l(!1),L.current&&!L.current.contains(Vr.target)&&v(!1)};return document.addEventListener("mousedown",zt),()=>document.removeEventListener("mousedown",zt)},[]);const ge=(((ft=e.themeConfig)==null?void 0:ft.focusPages)??[]).filter(zt=>zt==null?void 0:zt.slug).map(zt=>({to:`/${zt.slug}`,label:zt.navLabel||zt.title})).concat(MNe(e)?[{to:yVt,label:xVt}]:[]),$e=wCe(e)||Cv(e),{data:we}=FB($e?e.agentId:null),ke=((we==null?void 0:we.length)??0)>0,{data:Ae}=fQ(e.agentId),He=((Ae==null?void 0:Ae.length)??0)>0,ot=[{to:"/",label:"Home"},...$e?ke?[{to:"/listings",label:"My Listings"}]:[]:[{to:"/search",label:"Search"}],...He?[{to:"/sold",label:"Sold"}]:[],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],nt=[...ot,...ge],tt=e.siteTitle||`${G} - Real Estate`,vt=e.siteTagline||`Browse homes and listings with ${G}`,Vt=e.ogImageUrl||((Kt=e.agent)==null?void 0:Kt.avatar_url)||"",Ct=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`,Bt=be?j?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return s.jsxs("div",{className:`flex flex-col ${Le?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[s.jsx(_Q,{siteConfig:e,pagePath:r.pathname}),s.jsx(vQ,{siteConfig:e}),s.jsxs(mc,{children:[s.jsx("title",{children:tt}),s.jsx("meta",{name:"description",content:vt}),s.jsx("meta",{property:"og:title",content:tt}),s.jsx("meta",{property:"og:description",content:vt}),s.jsx("meta",{property:"og:type",content:"website"}),s.jsx("meta",{property:"og:url",content:Ct+r.pathname}),Vt&&s.jsx("meta",{property:"og:image",content:Vt}),s.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),s.jsx("meta",{name:"twitter:title",content:tt}),s.jsx("meta",{name:"twitter:description",content:vt}),Vt&&s.jsx("meta",{name:"twitter:image",content:Vt}),e.faviconUrl&&s.jsx("link",{rel:"icon",href:e.faviconUrl,type:"image/png"}),s.jsx("link",{rel:"canonical",href:`${Ct}${r.pathname}`}),s.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap",rel:"stylesheet"})]}),s.jsxs("header",{className:`${be?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${Bt}`,children:[s.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:s.jsxs("div",{className:"flex items-center justify-between min-h-20 py-3 gap-6",children:[s.jsxs(Nn,{to:"/",className:"flex items-center gap-3 shrink-0",children:[e.showTeamLogo&&e.teamLogoUrl&&s.jsx("img",{src:e.teamLogoUrl,alt:`${G} brokerage logo`,className:"h-9 sm:h-11 w-auto max-w-[150px] object-contain"}),s.jsxs("span",{className:"flex flex-col leading-tight",children:[s.jsx("span",{className:"block whitespace-nowrap text-white text-base sm:text-lg xl:text-xl tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:G}),e.brokerageLegalName&&s.jsx("span",{className:"hidden sm:block whitespace-nowrap text-[10px] sm:text-[11px] tracking-[0.14em] uppercase text-white/60",children:e.brokerageLegalName}),pe&&s.jsx("span",{className:"hidden xl:block whitespace-nowrap text-[10px] tracking-[0.18em] uppercase text-white/40",children:pe})]})]}),s.jsxs("nav",{className:"hidden lg:flex items-center justify-end gap-0 flex-1 min-w-0",children:[ot.map(zt=>s.jsx(Nn,{to:zt.to,className:`whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname===zt.to?"text-white":"text-white/40 hover:text-white"}`,children:zt.label},zt.to)),ge.length>0&&s.jsxs("div",{ref:L,className:"relative",children:[s.jsxs("button",{onClick:()=>v(!g),className:`flex items-center gap-1 whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${ge.some(zt=>r.pathname===zt.to)?"text-white":"text-white/40 hover:text-white"}`,children:["Specialty"," ",s.jsx(ad,{className:`h-3 w-3 transition-transform ${g?"rotate-180":""}`})]}),g&&s.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:ge.map(zt=>s.jsx(Nn,{to:zt.to,onClick:()=>v(!1),className:`block px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors ${r.pathname===zt.to?"text-white":""}`,children:zt.label},zt.to))})]}),E.length>0&&s.jsxs("div",{ref:C,className:"relative",children:[s.jsxs("button",{onClick:()=>l(!p),className:`flex items-center gap-1 whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",s.jsx(ad,{className:`h-3 w-3 transition-transform ${p?"rotate-180":""}`})]}),p&&s.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:E.map(zt=>s.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${zt.city_slug}`),l(!1)},className:"w-full text-left px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors",children:zt.city_name},zt.city_slug))})]}),O?s.jsx("div",{className:"ml-3",children:s.jsx(gQ,{savedClassName:"flex items-center gap-1.5 px-3 py-2 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",triggerClassName:"flex items-center gap-1.5 border border-white/20 py-1 pl-1 pr-3 text-xs uppercase tracking-wider text-white/70 outline-none transition-colors hover:text-white",avatarClassName:"flex h-6 w-6 items-center justify-center bg-white/15 text-[10px] font-semibold text-white"})}):Re?s.jsx("button",{onClick:()=>d(!0),className:"ml-3 px-5 py-2 text-xs tracking-[0.2em] uppercase border border-white/20 text-white/60 hover:bg-white hover:text-black transition-all duration-500",children:"Sign In"}):null,Te&&s.jsx(Fy,{bookingUrl:Te,label:"Schedule",size:"sm",className:"ml-3",source:"nav"})]}),s.jsxs("button",{onClick:()=>a(!i),className:"lg:hidden p-2 text-white/60 hover:text-white",children:[s.jsx("div",{className:"flex flex-col items-center gap-0.5",children:i?s.jsx(Ra,{className:"h-5 w-5"}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"w-6 h-px bg-current"}),s.jsx("div",{className:"w-4 h-px bg-current mt-1.5"}),s.jsx("div",{className:"w-6 h-px bg-current mt-1.5"})]})}),s.jsx("span",{className:"text-[8px] tracking-[0.3em] uppercase mt-1 block",children:"MENU"})]})]})}),i&&s.jsx("div",{className:"lg:hidden border-t border-white/5 bg-[#0d0b0a]/98 backdrop-blur-lg",children:s.jsxs("div",{className:"px-6 py-4 space-y-1",children:[Te&&s.jsx(Fy,{bookingUrl:Te,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),ot.map(zt=>s.jsx(Nn,{to:zt.to,onClick:()=>a(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${r.pathname===zt.to?"text-white":"text-white/40 hover:text-white"}`,children:zt.label},zt.to)),ge.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Ie},children:"Specialty"}),ge.map(zt=>s.jsx(Nn,{to:zt.to,onClick:()=>a(!1),className:`block px-3 py-2.5 text-xs tracking-wider uppercase transition-colors ${r.pathname===zt.to?"text-white":"text-white/40 hover:text-white"}`,children:zt.label},zt.to))]}),E.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Ie},children:"Cities"}),E.map(zt=>s.jsx(Nn,{to:`/homes-for-sale-in-${zt.city_slug}`,onClick:()=>a(!1),className:"block px-3 py-2.5 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:zt.city_name},zt.city_slug))]}),O?s.jsx(yQ,{dark:!0,onNavigate:()=>a(!1)}):Re?s.jsx("button",{onClick:()=>{d(!0),a(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign In / Register"}):null]})})]}),s.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:t}),!Le&&s.jsx("footer",{className:"bg-[#0a0908] text-white/70 border-t border-white/10",children:s.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-20",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-16",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-white text-xl tracking-tight mb-3",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:G}),s.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((ir=e.agent)==null?void 0:ir.title)||"Real Estate Professional"}),(W||Z)&&s.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[W&&s.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[$H(e.licenseState)," #",W]}),Z&&s.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",Z]})]}),((Gr=e.agent)==null?void 0:Gr.phone)&&s.jsxs("a",{href:`tel:${e.agent.phone}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors mb-3",children:[s.jsx(Ui,{className:"h-3.5 w-3.5"})," ",e.agent.phone]}),((tr=e.agent)==null?void 0:tr.email)&&s.jsxs("a",{href:`mailto:${e.agent.email}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors",children:[s.jsx(rs,{className:"h-3.5 w-3.5"})," ",e.agent.email]}),s.jsx(rJ,{siteConfig:e,className:"mt-6",iconClassName:"border-white/20"})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Ie},children:"Quick Links"}),s.jsxs("ul",{className:"space-y-3",children:[nt.map(zt=>s.jsx("li",{children:s.jsx(Nn,{to:zt.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:zt.label})},zt.to)),Te&&s.jsx("li",{children:s.jsx("a",{href:Te,target:"_blank",rel:"noopener noreferrer",className:"text-xs tracking-wider uppercase transition-colors hover:opacity-80",style:{color:qA},children:"Schedule a Free Consultation"})})]})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Ie},children:"Get In Touch"}),s.jsx("p",{className:"text-sm text-white/70 leading-relaxed mb-6",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:"Ready to experience luxury real estate? Let's connect."}),s.jsxs("div",{className:"flex flex-col items-start gap-3",children:[Te&&s.jsx(Fy,{bookingUrl:Te,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),s.jsx(Nn,{to:"/contact",className:"inline-block px-8 py-3 text-xs tracking-[0.3em] uppercase border border-white/20 text-white/90 hover:bg-white hover:text-black transition-all duration-500",children:"Contact Me"})]})]})]}),s.jsxs("div",{className:"mt-16 pt-8 border-t border-white/10",children:[e.showTeamLogo&&e.teamLogoUrl&&s.jsx("div",{className:"flex items-center justify-center mb-6",children:s.jsx("img",{src:e.teamLogoUrl,alt:"Team",className:"h-10 w-auto object-contain opacity-70"})}),e.brokerageLegalName&&s.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-[11px] text-white/70 tracking-wider uppercase mb-3",children:[s.jsxs("span",{children:[G," · ",e.brokerageLegalName]}),W&&s.jsxs("span",{children:[$H(e.licenseState)," #",W]}),Z&&s.jsxs("span",{children:["Brokerage #",Z]})]}),e.mlsDisclaimerText&&s.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[e.mlsLogoUrl&&s.jsx("img",{src:e.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-70"}),s.jsx("p",{className:"text-[11px] text-white/70 leading-relaxed max-w-3xl text-center",children:e.mlsDisclaimerText})]}),s.jsxs("div",{className:"flex items-center justify-center gap-4 text-[11px] text-white/70 tracking-wider uppercase",children:[e.equalHousingEnabled&&s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:s.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),s.jsx("span",{children:"Equal Housing Opportunity"})]}),s.jsxs("span",{children:["© ",new Date().getFullYear()," ",G,". Powered by LevelUp."]})]})]})]})}),!Le&&((Qt=e.agent)==null?void 0:Qt.avatar_url)&&s.jsx(vVt,{agent:e.agent,agentLicense:W,siteConfig:e,accentColor:Ie}),c&&s.jsx(pQ,{open:c,mode:"optional",siteConfig:e,onComplete:()=>d(!1),onSkip:()=>d(!1),theme:"luxury",accentColor:Ie}),s.jsx(JQ,{slug:e.subdomainSlug}),s.jsx(eJ,{slug:e.subdomainSlug}),s.jsx(tJ,{slug:e.subdomainSlug})]})}function vVt({agent:t,agentLicense:e,siteConfig:r,accentColor:n}){var d;const[i,a]=N.useState(!1),c=qa();return t?s.jsx("div",{className:`fixed right-6 z-40 ${r.bookingUrl?"bottom-24 md:bottom-6":"bottom-6"}`,children:i?s.jsxs("div",{className:"bg-[#1a1715] border border-white/10 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[s.jsxs("div",{className:"p-5",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-12 w-12 rounded-full object-cover ring-1 ring-white/10"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-white text-sm font-medium",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:t.full_name}),s.jsx("p",{className:"text-white/50 text-[10px] tracking-[0.1em] uppercase",children:t.title||"Real Estate Professional"})]})]}),e&&s.jsxs("div",{className:"mb-3 px-3 py-2 bg-white/5 border border-white/10",children:[s.jsx("p",{className:"text-[10px] text-white/50 tracking-wider uppercase",children:$H(r.licenseState)}),s.jsxs("p",{className:"text-xs text-white font-medium",children:["#",e]})]}),s.jsxs("div",{className:"space-y-2",children:[t.phone&&s.jsxs("a",{href:`tel:${t.phone}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/70 hover:text-white transition-colors tracking-wider",children:[s.jsx(Ui,{className:"h-3.5 w-3.5"})," ",t.phone]}),t.email&&s.jsxs("a",{href:`mailto:${t.email}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/70 hover:text-white transition-colors tracking-wider",children:[s.jsx(rs,{className:"h-3.5 w-3.5"})," Email Me"]}),s.jsx("button",{onClick:()=>{a(!1),c("/contact")},className:"w-full px-3 py-2.5 text-xs tracking-[0.2em] uppercase text-black hover:opacity-90 transition-colors",style:{backgroundColor:n},children:"Send a Message"})]})]}),s.jsx("button",{onClick:()=>a(!1),className:"absolute top-3 right-3 p-1 text-white/20 hover:text-white/50",children:s.jsx(Ra,{className:"h-4 w-4"})})]}):s.jsxs("button",{onClick:()=>a(!0),className:"group flex items-center gap-3 bg-[#1a1715] border border-white/10 pl-1.5 pr-5 py-1.5 hover:border-white/20 transition-all",children:[s.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-10 w-10 rounded-full object-cover ring-1 ring-white/10"}),s.jsxs("div",{className:"text-left",children:[s.jsx("p",{className:"text-[11px] text-white leading-none",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:(d=t.full_name)==null?void 0:d.split(" ")[0]}),s.jsx("p",{className:"text-[9px] tracking-[0.15em] uppercase mt-1",style:{color:n},children:"Let's connect →"})]})]})}):null}const II="#2c1810",dy="#b8860b";function bVt({children:t,siteConfig:e}){var be,Re,Ie;const r=ms();qa();const[n,i]=N.useState(!1),[a,c]=N.useState(!1);N.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&c(!0)},[]);const[d,p]=N.useState(!1),[l,g]=N.useState([]),[v,E]=N.useState(!1),T=N.useRef(null),{user:j,profile:P,signOut:C}=VA();bQ(e,j==null?void 0:j.id),wQ(e,j==null?void 0:j.id);const L=((be=e.agent)==null?void 0:be.full_name)||"Agent",O=e.siteTitle||`${L} Land & Ranch`,F=r.pathname==="/",$=e.leadRegistrationMode!=="disabled",G=Cv(e);N.useEffect(()=>{const Te=()=>E(window.scrollY>80);return window.addEventListener("scroll",Te,{passive:!0}),()=>window.removeEventListener("scroll",Te)},[]),N.useEffect(()=>{(async()=>{const{data:ge}=await Be.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",e.id).eq("is_published",!0).order("sort_order");ge&&g(ge)})()},[e.id]),N.useEffect(()=>{const Te=ge=>{T.current&&!T.current.contains(ge.target)&&p(!1)};return document.addEventListener("mousedown",Te),()=>document.removeEventListener("mousedown",Te)},[]);const{data:W}=fQ(e.agentId),{data:Z}=FB(e.agentId),Q=((W==null?void 0:W.length)??0)>0,ee=((Z==null?void 0:Z.length)??0)>0,ie=[{label:"Home",path:"/"},...G?[]:[{label:"Search Properties",path:"/search"}],...G&&ee?[{label:"My Listings",path:"/listings"}]:[],...Q?[{label:"Sold",path:"/sold"}]:[],{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],oe=v||!F?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",pe=v||!F?II:"#ffffff",Le=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`;return s.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[s.jsxs(mc,{children:[s.jsx("title",{children:O}),s.jsx("meta",{property:"og:url",content:Le+r.pathname}),s.jsx("link",{rel:"canonical",href:`${Le}${r.pathname}`}),s.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700;800&family=Lora:wght@400;500;600&display=swap",rel:"stylesheet"})]}),s.jsx(_Q,{siteConfig:e}),s.jsx(vQ,{siteConfig:e}),s.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${oe}`,children:[s.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6",children:s.jsxs("div",{className:"flex items-center justify-between h-16 md:h-20",children:[s.jsxs(Nn,{to:"/",className:"flex items-center gap-2.5",children:[s.jsx(qse,{className:"w-7 h-7",style:{color:dy}}),s.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:pe,fontFamily:"'Playfair Display', Georgia, serif"},children:O})]}),s.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[ie.map(Te=>s.jsx(Nn,{to:Te.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:r.pathname===Te.path?dy:pe},children:Te.label},Te.path)),l.length>0&&s.jsxs("div",{ref:T,className:"relative",children:[s.jsxs("button",{onClick:()=>p(!d),className:"px-4 py-2 text-sm font-medium tracking-wide uppercase flex items-center gap-1 transition-colors hover:opacity-80",style:{color:pe},children:["Area Guides ",s.jsx(ad,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-180":""}`})]}),d&&s.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-white rounded-xl shadow-xl border border-gray-100 py-2 animate-in fade-in-0 slide-in-from-top-2",children:l.map(Te=>s.jsx(Nn,{to:`/homes-for-sale-in-${Te.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:II},onClick:()=>p(!1),children:Te.city_name},Te.city_slug))})]}),j?s.jsx("div",{className:"ml-3",children:s.jsx(gQ,{showSaved:!1,triggerClassName:"flex items-center gap-1.5 rounded-full border-2 py-1 pl-1 pr-3 text-sm font-medium outline-none transition-all hover:scale-105",avatarClassName:"flex h-7 w-7 items-center justify-center rounded-full text-xs font-semibold text-white"})}):$?s.jsx("button",{onClick:()=>c(!0),className:"ml-3 px-5 py-2.5 text-sm font-semibold text-white rounded-full hover:shadow-lg transition-all hover:scale-105",style:{backgroundColor:dy},children:"Sign In"}):null]}),s.jsx("button",{onClick:()=>i(!n),className:"md:hidden p-2",style:{color:pe},children:n?s.jsx(Ra,{className:"w-6 h-6"}):s.jsx(nA,{className:"w-6 h-6"})})]})}),n&&s.jsx("div",{className:"md:hidden bg-white border-t border-gray-100 shadow-xl animate-in slide-in-from-top-2",children:s.jsxs("div",{className:"px-4 py-4 space-y-1",children:[ie.map(Te=>s.jsx(Nn,{to:Te.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:r.pathname===Te.path?dy:II},onClick:()=>i(!1),children:Te.label},Te.path)),l.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"px-4 py-2 text-xs font-semibold tracking-wider uppercase text-gray-400",children:"Area Guides"}),l.map(Te=>s.jsx(Nn,{to:`/homes-for-sale-in-${Te.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:II},onClick:()=>i(!1),children:Te.city_name},Te.city_slug))]}),j&&s.jsx(yQ,{onNavigate:()=>i(!1)}),!j&&$&&s.jsx("button",{onClick:()=>{c(!0),i(!1)},className:"w-full mt-3 px-5 py-3 text-white font-semibold rounded-full",style:{backgroundColor:dy},children:"Sign In"})]})})]}),s.jsx("main",{children:t}),s.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:II},children:s.jsxs("div",{className:"max-w-6xl mx-auto",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-10",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[s.jsx(qse,{className:"w-6 h-6",style:{color:dy}}),s.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:O})]}),s.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Personal guidance for buying and selling land, homes, and rural property."}),s.jsx(rJ,{siteConfig:e,className:"mt-5",iconClassName:"border-white/20 text-white"})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),s.jsx("div",{className:"space-y-2",children:ie.map(Te=>s.jsx(Nn,{to:Te.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:Te.label},Te.path))})]}),s.jsxs("div",{children:[s.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Contact"}),s.jsxs("div",{className:"space-y-3",children:[((Re=e.agent)==null?void 0:Re.phone)&&s.jsxs("a",{href:`tel:${e.agent.phone}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[s.jsx(Ui,{className:"w-4 h-4",style:{color:dy}}),e.agent.phone]}),((Ie=e.agent)==null?void 0:Ie.email)&&s.jsxs("a",{href:`mailto:${e.agent.email}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[s.jsx(rs,{className:"w-4 h-4",style:{color:dy}}),e.agent.email]})]})]})]}),s.jsxs("div",{className:"mt-12 pt-8 border-t border-white/10 flex items-center justify-between",children:[s.jsxs("p",{className:"text-white/40 text-xs",children:["© ",new Date().getFullYear()," ",O,". All rights reserved."]}),s.jsx("div",{className:"h-px w-16",style:{backgroundColor:dy}})]})]})}),a&&s.jsx(pQ,{open:a,mode:e.leadRegistrationMode==="required"?"required":"optional",siteConfig:e,onSkip:()=>c(!1),onComplete:()=>c(!1)}),s.jsx(JQ,{slug:e.subdomainSlug}),s.jsx(eJ,{slug:e.subdomainSlug}),s.jsx(tJ,{slug:e.subdomainSlug})]})}function TM(){const{pathname:t}=ms();return N.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[t]),null}const wVt=N.lazy(()=>Ge(()=>import("./LeadSiteHome-WrkmA9p1.js"),__vite__mapDeps([10,11,12,13,14,15,16,17,18]))),SVt=N.lazy(()=>Ge(()=>import("./LeadSiteLuxuryHome-BUsnB4ee.js"),__vite__mapDeps([19,20,14,15,21,18,22,23]))),EVt=N.lazy(()=>Ge(()=>import("./LeadSiteLandRanchHome-DKjZvLWe.js"),__vite__mapDeps([24,11,12,13,14,15,16,25,26,27]))),AM=N.lazy(()=>Ge(()=>import("./LeadSiteSearch-Bj8VZbDN.js"),__vite__mapDeps([28,11,12,13,29,30,31,32]))),TVt=N.lazy(()=>Ge(()=>import("./LeadSiteLuxurySearch-BKNyJtXL.js"),__vite__mapDeps([33,11,12,13,29,30,31,32]))),kM=N.lazy(()=>Ge(()=>import("./LeadSiteListingDetail-B7GS2mDf.js"),__vite__mapDeps([34,35,36,26,37,38,39,40,41]))),AVt=N.lazy(()=>Ge(()=>import("./LeadSiteLuxuryListingDetail-DRfpB3Os.js"),__vite__mapDeps([42,35,36,26,37,38,39,40,41]))),kVt=N.lazy(()=>Ge(()=>import("./LeadSiteAbout-DCzpqlQp.js"),__vite__mapDeps([43,17]))),IVt=N.lazy(()=>Ge(()=>import("./LeadSiteLuxuryAbout-C7YGm-HM.js"),__vite__mapDeps([44,45]))),jVt=N.lazy(()=>Ge(()=>import("./LeadSiteContact-CYPtXt6K.js"),[])),CVt=N.lazy(()=>Ge(()=>import("./LeadSiteLuxuryContact-jVdiGk4_.js"),[])),S8=N.lazy(()=>Ge(()=>import("./LeadSiteConsumerDashboard-bLw2viGy.js"),[])),b_=N.lazy(()=>Ge(()=>import("./LeadSiteBlog-5jS8fhrc.js"),__vite__mapDeps([46,47,48]))),E8=N.lazy(()=>Ge(()=>import("./LeadSiteCommunity-BC3_POQo.js"),__vite__mapDeps([49,40,6,50,51,52,53]))),PVt=N.lazy(()=>Ge(()=>import("./LeadSiteSellers-C1qj2iXX.js"),__vite__mapDeps([54,45]))),NVt=N.lazy(()=>Ge(()=>import("./LeadSiteCityPage-D4E5PyQE.js"),__vite__mapDeps([55,56,32,20,15]))),RVt=N.lazy(()=>Ge(()=>import("./LeadSiteSubdivisionPage-DFLeNz7P.js"),[])),T8=N.lazy(()=>Ge(()=>import("./LeadSiteCustomPage-CHScwCA8.js"),[])),LVt=N.lazy(()=>Ge(()=>import("./LeadSiteFocusPage-DN20shAh.js"),__vite__mapDeps([57,52]))),DVt=N.lazy(()=>Ge(()=>import("./LeadSiteExpReady-Cp9_Cqya.js"),__vite__mapDeps([58,59,51,22]))),MVt=N.lazy(()=>Ge(()=>import("./LeadSiteConsultation-COBX67Jk.js"),[])),hge=N.lazy(()=>Ge(()=>import("./LeadSiteReviews-DxoV48De.js"),[])),OVt=N.lazy(()=>Ge(()=>import("./LeadSiteExchangeListings-aktFQ31K.js"),[]).then(t=>({default:t.LeadSiteExchangeListingsIndex}))),FVt=N.lazy(()=>Ge(()=>import("./LeadSiteExchangeListings-aktFQ31K.js"),[]).then(t=>({default:t.LeadSiteSoldListingsIndex}))),BVt=N.lazy(()=>Ge(()=>import("./LeadSiteExchangeListings-aktFQ31K.js"),[]).then(t=>({default:t.LeadSiteExchangeListingDetail}))),zVt=N.lazy(()=>Ge(()=>import("./OrgSiteLayout-CZ71csk6.js"),__vite__mapDeps([60,61]))),$Vt=N.lazy(()=>Ge(()=>import("./OrgSiteHome-DNpitldw.js"),__vite__mapDeps([62,61]))),UVt=N.lazy(()=>Ge(()=>import("./OrgSiteAgents-BGj-L8yA.js"),__vite__mapDeps([63,61,62,64]))),VVt=N.lazy(()=>Ge(()=>import("./OrgSiteAgents-BGj-L8yA.js"),__vite__mapDeps([63,61,62,64])).then(t=>({default:t.OrgSiteAgentProfile}))),fge=N.lazy(()=>Ge(()=>import("./OrgSiteListings-Do0qw5I3.js"),__vite__mapDeps([65,61,62,64]))),qVt=N.lazy(()=>Ge(()=>import("./OrgSiteListings-Do0qw5I3.js"),__vite__mapDeps([65,61,62,64])).then(t=>({default:t.OrgSiteListingDetail}))),GVt=N.lazy(()=>Ge(()=>import("./OrgSitePages-DfD1aOvQ.js"),__vite__mapDeps([64,61,62])).then(t=>({default:t.OrgSiteAbout}))),HVt=N.lazy(()=>Ge(()=>import("./OrgSitePages-DfD1aOvQ.js"),__vite__mapDeps([64,61,62])).then(t=>({default:t.OrgSiteContact}))),WVt=N.lazy(()=>Ge(()=>import("./OrgSitePages-DfD1aOvQ.js"),__vite__mapDeps([64,61,62])).then(t=>({default:t.OrgSiteJoin})));function GI(){return s.jsx("div",{className:"min-h-[60vh] flex items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"})})}function KVt({siteConfig:t}){const{data:e,isLoading:r}=FB(t.agentId);return r?s.jsx(GI,{}):s.jsx(Oi,{to:e!=null&&e.length?"/listings":"/contact?interest=Property%20search",replace:!0})}function YVt(){N.useEffect(()=>{document.body.classList.add("lead-site-page");const t=['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",".widget-visible"],e=()=>{t.forEach(n=>{document.querySelectorAll(n).forEach(i=>{i.style.display="none"})})};e();const r=[500,1500,3e3,5e3].map(n=>setTimeout(e,n));return()=>{document.body.classList.remove("lead-site-page"),r.forEach(clearTimeout)}},[])}function ZVt(){var E,T,j;const{siteConfig:t,themeConfig:e,isLoading:r,error:n}=V3t();if(YVt(),r)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto mb-4"}),s.jsx("p",{className:"text-gray-500",children:"Loading..."})]})});if(n||!t)return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-6",children:s.jsxs("div",{className:"text-center max-w-md",children:[s.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Site Not Found"}),s.jsx("p",{className:"text-gray-500",children:"This lead site is not available or has not been set up yet."})]})});if(((E=t.themeConfig)==null?void 0:E.orgPreset)==="remaxcreative"){const P=V4t;return s.jsxs(aM,{siteConfig:t,children:[s.jsx(TM,{}),s.jsx(N.Suspense,{fallback:s.jsx(GI,{}),children:s.jsx(P4t,{siteConfig:t,children:s.jsxs(kb,{children:[s.jsx(Ce,{path:"/",element:s.jsx(L4t,{siteConfig:t})}),s.jsx(Ce,{path:"/buy",element:s.jsx(F4t,{siteConfig:t})}),s.jsx(Ce,{path:"/sell",element:s.jsx(B4t,{siteConfig:t})}),s.jsx(Ce,{path:"/about",element:s.jsx(z4t,{siteConfig:t})}),s.jsx(Ce,{path:"/agents",element:s.jsx(D4t,{siteConfig:t})}),s.jsx(Ce,{path:"/team",element:s.jsx(Oi,{to:"/agents",replace:!0})}),s.jsx(Ce,{path:"/offices",element:s.jsx(M4t,{siteConfig:t})}),s.jsx(Ce,{path:"/join",element:s.jsx($4t,{siteConfig:t})}),s.jsx(Ce,{path:"/communities",element:s.jsx(O4t,{siteConfig:t})}),s.jsx(Ce,{path:"/contact",element:s.jsx(U4t,{siteConfig:t})}),s.jsx(Ce,{path:"/search",element:s.jsx(P,{children:s.jsx(AM,{siteConfig:t})})}),s.jsx(Ce,{path:"/listing/:mlsNumber",element:s.jsx(P,{children:s.jsx(kM,{siteConfig:t})})}),s.jsx(Ce,{path:"/dashboard",element:s.jsx(P,{children:s.jsx(S8,{siteConfig:t})})}),s.jsx(Ce,{path:"/account",element:s.jsx(Oi,{to:"/dashboard",replace:!0})}),s.jsx(Ce,{path:"/blog",element:s.jsx(P,{children:s.jsx(b_,{siteConfig:t,isLuxury:!1})})}),s.jsx(Ce,{path:"/blog/:slug",element:s.jsx(P,{children:s.jsx(b_,{siteConfig:t,isLuxury:!1})})}),s.jsx(Ce,{path:"/community",element:s.jsx(P,{children:s.jsx(E8,{siteConfig:t,isLuxury:!1})})}),s.jsx(Ce,{path:"/p/:pageSlug",element:s.jsx(P,{children:s.jsx(T8,{siteConfig:t})})}),s.jsx(Ce,{path:"/*",element:s.jsx(P,{children:s.jsx(IM,{siteConfig:t})})})]})})})]})}if(t.ownerType==="brokerage"&&((T=t.themeConfig)==null?void 0:T.orgPreset)==="btb")return s.jsxs(aM,{siteConfig:t,children:[s.jsx(TM,{}),s.jsx(N.Suspense,{fallback:s.jsx(GI,{}),children:s.jsx(f4t,{children:s.jsxs(kb,{children:[s.jsx(Ce,{path:"/",element:s.jsx(p4t,{siteConfig:t})}),s.jsx(Ce,{path:"/buy",element:s.jsx(y4t,{siteConfig:t})}),s.jsx(Ce,{path:"/sell",element:s.jsx(x4t,{siteConfig:t})}),["/real-estate","/construction","/design","/work","/work/*"].map(P=>s.jsx(Ce,{path:P,element:s.jsx(Oi,{to:P==="/real-estate"?"/buy":"/",replace:!0})},P)),s.jsx(Ce,{path:"/about",element:s.jsx(_4t,{siteConfig:t})}),s.jsx(Ce,{path:"/team",element:s.jsx(v4t,{siteConfig:t})}),s.jsx(Ce,{path:"/agents",element:s.jsx(Oi,{to:"/team",replace:!0})}),s.jsx(Ce,{path:"/join",element:s.jsx(b4t,{siteConfig:t})}),s.jsx(Ce,{path:"/communities",element:s.jsx(w4t,{siteConfig:t})}),s.jsx(Ce,{path:"/contact",element:s.jsx(S4t,{siteConfig:t})}),s.jsx(Ce,{path:"/search",element:s.jsx(__,{children:s.jsx(AM,{siteConfig:t})})}),s.jsx(Ce,{path:"/listing/:mlsNumber",element:s.jsx(__,{children:s.jsx(kM,{siteConfig:t})})}),s.jsx(Ce,{path:"/dashboard",element:s.jsx(__,{children:s.jsx(S8,{siteConfig:t})})}),s.jsx(Ce,{path:"/account",element:s.jsx(Oi,{to:"/dashboard",replace:!0})}),s.jsx(Ce,{path:"/blog",element:s.jsx(__,{children:s.jsx(b_,{siteConfig:t,isLuxury:!1})})}),s.jsx(Ce,{path:"/blog/:slug",element:s.jsx(__,{children:s.jsx(b_,{siteConfig:t,isLuxury:!1})})}),s.jsx(Ce,{path:"/community",element:s.jsx(__,{children:s.jsx(E8,{siteConfig:t,isLuxury:!1})})}),s.jsx(Ce,{path:"/p/:pageSlug",element:s.jsx(__,{children:s.jsx(T8,{siteConfig:t})})}),s.jsx(Ce,{path:"/*",element:s.jsx(__,{children:s.jsx(IM,{siteConfig:t})})})]})})})]});if(t.ownerType==="brokerage"||t.ownerType==="team"){const P=t.orgTier==="pro";return s.jsxs(aM,{siteConfig:t,children:[s.jsx(TM,{}),s.jsx(N.Suspense,{fallback:s.jsx(GI,{}),children:s.jsx(zVt,{siteConfig:t,themeConfig:e??void 0,children:s.jsxs(kb,{children:[s.jsx(Ce,{path:"/",element:s.jsx($Vt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(Ce,{path:"/listings",element:s.jsx(fge,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(Ce,{path:"/sold",element:s.jsx(fge,{siteConfig:t,themeConfig:e??void 0,sold:!0})}),s.jsx(Ce,{path:"/listings/:slug",element:s.jsx(qVt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(Ce,{path:"/agents",element:s.jsx(UVt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(Ce,{path:"/agents/:slug",element:s.jsx(VVt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(Ce,{path:"/about",element:s.jsx(GVt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(Ce,{path:"/contact",element:s.jsx(HVt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(Ce,{path:"/join",element:s.jsx(WVt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(Ce,{path:"/blog",element:s.jsx(b_,{siteConfig:t,isLuxury:!1})}),s.jsx(Ce,{path:"/blog/:slug",element:s.jsx(b_,{siteConfig:t,isLuxury:!1})}),s.jsx(Ce,{path:"/search",element:P?s.jsx(AM,{siteConfig:t}):s.jsx(Oi,{to:"/listings",replace:!0})}),s.jsx(Ce,{path:"/listing/:mlsNumber",element:P?s.jsx(kM,{siteConfig:t}):s.jsx(Oi,{to:"/listings",replace:!0})}),s.jsx(Ce,{path:"/*",element:s.jsx(IM,{siteConfig:t,referralMode:!P})})]})})})]})}const i=(e==null?void 0:e.themeTier)==="luxury",a=(e==null?void 0:e.themeTier)==="land-ranch",c=a?bVt:i?_Vt:mVt,d=wCe(t),p=d||Cv(t,e),l=t.id==="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109",g=!d&&Cv(t,e),v=a?s.jsx(EVt,{siteConfig:t,themeConfig:e??void 0}):i?s.jsx(SVt,{siteConfig:t,themeConfig:e??void 0}):s.jsx(wVt,{siteConfig:t,themeConfig:e??void 0});return s.jsxs(aM,{siteConfig:t,children:[s.jsx(TM,{}),s.jsxs(c,{siteConfig:t,children:[s.jsx(N.Suspense,{fallback:s.jsx(GI,{}),children:s.jsxs(kb,{children:[s.jsx(Ce,{path:"/",element:v}),s.jsx(Ce,{path:"/listings",element:s.jsx(OVt,{siteConfig:t})}),s.jsx(Ce,{path:"/sold",element:s.jsx(FVt,{siteConfig:t})}),s.jsx(Ce,{path:"/listings/:slug",element:s.jsx(BVt,{siteConfig:t})}),s.jsx(Ce,{path:"/search",element:p?s.jsx(KVt,{siteConfig:t}):i?s.jsx(TVt,{siteConfig:t}):s.jsx(AM,{siteConfig:t})}),s.jsx(Ce,{path:"/listing/:mlsNumber",element:p?s.jsx(Oi,{to:"/contact?interest=Property%20details",replace:!0}):i?s.jsx(AVt,{siteConfig:t}):s.jsx(kM,{siteConfig:t})}),s.jsx(Ce,{path:"/about",element:i?s.jsx(IVt,{siteConfig:t}):s.jsx(kVt,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(Ce,{path:"/contact",element:i?s.jsx(CVt,{siteConfig:t}):s.jsx(jVt,{siteConfig:t})}),s.jsx(Ce,{path:"/account",element:s.jsx(S8,{siteConfig:t})}),s.jsx(Ce,{path:"/blog",element:s.jsx(b_,{siteConfig:t,isLuxury:i})}),s.jsx(Ce,{path:"/blog/:slug",element:s.jsx(b_,{siteConfig:t,isLuxury:i})}),s.jsx(Ce,{path:"/sell",element:s.jsx(PVt,{siteConfig:t,themeConfig:e??void 0,isLuxury:i})}),s.jsx(Ce,{path:"/community",element:s.jsx(E8,{siteConfig:t,isLuxury:i})}),s.jsx(Ce,{path:"/schedule",element:t.id===J3t?s.jsx(MVt,{siteConfig:t}):s.jsx(Q3t,{bookingUrl:t.bookingUrl,agentName:((j=t.agent)==null?void 0:j.full_name)||"your agent"})}),MNe(t)&&s.jsx(Ce,{path:"/exp-ready",element:s.jsx(DVt,{siteConfig:t})}),((e==null?void 0:e.focusPages)??[]).map(P=>s.jsx(Ce,{path:`/${P.slug}`,element:s.jsx(LVt,{siteConfig:t,page:P,accentColor:(e==null?void 0:e.accentColor)||t.accentColor||"#c9a96e"})},P.slug)),s.jsx(Ce,{path:"/reviews",element:s.jsx(hge,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(Ce,{path:"/reviews/:slug",element:s.jsx(hge,{siteConfig:t,themeConfig:e??void 0})}),s.jsx(Ce,{path:"/p/:pageSlug",element:s.jsx(T8,{siteConfig:t})}),s.jsx(Ce,{path:"/*",element:s.jsx(IM,{siteConfig:t,referralMode:g})})]})}),!l&&s.jsx(X3t,{bookingUrl:t.bookingUrl})]})]})}function IM({siteConfig:t,referralMode:e}){const r=ms(),n=r.pathname.match(/^\/homes-in-(.+)$/);if(n)return s.jsx(RVt,{siteConfig:t,subdivisionSlug:n[1]});const i=r.pathname.match(/^\/homes-for-sale-in-(.+)$/);if(i)return s.jsx(NVt,{siteConfig:t,citySlugOverride:i[1],referralMode:e});const a=r.pathname.match(/^\/communities\/([^/]+)\/?$/);if(a)return s.jsx(Oi,{to:`/homes-for-sale-in-${a[1]}${r.search}`,replace:!0});const c=r.pathname.match(/^\/([a-z0-9][a-z0-9-]*)\/?$/i);return c?s.jsx(XVt,{siteId:t==null?void 0:t.id,slug:c[1],search:r.search}):null}function XVt({siteId:t,slug:e,search:r}){const[n,i]=N.useState(null);return N.useEffect(()=>{let a=!1;if(!t){i(!1);return}return Be.from("lead_site_pages").select("id").eq("site_id",t).eq("slug",e).eq("is_published",!0).maybeSingle().then(({data:c})=>{a||i(!!c)}),()=>{a=!0}},[t,e]),n?s.jsx(Oi,{to:`/p/${e}${r}`,replace:!0}):null}function QVt(){const{user:t,loading:e}=_i(),{data:r,isLoading:n}=jr({queryKey:["feature-entitlement","levelup_attract",t==null?void 0:t.id],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:i,error:a}=await Be.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",t.id).eq("feature_key","levelup_attract").maybeSingle();if(a)throw a;return i?{hasAccess:i.enabled&&(!i.expires_at||new Date(i.expires_at).getTime()>Date.now()),tier:i.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:!!(r!=null&&r.hasAccess),tier:(r==null?void 0:r.tier)??null,isLoading:e||n}}function JVt({children:t}){const{user:e,loading:r}=_i(),{hasAccess:n,isLoading:i}=QVt(),a=ms();return N.useEffect(()=>{!r&&!i&&e&&!n&&lr.error("LevelUp Attract isn't available for your account yet.")},[r,i,e,n]),r||e&&i?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e?n?s.jsx(s.Fragment,{children:t}):s.jsx(Oi,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",a.pathname),s.jsx(Oi,{to:"/auth",replace:!0}))}function mge({children:t}){const{user:e,loading:r}=_i(),{hasAccess:n,isLoading:i}=YK(),a=ms();return r||e&&i?s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e?n?s.jsx(s.Fragment,{children:t}):s.jsx(Oi,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",a.pathname),s.jsx(Oi,{to:"/auth",replace:!0}))}const e8t=N.lazy(()=>Ge(()=>import("./CommercialMarketplace-CvkDdqEd.js"),[])),pge=N.lazy(()=>Ge(()=>import("./PrivacyPolicy-DQjBydOG.js"),[])),t8t=N.lazy(()=>Ge(()=>import("./CanvaSupport-DY0aaxOk.js"),__vite__mapDeps([66,67]))),gge=N.lazy(()=>Ge(()=>import("./TermsOfService-Cf_SiCAB.js"),[])),r8t=N.lazy(()=>Ge(()=>import("./DataDeletion-DBQBN1nf.js"),[])),yge=N.lazy(()=>Ge(()=>import("./McpDataUse-BnhswfJc.js"),[])),n8t=N.lazy(()=>Ge(()=>import("./SmsOptIn-BLCfMWhh.js"),__vite__mapDeps([68,69]))),A8=N.lazy(()=>Ge(()=>import("./OAuthConsent-CxVkNeRu.js"),[])),i8t=N.lazy(()=>Ge(()=>import("./ConnectChatGPT-BtQ1jJ_n.js"),__vite__mapDeps([70,71]))),xge=N.lazy(()=>Ge(()=>import("./LevelUpMCP-DE0s0lop.js"),[])),s8t=N.lazy(()=>Ge(()=>import("./SubscriptionSuccess-BboNQaIM.js"),__vite__mapDeps([72,71]))),a8t=N.lazy(()=>Ge(()=>import("./Subscription-BStRXpZW.js"),[])),o8t=N.lazy(()=>Ge(()=>import("./SetupBrokerage-ChdFRNkf.js"),__vite__mapDeps([73,71]))),_ge=N.lazy(()=>Ge(()=>import("./ClaimAccount-C64qJcH7.js"),[])),vge=N.lazy(()=>Ge(()=>import("./ConfirmPasswordReset-Le8Kmt34.js"),[])),l8t=N.lazy(()=>Ge(()=>import("./ActivateAccount-DaqD7_K7.js"),[])),c8t=N.lazy(()=>Ge(()=>import("./InviteSignup-DIdDtZWx.js"),__vite__mapDeps([74,75]))),u8t=N.lazy(()=>Ge(()=>import("./CoachingHub-CQnICbKP.js"),__vite__mapDeps([76,77]))),d8t=N.lazy(()=>Ge(()=>import("./CoachAgentWorkspace-DZxAgK0t.js"),__vite__mapDeps([78,77,79,80,81]))),h8t=N.lazy(()=>Ge(()=>import("./MyCoach-BdBvapH6.js"),__vite__mapDeps([82,77,79,83,84,80]))),f8t=N.lazy(()=>Ge(()=>import("./AdminCoaching-DWfSJPMi.js"),__vite__mapDeps([85,86,87,5,88]))),m8t=N.lazy(()=>Ge(()=>import("./CoachBilling-BnuqRqK9.js"),__vite__mapDeps([89,77,90]))),p8t=N.lazy(()=>Ge(()=>import("./CoachSettings-E37VG34v.js"),__vite__mapDeps([91,77,92,93,94,67,81,95]))),g8t=N.lazy(()=>Ge(()=>import("./GoogleCalendarReturn-DtKKZXa5.js"),[])),y8t=N.lazy(()=>Ge(()=>import("./Microsoft365Return-olagGOdA.js"),__vite__mapDeps([96,97,98]))),x8t=N.lazy(()=>Ge(()=>import("./CoachWaitlist-Ddz6Bq9r.js"),__vite__mapDeps([99,77,100]))),_8t=N.lazy(()=>Ge(()=>import("./CoachesDirectory-DJmoZDpS.js"),[])),v8t=N.lazy(()=>Ge(()=>import("./CoachProfile-EBBZ2u3v.js"),__vite__mapDeps([101,83]))),b8t=N.lazy(()=>Ge(()=>import("./CoachApply-B3sh0-Si.js"),[])),w8t=N.lazy(()=>Ge(()=>import("./Trial-DwJz4JIC.js"),__vite__mapDeps([102,103]))),S8t=N.lazy(()=>Ge(()=>import("./TrialSuccess-C4A8fQ-5.js"),__vite__mapDeps([104,105]))),E8t=N.lazy(()=>Ge(()=>import("./LaborDaySale-BbMTCdcT.js"),__vite__mapDeps([106,107,103,108,109]))),T8t=N.lazy(()=>Ge(()=>import("./BrokerageLaborDaySale-DUMaZ8Yx.js"),__vite__mapDeps([110,107,103,108,109]))),A8t=N.lazy(()=>Ge(()=>import("./BrokerageSolutions-Dqf2Er1N.js"),__vite__mapDeps([111,109,112,113,114,108]))),k8t=N.lazy(()=>Ge(()=>import("./Upgrade-DrT21Rsu.js"),__vite__mapDeps([115,116]))),I8t=N.lazy(()=>Ge(()=>import("./InstagramGift-B-HAVkrq.js"),__vite__mapDeps([117,116,90]))),bge=N.lazy(()=>Ge(()=>import("./VideoShare-CAMH0Y3G.js"),__vite__mapDeps([118,119,105,6,120,121,26,39,122,123,124]))),j8t=N.lazy(()=>Ge(()=>import("./VideoShareLayout-CnI0e6sm.js"),[])),C8t=N.lazy(()=>Ge(()=>import("./VideoOgRedirect-CzV1_88M.js"),[])),P8t=N.lazy(()=>Ge(()=>Promise.resolve().then(()=>bnt),void 0)),N8t=N.lazy(()=>Ge(()=>Promise.resolve().then(()=>pnt),void 0)),R8t=N.lazy(()=>Ge(()=>import("./NewListingChooser-CZPAxa3K.js"),[])),wge=N.lazy(()=>Ge(()=>import("./CommercialWizard-Dk6MDsOp.js"),__vite__mapDeps([125,126,127]))),L8t=N.lazy(()=>Ge(()=>import("./CommercialWorkspace-Da2oQIwr.js"),__vite__mapDeps([128,126,127,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,97,98,147,84,81,148,149]))),D8t=N.lazy(()=>Ge(()=>import("./CommercialPitchPreview-kbuDD0Qv.js"),__vite__mapDeps([150,149]))),M8t=N.lazy(()=>Ge(()=>import("./PrivateListingView-C2xj-MHd.js"),[])),O8t=N.lazy(()=>Ge(()=>import("./PublicAgentCard-DJyGhNFa.js"),[])),F8t=N.lazy(()=>Ge(()=>Promise.resolve().then(()=>v3t),void 0)),Sge=N.lazy(()=>Ge(()=>import("./PublicHomeValue-CpMRy4yq.js"),[])),B8t=N.lazy(()=>Ge(()=>import("./PublicLiveEvent-CuWSsDJX.js"),__vite__mapDeps([151,152,153,154,155]))),z8t=N.lazy(()=>Ge(()=>import("./LiveEvents-D4VyL-Tx.js"),__vite__mapDeps([156,157,158,159,147]))),$8t=N.lazy(()=>Ge(()=>import("./LiveEventConsole-BYsh0RBU.js"),__vite__mapDeps([160,158,154,75,161,152,162]))),U8t=N.lazy(()=>Ge(()=>import("./Dashboard-BHQxf4QZ.js"),__vite__mapDeps([163,164,165,77,166,167,168,169,170,171,126,127,172,173,174,175,3,39,80,176]))),V8t=N.lazy(()=>Ge(()=>import("./Profile-CVdKh0IU.js"),__vite__mapDeps([177,80,90,95,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,81,193,194,195,196,30,112,9,197]))),q8t=N.lazy(()=>Ge(()=>import("./Events-D59zC4lX.js"),__vite__mapDeps([198,166,167,168,199,173,200,201,202]))),G8t=N.lazy(()=>Ge(()=>import("./EventDetail-DLZoUD3P.js"),__vite__mapDeps([203,166,167,168,204,205,71]))),H8t=N.lazy(()=>Ge(()=>import("./Apps-DbZVQbC0.js"),__vite__mapDeps([206,122,90,207,5,208]))),W8t=N.lazy(()=>Ge(()=>import("./Templates-euCBPcNt.js"),__vite__mapDeps([209,95]))),K8t=N.lazy(()=>Ge(()=>import("./TemplateDetail-BMEB7sGK.js"),__vite__mapDeps([210,138,164,204,205,95]))),Y8t=N.lazy(()=>Ge(()=>import("./Programs-C82Sg6bm.js"),__vite__mapDeps([211,165]))),Z8t=N.lazy(()=>Ge(()=>import("./ProgramDetail-hg7UKgbq.js"),__vite__mapDeps([212,213,214,165,30,90]))),X8t=N.lazy(()=>Ge(()=>import("./ProgramEnroll-CWzOIJzK.js"),__vite__mapDeps([215,165,216,90]))),Q8t=N.lazy(()=>Ge(()=>import("./ProgramWorkspace-DeOiAup1.js"),__vite__mapDeps([217,165,218,219]))),J8t=N.lazy(()=>Ge(()=>import("./Programs-BN0PCtVg.js"),__vite__mapDeps([220,165,81,159,216,221,90,207,134,222,214,84,30]))),eqt=N.lazy(()=>Ge(()=>import("./Academy-DL4vihz4.js"),[])),tqt=N.lazy(()=>Ge(()=>import("./AcademyVideoDetail-BXJKJ-xg.js"),__vite__mapDeps([223,138,164,204,205,224]))),rqt=N.lazy(()=>Ge(()=>import("./PublicAcademyWatch-CpqlPcmx.js"),[])),nqt=N.lazy(()=>Ge(()=>import("./Toolbox-CLMuPCXO.js"),[])),iqt=N.lazy(()=>Ge(()=>import("./ToolboxDetail-27j59Gba.js"),__vite__mapDeps([225,138,164,204,205,224]))),sqt=N.lazy(()=>Ge(()=>import("./SocialSwag-C6fok9rj.js"),__vite__mapDeps([226,95]))),aqt=N.lazy(()=>Ge(()=>import("./SocialStudio-CTqW-IDT.js"),__vite__mapDeps([227,138,228,229,31,230,231,232,233,127,234,192,235,218,236,237,238,239,67,159,240,241,242,243,81,244,167,84,71,245,130,131]))),oqt=N.lazy(()=>Ge(()=>import("./MarketingStudio-CvorF0VN.js"),__vite__mapDeps([246,39,247]))),lqt=N.lazy(()=>Ge(()=>import("./BrandKit-CtlDSrFy.js"),__vite__mapDeps([248,249]))),cqt=N.lazy(()=>Ge(()=>import("./BrandingBarEditor-Chk1PK1Q.js"),__vite__mapDeps([250,245,249,251,252]))),uqt=N.lazy(()=>Ge(()=>import("./ListingTemplates-B_MEmRHa.js"),__vite__mapDeps([253,254,255,249,216,5]))),dqt=N.lazy(()=>Ge(()=>import("./PersonalBranding-BYmdJ9qP.js"),__vite__mapDeps([256,257,249,254]))),hqt=N.lazy(()=>Ge(()=>import("./SocialSwagDetail-W7WeSiip.js"),__vite__mapDeps([258,138,164,204,205,95]))),fqt=N.lazy(()=>Ge(()=>import("./Community-B_bIEsZg.js"),__vite__mapDeps([259,31,222,214,13,189,260,261,95,262,152]))),mqt=N.lazy(()=>Ge(()=>import("./Support-NLM8Bfsq.js"),__vite__mapDeps([263,138,264,265,176,147,84,71]))),pqt=N.lazy(()=>Ge(()=>import("./BrokerageResources-BDp3vdb5.js"),__vite__mapDeps([266,95]))),gqt=N.lazy(()=>Ge(()=>import("./BrokerageResourceDetail-DqoBdgve.js"),[])),Ege=N.lazy(()=>Ge(()=>import("./AdminDashboard-mu2fBi7-.js"),__vite__mapDeps([267,268,269,270,90,271,216]))),yqt=N.lazy(()=>Ge(()=>import("./Apps-DmQyKmNj.js"),[])),xqt=N.lazy(()=>Ge(()=>import("./MemberManagement-9arZTSdm.js"),__vite__mapDeps([272,157,273,219,105,274,153,275,90,276,277,278,279,280,281,202,282,5,283,284,80,285,87,286,116]))),_qt=N.lazy(()=>Ge(()=>import("./UnassignedMembers-DVMXjJNJ.js"),__vite__mapDeps([287,157]))),vqt=N.lazy(()=>Ge(()=>import("./InviteCodes-yEDnAH1y.js"),__vite__mapDeps([288,157]))),bqt=N.lazy(()=>Ge(()=>import("./Events-D2sBFklc.js"),__vite__mapDeps([289,178,179,180,181,182,183,184,185,186,187,95,158,290,157,291]))),wqt=N.lazy(()=>Ge(()=>import("./MCPAuditLog-cnAGqY3P.js"),__vite__mapDeps([292,157,293]))),Sqt=N.lazy(()=>Ge(()=>import("./Templates-BXM68Iv5.js"),__vite__mapDeps([294,157,178,179,180,181,182,183,184,185,186,187,95,290]))),Eqt=N.lazy(()=>Ge(()=>import("./Academy-BzmJfV7w.js"),__vite__mapDeps([295,157,178,179,180,181,182,183,184,185,186,187,95,296,218,290]))),Tqt=N.lazy(()=>Ge(()=>import("./Toolbox-DUuVEqgq.js"),__vite__mapDeps([297,178,179,180,181,182,183,184,185,186,187,95,296,218,290]))),Aqt=N.lazy(()=>Ge(()=>import("./SocialSwag-DnIEWROM.js"),__vite__mapDeps([298,157,178,179,180,181,182,183,184,185,186,187,95,290]))),kqt=N.lazy(()=>Ge(()=>import("./SocialSwag2-CschF9rq.js"),__vite__mapDeps([299,290,133,95,134]))),Iqt=N.lazy(()=>Ge(()=>import("./Community-C3DJc_3_.js"),__vite__mapDeps([300,157]))),jqt=N.lazy(()=>Ge(()=>import("./Analytics-CPHqc0WL.js"),__vite__mapDeps([301,274,153,275,71,302,303,304,305,306]))),Cqt=N.lazy(()=>Ge(()=>import("./BrokerageResources-t4B0ng5t.js"),__vite__mapDeps([307,178,179,180,181,182,183,184,185,186,187,95,216]))),Pqt=N.lazy(()=>Ge(()=>import("./DashboardManagement-Boz9ZKkC.js"),__vite__mapDeps([308,134,161,75]))),Nqt=N.lazy(()=>Ge(()=>import("./SupportTickets-BesKFGHH.js"),__vite__mapDeps([309,138,264,265,176,147,84,71,9]))),Rqt=N.lazy(()=>Ge(()=>import("./EmailTemplates-fousVngN.js"),__vite__mapDeps([310,179,180,311,184,185,186,187,95,312,313,81,314]))),Lqt=N.lazy(()=>Ge(()=>import("./AgentEmailTemplates-DIZZt809.js"),__vite__mapDeps([315,157,80]))),Dqt=N.lazy(()=>Ge(()=>import("./BrokerageDashboard-pJm3zCfI.js"),__vite__mapDeps([316,273,219,105,153,275,71,95,84,276,284,285,302,274,199,173,200]))),Mqt=N.lazy(()=>Ge(()=>import("./MyBrokerage-F6oHdBqF.js"),__vite__mapDeps([317,152,116,200,192,81,318,319,84,5]))),Oqt=N.lazy(()=>Ge(()=>import("./BrokerageContent-D6ui10cK.js"),__vite__mapDeps([320,171,80]))),Fqt=N.lazy(()=>Ge(()=>import("./BrokerageContentDetail-CoWtTlev.js"),[])),Bqt=N.lazy(()=>Ge(()=>import("./BrokerageHelpBoard-c3YmW9Ep.js"),__vite__mapDeps([321,322,9]))),zqt=N.lazy(()=>Ge(()=>import("./BrokerageHelpBoardNew-DGg_bO33.js"),__vite__mapDeps([323,322]))),$qt=N.lazy(()=>Ge(()=>import("./BrokerageHelpBoardDetail-DHllJyuH.js"),__vite__mapDeps([324,322,13]))),Uqt=N.lazy(()=>Ge(()=>import("./Newsletters-CCVrsknn.js"),__vite__mapDeps([325,326,257,327,184,328,185,95,161,314,153,275,329,330,81,331,114,332,5,169,140,141,142,143,333,334,293,335,216,336,75]))),Vqt=N.lazy(()=>Ge(()=>import("./NewsletterDetail-vK4LjMsi.js"),__vite__mapDeps([337,164,204,205,331,326,257,327,184,328,185,95,161,314,153,275,329,114,332,5,169,140,141,142,143,333,334,293,335,216,336,75]))),qqt=N.lazy(()=>Ge(()=>import("./Newsletters-Bb6Ktpf5.js"),__vite__mapDeps([338,290,157,178,179,180,181,182,183,184,185,186,187,95,327,134,339]))),Gqt=N.lazy(()=>Ge(()=>import("./MemberBroadcasts-gZqs_8xs.js"),__vite__mapDeps([340,157,178,179,180,181,182,183,184,185,186,187,95,218,202,312,341,81]))),Hqt=N.lazy(()=>Ge(()=>import("./BoostAnnouncements-CJah-sH2.js"),__vite__mapDeps([342,157,7]))),Wqt=N.lazy(()=>Ge(()=>import("./NewsletterGraphics-DAomMW91.js"),__vite__mapDeps([343,157,159]))),Kqt=N.lazy(()=>Ge(()=>import("./Wishlist-CLwnnaks.js"),__vite__mapDeps([344,153]))),Yqt=N.lazy(()=>Ge(()=>import("./WishlistDetail-KMoVz0Gg.js"),__vite__mapDeps([345,260,153]))),Zqt=N.lazy(()=>Ge(()=>import("./Wishlist-DtTQhORM.js"),[])),Xqt=N.lazy(()=>Ge(()=>import("./LevelUpBrief-BBNRzGCA.js"),__vite__mapDeps([346,157,178,179,180,181,182,183,184,185,186,187,95]))),Qqt=N.lazy(()=>Ge(()=>import("./AdditionalServices-DCuJULjJ.js"),__vite__mapDeps([347,178,179,180,181,182,183,184,185,186,187,95]))),Jqt=N.lazy(()=>Ge(()=>import("./Discounts-CxhuTzR6.js"),__vite__mapDeps([348,157]))),eGt=N.lazy(()=>Ge(()=>import("./Subscriptions-C2-VjwNY.js"),__vite__mapDeps([349,157,350,90,285]))),tGt=N.lazy(()=>Ge(()=>import("./InstagramGiftEmails-BuMhFKmo.js"),__vite__mapDeps([351,350,314]))),rGt=N.lazy(()=>Ge(()=>import("./Referrals-zKNVXSaR.js"),__vite__mapDeps([352,157,71,84]))),nGt=N.lazy(()=>Ge(()=>import("./OnboardingChecklist-nmVaqQ54.js"),[])),iGt=N.lazy(()=>Ge(()=>import("./AgentOSControlCenter-BDCsVpuT.js"),__vite__mapDeps([353,157,122,121,134]))),sGt=N.lazy(()=>Ge(()=>import("./AdditionalServices-CPC40ml2.js"),[])),aGt=N.lazy(()=>Ge(()=>import("./AdditionalServiceDetail-2QHePaCM.js"),[])),oGt=N.lazy(()=>Ge(()=>import("./AIToolkit-ChD-gBKB.js"),[])),lGt=N.lazy(()=>Ge(()=>import("./AskAI-vuii8J0t.js"),__vite__mapDeps([354,2,5]))),cGt=N.lazy(()=>Ge(()=>import("./InnerCircleHome-D7tQYLU9.js"),__vite__mapDeps([355,174,175,356,8,153,275,357,285,169,139,138,140,141,142,143,144,145,146,97,98,147,358,359,360,361,161,362]))),uGt=N.lazy(()=>Ge(()=>import("./InnerCircleContacts-D4BgutrB.js"),__vite__mapDeps([363,364,222,214,365,257,153,275,366,367,279,276,280,281,202,282,5,283,356,368,369,8,370,333,216,230,371,175,372,219,373,359,138,374,375,376,377,378,379,235,335,380,314,381,382,383,121,196,95,140,139,141,142,143,144,145,146,97,98,147,169,334,341,384,385,386,387,388,39,389,197,9,81,126,127,75,390,185]))),dGt=N.lazy(()=>Ge(()=>import("./InnerCircleContactDetail-DCnaKTvB.js"),__vite__mapDeps([391,388,138,364,169,140,139,141,142,143,144,145,146,97,98,147,392,383,369,175,333,368,356,8,370,216,230,371,393,285,389,9,81,197,387,394,395,222,214,396,397,202,268,398,399,271,293,358,359,360,361]))),hGt=N.lazy(()=>Ge(()=>import("./SentEmails-C-rEhys7.js"),__vite__mapDeps([400,169,139,138,140,141,142,143,144,145,146,97,98,147,395,190,161,197,84,371]))),fGt=N.lazy(()=>Ge(()=>import("./InnerCirclePlans-D08xEo7Z.js"),__vite__mapDeps([401,71,402,81,357,285]))),mGt=N.lazy(()=>Ge(()=>import("./CMAList-B5noKSUF.js"),__vite__mapDeps([403,392,404,141,405]))),pGt=N.lazy(()=>Ge(()=>import("./CMABuilder-HIxM0-OU.js"),__vite__mapDeps([406,392,404,141,381,407,162,408,409,410,411,314,5,8,81]))),gGt=N.lazy(()=>Ge(()=>import("./ListingPresentations-Ch8sWXVT.js"),__vite__mapDeps([412,413,414,130,415]))),yGt=N.lazy(()=>Ge(()=>import("./ListingPresentationBuilder-pPulDnNL.js"),__vite__mapDeps([416,138,213,214,417,418,130,413,414,419,159,5,218,153,275,415,81,341,420]))),xGt=N.lazy(()=>Ge(()=>Promise.resolve().then(()=>lut),void 0)),_Gt=N.lazy(()=>Ge(()=>import("./InnerCirclePopbys-DukCoC7m.js"),__vite__mapDeps([421,364,369,422,423,71]))),vGt=N.lazy(()=>Ge(()=>import("./ListingExchange-COtAkBa7.js"),__vite__mapDeps([424,126,127,425,122,135,53,426,333,385,386,384,142,143,216,200,427,397]))),bGt=N.lazy(()=>Ge(()=>import("./ListingDetail-wi-PG1Mh.js"),__vite__mapDeps([428,129,126,127,130,131,427,135,425,122,136,137,138,139,140,141,142,143,144,145,146,97,98,147,230,9,53,149]))),Tge=N.lazy(()=>Ge(()=>import("./ListingForm-DBlS6Oqk.js"),__vite__mapDeps([429,133,126,127,132,134,383,339,129,130,131,75]))),wGt=N.lazy(()=>Ge(()=>import("./CustomizeListingPage-C6GIUysY.js"),__vite__mapDeps([430,314,81,304,431,95,134])));function SGt(){const{search:t}=ms();return s.jsx(Oi,{to:`/video-studio${t}`,replace:!0})}const EGt=N.lazy(()=>Ge(()=>import("./VideoStudio-1FWiGqRf.js"),__vite__mapDeps([432,433,332,231,232,383,434,119,105,6,120,121,26,39,122,123,124,222,214,146,97,98,138,374,169,95,192,239,67,159,435,436,269,437,87,116,438,152,283,411,439,440,441,442,409,162,282,443,444,445,235,149,446,53,8,408,75,314,339,447,81,5,236,448]))),Age=N.lazy(()=>Ge(()=>import("./MainStageGate-B9sXMs7W.js"),__vite__mapDeps([449,450,436,435,201,440,411,439,451,80,452,283,453,438,236,389,116]))),TGt=N.lazy(()=>Ge(()=>import("./MainStageAdmin-WnYC5H_R.js"),__vite__mapDeps([454,450,314,436,81,159]))),AGt=N.lazy(()=>Ge(()=>import("./StudioKitsAdmin-Dzg6W-8w.js"),__vite__mapDeps([455,231,232,441,81]))),kGt=N.lazy(()=>Ge(()=>import("./StudioGuestJoin-BMo39j8B.js"),__vite__mapDeps([456,442,231,232,409,162,282,440,446,439,451,411,448]))),IGt=N.lazy(()=>Ge(()=>import("./VideoLibrary-Bn2xgkeO.js"),__vite__mapDeps([457,383,382,434,119,105,6,120,121,26,39,122,123,124,222,214,146,97,98,138,374,169,95,303,239,67,159,458,459,312]))),jGt=N.lazy(()=>Ge(()=>import("./DealPipeline-DoP6FUt1.js"),__vite__mapDeps([460,461,113,187,186,462,398,433,463,275,86,280,153,464,465,162,466,9,30,50,184,341,431,380,467,123,397,286,93,468,37,469,470,59,306,71,471,84,446,472,473,474,120,335,312,124,271,367,284,475,90,285,268,122,282,242,452,36,75,476,477,478,176,479,148,219,480,265,121,269,408,80,481,482,483,484,134,485,283,459,13,182,183,486,487,202,488,234,159,444,88,109,371,489,218,339,95,336,185,490,422,491,116,100,362,492,197,390,12,200,493,494,247,495,496,439,411,453,207,410,314,25,497,161,303,498,420,232,53,423,499,445,304,147,105,8,357,402,114,451,262,152,52,500,501,502,149,112,503,366,291,261,5,190,221,81,447,504,236,293,505,506,270,507,69,208,39,155,387,361,281,6,448,508,216,458,509,38,510,26,51,22,438,511,235,328,332,230,67,205,87,512,513,196,389,514,313,40,108,189,370,126,127,393,515,222,214,516,517,518,519,381,520,407,409,383,169,521,213,522,523]))),CGt=N.lazy(()=>Ge(()=>import("./FormsLibrary---hOgZl7.js"),__vite__mapDeps([524,518,525,81,418,497,380,235,509,517,476,153,275,452,398,479]))),PGt=N.lazy(()=>Ge(()=>import("./TransactionCoordinator-CF2MDIbJ.js"),__vite__mapDeps([526,521,213,214,291]))),NGt=N.lazy(()=>Ge(()=>import("./PortalReferrals-ukHbHG3N.js"),__vite__mapDeps([527,528]))),RGt=N.lazy(()=>Ge(()=>import("./AgentVendors-C9tnUY4y.js"),__vite__mapDeps([529,530,75]))),LGt=N.lazy(()=>Ge(()=>import("./BrokerageForms-ByROiw2Y.js"),__vite__mapDeps([531,518,525,81,418,497,380,235,509,481,482,398]))),DGt=N.lazy(()=>Ge(()=>import("./BrokerageVendors-1e6XlKKq.js"),__vite__mapDeps([532,530,75]))),MGt=N.lazy(()=>Ge(()=>import("./ClientPortalsHub-DuAgP3nC.js"),__vite__mapDeps([533,522,81,393,519,134,230,381,520,407,162,408,409,410,411,314,5,8,383,95,9,169,462,494,398,534,529,530,75,527,528,108]))),OGt=N.lazy(()=>Ge(()=>import("./ClientPortalDetail-DTSgeguy.js"),__vite__mapDeps([535,393,528,519,134,230,381,520,407,162,408,409,410,411,314,5,8,383,95,81,9,169,534,494,462,398]))),FGt=N.lazy(()=>Ge(()=>import("./MyCardEditor-B_5CjIP9.js"),__vite__mapDeps([536,188,189,190,191,537,216,134,153,275,75,247,137,314,90,149,161]))),BGt=N.lazy(()=>Ge(()=>import("./Integrations-kivBccYz.js"),__vite__mapDeps([538,222,214,365,257,153,275,71,458,539,98,540,138,329,81,229,31,239,67,159,541,97,232,514,236]))),zGt=N.lazy(()=>Ge(()=>import("./BrowserExtension-DWHTaUcL.js"),__vite__mapDeps([542,306]))),$Gt=N.lazy(()=>Ge(()=>import("./IntegrationsGmailCallback-CyMsuWwE.js"),__vite__mapDeps([543,71,84]))),UGt=N.lazy(()=>Ge(()=>import("./IntegrationsCanvaCallback-Dp6ZpNFs.js"),[])),VGt=N.lazy(()=>Ge(()=>import("./IntegrationsMetaCallback-Dh8zPY7L.js"),__vite__mapDeps([544,71,84]))),qGt=N.lazy(()=>Ge(()=>import("./ScorecardAdmin-C3XYQ3R8.js"),[])),GGt=N.lazy(()=>Ge(()=>import("./AgentActivation-CQPVfkas.js"),__vite__mapDeps([545,157,100,389]))),kge=N.lazy(()=>Ge(()=>import("./ScorecardAgentView-BxbcNmk3.js"),[])),HGt=N.lazy(()=>Ge(()=>import("./ListingExchange-BQ3WXJKe.js"),[])),WGt=N.lazy(()=>Ge(()=>import("./ListingLeads-BYlViCw0.js"),[])),KGt=N.lazy(()=>Ge(()=>import("./PublicSiteLeads-BRYkaunl.js"),[])),YGt=N.lazy(()=>Ge(()=>import("./MembershipReviews-DC4acSVN.js"),__vite__mapDeps([546,157]))),ZGt=N.lazy(()=>Ge(()=>import("./LeadNotifications-CwHxqUS9.js"),__vite__mapDeps([547,157]))),XGt=N.lazy(()=>Ge(()=>import("./WeeklyDigest-BgFsbNL0.js"),__vite__mapDeps([548,84]))),QGt=N.lazy(()=>Ge(()=>import("./AgentPoints-By1fPR8W.js"),__vite__mapDeps([549,202]))),JGt=N.lazy(()=>Ge(()=>import("./AgentCards-BQaPS_uG.js"),__vite__mapDeps([550,188,189,190,191,537,216,134,153,275,75,247,508]))),e9t=N.lazy(()=>Ge(()=>import("./Marketplace-B34eN3jX.js"),__vite__mapDeps([551,159,216,80]))),t9t=N.lazy(()=>Ge(()=>import("./RewardStore-Ah5PizEM.js"),__vite__mapDeps([552,553,80,95,81]))),r9t=N.lazy(()=>Ge(()=>import("./Integrations-CjbN4ufT.js"),__vite__mapDeps([554,157,229,31,228,230,269,539,98,71]))),n9t=N.lazy(()=>Ge(()=>import("./SocialConnections-CGT_xYwm.js"),__vite__mapDeps([555,157]))),i9t=N.lazy(()=>Ge(()=>import("./SocialAutopilot-Wso-Y4kH.js"),__vite__mapDeps([556,157,231,232,233,81]))),s9t=N.lazy(()=>Ge(()=>import("./McpUpdates-qn8ET3m6.js"),__vite__mapDeps([557,157]))),a9t=N.lazy(()=>Ge(()=>import("./RefreshMcpTools-BgEA6-m9.js"),[])),o9t=N.lazy(()=>Ge(()=>import("./NotificationSettings-BKhdFktC.js"),__vite__mapDeps([558,157]))),l9t=N.lazy(()=>Ge(()=>import("./PresentationAnalytics-CgyGdhIu.js"),__vite__mapDeps([559,274,153,275,161]))),c9t=N.lazy(()=>Ge(()=>import("./ListingPresentationStudioAdmin-6HEAf4P-.js"),__vite__mapDeps([560,157]))),u9t=N.lazy(()=>Ge(()=>import("./ListingRevivalAdmin-DQao4QVZ.js"),__vite__mapDeps([561,157,562]))),d9t=N.lazy(()=>Ge(()=>import("./GuestBookAnalytics-B1k9CuqR.js"),__vite__mapDeps([563,71]))),h9t=N.lazy(()=>Ge(()=>import("./IntegrationsCallback-B5XCRG4q.js"),__vite__mapDeps([564,71,84]))),f9t=N.lazy(()=>Ge(()=>import("./Prospector-BO-zNUAz.js"),[])),m9t=N.lazy(()=>Ge(()=>import("./AdminRecruiting-Bunkfz6q.js"),__vite__mapDeps([565,566,134,138,407,162,408,409,410,411,314,5,8,383,81,303,219,153,275,84,478,88,339,168,222,214,540,98,179,180,311,567,184,328,470,182,183,486,185,186,187,95,313,161,13,6,39,142,143,71,505]))),p9t=N.lazy(()=>Ge(()=>import("./BrokerageRecruiting-DFyW-Aes.js"),__vite__mapDeps([568,566,134,138,407,162,408,409,410,411,314,5,8,383,81,303,219,153,275,84,478,88,339,168,222,214,540,98,179,180,311,567,184,328,470,182,183,486,185,186,187,95,313,161,13,6,39,142,143,71,514,472,362,513,242,569]))),g9t=N.lazy(()=>Ge(()=>import("./BrokerageOnboarding-DYR8llq1.js"),__vite__mapDeps([570,318,319,84,5,81,170,514,472,476,512,153,275,569]))),y9t=N.lazy(()=>Ge(()=>import("./BrokerageTransactions-Cdrn6Siq.js"),__vite__mapDeps([571,516,202,480,84,572,523,476,80]))),x9t=N.lazy(()=>Ge(()=>import("./BrokerageOperations-1NraUHGM.js"),__vite__mapDeps([573,574,523,318,490]))),_9t=N.lazy(()=>Ge(()=>import("./WebsitesHub-BsYZyBnq.js"),__vite__mapDeps([575,576]))),v9t=N.lazy(()=>Ge(()=>import("./TeamWebsite-DDqP1CYY.js"),__vite__mapDeps([577,578,61,75,579,576]))),b9t=N.lazy(()=>Ge(()=>import("./BrokerageWebsite-BfzpDu4R.js"),__vite__mapDeps([580,578,61,75,579,576]))),w9t=N.lazy(()=>Ge(()=>import("./BrokerageCommissionPlans-G_V-Fjzc.js"),__vite__mapDeps([581,515,523,414,478,574,105,488,366,162,112,572,389]))),S9t=N.lazy(()=>Ge(()=>import("./BrokerageContentActivity-CZJeyOn5.js"),__vite__mapDeps([582,157]))),E9t=N.lazy(()=>Ge(()=>import("./BetaSocialPostGenerator-KkvEvrmR.js"),__vite__mapDeps([583,157,172,254,255,216,5]))),T9t=N.lazy(()=>Ge(()=>import("./AdminLMS-tQGP8OtX.js"),__vite__mapDeps([584,585,185,507,75]))),A9t=N.lazy(()=>Ge(()=>import("./AdminCourseDetail-DC-0LCjH.js"),__vite__mapDeps([586,585,185,507,75,159,81]))),k9t=N.lazy(()=>Ge(()=>import("./AdminLMSStats-CznPSrFG.js"),[])),I9t=N.lazy(()=>Ge(()=>import("./LevelUpU-CzWjLDdY.js"),__vite__mapDeps([587,585,185,507]))),j9t=N.lazy(()=>Ge(()=>import("./LevelUpUCourse-faA7Ft31.js"),__vite__mapDeps([588,585]))),C9t=N.lazy(()=>Ge(()=>import("./MobileAgentApp-Mu8lcksh.js"),__vite__mapDeps([589,88,169,333,139,138,140,141,142,143,144,145,146,97,98,147,216,37,39,282]))),P9t=N.lazy(()=>Ge(()=>import("./StagingStudio-BAbo_VtG.js"),__vite__mapDeps([590,213,214,591,473,452,51,159,592,593,36,594,193,194,236,80,444]))),N9t=N.lazy(()=>Ge(()=>import("./StagingLibrary-sFToGAPE.js"),__vite__mapDeps([595,591,473,452,51,592,193,481,80,444]))),R9t=N.lazy(()=>Ge(()=>import("./StagingCredits-CkLucpBS.js"),__vite__mapDeps([596,594,193,194,90]))),L9t=N.lazy(()=>Ge(()=>import("./AgentWallet-J1H0t4iX.js"),__vite__mapDeps([597,399,193,598,269,194,293]))),D9t=N.lazy(()=>Ge(()=>import("./StagingSharePage-Cr9L4AJY.js"),__vite__mapDeps([599,593]))),M9t=N.lazy(()=>Ge(()=>import("./StagingStudioAdmin-DR2U-x4j.js"),__vite__mapDeps([600,591,473,452,51,4,193,593,444,86]))),O9t=N.lazy(()=>Ge(()=>import("./ContactFinderAdmin-DjCXQthe.js"),__vite__mapDeps([601,399]))),F9t=N.lazy(()=>Ge(()=>import("./PostcardManager-CDLTMxlO.js"),__vite__mapDeps([602,603,251,252,604,235,186,81]))),B9t=N.lazy(()=>Ge(()=>import("./MailStudioTemplates-BfMP041K.js"),__vite__mapDeps([605,603,251,252,604,235,186,81,153,275]))),z9t=N.lazy(()=>Ge(()=>import("./HomeReelManager-BexcC4RN.js"),__vite__mapDeps([606,598,269,607,53,8,339,314,133,498,235,446,134,280,447,81,268,271,427,341]))),$9t=N.lazy(()=>Ge(()=>import("./AdminMusicVideos-D8F1X-ua.js"),__vite__mapDeps([608,53]))),U9t=N.lazy(()=>Ge(()=>import("./AdminVideoLab-Clvdr7Kh.js"),__vite__mapDeps([609,607,53,446,8,159,503,5]))),V9t=N.lazy(()=>Ge(()=>import("./BoostPreview-BjfcEAPb.js"),__vite__mapDeps([610,1,2,3,4,5,6]))),q9t=N.lazy(()=>Ge(()=>import("./AdminCredits-CyHDTGtk.js"),__vite__mapDeps([611,157,471,202]))),G9t=N.lazy(()=>Ge(()=>import("./AdminCleanup-D57O7IN7.js"),[])),H9t=N.lazy(()=>Ge(()=>import("./MailStudio-Bzky2hS4.js"),__vite__mapDeps([612,604,251,252,414,81,235,159,5,420,186,187,465,385,386,613,360,284,12,458,614,192,437,216,122,230,417,418,359,162,502,149,202,615]))),W9t=()=>{const t=ms();return s.jsx(Oi,{to:`/mission-control/direct-mail${t.search}`,replace:!0})},K9t=N.lazy(()=>Ge(()=>import("./InnerCirclePopbyMap-DJDdYXeK.js"),__vite__mapDeps([616,369,422,423,71]))),Y9t=N.lazy(()=>Ge(()=>import("./SphereMap-q9F77Nyu.js"),__vite__mapDeps([617,386,138,445,388,359,613,423,333,375,376,377,378,379,257,235,335,380,314,381,382,383,121,196,153,275,95,139,140,141,142,143,144,145,146,97,98,147,169,216,390,221,399,371,332,431,489]))),Z9t=N.lazy(()=>Ge(()=>import("./PropertyIntelligenceDashboard-B1U86liQ.js"),__vite__mapDeps([618,396,397,467,268]))),X9t=N.lazy(()=>Ge(()=>import("./LiveVisitorFeed-nTmfxRL9.js"),__vite__mapDeps([619,281]))),Q9t=N.lazy(()=>Ge(()=>import("./LeadSites-CH81xXqb.js"),__vite__mapDeps([620,501,500]))),Ige=N.lazy(()=>Ge(()=>import("./LeadSiteEditor-wzUPUOAQ.js"),__vite__mapDeps([621,105,622,378,379,47,48,461,113,187,186,462,398,433,463,275,86,280,153,464,465,162,466,9,30,50,184,341,431,380,467,123,397,286,93,468,37,469,470,59,306,71,471,84,446,472,473,474,120,335,312,124,271,367,284,475,90,285,268,122,282,242,452,36,75,476,477,478,176,479,148,219,480,265,121,269,408,80,481,482,483,484,134,485,283,459,13,182,183,486,487,202,488,234,159,444,88,109,371,489,218,339,95,336,185,490,422,491,116,100,362,492,197,390,12,200,493,494,247,495,496,439,411,453,207,410,314,25,497,161,303,498,420,232,53,423,499,445,304,147,8,357,402,114,451,262,152,52,500,501,502,149,112,503,366,291,261,5,190,221,81,447,504,236,293,505,506,270,507,69,208,39,155,387,361,281,6,448,508,216,458,509,38,510,26,51,22,438,511,235,328,332,230,67,205,87,512,513,196,389,514,313,40,108,189,623,133,624,56,405]))),J9t=N.lazy(()=>Ge(()=>import("./AdminLeadSiteThemes-D3T5qIiA.js"),__vite__mapDeps([625,622,624,304,235,484,285]))),e7t=N.lazy(()=>Ge(()=>import("./AdminFreeWebsiteOffers-DZu4g20F.js"),[])),t7t=N.lazy(()=>Ge(()=>import("./AdminPartnerships-C5kZSRAl.js"),[])),r7t=N.lazy(()=>Ge(()=>import("./MyPartnership-C3ZAuP6z.js"),[])),n7t=N.lazy(()=>Ge(()=>import("./UpgradeFeature-BYEVKRYN.js"),[])),i7t=N.lazy(()=>Ge(()=>import("./CoachingOnboarding-PWqlzaTd.js"),[])),s7t=N.lazy(()=>Ge(()=>import("./AdminFreeWebsiteOfferStudio-hbjWCEdm.js"),__vite__mapDeps([626,622,623,133,624,12,13,25,304,26,122,235,134,75,81]))),a7t=N.lazy(()=>Ge(()=>import("./AdminMlsFeeds-C56tI4Zt.js"),__vite__mapDeps([627,268]))),o7t=N.lazy(()=>Ge(()=>import("./AdminLeadSiteAnalytics-Cp0d-ABL.js"),[])),l7t=N.lazy(()=>Ge(()=>import("./AdminWebsiteInterests-I_KgUlo4.js"),[])),c7t=N.lazy(()=>Ge(()=>import("./AdminWebsiteRequests-CwJm3TSm.js"),__vite__mapDeps([628,84]))),u7t=N.lazy(()=>Ge(()=>import("./NeedAWebsite-DPIlgTWQ.js"),__vite__mapDeps([629,195,218,161,464]))),d7t=N.lazy(()=>Ge(()=>import("./AdminMlsFeeTracker-OBncGZzs.js"),[])),h7t=N.lazy(()=>Ge(()=>import("./MLSListings-B1L8ZRF-.js"),__vite__mapDeps([630,405,13,427,426,333,385,386,384,142,143,216,236,75,341,53]))),f7t=N.lazy(()=>Ge(()=>import("./MLSListingDetail-DIBbaQMR.js"),__vite__mapDeps([631,169,140,141,333,216,75,381,41,138,137,414,502,149,511]))),m7t=N.lazy(()=>Ge(()=>import("./MarketReportPage-CCasUv8I.js"),[]));N.lazy(()=>Ge(()=>import("./WebsiteActivityPage-DEydijSR.js"),__vite__mapDeps([632,169,139,138,140,141,142,143,144,145,146,97,98,147,12])));const p7t=N.lazy(()=>Ge(()=>import("./PublicRecruitForm-Dn4lfz-9.js"),__vite__mapDeps([633,27,478]))),g7t=N.lazy(()=>Ge(()=>import("./PublicRecruitVideo-Cuy8pNAs.js"),[])),y7t=N.lazy(()=>Ge(()=>import("./PublicRecruitUnsubscribe-dXhJK4Tg.js"),[])),x7t=N.lazy(()=>Ge(()=>import("./PublicEventInviteUnsubscribe-Ba6GHSzZ.js"),__vite__mapDeps([634,468]))),_7t=N.lazy(()=>Ge(()=>import("./SocialConnections-EXatQGNu.js"),__vite__mapDeps([635,239,67,159,71,232,269,84]))),v7t=N.lazy(()=>Ge(()=>import("./SocialConnectionsCallback-CeBII7gb.js"),__vite__mapDeps([636,71,84]))),b7t=N.lazy(()=>Ge(()=>import("./SocialConnectionsGoogleCallback-B6-ygiyq.js"),[])),w7t=N.lazy(()=>Ge(()=>import("./LinkedInCallback-CrQMZW8g.js"),__vite__mapDeps([637,71,84]))),S7t=N.lazy(()=>Ge(()=>import("./TikTokCallback-B3BxKr_H.js"),__vite__mapDeps([638,243,71,84,232]))),E7t=N.lazy(()=>Ge(()=>import("./MarketplaceProductDetail-BXgwgdiB.js"),[])),T7t=N.lazy(()=>Ge(()=>import("./MarketplaceCart-CYAtZwOO.js"),__vite__mapDeps([639,138,270]))),A7t=N.lazy(()=>Ge(()=>import("./MarketplaceOrders-0z7Eewrd.js"),[])),k7t=N.lazy(()=>Ge(()=>import("./MarketplaceOrderDetail-E_v2lmLW.js"),__vite__mapDeps([640,138,176,510,22]))),I7t=N.lazy(()=>Ge(()=>import("./MarketplaceSuccess-C9tMFOFO.js"),[])),j7t=N.lazy(()=>Ge(()=>import("./RewardStore-BuRvCYtt.js"),__vite__mapDeps([641,553,222,214,270]))),C7t=N.lazy(()=>Ge(()=>import("./ReferFriends-BfRTdvNg.js"),__vite__mapDeps([642,138,169]))),P7t=N.lazy(()=>Ge(()=>import("./SmartPresentations-BJb3CMbJ.js"),__vite__mapDeps([643,644,398]))),jge=N.lazy(()=>Ge(()=>import("./SmartPresentationCreate-BrOwa9hw.js"),__vite__mapDeps([645,178,179,180,181,182,183,184,185,186,187,95,407,162,408,409,410,411,314,5,8,646,75,383,71,381,644,169,139,138,140,141,142,143,144,145,146,97,98,147,134,159]))),N7t=N.lazy(()=>Ge(()=>import("./PublicPresentation-CbfEo1FN.js"),[])),R7t=N.lazy(()=>Ge(()=>import("./GuestBook-CVNv0yn-.js"),__vite__mapDeps([647,138,137,376,387,134,443,444,381,88,398,169,142,95,216,149,373,359,159,202,75,502]))),L7t=N.lazy(()=>Ge(()=>Promise.resolve().then(()=>Cit),void 0)),D7t=N.lazy(()=>Ge(()=>Promise.resolve().then(()=>Lit),void 0)),M7t=N.lazy(()=>Ge(()=>import("./PublicResourceLanding-B7gPtZgX.js"),[])),O7t=N.lazy(()=>Ge(()=>import("./SignDocument-CsZE8iUT.js"),__vite__mapDeps([648,418,84,509,235,452]))),F7t=N.lazy(()=>Ge(()=>import("./Blog-BHbUBSGk.js"),__vite__mapDeps([649,650]))),B7t=N.lazy(()=>Ge(()=>import("./BlogPost-C0wYx33u.js"),__vite__mapDeps([651,650,475,511]))),z7t=N.lazy(()=>Ge(()=>import("./AdminBlog-sNJITOlN.js"),__vite__mapDeps([652,138,179,181,567,184,328,183,486,185,312,186,187,95,159,75]))),$7t=N.lazy(()=>Ge(()=>import("./ReviewLanding-BsCHQDTs.js"),__vite__mapDeps([653,654,407,162,408,409,410,411,314,5,8]))),U7t=N.lazy(()=>Ge(()=>import("./PublicReviewsPage-iIvGW0il.js"),__vite__mapDeps([655,464,495]))),V7t=N.lazy(()=>Ge(()=>import("./PublicReviewSubmit-D2p5uwzE.js"),__vite__mapDeps([656,654,407,162,408,409,410,411,314,5,8]))),q7t=N.lazy(()=>Ge(()=>import("./Reviews-qNwm4k-W.js"),__vite__mapDeps([657,137,130,237,238,240,231,232,236,464,152,261,75,67,335,149,371]))),G7t=N.lazy(()=>Ge(()=>import("./ClientPortalPage-P64YPT6H.js"),[])),H7t=N.lazy(()=>Ge(()=>Promise.resolve().then(()=>nut),void 0)),W7t=N.lazy(()=>Ge(()=>import("./CardStudio-Bo74Gk0x.js"),__vite__mapDeps([658,383,520,407,162,408,409,410,411,314,5,8,381,238,169,145]))),K7t=N.lazy(()=>Ge(()=>import("./ListingStudio-CMJreyfz.js"),__vite__mapDeps([659,285,122,477,105,411,52,362,30,159]))),Y7t=N.lazy(()=>Ge(()=>Promise.resolve().then(()=>s3t),void 0)),Z7t=N.lazy(()=>Ge(()=>import("./SmartDrips-DzNnNUKX.js"),__vite__mapDeps([660,138,169,501,402,381,520,407,162,408,409,410,411,314,5,8,383,376,377,378,379,257,235,335,380,382,121,196,153,275,95,394,333,216,371,286]))),X7t=N.lazy(()=>Ge(()=>import("./WeeklyReels-Dii1kP-5.js"),__vite__mapDeps([661,213,214,662,138,222,663,446,244,236]))),Q7t=N.lazy(()=>Ge(()=>import("./WeeklyReelsOnboarding-BAALcN-4.js"),__vite__mapDeps([664,663]))),J7t=N.lazy(()=>Ge(()=>import("./WeeklyReelsAdmin-BTelLZnv.js"),__vite__mapDeps([665,244,663,662,138,222,214,446]))),eHt=N.lazy(()=>Ge(()=>import("./AttractLayout-Di0bGL3X.js"),__vite__mapDeps([666,667,668,669,155,6,242]))),tHt=N.lazy(()=>Ge(()=>import("./AttractToday-Dug4e5hS.js"),__vite__mapDeps([670,222,214,668,671,672,673,674,675,487,339,371,676,677,514,286,496,678,506]))),rHt=N.lazy(()=>Ge(()=>import("./AttractRelationships-BoniQF0c.js"),__vite__mapDeps([679,680,676,672,677,219,681,398,673,668,671,514]))),nHt=N.lazy(()=>Ge(()=>import("./AttractFollowUp-BJe1Eiom.js"),__vite__mapDeps([682,680,673,672,124]))),iHt=N.lazy(()=>Ge(()=>import("./AttractResources-BFh8GYiQ.js"),[])),sHt=N.lazy(()=>Ge(()=>import("./AttractTemplates-Dld2vPyK.js"),__vite__mapDeps([683,124,291]))),aHt=N.lazy(()=>Ge(()=>import("./AttractReports-BqKZlFDq.js"),__vite__mapDeps([684,680,672,674,677,305]))),oHt=N.lazy(()=>Ge(()=>import("./AttractSettings-RKe4_xZK.js"),__vite__mapDeps([685,680,667,5]))),lHt=N.lazy(()=>Ge(()=>import("./AttractToolkit-a2k0xAP5.js"),__vite__mapDeps([686,680,247,506,286,339]))),cHt=N.lazy(()=>Ge(()=>import("./Objections-CtuN1WlY.js"),__vite__mapDeps([687,506]))),uHt=N.lazy(()=>Ge(()=>import("./AttractCalculator-DY_kAWOZ.js"),__vite__mapDeps([688,680,689,502]))),dHt=N.lazy(()=>Ge(()=>import("./AttractEventList-BSedPwyH.js"),__vite__mapDeps([690,678]))),Cge=N.lazy(()=>Ge(()=>import("./AttractEventBuilder-DbodBmUT.js"),__vite__mapDeps([691,138,678,692,95,81]))),hHt=N.lazy(()=>Ge(()=>import("./AttractEventDetail-83VrXEc3.js"),__vite__mapDeps([693,678,672,149,247]))),fHt=N.lazy(()=>Ge(()=>import("./AttractEventCheckIn-DYnyKdLo.js"),__vite__mapDeps([694,437,678,149]))),mHt=N.lazy(()=>Ge(()=>import("./AttractOnboarding-CcszfYP1.js"),__vite__mapDeps([695,667,485,286,155]))),pHt=N.lazy(()=>Ge(()=>import("./ContentStudio-I8QMQl42.js"),__vite__mapDeps([696,680,504]))),gHt=N.lazy(()=>Ge(()=>import("./KitList-FHoF5H2f.js"),__vite__mapDeps([697,692,339,114]))),Pge=N.lazy(()=>Ge(()=>import("./KitBuilder-CcMcn_ht.js"),__vite__mapDeps([698,692,672,680,699,247,95,153,275,314,162]))),yHt=N.lazy(()=>Ge(()=>import("./KitAnalytics-BQPo9o79.js"),__vite__mapDeps([700,692,680,161,305]))),xHt=N.lazy(()=>Ge(()=>import("./KitTemplates-Cx8Ab3mZ.js"),__vite__mapDeps([701,692,680]))),_Ht=N.lazy(()=>Ge(()=>import("./AttractAgentDetail-DyMC07tE.js"),__vite__mapDeps([702,681,672,398,139,138,140,141,142,143,144,145,146,97,98,147,169,668,673,669,675,487,339,371,677,39,6,281,280,514]))),vHt=N.lazy(()=>Ge(()=>import("./AttractOpportunities-tTVv6yOm.js"),__vite__mapDeps([703,668,671,675,487,339,371]))),bHt=N.lazy(()=>Ge(()=>import("./AttractIntelligenceDebug-D3kEMvjh.js"),__vite__mapDeps([704,668,669,466]))),wHt=N.lazy(()=>Ge(()=>import("./AttractToolsQA-CrzueBoh.js"),[])),SHt=N.lazy(()=>Ge(()=>import("./PublicAttractKit-B2YWU8zw.js"),__vite__mapDeps([705,699,247,95]))),EHt=N.lazy(()=>Ge(()=>import("./PublicAttractEvent-CeNkd0tq.js"),__vite__mapDeps([706,678]))),THt=N.lazy(()=>Ge(()=>import("./PublicAttractEventCheckIn-CpRdh55q.js"),[])),AHt=N.lazy(()=>Ge(()=>import("./PublicAttractionPage-DAvSC1fL.js"),__vite__mapDeps([707,708,213,214]))),kHt=N.lazy(()=>Ge(()=>import("./RevivalLanding-DrwwSK-f.js"),__vite__mapDeps([709,710]))),Nge=N.lazy(()=>Ge(()=>import("./RevivalPlan-CxwN2Xjz.js"),__vite__mapDeps([711,712,137,710,414,437]))),IHt=N.lazy(()=>Ge(()=>import("./ListingRevival-2VovfzHb.js"),__vite__mapDeps([713,714,710,562,474,219,218,236,149,715,398,462]))),jHt=N.lazy(()=>Ge(()=>import("./RevivalCampaignWizard-Bk7GzWbP.js"),__vite__mapDeps([716,419,413,414,159,714,710,717,254,614]))),CHt=N.lazy(()=>Ge(()=>import("./RevivalCampaignDetail-fATNK7sB.js"),__vite__mapDeps([718,137,717,254,414,614,719,196,483,81,373,359,714,710,712,437,407,162,408,409,410,411,314,5,8,383,71,419,413,159,75,149,221,502,478,30]))),PHt=N.lazy(()=>Ge(()=>import("./FsboBreakthrough-BzE0K6u9.js"),__vite__mapDeps([720,721,722,723,419,413,414,159,218,236,149,715,398,462]))),NHt=N.lazy(()=>Ge(()=>import("./FsboCampaignWizard-BYhmJH2A.js"),__vite__mapDeps([724,419,413,414,159,721,722,717,254,614]))),RHt=N.lazy(()=>Ge(()=>import("./FsboCampaignDetail-DQtejuBo.js"),__vite__mapDeps([725,137,717,254,414,614,719,196,483,81,721,722,373,359,723,419,413,159,192,478,502]))),LHt=N.lazy(()=>Ge(()=>import("./FsboLanding-oiQwhlWr.js"),__vite__mapDeps([726,722,727]))),DHt=N.lazy(()=>Ge(()=>import("./FsboGuide-LahaKusA.js"),__vite__mapDeps([728,727]))),MHt=N.lazy(()=>Ge(()=>import("./FsboBreakthroughAdmin-XQUSCWYr.js"),__vite__mapDeps([729,721,149,715]))),OHt=N.lazy(()=>Ge(()=>import("./AttractLandingPageBuilder-CYGXtN2h.js"),__vite__mapDeps([730,689,708,213,214,81]))),FHt=N.lazy(()=>Ge(()=>import("./AttractAccess-CnFvnJLm.js"),__vite__mapDeps([731,157,202,84]))),BHt=N.lazy(()=>Ge(()=>import("./Teams-Buz_43KK.js"),__vite__mapDeps([732,276,285,277,278,279,280,281,202,282,5,283,284,80,87]))),zHt=N.lazy(()=>Ge(()=>import("./MyTeam-ChWU9ckD.js"),__vite__mapDeps([733,276,279,280,281,202,282,5,283,278,734,285,284,80]))),$Ht=N.lazy(()=>Ge(()=>import("./TeamHub--zKbayz1.js"),__vite__mapDeps([735,276,279,280,281,202,282,5,283,278,734,578,61,75,285,284,80]))),UHt=N.lazy(()=>Ge(()=>import("./SchedulerSettings-Ci7fQSlb.js"),__vite__mapDeps([736,92,93,94,67,138,493,84,541,97,98,236]))),VHt=N.lazy(()=>Ge(()=>import("./MyCalendar-5fkOJLwt.js"),__vite__mapDeps([737,94,238,241,240,242]))),qHt=N.lazy(()=>Ge(()=>Promise.resolve().then(()=>u3t),void 0)),GHt=N.lazy(()=>Ge(()=>import("./BookingManagePage-ChG4-iyk.js"),__vite__mapDeps([738,84]))),HHt=N.lazy(()=>Ge(()=>import("./LandingPages-BAHsy_IW.js"),__vite__mapDeps([739,137,149]))),WHt=N.lazy(()=>Ge(()=>import("./BuyerMatch-YVzQ2krP.js"),__vite__mapDeps([740,741,326,257,327,184,328,185,95,161,314,153,275,329,140,141,333,385,386,216,8,398]))),KHt=N.lazy(()=>Ge(()=>import("./BuyerMatchEditor-S85RHDKV.js"),__vite__mapDeps([742,137,741,326,257,327,184,328,185,95,161,314,153,275,329,140,141,333,385,386,216,139,138,142,143,144,145,146,97,98,147,743,81]))),YHt=N.lazy(()=>Ge(()=>import("./PublicBuyerMatch-BR4-1ktI.js"),__vite__mapDeps([744,743,491,84]))),ZHt=N.lazy(()=>Ge(()=>import("./LandingPageEditor-n3Z3Wx3i.js"),__vite__mapDeps([745,137,161,133,149,81,134]))),XHt=N.lazy(()=>Ge(()=>import("./LandingPageDefaults-p1iYS32S.js"),__vite__mapDeps([746,81]))),QHt=N.lazy(()=>Ge(()=>Promise.resolve().then(()=>N3t),void 0)),JHt=N.lazy(()=>Ge(()=>import("./WebsiteAppsHub-Bp0C2gsc.js"),__vite__mapDeps([747,748,285,749,461,113,187,186,462,398,433,463,275,86,280,153,464,465,162,466,9,30,50,184,341,431,380,467,123,397,286,93,468,37,469,470,59,306,71,471,84,446,472,473,474,120,335,312,124,271,367,284,475,90,268,122,282,242,452,36,75,476,477,478,176,479,148,219,480,265,121,269,408,80,481,482,483,484,134,485,283,459,13,182,183,486,487,202,488,234,159,444,88,109,371,489,218,339,95,336,185,490,422,491,116,100,362,492,197,390,12,200,493,494,247,495,496,439,411,453,207,410,314,25,497,161,303,498,420,232,53,423,499,445,304,147,105,8,357,402,114,451,262,152,52,500,501,502,149,112,503,366,291,261,5,190,221,81,447,504,236,293,505,506,270,507,69,208,39,155,387,361,281,6,448,508,216,458,509,38,510,26,51,22,438,511,235,328,332,230,67,205,87,512,513,196,389,514,313,40,108,189]))),eWt=N.lazy(()=>Ge(()=>import("./ClaimWebsite-CoOO_Fhn.js"),__vite__mapDeps([750,748,285]))),tWt=N.lazy(()=>Ge(()=>import("./VideoGreeterEditor-4EFPW7BY.js"),__vite__mapDeps([751,749,381,624,407,162,408,409,410,411,314,5,8,646,75,383,71]))),rWt=N.lazy(()=>Ge(()=>import("./ExitIntentEditor-Cpvt5Zqu.js"),__vite__mapDeps([752,749,753]))),nWt=N.lazy(()=>Ge(()=>import("./LeadMagnetEditor-BeKAF0Sz.js"),__vite__mapDeps([754,749,753]))),iWt=N.lazy(()=>Ge(()=>import("./EmbedVideoGreeter-Ckz25KqG.js"),[])),sWt=N.lazy(()=>Ge(()=>import("./EmbedLeadMagnet-DQBX2PUk.js"),[])),aWt=N.lazy(()=>Ge(()=>import("./RelationshipScorecard-BgpB5NHk.js"),__vite__mapDeps([755,372,175,168,357,463]))),oWt=N.lazy(()=>Ge(()=>import("./SphereGaps-BNIwgzVL.js"),__vite__mapDeps([756,144,169,139,138,140,141,142,143,145,146,97,98,147,333,216,499,81]))),lWt=N.lazy(()=>Ge(()=>import("./Signals-tHH1gFX3.js"),[])),cWt=N.lazy(()=>Ge(()=>import("./ConnectPageSettings-CwuHkfNa.js"),__vite__mapDeps([757,144]))),uWt=N.lazy(()=>Ge(()=>import("./WebsiteActivityPage-DEydijSR.js"),__vite__mapDeps([632,169,139,138,140,141,142,143,144,145,146,97,98,147,12]))),dWt=N.lazy(()=>Ge(()=>import("./EmailCampaigns-Bxcls9O1.js"),__vite__mapDeps([758,759,98,140,71]))),hWt=N.lazy(()=>Ge(()=>import("./EmailCompliance-1a2Lv5LS.js"),__vite__mapDeps([760,492]))),fWt=N.lazy(()=>Ge(()=>import("./EmailCampaignComposer-VfJRhOkr.js"),__vite__mapDeps([761,759,98,141,762,179,181,311,180,184,182,183,185,186,187,95,458,397,218,329,341,80,381,330,312,147]))),mWt=N.lazy(()=>Ge(()=>import("./EmailCampaignDetail-C5ipFBO6.js"),__vite__mapDeps([763,303,162]))),pWt=N.lazy(()=>Ge(()=>import("./SharedCampaignTemplates-hB9oG-R5.js"),__vite__mapDeps([764,765,762,179,181,311,180,184,182,183,185,186,187,95,458,397,218,341,312]))),gWt=N.lazy(()=>Ge(()=>import("./AgentTemplates-B4GDC38U.js"),__vite__mapDeps([766,765,762,179,181,311,180,184,182,183,185,186,187,95,458,397,218,341,312,80]))),Rge=N.lazy(()=>Ge(()=>import("./TheLocalMoveHome-Br4A1xnl.js"),__vite__mapDeps([767,768,284,469,123]))),Lge=N.lazy(()=>Ge(()=>import("./TheLocalMoveGetStarted-CS4nOL7Q.js"),__vite__mapDeps([769,768]))),Dge=N.lazy(()=>Ge(()=>import("./TheLocalMoveCheckout-CEjH_ZXX.js"),__vite__mapDeps([770,242]))),Mge=N.lazy(()=>Ge(()=>import("./TheLocalMoveCheckoutSuccess-CGaKN6-7.js"),[])),yWt=N.lazy(()=>Ge(()=>import("./AdminWebsiteOrders-CLfJ4HZF.js"),__vite__mapDeps([771,216]))),xWt=new eUe({defaultOptions:{queries:{refetchOnWindowFocus:!1,staleTime:5*60*1e3}}}),_Wt=()=>{const t=window.location.hostname;return t==="listings.relevelup.com"||t.startsWith("listings.")},vWt=()=>{const t=window.location.hostname;return t==="commercial.relevelup.com"||t.startsWith("commercial.")},bWt=()=>{const t=window.location.hostname;return t==="cards.relevelup.com"||t.startsWith("cards.")},wWt=()=>{const t=window.location.hostname;return t==="presentations.relevelup.com"||t.startsWith("presentations.")},SWt=()=>{const t=window.location.hostname;return t==="guestbook.relevelup.com"||t.startsWith("guestbook.")},EWt=()=>{const t=window.location.hostname;return t==="clients.relevelup.com"||t.startsWith("clients.")},TWt=()=>{const t=window.location.hostname;return t==="cma.relevelup.com"||t.startsWith("cma.")},AWt=()=>{const t=window.location.hostname;return t==="cardstudio.relevelup.com"||t.startsWith("cardstudio.")},kWt=()=>{const t=window.location.hostname;return t==="booking.relevelup.com"||t.startsWith("booking.")},IWt=()=>{const t=window.location.hostname;return t==="contacts.relevelup.com"||t.startsWith("contacts.")},jWt=()=>{const t=window.location.hostname;return t==="pages.relevelup.com"||t.startsWith("pages.")},ONe=()=>{const t=window.location.hostname;return t==="thelocalmove.com"||t==="www.thelocalmove.com"},CWt=new Set(["app","www","api","admin","embed","cdn","static","assets"]),PWt=()=>{const t=window.location.hostname;if(new URLSearchParams(window.location.search).get("previewSlug"))return!0;if(o_e(t))return!(window.location.pathname.startsWith("/embed/")||window.location.pathname.startsWith("/widgets/"));if(!t.endsWith(".thelocalmove.com")||ONe())return!1;const e=t.replace(/\.thelocalmove\.com$/,"").split(".").pop()||"";return!(CWt.has(e.toLowerCase())||window.location.pathname.startsWith("/embed/")||window.location.pathname.startsWith("/widgets/"))};if(typeof window<"u")try{const e=new URLSearchParams(window.location.search).get("ref");e&&/^[a-z0-9]{2,32}$/i.test(e)&&localStorage.setItem("levelup_referral_code",e.toLowerCase())}catch{}const NWt=()=>s.jsx(j6e,{client:xWt,children:s.jsx(sbe,{children:s.jsxs(k0e,{children:[s.jsx(uBe,{}),s.jsx(UBe,{}),s.jsx(r$e,{}),s.jsx(cVe,{future:{v7_startTransition:!0},children:s.jsx(sGe,{children:s.jsx(uGe,{children:s.jsx(hGe,{children:s.jsxs(cGe,{children:[s.jsx(dGe,{}),s.jsx(A9e,{}),s.jsx(brt,{}),AWt()?s.jsx(a3t,{}):bWt()?s.jsx(Jnt,{}):vWt()?s.jsx(Tnt,{}):_Wt()?s.jsx(Snt,{}):wWt()?s.jsx(nit,{}):SWt()?s.jsx(Dct,{}):EWt()?s.jsx(iut,{}):TWt()?s.jsx(cut,{}):kWt()?s.jsx(d3t,{}):IWt()?s.jsx(b3t,{}):jWt()?s.jsx(R3t,{}):ONe()?s.jsxs(kb,{children:[s.jsx(Ce,{path:"/get-started",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Lge,{})})}),s.jsx(Ce,{path:"/checkout",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Dge,{})})}),s.jsx(Ce,{path:"/checkout/success",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Mge,{})})}),s.jsx(Ce,{path:"/privacy-policy",element:s.jsx(pge,{})}),s.jsx(Ce,{path:"/terms-of-service",element:s.jsx(gge,{})}),s.jsx(Ce,{path:"/mcp-data-use",element:s.jsx(yge,{})}),s.jsx(Ce,{path:"*",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Rge,{})})})]}):PWt()?s.jsx(ZVt,{}):s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsxs(kb,{children:[s.jsx(Ce,{path:"/",element:s.jsx(Aut,{})}),s.jsx(Ce,{path:"/the-local-move",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Rge,{})})}),s.jsx(Ce,{path:"/get-started",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Lge,{})})}),s.jsx(Ce,{path:"/local-move/checkout",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Dge,{})})}),s.jsx(Ce,{path:"/local-move/checkout/success",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Mge,{})})}),s.jsx(Ce,{path:"/privacy-policy",element:s.jsx(pge,{})}),s.jsx(Ce,{path:"/terms-of-service",element:s.jsx(gge,{})}),s.jsx(Ce,{path:"/data-deletion",element:s.jsx(r8t,{})}),s.jsx(Ce,{path:"/mcp-data-use",element:s.jsx(yge,{})}),s.jsx(Ce,{path:"/canva-support",element:s.jsx(t8t,{})}),s.jsx(Ce,{path:"/sms-opt-in",element:s.jsx(n8t,{})}),s.jsx(Ce,{path:"/oauth-connect",element:s.jsx(A8,{})}),s.jsx(Ce,{path:"/.lovable/oauth/consent",element:s.jsx(A8,{})}),s.jsx(Ce,{path:"/oauth/consent",element:s.jsx(A8,{})}),s.jsx(Ce,{path:"/mcp",element:s.jsx(xge,{})}),s.jsx(Ce,{path:"/connect-chatgpt",element:s.jsx(xge,{})}),s.jsx(Ce,{path:"/connect-chatgpt/classic",element:s.jsx(i8t,{})}),s.jsx(Ce,{path:"/public/listings",element:s.jsx(P8t,{})}),s.jsx(Ce,{path:"/public/commercial",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(e8t,{})})}),s.jsx(Ce,{path:"/public/listing/:slugOrId",element:s.jsx(N8t,{})}),s.jsx(Ce,{path:"/listing/:slugOrId",element:s.jsx(RWt,{})}),s.jsx(Ce,{path:"/private-listing",element:s.jsx(M8t,{})}),s.jsx(Ce,{path:"/commercial-pitch/:token",element:s.jsx(D8t,{})}),s.jsx(Ce,{path:"/card/:slug",element:s.jsx(O8t,{})}),s.jsx(Ce,{path:"/join-brokerage/:slug",element:s.jsx(p7t,{})}),s.jsx(Ce,{path:"/recruit-unsubscribe",element:s.jsx(y7t,{})}),s.jsx(Ce,{path:"/event-invite-unsubscribe",element:s.jsx(x7t,{})}),s.jsx(Ce,{path:"/recruit-video/:shareToken",element:s.jsx(g7t,{})}),s.jsx(Ce,{path:"/connect/:slug",element:s.jsx(F8t,{})}),s.jsx(Ce,{path:"/home-value",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Sge,{})})}),s.jsx(Ce,{path:"/whats-my-home-worth",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(Sge,{})})}),s.jsx(Ce,{path:"/live/:slug",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(B8t,{})})}),s.jsx(Ce,{path:"/auth",element:s.jsx(pue,{})}),s.jsx(Ce,{path:"/login",element:s.jsx(pue,{})}),s.jsx(Ce,{path:"/subscription-success",element:s.jsx(s8t,{})}),s.jsx(Ce,{path:"/subscription",element:s.jsx(gt,{children:s.jsx(a8t,{})})}),s.jsxs(Ce,{path:"/share/video",element:s.jsx(j8t,{}),children:[s.jsx(Ce,{path:":shareToken",element:s.jsx(bge,{})}),s.jsx(Ce,{path:":shareToken/r/:recipientToken",element:s.jsx(bge,{})})]}),s.jsx(Ce,{path:"/p/:shareToken",element:s.jsx(N7t,{})}),s.jsx(Ce,{path:"/portal/:slug",element:s.jsx(G7t,{})}),s.jsx(Ce,{path:"/portal/:slug/refer",element:s.jsx(H7t,{})}),s.jsx(Ce,{path:"/og/video/:token",element:s.jsx(C8t,{})}),s.jsx(Ce,{path:"/setup-brokerage",element:s.jsx(gt,{children:s.jsx(o8t,{})})}),s.jsx(Ce,{path:"/claim-account",element:s.jsx(_ge,{})}),s.jsx(Ce,{path:"/claim",element:s.jsx(_ge,{})}),s.jsx(Ce,{path:"/activate",element:s.jsx(l8t,{})}),s.jsx(Ce,{path:"/auth/confirm-reset",element:s.jsx(vge,{})}),s.jsx(Ce,{path:"/auth/continue",element:s.jsx(vge,{})}),s.jsx(Ce,{path:"/join",element:s.jsx(c8t,{})}),s.jsx(Ce,{path:"/trial",element:s.jsx(w8t,{})}),s.jsx(Ce,{path:"/trial/success",element:s.jsx(S8t,{})}),s.jsx(Ce,{path:"/labor-day",element:s.jsx(E8t,{})}),s.jsx(Ce,{path:"/brokerage-labor-day",element:s.jsx(T8t,{})}),s.jsx(Ce,{path:"/brokerage-solutions",element:s.jsx(A8t,{})}),s.jsx(Ce,{path:"/upgrade",element:s.jsx(k8t,{})}),s.jsx(Ce,{path:"/instagram",element:s.jsx(I8t,{})}),s.jsx(Ce,{path:"/dashboard",element:s.jsx(gt,{children:s.jsx(U8t,{})})}),s.jsx(Ce,{path:"/coaching",element:s.jsx(gt,{children:s.jsx(u8t,{})})}),s.jsx(Ce,{path:"/coaching/billing",element:s.jsx(gt,{children:s.jsx(m8t,{})})}),s.jsx(Ce,{path:"/coaching/settings",element:s.jsx(gt,{children:s.jsx(p8t,{})})}),s.jsx(Ce,{path:"/coaching/waitlist",element:s.jsx(gt,{children:s.jsx(x8t,{})})}),s.jsx(Ce,{path:"/coaching/agent/:id",element:s.jsx(gt,{children:s.jsx(d8t,{})})}),s.jsx(Ce,{path:"/my-coach",element:s.jsx(gt,{children:s.jsx(h8t,{})})}),s.jsx(Ce,{path:"/admin/coaching",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(f8t,{})})}),s.jsx(Ce,{path:"/oauth/google-calendar/return",element:s.jsx(g8t,{})}),s.jsx(Ce,{path:"/oauth/microsoft-365/return",element:s.jsx(y8t,{})}),s.jsxs(Ce,{path:"/attract",element:s.jsx(gt,{children:s.jsx(JVt,{children:s.jsx(eHt,{})})}),children:[s.jsx(Ce,{index:!0,element:s.jsx(tHt,{})}),s.jsx(Ce,{path:"agents",element:s.jsx(rHt,{})}),s.jsx(Ce,{path:"agents/:agentId",element:s.jsx(_Ht,{})}),s.jsx(Ce,{path:"attract-page",element:s.jsx(OHt,{})}),s.jsx(Ce,{path:"calculator",element:s.jsx(uHt,{})}),s.jsx(Ce,{path:"results",element:s.jsx(aHt,{})}),s.jsx(Ce,{path:"onboarding",element:s.jsx(mHt,{})}),s.jsx(Ce,{path:"opportunities",element:s.jsx(vHt,{})}),s.jsx(Ce,{path:"follow-up",element:s.jsx(nHt,{})}),s.jsx(Ce,{path:"settings",element:s.jsx(oHt,{})}),s.jsxs(Ce,{path:"toolkit",element:s.jsx(lHt,{}),children:[s.jsx(Ce,{index:!0,element:s.jsx(Oi,{to:"/attract/toolkit/kits",replace:!0})}),s.jsx(Ce,{path:"kits",element:s.jsx(gHt,{})}),s.jsx(Ce,{path:"scripts",element:s.jsx(sHt,{})}),s.jsx(Ce,{path:"objections",element:s.jsx(cHt,{})}),s.jsx(Ce,{path:"events",element:s.jsx(dHt,{})}),s.jsx(Ce,{path:"content",element:s.jsx(pHt,{})}),s.jsx(Ce,{path:"resources",element:s.jsx(iHt,{})})]}),s.jsx(Ce,{path:"toolkit/kits/templates",element:s.jsx(xHt,{})}),s.jsx(Ce,{path:"toolkit/kits/new",element:s.jsx(Pge,{})}),s.jsx(Ce,{path:"toolkit/kits/:kitId/edit",element:s.jsx(Pge,{})}),s.jsx(Ce,{path:"toolkit/kits/:kitId/analytics",element:s.jsx(yHt,{})}),s.jsx(Ce,{path:"events/new",element:s.jsx(Cge,{})}),s.jsx(Ce,{path:"events/:eventId",element:s.jsx(hHt,{})}),s.jsx(Ce,{path:"events/:eventId/edit",element:s.jsx(Cge,{})}),s.jsx(Ce,{path:"events/:eventId/checkin",element:s.jsx(fHt,{})}),s.jsx(Ce,{path:"relationships",element:s.jsx(Oi,{to:"/attract/agents",replace:!0})}),s.jsx(Ce,{path:"pipeline",element:s.jsx(Oi,{to:"/attract/agents",replace:!0})}),s.jsx(Ce,{path:"plan",element:s.jsx(Oi,{to:"/attract/settings",replace:!0})}),s.jsx(Ce,{path:"digest",element:s.jsx(Oi,{to:"/attract/results",replace:!0})}),s.jsx(Ce,{path:"reports",element:s.jsx(Oi,{to:"/attract/results",replace:!0})}),s.jsx(Ce,{path:"dashboard-legacy",element:s.jsx(Oi,{to:"/attract",replace:!0})}),s.jsx(Ce,{path:"share",element:s.jsx(Oi,{to:"/attract/toolkit/kits",replace:!0})}),s.jsx(Ce,{path:"create",element:s.jsx(Oi,{to:"/attract/toolkit/content",replace:!0})}),s.jsx(Ce,{path:"templates",element:s.jsx(Oi,{to:"/attract/toolkit/scripts",replace:!0})}),s.jsx(Ce,{path:"resources",element:s.jsx(Oi,{to:"/attract/toolkit/resources",replace:!0})}),s.jsx(Ce,{path:"events",element:s.jsx(Oi,{to:"/attract/toolkit/events",replace:!0})}),s.jsx(Ce,{path:"landing-page",element:s.jsx(Oi,{to:"/attract/attract-page",replace:!0})}),s.jsx(Ce,{path:"provide/kits",element:s.jsx(Oi,{to:"/attract/toolkit/kits",replace:!0})}),s.jsx(Ce,{path:"provide/kits/templates",element:s.jsx(Oi,{to:"/attract/toolkit/kits/templates",replace:!0})}),s.jsx(Ce,{path:"provide/*",element:s.jsx(Oi,{to:"/attract/toolkit/kits",replace:!0})}),s.jsx(Ce,{path:"influence/content-studio",element:s.jsx(Oi,{to:"/attract/toolkit/content",replace:!0})}),s.jsx(Ce,{path:"influence/*",element:s.jsx(Oi,{to:"/attract/toolkit/content",replace:!0})}),s.jsx(Ce,{path:"produce/*",element:s.jsx(Oi,{to:"/attract/results",replace:!0})}),s.jsx(Ce,{path:"connect/*",element:s.jsx(Oi,{to:"/attract/toolkit/events",replace:!0})}),s.jsx(Ce,{path:"connect",element:s.jsx(Oi,{to:"/attract/toolkit/events",replace:!0})}),s.jsx(Ce,{path:"pillars/*",element:s.jsx(Oi,{to:"/attract",replace:!0})})]}),s.jsx(Ce,{path:"/weekly-reels",element:s.jsx(gt,{children:s.jsx(mge,{children:s.jsx(X7t,{})})})}),s.jsx(Ce,{path:"/weekly-reels/onboarding",element:s.jsx(gt,{children:s.jsx(mge,{children:s.jsx(Q7t,{})})})}),s.jsx(Ce,{path:"/admin/weekly-reels",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(J7t,{})})}),s.jsx(Ce,{path:"/admin/attract-access",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(FHt,{})})}),s.jsx(Ce,{path:"/admin/attract-intelligence",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(bHt,{})})}),s.jsx(Ce,{path:"/admin/attract-tools",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(wHt,{})})}),s.jsx(Ce,{path:"/attract-kit/:shareToken",element:s.jsx(SHt,{})}),s.jsx(Ce,{path:"/attract-event/:slug",element:s.jsx(EHt,{})}),s.jsx(Ce,{path:"/attract-event-checkin/:token",element:s.jsx(THt,{})}),s.jsx(Ce,{path:"/join/:slug",element:s.jsx(AHt,{})}),s.jsx(Ce,{path:"/revival/:slug",element:s.jsx(kHt,{})}),s.jsx(Ce,{path:"/revival/:slug/plan",element:s.jsx(Nge,{})}),s.jsx(Ce,{path:"/fsbo/:slug",element:s.jsx(LHt,{})}),s.jsx(Ce,{path:"/fsbo/:slug/guide",element:s.jsx(DHt,{})}),s.jsx(Ce,{path:"/revival/:slug/plan",element:s.jsx(Nge,{})}),s.jsx(Ce,{path:"/coaches",element:s.jsx(_8t,{})}),s.jsx(Ce,{path:"/coaches/apply",element:s.jsx(b8t,{})}),s.jsx(Ce,{path:"/coaches/:slug",element:s.jsx(v8t,{})}),s.jsx(Ce,{path:"/credits",element:s.jsx(gt,{children:s.jsx(L9t,{})})}),s.jsx(Ce,{path:"/wallet",element:s.jsx(Oi,{to:"/credits",replace:!0})}),s.jsx(Ce,{path:"/profile",element:s.jsx(gt,{children:s.jsx(V8t,{})})}),s.jsx(Ce,{path:"/apps/*",element:s.jsx(gt,{children:s.jsx(H8t,{})})}),s.jsx(Ce,{path:"/admin",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Ege,{})})}),s.jsx(Ce,{path:"/admin/dashboard",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Ege,{})})}),s.jsx(Ce,{path:"/admin/apps",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(yqt,{})})}),s.jsx(Ce,{path:"/admin/members",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(xqt,{})})}),s.jsx(Ce,{path:"/admin/unassigned-members",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(_qt,{})})}),s.jsx(Ce,{path:"/admin/invite-codes",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(vqt,{})})}),s.jsx(Ce,{path:"/admin/events",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(bqt,{})})}),s.jsx(Ce,{path:"/admin/live",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx(z8t,{})})})}),s.jsx(Ce,{path:"/admin/live/:id",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{}),children:s.jsx($8t,{})})})}),s.jsx(Ce,{path:"/admin/mcp-audit",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(wqt,{})})}),s.jsx(Ce,{path:"/events",element:s.jsx(gt,{children:s.jsx(q8t,{})})}),s.jsx(Ce,{path:"/events/:eventId",element:s.jsx(gt,{children:s.jsx(G8t,{})})}),s.jsx(Ce,{path:"/templates",element:s.jsx(gt,{children:s.jsx(W8t,{})})}),s.jsx(Ce,{path:"/templates/:templateId",element:s.jsx(gt,{children:s.jsx(K8t,{})})}),s.jsx(Ce,{path:"/admin/templates",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Sqt,{})})}),s.jsx(Ce,{path:"/programs",element:s.jsx(gt,{children:s.jsx(Y8t,{})})}),s.jsx(Ce,{path:"/programs/:slug",element:s.jsx(gt,{children:s.jsx(Z8t,{})})}),s.jsx(Ce,{path:"/programs/:slug/enroll",element:s.jsx(gt,{children:s.jsx(X8t,{})})}),s.jsx(Ce,{path:"/programs/:slug/workspace",element:s.jsx(gt,{children:s.jsx(Q8t,{})})}),s.jsx(Ce,{path:"/admin/programs",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(J8t,{})})}),s.jsx(Ce,{path:"/watch/:slug",element:s.jsx(rqt,{})}),s.jsx(Ce,{path:"/academy",element:s.jsx(gt,{children:s.jsx(eqt,{})})}),s.jsx(Ce,{path:"/academy/:videoId",element:s.jsx(gt,{children:s.jsx(tqt,{})})}),s.jsx(Ce,{path:"/admin/academy",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Eqt,{})})}),s.jsx(Ce,{path:"/toolbox",element:s.jsx(gt,{children:s.jsx(nqt,{})})}),s.jsx(Ce,{path:"/toolbox/:kitId",element:s.jsx(gt,{children:s.jsx(iqt,{})})}),s.jsx(Ce,{path:"/admin/toolbox",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Tqt,{})})}),s.jsx(Ce,{path:"/admin/blog",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(z7t,{})})}),s.jsx(Ce,{path:"/social-swag",element:s.jsx(gt,{children:s.jsx(sqt,{})})}),s.jsx(Ce,{path:"/social-studio",element:s.jsx(gt,{children:s.jsx(aqt,{})})}),s.jsx(Ce,{path:"/social-swag-2",element:s.jsx(Oi,{to:"/social-studio?tab=gallery",replace:!0})}),s.jsx(Ce,{path:"/marketing-studio",element:s.jsx(gt,{children:s.jsx(oqt,{})})}),s.jsx(Ce,{path:"/marketing-studio/brand-kit",element:s.jsx(gt,{children:s.jsx(lqt,{})})}),s.jsx(Ce,{path:"/marketing-studio/branding-bar",element:s.jsx(gt,{children:s.jsx(cqt,{})})}),s.jsx(Ce,{path:"/marketing-studio/listing-templates",element:s.jsx(gt,{children:s.jsx(uqt,{})})}),s.jsx(Ce,{path:"/marketing-studio/personal-branding",element:s.jsx(gt,{children:s.jsx(dqt,{})})}),s.jsx(Ce,{path:"/social-swag/:swagId",element:s.jsx(gt,{children:s.jsx(hqt,{})})}),s.jsx(Ce,{path:"/social-connections",element:s.jsx(gt,{children:s.jsx(_7t,{})})}),s.jsx(Ce,{path:"/social-connections/callback",element:s.jsx(gt,{children:s.jsx(v7t,{})})}),s.jsx(Ce,{path:"/social-connections/linkedin-callback",element:s.jsx(gt,{children:s.jsx(w7t,{})})}),s.jsx(Ce,{path:"/social-connections/tiktok-callback",element:s.jsx(gt,{children:s.jsx(S7t,{})})}),s.jsx(Ce,{path:"/social-connections/google-callback",element:s.jsx(gt,{children:s.jsx(b7t,{})})}),s.jsx(Ce,{path:"/admin/social-swag",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Aqt,{})})}),s.jsx(Ce,{path:"/admin/social-swag-2",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(kqt,{})})}),s.jsx(Ce,{path:"/community",element:s.jsx(gt,{children:s.jsx(fqt,{})})}),s.jsx(Ce,{path:"/support",element:s.jsx(gt,{children:s.jsx(mqt,{})})}),s.jsx(Ce,{path:"/admin/community",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Iqt,{})})}),s.jsx(Ce,{path:"/admin/support-tickets",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Nqt,{})})}),s.jsx(Ce,{path:"/admin/email-templates",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Rqt,{})})}),s.jsx(Ce,{path:"/admin/agent-email-templates",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Lqt,{})})}),s.jsx(Ce,{path:"/admin/analytics",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(jqt,{})})}),s.jsx(Ce,{path:"/admin/brokerage-resources",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Cqt,{})})}),s.jsx(Ce,{path:"/admin/dashboard-management",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Pqt,{})})}),s.jsx(Ce,{path:"/brokerage/dashboard",element:s.jsx(gt,{requireBrokerageManager:!0,children:s.jsx(Dqt,{})})}),s.jsx(Ce,{path:"/brokerage/teams",element:s.jsx(gt,{requireBrokerageManager:!0,children:s.jsx(BHt,{})})}),s.jsx(Ce,{path:"/brokerage/recruiting",element:s.jsx(gt,{requireBrokerageManager:!0,children:s.jsx(p9t,{})})}),s.jsx(Ce,{path:"/brokerage/onboarding",element:s.jsx(gt,{requireBrokerageManager:!0,children:s.jsx(g9t,{})})}),s.jsx(Ce,{path:"/brokerage/commission-plans",element:s.jsx(gt,{children:s.jsx(w9t,{})})}),s.jsx(Ce,{path:"/brokerage/operations",element:s.jsx(gt,{children:s.jsx(x9t,{})})}),s.jsx(Ce,{path:"/brokerage/website",element:s.jsx(gt,{children:s.jsx(b9t,{})})}),s.jsx(Ce,{path:"/websites",element:s.jsx(gt,{children:s.jsx(_9t,{})})}),s.jsx(Ce,{path:"/team/website",element:s.jsx(gt,{children:s.jsx(v9t,{})})}),s.jsx(Ce,{path:"/brokerage/transactions",element:s.jsx(gt,{children:s.jsx(y9t,{})})}),s.jsx(Ce,{path:"/team",element:s.jsx(gt,{children:s.jsx($Ht,{})})}),s.jsx(Ce,{path:"/my-team",element:s.jsx(gt,{children:s.jsx(zHt,{})})}),s.jsx(Ce,{path:"/my-brokerage",element:s.jsx(gt,{children:s.jsx(Mqt,{})})}),s.jsx(Ce,{path:"/brokerage/help-board",element:s.jsx(gt,{children:s.jsx(Bqt,{})})}),s.jsx(Ce,{path:"/brokerage/help-board/new",element:s.jsx(gt,{children:s.jsx(zqt,{})})}),s.jsx(Ce,{path:"/brokerage/help-board/:id",element:s.jsx(gt,{children:s.jsx($qt,{})})}),s.jsx(Ce,{path:"/brokerage-content",element:s.jsx(gt,{children:s.jsx(Oqt,{})})}),s.jsx(Ce,{path:"/brokerage-content/:contentId",element:s.jsx(gt,{children:s.jsx(Fqt,{})})}),s.jsx(Ce,{path:"/brokerage-resources",element:s.jsx(gt,{requireBrokerageManager:!0,children:s.jsx(pqt,{})})}),s.jsx(Ce,{path:"/brokerage-resources/:resourceId",element:s.jsx(gt,{requireBrokerageManager:!0,children:s.jsx(gqt,{})})}),s.jsx(Ce,{path:"/newsletters",element:s.jsx(gt,{children:s.jsx(Uqt,{})})}),s.jsx(Ce,{path:"/newsletters/:id",element:s.jsx(gt,{children:s.jsx(Vqt,{})})}),s.jsx(Ce,{path:"/wishlist",element:s.jsx(gt,{children:s.jsx(Kqt,{})})}),s.jsx(Ce,{path:"/wishlist/:itemId",element:s.jsx(gt,{children:s.jsx(Yqt,{})})}),s.jsx(Ce,{path:"/admin/wishlist",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Zqt,{})})}),s.jsx(Ce,{path:"/admin/levelup-brief",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Xqt,{})})}),s.jsx(Ce,{path:"/admin/boost-announcements",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Hqt,{})})}),s.jsx(Ce,{path:"/admin/broadcasts",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Gqt,{})})}),s.jsx(Ce,{path:"/admin/newsletters",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(qqt,{})})}),s.jsx(Ce,{path:"/admin/newsletter-graphics",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Wqt,{})})}),s.jsx(Ce,{path:"/admin/additional-services",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Qqt,{})})}),s.jsx(Ce,{path:"/admin/discounts",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Jqt,{})})}),s.jsx(Ce,{path:"/admin/subscriptions",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(eGt,{})})}),s.jsx(Ce,{path:"/admin/instagram-gift-emails",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(tGt,{})})}),s.jsx(Ce,{path:"/admin/referrals",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(rGt,{})})}),s.jsx(Ce,{path:"/admin/prospector",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(f9t,{})})}),s.jsx(Ce,{path:"/admin/recruiting",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(m9t,{})})}),s.jsx(Ce,{path:"/admin/beta/social-post-generator",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(E9t,{})})}),s.jsx(Ce,{path:"/admin/credits",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(q9t,{})})})}),s.jsx(Ce,{path:"/admin/cleanup",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(G9t,{})})})}),s.jsx(Ce,{path:"/admin/beta/postcard-manager",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(F9t,{})})})}),s.jsx(Ce,{path:"/admin/mail-studio/templates",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(B9t,{})})})}),s.jsx(Ce,{path:"/admin/beta/homereel",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(z9t,{})})})}),s.jsx(Ce,{path:"/admin/beta/boost",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(V9t,{})})})}),s.jsx(Ce,{path:"/admin/video-lab",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(U9t,{})})})}),s.jsx(Ce,{path:"/admin/music-videos",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx($9t,{})})})}),s.jsx(Ce,{path:"/admin/lms",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(T9t,{})})}),s.jsx(Ce,{path:"/admin/lms/stats",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(k9t,{})})}),s.jsx(Ce,{path:"/admin/lms/:courseId",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(A9t,{})})}),s.jsx(Ce,{path:"/levelup-u",element:s.jsx(gt,{children:s.jsx(I9t,{})})}),s.jsx(Ce,{path:"/levelup-u/:courseId",element:s.jsx(gt,{children:s.jsx(j9t,{})})}),s.jsx(Ce,{path:"/admin/brokerage-content-activity",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(S9t,{})})}),s.jsx(Ce,{path:"/admin/onboarding-checklist",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(nGt,{})})}),s.jsx(Ce,{path:"/admin/marketplace",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(e9t,{})})}),s.jsx(Ce,{path:"/admin/agent-points",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(QGt,{})})}),s.jsx(Ce,{path:"/admin/reward-store",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(t9t,{})})}),s.jsx(Ce,{path:"/admin/integrations",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(r9t,{})})}),s.jsx(Ce,{path:"/admin/mcp-updates",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(s9t,{})})}),s.jsx(Ce,{path:"/help/refresh-mcp-tools",element:s.jsx(gt,{children:s.jsx(a9t,{})})}),s.jsx(Ce,{path:"/admin/social-autopilot",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(i9t,{})})}),s.jsx(Ce,{path:"/admin/social-connections",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(n9t,{})})}),s.jsx(Ce,{path:"/admin/integrations/callback",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(h9t,{})})}),s.jsx(Ce,{path:"/admin/email-compliance",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(hWt,{})})})}),s.jsx(Ce,{path:"/admin/email-campaigns",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(dWt,{})})})}),s.jsx(Ce,{path:"/admin/email-campaigns/templates",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(pWt,{})})})}),s.jsx(Ce,{path:"/email-campaigns/templates",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(gWt,{})})})}),s.jsx(Ce,{path:"/admin/email-campaigns/new",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(fWt,{})})})}),s.jsx(Ce,{path:"/admin/email-campaigns/:id",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(mWt,{})})})}),s.jsx(Ce,{path:"/reward-store",element:s.jsx(gt,{children:s.jsx(j7t,{})})}),s.jsx(Ce,{path:"/refer-friends",element:s.jsx(gt,{children:s.jsx(C7t,{})})}),s.jsx(Ce,{path:"/additional-services",element:s.jsx(gt,{children:s.jsx(sGt,{})})}),s.jsx(Ce,{path:"/additional-services/:serviceId",element:s.jsx(gt,{children:s.jsx(aGt,{})})}),s.jsx(Ce,{path:"/ai-toolkit",element:s.jsx(gt,{children:s.jsx(oGt,{})})}),s.jsx(Ce,{path:"/ask-ai",element:s.jsx(gt,{children:s.jsx(lGt,{})})}),s.jsx(Ce,{path:"/mission-control",element:s.jsx(gt,{children:s.jsx(cGt,{})})}),s.jsx(Ce,{path:"/mission-control/contacts",element:s.jsx(gt,{children:s.jsx(uGt,{})})}),s.jsx(Ce,{path:"/mission-control/sphere-map",element:s.jsx(gt,{children:s.jsx(Y9t,{})})}),s.jsx(Ce,{path:"/mission-control/property-intelligence",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(Z9t,{})})}),s.jsx(Ce,{path:"/mission-control/contacts/:contactId",element:s.jsx(gt,{children:s.jsx(dGt,{})})}),s.jsx(Ce,{path:"/mission-control/sent-emails",element:s.jsx(gt,{children:s.jsx(hGt,{})})}),s.jsx(Ce,{path:"/mission-control/plans",element:s.jsx(gt,{children:s.jsx(fGt,{})})}),s.jsx(Ce,{path:"/mission-control/cma",element:s.jsx(gt,{children:s.jsx(mGt,{})})}),s.jsx(Ce,{path:"/mission-control/cma/:id",element:s.jsx(gt,{children:s.jsx(pGt,{})})}),s.jsx(Ce,{path:"/cma/:token",element:s.jsx(xGt,{})}),s.jsx(Ce,{path:"/apps/listing-presentation-studio",element:s.jsx(gt,{children:s.jsx(gGt,{})})}),s.jsx(Ce,{path:"/apps/listing-presentation-studio/:id",element:s.jsx(gt,{children:s.jsx(yGt,{})})}),s.jsx(Ce,{path:"/apps/listing-revival",element:s.jsx(gt,{children:s.jsx(IHt,{})})}),s.jsx(Ce,{path:"/apps/listing-revival/new",element:s.jsx(gt,{children:s.jsx(jHt,{})})}),s.jsx(Ce,{path:"/apps/listing-revival/campaigns/:id",element:s.jsx(gt,{children:s.jsx(CHt,{})})}),s.jsx(Ce,{path:"/staged/:token",element:s.jsx(D9t,{})}),s.jsx(Ce,{path:"/apps/staging-studio",element:s.jsx(gt,{children:s.jsx(NU,{children:s.jsx(P9t,{})})})}),s.jsx(Ce,{path:"/apps/staging-studio/library",element:s.jsx(gt,{children:s.jsx(NU,{children:s.jsx(N9t,{})})})}),s.jsx(Ce,{path:"/apps/staging-studio/credits",element:s.jsx(gt,{children:s.jsx(NU,{children:s.jsx(R9t,{})})})}),s.jsx(Ce,{path:"/apps/fsbo-breakthrough",element:s.jsx(gt,{children:s.jsx(PHt,{})})}),s.jsx(Ce,{path:"/apps/fsbo-breakthrough/new",element:s.jsx(gt,{children:s.jsx(NHt,{})})}),s.jsx(Ce,{path:"/apps/reviews",element:s.jsx(gt,{children:s.jsx(q7t,{})})}),s.jsx(Ce,{path:"/apps/fsbo-breakthrough/campaigns/:id",element:s.jsx(gt,{children:s.jsx(RHt,{})})}),s.jsx(Ce,{path:"/admin/fsbo-breakthrough",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(MHt,{})})}),s.jsx(Ce,{path:"/mission-control/listing-presentations",element:s.jsx(Oi,{to:"/apps/listing-presentation-studio",replace:!0})}),s.jsx(Ce,{path:"/mission-control/popbys",element:s.jsx(gt,{children:s.jsx(_Gt,{})})}),s.jsx(Ce,{path:"/mission-control/popbys/map",element:s.jsx(gt,{children:s.jsx(K9t,{})})}),s.jsx(Ce,{path:"/admin/notification-settings",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(o9t,{})})}),s.jsx(Ce,{path:"/admin/agent-os",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(iGt,{})})}),s.jsx(Ce,{path:"/mission-control/listings",element:s.jsx(gt,{children:s.jsx(vGt,{})})}),s.jsx(Ce,{path:"/mission-control/listing-studio",element:s.jsx(gt,{children:s.jsx(K7t,{})})}),s.jsx(Ce,{path:"/mission-control/listings/new",element:s.jsx(gt,{children:s.jsx(R8t,{})})}),s.jsx(Ce,{path:"/mission-control/listings/new/residential",element:s.jsx(gt,{children:s.jsx(Tge,{})})}),s.jsx(Ce,{path:"/mission-control/listings/new/commercial",element:s.jsx(gt,{children:s.jsx(wge,{})})}),s.jsx(Ce,{path:"/mission-control/listings/:listingId/commercial",element:s.jsx(gt,{children:s.jsx(L8t,{})})}),s.jsx(Ce,{path:"/mission-control/listings/:listingId/commercial/edit",element:s.jsx(gt,{children:s.jsx(wge,{})})}),s.jsx(Ce,{path:"/mission-control/listings/:listingId",element:s.jsx(gt,{children:s.jsx(bGt,{})})}),s.jsx(Ce,{path:"/mission-control/listings/:listingId/edit",element:s.jsx(gt,{children:s.jsx(Tge,{})})}),s.jsx(Ce,{path:"/mission-control/listings/:listingId/customize",element:s.jsx(gt,{children:s.jsx(wGt,{})})}),s.jsx(Ce,{path:"/admin/listing-exchange",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(HGt,{})})}),s.jsx(Ce,{path:"/admin/listing-leads",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(WGt,{})})}),s.jsx(Ce,{path:"/admin/public-site-leads",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(KGt,{})})}),s.jsx(Ce,{path:"/mission-control/pipeline",element:s.jsx(gt,{children:s.jsx(jGt,{})})}),s.jsx(Ce,{path:"/mission-control/forms",element:s.jsx(gt,{children:s.jsx(CGt,{})})}),s.jsx(Ce,{path:"/mission-control/tasks",element:s.jsx(gt,{children:s.jsx(YFt,{})})}),s.jsx(Ce,{path:"/mission-control/transactions",element:s.jsx(gt,{children:s.jsx(PGt,{})})}),s.jsx(Ce,{path:"/mission-control/client-portals",element:s.jsx(gt,{children:s.jsx(MGt,{})})}),s.jsx(Ce,{path:"/mission-control/client-portals/:portalId",element:s.jsx(gt,{children:s.jsx(OGt,{})})}),s.jsx(Ce,{path:"/mission-control/portal-referrals",element:s.jsx(gt,{children:s.jsx(NGt,{})})}),s.jsx(Ce,{path:"/mission-control/vendors",element:s.jsx(gt,{children:s.jsx(RGt,{})})}),s.jsx(Ce,{path:"/brokerage/forms",element:s.jsx(gt,{children:s.jsx(LGt,{})})}),s.jsx(Ce,{path:"/brokerage/vendors",element:s.jsx(gt,{children:s.jsx(DGt,{})})}),s.jsx(Ce,{path:"/mission-control/my-card",element:s.jsx(gt,{children:s.jsx(FGt,{})})}),s.jsx(Ce,{path:"/mission-control/integrations",element:s.jsx(gt,{children:s.jsx(BGt,{})})}),s.jsx(Ce,{path:"/mission-control/browser-extension",element:s.jsx(gt,{children:s.jsx(zGt,{})})}),s.jsx(Ce,{path:"/mission-control/integrations/gmail/callback",element:s.jsx(gt,{children:s.jsx($Gt,{})})}),s.jsx(Ce,{path:"/mission-control/integrations/canva/callback",element:s.jsx(UGt,{})}),s.jsx(Ce,{path:"/mission-control/integrations/meta/callback",element:s.jsx(gt,{children:s.jsx(VGt,{})})}),s.jsx(Ce,{path:"/mission-control/scorecard",element:s.jsx(gt,{children:s.jsx(QMt,{})})}),s.jsx(Ce,{path:"/admin/scorecard",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(qGt,{})})}),s.jsx(Ce,{path:"/admin/agent-activation",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(GGt,{})})}),s.jsx(Ce,{path:"/admin/scorecard/:userId",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(kge,{})})}),s.jsx(Ce,{path:"/mission-control/scorecard/:userId",element:s.jsx(gt,{children:s.jsx(kge,{})})}),s.jsx(Ce,{path:"/mission-control/relationship-scorecard",element:s.jsx(gt,{children:s.jsx(aWt,{})})}),s.jsx(Ce,{path:"/mission-control/sphere-gaps",element:s.jsx(gt,{children:s.jsx(oWt,{})})}),s.jsx(Ce,{path:"/mission-control/signals",element:s.jsx(gt,{children:s.jsx(lWt,{})})}),s.jsx(Ce,{path:"/mission-control/website-activity",element:s.jsx(gt,{children:s.jsx(uWt,{})})}),s.jsx(Ce,{path:"/mission-control/connect-page",element:s.jsx(gt,{children:s.jsx(cWt,{})})}),s.jsx(Ce,{path:"/admin/membership-reviews",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(YGt,{})})}),s.jsx(Ce,{path:"/admin/lead-notifications",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(ZGt,{})})}),s.jsx(Ce,{path:"/admin/weekly-digest",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(XGt,{})})}),s.jsx(Ce,{path:"/studio/join/:roomId",element:s.jsx(N.Suspense,{fallback:null,children:s.jsx(kGt,{})})}),s.jsx(Ce,{path:"/main-stage",element:s.jsx(N.Suspense,{fallback:null,children:s.jsx(Age,{})})}),s.jsx(Ce,{path:"/main-stage/e/:eventId",element:s.jsx(N.Suspense,{fallback:null,children:s.jsx(Age,{})})}),s.jsx(Ce,{path:"/admin/main-stage",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:null,children:s.jsx(TGt,{})})})}),s.jsx(Ce,{path:"/admin/studio-kits",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:null,children:s.jsx(AGt,{})})})}),s.jsx(Ce,{path:"/video-studio",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:null,children:s.jsx(EGt,{})})})}),s.jsx(Ce,{path:"/mission-control/video/record",element:s.jsx(SGt,{})}),s.jsx(Ce,{path:"/mission-control/video-library",element:s.jsx(gt,{children:s.jsx(IGt,{})})}),s.jsx(Ce,{path:"/my-partnership",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:null,children:s.jsx(r7t,{})})})}),s.jsx(Ce,{path:"/upgrade/:featureKey",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:null,children:s.jsx(n7t,{})})})}),s.jsx(Ce,{path:"/coaching/onboarding",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:null,children:s.jsx(i7t,{})})})}),s.jsx(Ce,{path:"/admin/partnerships",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:null,children:s.jsx(t7t,{})})})}),s.jsx(Ce,{path:"/website-apps",element:s.jsx(gt,{children:s.jsx(JHt,{})})}),s.jsx(Ce,{path:"/get-my-website",element:s.jsx(gt,{children:s.jsx(eWt,{})})}),s.jsx(Ce,{path:"/need-a-website",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(u7t,{})})})}),s.jsx(Ce,{path:"/website-apps/video_greeter",element:s.jsx(gt,{children:s.jsx(tWt,{})})}),s.jsx(Ce,{path:"/website-apps/exit_intent",element:s.jsx(gt,{children:s.jsx(rWt,{})})}),s.jsx(Ce,{path:"/website-apps/lead_magnet",element:s.jsx(gt,{children:s.jsx(nWt,{})})}),s.jsx(Ce,{path:"/embed/video-greeter/:slug",element:s.jsx(iWt,{})}),s.jsx(Ce,{path:"/embed/lead-magnet/:slug",element:s.jsx(sWt,{})}),s.jsx(Ce,{path:"/marketplace",element:s.jsx(gt,{children:s.jsx(QFt,{})})}),s.jsx(Ce,{path:"/marketplace/:productId",element:s.jsx(gt,{children:s.jsx(E7t,{})})}),s.jsx(Ce,{path:"/marketplace/cart",element:s.jsx(gt,{children:s.jsx(T7t,{})})}),s.jsx(Ce,{path:"/marketplace/orders",element:s.jsx(gt,{children:s.jsx(A7t,{})})}),s.jsx(Ce,{path:"/marketplace/orders/:orderId",element:s.jsx(gt,{children:s.jsx(k7t,{})})}),s.jsx(Ce,{path:"/marketplace/success",element:s.jsx(gt,{children:s.jsx(I7t,{})})}),s.jsx(Ce,{path:"/admin/agent-cards",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(JGt,{})})}),s.jsx(Ce,{path:"/admin/presentation-analytics",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(l9t,{})})}),s.jsx(Ce,{path:"/admin/listing-presentation-studio",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(c9t,{})})}),s.jsx(Ce,{path:"/admin/listing-revival",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(u9t,{})})}),s.jsx(Ce,{path:"/admin/contact-finder",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(O9t,{})})}),s.jsx(Ce,{path:"/admin/staging-studio",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(M9t,{})})}),s.jsx(Ce,{path:"/admin/guest-book-analytics",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(d9t,{})})}),s.jsx(Ce,{path:"/mission-control/smart-drips",element:s.jsx(gt,{children:s.jsx(Z7t,{})})}),s.jsx(Ce,{path:"/mission-control/mail-studio",element:s.jsx(W9t,{})}),s.jsx(Ce,{path:"/mission-control/direct-mail",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:s.jsx(H9t,{})})})}),s.jsx(Ce,{path:"/mission-control/presentations",element:s.jsx(gt,{children:s.jsx(P7t,{})})}),s.jsx(Ce,{path:"/mission-control/presentations/new",element:s.jsx(gt,{children:s.jsx(jge,{})})}),s.jsx(Ce,{path:"/mission-control/presentations/:id",element:s.jsx(gt,{children:s.jsx(jge,{})})}),s.jsx(Ce,{path:"/mission-control/guest-book",element:s.jsx(gt,{children:s.jsx(R7t,{})})}),s.jsx(Ce,{path:"/mission-control/guest-book/live/:id",element:s.jsx(gt,{children:s.jsx(X9t,{})})}),s.jsx(Ce,{path:"/guestbook/:slug",element:s.jsx(L7t,{})}),s.jsx(Ce,{path:"/review/:token",element:s.jsx($7t,{})}),s.jsx(Ce,{path:"/reviews/:slug/new",element:s.jsx(V7t,{})}),s.jsx(Ce,{path:"/reviews/:slug",element:s.jsx(U7t,{})}),s.jsx(Ce,{path:"/rsvp/:slug",element:s.jsx(D7t,{})}),s.jsx(Ce,{path:"/resources/:slug",element:s.jsx(M7t,{})}),s.jsx(Ce,{path:"/sign/:token",element:s.jsx(O7t,{})}),s.jsx(Ce,{path:"/blog",element:s.jsx(F7t,{})}),s.jsx(Ce,{path:"/blog/:slug",element:s.jsx(B7t,{})}),s.jsx(Ce,{path:"/mission-control/card-studio",element:s.jsx(gt,{children:s.jsx(W7t,{})})}),s.jsx(Ce,{path:"/mission-control/scheduler",element:s.jsx(gt,{children:s.jsx(UHt,{})})}),s.jsx(Ce,{path:"/mission-control/calendar",element:s.jsx(gt,{children:s.jsx(VHt,{})})}),s.jsx(Ce,{path:"/c/:shareToken",element:s.jsx(Y7t,{})}),s.jsx(Ce,{path:"/book/:slug",element:s.jsx(qHt,{})}),s.jsx(Ce,{path:"/booking/manage/:token",element:s.jsx(GHt,{})}),s.jsx(Ce,{path:"/page/:slug",element:s.jsx(QHt,{})}),s.jsx(Ce,{path:"/buyer-match/:slug",element:s.jsx(YHt,{})}),s.jsx(Ce,{path:"/mission-control/buyer-match",element:s.jsx(gt,{children:s.jsx(WHt,{})})}),s.jsx(Ce,{path:"/mission-control/buyer-match/:campaignId",element:s.jsx(gt,{children:s.jsx(KHt,{})})}),s.jsx(Ce,{path:"/mission-control/landing-pages",element:s.jsx(gt,{children:s.jsx(HHt,{})})}),s.jsx(Ce,{path:"/mission-control/landing-pages/defaults",element:s.jsx(gt,{children:s.jsx(XHt,{})})}),s.jsx(Ce,{path:"/mission-control/landing-pages/:pageId",element:s.jsx(gt,{children:s.jsx(ZHt,{})})}),s.jsx(Ce,{path:"/my-website/:siteId/edit",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(Ige,{})})})}),s.jsx(Ce,{path:"/my-website/mls-listings",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(h7t,{})})})}),s.jsx(Ce,{path:"/my-website/mls-listings/:mlsId",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(f7t,{})})})}),s.jsx(Ce,{path:"/my-website/market-report",element:s.jsx(gt,{children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(m7t,{})})})}),s.jsx(Ce,{path:"/admin/lead-sites",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(Q9t,{})})})}),s.jsx(Ce,{path:"/admin/lead-sites/themes",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(J9t,{})})})}),s.jsx(Ce,{path:"/admin/lead-sites/offers",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(e7t,{})})})}),s.jsx(Ce,{path:"/admin/lead-sites/offers/:brokerageId",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(s7t,{})})})}),s.jsx(Ce,{path:"/admin/lead-sites/:siteId/edit",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(Ige,{})})})}),s.jsx(Ce,{path:"/admin/mls-feeds",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(a7t,{})})})}),s.jsx(Ce,{path:"/admin/lead-site-analytics",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(o7t,{})})})}),s.jsx(Ce,{path:"/admin/website-interests",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(l7t,{})})})}),s.jsx(Ce,{path:"/admin/website-requests",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(c7t,{})})})}),s.jsx(Ce,{path:"/admin/website-orders",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(yWt,{})})})}),s.jsx(Ce,{path:"/admin/mls-fee-tracker",element:s.jsx(gt,{requireAdmin:!0,children:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(d7t,{})})})}),s.jsx(Ce,{path:"/m/*",element:s.jsx(N.Suspense,{fallback:s.jsx("div",{className:"flex min-h-screen items-center justify-center",children:s.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:s.jsx(C9t,{})})}),s.jsx(Ce,{path:"*",element:s.jsx(fCe,{})})]})})]})})})})})]})})});function RWt(){const t=ms(),e=t.pathname.replace(/^\/listing\//,"");return s.jsx(Oi,{to:`/public/listing/${e}${t.search}`,replace:!0})}const FNe=window.location.hostname;/(\.lovable\.app|\.lovableproject\.com)$/.test(FNe)&&/[?&]authorization_id=/.test(window.location.search)&&window.location.replace(`https://dashboard.relevelup.com/oauth-connect${window.location.search}`);if(FNe==="tile-portal.lovable.app"){const{pathname:t,search:e,hash:r}=window.location;if(/access_token=|refresh_token=|token_hash=|[?&]code=|type=(magiclink|recovery|invite|signup|email_change)/.test(r+e)){const i=t==="/"||t===""?"/claim-account":t;window.location.replace(`https://dashboard.relevelup.com${i}${e}${r}`)}}"serviceWorker"in navigator&&navigator.serviceWorker.getRegistrations().then(t=>{t.forEach(e=>void e.unregister())}).catch(()=>{});"caches"in window&&caches.keys().then(t=>{t.forEach(e=>void caches.delete(e))}).catch(()=>{});const UH="levelup:chunk-reload",LWt=t=>!!t&&/Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module/i.test(t),nJ=t=>{LWt(t)&&(sessionStorage.getItem(UH)||(sessionStorage.setItem(UH,"1"),window.location.reload()))};window.addEventListener("vite:preloadError",t=>{t.preventDefault(),nJ("Failed to fetch dynamically imported module")});window.addEventListener("error",t=>nJ(t.message));window.addEventListener("unhandledrejection",t=>{var e;return nJ((e=t.reason)==null?void 0:e.message)});window.setTimeout(()=>sessionStorage.removeItem(UH),15e3);a_e(document.getElementById("root")).render(s.jsx(NWt,{}));export{gT as $,Q_e as A,jl as B,TEe as C,Dle as D,rA as E,ug as F,wi as G,mc as H,hn as I,sn as J,XP as K,J4e as L,Va as M,lr as N,Gv as O,rF as P,Us as Q,TF as R,ef as S,iA as T,_i as U,zv as V,Wh as W,Kh as X,sC as Y,gh as Z,Di as _,Xo as a,Q4e as a$,$4e as a0,va as a1,Cq as a2,LP as a3,ql as a4,aF as a5,Gj as a6,lo as a7,Dc as a8,Ui as a9,df as aA,nF as aB,Twe as aC,Fd as aD,tu as aE,Ev as aF,KP as aG,Zm as aH,rj as aI,su as aJ,bg as aK,af as aL,w5 as aM,uf as aN,zWt as aO,wwe as aP,$6 as aQ,tT as aR,rve as aS,hr as aT,_E as aU,Cy as aV,pO as aW,c5e as aX,Lq as aY,$u as aZ,iF as a_,E4 as aa,Hj as ab,ig as ac,sve as ad,tf as ae,rf as af,nf as ag,Js as ah,wSe as ai,Sg as aj,Ur as ak,yv as al,XY as am,k5 as an,Dy as ao,Cl as ap,n5e as aq,eK as ar,lg as as,uv as at,Py as au,ds as av,gl as aw,Jo as ax,Bc as ay,pc as az,Mo as b,aYt as b$,I4 as b0,tve as b1,TA as b2,Ra as b3,u5e as b4,nve as b5,Vse as b6,JW as b7,sf as b8,sF as b9,Pq as bA,rT as bB,W4e as bC,f5e as bD,lve as bE,jq as bF,E5e as bG,mut as bH,RP as bI,lY as bJ,EY as bK,Cc as bL,sc as bM,ac as bN,oc as bO,Ym as bP,uY as bQ,h5e as bR,Do as bS,ove as bT,gve as bU,S5e as bV,WWt as bW,ms as bX,mYt as bY,pYt as bZ,yYt as b_,Bd as ba,fue as bb,Wj as bc,Yse as bd,$Ae as be,put as bf,gut as bg,yut as bh,xut as bi,_ut as bj,YW as bk,A4 as bl,nT as bm,Jm as bn,NP as bo,k5e as bp,U4e as bq,cg as br,Ule as bs,xr as bt,zr as bu,KW as bv,g5e as bw,HVe as bx,i5 as by,l5 as bz,Mle as c,P9e as c$,cYt as c0,gYt as c1,xYt as c2,e0e as c3,BWt as c4,lK as c5,cK as c6,dK as c7,hK as c8,uK as c9,ww as cA,Ant as cB,Vs as cC,Qnt as cD,Ynt as cE,q4e as cF,hve as cG,I5e as cH,$Z as cI,UZ as cJ,xC as cK,Cu as cL,VZ as cM,Pu as cN,V4e as cO,ad as cP,eXt as cQ,PZt as cR,QZt as cS,Oet as cT,k0e as cU,J_e as cV,k6e as cW,I6e as cX,I0e as cY,d5e as cZ,ZW as c_,mK as ca,fK as cb,ant as cc,oYt as cd,bYt as ce,vYt as cf,dYt as cg,hYt as ch,ont as ci,Use as cj,wYt as ck,_Yt as cl,uYt as cm,lYt as cn,LU as co,fYt as cp,ive as cq,HAe as cr,qZ as cs,Eg as ct,et as cu,vg as cv,An as cw,nd as cx,IEe as cy,tA as cz,lnt as d,VP as d$,tF as d0,CY as d1,oi as d2,qs as d3,Vut as d4,WAe as d5,Rut as d6,Ret as d7,hQe as d8,ba as d9,mT as dA,Y4e as dB,KWt as dC,Gse as dD,dve as dE,v5e as dF,YK as dG,hKt as dH,Z4e as dI,kb as dJ,Ce as dK,Oi as dL,OWt as dM,e5e as dN,Kse as dO,Wl as dP,Q3e as dQ,Nl as dR,ph as dS,Jn as dT,Uv as dU,Qr as dV,zc as dW,no as dX,ave as dY,PY as dZ,UP as d_,to as da,cve as db,eT as dc,c_e as dd,Xtt as de,l5e as df,PP as dg,Nq as dh,dj as di,Zse as dj,P3e as dk,Swe as dl,urt as dm,XW as dn,IG as dp,Awe as dq,z9e as dr,ZK as ds,Iwe as dt,jwe as du,XKt as dv,QKt as dw,eYt as dx,tYt as dy,ZKt as dz,Qo as e,LB as e$,G4e as e0,xA as e1,lh as e2,XSe as e3,QSe as e4,Zje as e5,Xje as e6,fO as e7,mO as e8,gj as e9,Bv as eA,V4 as eB,q4 as eC,D9e as eD,aKt as eE,mKt as eF,H4e as eG,nQe as eH,t5e as eI,rK as eJ,pve as eK,Rbe as eL,b5e as eM,cC as eN,uC as eO,dC as eP,hC as eQ,pT as eR,X_ as eS,nYt as eT,B4e as eU,Iq as eV,jw as eW,_A as eX,YG as eY,u7 as eZ,MMt as e_,uCe as ea,uve as eb,Fu as ec,het as ed,ISe as ee,Rq as ef,ea as eg,Ou as eh,K6e as ei,GWt as ej,qWt as ek,dUe as el,Ge as em,z4e as en,s5e as eo,m5e as ep,r5e as eq,yA as er,BK as es,zK as et,eA as eu,iC as ev,bwe as ew,N4 as ex,JT as ey,G4 as ez,Oo as f,VZt as f$,DB as f0,zm as f1,Lw as f2,OMt as f3,hx as f4,cB as f5,Wi as f6,hs as f7,WX as f8,qf as f9,XZt as fA,Uut as fB,OZt as fC,BZ as fD,Cwe as fE,V9e as fF,jd as fG,Rf as fH,Nut as fI,bZt as fJ,wZt as fK,y5e as fL,_T as fM,Ho as fN,idt as fO,LZt as fP,MZt as fQ,DZt as fR,k4 as fS,FAe as fT,NZt as fU,eve as fV,zZt as fW,WZt as fX,BZt as fY,KZt as fZ,$Zt as f_,wB as fa,$a as fb,$i as fc,N7 as fd,Jy as fe,P_ as ff,_B as fg,fs as fh,nXt as fi,hv as fj,Mu as fk,aN as fl,FA as fm,iXt as fn,qje as fo,FRt as fp,X4e as fq,U6 as fr,FZt as fs,ZZt as ft,lC as fu,OY as fv,RZt as fw,JZt as fx,YZt as fy,qut as fz,$n as g,$Kt as g$,qZt as g0,GZt as g1,HZt as g2,UZt as g3,JXt as g4,L9 as g5,aut as g6,Gm as g7,rnt as g8,_Xt as g9,aXt as gA,oXt as gB,xXt as gC,dXt as gD,JMt as gE,Uwe as gF,xZt as gG,_Zt as gH,vZt as gI,qse as gJ,K4e as gK,i5e as gL,nA as gM,p5e as gN,x5e as gO,fve as gP,mve as gQ,w5e as gR,tK as gS,F4e as gT,cue as gU,OKt as gV,DKt as gW,FKt as gX,xKt as gY,BKt as gZ,zKt as g_,aOt as ga,oOt as gb,lXt as gc,vXt as gd,bXt as ge,cXt as gf,B9e as gg,T4 as gh,a5e as gi,o5e as gj,A5e as gk,T5e as gl,JKt as gm,rYt as gn,vI as go,uXt as gp,lZt as gq,RKt as gr,fXt as gs,pXt as gt,mXt as gu,yXt as gv,gXt as gw,hXt as gx,zZ as gy,sXt as gz,_5e as h,vKt as h$,UKt as h0,yKt as h1,JXe as h2,nQ as h3,dZt as h4,pZt as h5,fZt as h6,mZt as h7,uue as h8,zct as h9,EXt as hA,TXt as hB,AXt as hC,XFt as hD,IXt as hE,jXt as hF,CXt as hG,PXt as hH,NXt as hI,RXt as hJ,LXt as hK,DXt as hL,MXt as hM,OXt as hN,zXt as hO,$Xt as hP,wXt as hQ,SXt as hR,TU as hS,Uf as hT,HKt as hU,qKt as hV,WKt as hW,LKt as hX,AKt as hY,MKt as hZ,_Kt as h_,hZt as ha,cZt as hb,uZt as hc,yZt as hd,Vct as he,qct as hf,gZt as hg,EYt as hh,TYt as hi,AYt as hj,kYt as hk,IYt as hl,jYt as hm,CYt as hn,PYt as ho,Bnt as hp,SZt as hq,VAe as hr,But as hs,Mut as ht,ddt as hu,t2e as hv,Yje as hw,Qje as hx,SYt as hy,ZFt as hz,Jt as i,UYt as i$,jje as i0,VKt as i1,GKt as i2,NKt as i3,IKt as i4,jKt as i5,kKt as i6,CKt as i7,PKt as i8,EKt as i9,L3t as iA,dQ as iB,wCe as iC,XXt as iD,WXt as iE,GXt as iF,HXt as iG,G4t as iH,qI as iI,sge as iJ,KK as iK,dKt as iL,R9e as iM,L9e as iN,MTe as iO,m_e as iP,kXt as iQ,JSe as iR,FXt as iS,BXt as iT,UXt as iU,VXt as iV,Wtt as iW,rit as iX,FYt as iY,zYt as iZ,$Yt as i_,TKt as ia,bKt as ib,wKt as ic,SKt as id,Fet as ie,l7e as ig,Htt as ih,Jse as ii,fKt as ij,nrt as ik,AZt as il,TZt as im,EZt as io,kZt as ip,CZt as iq,UMt as ir,RYt as is,LYt as it,iZt as iu,sZt as iv,aZt as iw,fAe as ix,Sr as iy,KXt as iz,s as j,H4t as j$,VYt as j0,qYt as j1,GYt as j2,ZYt as j3,HYt as j4,WYt as j5,KYt as j6,YYt as j7,XYt as j8,MYt as j9,eQt as jA,PE as jB,QXt as jC,FB as jD,nQt as jE,h4t as jF,iQt as jG,rQt as jH,YXt as jI,fQ as jJ,VA as jK,pQ as jL,q3t as jM,aQt as jN,uQt as jO,cQt as jP,rP as jQ,ZXt as jR,$H as jS,MNe as jT,yVt as jU,tQt as jV,dQt as jW,hQt as jX,W4t as jY,K4t as jZ,_Q as j_,BYt as ja,QYt as jb,JYt as jc,tZt as jd,rZt as je,nZt as jf,NYt as jg,DYt as jh,OYt as ji,tut as jj,pN as jk,coe as jl,NY as jm,ySe as jn,yB as jo,gn as jp,sN as jq,jSe as jr,sVt as js,cVt as jt,hVt as ju,Yj as jv,qV as jw,qXt as jx,x3t as jy,Cv as jz,Mc as k,g5 as k0,e4t as k1,sQt as k2,mQ as k3,oQt as k4,lQt as k5,UTe as k6,cot as k7,k9 as k8,IZt as k9,jZt as ka,sKt as kb,xv as l,cnt as m,Ole as n,Be as o,AEe as p,Nn as q,N as r,n9 as s,Hse as t,jr as u,Wse as v,QW as w,rs as x,od as y,qa as z};