const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/BoostCompanion-8vMfNIQL.js","assets/BoostPanel-DBQToaH7.js","assets/useAssistantChat-Co-Y1sye.js","assets/arrow-up-right-BQIQmETF.js","assets/useSmartQueue-CWvvk5QY.js","assets/useBoostGift-Cl8FnL8N.js","assets/rotate-ccw-KCg6JvXe.js","assets/sun-DUS8BzWl.js","assets/announcements-CHWMrHjI.js","assets/pause-FKsRZzLd.js","assets/bell-off-W0-AwRwt.js","assets/CommercialMarketplace-K0IRjonM.js","assets/LeadSiteHome-CRAFOob0.js","assets/useLeadSiteSearchSuggestions-CPRESDBb.js","assets/hash-CeaiMxbn.js","assets/map-CRQLl9Ix.js","assets/AgentReviewsSection-B_4aezuH.js","assets/credits-PIR_bev7.js","assets/ListingCarouselModule-BxpeupIW.js","assets/imageOptimization-Csrlnz8M.js","assets/maximize-Cr8XArHE.js","assets/ExchangeListingsSection-COuU8u0l.js","assets/leadSiteAgent--GbV6IdE.js","assets/ScrollLivingHero-zTMFaR6C.js","assets/LeadSiteLuxuryHome-BGL0h8DB.js","assets/RecentSalesSnapshot-aZ1EONQr.js","assets/LeadSiteExchangeListings-D7uNMBrY.js","assets/truck-CPwmvvVf.js","assets/LeadSiteLuxuryHome-DKt_VWIz.css","assets/LeadSiteLandRanchHome-BlKfmR7u.js","assets/use-in-view-C3Ua4Tof.js","assets/tree-pine-C-j5MgdV.js","assets/mountain-Bs0TjFve.js","assets/LeadSiteSearch-B4mltbMt.js","assets/ListingCardExtras-BBA8VDa3.js","assets/bell-ring-CiRNbhzm.js","assets/useInfiniteQuery-Cy5wlGLD.js","assets/LeadSiteMap-ZeOgDfuc.js","assets/LeadSiteLuxurySearch-BrALIqpU.js","assets/LeadSiteListingDetail-KR9aiRRA.js","assets/ListingVideoTour-9_Cc4QZ7.js","assets/expand-BkY20SQM.js","assets/car-B2qGnVJX.js","assets/thermometer-D3hPxm5o.js","assets/snowflake-BmeixC_7.js","assets/waves-CukerTUU.js","assets/useListingVideos-O7MEn_Ge.js","assets/LeadSiteLuxuryListingDetail-Ba2KFK_e.js","assets/LeadSiteAbout-Dk_wfJZY.js","assets/LeadSiteLuxuryAbout-CTXSV6Eu.js","assets/ExpReadySpotlight-CcD2np1N.js","assets/LeadSiteCommunity-DazlDSb3.js","assets/wine-Dcq7nXHc.js","assets/trees-BjzadMke.js","assets/plane-CV4MkSdO.js","assets/music-C1A-uJW9.js","assets/LeadSiteSellers-CLkqlq5h.js","assets/LeadSiteCityPage-Blm3wrjm.js","assets/CityFaqSection-Dk06fBmA.js","assets/LeadSiteSubdivisionPage-BuwnxgZD.js","assets/LeadSiteFocusPage-Dr_ardkp.js","assets/LeadSiteExpReady-B1JF-c5o.js","assets/paintbrush-LV4Gxw9y.js","assets/OrgSiteLayout-BK5tyKt-.js","assets/orgSiteBrand-DKMUe12O.js","assets/OrgSiteHome-6lS_1MSE.js","assets/OrgSiteAgents-CGii4xwQ.js","assets/OrgSitePages-B-T4zbvx.js","assets/OrgSiteListings-BidkX5iP.js","assets/CanvaSupport-BaCJ0Wbz.js","assets/unplug-D1DHMz0f.js","assets/SmsOptIn-BbYqFyKm.js","assets/signpost-BgZE9Kk6.js","assets/ConnectChatGPT-DBTSAfnT.js","assets/circle-check-big-qsU043Wq.js","assets/SubscriptionSuccess-C_MKnjlE.js","assets/SetupBrokerage-Uvem_4mB.js","assets/InviteSignup-BYys3y22.js","assets/eye-off-CVjuU6bi.js","assets/CoachingHub-C10jVq9g.js","assets/useCoaching-DA74nXXT.js","assets/CoachAgentWorkspace-2I2RV2Af.js","assets/CoachingFiles-Dqp7PgUQ.js","assets/folder-open-DUDYaDJZ.js","assets/save-y3B4JqXI.js","assets/MyCoach-fRvS9FyN.js","assets/CoachReviews-CnLmY7CC.js","assets/circle-x-DglvU1lx.js","assets/AdminCoaching-C0mR3yfK.js","assets/arrow-left-right-Y3JPeql7.js","assets/user-minus-j2qDf5-U.js","assets/inbox-cAC_Y9yI.js","assets/CoachBilling-CY1SEumG.js","assets/credit-card-CRIrdAQJ.js","assets/CoachSettings-ANsd98XR.js","assets/GoogleCalendarCard-Cciobhmq.js","assets/calendar-off-DSz7UvIl.js","assets/useCoachGoogleCalendar-DzVjPCeX.js","assets/link-BfdNr2OS.js","assets/Microsoft365Return-BQT5lEMk.js","assets/useMicrosoft365-VpqCbXv6.js","assets/freshAccessToken-D9mHqlBS.js","assets/CoachWaitlist-vVwJUs00.js","assets/mail-check-BW3Kz6Wi.js","assets/CoachProfile-B38-l47Q.js","assets/Trial-BrFgXI77.js","assets/testimonial-avatar-5-DBoTqx4u.js","assets/TrialSuccess-Bu38OEGd.js","assets/party-popper-CXvRcthl.js","assets/LaborDaySale-Dxvb-Fa1.js","assets/OpenHouseInviteModal-DX9wGpEP.js","assets/infinity-D46LrQWr.js","assets/workflow-CpsbMQrP.js","assets/BrokerageLaborDaySale-CL8IoADQ.js","assets/BrokerageSolutions-BcU5N1ll.js","assets/receipt-Jis4Y8Sv.js","assets/scale-BU5rkU9G.js","assets/pencil-line-C3kzV9cd.js","assets/Upgrade-CQba9lz8.js","assets/log-in-AE-j1vTg.js","assets/InstagramGift-s9YHE2ky.js","assets/VideoShare-cOCZJ_Wv.js","assets/VideoPageTemplates-DyLeEGgM.js","assets/flag-9FBM8bW1.js","assets/message-circle-heart-B6qqltMG.js","assets/door-open-DuRYLzJj.js","assets/brain-TgAi1FED.js","assets/coffee-6t-QxdXz.js","assets/CommercialWizard-_zY2Oc2Z.js","assets/useListingExchange-kdq_isGE.js","assets/useTeamListingAccess-JP5I_sB3.js","assets/CommercialWorkspace-t-wlFaGY.js","assets/ListingSocialDialog-_cu17iBc.js","assets/useAgentBrand-Ht_SZ426.js","assets/ListingPhotoGrid-BNecH88r.js","assets/sortable.esm-DuPikaz7.js","assets/grip-vertical-C9MuGQjC.js","assets/ShareListingDialog-BCHn7ygW.js","assets/EmailListingToSphereDialog-C3IKtqzx.js","assets/index-bKpQuXEk.js","assets/separator-DLG1TTu1.js","assets/GmailComposeDialog-C5eq1lRv.js","assets/useMassEmailReady-BKSt43vR.js","assets/useVerifiedSenderCheck-BGPnv429.js","assets/VerifySenderRequiredDialog-DxB1WEHn.js","assets/useContactIntakePage-Bvb99sjC.js","assets/ToContactAutocomplete-CrKkGABf.js","assets/paperclip-Dl0AosbW.js","assets/file-search-BR1CJkWZ.js","assets/qr-code-Cf9vIVzb.js","assets/CommercialPitchPreview-BfdsK-b2.js","assets/PublicLiveEvent-DtffWjQN.js","assets/pin-BYVdoNKN.js","assets/arrow-up-4dlAeuJW.js","assets/useLiveEngagement-DZXpa9rE.js","assets/sparkle-PTJS5XJp.js","assets/LiveEvents-D8Gm5LBZ.js","assets/AdminPageHeader-DBi3-ecx.js","assets/useLiveEvents-BH-aP18I.js","assets/image-plus-BCOdCXoh.js","assets/LiveEventConsole--fFZlTJ5.js","assets/mouse-pointer-click-DDUfcx1S.js","assets/ban-BzJ2wH0q.js","assets/Dashboard-Capa4jkL.js","assets/useContentEngagement-e6CpCil3.js","assets/usePrograms-CK8xdJRF.js","assets/timezone-CbF1Dd1A.js","assets/addMilliseconds-ByNtGfZl.js","assets/isWithinInterval-DT-K3Ztg.js","assets/useGmailIntegration-COFgq36G.js","assets/GoalTargetsDialog-CyjGO0fm.js","assets/useBrokerageContent-OuLze1ZX.js","assets/beta-badge-3k8Fp_Mr.js","assets/useEventGamification-DNHKL3GG.js","assets/RelationshipHealthWidget-VyCaCWrW.js","assets/useRelationshipScore-ClDHe2mv.js","assets/file-image-CWkhnUgp.js","assets/Profile-CQj7bw_w.js","assets/RichTextEditor-DbHhsHGi.js","assets/index-DUowumS_.js","assets/index-PJC6E6RU.js","assets/index-BGs1MeRH.js","assets/heading-1-CNgtdjtA.js","assets/heading-2-C2GHEKuy.js","assets/undo-OUJL7yZb.js","assets/list-ordered-DeXVhFaV.js","assets/align-left-BWiwiozI.js","assets/align-right-CdGYUEVo.js","assets/ImageCropper-C-4oOugk.js","assets/zoom-out-DGkHtJa-.js","assets/rotate-cw-CK1gwZSb.js","assets/ImageCropper-D8Md-CES.css","assets/useBrandKit-9dOLLvFu.js","assets/useStagingStudio-BS4_ucOB.js","assets/checkoutTab-Cf84e04b.js","assets/BrokerageLogoUpload-CQ5uvQaI.js","assets/user-round-BV_vhoI_.js","assets/mail-x-d36AQ1RA.js","assets/Events-Dnsuwdy6.js","assets/EventLeaderboard-DnreHqpf.js","assets/medal-C5D_ZDVn.js","assets/history-CLdT4-mz.js","assets/EventDetail-QCPn68IH.js","assets/ShareButton-BuNErYLb.js","assets/user-cog-hw_v_FKh.js","assets/Apps-CcO8Pofw.js","assets/monitor-play-CjrHD3fd.js","assets/skip-forward-CcTomk74.js","assets/Templates-HEyRseLF.js","assets/TemplateDetail-CciFqunH.js","assets/Programs-BMOnKKWg.js","assets/ProgramDetail-B5mBPnU3.js","assets/accordion-Dx3qS2md.js","assets/index-BF2ZJoNz.js","assets/ProgramEnroll-6bdIjf9B.js","assets/tag-m7-PA-hE.js","assets/ProgramWorkspace-CUDDm2OU.js","assets/file-spreadsheet-iy8p6svq.js","assets/layout-template-DhAyDim1.js","assets/Programs-Xxv_2WHL.js","assets/route-D_pooAKX.js","assets/collapsible-C46oHlCo.js","assets/AcademyVideoDetail-C_xJ_4yr.js","assets/LinkedTemplatePills-BlITg68r.js","assets/ToolboxDetail-DjaKDWkR.js","assets/SocialSwag-Yf7HAECC.js","assets/SocialStudio-LxB5D2aB.js","assets/CanvaImportDialog-Clc67wVa.js","assets/useCanvaMailStudio-DUkpAoo_.js","assets/unlink-Do7PVH-n.js","assets/platforms-D7GqUQhf.js","assets/music-2-DCp4_7dK.js","assets/jpegConvert-B0Ga8uXm.js","assets/repeat-2-XgWqRoEn.js","assets/scheduleTz-Yq-0FBS4.js","assets/calendarTz-JHe45SGp.js","assets/useCalendarTimezone-D7RXPwoA.js","assets/CalendarSettingsDialog-DsR16k8q.js","assets/earth-HXWHQN_t.js","assets/edgeError-BEitrywf.js","assets/jszip.min-U4VM72JP.js","assets/settings-2-DtXWjNqe.js","assets/MarketingStudio-B9hwTxrC.js","assets/message-square-quote-Cg10h42A.js","assets/BrandKit-CC5ekgV9.js","assets/useBrandPresets-ejrum7Pn.js","assets/BrandingBarEditor-BguBh4MK.js","assets/ReactKonvaCore-EOanP8Z-.js","assets/index-Y4qo4HvS.js","assets/ListingTemplates-pTjb451Q.js","assets/index-xVp0PEHv.js","assets/EditorialTemplate-MgpXBF7z.js","assets/PersonalBranding-Cf77Majz.js","assets/toggle-group-fGpIz8ol.js","assets/SocialSwagDetail-aymdDdNY.js","assets/Community-PhPlCz97.js","assets/MentionTextarea-D1vdue-c.js","assets/reply-BdT4Xp0D.js","assets/pin-off-BIg-AC6i.js","assets/Support-DK8Lwgc5.js","assets/SupportAttachmentList-B8o5PA2V.js","assets/file-video-bvXTdNru.js","assets/BrokerageResources-Bf2l0Dih.js","assets/AdminDashboard-BCW6Nznn.js","assets/coins-DpgYqwJ0.js","assets/shopping-bag-CNIObXCG.js","assets/flask-conical-BlNFLrWA.js","assets/database-C1QaEq5v.js","assets/MemberManagement-DqA34ghr.js","assets/SendCelebrationDialog-BNEu7y_4.js","assets/sortable-table-head-dvjn0D4m.js","assets/arrow-down-C0hrWrUt.js","assets/useTeams-BDXoq6Ir.js","assets/CreateTeamDialog-BAA6ilwn.js","assets/TeamSharedAssetsView-z7gyx2Qk.js","assets/LeadPondView-B1Xelw8T.js","assets/arrow-right-left-DFUEAVd7.js","assets/sticky-note-hULc_Dot.js","assets/droplets-DT_4xUX5.js","assets/hand-Ga5as36w.js","assets/contact-B0GR2nJv.js","assets/crown-PWhHwP3M.js","assets/calendar-heart-8aCp8evM.js","assets/UnassignedMembers-BuAxVSTF.js","assets/InviteCodes-DSDdZyHN.js","assets/Events-D1uKTOMn.js","assets/useNotifications-Bv8_bDgF.js","assets/repeat-DA5NXJGy.js","assets/MCPAuditLog-CgvJckkE.js","assets/shield-alert-B1jLhPMs.js","assets/Templates-DtoEEONz.js","assets/Academy-DM1nrjbc.js","assets/LinkedTemplatePicker-DcbKZvXm.js","assets/Toolbox-C0jW4ntU.js","assets/SocialSwag-BNSug24S.js","assets/SocialSwag2-B4PvBJpi.js","assets/Community-DopXr0t5.js","assets/Analytics-C3DUAFNC.js","assets/ShareAnalytics-CpAIS0gy.js","assets/mouse-pointer-xytJOnlX.js","assets/panels-top-left-DjVnyXOk.js","assets/LineChart-B1O60hDO.js","assets/chrome-D0tJk2E2.js","assets/BrokerageResources-Df4WSii6.js","assets/DashboardManagement-lgLc1rx3.js","assets/SupportTickets-Dh3dHV-q.js","assets/EmailTemplates-BJQDsBi_.js","assets/index-Dw_pVDbp.js","assets/code-DhB2X4s8.js","assets/variable-CRdGKFwq.js","assets/monitor-8JGR-gpG.js","assets/AgentEmailTemplates-C-e3Gv--.js","assets/BrokerageDashboard-DhjPZLaf.js","assets/MyBrokerage-CLVAc7bJ.js","assets/useBrokerageOnboarding-C0pSq-4M.js","assets/OnboardingChecklist-sw9YYSnT.js","assets/BrokerageContent-CpH4bg9K.js","assets/BrokerageHelpBoard-BKrQlvI8.js","assets/useBrokerageHelpBoard-DUJ18WPt.js","assets/BrokerageHelpBoardNew-RwrNkj6N.js","assets/BrokerageHelpBoardDetail-BbZziqts.js","assets/Newsletters-CobTDp9Q.js","assets/useMailingAddressGate-D7y3rHUp.js","assets/NewsletterGraphicsPicker-9eAcwkpE.js","assets/underline-BEhg6et0.js","assets/SenderAddressDialog-e1IAuD4V.js","assets/uploadBase64Images-Bp9yXibW.js","assets/SendNewsletterDialog-DVMJv3Vv.js","assets/undo-2-Bu0hIIbA.js","assets/useContactCustomTags-aoyDNFJ8.js","assets/useSmartLists-CWwLJ-ld.js","assets/code-xml-D-IoBkPP.js","assets/list-filter-D16I80IK.js","assets/NewsletterDetail-BgCwunF3.js","assets/Newsletters-CY42IWdf.js","assets/library-OwFhakse.js","assets/MemberBroadcasts-BiC_7Pwp.js","assets/bookmark-plus-CRnwyVye.js","assets/BoostAnnouncements--orjuIF7.js","assets/NewsletterGraphics-CkM2i9ll.js","assets/Wishlist-DI0vovFP.js","assets/WishlistDetail-BJVc2PCO.js","assets/LevelUpBrief-UmtB5RZc.js","assets/AdditionalServices-COOxpeZH.js","assets/Discounts-DFcFVeue.js","assets/Subscriptions-CpaQgZmI.js","assets/instagramEmailReview-DK4Cq88H.js","assets/InstagramGiftEmails-CyW3OlT1.js","assets/Referrals-b7y-7TO_.js","assets/AgentOSControlCenter-v1cCtxJQ.js","assets/AskAI-hCvsVa86.js","assets/InnerCircleHome-DrswTsuU.js","assets/SnoozeContactDialog-BjzH-Uoz.js","assets/pen-tool-Bk0VN_mn.js","assets/milestoneMail-Cs6qfJaR.js","assets/handoff-B7AOa2Ye.js","assets/milestones-De303X1G.js","assets/stamp-UAgoELU5.js","assets/mail-open-BdyDwNF8.js","assets/InnerCircleContacts-WxA4Djay.js","assets/mailingAddress-BJ5Zh-Ye.js","assets/SyncDirectionSelector-DEZpVFXN.js","assets/refresh-ccw-ChzYYD2m.js","assets/merge-CI5105RO.js","assets/ContactCriteriaForm-CCs6wfuX.js","assets/usePopbys-DmB-iTzQ.js","assets/ContactTagChip-iNZYs3Q3.js","assets/info-CdYR2g5U.js","assets/RelationshipScoreBadge-E-VIIBLn.js","assets/MailStudioHandoffButton-sJrD4kYE.js","assets/useVideoShareTracking-Cf5CukgI.js","assets/EnrollContactsDialog-C-hiiXTf.js","assets/useDripCampaigns-3h0LGITf.js","assets/CampaignBuilderDialog-bDhxrBMt.js","assets/VideoLibraryPicker-DKuQxXZD.js","assets/VideoUploadDialog-CGdu_71K.js","assets/useVideoTouch-DeJcg5yj.js","assets/NeighborhoodFilter-CBLGA8fA.js","assets/useNeighborhoods-CHERkS74.js","assets/sphereMap-CB44bYOF.js","assets/sprout-XaPvxNld.js","assets/ContactAvatar-BDgj4EoO.js","assets/user-x-DAVALTo6.js","assets/map-pinned-oeJ5TKIr.js","assets/InnerCircleContactDetail-CQm-b48t.js","assets/useCMA-qJddoFCk.js","assets/useClientPortal-ChwpsTM5.js","assets/futureSeller-BkhOXhcJ.js","assets/useSentEmails-FbaKwsi-.js","assets/propertyService-wGw1PCx8.js","assets/building-CuZp1lc3.js","assets/archive-BI-Kpfk_.js","assets/useContactFinder-Vl8yDZoj.js","assets/SentEmails-Dv2MKo5t.js","assets/InnerCirclePlans-b4qp2OSX.js","assets/pen-Bz0gCUO2.js","assets/CMAList-Bek4luu6.js","assets/SendCMADialog-Y4kzAV76.js","assets/UpgradeLockedCard-yaLjYH-r.js","assets/CMABuilder-CVl_K1aK.js","assets/VideoRecorder-BsKLDL-H.js","assets/flip-horizontal-Cxh59YCS.js","assets/videoSegmentation-23AN6N06.js","assets/monitor-up-DoTiI3iq.js","assets/mic-D0jSn6bU.js","assets/ListingPresentations-CIHhqI2b.js","assets/session-Iw2vcBV-.js","assets/jspdf.es.min-KiPRute2.js","assets/SendPresentationDialog-D9coZZ0B.js","assets/ListingPresentationBuilder-CAKtiV4Z.js","assets/PdfCanvasPreview-DTFIPGy6.js","assets/pdf.worker.min-BD-ONaJe.js","assets/ImageUploadField-DMVbSfb0.js","assets/move-B4XyZLj9.js","assets/InnerCirclePopbys-BzLNVLdE.js","assets/locate-D07f14Rt.js","assets/navigation--ZEptdbQ.js","assets/ListingExchange-BLyMOvou.js","assets/ListingLaunchKitModal-B7Fojs-4.js","assets/ListingSelectionBar-D8agyGjg.js","assets/musicVideoHandoff-Bs6IOG8F.js","assets/ListingDetail-BkhSUWHk.js","assets/ListingForm-CYHnUVRP.js","assets/CustomizeListingPage-BPfH9GQ9.js","assets/box-uLej_X_V.js","assets/VideoStudio-DSpu9F6u.js","assets/wifi-7wAwq_q5.js","assets/VideoShareWithTemplate-JRCFf_7f.js","assets/browser-CjSdxGTc.js","assets/BackdropPanel-CFYe6ZEA.js","assets/panel-right-close-C0ocVnDM.js","assets/clapperboard-C2va19NU.js","assets/scissors--d1gCIBr.js","assets/switch-camera-BEBdBc9v.js","assets/type-D7grHekD.js","assets/StudioGuestJoin-DE8cSrue.js","assets/video-off-B9pVvrnI.js","assets/VideoLibrary-3IO2QVlX.js","assets/hard-drive-DkQLX1yo.js","assets/DealPipeline-B8EbtsMy.js","assets/lucide-react-DbAsyUb5.js","assets/archive-restore-NS12J8X1.js","assets/arrow-down-right-ufXe-fb6.js","assets/badge-check-oPMfDJut.js","assets/circle-user-Db1wyDfY.js","assets/beaker-qU2AllcX.js","assets/mouse-pointer-2-C1J-9IKd.js","assets/brain-circuit-Sdl5G-XR.js","assets/calendar-x-DR2Cpe4Z.js","assets/file-code-D6H5WhOf.js","assets/table-CJlbbeY-.js","assets/circle-dollar-sign-BpJS2OW1.js","assets/clock-3-B9AGjDrF.js","assets/sunset-Ci6ht23Q.js","assets/cloud-upload-C-uabXe3.js","assets/corner-down-right-BCm2FD4o.js","assets/eraser-BNvp2iCY.js","assets/file-check-2-a74TwQ-s.js","assets/hammer-CoYrJXDW.js","assets/file-down-Dm1doTZ_.js","assets/file-plus-2-Bger5BSO.js","assets/piggy-bank-flHqFEk_.js","assets/folder-plus-QFtY9vTo.js","assets/folder-dBHe70Jx.js","assets/footprints-6NBBAJiN.js","assets/gem-D4QATrTr.js","assets/hand-heart-NsuifYA-.js","assets/heading-3-CQZicjJW.js","assets/heart-handshake-De3gAXdi.js","assets/id-card-DuyD4Jta.js","assets/locate-fixed-DKJNUY5z.js","assets/list-plus-kRwBijZ3.js","assets/lock-keyhole-Bb1EsM1Z.js","assets/mail-warning-DQFCMHBF.js","assets/message-square-more-CZGeZZZ7.js","assets/message-square-plus-BWgeH_9D.js","assets/message-square-reply-n3CQNE7J.js","assets/messages-square-DQxw-pdi.js","assets/skip-back-CK-Xdq5H.js","assets/octagon-alert-DGMv5_0u.js","assets/power-off-D38FnHsX.js","assets/power-Dy8bP48X.js","assets/printer-ssqSow2u.js","assets/rectangle-vertical-BzWwudCs.js","assets/scroll-text-CYlsbIaU.js","assets/shield-off-2NY1cEQq.js","assets/shield-question-D7gLIHBw.js","assets/shuffle-YdiVlQMM.js","assets/table-2-BgdP2Mcy.js","assets/tags-CZuCnR9r.js","assets/text-cursor-input-C3dIETa7.js","assets/thumbs-down-hPlyclLB.js","assets/twitter-DV9J4EPd.js","assets/user-round-check-CT2cem0i.js","assets/user-round-search-ByZf-4HU.js","assets/users-round-ByBhLiKl.js","assets/useCommissionPlans-aPzW9y2Y.js","assets/ComplianceMessageThread-CfhqVDQr.js","assets/SendForSignatureDialog-G0kpwhU-.js","assets/useFormEnvelopes-CnUiw4DS.js","assets/PortalInviteDialog-TilBskZn.js","assets/CardVideoRecorderDialog-Clfo9xCr.js","assets/PlaybookLibraryDialog-B9_fIRqz.js","assets/PortalListView-BDYABU-f.js","assets/complianceMetrics-Ce83UgLe.js","assets/FormsLibrary-NH01TNah.js","assets/FormPlacementEditor-DdW_HKcS.js","assets/TransactionCoordinator-6kUk2Ms-.js","assets/PortalReferrals-Cu5lvAK5.js","assets/usePortalReferrals-BpdsgV3s.js","assets/AgentVendors-CNRTT_mQ.js","assets/VendorFormDialog-DKyd8OSz.js","assets/BrokerageForms-DchZ2WB-.js","assets/BrokerageVendors-DGgazgzY.js","assets/ClientPortalsHub-YpV4G6rh.js","assets/PortalMessagesPanel-Cn1HJ7XZ.js","assets/ClientPortalDetail-CxDLmP4d.js","assets/MyCardEditor-DQssayrF.js","assets/CardBlocksEditor-XLIttD80.js","assets/Integrations-DtJKKJ3Q.js","assets/SesIntegrationCard-CwFjEIjy.js","assets/RecruitVerifiedSenders-BBupQJaG.js","assets/Microsoft365Card-CwJ9AUXA.js","assets/BrowserExtension-BhPrkDKB.js","assets/IntegrationsGmailCallback-CCGfrY1k.js","assets/IntegrationsMetaCallback-9kley_ls.js","assets/AgentActivation-H6Fc1loY.js","assets/MembershipReviews-Ctrxj0N1.js","assets/LeadNotifications-BMFd9X1b.js","assets/WeeklyDigest-DtwBgLub.js","assets/AgentPoints-CRniqOos.js","assets/AgentCards-D-1AUYJn.js","assets/Marketplace-qjaBREIw.js","assets/RewardStore-fAxKsWij.js","assets/usePointRewardSettings-CKKLKydj.js","assets/Integrations-BFtQfsCx.js","assets/SocialConnections-B6hO-F8D.js","assets/SocialAutopilot-jYvgaXAl.js","assets/McpUpdates-8lXVrSDI.js","assets/NotificationSettings-DajI5V8d.js","assets/PresentationAnalytics-DGqMqcf6.js","assets/ListingPresentationStudioAdmin-e6qb6orv.js","assets/ListingRevivalAdmin-BFvqw6Q_.js","assets/useListingRevivalAccess-1Kg8EcbW.js","assets/GuestBookAnalytics-CpyQlRJv.js","assets/IntegrationsCallback-Cc-fO1SL.js","assets/AdminRecruiting-DHCyS9sd.js","assets/RecruitPipelineStageEditor-BcflG_TF.js","assets/index-Dzim5nzm.js","assets/BrokerageRecruiting-DH4QVfWl.js","assets/600-BSKZD_mM.css","assets/BrokerageOnboarding-4uVblTTo.js","assets/BrokerageTransactions-BgJChh_y.js","assets/useDealEscrow-B2wgh-1p.js","assets/BrokerageOperations-BmcOwe6d.js","assets/renewals-DEHHXlkR.js","assets/WebsitesHub-ClhEgLSo.js","assets/useMyWebsites-BzaAKgtP.js","assets/TeamWebsite-vRCoHE1H.js","assets/OrgSiteBuilder-H9_Scf8V.js","assets/SiteSwitcher-rvueurW6.js","assets/BrokerageWebsite-Ckwd1KfY.js","assets/BrokerageCommissionPlans-CyrAF_bE.js","assets/BrokerageContentActivity-CKieVcvF.js","assets/BetaSocialPostGenerator-AhJq0UeD.js","assets/AdminLMS-BQyq351Z.js","assets/useLMS-CikRrfs-.js","assets/AdminCourseDetail-B7SMmP-Y.js","assets/LevelUpU-DV7LrBlS.js","assets/LevelUpUCourse-5IBTmmsD.js","assets/MobileAgentApp-DcH_7M1R.js","assets/StagingStudio-CJgdCX-e.js","assets/presets-BxS6QxwT.js","assets/download-BqCckdNk.js","assets/BeforeAfterSlider-Da1OZYbm.js","assets/BuyCreditsDialog-gl-kAPES.js","assets/StagingLibrary-4xzDWnTw.js","assets/StagingCredits-BkdmIITT.js","assets/AgentWallet-gL_EXWlH.js","assets/useHomeReel-B3j58aiQ.js","assets/StagingSharePage-B57914wZ.js","assets/StagingStudioAdmin-BIeUKp9A.js","assets/ContactFinderAdmin-BIg006HV.js","assets/PostcardManager-CR_8ZiwV.js","assets/PostcardZoneEditor-BvNiwMQr.js","assets/usePostcardZones-DnjeqbhB.js","assets/MailStudioTemplates-B3tuz4Pn.js","assets/HomeReelManager-DCo5xsx3.js","assets/videoRenderSink-KDd1M0JO.js","assets/AdminMusicVideos-BrcU9BNL.js","assets/AdminVideoLab-DwlH66H2.js","assets/BoostPreview-DBfkazE7.js","assets/AdminCredits-DxXe8lQm.js","assets/MailStudio-DJ9WILO7.js","assets/farmToCrm-BBxyNY2V.js","assets/artwork-DskgYQJH.js","assets/MailStudio-D-BotKHo.css","assets/InnerCirclePopbyMap-YlyB4HOu.js","assets/SphereMap-CQaxW25m.js","assets/PropertyIntelligenceDashboard-FxvNuWhY.js","assets/LiveVisitorFeed-CJhQ_8xK.js","assets/LeadSites-BB79sgUd.js","assets/LeadSiteEditor-D0r5VUIw.js","assets/ImageUrlField-vqFSifpj.js","assets/HomepageModuleManager-h_MIXv-Z.js","assets/VideoUrlField-DNBzNyqe.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-CJ_1OpWd.js","assets/AdminFreeWebsiteOfferStudio-Dhm8oGKu.js","assets/AdminMlsFeeds-UxHXYzqb.js","assets/AdminWebsiteRequests-pwjMHHHw.js","assets/NeedAWebsite-Db7N2eps.js","assets/MLSListings-BLfwbm32.js","assets/MLSListingDetail-D_3eQt7e.js","assets/WebsiteActivityPage-D4AWT2GM.js","assets/PublicRecruitForm-BB-kz8VW.js","assets/PublicEventInviteUnsubscribe-DfBDBNBT.js","assets/SocialConnections-BoXB26A8.js","assets/SocialConnectionsCallback-5tW7QJpm.js","assets/LinkedInCallback-DSF4apqS.js","assets/TikTokCallback-BcjzXx5U.js","assets/MarketplaceCart-6Ef30jfV.js","assets/MarketplaceOrderDetail-Dzgys1A3.js","assets/RewardStore-CXTDkQUw.js","assets/ReferFriends-B5u3d3T9.js","assets/SmartPresentations-6k10UHxo.js","assets/useSmartPresentations-Z8iEZPlK.js","assets/SmartPresentationCreate-Bc1IHHbQ.js","assets/TeleprompterOverlay-C_nBQ4QY.js","assets/GuestBook-CcBULnob.js","assets/SignDocument-BW3l-X_F.js","assets/Blog-Cxe7YgqW.js","assets/TrialCTA-Df0vCTRI.js","assets/BlogPost-sSN5_57O.js","assets/AdminBlog-rYsVHr1I.js","assets/ReviewLanding-w8iZ4b12.js","assets/ReviewIntake-C8X1iZyR.js","assets/PublicReviewsPage-CzcFnt9M.js","assets/PublicReviewSubmit-CZ18nQXU.js","assets/Reviews-DNmYouE9.js","assets/CardStudio-DaE7xb9I.js","assets/ListingStudio-DSJJYanw.js","assets/SmartDrips-Chh4aGyN.js","assets/WeeklyReels-DB8CKQKC.js","assets/ReelCard-33ItRraA.js","assets/useWeeklyReels-B1I8NvJC.js","assets/WeeklyReelsOnboarding-Cdk_u_DS.js","assets/WeeklyReelsAdmin-Dk_77-SV.js","assets/AttractLayout-CzEBTdSG.js","assets/useAttractSettings-CYd6g-SA.js","assets/useAttractIntelligence-Bq8gBgND.js","assets/HealthScoreBadge-Cih3pa7n.js","assets/AttractToday-C3pt_hhb.js","assets/useAttractIntelSync-BWyvMncy.js","assets/useAttractAgents-CKBjWI_Y.js","assets/useAttractFollowUps-Cmq9nGjK.js","assets/useAttractActivities-DSGfcI2H.js","assets/RecommendationCard-CgzAk8Ek.js","assets/QuickAddRelationship-CXeBRS5Y.js","assets/relationshipStages-Buh5_cBI.js","assets/useAttractEvents-Co-wLBII.js","assets/AttractRelationships-QXy_G11s.js","assets/AttractPageHeader-Bwt-qMpU.js","assets/AgentEditSheet-B3xjtz8F.js","assets/AttractFollowUp-TReIMQnx.js","assets/AttractTemplates-BGzozfCi.js","assets/AttractReports-AukJkuau.js","assets/AttractSettings-DWpGNt05.js","assets/AttractToolkit-hUjkgoWm.js","assets/Objections-Bzx3ROYE.js","assets/AttractCalculator-CKnmFbkM.js","assets/attractionPageTemplate-C9AaZMgq.js","assets/AttractEventList-Z0migxh8.js","assets/AttractEventBuilder-lRU6Okv4.js","assets/useAttractKits-DHeOVClv.js","assets/AttractEventDetail-CwTWmoKd.js","assets/AttractEventCheckIn-L9JpuW1n.js","assets/AttractOnboarding-D2Y7GNDi.js","assets/ContentStudio-Cc4bdLpo.js","assets/KitList-Dp-qmbGR.js","assets/KitBuilder-DD5b_pdy.js","assets/KitPreview-Ce-RByty.js","assets/KitAnalytics-CfXcRkfD.js","assets/KitTemplates-CjqmP3LT.js","assets/AttractAgentDetail-CC1sMV9s.js","assets/AttractOpportunities-BPudArYm.js","assets/AttractIntelligenceDebug-DP0otB8-.js","assets/PublicAttractKit-Cs7jmRHJ.js","assets/PublicAttractEvent-DSvBiYWg.js","assets/PublicAttractionPage-B1N8Qf9l.js","assets/AttractionPageView-DbPAA5wm.js","assets/RevivalLanding-nVNMsGUT.js","assets/types-Bbp_6W6m.js","assets/RevivalPlan-C-zq3ITw.js","assets/revivalPdf-BwKMELDh.js","assets/ListingRevival-B7vxl_vN.js","assets/useListingRevival-BI7bo_Cp.js","assets/AreaChart-Dwfqh_d8.js","assets/RevivalCampaignWizard-EvlNS_VR.js","assets/campaignMail-COyWjzkP.js","assets/RevivalCampaignDetail-Cj4vzpV_.js","assets/LetterEditor-1yCX_R3h.js","assets/FsboBreakthrough-Cf9x2q9y.js","assets/useFsboBreakthrough-DgONelAg.js","assets/types-CK1tolb7.js","assets/FsboPropertyDialog-DGAGjpmL.js","assets/FsboCampaignWizard-CCGq3lr8.js","assets/FsboCampaignDetail-Dl-W8PNn.js","assets/FsboLanding-d2WyjI8M.js","assets/publicApi-BEaFpcRg.js","assets/FsboGuide-DQYn2D4U.js","assets/FsboBreakthroughAdmin-DxC_NM9h.js","assets/AttractLandingPageBuilder-Bmsaeknb.js","assets/AttractAccess-BLj_aJ0R.js","assets/Teams-BE3uO2Vl.js","assets/MyTeam-Ch6pGmn7.js","assets/TeamLeaderSettings-ByVWZXDK.js","assets/TeamHub-C3O_2ulo.js","assets/SchedulerSettings-zQ3l43z0.js","assets/MyCalendar-rDlxKC_n.js","assets/BookingManagePage-DZ4Qdoaq.js","assets/LandingPages-CcwClFr7.js","assets/BuyerMatch-DT7jyiW8.js","assets/SendBuyerMatchEmailDialog-Dl2os4OK.js","assets/BuyerMatchEditor-Dn59XyB6.js","assets/matching-BdEgbJjD.js","assets/PublicBuyerMatch-Dw5byq_C.js","assets/LandingPageEditor-pEE4cgsy.js","assets/LandingPageDefaults-BeA22mS3.js","assets/WebsiteAppsHub-5fvcud4U.js","assets/ClaimFreeLeadSiteCard-B9myfxgK.js","assets/useWebsiteApps-DRNZO6hy.js","assets/ClaimWebsite-B7vlV0hm.js","assets/VideoGreeterEditor-DSWsNRY5.js","assets/ExitIntentEditor-Dq1FFl57.js","assets/widgetTemplates-keLygp7O.js","assets/LeadMagnetEditor-ChwW0X4J.js","assets/RelationshipScorecard-C29Im344.js","assets/SphereGaps-D8i8bSVF.js","assets/ConnectPageSettings-CdEBWq4a.js","assets/EmailCampaigns-CLgeHIJe.js","assets/sesRequest-DXWKxr60.js","assets/EmailCompliance-CbPUZHaD.js","assets/EmailCampaignComposer-ZuFoThaS.js","assets/EditorModeSelector-CrPtu35l.js","assets/EmailCampaignDetail-0GwSQRQ-.js","assets/SharedCampaignTemplates-Dd11JX9v.js","assets/TemplateEditorDialog-BEp6mYsn.js","assets/AgentTemplates-DZgAEWHF.js","assets/TheLocalMoveHome-BzGUEVT0.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-C5eYI5Yu.js","assets/TheLocalMoveCheckout-CoV3tLtt.js","assets/AdminWebsiteOrders-C8_axBPN.js"])))=>i.map(i=>d[i]); var lIe=Object.defineProperty;var rQ=t=>{throw TypeError(t)};var cIe=(t,e,r)=>e in t?lIe(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var un=(t,e,r)=>cIe(t,typeof e!="symbol"?e+"":e,r),k4=(t,e,r)=>e.has(t)||rQ("Cannot "+r);var Tt=(t,e,r)=>(k4(t,e,"read from private field"),r?r.call(t):e.get(t)),Zn=(t,e,r)=>e.has(t)?rQ("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),xn=(t,e,r,n)=>(k4(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Fi=(t,e,r)=>(k4(t,e,"access private method"),r);var DP=(t,e,r,n)=>({set _(i){xn(t,e,i,r)},get _(){return Tt(t,e,n)}});function uIe(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 Wl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ds(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function dIe(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 Hce={exports:{}},IO={},Wce={exports:{}},Hi={};/** * @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 yC=Symbol.for("react.element"),hIe=Symbol.for("react.portal"),fIe=Symbol.for("react.fragment"),pIe=Symbol.for("react.strict_mode"),mIe=Symbol.for("react.profiler"),gIe=Symbol.for("react.provider"),yIe=Symbol.for("react.context"),xIe=Symbol.for("react.forward_ref"),_Ie=Symbol.for("react.suspense"),vIe=Symbol.for("react.memo"),bIe=Symbol.for("react.lazy"),nQ=Symbol.iterator;function wIe(t){return t===null||typeof t!="object"?null:(t=nQ&&t[nQ]||t["@@iterator"],typeof t=="function"?t:null)}var Kce={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Yce=Object.assign,Zce={};function nS(t,e,r){this.props=t,this.context=e,this.refs=Zce,this.updater=r||Kce}nS.prototype.isReactComponent={};nS.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")};nS.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Xce(){}Xce.prototype=nS.prototype;function hq(t,e,r){this.props=t,this.context=e,this.refs=Zce,this.updater=r||Kce}var fq=hq.prototype=new Xce;fq.constructor=hq;Yce(fq,nS.prototype);fq.isPureReactComponent=!0;var iQ=Array.isArray,Qce=Object.prototype.hasOwnProperty,pq={current:null},Jce={key:!0,ref:!0,__self:!0,__source:!0};function eue(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)Qce.call(e,n)&&!Jce.hasOwnProperty(n)&&(i[n]=e[n]);var s=arguments.length-2;if(s===1)i.children=r;else if(1>>1,be=ge[Te];if(0>>1;Tei(at,Ie))Eti(_t,at)?(ge[Te]=_t,ge[Et]=Ie,Te=Et):(ge[Te]=at,ge[rt]=Ie,Te=rt);else if(Eti(_t,Ie))ge[Te]=_t,ge[Et]=Ie,Te=Et;else break e}}return Ne}function i(ge,Ne){var Ie=ge.sortIndex-Ne.sortIndex;return Ie!==0?Ie:ge.id-Ne.id}if(typeof performance=="object"&&typeof performance.now=="function"){var a=performance;t.unstable_now=function(){return a.now()}}else{var c=Date,s=c.now();t.unstable_now=function(){return c.now()-s}}var f=[],m=[],x=1,_=null,T=3,E=!1,C=!1,N=!1,R=typeof setTimeout=="function"?setTimeout:null,D=typeof clearTimeout=="function"?clearTimeout:null,M=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function B(ge){for(var Ne=r(m);Ne!==null;){if(Ne.callback===null)n(m);else if(Ne.startTime<=ge)n(m),Ne.sortIndex=Ne.expirationTime,e(f,Ne);else break;Ne=r(m)}}function V(ge){if(N=!1,B(ge),!C)if(r(f)!==null)C=!0,Ae(G);else{var Ne=r(m);Ne!==null&&we(V,Ne.startTime-ge)}}function G(ge,Ne){C=!1,N&&(N=!1,D(Q),Q=-1),E=!0;var Ie=T;try{for(B(Ne),_=r(f);_!==null&&(!(_.expirationTime>Ne)||ge&&!ue());){var Te=_.callback;if(typeof Te=="function"){_.callback=null,T=_.priorityLevel;var be=Te(_.expirationTime<=Ne);Ne=t.unstable_now(),typeof be=="function"?_.callback=be:_===r(f)&&n(f),B(Ne)}else n(f);_=r(f)}if(_!==null)var We=!0;else{var rt=r(m);rt!==null&&we(V,rt.startTime-Ne),We=!1}return We}finally{_=null,T=Ie,E=!1}}var W=!1,X=null,Q=-1,re=5,se=-1;function ue(){return!(t.unstable_now()-sege||125Te?(ge.sortIndex=Ie,e(m,ge),r(f)===null&&ge===r(m)&&(N?(D(Q),Q=-1):N=!0,we(V,Ie-Te))):(ge.sortIndex=be,e(f,ge),C||E||(C=!0,Ae(G))),ge},t.unstable_shouldYield=ue,t.unstable_wrapCallback=function(ge){var Ne=T;return function(){var Ie=T;T=Ne;try{return ge.apply(this,arguments)}finally{T=Ie}}}})(sue);iue.exports=sue;var RIe=iue.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 LIe=P,sd=RIe;function Vr(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"),A$=Object.prototype.hasOwnProperty,DIe=/^[: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]*$/,aQ={},oQ={};function OIe(t){return A$.call(oQ,t)?!0:A$.call(aQ,t)?!1:DIe.test(t)?oQ[t]=!0:(aQ[t]=!0,!1)}function MIe(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 FIe(t,e,r,n){if(e===null||typeof e>"u"||MIe(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 Jc(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 Ql={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){Ql[t]=new Jc(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];Ql[e]=new Jc(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){Ql[t]=new Jc(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){Ql[t]=new Jc(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){Ql[t]=new Jc(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){Ql[t]=new Jc(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){Ql[t]=new Jc(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){Ql[t]=new Jc(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){Ql[t]=new Jc(t,5,!1,t.toLowerCase(),null,!1,!1)});var yq=/[\-:]([a-z])/g;function xq(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(yq,xq);Ql[e]=new Jc(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(yq,xq);Ql[e]=new Jc(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(yq,xq);Ql[e]=new Jc(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){Ql[t]=new Jc(t,1,!1,t.toLowerCase(),null,!1,!1)});Ql.xlinkHref=new Jc("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){Ql[t]=new Jc(t,1,!1,t.toLowerCase(),null,!0,!0)});function _q(t,e,r,n){var i=Ql.hasOwnProperty(e)?Ql[e]:null;(i!==null?i.type!==0:n||!(2s||i[c]!==a[s]){var f=` `+i[c].replace(" at new "," at ");return t.displayName&&f.includes("")&&(f=f.replace("",t.displayName)),f}while(1<=c&&0<=s);break}}}finally{I4=!1,Error.prepareStackTrace=r}return(t=t?t.displayName||t.name:"")?$2(t):""}function BIe(t){switch(t.tag){case 5:return $2(t.type);case 16:return $2("Lazy");case 13:return $2("Suspense");case 19:return $2("SuspenseList");case 0:case 2:case 15:return t=P4(t.type,!1),t;case 11:return t=P4(t.type.render,!1),t;case 1:return t=P4(t.type,!0),t;default:return""}}function I$(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 tw:return"Fragment";case ew:return"Portal";case k$:return"Profiler";case vq:return"StrictMode";case C$:return"Suspense";case j$:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case lue:return(t.displayName||"Context")+".Consumer";case oue:return(t._context.displayName||"Context")+".Provider";case bq:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case wq:return e=t.displayName||null,e!==null?e:I$(t.type)||"Memo";case Kg:e=t._payload,t=t._init;try{return I$(t(e))}catch{}}return null}function zIe(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 I$(e);case 8:return e===vq?"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 Oy(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function uue(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function $Ie(t){var e=uue(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 FP(t){t._valueTracker||(t._valueTracker=$Ie(t))}function due(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var r=e.getValue(),n="";return t&&(n=uue(t)?t.checked?"true":"false":t.value),t=n,t!==r?(e.setValue(t),!0):!1}function nL(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 P$(t,e){var r=e.checked;return to({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??t._wrapperState.initialChecked})}function cQ(t,e){var r=e.defaultValue==null?"":e.defaultValue,n=e.checked!=null?e.checked:e.defaultChecked;r=Oy(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 hue(t,e){e=e.checked,e!=null&&_q(t,"checked",e,!1)}function N$(t,e){hue(t,e);var r=Oy(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")?R$(t,e.type,r):e.hasOwnProperty("defaultValue")&&R$(t,e.type,Oy(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function uQ(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 R$(t,e,r){(e!=="number"||nL(t.ownerDocument)!==t)&&(r==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+r&&(t.defaultValue=""+r))}var U2=Array.isArray;function Sw(t,e,r,n){if(t=t.options,e){e={};for(var i=0;i"+e.valueOf().toString()+"",e=BP.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function LA(t,e){if(e){var r=t.firstChild;if(r&&r===t.lastChild&&r.nodeType===3){r.nodeValue=e;return}}t.textContent=e}var eA={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},UIe=["Webkit","ms","Moz","O"];Object.keys(eA).forEach(function(t){UIe.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),eA[e]=eA[t]})});function gue(t,e,r){return e==null||typeof e=="boolean"||e===""?"":r||typeof e!="number"||e===0||eA.hasOwnProperty(t)&&eA[t]?(""+e).trim():e+"px"}function yue(t,e){t=t.style;for(var r in e)if(e.hasOwnProperty(r)){var n=r.indexOf("--")===0,i=gue(r,e[r],n);r==="float"&&(r="cssFloat"),n?t.setProperty(r,i):t[r]=i}}var VIe=to({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 O$(t,e){if(e){if(VIe[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(Vr(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(Vr(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(Vr(61))}if(e.style!=null&&typeof e.style!="object")throw Error(Vr(62))}}function M$(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 F$=null;function Sq(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var B$=null,Tw=null,Ew=null;function fQ(t){if(t=vC(t)){if(typeof B$!="function")throw Error(Vr(280));var e=t.stateNode;e&&(e=DO(e),B$(t.stateNode,t.type,e))}}function xue(t){Tw?Ew?Ew.push(t):Ew=[t]:Tw=t}function _ue(){if(Tw){var t=Tw,e=Ew;if(Ew=Tw=null,fQ(t),e)for(t=0;t>>=0,t===0?32:31-(ePe(t)/tPe|0)|0}var zP=64,$P=4194304;function V2(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 oL(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 s=c&~i;s!==0?n=V2(s):(a&=c,a!==0&&(n=V2(a)))}else c=r&~i,c!==0?n=V2(c):a!==0&&(n=V2(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 xC(t,e,r){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-Wh(e),t[e]=r}function sPe(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=rA),wQ=" ",SQ=!1;function Bue(t,e){switch(t){case"keyup":return RPe.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function zue(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var rw=!1;function DPe(t,e){switch(t){case"compositionend":return zue(e);case"keypress":return e.which!==32?null:(SQ=!0,wQ);case"textInput":return t=e.data,t===wQ&&SQ?null:t;default:return null}}function OPe(t,e){if(rw)return t==="compositionend"||!Pq&&Bue(t,e)?(t=Mue(),fR=Cq=my=null,rw=!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=kQ(r)}}function que(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?que(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Gue(){for(var t=window,e=nL();e instanceof t.HTMLIFrameElement;){try{var r=typeof e.contentWindow.location.href=="string"}catch{r=!1}if(r)t=e.contentWindow;else break;e=nL(t.document)}return e}function Nq(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 GPe(t){var e=Gue(),r=t.focusedElem,n=t.selectionRange;if(e!==r&&r&&r.ownerDocument&&que(r.ownerDocument.documentElement,r)){if(n!==null&&Nq(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=CQ(r,a);var c=CQ(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,nw=null,G$=null,iA=null,H$=!1;function jQ(t,e,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;H$||nw==null||nw!==nL(n)||(n=nw,"selectionStart"in n&&Nq(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}),iA&&zA(iA,n)||(iA=n,n=uL(G$,"onSelect"),0aw||(t.current=Q$[aw],Q$[aw]=null,aw--)}function fa(t,e){aw++,Q$[aw]=t.current,t.current=e}var My={},yc=tx(My),Tu=tx(!1),y0=My;function i1(t,e){var r=t.type.contextTypes;if(!r)return My;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 Eu(t){return t=t.childContextTypes,t!=null}function hL(){Ca(Tu),Ca(yc)}function OQ(t,e,r){if(yc.current!==My)throw Error(Vr(168));fa(yc,e),fa(Tu,r)}function ede(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(Vr(108,zIe(t)||"Unknown",i));return to({},r,n)}function fL(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||My,y0=yc.current,fa(yc,t),fa(Tu,Tu.current),!0}function MQ(t,e,r){var n=t.stateNode;if(!n)throw Error(Vr(169));r?(t=ede(t,e,y0),n.__reactInternalMemoizedMergedChildContext=t,Ca(Tu),Ca(yc),fa(yc,t)):Ca(Tu),fa(Tu,r)}var om=null,OO=!1,G4=!1;function tde(t){om===null?om=[t]:om.push(t)}function nNe(t){OO=!0,tde(t)}function rx(){if(!G4&&om!==null){G4=!0;var t=0,e=Us;try{var r=om;for(Us=1;t>=c,i-=c,dm=1<<32-Wh(e)+i|r<Q?(re=X,X=null):re=X.sibling;var se=T(D,X,B[Q],V);if(se===null){X===null&&(X=re);break}t&&X&&se.alternate===null&&e(D,X),M=a(se,M,Q),W===null?G=se:W.sibling=se,W=se,X=re}if(Q===B.length)return r(D,X),Oa&&R_(D,Q),G;if(X===null){for(;QQ?(re=X,X=null):re=X.sibling;var ue=T(D,X,se.value,V);if(ue===null){X===null&&(X=re);break}t&&X&&ue.alternate===null&&e(D,X),M=a(ue,M,Q),W===null?G=ue:W.sibling=ue,W=ue,X=re}if(se.done)return r(D,X),Oa&&R_(D,Q),G;if(X===null){for(;!se.done;Q++,se=B.next())se=_(D,se.value,V),se!==null&&(M=a(se,M,Q),W===null?G=se:W.sibling=se,W=se);return Oa&&R_(D,Q),G}for(X=n(D,X);!se.done;Q++,se=B.next())se=E(X,D,Q,se.value,V),se!==null&&(t&&se.alternate!==null&&X.delete(se.key===null?Q:se.key),M=a(se,M,Q),W===null?G=se:W.sibling=se,W=se);return t&&X.forEach(function(_e){return e(D,_e)}),Oa&&R_(D,Q),G}function R(D,M,B,V){if(typeof B=="object"&&B!==null&&B.type===tw&&B.key===null&&(B=B.props.children),typeof B=="object"&&B!==null){switch(B.$$typeof){case MP:e:{for(var G=B.key,W=M;W!==null;){if(W.key===G){if(G=B.type,G===tw){if(W.tag===7){r(D,W.sibling),M=i(W,B.props.children),M.return=D,D=M;break e}}else if(W.elementType===G||typeof G=="object"&&G!==null&&G.$$typeof===Kg&&zQ(G)===W.type){r(D,W.sibling),M=i(W,B.props),M.ref=l2(D,W,B),M.return=D,D=M;break e}r(D,W);break}else e(D,W);W=W.sibling}B.type===tw?(M=d0(B.props.children,D.mode,V,B.key),M.return=D,D=M):(V=bR(B.type,B.key,B.props,null,D.mode,V),V.ref=l2(D,M,B),V.return=D,D=V)}return c(D);case ew:e:{for(W=B.key;M!==null;){if(M.key===W)if(M.tag===4&&M.stateNode.containerInfo===B.containerInfo&&M.stateNode.implementation===B.implementation){r(D,M.sibling),M=i(M,B.children||[]),M.return=D,D=M;break e}else{r(D,M);break}else e(D,M);M=M.sibling}M=J4(B,D.mode,V),M.return=D,D=M}return c(D);case Kg:return W=B._init,R(D,M,W(B._payload),V)}if(U2(B))return C(D,M,B,V);if(n2(B))return N(D,M,B,V);KP(D,B)}return typeof B=="string"&&B!==""||typeof B=="number"?(B=""+B,M!==null&&M.tag===6?(r(D,M.sibling),M=i(M,B),M.return=D,D=M):(r(D,M),M=Q4(B,D.mode,V),M.return=D,D=M),c(D)):r(D,M)}return R}var a1=sde(!0),ade=sde(!1),gL=tx(null),yL=null,cw=null,Oq=null;function Mq(){Oq=cw=yL=null}function Fq(t){var e=gL.current;Ca(gL),t._currentValue=e}function tU(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 kw(t,e){yL=t,Oq=cw=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(bu=!0),t.firstContext=null)}function Kd(t){var e=t._currentValue;if(Oq!==t)if(t={context:t,memoizedValue:e,next:null},cw===null){if(yL===null)throw Error(Vr(308));cw=t,yL.dependencies={lanes:0,firstContext:t}}else cw=cw.next=t;return e}var G_=null;function Bq(t){G_===null?G_=[t]:G_.push(t)}function ode(t,e,r,n){var i=e.interleaved;return i===null?(r.next=r,Bq(e)):(r.next=i.next,i.next=r),e.interleaved=r,km(t,n)}function km(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 Yg=!1;function zq(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function lde(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 gm(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function Ey(t,e,r){var n=t.updateQueue;if(n===null)return null;if(n=n.shared,ms&2){var i=n.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),n.pending=e,km(t,r)}return i=n.interleaved,i===null?(e.next=e,Bq(n)):(e.next=i.next,i.next=e),n.interleaved=e,km(t,r)}function mR(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,Eq(t,r)}}function $Q(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 xL(t,e,r,n){var i=t.updateQueue;Yg=!1;var a=i.firstBaseUpdate,c=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var f=s,m=f.next;f.next=null,c===null?a=m:c.next=m,c=f;var x=t.alternate;x!==null&&(x=x.updateQueue,s=x.lastBaseUpdate,s!==c&&(s===null?x.firstBaseUpdate=m:s.next=m,x.lastBaseUpdate=f))}if(a!==null){var _=i.baseState;c=0,x=m=f=null,s=a;do{var T=s.lane,E=s.eventTime;if((n&T)===T){x!==null&&(x=x.next={eventTime:E,lane:0,tag:s.tag,payload:s.payload,callback:s.callback,next:null});e:{var C=t,N=s;switch(T=e,E=r,N.tag){case 1:if(C=N.payload,typeof C=="function"){_=C.call(E,_,T);break e}_=C;break e;case 3:C.flags=C.flags&-65537|128;case 0:if(C=N.payload,T=typeof C=="function"?C.call(E,_,T):C,T==null)break e;_=to({},_,T);break e;case 2:Yg=!0}}s.callback!==null&&s.lane!==0&&(t.flags|=64,T=i.effects,T===null?i.effects=[s]:T.push(s))}else E={eventTime:E,lane:T,tag:s.tag,payload:s.payload,callback:s.callback,next:null},x===null?(m=x=E,f=_):x=x.next=E,c|=T;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;T=s,s=T.next,T.next=null,i.lastBaseUpdate=T,i.shared.pending=null}}while(!0);if(x===null&&(f=_),i.baseState=f,i.firstBaseUpdate=m,i.lastBaseUpdate=x,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);v0|=c,t.lanes=c,t.memoizedState=_}}function UQ(t,e,r){if(t=e.effects,e.effects=null,t!==null)for(e=0;er?r:4,t(!0);var n=W4.transition;W4.transition={};try{t(!1),e()}finally{Us=r,W4.transition=n}}function Ede(){return Yd().memoizedState}function oNe(t,e,r){var n=ky(t);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},Ade(t))kde(e,r);else if(r=ode(t,e,r,n),r!==null){var i=Yc();Kh(r,t,n,i),Cde(r,e,n)}}function lNe(t,e,r){var n=ky(t),i={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(Ade(t))kde(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,s=a(c,r);if(i.hasEagerState=!0,i.eagerState=s,Qh(s,c)){var f=e.interleaved;f===null?(i.next=i,Bq(e)):(i.next=f.next,f.next=i),e.interleaved=i;return}}catch{}finally{}r=ode(t,e,i,n),r!==null&&(i=Yc(),Kh(r,t,n,i),Cde(r,e,n))}}function Ade(t){var e=t.alternate;return t===Ja||e!==null&&e===Ja}function kde(t,e){sA=vL=!0;var r=t.pending;r===null?e.next=e:(e.next=r.next,r.next=e),t.pending=e}function Cde(t,e,r){if(r&4194240){var n=e.lanes;n&=t.pendingLanes,r|=n,e.lanes=r,Eq(t,r)}}var bL={readContext:Kd,useCallback:lc,useContext:lc,useEffect:lc,useImperativeHandle:lc,useInsertionEffect:lc,useLayoutEffect:lc,useMemo:lc,useReducer:lc,useRef:lc,useState:lc,useDebugValue:lc,useDeferredValue:lc,useTransition:lc,useMutableSource:lc,useSyncExternalStore:lc,useId:lc,unstable_isNewReconciler:!1},cNe={readContext:Kd,useCallback:function(t,e){return Pf().memoizedState=[t,e===void 0?null:e],t},useContext:Kd,useEffect:qQ,useImperativeHandle:function(t,e,r){return r=r!=null?r.concat([t]):null,yR(4194308,4,vde.bind(null,e,t),r)},useLayoutEffect:function(t,e){return yR(4194308,4,t,e)},useInsertionEffect:function(t,e){return yR(4,2,t,e)},useMemo:function(t,e){var r=Pf();return e=e===void 0?null:e,t=t(),r.memoizedState=[t,e],t},useReducer:function(t,e,r){var n=Pf();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=oNe.bind(null,Ja,t),[n.memoizedState,t]},useRef:function(t){var e=Pf();return t={current:t},e.memoizedState=t},useState:VQ,useDebugValue:Kq,useDeferredValue:function(t){return Pf().memoizedState=t},useTransition:function(){var t=VQ(!1),e=t[0];return t=aNe.bind(null,t[1]),Pf().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,r){var n=Ja,i=Pf();if(Oa){if(r===void 0)throw Error(Vr(407));r=r()}else{if(r=e(),kl===null)throw Error(Vr(349));_0&30||hde(n,e,r)}i.memoizedState=r;var a={value:r,getSnapshot:e};return i.queue=a,qQ(pde.bind(null,n,a,t),[t]),n.flags|=2048,KA(9,fde.bind(null,n,a,r,e),void 0,null),r},useId:function(){var t=Pf(),e=kl.identifierPrefix;if(Oa){var r=hm,n=dm;r=(n&~(1<<32-Wh(n)-1)).toString(32)+r,e=":"+e+"R"+r,r=HA++,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[Bf]=e,t[VA]=n,Fde(t,e,!1,!1),e.stateNode=t;e:{switch(c=M$(r,n),r){case"dialog":Ta("cancel",t),Ta("close",t),i=n;break;case"iframe":case"object":case"embed":Ta("load",t),i=n;break;case"video":case"audio":for(i=0;ic1&&(e.flags|=128,n=!0,c2(a,!1),e.lanes=4194304)}else{if(!n)if(t=_L(c),t!==null){if(e.flags|=128,n=!0,r=t.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),c2(a,!0),a.tail===null&&a.tailMode==="hidden"&&!c.alternate&&!Oa)return cc(e),null}else 2*So()-a.renderingStartTime>c1&&r!==1073741824&&(e.flags|=128,n=!0,c2(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=So(),e.sibling=null,r=Za.current,fa(Za,n?r&1|2:r&1),e):(cc(e),null);case 22:case 23:return eG(),n=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==n&&(e.flags|=8192),n&&e.mode&1?Hu&1073741824&&(cc(e),e.subtreeFlags&6&&(e.flags|=8192)):cc(e),null;case 24:return null;case 25:return null}throw Error(Vr(156,e.tag))}function yNe(t,e){switch(Lq(e),e.tag){case 1:return Eu(e.type)&&hL(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return o1(),Ca(Tu),Ca(yc),Vq(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return Uq(e),null;case 13:if(Ca(Za),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(Vr(340));s1()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Ca(Za),null;case 4:return o1(),null;case 10:return Fq(e.type._context),null;case 22:case 23:return eG(),null;case 24:return null;default:return null}}var ZP=!1,hc=!1,xNe=typeof WeakSet=="function"?WeakSet:Set,En=null;function uw(t,e){var r=t.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){uo(t,e,n)}else r.current=null}function uU(t,e,r){try{r()}catch(n){uo(t,e,n)}}var tJ=!1;function _Ne(t,e){if(W$=lL,t=Gue(),Nq(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,s=-1,f=-1,m=0,x=0,_=t,T=null;t:for(;;){for(var E;_!==r||i!==0&&_.nodeType!==3||(s=c+i),_!==a||n!==0&&_.nodeType!==3||(f=c+n),_.nodeType===3&&(c+=_.nodeValue.length),(E=_.firstChild)!==null;)T=_,_=E;for(;;){if(_===t)break t;if(T===r&&++m===i&&(s=c),T===a&&++x===n&&(f=c),(E=_.nextSibling)!==null)break;_=T,T=_.parentNode}_=E}r=s===-1||f===-1?null:{start:s,end:f}}else r=null}r=r||{start:0,end:0}}else r=null;for(K$={focusedElem:t,selectionRange:r},lL=!1,En=e;En!==null;)if(e=En,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,En=t;else for(;En!==null;){e=En;try{var C=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(C!==null){var N=C.memoizedProps,R=C.memoizedState,D=e.stateNode,M=D.getSnapshotBeforeUpdate(e.elementType===e.type?N:Nh(e.type,N),R);D.__reactInternalSnapshotBeforeUpdate=M}break;case 3:var B=e.stateNode.containerInfo;B.nodeType===1?B.textContent="":B.nodeType===9&&B.documentElement&&B.removeChild(B.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Vr(163))}}catch(V){uo(e,e.return,V)}if(t=e.sibling,t!==null){t.return=e.return,En=t;break}En=e.return}return C=tJ,tJ=!1,C}function aA(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&&uU(e,r,a)}i=i.next}while(i!==n)}}function BO(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 dU(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 $de(t){var e=t.alternate;e!==null&&(t.alternate=null,$de(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[Bf],delete e[VA],delete e[X$],delete e[tNe],delete e[rNe])),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 Ude(t){return t.tag===5||t.tag===3||t.tag===4}function rJ(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Ude(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 hU(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=dL));else if(n!==4&&(t=t.child,t!==null))for(hU(t,e,r),t=t.sibling;t!==null;)hU(t,e,r),t=t.sibling}function fU(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(fU(t,e,r),t=t.sibling;t!==null;)fU(t,e,r),t=t.sibling}var Fl=null,Dh=!1;function Rg(t,e,r){for(r=r.child;r!==null;)Vde(t,e,r),r=r.sibling}function Vde(t,e,r){if(Kf&&typeof Kf.onCommitFiberUnmount=="function")try{Kf.onCommitFiberUnmount(PO,r)}catch{}switch(r.tag){case 5:hc||uw(r,e);case 6:var n=Fl,i=Dh;Fl=null,Rg(t,e,r),Fl=n,Dh=i,Fl!==null&&(Dh?(t=Fl,r=r.stateNode,t.nodeType===8?t.parentNode.removeChild(r):t.removeChild(r)):Fl.removeChild(r.stateNode));break;case 18:Fl!==null&&(Dh?(t=Fl,r=r.stateNode,t.nodeType===8?q4(t.parentNode,r):t.nodeType===1&&q4(t,r),FA(t)):q4(Fl,r.stateNode));break;case 4:n=Fl,i=Dh,Fl=r.stateNode.containerInfo,Dh=!0,Rg(t,e,r),Fl=n,Dh=i;break;case 0:case 11:case 14:case 15:if(!hc&&(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)&&uU(r,e,c),i=i.next}while(i!==n)}Rg(t,e,r);break;case 1:if(!hc&&(uw(r,e),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(s){uo(r,e,s)}Rg(t,e,r);break;case 21:Rg(t,e,r);break;case 22:r.mode&1?(hc=(n=hc)||r.memoizedState!==null,Rg(t,e,r),hc=n):Rg(t,e,r);break;default:Rg(t,e,r)}}function nJ(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var r=t.stateNode;r===null&&(r=t.stateNode=new xNe),e.forEach(function(n){var i=CNe.bind(null,t,n);r.has(n)||(r.add(n),n.then(i,i))})}}function Th(t,e){var r=e.deletions;if(r!==null)for(var n=0;ni&&(i=c),n&=~a}if(n=i,n=So()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*bNe(n/1960))-n,10t?16:t,gy===null)var n=!1;else{if(t=gy,gy=null,TL=0,ms&6)throw Error(Vr(331));var i=ms;for(ms|=4,En=t.current;En!==null;){var a=En,c=a.child;if(En.flags&16){var s=a.deletions;if(s!==null){for(var f=0;fSo()-Qq?u0(t,0):Xq|=r),Au(t,e)}function Xde(t,e){e===0&&(t.mode&1?(e=$P,$P<<=1,!($P&130023424)&&($P=4194304)):e=1);var r=Yc();t=km(t,e),t!==null&&(xC(t,e,r),Au(t,r))}function kNe(t){var e=t.memoizedState,r=0;e!==null&&(r=e.retryLane),Xde(t,r)}function CNe(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(Vr(314))}n!==null&&n.delete(e),Xde(t,r)}var Qde;Qde=function(t,e,r){if(t!==null)if(t.memoizedProps!==e.pendingProps||Tu.current)bu=!0;else{if(!(t.lanes&r)&&!(e.flags&128))return bu=!1,mNe(t,e,r);bu=!!(t.flags&131072)}else bu=!1,Oa&&e.flags&1048576&&rde(e,mL,e.index);switch(e.lanes=0,e.tag){case 2:var n=e.type;xR(t,e),t=e.pendingProps;var i=i1(e,yc.current);kw(e,r),i=Gq(null,e,n,t,i,r);var a=Hq();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,Eu(n)?(a=!0,fL(e)):a=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,zq(e),i.updater=FO,e.stateNode=i,i._reactInternals=e,nU(e,n,t,r),e=aU(null,e,n,!0,a,r)):(e.tag=0,Oa&&a&&Rq(e),Bc(null,e,i,r),e=e.child),e;case 16:n=e.elementType;e:{switch(xR(t,e),t=e.pendingProps,i=n._init,n=i(n._payload),e.type=n,i=e.tag=INe(n),t=Nh(n,t),i){case 0:e=sU(null,e,n,t,r);break e;case 1:e=QQ(null,e,n,t,r);break e;case 11:e=ZQ(null,e,n,t,r);break e;case 14:e=XQ(null,e,n,Nh(n.type,t),r);break e}throw Error(Vr(306,n,""))}return e;case 0:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Nh(n,i),sU(t,e,n,i,r);case 1:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Nh(n,i),QQ(t,e,n,i,r);case 3:e:{if(Dde(e),t===null)throw Error(Vr(387));n=e.pendingProps,a=e.memoizedState,i=a.element,lde(t,e),xL(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=l1(Error(Vr(423)),e),e=JQ(t,e,n,r,i);break e}else if(n!==i){i=l1(Error(Vr(424)),e),e=JQ(t,e,n,r,i);break e}else for(Qu=Ty(e.stateNode.containerInfo.firstChild),td=e,Oa=!0,Bh=null,r=ade(e,null,n,r),e.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(s1(),n===i){e=Cm(t,e,r);break e}Bc(t,e,n,r)}e=e.child}return e;case 5:return cde(e),t===null&&eU(e),n=e.type,i=e.pendingProps,a=t!==null?t.memoizedProps:null,c=i.children,Y$(n,i)?c=null:a!==null&&Y$(n,a)&&(e.flags|=32),Lde(t,e),Bc(t,e,c,r),e.child;case 6:return t===null&&eU(e),null;case 13:return Ode(t,e,r);case 4:return $q(e,e.stateNode.containerInfo),n=e.pendingProps,t===null?e.child=a1(e,null,n,r):Bc(t,e,n,r),e.child;case 11:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Nh(n,i),ZQ(t,e,n,i,r);case 7:return Bc(t,e,e.pendingProps,r),e.child;case 8:return Bc(t,e,e.pendingProps.children,r),e.child;case 12:return Bc(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,fa(gL,n._currentValue),n._currentValue=c,a!==null)if(Qh(a.value,c)){if(a.children===i.children&&!Tu.current){e=Cm(t,e,r);break e}}else for(a=e.child,a!==null&&(a.return=e);a!==null;){var s=a.dependencies;if(s!==null){c=a.child;for(var f=s.firstContext;f!==null;){if(f.context===n){if(a.tag===1){f=gm(-1,r&-r),f.tag=2;var m=a.updateQueue;if(m!==null){m=m.shared;var x=m.pending;x===null?f.next=f:(f.next=x.next,x.next=f),m.pending=f}}a.lanes|=r,f=a.alternate,f!==null&&(f.lanes|=r),tU(a.return,r,e),s.lanes|=r;break}f=f.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(Vr(341));c.lanes|=r,s=c.alternate,s!==null&&(s.lanes|=r),tU(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}Bc(t,e,i.children,r),e=e.child}return e;case 9:return i=e.type,n=e.pendingProps.children,kw(e,r),i=Kd(i),n=n(i),e.flags|=1,Bc(t,e,n,r),e.child;case 14:return n=e.type,i=Nh(n,e.pendingProps),i=Nh(n.type,i),XQ(t,e,n,i,r);case 15:return Nde(t,e,e.type,e.pendingProps,r);case 17:return n=e.type,i=e.pendingProps,i=e.elementType===n?i:Nh(n,i),xR(t,e),e.tag=1,Eu(n)?(t=!0,fL(e)):t=!1,kw(e,r),jde(e,n,i),nU(e,n,i,r),aU(null,e,n,!0,t,r);case 19:return Mde(t,e,r);case 22:return Rde(t,e,r)}throw Error(Vr(156,e.tag))};function Jde(t,e){return Aue(t,e)}function jNe(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 zd(t,e,r,n){return new jNe(t,e,r,n)}function rG(t){return t=t.prototype,!(!t||!t.isReactComponent)}function INe(t){if(typeof t=="function")return rG(t)?1:0;if(t!=null){if(t=t.$$typeof,t===bq)return 11;if(t===wq)return 14}return 2}function Cy(t,e){var r=t.alternate;return r===null?(r=zd(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 bR(t,e,r,n,i,a){var c=2;if(n=t,typeof t=="function")rG(t)&&(c=1);else if(typeof t=="string")c=5;else e:switch(t){case tw:return d0(r.children,i,a,e);case vq:c=8,i|=8;break;case k$:return t=zd(12,r,e,i|2),t.elementType=k$,t.lanes=a,t;case C$:return t=zd(13,r,e,i),t.elementType=C$,t.lanes=a,t;case j$:return t=zd(19,r,e,i),t.elementType=j$,t.lanes=a,t;case cue:return $O(r,i,a,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case oue:c=10;break e;case lue:c=9;break e;case bq:c=11;break e;case wq:c=14;break e;case Kg:c=16,n=null;break e}throw Error(Vr(130,t==null?t:typeof t,""))}return e=zd(c,r,e,i),e.elementType=t,e.type=n,e.lanes=a,e}function d0(t,e,r,n){return t=zd(7,t,n,e),t.lanes=r,t}function $O(t,e,r,n){return t=zd(22,t,n,e),t.elementType=cue,t.lanes=r,t.stateNode={isHidden:!1},t}function Q4(t,e,r){return t=zd(6,t,null,e),t.lanes=r,t}function J4(t,e,r){return e=zd(4,t.children!==null?t.children:[],t.key,e),e.lanes=r,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function PNe(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=R4(0),this.expirationTimes=R4(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=R4(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function nG(t,e,r,n,i,a,c,s,f){return t=new PNe(t,e,r,s,f),e===1?(e=1,a===!0&&(e|=8)):e=0,a=zd(3,null,null,e),t.current=a,a.stateNode=t,a.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},zq(a),t}function NNe(t,e,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(nhe)}catch(t){console.error(t)}}nhe(),nue.exports=ud;var zm=nue.exports;const ihe=ds(zm);var she,dJ=zm;she=dJ.createRoot,dJ.hydrateRoot;const MNe="modulepreload",FNe=function(t){return"/"+t},hJ={},Be=function(e,r,n){let i=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),s=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));i=Promise.allSettled(r.map(f=>{if(f=FNe(f),f in hJ)return;hJ[f]=!0;const m=f.endsWith(".css"),x=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${x}`))return;const _=document.createElement("link");if(_.rel=m?"stylesheet":MNe,m||(_.as="script"),_.crossOrigin="",_.href=f,s&&_.setAttribute("nonce",s),document.head.appendChild(_),m)return new Promise((T,E)=>{_.addEventListener("load",T),_.addEventListener("error",()=>E(new Error(`Unable to preload CSS for ${f}`)))})}))}function a(c){const s=new Event("vite:preloadError",{cancelable:!0});if(s.payload=c,window.dispatchEvent(s),!s.defaultPrevented)throw c}return i.then(c=>{for(const s of c||[])s.status==="rejected"&&a(s.reason);return e().catch(a)})},BNe=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),zNe=t=>t.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function $Ne(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")||BNe.has(t))}function ahe(t){return ohe(t)!==null}function ohe(t){const e=zNe(t);return $Ne(e)?null:e}const UNe=1,VNe=1e6;let eB=0;function qNe(){return eB=(eB+1)%Number.MAX_SAFE_INTEGER,eB.toString()}const tB=new Map,fJ=t=>{if(tB.has(t))return;const e=setTimeout(()=>{tB.delete(t),cA({type:"REMOVE_TOAST",toastId:t})},VNe);tB.set(t,e)},GNe=(t,e)=>{switch(e.type){case"ADD_TOAST":return{...t,toasts:[e.toast,...t.toasts].slice(0,UNe)};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?fJ(r):t.toasts.forEach(n=>{fJ(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)}}},wR=[];let SR={toasts:[]};function cA(t){SR=GNe(SR,t),wR.forEach(e=>{e(SR)})}function Ts({...t}){const e=qNe(),r=i=>cA({type:"UPDATE_TOAST",toast:{...i,id:e}}),n=()=>cA({type:"DISMISS_TOAST",toastId:e});return cA({type:"ADD_TOAST",toast:{...t,id:e,open:!0,onOpenChange:i=>{i||n()}}}),{id:e,dismiss:n,update:r}}function lhe(){const[t,e]=P.useState(SR);return P.useEffect(()=>(wR.push(e),()=>{const r=wR.indexOf(e);r>-1&&wR.splice(r,1)}),[t]),{...t,toast:Ts,dismiss:r=>cA({type:"DISMISS_TOAST",toastId:r})}}function Or(t,e,{checkForDefaultPrevented:r=!0}={}){return function(i){if(t==null||t(i),r===!1||!i.defaultPrevented)return e==null?void 0:e(i)}}function pJ(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function jm(...t){return e=>{let r=!1;const n=t.map(i=>{const a=pJ(i,e);return!r&&typeof a=="function"&&(r=!0),a});if(r)return()=>{for(let i=0;i{const{children:c,...s}=a,f=P.useMemo(()=>s,Object.values(s));return o.jsx(r.Provider,{value:f,children:c})};n.displayName=t+"Provider";function i(a){const c=P.useContext(r);if(c)return c;if(e!==void 0)return e;throw new Error(`\`${a}\` must be used within \`${t}\``)}return[n,i]}function Ho(t,e=[]){let r=[];function n(a,c){const s=P.createContext(c),f=r.length;r=[...r,c];const m=_=>{var D;const{scope:T,children:E,...C}=_,N=((D=T==null?void 0:T[t])==null?void 0:D[f])||s,R=P.useMemo(()=>C,Object.values(C));return o.jsx(N.Provider,{value:R,children:E})};m.displayName=a+"Provider";function x(_,T){var N;const E=((N=T==null?void 0:T[t])==null?void 0:N[f])||s,C=P.useContext(E);if(C)return C;if(c!==void 0)return c;throw new Error(`\`${_}\` must be used within \`${a}\``)}return[m,x]}const i=()=>{const a=r.map(c=>P.createContext(c));return function(s){const f=(s==null?void 0:s[t])||a;return P.useMemo(()=>({[`__scope${t}`]:{...s,[t]:f}}),[s,f])}};return i.scopeName=t,[n,WNe(i,...e)]}function WNe(...t){const e=t[0];if(t.length===1)return e;const r=()=>{const n=t.map(i=>({useScope:i(),scopeName:i.scopeName}));return function(a){const c=n.reduce((s,{useScope:f,scopeName:m})=>{const _=f(a)[`__scope${m}`];return{...s,..._}},{});return P.useMemo(()=>({[`__scope${e.scopeName}`]:c}),[c])}};return r.scopeName=e.scopeName,r}function Fy(t){const e=KNe(t),r=P.forwardRef((n,i)=>{const{children:a,...c}=n,s=P.Children.toArray(a),f=s.find(YNe);if(f){const m=f.props.children,x=s.map(_=>_===f?P.Children.count(m)>1?P.Children.only(null):P.isValidElement(m)?m.props.children:null:_);return o.jsx(e,{...c,ref:i,children:P.isValidElement(m)?P.cloneElement(m,void 0,x):null})}return o.jsx(e,{...c,ref:i,children:a})});return r.displayName=`${t}.Slot`,r}var che=Fy("Slot");function KNe(t){const e=P.forwardRef((r,n)=>{const{children:i,...a}=r;if(P.isValidElement(i)){const c=XNe(i),s=ZNe(a,i.props);return i.type!==P.Fragment&&(s.ref=n?jm(n,c):c),P.cloneElement(i,s)}return P.Children.count(i)>1?P.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var uhe=Symbol("radix.slottable");function dhe(t){const e=({children:r})=>o.jsx(o.Fragment,{children:r});return e.displayName=`${t}.Slottable`,e.__radixId=uhe,e}function YNe(t){return P.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===uhe}function ZNe(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]=(...s)=>{const f=a(...s);return i(...s),f}:i&&(r[n]=i):n==="style"?r[n]={...i,...a}:n==="className"&&(r[n]=[i,a].filter(Boolean).join(" "))}return{...t,...r}}function XNe(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)}function wC(t){const e=t+"CollectionProvider",[r,n]=Ho(e),[i,a]=r(e,{collectionRef:{current:null},itemMap:new Map}),c=N=>{const{scope:R,children:D}=N,M=Xe.useRef(null),B=Xe.useRef(new Map).current;return o.jsx(i,{scope:R,itemMap:B,collectionRef:M,children:D})};c.displayName=e;const s=t+"CollectionSlot",f=Fy(s),m=Xe.forwardRef((N,R)=>{const{scope:D,children:M}=N,B=a(s,D),V=Wn(R,B.collectionRef);return o.jsx(f,{ref:V,children:M})});m.displayName=s;const x=t+"CollectionItemSlot",_="data-radix-collection-item",T=Fy(x),E=Xe.forwardRef((N,R)=>{const{scope:D,children:M,...B}=N,V=Xe.useRef(null),G=Wn(R,V),W=a(x,D);return Xe.useEffect(()=>(W.itemMap.set(V,{ref:V,...B}),()=>void W.itemMap.delete(V))),o.jsx(T,{[_]:"",ref:G,children:M})});E.displayName=x;function C(N){const R=a(t+"CollectionConsumer",N);return Xe.useCallback(()=>{const M=R.collectionRef.current;if(!M)return[];const B=Array.from(M.querySelectorAll(`[${_}]`));return Array.from(R.itemMap.values()).sort((W,X)=>B.indexOf(W.ref.current)-B.indexOf(X.ref.current))},[R.collectionRef,R.itemMap])}return[{Provider:c,Slot:m,ItemSlot:E},C,n]}var QNe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rn=QNe.reduce((t,e)=>{const r=Fy(`Primitive.${e}`),n=P.forwardRef((i,a)=>{const{asChild:c,...s}=i,f=c?r:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),o.jsx(f,{...s,ref:a})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{});function oG(t,e){t&&zm.flushSync(()=>t.dispatchEvent(e))}function fo(t){const e=P.useRef(t);return P.useEffect(()=>{e.current=t}),P.useMemo(()=>(...r)=>{var n;return(n=e.current)==null?void 0:n.call(e,...r)},[])}function JNe(t,e=globalThis==null?void 0:globalThis.document){const r=fo(t);P.useEffect(()=>{const n=i=>{i.key==="Escape"&&r(i)};return e.addEventListener("keydown",n,{capture:!0}),()=>e.removeEventListener("keydown",n,{capture:!0})},[r,e])}var eRe="DismissableLayer",xU="dismissableLayer.update",tRe="dismissableLayer.pointerDownOutside",rRe="dismissableLayer.focusOutside",mJ,hhe=P.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),F0=P.forwardRef((t,e)=>{const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:n,onPointerDownOutside:i,onFocusOutside:a,onInteractOutside:c,onDismiss:s,...f}=t,m=P.useContext(hhe),[x,_]=P.useState(null),T=(x==null?void 0:x.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,E]=P.useState({}),C=Wn(e,X=>_(X)),N=Array.from(m.layers),[R]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),D=N.indexOf(R),M=x?N.indexOf(x):-1,B=m.layersWithOutsidePointerEventsDisabled.size>0,V=M>=D,G=iRe(X=>{const Q=X.target,re=[...m.branches].some(se=>se.contains(Q));!V||re||(i==null||i(X),c==null||c(X),X.defaultPrevented||s==null||s())},T),W=sRe(X=>{const Q=X.target;[...m.branches].some(se=>se.contains(Q))||(a==null||a(X),c==null||c(X),X.defaultPrevented||s==null||s())},T);return JNe(X=>{M===m.layers.size-1&&(n==null||n(X),!X.defaultPrevented&&s&&(X.preventDefault(),s()))},T),P.useEffect(()=>{if(x)return r&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(mJ=T.body.style.pointerEvents,T.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(x)),m.layers.add(x),gJ(),()=>{r&&m.layersWithOutsidePointerEventsDisabled.size===1&&(T.body.style.pointerEvents=mJ)}},[x,T,r,m]),P.useEffect(()=>()=>{x&&(m.layers.delete(x),m.layersWithOutsidePointerEventsDisabled.delete(x),gJ())},[x,m]),P.useEffect(()=>{const X=()=>E({});return document.addEventListener(xU,X),()=>document.removeEventListener(xU,X)},[]),o.jsx(rn.div,{...f,ref:C,style:{pointerEvents:B?V?"auto":"none":void 0,...t.style},onFocusCapture:Or(t.onFocusCapture,W.onFocusCapture),onBlurCapture:Or(t.onBlurCapture,W.onBlurCapture),onPointerDownCapture:Or(t.onPointerDownCapture,G.onPointerDownCapture)})});F0.displayName=eRe;var nRe="DismissableLayerBranch",fhe=P.forwardRef((t,e)=>{const r=P.useContext(hhe),n=P.useRef(null),i=Wn(e,n);return P.useEffect(()=>{const a=n.current;if(a)return r.branches.add(a),()=>{r.branches.delete(a)}},[r.branches]),o.jsx(rn.div,{...t,ref:i})});fhe.displayName=nRe;function iRe(t,e=globalThis==null?void 0:globalThis.document){const r=fo(t),n=P.useRef(!1),i=P.useRef(()=>{});return P.useEffect(()=>{const a=s=>{if(s.target&&!n.current){let f=function(){phe(tRe,r,m,{discrete:!0})};const m={originalEvent:s};s.pointerType==="touch"?(e.removeEventListener("click",i.current),i.current=f,e.addEventListener("click",i.current,{once:!0})):f()}else e.removeEventListener("click",i.current);n.current=!1},c=window.setTimeout(()=>{e.addEventListener("pointerdown",a)},0);return()=>{window.clearTimeout(c),e.removeEventListener("pointerdown",a),e.removeEventListener("click",i.current)}},[e,r]),{onPointerDownCapture:()=>n.current=!0}}function sRe(t,e=globalThis==null?void 0:globalThis.document){const r=fo(t),n=P.useRef(!1);return P.useEffect(()=>{const i=a=>{a.target&&!n.current&&phe(rRe,r,{originalEvent:a},{discrete:!1})};return e.addEventListener("focusin",i),()=>e.removeEventListener("focusin",i)},[e,r]),{onFocusCapture:()=>n.current=!0,onBlurCapture:()=>n.current=!1}}function gJ(){const t=new CustomEvent(xU);document.dispatchEvent(t)}function phe(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?oG(i,a):i.dispatchEvent(a)}var aRe=F0,oRe=fhe,Io=globalThis!=null&&globalThis.document?P.useLayoutEffect:()=>{},lRe="Portal",aS=P.forwardRef((t,e)=>{var s;const{container:r,...n}=t,[i,a]=P.useState(!1);Io(()=>a(!0),[]);const c=r||i&&((s=globalThis==null?void 0:globalThis.document)==null?void 0:s.body);return c?ihe.createPortal(o.jsx(rn.div,{...n,ref:e}),c):null});aS.displayName=lRe;function cRe(t,e){return P.useReducer((r,n)=>e[r][n]??r,t)}var dl=t=>{const{present:e,children:r}=t,n=uRe(e),i=typeof r=="function"?r({present:n.isPresent}):P.Children.only(r),a=Wn(n.ref,dRe(i));return typeof r=="function"||n.isPresent?P.cloneElement(i,{ref:a}):null};dl.displayName="Presence";function uRe(t){const[e,r]=P.useState(),n=P.useRef(null),i=P.useRef(t),a=P.useRef("none"),c=t?"mounted":"unmounted",[s,f]=cRe(c,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return P.useEffect(()=>{const m=JP(n.current);a.current=s==="mounted"?m:"none"},[s]),Io(()=>{const m=n.current,x=i.current;if(x!==t){const T=a.current,E=JP(m);t?f("MOUNT"):E==="none"||(m==null?void 0:m.display)==="none"?f("UNMOUNT"):f(x&&T!==E?"ANIMATION_OUT":"UNMOUNT"),i.current=t}},[t,f]),Io(()=>{if(e){let m;const x=e.ownerDocument.defaultView??window,_=E=>{const N=JP(n.current).includes(E.animationName);if(E.target===e&&N&&(f("ANIMATION_END"),!i.current)){const R=e.style.animationFillMode;e.style.animationFillMode="forwards",m=x.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=R)})}},T=E=>{E.target===e&&(a.current=JP(n.current))};return e.addEventListener("animationstart",T),e.addEventListener("animationcancel",_),e.addEventListener("animationend",_),()=>{x.clearTimeout(m),e.removeEventListener("animationstart",T),e.removeEventListener("animationcancel",_),e.removeEventListener("animationend",_)}}else f("ANIMATION_END")},[e,f]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:P.useCallback(m=>{n.current=m?getComputedStyle(m):null,r(m)},[])}}function JP(t){return(t==null?void 0:t.animationName)||"none"}function dRe(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)}var hRe=gq[" useInsertionEffect ".trim().toString()]||Io;function ad({prop:t,defaultProp:e,onChange:r=()=>{},caller:n}){const[i,a,c]=fRe({defaultProp:e,onChange:r}),s=t!==void 0,f=s?t:i;{const x=P.useRef(t!==void 0);P.useEffect(()=>{const _=x.current;_!==s&&console.warn(`${n} is changing from ${_?"controlled":"uncontrolled"} to ${s?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),x.current=s},[s,n])}const m=P.useCallback(x=>{var _;if(s){const T=pRe(x)?x(t):x;T!==t&&((_=c.current)==null||_.call(c,T))}else a(x)},[s,t,a,c]);return[f,m]}function fRe({defaultProp:t,onChange:e}){const[r,n]=P.useState(t),i=P.useRef(r),a=P.useRef(e);return hRe(()=>{a.current=e},[e]),P.useEffect(()=>{var c;i.current!==r&&((c=a.current)==null||c.call(a,r),i.current=r)},[r,i]),[r,n,a]}function pRe(t){return typeof t=="function"}var mhe=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"}),mRe="VisuallyHidden",HO=P.forwardRef((t,e)=>o.jsx(rn.span,{...t,ref:e,style:{...mhe,...t.style}}));HO.displayName=mRe;var gRe=HO,lG="ToastProvider",[cG,yRe,xRe]=wC("Toast"),[ghe,U$t]=Ho("Toast",[xRe]),[_Re,WO]=ghe(lG),yhe=t=>{const{__scopeToast:e,label:r="Notification",duration:n=5e3,swipeDirection:i="right",swipeThreshold:a=50,children:c}=t,[s,f]=P.useState(null),[m,x]=P.useState(0),_=P.useRef(!1),T=P.useRef(!1);return r.trim()||console.error(`Invalid prop \`label\` supplied to \`${lG}\`. Expected non-empty \`string\`.`),o.jsx(cG.Provider,{scope:e,children:o.jsx(_Re,{scope:e,label:r,duration:n,swipeDirection:i,swipeThreshold:a,toastCount:m,viewport:s,onViewportChange:f,onToastAdd:P.useCallback(()=>x(E=>E+1),[]),onToastRemove:P.useCallback(()=>x(E=>E-1),[]),isFocusedToastEscapeKeyDownRef:_,isClosePausedRef:T,children:c})})};yhe.displayName=lG;var xhe="ToastViewport",vRe=["F8"],_U="toast.viewportPause",vU="toast.viewportResume",_he=P.forwardRef((t,e)=>{const{__scopeToast:r,hotkey:n=vRe,label:i="Notifications ({hotkey})",...a}=t,c=WO(xhe,r),s=yRe(r),f=P.useRef(null),m=P.useRef(null),x=P.useRef(null),_=P.useRef(null),T=Wn(e,_,c.onViewportChange),E=n.join("+").replace(/Key/g,"").replace(/Digit/g,""),C=c.toastCount>0;P.useEffect(()=>{const R=D=>{var B;n.length!==0&&n.every(V=>D[V]||D.code===V)&&((B=_.current)==null||B.focus())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[n]),P.useEffect(()=>{const R=f.current,D=_.current;if(C&&R&&D){const M=()=>{if(!c.isClosePausedRef.current){const W=new CustomEvent(_U);D.dispatchEvent(W),c.isClosePausedRef.current=!0}},B=()=>{if(c.isClosePausedRef.current){const W=new CustomEvent(vU);D.dispatchEvent(W),c.isClosePausedRef.current=!1}},V=W=>{!R.contains(W.relatedTarget)&&B()},G=()=>{R.contains(document.activeElement)||B()};return R.addEventListener("focusin",M),R.addEventListener("focusout",V),R.addEventListener("pointermove",M),R.addEventListener("pointerleave",G),window.addEventListener("blur",M),window.addEventListener("focus",B),()=>{R.removeEventListener("focusin",M),R.removeEventListener("focusout",V),R.removeEventListener("pointermove",M),R.removeEventListener("pointerleave",G),window.removeEventListener("blur",M),window.removeEventListener("focus",B)}}},[C,c.isClosePausedRef]);const N=P.useCallback(({tabbingDirection:R})=>{const M=s().map(B=>{const V=B.ref.current,G=[V,...RRe(V)];return R==="forwards"?G:G.reverse()});return(R==="forwards"?M.reverse():M).flat()},[s]);return P.useEffect(()=>{const R=_.current;if(R){const D=M=>{var G,W,X;const B=M.altKey||M.ctrlKey||M.metaKey;if(M.key==="Tab"&&!B){const Q=document.activeElement,re=M.shiftKey;if(M.target===R&&re){(G=m.current)==null||G.focus();return}const _e=N({tabbingDirection:re?"backwards":"forwards"}),Se=_e.findIndex(ve=>ve===Q);rB(_e.slice(Se+1))?M.preventDefault():re?(W=m.current)==null||W.focus():(X=x.current)==null||X.focus()}};return R.addEventListener("keydown",D),()=>R.removeEventListener("keydown",D)}},[s,N]),o.jsxs(oRe,{ref:f,role:"region","aria-label":i.replace("{hotkey}",E),tabIndex:-1,style:{pointerEvents:C?void 0:"none"},children:[C&&o.jsx(bU,{ref:m,onFocusFromOutsideViewport:()=>{const R=N({tabbingDirection:"forwards"});rB(R)}}),o.jsx(cG.Slot,{scope:r,children:o.jsx(rn.ol,{tabIndex:-1,...a,ref:T})}),C&&o.jsx(bU,{ref:x,onFocusFromOutsideViewport:()=>{const R=N({tabbingDirection:"backwards"});rB(R)}})]})});_he.displayName=xhe;var vhe="ToastFocusProxy",bU=P.forwardRef((t,e)=>{const{__scopeToast:r,onFocusFromOutsideViewport:n,...i}=t,a=WO(vhe,r);return o.jsx(HO,{"aria-hidden":!0,tabIndex:0,...i,ref:e,style:{position:"fixed"},onFocus:c=>{var m;const s=c.relatedTarget;!((m=a.viewport)!=null&&m.contains(s))&&n()}})});bU.displayName=vhe;var SC="Toast",bRe="toast.swipeStart",wRe="toast.swipeMove",SRe="toast.swipeCancel",TRe="toast.swipeEnd",bhe=P.forwardRef((t,e)=>{const{forceMount:r,open:n,defaultOpen:i,onOpenChange:a,...c}=t,[s,f]=ad({prop:n,defaultProp:i??!0,onChange:a,caller:SC});return o.jsx(dl,{present:r||s,children:o.jsx(kRe,{open:s,...c,ref:e,onClose:()=>f(!1),onPause:fo(t.onPause),onResume:fo(t.onResume),onSwipeStart:Or(t.onSwipeStart,m=>{m.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:Or(t.onSwipeMove,m=>{const{x,y:_}=m.detail.delta;m.currentTarget.setAttribute("data-swipe","move"),m.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${x}px`),m.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${_}px`)}),onSwipeCancel:Or(t.onSwipeCancel,m=>{m.currentTarget.setAttribute("data-swipe","cancel"),m.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),m.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),m.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),m.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:Or(t.onSwipeEnd,m=>{const{x,y:_}=m.detail.delta;m.currentTarget.setAttribute("data-swipe","end"),m.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),m.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),m.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${x}px`),m.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${_}px`),f(!1)})})})});bhe.displayName=SC;var[ERe,ARe]=ghe(SC,{onClose(){}}),kRe=P.forwardRef((t,e)=>{const{__scopeToast:r,type:n="foreground",duration:i,open:a,onClose:c,onEscapeKeyDown:s,onPause:f,onResume:m,onSwipeStart:x,onSwipeMove:_,onSwipeCancel:T,onSwipeEnd:E,...C}=t,N=WO(SC,r),[R,D]=P.useState(null),M=Wn(e,ve=>D(ve)),B=P.useRef(null),V=P.useRef(null),G=i||N.duration,W=P.useRef(0),X=P.useRef(G),Q=P.useRef(0),{onToastAdd:re,onToastRemove:se}=N,ue=fo(()=>{var Oe;(R==null?void 0:R.contains(document.activeElement))&&((Oe=N.viewport)==null||Oe.focus()),c()}),_e=P.useCallback(ve=>{!ve||ve===1/0||(window.clearTimeout(Q.current),W.current=new Date().getTime(),Q.current=window.setTimeout(ue,ve))},[ue]);P.useEffect(()=>{const ve=N.viewport;if(ve){const Oe=()=>{_e(X.current),m==null||m()},Ae=()=>{const we=new Date().getTime()-W.current;X.current=X.current-we,window.clearTimeout(Q.current),f==null||f()};return ve.addEventListener(_U,Ae),ve.addEventListener(vU,Oe),()=>{ve.removeEventListener(_U,Ae),ve.removeEventListener(vU,Oe)}}},[N.viewport,G,f,m,_e]),P.useEffect(()=>{a&&!N.isClosePausedRef.current&&_e(G)},[a,G,N.isClosePausedRef,_e]),P.useEffect(()=>(re(),()=>se()),[re,se]);const Se=P.useMemo(()=>R?Che(R):null,[R]);return N.viewport?o.jsxs(o.Fragment,{children:[Se&&o.jsx(CRe,{__scopeToast:r,role:"status","aria-live":n==="foreground"?"assertive":"polite","aria-atomic":!0,children:Se}),o.jsx(ERe,{scope:r,onClose:ue,children:zm.createPortal(o.jsx(cG.ItemSlot,{scope:r,children:o.jsx(aRe,{asChild:!0,onEscapeKeyDown:Or(s,()=>{N.isFocusedToastEscapeKeyDownRef.current||ue(),N.isFocusedToastEscapeKeyDownRef.current=!1}),children:o.jsx(rn.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":a?"open":"closed","data-swipe-direction":N.swipeDirection,...C,ref:M,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:Or(t.onKeyDown,ve=>{ve.key==="Escape"&&(s==null||s(ve.nativeEvent),ve.nativeEvent.defaultPrevented||(N.isFocusedToastEscapeKeyDownRef.current=!0,ue()))}),onPointerDown:Or(t.onPointerDown,ve=>{ve.button===0&&(B.current={x:ve.clientX,y:ve.clientY})}),onPointerMove:Or(t.onPointerMove,ve=>{if(!B.current)return;const Oe=ve.clientX-B.current.x,Ae=ve.clientY-B.current.y,we=!!V.current,ge=["left","right"].includes(N.swipeDirection),Ne=["left","up"].includes(N.swipeDirection)?Math.min:Math.max,Ie=ge?Ne(0,Oe):0,Te=ge?0:Ne(0,Ae),be=ve.pointerType==="touch"?10:2,We={x:Ie,y:Te},rt={originalEvent:ve,delta:We};we?(V.current=We,eN(wRe,_,rt,{discrete:!1})):yJ(We,N.swipeDirection,be)?(V.current=We,eN(bRe,x,rt,{discrete:!1}),ve.target.setPointerCapture(ve.pointerId)):(Math.abs(Oe)>be||Math.abs(Ae)>be)&&(B.current=null)}),onPointerUp:Or(t.onPointerUp,ve=>{const Oe=V.current,Ae=ve.target;if(Ae.hasPointerCapture(ve.pointerId)&&Ae.releasePointerCapture(ve.pointerId),V.current=null,B.current=null,Oe){const we=ve.currentTarget,ge={originalEvent:ve,delta:Oe};yJ(Oe,N.swipeDirection,N.swipeThreshold)?eN(TRe,E,ge,{discrete:!0}):eN(SRe,T,ge,{discrete:!0}),we.addEventListener("click",Ne=>Ne.preventDefault(),{once:!0})}})})})}),N.viewport)})]}):null}),CRe=t=>{const{__scopeToast:e,children:r,...n}=t,i=WO(SC,e),[a,c]=P.useState(!1),[s,f]=P.useState(!1);return PRe(()=>c(!0)),P.useEffect(()=>{const m=window.setTimeout(()=>f(!0),1e3);return()=>window.clearTimeout(m)},[]),s?null:o.jsx(aS,{asChild:!0,children:o.jsx(HO,{...n,children:a&&o.jsxs(o.Fragment,{children:[i.label," ",r]})})})},jRe="ToastTitle",whe=P.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t;return o.jsx(rn.div,{...n,ref:e})});whe.displayName=jRe;var IRe="ToastDescription",She=P.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t;return o.jsx(rn.div,{...n,ref:e})});She.displayName=IRe;var The="ToastAction",Ehe=P.forwardRef((t,e)=>{const{altText:r,...n}=t;return r.trim()?o.jsx(khe,{altText:r,asChild:!0,children:o.jsx(uG,{...n,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${The}\`. Expected non-empty \`string\`.`),null)});Ehe.displayName=The;var Ahe="ToastClose",uG=P.forwardRef((t,e)=>{const{__scopeToast:r,...n}=t,i=ARe(Ahe,r);return o.jsx(khe,{asChild:!0,children:o.jsx(rn.button,{type:"button",...n,ref:e,onClick:Or(t.onClick,i.onClose)})})});uG.displayName=Ahe;var khe=P.forwardRef((t,e)=>{const{__scopeToast:r,altText:n,...i}=t;return o.jsx(rn.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":n||void 0,...i,ref:e})});function Che(t){const e=[];return Array.from(t.childNodes).forEach(n=>{if(n.nodeType===n.TEXT_NODE&&n.textContent&&e.push(n.textContent),NRe(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(...Che(n))}}),e}function eN(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?oG(i,a):i.dispatchEvent(a)}var yJ=(t,e,r=0)=>{const n=Math.abs(t.x),i=Math.abs(t.y),a=n>i;return e==="left"||e==="right"?a&&n>r:!a&&i>r};function PRe(t=()=>{}){const e=fo(t);Io(()=>{let r=0,n=0;return r=window.requestAnimationFrame(()=>n=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(r),window.cancelAnimationFrame(n)}},[e])}function NRe(t){return t.nodeType===t.ELEMENT_NODE}function RRe(t){const e=[],r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode: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}});for(;r.nextNode();)e.push(r.currentNode);return e}function rB(t){const e=document.activeElement;return t.some(r=>r===e?!0:(r.focus(),document.activeElement!==e))}var LRe=yhe,jhe=_he,Ihe=bhe,Phe=whe,Nhe=She,Rhe=Ehe,Lhe=uG;function Dhe(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,_J=Li,oS=(t,e)=>r=>{var n;if((e==null?void 0:e.variants)==null)return _J(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:a}=e,c=Object.keys(i).map(m=>{const x=r==null?void 0:r[m],_=a==null?void 0:a[m];if(x===null)return null;const T=xJ(x)||xJ(_);return i[m][T]}),s=r&&Object.entries(r).reduce((m,x)=>{let[_,T]=x;return T===void 0||(m[_]=T),m},{}),f=e==null||(n=e.compoundVariants)===null||n===void 0?void 0:n.reduce((m,x)=>{let{class:_,className:T,...E}=x;return Object.entries(E).every(C=>{let[N,R]=C;return Array.isArray(R)?R.includes({...a,...s}[N]):{...a,...s}[N]===R})?[...m,_,T]:m},[]);return _J(t,c,f,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 DRe=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ohe=(...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 ORe={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 MRe=P.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:i="",children:a,iconNode:c,...s},f)=>P.createElement("svg",{ref:f,...ORe,width:e,height:e,stroke:t,strokeWidth:n?Number(r)*24/Number(e):r,className:Ohe("lucide",i),...s},[...c.map(([m,x])=>P.createElement(m,x)),...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 ur=(t,e)=>{const r=P.forwardRef(({className:n,...i},a)=>P.createElement(MRe,{ref:a,iconNode:e,className:Ohe(`lucide-${DRe(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 vJ=ur("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 By=ur("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 pc=ur("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 FRe=ur("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 uA=ur("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 lS=ur("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 BRe=ur("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 TC=ur("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 EC=ur("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 u1=ur("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 kL=ur("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 zRe=ur("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 Mhe=ur("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 Eo=ur("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 $Re=ur("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 Fhe=ur("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 dG=ur("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 Bhe=ur("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 Zf=ur("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 zhe=ur("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 po=ur("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 bJ=ur("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 ZA=ur("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 Ao=ur("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 od=ur("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 $m=ur("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 th=ur("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 URe=ur("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 wU=ur("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 $he=ur("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 xc=ur("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 VRe=ur("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 hG=ur("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 d1=ur("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 SU=ur("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 nB=ur("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 mc=ur("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 wJ=ur("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 TU=ur("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 ym=ur("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 Xl=ur("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 qRe=ur("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 GRe=ur("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 cS=ur("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 KO=ur("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 Uhe=ur("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 HRe=ur("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 WRe=ur("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 ep=ur("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 SJ=ur("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 KRe=ur("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 Vhe=ur("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 Yh=ur("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 h1=ur("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 XA=ur("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 YRe=ur("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 ZRe=ur("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 EU=ur("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 tp=ur("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 Ma=ur("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 TJ=ur("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 qhe=ur("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 fG=ur("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 XRe=ur("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 Ghe=ur("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 Hhe=ur("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 QRe=ur("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 Whe=ur("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 JRe=ur("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 eLe=ur("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 tLe=ur("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 EJ=ur("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 Khe=ur("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 rLe=ur("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 AU=ur("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 Cu=ur("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 zy=ur("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 YO=ur("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 Bi=ur("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 na=ur("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 nLe=ur("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 AC=ur("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 ZO=ur("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 iLe=ur("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 f1=ur("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 rp=ur("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 sLe=ur("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 Yhe=ur("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 AJ=ur("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 XO=ur("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 aLe=ur("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 oLe=ur("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 lLe=ur("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 cLe=ur("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 zi=ur("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 uLe=ur("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 CL=ur("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 xm=ur("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 dLe=ur("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 hLe=ur("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 fLe=ur("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 pLe=ur("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 mLe=ur("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 kJ=ur("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 QO=ur("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 gLe=ur("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 $y=ur("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 jL=ur("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 pG=ur("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 kC=ur("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 yLe=ur("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 mG=ur("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 QA=ur("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 Zhe=ur("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 xLe=ur("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 iB=ur("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 _Le=ur("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 Ss=ur("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 vLe=ur("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 kU=ur("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 gG=ur("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 Xc=ur("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 Xhe=ur("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 bLe=ur("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 yG=ur("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 wLe=ur("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 Qhe=ur("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 IL=ur("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 Jhe=ur("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 uS=ur("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 CC=ur("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 PL=ur("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 CU=ur("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 SLe=ur("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 JO=ur("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 gc=ur("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 Al=ur("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 dA=ur("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 TLe=ur("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 ELe=ur("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 xG=ur("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 ALe=ur("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 _G=ur("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 Ks=ur("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 kLe=ur("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 NL=ur("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 CJ=ur("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"}]]),vG="-",CLe=t=>{const e=ILe(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:c=>{const s=c.split(vG);return s[0]===""&&s.length!==1&&s.shift(),efe(s,e)||jLe(c)},getConflictingClassGroupIds:(c,s)=>{const f=r[c]||[];return s&&n[c]?[...f,...n[c]]:f}}},efe=(t,e)=>{var c;if(t.length===0)return e.classGroupId;const r=t[0],n=e.nextPart.get(r),i=n?efe(t.slice(1),n):void 0;if(i)return i;if(e.validators.length===0)return;const a=t.join(vG);return(c=e.validators.find(({validator:s})=>s(a)))==null?void 0:c.classGroupId},jJ=/^\[(.+)\]$/,jLe=t=>{if(jJ.test(t)){const e=jJ.exec(t)[1],r=e==null?void 0:e.substring(0,e.indexOf(":"));if(r)return"arbitrary.."+r}},ILe=t=>{const{theme:e,prefix:r}=t,n={nextPart:new Map,validators:[]};return NLe(Object.entries(t.classGroups),r).forEach(([a,c])=>{jU(c,n,a,e)}),n},jU=(t,e,r,n)=>{t.forEach(i=>{if(typeof i=="string"){const a=i===""?e:IJ(e,i);a.classGroupId=r;return}if(typeof i=="function"){if(PLe(i)){jU(i(n),e,r,n);return}e.validators.push({validator:i,classGroupId:r});return}Object.entries(i).forEach(([a,c])=>{jU(c,IJ(e,a),r,n)})})},IJ=(t,e)=>{let r=t;return e.split(vG).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},PLe=t=>t.isThemeGetter,NLe=(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,s])=>[e+c,s])):a);return[r,i]}):t,RLe=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)}}},tfe="!",LLe=t=>{const{separator:e,experimentalParseClassName:r}=t,n=e.length===1,i=e[0],a=e.length,c=s=>{const f=[];let m=0,x=0,_;for(let R=0;Rx?_-x:void 0;return{modifiers:f,hasImportantModifier:E,baseClassName:C,maybePostfixModifierPosition:N}};return r?s=>r({className:s,parseClassName:c}):c},DLe=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},OLe=t=>({cache:RLe(t.cacheSize),parseClassName:LLe(t),...CLe(t)}),MLe=/\s+/,FLe=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:i}=e,a=[],c=t.trim().split(MLe);let s="";for(let f=c.length-1;f>=0;f-=1){const m=c[f],{modifiers:x,hasImportantModifier:_,baseClassName:T,maybePostfixModifierPosition:E}=r(m);let C=!!E,N=n(C?T.substring(0,E):T);if(!N){if(!C){s=m+(s.length>0?" "+s:s);continue}if(N=n(T),!N){s=m+(s.length>0?" "+s:s);continue}C=!1}const R=DLe(x).join(":"),D=_?R+tfe:R,M=D+N;if(a.includes(M))continue;a.push(M);const B=i(N,C);for(let V=0;V0?" "+s:s)}return s};function BLe(){let t=0,e,r,n="";for(;t{if(typeof t=="string")return t;let e,r="";for(let n=0;n_(x),t());return r=OLe(m),n=r.cache.get,i=r.cache.set,a=s,s(f)}function s(f){const m=n(f);if(m)return m;const x=FLe(f,r);return i(f,x),x}return function(){return a(BLe.apply(null,arguments))}}const Sa=t=>{const e=r=>r[t]||[];return e.isThemeGetter=!0,e},nfe=/^\[(?:([a-z-]+):)?(.+)\]$/i,$Le=/^\d+\/\d+$/,ULe=new Set(["px","full","screen"]),VLe=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,qLe=/\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$/,GLe=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,HLe=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,WLe=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Kp=t=>jw(t)||ULe.has(t)||$Le.test(t),Lg=t=>dS(t,"length",tDe),jw=t=>!!t&&!Number.isNaN(Number(t)),sB=t=>dS(t,"number",jw),d2=t=>!!t&&Number.isInteger(Number(t)),KLe=t=>t.endsWith("%")&&jw(t.slice(0,-1)),Pi=t=>nfe.test(t),Dg=t=>VLe.test(t),YLe=new Set(["length","size","percentage"]),ZLe=t=>dS(t,YLe,ife),XLe=t=>dS(t,"position",ife),QLe=new Set(["image","url"]),JLe=t=>dS(t,QLe,nDe),eDe=t=>dS(t,"",rDe),h2=()=>!0,dS=(t,e,r)=>{const n=nfe.exec(t);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):r(n[2]):!1},tDe=t=>qLe.test(t)&&!GLe.test(t),ife=()=>!1,rDe=t=>HLe.test(t),nDe=t=>WLe.test(t),iDe=()=>{const t=Sa("colors"),e=Sa("spacing"),r=Sa("blur"),n=Sa("brightness"),i=Sa("borderColor"),a=Sa("borderRadius"),c=Sa("borderSpacing"),s=Sa("borderWidth"),f=Sa("contrast"),m=Sa("grayscale"),x=Sa("hueRotate"),_=Sa("invert"),T=Sa("gap"),E=Sa("gradientColorStops"),C=Sa("gradientColorStopPositions"),N=Sa("inset"),R=Sa("margin"),D=Sa("opacity"),M=Sa("padding"),B=Sa("saturate"),V=Sa("scale"),G=Sa("sepia"),W=Sa("skew"),X=Sa("space"),Q=Sa("translate"),re=()=>["auto","contain","none"],se=()=>["auto","hidden","clip","visible","scroll"],ue=()=>["auto",Pi,e],_e=()=>[Pi,e],Se=()=>["",Kp,Lg],ve=()=>["auto",jw,Pi],Oe=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Ae=()=>["solid","dashed","dotted","double","none"],we=()=>["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"],Ne=()=>["","0",Pi],Ie=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Te=()=>[jw,Pi];return{cacheSize:500,separator:":",theme:{colors:[h2],spacing:[Kp,Lg],blur:["none","",Dg,Pi],brightness:Te(),borderColor:[t],borderRadius:["none","","full",Dg,Pi],borderSpacing:_e(),borderWidth:Se(),contrast:Te(),grayscale:Ne(),hueRotate:Te(),invert:Ne(),gap:_e(),gradientColorStops:[t],gradientColorStopPositions:[KLe,Lg],inset:ue(),margin:ue(),opacity:Te(),padding:_e(),saturate:Te(),scale:Te(),sepia:Ne(),skew:Te(),space:_e(),translate:_e()},classGroups:{aspect:[{aspect:["auto","square","video",Pi]}],container:["container"],columns:[{columns:[Dg]}],"break-after":[{"break-after":Ie()}],"break-before":[{"break-before":Ie()}],"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:[...Oe(),Pi]}],overflow:[{overflow:se()}],"overflow-x":[{"overflow-x":se()}],"overflow-y":[{"overflow-y":se()}],overscroll:[{overscroll:re()}],"overscroll-x":[{"overscroll-x":re()}],"overscroll-y":[{"overscroll-y":re()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[N]}],"inset-x":[{"inset-x":[N]}],"inset-y":[{"inset-y":[N]}],start:[{start:[N]}],end:[{end:[N]}],top:[{top:[N]}],right:[{right:[N]}],bottom:[{bottom:[N]}],left:[{left:[N]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",d2,Pi]}],basis:[{basis:ue()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Pi]}],grow:[{grow:Ne()}],shrink:[{shrink:Ne()}],order:[{order:["first","last","none",d2,Pi]}],"grid-cols":[{"grid-cols":[h2]}],"col-start-end":[{col:["auto",{span:["full",d2,Pi]},Pi]}],"col-start":[{"col-start":ve()}],"col-end":[{"col-end":ve()}],"grid-rows":[{"grid-rows":[h2]}],"row-start-end":[{row:["auto",{span:[d2,Pi]},Pi]}],"row-start":[{"row-start":ve()}],"row-end":[{"row-end":ve()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Pi]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Pi]}],gap:[{gap:[T]}],"gap-x":[{"gap-x":[T]}],"gap-y":[{"gap-y":[T]}],"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:[M]}],px:[{px:[M]}],py:[{py:[M]}],ps:[{ps:[M]}],pe:[{pe:[M]}],pt:[{pt:[M]}],pr:[{pr:[M]}],pb:[{pb:[M]}],pl:[{pl:[M]}],m:[{m:[R]}],mx:[{mx:[R]}],my:[{my:[R]}],ms:[{ms:[R]}],me:[{me:[R]}],mt:[{mt:[R]}],mr:[{mr:[R]}],mb:[{mb:[R]}],ml:[{ml:[R]}],"space-x":[{"space-x":[X]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[X]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Pi,e]}],"min-w":[{"min-w":[Pi,e,"min","max","fit"]}],"max-w":[{"max-w":[Pi,e,"none","full","min","max","fit","prose",{screen:[Dg]},Dg]}],h:[{h:[Pi,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Pi,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Pi,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Pi,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Dg,Lg]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",sB]}],"font-family":[{font:[h2]}],"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",Pi]}],"line-clamp":[{"line-clamp":["none",jw,sB]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Kp,Pi]}],"list-image":[{"list-image":["none",Pi]}],"list-style-type":[{list:["none","disc","decimal",Pi]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[D]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[D]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Ae(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Kp,Lg]}],"underline-offset":[{"underline-offset":["auto",Kp,Pi]}],"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:_e()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Pi]}],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",Pi]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[D]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...Oe(),XLe]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",ZLe]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},JLe]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[C]}],"gradient-via-pos":[{via:[C]}],"gradient-to-pos":[{to:[C]}],"gradient-from":[{from:[E]}],"gradient-via":[{via:[E]}],"gradient-to":[{to:[E]}],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:[s]}],"border-w-x":[{"border-x":[s]}],"border-w-y":[{"border-y":[s]}],"border-w-s":[{"border-s":[s]}],"border-w-e":[{"border-e":[s]}],"border-w-t":[{"border-t":[s]}],"border-w-r":[{"border-r":[s]}],"border-w-b":[{"border-b":[s]}],"border-w-l":[{"border-l":[s]}],"border-opacity":[{"border-opacity":[D]}],"border-style":[{border:[...Ae(),"hidden"]}],"divide-x":[{"divide-x":[s]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[s]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[D]}],"divide-style":[{divide:Ae()}],"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:["",...Ae()]}],"outline-offset":[{"outline-offset":[Kp,Pi]}],"outline-w":[{outline:[Kp,Lg]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:Se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[D]}],"ring-offset-w":[{"ring-offset":[Kp,Lg]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Dg,eDe]}],"shadow-color":[{shadow:[h2]}],opacity:[{opacity:[D]}],"mix-blend":[{"mix-blend":[...we(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":we()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[f]}],"drop-shadow":[{"drop-shadow":["","none",Dg,Pi]}],grayscale:[{grayscale:[m]}],"hue-rotate":[{"hue-rotate":[x]}],invert:[{invert:[_]}],saturate:[{saturate:[B]}],sepia:[{sepia:[G]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[f]}],"backdrop-grayscale":[{"backdrop-grayscale":[m]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[x]}],"backdrop-invert":[{"backdrop-invert":[_]}],"backdrop-opacity":[{"backdrop-opacity":[D]}],"backdrop-saturate":[{"backdrop-saturate":[B]}],"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",Pi]}],duration:[{duration:Te()}],ease:[{ease:["linear","in","out","in-out",Pi]}],delay:[{delay:Te()}],animate:[{animate:["none","spin","ping","pulse","bounce",Pi]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[V]}],"scale-x":[{"scale-x":[V]}],"scale-y":[{"scale-y":[V]}],rotate:[{rotate:[d2,Pi]}],"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",Pi]}],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",Pi]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":_e()}],"scroll-mx":[{"scroll-mx":_e()}],"scroll-my":[{"scroll-my":_e()}],"scroll-ms":[{"scroll-ms":_e()}],"scroll-me":[{"scroll-me":_e()}],"scroll-mt":[{"scroll-mt":_e()}],"scroll-mr":[{"scroll-mr":_e()}],"scroll-mb":[{"scroll-mb":_e()}],"scroll-ml":[{"scroll-ml":_e()}],"scroll-p":[{"scroll-p":_e()}],"scroll-px":[{"scroll-px":_e()}],"scroll-py":[{"scroll-py":_e()}],"scroll-ps":[{"scroll-ps":_e()}],"scroll-pe":[{"scroll-pe":_e()}],"scroll-pt":[{"scroll-pt":_e()}],"scroll-pr":[{"scroll-pr":_e()}],"scroll-pb":[{"scroll-pb":_e()}],"scroll-pl":[{"scroll-pl":_e()}],"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",Pi]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[Kp,Lg,sB]}],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"]}}},sDe=zLe(iDe);function sr(...t){return sDe(Li(t))}function Da(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 PJ(t){const e=new Date(t);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(e)}function V$t(t){return t?t.replace(/<[^>]*>/g,""):""}const aDe=LRe,sfe=P.forwardRef(({className:t,...e},r)=>o.jsx(jhe,{ref:r,className:sr("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}));sfe.displayName=jhe.displayName;const oDe=oS("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"}}),afe=P.forwardRef(({className:t,variant:e,...r},n)=>o.jsx(Ihe,{ref:n,className:sr(oDe({variant:e}),t),...r}));afe.displayName=Ihe.displayName;const lDe=P.forwardRef(({className:t,...e},r)=>o.jsx(Rhe,{ref:r,className:sr("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}));lDe.displayName=Rhe.displayName;const ofe=P.forwardRef(({className:t,...e},r)=>o.jsx(Lhe,{ref:r,className:sr("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:o.jsx(Ks,{className:"h-4 w-4"})}));ofe.displayName=Lhe.displayName;const lfe=P.forwardRef(({className:t,...e},r)=>o.jsx(Phe,{ref:r,className:sr("text-sm font-semibold",t),...e}));lfe.displayName=Phe.displayName;const cfe=P.forwardRef(({className:t,...e},r)=>o.jsx(Nhe,{ref:r,className:sr("text-sm opacity-90",t),...e}));cfe.displayName=Nhe.displayName;function cDe(){const{toasts:t}=lhe();return o.jsxs(aDe,{children:[t.map(function({id:e,title:r,description:n,action:i,...a}){return o.jsxs(afe,{...a,children:[o.jsxs("div",{className:"grid gap-1",children:[r&&o.jsx(lfe,{children:r}),n&&o.jsx(cfe,{children:n})]}),i,o.jsx(ofe,{})]},e)}),o.jsx(sfe,{})]})}var NJ=["light","dark"],uDe="(prefers-color-scheme: dark)",dDe=P.createContext(void 0),hDe={setTheme:t=>{},themes:[]},fDe=()=>{var t;return(t=P.useContext(dDe))!=null?t:hDe};P.memo(({forcedTheme:t,storageKey:e,attribute:r,enableSystem:n,enableColorScheme:i,defaultTheme:a,value:c,attrs:s,nonce:f})=>{let m=a==="system",x=r==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${s.map(C=>`'${C}'`).join(",")})`};`:`var d=document.documentElement,n='${r}',s='setAttribute';`,_=i?NJ.includes(a)&&a?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${a}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",T=(C,N=!1,R=!0)=>{let D=c?c[C]:C,M=N?C+"|| ''":`'${D}'`,B="";return i&&R&&!N&&NJ.includes(C)&&(B+=`d.style.colorScheme = '${C}';`),r==="class"?N||D?B+=`c.add(${M})`:B+="null":D&&(B+=`d[s](n,${M})`),B},E=t?`!function(){${x}${T(t)}}()`:n?`!function(){try{${x}var e=localStorage.getItem('${e}');if('system'===e||(!e&&${m})){var t='${uDe}',m=window.matchMedia(t);if(m.media!==t||m.matches){${T("dark")}}else{${T("light")}}}else if(e){${c?`var x=${JSON.stringify(c)};`:""}${T(c?"x[e]":"e",!0)}}${m?"":"else{"+T(a,!1,!1)+"}"}${_}}catch(e){}}()`:`!function(){try{${x}var e=localStorage.getItem('${e}');if(e){${c?`var x=${JSON.stringify(c)};`:""}${T(c?"x[e]":"e",!0)}}else{${T(a,!1,!1)};}${_}}catch(t){}}();`;return P.createElement("script",{nonce:f,dangerouslySetInnerHTML:{__html:E}})});var pDe=t=>{switch(t){case"success":return yDe;case"info":return _De;case"warning":return xDe;case"error":return vDe;default:return null}},mDe=Array(12).fill(0),gDe=({visible:t,className:e})=>Xe.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":t},Xe.createElement("div",{className:"sonner-spinner"},mDe.map((r,n)=>Xe.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),yDe=Xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Xe.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"})),xDe=Xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Xe.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"})),_De=Xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Xe.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"})),vDe=Xe.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Xe.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"})),bDe=Xe.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"},Xe.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Xe.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),wDe=()=>{let[t,e]=Xe.useState(document.hidden);return Xe.useEffect(()=>{let r=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",r),()=>window.removeEventListener("visibilitychange",r)},[]),t},IU=1,SDe=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:IU++,a=this.toasts.find(s=>s.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(s=>s.id===i?(this.publish({...s,...t,id:i,title:r}),{...s,...t,id:i,dismissible:c,title:r}):s):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 f=>{if(a=["resolve",f],Xe.isValidElement(f))i=!1,this.create({id:r,type:"default",message:f});else if(EDe(f)&&!f.ok){i=!1;let m=typeof e.error=="function"?await e.error(`HTTP error! status: ${f.status}`):e.error,x=typeof e.description=="function"?await e.description(`HTTP error! status: ${f.status}`):e.description;this.create({id:r,type:"error",message:m,description:x})}else if(e.success!==void 0){i=!1;let m=typeof e.success=="function"?await e.success(f):e.success,x=typeof e.description=="function"?await e.description(f):e.description;this.create({id:r,type:"success",message:m,description:x})}}).catch(async f=>{if(a=["reject",f],e.error!==void 0){i=!1;let m=typeof e.error=="function"?await e.error(f):e.error,x=typeof e.description=="function"?await e.description(f):e.description;this.create({id:r,type:"error",message:m,description:x})}}).finally(()=>{var f;i&&(this.dismiss(r),r=void 0),(f=e.finally)==null||f.call(e)}),s=()=>new Promise((f,m)=>c.then(()=>a[0]==="reject"?m(a[1]):f(a[1])).catch(m));return typeof r!="string"&&typeof r!="number"?{unwrap:s}:Object.assign(r,{unwrap:s})},this.custom=(t,e)=>{let r=(e==null?void 0:e.id)||IU++;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}},yu=new SDe,TDe=(t,e)=>{let r=(e==null?void 0:e.id)||IU++;return yu.addToast({title:t,...e,id:r}),r},EDe=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",ADe=TDe,kDe=()=>yu.toasts,CDe=()=>yu.getActiveToasts(),Jt=Object.assign(ADe,{success:yu.success,info:yu.info,warning:yu.warning,error:yu.error,custom:yu.custom,message:yu.message,promise:yu.promise,dismiss:yu.dismiss,loading:yu.loading},{getHistory:kDe,getToasts:CDe});function jDe(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))}jDe(`: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 tN(t){return t.label!==void 0}var IDe=3,PDe="32px",NDe="16px",RJ=4e3,RDe=356,LDe=14,DDe=20,ODe=200;function Eh(...t){return t.filter(Boolean).join(" ")}function MDe(t){let[e,r]=t.split("-"),n=[];return e&&n.push(e),r&&n.push(r),n}var FDe=t=>{var e,r,n,i,a,c,s,f,m,x,_;let{invert:T,toast:E,unstyled:C,interacting:N,setHeights:R,visibleToasts:D,heights:M,index:B,toasts:V,expanded:G,removeToast:W,defaultRichColors:X,closeButton:Q,style:re,cancelButtonStyle:se,actionButtonStyle:ue,className:_e="",descriptionClassName:Se="",duration:ve,position:Oe,gap:Ae,loadingIcon:we,expandByDefault:ge,classNames:Ne,icons:Ie,closeButtonAriaLabel:Te="Close toast",pauseWhenPageIsHidden:be}=t,[We,rt]=Xe.useState(null),[at,Et]=Xe.useState(null),[_t,Vt]=Xe.useState(!1),[mt,Pt]=Xe.useState(!1),[er,wt]=Xe.useState(!1),[or,Sr]=Xe.useState(!1),[nn,lr]=Xe.useState(!1),[yr,tr]=Xe.useState(0),[yn,lt]=Xe.useState(0),At=Xe.useRef(E.duration||ve||RJ),Ot=Xe.useRef(null),dr=Xe.useRef(null),cr=B===0,hr=B+1<=D,Zt=E.type,Pr=E.dismissible!==!1,Nn=E.className||"",ai=E.descriptionClassName||"",ei=Xe.useMemo(()=>M.findIndex(Jr=>Jr.toastId===E.id)||0,[M,E.id]),Oi=Xe.useMemo(()=>{var Jr;return(Jr=E.closeButton)!=null?Jr:Q},[E.closeButton,Q]),ya=Xe.useMemo(()=>E.duration||ve||RJ,[E.duration,ve]),mi=Xe.useRef(0),ia=Xe.useRef(0),jr=Xe.useRef(0),Mn=Xe.useRef(null),[As,xa]=Oe.split("-"),go=Xe.useMemo(()=>M.reduce((Jr,Fn,es)=>es>=ei?Jr:Jr+Fn.height,0),[M,ei]),Yr=wDe(),hn=E.invert||T,gn=Zt==="loading";ia.current=Xe.useMemo(()=>ei*Ae+go,[ei,go]),Xe.useEffect(()=>{At.current=ya},[ya]),Xe.useEffect(()=>{Vt(!0)},[]),Xe.useEffect(()=>{let Jr=dr.current;if(Jr){let Fn=Jr.getBoundingClientRect().height;return lt(Fn),R(es=>[{toastId:E.id,height:Fn,position:E.position},...es]),()=>R(es=>es.filter(fl=>fl.toastId!==E.id))}},[R,E.id]),Xe.useLayoutEffect(()=>{if(!_t)return;let Jr=dr.current,Fn=Jr.style.height;Jr.style.height="auto";let es=Jr.getBoundingClientRect().height;Jr.style.height=Fn,lt(es),R(fl=>fl.find(Wo=>Wo.toastId===E.id)?fl.map(Wo=>Wo.toastId===E.id?{...Wo,height:es}:Wo):[{toastId:E.id,height:es,position:E.position},...fl])},[_t,E.title,E.description,R,E.id]);let Zr=Xe.useCallback(()=>{Pt(!0),tr(ia.current),R(Jr=>Jr.filter(Fn=>Fn.toastId!==E.id)),setTimeout(()=>{W(E)},ODe)},[E,W,R,ia]);Xe.useEffect(()=>{if(E.promise&&Zt==="loading"||E.duration===1/0||E.type==="loading")return;let Jr;return G||N||be&&Yr?(()=>{if(jr.current{var Fn;(Fn=E.onAutoClose)==null||Fn.call(E,E),Zr()},At.current)),()=>clearTimeout(Jr)},[G,N,E,Zt,be,Yr,Zr]),Xe.useEffect(()=>{E.delete&&Zr()},[Zr,E.delete]);function oi(){var Jr,Fn,es;return Ie!=null&&Ie.loading?Xe.createElement("div",{className:Eh(Ne==null?void 0:Ne.loader,(Jr=E==null?void 0:E.classNames)==null?void 0:Jr.loader,"sonner-loader"),"data-visible":Zt==="loading"},Ie.loading):we?Xe.createElement("div",{className:Eh(Ne==null?void 0:Ne.loader,(Fn=E==null?void 0:E.classNames)==null?void 0:Fn.loader,"sonner-loader"),"data-visible":Zt==="loading"},we):Xe.createElement(gDe,{className:Eh(Ne==null?void 0:Ne.loader,(es=E==null?void 0:E.classNames)==null?void 0:es.loader),visible:Zt==="loading"})}return Xe.createElement("li",{tabIndex:0,ref:dr,className:Eh(_e,Nn,Ne==null?void 0:Ne.toast,(e=E==null?void 0:E.classNames)==null?void 0:e.toast,Ne==null?void 0:Ne.default,Ne==null?void 0:Ne[Zt],(r=E==null?void 0:E.classNames)==null?void 0:r[Zt]),"data-sonner-toast":"","data-rich-colors":(n=E.richColors)!=null?n:X,"data-styled":!(E.jsx||E.unstyled||C),"data-mounted":_t,"data-promise":!!E.promise,"data-swiped":nn,"data-removed":mt,"data-visible":hr,"data-y-position":As,"data-x-position":xa,"data-index":B,"data-front":cr,"data-swiping":er,"data-dismissible":Pr,"data-type":Zt,"data-invert":hn,"data-swipe-out":or,"data-swipe-direction":at,"data-expanded":!!(G||ge&&_t),style:{"--index":B,"--toasts-before":B,"--z-index":V.length-B,"--offset":`${mt?yr:ia.current}px`,"--initial-height":ge?"auto":`${yn}px`,...re,...E.style},onDragEnd:()=>{wt(!1),rt(null),Mn.current=null},onPointerDown:Jr=>{gn||!Pr||(Ot.current=new Date,tr(ia.current),Jr.target.setPointerCapture(Jr.pointerId),Jr.target.tagName!=="BUTTON"&&(wt(!0),Mn.current={x:Jr.clientX,y:Jr.clientY}))},onPointerUp:()=>{var Jr,Fn,es,fl;if(or||!Pr)return;Mn.current=null;let Wo=Number(((Jr=dr.current)==null?void 0:Jr.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Mt=Number(((Fn=dr.current)==null?void 0:Fn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Po=new Date().getTime()-((es=Ot.current)==null?void 0:es.getTime()),bi=We==="x"?Wo:Mt,ks=Math.abs(bi)/Po;if(Math.abs(bi)>=DDe||ks>.11){tr(ia.current),(fl=E.onDismiss)==null||fl.call(E,E),Et(We==="x"?Wo>0?"right":"left":Mt>0?"down":"up"),Zr(),Sr(!0),lr(!1);return}wt(!1),rt(null)},onPointerMove:Jr=>{var Fn,es,fl,Wo;if(!Mn.current||!Pr||((Fn=window.getSelection())==null?void 0:Fn.toString().length)>0)return;let Mt=Jr.clientY-Mn.current.y,Po=Jr.clientX-Mn.current.x,bi=(es=t.swipeDirections)!=null?es:MDe(Oe);!We&&(Math.abs(Po)>1||Math.abs(Mt)>1)&&rt(Math.abs(Po)>Math.abs(Mt)?"x":"y");let ks={x:0,y:0};We==="y"?(bi.includes("top")||bi.includes("bottom"))&&(bi.includes("top")&&Mt<0||bi.includes("bottom")&&Mt>0)&&(ks.y=Mt):We==="x"&&(bi.includes("left")||bi.includes("right"))&&(bi.includes("left")&&Po<0||bi.includes("right")&&Po>0)&&(ks.x=Po),(Math.abs(ks.x)>0||Math.abs(ks.y)>0)&&lr(!0),(fl=dr.current)==null||fl.style.setProperty("--swipe-amount-x",`${ks.x}px`),(Wo=dr.current)==null||Wo.style.setProperty("--swipe-amount-y",`${ks.y}px`)}},Oi&&!E.jsx?Xe.createElement("button",{"aria-label":Te,"data-disabled":gn,"data-close-button":!0,onClick:gn||!Pr?()=>{}:()=>{var Jr;Zr(),(Jr=E.onDismiss)==null||Jr.call(E,E)},className:Eh(Ne==null?void 0:Ne.closeButton,(i=E==null?void 0:E.classNames)==null?void 0:i.closeButton)},(a=Ie==null?void 0:Ie.close)!=null?a:bDe):null,E.jsx||P.isValidElement(E.title)?E.jsx?E.jsx:typeof E.title=="function"?E.title():E.title:Xe.createElement(Xe.Fragment,null,Zt||E.icon||E.promise?Xe.createElement("div",{"data-icon":"",className:Eh(Ne==null?void 0:Ne.icon,(c=E==null?void 0:E.classNames)==null?void 0:c.icon)},E.promise||E.type==="loading"&&!E.icon?E.icon||oi():null,E.type!=="loading"?E.icon||(Ie==null?void 0:Ie[Zt])||pDe(Zt):null):null,Xe.createElement("div",{"data-content":"",className:Eh(Ne==null?void 0:Ne.content,(s=E==null?void 0:E.classNames)==null?void 0:s.content)},Xe.createElement("div",{"data-title":"",className:Eh(Ne==null?void 0:Ne.title,(f=E==null?void 0:E.classNames)==null?void 0:f.title)},typeof E.title=="function"?E.title():E.title),E.description?Xe.createElement("div",{"data-description":"",className:Eh(Se,ai,Ne==null?void 0:Ne.description,(m=E==null?void 0:E.classNames)==null?void 0:m.description)},typeof E.description=="function"?E.description():E.description):null),P.isValidElement(E.cancel)?E.cancel:E.cancel&&tN(E.cancel)?Xe.createElement("button",{"data-button":!0,"data-cancel":!0,style:E.cancelButtonStyle||se,onClick:Jr=>{var Fn,es;tN(E.cancel)&&Pr&&((es=(Fn=E.cancel).onClick)==null||es.call(Fn,Jr),Zr())},className:Eh(Ne==null?void 0:Ne.cancelButton,(x=E==null?void 0:E.classNames)==null?void 0:x.cancelButton)},E.cancel.label):null,P.isValidElement(E.action)?E.action:E.action&&tN(E.action)?Xe.createElement("button",{"data-button":!0,"data-action":!0,style:E.actionButtonStyle||ue,onClick:Jr=>{var Fn,es;tN(E.action)&&((es=(Fn=E.action).onClick)==null||es.call(Fn,Jr),!Jr.defaultPrevented&&Zr())},className:Eh(Ne==null?void 0:Ne.actionButton,(_=E==null?void 0:E.classNames)==null?void 0:_.actionButton)},E.action.label):null))};function LJ(){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 BDe(t,e){let r={};return[t,e].forEach((n,i)=>{let a=i===1,c=a?"--mobile-offset":"--offset",s=a?NDe:PDe;function f(m){["top","right","bottom","left"].forEach(x=>{r[`${c}-${x}`]=typeof m=="number"?`${m}px`:m})}typeof n=="number"||typeof n=="string"?f(n):typeof n=="object"?["top","right","bottom","left"].forEach(m=>{n[m]===void 0?r[`${c}-${m}`]=s:r[`${c}-${m}`]=typeof n[m]=="number"?`${n[m]}px`:n[m]}):f(s)}),r}var zDe=P.forwardRef(function(t,e){let{invert:r,position:n="bottom-right",hotkey:i=["altKey","KeyT"],expand:a,closeButton:c,className:s,offset:f,mobileOffset:m,theme:x="light",richColors:_,duration:T,style:E,visibleToasts:C=IDe,toastOptions:N,dir:R=LJ(),gap:D=LDe,loadingIcon:M,icons:B,containerAriaLabel:V="Notifications",pauseWhenPageIsHidden:G}=t,[W,X]=Xe.useState([]),Q=Xe.useMemo(()=>Array.from(new Set([n].concat(W.filter(be=>be.position).map(be=>be.position)))),[W,n]),[re,se]=Xe.useState([]),[ue,_e]=Xe.useState(!1),[Se,ve]=Xe.useState(!1),[Oe,Ae]=Xe.useState(x!=="system"?x:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),we=Xe.useRef(null),ge=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),Ne=Xe.useRef(null),Ie=Xe.useRef(!1),Te=Xe.useCallback(be=>{X(We=>{var rt;return(rt=We.find(at=>at.id===be.id))!=null&&rt.delete||yu.dismiss(be.id),We.filter(({id:at})=>at!==be.id)})},[]);return Xe.useEffect(()=>yu.subscribe(be=>{if(be.dismiss){X(We=>We.map(rt=>rt.id===be.id?{...rt,delete:!0}:rt));return}setTimeout(()=>{ihe.flushSync(()=>{X(We=>{let rt=We.findIndex(at=>at.id===be.id);return rt!==-1?[...We.slice(0,rt),{...We[rt],...be},...We.slice(rt+1)]:[be,...We]})})})}),[]),Xe.useEffect(()=>{if(x!=="system"){Ae(x);return}if(x==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Ae("dark"):Ae("light")),typeof window>"u")return;let be=window.matchMedia("(prefers-color-scheme: dark)");try{be.addEventListener("change",({matches:We})=>{Ae(We?"dark":"light")})}catch{be.addListener(({matches:rt})=>{try{Ae(rt?"dark":"light")}catch(at){console.error(at)}})}},[x]),Xe.useEffect(()=>{W.length<=1&&_e(!1)},[W]),Xe.useEffect(()=>{let be=We=>{var rt,at;i.every(Et=>We[Et]||We.code===Et)&&(_e(!0),(rt=we.current)==null||rt.focus()),We.code==="Escape"&&(document.activeElement===we.current||(at=we.current)!=null&&at.contains(document.activeElement))&&_e(!1)};return document.addEventListener("keydown",be),()=>document.removeEventListener("keydown",be)},[i]),Xe.useEffect(()=>{if(we.current)return()=>{Ne.current&&(Ne.current.focus({preventScroll:!0}),Ne.current=null,Ie.current=!1)}},[we.current]),Xe.createElement("section",{ref:e,"aria-label":`${V} ${ge}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},Q.map((be,We)=>{var rt;let[at,Et]=be.split("-");return W.length?Xe.createElement("ol",{key:be,dir:R==="auto"?LJ():R,tabIndex:-1,ref:we,className:s,"data-sonner-toaster":!0,"data-theme":Oe,"data-y-position":at,"data-lifted":ue&&W.length>1&&!a,"data-x-position":Et,style:{"--front-toast-height":`${((rt=re[0])==null?void 0:rt.height)||0}px`,"--width":`${RDe}px`,"--gap":`${D}px`,...E,...BDe(f,m)},onBlur:_t=>{Ie.current&&!_t.currentTarget.contains(_t.relatedTarget)&&(Ie.current=!1,Ne.current&&(Ne.current.focus({preventScroll:!0}),Ne.current=null))},onFocus:_t=>{_t.target instanceof HTMLElement&&_t.target.dataset.dismissible==="false"||Ie.current||(Ie.current=!0,Ne.current=_t.relatedTarget)},onMouseEnter:()=>_e(!0),onMouseMove:()=>_e(!0),onMouseLeave:()=>{Se||_e(!1)},onDragEnd:()=>_e(!1),onPointerDown:_t=>{_t.target instanceof HTMLElement&&_t.target.dataset.dismissible==="false"||ve(!0)},onPointerUp:()=>ve(!1)},W.filter(_t=>!_t.position&&We===0||_t.position===be).map((_t,Vt)=>{var mt,Pt;return Xe.createElement(FDe,{key:_t.id,icons:B,index:Vt,toast:_t,defaultRichColors:_,duration:(mt=N==null?void 0:N.duration)!=null?mt:T,className:N==null?void 0:N.className,descriptionClassName:N==null?void 0:N.descriptionClassName,invert:r,visibleToasts:C,closeButton:(Pt=N==null?void 0:N.closeButton)!=null?Pt:c,interacting:Se,position:be,style:N==null?void 0:N.style,unstyled:N==null?void 0:N.unstyled,classNames:N==null?void 0:N.classNames,cancelButtonStyle:N==null?void 0:N.cancelButtonStyle,actionButtonStyle:N==null?void 0:N.actionButtonStyle,removeToast:Te,toasts:W.filter(er=>er.position==_t.position),heights:re.filter(er=>er.position==_t.position),setHeights:se,expandByDefault:a,gap:D,loadingIcon:M,expanded:ue,pauseWhenPageIsHidden:G,swipeDirections:t.swipeDirections})})):null}))});const $De=({...t})=>{const{theme:e="system"}=fDe();return o.jsx(zDe,{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 UDe=gq[" useId ".trim().toString()]||(()=>{}),VDe=0;function Cl(t){const[e,r]=P.useState(UDe());return Io(()=>{r(n=>n??String(VDe++))},[t]),e?`radix-${e}`:""}var aB="focusScope.autoFocusOnMount",oB="focusScope.autoFocusOnUnmount",DJ={bubbles:!1,cancelable:!0},qDe="FocusScope",jC=P.forwardRef((t,e)=>{const{loop:r=!1,trapped:n=!1,onMountAutoFocus:i,onUnmountAutoFocus:a,...c}=t,[s,f]=P.useState(null),m=fo(i),x=fo(a),_=P.useRef(null),T=Wn(e,N=>f(N)),E=P.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;P.useEffect(()=>{if(n){let N=function(B){if(E.paused||!s)return;const V=B.target;s.contains(V)?_.current=V:Ug(_.current,{select:!0})},R=function(B){if(E.paused||!s)return;const V=B.relatedTarget;V!==null&&(s.contains(V)||Ug(_.current,{select:!0}))},D=function(B){if(document.activeElement===document.body)for(const G of B)G.removedNodes.length>0&&Ug(s)};document.addEventListener("focusin",N),document.addEventListener("focusout",R);const M=new MutationObserver(D);return s&&M.observe(s,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",N),document.removeEventListener("focusout",R),M.disconnect()}}},[n,s,E.paused]),P.useEffect(()=>{if(s){MJ.add(E);const N=document.activeElement;if(!s.contains(N)){const D=new CustomEvent(aB,DJ);s.addEventListener(aB,m),s.dispatchEvent(D),D.defaultPrevented||(GDe(ZDe(ufe(s)),{select:!0}),document.activeElement===N&&Ug(s))}return()=>{s.removeEventListener(aB,m),setTimeout(()=>{const D=new CustomEvent(oB,DJ);s.addEventListener(oB,x),s.dispatchEvent(D),D.defaultPrevented||Ug(N??document.body,{select:!0}),s.removeEventListener(oB,x),MJ.remove(E)},0)}}},[s,m,x,E]);const C=P.useCallback(N=>{if(!r&&!n||E.paused)return;const R=N.key==="Tab"&&!N.altKey&&!N.ctrlKey&&!N.metaKey,D=document.activeElement;if(R&&D){const M=N.currentTarget,[B,V]=HDe(M);B&&V?!N.shiftKey&&D===V?(N.preventDefault(),r&&Ug(B,{select:!0})):N.shiftKey&&D===B&&(N.preventDefault(),r&&Ug(V,{select:!0})):D===M&&N.preventDefault()}},[r,n,E.paused]);return o.jsx(rn.div,{tabIndex:-1,...c,ref:T,onKeyDown:C})});jC.displayName=qDe;function GDe(t,{select:e=!1}={}){const r=document.activeElement;for(const n of t)if(Ug(n,{select:e}),document.activeElement!==r)return}function HDe(t){const e=ufe(t),r=OJ(e,t),n=OJ(e.reverse(),t);return[r,n]}function ufe(t){const e=[],r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode: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}});for(;r.nextNode();)e.push(r.currentNode);return e}function OJ(t,e){for(const r of t)if(!WDe(r,{upTo:e}))return r}function WDe(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}function KDe(t){return t instanceof HTMLInputElement&&"select"in t}function Ug(t,{select:e=!1}={}){if(t&&t.focus){const r=document.activeElement;t.focus({preventScroll:!0}),t!==r&&KDe(t)&&e&&t.select()}}var MJ=YDe();function YDe(){let t=[];return{add(e){const r=t[0];e!==r&&(r==null||r.pause()),t=FJ(t,e),t.unshift(e)},remove(e){var r;t=FJ(t,e),(r=t[0])==null||r.resume()}}}function FJ(t,e){const r=[...t],n=r.indexOf(e);return n!==-1&&r.splice(n,1),r}function ZDe(t){return t.filter(e=>e.tagName!=="A")}var lB=0;function eM(){P.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??BJ()),document.body.insertAdjacentElement("beforeend",t[1]??BJ()),lB++,()=>{lB===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),lB--}},[])}function BJ(){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}var zf=function(){return zf=Object.assign||function(e){for(var r,n=1,i=arguments.length;n"u")return fOe;var e=pOe(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])}},gOe=pfe(),Iw="data-scroll-locked",yOe=function(t,e,r,n){var i=t.left,a=t.top,c=t.right,s=t.gap;return r===void 0&&(r="margin"),` .`.concat(QDe,` { overflow: hidden `).concat(n,`; padding-right: `).concat(s,"px ").concat(n,`; } body[`).concat(Iw,`] { 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(s,"px ").concat(n,`; `),r==="padding"&&"padding-right: ".concat(s,"px ").concat(n,";")].filter(Boolean).join(""),` } .`).concat(TR,` { right: `).concat(s,"px ").concat(n,`; } .`).concat(ER,` { margin-right: `).concat(s,"px ").concat(n,`; } .`).concat(TR," .").concat(TR,` { right: 0 `).concat(n,`; } .`).concat(ER," .").concat(ER,` { margin-right: 0 `).concat(n,`; } body[`).concat(Iw,`] { `).concat(JDe,": ").concat(s,`px; } `)},$J=function(){var t=parseInt(document.body.getAttribute(Iw)||"0",10);return isFinite(t)?t:0},xOe=function(){P.useEffect(function(){return document.body.setAttribute(Iw,($J()+1).toString()),function(){var t=$J()-1;t<=0?document.body.removeAttribute(Iw):document.body.setAttribute(Iw,t.toString())}},[])},_Oe=function(t){var e=t.noRelative,r=t.noImportant,n=t.gapMode,i=n===void 0?"margin":n;xOe();var a=P.useMemo(function(){return mOe(i)},[i]);return P.createElement(gOe,{styles:yOe(a,!e,i,r?"":"!important")})},PU=!1;if(typeof window<"u")try{var rN=Object.defineProperty({},"passive",{get:function(){return PU=!0,!0}});window.addEventListener("test",rN,rN),window.removeEventListener("test",rN,rN)}catch{PU=!1}var kb=PU?{passive:!1}:!1,vOe=function(t){return t.tagName==="TEXTAREA"},mfe=function(t,e){if(!(t instanceof Element))return!1;var r=window.getComputedStyle(t);return r[e]!=="hidden"&&!(r.overflowY===r.overflowX&&!vOe(t)&&r[e]==="visible")},bOe=function(t){return mfe(t,"overflowY")},wOe=function(t){return mfe(t,"overflowX")},UJ=function(t,e){var r=e.ownerDocument,n=e;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var i=gfe(t,n);if(i){var a=yfe(t,n),c=a[1],s=a[2];if(c>s)return!0}n=n.parentNode}while(n&&n!==r.body);return!1},SOe=function(t){var e=t.scrollTop,r=t.scrollHeight,n=t.clientHeight;return[e,r,n]},TOe=function(t){var e=t.scrollLeft,r=t.scrollWidth,n=t.clientWidth;return[e,r,n]},gfe=function(t,e){return t==="v"?bOe(e):wOe(e)},yfe=function(t,e){return t==="v"?SOe(e):TOe(e)},EOe=function(t,e){return t==="h"&&e==="rtl"?-1:1},AOe=function(t,e,r,n,i){var a=EOe(t,window.getComputedStyle(e).direction),c=a*n,s=r.target,f=e.contains(s),m=!1,x=c>0,_=0,T=0;do{if(!s)break;var E=yfe(t,s),C=E[0],N=E[1],R=E[2],D=N-R-a*C;(C||D)&&gfe(t,s)&&(_+=D,T+=C);var M=s.parentNode;s=M&&M.nodeType===Node.DOCUMENT_FRAGMENT_NODE?M.host:M}while(!f&&s!==document.body||f&&(e.contains(s)||e===s));return(x&&(Math.abs(_)<1||!i)||!x&&(Math.abs(T)<1||!i))&&(m=!0),m},nN=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},VJ=function(t){return[t.deltaX,t.deltaY]},qJ=function(t){return t&&"current"in t?t.current:t},kOe=function(t,e){return t[0]===e[0]&&t[1]===e[1]},COe=function(t){return` .block-interactivity-`.concat(t,` {pointer-events: none;} .allow-interactivity-`).concat(t,` {pointer-events: all;} `)},jOe=0,Cb=[];function IOe(t){var e=P.useRef([]),r=P.useRef([0,0]),n=P.useRef(),i=P.useState(jOe++)[0],a=P.useState(pfe)[0],c=P.useRef(t);P.useEffect(function(){c.current=t},[t]),P.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(i));var N=XDe([t.lockRef.current],(t.shards||[]).map(qJ),!0).filter(Boolean);return N.forEach(function(R){return R.classList.add("allow-interactivity-".concat(i))}),function(){document.body.classList.remove("block-interactivity-".concat(i)),N.forEach(function(R){return R.classList.remove("allow-interactivity-".concat(i))})}}},[t.inert,t.lockRef.current,t.shards]);var s=P.useCallback(function(N,R){if("touches"in N&&N.touches.length===2||N.type==="wheel"&&N.ctrlKey)return!c.current.allowPinchZoom;var D=nN(N),M=r.current,B="deltaX"in N?N.deltaX:M[0]-D[0],V="deltaY"in N?N.deltaY:M[1]-D[1],G,W=N.target,X=Math.abs(B)>Math.abs(V)?"h":"v";if("touches"in N&&X==="h"&&W.type==="range")return!1;var Q=UJ(X,W);if(!Q)return!0;if(Q?G=X:(G=X==="v"?"h":"v",Q=UJ(X,W)),!Q)return!1;if(!n.current&&"changedTouches"in N&&(B||V)&&(n.current=G),!G)return!0;var re=n.current||G;return AOe(re,R,N,re==="h"?B:V,!0)},[]),f=P.useCallback(function(N){var R=N;if(!(!Cb.length||Cb[Cb.length-1]!==a)){var D="deltaY"in R?VJ(R):nN(R),M=e.current.filter(function(G){return G.name===R.type&&(G.target===R.target||R.target===G.shadowParent)&&kOe(G.delta,D)})[0];if(M&&M.should){R.cancelable&&R.preventDefault();return}if(!M){var B=(c.current.shards||[]).map(qJ).filter(Boolean).filter(function(G){return G.contains(R.target)}),V=B.length>0?s(R,B[0]):!c.current.noIsolation;V&&R.cancelable&&R.preventDefault()}}},[]),m=P.useCallback(function(N,R,D,M){var B={name:N,delta:R,target:D,should:M,shadowParent:POe(D)};e.current.push(B),setTimeout(function(){e.current=e.current.filter(function(V){return V!==B})},1)},[]),x=P.useCallback(function(N){r.current=nN(N),n.current=void 0},[]),_=P.useCallback(function(N){m(N.type,VJ(N),N.target,s(N,t.lockRef.current))},[]),T=P.useCallback(function(N){m(N.type,nN(N),N.target,s(N,t.lockRef.current))},[]);P.useEffect(function(){return Cb.push(a),t.setCallbacks({onScrollCapture:_,onWheelCapture:_,onTouchMoveCapture:T}),document.addEventListener("wheel",f,kb),document.addEventListener("touchmove",f,kb),document.addEventListener("touchstart",x,kb),function(){Cb=Cb.filter(function(N){return N!==a}),document.removeEventListener("wheel",f,kb),document.removeEventListener("touchmove",f,kb),document.removeEventListener("touchstart",x,kb)}},[]);var E=t.removeScrollBar,C=t.inert;return P.createElement(P.Fragment,null,C?P.createElement(a,{styles:COe(i)}):null,E?P.createElement(_Oe,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function POe(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}const NOe=aOe(ffe,IOe);var IC=P.forwardRef(function(t,e){return P.createElement(tM,zf({},t,{ref:e,sideCar:NOe}))});IC.classNames=tM.classNames;var ROe=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},jb=new WeakMap,iN=new WeakMap,sN={},hB=0,xfe=function(t){return t&&(t.host||xfe(t.parentNode))},LOe=function(t,e){return e.map(function(r){if(t.contains(r))return r;var n=xfe(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})},DOe=function(t,e,r,n){var i=LOe(e,Array.isArray(t)?t:[t]);sN[r]||(sN[r]=new WeakMap);var a=sN[r],c=[],s=new Set,f=new Set(i),m=function(_){!_||s.has(_)||(s.add(_),m(_.parentNode))};i.forEach(m);var x=function(_){!_||f.has(_)||Array.prototype.forEach.call(_.children,function(T){if(s.has(T))x(T);else try{var E=T.getAttribute(n),C=E!==null&&E!=="false",N=(jb.get(T)||0)+1,R=(a.get(T)||0)+1;jb.set(T,N),a.set(T,R),c.push(T),N===1&&C&&iN.set(T,!0),R===1&&T.setAttribute(r,"true"),C||T.setAttribute(n,"true")}catch(D){console.error("aria-hidden: cannot operate on ",T,D)}})};return x(e),s.clear(),hB++,function(){c.forEach(function(_){var T=jb.get(_)-1,E=a.get(_)-1;jb.set(_,T),a.set(_,E),T||(iN.has(_)||_.removeAttribute(n),iN.delete(_)),E||_.removeAttribute(r)}),hB--,hB||(jb=new WeakMap,jb=new WeakMap,iN=new WeakMap,sN={})}},rM=function(t,e,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(t)?t:[t]),i=ROe(t);return i?(n.push.apply(n,Array.from(i.querySelectorAll("[aria-live]"))),DOe(n,i,r,"aria-hidden")):function(){return null}},nM="Dialog",[_fe,vfe]=Ho(nM),[OOe,rf]=_fe(nM),bfe=t=>{const{__scopeDialog:e,children:r,open:n,defaultOpen:i,onOpenChange:a,modal:c=!0}=t,s=P.useRef(null),f=P.useRef(null),[m,x]=ad({prop:n,defaultProp:i??!1,onChange:a,caller:nM});return o.jsx(OOe,{scope:e,triggerRef:s,contentRef:f,contentId:Cl(),titleId:Cl(),descriptionId:Cl(),open:m,onOpenChange:x,onOpenToggle:P.useCallback(()=>x(_=>!_),[x]),modal:c,children:r})};bfe.displayName=nM;var wfe="DialogTrigger",Sfe=P.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=rf(wfe,r),a=Wn(e,i.triggerRef);return o.jsx(rn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":SG(i.open),...n,ref:a,onClick:Or(t.onClick,i.onOpenToggle)})});Sfe.displayName=wfe;var bG="DialogPortal",[MOe,Tfe]=_fe(bG,{forceMount:void 0}),Efe=t=>{const{__scopeDialog:e,forceMount:r,children:n,container:i}=t,a=rf(bG,e);return o.jsx(MOe,{scope:e,forceMount:r,children:P.Children.map(n,c=>o.jsx(dl,{present:r||a.open,children:o.jsx(aS,{asChild:!0,container:i,children:c})}))})};Efe.displayName=bG;var RL="DialogOverlay",Afe=P.forwardRef((t,e)=>{const r=Tfe(RL,t.__scopeDialog),{forceMount:n=r.forceMount,...i}=t,a=rf(RL,t.__scopeDialog);return a.modal?o.jsx(dl,{present:n||a.open,children:o.jsx(BOe,{...i,ref:e})}):null});Afe.displayName=RL;var FOe=Fy("DialogOverlay.RemoveScroll"),BOe=P.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=rf(RL,r);return o.jsx(IC,{as:FOe,allowPinchZoom:!0,shards:[i.contentRef],children:o.jsx(rn.div,{"data-state":SG(i.open),...n,ref:e,style:{pointerEvents:"auto",...n.style}})})}),w0="DialogContent",kfe=P.forwardRef((t,e)=>{const r=Tfe(w0,t.__scopeDialog),{forceMount:n=r.forceMount,...i}=t,a=rf(w0,t.__scopeDialog);return o.jsx(dl,{present:n||a.open,children:a.modal?o.jsx(zOe,{...i,ref:e}):o.jsx($Oe,{...i,ref:e})})});kfe.displayName=w0;var zOe=P.forwardRef((t,e)=>{const r=rf(w0,t.__scopeDialog),n=P.useRef(null),i=Wn(e,r.contentRef,n);return P.useEffect(()=>{const a=n.current;if(a)return rM(a)},[]),o.jsx(Cfe,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Or(t.onCloseAutoFocus,a=>{var c;a.preventDefault(),(c=r.triggerRef.current)==null||c.focus()}),onPointerDownOutside:Or(t.onPointerDownOutside,a=>{const c=a.detail.originalEvent,s=c.button===0&&c.ctrlKey===!0;(c.button===2||s)&&a.preventDefault()}),onFocusOutside:Or(t.onFocusOutside,a=>a.preventDefault())})}),$Oe=P.forwardRef((t,e)=>{const r=rf(w0,t.__scopeDialog),n=P.useRef(!1),i=P.useRef(!1);return o.jsx(Cfe,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{var c,s;(c=t.onCloseAutoFocus)==null||c.call(t,a),a.defaultPrevented||(n.current||(s=r.triggerRef.current)==null||s.focus(),a.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:a=>{var f,m;(f=t.onInteractOutside)==null||f.call(t,a),a.defaultPrevented||(n.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const c=a.target;((m=r.triggerRef.current)==null?void 0:m.contains(c))&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})}),Cfe=P.forwardRef((t,e)=>{const{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:a,...c}=t,s=rf(w0,r),f=P.useRef(null),m=Wn(e,f);return eM(),o.jsxs(o.Fragment,{children:[o.jsx(jC,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:a,children:o.jsx(F0,{role:"dialog",id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":SG(s.open),...c,ref:m,onDismiss:()=>s.onOpenChange(!1)})}),o.jsxs(o.Fragment,{children:[o.jsx(VOe,{titleId:s.titleId}),o.jsx(GOe,{contentRef:f,descriptionId:s.descriptionId})]})]})}),wG="DialogTitle",jfe=P.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=rf(wG,r);return o.jsx(rn.h2,{id:i.titleId,...n,ref:e})});jfe.displayName=wG;var Ife="DialogDescription",Pfe=P.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=rf(Ife,r);return o.jsx(rn.p,{id:i.descriptionId,...n,ref:e})});Pfe.displayName=Ife;var Nfe="DialogClose",Rfe=P.forwardRef((t,e)=>{const{__scopeDialog:r,...n}=t,i=rf(Nfe,r);return o.jsx(rn.button,{type:"button",...n,ref:e,onClick:Or(t.onClick,()=>i.onOpenChange(!1))})});Rfe.displayName=Nfe;function SG(t){return t?"open":"closed"}var Lfe="DialogTitleWarning",[UOe,Dfe]=HNe(Lfe,{contentName:w0,titleName:wG,docsSlug:"dialog"}),VOe=({titleId:t})=>{const e=Dfe(Lfe),r=`\`${e.contentName}\` requires a \`${e.titleName}\` for the component to be accessible for screen reader users. If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component. For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return P.useEffect(()=>{t&&(document.getElementById(t)||console.error(r))},[r,t]),null},qOe="DialogDescriptionWarning",GOe=({contentRef:t,descriptionId:e})=>{const n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Dfe(qOe).contentName}}.`;return P.useEffect(()=>{var a;const i=(a=t.current)==null?void 0:a.getAttribute("aria-describedby");e&&i&&(document.getElementById(e)||console.warn(n))},[n,t,e]),null},iM=bfe,TG=Sfe,sM=Efe,hS=Afe,fS=kfe,PC=jfe,NC=Pfe,RC=Rfe,Ofe="AlertDialog",[HOe,q$t]=Ho(Ofe,[vfe]),Um=vfe(),Mfe=t=>{const{__scopeAlertDialog:e,...r}=t,n=Um(e);return o.jsx(iM,{...n,...r,modal:!0})};Mfe.displayName=Ofe;var WOe="AlertDialogTrigger",Ffe=P.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Um(r);return o.jsx(TG,{...i,...n,ref:e})});Ffe.displayName=WOe;var KOe="AlertDialogPortal",Bfe=t=>{const{__scopeAlertDialog:e,...r}=t,n=Um(e);return o.jsx(sM,{...n,...r})};Bfe.displayName=KOe;var YOe="AlertDialogOverlay",zfe=P.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Um(r);return o.jsx(hS,{...i,...n,ref:e})});zfe.displayName=YOe;var Pw="AlertDialogContent",[ZOe,XOe]=HOe(Pw),QOe=dhe("AlertDialogContent"),$fe=P.forwardRef((t,e)=>{const{__scopeAlertDialog:r,children:n,...i}=t,a=Um(r),c=P.useRef(null),s=Wn(e,c),f=P.useRef(null);return o.jsx(UOe,{contentName:Pw,titleName:Ufe,docsSlug:"alert-dialog",children:o.jsx(ZOe,{scope:r,cancelRef:f,children:o.jsxs(fS,{role:"alertdialog",...a,...i,ref:s,onOpenAutoFocus:Or(i.onOpenAutoFocus,m=>{var x;m.preventDefault(),(x=f.current)==null||x.focus({preventScroll:!0})}),onPointerDownOutside:m=>m.preventDefault(),onInteractOutside:m=>m.preventDefault(),children:[o.jsx(QOe,{children:n}),o.jsx(eMe,{contentRef:c})]})})})});$fe.displayName=Pw;var Ufe="AlertDialogTitle",Vfe=P.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Um(r);return o.jsx(PC,{...i,...n,ref:e})});Vfe.displayName=Ufe;var qfe="AlertDialogDescription",Gfe=P.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Um(r);return o.jsx(NC,{...i,...n,ref:e})});Gfe.displayName=qfe;var JOe="AlertDialogAction",Hfe=P.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,i=Um(r);return o.jsx(RC,{...i,...n,ref:e})});Hfe.displayName=JOe;var Wfe="AlertDialogCancel",Kfe=P.forwardRef((t,e)=>{const{__scopeAlertDialog:r,...n}=t,{cancelRef:i}=XOe(Wfe,r),a=Um(r),c=Wn(e,i);return o.jsx(RC,{...a,...n,ref:c})});Kfe.displayName=Wfe;var eMe=({contentRef:t})=>{const e=`\`${Pw}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${Pw}\` by passing a \`${qfe}\` component as a child, which also benefits sighted users by adding visible context to the dialog. Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${Pw}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component. For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return P.useEffect(()=>{var n;document.getElementById((n=t.current)==null?void 0:n.getAttribute("aria-describedby"))||console.warn(e)},[e,t]),null},tMe=Mfe,rMe=Ffe,nMe=Bfe,Yfe=zfe,Zfe=$fe,Xfe=Hfe,Qfe=Kfe,Jfe=Vfe,epe=Gfe;const JA=oS("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"}}),Ut=P.forwardRef(({className:t,variant:e,size:r,asChild:n=!1,...i},a)=>{const c=n?che:"button";return o.jsx(c,{className:sr(JA({variant:e,size:r,className:t})),ref:a,...i})});Ut.displayName="Button";const tpe=tMe,G$t=rMe,iMe=nMe,rpe=P.forwardRef(({className:t,...e},r)=>o.jsx(Yfe,{className:sr("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}));rpe.displayName=Yfe.displayName;const EG=P.forwardRef(({className:t,...e},r)=>o.jsxs(iMe,{children:[o.jsx(rpe,{}),o.jsx(Zfe,{ref:r,className:sr("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})]}));EG.displayName=Zfe.displayName;const AG=({className:t,...e})=>o.jsx("div",{className:sr("flex flex-col space-y-2 text-center sm:text-left",t),...e});AG.displayName="AlertDialogHeader";const kG=({className:t,...e})=>o.jsx("div",{className:sr("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});kG.displayName="AlertDialogFooter";const CG=P.forwardRef(({className:t,...e},r)=>o.jsx(Jfe,{ref:r,className:sr("text-lg font-semibold",t),...e}));CG.displayName=Jfe.displayName;const jG=P.forwardRef(({className:t,...e},r)=>o.jsx(epe,{ref:r,className:sr("text-sm text-muted-foreground",t),...e}));jG.displayName=epe.displayName;const IG=P.forwardRef(({className:t,...e},r)=>o.jsx(Xfe,{ref:r,className:sr(JA(),t),...e}));IG.displayName=Xfe.displayName;const PG=P.forwardRef(({className:t,...e},r)=>o.jsx(Qfe,{ref:r,className:sr(JA({variant:"outline"}),"mt-2 sm:mt-0",t),...e}));PG.displayName=Qfe.displayName;let LL=null;const sMe=["delete","remove","revoke","cannot be undone","permanently"];function H$t(t,e={}){const r=typeof t=="string"?{description:t,...e}:t,n=`${r.title??""} ${r.description??""}`.toLowerCase(),i=r.destructive??sMe.some(a=>n.includes(a));return new Promise(a=>{if(!LL){a(window.confirm(r.description??r.title??"Are you sure?"));return}LL({...r,destructive:i,resolve:a})})}function aMe(){const[t,e]=P.useState(null);P.useEffect(()=>(LL=i=>e(i),()=>{LL=null}),[]);const r=i=>{t==null||t.resolve(i),e(null)},n=!!(t!=null&&t.destructive);return o.jsx(tpe,{open:!!t,onOpenChange:i=>!i&&r(!1),children:o.jsxs(EG,{className:"sm:max-w-md",children:[o.jsx(AG,{children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:sr("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:o.jsx(CC,{className:"h-5 w-5"})}),o.jsxs("div",{className:"space-y-1.5 text-left",children:[o.jsx(CG,{children:(t==null?void 0:t.title)??(n?"Are you sure?":"Please confirm")}),(t==null?void 0:t.description)&&o.jsx(jG,{className:"leading-relaxed",children:t.description})]})]})}),o.jsxs(kG,{className:"gap-2 sm:gap-2",children:[o.jsx(PG,{onClick:()=>r(!1),children:(t==null?void 0:t.cancelText)??"Cancel"}),o.jsx(IG,{onClick:()=>r(!0),className:sr(n&&"bg-destructive text-destructive-foreground hover:bg-destructive/90"),children:(t==null?void 0:t.confirmText)??(n?"Delete":"Continue")})]})]})})}const oMe=["top","right","bottom","left"],Uy=Math.min,Yu=Math.max,DL=Math.round,aN=Math.floor,Vy=t=>({x:t,y:t}),lMe={left:"right",right:"left",bottom:"top",top:"bottom"},cMe={start:"end",end:"start"};function NU(t,e,r){return Yu(t,Uy(e,r))}function Im(t,e){return typeof t=="function"?t(e):t}function Pm(t){return t.split("-")[0]}function pS(t){return t.split("-")[1]}function NG(t){return t==="x"?"y":"x"}function RG(t){return t==="y"?"height":"width"}function qy(t){return["top","bottom"].includes(Pm(t))?"y":"x"}function LG(t){return NG(qy(t))}function uMe(t,e,r){r===void 0&&(r=!1);const n=pS(t),i=LG(t),a=RG(i);let c=i==="x"?n===(r?"end":"start")?"right":"left":n==="start"?"bottom":"top";return e.reference[a]>e.floating[a]&&(c=OL(c)),[c,OL(c)]}function dMe(t){const e=OL(t);return[RU(t),e,RU(e)]}function RU(t){return t.replace(/start|end/g,e=>cMe[e])}function hMe(t,e,r){const n=["left","right"],i=["right","left"],a=["top","bottom"],c=["bottom","top"];switch(t){case"top":case"bottom":return r?e?i:n:e?n:i;case"left":case"right":return e?a:c;default:return[]}}function fMe(t,e,r,n){const i=pS(t);let a=hMe(Pm(t),r==="start",n);return i&&(a=a.map(c=>c+"-"+i),e&&(a=a.concat(a.map(RU)))),a}function OL(t){return t.replace(/left|right|bottom|top/g,e=>lMe[e])}function pMe(t){return{top:0,right:0,bottom:0,left:0,...t}}function npe(t){return typeof t!="number"?pMe(t):{top:t,right:t,bottom:t,left:t}}function ML(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 GJ(t,e,r){let{reference:n,floating:i}=t;const a=qy(e),c=LG(e),s=RG(c),f=Pm(e),m=a==="y",x=n.x+n.width/2-i.width/2,_=n.y+n.height/2-i.height/2,T=n[s]/2-i[s]/2;let E;switch(f){case"top":E={x,y:n.y-i.height};break;case"bottom":E={x,y:n.y+n.height};break;case"right":E={x:n.x+n.width,y:_};break;case"left":E={x:n.x-i.width,y:_};break;default:E={x:n.x,y:n.y}}switch(pS(e)){case"start":E[c]-=T*(r&&m?-1:1);break;case"end":E[c]+=T*(r&&m?-1:1);break}return E}const mMe=async(t,e,r)=>{const{placement:n="bottom",strategy:i="absolute",middleware:a=[],platform:c}=r,s=a.filter(Boolean),f=await(c.isRTL==null?void 0:c.isRTL(e));let m=await c.getElementRects({reference:t,floating:e,strategy:i}),{x,y:_}=GJ(m,n,f),T=n,E={},C=0;for(let N=0;N({name:"arrow",options:t,async fn(e){const{x:r,y:n,placement:i,rects:a,platform:c,elements:s,middlewareData:f}=e,{element:m,padding:x=0}=Im(t,e)||{};if(m==null)return{};const _=npe(x),T={x:r,y:n},E=LG(i),C=RG(E),N=await c.getDimensions(m),R=E==="y",D=R?"top":"left",M=R?"bottom":"right",B=R?"clientHeight":"clientWidth",V=a.reference[C]+a.reference[E]-T[E]-a.floating[C],G=T[E]-a.reference[E],W=await(c.getOffsetParent==null?void 0:c.getOffsetParent(m));let X=W?W[B]:0;(!X||!await(c.isElement==null?void 0:c.isElement(W)))&&(X=s.floating[B]||a.floating[C]);const Q=V/2-G/2,re=X/2-N[C]/2-1,se=Uy(_[D],re),ue=Uy(_[M],re),_e=se,Se=X-N[C]-ue,ve=X/2-N[C]/2+Q,Oe=NU(_e,ve,Se),Ae=!f.arrow&&pS(i)!=null&&ve!==Oe&&a.reference[C]/2-(ve<_e?se:ue)-N[C]/2<0,we=Ae?ve<_e?ve-_e:ve-Se:0;return{[E]:T[E]+we,data:{[E]:Oe,centerOffset:ve-Oe-we,...Ae&&{alignmentOffset:we}},reset:Ae}}}),yMe=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var r,n;const{placement:i,middlewareData:a,rects:c,initialPlacement:s,platform:f,elements:m}=e,{mainAxis:x=!0,crossAxis:_=!0,fallbackPlacements:T,fallbackStrategy:E="bestFit",fallbackAxisSideDirection:C="none",flipAlignment:N=!0,...R}=Im(t,e);if((r=a.arrow)!=null&&r.alignmentOffset)return{};const D=Pm(i),M=qy(s),B=Pm(s)===s,V=await(f.isRTL==null?void 0:f.isRTL(m.floating)),G=T||(B||!N?[OL(s)]:dMe(s)),W=C!=="none";!T&&W&&G.push(...fMe(s,N,C,V));const X=[s,...G],Q=await ek(e,R),re=[];let se=((n=a.flip)==null?void 0:n.overflows)||[];if(x&&re.push(Q[D]),_){const ve=uMe(i,c,V);re.push(Q[ve[0]],Q[ve[1]])}if(se=[...se,{placement:i,overflows:re}],!re.every(ve=>ve<=0)){var ue,_e;const ve=(((ue=a.flip)==null?void 0:ue.index)||0)+1,Oe=X[ve];if(Oe)return{data:{index:ve,overflows:se},reset:{placement:Oe}};let Ae=(_e=se.filter(we=>we.overflows[0]<=0).sort((we,ge)=>we.overflows[1]-ge.overflows[1])[0])==null?void 0:_e.placement;if(!Ae)switch(E){case"bestFit":{var Se;const we=(Se=se.filter(ge=>{if(W){const Ne=qy(ge.placement);return Ne===M||Ne==="y"}return!0}).map(ge=>[ge.placement,ge.overflows.filter(Ne=>Ne>0).reduce((Ne,Ie)=>Ne+Ie,0)]).sort((ge,Ne)=>ge[1]-Ne[1])[0])==null?void 0:Se[0];we&&(Ae=we);break}case"initialPlacement":Ae=s;break}if(i!==Ae)return{reset:{placement:Ae}}}return{}}}};function HJ(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function WJ(t){return oMe.some(e=>t[e]>=0)}const xMe=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:r}=e,{strategy:n="referenceHidden",...i}=Im(t,e);switch(n){case"referenceHidden":{const a=await ek(e,{...i,elementContext:"reference"}),c=HJ(a,r.reference);return{data:{referenceHiddenOffsets:c,referenceHidden:WJ(c)}}}case"escaped":{const a=await ek(e,{...i,altBoundary:!0}),c=HJ(a,r.floating);return{data:{escapedOffsets:c,escaped:WJ(c)}}}default:return{}}}}};async function _Me(t,e){const{placement:r,platform:n,elements:i}=t,a=await(n.isRTL==null?void 0:n.isRTL(i.floating)),c=Pm(r),s=pS(r),f=qy(r)==="y",m=["left","top"].includes(c)?-1:1,x=a&&f?-1:1,_=Im(e,t);let{mainAxis:T,crossAxis:E,alignmentAxis:C}=typeof _=="number"?{mainAxis:_,crossAxis:0,alignmentAxis:null}:{mainAxis:_.mainAxis||0,crossAxis:_.crossAxis||0,alignmentAxis:_.alignmentAxis};return s&&typeof C=="number"&&(E=s==="end"?C*-1:C),f?{x:E*x,y:T*m}:{x:T*m,y:E*x}}const vMe=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:s}=e,f=await _Me(e,t);return c===((r=s.offset)==null?void 0:r.placement)&&(n=s.arrow)!=null&&n.alignmentOffset?{}:{x:i+f.x,y:a+f.y,data:{...f,placement:c}}}}},bMe=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:r,y:n,placement:i}=e,{mainAxis:a=!0,crossAxis:c=!1,limiter:s={fn:R=>{let{x:D,y:M}=R;return{x:D,y:M}}},...f}=Im(t,e),m={x:r,y:n},x=await ek(e,f),_=qy(Pm(i)),T=NG(_);let E=m[T],C=m[_];if(a){const R=T==="y"?"top":"left",D=T==="y"?"bottom":"right",M=E+x[R],B=E-x[D];E=NU(M,E,B)}if(c){const R=_==="y"?"top":"left",D=_==="y"?"bottom":"right",M=C+x[R],B=C-x[D];C=NU(M,C,B)}const N=s.fn({...e,[T]:E,[_]:C});return{...N,data:{x:N.x-r,y:N.y-n,enabled:{[T]:a,[_]:c}}}}}},wMe=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:r,y:n,placement:i,rects:a,middlewareData:c}=e,{offset:s=0,mainAxis:f=!0,crossAxis:m=!0}=Im(t,e),x={x:r,y:n},_=qy(i),T=NG(_);let E=x[T],C=x[_];const N=Im(s,e),R=typeof N=="number"?{mainAxis:N,crossAxis:0}:{mainAxis:0,crossAxis:0,...N};if(f){const B=T==="y"?"height":"width",V=a.reference[T]-a.floating[B]+R.mainAxis,G=a.reference[T]+a.reference[B]-R.mainAxis;EG&&(E=G)}if(m){var D,M;const B=T==="y"?"width":"height",V=["top","left"].includes(Pm(i)),G=a.reference[_]-a.floating[B]+(V&&((D=c.offset)==null?void 0:D[_])||0)+(V?0:R.crossAxis),W=a.reference[_]+a.reference[B]+(V?0:((M=c.offset)==null?void 0:M[_])||0)-(V?R.crossAxis:0);CW&&(C=W)}return{[T]:E,[_]:C}}}},SMe=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var r,n;const{placement:i,rects:a,platform:c,elements:s}=e,{apply:f=()=>{},...m}=Im(t,e),x=await ek(e,m),_=Pm(i),T=pS(i),E=qy(i)==="y",{width:C,height:N}=a.floating;let R,D;_==="top"||_==="bottom"?(R=_,D=T===(await(c.isRTL==null?void 0:c.isRTL(s.floating))?"start":"end")?"left":"right"):(D=_,R=T==="end"?"top":"bottom");const M=N-x.top-x.bottom,B=C-x.left-x.right,V=Uy(N-x[R],M),G=Uy(C-x[D],B),W=!e.middlewareData.shift;let X=V,Q=G;if((r=e.middlewareData.shift)!=null&&r.enabled.x&&(Q=B),(n=e.middlewareData.shift)!=null&&n.enabled.y&&(X=M),W&&!T){const se=Yu(x.left,0),ue=Yu(x.right,0),_e=Yu(x.top,0),Se=Yu(x.bottom,0);E?Q=C-2*(se!==0||ue!==0?se+ue:Yu(x.left,x.right)):X=N-2*(_e!==0||Se!==0?_e+Se:Yu(x.top,x.bottom))}await f({...e,availableWidth:Q,availableHeight:X});const re=await c.getDimensions(s.floating);return C!==re.width||N!==re.height?{reset:{rects:!0}}:{}}}};function aM(){return typeof window<"u"}function mS(t){return ipe(t)?(t.nodeName||"").toLowerCase():"#document"}function rd(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function up(t){var e;return(e=(ipe(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function ipe(t){return aM()?t instanceof Node||t instanceof rd(t).Node:!1}function Jh(t){return aM()?t instanceof Element||t instanceof rd(t).Element:!1}function np(t){return aM()?t instanceof HTMLElement||t instanceof rd(t).HTMLElement:!1}function KJ(t){return!aM()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof rd(t).ShadowRoot}function LC(t){const{overflow:e,overflowX:r,overflowY:n,display:i}=ef(t);return/auto|scroll|overlay|hidden|clip/.test(e+n+r)&&!["inline","contents"].includes(i)}function TMe(t){return["table","td","th"].includes(mS(t))}function oM(t){return[":popover-open",":modal"].some(e=>{try{return t.matches(e)}catch{return!1}})}function DG(t){const e=OG(),r=Jh(t)?ef(t):t;return r.transform!=="none"||r.perspective!=="none"||(r.containerType?r.containerType!=="normal":!1)||!e&&(r.backdropFilter?r.backdropFilter!=="none":!1)||!e&&(r.filter?r.filter!=="none":!1)||["transform","perspective","filter"].some(n=>(r.willChange||"").includes(n))||["paint","layout","strict","content"].some(n=>(r.contain||"").includes(n))}function EMe(t){let e=Gy(t);for(;np(e)&&!p1(e);){if(DG(e))return e;if(oM(e))return null;e=Gy(e)}return null}function OG(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function p1(t){return["html","body","#document"].includes(mS(t))}function ef(t){return rd(t).getComputedStyle(t)}function lM(t){return Jh(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function Gy(t){if(mS(t)==="html")return t;const e=t.assignedSlot||t.parentNode||KJ(t)&&t.host||up(t);return KJ(e)?e.host:e}function spe(t){const e=Gy(t);return p1(e)?t.ownerDocument?t.ownerDocument.body:t.body:np(e)&&LC(e)?e:spe(e)}function tk(t,e,r){var n;e===void 0&&(e=[]),r===void 0&&(r=!0);const i=spe(t),a=i===((n=t.ownerDocument)==null?void 0:n.body),c=rd(i);if(a){const s=LU(c);return e.concat(c,c.visualViewport||[],LC(i)?i:[],s&&r?tk(s):[])}return e.concat(i,tk(i,[],r))}function LU(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function ape(t){const e=ef(t);let r=parseFloat(e.width)||0,n=parseFloat(e.height)||0;const i=np(t),a=i?t.offsetWidth:r,c=i?t.offsetHeight:n,s=DL(r)!==a||DL(n)!==c;return s&&(r=a,n=c),{width:r,height:n,$:s}}function MG(t){return Jh(t)?t:t.contextElement}function Nw(t){const e=MG(t);if(!np(e))return Vy(1);const r=e.getBoundingClientRect(),{width:n,height:i,$:a}=ape(e);let c=(a?DL(r.width):r.width)/n,s=(a?DL(r.height):r.height)/i;return(!c||!Number.isFinite(c))&&(c=1),(!s||!Number.isFinite(s))&&(s=1),{x:c,y:s}}const AMe=Vy(0);function ope(t){const e=rd(t);return!OG()||!e.visualViewport?AMe:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function kMe(t,e,r){return e===void 0&&(e=!1),!r||e&&r!==rd(t)?!1:e}function S0(t,e,r,n){e===void 0&&(e=!1),r===void 0&&(r=!1);const i=t.getBoundingClientRect(),a=MG(t);let c=Vy(1);e&&(n?Jh(n)&&(c=Nw(n)):c=Nw(t));const s=kMe(a,r,n)?ope(a):Vy(0);let f=(i.left+s.x)/c.x,m=(i.top+s.y)/c.y,x=i.width/c.x,_=i.height/c.y;if(a){const T=rd(a),E=n&&Jh(n)?rd(n):n;let C=T,N=LU(C);for(;N&&n&&E!==C;){const R=Nw(N),D=N.getBoundingClientRect(),M=ef(N),B=D.left+(N.clientLeft+parseFloat(M.paddingLeft))*R.x,V=D.top+(N.clientTop+parseFloat(M.paddingTop))*R.y;f*=R.x,m*=R.y,x*=R.x,_*=R.y,f+=B,m+=V,C=rd(N),N=LU(C)}}return ML({width:x,height:_,x:f,y:m})}function CMe(t){let{elements:e,rect:r,offsetParent:n,strategy:i}=t;const a=i==="fixed",c=up(n),s=e?oM(e.floating):!1;if(n===c||s&&a)return r;let f={scrollLeft:0,scrollTop:0},m=Vy(1);const x=Vy(0),_=np(n);if((_||!_&&!a)&&((mS(n)!=="body"||LC(c))&&(f=lM(n)),np(n))){const T=S0(n);m=Nw(n),x.x=T.x+n.clientLeft,x.y=T.y+n.clientTop}return{width:r.width*m.x,height:r.height*m.y,x:r.x*m.x-f.scrollLeft*m.x+x.x,y:r.y*m.y-f.scrollTop*m.y+x.y}}function jMe(t){return Array.from(t.getClientRects())}function DU(t,e){const r=lM(t).scrollLeft;return e?e.left+r:S0(up(t)).left+r}function IMe(t){const e=up(t),r=lM(t),n=t.ownerDocument.body,i=Yu(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),a=Yu(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight);let c=-r.scrollLeft+DU(t);const s=-r.scrollTop;return ef(n).direction==="rtl"&&(c+=Yu(e.clientWidth,n.clientWidth)-i),{width:i,height:a,x:c,y:s}}function PMe(t,e){const r=rd(t),n=up(t),i=r.visualViewport;let a=n.clientWidth,c=n.clientHeight,s=0,f=0;if(i){a=i.width,c=i.height;const m=OG();(!m||m&&e==="fixed")&&(s=i.offsetLeft,f=i.offsetTop)}return{width:a,height:c,x:s,y:f}}function NMe(t,e){const r=S0(t,!0,e==="fixed"),n=r.top+t.clientTop,i=r.left+t.clientLeft,a=np(t)?Nw(t):Vy(1),c=t.clientWidth*a.x,s=t.clientHeight*a.y,f=i*a.x,m=n*a.y;return{width:c,height:s,x:f,y:m}}function YJ(t,e,r){let n;if(e==="viewport")n=PMe(t,r);else if(e==="document")n=IMe(up(t));else if(Jh(e))n=NMe(e,r);else{const i=ope(t);n={...e,x:e.x-i.x,y:e.y-i.y}}return ML(n)}function lpe(t,e){const r=Gy(t);return r===e||!Jh(r)||p1(r)?!1:ef(r).position==="fixed"||lpe(r,e)}function RMe(t,e){const r=e.get(t);if(r)return r;let n=tk(t,[],!1).filter(s=>Jh(s)&&mS(s)!=="body"),i=null;const a=ef(t).position==="fixed";let c=a?Gy(t):t;for(;Jh(c)&&!p1(c);){const s=ef(c),f=DG(c);!f&&s.position==="fixed"&&(i=null),(a?!f&&!i:!f&&s.position==="static"&&!!i&&["absolute","fixed"].includes(i.position)||LC(c)&&!f&&lpe(t,c))?n=n.filter(x=>x!==c):i=s,c=Gy(c)}return e.set(t,n),n}function LMe(t){let{element:e,boundary:r,rootBoundary:n,strategy:i}=t;const c=[...r==="clippingAncestors"?oM(e)?[]:RMe(e,this._c):[].concat(r),n],s=c[0],f=c.reduce((m,x)=>{const _=YJ(e,x,i);return m.top=Yu(_.top,m.top),m.right=Uy(_.right,m.right),m.bottom=Uy(_.bottom,m.bottom),m.left=Yu(_.left,m.left),m},YJ(e,s,i));return{width:f.right-f.left,height:f.bottom-f.top,x:f.left,y:f.top}}function DMe(t){const{width:e,height:r}=ape(t);return{width:e,height:r}}function OMe(t,e,r){const n=np(e),i=up(e),a=r==="fixed",c=S0(t,!0,a,e);let s={scrollLeft:0,scrollTop:0};const f=Vy(0);if(n||!n&&!a)if((mS(e)!=="body"||LC(i))&&(s=lM(e)),n){const E=S0(e,!0,a,e);f.x=E.x+e.clientLeft,f.y=E.y+e.clientTop}else i&&(f.x=DU(i));let m=0,x=0;if(i&&!n&&!a){const E=i.getBoundingClientRect();x=E.top+s.scrollTop,m=E.left+s.scrollLeft-DU(i,E)}const _=c.left+s.scrollLeft-f.x-m,T=c.top+s.scrollTop-f.y-x;return{x:_,y:T,width:c.width,height:c.height}}function fB(t){return ef(t).position==="static"}function ZJ(t,e){if(!np(t)||ef(t).position==="fixed")return null;if(e)return e(t);let r=t.offsetParent;return up(t)===r&&(r=r.ownerDocument.body),r}function cpe(t,e){const r=rd(t);if(oM(t))return r;if(!np(t)){let i=Gy(t);for(;i&&!p1(i);){if(Jh(i)&&!fB(i))return i;i=Gy(i)}return r}let n=ZJ(t,e);for(;n&&TMe(n)&&fB(n);)n=ZJ(n,e);return n&&p1(n)&&fB(n)&&!DG(n)?r:n||EMe(t)||r}const MMe=async function(t){const e=this.getOffsetParent||cpe,r=this.getDimensions,n=await r(t.floating);return{reference:OMe(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}};function FMe(t){return ef(t).direction==="rtl"}const BMe={convertOffsetParentRelativeRectToViewportRelativeRect:CMe,getDocumentElement:up,getClippingRect:LMe,getOffsetParent:cpe,getElementRects:MMe,getClientRects:jMe,getDimensions:DMe,getScale:Nw,isElement:Jh,isRTL:FMe};function zMe(t,e){let r=null,n;const i=up(t);function a(){var s;clearTimeout(n),(s=r)==null||s.disconnect(),r=null}function c(s,f){s===void 0&&(s=!1),f===void 0&&(f=1),a();const{left:m,top:x,width:_,height:T}=t.getBoundingClientRect();if(s||e(),!_||!T)return;const E=aN(x),C=aN(i.clientWidth-(m+_)),N=aN(i.clientHeight-(x+T)),R=aN(m),M={rootMargin:-E+"px "+-C+"px "+-N+"px "+-R+"px",threshold:Yu(0,Uy(1,f))||1};let B=!0;function V(G){const W=G[0].intersectionRatio;if(W!==f){if(!B)return c();W?c(!1,W):n=setTimeout(()=>{c(!1,1e-7)},1e3)}B=!1}try{r=new IntersectionObserver(V,{...M,root:i.ownerDocument})}catch{r=new IntersectionObserver(V,M)}r.observe(t)}return c(!0),a}function $Me(t,e,r,n){n===void 0&&(n={});const{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:c=typeof ResizeObserver=="function",layoutShift:s=typeof IntersectionObserver=="function",animationFrame:f=!1}=n,m=MG(t),x=i||a?[...m?tk(m):[],...tk(e)]:[];x.forEach(D=>{i&&D.addEventListener("scroll",r,{passive:!0}),a&&D.addEventListener("resize",r)});const _=m&&s?zMe(m,r):null;let T=-1,E=null;c&&(E=new ResizeObserver(D=>{let[M]=D;M&&M.target===m&&E&&(E.unobserve(e),cancelAnimationFrame(T),T=requestAnimationFrame(()=>{var B;(B=E)==null||B.observe(e)})),r()}),m&&!f&&E.observe(m),E.observe(e));let C,N=f?S0(t):null;f&&R();function R(){const D=S0(t);N&&(D.x!==N.x||D.y!==N.y||D.width!==N.width||D.height!==N.height)&&r(),N=D,C=requestAnimationFrame(R)}return r(),()=>{var D;x.forEach(M=>{i&&M.removeEventListener("scroll",r),a&&M.removeEventListener("resize",r)}),_==null||_(),(D=E)==null||D.disconnect(),E=null,f&&cancelAnimationFrame(C)}}const UMe=vMe,VMe=bMe,qMe=yMe,GMe=SMe,HMe=xMe,XJ=gMe,WMe=wMe,KMe=(t,e,r)=>{const n=new Map,i={platform:BMe,...r},a={...i.platform,_c:n};return mMe(t,e,{...i,platform:a})};var AR=typeof document<"u"?P.useLayoutEffect:P.useEffect;function FL(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(!FL(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)&&!FL(t[a],e[a]))return!1}return!0}return t!==t&&e!==e}function upe(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function QJ(t,e){const r=upe(t);return Math.round(e*r)/r}function pB(t){const e=P.useRef(t);return AR(()=>{e.current=t}),e}function YMe(t){t===void 0&&(t={});const{placement:e="bottom",strategy:r="absolute",middleware:n=[],platform:i,elements:{reference:a,floating:c}={},transform:s=!0,whileElementsMounted:f,open:m}=t,[x,_]=P.useState({x:0,y:0,strategy:r,placement:e,middlewareData:{},isPositioned:!1}),[T,E]=P.useState(n);FL(T,n)||E(n);const[C,N]=P.useState(null),[R,D]=P.useState(null),M=P.useCallback(ge=>{ge!==W.current&&(W.current=ge,N(ge))},[]),B=P.useCallback(ge=>{ge!==X.current&&(X.current=ge,D(ge))},[]),V=a||C,G=c||R,W=P.useRef(null),X=P.useRef(null),Q=P.useRef(x),re=f!=null,se=pB(f),ue=pB(i),_e=pB(m),Se=P.useCallback(()=>{if(!W.current||!X.current)return;const ge={placement:e,strategy:r,middleware:T};ue.current&&(ge.platform=ue.current),KMe(W.current,X.current,ge).then(Ne=>{const Ie={...Ne,isPositioned:_e.current!==!1};ve.current&&!FL(Q.current,Ie)&&(Q.current=Ie,zm.flushSync(()=>{_(Ie)}))})},[T,e,r,ue,_e]);AR(()=>{m===!1&&Q.current.isPositioned&&(Q.current.isPositioned=!1,_(ge=>({...ge,isPositioned:!1})))},[m]);const ve=P.useRef(!1);AR(()=>(ve.current=!0,()=>{ve.current=!1}),[]),AR(()=>{if(V&&(W.current=V),G&&(X.current=G),V&&G){if(se.current)return se.current(V,G,Se);Se()}},[V,G,Se,se,re]);const Oe=P.useMemo(()=>({reference:W,floating:X,setReference:M,setFloating:B}),[M,B]),Ae=P.useMemo(()=>({reference:V,floating:G}),[V,G]),we=P.useMemo(()=>{const ge={position:r,left:0,top:0};if(!Ae.floating)return ge;const Ne=QJ(Ae.floating,x.x),Ie=QJ(Ae.floating,x.y);return s?{...ge,transform:"translate("+Ne+"px, "+Ie+"px)",...upe(Ae.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:Ne,top:Ie}},[r,s,Ae.floating,x.x,x.y]);return P.useMemo(()=>({...x,update:Se,refs:Oe,elements:Ae,floatingStyles:we}),[x,Se,Oe,Ae,we])}const ZMe=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?XJ({element:n.current,padding:i}).fn(r):{}:n?XJ({element:n,padding:i}).fn(r):{}}}},XMe=(t,e)=>({...UMe(t),options:[t,e]}),QMe=(t,e)=>({...VMe(t),options:[t,e]}),JMe=(t,e)=>({...WMe(t),options:[t,e]}),eFe=(t,e)=>({...qMe(t),options:[t,e]}),tFe=(t,e)=>({...GMe(t),options:[t,e]}),rFe=(t,e)=>({...HMe(t),options:[t,e]}),nFe=(t,e)=>({...ZMe(t),options:[t,e]});var iFe="Arrow",dpe=P.forwardRef((t,e)=>{const{children:r,width:n=10,height:i=5,...a}=t;return o.jsx(rn.svg,{...a,ref:e,width:n,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?r:o.jsx("polygon",{points:"0,0 30,0 15,10"})})});dpe.displayName=iFe;var sFe=dpe;function DC(t){const[e,r]=P.useState(void 0);return Io(()=>{if(t){r({width:t.offsetWidth,height:t.offsetHeight});const n=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const a=i[0];let c,s;if("borderBoxSize"in a){const f=a.borderBoxSize,m=Array.isArray(f)?f[0]:f;c=m.inlineSize,s=m.blockSize}else c=t.offsetWidth,s=t.offsetHeight;r({width:c,height:s})});return n.observe(t,{box:"border-box"}),()=>n.unobserve(t)}else r(void 0)},[t]),e}var FG="Popper",[hpe,nx]=Ho(FG),[aFe,fpe]=hpe(FG),ppe=t=>{const{__scopePopper:e,children:r}=t,[n,i]=P.useState(null);return o.jsx(aFe,{scope:e,anchor:n,onAnchorChange:i,children:r})};ppe.displayName=FG;var mpe="PopperAnchor",gpe=P.forwardRef((t,e)=>{const{__scopePopper:r,virtualRef:n,...i}=t,a=fpe(mpe,r),c=P.useRef(null),s=Wn(e,c);return P.useEffect(()=>{a.onAnchorChange((n==null?void 0:n.current)||c.current)}),n?null:o.jsx(rn.div,{...i,ref:s})});gpe.displayName=mpe;var BG="PopperContent",[oFe,lFe]=hpe(BG),ype=P.forwardRef((t,e)=>{var _t,Vt,mt,Pt,er,wt;const{__scopePopper:r,side:n="bottom",sideOffset:i=0,align:a="center",alignOffset:c=0,arrowPadding:s=0,avoidCollisions:f=!0,collisionBoundary:m=[],collisionPadding:x=0,sticky:_="partial",hideWhenDetached:T=!1,updatePositionStrategy:E="optimized",onPlaced:C,...N}=t,R=fpe(BG,r),[D,M]=P.useState(null),B=Wn(e,or=>M(or)),[V,G]=P.useState(null),W=DC(V),X=(W==null?void 0:W.width)??0,Q=(W==null?void 0:W.height)??0,re=n+(a!=="center"?"-"+a:""),se=typeof x=="number"?x:{top:0,right:0,bottom:0,left:0,...x},ue=Array.isArray(m)?m:[m],_e=ue.length>0,Se={padding:se,boundary:ue.filter(uFe),altBoundary:_e},{refs:ve,floatingStyles:Oe,placement:Ae,isPositioned:we,middlewareData:ge}=YMe({strategy:"fixed",placement:re,whileElementsMounted:(...or)=>$Me(...or,{animationFrame:E==="always"}),elements:{reference:R.anchor},middleware:[XMe({mainAxis:i+Q,alignmentAxis:c}),f&&QMe({mainAxis:!0,crossAxis:!1,limiter:_==="partial"?JMe():void 0,...Se}),f&&eFe({...Se}),tFe({...Se,apply:({elements:or,rects:Sr,availableWidth:nn,availableHeight:lr})=>{const{width:yr,height:tr}=Sr.reference,yn=or.floating.style;yn.setProperty("--radix-popper-available-width",`${nn}px`),yn.setProperty("--radix-popper-available-height",`${lr}px`),yn.setProperty("--radix-popper-anchor-width",`${yr}px`),yn.setProperty("--radix-popper-anchor-height",`${tr}px`)}}),V&&nFe({element:V,padding:s}),dFe({arrowWidth:X,arrowHeight:Q}),T&&rFe({strategy:"referenceHidden",...Se})]}),[Ne,Ie]=vpe(Ae),Te=fo(C);Io(()=>{we&&(Te==null||Te())},[we,Te]);const be=(_t=ge.arrow)==null?void 0:_t.x,We=(Vt=ge.arrow)==null?void 0:Vt.y,rt=((mt=ge.arrow)==null?void 0:mt.centerOffset)!==0,[at,Et]=P.useState();return Io(()=>{D&&Et(window.getComputedStyle(D).zIndex)},[D]),o.jsx("div",{ref:ve.setFloating,"data-radix-popper-content-wrapper":"",style:{...Oe,transform:we?Oe.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:at,"--radix-popper-transform-origin":[(Pt=ge.transformOrigin)==null?void 0:Pt.x,(er=ge.transformOrigin)==null?void 0:er.y].join(" "),...((wt=ge.hide)==null?void 0:wt.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:o.jsx(oFe,{scope:r,placedSide:Ne,onArrowChange:G,arrowX:be,arrowY:We,shouldHideArrow:rt,children:o.jsx(rn.div,{"data-side":Ne,"data-align":Ie,...N,ref:B,style:{...N.style,animation:we?void 0:"none"}})})})});ype.displayName=BG;var xpe="PopperArrow",cFe={top:"bottom",right:"left",bottom:"top",left:"right"},_pe=P.forwardRef(function(e,r){const{__scopePopper:n,...i}=e,a=lFe(xpe,n),c=cFe[a.placedSide];return o.jsx("span",{ref:a.onArrowChange,style:{position:"absolute",left:a.arrowX,top:a.arrowY,[c]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[a.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[a.placedSide],visibility:a.shouldHideArrow?"hidden":void 0},children:o.jsx(sFe,{...i,ref:r,style:{...i.style,display:"block"}})})});_pe.displayName=xpe;function uFe(t){return t!==null}var dFe=t=>({name:"transformOrigin",options:t,fn(e){var R,D,M;const{placement:r,rects:n,middlewareData:i}=e,c=((R=i.arrow)==null?void 0:R.centerOffset)!==0,s=c?0:t.arrowWidth,f=c?0:t.arrowHeight,[m,x]=vpe(r),_={start:"0%",center:"50%",end:"100%"}[x],T=(((D=i.arrow)==null?void 0:D.x)??0)+s/2,E=(((M=i.arrow)==null?void 0:M.y)??0)+f/2;let C="",N="";return m==="bottom"?(C=c?_:`${T}px`,N=`${-f}px`):m==="top"?(C=c?_:`${T}px`,N=`${n.floating.height+f}px`):m==="right"?(C=`${-f}px`,N=c?_:`${E}px`):m==="left"&&(C=`${n.floating.width+f}px`,N=c?_:`${E}px`),{data:{x:C,y:N}}}});function vpe(t){const[e,r="center"]=t.split("-");return[e,r]}var cM=ppe,OC=gpe,uM=ype,dM=_pe,[hM,W$t]=Ho("Tooltip",[nx]),fM=nx(),bpe="TooltipProvider",hFe=700,OU="tooltip.open",[fFe,zG]=hM(bpe),wpe=t=>{const{__scopeTooltip:e,delayDuration:r=hFe,skipDelayDuration:n=300,disableHoverableContent:i=!1,children:a}=t,c=P.useRef(!0),s=P.useRef(!1),f=P.useRef(0);return P.useEffect(()=>{const m=f.current;return()=>window.clearTimeout(m)},[]),o.jsx(fFe,{scope:e,isOpenDelayedRef:c,delayDuration:r,onOpen:P.useCallback(()=>{window.clearTimeout(f.current),c.current=!1},[]),onClose:P.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>c.current=!0,n)},[n]),isPointerInTransitRef:s,onPointerInTransitChange:P.useCallback(m=>{s.current=m},[]),disableHoverableContent:i,children:a})};wpe.displayName=bpe;var rk="Tooltip",[pFe,pM]=hM(rk),Spe=t=>{const{__scopeTooltip:e,children:r,open:n,defaultOpen:i,onOpenChange:a,disableHoverableContent:c,delayDuration:s}=t,f=zG(rk,t.__scopeTooltip),m=fM(e),[x,_]=P.useState(null),T=Cl(),E=P.useRef(0),C=c??f.disableHoverableContent,N=s??f.delayDuration,R=P.useRef(!1),[D,M]=ad({prop:n,defaultProp:i??!1,onChange:X=>{X?(f.onOpen(),document.dispatchEvent(new CustomEvent(OU))):f.onClose(),a==null||a(X)},caller:rk}),B=P.useMemo(()=>D?R.current?"delayed-open":"instant-open":"closed",[D]),V=P.useCallback(()=>{window.clearTimeout(E.current),E.current=0,R.current=!1,M(!0)},[M]),G=P.useCallback(()=>{window.clearTimeout(E.current),E.current=0,M(!1)},[M]),W=P.useCallback(()=>{window.clearTimeout(E.current),E.current=window.setTimeout(()=>{R.current=!0,M(!0),E.current=0},N)},[N,M]);return P.useEffect(()=>()=>{E.current&&(window.clearTimeout(E.current),E.current=0)},[]),o.jsx(cM,{...m,children:o.jsx(pFe,{scope:e,contentId:T,open:D,stateAttribute:B,trigger:x,onTriggerChange:_,onTriggerEnter:P.useCallback(()=>{f.isOpenDelayedRef.current?W():V()},[f.isOpenDelayedRef,W,V]),onTriggerLeave:P.useCallback(()=>{C?G():(window.clearTimeout(E.current),E.current=0)},[G,C]),onOpen:V,onClose:G,disableHoverableContent:C,children:r})})};Spe.displayName=rk;var MU="TooltipTrigger",Tpe=P.forwardRef((t,e)=>{const{__scopeTooltip:r,...n}=t,i=pM(MU,r),a=zG(MU,r),c=fM(r),s=P.useRef(null),f=Wn(e,s,i.onTriggerChange),m=P.useRef(!1),x=P.useRef(!1),_=P.useCallback(()=>m.current=!1,[]);return P.useEffect(()=>()=>document.removeEventListener("pointerup",_),[_]),o.jsx(OC,{asChild:!0,...c,children:o.jsx(rn.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...n,ref:f,onPointerMove:Or(t.onPointerMove,T=>{T.pointerType!=="touch"&&!x.current&&!a.isPointerInTransitRef.current&&(i.onTriggerEnter(),x.current=!0)}),onPointerLeave:Or(t.onPointerLeave,()=>{i.onTriggerLeave(),x.current=!1}),onPointerDown:Or(t.onPointerDown,()=>{i.open&&i.onClose(),m.current=!0,document.addEventListener("pointerup",_,{once:!0})}),onFocus:Or(t.onFocus,()=>{m.current||i.onOpen()}),onBlur:Or(t.onBlur,i.onClose),onClick:Or(t.onClick,i.onClose)})})});Tpe.displayName=MU;var mFe="TooltipPortal",[K$t,gFe]=hM(mFe,{forceMount:void 0}),m1="TooltipContent",Epe=P.forwardRef((t,e)=>{const r=gFe(m1,t.__scopeTooltip),{forceMount:n=r.forceMount,side:i="top",...a}=t,c=pM(m1,t.__scopeTooltip);return o.jsx(dl,{present:n||c.open,children:c.disableHoverableContent?o.jsx(Ape,{side:i,...a,ref:e}):o.jsx(yFe,{side:i,...a,ref:e})})}),yFe=P.forwardRef((t,e)=>{const r=pM(m1,t.__scopeTooltip),n=zG(m1,t.__scopeTooltip),i=P.useRef(null),a=Wn(e,i),[c,s]=P.useState(null),{trigger:f,onClose:m}=r,x=i.current,{onPointerInTransitChange:_}=n,T=P.useCallback(()=>{s(null),_(!1)},[_]),E=P.useCallback((C,N)=>{const R=C.currentTarget,D={x:C.clientX,y:C.clientY},M=wFe(D,R.getBoundingClientRect()),B=SFe(D,M),V=TFe(N.getBoundingClientRect()),G=AFe([...B,...V]);s(G),_(!0)},[_]);return P.useEffect(()=>()=>T(),[T]),P.useEffect(()=>{if(f&&x){const C=R=>E(R,x),N=R=>E(R,f);return f.addEventListener("pointerleave",C),x.addEventListener("pointerleave",N),()=>{f.removeEventListener("pointerleave",C),x.removeEventListener("pointerleave",N)}}},[f,x,E,T]),P.useEffect(()=>{if(c){const C=N=>{const R=N.target,D={x:N.clientX,y:N.clientY},M=(f==null?void 0:f.contains(R))||(x==null?void 0:x.contains(R)),B=!EFe(D,c);M?T():B&&(T(),m())};return document.addEventListener("pointermove",C),()=>document.removeEventListener("pointermove",C)}},[f,x,c,m,T]),o.jsx(Ape,{...t,ref:a})}),[xFe,_Fe]=hM(rk,{isInside:!1}),vFe=dhe("TooltipContent"),Ape=P.forwardRef((t,e)=>{const{__scopeTooltip:r,children:n,"aria-label":i,onEscapeKeyDown:a,onPointerDownOutside:c,...s}=t,f=pM(m1,r),m=fM(r),{onClose:x}=f;return P.useEffect(()=>(document.addEventListener(OU,x),()=>document.removeEventListener(OU,x)),[x]),P.useEffect(()=>{if(f.trigger){const _=T=>{const E=T.target;E!=null&&E.contains(f.trigger)&&x()};return window.addEventListener("scroll",_,{capture:!0}),()=>window.removeEventListener("scroll",_,{capture:!0})}},[f.trigger,x]),o.jsx(F0,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:a,onPointerDownOutside:c,onFocusOutside:_=>_.preventDefault(),onDismiss:x,children:o.jsxs(uM,{"data-state":f.stateAttribute,...m,...s,ref:e,style:{...s.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:[o.jsx(vFe,{children:n}),o.jsx(xFe,{scope:r,isInside:!0,children:o.jsx(gRe,{id:f.contentId,role:"tooltip",children:i||n})})]})})});Epe.displayName=m1;var kpe="TooltipArrow",bFe=P.forwardRef((t,e)=>{const{__scopeTooltip:r,...n}=t,i=fM(r);return _Fe(kpe,r).isInside?null:o.jsx(dM,{...i,...n,ref:e})});bFe.displayName=kpe;function wFe(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")}}function SFe(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}function TFe(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}]}function EFe(t,e){const{x:r,y:n}=t;let i=!1;for(let a=0,c=e.length-1;an!=T>n&&r<(_-m)*(n-x)/(T-x)+m&&(i=!i)}return i}function AFe(t){const e=t.slice();return e.sort((r,n)=>r.xn.x?1:r.yn.y?1:0),kFe(e)}function kFe(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)}var CFe=wpe,jFe=Spe,IFe=Tpe,Cpe=Epe;const jpe=CFe,PFe=jFe,NFe=IFe,Ipe=P.forwardRef(({className:t,sideOffset:e=4,...r},n)=>o.jsx(Cpe,{ref:n,sideOffset:e,className:sr("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}));Ipe.displayName=Cpe.displayName;var gS=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(){}},T0=typeof window>"u"||"Deno"in globalThis;function zc(){}function RFe(t,e){return typeof t=="function"?t(e):t}function FU(t){return typeof t=="number"&&t>=0&&t!==1/0}function Ppe(t,e){return Math.max(t+(e||0)-Date.now(),0)}function jy(t,e){return typeof t=="function"?t(e):t}function Dd(t,e){return typeof t=="function"?t(e):t}function JJ(t,e){const{type:r="all",exact:n,fetchStatus:i,predicate:a,queryKey:c,stale:s}=t;if(c){if(n){if(e.queryHash!==$G(c,e.options))return!1}else if(!nk(e.queryKey,c))return!1}if(r!=="all"){const f=e.isActive();if(r==="active"&&!f||r==="inactive"&&f)return!1}return!(typeof s=="boolean"&&e.isStale()!==s||i&&i!==e.state.fetchStatus||a&&!a(e))}function eee(t,e){const{exact:r,status:n,predicate:i,mutationKey:a}=t;if(a){if(!e.options.mutationKey)return!1;if(r){if(E0(e.options.mutationKey)!==E0(a))return!1}else if(!nk(e.options.mutationKey,a))return!1}return!(n&&e.state.status!==n||i&&!i(e))}function $G(t,e){return((e==null?void 0:e.queryKeyHashFn)||E0)(t)}function E0(t){return JSON.stringify(t,(e,r)=>BU(r)?Object.keys(r).sort().reduce((n,i)=>(n[i]=r[i],n),{}):r)}function nk(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"&&typeof e=="object"?Object.keys(e).every(r=>nk(t[r],e[r])):!1}function Npe(t,e){if(t===e)return t;const r=tee(t)&&tee(e);if(r||BU(t)&&BU(e)){const n=r?t:Object.keys(t),i=n.length,a=r?e:Object.keys(e),c=a.length,s=r?[]:{},f=new Set(n);let m=0;for(let x=0;x{setTimeout(e,t)})}function zU(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?Npe(t,e):e}function DFe(t,e,r=0){const n=[...t,e];return r&&n.length>r?n.slice(1):n}function OFe(t,e,r=0){const n=[e,...t];return r&&n.length>r?n.slice(0,-1):n}var UG=Symbol();function Rpe(t,e){return!t.queryFn&&(e!=null&&e.initialPromise)?()=>e.initialPromise:!t.queryFn||t.queryFn===UG?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}function Lpe(t,e){return typeof t=="function"?t(...e):!!t}var e0,sy,Gw,Oce,MFe=(Oce=class extends gS{constructor(){super();Zn(this,e0);Zn(this,sy);Zn(this,Gw);xn(this,Gw,e=>{if(!T0&&window.addEventListener){const r=()=>e();return window.addEventListener("visibilitychange",r,!1),()=>{window.removeEventListener("visibilitychange",r)}}})}onSubscribe(){Tt(this,sy)||this.setEventListener(Tt(this,Gw))}onUnsubscribe(){var e;this.hasListeners()||((e=Tt(this,sy))==null||e.call(this),xn(this,sy,void 0))}setEventListener(e){var r;xn(this,Gw,e),(r=Tt(this,sy))==null||r.call(this),xn(this,sy,e(n=>{typeof n=="boolean"?this.setFocused(n):this.onFocus()}))}setFocused(e){Tt(this,e0)!==e&&(xn(this,e0,e),this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(r=>{r(e)})}isFocused(){var e;return typeof Tt(this,e0)=="boolean"?Tt(this,e0):((e=globalThis.document)==null?void 0:e.visibilityState)!=="hidden"}},e0=new WeakMap,sy=new WeakMap,Gw=new WeakMap,Oce),VG=new MFe,Hw,ay,Ww,Mce,FFe=(Mce=class extends gS{constructor(){super();Zn(this,Hw,!0);Zn(this,ay);Zn(this,Ww);xn(this,Ww,e=>{if(!T0&&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(){Tt(this,ay)||this.setEventListener(Tt(this,Ww))}onUnsubscribe(){var e;this.hasListeners()||((e=Tt(this,ay))==null||e.call(this),xn(this,ay,void 0))}setEventListener(e){var r;xn(this,Ww,e),(r=Tt(this,ay))==null||r.call(this),xn(this,ay,e(this.setOnline.bind(this)))}setOnline(e){Tt(this,Hw)!==e&&(xn(this,Hw,e),this.listeners.forEach(n=>{n(e)}))}isOnline(){return Tt(this,Hw)}},Hw=new WeakMap,ay=new WeakMap,Ww=new WeakMap,Mce),zL=new FFe;function $U(){let t,e;const r=new Promise((i,a)=>{t=i,e=a});r.status="pending",r.catch(()=>{});function n(i){Object.assign(r,i),delete r.resolve,delete r.reject}return r.resolve=i=>{n({status:"fulfilled",value:i}),t(i)},r.reject=i=>{n({status:"rejected",reason:i}),e(i)},r}function BFe(t){return Math.min(1e3*2**t,3e4)}function Dpe(t){return(t??"online")==="online"?zL.isOnline():!0}var Ope=class extends Error{constructor(t){super("CancelledError"),this.revert=t==null?void 0:t.revert,this.silent=t==null?void 0:t.silent}};function mB(t){return t instanceof Ope}function Mpe(t){let e=!1,r=0,n=!1,i;const a=$U(),c=N=>{var R;n||(T(new Ope(N)),(R=t.abort)==null||R.call(t))},s=()=>{e=!0},f=()=>{e=!1},m=()=>VG.isFocused()&&(t.networkMode==="always"||zL.isOnline())&&t.canRun(),x=()=>Dpe(t.networkMode)&&t.canRun(),_=N=>{var R;n||(n=!0,(R=t.onSuccess)==null||R.call(t,N),i==null||i(),a.resolve(N))},T=N=>{var R;n||(n=!0,(R=t.onError)==null||R.call(t,N),i==null||i(),a.reject(N))},E=()=>new Promise(N=>{var R;i=D=>{(n||m())&&N(D)},(R=t.onPause)==null||R.call(t)}).then(()=>{var N;i=void 0,n||(N=t.onContinue)==null||N.call(t)}),C=()=>{if(n)return;let N;const R=r===0?t.initialPromise:void 0;try{N=R??t.fn()}catch(D){N=Promise.reject(D)}Promise.resolve(N).then(_).catch(D=>{var W;if(n)return;const M=t.retry??(T0?0:3),B=t.retryDelay??BFe,V=typeof B=="function"?B(r,D):B,G=M===!0||typeof M=="number"&&rm()?void 0:E()).then(()=>{e?T(D):C()})})};return{promise:a,cancel:c,continue:()=>(i==null||i(),a),cancelRetry:s,continueRetry:f,canStart:x,start:()=>(x()?C():E().then(C),a)}}var zFe=t=>setTimeout(t,0);function $Fe(){let t=[],e=0,r=s=>{s()},n=s=>{s()},i=zFe;const a=s=>{e?t.push(s):i(()=>{r(s)})},c=()=>{const s=t;t=[],s.length&&i(()=>{n(()=>{s.forEach(f=>{r(f)})})})};return{batch:s=>{let f;e++;try{f=s()}finally{e--,e||c()}return f},batchCalls:s=>(...f)=>{a(()=>{s(...f)})},schedule:a,setNotifyFunction:s=>{r=s},setBatchNotifyFunction:s=>{n=s},setScheduler:s=>{i=s}}}var al=$Fe(),t0,Fce,Fpe=(Fce=class{constructor(){Zn(this,t0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),FU(this.gcTime)&&xn(this,t0,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(T0?1/0:5*60*1e3))}clearGcTimeout(){Tt(this,t0)&&(clearTimeout(Tt(this,t0)),xn(this,t0,void 0))}},t0=new WeakMap,Fce),Kw,r0,Ld,n0,uc,fC,i0,Rh,tm,Bce,UFe=(Bce=class extends Fpe{constructor(e){super();Zn(this,Rh);Zn(this,Kw);Zn(this,r0);Zn(this,Ld);Zn(this,n0);Zn(this,uc);Zn(this,fC);Zn(this,i0);xn(this,i0,!1),xn(this,fC,e.defaultOptions),this.setOptions(e.options),this.observers=[],xn(this,n0,e.client),xn(this,Ld,Tt(this,n0).getQueryCache()),this.queryKey=e.queryKey,this.queryHash=e.queryHash,xn(this,Kw,VFe(this.options)),this.state=e.state??Tt(this,Kw),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var e;return(e=Tt(this,uc))==null?void 0:e.promise}setOptions(e){this.options={...Tt(this,fC),...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Tt(this,Ld).remove(this)}setData(e,r){const n=zU(this.state.data,e,this.options);return Fi(this,Rh,tm).call(this,{data:n,type:"success",dataUpdatedAt:r==null?void 0:r.updatedAt,manual:r==null?void 0:r.manual}),n}setState(e,r){Fi(this,Rh,tm).call(this,{type:"setState",state:e,setStateOptions:r})}cancel(e){var n,i;const r=(n=Tt(this,uc))==null?void 0:n.promise;return(i=Tt(this,uc))==null||i.cancel(e),r?r.then(zc).catch(zc):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Tt(this,Kw))}isActive(){return this.observers.some(e=>Dd(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===UG||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>jy(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:!Ppe(this.state.dataUpdatedAt,e)}onFocus(){var r;const e=this.observers.find(n=>n.shouldFetchOnWindowFocus());e==null||e.refetch({cancelRefetch:!1}),(r=Tt(this,uc))==null||r.continue()}onOnline(){var r;const e=this.observers.find(n=>n.shouldFetchOnReconnect());e==null||e.refetch({cancelRefetch:!1}),(r=Tt(this,uc))==null||r.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),Tt(this,Ld).notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(r=>r!==e),this.observers.length||(Tt(this,uc)&&(Tt(this,i0)?Tt(this,uc).cancel({revert:!0}):Tt(this,uc).cancelRetry()),this.scheduleGc()),Tt(this,Ld).notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Fi(this,Rh,tm).call(this,{type:"invalidate"})}fetch(e,r){var m,x,_;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(r!=null&&r.cancelRefetch))this.cancel({silent:!0});else if(Tt(this,uc))return Tt(this,uc).continueRetry(),Tt(this,uc).promise}if(e&&this.setOptions(e),!this.options.queryFn){const T=this.observers.find(E=>E.options.queryFn);T&&this.setOptions(T.options)}const n=new AbortController,i=T=>{Object.defineProperty(T,"signal",{enumerable:!0,get:()=>(xn(this,i0,!0),n.signal)})},a=()=>{const T=Rpe(this.options,r),C=(()=>{const N={client:Tt(this,n0),queryKey:this.queryKey,meta:this.meta};return i(N),N})();return xn(this,i0,!1),this.options.persister?this.options.persister(T,C,this):T(C)},s=(()=>{const T={fetchOptions:r,options:this.options,queryKey:this.queryKey,client:Tt(this,n0),state:this.state,fetchFn:a};return i(T),T})();(m=this.options.behavior)==null||m.onFetch(s,this),xn(this,r0,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((x=s.fetchOptions)==null?void 0:x.meta))&&Fi(this,Rh,tm).call(this,{type:"fetch",meta:(_=s.fetchOptions)==null?void 0:_.meta});const f=T=>{var E,C,N,R;mB(T)&&T.silent||Fi(this,Rh,tm).call(this,{type:"error",error:T}),mB(T)||((C=(E=Tt(this,Ld).config).onError)==null||C.call(E,T,this),(R=(N=Tt(this,Ld).config).onSettled)==null||R.call(N,this.state.data,T,this)),this.scheduleGc()};return xn(this,uc,Mpe({initialPromise:r==null?void 0:r.initialPromise,fn:s.fetchFn,abort:n.abort.bind(n),onSuccess:T=>{var E,C,N,R;if(T===void 0){f(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(T)}catch(D){f(D);return}(C=(E=Tt(this,Ld).config).onSuccess)==null||C.call(E,T,this),(R=(N=Tt(this,Ld).config).onSettled)==null||R.call(N,T,this.state.error,this),this.scheduleGc()},onError:f,onFail:(T,E)=>{Fi(this,Rh,tm).call(this,{type:"failed",failureCount:T,error:E})},onPause:()=>{Fi(this,Rh,tm).call(this,{type:"pause"})},onContinue:()=>{Fi(this,Rh,tm).call(this,{type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0})),Tt(this,uc).start()}},Kw=new WeakMap,r0=new WeakMap,Ld=new WeakMap,n0=new WeakMap,uc=new WeakMap,fC=new WeakMap,i0=new WeakMap,Rh=new WeakSet,tm=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,...Bpe(n.data,this.options),fetchMeta:e.meta??null};case"success":return xn(this,r0,void 0),{...n,data:e.data,dataUpdateCount:n.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const i=e.error;return mB(i)&&i.revert&&Tt(this,r0)?{...Tt(this,r0),fetchStatus:"idle"}:{...n,error:i,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error"};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=r(this.state),al.batch(()=>{this.observers.forEach(n=>{n.onQueryUpdate()}),Tt(this,Ld).notify({query:this,type:"updated",action:e})})},Bce);function Bpe(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Dpe(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}function VFe(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 Lf,zce,qFe=(zce=class extends gS{constructor(e={}){super();Zn(this,Lf);this.config=e,xn(this,Lf,new Map)}build(e,r,n){const i=r.queryKey,a=r.queryHash??$G(i,r);let c=this.get(a);return c||(c=new UFe({client:e,queryKey:i,queryHash:a,options:e.defaultQueryOptions(r),state:n,defaultOptions:e.getQueryDefaults(i)}),this.add(c)),c}add(e){Tt(this,Lf).has(e.queryHash)||(Tt(this,Lf).set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const r=Tt(this,Lf).get(e.queryHash);r&&(e.destroy(),r===e&&Tt(this,Lf).delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){al.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return Tt(this,Lf).get(e)}getAll(){return[...Tt(this,Lf).values()]}find(e){const r={exact:!0,...e};return this.getAll().find(n=>JJ(r,n))}findAll(e={}){const r=this.getAll();return Object.keys(e).length>0?r.filter(n=>JJ(e,n)):r}notify(e){al.batch(()=>{this.listeners.forEach(r=>{r(e)})})}onFocus(){al.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){al.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Lf=new WeakMap,zce),Df,Mc,s0,Of,Vg,$ce,GFe=($ce=class extends Fpe{constructor(e){super();Zn(this,Of);Zn(this,Df);Zn(this,Mc);Zn(this,s0);this.mutationId=e.mutationId,xn(this,Mc,e.mutationCache),xn(this,Df,[]),this.state=e.state||zpe(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){Tt(this,Df).includes(e)||(Tt(this,Df).push(e),this.clearGcTimeout(),Tt(this,Mc).notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){xn(this,Df,Tt(this,Df).filter(r=>r!==e)),this.scheduleGc(),Tt(this,Mc).notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){Tt(this,Df).length||(this.state.status==="pending"?this.scheduleGc():Tt(this,Mc).remove(this))}continue(){var e;return((e=Tt(this,s0))==null?void 0:e.continue())??this.execute(this.state.variables)}async execute(e){var a,c,s,f,m,x,_,T,E,C,N,R,D,M,B,V,G,W,X,Q;const r=()=>{Fi(this,Of,Vg).call(this,{type:"continue"})};xn(this,s0,Mpe({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(re,se)=>{Fi(this,Of,Vg).call(this,{type:"failed",failureCount:re,error:se})},onPause:()=>{Fi(this,Of,Vg).call(this,{type:"pause"})},onContinue:r,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Tt(this,Mc).canRun(this)}));const n=this.state.status==="pending",i=!Tt(this,s0).canStart();try{if(n)r();else{Fi(this,Of,Vg).call(this,{type:"pending",variables:e,isPaused:i}),await((c=(a=Tt(this,Mc).config).onMutate)==null?void 0:c.call(a,e,this));const se=await((f=(s=this.options).onMutate)==null?void 0:f.call(s,e));se!==this.state.context&&Fi(this,Of,Vg).call(this,{type:"pending",context:se,variables:e,isPaused:i})}const re=await Tt(this,s0).start();return await((x=(m=Tt(this,Mc).config).onSuccess)==null?void 0:x.call(m,re,e,this.state.context,this)),await((T=(_=this.options).onSuccess)==null?void 0:T.call(_,re,e,this.state.context)),await((C=(E=Tt(this,Mc).config).onSettled)==null?void 0:C.call(E,re,null,this.state.variables,this.state.context,this)),await((R=(N=this.options).onSettled)==null?void 0:R.call(N,re,null,e,this.state.context)),Fi(this,Of,Vg).call(this,{type:"success",data:re}),re}catch(re){try{throw await((M=(D=Tt(this,Mc).config).onError)==null?void 0:M.call(D,re,e,this.state.context,this)),await((V=(B=this.options).onError)==null?void 0:V.call(B,re,e,this.state.context)),await((W=(G=Tt(this,Mc).config).onSettled)==null?void 0:W.call(G,void 0,re,this.state.variables,this.state.context,this)),await((Q=(X=this.options).onSettled)==null?void 0:Q.call(X,void 0,re,e,this.state.context)),re}finally{Fi(this,Of,Vg).call(this,{type:"error",error:re})}}finally{Tt(this,Mc).runNext(this)}}},Df=new WeakMap,Mc=new WeakMap,s0=new WeakMap,Of=new WeakSet,Vg=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),al.batch(()=>{Tt(this,Df).forEach(n=>{n.onMutationUpdate(e)}),Tt(this,Mc).notify({mutation:this,type:"updated",action:e})})},$ce);function zpe(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var lm,Lh,pC,Uce,HFe=(Uce=class extends gS{constructor(e={}){super();Zn(this,lm);Zn(this,Lh);Zn(this,pC);this.config=e,xn(this,lm,new Set),xn(this,Lh,new Map),xn(this,pC,0)}build(e,r,n){const i=new GFe({mutationCache:this,mutationId:++DP(this,pC)._,options:e.defaultMutationOptions(r),state:n});return this.add(i),i}add(e){Tt(this,lm).add(e);const r=oN(e);if(typeof r=="string"){const n=Tt(this,Lh).get(r);n?n.push(e):Tt(this,Lh).set(r,[e])}this.notify({type:"added",mutation:e})}remove(e){if(Tt(this,lm).delete(e)){const r=oN(e);if(typeof r=="string"){const n=Tt(this,Lh).get(r);if(n)if(n.length>1){const i=n.indexOf(e);i!==-1&&n.splice(i,1)}else n[0]===e&&Tt(this,Lh).delete(r)}}this.notify({type:"removed",mutation:e})}canRun(e){const r=oN(e);if(typeof r=="string"){const n=Tt(this,Lh).get(r),i=n==null?void 0:n.find(a=>a.state.status==="pending");return!i||i===e}else return!0}runNext(e){var n;const r=oN(e);if(typeof r=="string"){const i=(n=Tt(this,Lh).get(r))==null?void 0:n.find(a=>a!==e&&a.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){al.batch(()=>{Tt(this,lm).forEach(e=>{this.notify({type:"removed",mutation:e})}),Tt(this,lm).clear(),Tt(this,Lh).clear()})}getAll(){return Array.from(Tt(this,lm))}find(e){const r={exact:!0,...e};return this.getAll().find(n=>eee(r,n))}findAll(e={}){return this.getAll().filter(r=>eee(e,r))}notify(e){al.batch(()=>{this.listeners.forEach(r=>{r(e)})})}resumePausedMutations(){const e=this.getAll().filter(r=>r.state.isPaused);return al.batch(()=>Promise.all(e.map(r=>r.continue().catch(zc))))}},lm=new WeakMap,Lh=new WeakMap,pC=new WeakMap,Uce);function oN(t){var e;return(e=t.options.scope)==null?void 0:e.id}function nee(t){return{onFetch:(e,r)=>{var x,_,T,E,C;const n=e.options,i=(T=(_=(x=e.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:T.direction,a=((E=e.state.data)==null?void 0:E.pages)||[],c=((C=e.state.data)==null?void 0:C.pageParams)||[];let s={pages:[],pageParams:[]},f=0;const m=async()=>{let N=!1;const R=B=>{Object.defineProperty(B,"signal",{enumerable:!0,get:()=>(e.signal.aborted?N=!0:e.signal.addEventListener("abort",()=>{N=!0}),e.signal)})},D=Rpe(e.options,e.fetchOptions),M=async(B,V,G)=>{if(N)return Promise.reject();if(V==null&&B.pages.length)return Promise.resolve(B);const X=(()=>{const ue={client:e.client,queryKey:e.queryKey,pageParam:V,direction:G?"backward":"forward",meta:e.options.meta};return R(ue),ue})(),Q=await D(X),{maxPages:re}=e.options,se=G?OFe:DFe;return{pages:se(B.pages,Q,re),pageParams:se(B.pageParams,V,re)}};if(i&&a.length){const B=i==="backward",V=B?$pe:UU,G={pages:a,pageParams:c},W=V(n,G);s=await M(G,W,B)}else{const B=t??a.length;do{const V=f===0?c[0]??n.initialPageParam:UU(n,s);if(f>0&&V==null)break;s=await M(s,V),f++}while(f{var N,R;return(R=(N=e.options).persister)==null?void 0:R.call(N,m,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r)}:e.fetchFn=m}}}function UU(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 $pe(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 Y$t(t,e){return e?UU(t,e)!=null:!1}function Z$t(t,e){return!e||!t.getPreviousPageParam?!1:$pe(t,e)!=null}var co,oy,ly,Yw,Zw,cy,Xw,Qw,Vce,WFe=(Vce=class{constructor(t={}){Zn(this,co);Zn(this,oy);Zn(this,ly);Zn(this,Yw);Zn(this,Zw);Zn(this,cy);Zn(this,Xw);Zn(this,Qw);xn(this,co,t.queryCache||new qFe),xn(this,oy,t.mutationCache||new HFe),xn(this,ly,t.defaultOptions||{}),xn(this,Yw,new Map),xn(this,Zw,new Map),xn(this,cy,0)}mount(){DP(this,cy)._++,Tt(this,cy)===1&&(xn(this,Xw,VG.subscribe(async t=>{t&&(await this.resumePausedMutations(),Tt(this,co).onFocus())})),xn(this,Qw,zL.subscribe(async t=>{t&&(await this.resumePausedMutations(),Tt(this,co).onOnline())})))}unmount(){var t,e;DP(this,cy)._--,Tt(this,cy)===0&&((t=Tt(this,Xw))==null||t.call(this),xn(this,Xw,void 0),(e=Tt(this,Qw))==null||e.call(this),xn(this,Qw,void 0))}isFetching(t){return Tt(this,co).findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return Tt(this,oy).findAll({...t,status:"pending"}).length}getQueryData(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=Tt(this,co).get(e.queryHash))==null?void 0:r.state.data}ensureQueryData(t){const e=this.defaultQueryOptions(t),r=Tt(this,co).build(this,e),n=r.state.data;return n===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(jy(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(n))}getQueriesData(t){return Tt(this,co).findAll(t).map(({queryKey:e,state:r})=>{const n=r.data;return[e,n]})}setQueryData(t,e,r){const n=this.defaultQueryOptions({queryKey:t}),i=Tt(this,co).get(n.queryHash),a=i==null?void 0:i.state.data,c=RFe(e,a);if(c!==void 0)return Tt(this,co).build(this,n).setData(c,{...r,manual:!0})}setQueriesData(t,e,r){return al.batch(()=>Tt(this,co).findAll(t).map(({queryKey:n})=>[n,this.setQueryData(n,e,r)]))}getQueryState(t){var r;const e=this.defaultQueryOptions({queryKey:t});return(r=Tt(this,co).get(e.queryHash))==null?void 0:r.state}removeQueries(t){const e=Tt(this,co);al.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){const r=Tt(this,co);return al.batch(()=>(r.findAll(t).forEach(n=>{n.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){const r={revert:!0,...e},n=al.batch(()=>Tt(this,co).findAll(t).map(i=>i.cancel(r)));return Promise.all(n).then(zc).catch(zc)}invalidateQueries(t,e={}){return al.batch(()=>(Tt(this,co).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=al.batch(()=>Tt(this,co).findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,r);return r.throwOnError||(a=a.catch(zc)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(n).then(zc)}fetchQuery(t){const e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);const r=Tt(this,co).build(this,e);return r.isStaleByTime(jy(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(zc).catch(zc)}fetchInfiniteQuery(t){return t.behavior=nee(t.pages),this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(zc).catch(zc)}ensureInfiniteQueryData(t){return t.behavior=nee(t.pages),this.ensureQueryData(t)}resumePausedMutations(){return zL.isOnline()?Tt(this,oy).resumePausedMutations():Promise.resolve()}getQueryCache(){return Tt(this,co)}getMutationCache(){return Tt(this,oy)}getDefaultOptions(){return Tt(this,ly)}setDefaultOptions(t){xn(this,ly,t)}setQueryDefaults(t,e){Tt(this,Yw).set(E0(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){const e=[...Tt(this,Yw).values()],r={};return e.forEach(n=>{nk(t,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(t,e){Tt(this,Zw).set(E0(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){const e=[...Tt(this,Zw).values()],r={};return e.forEach(n=>{nk(t,n.mutationKey)&&Object.assign(r,n.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;const e={...Tt(this,ly).queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=$G(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===UG&&(e.enabled=!1),e}defaultMutationOptions(t){return t!=null&&t._defaulted?t:{...Tt(this,ly).mutations,...(t==null?void 0:t.mutationKey)&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){Tt(this,co).clear(),Tt(this,oy).clear()}},co=new WeakMap,oy=new WeakMap,ly=new WeakMap,Yw=new WeakMap,Zw=new WeakMap,cy=new WeakMap,Xw=new WeakMap,Qw=new WeakMap,Vce),pu,ns,mC,Fc,a0,Jw,uy,dy,gC,e1,t1,o0,l0,hy,r1,Ls,G2,VU,qU,GU,HU,WU,KU,YU,Upe,qce,KFe=(qce=class extends gS{constructor(e,r){super();Zn(this,Ls);Zn(this,pu);Zn(this,ns);Zn(this,mC);Zn(this,Fc);Zn(this,a0);Zn(this,Jw);Zn(this,uy);Zn(this,dy);Zn(this,gC);Zn(this,e1);Zn(this,t1);Zn(this,o0);Zn(this,l0);Zn(this,hy);Zn(this,r1,new Set);this.options=r,xn(this,pu,e),xn(this,dy,null),xn(this,uy,$U()),this.options.experimental_prefetchInRender||Tt(this,uy).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(r)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Tt(this,ns).addObserver(this),iee(Tt(this,ns),this.options)?Fi(this,Ls,G2).call(this):this.updateResult(),Fi(this,Ls,HU).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ZU(Tt(this,ns),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ZU(Tt(this,ns),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Fi(this,Ls,WU).call(this),Fi(this,Ls,KU).call(this),Tt(this,ns).removeObserver(this)}setOptions(e){const r=this.options,n=Tt(this,ns);if(this.options=Tt(this,pu).defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Dd(this.options.enabled,Tt(this,ns))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Fi(this,Ls,YU).call(this),Tt(this,ns).setOptions(this.options),r._defaulted&&!BL(this.options,r)&&Tt(this,pu).getQueryCache().notify({type:"observerOptionsUpdated",query:Tt(this,ns),observer:this});const i=this.hasListeners();i&&see(Tt(this,ns),n,this.options,r)&&Fi(this,Ls,G2).call(this),this.updateResult(),i&&(Tt(this,ns)!==n||Dd(this.options.enabled,Tt(this,ns))!==Dd(r.enabled,Tt(this,ns))||jy(this.options.staleTime,Tt(this,ns))!==jy(r.staleTime,Tt(this,ns)))&&Fi(this,Ls,VU).call(this);const a=Fi(this,Ls,qU).call(this);i&&(Tt(this,ns)!==n||Dd(this.options.enabled,Tt(this,ns))!==Dd(r.enabled,Tt(this,ns))||a!==Tt(this,hy))&&Fi(this,Ls,GU).call(this,a)}getOptimisticResult(e){const r=Tt(this,pu).getQueryCache().build(Tt(this,pu),e),n=this.createResult(r,e);return ZFe(this,n)&&(xn(this,Fc,n),xn(this,Jw,this.options),xn(this,a0,Tt(this,ns).state)),n}getCurrentResult(){return Tt(this,Fc)}trackResult(e,r){return new Proxy(e,{get:(n,i)=>(this.trackProp(i),r==null||r(i),Reflect.get(n,i))})}trackProp(e){Tt(this,r1).add(e)}getCurrentQuery(){return Tt(this,ns)}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const r=Tt(this,pu).defaultQueryOptions(e),n=Tt(this,pu).getQueryCache().build(Tt(this,pu),r);return n.fetch().then(()=>this.createResult(n,r))}fetch(e){return Fi(this,Ls,G2).call(this,{...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),Tt(this,Fc)))}createResult(e,r){var re;const n=Tt(this,ns),i=this.options,a=Tt(this,Fc),c=Tt(this,a0),s=Tt(this,Jw),m=e!==n?e.state:Tt(this,mC),{state:x}=e;let _={...x},T=!1,E;if(r._optimisticResults){const se=this.hasListeners(),ue=!se&&iee(e,r),_e=se&&see(e,n,r,i);(ue||_e)&&(_={..._,...Bpe(x.data,e.options)}),r._optimisticResults==="isRestoring"&&(_.fetchStatus="idle")}let{error:C,errorUpdatedAt:N,status:R}=_;E=_.data;let D=!1;if(r.placeholderData!==void 0&&E===void 0&&R==="pending"){let se;a!=null&&a.isPlaceholderData&&r.placeholderData===(s==null?void 0:s.placeholderData)?(se=a.data,D=!0):se=typeof r.placeholderData=="function"?r.placeholderData((re=Tt(this,t1))==null?void 0:re.state.data,Tt(this,t1)):r.placeholderData,se!==void 0&&(R="success",E=zU(a==null?void 0:a.data,se,r),T=!0)}if(r.select&&E!==void 0&&!D)if(a&&E===(c==null?void 0:c.data)&&r.select===Tt(this,gC))E=Tt(this,e1);else try{xn(this,gC,r.select),E=r.select(E),E=zU(a==null?void 0:a.data,E,r),xn(this,e1,E),xn(this,dy,null)}catch(se){xn(this,dy,se)}Tt(this,dy)&&(C=Tt(this,dy),E=Tt(this,e1),N=Date.now(),R="error");const M=_.fetchStatus==="fetching",B=R==="pending",V=R==="error",G=B&&M,W=E!==void 0,Q={status:R,fetchStatus:_.fetchStatus,isPending:B,isSuccess:R==="success",isError:V,isInitialLoading:G,isLoading:G,data:E,dataUpdatedAt:_.dataUpdatedAt,error:C,errorUpdatedAt:N,failureCount:_.fetchFailureCount,failureReason:_.fetchFailureReason,errorUpdateCount:_.errorUpdateCount,isFetched:_.dataUpdateCount>0||_.errorUpdateCount>0,isFetchedAfterMount:_.dataUpdateCount>m.dataUpdateCount||_.errorUpdateCount>m.errorUpdateCount,isFetching:M,isRefetching:M&&!B,isLoadingError:V&&!W,isPaused:_.fetchStatus==="paused",isPlaceholderData:T,isRefetchError:V&&W,isStale:qG(e,r),refetch:this.refetch,promise:Tt(this,uy),isEnabled:Dd(r.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const se=Se=>{Q.status==="error"?Se.reject(Q.error):Q.data!==void 0&&Se.resolve(Q.data)},ue=()=>{const Se=xn(this,uy,Q.promise=$U());se(Se)},_e=Tt(this,uy);switch(_e.status){case"pending":e.queryHash===n.queryHash&&se(_e);break;case"fulfilled":(Q.status==="error"||Q.data!==_e.value)&&ue();break;case"rejected":(Q.status!=="error"||Q.error!==_e.reason)&&ue();break}}return Q}updateResult(){const e=Tt(this,Fc),r=this.createResult(Tt(this,ns),this.options);if(xn(this,a0,Tt(this,ns).state),xn(this,Jw,this.options),Tt(this,a0).data!==void 0&&xn(this,t1,Tt(this,ns)),BL(r,e))return;xn(this,Fc,r);const n=()=>{if(!e)return!0;const{notifyOnChangeProps:i}=this.options,a=typeof i=="function"?i():i;if(a==="all"||!a&&!Tt(this,r1).size)return!0;const c=new Set(a??Tt(this,r1));return this.options.throwOnError&&c.add("error"),Object.keys(Tt(this,Fc)).some(s=>{const f=s;return Tt(this,Fc)[f]!==e[f]&&c.has(f)})};Fi(this,Ls,Upe).call(this,{listeners:n()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Fi(this,Ls,HU).call(this)}},pu=new WeakMap,ns=new WeakMap,mC=new WeakMap,Fc=new WeakMap,a0=new WeakMap,Jw=new WeakMap,uy=new WeakMap,dy=new WeakMap,gC=new WeakMap,e1=new WeakMap,t1=new WeakMap,o0=new WeakMap,l0=new WeakMap,hy=new WeakMap,r1=new WeakMap,Ls=new WeakSet,G2=function(e){Fi(this,Ls,YU).call(this);let r=Tt(this,ns).fetch(this.options,e);return e!=null&&e.throwOnError||(r=r.catch(zc)),r},VU=function(){Fi(this,Ls,WU).call(this);const e=jy(this.options.staleTime,Tt(this,ns));if(T0||Tt(this,Fc).isStale||!FU(e))return;const n=Ppe(Tt(this,Fc).dataUpdatedAt,e)+1;xn(this,o0,setTimeout(()=>{Tt(this,Fc).isStale||this.updateResult()},n))},qU=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Tt(this,ns)):this.options.refetchInterval)??!1},GU=function(e){Fi(this,Ls,KU).call(this),xn(this,hy,e),!(T0||Dd(this.options.enabled,Tt(this,ns))===!1||!FU(Tt(this,hy))||Tt(this,hy)===0)&&xn(this,l0,setInterval(()=>{(this.options.refetchIntervalInBackground||VG.isFocused())&&Fi(this,Ls,G2).call(this)},Tt(this,hy)))},HU=function(){Fi(this,Ls,VU).call(this),Fi(this,Ls,GU).call(this,Fi(this,Ls,qU).call(this))},WU=function(){Tt(this,o0)&&(clearTimeout(Tt(this,o0)),xn(this,o0,void 0))},KU=function(){Tt(this,l0)&&(clearInterval(Tt(this,l0)),xn(this,l0,void 0))},YU=function(){const e=Tt(this,pu).getQueryCache().build(Tt(this,pu),this.options);if(e===Tt(this,ns))return;const r=Tt(this,ns);xn(this,ns,e),xn(this,mC,e.state),this.hasListeners()&&(r==null||r.removeObserver(this),e.addObserver(this))},Upe=function(e){al.batch(()=>{e.listeners&&this.listeners.forEach(r=>{r(Tt(this,Fc))}),Tt(this,pu).getQueryCache().notify({query:Tt(this,ns),type:"observerResultsUpdated"})})},qce);function YFe(t,e){return Dd(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&e.retryOnMount===!1)}function iee(t,e){return YFe(t,e)||t.state.data!==void 0&&ZU(t,e,e.refetchOnMount)}function ZU(t,e,r){if(Dd(e.enabled,t)!==!1&&jy(e.staleTime,t)!=="static"){const n=typeof r=="function"?r(t):r;return n==="always"||n!==!1&&qG(t,e)}return!1}function see(t,e,r,n){return(t!==e||Dd(n.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&qG(t,r)}function qG(t,e){return Dd(e.enabled,t)!==!1&&t.isStaleByTime(jy(e.staleTime,t))}function ZFe(t,e){return!BL(t.getCurrentResult(),e)}var fy,py,mu,cm,Tm,kR,XU,Gce,XFe=(Gce=class extends gS{constructor(r,n){super();Zn(this,Tm);Zn(this,fy);Zn(this,py);Zn(this,mu);Zn(this,cm);xn(this,fy,r),this.setOptions(n),this.bindMethods(),Fi(this,Tm,kR).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=Tt(this,fy).defaultMutationOptions(r),BL(this.options,n)||Tt(this,fy).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Tt(this,mu),observer:this}),n!=null&&n.mutationKey&&this.options.mutationKey&&E0(n.mutationKey)!==E0(this.options.mutationKey)?this.reset():((i=Tt(this,mu))==null?void 0:i.state.status)==="pending"&&Tt(this,mu).setOptions(this.options)}onUnsubscribe(){var r;this.hasListeners()||(r=Tt(this,mu))==null||r.removeObserver(this)}onMutationUpdate(r){Fi(this,Tm,kR).call(this),Fi(this,Tm,XU).call(this,r)}getCurrentResult(){return Tt(this,py)}reset(){var r;(r=Tt(this,mu))==null||r.removeObserver(this),xn(this,mu,void 0),Fi(this,Tm,kR).call(this),Fi(this,Tm,XU).call(this)}mutate(r,n){var i;return xn(this,cm,n),(i=Tt(this,mu))==null||i.removeObserver(this),xn(this,mu,Tt(this,fy).getMutationCache().build(Tt(this,fy),this.options)),Tt(this,mu).addObserver(this),Tt(this,mu).execute(r)}},fy=new WeakMap,py=new WeakMap,mu=new WeakMap,cm=new WeakMap,Tm=new WeakSet,kR=function(){var n;const r=((n=Tt(this,mu))==null?void 0:n.state)??zpe();xn(this,py,{...r,isPending:r.status==="pending",isSuccess:r.status==="success",isError:r.status==="error",isIdle:r.status==="idle",mutate:this.mutate,reset:this.reset})},XU=function(r){al.batch(()=>{var n,i,a,c,s,f,m,x;if(Tt(this,cm)&&this.hasListeners()){const _=Tt(this,py).variables,T=Tt(this,py).context;(r==null?void 0:r.type)==="success"?((i=(n=Tt(this,cm)).onSuccess)==null||i.call(n,r.data,_,T),(c=(a=Tt(this,cm)).onSettled)==null||c.call(a,r.data,null,_,T)):(r==null?void 0:r.type)==="error"&&((f=(s=Tt(this,cm)).onError)==null||f.call(s,r.error,_,T),(x=(m=Tt(this,cm)).onSettled)==null||x.call(m,void 0,r.error,_,T))}this.listeners.forEach(_=>{_(Tt(this,py))})})},Gce),Vpe=P.createContext(void 0),Nr=t=>{const e=P.useContext(Vpe);if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},QFe=({client:t,children:e})=>(P.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),o.jsx(Vpe.Provider,{value:t,children:e})),qpe=P.createContext(!1),JFe=()=>P.useContext(qpe);qpe.Provider;function e3e(){let t=!1;return{clearReset:()=>{t=!1},reset:()=>{t=!0},isReset:()=>t}}var t3e=P.createContext(e3e()),r3e=()=>P.useContext(t3e),n3e=(t,e)=>{(t.suspense||t.throwOnError||t.experimental_prefetchInRender)&&(e.isReset()||(t.retryOnMount=!1))},i3e=t=>{P.useEffect(()=>{t.clearReset()},[t])},s3e=({result:t,errorResetBoundary:e,throwOnError:r,query:n,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&n&&(i&&t.data===void 0||Lpe(r,[t.error,n])),a3e=t=>{if(t.suspense){const e=n=>n==="static"?n:Math.max(n??1e3,1e3),r=t.staleTime;t.staleTime=typeof r=="function"?(...n)=>e(r(...n)):e(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},o3e=(t,e)=>t.isLoading&&t.isFetching&&!e,l3e=(t,e)=>(t==null?void 0:t.suspense)&&e.isPending,aee=(t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()});function c3e(t,e,r){var _,T,E,C,N;const n=JFe(),i=r3e(),a=Nr(),c=a.defaultQueryOptions(t);(T=(_=a.getDefaultOptions().queries)==null?void 0:_._experimental_beforeQuery)==null||T.call(_,c),c._optimisticResults=n?"isRestoring":"optimistic",a3e(c),n3e(c,i),i3e(i);const s=!a.getQueryCache().get(c.queryHash),[f]=P.useState(()=>new e(a,c)),m=f.getOptimisticResult(c),x=!n&&t.subscribed!==!1;if(P.useSyncExternalStore(P.useCallback(R=>{const D=x?f.subscribe(al.batchCalls(R)):zc;return f.updateResult(),D},[f,x]),()=>f.getCurrentResult(),()=>f.getCurrentResult()),P.useEffect(()=>{f.setOptions(c)},[c,f]),l3e(c,m))throw aee(c,f,i);if(s3e({result:m,errorResetBoundary:i,throwOnError:c.throwOnError,query:a.getQueryCache().get(c.queryHash),suspense:c.suspense}))throw m.error;if((C=(E=a.getDefaultOptions().queries)==null?void 0:E._experimental_afterQuery)==null||C.call(E,c,m),c.experimental_prefetchInRender&&!T0&&o3e(m,n)){const R=s?aee(c,f,i):(N=a.getQueryCache().get(c.queryHash))==null?void 0:N.promise;R==null||R.catch(zc).finally(()=>{f.updateResult()})}return c.notifyOnChangeProps?m:f.trackResult(m)}function wr(t,e){return c3e(t,KFe)}function Cr(t,e){const r=Nr(),[n]=P.useState(()=>new XFe(r,t));P.useEffect(()=>{n.setOptions(t)},[n,t]);const i=P.useSyncExternalStore(P.useCallback(c=>n.subscribe(al.batchCalls(c)),[n]),()=>n.getCurrentResult(),()=>n.getCurrentResult()),a=P.useCallback((c,s)=>{n.mutate(c,s).catch(zc)},[n]);if(i.error&&Lpe(n.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}/** * @remix-run/router v1.23.0 * * 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 ik(){return ik=Object.assign?Object.assign.bind():function(t){for(var e=1;e"u")throw new Error(e)}function Gpe(t,e){if(!t){typeof console<"u"&&console.warn(e);try{throw new Error(e)}catch{}}}function d3e(){return Math.random().toString(36).substr(2,8)}function lee(t,e){return{usr:t.state,key:t.key,idx:e}}function QU(t,e,r,n){return r===void 0&&(r=null),ik({pathname:typeof t=="string"?t:t.pathname,search:"",hash:""},typeof e=="string"?yS(e):e,{state:r,key:e&&e.key||n||d3e()})}function $L(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 yS(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 h3e(t,e,r,n){n===void 0&&(n={});let{window:i=document.defaultView,v5Compat:a=!1}=n,c=i.history,s=yy.Pop,f=null,m=x();m==null&&(m=0,c.replaceState(ik({},c.state,{idx:m}),""));function x(){return(c.state||{idx:null}).idx}function _(){s=yy.Pop;let R=x(),D=R==null?null:R-m;m=R,f&&f({action:s,location:N.location,delta:D})}function T(R,D){s=yy.Push;let M=QU(N.location,R,D);m=x()+1;let B=lee(M,m),V=N.createHref(M);try{c.pushState(B,"",V)}catch(G){if(G instanceof DOMException&&G.name==="DataCloneError")throw G;i.location.assign(V)}a&&f&&f({action:s,location:N.location,delta:1})}function E(R,D){s=yy.Replace;let M=QU(N.location,R,D);m=x();let B=lee(M,m),V=N.createHref(M);c.replaceState(B,"",V),a&&f&&f({action:s,location:N.location,delta:0})}function C(R){let D=i.location.origin!=="null"?i.location.origin:i.location.href,M=typeof R=="string"?R:$L(R);return M=M.replace(/ $/,"%20"),eo(D,"No window.location.(origin|href) available to create URL for href: "+M),new URL(M,D)}let N={get action(){return s},get location(){return t(i,c)},listen(R){if(f)throw new Error("A history only accepts one active listener");return i.addEventListener(oee,_),f=R,()=>{i.removeEventListener(oee,_),f=null}},createHref(R){return e(i,R)},createURL:C,encodeLocation(R){let D=C(R);return{pathname:D.pathname,search:D.search,hash:D.hash}},push:T,replace:E,go(R){return c.go(R)}};return N}var cee;(function(t){t.data="data",t.deferred="deferred",t.redirect="redirect",t.error="error"})(cee||(cee={}));function f3e(t,e,r){return r===void 0&&(r="/"),p3e(t,e,r,!1)}function p3e(t,e,r,n){let i=typeof e=="string"?yS(e):e,a=g1(i.pathname||"/",r);if(a==null)return null;let c=Hpe(t);m3e(c);let s=null;for(let f=0;s==null&&f{let f={relativePath:s===void 0?a.path||"":s,caseSensitive:a.caseSensitive===!0,childrenIndex:c,route:a};f.relativePath.startsWith("/")&&(eo(f.relativePath.startsWith(n),'Absolute route path "'+f.relativePath+'" nested under path '+('"'+n+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),f.relativePath=f.relativePath.slice(n.length));let m=Iy([n,f.relativePath]),x=r.concat(f);a.children&&a.children.length>0&&(eo(a.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+m+'".')),Hpe(a.children,e,x,m)),!(a.path==null&&!a.index)&&e.push({path:m,score:w3e(m,a.index),routesMeta:x})};return t.forEach((a,c)=>{var s;if(a.path===""||!((s=a.path)!=null&&s.includes("?")))i(a,c);else for(let f of Wpe(a.path))i(a,c,f)}),e}function Wpe(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=Wpe(n.join("/")),s=[];return s.push(...c.map(f=>f===""?a:[a,f].join("/"))),i&&s.push(...c),s.map(f=>t.startsWith("/")&&f===""?"/":f)}function m3e(t){t.sort((e,r)=>e.score!==r.score?r.score-e.score:S3e(e.routesMeta.map(n=>n.childrenIndex),r.routesMeta.map(n=>n.childrenIndex)))}const g3e=/^:[\w-]+$/,y3e=3,x3e=2,_3e=1,v3e=10,b3e=-2,uee=t=>t==="*";function w3e(t,e){let r=t.split("/"),n=r.length;return r.some(uee)&&(n+=b3e),e&&(n+=x3e),r.filter(i=>!uee(i)).reduce((i,a)=>i+(g3e.test(a)?y3e:a===""?_3e:v3e),n)}function S3e(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 T3e(t,e,r){let{routesMeta:n}=t,i={},a="/",c=[];for(let s=0;s{let{paramName:T,isOptional:E}=x;if(T==="*"){let N=s[_]||"";c=a.slice(0,a.length-N.length).replace(/(.)\/+$/,"$1")}const C=s[_];return E&&!C?m[T]=void 0:m[T]=(C||"").replace(/%2F/g,"/"),m},{}),pathname:a,pathnameBase:c,pattern:t}}function E3e(t,e,r){e===void 0&&(e=!1),r===void 0&&(r=!0),Gpe(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,s,f)=>(n.push({paramName:s,isOptional:f!=null}),f?"/?([^\\/]+)?":"/([^\\/]+)"));return t.endsWith("*")?(n.push({paramName:"*"}),i+=t==="*"||t==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):r?i+="\\/*$":t!==""&&t!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,e?void 0:"i"),n]}function A3e(t){try{return t.split("/").map(e=>decodeURIComponent(e).replace(/\//g,"%2F")).join("/")}catch(e){return Gpe(!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 g1(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 k3e(t,e){e===void 0&&(e="/");let{pathname:r,search:n="",hash:i=""}=typeof t=="string"?yS(t):t;return{pathname:r?r.startsWith("/")?r:C3e(r,e):e,search:P3e(n),hash:N3e(i)}}function C3e(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 gB(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 j3e(t){return t.filter((e,r)=>r===0||e.route.path&&e.route.path.length>0)}function GG(t,e){let r=j3e(t);return e?r.map((n,i)=>i===r.length-1?n.pathname:n.pathnameBase):r.map(n=>n.pathnameBase)}function HG(t,e,r,n){n===void 0&&(n=!1);let i;typeof t=="string"?i=yS(t):(i=ik({},t),eo(!i.pathname||!i.pathname.includes("?"),gB("?","pathname","search",i)),eo(!i.pathname||!i.pathname.includes("#"),gB("#","pathname","hash",i)),eo(!i.search||!i.search.includes("#"),gB("#","search","hash",i)));let a=t===""||i.pathname==="",c=a?"/":i.pathname,s;if(c==null)s=r;else{let _=e.length-1;if(!n&&c.startsWith("..")){let T=c.split("/");for(;T[0]==="..";)T.shift(),_-=1;i.pathname=T.join("/")}s=_>=0?e[_]:"/"}let f=k3e(i,s),m=c&&c!=="/"&&c.endsWith("/"),x=(a||c===".")&&r.endsWith("/");return!f.pathname.endsWith("/")&&(m||x)&&(f.pathname+="/"),f}const Iy=t=>t.join("/").replace(/\/\/+/g,"/"),I3e=t=>t.replace(/\/+$/,"").replace(/^\/*/,"/"),P3e=t=>!t||t==="?"?"":t.startsWith("?")?t:"?"+t,N3e=t=>!t||t==="#"?"":t.startsWith("#")?t:"#"+t;function R3e(t){return t!=null&&typeof t.status=="number"&&typeof t.statusText=="string"&&typeof t.internal=="boolean"&&"data"in t}const Kpe=["post","put","patch","delete"];new Set(Kpe);const L3e=["get",...Kpe];new Set(L3e);/** * React Router v6.30.1 * * 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 sk(){return sk=Object.assign?Object.assign.bind():function(t){for(var e=1;e{s.current=!0}),P.useCallback(function(m,x){if(x===void 0&&(x={}),!s.current)return;if(typeof m=="number"){n.go(m);return}let _=HG(m,JSON.parse(c),a,x.relative==="path");t==null&&e!=="/"&&(_.pathname=_.pathname==="/"?e:Iy([e,_.pathname])),(x.replace?n.replace:n.push)(_,x.state,x)},[e,n,c,a,t])}const M3e=P.createContext(null);function F3e(t){let e=P.useContext(dp).outlet;return e&&P.createElement(M3e.Provider,{value:t},e)}function hp(){let{matches:t}=P.useContext(dp),e=t[t.length-1];return e?e.params:{}}function yM(t,e){let{relative:r}=e===void 0?{}:e,{future:n}=P.useContext(Vm),{matches:i}=P.useContext(dp),{pathname:a}=Wi(),c=JSON.stringify(GG(i,n.v7_relativeSplatPath));return P.useMemo(()=>HG(t,JSON.parse(c),a,r==="path"),[t,c,a,r])}function B3e(t,e){return z3e(t,e)}function z3e(t,e,r,n){xS()||eo(!1);let{navigator:i}=P.useContext(Vm),{matches:a}=P.useContext(dp),c=a[a.length-1],s=c?c.params:{};c&&c.pathname;let f=c?c.pathnameBase:"/";c&&c.route;let m=Wi(),x;if(e){var _;let R=typeof e=="string"?yS(e):e;f==="/"||(_=R.pathname)!=null&&_.startsWith(f)||eo(!1),x=R}else x=m;let T=x.pathname||"/",E=T;if(f!=="/"){let R=f.replace(/^\//,"").split("/");E="/"+T.replace(/^\//,"").split("/").slice(R.length).join("/")}let C=f3e(t,{pathname:E}),N=G3e(C&&C.map(R=>Object.assign({},R,{params:Object.assign({},s,R.params),pathname:Iy([f,i.encodeLocation?i.encodeLocation(R.pathname).pathname:R.pathname]),pathnameBase:R.pathnameBase==="/"?f:Iy([f,i.encodeLocation?i.encodeLocation(R.pathnameBase).pathname:R.pathnameBase])})),a,r,n);return e&&N?P.createElement(gM.Provider,{value:{location:sk({pathname:"/",search:"",hash:"",state:null,key:"default"},x),navigationType:yy.Pop}},N):N}function $3e(){let t=Y3e(),e=R3e(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 P.createElement(P.Fragment,null,P.createElement("h2",null,"Unexpected Application Error!"),P.createElement("h3",{style:{fontStyle:"italic"}},e),r?P.createElement("pre",{style:i},r):null,null)}const U3e=P.createElement($3e,null);class V3e extends P.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?P.createElement(dp.Provider,{value:this.props.routeContext},P.createElement(Zpe.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function q3e(t){let{routeContext:e,match:r,children:n}=t,i=P.useContext(mM);return i&&i.static&&i.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(i.staticContext._deepestRenderedBoundaryId=r.route.id),P.createElement(dp.Provider,{value:e},n)}function G3e(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,s=(i=r)==null?void 0:i.errors;if(s!=null){let x=c.findIndex(_=>_.route.id&&(s==null?void 0:s[_.route.id])!==void 0);x>=0||eo(!1),c=c.slice(0,Math.min(c.length,x+1))}let f=!1,m=-1;if(r&&n&&n.v7_partialHydration)for(let x=0;x=0?c=c.slice(0,m+1):c=[c[0]];break}}}return c.reduceRight((x,_,T)=>{let E,C=!1,N=null,R=null;r&&(E=s&&_.route.id?s[_.route.id]:void 0,N=_.route.errorElement||U3e,f&&(m<0&&T===0?(C=!0,R=null):m===T&&(C=!0,R=_.route.hydrateFallbackElement||null)));let D=e.concat(c.slice(0,T+1)),M=()=>{let B;return E?B=N:C?B=R:_.route.Component?B=P.createElement(_.route.Component,null):_.route.element?B=_.route.element:B=x,P.createElement(q3e,{match:_,routeContext:{outlet:x,matches:D,isDataRoute:r!=null},children:B})};return r&&(_.route.ErrorBoundary||_.route.errorElement||T===0)?P.createElement(V3e,{location:r.location,revalidation:r.revalidation,component:N,error:E,children:M(),routeContext:{outlet:null,matches:D,isDataRoute:!0}}):M()},null)}var Qpe=function(t){return t.UseBlocker="useBlocker",t.UseRevalidator="useRevalidator",t.UseNavigateStable="useNavigate",t}(Qpe||{}),VL=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}(VL||{});function H3e(t){let e=P.useContext(mM);return e||eo(!1),e}function W3e(t){let e=P.useContext(Ype);return e||eo(!1),e}function K3e(t){let e=P.useContext(dp);return e||eo(!1),e}function Jpe(t){let e=K3e(),r=e.matches[e.matches.length-1];return r.route.id||eo(!1),r.route.id}function Y3e(){var t;let e=P.useContext(Zpe),r=W3e(VL.UseRouteError),n=Jpe(VL.UseRouteError);return e!==void 0?e:(t=r.errors)==null?void 0:t[n]}function Z3e(){let{router:t}=H3e(Qpe.UseNavigateStable),e=Jpe(VL.UseNavigateStable),r=P.useRef(!1);return Xpe(()=>{r.current=!0}),P.useCallback(function(i,a){a===void 0&&(a={}),r.current&&(typeof i=="number"?t.navigate(i):t.navigate(i,sk({fromRouteId:e},a)))},[t,e])}function X3e(t,e){t==null||t.v7_startTransition,t==null||t.v7_relativeSplatPath}function ki(t){let{to:e,replace:r,state:n,relative:i}=t;xS()||eo(!1);let{future:a,static:c}=P.useContext(Vm),{matches:s}=P.useContext(dp),{pathname:f}=Wi(),m=ma(),x=HG(e,GG(s,a.v7_relativeSplatPath),f,i==="path"),_=JSON.stringify(x);return P.useEffect(()=>m(JSON.parse(_),{replace:r,state:n,relative:i}),[m,_,i,r,n]),null}function Q$t(t){return F3e(t.context)}function Pe(t){eo(!1)}function Q3e(t){let{basename:e="/",children:r=null,location:n,navigationType:i=yy.Pop,navigator:a,static:c=!1,future:s}=t;xS()&&eo(!1);let f=e.replace(/^\/*/,"/"),m=P.useMemo(()=>({basename:f,navigator:a,static:c,future:sk({v7_relativeSplatPath:!1},s)}),[f,s,a,c]);typeof n=="string"&&(n=yS(n));let{pathname:x="/",search:_="",hash:T="",state:E=null,key:C="default"}=n,N=P.useMemo(()=>{let R=g1(x,f);return R==null?null:{location:{pathname:R,search:_,hash:T,state:E,key:C},navigationType:i}},[f,x,_,T,E,C,i]);return N==null?null:P.createElement(Vm.Provider,{value:m},P.createElement(gM.Provider,{children:r,value:N}))}function ak(t){let{children:e,location:r}=t;return B3e(JU(e),r)}new Promise(()=>{});function JU(t,e){e===void 0&&(e=[]);let r=[];return P.Children.forEach(t,(n,i)=>{if(!P.isValidElement(n))return;let a=[...e,i];if(n.type===P.Fragment){r.push.apply(r,JU(n.props.children,a));return}n.type!==Pe&&eo(!1),!n.props.index||!n.props.children||eo(!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=JU(n.props.children,a)),r.push(c)}),r}/** * React Router DOM v6.30.1 * * 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 qL(){return qL=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0)&&(r[i]=t[i]);return r}function J3e(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}function e5e(t,e){return t.button===0&&(!e||e==="_self")&&!J3e(t)}function e6(t){return t===void 0&&(t=""),new URLSearchParams(typeof t=="string"||Array.isArray(t)||t instanceof URLSearchParams?t:Object.keys(t).reduce((e,r)=>{let n=t[r];return e.concat(Array.isArray(n)?n.map(i=>[r,i]):[[r,n]])},[]))}function t5e(t,e){let r=e6(t);return e&&e.forEach((n,i)=>{r.has(i)||e.getAll(i).forEach(a=>{r.append(i,a)})}),r}const r5e=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],n5e=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],i5e="6";try{window.__reactRouterVersion=i5e}catch{}const s5e=P.createContext({isTransitioning:!1}),a5e="startTransition",dee=gq[a5e];function o5e(t){let{basename:e,children:r,future:n,window:i}=t,a=P.useRef();a.current==null&&(a.current=u3e({window:i,v5Compat:!0}));let c=a.current,[s,f]=P.useState({action:c.action,location:c.location}),{v7_startTransition:m}=n||{},x=P.useCallback(_=>{m&&dee?dee(()=>f(_)):f(_)},[f,m]);return P.useLayoutEffect(()=>c.listen(x),[c,x]),P.useEffect(()=>X3e(n),[n]),P.createElement(Q3e,{basename:e,children:r,location:s.location,navigationType:s.action,navigator:c,future:n})}const l5e=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",c5e=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,cs=P.forwardRef(function(e,r){let{onClick:n,relative:i,reloadDocument:a,replace:c,state:s,target:f,to:m,preventScrollReset:x,viewTransition:_}=e,T=eme(e,r5e),{basename:E}=P.useContext(Vm),C,N=!1;if(typeof m=="string"&&c5e.test(m)&&(C=m,l5e))try{let B=new URL(window.location.href),V=m.startsWith("//")?new URL(B.protocol+m):new URL(m),G=g1(V.pathname,E);V.origin===B.origin&&G!=null?m=G+V.search+V.hash:N=!0}catch{}let R=D3e(m,{relative:i}),D=d5e(m,{replace:c,state:s,target:f,preventScrollReset:x,relative:i,viewTransition:_});function M(B){n&&n(B),B.defaultPrevented||D(B)}return P.createElement("a",qL({},T,{href:C||R,onClick:N||a?n:M,ref:r,target:f}))}),J$t=P.forwardRef(function(e,r){let{"aria-current":n="page",caseSensitive:i=!1,className:a="",end:c=!1,style:s,to:f,viewTransition:m,children:x}=e,_=eme(e,n5e),T=yM(f,{relative:_.relative}),E=Wi(),C=P.useContext(Ype),{navigator:N,basename:R}=P.useContext(Vm),D=C!=null&&h5e(T)&&m===!0,M=N.encodeLocation?N.encodeLocation(T).pathname:T.pathname,B=E.pathname,V=C&&C.navigation&&C.navigation.location?C.navigation.location.pathname:null;i||(B=B.toLowerCase(),V=V?V.toLowerCase():null,M=M.toLowerCase()),V&&R&&(V=g1(V,R)||V);const G=M!=="/"&&M.endsWith("/")?M.length-1:M.length;let W=B===M||!c&&B.startsWith(M)&&B.charAt(G)==="/",X=V!=null&&(V===M||!c&&V.startsWith(M)&&V.charAt(M.length)==="/"),Q={isActive:W,isPending:X,isTransitioning:D},re=W?n:void 0,se;typeof a=="function"?se=a(Q):se=[a,W?"active":null,X?"pending":null,D?"transitioning":null].filter(Boolean).join(" ");let ue=typeof s=="function"?s(Q):s;return P.createElement(cs,qL({},_,{"aria-current":re,className:se,ref:r,style:ue,to:f,viewTransition:m}),typeof x=="function"?x(Q):x)});var t6;(function(t){t.UseScrollRestoration="useScrollRestoration",t.UseSubmit="useSubmit",t.UseSubmitFetcher="useSubmitFetcher",t.UseFetcher="useFetcher",t.useViewTransitionState="useViewTransitionState"})(t6||(t6={}));var hee;(function(t){t.UseFetcher="useFetcher",t.UseFetchers="useFetchers",t.UseScrollRestoration="useScrollRestoration"})(hee||(hee={}));function u5e(t){let e=P.useContext(mM);return e||eo(!1),e}function d5e(t,e){let{target:r,replace:n,state:i,preventScrollReset:a,relative:c,viewTransition:s}=e===void 0?{}:e,f=ma(),m=Wi(),x=yM(t,{relative:c});return P.useCallback(_=>{if(e5e(_,r)){_.preventDefault();let T=n!==void 0?n:$L(m)===$L(x);f(t,{replace:T,state:i,preventScrollReset:a,relative:c,viewTransition:s})}},[m,f,x,n,i,r,t,a,c,s])}function B0(t){let e=P.useRef(e6(t)),r=P.useRef(!1),n=Wi(),i=P.useMemo(()=>t5e(n.search,r.current?null:e.current),[n.search]),a=ma(),c=P.useCallback((s,f)=>{const m=e6(typeof s=="function"?s(i):s);r.current=!0,a("?"+m,f)},[a,i]);return[i,c]}function h5e(t,e){e===void 0&&(e={});let r=P.useContext(s5e);r==null&&eo(!1);let{basename:n}=u5e(t6.useViewTransitionState),i=yM(t,{relative:e.relative});if(!r.isTransitioning)return!1;let a=g1(r.currentLocation.pathname,n)||r.currentLocation.pathname,c=g1(r.nextLocation.pathname,n)||r.nextLocation.pathname;return UL(i.pathname,c)!=null||UL(i.pathname,a)!=null}var f5e=typeof Element<"u",p5e=typeof Map=="function",m5e=typeof Set=="function",g5e=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function CR(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(!CR(t[n],e[n]))return!1;return!0}var a;if(p5e&&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(!CR(n.value[1],e.get(n.value[0])))return!1;return!0}if(m5e&&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(g5e&&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(f5e&&t instanceof Element)return!1;for(n=r;n--!==0;)if(!((i[n]==="_owner"||i[n]==="__v"||i[n]==="__o")&&t.$$typeof)&&!CR(t[i[n]],e[i[n]]))return!1;return!0}return t!==t&&e!==e}var y5e=function(e,r){try{return CR(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 x5e=ds(y5e);var _5e=function(t,e,r,n,i,a,c,s){if(!t){var f;if(e===void 0)f=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var m=[r,n,i,a,c,s],x=0;f=new Error(e.replace(/%s/g,function(){return m[x++]})),f.name="Invariant Violation"}throw f.framesToPop=1,f}},v5e=_5e;const fee=ds(v5e);var b5e=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),s=Object.keys(r);if(c.length!==s.length)return!1;for(var f=Object.prototype.hasOwnProperty.bind(r),m=0;m(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))(tme||{}),yB={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"]}},pee=Object.values(tme),WG={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},S5e=Object.entries(WG).reduce((t,[e,r])=>(t[r]=e,t),{}),qh="data-rh",Rw={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},Lw=(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},T5e=t=>{let e=Lw(t,"title");const r=Lw(t,Rw.TITLE_TEMPLATE);if(Array.isArray(e)&&(e=e.join("")),r&&e)return r.replace(/%s/g,()=>e);const n=Lw(t,Rw.DEFAULT_TITLE);return e||n||void 0},E5e=t=>Lw(t,Rw.ON_CHANGE_CLIENT_STATE)||(()=>{}),xB=(t,e)=>e.filter(r=>typeof r[t]<"u").map(r=>r[t]).reduce((r,n)=>({...r,...n}),{}),A5e=(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),f2=(t,e,r)=>{const n={};return r.filter(i=>Array.isArray(i[t])?!0:(typeof i[t]<"u"&&k5e(`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(f=>{let m;const x=Object.keys(f);for(let T=0;Ti.push(f));const s=Object.keys(c);for(let f=0;f{if(Array.isArray(t)&&t.length){for(let r=0;r({baseTag:A5e(["href"],t),bodyAttributes:xB("bodyAttributes",t),defer:Lw(t,Rw.DEFER),encode:Lw(t,Rw.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:xB("htmlAttributes",t),linkTags:f2("link",["rel","href"],t),metaTags:f2("meta",["name","charset","http-equiv","property","itemprop"],t),noscriptTags:f2("noscript",["innerHTML"],t),onChangeClientState:E5e(t),scriptTags:f2("script",["src","innerHTML"],t),styleTags:f2("style",["cssText"],t),title:T5e(t),titleAttributes:xB("titleAttributes",t),prioritizeSeoTags:C5e(t,Rw.PRIORITIZE_SEO_TAGS)}),rme=t=>Array.isArray(t)?t.join(""):t,I5e=(t,e)=>{const r=Object.keys(t);for(let n=0;nArray.isArray(t)?t.reduce((r,n)=>(I5e(n,e)?r.priority.push(n):r.default.push(n),r),{priority:[],default:[]}):{default:t,priority:[]},mee=(t,e)=>({...t,[e]:void 0}),P5e=["noscript","script","style"],r6=(t,e=!0)=>e===!1?String(t):String(t).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),nme=t=>Object.keys(t).reduce((e,r)=>{const n=typeof t[r]<"u"?`${r}="${t[r]}"`:`${r}`;return e?`${e} ${n}`:n},""),N5e=(t,e,r,n)=>{const i=nme(r),a=rme(e);return i?`<${t} ${qh}="true" ${i}>${r6(a,n)}`:`<${t} ${qh}="true">${r6(a,n)}`},R5e=(t,e,r=!0)=>e.reduce((n,i)=>{const a=i,c=Object.keys(a).filter(m=>!(m==="innerHTML"||m==="cssText")).reduce((m,x)=>{const _=typeof a[x]>"u"?x:`${x}="${r6(a[x],r)}"`;return m?`${m} ${_}`:_},""),s=a.innerHTML||a.cssText||"",f=P5e.indexOf(t)===-1;return`${n}<${t} ${qh}="true" ${c}${f?"/>":`>${s}`}`},""),ime=(t,e={})=>Object.keys(t).reduce((r,n)=>{const i=WG[n];return r[i||n]=t[n],r},e),L5e=(t,e,r)=>{const n={key:e,[qh]:!0},i=ime(r,n);return[Xe.createElement("title",i,e)]},jR=(t,e)=>e.map((r,n)=>{const i={key:n,[qh]:!0};return Object.keys(r).forEach(a=>{const s=WG[a]||a;if(s==="innerHTML"||s==="cssText"){const f=r.innerHTML||r.cssText;i.dangerouslySetInnerHTML={__html:f}}else i[s]=r[a]}),Xe.createElement(t,i)}),Rd=(t,e,r=!0)=>{switch(t){case"title":return{toComponent:()=>L5e(t,e.title,e.titleAttributes),toString:()=>N5e(t,e.title,e.titleAttributes,r)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>ime(e),toString:()=>nme(e)};default:return{toComponent:()=>jR(t,e),toString:()=>R5e(t,e,r)}}},D5e=({metaTags:t,linkTags:e,scriptTags:r,encode:n})=>{const i=_B(t,yB.meta),a=_B(e,yB.link),c=_B(r,yB.script);return{priorityMethods:{toComponent:()=>[...jR("meta",i.priority),...jR("link",a.priority),...jR("script",c.priority)],toString:()=>`${Rd("meta",i.priority,n)} ${Rd("link",a.priority,n)} ${Rd("script",c.priority,n)}`},metaTags:i.default,linkTags:a.default,scriptTags:c.default}},O5e=t=>{const{baseTag:e,bodyAttributes:r,encode:n=!0,htmlAttributes:i,noscriptTags:a,styleTags:c,title:s="",titleAttributes:f,prioritizeSeoTags:m}=t;let{linkTags:x,metaTags:_,scriptTags:T}=t,E={toComponent:()=>{},toString:()=>""};return m&&({priorityMethods:E,linkTags:x,metaTags:_,scriptTags:T}=D5e(t)),{priority:E,base:Rd("base",e,n),bodyAttributes:Rd("bodyAttributes",r,n),htmlAttributes:Rd("htmlAttributes",i,n),link:Rd("link",x,n),meta:Rd("meta",_,n),noscript:Rd("noscript",a,n),script:Rd("script",T,n),style:Rd("style",c,n),title:Rd("title",{title:s,titleAttributes:f},n)}},n6=O5e,lN=[],sme=!!(typeof window<"u"&&window.document&&window.document.createElement),i6=class{constructor(t,e){un(this,"instances",[]);un(this,"canUseDOM",sme);un(this,"context");un(this,"value",{setHelmet:t=>{this.context.helmet=t},helmetInstances:{get:()=>this.canUseDOM?lN:this.instances,add:t=>{(this.canUseDOM?lN:this.instances).push(t)},remove:t=>{const e=(this.canUseDOM?lN:this.instances).indexOf(t);(this.canUseDOM?lN:this.instances).splice(e,1)}}});this.context=t,this.canUseDOM=e||!1,e||(t.helmet=n6({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},M5e={},ame=Xe.createContext(M5e),c0,ome=(c0=class extends P.Component{constructor(r){super(r);un(this,"helmetData");this.helmetData=new i6(this.props.context||{},c0.canUseDOM)}render(){return Xe.createElement(ame.Provider,{value:this.helmetData.value},this.props.children)}},un(c0,"canUseDOM",sme),c0),Ib=(t,e)=>{const r=document.head||document.querySelector("head"),n=r.querySelectorAll(`${t}[${qh}]`),i=[].slice.call(n),a=[];let c;return e&&e.length&&e.forEach(s=>{const f=document.createElement(t);for(const m in s)if(Object.prototype.hasOwnProperty.call(s,m))if(m==="innerHTML")f.innerHTML=s.innerHTML;else if(m==="cssText")f.styleSheet?f.styleSheet.cssText=s.cssText:f.appendChild(document.createTextNode(s.cssText));else{const x=m,_=typeof s[x]>"u"?"":s[x];f.setAttribute(m,_)}f.setAttribute(qh,"true"),i.some((m,x)=>(c=x,f.isEqualNode(m)))?i.splice(c,1):a.push(f)}),i.forEach(s=>{var f;return(f=s.parentNode)==null?void 0:f.removeChild(s)}),a.forEach(s=>r.appendChild(s)),{oldTags:i,newTags:a}},s6=(t,e)=>{const r=document.getElementsByTagName(t)[0];if(!r)return;const n=r.getAttribute(qh),i=n?n.split(","):[],a=[...i],c=Object.keys(e);for(const s of c){const f=e[s]||"";r.getAttribute(s)!==f&&r.setAttribute(s,f),i.indexOf(s)===-1&&i.push(s);const m=a.indexOf(s);m!==-1&&a.splice(m,1)}for(let s=a.length-1;s>=0;s-=1)r.removeAttribute(a[s]);i.length===a.length?r.removeAttribute(qh):r.getAttribute(qh)!==c.join(",")&&r.setAttribute(qh,c.join(","))},F5e=(t,e)=>{typeof t<"u"&&document.title!==t&&(document.title=rme(t)),s6("title",e)},gee=(t,e)=>{const{baseTag:r,bodyAttributes:n,htmlAttributes:i,linkTags:a,metaTags:c,noscriptTags:s,onChangeClientState:f,scriptTags:m,styleTags:x,title:_,titleAttributes:T}=t;s6("body",n),s6("html",i),F5e(_,T);const E={baseTag:Ib("base",r),linkTags:Ib("link",a),metaTags:Ib("meta",c),noscriptTags:Ib("noscript",s),scriptTags:Ib("script",m),styleTags:Ib("style",x)},C={},N={};Object.keys(E).forEach(R=>{const{newTags:D,oldTags:M}=E[R];D.length&&(C[R]=D),M.length&&(N[R]=E[R].oldTags)}),e&&e(),f(t,C,N)},p2=null,B5e=t=>{p2&&cancelAnimationFrame(p2),t.defer?p2=requestAnimationFrame(()=>{gee(t,()=>{p2=null})}):(gee(t),p2=null)},z5e=B5e,yee=class extends P.Component{constructor(){super(...arguments);un(this,"rendered",!1)}shouldComponentUpdate(e){return!w5e(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=j5e(e.get().map(a=>{const c={...a.props};return delete c.context,c}));ome.canUseDOM?z5e(i):n6&&(n=n6(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}},E$,jl=(E$=class extends P.Component{shouldComponentUpdate(t){return!x5e(mee(this.props,"helmetData"),mee(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 fee(pee.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 ${pee.join(", ")} are allowed. Helmet does not support rendering <${t.type}> elements. Refer to our API for more information.`),fee(!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 Xe.Children.forEach(t,n=>{if(!n||!n.props)return;const{children:i,...a}=n.props,c=Object.keys(a).reduce((f,m)=>(f[S5e[m]||m]=a[m],f),{});let{type:s}=n;switch(typeof s=="symbol"?s=s.toString():this.warnOnInvalidChildren(n,i),s){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 i6)){const i=n;n=new i6(i.context,!0),delete r.helmetData}return n?Xe.createElement(yee,{...r,context:n.value}):Xe.createElement(ame.Consumer,null,i=>Xe.createElement(yee,{...r,context:i}))}},un(E$,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),E$);const $5e=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Be(async()=>{const{default:n}=await Promise.resolve().then(()=>_S);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)};class KG extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}}class U5e extends KG{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class V5e extends KG{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class q5e extends KG{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var a6;(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"})(a6||(a6={}));var G5e=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 s(x){try{m(n.next(x))}catch(_){c(_)}}function f(x){try{m(n.throw(x))}catch(_){c(_)}}function m(x){x.done?a(x.value):i(x.value).then(s,f)}m((n=n.apply(t,e||[])).next())})};class H5e{constructor(e,{headers:r={},customFetch:n,region:i=a6.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=$5e(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,r={}){var n;return G5e(this,void 0,void 0,function*(){try{const{headers:i,method:a,body:c}=r;let s={},{region:f}=r;f||(f=this.region),f&&f!=="any"&&(s["x-region"]=f);let m;c&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(s["Content-Type"]="application/octet-stream",m=c):typeof c=="string"?(s["Content-Type"]="text/plain",m=c):typeof FormData<"u"&&c instanceof FormData?m=c:(s["Content-Type"]="application/json",m=JSON.stringify(c)));const x=yield this.fetch(`${this.url}/${e}`,{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},s),this.headers),i),body:m}).catch(C=>{throw new U5e(C)}),_=x.headers.get("x-relay-error");if(_&&_==="true")throw new V5e(x);if(!x.ok)throw new q5e(x);let T=((n=x.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),E;return T==="application/json"?E=yield x.json():T==="application/octet-stream"?E=yield x.blob():T==="text/event-stream"?E=x:T==="multipart/form-data"?E=yield x.formData():E=yield x.text(),{data:E,error:null}}catch(i){return{data:null,error:i}}})}}var _u={},YG={},xM={},MC={},_M={},vM={},W5e=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")},y1=W5e();const K5e=y1.fetch,lme=y1.fetch.bind(y1),cme=y1.Headers,Y5e=y1.Request,Z5e=y1.Response,_S=Object.freeze(Object.defineProperty({__proto__:null,Headers:cme,Request:Y5e,Response:Z5e,default:lme,fetch:K5e},Symbol.toStringTag,{value:"Module"})),X5e=dIe(_S);var bM={};Object.defineProperty(bM,"__esModule",{value:!0});let Q5e=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}};bM.default=Q5e;var ume=Wl&&Wl.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(vM,"__esModule",{value:!0});const J5e=ume(X5e),e4e=ume(bM);let t4e=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=J5e.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,s,f;let m=null,x=null,_=null,T=a.status,E=a.statusText;if(a.ok){if(this.method!=="HEAD"){const D=await a.text();D===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?x=D:x=JSON.parse(D))}const N=(c=this.headers.Prefer)===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),R=(s=a.headers.get("content-range"))===null||s===void 0?void 0:s.split("/");N&&R&&R.length>1&&(_=parseInt(R[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(x)&&(x.length>1?(m={code:"PGRST116",details:`Results contain ${x.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},x=null,_=null,T=406,E="Not Acceptable"):x.length===1?x=x[0]:x=null)}else{const N=await a.text();try{m=JSON.parse(N),Array.isArray(m)&&a.status===404&&(x=[],m=null,T=200,E="OK")}catch{a.status===404&&N===""?(T=204,E="No Content"):m={message:N}}if(m&&this.isMaybeSingle&&(!((f=m==null?void 0:m.details)===null||f===void 0)&&f.includes("0 rows"))&&(m=null,T=200,E="OK"),m&&this.shouldThrowOnError)throw new e4e.default(m)}return{error:m,data:x,count:_,status:T,statusText:E}});return this.shouldThrowOnError||(i=i.catch(a=>{var c,s,f;return{error:{message:`${(c=a==null?void 0:a.name)!==null&&c!==void 0?c:"FetchError"}: ${a==null?void 0:a.message}`,details:`${(s=a==null?void 0:a.stack)!==null&&s!==void 0?s:""}`,hint:"",code:`${(f=a==null?void 0:a.code)!==null&&f!==void 0?f:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,r)}returns(){return this}overrideTypes(){return this}};vM.default=t4e;var r4e=Wl&&Wl.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_M,"__esModule",{value:!0});const n4e=r4e(vM);let i4e=class extends n4e.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",s=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${s?`${s},`:""}${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 s;const f=[e?"analyze":null,r?"verbose":null,n?"settings":null,i?"buffers":null,a?"wal":null].filter(Boolean).join("|"),m=(s=this.headers.Accept)!==null&&s!==void 0?s:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${c}; for="${m}"; options=${f};`,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}};_M.default=i4e;var s4e=Wl&&Wl.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(MC,"__esModule",{value:!0});const a4e=s4e(_M);let o4e=class extends a4e.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}};MC.default=o4e;var l4e=Wl&&Wl.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(xM,"__esModule",{value:!0});const m2=l4e(MC);let c4e=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(s=>/\s/.test(s)&&!a?"":(s==='"'&&(a=!a),s)).join("");return this.url.searchParams.set("select",c),n&&(this.headers.Prefer=`count=${n}`),new m2.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((s,f)=>s.concat(Object.keys(f)),[]);if(c.length>0){const s=[...new Set(c)].map(f=>`"${f}"`);this.url.searchParams.set("columns",s.join(","))}}return new m2.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",s=[`resolution=${n?"ignore":"merge"}-duplicates`];if(r!==void 0&&this.url.searchParams.set("on_conflict",r),this.headers.Prefer&&s.push(this.headers.Prefer),i&&s.push(`count=${i}`),a||s.push("missing=default"),this.headers.Prefer=s.join(","),Array.isArray(e)){const f=e.reduce((m,x)=>m.concat(Object.keys(x)),[]);if(f.length>0){const m=[...new Set(f)].map(x=>`"${x}"`);this.url.searchParams.set("columns",m.join(","))}}return new m2.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 m2.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 m2.default({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};xM.default=c4e;var wM={},SM={};Object.defineProperty(SM,"__esModule",{value:!0});SM.version=void 0;SM.version="0.0.0-automated";Object.defineProperty(wM,"__esModule",{value:!0});wM.DEFAULT_HEADERS=void 0;const u4e=SM;wM.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${u4e.version}`};var dme=Wl&&Wl.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(YG,"__esModule",{value:!0});const d4e=dme(xM),h4e=dme(MC),f4e=wM;let p4e=class hme{constructor(e,{headers:r={},schema:n,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},f4e.DEFAULT_HEADERS),r),this.schemaName=n,this.fetch=i}from(e){const r=new URL(`${this.url}/${e}`);return new d4e.default(r,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new hme(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,r={},{head:n=!1,get:i=!1,count:a}={}){let c;const s=new URL(`${this.url}/rpc/${e}`);let f;n||i?(c=n?"HEAD":"GET",Object.entries(r).filter(([x,_])=>_!==void 0).map(([x,_])=>[x,Array.isArray(_)?`{${_.join(",")}}`:`${_}`]).forEach(([x,_])=>{s.searchParams.append(x,_)})):(c="POST",f=r);const m=Object.assign({},this.headers);return a&&(m.Prefer=`count=${a}`),new h4e.default({method:c,url:s,headers:m,schema:this.schemaName,body:f,fetch:this.fetch,allowEmpty:!1})}};YG.default=p4e;var vS=Wl&&Wl.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_u,"__esModule",{value:!0});_u.PostgrestError=_u.PostgrestBuilder=_u.PostgrestTransformBuilder=_u.PostgrestFilterBuilder=_u.PostgrestQueryBuilder=_u.PostgrestClient=void 0;const fme=vS(YG);_u.PostgrestClient=fme.default;const pme=vS(xM);_u.PostgrestQueryBuilder=pme.default;const mme=vS(MC);_u.PostgrestFilterBuilder=mme.default;const gme=vS(_M);_u.PostgrestTransformBuilder=gme.default;const yme=vS(vM);_u.PostgrestBuilder=yme.default;const xme=vS(bM);_u.PostgrestError=xme.default;var m4e=_u.default={PostgrestClient:fme.default,PostgrestQueryBuilder:pme.default,PostgrestFilterBuilder:mme.default,PostgrestTransformBuilder:gme.default,PostgrestBuilder:yme.default,PostgrestError:xme.default};const{PostgrestClient:g4e,PostgrestQueryBuilder:sUt,PostgrestFilterBuilder:aUt,PostgrestTransformBuilder:oUt,PostgrestBuilder:lUt,PostgrestError:cUt}=m4e;let o6;typeof window>"u"?o6=require("ws"):o6=window.WebSocket;const y4e=o6,x4e="2.11.10",_4e={"X-Client-Info":`realtime-js/${x4e}`},v4e="1.0.0",_me=1e4,b4e=1e3;var Dw;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(Dw||(Dw={}));var Oc;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(Oc||(Oc={}));var Oh;(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"})(Oh||(Oh={}));var l6;(function(t){t.websocket="websocket"})(l6||(l6={}));var U_;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(U_||(U_={}));class w4e{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 s=n.decode(e.slice(c,c+i));c=c+i;const f=n.decode(e.slice(c,c+a));c=c+a;const m=JSON.parse(n.decode(e.slice(c,e.byteLength)));return{ref:null,topic:s,event:f,payload:m}}}class vme{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 ua;(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"})(ua||(ua={}));const xee=(t,e,r={})=>{var n;const i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return Object.keys(e).reduce((a,c)=>(a[c]=S4e(c,t,e,i),a),{})},S4e=(t,e,r,n)=>{const i=e.find(s=>s.name===t),a=i==null?void 0:i.type,c=r[t];return a&&!n.includes(a)?bme(a,c):c6(c)},bme=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return k4e(e,r)}switch(t){case ua.bool:return T4e(e);case ua.float4:case ua.float8:case ua.int2:case ua.int4:case ua.int8:case ua.numeric:case ua.oid:return E4e(e);case ua.json:case ua.jsonb:return A4e(e);case ua.timestamp:return C4e(e);case ua.abstime:case ua.date:case ua.daterange:case ua.int4range:case ua.int8range:case ua.money:case ua.reltime:case ua.text:case ua.time:case ua.timestamptz:case ua.timetz:case ua.tsrange:case ua.tstzrange:return c6(e);default:return c6(e)}},c6=t=>t,T4e=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},E4e=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},A4e=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch(e){return console.log(`JSON parse error: ${e}`),t}return t},k4e=(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(s=>bme(e,s))}return t},C4e=t=>typeof t=="string"?t.replace(" ","T"):t,wme=t=>{let e=t;return e=e.replace(/^ws/i,"http"),e=e.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),e.replace(/\/+$/,"")};class vB{constructor(e,r,n={},i=_me){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 _ee;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(_ee||(_ee={}));class hA{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:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=hA.syncState(this.state,i,a,c),this.pendingDiffs.forEach(f=>{this.state=hA.syncDiff(this.state,f,a,c)}),this.pendingDiffs=[],s()}),this.channel._on(n.diff,{},i=>{const{onJoin:a,onLeave:c,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=hA.syncDiff(this.state,i,a,c),s())}),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),s={},f={};return this.map(a,(m,x)=>{c[m]||(f[m]=x)}),this.map(c,(m,x)=>{const _=a[m];if(_){const T=x.map(R=>R.presence_ref),E=_.map(R=>R.presence_ref),C=x.filter(R=>E.indexOf(R.presence_ref)<0),N=_.filter(R=>T.indexOf(R.presence_ref)<0);C.length>0&&(s[m]=C),N.length>0&&(f[m]=N)}else s[m]=x}),this.syncDiff(a,{joins:s,leaves:f},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,(s,f)=>{var m;const x=(m=e[s])!==null&&m!==void 0?m:[];if(e[s]=this.cloneDeep(f),x.length>0){const _=e[s].map(E=>E.presence_ref),T=x.filter(E=>_.indexOf(E.presence_ref)<0);e[s].unshift(...T)}n(s,x,f)}),this.map(c,(s,f)=>{let m=e[s];if(!m)return;const x=f.map(_=>_.presence_ref);m=m.filter(_=>x.indexOf(_.presence_ref)<0),e[s]=m,i(s,m,f),m.length===0&&delete e[s]}),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 vee;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(vee||(vee={}));var bee;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(bee||(bee={}));var nm;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(nm||(nm={}));class ZG{constructor(e,r={config:{}},n){this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=Oc.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 vB(this,Oh.join,this.params,this.timeout),this.rejoinTimer=new vme(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Oc.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=Oc.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=Oc.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Oc.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Oh.reply,{},(i,a)=>{this._trigger(this._replyEventName(a),i)}),this.presence=new hA(this),this.broadcastEndpointURL=wme(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:s}}=this.params;this._onError(x=>e==null?void 0:e(nm.CHANNEL_ERROR,x)),this._onClose(()=>e==null?void 0:e(nm.CLOSED));const f={},m={broadcast:a,presence:c,postgres_changes:(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(x=>x.filter))!==null&&i!==void 0?i:[],private:s};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:m},f)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:x})=>{var _;if(this.socket.setAuth(),x===void 0){e==null||e(nm.SUBSCRIBED);return}else{const T=this.bindings.postgres_changes,E=(_=T==null?void 0:T.length)!==null&&_!==void 0?_:0,C=[];for(let N=0;N{this.state=Oc.errored,e==null||e(nm.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(x).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(nm.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,f={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 m=await this._fetchWithTimeout(this.broadcastEndpointURL,f,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=m.body)===null||i===void 0?void 0:i.cancel()),m.ok?"ok":"error"}catch(m){return m.name==="AbortError"?"timed out":"error"}}else return new Promise(a=>{var c,s,f;const m=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((f=(s=(c=this.params)===null||c===void 0?void 0:c.config)===null||s===void 0?void 0:s.broadcast)===null||f===void 0)&&f.ack)&&a("ok"),m.receive("ok",()=>a("ok")),m.receive("error",()=>a("error")),m.receive("timeout",()=>a("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=Oc.leaving;const r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Oh.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(n=>{const i=new vB(this,Oh.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 vB(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:s,error:f,leave:m,join:x}=Oh;if(n&&[s,f,m,x].indexOf(c)>=0&&n!==this._joinRef())return;let T=this._onMessage(c,r,n);if(r&&!T)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(E=>{var C,N,R;return((C=E.filter)===null||C===void 0?void 0:C.event)==="*"||((R=(N=E.filter)===null||N===void 0?void 0:N.event)===null||R===void 0?void 0:R.toLocaleLowerCase())===c}).map(E=>E.callback(T,n)):(a=this.bindings[c])===null||a===void 0||a.filter(E=>{var C,N,R,D,M,B;if(["broadcast","presence","postgres_changes"].includes(c))if("id"in E){const V=E.id,G=(C=E.filter)===null||C===void 0?void 0:C.event;return V&&((N=r.ids)===null||N===void 0?void 0:N.includes(V))&&(G==="*"||(G==null?void 0:G.toLocaleLowerCase())===((R=r.data)===null||R===void 0?void 0:R.type.toLocaleLowerCase()))}else{const V=(M=(D=E==null?void 0:E.filter)===null||D===void 0?void 0:D.event)===null||M===void 0?void 0:M.toLocaleLowerCase();return V==="*"||V===((B=r==null?void 0:r.event)===null||B===void 0?void 0:B.toLocaleLowerCase())}else return E.type.toLocaleLowerCase()===c}).map(E=>{if(typeof T=="object"&&"ids"in T){const C=T.data,{schema:N,table:R,commit_timestamp:D,type:M,errors:B}=C;T=Object.assign(Object.assign({},{schema:N,table:R,commit_timestamp:D,eventType:M,new:{},old:{},errors:B}),this._getPayloadRecords(C))}E.callback(T,n)})}_isClosed(){return this.state===Oc.closed}_isJoined(){return this.state===Oc.joined}_isJoining(){return this.state===Oc.joining}_isLeaving(){return this.state===Oc.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&&ZG.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(Oh.close,{},e)}_onError(e){this._on(Oh.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Oc.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=xee(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=xee(e.columns,e.old_record)),r}}const wee=()=>{},j4e=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class I4e{constructor(e,r){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=_4e,this.params={},this.timeout=_me,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=wee,this.ref=0,this.logger=wee,this.conn=null,this.sendBuffer=[],this.serializer=new w4e,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=a=>{let c;return a?c=a:typeof fetch>"u"?c=(...s)=>Be(async()=>{const{default:f}=await Promise.resolve().then(()=>_S);return{default:f}},void 0).then(({default:f})=>f(...s)):c=fetch,(...s)=>c(...s)},this.endPoint=`${e}/${l6.websocket}`,this.httpEndpoint=wme(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 vme(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=y4e),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 P4e(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:v4e}))}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 Dw.connecting:return U_.Connecting;case Dw.open:return U_.Open;case Dw.closing:return U_.Closing;default:return U_.Closed}}isConnected(){return this.connectionState()===U_.Open}channel(e,r={config:{}}){const n=`realtime:${e}`,i=this.getChannels().find(a=>a.topic===n);if(i)return i;{const a=new ZG(`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,s=>{var f;(f=this.conn)===null||f===void 0||f.send(s)})};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(Oh.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(b4e,"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(s=>s._isMember(n)).forEach(s=>s._trigger(i,a,c)),this.stateChangeCallbacks.message.forEach(s=>s(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(Oh.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([j4e],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}}class P4e{constructor(e,r,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Dw.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}}class XG extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function bl(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}class N4e extends XG{constructor(e,r){super(e),this.name="StorageApiError",this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class u6 extends XG{constructor(e,r){super(e),this.name="StorageUnknownError",this.originalError=r}}var R4e=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 s(x){try{m(n.next(x))}catch(_){c(_)}}function f(x){try{m(n.throw(x))}catch(_){c(_)}}function m(x){x.done?a(x.value):i(x.value).then(s,f)}m((n=n.apply(t,e||[])).next())})};const Sme=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Be(async()=>{const{default:n}=await Promise.resolve().then(()=>_S);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},L4e=()=>R4e(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Be(()=>Promise.resolve().then(()=>_S),void 0)).Response:Response}),d6=t=>{if(Array.isArray(t))return t.map(r=>d6(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]=d6(n)}),e};var z0=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 s(x){try{m(n.next(x))}catch(_){c(_)}}function f(x){try{m(n.throw(x))}catch(_){c(_)}}function m(x){x.done?a(x.value):i(x.value).then(s,f)}m((n=n.apply(t,e||[])).next())})};const bB=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),D4e=(t,e,r)=>z0(void 0,void 0,void 0,function*(){const n=yield L4e();t instanceof n&&!(r!=null&&r.noResolveJson)?t.json().then(i=>{e(new N4e(bB(i),t.status||500))}).catch(i=>{e(new u6(bB(i),i))}):e(new u6(bB(t),t))}),O4e=(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 FC(t,e,r,n,i,a){return z0(this,void 0,void 0,function*(){return new Promise((c,s)=>{t(r,O4e(e,n,i,a)).then(f=>{if(!f.ok)throw f;return n!=null&&n.noResolveJson?f:f.json()}).then(f=>c(f)).catch(f=>D4e(f,s,n))})})}function GL(t,e,r,n){return z0(this,void 0,void 0,function*(){return FC(t,"GET",e,r,n)})}function Zg(t,e,r,n,i){return z0(this,void 0,void 0,function*(){return FC(t,"POST",e,n,i,r)})}function M4e(t,e,r,n,i){return z0(this,void 0,void 0,function*(){return FC(t,"PUT",e,n,i,r)})}function F4e(t,e,r,n){return z0(this,void 0,void 0,function*(){return FC(t,"HEAD",e,Object.assign(Object.assign({},r),{noResolveJson:!0}),n)})}function Tme(t,e,r,n,i){return z0(this,void 0,void 0,function*(){return FC(t,"DELETE",e,n,i,r)})}var hu=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 s(x){try{m(n.next(x))}catch(_){c(_)}}function f(x){try{m(n.throw(x))}catch(_){c(_)}}function m(x){x.done?a(x.value):i(x.value).then(s,f)}m((n=n.apply(t,e||[])).next())})};const B4e={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},See={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class z4e{constructor(e,r={},n,i){this.url=e,this.headers=r,this.bucketId=n,this.fetch=Sme(i)}uploadOrUpdate(e,r,n,i){return hu(this,void 0,void 0,function*(){try{let a;const c=Object.assign(Object.assign({},See),i);let s=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(c.upsert)});const f=c.metadata;typeof Blob<"u"&&n instanceof Blob?(a=new FormData,a.append("cacheControl",c.cacheControl),f&&a.append("metadata",this.encodeMetadata(f)),a.append("",n)):typeof FormData<"u"&&n instanceof FormData?(a=n,a.append("cacheControl",c.cacheControl),f&&a.append("metadata",this.encodeMetadata(f))):(a=n,s["cache-control"]=`max-age=${c.cacheControl}`,s["content-type"]=c.contentType,f&&(s["x-metadata"]=this.toBase64(this.encodeMetadata(f)))),i!=null&&i.headers&&(s=Object.assign(Object.assign({},s),i.headers));const m=this._removeEmptyFolders(r),x=this._getFinalPath(m),_=yield this.fetch(`${this.url}/object/${x}`,Object.assign({method:e,body:a,headers:s},c!=null&&c.duplex?{duplex:c.duplex}:{})),T=yield _.json();return _.ok?{data:{path:m,id:T.Id,fullPath:T.Key},error:null}:{data:null,error:T}}catch(a){if(bl(a))return{data:null,error:a};throw a}})}upload(e,r,n){return hu(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,r,n)})}uploadToSignedUrl(e,r,n,i){return hu(this,void 0,void 0,function*(){const a=this._removeEmptyFolders(e),c=this._getFinalPath(a),s=new URL(this.url+`/object/upload/sign/${c}`);s.searchParams.set("token",r);try{let f;const m=Object.assign({upsert:See.upsert},i),x=Object.assign(Object.assign({},this.headers),{"x-upsert":String(m.upsert)});typeof Blob<"u"&&n instanceof Blob?(f=new FormData,f.append("cacheControl",m.cacheControl),f.append("",n)):typeof FormData<"u"&&n instanceof FormData?(f=n,f.append("cacheControl",m.cacheControl)):(f=n,x["cache-control"]=`max-age=${m.cacheControl}`,x["content-type"]=m.contentType);const _=yield this.fetch(s.toString(),{method:"PUT",body:f,headers:x}),T=yield _.json();return _.ok?{data:{path:a,fullPath:T.Key},error:null}:{data:null,error:T}}catch(f){if(bl(f))return{data:null,error:f};throw f}})}createSignedUploadUrl(e,r){return hu(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 Zg(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:i}),c=new URL(this.url+a.url),s=c.searchParams.get("token");if(!s)throw new XG("No token returned by API");return{data:{signedUrl:c.toString(),path:e,token:s},error:null}}catch(n){if(bl(n))return{data:null,error:n};throw n}})}update(e,r,n){return hu(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,r,n)})}move(e,r,n){return hu(this,void 0,void 0,function*(){try{return{data:yield Zg(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(bl(i))return{data:null,error:i};throw i}})}copy(e,r,n){return hu(this,void 0,void 0,function*(){try{return{data:{path:(yield Zg(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(bl(i))return{data:null,error:i};throw i}})}createSignedUrl(e,r,n){return hu(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),a=yield Zg(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(bl(i))return{data:null,error:i};throw i}})}createSignedUrls(e,r,n){return hu(this,void 0,void 0,function*(){try{const i=yield Zg(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(bl(i))return{data:null,error:i};throw i}})}download(e,r){return hu(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 s=this._getFinalPath(e);return{data:yield(yield GL(this.fetch,`${this.url}/${i}/${s}${c}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(s){if(bl(s))return{data:null,error:s};throw s}})}info(e){return hu(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{const n=yield GL(this.fetch,`${this.url}/object/info/${r}`,{headers:this.headers});return{data:d6(n),error:null}}catch(n){if(bl(n))return{data:null,error:n};throw n}})}exists(e){return hu(this,void 0,void 0,function*(){const r=this._getFinalPath(e);try{return yield F4e(this.fetch,`${this.url}/object/${r}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(bl(n)&&n instanceof u6){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 s=typeof(r==null?void 0:r.transform)<"u"?"render/image":"object",f=this.transformOptsToQueryString((r==null?void 0:r.transform)||{});f!==""&&i.push(f);let m=i.join("&");return m!==""&&(m=`?${m}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${n}${m}`)}}}remove(e){return hu(this,void 0,void 0,function*(){try{return{data:yield Tme(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(r){if(bl(r))return{data:null,error:r};throw r}})}list(e,r,n){return hu(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},B4e),r),{prefix:e||""});return{data:yield Zg(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},n),error:null}}catch(i){if(bl(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 $4e="2.7.1",U4e={"X-Client-Info":`storage-js/${$4e}`};var Pb=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 s(x){try{m(n.next(x))}catch(_){c(_)}}function f(x){try{m(n.throw(x))}catch(_){c(_)}}function m(x){x.done?a(x.value):i(x.value).then(s,f)}m((n=n.apply(t,e||[])).next())})};class V4e{constructor(e,r={},n){this.url=e,this.headers=Object.assign(Object.assign({},U4e),r),this.fetch=Sme(n)}listBuckets(){return Pb(this,void 0,void 0,function*(){try{return{data:yield GL(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(bl(e))return{data:null,error:e};throw e}})}getBucket(e){return Pb(this,void 0,void 0,function*(){try{return{data:yield GL(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(r){if(bl(r))return{data:null,error:r};throw r}})}createBucket(e,r={public:!1}){return Pb(this,void 0,void 0,function*(){try{return{data:yield Zg(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(bl(n))return{data:null,error:n};throw n}})}updateBucket(e,r){return Pb(this,void 0,void 0,function*(){try{return{data:yield M4e(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(bl(n))return{data:null,error:n};throw n}})}emptyBucket(e){return Pb(this,void 0,void 0,function*(){try{return{data:yield Zg(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(r){if(bl(r))return{data:null,error:r};throw r}})}deleteBucket(e){return Pb(this,void 0,void 0,function*(){try{return{data:yield Tme(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(r){if(bl(r))return{data:null,error:r};throw r}})}}class q4e extends V4e{constructor(e,r={},n){super(e,r,n)}from(e){return new z4e(this.url,this.headers,e,this.fetch)}}const G4e="2.49.10";let H2="";typeof Deno<"u"?H2="deno":typeof document<"u"?H2="web":typeof navigator<"u"&&navigator.product==="ReactNative"?H2="react-native":H2="node";const H4e={"X-Client-Info":`supabase-js-${H2}/${G4e}`},W4e={headers:H4e},K4e={schema:"public"},Y4e={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Z4e={};var X4e=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 s(x){try{m(n.next(x))}catch(_){c(_)}}function f(x){try{m(n.throw(x))}catch(_){c(_)}}function m(x){x.done?a(x.value):i(x.value).then(s,f)}m((n=n.apply(t,e||[])).next())})};const Q4e=t=>{let e;return t?e=t:typeof fetch>"u"?e=lme:e=fetch,(...r)=>e(...r)},J4e=()=>typeof Headers>"u"?cme:Headers,eBe=(t,e,r)=>{const n=Q4e(r),i=J4e();return(a,c)=>X4e(void 0,void 0,void 0,function*(){var s;const f=(s=yield e())!==null&&s!==void 0?s:t;let m=new i(c==null?void 0:c.headers);return m.has("apikey")||m.set("apikey",t),m.has("Authorization")||m.set("Authorization",`Bearer ${f}`),n(a,Object.assign(Object.assign({},c),{headers:m}))})};var tBe=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 s(x){try{m(n.next(x))}catch(_){c(_)}}function f(x){try{m(n.throw(x))}catch(_){c(_)}}function m(x){x.done?a(x.value):i(x.value).then(s,f)}m((n=n.apply(t,e||[])).next())})};function rBe(t){return t.endsWith("/")?t:t+"/"}function nBe(t,e){var r,n;const{db:i,auth:a,realtime:c,global:s}=t,{db:f,auth:m,realtime:x,global:_}=e,T={db:Object.assign(Object.assign({},f),i),auth:Object.assign(Object.assign({},m),a),realtime:Object.assign(Object.assign({},x),c),global:Object.assign(Object.assign(Object.assign({},_),s),{headers:Object.assign(Object.assign({},(r=_==null?void 0:_.headers)!==null&&r!==void 0?r:{}),(n=s==null?void 0:s.headers)!==null&&n!==void 0?n:{})}),accessToken:()=>tBe(this,void 0,void 0,function*(){return""})};return t.accessToken?T.accessToken=t.accessToken:delete T.accessToken,T}const Eme="2.69.1",Yb=30*1e3,h6=3,wB=h6*Yb,iBe="http://localhost:9999",sBe="supabase.auth.token",aBe={"X-Client-Info":`gotrue-js/${Eme}`},f6="X-Supabase-Api-Version",Ame={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},oBe=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,lBe=6e5;class QG extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}}function Ni(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class cBe extends QG{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function uBe(t){return Ni(t)&&t.name==="AuthApiError"}class kme extends QG{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class ix extends QG{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n}}class qg extends ix{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function dBe(t){return Ni(t)&&t.name==="AuthSessionMissingError"}class SB extends ix{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class cN extends ix{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class uN extends ix{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 hBe(t){return Ni(t)&&t.name==="AuthImplicitGrantRedirectError"}class Tee extends ix{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 p6 extends ix{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function TB(t){return Ni(t)&&t.name==="AuthRetryableFetchError"}class Eee extends ix{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}}class fA extends ix{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Aee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),kee=` \r=`.split(""),fBe=(()=>{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 Cee(t){const e=[],r=c=>{e.push(String.fromCodePoint(c))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},a=c=>{gBe(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 mBe(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}pBe(n,e)}}function gBe(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 yBe(t){const e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};for(let i=0;ie.push(r)),new Uint8Array(e)}function _Be(t){return Math.round(Date.now()/1e3)+t}function vBe(){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 If=()=>typeof window<"u"&&typeof document<"u",T_={tested:!1,writable:!1},pA=()=>{if(!If())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(T_.tested)return T_.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),T_.tested=!0,T_.writable=!0}catch{T_.tested=!0,T_.writable=!1}return T_.writable};function bBe(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 jme=t=>{let e;return t?e=t:typeof fetch>"u"?e=(...r)=>Be(async()=>{const{default:n}=await Promise.resolve().then(()=>_S);return{default:n}},void 0).then(({default:n})=>n(...r)):e=fetch,(...r)=>e(...r)},wBe=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Ime=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},dN=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},hN=async(t,e)=>{await t.removeItem(e)};class TM{constructor(){this.promise=new TM.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}TM.promiseConstructor=Promise;function EB(t){const e=t.split(".");if(e.length!==3)throw new fA("Invalid JWT structure");for(let n=0;n{setTimeout(()=>e(null),t)})}function TBe(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 EBe(t){return("0"+t.toString(16)).substr(-2)}function ABe(){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,EBe).join("")}async function kBe(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 CBe(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 kBe(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Nb(t,e,r=!1){const n=ABe();let i=n;r&&(i+="/PASSWORD_RECOVERY"),await Ime(t,`${e}-code-verifier`,i);const a=await CBe(n);return[a,n===a?"plain":"s256"]}const jBe=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function IBe(t){const e=t.headers.get(f6);if(!e||!e.match(jBe))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function PBe(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 NBe(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 RBe=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),LBe=[502,503,504];async function jee(t){var e;if(!wBe(t))throw new p6(D_(t),0);if(LBe.includes(t.status))throw new p6(D_(t),t.status);let r;try{r=await t.json()}catch(a){throw new kme(D_(a),a)}let n;const i=IBe(t);if(i&&i.getTime()>=Ame["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 Eee(D_(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new qg}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 Eee(D_(r),t.status,r.weak_password.reasons);throw new cBe(D_(r),t.status||500,n)}const DBe=(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 Zi(t,e,r,n){var i;const a=Object.assign({},n==null?void 0:n.headers);a[f6]||(a[f6]=Ame["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 s=Object.keys(c).length?"?"+new URLSearchParams(c).toString():"",f=await OBe(t,e,r+s,{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(f):{data:Object.assign({},f),error:null}}async function OBe(t,e,r,n,i,a){const c=DBe(e,n,i,a);let s;try{s=await t(r,Object.assign({},c))}catch(f){throw console.error(f),new p6(D_(f),0)}if(s.ok||await jee(s),n!=null&&n.noResolveJson)return s;try{return await s.json()}catch(f){await jee(f)}}function Gg(t){var e;let r=null;zBe(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=_Be(t.expires_in)));const n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function Iee(t){const e=Gg(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 ny(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function MBe(t){return{data:t,error:null}}function FBe(t){const{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:a}=t,c=RBe(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),s={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:a},f=Object.assign({},c);return{data:{properties:s,user:f},error:null}}function BBe(t){return t}function zBe(t){return t.access_token&&t.refresh_token&&t.expires_in}var $Be=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&&(E.forEach(C=>{const N=parseInt(C.split(";")[0].split("=")[1].substring(0,1)),R=JSON.parse(C.split(";")[1].split("=")[1]);m[`${R}Page`]=N}),m.total=parseInt(T)),{data:Object.assign(Object.assign({},_),m),error:null}}catch(m){if(Ni(m))return{data:{users:[]},error:m};throw m}}async getUserById(e){try{return await Zi(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ny})}catch(r){if(Ni(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){try{return await Zi(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:ny})}catch(n){if(Ni(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){try{return await Zi(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:ny})}catch(n){if(Ni(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{const{data:r,error:n}=await Zi(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(Ni(r))return{data:null,error:r};throw r}}async _deleteFactor(e){try{return{data:await Zi(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(Ni(r))return{data:null,error:r};throw r}}}const VBe={getItem:t=>pA()?globalThis.localStorage.getItem(t):null,setItem:(t,e)=>{pA()&&globalThis.localStorage.setItem(t,e)},removeItem:t=>{pA()&&globalThis.localStorage.removeItem(t)}};function Pee(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}function qBe(){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 Rb={debug:!!(globalThis&&pA()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Pme extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class GBe extends Pme{}async function HBe(t,e,r){Rb.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Rb.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){Rb.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,i.name);try{return await r()}finally{Rb.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,i.name)}}else{if(e===0)throw Rb.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new GBe(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(Rb.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()}}))}qBe();const WBe={url:iBe,storageKey:sBe,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:aBe,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Nee(t,e,r){return await r()}class ok{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=ok.nextInstanceID,ok.nextInstanceID+=1,this.instanceID>0&&If()&&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({},WBe),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 UBe({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=jme(i.fetch),this.lock=i.lock||Nee,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,i.lock?this.lock=i.lock:If()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=HBe:this.lock=Nee,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:pA()?this.storage=VBe:(this.memoryStorage={},this.storage=Pee(this.memoryStorage)):(this.memoryStorage={},this.storage=Pee(this.memoryStorage)),If()&&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} (${Eme}) ${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=bBe(window.location.href);let n="none";if(this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce"),If()&&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),hBe(a)){const f=(e=a.details)===null||e===void 0?void 0:e.code;if(f==="identity_already_exists"||f==="identity_not_found"||f==="single_identity_not_deletable")return{error:a}}return await this._removeSession(),{error:a}}const{session:c,redirectType:s}=i;return this._debug("#_initialize()","detected session in URL",c,"redirect type",s),await this._saveSession(c),setTimeout(async()=>{s==="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 Ni(r)?{error:r}:{error:new kme("Unexpected error during initialization",r)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{const a=await Zi(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:Gg}),{data:c,error:s}=a;if(s||!c)return{data:{user:null,session:null},error:s};const f=c.session,m=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(a){if(Ni(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:x,password:_,options:T}=e;let E=null,C=null;this.flowType==="pkce"&&([E,C]=await Nb(this.storage,this.storageKey)),a=await Zi(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:T==null?void 0:T.emailRedirectTo,body:{email:x,password:_,data:(r=T==null?void 0:T.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:T==null?void 0:T.captchaToken},code_challenge:E,code_challenge_method:C},xform:Gg})}else if("phone"in e){const{phone:x,password:_,options:T}=e;a=await Zi(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:x,password:_,data:(n=T==null?void 0:T.data)!==null&&n!==void 0?n:{},channel:(i=T==null?void 0:T.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:T==null?void 0:T.captchaToken}},xform:Gg})}else throw new cN("You must provide either an email or phone number and a password");const{data:c,error:s}=a;if(s||!c)return{data:{user:null,session:null},error:s};const f=c.session,m=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(a){if(Ni(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:s}=e;r=await Zi(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:c,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},xform:Iee})}else if("phone"in e){const{phone:a,password:c,options:s}=e;r=await Zi(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:c,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},xform:Iee})}else throw new cN("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 SB}:(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(Ni(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 dN(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{const{data:a,error:c}=await Zi(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Gg});if(await hN(this.storage,`${this.storageKey}-code-verifier`),c)throw c;return!a||!a.session||!a.user?{data:{user:null,session:null,redirectType:null},error:new SB}:(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(Ni(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,s=await Zi(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:Gg}),{data:f,error:m}=s;return m?{data:{user:null,session:null},error:m}:!f||!f.session||!f.user?{data:{user:null,session:null},error:new SB}:(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("SIGNED_IN",f.session)),{data:f,error:m})}catch(r){if(Ni(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:s,options:f}=e;let m=null,x=null;this.flowType==="pkce"&&([m,x]=await Nb(this.storage,this.storageKey));const{error:_}=await Zi(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},create_user:(n=f==null?void 0:f.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:m,code_challenge_method:x},redirectTo:f==null?void 0:f.emailRedirectTo});return{data:{user:null,session:null},error:_}}if("phone"in e){const{phone:s,options:f}=e,{data:m,error:x}=await Zi(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:s,data:(i=f==null?void 0:f.data)!==null&&i!==void 0?i:{},create_user:(a=f==null?void 0:f.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},channel:(c=f==null?void 0:f.channel)!==null&&c!==void 0?c:"sms"}});return{data:{user:null,session:null,messageId:m==null?void 0:m.message_id},error:x}}throw new cN("You must provide either an email or phone number.")}catch(s){if(Ni(s))return{data:{user:null,session:null},error:s};throw s}}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:s}=await Zi(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:i,xform:Gg});if(s)throw s;if(!c)throw new Error("An error occurred on token verification.");const f=c.session,m=c.user;return f!=null&&f.access_token&&(await this._saveSession(f),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(i){if(Ni(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 Nb(this.storage,this.storageKey)),await Zi(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:MBe})}catch(a){if(Ni(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 qg;const{error:i}=await Zi(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(Ni(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 Zi(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:s}=await Zi(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:s}}throw new cN("You must provide either an email or phone number and a type")}catch(r){if(Ni(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 dN(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&&m==="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(f,m,x))})}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 Zi(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ny}):await this._useSession(async r=>{var n,i,a;const{data:c,error:s}=r;if(s)throw s;return!(!((n=c.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new qg}:await Zi(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:ny})})}catch(r){if(Ni(r))return dBe(r)&&(await this._removeSession(),await hN(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 qg;const c=i.session;let s=null,f=null;this.flowType==="pkce"&&e.email!=null&&([s,f]=await Nb(this.storage,this.storageKey));const{data:m,error:x}=await Zi(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:s,code_challenge_method:f}),jwt:c.access_token,xform:ny});if(x)throw x;return c.user=m.user,await this._saveSession(c),await this._notifyAllSubscribers("USER_UPDATED",c),{data:{user:c.user},error:null}})}catch(n){if(Ni(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 qg;const r=Date.now()/1e3;let n=r,i=!0,a=null;const{payload:c}=EB(e.access_token);if(c.exp&&(n=c.exp,i=n<=r),i){const{session:s,error:f}=await this._callRefreshToken(e.refresh_token);if(f)return{data:{user:null,session:null},error:f};if(!s)return{data:{user:null,session:null},error:null};a=s}else{const{data:s,error:f}=await this._getUser(e.access_token);if(f)throw f;a={access_token:e.access_token,refresh_token:e.refresh_token,user:s.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(Ni(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:s}=r;if(s)throw s;e=(n=c.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new qg;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(Ni(r))return{data:{user:null,session:null},error:r};throw r}}async _getSessionFromURL(e,r){try{if(!If())throw new uN("No browser detected.");if(e.error||e.error_description||e.error_code)throw new uN(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 Tee("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new uN("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 Tee("No code detected.");const{data:M,error:B}=await this._exchangeCodeForSession(e.code);if(B)throw B;const V=new URL(window.location.href);return V.searchParams.delete("code"),window.history.replaceState(window.history.state,"",V.toString()),{data:{session:M.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:a,refresh_token:c,expires_in:s,expires_at:f,token_type:m}=e;if(!a||!s||!c||!m)throw new uN("No session defined in URL");const x=Math.round(Date.now()/1e3),_=parseInt(s);let T=x+_;f&&(T=parseInt(f));const E=T-x;E*1e3<=Yb&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${E}s, should have been closer to ${_}s`);const C=T-_;x-C>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",C,T,x):x-C<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",C,T,x);const{data:N,error:R}=await this._getUser(a);if(R)throw R;const D={provider_token:n,provider_refresh_token:i,access_token:a,expires_in:_,expires_at:T,refresh_token:c,token_type:m,user:N.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:D,redirectType:e.type},error:null}}catch(n){if(Ni(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 dN(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:s}=await this.admin.signOut(c,e);if(s&&!(uBe(s)&&(s.status===404||s.status===401||s.status===403)))return{error:s}}return e!=="others"&&(await this._removeSession(),await hN(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){const r=vBe(),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 Nb(this.storage,this.storageKey,!0));try{return await Zi(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(Ni(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(Ni(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,s,f,m,x;const{data:_,error:T}=a;if(T)throw T;const E=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(c=e.options)===null||c===void 0?void 0:c.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(f=e.options)===null||f===void 0?void 0:f.queryParams,skipBrowserRedirect:!0});return await Zi(this.fetch,"GET",E,{headers:this.headers,jwt:(x=(m=_.session)===null||m===void 0?void 0:m.access_token)!==null&&x!==void 0?x:void 0})});if(i)throw i;return If()&&!(!((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(Ni(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 Zi(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(Ni(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 TBe(async i=>(i>0&&await SBe(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await Zi(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Gg})),(i,a)=>{const c=200*Math.pow(2,i);return a&&TB(a)&&Date.now()+c-n{try{await s.callback(e,r)}catch(f){a.push(f)}});if(await Promise.all(c),a.length>0){for(let s=0;sthis._autoRefreshTokenTick(),Yb);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)/Yb);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Yb}ms, refresh threshold is ${h6} ticks`),i<=h6&&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 Pme)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!If()||!(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 Nb(this.storage,this.storageKey),s=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(c)}`});i.push(s.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 Zi(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(Ni(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 s=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:f,error:m}=await Zi(this.fetch,"POST",`${this.url}/factors`,{body:s,headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return m?{data:null,error:m}:(e.factorType==="totp"&&(!((i=f==null?void 0:f.totp)===null||i===void 0)&&i.qr_code)&&(f.totp.qr_code=`data:image/svg+xml;utf-8,${f.totp.qr_code}`),{data:f,error:null})})}catch(r){if(Ni(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:s}=await Zi(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 s?{data:null,error:s}:(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:s})})}catch(r){if(Ni(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 Zi(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(Ni(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}=EB(i.access_token);let s=null;c.aal&&(s=c.aal);let f=s;((n=(r=i.user.factors)===null||r===void 0?void 0:r.filter(_=>_.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(f="aal2");const x=c.amr||[];return{data:{currentLevel:s,nextLevel:f,currentAuthenticationMethods:x},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+lBe>Date.now()))return n;const{data:i,error:a}=await Zi(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 fA("JWKS is empty");if(this.jwks=i,this.jwks_cached_at=Date.now(),n=i.keys.find(c=>c.kid===e),!n)throw new fA("No matching signing key found in JWKS");return n}async getClaims(e,r={keys:[]}){try{let n=e;if(!n){const{data:E,error:C}=await this.getSession();if(C||!E.session)return{data:null,error:C};n=E.session.access_token}const{header:i,payload:a,signature:c,raw:{header:s,payload:f}}=EB(n);if(PBe(a.exp),!i.kid||i.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:E}=await this.getUser(n);if(E)throw E;return{data:{claims:a,header:i,signature:c},error:null}}const m=NBe(i.alg),x=await this.fetchJwk(i.kid,r),_=await crypto.subtle.importKey("jwk",x,m,!0,["verify"]);if(!await crypto.subtle.verify(m,_,c,xBe(`${s}.${f}`)))throw new fA("Invalid JWT signature");return{data:{claims:a,header:i,signature:c},error:null}}catch(n){if(Ni(n))return{data:null,error:n};throw n}}}ok.nextInstanceID=0;const KBe=ok;class YBe extends KBe{constructor(e){super(e)}}var ZBe=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 s(x){try{m(n.next(x))}catch(_){c(_)}}function f(x){try{m(n.throw(x))}catch(_){c(_)}}function m(x){x.done?a(x.value):i(x.value).then(s,f)}m((n=n.apply(t,e||[])).next())})};class XBe{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 s=rBe(e),f=new URL(s);this.realtimeUrl=new URL("realtime/v1",f),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",f),this.storageUrl=new URL("storage/v1",f),this.functionsUrl=new URL("functions/v1",f);const m=`sb-${f.hostname.split(".")[0]}-auth-token`,x={db:K4e,realtime:Z4e,auth:Object.assign(Object.assign({},Y4e),{storageKey:m}),global:W4e},_=nBe(n??{},x);this.storageKey=(i=_.auth.storageKey)!==null&&i!==void 0?i:"",this.headers=(a=_.global.headers)!==null&&a!==void 0?a:{},_.accessToken?(this.accessToken=_.accessToken,this.auth=new Proxy({},{get:(T,E)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(E)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((c=_.auth)!==null&&c!==void 0?c:{},this.headers,_.global.fetch),this.fetch=eBe(r,this._getAccessToken.bind(this),_.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},_.realtime)),this.rest=new g4e(new URL("rest/v1",f).href,{headers:this.headers,schema:_.db.schema,fetch:this.fetch}),_.accessToken||this._listenForAuthEvents()}get functions(){return new H5e(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new q4e(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 ZBe(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:s,debug:f},m,x){const _={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new YBe({url:this.authUrl.href,headers:Object.assign(Object.assign({},_),m),storageKey:a,autoRefreshToken:e,persistSession:r,detectSessionInUrl:n,storage:i,flowType:c,lock:s,debug:f,fetch:x,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new I4e(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 QBe=(t,e,r)=>new XBe(t,e,r),JBe="lovable-preview-auth:result";function eze(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!==JBe||!("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 tze(){var M,B;if(typeof window>"u")return;const t=location.hostname,r=["lovableproject.com","lovableproject-dev.com","lovable.app","gpt-eng.com","gptengineer.run"].some(V=>t===V||t.endsWith("."+V)),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?((M=new RegExp("^(?:id-preview(?:-[a-z0-9]+)?|project)--("+n+")(?:-dev)?(?=\\.|$)","i").exec(t))==null?void 0:M[1])??((B=new RegExp("^("+n+")(?=[.-])","i").exec(t))==null?void 0:B[1]):void 0,a=window.parent;if(!i||!(a!==null&&a!==window))return localStorage;const s=t.endsWith(".lovableproject-dev.com")||t.endsWith(".gpt-eng.com"),f=s?/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$|^http:\/\/localhost:3000$/:/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$/,m=location.ancestorOrigins,x=(m==null?void 0:m[0])??(document.referrer?new URL(document.referrer).origin:""),_=x&&f.test(x)?[x]:s?["https://lovable.dev","http://localhost:3000"]:["https://lovable.dev"],T=2e3,E=()=>Math.random().toString(36).slice(2)+Date.now().toString(36),C=(V,G,W)=>new Promise(X=>{const Q=E();let re=!1;const se=ve=>{re||(re=!0,clearTimeout(_e),window.removeEventListener("message",ue),X(ve))},ue=ve=>{if(!_.includes(ve.origin))return;const Oe=eze(ve.data,Q);Oe&&se(Oe)};window.addEventListener("message",ue);const _e=setTimeout(()=>{se(null)},T),Se={type:V,requestId:Q,projectId:i,key:G};W!==void 0&&(Se.value=W);for(const ve of _)window.parent.postMessage(Se,ve)});let N=!0;const R=250,D=V=>{try{return localStorage.getItem(V)}catch{return}};return{getItem:async V=>{const G=D(V);let W=await C("lovable-preview-auth:get",V,G??void 0);if(!W&&N&&(await new Promise(X=>setTimeout(X,R)),W=await C("lovable-preview-auth:get",V,G??void 0)),N=!1,W!=null&&W.ok&&W.value!==null){if(W.value==="")return G!==void 0&&D(V)===G&&localStorage.removeItem(V),null;if(G===null&&D(V)===null)try{localStorage.setItem(V,W.value)}catch{}return W.value}return localStorage.getItem(V)},setItem:(V,G)=>(localStorage.setItem(V,G),C("lovable-preview-auth:set",V,G).then(W=>{W!=null&&W.ok&&W.value!==null&&localStorage.getItem(V)===G&&(W.value===""?localStorage.removeItem(V):localStorage.setItem(V,W.value))})),removeItem:V=>{const G=D(V);return localStorage.removeItem(V),C("lovable-preview-auth:remove",V,G??void 0).then(()=>{})}}}const rze="https://relzejiswnotikjgvjhz.supabase.co",nze="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",Le=QBe(rze,nze,{auth:{storage:tze(),persistSession:!0,autoRefreshToken:!0}}),uUt=Object.freeze(Object.defineProperty({__proto__:null,supabase:Le},Symbol.toStringTag,{value:"Module"})),Nme=P.createContext(void 0),ize=({children:t})=>{const[e,r]=P.useState(null),[n,i]=P.useState(null),[a,c]=P.useState(!0),[s,f]=P.useState(!0),[m,x]=P.useState(!1),[_,T]=P.useState(!1),[E,C]=P.useState(!1),[N,R]=P.useState(null),[D,M]=P.useState([]),[B,V]=P.useState(null),G=P.useRef(null),W=P.useRef(!1),X=P.useRef(!1),Q=ma(),re=()=>{x(!1),T(!1),C(!1),R(null),M([]),V(null),G.current=null,W.current=!1},se=async ve=>{if(W.current&&G.current===ve||X.current)return;X.current=!0,f(!0);const Oe=window.setTimeout(()=>{console.warn("Role check timeout reached — unblocking UI."),X.current=!1,f(!1)},8e3);try{console.log("Checking roles via RPC for user:",ve);const[{data:Ae,error:we},{data:ge,error:Ne},{data:Ie,error:Te}]=await Promise.all([Le.rpc("has_role",{_user_id:ve,_role:"admin"}),Le.rpc("has_role",{_user_id:ve,_role:"brokerage_manager"}),Le.rpc("has_role",{_user_id:ve,_role:"coach"})]);if(we||Ne)console.error("Role RPC errors:",{isAdminError:we,isBrokerError:Ne,isCoachError:Te}),x(!1),T(!1),C(!1);else{const rt=!!Ae,at=!!ge,Et=!!Ie;console.log("RPC roles result:",{adminValue:rt,brokerValue:at,coachValue:Et}),x(rt),T(at),C(Et)}G.current=ve,W.current=!0,window.clearTimeout(Oe),f(!1);const{data:be,error:We}=await Le.from("profiles").select("brokerage_id, is_paused, paused_reason").eq("id",ve).single();if(!We&&(be!=null&&be.is_paused)){const rt=be.paused_reason;try{sessionStorage.setItem("accountPausedReason",rt||"")}catch{}await Le.auth.signOut(),re(),Q("/auth?paused=1",{replace:!0});return}if(R(!We&&be?be.brokerage_id:null),ge){console.log("Fetching managed brokerages for user:",ve);const{data:rt,error:at}=await Le.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",ve);if(console.log("Managed brokerage assignments result:",{assignments:rt,assignmentsError:at}),at||!rt){console.error("Error fetching managed brokerage assignments:",at),M([]);return}const Et=Array.from(new Set(rt.map(Pt=>Pt.brokerage_id).filter(Boolean)));if(Et.length===0){M([]);return}const{data:_t,error:Vt}=await Le.from("brokerages").select("id, name").in("id",Et);if(console.log("Managed brokerages details result:",{brokeragesData:_t,brokeragesError:Vt}),Vt||!_t){console.error("Error fetching managed brokerages details:",Vt),M([]);return}const mt=_t.map(Pt=>({id:Pt.id,name:Pt.name})).sort((Pt,er)=>Et.indexOf(Pt.id)-Et.indexOf(er.id));console.log("Parsed managed brokerages:",mt),M(mt),mt.length>0&&V(Pt=>Pt??mt[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),M([]);G.current=ve,W.current=!0}catch(Ae){console.error("Unexpected error in checkRoles:",Ae),re()}finally{window.clearTimeout(Oe),X.current=!1,f(!1)}};P.useEffect(()=>{let ve=!0,Oe=!1;const Ae=()=>{!ve||Oe||(Oe=!0,c(!1))},{data:{subscription:we}}=Le.auth.onAuthStateChange((Ne,Ie)=>{console.log("Auth event:",Ne),ve&&(i(Ie),r((Ie==null?void 0:Ie.user)??null),Ae(),Ne==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{Q("/profile?reset=true")},100)),Ie!=null&&Ie.user?(!W.current||G.current!==Ie.user.id)&&setTimeout(()=>{se(Ie.user.id)},0):(re(),f(!1)))}),ge=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),Ae()},8e3);return()=>{ve=!1,window.clearTimeout(ge),we.unsubscribe()}},[]);const ue=async(ve,Oe)=>{var Ne;const Ae=(ve||"").trim().toLowerCase(),{data:we,error:ge}=await Le.auth.signInWithPassword({email:Ae,password:Oe});if(ge)throw Jt.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((Ne=we.user)!=null&&Ne.id){const{data:Ie}=await Le.from("profiles").select("is_paused, paused_reason").eq("id",we.user.id).maybeSingle();if(Ie!=null&&Ie.is_paused){const Te=Ie.paused_reason||"";try{sessionStorage.setItem("accountPausedReason",Te)}catch{}await Le.auth.signOut(),re(),r(null),i(null);const be=new Error(Te?`Your account is paused. ${Te}`:"Your account is paused. Please contact LevelUp support to reactivate it.");throw be.name="AccountPaused",Jt.error(be.message),be}}Jt.success("Welcome back!")},_e=async(ve,Oe,Ae)=>{var Te;const we="https://dashboard.relevelup.com/dashboard",ge=localStorage.getItem("levelup_referral_code")||null,{data:Ne,error:Ie}=await Le.auth.signUp({email:ve,password:Oe,options:{emailRedirectTo:we,data:{name:Ae,referred_by_code:ge}}});if(Ie)throw Jt.error(Ie.message),Ie;if(ge&&((Te=Ne.user)!=null&&Te.id))try{await Le.from("profiles").update({referred_by_code:ge}).eq("id",Ne.user.id),localStorage.removeItem("levelup_referral_code")}catch(be){console.warn("Failed to attach referral code to profile",be)}Jt.success("Account created! Welcome to LevelUp."),Q("/dashboard")},Se=async()=>{try{const{data:{session:ve}}=await Le.auth.getSession();if(ve){const{error:Oe}=await Le.auth.signOut();Oe?Oe.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",Oe.message):(console.error("Sign out error:",Oe),Jt.error(Oe.message)):Jt.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");r(null),i(null),x(!1),T(!1),R(null),M([]),V(null),Q("/auth")}catch(ve){console.error("Unexpected sign out error:",ve),Q("/auth")}};return o.jsx(Nme.Provider,{value:{user:e,session:n,loading:a,rolesLoading:s,signIn:ue,signUp:_e,signOut:Se,isAdmin:m,isBrokerageManager:_,isCoach:E,brokerageId:N,managedBrokerages:D,selectedBrokerageId:B,setSelectedBrokerageId:V},children:t})},qn=()=>{const t=P.useContext(Nme);if(t===void 0)throw new Error("useAuth must be used within an AuthProvider");return t},Rme=P.createContext({onlineUsers:[],totalOnline:0}),sze=3*60*1e3,aze=45*1e3,oze=30*1e3,lze=({children:t})=>{const{user:e,brokerageId:r,isAdmin:n}=qn(),[i,a]=P.useState([]),c=P.useRef(new Date().toISOString()),s=P.useCallback(async()=>{e&&await Le.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]),f=P.useCallback(async()=>{if(!e)return;const x=new Date(Date.now()-sze).toISOString(),{data:_}=await Le.from("user_presence").select("user_id, last_seen_at, online_since").gte("last_seen_at",x).order("last_seen_at",{ascending:!1}).limit(200);if(!(_!=null&&_.length)){a([]);return}const T=_.map(N=>N.user_id),{data:E}=await Le.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",T),C=new Map((E||[]).map(N=>[N.id,N]));a(_.map(N=>{var D;const R=C.get(N.user_id);return{id:N.user_id,name:(R==null?void 0:R.name)||((D=R==null?void 0:R.email)==null?void 0:D.split("@")[0])||"Member",avatarUrl:(R==null?void 0:R.avatar_url)||void 0,brokerageId:(R==null?void 0:R.brokerage_id)||void 0,onlineSince:N.online_since||N.last_seen_at}}))},[e==null?void 0:e.id]);P.useEffect(()=>{if(!e){a([]);return}c.current=new Date().toISOString();let x=!1;const _=async()=>{x||(await s(),await f())};_();const T=window.setInterval(()=>{s()},aze),E=window.setInterval(()=>{f()},oze),C=()=>{document.visibilityState==="visible"&&_()};return document.addEventListener("visibilitychange",C),()=>{x=!0,window.clearInterval(T),window.clearInterval(E),document.removeEventListener("visibilitychange",C)}},[e==null?void 0:e.id,s,f]);const m=i.filter(x=>!!(x.id===(e==null?void 0:e.id)||n||r&&x.brokerageId===r||!r&&!x.brokerageId));return o.jsx(Rme.Provider,{value:{onlineUsers:m,totalOnline:m.length},children:t})},dUt=()=>P.useContext(Rme),Lme=P.createContext(void 0),E_="levelup_admin_session",Og="levelup_impersonation",AB="levelup_impersonation_return",cze=({children:t})=>{const[e,r]=P.useState(!1),[n,i]=P.useState(null),[a,c]=P.useState(!1);P.useEffect(()=>{const m=sessionStorage.getItem(Og);if(m)try{const x=JSON.parse(m);r(!0),i(x)}catch{sessionStorage.removeItem(Og)}},[]);const s=async(m,x)=>{c(!0);try{const{data:{session:_}}=await Le.auth.getSession();if(!_)return Jt.error("No active session found"),!1;const T={access_token:_.access_token,refresh_token:_.refresh_token};sessionStorage.setItem(E_,JSON.stringify(T)),x&&sessionStorage.setItem(AB,x);const E=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_.access_token}`},body:JSON.stringify({targetUserId:m})}),C=await E.json();if(!E.ok)throw new Error(C.error||"Failed to impersonate user");const N={id:C.targetUser.id,name:C.targetUser.name,email:C.targetUser.email};if(sessionStorage.setItem(Og,JSON.stringify(N)),C.method==="session"){const{error:R}=await Le.auth.setSession({access_token:C.access_token,refresh_token:C.refresh_token});if(R)throw console.error("Set session error:",R),sessionStorage.removeItem(E_),sessionStorage.removeItem(Og),new Error("Failed to establish impersonation session")}else{const R=C.type||"recovery",{error:D}=await Le.auth.verifyOtp({token_hash:C.token_hash,type:R});if(D)throw console.error("Verify OTP error:",D),sessionStorage.removeItem(E_),sessionStorage.removeItem(Og),new Error("Failed to establish impersonation session")}return r(!0),i(N),Jt.success(`Now viewing as ${N.name}`),window.location.href="/dashboard",!0}catch(_){return console.error("Impersonation error:",_),Jt.error(_.message||"Failed to impersonate user"),sessionStorage.removeItem(E_),sessionStorage.removeItem(Og),!1}finally{c(!1)}},f=async()=>{c(!0);try{const m=sessionStorage.getItem(E_);if(!m){await Le.auth.signOut(),window.location.href="/auth";return}const x=JSON.parse(m);await Le.auth.signOut();const{error:_}=await Le.auth.setSession({access_token:x.access_token,refresh_token:x.refresh_token});if(sessionStorage.removeItem(E_),sessionStorage.removeItem(Og),_){console.error("Failed to restore admin session:",_),Jt.error("Admin session expired, please sign in again"),window.location.href="/auth";return}r(!1),i(null),Jt.success("Returned to your account");const T=sessionStorage.getItem(AB)||"/admin/members";sessionStorage.removeItem(AB),window.location.href=T}catch(m){console.error("Stop impersonation error:",m),Jt.error("Failed to restore admin session"),sessionStorage.removeItem(E_),sessionStorage.removeItem(Og),window.location.href="/auth"}finally{c(!1)}};return o.jsx(Lme.Provider,{value:{isImpersonating:e,impersonatedUser:n,startImpersonation:s,stopImpersonation:f,isLoading:a},children:t})},Dme=()=>{const t=P.useContext(Lme);if(t===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return t},uze=()=>{const{isImpersonating:t,impersonatedUser:e,stopImpersonation:r,isLoading:n}=Dme();return!t||!e?null:o.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:o.jsxs("div",{className:"container mx-auto flex items-center justify-between gap-4",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(CC,{className:"h-5 w-5 flex-shrink-0"}),o.jsxs("span",{className:"font-medium text-sm md:text-base",children:[o.jsx("span",{className:"hidden sm:inline",children:"You are viewing as "}),o.jsx("strong",{children:e.name}),o.jsxs("span",{className:"hidden md:inline text-amber-800",children:[" (",e.email,")"]})]})]}),o.jsx(Ut,{size:"sm",variant:"secondary",onClick:r,disabled:n,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:n?o.jsx(Cu,{className:"h-4 w-4 animate-spin"}):o.jsxs(o.Fragment,{children:[o.jsx(Ks,{className:"h-4 w-4 mr-1"}),o.jsx("span",{className:"hidden sm:inline",children:"Exit Impersonation"}),o.jsx("span",{className:"sm:hidden",children:"Exit"})]})})]})})},Ome=P.createContext(void 0),Lb="levelup_acting_as",fN="levelup_acting_as_self",dze=({children:t})=>{const{user:e}=qn(),[r,n]=P.useState(!1),[i,a]=P.useState([]),[c,s]=P.useState(null),[f,m]=P.useState({}),[x,_]=P.useState(!0),[T,E]=P.useState(()=>sessionStorage.getItem(fN)==="true");P.useEffect(()=>{if(!(e!=null&&e.id)){n(!1),a([]),s(null),m({}),_(!1);return}(async()=>{_(!0);try{const{data:B}=await Le.rpc("has_role",{_user_id:e.id,_role:"assistant"});if(!B){n(!1),a([]),s(null),m({}),_(!1);return}n(!0);const{data:V,error:G}=await Le.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",e.id);if(G||!V||V.length===0){a([]),_(!1);return}const W=V.map(re=>re.agent_id),{data:X}=await Le.from("profiles").select("id, name, email, avatar_url").in("id",W),Q=(X||[]).map(re=>({id:re.id,name:re.name||re.email||"Unknown",email:re.email||"",avatar_url:re.avatar_url}));if(a(Q),sessionStorage.getItem(fN)==="true")E(!0),s(null),m({});else{const re=sessionStorage.getItem(Lb);if(re){const se=Q.find(ue=>ue.id===re);if(se){s(se);const ue=V.find(_e=>_e.agent_id===re);m((ue==null?void 0:ue.permissions)||{})}else if(Q.length>0){s(Q[0]);const ue=V.find(_e=>_e.agent_id===Q[0].id);m((ue==null?void 0:ue.permissions)||{}),sessionStorage.setItem(Lb,Q[0].id)}}else if(Q.length>0){s(Q[0]);const se=V.find(ue=>ue.agent_id===Q[0].id);m((se==null?void 0:se.permissions)||{}),sessionStorage.setItem(Lb,Q[0].id)}}}catch(B){console.error("Error loading assistant data:",B)}finally{_(!1)}})()},[e==null?void 0:e.id]);const C=M=>{s(M),E(!1),sessionStorage.removeItem(fN),M?(sessionStorage.setItem(Lb,M.id),Le.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(e==null?void 0:e.id)||"").eq("agent_id",M.id).single().then(({data:B})=>{m((B==null?void 0:B.permissions)||{})})):(sessionStorage.removeItem(Lb),m({}))},N=()=>{E(!0),s(null),m({}),sessionStorage.setItem(fN,"true"),sessionStorage.removeItem(Lb)},R=M=>!r||T?!0:f[M]===!0,D=r&&c&&!T?c.id:(e==null?void 0:e.id)||null;return o.jsx(Ome.Provider,{value:{isAssistant:r,assignedAgents:i,actingAsAgent:c,setActingAsAgent:C,effectiveUserId:D,permissions:f,hasPermission:R,isLoading:x,isActingAsSelf:T,setActingAsSelf:N},children:t})},EM=()=>{const t=P.useContext(Ome);if(t===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return t},Ji=()=>{const{effectiveUserId:t}=EM();return t};var Mme={exports:{}},Fme={};/** * @license React * use-sync-external-store-shim.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var x1=P;function hze(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var fze=typeof Object.is=="function"?Object.is:hze,pze=x1.useState,mze=x1.useEffect,gze=x1.useLayoutEffect,yze=x1.useDebugValue;function xze(t,e){var r=e(),n=pze({inst:{value:r,getSnapshot:e}}),i=n[0].inst,a=n[1];return gze(function(){i.value=r,i.getSnapshot=e,kB(i)&&a({inst:i})},[t,r,e]),mze(function(){return kB(i)&&a({inst:i}),t(function(){kB(i)&&a({inst:i})})},[t]),yze(r),r}function kB(t){var e=t.getSnapshot;t=t.value;try{var r=e();return!fze(t,r)}catch{return!0}}function _ze(t,e){return e()}var vze=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?_ze:xze;Fme.useSyncExternalStore=x1.useSyncExternalStore!==void 0?x1.useSyncExternalStore:vze;Mme.exports=Fme;var bze=Mme.exports;function wze(){return bze.useSyncExternalStore(Sze,()=>!0,()=>!1)}function Sze(){return()=>{}}var JG="Avatar",[Tze,hUt]=Ho(JG),[Eze,Bme]=Tze(JG),zme=P.forwardRef((t,e)=>{const{__scopeAvatar:r,...n}=t,[i,a]=P.useState("idle");return o.jsx(Eze,{scope:r,imageLoadingStatus:i,onImageLoadingStatusChange:a,children:o.jsx(rn.span,{...n,ref:e})})});zme.displayName=JG;var $me="AvatarImage",Ume=P.forwardRef((t,e)=>{const{__scopeAvatar:r,src:n,onLoadingStatusChange:i=()=>{},...a}=t,c=Bme($me,r),s=Aze(n,a),f=fo(m=>{i(m),c.onImageLoadingStatusChange(m)});return Io(()=>{s!=="idle"&&f(s)},[s,f]),s==="loaded"?o.jsx(rn.img,{...a,ref:e,src:n}):null});Ume.displayName=$me;var Vme="AvatarFallback",qme=P.forwardRef((t,e)=>{const{__scopeAvatar:r,delayMs:n,...i}=t,a=Bme(Vme,r),[c,s]=P.useState(n===void 0);return P.useEffect(()=>{if(n!==void 0){const f=window.setTimeout(()=>s(!0),n);return()=>window.clearTimeout(f)}},[n]),c&&a.imageLoadingStatus!=="loaded"?o.jsx(rn.span,{...i,ref:e}):null});qme.displayName=Vme;function Ree(t,e){return t?e?(t.src!==e&&(t.src=e),t.complete&&t.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Aze(t,{referrerPolicy:e,crossOrigin:r}){const n=wze(),i=P.useRef(null),a=n?(i.current||(i.current=new window.Image),i.current):null,[c,s]=P.useState(()=>Ree(a,t));return Io(()=>{s(Ree(a,t))},[a,t]),Io(()=>{const f=_=>()=>{s(_)};if(!a)return;const m=f("loaded"),x=f("error");return a.addEventListener("load",m),a.addEventListener("error",x),e&&(a.referrerPolicy=e),typeof r=="string"&&(a.crossOrigin=r),()=>{a.removeEventListener("load",m),a.removeEventListener("error",x)}},[a,r,e]),c}var Gme=zme,Hme=Ume,Wme=qme;const Zd=P.forwardRef(({className:t,...e},r)=>o.jsx(Gme,{ref:r,className:sr("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...e}));Zd.displayName=Gme.displayName;const Xd=P.forwardRef(({className:t,...e},r)=>o.jsx(Hme,{ref:r,className:sr("aspect-square h-full w-full",t),...e}));Xd.displayName=Hme.displayName;const Qd=P.forwardRef(({className:t,...e},r)=>o.jsx(Wme,{ref:r,className:sr("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...e}));Qd.displayName=Wme.displayName;const kze=oS("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 us({className:t,variant:e,...r}){return o.jsx("div",{className:sr(kze({variant:e}),t),...r})}var Cze=P.createContext(void 0);function $0(t){const e=P.useContext(Cze);return t||e||"ltr"}var CB="rovingFocusGroup.onEntryFocus",jze={bubbles:!1,cancelable:!0},BC="RovingFocusGroup",[m6,Kme,Ize]=wC(BC),[Pze,bS]=Ho(BC,[Ize]),[Nze,Rze]=Pze(BC),Yme=P.forwardRef((t,e)=>o.jsx(m6.Provider,{scope:t.__scopeRovingFocusGroup,children:o.jsx(m6.Slot,{scope:t.__scopeRovingFocusGroup,children:o.jsx(Lze,{...t,ref:e})})}));Yme.displayName=BC;var Lze=P.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:r,orientation:n,loop:i=!1,dir:a,currentTabStopId:c,defaultCurrentTabStopId:s,onCurrentTabStopIdChange:f,onEntryFocus:m,preventScrollOnEntryFocus:x=!1,..._}=t,T=P.useRef(null),E=Wn(e,T),C=$0(a),[N,R]=ad({prop:c,defaultProp:s??null,onChange:f,caller:BC}),[D,M]=P.useState(!1),B=fo(m),V=Kme(r),G=P.useRef(!1),[W,X]=P.useState(0);return P.useEffect(()=>{const Q=T.current;if(Q)return Q.addEventListener(CB,B),()=>Q.removeEventListener(CB,B)},[B]),o.jsx(Nze,{scope:r,orientation:n,dir:C,loop:i,currentTabStopId:N,onItemFocus:P.useCallback(Q=>R(Q),[R]),onItemShiftTab:P.useCallback(()=>M(!0),[]),onFocusableItemAdd:P.useCallback(()=>X(Q=>Q+1),[]),onFocusableItemRemove:P.useCallback(()=>X(Q=>Q-1),[]),children:o.jsx(rn.div,{tabIndex:D||W===0?-1:0,"data-orientation":n,..._,ref:E,style:{outline:"none",...t.style},onMouseDown:Or(t.onMouseDown,()=>{G.current=!0}),onFocus:Or(t.onFocus,Q=>{const re=!G.current;if(Q.target===Q.currentTarget&&re&&!D){const se=new CustomEvent(CB,jze);if(Q.currentTarget.dispatchEvent(se),!se.defaultPrevented){const ue=V().filter(Ae=>Ae.focusable),_e=ue.find(Ae=>Ae.active),Se=ue.find(Ae=>Ae.id===N),Oe=[_e,Se,...ue].filter(Boolean).map(Ae=>Ae.ref.current);Qme(Oe,x)}}G.current=!1}),onBlur:Or(t.onBlur,()=>M(!1))})})}),Zme="RovingFocusGroupItem",Xme=P.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:r,focusable:n=!0,active:i=!1,tabStopId:a,children:c,...s}=t,f=Cl(),m=a||f,x=Rze(Zme,r),_=x.currentTabStopId===m,T=Kme(r),{onFocusableItemAdd:E,onFocusableItemRemove:C,currentTabStopId:N}=x;return P.useEffect(()=>{if(n)return E(),()=>C()},[n,E,C]),o.jsx(m6.ItemSlot,{scope:r,id:m,focusable:n,active:i,children:o.jsx(rn.span,{tabIndex:_?0:-1,"data-orientation":x.orientation,...s,ref:e,onMouseDown:Or(t.onMouseDown,R=>{n?x.onItemFocus(m):R.preventDefault()}),onFocus:Or(t.onFocus,()=>x.onItemFocus(m)),onKeyDown:Or(t.onKeyDown,R=>{if(R.key==="Tab"&&R.shiftKey){x.onItemShiftTab();return}if(R.target!==R.currentTarget)return;const D=Mze(R,x.orientation,x.dir);if(D!==void 0){if(R.metaKey||R.ctrlKey||R.altKey||R.shiftKey)return;R.preventDefault();let B=T().filter(V=>V.focusable).map(V=>V.ref.current);if(D==="last")B.reverse();else if(D==="prev"||D==="next"){D==="prev"&&B.reverse();const V=B.indexOf(R.currentTarget);B=x.loop?Fze(B,V+1):B.slice(V+1)}setTimeout(()=>Qme(B))}}),children:typeof c=="function"?c({isCurrentTabStop:_,hasTabStop:N!=null}):c})})});Xme.displayName=Zme;var Dze={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Oze(t,e){return e!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function Mze(t,e,r){const n=Oze(t.key,r);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(n))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(n)))return Dze[n]}function Qme(t,e=!1){const r=document.activeElement;for(const n of t)if(n===r||(n.focus({preventScroll:e}),document.activeElement!==r))return}function Fze(t,e){return t.map((r,n)=>t[(e+n)%t.length])}var e9=Yme,t9=Xme,g6=["Enter"," "],Bze=["ArrowDown","PageUp","Home"],Jme=["ArrowUp","PageDown","End"],zze=[...Bze,...Jme],$ze={ltr:[...g6,"ArrowRight"],rtl:[...g6,"ArrowLeft"]},Uze={ltr:["ArrowLeft"],rtl:["ArrowRight"]},zC="Menu",[lk,Vze,qze]=wC(zC),[U0,ege]=Ho(zC,[qze,nx,bS]),AM=nx(),tge=bS(),[Gze,V0]=U0(zC),[Hze,$C]=U0(zC),rge=t=>{const{__scopeMenu:e,open:r=!1,children:n,dir:i,onOpenChange:a,modal:c=!0}=t,s=AM(e),[f,m]=P.useState(null),x=P.useRef(!1),_=fo(a),T=$0(i);return P.useEffect(()=>{const E=()=>{x.current=!0,document.addEventListener("pointerdown",C,{capture:!0,once:!0}),document.addEventListener("pointermove",C,{capture:!0,once:!0})},C=()=>x.current=!1;return document.addEventListener("keydown",E,{capture:!0}),()=>{document.removeEventListener("keydown",E,{capture:!0}),document.removeEventListener("pointerdown",C,{capture:!0}),document.removeEventListener("pointermove",C,{capture:!0})}},[]),o.jsx(cM,{...s,children:o.jsx(Gze,{scope:e,open:r,onOpenChange:_,content:f,onContentChange:m,children:o.jsx(Hze,{scope:e,onClose:P.useCallback(()=>_(!1),[_]),isUsingKeyboardRef:x,dir:T,modal:c,children:n})})})};rge.displayName=zC;var Wze="MenuAnchor",r9=P.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t,i=AM(r);return o.jsx(OC,{...i,...n,ref:e})});r9.displayName=Wze;var n9="MenuPortal",[Kze,nge]=U0(n9,{forceMount:void 0}),ige=t=>{const{__scopeMenu:e,forceMount:r,children:n,container:i}=t,a=V0(n9,e);return o.jsx(Kze,{scope:e,forceMount:r,children:o.jsx(dl,{present:r||a.open,children:o.jsx(aS,{asChild:!0,container:i,children:n})})})};ige.displayName=n9;var qd="MenuContent",[Yze,i9]=U0(qd),sge=P.forwardRef((t,e)=>{const r=nge(qd,t.__scopeMenu),{forceMount:n=r.forceMount,...i}=t,a=V0(qd,t.__scopeMenu),c=$C(qd,t.__scopeMenu);return o.jsx(lk.Provider,{scope:t.__scopeMenu,children:o.jsx(dl,{present:n||a.open,children:o.jsx(lk.Slot,{scope:t.__scopeMenu,children:c.modal?o.jsx(Zze,{...i,ref:e}):o.jsx(Xze,{...i,ref:e})})})})}),Zze=P.forwardRef((t,e)=>{const r=V0(qd,t.__scopeMenu),n=P.useRef(null),i=Wn(e,n);return P.useEffect(()=>{const a=n.current;if(a)return rM(a)},[]),o.jsx(s9,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:Or(t.onFocusOutside,a=>a.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})}),Xze=P.forwardRef((t,e)=>{const r=V0(qd,t.__scopeMenu);return o.jsx(s9,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})}),Qze=Fy("MenuContent.ScrollLock"),s9=P.forwardRef((t,e)=>{const{__scopeMenu:r,loop:n=!1,trapFocus:i,onOpenAutoFocus:a,onCloseAutoFocus:c,disableOutsidePointerEvents:s,onEntryFocus:f,onEscapeKeyDown:m,onPointerDownOutside:x,onFocusOutside:_,onInteractOutside:T,onDismiss:E,disableOutsideScroll:C,...N}=t,R=V0(qd,r),D=$C(qd,r),M=AM(r),B=tge(r),V=Vze(r),[G,W]=P.useState(null),X=P.useRef(null),Q=Wn(e,X,R.onContentChange),re=P.useRef(0),se=P.useRef(""),ue=P.useRef(0),_e=P.useRef(null),Se=P.useRef("right"),ve=P.useRef(0),Oe=C?IC:P.Fragment,Ae=C?{as:Qze,allowPinchZoom:!0}:void 0,we=Ne=>{var _t,Vt;const Ie=se.current+Ne,Te=V().filter(mt=>!mt.disabled),be=document.activeElement,We=(_t=Te.find(mt=>mt.ref.current===be))==null?void 0:_t.textValue,rt=Te.map(mt=>mt.textValue),at=u$e(rt,Ie,We),Et=(Vt=Te.find(mt=>mt.textValue===at))==null?void 0:Vt.ref.current;(function mt(Pt){se.current=Pt,window.clearTimeout(re.current),Pt!==""&&(re.current=window.setTimeout(()=>mt(""),1e3))})(Ie),Et&&setTimeout(()=>Et.focus())};P.useEffect(()=>()=>window.clearTimeout(re.current),[]),eM();const ge=P.useCallback(Ne=>{var Te,be;return Se.current===((Te=_e.current)==null?void 0:Te.side)&&h$e(Ne,(be=_e.current)==null?void 0:be.area)},[]);return o.jsx(Yze,{scope:r,searchRef:se,onItemEnter:P.useCallback(Ne=>{ge(Ne)&&Ne.preventDefault()},[ge]),onItemLeave:P.useCallback(Ne=>{var Ie;ge(Ne)||((Ie=X.current)==null||Ie.focus(),W(null))},[ge]),onTriggerLeave:P.useCallback(Ne=>{ge(Ne)&&Ne.preventDefault()},[ge]),pointerGraceTimerRef:ue,onPointerGraceIntentChange:P.useCallback(Ne=>{_e.current=Ne},[]),children:o.jsx(Oe,{...Ae,children:o.jsx(jC,{asChild:!0,trapped:i,onMountAutoFocus:Or(a,Ne=>{var Ie;Ne.preventDefault(),(Ie=X.current)==null||Ie.focus({preventScroll:!0})}),onUnmountAutoFocus:c,children:o.jsx(F0,{asChild:!0,disableOutsidePointerEvents:s,onEscapeKeyDown:m,onPointerDownOutside:x,onFocusOutside:_,onInteractOutside:T,onDismiss:E,children:o.jsx(e9,{asChild:!0,...B,dir:D.dir,orientation:"vertical",loop:n,currentTabStopId:G,onCurrentTabStopIdChange:W,onEntryFocus:Or(f,Ne=>{D.isUsingKeyboardRef.current||Ne.preventDefault()}),preventScrollOnEntryFocus:!0,children:o.jsx(uM,{role:"menu","aria-orientation":"vertical","data-state":bge(R.open),"data-radix-menu-content":"",dir:D.dir,...M,...N,ref:Q,style:{outline:"none",...N.style},onKeyDown:Or(N.onKeyDown,Ne=>{const Te=Ne.target.closest("[data-radix-menu-content]")===Ne.currentTarget,be=Ne.ctrlKey||Ne.altKey||Ne.metaKey,We=Ne.key.length===1;Te&&(Ne.key==="Tab"&&Ne.preventDefault(),!be&&We&&we(Ne.key));const rt=X.current;if(Ne.target!==rt||!zze.includes(Ne.key))return;Ne.preventDefault();const Et=V().filter(_t=>!_t.disabled).map(_t=>_t.ref.current);Jme.includes(Ne.key)&&Et.reverse(),l$e(Et)}),onBlur:Or(t.onBlur,Ne=>{Ne.currentTarget.contains(Ne.target)||(window.clearTimeout(re.current),se.current="")}),onPointerMove:Or(t.onPointerMove,ck(Ne=>{const Ie=Ne.target,Te=ve.current!==Ne.clientX;if(Ne.currentTarget.contains(Ie)&&Te){const be=Ne.clientX>ve.current?"right":"left";Se.current=be,ve.current=Ne.clientX}}))})})})})})})});sge.displayName=qd;var Jze="MenuGroup",a9=P.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return o.jsx(rn.div,{role:"group",...n,ref:e})});a9.displayName=Jze;var e$e="MenuLabel",age=P.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return o.jsx(rn.div,{...n,ref:e})});age.displayName=e$e;var HL="MenuItem",Lee="menu.itemSelect",kM=P.forwardRef((t,e)=>{const{disabled:r=!1,onSelect:n,...i}=t,a=P.useRef(null),c=$C(HL,t.__scopeMenu),s=i9(HL,t.__scopeMenu),f=Wn(e,a),m=P.useRef(!1),x=()=>{const _=a.current;if(!r&&_){const T=new CustomEvent(Lee,{bubbles:!0,cancelable:!0});_.addEventListener(Lee,E=>n==null?void 0:n(E),{once:!0}),oG(_,T),T.defaultPrevented?m.current=!1:c.onClose()}};return o.jsx(oge,{...i,ref:f,disabled:r,onClick:Or(t.onClick,x),onPointerDown:_=>{var T;(T=t.onPointerDown)==null||T.call(t,_),m.current=!0},onPointerUp:Or(t.onPointerUp,_=>{var T;m.current||(T=_.currentTarget)==null||T.click()}),onKeyDown:Or(t.onKeyDown,_=>{const T=s.searchRef.current!=="";r||T&&_.key===" "||g6.includes(_.key)&&(_.currentTarget.click(),_.preventDefault())})})});kM.displayName=HL;var oge=P.forwardRef((t,e)=>{const{__scopeMenu:r,disabled:n=!1,textValue:i,...a}=t,c=i9(HL,r),s=tge(r),f=P.useRef(null),m=Wn(e,f),[x,_]=P.useState(!1),[T,E]=P.useState("");return P.useEffect(()=>{const C=f.current;C&&E((C.textContent??"").trim())},[a.children]),o.jsx(lk.ItemSlot,{scope:r,disabled:n,textValue:i??T,children:o.jsx(t9,{asChild:!0,...s,focusable:!n,children:o.jsx(rn.div,{role:"menuitem","data-highlighted":x?"":void 0,"aria-disabled":n||void 0,"data-disabled":n?"":void 0,...a,ref:m,onPointerMove:Or(t.onPointerMove,ck(C=>{n?c.onItemLeave(C):(c.onItemEnter(C),C.defaultPrevented||C.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Or(t.onPointerLeave,ck(C=>c.onItemLeave(C))),onFocus:Or(t.onFocus,()=>_(!0)),onBlur:Or(t.onBlur,()=>_(!1))})})})}),t$e="MenuCheckboxItem",lge=P.forwardRef((t,e)=>{const{checked:r=!1,onCheckedChange:n,...i}=t;return o.jsx(fge,{scope:t.__scopeMenu,checked:r,children:o.jsx(kM,{role:"menuitemcheckbox","aria-checked":WL(r)?"mixed":r,...i,ref:e,"data-state":l9(r),onSelect:Or(i.onSelect,()=>n==null?void 0:n(WL(r)?!0:!r),{checkForDefaultPrevented:!1})})})});lge.displayName=t$e;var cge="MenuRadioGroup",[r$e,n$e]=U0(cge,{value:void 0,onValueChange:()=>{}}),uge=P.forwardRef((t,e)=>{const{value:r,onValueChange:n,...i}=t,a=fo(n);return o.jsx(r$e,{scope:t.__scopeMenu,value:r,onValueChange:a,children:o.jsx(a9,{...i,ref:e})})});uge.displayName=cge;var dge="MenuRadioItem",hge=P.forwardRef((t,e)=>{const{value:r,...n}=t,i=n$e(dge,t.__scopeMenu),a=r===i.value;return o.jsx(fge,{scope:t.__scopeMenu,checked:a,children:o.jsx(kM,{role:"menuitemradio","aria-checked":a,...n,ref:e,"data-state":l9(a),onSelect:Or(n.onSelect,()=>{var c;return(c=i.onValueChange)==null?void 0:c.call(i,r)},{checkForDefaultPrevented:!1})})})});hge.displayName=dge;var o9="MenuItemIndicator",[fge,i$e]=U0(o9,{checked:!1}),pge=P.forwardRef((t,e)=>{const{__scopeMenu:r,forceMount:n,...i}=t,a=i$e(o9,r);return o.jsx(dl,{present:n||WL(a.checked)||a.checked===!0,children:o.jsx(rn.span,{...i,ref:e,"data-state":l9(a.checked)})})});pge.displayName=o9;var s$e="MenuSeparator",mge=P.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t;return o.jsx(rn.div,{role:"separator","aria-orientation":"horizontal",...n,ref:e})});mge.displayName=s$e;var a$e="MenuArrow",gge=P.forwardRef((t,e)=>{const{__scopeMenu:r,...n}=t,i=AM(r);return o.jsx(dM,{...i,...n,ref:e})});gge.displayName=a$e;var o$e="MenuSub",[fUt,yge]=U0(o$e),W2="MenuSubTrigger",xge=P.forwardRef((t,e)=>{const r=V0(W2,t.__scopeMenu),n=$C(W2,t.__scopeMenu),i=yge(W2,t.__scopeMenu),a=i9(W2,t.__scopeMenu),c=P.useRef(null),{pointerGraceTimerRef:s,onPointerGraceIntentChange:f}=a,m={__scopeMenu:t.__scopeMenu},x=P.useCallback(()=>{c.current&&window.clearTimeout(c.current),c.current=null},[]);return P.useEffect(()=>x,[x]),P.useEffect(()=>{const _=s.current;return()=>{window.clearTimeout(_),f(null)}},[s,f]),o.jsx(r9,{asChild:!0,...m,children:o.jsx(oge,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":i.contentId,"data-state":bge(r.open),...t,ref:jm(e,i.onTriggerChange),onClick:_=>{var T;(T=t.onClick)==null||T.call(t,_),!(t.disabled||_.defaultPrevented)&&(_.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:Or(t.onPointerMove,ck(_=>{a.onItemEnter(_),!_.defaultPrevented&&!t.disabled&&!r.open&&!c.current&&(a.onPointerGraceIntentChange(null),c.current=window.setTimeout(()=>{r.onOpenChange(!0),x()},100))})),onPointerLeave:Or(t.onPointerLeave,ck(_=>{var E,C;x();const T=(E=r.content)==null?void 0:E.getBoundingClientRect();if(T){const N=(C=r.content)==null?void 0:C.dataset.side,R=N==="right",D=R?-5:5,M=T[R?"left":"right"],B=T[R?"right":"left"];a.onPointerGraceIntentChange({area:[{x:_.clientX+D,y:_.clientY},{x:M,y:T.top},{x:B,y:T.top},{x:B,y:T.bottom},{x:M,y:T.bottom}],side:N}),window.clearTimeout(s.current),s.current=window.setTimeout(()=>a.onPointerGraceIntentChange(null),300)}else{if(a.onTriggerLeave(_),_.defaultPrevented)return;a.onPointerGraceIntentChange(null)}})),onKeyDown:Or(t.onKeyDown,_=>{var E;const T=a.searchRef.current!=="";t.disabled||T&&_.key===" "||$ze[n.dir].includes(_.key)&&(r.onOpenChange(!0),(E=r.content)==null||E.focus(),_.preventDefault())})})})});xge.displayName=W2;var _ge="MenuSubContent",vge=P.forwardRef((t,e)=>{const r=nge(qd,t.__scopeMenu),{forceMount:n=r.forceMount,...i}=t,a=V0(qd,t.__scopeMenu),c=$C(qd,t.__scopeMenu),s=yge(_ge,t.__scopeMenu),f=P.useRef(null),m=Wn(e,f);return o.jsx(lk.Provider,{scope:t.__scopeMenu,children:o.jsx(dl,{present:n||a.open,children:o.jsx(lk.Slot,{scope:t.__scopeMenu,children:o.jsx(s9,{id:s.contentId,"aria-labelledby":s.triggerId,...i,ref:m,align:"start",side:c.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:x=>{var _;c.isUsingKeyboardRef.current&&((_=f.current)==null||_.focus()),x.preventDefault()},onCloseAutoFocus:x=>x.preventDefault(),onFocusOutside:Or(t.onFocusOutside,x=>{x.target!==s.trigger&&a.onOpenChange(!1)}),onEscapeKeyDown:Or(t.onEscapeKeyDown,x=>{c.onClose(),x.preventDefault()}),onKeyDown:Or(t.onKeyDown,x=>{var E;const _=x.currentTarget.contains(x.target),T=Uze[c.dir].includes(x.key);_&&T&&(a.onOpenChange(!1),(E=s.trigger)==null||E.focus(),x.preventDefault())})})})})})});vge.displayName=_ge;function bge(t){return t?"open":"closed"}function WL(t){return t==="indeterminate"}function l9(t){return WL(t)?"indeterminate":t?"checked":"unchecked"}function l$e(t){const e=document.activeElement;for(const r of t)if(r===e||(r.focus(),document.activeElement!==e))return}function c$e(t,e){return t.map((r,n)=>t[(e+n)%t.length])}function u$e(t,e,r){const i=e.length>1&&Array.from(e).every(m=>m===e[0])?e[0]:e,a=r?t.indexOf(r):-1;let c=c$e(t,Math.max(a,0));i.length===1&&(c=c.filter(m=>m!==r));const f=c.find(m=>m.toLowerCase().startsWith(i.toLowerCase()));return f!==r?f:void 0}function d$e(t,e){const{x:r,y:n}=t;let i=!1;for(let a=0,c=e.length-1;an!=T>n&&r<(_-m)*(n-x)/(T-x)+m&&(i=!i)}return i}function h$e(t,e){if(!e)return!1;const r={x:t.clientX,y:t.clientY};return d$e(r,e)}function ck(t){return e=>e.pointerType==="mouse"?t(e):void 0}var f$e=rge,p$e=r9,m$e=ige,g$e=sge,y$e=a9,x$e=age,_$e=kM,v$e=lge,b$e=uge,w$e=hge,S$e=pge,T$e=mge,E$e=gge,A$e=xge,k$e=vge,CM="DropdownMenu",[C$e,pUt]=Ho(CM,[ege]),eu=ege(),[j$e,wge]=C$e(CM),Sge=t=>{const{__scopeDropdownMenu:e,children:r,dir:n,open:i,defaultOpen:a,onOpenChange:c,modal:s=!0}=t,f=eu(e),m=P.useRef(null),[x,_]=ad({prop:i,defaultProp:a??!1,onChange:c,caller:CM});return o.jsx(j$e,{scope:e,triggerId:Cl(),triggerRef:m,contentId:Cl(),open:x,onOpenChange:_,onOpenToggle:P.useCallback(()=>_(T=>!T),[_]),modal:s,children:o.jsx(f$e,{...f,open:x,onOpenChange:_,dir:n,modal:s,children:r})})};Sge.displayName=CM;var Tge="DropdownMenuTrigger",Ege=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,disabled:n=!1,...i}=t,a=wge(Tge,r),c=eu(r);return o.jsx(p$e,{asChild:!0,...c,children:o.jsx(rn.button,{type:"button",id:a.triggerId,"aria-haspopup":"menu","aria-expanded":a.open,"aria-controls":a.open?a.contentId:void 0,"data-state":a.open?"open":"closed","data-disabled":n?"":void 0,disabled:n,...i,ref:jm(e,a.triggerRef),onPointerDown:Or(t.onPointerDown,s=>{!n&&s.button===0&&s.ctrlKey===!1&&(a.onOpenToggle(),a.open||s.preventDefault())}),onKeyDown:Or(t.onKeyDown,s=>{n||(["Enter"," "].includes(s.key)&&a.onOpenToggle(),s.key==="ArrowDown"&&a.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(s.key)&&s.preventDefault())})})})});Ege.displayName=Tge;var I$e="DropdownMenuPortal",Age=t=>{const{__scopeDropdownMenu:e,...r}=t,n=eu(e);return o.jsx(m$e,{...n,...r})};Age.displayName=I$e;var kge="DropdownMenuContent",Cge=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=wge(kge,r),a=eu(r),c=P.useRef(!1);return o.jsx(g$e,{id:i.contentId,"aria-labelledby":i.triggerId,...a,...n,ref:e,onCloseAutoFocus:Or(t.onCloseAutoFocus,s=>{var f;c.current||(f=i.triggerRef.current)==null||f.focus(),c.current=!1,s.preventDefault()}),onInteractOutside:Or(t.onInteractOutside,s=>{const f=s.detail.originalEvent,m=f.button===0&&f.ctrlKey===!0,x=f.button===2||m;(!i.modal||x)&&(c.current=!0)}),style:{...t.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)"}})});Cge.displayName=kge;var P$e="DropdownMenuGroup",N$e=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=eu(r);return o.jsx(y$e,{...i,...n,ref:e})});N$e.displayName=P$e;var R$e="DropdownMenuLabel",jge=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=eu(r);return o.jsx(x$e,{...i,...n,ref:e})});jge.displayName=R$e;var L$e="DropdownMenuItem",Ige=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=eu(r);return o.jsx(_$e,{...i,...n,ref:e})});Ige.displayName=L$e;var D$e="DropdownMenuCheckboxItem",Pge=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=eu(r);return o.jsx(v$e,{...i,...n,ref:e})});Pge.displayName=D$e;var O$e="DropdownMenuRadioGroup",M$e=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=eu(r);return o.jsx(b$e,{...i,...n,ref:e})});M$e.displayName=O$e;var F$e="DropdownMenuRadioItem",Nge=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=eu(r);return o.jsx(w$e,{...i,...n,ref:e})});Nge.displayName=F$e;var B$e="DropdownMenuItemIndicator",Rge=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=eu(r);return o.jsx(S$e,{...i,...n,ref:e})});Rge.displayName=B$e;var z$e="DropdownMenuSeparator",Lge=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=eu(r);return o.jsx(T$e,{...i,...n,ref:e})});Lge.displayName=z$e;var $$e="DropdownMenuArrow",U$e=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=eu(r);return o.jsx(E$e,{...i,...n,ref:e})});U$e.displayName=$$e;var V$e="DropdownMenuSubTrigger",Dge=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=eu(r);return o.jsx(A$e,{...i,...n,ref:e})});Dge.displayName=V$e;var q$e="DropdownMenuSubContent",Oge=P.forwardRef((t,e)=>{const{__scopeDropdownMenu:r,...n}=t,i=eu(r);return o.jsx(k$e,{...i,...n,ref:e,style:{...t.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)"}})});Oge.displayName=q$e;var G$e=Sge,H$e=Ege,W$e=Age,Mge=Cge,Fge=jge,Bge=Ige,zge=Pge,$ge=Nge,Uge=Rge,Vge=Lge,qge=Dge,Gge=Oge;const UC=G$e,VC=H$e,K$e=P.forwardRef(({className:t,inset:e,children:r,...n},i)=>o.jsxs(qge,{ref:i,className:sr("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,o.jsx(th,{className:"ml-auto h-4 w-4"})]}));K$e.displayName=qge.displayName;const Y$e=P.forwardRef(({className:t,...e},r)=>o.jsx(Gge,{ref:r,className:sr("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}));Y$e.displayName=Gge.displayName;const wS=P.forwardRef(({className:t,sideOffset:e=4,...r},n)=>o.jsx(W$e,{children:o.jsx(Mge,{ref:n,sideOffset:e,className:sr("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})}));wS.displayName=Mge.displayName;const vu=P.forwardRef(({className:t,inset:e,...r},n)=>o.jsx(Bge,{ref:n,className:sr("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}));vu.displayName=Bge.displayName;const Z$e=P.forwardRef(({className:t,children:e,checked:r,...n},i)=>o.jsxs(zge,{ref:i,className:sr("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:[o.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:o.jsx(Uge,{children:o.jsx(Ao,{className:"h-4 w-4"})})}),e]}));Z$e.displayName=zge.displayName;const X$e=P.forwardRef(({className:t,children:e,...r},n)=>o.jsxs($ge,{ref:n,className:sr("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:[o.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:o.jsx(Uge,{children:o.jsx(d1,{className:"h-2 w-2 fill-current"})})}),e]}));X$e.displayName=$ge.displayName;const Hge=P.forwardRef(({className:t,inset:e,...r},n)=>o.jsx(Fge,{ref:n,className:sr("px-2 py-1.5 text-sm font-semibold",e&&"pl-8",t),...r}));Hge.displayName=Fge.displayName;const uk=P.forwardRef(({className:t,...e},r)=>o.jsx(Vge,{ref:r,className:sr("-mx-1 my-1 h-px bg-muted",t),...e}));uk.displayName=Vge.displayName;const Q$e=()=>{const{isAssistant:t,actingAsAgent:e,assignedAgents:r,setActingAsAgent:n,isActingAsSelf:i,setActingAsSelf:a}=EM();if(!t)return null;const c=s=>s.split(" ").map(f=>f[0]).join("").toUpperCase().slice(0,2);return o.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:o.jsxs("div",{className:"container mx-auto flex items-center justify-between gap-4 h-full",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[i?o.jsxs(o.Fragment,{children:[o.jsx(gc,{className:"h-4 w-4 flex-shrink-0"}),o.jsx("span",{className:"font-medium text-sm",children:"My Account"})]}):o.jsxs(o.Fragment,{children:[o.jsx(Al,{className:"h-4 w-4 flex-shrink-0"}),o.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),o.jsxs(UC,{children:[o.jsx(VC,{asChild:!0,children:o.jsxs(Ut,{variant:"secondary",size:"sm",className:"gap-2 bg-primary-foreground/20 hover:bg-primary-foreground/30 text-primary-foreground border-0",children:[i?o.jsxs(o.Fragment,{children:[o.jsx(gc,{className:"h-4 w-4"}),o.jsx("strong",{children:"My Account"})]}):e?o.jsxs(o.Fragment,{children:[o.jsxs(Zd,{className:"h-5 w-5",children:[o.jsx(Xd,{src:e.avatar_url||void 0}),o.jsx(Qd,{className:"text-[10px] bg-primary-foreground/30",children:c(e.name)})]}),o.jsx("strong",{children:e.name})]}):o.jsx("strong",{children:"Select..."}),o.jsx(od,{className:"h-3 w-3"})]})}),o.jsxs(wS,{align:"start",className:"z-[2147483647]",children:[o.jsxs(vu,{onClick:a,className:"gap-2",children:[o.jsx(gc,{className:"h-4 w-4"}),o.jsx("span",{children:"My Account"}),i&&o.jsx(us,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),o.jsx(uk,{}),r.map(s=>o.jsxs(vu,{onClick:()=>n(s),className:"gap-2",children:[o.jsxs(Zd,{className:"h-6 w-6",children:[o.jsx(Xd,{src:s.avatar_url||void 0}),o.jsx(Qd,{className:"text-[10px]",children:c(s.name)})]}),o.jsx("span",{children:s.name}),!i&&s.id===(e==null?void 0:e.id)&&o.jsx(us,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},s.id))]})]})]}),o.jsx(us,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:i?"Personal Mode":"Assistant Mode"})]})})};function Wge(){var f,m;const{user:t,isAdmin:e}=qn(),{data:r,isLoading:n}=wr({queryKey:["partnership-membership",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:x}=await Le.from("partnership_memberships").select("id, status, package_id, program_id").eq("user_id",t.id).eq("status","active").maybeSingle();if(!x)return null;const[{data:_},{data:T}]=await Promise.all([Le.from("partnership_packages").select("*").eq("id",x.package_id).maybeSingle(),Le.from("partnership_programs").select("id, name, enabled, brokerage_id").eq("id",x.program_id).maybeSingle()]);return!_||!(T!=null&&T.enabled)?null:{membership:x,pkg:_,program:T}}}),i=P.useMemo(()=>{var x;return new Set(((x=r==null?void 0:r.pkg)==null?void 0:x.included_features)||[])},[r]),a=!!r,c=x=>e||!a?!0:i.has(x),s=x=>{var E,C;const _=((E=r==null?void 0:r.pkg)==null?void 0:E.feature_limits)||{},T=(C=_==null?void 0:_[x])==null?void 0:C.monthly_limit;return typeof T=="number"?T: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:((f=r==null?void 0:r.pkg)==null?void 0:f.key)??null,packageName:((m=r==null?void 0:r.pkg)==null?void 0:m.name)??null,features:i,hasFeature:c,limitFor:s,isRestricted:a&&!e}}const c9={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"},mUt=Object.keys(c9),J$e={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},Dee={"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"},eUe={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 tUe(t){return t.id in Dee?Dee[t.id]:J$e[t.primaryCategory]??null}function gUt(t){return eUe[t]??null}const rUe=[["/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 nUe(t){let e=null;for(const r of rUe){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 Hn=P.forwardRef(({className:t,...e},r)=>o.jsx("div",{ref:r,className:sr("rounded-lg border bg-card text-card-foreground shadow-sm",t),...e}));Hn.displayName="Card";const Ju=P.forwardRef(({className:t,...e},r)=>o.jsx("div",{ref:r,className:sr("flex flex-col space-y-1.5 p-6",t),...e}));Ju.displayName="CardHeader";const ed=P.forwardRef(({className:t,...e},r)=>o.jsx("h3",{ref:r,className:sr("text-2xl font-semibold leading-none tracking-tight",t),...e}));ed.displayName="CardTitle";const dk=P.forwardRef(({className:t,...e},r)=>o.jsx("p",{ref:r,className:sr("text-sm text-muted-foreground",t),...e}));dk.displayName="CardDescription";const ii=P.forwardRef(({className:t,...e},r)=>o.jsx("div",{ref:r,className:sr("p-6 pt-0",t),...e}));ii.displayName="CardContent";const y6=P.forwardRef(({className:t,...e},r)=>o.jsx("div",{ref:r,className:sr("flex items-center p-6 pt-0",t),...e}));y6.displayName="CardFooter";const hd=P.forwardRef(({className:t,...e},r)=>o.jsx("textarea",{className:sr("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}));hd.displayName="Textarea";const ro=iM,Kge=TG,iUe=sM,yUt=RC,Yge=P.forwardRef(({className:t,...e},r)=>o.jsx(hS,{ref:r,className:sr("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}));Yge.displayName=hS.displayName;const $a=P.forwardRef(({className:t,children:e,overlayClassName:r,...n},i)=>o.jsxs(iUe,{children:[o.jsx(Yge,{className:r}),o.jsxs(fS,{ref:i,className:sr("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,o.jsxs(RC,{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:[o.jsx(Ks,{className:"h-4 w-4"}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));$a.displayName=fS.displayName;const ul=({className:t,...e})=>o.jsx("div",{className:sr("flex flex-col space-y-1.5 text-center sm:text-left",t),...e});ul.displayName="DialogHeader";const Zge=({className:t,...e})=>o.jsx("div",{className:sr("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});Zge.displayName="DialogFooter";const Go=P.forwardRef(({className:t,...e},r)=>o.jsx(PC,{ref:r,className:sr("text-lg font-semibold leading-none tracking-tight",t),...e}));Go.displayName=PC.displayName;const ld=P.forwardRef(({className:t,...e},r)=>o.jsx(NC,{ref:r,className:sr("text-sm text-muted-foreground",t),...e}));ld.displayName=NC.displayName;function sUe({featureKey:t,open:e,onOpenChange:r}){const{user:n}=qn(),i=Nr(),[a,c]=P.useState(""),{data:s}=wr({queryKey:["partnership-upgrade-requests",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&e,queryFn:async()=>{const{data:_}=await Le.from("lead_site_upgrade_requests").select("id, feature_key, status").eq("user_id",n.id);return _||[]}}),f=!!(s!=null&&s.some(_=>_.feature_key===t&&_.status!=="declined")),m=Cr({mutationFn:async()=>{const{error:_}=await Le.from("lead_site_upgrade_requests").insert({user_id:n.id,feature_key:t,notes:a||null});if(_)throw _},onSuccess:()=>{i.invalidateQueries({queryKey:["partnership-upgrade-requests"]}),Jt.success("Request sent — we'll be in touch shortly."),c(""),r(!1)},onError:_=>Jt.error((_==null?void 0:_.message)||"Could not send your request")}),x=c9[t]||t;return o.jsx(ro,{open:e,onOpenChange:r,children:o.jsxs($a,{className:"sm:max-w-md",children:[o.jsxs(ul,{children:[o.jsxs(Go,{className:"flex items-center gap-2",children:[o.jsx(Ss,{className:"h-5 w-5 text-primary"}),"Request ",x]}),o.jsxs(ld,{children:[x," is included with the Signature package. Send a request and we'll get you set up."]})]}),f?o.jsxs("div",{className:"rounded-lg border border-border bg-muted/40 p-4 text-sm flex items-start gap-2",children:[o.jsx(Ao,{className:"h-4 w-4 mt-0.5 text-primary"}),o.jsx("span",{children:"You've already requested this. We'll follow up soon."})]}):o.jsx(hd,{placeholder:"Anything we should know? (optional)",value:a,onChange:_=>c(_.target.value),rows:4}),o.jsxs(Zge,{children:[o.jsx(Ut,{variant:"outline",onClick:()=>r(!1),children:"Close"}),!f&&o.jsx(Ut,{onClick:()=>m.mutate(),disabled:m.isPending,children:m.isPending?"Sending…":"Send request"})]})]})})}function aUe({featureKey:t}){const[e,r]=P.useState(!1),n=c9[t]||t;return o.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[o.jsx(Hn,{className:"max-w-lg w-full border-border/60",children:o.jsxs(ii,{className:"p-8 text-center space-y-4",children:[o.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:o.jsx(zy,{className:"h-6 w-6 text-primary"})}),o.jsxs("h2",{className:"text-2xl font-semibold",children:[n," is a Signature feature"]}),o.jsxs("p",{className:"text-muted-foreground",children:["Your current package doesn't include ",n,". Request access and our team will upgrade your account."]}),o.jsxs(Ut,{onClick:()=>r(!0),className:"gap-2",children:[o.jsx(Ss,{className:"h-4 w-4"})," Request access"]})]})}),o.jsx(sUe,{featureKey:t,open:e,onOpenChange:r})]})}const oUe=t=>{const[e,r]=P.useState(null),[n,i]=P.useState(!0);return P.useEffect(()=>{if(!t){i(!1);return}(async()=>{try{const{data:s}=await Le.storage.from("avatars").list(`${t}`);if(s&&s.length>0){const{data:f}=Le.storage.from("avatars").getPublicUrl(`${t}/${s[0].name}`);r(`${f.publicUrl}?t=${Date.now()}`)}else r(null)}catch(s){console.error("Error fetching avatar:",s),r(null)}finally{i(!1)}})()},[t]),{avatarUrl:e,loading:n,refreshAvatar:async()=>{if(t)try{const{data:c}=await Le.storage.from("avatars").list(`${t}`);if(c&&c.length>0){const{data:s}=Le.storage.from("avatars").getPublicUrl(`${t}/${c[0].name}`);r(`${s.publicUrl}?t=${Date.now()}`)}}catch(c){console.error("Error refreshing avatar:",c)}}}},xUt=async t=>{const e=new Map;return await Promise.all(t.map(async r=>{try{const{data:n}=await Le.storage.from("avatars").list(`${r}`);if(n&&n.length>0){const{data:i}=Le.storage.from("avatars").getPublicUrl(`${r}/${n[0].name}`);e.set(r,i.publicUrl)}}catch{}})),e},lUe=t=>{const[e,r]=P.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return P.useEffect(()=>{if(!t){r(i=>({...i,loading:!1}));return}(async()=>{try{const{data:i,error:a}=await Le.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(_=>({..._,loading:!1}));return}const c=(i==null?void 0:i.subscription_status)==="trialing",s=!!(i!=null&&i.is_trial),f=!!(i!=null&&i.trial_expires_at)&&new Date(i.trial_expires_at).getTime()>Date.now()&&(i==null?void 0:i.subscription_status)!=="active",m=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||s||f)&&!!m&&m){const _=new Date().getTime(),T=new Date(m).getTime(),E=Math.ceil((T-_)/(1e3*60*60*24)),C=E<=0;r({isTrial:!0,isExpired:C,expiresAt:m,daysLeft:C?0:E,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},jM=()=>{const{data:t,isLoading:e}=wr({queryKey:["feature-flags"],queryFn:async()=>{const{data:n,error:i}=await Le.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")}},Oee="community_last_seen_post_at";function cUe(){const{user:t}=qn(),e=Wi(),[r,n]=P.useState(0),[i,a]=P.useState(null);P.useEffect(()=>{if(!t)return;const s=localStorage.getItem(`${Oee}_${t.id}`);a(s)},[t]),P.useEffect(()=>{if(!t)return;const s=`community_unread_count_${t.id}`,f=2*60*1e3;(async()=>{try{const E=sessionStorage.getItem(s);if(E){const C=JSON.parse(E);if(C.ts&&Date.now()-C.ts{if(!t)return;const s=Le.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async f=>{const m=f.new;if(m.user_id===t.id)return;const x=e.pathname==="/community";x||n(N=>N+1);const{data:_}=await Le.from("profiles").select("name").eq("id",m.user_id).single(),T=(_==null?void 0:_.name)||"Someone",E=m.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),C=E.length>50?E.substring(0,50)+"...":E;x||Jt("New Community Post",{description:`${T}: ${C}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{Le.removeChannel(s)}},[t,e.pathname]);const c=P.useCallback(()=>{if(!t)return;const s=new Date().toISOString();localStorage.setItem(`${Oee}_${t.id}`,s),a(s),n(0)},[t]);return P.useEffect(()=>{e.pathname==="/community"&&r>0&&c()},[e.pathname,r,c]),{unreadCount:r,markAsRead:c}}function uUe(){const{isAdmin:t}=qn(),{data:e=0}=wr({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:r,error:n}=await Le.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 jB=t=>`levelup:activeTeam:${t}`,dUe=()=>{const t=Ji();return wr({queryKey:["user-teams",t],queryFn:async()=>{const{data:e,error:r}=await Le.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 Le.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,s)=>{var f,m;return c.role!==s.role?c.role==="team_leader"?-1:1:(((f=c.team)==null?void 0:f.name)||"").localeCompare(((m=s.team)==null?void 0:m.name)||"")})},enabled:!!t,staleTime:5*60*1e3})},SS=()=>{const t=Ji(),e=dUe(),r=P.useMemo(()=>e.data||[],[e.data]),[n,i]=P.useState(()=>!t||typeof window>"u"?null:window.localStorage.getItem(jB(t)));P.useEffect(()=>{!t||typeof window>"u"||i(window.localStorage.getItem(jB(t)))},[t]);const a=P.useCallback(s=>{i(s),t&&typeof window<"u"&&window.localStorage.setItem(jB(t),s)},[t]),c=P.useMemo(()=>r.length?r.find(s=>s.teamId===n)||r[0]:null,[r,n]);return{...e,data:c,teams:r,activeTeamId:(c==null?void 0:c.teamId)??null,setActiveTeamId:a}},Mee="weekly_reels";function u9(){const{user:t,loading:e,isAdmin:r}=qn(),{data:n,isLoading:i}=wr({queryKey:["feature-entitlement",Mee,t==null?void 0:t.id],enabled:!!t&&!r,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:c}=await Le.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",t.id).eq("feature_key",Mee).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 Xge=iM,hUe=TG,fUe=sM,Qge=P.forwardRef(({className:t,...e},r)=>o.jsx(hS,{className:sr("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}));Qge.displayName=hS.displayName;const pUe=oS("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"}}),d9=P.forwardRef(({side:t="right",className:e,children:r,...n},i)=>o.jsxs(fUe,{children:[o.jsx(Qge,{}),o.jsxs(fS,{ref:i,className:sr(pUe({side:t}),e),...n,children:[r,o.jsxs(RC,{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:[o.jsx(Ks,{className:"h-4 w-4"}),o.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));d9.displayName=fS.displayName;const Jge=({className:t,...e})=>o.jsx("div",{className:sr("flex flex-col space-y-2 text-center sm:text-left",t),...e});Jge.displayName="SheetHeader";const mUe=({className:t,...e})=>o.jsx("div",{className:sr("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...e});mUe.displayName="SheetFooter";const eye=P.forwardRef(({className:t,...e},r)=>o.jsx(PC,{ref:r,className:sr("text-lg font-semibold text-foreground",t),...e}));eye.displayName=PC.displayName;const tye=P.forwardRef(({className:t,...e},r)=>o.jsx(NC,{ref:r,className:sr("text-sm text-muted-foreground",t),...e}));tye.displayName=NC.displayName;function hk(t,[e,r]){return Math.min(r,Math.max(e,t))}function gUe(t,e){return P.useReducer((r,n)=>e[r][n]??r,t)}var h9="ScrollArea",[rye,_Ut]=Ho(h9),[yUe,rh]=rye(h9),nye=P.forwardRef((t,e)=>{const{__scopeScrollArea:r,type:n="hover",dir:i,scrollHideDelay:a=600,...c}=t,[s,f]=P.useState(null),[m,x]=P.useState(null),[_,T]=P.useState(null),[E,C]=P.useState(null),[N,R]=P.useState(null),[D,M]=P.useState(0),[B,V]=P.useState(0),[G,W]=P.useState(!1),[X,Q]=P.useState(!1),re=Wn(e,ue=>f(ue)),se=$0(i);return o.jsx(yUe,{scope:r,type:n,dir:se,scrollHideDelay:a,scrollArea:s,viewport:m,onViewportChange:x,content:_,onContentChange:T,scrollbarX:E,onScrollbarXChange:C,scrollbarXEnabled:G,onScrollbarXEnabledChange:W,scrollbarY:N,onScrollbarYChange:R,scrollbarYEnabled:X,onScrollbarYEnabledChange:Q,onCornerWidthChange:M,onCornerHeightChange:V,children:o.jsx(rn.div,{dir:se,...c,ref:re,style:{position:"relative","--radix-scroll-area-corner-width":D+"px","--radix-scroll-area-corner-height":B+"px",...t.style}})})});nye.displayName=h9;var iye="ScrollAreaViewport",sye=P.forwardRef((t,e)=>{const{__scopeScrollArea:r,children:n,nonce:i,...a}=t,c=rh(iye,r),s=P.useRef(null),f=Wn(e,s,c.onViewportChange);return o.jsxs(o.Fragment,{children:[o.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:i}),o.jsx(rn.div,{"data-radix-scroll-area-viewport":"",...a,ref:f,style:{overflowX:c.scrollbarXEnabled?"scroll":"hidden",overflowY:c.scrollbarYEnabled?"scroll":"hidden",...t.style},children:o.jsx("div",{ref:c.onContentChange,style:{minWidth:"100%",display:"table"},children:n})})]})});sye.displayName=iye;var fp="ScrollAreaScrollbar",f9=P.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=rh(fp,t.__scopeScrollArea),{onScrollbarXEnabledChange:a,onScrollbarYEnabledChange:c}=i,s=t.orientation==="horizontal";return P.useEffect(()=>(s?a(!0):c(!0),()=>{s?a(!1):c(!1)}),[s,a,c]),i.type==="hover"?o.jsx(xUe,{...n,ref:e,forceMount:r}):i.type==="scroll"?o.jsx(_Ue,{...n,ref:e,forceMount:r}):i.type==="auto"?o.jsx(aye,{...n,ref:e,forceMount:r}):i.type==="always"?o.jsx(p9,{...n,ref:e}):null});f9.displayName=fp;var xUe=P.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=rh(fp,t.__scopeScrollArea),[a,c]=P.useState(!1);return P.useEffect(()=>{const s=i.scrollArea;let f=0;if(s){const m=()=>{window.clearTimeout(f),c(!0)},x=()=>{f=window.setTimeout(()=>c(!1),i.scrollHideDelay)};return s.addEventListener("pointerenter",m),s.addEventListener("pointerleave",x),()=>{window.clearTimeout(f),s.removeEventListener("pointerenter",m),s.removeEventListener("pointerleave",x)}}},[i.scrollArea,i.scrollHideDelay]),o.jsx(dl,{present:r||a,children:o.jsx(aye,{"data-state":a?"visible":"hidden",...n,ref:e})})}),_Ue=P.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=rh(fp,t.__scopeScrollArea),a=t.orientation==="horizontal",c=PM(()=>f("SCROLL_END"),100),[s,f]=gUe("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 P.useEffect(()=>{if(s==="idle"){const m=window.setTimeout(()=>f("HIDE"),i.scrollHideDelay);return()=>window.clearTimeout(m)}},[s,i.scrollHideDelay,f]),P.useEffect(()=>{const m=i.viewport,x=a?"scrollLeft":"scrollTop";if(m){let _=m[x];const T=()=>{const E=m[x];_!==E&&(f("SCROLL"),c()),_=E};return m.addEventListener("scroll",T),()=>m.removeEventListener("scroll",T)}},[i.viewport,a,f,c]),o.jsx(dl,{present:r||s!=="hidden",children:o.jsx(p9,{"data-state":s==="hidden"?"hidden":"visible",...n,ref:e,onPointerEnter:Or(t.onPointerEnter,()=>f("POINTER_ENTER")),onPointerLeave:Or(t.onPointerLeave,()=>f("POINTER_LEAVE"))})})}),aye=P.forwardRef((t,e)=>{const r=rh(fp,t.__scopeScrollArea),{forceMount:n,...i}=t,[a,c]=P.useState(!1),s=t.orientation==="horizontal",f=PM(()=>{if(r.viewport){const m=r.viewport.offsetWidth{const{orientation:r="vertical",...n}=t,i=rh(fp,t.__scopeScrollArea),a=P.useRef(null),c=P.useRef(0),[s,f]=P.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),m=dye(s.viewport,s.content),x={...n,sizes:s,onSizesChange:f,hasThumb:m>0&&m<1,onThumbChange:T=>a.current=T,onThumbPointerUp:()=>c.current=0,onThumbPointerDown:T=>c.current=T};function _(T,E){return EUe(T,c.current,s,E)}return r==="horizontal"?o.jsx(vUe,{...x,ref:e,onThumbPositionChange:()=>{if(i.viewport&&a.current){const T=i.viewport.scrollLeft,E=Fee(T,s,i.dir);a.current.style.transform=`translate3d(${E}px, 0, 0)`}},onWheelScroll:T=>{i.viewport&&(i.viewport.scrollLeft=T)},onDragScroll:T=>{i.viewport&&(i.viewport.scrollLeft=_(T,i.dir))}}):r==="vertical"?o.jsx(bUe,{...x,ref:e,onThumbPositionChange:()=>{if(i.viewport&&a.current){const T=i.viewport.scrollTop,E=Fee(T,s);a.current.style.transform=`translate3d(0, ${E}px, 0)`}},onWheelScroll:T=>{i.viewport&&(i.viewport.scrollTop=T)},onDragScroll:T=>{i.viewport&&(i.viewport.scrollTop=_(T))}}):null}),vUe=P.forwardRef((t,e)=>{const{sizes:r,onSizesChange:n,...i}=t,a=rh(fp,t.__scopeScrollArea),[c,s]=P.useState(),f=P.useRef(null),m=Wn(e,f,a.onScrollbarXChange);return P.useEffect(()=>{f.current&&s(getComputedStyle(f.current))},[f]),o.jsx(lye,{"data-orientation":"horizontal",...i,ref:m,sizes:r,style:{bottom:0,left:a.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:a.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":IM(r)+"px",...t.style},onThumbPointerDown:x=>t.onThumbPointerDown(x.x),onDragScroll:x=>t.onDragScroll(x.x),onWheelScroll:(x,_)=>{if(a.viewport){const T=a.viewport.scrollLeft+x.deltaX;t.onWheelScroll(T),fye(T,_)&&x.preventDefault()}},onResize:()=>{f.current&&a.viewport&&c&&n({content:a.viewport.scrollWidth,viewport:a.viewport.offsetWidth,scrollbar:{size:f.current.clientWidth,paddingStart:YL(c.paddingLeft),paddingEnd:YL(c.paddingRight)}})}})}),bUe=P.forwardRef((t,e)=>{const{sizes:r,onSizesChange:n,...i}=t,a=rh(fp,t.__scopeScrollArea),[c,s]=P.useState(),f=P.useRef(null),m=Wn(e,f,a.onScrollbarYChange);return P.useEffect(()=>{f.current&&s(getComputedStyle(f.current))},[f]),o.jsx(lye,{"data-orientation":"vertical",...i,ref:m,sizes:r,style:{top:0,right:a.dir==="ltr"?0:void 0,left:a.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":IM(r)+"px",...t.style},onThumbPointerDown:x=>t.onThumbPointerDown(x.y),onDragScroll:x=>t.onDragScroll(x.y),onWheelScroll:(x,_)=>{if(a.viewport){const T=a.viewport.scrollTop+x.deltaY;t.onWheelScroll(T),fye(T,_)&&x.preventDefault()}},onResize:()=>{f.current&&a.viewport&&c&&n({content:a.viewport.scrollHeight,viewport:a.viewport.offsetHeight,scrollbar:{size:f.current.clientHeight,paddingStart:YL(c.paddingTop),paddingEnd:YL(c.paddingBottom)}})}})}),[wUe,oye]=rye(fp),lye=P.forwardRef((t,e)=>{const{__scopeScrollArea:r,sizes:n,hasThumb:i,onThumbChange:a,onThumbPointerUp:c,onThumbPointerDown:s,onThumbPositionChange:f,onDragScroll:m,onWheelScroll:x,onResize:_,...T}=t,E=rh(fp,r),[C,N]=P.useState(null),R=Wn(e,re=>N(re)),D=P.useRef(null),M=P.useRef(""),B=E.viewport,V=n.content-n.viewport,G=fo(x),W=fo(f),X=PM(_,10);function Q(re){if(D.current){const se=re.clientX-D.current.left,ue=re.clientY-D.current.top;m({x:se,y:ue})}}return P.useEffect(()=>{const re=se=>{const ue=se.target;(C==null?void 0:C.contains(ue))&&G(se,V)};return document.addEventListener("wheel",re,{passive:!1}),()=>document.removeEventListener("wheel",re,{passive:!1})},[B,C,V,G]),P.useEffect(W,[n,W]),_1(C,X),_1(E.content,X),o.jsx(wUe,{scope:r,scrollbar:C,hasThumb:i,onThumbChange:fo(a),onThumbPointerUp:fo(c),onThumbPositionChange:W,onThumbPointerDown:fo(s),children:o.jsx(rn.div,{...T,ref:R,style:{position:"absolute",...T.style},onPointerDown:Or(t.onPointerDown,re=>{re.button===0&&(re.target.setPointerCapture(re.pointerId),D.current=C.getBoundingClientRect(),M.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",E.viewport&&(E.viewport.style.scrollBehavior="auto"),Q(re))}),onPointerMove:Or(t.onPointerMove,Q),onPointerUp:Or(t.onPointerUp,re=>{const se=re.target;se.hasPointerCapture(re.pointerId)&&se.releasePointerCapture(re.pointerId),document.body.style.webkitUserSelect=M.current,E.viewport&&(E.viewport.style.scrollBehavior=""),D.current=null})})})}),KL="ScrollAreaThumb",cye=P.forwardRef((t,e)=>{const{forceMount:r,...n}=t,i=oye(KL,t.__scopeScrollArea);return o.jsx(dl,{present:r||i.hasThumb,children:o.jsx(SUe,{ref:e,...n})})}),SUe=P.forwardRef((t,e)=>{const{__scopeScrollArea:r,style:n,...i}=t,a=rh(KL,r),c=oye(KL,r),{onThumbPositionChange:s}=c,f=Wn(e,_=>c.onThumbChange(_)),m=P.useRef(void 0),x=PM(()=>{m.current&&(m.current(),m.current=void 0)},100);return P.useEffect(()=>{const _=a.viewport;if(_){const T=()=>{if(x(),!m.current){const E=AUe(_,s);m.current=E,s()}};return s(),_.addEventListener("scroll",T),()=>_.removeEventListener("scroll",T)}},[a.viewport,x,s]),o.jsx(rn.div,{"data-state":c.hasThumb?"visible":"hidden",...i,ref:f,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...n},onPointerDownCapture:Or(t.onPointerDownCapture,_=>{const E=_.target.getBoundingClientRect(),C=_.clientX-E.left,N=_.clientY-E.top;c.onThumbPointerDown({x:C,y:N})}),onPointerUp:Or(t.onPointerUp,c.onThumbPointerUp)})});cye.displayName=KL;var m9="ScrollAreaCorner",uye=P.forwardRef((t,e)=>{const r=rh(m9,t.__scopeScrollArea),n=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&n?o.jsx(TUe,{...t,ref:e}):null});uye.displayName=m9;var TUe=P.forwardRef((t,e)=>{const{__scopeScrollArea:r,...n}=t,i=rh(m9,r),[a,c]=P.useState(0),[s,f]=P.useState(0),m=!!(a&&s);return _1(i.scrollbarX,()=>{var _;const x=((_=i.scrollbarX)==null?void 0:_.offsetHeight)||0;i.onCornerHeightChange(x),f(x)}),_1(i.scrollbarY,()=>{var _;const x=((_=i.scrollbarY)==null?void 0:_.offsetWidth)||0;i.onCornerWidthChange(x),c(x)}),m?o.jsx(rn.div,{...n,ref:e,style:{width:a,height:s,position:"absolute",right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:0,...t.style}}):null});function YL(t){return t?parseInt(t,10):0}function dye(t,e){const r=t/e;return isNaN(r)?0:r}function IM(t){const e=dye(t.viewport,t.content),r=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,n=(t.scrollbar.size-r)*e;return Math.max(n,18)}function EUe(t,e,r,n="ltr"){const i=IM(r),a=i/2,c=e||a,s=i-c,f=r.scrollbar.paddingStart+c,m=r.scrollbar.size-r.scrollbar.paddingEnd-s,x=r.content-r.viewport,_=n==="ltr"?[0,x]:[x*-1,0];return hye([f,m],_)(t)}function Fee(t,e,r="ltr"){const n=IM(e),i=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,a=e.scrollbar.size-i,c=e.content-e.viewport,s=a-n,f=r==="ltr"?[0,c]:[c*-1,0],m=hk(t,f);return hye([0,c],[0,s])(m)}function hye(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])}}function fye(t,e){return t>0&&t{})=>{let r={left:t.scrollLeft,top:t.scrollTop},n=0;return function i(){const a={left:t.scrollLeft,top:t.scrollTop},c=r.left!==a.left,s=r.top!==a.top;(c||s)&&e(),r=a,n=window.requestAnimationFrame(i)}(),()=>window.cancelAnimationFrame(n)};function PM(t,e){const r=fo(t),n=P.useRef(0);return P.useEffect(()=>()=>window.clearTimeout(n.current),[]),P.useCallback(()=>{window.clearTimeout(n.current),n.current=window.setTimeout(r,e)},[r,e])}function _1(t,e){const r=fo(e);Io(()=>{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])}var pye=nye,kUe=sye,CUe=uye;const pp=P.forwardRef(({className:t,children:e,...r},n)=>o.jsxs(pye,{ref:n,className:sr("relative overflow-hidden",t),...r,children:[o.jsx(kUe,{className:"h-full w-full rounded-[inherit]",children:e}),o.jsx(mye,{}),o.jsx(CUe,{})]}));pp.displayName=pye.displayName;const mye=P.forwardRef(({className:t,orientation:e="vertical",...r},n)=>o.jsx(f9,{ref:n,orientation:e,className:sr("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:o.jsx(cye,{className:"relative flex-1 rounded-full bg-border"})}));mye.displayName=f9.displayName;const jUe="/assets/levelup-logo-Eif24dqY.png",IUe="/assets/levelup-logo-icon-C-7iromj.png",PUe="/assets/levelup-logo-mobile-B9skSjUG.png";var qC=t=>t.type==="checkbox",W_=t=>t instanceof Date,$c=t=>t==null;const gye=t=>typeof t=="object";var jo=t=>!$c(t)&&!Array.isArray(t)&&gye(t)&&!W_(t),yye=t=>jo(t)&&t.target?qC(t.target)?t.target.checked:t.target.value:t,NUe=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,xye=(t,e)=>t.has(NUe(e)),RUe=t=>{const e=t.constructor&&t.constructor.prototype;return jo(e)&&e.hasOwnProperty("isPrototypeOf")},g9=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function el(t){let e;const r=Array.isArray(t),n=typeof FileList<"u"?t instanceof FileList:!1;if(t instanceof Date)e=new Date(t);else if(!(g9&&(t instanceof Blob||n))&&(r||jo(t)))if(e=r?[]:{},!r&&!RUe(t))e=t;else for(const i in t)t.hasOwnProperty(i)&&(e[i]=el(t[i]));else return t;return e}var NM=t=>/^\w*$/.test(t),wo=t=>t===void 0,y9=t=>Array.isArray(t)?t.filter(Boolean):[],x9=t=>y9(t.replace(/["|']|\]/g,"").split(/\.|\[/)),dn=(t,e,r)=>{if(!e||!jo(t))return r;const n=(NM(e)?[e]:x9(e)).reduce((i,a)=>$c(i)?i:i[a],t);return wo(n)||n===t?wo(t[e])?r:t[e]:n},Ku=t=>typeof t=="boolean",Ms=(t,e,r)=>{let n=-1;const i=NM(e)?[e]:x9(e),a=i.length,c=a-1;for(;++nXe.useContext(_9),LUe=t=>{const{children:e,...r}=t;return Xe.createElement(_9.Provider,{value:r},e)};var _ye=(t,e,r,n=!0)=>{const i={defaultValues:e._defaultValues};for(const a in t)Object.defineProperty(i,a,{get:()=>{const c=a;return e._proxyFormState[c]!==zh.all&&(e._proxyFormState[c]=!n||zh.all),r&&(r[c]=!0),t[c]}});return i};const v9=typeof window<"u"?Xe.useLayoutEffect:Xe.useEffect;function DUe(t){const e=RM(),{control:r=e.control,disabled:n,name:i,exact:a}=t||{},[c,s]=Xe.useState(r._formState),f=Xe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return v9(()=>r._subscribe({name:i,formState:f.current,exact:a,callback:m=>{!n&&s({...r._formState,...m})}}),[i,n,a]),Xe.useEffect(()=>{f.current.isValid&&r._setValid(!0)},[r]),Xe.useMemo(()=>_ye(c,r,f.current,!1),[c,r])}var qf=t=>typeof t=="string",vye=(t,e,r,n,i)=>qf(t)?(n&&e.watch.add(t),dn(r,t,i)):Array.isArray(t)?t.map(a=>(n&&e.watch.add(a),dn(r,a))):(n&&(e.watchAll=!0),r),x6=t=>$c(t)||!gye(t);function um(t,e,r=new WeakSet){if(x6(t)||x6(e))return t===e;if(W_(t)&&W_(e))return t.getTime()===e.getTime();const n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;if(r.has(t)||r.has(e))return!0;r.add(t),r.add(e);for(const a of n){const c=t[a];if(!i.includes(a))return!1;if(a!=="ref"){const s=e[a];if(W_(c)&&W_(s)||jo(c)&&jo(s)||Array.isArray(c)&&Array.isArray(s)?!um(c,s,r):c!==s)return!1}}return!0}function OUe(t){const e=RM(),{control:r=e.control,name:n,defaultValue:i,disabled:a,exact:c,compute:s}=t||{},f=Xe.useRef(i),m=Xe.useRef(s),x=Xe.useRef(void 0);m.current=s;const _=Xe.useMemo(()=>r._getWatch(n,f.current),[r,n]),[T,E]=Xe.useState(m.current?m.current(_):_);return v9(()=>r._subscribe({name:n,formState:{values:!0},exact:c,callback:C=>{if(!a){const N=vye(n,r._names,C.values||r._formValues,!1,f.current);if(m.current){const R=m.current(N);um(R,x.current)||(E(R),x.current=R)}else E(N)}}}),[r,a,n,c]),Xe.useEffect(()=>r._removeUnmounted()),T}function MUe(t){const e=RM(),{name:r,disabled:n,control:i=e.control,shouldUnregister:a,defaultValue:c}=t,s=xye(i._names.array,r),f=Xe.useMemo(()=>dn(i._formValues,r,dn(i._defaultValues,r,c)),[i,r,c]),m=OUe({control:i,name:r,defaultValue:f,exact:!0}),x=DUe({control:i,name:r,exact:!0}),_=Xe.useRef(t),T=Xe.useRef(i.register(r,{...t.rules,value:m,...Ku(t.disabled)?{disabled:t.disabled}:{}}));_.current=t;const E=Xe.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!dn(x.errors,r)},isDirty:{enumerable:!0,get:()=>!!dn(x.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!dn(x.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!dn(x.validatingFields,r)},error:{enumerable:!0,get:()=>dn(x.errors,r)}}),[x,r]),C=Xe.useCallback(M=>T.current.onChange({target:{value:yye(M),name:r},type:ZL.CHANGE}),[r]),N=Xe.useCallback(()=>T.current.onBlur({target:{value:dn(i._formValues,r),name:r},type:ZL.BLUR}),[r,i._formValues]),R=Xe.useCallback(M=>{const B=dn(i._fields,r);B&&M&&(B._f.ref={focus:()=>M.focus&&M.focus(),select:()=>M.select&&M.select(),setCustomValidity:V=>M.setCustomValidity(V),reportValidity:()=>M.reportValidity()})},[i._fields,r]),D=Xe.useMemo(()=>({name:r,value:m,...Ku(n)||x.disabled?{disabled:x.disabled||n}:{},onChange:C,onBlur:N,ref:R}),[r,n,x.disabled,C,N,R,m]);return Xe.useEffect(()=>{const M=i._options.shouldUnregister||a;i.register(r,{..._.current.rules,...Ku(_.current.disabled)?{disabled:_.current.disabled}:{}});const B=(V,G)=>{const W=dn(i._fields,V);W&&W._f&&(W._f.mount=G)};if(B(r,!0),M){const V=el(dn(i._options.defaultValues,r));Ms(i._defaultValues,r,V),wo(dn(i._formValues,r))&&Ms(i._formValues,r,V)}return!s&&i.register(r),()=>{(s?M&&!i._state.action:M)?i.unregister(r):B(r,!1)}},[r,i,s,a]),Xe.useEffect(()=>{i._setDisabledField({disabled:n,name:r})},[n,r,i]),Xe.useMemo(()=>({field:D,formState:x,fieldState:E}),[D,x,E])}const FUe=t=>t.render(MUe(t));var bye=(t,e,r,n,i)=>e?{...r[t],types:{...r[t]&&r[t].types?r[t].types:{},[n]:i||!0}}:{},mA=t=>Array.isArray(t)?t:[t],Bee=()=>{let t=[];return{get observers(){return t},next:i=>{for(const a of t)a.next&&a.next(i)},subscribe:i=>(t.push(i),{unsubscribe:()=>{t=t.filter(a=>a!==i)}}),unsubscribe:()=>{t=[]}}},gu=t=>jo(t)&&!Object.keys(t).length,b9=t=>t.type==="file",$h=t=>typeof t=="function",XL=t=>{if(!g9)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},wye=t=>t.type==="select-multiple",w9=t=>t.type==="radio",BUe=t=>w9(t)||qC(t),IB=t=>XL(t)&&t.isConnected;function zUe(t,e){const r=e.slice(0,-1).length;let n=0;for(;n{for(const e in t)if($h(t[e]))return!0;return!1};function QL(t,e={}){const r=Array.isArray(t);if(jo(t)||r)for(const n in t)Array.isArray(t[n])||jo(t[n])&&!Sye(t[n])?(e[n]=Array.isArray(t[n])?[]:{},QL(t[n],e[n])):$c(t[n])||(e[n]=!0);return e}function Tye(t,e,r){const n=Array.isArray(t);if(jo(t)||n)for(const i in t)Array.isArray(t[i])||jo(t[i])&&!Sye(t[i])?wo(e)||x6(r[i])?r[i]=Array.isArray(t[i])?QL(t[i],[]):{...QL(t[i])}:Tye(t[i],$c(e)?{}:e[i],r[i]):r[i]=!um(t[i],e[i]);return r}var g2=(t,e)=>Tye(t,e,QL(e));const zee={value:!1,isValid:!1},$ee={value:!0,isValid:!0};var Eye=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!wo(t[0].attributes.value)?wo(t[0].value)||t[0].value===""?$ee:{value:t[0].value,isValid:!0}:$ee:zee}return zee},Aye=(t,{valueAsNumber:e,valueAsDate:r,setValueAs:n})=>wo(t)?t:e?t===""?NaN:t&&+t:r&&qf(t)?new Date(t):n?n(t):t;const Uee={isValid:!1,value:null};var kye=t=>Array.isArray(t)?t.reduce((e,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:e,Uee):Uee;function Vee(t){const e=t.ref;return b9(e)?e.files:w9(e)?kye(t.refs).value:wye(e)?[...e.selectedOptions].map(({value:r})=>r):qC(e)?Eye(t.refs).value:Aye(wo(e.value)?t.ref.value:e.value,t)}var UUe=(t,e,r,n)=>{const i={};for(const a of t){const c=dn(e,a);c&&Ms(i,a,c._f)}return{criteriaMode:r,names:[...t],fields:i,shouldUseNativeValidation:n}},JL=t=>t instanceof RegExp,y2=t=>wo(t)?t:JL(t)?t.source:jo(t)?JL(t.value)?t.value.source:t.value:t,qee=t=>({isOnSubmit:!t||t===zh.onSubmit,isOnBlur:t===zh.onBlur,isOnChange:t===zh.onChange,isOnAll:t===zh.all,isOnTouch:t===zh.onTouched});const Gee="AsyncFunction";var VUe=t=>!!t&&!!t.validate&&!!($h(t.validate)&&t.validate.constructor.name===Gee||jo(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===Gee)),qUe=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),Hee=(t,e,r)=>!r&&(e.watchAll||e.watch.has(t)||[...e.watch].some(n=>t.startsWith(n)&&/^\.\w+/.test(t.slice(n.length))));const gA=(t,e,r,n)=>{for(const i of r||Object.keys(t)){const a=dn(t,i);if(a){const{_f:c,...s}=a;if(c){if(c.refs&&c.refs[0]&&e(c.refs[0],i)&&!n)return!0;if(c.ref&&e(c.ref,c.name)&&!n)return!0;if(gA(s,e))break}else if(jo(s)&&gA(s,e))break}}};function Wee(t,e,r){const n=dn(t,r);if(n||NM(r))return{error:n,name:r};const i=r.split(".");for(;i.length;){const a=i.join("."),c=dn(e,a),s=dn(t,a);if(c&&!Array.isArray(c)&&r!==a)return{name:r};if(s&&s.type)return{name:a,error:s};if(s&&s.root&&s.root.type)return{name:`${a}.root`,error:s.root};i.pop()}return{name:r}}var GUe=(t,e,r,n)=>{r(t);const{name:i,...a}=t;return gu(a)||Object.keys(a).length>=Object.keys(e).length||Object.keys(a).find(c=>e[c]===(!n||zh.all))},HUe=(t,e,r)=>!t||!e||t===e||mA(t).some(n=>n&&(r?n===e:n.startsWith(e)||e.startsWith(n))),WUe=(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,KUe=(t,e)=>!y9(dn(t,e)).length&&Oo(t,e),YUe=(t,e,r)=>{const n=mA(dn(t,r));return Ms(n,"root",e[r]),Ms(t,r,n),t},IR=t=>qf(t);function Kee(t,e,r="validate"){if(IR(t)||Array.isArray(t)&&t.every(IR)||Ku(t)&&!t)return{type:r,message:IR(t)?t:"",ref:e}}var Db=t=>jo(t)&&!JL(t)?t:{value:t,message:""},Yee=async(t,e,r,n,i,a)=>{const{ref:c,refs:s,required:f,maxLength:m,minLength:x,min:_,max:T,pattern:E,validate:C,name:N,valueAsNumber:R,mount:D}=t._f,M=dn(r,N);if(!D||e.has(N))return{};const B=s?s[0]:c,V=_e=>{i&&B.reportValidity&&(B.setCustomValidity(Ku(_e)?"":_e||""),B.reportValidity())},G={},W=w9(c),X=qC(c),Q=W||X,re=(R||b9(c))&&wo(c.value)&&wo(M)||XL(c)&&c.value===""||M===""||Array.isArray(M)&&!M.length,se=bye.bind(null,N,n,G),ue=(_e,Se,ve,Oe=Yp.maxLength,Ae=Yp.minLength)=>{const we=_e?Se:ve;G[N]={type:_e?Oe:Ae,message:we,ref:c,...se(_e?Oe:Ae,we)}};if(a?!Array.isArray(M)||!M.length:f&&(!Q&&(re||$c(M))||Ku(M)&&!M||X&&!Eye(s).isValid||W&&!kye(s).isValid)){const{value:_e,message:Se}=IR(f)?{value:!!f,message:f}:Db(f);if(_e&&(G[N]={type:Yp.required,message:Se,ref:B,...se(Yp.required,Se)},!n))return V(Se),G}if(!re&&(!$c(_)||!$c(T))){let _e,Se;const ve=Db(T),Oe=Db(_);if(!$c(M)&&!isNaN(M)){const Ae=c.valueAsNumber||M&&+M;$c(ve.value)||(_e=Ae>ve.value),$c(Oe.value)||(Se=Aenew Date(new Date().toDateString()+" "+Ie),ge=c.type=="time",Ne=c.type=="week";qf(ve.value)&&M&&(_e=ge?we(M)>we(ve.value):Ne?M>ve.value:Ae>new Date(ve.value)),qf(Oe.value)&&M&&(Se=ge?we(M)+_e.value,Oe=!$c(Se.value)&&M.length<+Se.value;if((ve||Oe)&&(ue(ve,_e.message,Se.message),!n))return V(G[N].message),G}if(E&&!re&&qf(M)){const{value:_e,message:Se}=Db(E);if(JL(_e)&&!M.match(_e)&&(G[N]={type:Yp.pattern,message:Se,ref:c,...se(Yp.pattern,Se)},!n))return V(Se),G}if(C){if($h(C)){const _e=await C(M,r),Se=Kee(_e,B);if(Se&&(G[N]={...Se,...se(Yp.validate,Se.message)},!n))return V(Se.message),G}else if(jo(C)){let _e={};for(const Se in C){if(!gu(_e)&&!n)break;const ve=Kee(await C[Se](M,r),B,Se);ve&&(_e={...ve,...se(Se,ve.message)},V(ve.message),n&&(G[N]=_e))}if(!gu(_e)&&(G[N]={ref:B,..._e},!n))return G}}return V(!0),G};const ZUe={mode:zh.onSubmit,reValidateMode:zh.onChange,shouldFocusError:!0};function XUe(t={}){let e={...ZUe,...t},r={submitCount:0,isDirty:!1,isReady:!1,isLoading:$h(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1},n={},i=jo(e.defaultValues)||jo(e.values)?el(e.defaultValues||e.values)||{}:{},a=e.shouldUnregister?{}:el(i),c={action:!1,mount:!1,watch:!1},s={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},f,m=0;const x={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let _={...x};const T={array:Bee(),state:Bee()},E=e.criteriaMode===zh.all,C=lt=>At=>{clearTimeout(m),m=setTimeout(lt,At)},N=async lt=>{if(!e.disabled&&(x.isValid||_.isValid||lt)){const At=e.resolver?gu((await X()).errors):await re(n,!0);At!==r.isValid&&T.state.next({isValid:At})}},R=(lt,At)=>{!e.disabled&&(x.isValidating||x.validatingFields||_.isValidating||_.validatingFields)&&((lt||Array.from(s.mount)).forEach(Ot=>{Ot&&(At?Ms(r.validatingFields,Ot,At):Oo(r.validatingFields,Ot))}),T.state.next({validatingFields:r.validatingFields,isValidating:!gu(r.validatingFields)}))},D=(lt,At=[],Ot,dr,cr=!0,hr=!0)=>{if(dr&&Ot&&!e.disabled){if(c.action=!0,hr&&Array.isArray(dn(n,lt))){const Zt=Ot(dn(n,lt),dr.argA,dr.argB);cr&&Ms(n,lt,Zt)}if(hr&&Array.isArray(dn(r.errors,lt))){const Zt=Ot(dn(r.errors,lt),dr.argA,dr.argB);cr&&Ms(r.errors,lt,Zt),KUe(r.errors,lt)}if((x.touchedFields||_.touchedFields)&&hr&&Array.isArray(dn(r.touchedFields,lt))){const Zt=Ot(dn(r.touchedFields,lt),dr.argA,dr.argB);cr&&Ms(r.touchedFields,lt,Zt)}(x.dirtyFields||_.dirtyFields)&&(r.dirtyFields=g2(i,a)),T.state.next({name:lt,isDirty:ue(lt,At),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else Ms(a,lt,At)},M=(lt,At)=>{Ms(r.errors,lt,At),T.state.next({errors:r.errors})},B=lt=>{r.errors=lt,T.state.next({errors:r.errors,isValid:!1})},V=(lt,At,Ot,dr)=>{const cr=dn(n,lt);if(cr){const hr=dn(a,lt,wo(Ot)?dn(i,lt):Ot);wo(hr)||dr&&dr.defaultChecked||At?Ms(a,lt,At?hr:Vee(cr._f)):ve(lt,hr),c.mount&&N()}},G=(lt,At,Ot,dr,cr)=>{let hr=!1,Zt=!1;const Pr={name:lt};if(!e.disabled){if(!Ot||dr){(x.isDirty||_.isDirty)&&(Zt=r.isDirty,r.isDirty=Pr.isDirty=ue(),hr=Zt!==Pr.isDirty);const Nn=um(dn(i,lt),At);Zt=!!dn(r.dirtyFields,lt),Nn?Oo(r.dirtyFields,lt):Ms(r.dirtyFields,lt,!0),Pr.dirtyFields=r.dirtyFields,hr=hr||(x.dirtyFields||_.dirtyFields)&&Zt!==!Nn}if(Ot){const Nn=dn(r.touchedFields,lt);Nn||(Ms(r.touchedFields,lt,Ot),Pr.touchedFields=r.touchedFields,hr=hr||(x.touchedFields||_.touchedFields)&&Nn!==Ot)}hr&&cr&&T.state.next(Pr)}return hr?Pr:{}},W=(lt,At,Ot,dr)=>{const cr=dn(r.errors,lt),hr=(x.isValid||_.isValid)&&Ku(At)&&r.isValid!==At;if(e.delayError&&Ot?(f=C(()=>M(lt,Ot)),f(e.delayError)):(clearTimeout(m),f=null,Ot?Ms(r.errors,lt,Ot):Oo(r.errors,lt)),(Ot?!um(cr,Ot):cr)||!gu(dr)||hr){const Zt={...dr,...hr&&Ku(At)?{isValid:At}:{},errors:r.errors,name:lt};r={...r,...Zt},T.state.next(Zt)}},X=async lt=>{R(lt,!0);const At=await e.resolver(a,e.context,UUe(lt||s.mount,n,e.criteriaMode,e.shouldUseNativeValidation));return R(lt),At},Q=async lt=>{const{errors:At}=await X(lt);if(lt)for(const Ot of lt){const dr=dn(At,Ot);dr?Ms(r.errors,Ot,dr):Oo(r.errors,Ot)}else r.errors=At;return At},re=async(lt,At,Ot={valid:!0})=>{for(const dr in lt){const cr=lt[dr];if(cr){const{_f:hr,...Zt}=cr;if(hr){const Pr=s.array.has(hr.name),Nn=cr._f&&VUe(cr._f);Nn&&x.validatingFields&&R([dr],!0);const ai=await Yee(cr,s.disabled,a,E,e.shouldUseNativeValidation&&!At,Pr);if(Nn&&x.validatingFields&&R([dr]),ai[hr.name]&&(Ot.valid=!1,At))break;!At&&(dn(ai,hr.name)?Pr?YUe(r.errors,ai,hr.name):Ms(r.errors,hr.name,ai[hr.name]):Oo(r.errors,hr.name))}!gu(Zt)&&await re(Zt,At,Ot)}}return Ot.valid},se=()=>{for(const lt of s.unMount){const At=dn(n,lt);At&&(At._f.refs?At._f.refs.every(Ot=>!IB(Ot)):!IB(At._f.ref))&&_t(lt)}s.unMount=new Set},ue=(lt,At)=>!e.disabled&&(lt&&At&&Ms(a,lt,At),!um(Ie(),i)),_e=(lt,At,Ot)=>vye(lt,s,{...c.mount?a:wo(At)?i:qf(lt)?{[lt]:At}:At},Ot,At),Se=lt=>y9(dn(c.mount?a:i,lt,e.shouldUnregister?dn(i,lt,[]):[])),ve=(lt,At,Ot={})=>{const dr=dn(n,lt);let cr=At;if(dr){const hr=dr._f;hr&&(!hr.disabled&&Ms(a,lt,Aye(At,hr)),cr=XL(hr.ref)&&$c(At)?"":At,wye(hr.ref)?[...hr.ref.options].forEach(Zt=>Zt.selected=cr.includes(Zt.value)):hr.refs?qC(hr.ref)?hr.refs.forEach(Zt=>{(!Zt.defaultChecked||!Zt.disabled)&&(Array.isArray(cr)?Zt.checked=!!cr.find(Pr=>Pr===Zt.value):Zt.checked=cr===Zt.value||!!cr)}):hr.refs.forEach(Zt=>Zt.checked=Zt.value===cr):b9(hr.ref)?hr.ref.value="":(hr.ref.value=cr,hr.ref.type||T.state.next({name:lt,values:el(a)})))}(Ot.shouldDirty||Ot.shouldTouch)&&G(lt,cr,Ot.shouldTouch,Ot.shouldDirty,!0),Ot.shouldValidate&&Ne(lt)},Oe=(lt,At,Ot)=>{for(const dr in At){if(!At.hasOwnProperty(dr))return;const cr=At[dr],hr=lt+"."+dr,Zt=dn(n,hr);(s.array.has(lt)||jo(cr)||Zt&&!Zt._f)&&!W_(cr)?Oe(hr,cr,Ot):ve(hr,cr,Ot)}},Ae=(lt,At,Ot={})=>{const dr=dn(n,lt),cr=s.array.has(lt),hr=el(At);Ms(a,lt,hr),cr?(T.array.next({name:lt,values:el(a)}),(x.isDirty||x.dirtyFields||_.isDirty||_.dirtyFields)&&Ot.shouldDirty&&T.state.next({name:lt,dirtyFields:g2(i,a),isDirty:ue(lt,hr)})):dr&&!dr._f&&!$c(hr)?Oe(lt,hr,Ot):ve(lt,hr,Ot),Hee(lt,s)&&T.state.next({...r,name:lt}),T.state.next({name:c.mount?lt:void 0,values:el(a)})},we=async lt=>{c.mount=!0;const At=lt.target;let Ot=At.name,dr=!0;const cr=dn(n,Ot),hr=Nn=>{dr=Number.isNaN(Nn)||W_(Nn)&&isNaN(Nn.getTime())||um(Nn,dn(a,Ot,Nn))},Zt=qee(e.mode),Pr=qee(e.reValidateMode);if(cr){let Nn,ai;const ei=At.type?Vee(cr._f):yye(lt),Oi=lt.type===ZL.BLUR||lt.type===ZL.FOCUS_OUT,ya=!qUe(cr._f)&&!e.resolver&&!dn(r.errors,Ot)&&!cr._f.deps||WUe(Oi,dn(r.touchedFields,Ot),r.isSubmitted,Pr,Zt),mi=Hee(Ot,s,Oi);Ms(a,Ot,ei),Oi?(cr._f.onBlur&&cr._f.onBlur(lt),f&&f(0)):cr._f.onChange&&cr._f.onChange(lt);const ia=G(Ot,ei,Oi),jr=!gu(ia)||mi;if(!Oi&&T.state.next({name:Ot,type:lt.type,values:el(a)}),ya)return(x.isValid||_.isValid)&&(e.mode==="onBlur"?Oi&&N():Oi||N()),jr&&T.state.next({name:Ot,...mi?{}:ia});if(!Oi&&mi&&T.state.next({...r}),e.resolver){const{errors:Mn}=await X([Ot]);if(hr(ei),dr){const As=Wee(r.errors,n,Ot),xa=Wee(Mn,n,As.name||Ot);Nn=xa.error,Ot=xa.name,ai=gu(Mn)}}else R([Ot],!0),Nn=(await Yee(cr,s.disabled,a,E,e.shouldUseNativeValidation))[Ot],R([Ot]),hr(ei),dr&&(Nn?ai=!1:(x.isValid||_.isValid)&&(ai=await re(n,!0)));dr&&(cr._f.deps&&Ne(cr._f.deps),W(Ot,ai,Nn,ia))}},ge=(lt,At)=>{if(dn(r.errors,At)&<.focus)return lt.focus(),1},Ne=async(lt,At={})=>{let Ot,dr;const cr=mA(lt);if(e.resolver){const hr=await Q(wo(lt)?lt:cr);Ot=gu(hr),dr=lt?!cr.some(Zt=>dn(hr,Zt)):Ot}else lt?(dr=(await Promise.all(cr.map(async hr=>{const Zt=dn(n,hr);return await re(Zt&&Zt._f?{[hr]:Zt}:Zt)}))).every(Boolean),!(!dr&&!r.isValid)&&N()):dr=Ot=await re(n);return T.state.next({...!qf(lt)||(x.isValid||_.isValid)&&Ot!==r.isValid?{}:{name:lt},...e.resolver||!lt?{isValid:Ot}:{},errors:r.errors}),At.shouldFocus&&!dr&&gA(n,ge,lt?cr:s.mount),dr},Ie=lt=>{const At={...c.mount?a:i};return wo(lt)?At:qf(lt)?dn(At,lt):lt.map(Ot=>dn(At,Ot))},Te=(lt,At)=>({invalid:!!dn((At||r).errors,lt),isDirty:!!dn((At||r).dirtyFields,lt),error:dn((At||r).errors,lt),isValidating:!!dn(r.validatingFields,lt),isTouched:!!dn((At||r).touchedFields,lt)}),be=lt=>{lt&&mA(lt).forEach(At=>Oo(r.errors,At)),T.state.next({errors:lt?r.errors:{}})},We=(lt,At,Ot)=>{const dr=(dn(n,lt,{_f:{}})._f||{}).ref,cr=dn(r.errors,lt)||{},{ref:hr,message:Zt,type:Pr,...Nn}=cr;Ms(r.errors,lt,{...Nn,...At,ref:dr}),T.state.next({name:lt,errors:r.errors,isValid:!1}),Ot&&Ot.shouldFocus&&dr&&dr.focus&&dr.focus()},rt=(lt,At)=>$h(lt)?T.state.subscribe({next:Ot=>"values"in Ot&<(_e(void 0,At),Ot)}):_e(lt,At,!0),at=lt=>T.state.subscribe({next:At=>{HUe(lt.name,At.name,lt.exact)&&GUe(At,lt.formState||x,yr,lt.reRenderRoot)&<.callback({values:{...a},...r,...At,defaultValues:i})}}).unsubscribe,Et=lt=>(c.mount=!0,_={..._,...lt.formState},at({...lt,formState:_})),_t=(lt,At={})=>{for(const Ot of lt?mA(lt):s.mount)s.mount.delete(Ot),s.array.delete(Ot),At.keepValue||(Oo(n,Ot),Oo(a,Ot)),!At.keepError&&Oo(r.errors,Ot),!At.keepDirty&&Oo(r.dirtyFields,Ot),!At.keepTouched&&Oo(r.touchedFields,Ot),!At.keepIsValidating&&Oo(r.validatingFields,Ot),!e.shouldUnregister&&!At.keepDefaultValue&&Oo(i,Ot);T.state.next({values:el(a)}),T.state.next({...r,...At.keepDirty?{isDirty:ue()}:{}}),!At.keepIsValid&&N()},Vt=({disabled:lt,name:At})=>{(Ku(lt)&&c.mount||lt||s.disabled.has(At))&&(lt?s.disabled.add(At):s.disabled.delete(At))},mt=(lt,At={})=>{let Ot=dn(n,lt);const dr=Ku(At.disabled)||Ku(e.disabled);return Ms(n,lt,{...Ot||{},_f:{...Ot&&Ot._f?Ot._f:{ref:{name:lt}},name:lt,mount:!0,...At}}),s.mount.add(lt),Ot?Vt({disabled:Ku(At.disabled)?At.disabled:e.disabled,name:lt}):V(lt,!0,At.value),{...dr?{disabled:At.disabled||e.disabled}:{},...e.progressive?{required:!!At.required,min:y2(At.min),max:y2(At.max),minLength:y2(At.minLength),maxLength:y2(At.maxLength),pattern:y2(At.pattern)}:{},name:lt,onChange:we,onBlur:we,ref:cr=>{if(cr){mt(lt,At),Ot=dn(n,lt);const hr=wo(cr.value)&&cr.querySelectorAll&&cr.querySelectorAll("input,select,textarea")[0]||cr,Zt=BUe(hr),Pr=Ot._f.refs||[];if(Zt?Pr.find(Nn=>Nn===hr):hr===Ot._f.ref)return;Ms(n,lt,{_f:{...Ot._f,...Zt?{refs:[...Pr.filter(IB),hr,...Array.isArray(dn(i,lt))?[{}]:[]],ref:{type:hr.type,name:lt}}:{ref:hr}}}),V(lt,!1,void 0,hr)}else Ot=dn(n,lt,{}),Ot._f&&(Ot._f.mount=!1),(e.shouldUnregister||At.shouldUnregister)&&!(xye(s.array,lt)&&c.action)&&s.unMount.add(lt)}}},Pt=()=>e.shouldFocusError&&gA(n,ge,s.mount),er=lt=>{Ku(lt)&&(T.state.next({disabled:lt}),gA(n,(At,Ot)=>{const dr=dn(n,Ot);dr&&(At.disabled=dr._f.disabled||lt,Array.isArray(dr._f.refs)&&dr._f.refs.forEach(cr=>{cr.disabled=dr._f.disabled||lt}))},0,!1))},wt=(lt,At)=>async Ot=>{let dr;Ot&&(Ot.preventDefault&&Ot.preventDefault(),Ot.persist&&Ot.persist());let cr=el(a);if(T.state.next({isSubmitting:!0}),e.resolver){const{errors:hr,values:Zt}=await X();r.errors=hr,cr=el(Zt)}else await re(n);if(s.disabled.size)for(const hr of s.disabled)Oo(cr,hr);if(Oo(r.errors,"root"),gu(r.errors)){T.state.next({errors:{}});try{await lt(cr,Ot)}catch(hr){dr=hr}}else At&&await At({...r.errors},Ot),Pt(),setTimeout(Pt);if(T.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:gu(r.errors)&&!dr,submitCount:r.submitCount+1,errors:r.errors}),dr)throw dr},or=(lt,At={})=>{dn(n,lt)&&(wo(At.defaultValue)?Ae(lt,el(dn(i,lt))):(Ae(lt,At.defaultValue),Ms(i,lt,el(At.defaultValue))),At.keepTouched||Oo(r.touchedFields,lt),At.keepDirty||(Oo(r.dirtyFields,lt),r.isDirty=At.defaultValue?ue(lt,el(dn(i,lt))):ue()),At.keepError||(Oo(r.errors,lt),x.isValid&&N()),T.state.next({...r}))},Sr=(lt,At={})=>{const Ot=lt?el(lt):i,dr=el(Ot),cr=gu(lt),hr=cr?i:dr;if(At.keepDefaultValues||(i=Ot),!At.keepValues){if(At.keepDirtyValues){const Zt=new Set([...s.mount,...Object.keys(g2(i,a))]);for(const Pr of Array.from(Zt))dn(r.dirtyFields,Pr)?Ms(hr,Pr,dn(a,Pr)):Ae(Pr,dn(hr,Pr))}else{if(g9&&wo(lt))for(const Zt of s.mount){const Pr=dn(n,Zt);if(Pr&&Pr._f){const Nn=Array.isArray(Pr._f.refs)?Pr._f.refs[0]:Pr._f.ref;if(XL(Nn)){const ai=Nn.closest("form");if(ai){ai.reset();break}}}}if(At.keepFieldsRef)for(const Zt of s.mount)Ae(Zt,dn(hr,Zt));else n={}}a=e.shouldUnregister?At.keepDefaultValues?el(i):{}:el(hr),T.array.next({values:{...hr}}),T.state.next({values:{...hr}})}s={mount:At.keepDirtyValues?s.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},c.mount=!x.isValid||!!At.keepIsValid||!!At.keepDirtyValues,c.watch=!!e.shouldUnregister,T.state.next({submitCount:At.keepSubmitCount?r.submitCount:0,isDirty:cr?!1:At.keepDirty?r.isDirty:!!(At.keepDefaultValues&&!um(lt,i)),isSubmitted:At.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:cr?{}:At.keepDirtyValues?At.keepDefaultValues&&a?g2(i,a):r.dirtyFields:At.keepDefaultValues&<?g2(i,lt):At.keepDirty?r.dirtyFields:{},touchedFields:At.keepTouched?r.touchedFields:{},errors:At.keepErrors?r.errors:{},isSubmitSuccessful:At.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},nn=(lt,At)=>Sr($h(lt)?lt(a):lt,At),lr=(lt,At={})=>{const Ot=dn(n,lt),dr=Ot&&Ot._f;if(dr){const cr=dr.refs?dr.refs[0]:dr.ref;cr.focus&&(cr.focus(),At.shouldSelect&&$h(cr.select)&&cr.select())}},yr=lt=>{r={...r,...lt}},yn={control:{register:mt,unregister:_t,getFieldState:Te,handleSubmit:wt,setError:We,_subscribe:at,_runSchema:X,_focusError:Pt,_getWatch:_e,_getDirty:ue,_setValid:N,_setFieldArray:D,_setDisabledField:Vt,_setErrors:B,_getFieldArray:Se,_reset:Sr,_resetDefaultValues:()=>$h(e.defaultValues)&&e.defaultValues().then(lt=>{nn(lt,e.resetOptions),T.state.next({isLoading:!1})}),_removeUnmounted:se,_disableForm:er,_subjects:T,_proxyFormState:x,get _fields(){return n},get _formValues(){return a},get _state(){return c},set _state(lt){c=lt},get _defaultValues(){return i},get _names(){return s},set _names(lt){s=lt},get _formState(){return r},get _options(){return e},set _options(lt){e={...e,...lt}}},subscribe:Et,trigger:Ne,register:mt,handleSubmit:wt,watch:rt,setValue:Ae,getValues:Ie,reset:nn,resetField:or,clearErrors:be,unregister:_t,setError:We,setFocus:lr,getFieldState:Te};return{...yn,formControl:yn}}function S9(t={}){const e=Xe.useRef(void 0),r=Xe.useRef(void 0),[n,i]=Xe.useState({isDirty:!1,isValidating:!1,isLoading:$h(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,isReady:!1,defaultValues:$h(t.defaultValues)?void 0:t.defaultValues});if(!e.current)if(t.formControl)e.current={...t.formControl,formState:n},t.defaultValues&&!$h(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions);else{const{formControl:c,...s}=XUe(t);e.current={...s,formState:n}}const a=e.current.control;return a._options=t,v9(()=>{const c=a._subscribe({formState:a._proxyFormState,callback:()=>i({...a._formState}),reRenderRoot:!0});return i(s=>({...s,isReady:!0})),a._formState.isReady=!0,c},[a]),Xe.useEffect(()=>a._disableForm(t.disabled),[a,t.disabled]),Xe.useEffect(()=>{t.mode&&(a._options.mode=t.mode),t.reValidateMode&&(a._options.reValidateMode=t.reValidateMode)},[a,t.mode,t.reValidateMode]),Xe.useEffect(()=>{t.errors&&(a._setErrors(t.errors),a._focusError())},[a,t.errors]),Xe.useEffect(()=>{t.shouldUnregister&&a._subjects.state.next({values:a._getWatch()})},[a,t.shouldUnregister]),Xe.useEffect(()=>{if(a._proxyFormState.isDirty){const c=a._getDirty();c!==n.isDirty&&a._subjects.state.next({isDirty:c})}},[a,n.isDirty]),Xe.useEffect(()=>{t.values&&!um(t.values,r.current)?(a._reset(t.values,{keepFieldsRef:!0,...a._options.resetOptions}),r.current=t.values,i(c=>({...c}))):a._resetDefaultValues()},[a,t.values]),Xe.useEffect(()=>{a._state.mount||(a._setValid(),a._state.mount=!0),a._state.watch&&(a._state.watch=!1,a._subjects.state.next({...a._formState})),a._removeUnmounted()}),e.current.formState=_ye(n,a),e.current}const Zee=(t,e,r)=>{if(t&&"reportValidity"in t){const n=dn(r,e);t.setCustomValidity(n&&n.message||""),t.reportValidity()}},Cye=(t,e)=>{for(const r in e.fields){const n=e.fields[r];n&&n.ref&&"reportValidity"in n.ref?Zee(n.ref,r,t):n.refs&&n.refs.forEach(i=>Zee(i,r,t))}},QUe=(t,e)=>{e.shouldUseNativeValidation&&Cye(t,e);const r={};for(const n in t){const i=dn(e.fields,n),a=Object.assign(t[n]||{},{ref:i&&i.ref});if(JUe(e.names||Object.keys(t),n)){const c=Object.assign({},dn(r,n));Ms(c,"root",a),Ms(r,n,c)}else Ms(r,n,a)}return r},JUe=(t,e)=>t.some(r=>r.startsWith(e+"."));var e6e=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 s=n.unionErrors[0].errors[0];r[c]={message:s.message,type:s.code}}else r[c]={message:a,type:i};if("unionErrors"in n&&n.unionErrors.forEach(function(x){return x.errors.forEach(function(_){return t.push(_)})}),e){var f=r[c].types,m=f&&f[n.code];r[c]=bye(c,e,r,i,m?[].concat(m,n.message):n.message)}t.shift()}return r},T9=function(t,e,r){return r===void 0&&(r={}),function(n,i,a){try{return Promise.resolve(function(c,s){try{var f=Promise.resolve(t[r.mode==="sync"?"parse":"parseAsync"](n,e)).then(function(m){return a.shouldUseNativeValidation&&Cye({},a),{errors:{},values:r.raw?n:m}})}catch(m){return s(m)}return f&&f.then?f.then(void 0,s):f}(0,function(c){if(function(s){return Array.isArray(s==null?void 0:s.errors)}(c))return{values:{},errors:QUe(e6e(c.errors,!a.shouldUseNativeValidation&&a.criteriaMode==="all"),a)};throw c}))}catch(c){return Promise.reject(c)}}},Xee;function Er(t,e,r){function n(s,f){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:f,constr:c,traits:new Set},enumerable:!1}),s._zod.traits.has(t))return;s._zod.traits.add(t),e(s,f);const m=c.prototype,x=Object.keys(m);for(let _=0;_{var f,m;return r!=null&&r.Parent&&s instanceof r.Parent?!0:(m=(f=s==null?void 0:s._zod)==null?void 0:f.traits)==null?void 0:m.has(t)}}),Object.defineProperty(c,"name",{value:t}),c}class Ow extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class jye extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(Xee=globalThis).__zod_globalConfig??(Xee.__zod_globalConfig={});const E9=globalThis.__zod_globalConfig;function Nm(t){return E9}function Iye(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 _6(t,e){return typeof e=="bigint"?e.toString():e}function A9(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function k9(t){return t==null}function C9(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function t6e(t,e){const r=t/e,n=Math.round(r),i=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n){};function eD(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const n6e=A9(()=>{var t;if(E9.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 v1(t){if(eD(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const r=e.prototype;return!(eD(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Nye(t){return v1(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}const i6e=new Set(["string","number","symbol"]);function b1(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ax(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 $n(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 s6e(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const a6e={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]};function o6e(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=sx(t._zod.def,{get shape(){const c={};for(const s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(c[s]=r.shape[s])}return q0(this,"shape",c),c},checks:[]});return ax(t,a)}function l6e(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=sx(t._zod.def,{get shape(){const c={...t._zod.def.shape};for(const s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete c[s]}return q0(this,"shape",c),c},checks:[]});return ax(t,a)}function c6e(t,e){if(!v1(e))throw new Error("Invalid input to extend: expected a plain object");const r=t._zod.def.checks;if(r&&r.length>0){const a=t._zod.def.shape;for(const c in e)if(Object.getOwnPropertyDescriptor(a,c)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=sx(t._zod.def,{get shape(){const a={...t._zod.def.shape,...e};return q0(this,"shape",a),a}});return ax(t,i)}function u6e(t,e){if(!v1(e))throw new Error("Invalid input to safeExtend: expected a plain object");const r=sx(t._zod.def,{get shape(){const n={...t._zod.def.shape,...e};return q0(this,"shape",n),n}});return ax(t,r)}function d6e(t,e){var n;if((n=t._zod.def.checks)!=null&&n.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const r=sx(t._zod.def,{get shape(){const i={...t._zod.def.shape,...e._zod.def.shape};return q0(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return ax(t,r)}function h6e(t,e,r){const i=e._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const c=sx(e._zod.def,{get shape(){const s=e._zod.def.shape,f={...s};if(r)for(const m in r){if(!(m in s))throw new Error(`Unrecognized key: "${m}"`);r[m]&&(f[m]=t?new t({type:"optional",innerType:s[m]}):s[m])}else for(const m in s)f[m]=t?new t({type:"optional",innerType:s[m]}):s[m];return q0(this,"shape",f),f},checks:[]});return ax(e,c)}function f6e(t,e,r){const n=sx(e._zod.def,{get shape(){const i=e._zod.def.shape,a={...i};if(r)for(const c in r){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);r[c]&&(a[c]=new t({type:"nonoptional",innerType:i[c]}))}else for(const c in i)a[c]=new t({type:"nonoptional",innerType:i[c]});return q0(this,"shape",a),a}});return ax(e,n)}function hw(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 pN(t){return typeof t=="string"?t:t==null?void 0:t.message}function Rm(t,e,r){var f,m,x,_,T,E;const n=t.message?t.message:pN((x=(m=(f=t.inst)==null?void 0:f._zod.def)==null?void 0:m.error)==null?void 0:x.call(m,t))??pN((_=e==null?void 0:e.error)==null?void 0:_.call(e,t))??pN((T=r.customError)==null?void 0:T.call(r,t))??pN((E=r.localeError)==null?void 0:E.call(r,t))??"Invalid input",{inst:i,continue:a,input:c,...s}=t;return s.path??(s.path=[]),s.message=n,e!=null&&e.reportInput&&(s.input=c),s}function j9(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function fk(...t){const[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}const Rye=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,_6,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Lye=Er("$ZodError",Rye),Dye=Er("$ZodError",Rye,{Parent:Error});function m6e(t,e=r=>r.message){const r={},n=[];for(const i of t.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}function g6e(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(s=>n({issues:s},[...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 s=[...a,...c.path];if(s.length===0)r._errors.push(e(c));else{let f=r,m=0;for(;m(e,r,n,i)=>{const a=n?{...n,async:!1}:{async:!1},c=e._zod.run({value:r,issues:[]},a);if(c instanceof Promise)throw new Ow;if(c.issues.length){const s=new((i==null?void 0:i.Err)??t)(c.issues.map(f=>Rm(f,a,Nm())));throw Pye(s,i==null?void 0:i.callee),s}return c.value},P9=t=>async(e,r,n,i)=>{const a=n?{...n,async:!0}:{async:!0};let c=e._zod.run({value:r,issues:[]},a);if(c instanceof Promise&&(c=await c),c.issues.length){const s=new((i==null?void 0:i.Err)??t)(c.issues.map(f=>Rm(f,a,Nm())));throw Pye(s,i==null?void 0:i.callee),s}return c.value},LM=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 Ow;return a.issues.length?{success:!1,error:new(t??Lye)(a.issues.map(c=>Rm(c,i,Nm())))}:{success:!0,data:a.value}},y6e=LM(Dye),DM=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?{success:!1,error:new t(a.issues.map(c=>Rm(c,i,Nm())))}:{success:!0,data:a.value}},x6e=DM(Dye),_6e=t=>(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return I9(t)(e,r,i)},v6e=t=>(e,r,n)=>I9(t)(e,r,n),b6e=t=>async(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return P9(t)(e,r,i)},w6e=t=>async(e,r,n)=>P9(t)(e,r,n),S6e=t=>(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return LM(t)(e,r,i)},T6e=t=>(e,r,n)=>LM(t)(e,r,n),E6e=t=>async(e,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return DM(t)(e,r,i)},A6e=t=>async(e,r,n)=>DM(t)(e,r,n),k6e=/^[cC][0-9a-z]{6,}$/,C6e=/^[0-9a-z]+$/,j6e=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,I6e=/^[0-9a-vA-V]{20}$/,P6e=/^[A-Za-z0-9]{27}$/,N6e=/^[a-zA-Z0-9_-]{21}$/,R6e=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,L6e=/^([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})$/,ete=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)$/,D6e=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,O6e="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function M6e(){return new RegExp(O6e,"u")}const F6e=/^(?:(?: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])$/,B6e=/^(([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}|:))$/,z6e=/^((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])$/,$6e=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,U6e=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Oye=/^[A-Za-z0-9_-]*$/,V6e=/^https?$/,q6e=/^\+[1-9]\d{6,14}$/,Mye="(?:(?:\\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])))",G6e=new RegExp(`^${Mye}$`);function Fye(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}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function H6e(t){return new RegExp(`^${Fye(t)}$`)}function W6e(t){const e=Fye({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Mye}T(?:${n})$`)}const K6e=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Y6e=/^-?\d+$/,Bye=/^-?\d+(?:\.\d+)?$/,Z6e=/^(?:true|false)$/i,X6e=/^[^A-Z]*$/,Q6e=/^[^a-z]*$/,ju=Er("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),zye={number:"number",bigint:"bigint",object:"date"},$ye=Er("$ZodCheckLessThan",(t,e)=>{ju.init(t,e);const r=zye[typeof e.value];t._zod.onattach.push(n=>{const i=n._zod.bag,a=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value{(e.inclusive?n.value<=e.value:n.value{ju.init(t,e);const r=zye[typeof e.value];t._zod.onattach.push(n=>{const i=n._zod.bag,a=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>a&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin: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})}}),J6e=Er("$ZodCheckMultipleOf",(t,e)=>{ju.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),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"?r.value%e.value===BigInt(0):t6e(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})}}),eVe=Er("$ZodCheckNumberFormat",(t,e)=>{var c;ju.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]=a6e[e.format];t._zod.onattach.push(s=>{const f=s._zod.bag;f.format=e.format,f.minimum=i,f.maximum=a,r&&(f.pattern=Y6e)}),t._zod.check=s=>{const f=s.value;if(r){if(!Number.isInteger(f)){s.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:f,inst:t});return}if(!Number.isSafeInteger(f)){f>0?s.issues.push({input:f,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}):s.issues.push({input:f,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}}fa&&s.issues.push({origin:"number",input:f,code:"too_big",maximum:a,inclusive:!0,inst:t,continue:!e.abort})}}),tVe=Er("$ZodCheckMaxLength",(t,e)=>{var r;ju.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!k9(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{const i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum{const i=n.value;if(i.length<=e.maximum)return;const c=j9(i);n.issues.push({origin:c,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),rVe=Er("$ZodCheckMinLength",(t,e)=>{var r;ju.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!k9(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{const i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{const i=n.value;if(i.length>=e.minimum)return;const c=j9(i);n.issues.push({origin:c,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),nVe=Er("$ZodCheckLengthEquals",(t,e)=>{var r;ju.init(t,e),(r=t._zod.def).when??(r.when=n=>{const i=n.value;return!k9(i)&&i.length!==void 0}),t._zod.onattach.push(n=>{const i=n._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=n=>{const i=n.value,a=i.length;if(a===e.length)return;const c=j9(i),s=a>e.length;n.issues.push({origin:c,...s?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),OM=Er("$ZodCheckStringFormat",(t,e)=>{var r,n;ju.init(t,e),t._zod.onattach.push(i=>{const a=i._zod.bag;a.format=e.format,e.pattern&&(a.patterns??(a.patterns=new Set),a.patterns.add(e.pattern))}),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=()=>{})}),iVe=Er("$ZodCheckRegex",(t,e)=>{OM.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})}}),sVe=Er("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=X6e),OM.init(t,e)}),aVe=Er("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Q6e),OM.init(t,e)}),oVe=Er("$ZodCheckIncludes",(t,e)=>{ju.init(t,e);const r=b1(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(i=>{const a=i._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(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})}}),lVe=Er("$ZodCheckStartsWith",(t,e)=>{ju.init(t,e);const r=new RegExp(`^${b1(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(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})}}),cVe=Er("$ZodCheckEndsWith",(t,e)=>{ju.init(t,e);const r=new RegExp(`.*${b1(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{const i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(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})}}),uVe=Er("$ZodCheckOverwrite",(t,e)=>{ju.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});class dVe{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),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.args,i=[...((this==null?void 0:this.content)??[""]).map(a=>` ${a}`)];return new e(...r,i.join(` `))}}const hVe={major:4,minor:4,patch:3},no=Er("$ZodType",(t,e)=>{var i;var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=hVe;const n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(const a of n)for(const c of a._zod.onattach)c(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),(i=t._zod.deferred)==null||i.push(()=>{t._zod.run=t._zod.parse});else{const a=(s,f,m)=>{let x=hw(s),_;for(const T of f){if(T._zod.def.when){if(p6e(s)||!T._zod.def.when(s))continue}else if(x)continue;const E=s.issues.length,C=T._zod.check(s);if(C instanceof Promise&&(m==null?void 0:m.async)===!1)throw new Ow;if(_||C instanceof Promise)_=(_??Promise.resolve()).then(async()=>{await C,s.issues.length!==E&&(x||(x=hw(s,E)))});else{if(s.issues.length===E)continue;x||(x=hw(s,E))}}return _?_.then(()=>s):s},c=(s,f,m)=>{if(hw(s))return s.aborted=!0,s;const x=a(f,n,m);if(x instanceof Promise){if(m.async===!1)throw new Ow;return x.then(_=>t._zod.parse(_,m))}return t._zod.parse(x,m)};t._zod.run=(s,f)=>{if(f.skipChecks)return t._zod.parse(s,f);if(f.direction==="backward"){const x=t._zod.parse({value:s.value,issues:[]},{...f,skipChecks:!0});return x instanceof Promise?x.then(_=>c(_,s,f)):c(x,s,f)}const m=t._zod.parse(s,f);if(m instanceof Promise){if(f.async===!1)throw new Ow;return m.then(x=>a(x,n,f))}return a(m,n,f)}}Ws(t,"~standard",()=>({validate:a=>{var c;try{const s=y6e(t,a);return s.success?{value:s.data}:{issues:(c=s.error)==null?void 0:c.issues}}catch{return x6e(t,a).then(f=>{var m;return f.success?{value:f.data}:{issues:(m=f.error)==null?void 0:m.issues}})}},vendor:"zod",version:1}))}),N9=Er("$ZodString",(t,e)=>{var r;no.init(t,e),t._zod.pattern=[...((r=t==null?void 0:t._zod.bag)==null?void 0:r.patterns)??[]].pop()??K6e(t._zod.bag),t._zod.parse=(n,i)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),Ua=Er("$ZodStringFormat",(t,e)=>{OM.init(t,e),N9.init(t,e)}),fVe=Er("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=L6e),Ua.init(t,e)}),pVe=Er("$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=ete(n))}else e.pattern??(e.pattern=ete());Ua.init(t,e)}),mVe=Er("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=D6e),Ua.init(t,e)}),gVe=Er("$ZodURL",(t,e)=>{Ua.init(t,e),t._zod.check=r=>{var n;try{const i=r.value.trim();if(!e.normalize&&((n=e.protocol)==null?void 0:n.source)===V6e.source&&!/^https?:\/\//i.test(i)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}const a=new URL(i);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(a.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&&(e.protocol.lastIndex=0,e.protocol.test(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=a.href:r.value=i;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),yVe=Er("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=M6e()),Ua.init(t,e)}),xVe=Er("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=N6e),Ua.init(t,e)}),_Ve=Er("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=k6e),Ua.init(t,e)}),vVe=Er("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=C6e),Ua.init(t,e)}),bVe=Er("$ZodULID",(t,e)=>{e.pattern??(e.pattern=j6e),Ua.init(t,e)}),wVe=Er("$ZodXID",(t,e)=>{e.pattern??(e.pattern=I6e),Ua.init(t,e)}),SVe=Er("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=P6e),Ua.init(t,e)}),TVe=Er("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=W6e(e)),Ua.init(t,e)}),EVe=Er("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=G6e),Ua.init(t,e)}),AVe=Er("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=H6e(e)),Ua.init(t,e)}),kVe=Er("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=R6e),Ua.init(t,e)}),CVe=Er("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=F6e),Ua.init(t,e),t._zod.bag.format="ipv4"}),jVe=Er("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=B6e),Ua.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),IVe=Er("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=z6e),Ua.init(t,e)}),PVe=Er("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=$6e),Ua.init(t,e),t._zod.check=r=>{const n=r.value.split("/");try{if(n.length!==2)throw new Error;const[i,a]=n;if(!a)throw new Error;const c=Number(a);if(`${c}`!==a)throw new Error;if(c<0||c>128)throw new Error;new URL(`http://[${i}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Vye(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const NVe=Er("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=U6e),Ua.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Vye(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function RVe(t){if(!Oye.test(t))return!1;const e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Vye(r)}const LVe=Er("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Oye),Ua.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{RVe(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),DVe=Er("$ZodE164",(t,e)=>{e.pattern??(e.pattern=q6e),Ua.init(t,e)});function OVe(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 MVe=Er("$ZodJWT",(t,e)=>{Ua.init(t,e),t._zod.check=r=>{OVe(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),qye=Er("$ZodNumber",(t,e)=>{no.init(t,e),t._zod.pattern=t._zod.bag.pattern??Bye,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:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...a?{received:a}:{}}),r}}),FVe=Er("$ZodNumberFormat",(t,e)=>{eVe.init(t,e),qye.init(t,e)}),BVe=Er("$ZodBoolean",(t,e)=>{no.init(t,e),t._zod.pattern=Z6e,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}}),zVe=Er("$ZodUnknown",(t,e)=>{no.init(t,e),t._zod.parse=r=>r}),$Ve=Er("$ZodNever",(t,e)=>{no.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function tte(t,e,r){t.issues.length&&e.issues.push(...fw(r,t.issues)),e.value[r]=t.value}const UVe=Er("$ZodArray",(t,e)=>{no.init(t,e),t._zod.parse=(r,n)=>{const i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),r;r.value=Array(i.length);const a=[];for(let c=0;ctte(m,r,c))):tte(f,r,c)}return a.length?Promise.all(a).then(()=>r):r}});function tD(t,e,r,n,i,a){const c=r in n;if(t.issues.length){if(i&&a&&!c)return;e.issues.push(...fw(r,t.issues))}if(!c&&!i){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?c&&(e.value[r]=void 0):e.value[r]=t.value}function Gye(t){var n,i,a,c;const e=Object.keys(t.shape);for(const s of e)if(!((c=(a=(i=(n=t.shape)==null?void 0:n[s])==null?void 0:i._zod)==null?void 0:a.traits)!=null&&c.has("$ZodType")))throw new Error(`Invalid element at key "${s}": expected a Zod schema`);const r=s6e(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Hye(t,e,r,n,i,a){const c=[],s=i.keySet,f=i.catchall._zod,m=f.def.type,x=f.optin==="optional",_=f.optout==="optional";for(const T in e){if(T==="__proto__"||s.has(T))continue;if(m==="never"){c.push(T);continue}const E=f.run({value:e[T],issues:[]},n);E instanceof Promise?t.push(E.then(C=>tD(C,r,T,e,x,_))):tD(E,r,T,e,x,_)}return c.length&&r.issues.push({code:"unrecognized_keys",keys:c,input:e,inst:a}),t.length?Promise.all(t).then(()=>r):r}const VVe=Er("$ZodObject",(t,e)=>{no.init(t,e);const r=Object.getOwnPropertyDescriptor(e,"shape");if(!(r!=null&&r.get)){const s=e.shape;Object.defineProperty(e,"shape",{get:()=>{const f={...s};return Object.defineProperty(e,"shape",{value:f}),f}})}const n=A9(()=>Gye(e));Ws(t._zod,"propValues",()=>{const s=e.shape,f={};for(const m in s){const x=s[m]._zod;if(x.values){f[m]??(f[m]=new Set);for(const _ of x.values)f[m].add(_)}}return f});const i=eD,a=e.catchall;let c;t._zod.parse=(s,f)=>{c??(c=n.value);const m=s.value;if(!i(m))return s.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),s;s.value={};const x=[],_=c.shape;for(const T of c.keys){const E=_[T],C=E._zod.optin==="optional",N=E._zod.optout==="optional",R=E._zod.run({value:m[T],issues:[]},f);R instanceof Promise?x.push(R.then(D=>tD(D,s,T,m,C,N))):tD(R,s,T,m,C,N)}return a?Hye(x,m,s,f,n.value,t):x.length?Promise.all(x).then(()=>s):s}}),qVe=Er("$ZodObjectJIT",(t,e)=>{VVe.init(t,e);const r=t._zod.parse,n=A9(()=>Gye(e)),i=T=>{var B,V;const E=new dVe(["shape","payload","ctx"]),C=n.value,N=G=>{const W=Jee(G);return`shape[${W}]._zod.run({ value: input[${W}], issues: [] }, ctx)`};E.write("const input = payload.value;");const R=Object.create(null);let D=0;for(const G of C.keys)R[G]=`key_${D++}`;E.write("const newResult = {};");for(const G of C.keys){const W=R[G],X=Jee(G),Q=T[G],re=((B=Q==null?void 0:Q._zod)==null?void 0:B.optin)==="optional",se=((V=Q==null?void 0:Q._zod)==null?void 0:V.optout)==="optional";E.write(`const ${W} = ${N(G)};`),re&&se?E.write(` if (${W}.issues.length) { if (${X} in input) { payload.issues = payload.issues.concat(${W}.issues.map(iss => ({ ...iss, path: iss.path ? [${X}, ...iss.path] : [${X}] }))); } } if (${W}.value === undefined) { if (${X} in input) { newResult[${X}] = undefined; } } else { newResult[${X}] = ${W}.value; } `):re?E.write(` if (${W}.issues.length) { payload.issues = payload.issues.concat(${W}.issues.map(iss => ({ ...iss, path: iss.path ? [${X}, ...iss.path] : [${X}] }))); } if (${W}.value === undefined) { if (${X} in input) { newResult[${X}] = undefined; } } else { newResult[${X}] = ${W}.value; } `):E.write(` const ${W}_present = ${X} in input; if (${W}.issues.length) { payload.issues = payload.issues.concat(${W}.issues.map(iss => ({ ...iss, path: iss.path ? [${X}, ...iss.path] : [${X}] }))); } if (!${W}_present && !${W}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${X}] }); } if (${W}_present) { if (${W}.value === undefined) { newResult[${X}] = undefined; } else { newResult[${X}] = ${W}.value; } } `)}E.write("payload.value = newResult;"),E.write("return payload;");const M=E.compile();return(G,W)=>M(T,G,W)};let a;const c=eD,s=!E9.jitless,m=s&&n6e.value,x=e.catchall;let _;t._zod.parse=(T,E)=>{_??(_=n.value);const C=T.value;return c(C)?s&&m&&(E==null?void 0:E.async)===!1&&E.jitless!==!0?(a||(a=i(e.shape)),T=a(T,E),x?Hye([],C,T,E,_,t):T):r(T,E):(T.issues.push({expected:"object",code:"invalid_type",input:C,inst:t}),T)}});function rte(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=>!hw(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=>Rm(c,n,Nm())))}),e)}const GVe=Er("$ZodUnion",(t,e)=>{no.init(t,e),Ws(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Ws(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Ws(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Ws(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){const n=e.options.map(i=>i._zod.pattern);return new RegExp(`^(${n.map(i=>C9(i.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 s of e.options){const f=s._zod.run({value:n.value,issues:[]},i);if(f instanceof Promise)c.push(f),a=!0;else{if(f.issues.length===0)return f;c.push(f)}}return a?Promise.all(c).then(s=>rte(s,n,t,i)):rte(c,n,t,i)}}),HVe=Er("$ZodIntersection",(t,e)=>{no.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(([f,m])=>nte(r,f,m)):nte(r,a,c)}});function v6(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(v1(t)&&v1(e)){const r=Object.keys(e),n=Object.keys(t).filter(a=>r.indexOf(a)!==-1),i={...t,...e};for(const a of n){const c=v6(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;ns.l&&s.r).map(([s])=>s);if(a.length&&i&&t.issues.push({...i,keys:a}),hw(t))return t;const c=v6(e.value,r.value);if(!c.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`);return t.value=c.data,t}const WVe=Er("$ZodRecord",(t,e)=>{no.init(t,e),t._zod.parse=(r,n)=>{const i=r.value;if(!v1(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),r;const a=[],c=e.keyType._zod.values;if(c){r.value={};const s=new Set;for(const m of c)if(typeof m=="string"||typeof m=="number"||typeof m=="symbol"){s.add(typeof m=="number"?m.toString():m);const x=e.keyType._zod.run({value:m,issues:[]},n);if(x instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(x.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:x.issues.map(E=>Rm(E,n,Nm())),input:m,path:[m],inst:t});continue}const _=x.value,T=e.valueType._zod.run({value:i[m],issues:[]},n);T instanceof Promise?a.push(T.then(E=>{E.issues.length&&r.issues.push(...fw(m,E.issues)),r.value[_]=E.value})):(T.issues.length&&r.issues.push(...fw(m,T.issues)),r.value[_]=T.value)}let f;for(const m in i)s.has(m)||(f=f??[],f.push(m));f&&f.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:f})}else{r.value={};for(const s of Reflect.ownKeys(i)){if(s==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,s))continue;let f=e.keyType._zod.run({value:s,issues:[]},n);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&Bye.test(s)&&f.issues.length){const _=e.keyType._zod.run({value:Number(s),issues:[]},n);if(_ instanceof Promise)throw new Error("Async schemas not supported in object keys currently");_.issues.length===0&&(f=_)}if(f.issues.length){e.mode==="loose"?r.value[s]=i[s]:r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(_=>Rm(_,n,Nm())),input:s,path:[s],inst:t});continue}const x=e.valueType._zod.run({value:i[s],issues:[]},n);x instanceof Promise?a.push(x.then(_=>{_.issues.length&&r.issues.push(...fw(s,_.issues)),r.value[f.value]=_.value})):(x.issues.length&&r.issues.push(...fw(s,x.issues)),r.value[f.value]=x.value)}}return a.length?Promise.all(a).then(()=>r):r}}),KVe=Er("$ZodEnum",(t,e)=>{no.init(t,e);const r=Iye(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(i=>i6e.has(typeof i)).map(i=>typeof i=="string"?b1(i):i.toString()).join("|")})$`),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}}),YVe=Er("$ZodLiteral",(t,e)=>{if(no.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");const r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?b1(n):n?b1(n.toString()):String(n)).join("|")})$`),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}}),ZVe=Er("$ZodTransform",(t,e)=>{no.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new jye(t.constructor.name);const i=e.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(c=>(r.value=c,r.fallback=!0,r));if(i instanceof Promise)throw new Ow;return r.value=i,r.fallback=!0,r}});function ite(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}const Wye=Er("$ZodOptional",(t,e)=>{no.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ws(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ws(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${C9(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){const i=r.value,a=e.innerType._zod.run(r,n);return a instanceof Promise?a.then(c=>ite(c,i)):ite(a,i)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),XVe=Er("$ZodExactOptional",(t,e)=>{Wye.init(t,e),Ws(t._zod,"values",()=>e.innerType._zod.values),Ws(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),QVe=Er("$ZodNullable",(t,e)=>{no.init(t,e),Ws(t._zod,"optin",()=>e.innerType._zod.optin),Ws(t._zod,"optout",()=>e.innerType._zod.optout),Ws(t._zod,"pattern",()=>{const r=e.innerType._zod.pattern;return r?new RegExp(`^(${C9(r.source)}|null)$`):void 0}),Ws(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),JVe=Er("$ZodDefault",(t,e)=>{no.init(t,e),t._zod.optin="optional",Ws(t._zod,"values",()=>e.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=>ste(a,e)):ste(i,e)}});function ste(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const e8e=Er("$ZodPrefault",(t,e)=>{no.init(t,e),t._zod.optin="optional",Ws(t._zod,"values",()=>e.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))}),t8e=Er("$ZodNonOptional",(t,e)=>{no.init(t,e),Ws(t._zod,"values",()=>{const r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{const i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(a=>ate(a,t)):ate(i,t)}});function ate(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const r8e=Er("$ZodCatch",(t,e)=>{no.init(t,e),t._zod.optin="optional",Ws(t._zod,"optout",()=>e.innerType._zod.optout),Ws(t._zod,"values",()=>e.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(r,n);return i instanceof Promise?i.then(a=>(r.value=a.value,a.issues.length&&(r.value=e.catchValue({...r,error:{issues:a.issues.map(c=>Rm(c,n,Nm()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(a=>Rm(a,n,Nm()))},input:r.value}),r.issues=[],r.fallback=!0),r)}}),n8e=Er("$ZodPipe",(t,e)=>{no.init(t,e),Ws(t._zod,"values",()=>e.in._zod.values),Ws(t._zod,"optin",()=>e.in._zod.optin),Ws(t._zod,"optout",()=>e.out._zod.optout),Ws(t._zod,"propValues",()=>e.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=>mN(c,e.in,n)):mN(a,e.in,n)}const i=e.in._zod.run(r,n);return i instanceof Promise?i.then(a=>mN(a,e.out,n)):mN(i,e.out,n)}});function mN(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}const i8e=Er("$ZodReadonly",(t,e)=>{no.init(t,e),Ws(t._zod,"propValues",()=>e.innerType._zod.propValues),Ws(t._zod,"values",()=>e.innerType._zod.values),Ws(t._zod,"optin",()=>{var r,n;return(n=(r=e.innerType)==null?void 0:r._zod)==null?void 0:n.optin}),Ws(t._zod,"optout",()=>{var r,n;return(n=(r=e.innerType)==null?void 0:r._zod)==null?void 0:n.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(ote):ote(i)}});function ote(t){return t.value=Object.freeze(t.value),t}const s8e=Er("$ZodCustom",(t,e)=>{ju.init(t,e),no.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=>lte(a,r,n,t));lte(i,r,n,t)}});function lte(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(fk(i))}}var cte;class a8e{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 o8e(){return new a8e}(cte=globalThis).__zod_globalRegistry??(cte.__zod_globalRegistry=o8e());const K2=globalThis.__zod_globalRegistry;function l8e(t,e){return new t({type:"string",...$n(e)})}function c8e(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...$n(e)})}function ute(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...$n(e)})}function u8e(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...$n(e)})}function d8e(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...$n(e)})}function h8e(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...$n(e)})}function f8e(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...$n(e)})}function p8e(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...$n(e)})}function m8e(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...$n(e)})}function g8e(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...$n(e)})}function y8e(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...$n(e)})}function x8e(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...$n(e)})}function _8e(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...$n(e)})}function v8e(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...$n(e)})}function b8e(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...$n(e)})}function w8e(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...$n(e)})}function S8e(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...$n(e)})}function T8e(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...$n(e)})}function E8e(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...$n(e)})}function A8e(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...$n(e)})}function k8e(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...$n(e)})}function C8e(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...$n(e)})}function j8e(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...$n(e)})}function I8e(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...$n(e)})}function P8e(t,e){return new t({type:"string",format:"date",check:"string_format",...$n(e)})}function N8e(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...$n(e)})}function R8e(t,e){return new t({type:"string",format:"duration",check:"string_format",...$n(e)})}function L8e(t,e){return new t({type:"number",checks:[],...$n(e)})}function D8e(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...$n(e)})}function O8e(t,e){return new t({type:"boolean",...$n(e)})}function M8e(t){return new t({type:"unknown"})}function F8e(t,e){return new t({type:"never",...$n(e)})}function dte(t,e){return new $ye({check:"less_than",...$n(e),value:t,inclusive:!1})}function PB(t,e){return new $ye({check:"less_than",...$n(e),value:t,inclusive:!0})}function hte(t,e){return new Uye({check:"greater_than",...$n(e),value:t,inclusive:!1})}function NB(t,e){return new Uye({check:"greater_than",...$n(e),value:t,inclusive:!0})}function fte(t,e){return new J6e({check:"multiple_of",...$n(e),value:t})}function Kye(t,e){return new tVe({check:"max_length",...$n(e),maximum:t})}function rD(t,e){return new rVe({check:"min_length",...$n(e),minimum:t})}function Yye(t,e){return new nVe({check:"length_equals",...$n(e),length:t})}function B8e(t,e){return new iVe({check:"string_format",format:"regex",...$n(e),pattern:t})}function z8e(t){return new sVe({check:"string_format",format:"lowercase",...$n(t)})}function $8e(t){return new aVe({check:"string_format",format:"uppercase",...$n(t)})}function U8e(t,e){return new oVe({check:"string_format",format:"includes",...$n(e),includes:t})}function V8e(t,e){return new lVe({check:"string_format",format:"starts_with",...$n(e),prefix:t})}function q8e(t,e){return new cVe({check:"string_format",format:"ends_with",...$n(e),suffix:t})}function TS(t){return new uVe({check:"overwrite",tx:t})}function G8e(t){return TS(e=>e.normalize(t))}function H8e(){return TS(t=>t.trim())}function W8e(){return TS(t=>t.toLowerCase())}function K8e(){return TS(t=>t.toUpperCase())}function Y8e(){return TS(t=>r6e(t))}function Z8e(t,e,r){return new t({type:"array",element:e,...$n(r)})}function X8e(t,e,r){return new t({type:"custom",check:"custom",fn:e,...$n(r)})}function Q8e(t,e){const r=J8e(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(fk(i,n.value,r._zod.def));else{const a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=r),a.continue??(a.continue=!r._zod.def.abort),n.issues.push(fk(a))}},t(n.value,n)),e);return r}function J8e(t,e){const r=new ju({check:"custom",...$n(e)});return r._zod.check=t,r}function Zye(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)??K2,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,cycles:(t==null?void 0:t.cycles)??"ref",reused:(t==null?void 0:t.reused)??"inline",external:(t==null?void 0:t.external)??void 0}}function Vo(t,e,r={path:[],schemaPath:[]}){var x,_;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);const s=(_=(x=t._zod).toJSONSchema)==null?void 0:_.call(x);if(s)c.schema=s;else{const T={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,c.schema,T);else{const C=c.schema,N=e.processors[i.type];if(!N)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);N(t,e,C,T)}const E=t._zod.parent;E&&(c.ref||(c.ref=E),Vo(E,e,T),e.seen.get(E).isParent=!0)}const f=e.metadataRegistry.get(t);return f&&Object.assign(c.schema,f),e.io==="input"&&Dc(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 Xye(t,e){var c,s,f,m;const r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const x of t.seen.entries()){const _=(c=t.metadataRegistry.get(x[0]))==null?void 0:c.id;if(_){const T=n.get(_);if(T&&T!==x[0])throw new Error(`Duplicate schema id "${_}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(_,x[0])}}const i=x=>{var N;const _=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const R=(N=t.external.registry.get(x[0]))==null?void 0:N.id,D=t.external.uri??(B=>B);if(R)return{ref:D(R)};const M=x[1].defId??x[1].schema.id??`schema${t.counter++}`;return x[1].defId=M,{defId:M,ref:`${D("__shared")}#/${_}/${M}`}}if(x[1]===r)return{ref:"#"};const E=`#/${_}/`,C=x[1].schema.id??`__schema${t.counter++}`;return{defId:C,ref:E+C}},a=x=>{if(x[1].schema.$ref)return;const _=x[1],{ref:T,defId:E}=i(x);_.def={..._.schema},E&&(_.defId=E);const C=_.schema;for(const N in C)delete C[N];C.$ref=T};if(t.cycles==="throw")for(const x of t.seen.entries()){const _=x[1];if(_.cycle)throw new Error(`Cycle detected: #/${(s=_.cycle)==null?void 0:s.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const x of t.seen.entries()){const _=x[1];if(e===x[0]){a(x);continue}if(t.external){const E=(f=t.external.registry.get(x[0]))==null?void 0:f.id;if(e!==x[0]&&E){a(x);continue}}if((m=t.metadataRegistry.get(x[0]))==null?void 0:m.id){a(x);continue}if(_.cycle){a(x);continue}if(_.count>1&&t.reused==="ref"){a(x);continue}}}function Qye(t,e){var s,f,m,x;const r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=_=>{const T=t.seen.get(_);if(T.ref===null)return;const E=T.def??T.schema,C={...E},N=T.ref;if(T.ref=null,N){n(N);const D=t.seen.get(N),M=D.schema;if(M.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(E.allOf=E.allOf??[],E.allOf.push(M)):Object.assign(E,M),Object.assign(E,C),_._zod.parent===N)for(const V in E)V==="$ref"||V==="allOf"||V in C||delete E[V];if(M.$ref&&D.def)for(const V in E)V==="$ref"||V==="allOf"||V in D.def&&JSON.stringify(E[V])===JSON.stringify(D.def[V])&&delete E[V]}const R=_._zod.parent;if(R&&R!==N){n(R);const D=t.seen.get(R);if(D!=null&&D.schema.$ref&&(E.$ref=D.schema.$ref,D.def))for(const M in E)M==="$ref"||M==="allOf"||M in D.def&&JSON.stringify(E[M])===JSON.stringify(D.def[M])&&delete E[M]}t.override({zodSchema:_,jsonSchema:E,path:T.path??[]})};for(const _ of[...t.seen.entries()].reverse())n(_[0]);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,(s=t.external)!=null&&s.uri){const _=(f=t.external.registry.get(e))==null?void 0:f.id;if(!_)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(_)}Object.assign(i,r.def??r.schema);const a=(m=t.metadataRegistry.get(e))==null?void 0:m.id;a!==void 0&&i.id===a&&delete i.id;const c=((x=t.external)==null?void 0:x.defs)??{};for(const _ of t.seen.entries()){const T=_[1];T.def&&T.defId&&(T.def.id===T.defId&&delete T.def.id,c[T.defId]=T.def)}t.external||Object.keys(c).length>0&&(t.target==="draft-2020-12"?i.$defs=c:i.definitions=c);try{const _=JSON.parse(JSON.stringify(i));return Object.defineProperty(_,"~standard",{value:{...e["~standard"],jsonSchema:{input:nD(e,"input",t.processors),output:nD(e,"output",t.processors)}},enumerable:!1,writable:!1}),_}catch{throw new Error("Error converting schema to JSON.")}}function Dc(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 Dc(n.element,r);if(n.type==="set")return Dc(n.valueType,r);if(n.type==="lazy")return Dc(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")return Dc(n.innerType,r);if(n.type==="intersection")return Dc(n.left,r)||Dc(n.right,r);if(n.type==="record"||n.type==="map")return Dc(n.keyType,r)||Dc(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Dc(n.in,r)||Dc(n.out,r);if(n.type==="object"){for(const i in n.shape)if(Dc(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(const i of n.options)if(Dc(i,r))return!0;return!1}if(n.type==="tuple"){for(const i of n.items)if(Dc(i,r))return!0;return!!(n.rest&&Dc(n.rest,r))}return!1}const eqe=(t,e={})=>r=>{const n=Zye({...r,processors:e});return Vo(t,n),Xye(n,t),Qye(n,t)},nD=(t,e,r={})=>n=>{const{libraryOptions:i,target:a}=n??{},c=Zye({...i??{},target:a,io:e,processors:r});return Vo(t,c),Xye(c,t),Qye(c,t)},tqe={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},rqe=(t,e,r,n)=>{const i=r;i.type="string";const{minimum:a,maximum:c,format:s,patterns:f,contentEncoding:m}=t._zod.bag;if(typeof a=="number"&&(i.minLength=a),typeof c=="number"&&(i.maxLength=c),s&&(i.format=tqe[s]??s,i.format===""&&delete i.format,s==="time"&&delete i.format),m&&(i.contentEncoding=m),f&&f.size>0){const x=[...f];x.length===1?i.pattern=x[0].source:x.length>1&&(i.allOf=[...x.map(_=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:_.source}))])}},nqe=(t,e,r,n)=>{const i=r,{minimum:a,maximum:c,format:s,multipleOf:f,exclusiveMaximum:m,exclusiveMinimum:x}=t._zod.bag;typeof s=="string"&&s.includes("int")?i.type="integer":i.type="number";const _=typeof x=="number"&&x>=(a??Number.NEGATIVE_INFINITY),T=typeof m=="number"&&m<=(c??Number.POSITIVE_INFINITY),E=e.target==="draft-04"||e.target==="openapi-3.0";_?E?(i.minimum=x,i.exclusiveMinimum=!0):i.exclusiveMinimum=x:typeof a=="number"&&(i.minimum=a),T?E?(i.maximum=m,i.exclusiveMaximum=!0):i.exclusiveMaximum=m:typeof c=="number"&&(i.maximum=c),typeof f=="number"&&(i.multipleOf=f)},iqe=(t,e,r,n)=>{r.type="boolean"},sqe=(t,e,r,n)=>{r.not={}},aqe=(t,e,r,n)=>{},oqe=(t,e,r,n)=>{const i=t._zod.def,a=Iye(i.entries);a.every(c=>typeof c=="number")&&(r.type="number"),a.every(c=>typeof c=="string")&&(r.type="string"),r.enum=a},lqe=(t,e,r,n)=>{const i=t._zod.def,a=[];for(const c of i.values)if(c===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof c=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");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},cqe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},uqe=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},dqe=(t,e,r,n)=>{const i=r,a=t._zod.def,{minimum:c,maximum:s}=t._zod.bag;typeof c=="number"&&(i.minItems=c),typeof s=="number"&&(i.maxItems=s),i.type="array",i.items=Vo(a.element,e,{...n,path:[...n.path,"items"]})},hqe=(t,e,r,n)=>{var m;const i=r,a=t._zod.def;i.type="object",i.properties={};const c=a.shape;for(const x in c)i.properties[x]=Vo(c[x],e,{...n,path:[...n.path,"properties",x]});const s=new Set(Object.keys(c)),f=new Set([...s].filter(x=>{const _=a.shape[x]._zod;return e.io==="input"?_.optin===void 0:_.optout===void 0}));f.size>0&&(i.required=Array.from(f)),((m=a.catchall)==null?void 0:m._zod.def.type)==="never"?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Vo(a.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},fqe=(t,e,r,n)=>{const i=t._zod.def,a=i.inclusive===!1,c=i.options.map((s,f)=>Vo(s,e,{...n,path:[...n.path,a?"oneOf":"anyOf",f]}));a?r.oneOf=c:r.anyOf=c},pqe=(t,e,r,n)=>{const i=t._zod.def,a=Vo(i.left,e,{...n,path:[...n.path,"allOf",0]}),c=Vo(i.right,e,{...n,path:[...n.path,"allOf",1]}),s=m=>"allOf"in m&&Object.keys(m).length===1,f=[...s(a)?a.allOf:[a],...s(c)?c.allOf:[c]];r.allOf=f},mqe=(t,e,r,n)=>{const i=r,a=t._zod.def;i.type="object";const c=a.keyType,s=c._zod.bag,f=s==null?void 0:s.patterns;if(a.mode==="loose"&&f&&f.size>0){const x=Vo(a.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(const _ of f)i.patternProperties[_.source]=x}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=Vo(a.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Vo(a.valueType,e,{...n,path:[...n.path,"additionalProperties"]});const m=c._zod.values;if(m){const x=[...m].filter(_=>typeof _=="string"||typeof _=="number");x.length>0&&(i.required=x)}},gqe=(t,e,r,n)=>{const i=t._zod.def,a=Vo(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"}]},yqe=(t,e,r,n)=>{const i=t._zod.def;Vo(i.innerType,e,n);const a=e.seen.get(t);a.ref=i.innerType},xqe=(t,e,r,n)=>{const i=t._zod.def;Vo(i.innerType,e,n);const a=e.seen.get(t);a.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))},_qe=(t,e,r,n)=>{const i=t._zod.def;Vo(i.innerType,e,n);const a=e.seen.get(t);a.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},vqe=(t,e,r,n)=>{const i=t._zod.def;Vo(i.innerType,e,n);const a=e.seen.get(t);a.ref=i.innerType;let c;try{c=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=c},bqe=(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;Vo(c,e,n);const s=e.seen.get(t);s.ref=c},wqe=(t,e,r,n)=>{const i=t._zod.def;Vo(i.innerType,e,n);const a=e.seen.get(t);a.ref=i.innerType,r.readOnly=!0},Jye=(t,e,r,n)=>{const i=t._zod.def;Vo(i.innerType,e,n);const a=e.seen.get(t);a.ref=i.innerType},Sqe=Er("ZodISODateTime",(t,e)=>{TVe.init(t,e),so.init(t,e)});function Tqe(t){return I8e(Sqe,t)}const Eqe=Er("ZodISODate",(t,e)=>{EVe.init(t,e),so.init(t,e)});function Aqe(t){return P8e(Eqe,t)}const kqe=Er("ZodISOTime",(t,e)=>{AVe.init(t,e),so.init(t,e)});function Cqe(t){return N8e(kqe,t)}const jqe=Er("ZodISODuration",(t,e)=>{kVe.init(t,e),so.init(t,e)});function Iqe(t){return R8e(jqe,t)}const exe=(t,e)=>{Lye.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>g6e(t,r)},flatten:{value:r=>m6e(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,_6,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,_6,2)}},isEmpty:{get(){return t.issues.length===0}}})},Pqe=Er("ZodError",exe),nh=Er("ZodError",exe,{Parent:Error}),Nqe=I9(nh),Rqe=P9(nh),Lqe=LM(nh),Dqe=DM(nh),Oqe=_6e(nh),Mqe=v6e(nh),Fqe=b6e(nh),Bqe=w6e(nh),zqe=S6e(nh),$qe=T6e(nh),Uqe=E6e(nh),Vqe=A6e(nh),pte=new WeakMap;function GC(t,e,r){const n=Object.getPrototypeOf(t);let i=pte.get(n);if(i||(i=new Set,pte.set(n,i)),!i.has(e)){i.add(e);for(const a in r){const c=r[a];Object.defineProperty(n,a,{configurable:!0,enumerable:!1,get(){const s=c.bind(this);return Object.defineProperty(this,a,{configurable:!0,writable:!0,enumerable:!0,value:s}),s},set(s){Object.defineProperty(this,a,{configurable:!0,writable:!0,enumerable:!0,value:s})}})}}}const io=Er("ZodType",(t,e)=>(no.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:nD(t,"input"),output:nD(t,"output")}}),t.toJSONSchema=eqe(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>Nqe(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Lqe(t,r,n),t.parseAsync=async(r,n)=>Rqe(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Dqe(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>Oqe(t,r,n),t.decode=(r,n)=>Mqe(t,r,n),t.encodeAsync=async(r,n)=>Fqe(t,r,n),t.decodeAsync=async(r,n)=>Bqe(t,r,n),t.safeEncode=(r,n)=>zqe(t,r,n),t.safeDecode=(r,n)=>$qe(t,r,n),t.safeEncodeAsync=async(r,n)=>Uqe(t,r,n),t.safeDecodeAsync=async(r,n)=>Vqe(t,r,n),GC(t,"ZodType",{check(...r){const n=this.def;return this.clone(sx(n,{checks:[...n.checks??[],...r.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return ax(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(BGe(r,n))},superRefine(r,n){return this.check(zGe(r,n))},overwrite(r){return this.check(TS(r))},optional(){return xte(this)},exactOptional(){return AGe(this)},nullable(){return _te(this)},nullish(){return xte(_te(this))},nonoptional(r){return NGe(this,r)},array(){return mGe(this)},or(r){return xGe([this,r])},and(r){return vGe(this,r)},transform(r){return vte(this,TGe(r))},default(r){return jGe(this,r)},prefault(r){return PGe(this,r)},catch(r){return LGe(this,r)},pipe(r){return vte(this,r)},readonly(){return MGe(this)},describe(r){const n=this.clone();return K2.add(n,{description:r}),n},meta(...r){if(r.length===0)return K2.get(this);const n=this.clone();return K2.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){var r;return(r=K2.get(t))==null?void 0:r.description},configurable:!0}),t)),txe=Er("_ZodString",(t,e)=>{N9.init(t,e),io.init(t,e),t._zod.processJSONSchema=(n,i,a)=>rqe(t,n,i);const r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,GC(t,"_ZodString",{regex(...n){return this.check(B8e(...n))},includes(...n){return this.check(U8e(...n))},startsWith(...n){return this.check(V8e(...n))},endsWith(...n){return this.check(q8e(...n))},min(...n){return this.check(rD(...n))},max(...n){return this.check(Kye(...n))},length(...n){return this.check(Yye(...n))},nonempty(...n){return this.check(rD(1,...n))},lowercase(n){return this.check(z8e(n))},uppercase(n){return this.check($8e(n))},trim(){return this.check(H8e())},normalize(...n){return this.check(G8e(...n))},toLowerCase(){return this.check(W8e())},toUpperCase(){return this.check(K8e())},slugify(){return this.check(Y8e())}})}),qqe=Er("ZodString",(t,e)=>{N9.init(t,e),txe.init(t,e),t.email=r=>t.check(c8e(Gqe,r)),t.url=r=>t.check(p8e(Hqe,r)),t.jwt=r=>t.check(j8e(oGe,r)),t.emoji=r=>t.check(m8e(Wqe,r)),t.guid=r=>t.check(ute(mte,r)),t.uuid=r=>t.check(u8e(gN,r)),t.uuidv4=r=>t.check(d8e(gN,r)),t.uuidv6=r=>t.check(h8e(gN,r)),t.uuidv7=r=>t.check(f8e(gN,r)),t.nanoid=r=>t.check(g8e(Kqe,r)),t.guid=r=>t.check(ute(mte,r)),t.cuid=r=>t.check(y8e(Yqe,r)),t.cuid2=r=>t.check(x8e(Zqe,r)),t.ulid=r=>t.check(_8e(Xqe,r)),t.base64=r=>t.check(A8e(iGe,r)),t.base64url=r=>t.check(k8e(sGe,r)),t.xid=r=>t.check(v8e(Qqe,r)),t.ksuid=r=>t.check(b8e(Jqe,r)),t.ipv4=r=>t.check(w8e(eGe,r)),t.ipv6=r=>t.check(S8e(tGe,r)),t.cidrv4=r=>t.check(T8e(rGe,r)),t.cidrv6=r=>t.check(E8e(nGe,r)),t.e164=r=>t.check(C8e(aGe,r)),t.datetime=r=>t.check(Tqe(r)),t.date=r=>t.check(Aqe(r)),t.time=r=>t.check(Cqe(r)),t.duration=r=>t.check(Iqe(r))});function Xi(t){return l8e(qqe,t)}const so=Er("ZodStringFormat",(t,e)=>{Ua.init(t,e),txe.init(t,e)}),Gqe=Er("ZodEmail",(t,e)=>{mVe.init(t,e),so.init(t,e)}),mte=Er("ZodGUID",(t,e)=>{fVe.init(t,e),so.init(t,e)}),gN=Er("ZodUUID",(t,e)=>{pVe.init(t,e),so.init(t,e)}),Hqe=Er("ZodURL",(t,e)=>{gVe.init(t,e),so.init(t,e)}),Wqe=Er("ZodEmoji",(t,e)=>{yVe.init(t,e),so.init(t,e)}),Kqe=Er("ZodNanoID",(t,e)=>{xVe.init(t,e),so.init(t,e)}),Yqe=Er("ZodCUID",(t,e)=>{_Ve.init(t,e),so.init(t,e)}),Zqe=Er("ZodCUID2",(t,e)=>{vVe.init(t,e),so.init(t,e)}),Xqe=Er("ZodULID",(t,e)=>{bVe.init(t,e),so.init(t,e)}),Qqe=Er("ZodXID",(t,e)=>{wVe.init(t,e),so.init(t,e)}),Jqe=Er("ZodKSUID",(t,e)=>{SVe.init(t,e),so.init(t,e)}),eGe=Er("ZodIPv4",(t,e)=>{CVe.init(t,e),so.init(t,e)}),tGe=Er("ZodIPv6",(t,e)=>{jVe.init(t,e),so.init(t,e)}),rGe=Er("ZodCIDRv4",(t,e)=>{IVe.init(t,e),so.init(t,e)}),nGe=Er("ZodCIDRv6",(t,e)=>{PVe.init(t,e),so.init(t,e)}),iGe=Er("ZodBase64",(t,e)=>{NVe.init(t,e),so.init(t,e)}),sGe=Er("ZodBase64URL",(t,e)=>{LVe.init(t,e),so.init(t,e)}),aGe=Er("ZodE164",(t,e)=>{DVe.init(t,e),so.init(t,e)}),oGe=Er("ZodJWT",(t,e)=>{MVe.init(t,e),so.init(t,e)}),rxe=Er("ZodNumber",(t,e)=>{qye.init(t,e),io.init(t,e),t._zod.processJSONSchema=(n,i,a)=>nqe(t,n,i),GC(t,"ZodNumber",{gt(n,i){return this.check(hte(n,i))},gte(n,i){return this.check(NB(n,i))},min(n,i){return this.check(NB(n,i))},lt(n,i){return this.check(dte(n,i))},lte(n,i){return this.check(PB(n,i))},max(n,i){return this.check(PB(n,i))},int(n){return this.check(gte(n))},safe(n){return this.check(gte(n))},positive(n){return this.check(hte(0,n))},nonnegative(n){return this.check(NB(0,n))},negative(n){return this.check(dte(0,n))},nonpositive(n){return this.check(PB(0,n))},multipleOf(n,i){return this.check(fte(n,i))},step(n,i){return this.check(fte(n,i))},finite(){return this}});const r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function yA(t){return L8e(rxe,t)}const lGe=Er("ZodNumberFormat",(t,e)=>{FVe.init(t,e),rxe.init(t,e)});function gte(t){return D8e(lGe,t)}const cGe=Er("ZodBoolean",(t,e)=>{BVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>iqe(t,r,n)});function uGe(t){return O8e(cGe,t)}const dGe=Er("ZodUnknown",(t,e)=>{zVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>aqe()});function b6(){return M8e(dGe)}const hGe=Er("ZodNever",(t,e)=>{$Ve.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>sqe(t,r,n)});function fGe(t){return F8e(hGe,t)}const pGe=Er("ZodArray",(t,e)=>{UVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>dqe(t,r,n,i),t.element=e.element,GC(t,"ZodArray",{min(r,n){return this.check(rD(r,n))},nonempty(r){return this.check(rD(1,r))},max(r,n){return this.check(Kye(r,n))},length(r,n){return this.check(Yye(r,n))},unwrap(){return this.element}})});function mGe(t,e){return Z8e(pGe,t,e)}const gGe=Er("ZodObject",(t,e)=>{qVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>hqe(t,r,n,i),Ws(t,"shape",()=>e.shape),GC(t,"ZodObject",{keyof(){return MM(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:b6()})},loose(){return this.clone({...this._zod.def,catchall:b6()})},strict(){return this.clone({...this._zod.def,catchall:fGe()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return c6e(this,r)},safeExtend(r){return u6e(this,r)},merge(r){return d6e(this,r)},pick(r){return o6e(this,r)},omit(r){return l6e(this,r)},partial(...r){return h6e(nxe,this,r[0])},required(...r){return f6e(ixe,this,r[0])}})});function ox(t,e){const r={type:"object",shape:t??{},...$n(e)};return new gGe(r)}const yGe=Er("ZodUnion",(t,e)=>{GVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>fqe(t,r,n,i),t.options=e.options});function xGe(t,e){return new yGe({type:"union",options:t,...$n(e)})}const _Ge=Er("ZodIntersection",(t,e)=>{HVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>pqe(t,r,n,i)});function vGe(t,e){return new _Ge({type:"intersection",left:t,right:e})}const yte=Er("ZodRecord",(t,e)=>{WVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>mqe(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function bGe(t,e,r){return!e||!e._zod?new yte({type:"record",keyType:Xi(),valueType:t,...$n(e)}):new yte({type:"record",keyType:t,valueType:e,...$n(r)})}const w6=Er("ZodEnum",(t,e)=>{KVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(n,i,a)=>oqe(t,n,i),t.enum=e.entries,t.options=Object.values(e.entries);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 w6({...e,checks:[],...$n(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 w6({...e,checks:[],...$n(i),entries:a})}});function MM(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new w6({type:"enum",entries:r,...$n(e)})}const wGe=Er("ZodLiteral",(t,e)=>{YVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>lqe(t,r,n),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 iD(t,e){return new wGe({type:"literal",values:Array.isArray(t)?t:[t],...$n(e)})}const SGe=Er("ZodTransform",(t,e)=>{ZVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>uqe(t,r),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new jye(t.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(fk(a,r.value,e));else{const c=a;c.fatal&&(c.continue=!1),c.code??(c.code="custom"),c.input??(c.input=r.value),c.inst??(c.inst=t),r.issues.push(fk(c))}};const i=e.transform(r.value,r);return i instanceof Promise?i.then(a=>(r.value=a,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}});function TGe(t){return new SGe({type:"transform",transform:t})}const nxe=Er("ZodOptional",(t,e)=>{Wye.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Jye(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function xte(t){return new nxe({type:"optional",innerType:t})}const EGe=Er("ZodExactOptional",(t,e)=>{XVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>Jye(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function AGe(t){return new EGe({type:"optional",innerType:t})}const kGe=Er("ZodNullable",(t,e)=>{QVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>gqe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function _te(t){return new kGe({type:"nullable",innerType:t})}const CGe=Er("ZodDefault",(t,e)=>{JVe.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>xqe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function jGe(t,e){return new CGe({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Nye(e)}})}const IGe=Er("ZodPrefault",(t,e)=>{e8e.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>_qe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function PGe(t,e){return new IGe({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Nye(e)}})}const ixe=Er("ZodNonOptional",(t,e)=>{t8e.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>yqe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function NGe(t,e){return new ixe({type:"nonoptional",innerType:t,...$n(e)})}const RGe=Er("ZodCatch",(t,e)=>{r8e.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>vqe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function LGe(t,e){return new RGe({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const DGe=Er("ZodPipe",(t,e)=>{n8e.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>bqe(t,r,n,i),t.in=e.in,t.out=e.out});function vte(t,e){return new DGe({type:"pipe",in:t,out:e})}const OGe=Er("ZodReadonly",(t,e)=>{i8e.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>wqe(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function MGe(t){return new OGe({type:"readonly",innerType:t})}const FGe=Er("ZodCustom",(t,e)=>{s8e.init(t,e),io.init(t,e),t._zod.processJSONSchema=(r,n,i)=>cqe(t,r)});function BGe(t,e={}){return X8e(FGe,t,e)}function zGe(t,e){return Q8e(t,e)}var $Ge="Label",sxe=P.forwardRef((t,e)=>o.jsx(rn.label,{...t,ref:e,onMouseDown:r=>{var i;r.target.closest("button, input, select, textarea")||((i=t.onMouseDown)==null||i.call(t,r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));sxe.displayName=$Ge;var axe=sxe;const UGe=oS("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Mr=P.forwardRef(({className:t,...e},r)=>o.jsx(axe,{ref:r,className:sr(UGe(),t),...e}));Mr.displayName=axe.displayName;const R9=LUe,oxe=P.createContext({}),rl=({...t})=>o.jsx(oxe.Provider,{value:{name:t.name},children:o.jsx(FUe,{...t})}),FM=()=>{const t=P.useContext(oxe),e=P.useContext(lxe),{getFieldState:r,formState:n}=RM(),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}},lxe=P.createContext({}),Fo=P.forwardRef(({className:t,...e},r)=>{const n=P.useId();return o.jsx(lxe.Provider,{value:{id:n},children:o.jsx("div",{ref:r,className:sr("space-y-2",t),...e})})});Fo.displayName="FormItem";const Bo=P.forwardRef(({className:t,...e},r)=>{const{error:n,formItemId:i}=FM();return o.jsx(Mr,{ref:r,className:sr(n&&"text-destructive",t),htmlFor:i,...e})});Bo.displayName="FormLabel";const zo=P.forwardRef(({...t},e)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:a}=FM();return o.jsx(che,{ref:e,id:n,"aria-describedby":r?`${i} ${a}`:`${i}`,"aria-invalid":!!r,...t})});zo.displayName="FormControl";const PR=P.forwardRef(({className:t,...e},r)=>{const{formDescriptionId:n}=FM();return o.jsx("p",{ref:r,id:n,className:sr("text-sm text-muted-foreground",t),...e})});PR.displayName="FormDescription";const Gh=P.forwardRef(({className:t,children:e,...r},n)=>{const{error:i,formMessageId:a}=FM(),c=i?String(i==null?void 0:i.message):e;return c?o.jsx("p",{ref:n,id:a,className:sr("text-sm font-medium text-destructive",t),...r,children:c}):null});Gh.displayName="FormMessage";const Ur=P.forwardRef(({className:t,type:e,...r},n)=>o.jsx("input",{type:e,className:sr("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}));Ur.displayName="Input";function HC(t){const e=P.useRef({value:t,previous:t});return P.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var VGe=[" ","Enter","ArrowUp","ArrowDown"],qGe=[" ","Enter"],A0="Select",[BM,zM,GGe]=wC(A0),[ES,vUt]=Ho(A0,[GGe,nx]),$M=nx(),[HGe,lx]=ES(A0),[WGe,KGe]=ES(A0),cxe=t=>{const{__scopeSelect:e,children:r,open:n,defaultOpen:i,onOpenChange:a,value:c,defaultValue:s,onValueChange:f,dir:m,name:x,autoComplete:_,disabled:T,required:E,form:C}=t,N=$M(e),[R,D]=P.useState(null),[M,B]=P.useState(null),[V,G]=P.useState(!1),W=$0(m),[X,Q]=ad({prop:n,defaultProp:i??!1,onChange:a,caller:A0}),[re,se]=ad({prop:c,defaultProp:s,onChange:f,caller:A0}),ue=P.useRef(null),_e=R?C||!!R.closest("form"):!0,[Se,ve]=P.useState(new Set),Oe=Array.from(Se).map(Ae=>Ae.props.value).join(";");return o.jsx(cM,{...N,children:o.jsxs(HGe,{required:E,scope:e,trigger:R,onTriggerChange:D,valueNode:M,onValueNodeChange:B,valueNodeHasChildren:V,onValueNodeHasChildrenChange:G,contentId:Cl(),value:re,onValueChange:se,open:X,onOpenChange:Q,dir:W,triggerPointerDownPosRef:ue,disabled:T,children:[o.jsx(BM.Provider,{scope:e,children:o.jsx(WGe,{scope:t.__scopeSelect,onNativeOptionAdd:P.useCallback(Ae=>{ve(we=>new Set(we).add(Ae))},[]),onNativeOptionRemove:P.useCallback(Ae=>{ve(we=>{const ge=new Set(we);return ge.delete(Ae),ge})},[]),children:r})}),_e?o.jsxs(Lxe,{"aria-hidden":!0,required:E,tabIndex:-1,name:x,autoComplete:_,value:re,onChange:Ae=>se(Ae.target.value),disabled:T,form:C,children:[re===void 0?o.jsx("option",{value:""}):null,Array.from(Se)]},Oe):null]})})};cxe.displayName=A0;var uxe="SelectTrigger",dxe=P.forwardRef((t,e)=>{const{__scopeSelect:r,disabled:n=!1,...i}=t,a=$M(r),c=lx(uxe,r),s=c.disabled||n,f=Wn(e,c.onTriggerChange),m=zM(r),x=P.useRef("touch"),[_,T,E]=Oxe(N=>{const R=m().filter(B=>!B.disabled),D=R.find(B=>B.value===c.value),M=Mxe(R,N,D);M!==void 0&&c.onValueChange(M.value)}),C=N=>{s||(c.onOpenChange(!0),E()),N&&(c.triggerPointerDownPosRef.current={x:Math.round(N.pageX),y:Math.round(N.pageY)})};return o.jsx(OC,{asChild:!0,...a,children:o.jsx(rn.button,{type:"button",role:"combobox","aria-controls":c.contentId,"aria-expanded":c.open,"aria-required":c.required,"aria-autocomplete":"none",dir:c.dir,"data-state":c.open?"open":"closed",disabled:s,"data-disabled":s?"":void 0,"data-placeholder":Dxe(c.value)?"":void 0,...i,ref:f,onClick:Or(i.onClick,N=>{N.currentTarget.focus(),x.current!=="mouse"&&C(N)}),onPointerDown:Or(i.onPointerDown,N=>{x.current=N.pointerType;const R=N.target;R.hasPointerCapture(N.pointerId)&&R.releasePointerCapture(N.pointerId),N.button===0&&N.ctrlKey===!1&&N.pointerType==="mouse"&&(C(N),N.preventDefault())}),onKeyDown:Or(i.onKeyDown,N=>{const R=_.current!=="";!(N.ctrlKey||N.altKey||N.metaKey)&&N.key.length===1&&T(N.key),!(R&&N.key===" ")&&VGe.includes(N.key)&&(C(),N.preventDefault())})})})});dxe.displayName=uxe;var hxe="SelectValue",fxe=P.forwardRef((t,e)=>{const{__scopeSelect:r,className:n,style:i,children:a,placeholder:c="",...s}=t,f=lx(hxe,r),{onValueNodeHasChildrenChange:m}=f,x=a!==void 0,_=Wn(e,f.onValueNodeChange);return Io(()=>{m(x)},[m,x]),o.jsx(rn.span,{...s,ref:_,style:{pointerEvents:"none"},children:Dxe(f.value)?o.jsx(o.Fragment,{children:c}):a})});fxe.displayName=hxe;var YGe="SelectIcon",pxe=P.forwardRef((t,e)=>{const{__scopeSelect:r,children:n,...i}=t;return o.jsx(rn.span,{"aria-hidden":!0,...i,ref:e,children:n||"▼"})});pxe.displayName=YGe;var ZGe="SelectPortal",mxe=t=>o.jsx(aS,{asChild:!0,...t});mxe.displayName=ZGe;var k0="SelectContent",gxe=P.forwardRef((t,e)=>{const r=lx(k0,t.__scopeSelect),[n,i]=P.useState();if(Io(()=>{i(new DocumentFragment)},[]),!r.open){const a=n;return a?zm.createPortal(o.jsx(yxe,{scope:t.__scopeSelect,children:o.jsx(BM.Slot,{scope:t.__scopeSelect,children:o.jsx("div",{children:t.children})})}),a):null}return o.jsx(xxe,{...t,ref:e})});gxe.displayName=k0;var jh=10,[yxe,cx]=ES(k0),XGe="SelectContentImpl",QGe=Fy("SelectContent.RemoveScroll"),xxe=P.forwardRef((t,e)=>{const{__scopeSelect:r,position:n="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:a,onPointerDownOutside:c,side:s,sideOffset:f,align:m,alignOffset:x,arrowPadding:_,collisionBoundary:T,collisionPadding:E,sticky:C,hideWhenDetached:N,avoidCollisions:R,...D}=t,M=lx(k0,r),[B,V]=P.useState(null),[G,W]=P.useState(null),X=Wn(e,_t=>V(_t)),[Q,re]=P.useState(null),[se,ue]=P.useState(null),_e=zM(r),[Se,ve]=P.useState(!1),Oe=P.useRef(!1);P.useEffect(()=>{if(B)return rM(B)},[B]),eM();const Ae=P.useCallback(_t=>{const[Vt,...mt]=_e().map(wt=>wt.ref.current),[Pt]=mt.slice(-1),er=document.activeElement;for(const wt of _t)if(wt===er||(wt==null||wt.scrollIntoView({block:"nearest"}),wt===Vt&&G&&(G.scrollTop=0),wt===Pt&&G&&(G.scrollTop=G.scrollHeight),wt==null||wt.focus(),document.activeElement!==er))return},[_e,G]),we=P.useCallback(()=>Ae([Q,B]),[Ae,Q,B]);P.useEffect(()=>{Se&&we()},[Se,we]);const{onOpenChange:ge,triggerPointerDownPosRef:Ne}=M;P.useEffect(()=>{if(B){let _t={x:0,y:0};const Vt=Pt=>{var er,wt;_t={x:Math.abs(Math.round(Pt.pageX)-(((er=Ne.current)==null?void 0:er.x)??0)),y:Math.abs(Math.round(Pt.pageY)-(((wt=Ne.current)==null?void 0:wt.y)??0))}},mt=Pt=>{_t.x<=10&&_t.y<=10?Pt.preventDefault():B.contains(Pt.target)||ge(!1),document.removeEventListener("pointermove",Vt),Ne.current=null};return Ne.current!==null&&(document.addEventListener("pointermove",Vt),document.addEventListener("pointerup",mt,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Vt),document.removeEventListener("pointerup",mt,{capture:!0})}}},[B,ge,Ne]),P.useEffect(()=>{const _t=()=>ge(!1);return window.addEventListener("blur",_t),window.addEventListener("resize",_t),()=>{window.removeEventListener("blur",_t),window.removeEventListener("resize",_t)}},[ge]);const[Ie,Te]=Oxe(_t=>{const Vt=_e().filter(er=>!er.disabled),mt=Vt.find(er=>er.ref.current===document.activeElement),Pt=Mxe(Vt,_t,mt);Pt&&setTimeout(()=>Pt.ref.current.focus())}),be=P.useCallback((_t,Vt,mt)=>{const Pt=!Oe.current&&!mt;(M.value!==void 0&&M.value===Vt||Pt)&&(re(_t),Pt&&(Oe.current=!0))},[M.value]),We=P.useCallback(()=>B==null?void 0:B.focus(),[B]),rt=P.useCallback((_t,Vt,mt)=>{const Pt=!Oe.current&&!mt;(M.value!==void 0&&M.value===Vt||Pt)&&ue(_t)},[M.value]),at=n==="popper"?S6:_xe,Et=at===S6?{side:s,sideOffset:f,align:m,alignOffset:x,arrowPadding:_,collisionBoundary:T,collisionPadding:E,sticky:C,hideWhenDetached:N,avoidCollisions:R}:{};return o.jsx(yxe,{scope:r,content:B,viewport:G,onViewportChange:W,itemRefCallback:be,selectedItem:Q,onItemLeave:We,itemTextRefCallback:rt,focusSelectedItem:we,selectedItemText:se,position:n,isPositioned:Se,searchRef:Ie,children:o.jsx(IC,{as:QGe,allowPinchZoom:!0,children:o.jsx(jC,{asChild:!0,trapped:M.open,onMountAutoFocus:_t=>{_t.preventDefault()},onUnmountAutoFocus:Or(i,_t=>{var Vt;(Vt=M.trigger)==null||Vt.focus({preventScroll:!0}),_t.preventDefault()}),children:o.jsx(F0,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:a,onPointerDownOutside:c,onFocusOutside:_t=>_t.preventDefault(),onDismiss:()=>M.onOpenChange(!1),children:o.jsx(at,{role:"listbox",id:M.contentId,"data-state":M.open?"open":"closed",dir:M.dir,onContextMenu:_t=>_t.preventDefault(),...D,...Et,onPlaced:()=>ve(!0),ref:X,style:{display:"flex",flexDirection:"column",outline:"none",...D.style},onKeyDown:Or(D.onKeyDown,_t=>{const Vt=_t.ctrlKey||_t.altKey||_t.metaKey;if(_t.key==="Tab"&&_t.preventDefault(),!Vt&&_t.key.length===1&&Te(_t.key),["ArrowUp","ArrowDown","Home","End"].includes(_t.key)){let Pt=_e().filter(er=>!er.disabled).map(er=>er.ref.current);if(["ArrowUp","End"].includes(_t.key)&&(Pt=Pt.slice().reverse()),["ArrowUp","ArrowDown"].includes(_t.key)){const er=_t.target,wt=Pt.indexOf(er);Pt=Pt.slice(wt+1)}setTimeout(()=>Ae(Pt)),_t.preventDefault()}})})})})})})});xxe.displayName=XGe;var JGe="SelectItemAlignedPosition",_xe=P.forwardRef((t,e)=>{const{__scopeSelect:r,onPlaced:n,...i}=t,a=lx(k0,r),c=cx(k0,r),[s,f]=P.useState(null),[m,x]=P.useState(null),_=Wn(e,X=>x(X)),T=zM(r),E=P.useRef(!1),C=P.useRef(!0),{viewport:N,selectedItem:R,selectedItemText:D,focusSelectedItem:M}=c,B=P.useCallback(()=>{if(a.trigger&&a.valueNode&&s&&m&&N&&R&&D){const X=a.trigger.getBoundingClientRect(),Q=m.getBoundingClientRect(),re=a.valueNode.getBoundingClientRect(),se=D.getBoundingClientRect();if(a.dir!=="rtl"){const er=se.left-Q.left,wt=re.left-er,or=X.left-wt,Sr=X.width+or,nn=Math.max(Sr,Q.width),lr=window.innerWidth-jh,yr=hk(wt,[jh,Math.max(jh,lr-nn)]);s.style.minWidth=Sr+"px",s.style.left=yr+"px"}else{const er=Q.right-se.right,wt=window.innerWidth-re.right-er,or=window.innerWidth-X.right-wt,Sr=X.width+or,nn=Math.max(Sr,Q.width),lr=window.innerWidth-jh,yr=hk(wt,[jh,Math.max(jh,lr-nn)]);s.style.minWidth=Sr+"px",s.style.right=yr+"px"}const ue=T(),_e=window.innerHeight-jh*2,Se=N.scrollHeight,ve=window.getComputedStyle(m),Oe=parseInt(ve.borderTopWidth,10),Ae=parseInt(ve.paddingTop,10),we=parseInt(ve.borderBottomWidth,10),ge=parseInt(ve.paddingBottom,10),Ne=Oe+Ae+Se+ge+we,Ie=Math.min(R.offsetHeight*5,Ne),Te=window.getComputedStyle(N),be=parseInt(Te.paddingTop,10),We=parseInt(Te.paddingBottom,10),rt=X.top+X.height/2-jh,at=_e-rt,Et=R.offsetHeight/2,_t=R.offsetTop+Et,Vt=Oe+Ae+_t,mt=Ne-Vt;if(Vt<=rt){const er=ue.length>0&&R===ue[ue.length-1].ref.current;s.style.bottom="0px";const wt=m.clientHeight-N.offsetTop-N.offsetHeight,or=Math.max(at,Et+(er?We:0)+wt+we),Sr=Vt+or;s.style.height=Sr+"px"}else{const er=ue.length>0&&R===ue[0].ref.current;s.style.top="0px";const or=Math.max(rt,Oe+N.offsetTop+(er?be:0)+Et)+mt;s.style.height=or+"px",N.scrollTop=Vt-rt+N.offsetTop}s.style.margin=`${jh}px 0`,s.style.minHeight=Ie+"px",s.style.maxHeight=_e+"px",n==null||n(),requestAnimationFrame(()=>E.current=!0)}},[T,a.trigger,a.valueNode,s,m,N,R,D,a.dir,n]);Io(()=>B(),[B]);const[V,G]=P.useState();Io(()=>{m&&G(window.getComputedStyle(m).zIndex)},[m]);const W=P.useCallback(X=>{X&&C.current===!0&&(B(),M==null||M(),C.current=!1)},[B,M]);return o.jsx(t9e,{scope:r,contentWrapper:s,shouldExpandOnScrollRef:E,onScrollButtonChange:W,children:o.jsx("div",{ref:f,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:V},children:o.jsx(rn.div,{...i,ref:_,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});_xe.displayName=JGe;var e9e="SelectPopperPosition",S6=P.forwardRef((t,e)=>{const{__scopeSelect:r,align:n="start",collisionPadding:i=jh,...a}=t,c=$M(r);return o.jsx(uM,{...c,...a,ref:e,align:n,collisionPadding:i,style:{boxSizing:"border-box",...a.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)"}})});S6.displayName=e9e;var[t9e,L9]=ES(k0,{}),T6="SelectViewport",vxe=P.forwardRef((t,e)=>{const{__scopeSelect:r,nonce:n,...i}=t,a=cx(T6,r),c=L9(T6,r),s=Wn(e,a.onViewportChange),f=P.useRef(0);return o.jsxs(o.Fragment,{children:[o.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:n}),o.jsx(BM.Slot,{scope:r,children:o.jsx(rn.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:s,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:Or(i.onScroll,m=>{const x=m.currentTarget,{contentWrapper:_,shouldExpandOnScrollRef:T}=c;if(T!=null&&T.current&&_){const E=Math.abs(f.current-x.scrollTop);if(E>0){const C=window.innerHeight-jh*2,N=parseFloat(_.style.minHeight),R=parseFloat(_.style.height),D=Math.max(N,R);if(D0?V:0,_.style.justifyContent="flex-end")}}}f.current=x.scrollTop})})})]})});vxe.displayName=T6;var bxe="SelectGroup",[r9e,n9e]=ES(bxe),wxe=P.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=Cl();return o.jsx(r9e,{scope:r,id:i,children:o.jsx(rn.div,{role:"group","aria-labelledby":i,...n,ref:e})})});wxe.displayName=bxe;var Sxe="SelectLabel",Txe=P.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=n9e(Sxe,r);return o.jsx(rn.div,{id:i.id,...n,ref:e})});Txe.displayName=Sxe;var sD="SelectItem",[i9e,Exe]=ES(sD),Axe=P.forwardRef((t,e)=>{const{__scopeSelect:r,value:n,disabled:i=!1,textValue:a,...c}=t,s=lx(sD,r),f=cx(sD,r),m=s.value===n,[x,_]=P.useState(a??""),[T,E]=P.useState(!1),C=Wn(e,M=>{var B;return(B=f.itemRefCallback)==null?void 0:B.call(f,M,n,i)}),N=Cl(),R=P.useRef("touch"),D=()=>{i||(s.onValueChange(n),s.onOpenChange(!1))};if(n==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return o.jsx(i9e,{scope:r,value:n,disabled:i,textId:N,isSelected:m,onItemTextChange:P.useCallback(M=>{_(B=>B||((M==null?void 0:M.textContent)??"").trim())},[]),children:o.jsx(BM.ItemSlot,{scope:r,value:n,disabled:i,textValue:x,children:o.jsx(rn.div,{role:"option","aria-labelledby":N,"data-highlighted":T?"":void 0,"aria-selected":m&&T,"data-state":m?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...c,ref:C,onFocus:Or(c.onFocus,()=>E(!0)),onBlur:Or(c.onBlur,()=>E(!1)),onClick:Or(c.onClick,()=>{R.current!=="mouse"&&D()}),onPointerUp:Or(c.onPointerUp,()=>{R.current==="mouse"&&D()}),onPointerDown:Or(c.onPointerDown,M=>{R.current=M.pointerType}),onPointerMove:Or(c.onPointerMove,M=>{var B;R.current=M.pointerType,i?(B=f.onItemLeave)==null||B.call(f):R.current==="mouse"&&M.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Or(c.onPointerLeave,M=>{var B;M.currentTarget===document.activeElement&&((B=f.onItemLeave)==null||B.call(f))}),onKeyDown:Or(c.onKeyDown,M=>{var V;((V=f.searchRef)==null?void 0:V.current)!==""&&M.key===" "||(qGe.includes(M.key)&&D(),M.key===" "&&M.preventDefault())})})})})});Axe.displayName=sD;var Y2="SelectItemText",kxe=P.forwardRef((t,e)=>{const{__scopeSelect:r,className:n,style:i,...a}=t,c=lx(Y2,r),s=cx(Y2,r),f=Exe(Y2,r),m=KGe(Y2,r),[x,_]=P.useState(null),T=Wn(e,D=>_(D),f.onItemTextChange,D=>{var M;return(M=s.itemTextRefCallback)==null?void 0:M.call(s,D,f.value,f.disabled)}),E=x==null?void 0:x.textContent,C=P.useMemo(()=>o.jsx("option",{value:f.value,disabled:f.disabled,children:E},f.value),[f.disabled,f.value,E]),{onNativeOptionAdd:N,onNativeOptionRemove:R}=m;return Io(()=>(N(C),()=>R(C)),[N,R,C]),o.jsxs(o.Fragment,{children:[o.jsx(rn.span,{id:f.textId,...a,ref:T}),f.isSelected&&c.valueNode&&!c.valueNodeHasChildren?zm.createPortal(a.children,c.valueNode):null]})});kxe.displayName=Y2;var Cxe="SelectItemIndicator",jxe=P.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t;return Exe(Cxe,r).isSelected?o.jsx(rn.span,{"aria-hidden":!0,...n,ref:e}):null});jxe.displayName=Cxe;var E6="SelectScrollUpButton",Ixe=P.forwardRef((t,e)=>{const r=cx(E6,t.__scopeSelect),n=L9(E6,t.__scopeSelect),[i,a]=P.useState(!1),c=Wn(e,n.onScrollButtonChange);return Io(()=>{if(r.viewport&&r.isPositioned){let s=function(){const m=f.scrollTop>0;a(m)};const f=r.viewport;return s(),f.addEventListener("scroll",s),()=>f.removeEventListener("scroll",s)}},[r.viewport,r.isPositioned]),i?o.jsx(Nxe,{...t,ref:c,onAutoScroll:()=>{const{viewport:s,selectedItem:f}=r;s&&f&&(s.scrollTop=s.scrollTop-f.offsetHeight)}}):null});Ixe.displayName=E6;var A6="SelectScrollDownButton",Pxe=P.forwardRef((t,e)=>{const r=cx(A6,t.__scopeSelect),n=L9(A6,t.__scopeSelect),[i,a]=P.useState(!1),c=Wn(e,n.onScrollButtonChange);return Io(()=>{if(r.viewport&&r.isPositioned){let s=function(){const m=f.scrollHeight-f.clientHeight,x=Math.ceil(f.scrollTop)f.removeEventListener("scroll",s)}},[r.viewport,r.isPositioned]),i?o.jsx(Nxe,{...t,ref:c,onAutoScroll:()=>{const{viewport:s,selectedItem:f}=r;s&&f&&(s.scrollTop=s.scrollTop+f.offsetHeight)}}):null});Pxe.displayName=A6;var Nxe=P.forwardRef((t,e)=>{const{__scopeSelect:r,onAutoScroll:n,...i}=t,a=cx("SelectScrollButton",r),c=P.useRef(null),s=zM(r),f=P.useCallback(()=>{c.current!==null&&(window.clearInterval(c.current),c.current=null)},[]);return P.useEffect(()=>()=>f(),[f]),Io(()=>{var x;const m=s().find(_=>_.ref.current===document.activeElement);(x=m==null?void 0:m.ref.current)==null||x.scrollIntoView({block:"nearest"})},[s]),o.jsx(rn.div,{"aria-hidden":!0,...i,ref:e,style:{flexShrink:0,...i.style},onPointerDown:Or(i.onPointerDown,()=>{c.current===null&&(c.current=window.setInterval(n,50))}),onPointerMove:Or(i.onPointerMove,()=>{var m;(m=a.onItemLeave)==null||m.call(a),c.current===null&&(c.current=window.setInterval(n,50))}),onPointerLeave:Or(i.onPointerLeave,()=>{f()})})}),s9e="SelectSeparator",Rxe=P.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t;return o.jsx(rn.div,{"aria-hidden":!0,...n,ref:e})});Rxe.displayName=s9e;var k6="SelectArrow",a9e=P.forwardRef((t,e)=>{const{__scopeSelect:r,...n}=t,i=$M(r),a=lx(k6,r),c=cx(k6,r);return a.open&&c.position==="popper"?o.jsx(dM,{...i,...n,ref:e}):null});a9e.displayName=k6;var o9e="SelectBubbleInput",Lxe=P.forwardRef(({__scopeSelect:t,value:e,...r},n)=>{const i=P.useRef(null),a=Wn(n,i),c=HC(e);return P.useEffect(()=>{const s=i.current;if(!s)return;const f=window.HTMLSelectElement.prototype,x=Object.getOwnPropertyDescriptor(f,"value").set;if(c!==e&&x){const _=new Event("change",{bubbles:!0});x.call(s,e),s.dispatchEvent(_)}},[c,e]),o.jsx(rn.select,{...r,style:{...mhe,...r.style},ref:a,defaultValue:e})});Lxe.displayName=o9e;function Dxe(t){return t===""||t===void 0}function Oxe(t){const e=fo(t),r=P.useRef(""),n=P.useRef(0),i=P.useCallback(c=>{const s=r.current+c;e(s),function f(m){r.current=m,window.clearTimeout(n.current),m!==""&&(n.current=window.setTimeout(()=>f(""),1e3))}(s)},[e]),a=P.useCallback(()=>{r.current="",window.clearTimeout(n.current)},[]);return P.useEffect(()=>()=>window.clearTimeout(n.current),[]),[r,i,a]}function Mxe(t,e,r){const i=e.length>1&&Array.from(e).every(m=>m===e[0])?e[0]:e,a=r?t.indexOf(r):-1;let c=l9e(t,Math.max(a,0));i.length===1&&(c=c.filter(m=>m!==r));const f=c.find(m=>m.textValue.toLowerCase().startsWith(i.toLowerCase()));return f!==r?f:void 0}function l9e(t,e){return t.map((r,n)=>t[(e+n)%t.length])}var c9e=cxe,Fxe=dxe,u9e=fxe,d9e=pxe,h9e=mxe,Bxe=gxe,f9e=vxe,p9e=wxe,zxe=Txe,$xe=Axe,m9e=kxe,g9e=jxe,Uxe=Ixe,Vxe=Pxe,qxe=Rxe;const Ba=c9e,bUt=p9e,za=u9e,ja=P.forwardRef(({className:t,children:e,...r},n)=>o.jsxs(Fxe,{ref:n,className:sr("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,o.jsx(d9e,{asChild:!0,children:o.jsx(od,{className:"h-4 w-4 opacity-50"})})]}));ja.displayName=Fxe.displayName;const Gxe=P.forwardRef(({className:t,...e},r)=>o.jsx(Uxe,{ref:r,className:sr("flex cursor-default items-center justify-center py-1",t),...e,children:o.jsx(URe,{className:"h-4 w-4"})}));Gxe.displayName=Uxe.displayName;const Hxe=P.forwardRef(({className:t,...e},r)=>o.jsx(Vxe,{ref:r,className:sr("flex cursor-default items-center justify-center py-1",t),...e,children:o.jsx(od,{className:"h-4 w-4"})}));Hxe.displayName=Vxe.displayName;const Ia=P.forwardRef(({className:t,children:e,position:r="popper",...n},i)=>o.jsx(h9e,{children:o.jsxs(Bxe,{ref:i,className:sr("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:[o.jsx(Gxe,{}),o.jsx(f9e,{className:sr("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e}),o.jsx(Hxe,{})]})}));Ia.displayName=Bxe.displayName;const y9e=P.forwardRef(({className:t,...e},r)=>o.jsx(zxe,{ref:r,className:sr("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...e}));y9e.displayName=zxe.displayName;const wn=P.forwardRef(({className:t,children:e,...r},n)=>o.jsxs($xe,{ref:n,className:sr("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:[o.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:o.jsx(g9e,{children:o.jsx(Ao,{className:"h-4 w-4"})})}),o.jsx(m9e,{children:e})]}));wn.displayName=$xe.displayName;const x9e=P.forwardRef(({className:t,...e},r)=>o.jsx(qxe,{ref:r,className:sr("-mx-1 my-1 h-px bg-muted",t),...e}));x9e.displayName=qxe.displayName;const _9e=ox({category:MM(["general","technology","crm","marketing"]),subject:Xi().min(5,"Subject must be at least 5 characters").max(200),description:Xi().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),v9e={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function b9e({trigger:t}){const[e,r]=P.useState(!1),[n,i]=P.useState(!1),{user:a}=qn(),c=S9({resolver:T9(_9e),defaultValues:{category:"general",subject:"",description:""}}),s=async f=>{if(!a){Jt.error("You must be logged in to submit a ticket");return}i(!0);try{const{error:m}=await Le.from("support_tickets").insert({user_id:a.id,category:f.category,subject:f.subject,description:f.description});if(m)throw m;try{await Le.functions.invoke("support-ticket-notify",{body:{category:v9e[f.category],subject:f.subject}})}catch(x){console.log("Notification send attempted:",x)}Jt.success("Support ticket submitted successfully!"),c.reset(),r(!1)}catch(m){console.error("Error submitting ticket:",m),Jt.error("Failed to submit ticket. Please try again.")}finally{i(!1)}};return o.jsxs(ro,{open:e,onOpenChange:r,children:[o.jsx(Kge,{asChild:!0,children:t||o.jsxs(Ut,{variant:"ghost",size:"icon",className:"relative",children:[o.jsx(iLe,{className:"h-5 w-5"}),o.jsx("span",{className:"sr-only",children:"Support"})]})}),o.jsxs($a,{className:"sm:max-w-[500px]",children:[o.jsxs(ul,{children:[o.jsx(Go,{children:"Need Help?"}),o.jsx(ld,{children:"Submit a support ticket and we'll get back to you as soon as possible."})]}),o.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted rounded-lg mb-4",children:[o.jsx(zi,{className:"h-4 w-4 text-muted-foreground"}),o.jsxs("span",{className:"text-sm text-muted-foreground",children:["You can also text us at: ",o.jsx("span",{className:"font-medium text-foreground",children:"1-866-527-8668"})]})]}),o.jsx(R9,{...c,children:o.jsxs("form",{onSubmit:c.handleSubmit(s),className:"space-y-4",children:[o.jsx(rl,{control:c.control,name:"category",render:({field:f})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Category"}),o.jsxs(Ba,{onValueChange:f.onChange,defaultValue:f.value,children:[o.jsx(zo,{children:o.jsx(ja,{children:o.jsx(za,{placeholder:"Select a category"})})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"general",children:"General Support"}),o.jsx(wn,{value:"technology",children:"Technology Support"}),o.jsx(wn,{value:"crm",children:"CRM Support"}),o.jsx(wn,{value:"marketing",children:"Marketing Support"})]})]}),o.jsx(Gh,{})]})}),o.jsx(rl,{control:c.control,name:"subject",render:({field:f})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Subject"}),o.jsx(zo,{children:o.jsx(Ur,{placeholder:"Brief description of your issue",...f})}),o.jsx(Gh,{})]})}),o.jsx(rl,{control:c.control,name:"description",render:({field:f})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Description"}),o.jsx(zo,{children:o.jsx(hd,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...f})}),o.jsx(Gh,{})]})}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(Ut,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),o.jsx(Ut,{type:"submit",disabled:n,children:n?"Submitting...":"Submit Ticket"})]})]})})]})]})}function On(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 Hs(t,e){return t instanceof Date?new t.constructor(e):new Date(e)}function Tl(t,e){const r=On(t);return isNaN(e)?Hs(t,NaN):(e&&r.setDate(r.getDate()+e),r)}function cd(t,e){const r=On(t);if(isNaN(e))return Hs(t,NaN);if(!e)return r;const n=r.getDate(),i=Hs(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 D9=6048e5,w9e=864e5,O9=6e4,M9=36e5,S9e=1e3,yN=43200,bte=1440;let T9e={};function ux(){return T9e}function _c(t,e){var s,f,m,x;const r=ux(),n=(e==null?void 0:e.weekStartsOn)??((f=(s=e==null?void 0:e.locale)==null?void 0:s.options)==null?void 0:f.weekStartsOn)??r.weekStartsOn??((x=(m=r.locale)==null?void 0:m.options)==null?void 0:x.weekStartsOn)??0,i=On(t),a=i.getDay(),c=(a=i.getTime()?r+1:e.getTime()>=c.getTime()?r:r-1}function Hy(t){const e=On(t);return e.setHours(0,0,0,0),e}function Wy(t){const e=On(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 Hh(t,e){const r=Hy(t),n=Hy(e),i=+r-Wy(r),a=+n-Wy(n);return Math.round((i-a)/w9e)}function E9e(t){const e=Wxe(t),r=Hs(t,0);return r.setFullYear(e,0,4),r.setHours(0,0,0,0),Lm(r)}function C6(t,e){const r=e*7;return Tl(t,r)}function A9e(t,e){return cd(t,e*12)}function k9e(t){let e;return t.forEach(function(r){const n=On(r);(e===void 0||e{const n=On(r);(!e||e>n||isNaN(+n))&&(e=n)}),e||new Date(NaN)}function NR(t,e){const r=On(t),n=On(e),i=r.getTime()-n.getTime();return i<0?-1:i>0?1:i}function F9(t){return Hs(t,Date.now())}function Kl(t,e){const r=Hy(t),n=Hy(e);return+r==+n}function B9(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function j6(t){if(!B9(t)&&typeof t!="number")return!1;const e=On(t);return!isNaN(Number(e))}function w1(t,e){const r=On(t),n=On(e),i=r.getFullYear()-n.getFullYear(),a=r.getMonth()-n.getMonth();return i*12+a}function j9e(t,e,r){const n=_c(t,r),i=_c(e,r),a=+n-Wy(n),c=+i-Wy(i);return Math.round((a-c)/D9)}function I9e(t,e){const r=On(t),n=On(e),i=wte(r,n),a=Math.abs(Hh(r,n));r.setDate(r.getDate()-i*a);const c=+(wte(r,n)===-i),s=i*(a-c);return s===0?0:s}function wte(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 P9e(t){return e=>{const n=(t?Math[t]:Math.trunc)(e);return n===0?0:n}}function N9e(t,e){return+On(t)-+On(e)}function R9e(t){const e=On(t);return e.setHours(23,59,59,999),e}function WC(t){const e=On(t),r=e.getMonth();return e.setFullYear(e.getFullYear(),r+1,0),e.setHours(23,59,59,999),e}function L9e(t){const e=On(t);return+R9e(e)==+WC(e)}function D9e(t,e){const r=On(t),n=On(e),i=NR(r,n),a=Math.abs(w1(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 s=NR(r,n)===-i;L9e(On(t))&&a===1&&NR(t,n)===1&&(s=!1),c=i*(a-Number(s))}return c===0?0:c}function O9e(t,e,r){const n=N9e(t,e)/1e3;return P9e(r==null?void 0:r.roundingMethod)(n)}function M9e(t,e){const r=On(t.start),n=On(t.end);let i=+r>+n;const a=i?+r:+n,c=i?n:r;c.setHours(0,0,0,0);let s=1;const f=[];for(;+c<=a;)f.push(On(c)),c.setDate(c.getDate()+s),c.setHours(0,0,0,0);return i?f.reverse():f}function Zc(t){const e=On(t);return e.setDate(1),e.setHours(0,0,0,0),e}function Kxe(t){const e=On(t),r=Hs(t,0);return r.setFullYear(e.getFullYear(),0,1),r.setHours(0,0,0,0),r}function UM(t,e){var s,f,m,x;const r=ux(),n=(e==null?void 0:e.weekStartsOn)??((f=(s=e==null?void 0:e.locale)==null?void 0:s.options)==null?void 0:f.weekStartsOn)??r.weekStartsOn??((x=(m=r.locale)==null?void 0:m.options)==null?void 0:x.weekStartsOn)??0,i=On(t),a=i.getDay(),c=(a{let n;const i=F9e[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 RB(t){return(e={})=>{const r=e.width?String(e.width):t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}const z9e={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},$9e={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},U9e={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},V9e={date:RB({formats:z9e,defaultWidth:"full"}),time:RB({formats:$9e,defaultWidth:"full"}),dateTime:RB({formats:U9e,defaultWidth:"full"})},q9e={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},G9e=(t,e,r,n)=>q9e[t];function x2(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,s=r!=null&&r.width?String(r.width):c;i=t.formattingValues[s]||t.formattingValues[c]}else{const c=t.defaultWidth,s=r!=null&&r.width?String(r.width):t.defaultWidth;i=t.values[s]||t.values[c]}const a=t.argumentCallback?t.argumentCallback(e):e;return i[a]}}const H9e={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},W9e={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},K9e={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"]},Y9e={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"]},Z9e={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"}},X9e={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"}},Q9e=(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"},J9e={ordinalNumber:Q9e,era:x2({values:H9e,defaultWidth:"wide"}),quarter:x2({values:W9e,defaultWidth:"wide",argumentCallback:t=>t-1}),month:x2({values:K9e,defaultWidth:"wide"}),day:x2({values:Y9e,defaultWidth:"wide"}),dayPeriod:x2({values:Z9e,defaultWidth:"wide",formattingValues:X9e,defaultFormattingWidth:"wide"})};function _2(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],s=n&&t.parsePatterns[n]||t.parsePatterns[t.defaultParseWidth],f=Array.isArray(s)?t7e(s,_=>_.test(c)):e7e(s,_=>_.test(c));let m;m=t.valueCallback?t.valueCallback(f):f,m=r.valueCallback?r.valueCallback(m):m;const x=e.slice(c.length);return{value:m,rest:x}}}function e7e(t,e){for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return r}function t7e(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 s=e.slice(i.length);return{value:c,rest:s}}}const n7e=/^(\d+)(th|st|nd|rd)?/i,i7e=/\d+/i,s7e={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},a7e={any:[/^b/i,/^(a|c)/i]},o7e={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},l7e={any:[/1/i,/2/i,/3/i,/4/i]},c7e={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},u7e={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]},d7e={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},h7e={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]},f7e={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},p7e={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}},m7e={ordinalNumber:r7e({matchPattern:n7e,parsePattern:i7e,valueCallback:t=>parseInt(t,10)}),era:_2({matchPatterns:s7e,defaultMatchWidth:"wide",parsePatterns:a7e,defaultParseWidth:"any"}),quarter:_2({matchPatterns:o7e,defaultMatchWidth:"wide",parsePatterns:l7e,defaultParseWidth:"any",valueCallback:t=>t+1}),month:_2({matchPatterns:c7e,defaultMatchWidth:"wide",parsePatterns:u7e,defaultParseWidth:"any"}),day:_2({matchPatterns:d7e,defaultMatchWidth:"wide",parsePatterns:h7e,defaultParseWidth:"any"}),dayPeriod:_2({matchPatterns:f7e,defaultMatchWidth:"any",parsePatterns:p7e,defaultParseWidth:"any"})},VM={code:"en-US",formatDistance:B9e,formatLong:V9e,formatRelative:G9e,localize:J9e,match:m7e,options:{weekStartsOn:0,firstWeekContainsDate:1}};function g7e(t){const e=On(t);return Hh(e,Kxe(e))+1}function z9(t){const e=On(t),r=+Lm(e)-+E9e(e);return Math.round(r/D9)+1}function $9(t,e){var x,_,T,E;const r=On(t),n=r.getFullYear(),i=ux(),a=(e==null?void 0:e.firstWeekContainsDate)??((_=(x=e==null?void 0:e.locale)==null?void 0:x.options)==null?void 0:_.firstWeekContainsDate)??i.firstWeekContainsDate??((E=(T=i.locale)==null?void 0:T.options)==null?void 0:E.firstWeekContainsDate)??1,c=Hs(t,0);c.setFullYear(n+1,0,a),c.setHours(0,0,0,0);const s=_c(c,e),f=Hs(t,0);f.setFullYear(n,0,a),f.setHours(0,0,0,0);const m=_c(f,e);return r.getTime()>=s.getTime()?n+1:r.getTime()>=m.getTime()?n:n-1}function y7e(t,e){var s,f,m,x;const r=ux(),n=(e==null?void 0:e.firstWeekContainsDate)??((f=(s=e==null?void 0:e.locale)==null?void 0:s.options)==null?void 0:f.firstWeekContainsDate)??r.firstWeekContainsDate??((x=(m=r.locale)==null?void 0:m.options)==null?void 0:x.firstWeekContainsDate)??1,i=$9(t,e),a=Hs(t,0);return a.setFullYear(i,0,n),a.setHours(0,0,0,0),_c(a,e)}function U9(t,e){const r=On(t),n=+_c(r,e)-+y7e(r,e);return Math.round(n/D9)+1}function Fs(t,e){const r=t<0?"-":"",n=Math.abs(t).toString().padStart(e,"0");return r+n}const Mg={y(t,e){const r=t.getFullYear(),n=r>0?r:1-r;return Fs(e==="yy"?n%100:n,e.length)},M(t,e){const r=t.getMonth();return e==="M"?String(r+1):Fs(r+1,2)},d(t,e){return Fs(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 Fs(t.getHours()%12||12,e.length)},H(t,e){return Fs(t.getHours(),e.length)},m(t,e){return Fs(t.getMinutes(),e.length)},s(t,e){return Fs(t.getSeconds(),e.length)},S(t,e){const r=e.length,n=t.getMilliseconds(),i=Math.trunc(n*Math.pow(10,r-3));return Fs(i,e.length)}},Ob={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ste={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 Mg.y(t,e)},Y:function(t,e,r,n){const i=$9(t,n),a=i>0?i:1-i;if(e==="YY"){const c=a%100;return Fs(c,2)}return e==="Yo"?r.ordinalNumber(a,{unit:"year"}):Fs(a,e.length)},R:function(t,e){const r=Wxe(t);return Fs(r,e.length)},u:function(t,e){const r=t.getFullYear();return Fs(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 Fs(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 Fs(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 Mg.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 Fs(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=U9(t,n);return e==="wo"?r.ordinalNumber(i,{unit:"week"}):Fs(i,e.length)},I:function(t,e,r){const n=z9(t);return e==="Io"?r.ordinalNumber(n,{unit:"week"}):Fs(n,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):Mg.d(t,e)},D:function(t,e,r){const n=g7e(t);return e==="Do"?r.ordinalNumber(n,{unit:"dayOfYear"}):Fs(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 Fs(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 Fs(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 Fs(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=Ob.noon:n===0?i=Ob.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=Ob.evening:n>=12?i=Ob.afternoon:n>=4?i=Ob.morning:i=Ob.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 Mg.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):Mg.H(t,e)},K:function(t,e,r){const n=t.getHours()%12;return e==="Ko"?r.ordinalNumber(n,{unit:"hour"}):Fs(n,e.length)},k:function(t,e,r){let n=t.getHours();return n===0&&(n=24),e==="ko"?r.ordinalNumber(n,{unit:"hour"}):Fs(n,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):Mg.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):Mg.s(t,e)},S:function(t,e){return Mg.S(t,e)},X:function(t,e,r){const n=t.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return Ete(n);case"XXXX":case"XX":return O_(n);case"XXXXX":case"XXX":default:return O_(n,":")}},x:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"x":return Ete(n);case"xxxx":case"xx":return O_(n);case"xxxxx":case"xxx":default:return O_(n,":")}},O:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+Tte(n,":");case"OOOO":default:return"GMT"+O_(n,":")}},z:function(t,e,r){const n=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+Tte(n,":");case"zzzz":default:return"GMT"+O_(n,":")}},t:function(t,e,r){const n=Math.trunc(t.getTime()/1e3);return Fs(n,e.length)},T:function(t,e,r){const n=t.getTime();return Fs(n,e.length)}};function Tte(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+Fs(a,2)}function Ete(t,e){return t%60===0?(t>0?"-":"+")+Fs(Math.abs(t)/60,2):O_(t,e)}function O_(t,e=""){const r=t>0?"-":"+",n=Math.abs(t),i=Fs(Math.trunc(n/60),2),a=Fs(n%60,2);return r+i+e+a}const Ate=(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"})}},Zxe=(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"})}},x7e=(t,e)=>{const r=t.match(/(P+)(p+)?/)||[],n=r[1],i=r[2];if(!i)return Ate(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}}",Ate(n,e)).replace("{{time}}",Zxe(i,e))},I6={p:Zxe,P:x7e},_7e=/^D+$/,v7e=/^Y+$/,b7e=["D","DD","YY","YYYY"];function Xxe(t){return _7e.test(t)}function Qxe(t){return v7e.test(t)}function P6(t,e,r){const n=w7e(t,e,r);if(console.warn(n),b7e.includes(t))throw new RangeError(n)}function w7e(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 S7e=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,T7e=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,E7e=/^'([^]*?)'?$/,A7e=/''/g,k7e=/[a-zA-Z]/;function Ri(t,e,r){var x,_,T,E,C,N,R,D;const n=ux(),i=(r==null?void 0:r.locale)??n.locale??VM,a=(r==null?void 0:r.firstWeekContainsDate)??((_=(x=r==null?void 0:r.locale)==null?void 0:x.options)==null?void 0:_.firstWeekContainsDate)??n.firstWeekContainsDate??((E=(T=n.locale)==null?void 0:T.options)==null?void 0:E.firstWeekContainsDate)??1,c=(r==null?void 0:r.weekStartsOn)??((N=(C=r==null?void 0:r.locale)==null?void 0:C.options)==null?void 0:N.weekStartsOn)??n.weekStartsOn??((D=(R=n.locale)==null?void 0:R.options)==null?void 0:D.weekStartsOn)??0,s=On(t);if(!j6(s))throw new RangeError("Invalid time value");let f=e.match(T7e).map(M=>{const B=M[0];if(B==="p"||B==="P"){const V=I6[B];return V(M,i.formatLong)}return M}).join("").match(S7e).map(M=>{if(M==="''")return{isToken:!1,value:"'"};const B=M[0];if(B==="'")return{isToken:!1,value:C7e(M)};if(Ste[B])return{isToken:!0,value:M};if(B.match(k7e))throw new RangeError("Format string contains an unescaped latin alphabet character `"+B+"`");return{isToken:!1,value:M}});i.localize.preprocessor&&(f=i.localize.preprocessor(s,f));const m={firstWeekContainsDate:a,weekStartsOn:c,locale:i};return f.map(M=>{if(!M.isToken)return M.value;const B=M.value;(!(r!=null&&r.useAdditionalWeekYearTokens)&&Qxe(B)||!(r!=null&&r.useAdditionalDayOfYearTokens)&&Xxe(B))&&P6(B,e,String(t));const V=Ste[B[0]];return V(s,B,i.localize,m)}).join("")}function C7e(t){const e=t.match(E7e);return e?e[1].replace(A7e,"'"):t}function j7e(t,e,r){const n=ux(),i=(r==null?void 0:r.locale)??n.locale??VM,a=2520,c=NR(t,e);if(isNaN(c))throw new RangeError("Invalid time value");const s=Object.assign({},r,{addSuffix:r==null?void 0:r.addSuffix,comparison:c});let f,m;c>0?(f=On(e),m=On(t)):(f=On(t),m=On(e));const x=O9e(m,f),_=(Wy(m)-Wy(f))/1e3,T=Math.round((x-_)/60);let E;if(T<2)return r!=null&&r.includeSeconds?x<5?i.formatDistance("lessThanXSeconds",5,s):x<10?i.formatDistance("lessThanXSeconds",10,s):x<20?i.formatDistance("lessThanXSeconds",20,s):x<40?i.formatDistance("halfAMinute",0,s):x<60?i.formatDistance("lessThanXMinutes",1,s):i.formatDistance("xMinutes",1,s):T===0?i.formatDistance("lessThanXMinutes",1,s):i.formatDistance("xMinutes",T,s);if(T<45)return i.formatDistance("xMinutes",T,s);if(T<90)return i.formatDistance("aboutXHours",1,s);if(Tn.getTime()}function V9(t,e){const r=On(t),n=On(e);return+r<+n}function O7e(t,e){const r=e instanceof Date?Hs(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 M7e=10;class e_e{constructor(){un(this,"subPriority",0)}validate(e,r){return!0}}class F7e extends e_e{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 B7e extends e_e{constructor(){super(...arguments);un(this,"priority",M7e);un(this,"subPriority",-1)}set(r,n){return n.timestampIsSet?r:Hs(r,O7e(r,Date))}}class Es{run(e,r,n,i){const a=this.parse(e,r,n,i);return a?{setter:new F7e(a.value,this.validate,this.set,this.priority,this.subPriority),rest:a.rest}:null}validate(e,r,n){return!0}}class z7e extends Es{constructor(){super(...arguments);un(this,"priority",140);un(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 ko={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}/},$f={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 Co(t,e){return t&&{value:e(t.value),rest:t.rest}}function Qa(t,e){const r=e.match(t);return r?{value:parseInt(r[0],10),rest:e.slice(r[0].length)}:null}function Uf(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*M9+a*O9+c*S9e),rest:e.slice(r[0].length)}}function t_e(t){return Qa(ko.anyDigitsSigned,t)}function mo(t,e){switch(t){case 1:return Qa(ko.singleDigit,e);case 2:return Qa(ko.twoDigits,e);case 3:return Qa(ko.threeDigits,e);case 4:return Qa(ko.fourDigits,e);default:return Qa(new RegExp("^\\d{1,"+t+"}"),e)}}function aD(t,e){switch(t){case 1:return Qa(ko.singleDigitSigned,e);case 2:return Qa(ko.twoDigitsSigned,e);case 3:return Qa(ko.threeDigitsSigned,e);case 4:return Qa(ko.fourDigitsSigned,e);default:return Qa(new RegExp("^-?\\d{1,"+t+"}"),e)}}function q9(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 r_e(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,s=t>=a%100;i=t+c-(s?100:0)}return r?i:1-i}function n_e(t){return t%400===0||t%4===0&&t%100!==0}class $7e extends Es{constructor(){super(...arguments);un(this,"priority",130);un(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 Co(mo(4,r),a);case"yo":return Co(i.ordinalNumber(r,{unit:"year"}),a);default:return Co(mo(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 s=r_e(i.year,a);return r.setFullYear(s,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 U7e extends Es{constructor(){super(...arguments);un(this,"priority",130);un(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 Co(mo(4,r),a);case"Yo":return Co(i.ordinalNumber(r,{unit:"year"}),a);default:return Co(mo(n.length,r),a)}}validate(r,n){return n.isTwoDigitYear||n.year>0}set(r,n,i,a){const c=$9(r,a);if(i.isTwoDigitYear){const f=r_e(i.year,c);return r.setFullYear(f,0,a.firstWeekContainsDate),r.setHours(0,0,0,0),_c(r,a)}const s=!("era"in n)||n.era===1?i.year:1-i.year;return r.setFullYear(s,0,a.firstWeekContainsDate),r.setHours(0,0,0,0),_c(r,a)}}class V7e extends Es{constructor(){super(...arguments);un(this,"priority",130);un(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(r,n){return aD(n==="R"?4:n.length,r)}set(r,n,i){const a=Hs(r,0);return a.setFullYear(i,0,4),a.setHours(0,0,0,0),Lm(a)}}class q7e extends Es{constructor(){super(...arguments);un(this,"priority",130);un(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(r,n){return aD(n==="u"?4:n.length,r)}set(r,n,i){return r.setFullYear(i,0,1),r.setHours(0,0,0,0),r}}class G7e extends Es{constructor(){super(...arguments);un(this,"priority",120);un(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 mo(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 H7e extends Es{constructor(){super(...arguments);un(this,"priority",120);un(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 mo(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 W7e extends Es{constructor(){super(...arguments);un(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);un(this,"priority",110)}parse(r,n,i){const a=c=>c-1;switch(n){case"M":return Co(Qa(ko.month,r),a);case"MM":return Co(mo(2,r),a);case"Mo":return Co(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 K7e extends Es{constructor(){super(...arguments);un(this,"priority",110);un(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 Co(Qa(ko.month,r),a);case"LL":return Co(mo(2,r),a);case"Lo":return Co(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 Y7e(t,e,r){const n=On(t),i=U9(n,r)-e;return n.setDate(n.getDate()-i*7),n}class Z7e extends Es{constructor(){super(...arguments);un(this,"priority",100);un(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(r,n,i){switch(n){case"w":return Qa(ko.week,r);case"wo":return i.ordinalNumber(r,{unit:"week"});default:return mo(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,i,a){return _c(Y7e(r,i,a),a)}}function X7e(t,e){const r=On(t),n=z9(r)-e;return r.setDate(r.getDate()-n*7),r}class Q7e extends Es{constructor(){super(...arguments);un(this,"priority",100);un(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 Qa(ko.week,r);case"Io":return i.ordinalNumber(r,{unit:"week"});default:return mo(n.length,r)}}validate(r,n){return n>=1&&n<=53}set(r,n,i){return Lm(X7e(r,i))}}const J7e=[31,28,31,30,31,30,31,31,30,31,30,31],eHe=[31,29,31,30,31,30,31,31,30,31,30,31];class tHe extends Es{constructor(){super(...arguments);un(this,"priority",90);un(this,"subPriority",1);un(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(r,n,i){switch(n){case"d":return Qa(ko.date,r);case"do":return i.ordinalNumber(r,{unit:"date"});default:return mo(n.length,r)}}validate(r,n){const i=r.getFullYear(),a=n_e(i),c=r.getMonth();return a?n>=1&&n<=eHe[c]:n>=1&&n<=J7e[c]}set(r,n,i){return r.setDate(i),r.setHours(0,0,0,0),r}}class rHe extends Es{constructor(){super(...arguments);un(this,"priority",90);un(this,"subpriority",1);un(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 Qa(ko.dayOfYear,r);case"Do":return i.ordinalNumber(r,{unit:"date"});default:return mo(n.length,r)}}validate(r,n){const i=r.getFullYear();return n_e(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 G9(t,e,r){var _,T,E,C;const n=ux(),i=(r==null?void 0:r.weekStartsOn)??((T=(_=r==null?void 0:r.locale)==null?void 0:_.options)==null?void 0:T.weekStartsOn)??n.weekStartsOn??((C=(E=n.locale)==null?void 0:E.options)==null?void 0:C.weekStartsOn)??0,a=On(t),c=a.getDay(),f=(e%7+7)%7,m=7-i,x=e<0||e>6?e-(c+m)%7:(f+m)%7-(c+m)%7;return Tl(a,x)}class nHe extends Es{constructor(){super(...arguments);un(this,"priority",90);un(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=G9(r,i,a),r.setHours(0,0,0,0),r}}class iHe extends Es{constructor(){super(...arguments);un(this,"priority",90);un(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(r,n,i,a){const c=s=>{const f=Math.floor((s-1)/7)*7;return(s+a.weekStartsOn+6)%7+f};switch(n){case"e":case"ee":return Co(mo(n.length,r),c);case"eo":return Co(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=G9(r,i,a),r.setHours(0,0,0,0),r}}class sHe extends Es{constructor(){super(...arguments);un(this,"priority",90);un(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(r,n,i,a){const c=s=>{const f=Math.floor((s-1)/7)*7;return(s+a.weekStartsOn+6)%7+f};switch(n){case"c":case"cc":return Co(mo(n.length,r),c);case"co":return Co(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=G9(r,i,a),r.setHours(0,0,0,0),r}}function aHe(t,e){const r=On(t),n=N7e(r),i=e-n;return Tl(r,i)}class oHe extends Es{constructor(){super(...arguments);un(this,"priority",90);un(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 mo(n.length,r);case"io":return i.ordinalNumber(r,{unit:"day"});case"iii":return Co(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 Co(i.day(r,{width:"narrow",context:"formatting"}),a);case"iiiiii":return Co(i.day(r,{width:"short",context:"formatting"})||i.day(r,{width:"narrow",context:"formatting"}),a);case"iiii":default:return Co(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=aHe(r,i),r.setHours(0,0,0,0),r}}class lHe extends Es{constructor(){super(...arguments);un(this,"priority",80);un(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(q9(i),0,0,0),r}}class cHe extends Es{constructor(){super(...arguments);un(this,"priority",80);un(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(q9(i),0,0,0),r}}class uHe extends Es{constructor(){super(...arguments);un(this,"priority",80);un(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(q9(i),0,0,0),r}}class dHe extends Es{constructor(){super(...arguments);un(this,"priority",70);un(this,"incompatibleTokens",["H","K","k","t","T"])}parse(r,n,i){switch(n){case"h":return Qa(ko.hour12h,r);case"ho":return i.ordinalNumber(r,{unit:"hour"});default:return mo(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 hHe extends Es{constructor(){super(...arguments);un(this,"priority",70);un(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(r,n,i){switch(n){case"H":return Qa(ko.hour23h,r);case"Ho":return i.ordinalNumber(r,{unit:"hour"});default:return mo(n.length,r)}}validate(r,n){return n>=0&&n<=23}set(r,n,i){return r.setHours(i,0,0,0),r}}class fHe extends Es{constructor(){super(...arguments);un(this,"priority",70);un(this,"incompatibleTokens",["h","H","k","t","T"])}parse(r,n,i){switch(n){case"K":return Qa(ko.hour11h,r);case"Ko":return i.ordinalNumber(r,{unit:"hour"});default:return mo(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 pHe extends Es{constructor(){super(...arguments);un(this,"priority",70);un(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(r,n,i){switch(n){case"k":return Qa(ko.hour24h,r);case"ko":return i.ordinalNumber(r,{unit:"hour"});default:return mo(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 mHe extends Es{constructor(){super(...arguments);un(this,"priority",60);un(this,"incompatibleTokens",["t","T"])}parse(r,n,i){switch(n){case"m":return Qa(ko.minute,r);case"mo":return i.ordinalNumber(r,{unit:"minute"});default:return mo(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,i){return r.setMinutes(i,0,0),r}}class gHe extends Es{constructor(){super(...arguments);un(this,"priority",50);un(this,"incompatibleTokens",["t","T"])}parse(r,n,i){switch(n){case"s":return Qa(ko.second,r);case"so":return i.ordinalNumber(r,{unit:"second"});default:return mo(n.length,r)}}validate(r,n){return n>=0&&n<=59}set(r,n,i){return r.setSeconds(i,0),r}}class yHe extends Es{constructor(){super(...arguments);un(this,"priority",30);un(this,"incompatibleTokens",["t","T"])}parse(r,n){const i=a=>Math.trunc(a*Math.pow(10,-n.length+3));return Co(mo(n.length,r),i)}set(r,n,i){return r.setMilliseconds(i),r}}class xHe extends Es{constructor(){super(...arguments);un(this,"priority",10);un(this,"incompatibleTokens",["t","T","x"])}parse(r,n){switch(n){case"X":return Uf($f.basicOptionalMinutes,r);case"XX":return Uf($f.basic,r);case"XXXX":return Uf($f.basicOptionalSeconds,r);case"XXXXX":return Uf($f.extendedOptionalSeconds,r);case"XXX":default:return Uf($f.extended,r)}}set(r,n,i){return n.timestampIsSet?r:Hs(r,r.getTime()-Wy(r)-i)}}class _He extends Es{constructor(){super(...arguments);un(this,"priority",10);un(this,"incompatibleTokens",["t","T","X"])}parse(r,n){switch(n){case"x":return Uf($f.basicOptionalMinutes,r);case"xx":return Uf($f.basic,r);case"xxxx":return Uf($f.basicOptionalSeconds,r);case"xxxxx":return Uf($f.extendedOptionalSeconds,r);case"xxx":default:return Uf($f.extended,r)}}set(r,n,i){return n.timestampIsSet?r:Hs(r,r.getTime()-Wy(r)-i)}}class vHe extends Es{constructor(){super(...arguments);un(this,"priority",40);un(this,"incompatibleTokens","*")}parse(r){return t_e(r)}set(r,n,i){return[Hs(r,i*1e3),{timestampIsSet:!0}]}}class bHe extends Es{constructor(){super(...arguments);un(this,"priority",20);un(this,"incompatibleTokens","*")}parse(r){return t_e(r)}set(r,n,i){return[Hs(r,i),{timestampIsSet:!0}]}}const wHe={G:new z7e,y:new $7e,Y:new U7e,R:new V7e,u:new q7e,Q:new G7e,q:new H7e,M:new W7e,L:new K7e,w:new Z7e,I:new Q7e,d:new tHe,D:new rHe,E:new nHe,e:new iHe,c:new sHe,i:new oHe,a:new lHe,b:new cHe,B:new uHe,h:new dHe,H:new hHe,K:new fHe,k:new pHe,m:new mHe,s:new gHe,S:new yHe,X:new xHe,x:new _He,t:new vHe,T:new bHe},SHe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,THe=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,EHe=/^'([^]*?)'?$/,AHe=/''/g,kHe=/\S/,CHe=/[a-zA-Z]/;function jHe(t,e,r,n){var N,R,D,M;const i=P7e(),a=i.locale??VM,c=i.firstWeekContainsDate??((R=(N=i.locale)==null?void 0:N.options)==null?void 0:R.firstWeekContainsDate)??1,s=i.weekStartsOn??((M=(D=i.locale)==null?void 0:D.options)==null?void 0:M.weekStartsOn)??0;if(e==="")return t===""?On(r):Hs(r,NaN);const f={firstWeekContainsDate:c,weekStartsOn:s,locale:a},m=[new B7e],x=e.match(THe).map(B=>{const V=B[0];if(V in I6){const G=I6[V];return G(B,a.formatLong)}return B}).join("").match(SHe),_=[];for(let B of x){Qxe(B)&&P6(B,e,t),Xxe(B)&&P6(B,e,t);const V=B[0],G=wHe[V];if(G){const{incompatibleTokens:W}=G;if(Array.isArray(W)){const Q=_.find(re=>W.includes(re.token)||re.token===V);if(Q)throw new RangeError(`The format string mustn't contain \`${Q.fullToken}\` and \`${B}\` at the same time`)}else if(G.incompatibleTokens==="*"&&_.length>0)throw new RangeError(`The format string mustn't contain \`${B}\` and any other token at the same time`);_.push({token:V,fullToken:B});const X=G.run(t,B,a.match,f);if(!X)return Hs(r,NaN);m.push(X.setter),t=X.rest}else{if(V.match(CHe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+V+"`");if(B==="''"?B="'":V==="'"&&(B=IHe(B)),t.indexOf(B)===0)t=t.slice(B.length);else return Hs(r,NaN)}}if(t.length>0&&kHe.test(t))return Hs(r,NaN);const T=m.map(B=>B.priority).sort((B,V)=>V-B).filter((B,V,G)=>G.indexOf(B)===V).map(B=>m.filter(V=>V.priority===B).sort((V,G)=>G.subPriority-V.subPriority)).map(B=>B[0]);let E=On(r);if(isNaN(E.getTime()))return Hs(r,NaN);const C={};for(const B of T){if(!B.validate(E,f))return Hs(r,NaN);const V=B.set(E,C,f);Array.isArray(V)?(E=V[0],Object.assign(C,V[1])):E=V}return Hs(r,E)}function IHe(t){return t.match(EHe)[1].replace(AHe,"'")}function S1(t){return+On(t)2)return e;if(/:/.test(r[0])?n=r[0]:(e.date=r[0],n=r[1],xN.timeZoneDelimiter.test(e.date)&&(e.date=t.split(xN.timeZoneDelimiter)[0],n=t.substr(e.date.length,t.length))),n){const i=xN.timezone.exec(n);i?(e.time=n.replace(i[1],""),e.timezone=i[1]):e.time=n}return e}function FHe(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 BHe(t,e){if(e===null)return new Date(NaN);const r=t.match(LHe);if(!r)return new Date(NaN);const n=!!r[4],i=v2(r[1]),a=v2(r[2])-1,c=v2(r[3]),s=v2(r[4]),f=v2(r[5])-1;if(n)return HHe(e,s,f)?UHe(e,s,f):new Date(NaN);{const m=new Date(0);return!qHe(e,a,c)||!GHe(e,i)?new Date(NaN):(m.setUTCFullYear(e,a,Math.max(i,c)),m)}}function v2(t){return t?parseInt(t):1}function zHe(t){const e=t.match(DHe);if(!e)return NaN;const r=DB(e[1]),n=DB(e[2]),i=DB(e[3]);return WHe(r,n,i)?r*M9+n*O9+i*1e3:NaN}function DB(t){return t&&parseFloat(t.replace(",","."))||0}function $He(t){if(t==="Z")return 0;const e=t.match(OHe);if(!e)return 0;const r=e[1]==="+"?-1:1,n=parseInt(e[2]),i=e[3]&&parseInt(e[3])||0;return KHe(n,i)?r*(n*M9+i*O9):NaN}function UHe(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 VHe=[31,null,31,30,31,30,31,31,30,31,30,31];function i_e(t){return t%400===0||t%4===0&&t%100!==0}function qHe(t,e,r){return e>=0&&e<=11&&r>=1&&r<=(VHe[e]||(i_e(t)?29:28))}function GHe(t,e){return e>=1&&e<=(i_e(t)?366:365)}function HHe(t,e,r){return e>=1&&e<=53&&r>=0&&r<=6}function WHe(t,e,r){return t===24?e===0&&r===0:r>=0&&r<60&&e>=0&&e<60&&t>=0&&t<25}function KHe(t,e){return e>=0&&e<=59}function OB(t,e){const r=On(t),n=r.getFullYear(),i=r.getDate(),a=Hs(t,0);a.setFullYear(n,e,15),a.setHours(0,0,0,0);const c=I7e(a);return r.setMonth(e,Math.min(i,c)),r}function kte(t,e){const r=On(t);return isNaN(+r)?Hs(t,NaN):(r.setFullYear(e),r)}function YHe(t,e){return cd(t,-e)}const ZHe=()=>{const{user:t}=qn(),e=ma(),[r,n]=P.useState([]),[i,a]=P.useState(0),[c,s]=P.useState(!1),[f,m]=P.useState(null),x=P.useRef(null);P.useEffect(()=>{x.current=f},[f]),P.useEffect(()=>{if(!t)return;const N=`notification_last_read_${t.id}`,R=localStorage.getItem(N);R&&!x.current&&(x.current=R,m(R));const D=`nb_cache_${t.id}`,M=60*1e3,B=async()=>{try{const Q=sessionStorage.getItem(D);if(Q){const re=JSON.parse(Q);if(re.ts&&Date.now()-re.ts{n(W);const X=x.current?new Date(x.current):null,Q=W.filter(re=>X?new Date(re.created_at)>X:!0);a(Q.length)};B();const G=Le.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},W=>{const X=W.new;n(re=>{const se=[X,...re].slice(0,20);try{sessionStorage.setItem(D,JSON.stringify({ts:Date.now(),data:se}))}catch{}return se});const Q=x.current?new Date(x.current):null;(!Q||new Date(X.created_at)>Q)&&a(re=>re+1),Notification.permission==="granted"&&new Notification(X.title,{body:X.body,icon:"/favicon.ico"})}).subscribe();return()=>{Le.removeChannel(G)}},[t]);const _=N=>{const R=N.toLowerCase();return R.includes("community")||R.includes("post")?rp:R.includes("academy")||R.includes("video")?dA:R.includes("template")?XO:R.includes("event")?po:R.includes("newsletter")?Yhe:R.includes("brokerage")?Mhe:R.includes("swag")||R.includes("social")?Yh:R.includes("toolbox")||R.includes("tool")?_G:R.includes("brief")?Ss:rp},T=N=>{s(!1),N.url&&N.url!=="/"&&e(N.url)},E=()=>{if(!t)return;const N=new Date().toISOString(),R=`notification_last_read_${t.id}`;localStorage.setItem(R,N),m(N),a(0)},C=N=>{s(N),N&&i>0&&E()};return o.jsxs(UC,{open:c,onOpenChange:C,children:[o.jsx(VC,{asChild:!0,children:o.jsxs(Ut,{variant:"ghost",size:"icon",className:"relative",children:[o.jsx(EC,{className:"h-5 w-5"}),i>0&&o.jsx(us,{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})]})}),o.jsxs(wS,{align:"end",className:"w-80",children:[o.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[o.jsx("span",{className:"font-semibold",children:"Notifications"}),r.length>0&&o.jsx(Ut,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:E,children:"Mark all read"})]}),o.jsx(pp,{className:"h-[300px]",children:r.length===0?o.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):r.map(N=>{const R=_(N.title);return o.jsxs(vu,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>T(N),children:[o.jsx("div",{className:"flex-shrink-0 mt-0.5",children:o.jsx(R,{className:"h-4 w-4 text-primary"})}),o.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[o.jsx("span",{className:"font-medium text-sm",children:N.title}),o.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:N.body}),o.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:Jxe(new Date(N.created_at),{addSuffix:!0})})]})]},N.id)})})]})]})};function XHe(t){return t!=null&&t.length?t.find(e=>e.is_active&&e.mls_provider_id&&!e.no_mls_mode)||t[0]:null}function s_e(){const{user:t}=qn(),{data:e,isLoading:r}=wr({queryKey:["agent-lead-site",t==null?void 0:t.id],queryFn:async()=>{const{data:n,error:i}=await Le.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 XHe(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 a_e(t=!0){const{user:e}=qn(),{data:r,isLoading:n}=wr({queryKey:["free-lead-site-offer",e==null?void 0:e.id],enabled:!!e&&t,staleTime:5*60*1e3,queryFn:async()=>{const{data:i}=await Le.from("profiles").select("brokerage_id").eq("id",e.id).maybeSingle();if(!(i!=null&&i.brokerage_id))return null;const{data:a}=await Le.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 QHe="coaching_access";function JHe(){const{user:t,loading:e,isAdmin:r,isCoach:n}=qn(),{data:i,isLoading:a}=wr({queryKey:["coaching-access",t==null?void 0:t.id],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const[c,s]=await Promise.all([Le.from("coaching_assignments").select("id").eq("agent_id",t.id).eq("status","active").limit(1),Le.from("feature_entitlements").select("enabled, expires_at").eq("user_id",t.id).eq("feature_key",QHe).maybeSingle()]),f=(c.data||[]).length>0,m=s.data,x=!!(m!=null&&m.enabled)&&(!m.expires_at||new Date(m.expires_at).getTime()>Date.now());return{hasAssignment:f,entitled:x}}});return{hasAccess:!!(r||n||i!=null&&i.hasAssignment||i!=null&&i.entitled),hasAssignment:!!(i!=null&&i.hasAssignment),isLoading:e||a}}const qi=Le,wUt=[{value:"contract",label:"Under contract"},{value:"inspection",label:"Inspection / due diligence"},{value:"closing",label:"Closing"},{value:"closed",label:"Closed"}];function SUt(t){return t.total_items===0?"not_started":t.rejected_items>0?"changes_requested":t.approved_items>=t.total_items?"compliant":"in_review"}const TUt={not_started:"Not started",in_review:"In review",changes_requested:"Changes requested",compliant:"Compliant"};function eWe(){return wr({queryKey:["transaction-admin-seats"],queryFn:async()=>{const{data:t}=await Le.auth.getUser();if(!t.user)return[];const{data:e,error:r}=await qi.from("brokerage_transaction_admins").select("brokerage_id").eq("user_id",t.user.id);if(r)throw r;return e||[]}})}function EUt(t){return wr({queryKey:["transaction-admins",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await qi.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 qi.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 s,f;return{...c,name:((s=a.get(c.user_id))==null?void 0:s.name)??null,email:((f=a.get(c.user_id))==null?void 0:f.email)??null}})}})}function AUt(){const t=Nr();return Cr({mutationFn:async({brokerageId:e,userId:r})=>{const{error:n}=await qi.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 kUt(){const t=Nr();return Cr({mutationFn:async({id:e})=>{const{error:r}=await qi.from("brokerage_transaction_admins").delete().eq("id",e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["transaction-admins",r.brokerageId]})})}function CUt(t){return wr({queryKey:["compliance-settings",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await qi.from("brokerage_compliance_settings").select("*").eq("brokerage_id",t).maybeSingle();if(r)throw r;return e}})}function jUt(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await qi.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 IUt(t){return wr({queryKey:["compliance-templates",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await qi.from("brokerage_checklist_templates").select("*").eq("brokerage_id",t).order("created_at",{ascending:!0});if(r)throw r;return e||[]}})}function PUt(t){return wr({queryKey:["compliance-template-items",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await qi.from("brokerage_checklist_template_items").select("*").eq("template_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]}})}function NUt(){const t=Nr();return Cr({mutationFn:async e=>{if(e.id){const{error:i}=await qi.from("brokerage_checklist_templates").update(e).eq("id",e.id);if(i)throw i;return e.id}const{data:r,error:n}=await qi.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 RUt(){const t=Nr();return Cr({mutationFn:async({id:e})=>{const{error:r}=await qi.from("brokerage_checklist_templates").delete().eq("id",e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-templates",r.brokerageId]})})}function LUt(){const t=Nr();return Cr({mutationFn:async e=>{if(e.id){const{error:n}=await qi.from("brokerage_checklist_template_items").update(e).eq("id",e.id);if(n)throw n;return}const{error:r}=await qi.from("brokerage_checklist_template_items").insert(e);if(r)throw r},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["compliance-template-items",r.template_id]})})}function DUt(){const t=Nr();return Cr({mutationFn:async({id:e})=>{const{error:r}=await qi.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 OUt(t){return wr({queryKey:["compliance-deals",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await qi.rpc("get_brokerage_compliance_deals",{_brokerage_id:t});if(r)throw r;return e||[]}})}function MUt(t){return wr({queryKey:["deal-compliance-items",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await qi.from("deal_compliance_items").select("*").eq("deal_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]}})}function FUt(t){return wr({queryKey:["deal-compliance-events",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await qi.from("deal_compliance_events").select("*").eq("deal_id",t).order("created_at",{ascending:!1}).limit(200);if(r)throw r;return e||[]}})}async function KC(t){var r;const{data:e}=await Le.auth.getUser();await qi.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 BUt(){const t=Nr();return Cr({mutationFn:async({item:e,status:r,note:n})=>{var c;const{data:i}=await Le.auth.getUser(),{error:a}=await qi.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 KC({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 zUt(){const t=Nr();return Cr({mutationFn:async({dealId:e,brokerageId:r,templateId:n,deal:i})=>{const{data:a,error:c}=await qi.from("brokerage_checklist_template_items").select("*").eq("template_id",n).order("sort_order",{ascending:!0});if(c)throw c;const s=(x,_)=>{if(!x)return null;const[T,E,C]=x.split(/[-/T]/).map(Number);return new Date(Date.UTC(T,E-1,C+(_||0))).toISOString().slice(0,10)},f=(a||[]).map(x=>({deal_id:e,brokerage_id:r,template_item_id:x.id,title:x.title,description:x.description,phase:x.phase,requires_document:x.requires_document,required_for_closing:x.required_for_closing,due_date:x.due_anchor==="contract_date"?s(i==null?void 0:i.contract_date,x.due_offset_days):x.due_anchor==="target_close_date"?s(i==null?void 0:i.target_close_date,x.due_offset_days):null,sort_order:x.sort_order}));if(f.length===0)return;const{error:m}=await qi.from("deal_compliance_items").insert(f);if(m)throw m;await KC({dealId:e,brokerageId:r,eventType:"checklist_applied",detail:`${f.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 $Ut(t){return wr({queryKey:["deal-compliance-files",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await qi.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 UUt(){const t=Nr();return Cr({mutationFn:async({item:e,file:r})=>{var _,T;const{data:n}=await Le.auth.getUser(),i=(_=n.user)==null?void 0:_.id;if(!i)throw new Error("Not signed in");const{data:a}=await qi.from("deal_files").select("id, version_no").eq("compliance_item_id",e.id).order("version_no",{ascending:!1}).limit(1),c=(((T=a==null?void 0:a[0])==null?void 0:T.version_no)||0)+1,s=r.name.split(".").pop(),f=`${i}/${e.deal_id}/${crypto.randomUUID()}.${s}`,{error:m}=await Le.storage.from("deal-files").upload(f,r);if(m)throw m;a!=null&&a.length&&await qi.from("deal_files").update({is_current:!1}).eq("compliance_item_id",e.id);const{error:x}=await qi.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:f,compliance_item_id:e.id,version_no:c,is_current:!0});if(x)throw x;await qi.from("deal_compliance_items").update({status:"submitted",review_note:null,reviewed_at:null,reviewed_by:null}).eq("id",e.id),await KC({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 VUt(t){const{data:e,error:r}=await Le.storage.from("deal-files").createSignedUrl(t,3600);if(r)throw r;window.open(e.signedUrl,"_blank","noopener,noreferrer")}function qUt(t){return wr({queryKey:["deal-compliance-messages",t],enabled:!!t,refetchInterval:3e4,queryFn:async()=>{const{data:e,error:r}=await qi.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(s=>s.sender_user_id)));if(i.length===0)return n;const{data:a}=await qi.from("profiles").select("id, name").in("id",i),c=new Map((a||[]).map(s=>[s.id,s.name??null]));return n.map(s=>({...s,sender_name:c.get(s.sender_user_id)??null}))}})}function GUt(){const t=Nr();return Cr({mutationFn:async({dealId:e,brokerageId:r,body:n,senderRole:i,itemId:a})=>{var x;const{data:c}=await Le.auth.getUser(),s=(x=c.user)==null?void 0:x.id;if(!s)throw new Error("Not signed in");const{data:f,error:m}=await qi.from("deal_compliance_messages").insert({deal_id:e,brokerage_id:r,sender_user_id:s,sender_role:i,item_id:a??null,body:n.trim()}).select("id").single();if(m)throw m;try{await Le.functions.invoke("compliance-message-notify",{body:{messageId:f.id}})}catch(_){console.error("compliance message notify failed",_)}return f.id},onSuccess:(e,r)=>t.invalidateQueries({queryKey:["deal-compliance-messages",r.dealId]})})}function HUt(){const t=Nr();return Cr({mutationFn:async({dealId:e,senderRole:r})=>{const{error:n}=await qi.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 WUt(t){return wr({queryKey:["brokerage-agent-roster",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await qi.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",t).order("name",{ascending:!0});if(r)throw r;return e||[]}})}function KUt(t){return wr({queryKey:["agent-pipeline-stages",t],enabled:!!t,queryFn:async()=>{const e=async()=>{const{data:n,error:i}=await qi.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 qi.rpc("initialize_deal_pipeline_stages",{p_user_id:t});n||(r=await e())}return r}})}function YUt(){const t=Nr();return Cr({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 qi.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 qi.rpc("ensure_deal_compliance",{_deal_id:a})}catch(c){console.error("ensure_deal_compliance failed",c)}return await KC({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 ZUt(t){return wr({queryKey:["staff-deal-detail",t],enabled:!!t,queryFn:async()=>{const{data:e,error:r}=await qi.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 XUt(){const t=Nr();return Cr({mutationFn:async e=>{const r=e.price!=null&&e.commissionPercentage!=null?Math.round(e.price*(e.commissionPercentage/100)*100)/100:null,{error:n}=await qi.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 KC({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 GM=[{id:"home",label:"Home",icon:Whe,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:tp,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:fG,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:Eo,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:AC,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:h1,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:XA,description:"Training, programs and coaching",accent:"nav-academy"},{id:"events",label:"Events",icon:Qhe,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:YRe,route:"/apps",accent:"nav-apps"},{id:"team",label:"Team",icon:Al,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:Hhe,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:t=>!t.isAdmin&&(!!t.brokerageId||t.isBrokerageManager||t.isOnTeam)},{id:"more",label:"More",icon:GRe,description:"Community, marketplace and help",accent:"nav-more"}],Ol=t=>e=>e.hasPermission(t),tWe=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:zRe,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:Ol("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:Ss,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:Al,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:Ol("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"contact-map",label:"Contact Map",route:"/mission-control/sphere-map",icon:na,iconTone:"red",description:"See your sphere on a map — boundaries, farms and prospects",primaryCategory:"crm",section:"Contacts",visible:Ol("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:vJ,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:Ol("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:gLe,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:Ol("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:jL,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:Ol("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:EJ,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:Ol("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"property-intelligence",label:"Property Intelligence",route:"/mission-control/property-intelligence",icon:Eo,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:Zf,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:Ol("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:NL,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:Bi,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:fLe,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:Yh,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:Ol("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:fG,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:Ol("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:SU,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:Ol("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"forms",label:"Forms Library",route:"/mission-control/forms",icon:HRe,description:"Your PDF form templates, filled from any deal",primaryCategory:"deals",section:"Pipeline",visible:Ol("pipeline"),searchKeywords:["forms","pdf","templates","contracts","documents"],displayOrder:145},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:vLe,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:Ol("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:ZA,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:Ol("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"my-calendar",label:"My Calendar",route:"/mission-control/calendar",icon:Zf,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:Zf,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:Eo,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:Ol("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:dLe,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:Vhe,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:Ma,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:Fhe,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:SU,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:TJ,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:XO,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:_Le,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:Xc,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:TJ,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:iB,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:iB,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:SJ,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:Yhe,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:Bi,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:jL,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:Yh,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:dA,description:"All of your recorded videos",primaryCategory:"marketing",section:"Video",visible:Ol("videos"),searchKeywords:["videos","library"],displayOrder:90},{id:"video-studio",label:"Video Studio",route:"/video-studio",icon:dA,description:"Record vertical or horizontal videos with a scrolling teleprompter",primaryCategory:"marketing",section:"Video",visible:Ol("videos"),searchKeywords:["teleprompter","studio","reels","record video","social video"],displayOrder:95},{id:"quickvid",label:"Video Messages",route:"/video-studio",icon:dA,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:SJ,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:kJ,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:EU,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:EJ,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:JRe,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:h1,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:h1,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:KO,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:oLe,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:Eo,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:Al,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:Ma,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:ZA,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:vJ,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:iB,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:Ss,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:XA,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:u1,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:_G,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:Qhe,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:kJ,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:XA,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:tp,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:rp,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:tLe,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:cS,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:Xhe,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:PL,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:Yh,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:eLe,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:Ss,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:CL,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:CL,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:Ss,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:zy,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:NL,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:Eo,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:ZRe,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:u1,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:Al,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:Al,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:pG,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:Al,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:AC,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:nB,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:Whe,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:lLe,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:nB,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:EU,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:ep,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:Mhe,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:Ss,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:nB,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 o_e(t,e){return typeof t.route=="function"?t.route(e):t.route}function l_e(){const{user:t,isAdmin:e,isBrokerageManager:r,isCoach:n,brokerageId:i}=qn(),{hasPermission:a}=EM(),{isInnerCircleEnabled:c,isMarketplaceEnabled:s,isFeatureEnabled:f}=jM(),{hasAccess:m}=u9(),{data:x,teams:_}=SS(),{leadSite:T,hasLeadSite:E,siteUrl:C}=s_e(),{hasOffer:N}=a_e(!E),R=Wge(),{hasAccess:D}=JHe(),{data:M}=eWe(),B=Nr(),{data:V}=wr({queryKey:["my-coach-nav",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:we}=await Le.from("coaching_assignments").select("id").eq("agent_id",t.id).eq("status","active").limit(1);return(we||[]).length>0}}),{data:G}=wr({queryKey:["user-tool-favorites",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),staleTime:60*1e3,queryFn:async()=>{const{data:we}=await Le.from("user_tool_favorites").select("tool_id").eq("user_id",t.id);return(we||[]).map(ge=>ge.tool_id)}}),W=P.useMemo(()=>new Set(G||[]),[G]),X=Cr({mutationFn:async we=>{t!=null&&t.id&&(W.has(we)?await Le.from("user_tool_favorites").delete().eq("user_id",t.id).eq("tool_id",we):await Le.from("user_tool_favorites").insert({user_id:t.id,tool_id:we}))},onSuccess:()=>{B.invalidateQueries({queryKey:["user-tool-favorites"]}),B.invalidateQueries({queryKey:["app-catalog"]})}}),Q=P.useMemo(()=>{var we,ge;return{isAdmin:!!e,isBrokerageManager:!!r,isTransactionAdmin:((M==null?void 0:M.length)||0)>0,isCoach:!!n,isOnTeam:!!x,isTeamLeader:(_||[]).some(Ne=>Ne.role==="team_leader"),hasCoach:!!V,brokerageId:i??null,hasPermission:a,isInnerCircleEnabled:!!c,stagingStudioEnabled:f("staging_studio_enabled"),isMarketplaceEnabled:!!s,hasWeeklyReels:!!m,hasLeadSite:!!E,hasLeadSiteMLS:!!(T!=null&&T.mls_provider_id),hasFreeSiteOffer:!!N,leadSiteId:(T==null?void 0:T.id)??null,siteUrl:C??null,email:(t==null?void 0:t.email)??null,isPartnershipMember:R.isMember,hasCoachingOnboarding:R.isMember&&!!((we=R.pkg)!=null&&we.includes_coaching),hasCoachingAccess:!!D||R.isMember&&!!((ge=R.pkg)!=null&&ge.includes_coaching)}},[e,r,M,n,x,_,V,i,a,c,s,f,m,E,T,N,C,t==null?void 0:t.email,R.isMember,R.pkg,D]),re=P.useMemo(()=>tWe.filter(we=>we.visible?we.visible(Q):!0).map(we=>{if(!R.isRestricted)return we;const ge=tUe(we);return!ge||R.hasFeature(ge)?we:{...we,locked:!0,route:`/upgrade/${ge}`}}).sort((we,ge)=>we.displayOrder-ge.displayOrder),[Q,R.isRestricted,R.features]),se=P.useMemo(()=>GM.filter(we=>we.visible?we.visible(Q):!0),[Q]),ue=P.useMemo(()=>se.filter(we=>!we.route).map(we=>{const ge=re.filter(Te=>Te.primaryCategory===we.id),Ne=[],Ie=new Map;for(const Te of ge)Ie.has(Te.section)||(Ie.set(Te.section,[]),Ne.push(Te.section)),Ie.get(Te.section).push(Te);return{id:we.id,label:we.label,sections:Ne.map(Te=>({title:Te,items:Ie.get(Te)}))}}),[re,se]),_e=P.useMemo(()=>new Map(ue.map(we=>[we.id,we])),[ue]),Se=we=>we.toolId||`nav:${we.id}`,ve=we=>W.has(Se(we));return{ctx:Q,categories:ue,railCategories:se,categoryMap:_e,destinations:re,favorites:W,isFavorite:ve,favoritesFor:we=>re.filter(ge=>ge.primaryCategory===we&&ve(ge)),favoriteKey:Se,toggleFavorite:we=>X.mutate(we),searchDestinations:we=>{const ge=we.trim().toLowerCase();return ge?re.map(Ie=>{const Te=Ie.label.toLowerCase(),be=(Ie.description||"").toLowerCase(),We=(Ie.searchKeywords||[]).join(" ").toLowerCase();let rt=0;return Te===ge?rt=100:Te.startsWith(ge)?rt=80:Te.includes(ge)?rt=60:We.includes(ge)?rt=40:be.includes(ge)?rt=20:Ie.section.toLowerCase().includes(ge)&&(rt=10),rt&&ve(Ie)&&(rt+=5),{d:Ie,score:rt}}).filter(Ie=>Ie.score>0).sort((Ie,Te)=>Te.score-Ie.score).map(Ie=>Ie.d):[]},routeFor:we=>o_e(we,Q)}}var Cte=1,rWe=.9,nWe=.8,iWe=.17,MB=.1,FB=.999,sWe=.9999,aWe=.99,oWe=/[\\\/_+.#"@\[\(\{&]/,lWe=/[\\\/_+.#"@\[\(\{&]/g,cWe=/[\s-]/,c_e=/[\s-]/g;function N6(t,e,r,n,i,a,c){if(a===e.length)return i===t.length?Cte:aWe;var s=`${i},${a}`;if(c[s]!==void 0)return c[s];for(var f=n.charAt(a),m=r.indexOf(f,i),x=0,_,T,E,C;m>=0;)_=N6(t,e,r,n,m+1,a+1,c),_>x&&(m===i?_*=Cte:oWe.test(t.charAt(m-1))?(_*=nWe,E=t.slice(i,m-1).match(lWe),E&&i>0&&(_*=Math.pow(FB,E.length))):cWe.test(t.charAt(m-1))?(_*=rWe,C=t.slice(i,m-1).match(c_e),C&&i>0&&(_*=Math.pow(FB,C.length))):(_*=iWe,i>0&&(_*=Math.pow(FB,m-i))),t.charAt(m)!==e.charAt(a)&&(_*=sWe)),(__&&(_=T*MB)),_>x&&(x=_),m=r.indexOf(f,m+1);return c[s]=x,x}function jte(t){return t.toLowerCase().replace(c_e," ")}function uWe(t,e,r){return t=r&&r.length>0?`${t+" "+r.join(" ")}`:t,N6(t,e,jte(t),jte(e),0,0,{})}var b2='[cmdk-group=""]',BB='[cmdk-group-items=""]',dWe='[cmdk-group-heading=""]',u_e='[cmdk-item=""]',Ite=`${u_e}:not([aria-disabled="true"])`,R6="cmdk-item-select",Zb="data-value",hWe=(t,e,r)=>uWe(t,e,r),d_e=P.createContext(void 0),YC=()=>P.useContext(d_e),h_e=P.createContext(void 0),H9=()=>P.useContext(h_e),f_e=P.createContext(void 0),p_e=P.forwardRef((t,e)=>{let r=Xb(()=>{var be,We;return{search:"",value:(We=(be=t.value)!=null?be:t.defaultValue)!=null?We:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),n=Xb(()=>new Set),i=Xb(()=>new Map),a=Xb(()=>new Map),c=Xb(()=>new Set),s=m_e(t),{label:f,children:m,value:x,onValueChange:_,filter:T,shouldFilter:E,loop:C,disablePointerSelection:N=!1,vimBindings:R=!0,...D}=t,M=Cl(),B=Cl(),V=Cl(),G=P.useRef(null),W=SWe();C0(()=>{if(x!==void 0){let be=x.trim();r.current.value=be,X.emit()}},[x]),C0(()=>{W(6,Se)},[]);let X=P.useMemo(()=>({subscribe:be=>(c.current.add(be),()=>c.current.delete(be)),snapshot:()=>r.current,setState:(be,We,rt)=>{var at,Et,_t,Vt;if(!Object.is(r.current[be],We)){if(r.current[be]=We,be==="search")_e(),se(),W(1,ue);else if(be==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let mt=document.getElementById(V);mt?mt.focus():(at=document.getElementById(M))==null||at.focus()}if(W(7,()=>{var mt;r.current.selectedItemId=(mt=ve())==null?void 0:mt.id,X.emit()}),rt||W(5,Se),((Et=s.current)==null?void 0:Et.value)!==void 0){let mt=We??"";(Vt=(_t=s.current).onValueChange)==null||Vt.call(_t,mt);return}}X.emit()}},emit:()=>{c.current.forEach(be=>be())}}),[]),Q=P.useMemo(()=>({value:(be,We,rt)=>{var at;We!==((at=a.current.get(be))==null?void 0:at.value)&&(a.current.set(be,{value:We,keywords:rt}),r.current.filtered.items.set(be,re(We,rt)),W(2,()=>{se(),X.emit()}))},item:(be,We)=>(n.current.add(be),We&&(i.current.has(We)?i.current.get(We).add(be):i.current.set(We,new Set([be]))),W(3,()=>{_e(),se(),r.current.value||ue(),X.emit()}),()=>{a.current.delete(be),n.current.delete(be),r.current.filtered.items.delete(be);let rt=ve();W(4,()=>{_e(),(rt==null?void 0:rt.getAttribute("id"))===be&&ue(),X.emit()})}),group:be=>(i.current.has(be)||i.current.set(be,new Set),()=>{a.current.delete(be),i.current.delete(be)}),filter:()=>s.current.shouldFilter,label:f||t["aria-label"],getDisablePointerSelection:()=>s.current.disablePointerSelection,listId:M,inputId:V,labelId:B,listInnerRef:G}),[]);function re(be,We){var rt,at;let Et=(at=(rt=s.current)==null?void 0:rt.filter)!=null?at:hWe;return be?Et(be,r.current.search,We):0}function se(){if(!r.current.search||s.current.shouldFilter===!1)return;let be=r.current.filtered.items,We=[];r.current.filtered.groups.forEach(at=>{let Et=i.current.get(at),_t=0;Et.forEach(Vt=>{let mt=be.get(Vt);_t=Math.max(mt,_t)}),We.push([at,_t])});let rt=G.current;Oe().sort((at,Et)=>{var _t,Vt;let mt=at.getAttribute("id"),Pt=Et.getAttribute("id");return((_t=be.get(Pt))!=null?_t:0)-((Vt=be.get(mt))!=null?Vt:0)}).forEach(at=>{let Et=at.closest(BB);Et?Et.appendChild(at.parentElement===Et?at:at.closest(`${BB} > *`)):rt.appendChild(at.parentElement===rt?at:at.closest(`${BB} > *`))}),We.sort((at,Et)=>Et[1]-at[1]).forEach(at=>{var Et;let _t=(Et=G.current)==null?void 0:Et.querySelector(`${b2}[${Zb}="${encodeURIComponent(at[0])}"]`);_t==null||_t.parentElement.appendChild(_t)})}function ue(){let be=Oe().find(rt=>rt.getAttribute("aria-disabled")!=="true"),We=be==null?void 0:be.getAttribute(Zb);X.setState("value",We||void 0)}function _e(){var be,We,rt,at;if(!r.current.search||s.current.shouldFilter===!1){r.current.filtered.count=n.current.size;return}r.current.filtered.groups=new Set;let Et=0;for(let _t of n.current){let Vt=(We=(be=a.current.get(_t))==null?void 0:be.value)!=null?We:"",mt=(at=(rt=a.current.get(_t))==null?void 0:rt.keywords)!=null?at:[],Pt=re(Vt,mt);r.current.filtered.items.set(_t,Pt),Pt>0&&Et++}for(let[_t,Vt]of i.current)for(let mt of Vt)if(r.current.filtered.items.get(mt)>0){r.current.filtered.groups.add(_t);break}r.current.filtered.count=Et}function Se(){var be,We,rt;let at=ve();at&&(((be=at.parentElement)==null?void 0:be.firstChild)===at&&((rt=(We=at.closest(b2))==null?void 0:We.querySelector(dWe))==null||rt.scrollIntoView({block:"nearest"})),at.scrollIntoView({block:"nearest"}))}function ve(){var be;return(be=G.current)==null?void 0:be.querySelector(`${u_e}[aria-selected="true"]`)}function Oe(){var be;return Array.from(((be=G.current)==null?void 0:be.querySelectorAll(Ite))||[])}function Ae(be){let We=Oe()[be];We&&X.setState("value",We.getAttribute(Zb))}function we(be){var We;let rt=ve(),at=Oe(),Et=at.findIndex(Vt=>Vt===rt),_t=at[Et+be];(We=s.current)!=null&&We.loop&&(_t=Et+be<0?at[at.length-1]:Et+be===at.length?at[0]:at[Et+be]),_t&&X.setState("value",_t.getAttribute(Zb))}function ge(be){let We=ve(),rt=We==null?void 0:We.closest(b2),at;for(;rt&&!at;)rt=be>0?bWe(rt,b2):wWe(rt,b2),at=rt==null?void 0:rt.querySelector(Ite);at?X.setState("value",at.getAttribute(Zb)):we(be)}let Ne=()=>Ae(Oe().length-1),Ie=be=>{be.preventDefault(),be.metaKey?Ne():be.altKey?ge(1):we(1)},Te=be=>{be.preventDefault(),be.metaKey?Ae(0):be.altKey?ge(-1):we(-1)};return P.createElement(rn.div,{ref:e,tabIndex:-1,...D,"cmdk-root":"",onKeyDown:be=>{var We;(We=D.onKeyDown)==null||We.call(D,be);let rt=be.nativeEvent.isComposing||be.keyCode===229;if(!(be.defaultPrevented||rt))switch(be.key){case"n":case"j":{R&&be.ctrlKey&&Ie(be);break}case"ArrowDown":{Ie(be);break}case"p":case"k":{R&&be.ctrlKey&&Te(be);break}case"ArrowUp":{Te(be);break}case"Home":{be.preventDefault(),Ae(0);break}case"End":{be.preventDefault(),Ne();break}case"Enter":{be.preventDefault();let at=ve();if(at){let Et=new Event(R6);at.dispatchEvent(Et)}}}}},P.createElement("label",{"cmdk-label":"",htmlFor:Q.inputId,id:Q.labelId,style:EWe},f),HM(t,be=>P.createElement(h_e.Provider,{value:X},P.createElement(d_e.Provider,{value:Q},be))))}),fWe=P.forwardRef((t,e)=>{var r,n;let i=Cl(),a=P.useRef(null),c=P.useContext(f_e),s=YC(),f=m_e(t),m=(n=(r=f.current)==null?void 0:r.forceMount)!=null?n:c==null?void 0:c.forceMount;C0(()=>{if(!m)return s.item(i,c==null?void 0:c.id)},[m]);let x=g_e(i,a,[t.value,t.children,a],t.keywords),_=H9(),T=Ky(W=>W.value&&W.value===x.current),E=Ky(W=>m||s.filter()===!1?!0:W.search?W.filtered.items.get(i)>0:!0);P.useEffect(()=>{let W=a.current;if(!(!W||t.disabled))return W.addEventListener(R6,C),()=>W.removeEventListener(R6,C)},[E,t.onSelect,t.disabled]);function C(){var W,X;N(),(X=(W=f.current).onSelect)==null||X.call(W,x.current)}function N(){_.setState("value",x.current,!0)}if(!E)return null;let{disabled:R,value:D,onSelect:M,forceMount:B,keywords:V,...G}=t;return P.createElement(rn.div,{ref:jm(a,e),...G,id:i,"cmdk-item":"",role:"option","aria-disabled":!!R,"aria-selected":!!T,"data-disabled":!!R,"data-selected":!!T,onPointerMove:R||s.getDisablePointerSelection()?void 0:N,onClick:R?void 0:C},t.children)}),pWe=P.forwardRef((t,e)=>{let{heading:r,children:n,forceMount:i,...a}=t,c=Cl(),s=P.useRef(null),f=P.useRef(null),m=Cl(),x=YC(),_=Ky(E=>i||x.filter()===!1?!0:E.search?E.filtered.groups.has(c):!0);C0(()=>x.group(c),[]),g_e(c,s,[t.value,t.heading,f]);let T=P.useMemo(()=>({id:c,forceMount:i}),[i]);return P.createElement(rn.div,{ref:jm(s,e),...a,"cmdk-group":"",role:"presentation",hidden:_?void 0:!0},r&&P.createElement("div",{ref:f,"cmdk-group-heading":"","aria-hidden":!0,id:m},r),HM(t,E=>P.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":r?m:void 0},P.createElement(f_e.Provider,{value:T},E))))}),mWe=P.forwardRef((t,e)=>{let{alwaysRender:r,...n}=t,i=P.useRef(null),a=Ky(c=>!c.search);return!r&&!a?null:P.createElement(rn.div,{ref:jm(i,e),...n,"cmdk-separator":"",role:"separator"})}),gWe=P.forwardRef((t,e)=>{let{onValueChange:r,...n}=t,i=t.value!=null,a=H9(),c=Ky(m=>m.search),s=Ky(m=>m.selectedItemId),f=YC();return P.useEffect(()=>{t.value!=null&&a.setState("search",t.value)},[t.value]),P.createElement(rn.input,{ref:e,...n,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":f.listId,"aria-labelledby":f.labelId,"aria-activedescendant":s,id:f.inputId,type:"text",value:i?t.value:c,onChange:m=>{i||a.setState("search",m.target.value),r==null||r(m.target.value)}})}),yWe=P.forwardRef((t,e)=>{let{children:r,label:n="Suggestions",...i}=t,a=P.useRef(null),c=P.useRef(null),s=Ky(m=>m.selectedItemId),f=YC();return P.useEffect(()=>{if(c.current&&a.current){let m=c.current,x=a.current,_,T=new ResizeObserver(()=>{_=requestAnimationFrame(()=>{let E=m.offsetHeight;x.style.setProperty("--cmdk-list-height",E.toFixed(1)+"px")})});return T.observe(m),()=>{cancelAnimationFrame(_),T.unobserve(m)}}},[]),P.createElement(rn.div,{ref:jm(a,e),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":s,"aria-label":n,id:f.listId},HM(t,m=>P.createElement("div",{ref:jm(c,f.listInnerRef),"cmdk-list-sizer":""},m)))}),xWe=P.forwardRef((t,e)=>{let{open:r,onOpenChange:n,overlayClassName:i,contentClassName:a,container:c,...s}=t;return P.createElement(iM,{open:r,onOpenChange:n},P.createElement(sM,{container:c},P.createElement(hS,{"cmdk-overlay":"",className:i}),P.createElement(fS,{"aria-label":t.label,"cmdk-dialog":"",className:a},P.createElement(p_e,{ref:e,...s}))))}),_We=P.forwardRef((t,e)=>Ky(r=>r.filtered.count===0)?P.createElement(rn.div,{ref:e,...t,"cmdk-empty":"",role:"presentation"}):null),vWe=P.forwardRef((t,e)=>{let{progress:r,children:n,label:i="Loading...",...a}=t;return P.createElement(rn.div,{ref:e,...a,"cmdk-loading":"",role:"progressbar","aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},HM(t,c=>P.createElement("div",{"aria-hidden":!0},c)))}),Iu=Object.assign(p_e,{List:yWe,Item:fWe,Input:gWe,Group:pWe,Separator:mWe,Dialog:xWe,Empty:_We,Loading:vWe});function bWe(t,e){let r=t.nextElementSibling;for(;r;){if(r.matches(e))return r;r=r.nextElementSibling}}function wWe(t,e){let r=t.previousElementSibling;for(;r;){if(r.matches(e))return r;r=r.previousElementSibling}}function m_e(t){let e=P.useRef(t);return C0(()=>{e.current=t}),e}var C0=typeof window>"u"?P.useEffect:P.useLayoutEffect;function Xb(t){let e=P.useRef();return e.current===void 0&&(e.current=t()),e}function Ky(t){let e=H9(),r=()=>t(e.snapshot());return P.useSyncExternalStore(e.subscribe,r,r)}function g_e(t,e,r,n=[]){let i=P.useRef(),a=YC();return C0(()=>{var c;let s=(()=>{var m;for(let x of r){if(typeof x=="string")return x.trim();if(typeof x=="object"&&"current"in x)return x.current?(m=x.current.textContent)==null?void 0:m.trim():i.current}})(),f=n.map(m=>m.trim());a.value(t,s,f),(c=e.current)==null||c.setAttribute(Zb,s),i.current=s}),i}var SWe=()=>{let[t,e]=P.useState(),r=Xb(()=>new Map);return C0(()=>{r.current.forEach(n=>n()),r.current=new Map},[t]),(n,i)=>{r.current.set(n,i),e({})}};function TWe(t){let e=t.type;return typeof e=="function"?e(t.props):"render"in e?e.render(t.props):t}function HM({asChild:t,children:e},r){return t&&P.isValidElement(e)?P.cloneElement(TWe(e),{ref:e.ref},r(e.props.children)):r(e)}var EWe={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const mk=P.forwardRef(({className:t,...e},r)=>o.jsx(Iu,{ref:r,className:sr("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",t),...e}));mk.displayName=Iu.displayName;const AWe=({children:t,...e})=>o.jsx(ro,{...e,children:o.jsx($a,{className:"overflow-hidden p-0 shadow-lg",children:o.jsx(mk,{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})})}),gk=P.forwardRef(({className:t,...e},r)=>o.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[o.jsx($y,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),o.jsx(Iu.Input,{ref:r,className:sr("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})]}));gk.displayName=Iu.Input.displayName;const yk=P.forwardRef(({className:t,...e},r)=>o.jsx(Iu.List,{ref:r,className:sr("max-h-[300px] overflow-y-auto overflow-x-hidden",t),...e}));yk.displayName=Iu.List.displayName;const xk=P.forwardRef((t,e)=>o.jsx(Iu.Empty,{ref:e,className:"py-6 text-center text-sm",...t}));xk.displayName=Iu.Empty.displayName;const T1=P.forwardRef(({className:t,...e},r)=>o.jsx(Iu.Group,{ref:r,className:sr("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}));T1.displayName=Iu.Group.displayName;const kWe=P.forwardRef(({className:t,...e},r)=>o.jsx(Iu.Separator,{ref:r,className:sr("-mx-1 h-px bg-border",t),...e}));kWe.displayName=Iu.Separator.displayName;const xy=P.forwardRef(({className:t,...e},r)=>o.jsx(Iu.Item,{ref:r,className:sr("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}));xy.displayName=Iu.Item.displayName;const CWe={event:{label:"Events",icon:Zf,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:XO,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:XA,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:_G,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:Ss,color:"bg-fuchsia-500/10 text-fuchsia-600"}},Pte=()=>{const[t,e]=P.useState(!1),[r,n]=P.useState(""),[i,a]=P.useState([]),[c,s]=P.useState(!1),f=ma(),{searchDestinations:m,isFavorite:x,routeFor:_}=l_e(),T=r.trim()?m(r).slice(0,6):[];P.useEffect(()=>{const R=D=>{D.key==="k"&&(D.metaKey||D.ctrlKey)&&(D.preventDefault(),e(M=>!M))};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[]);const E=P.useCallback(async R=>{if(!R.trim()){a([]);return}s(!0);const D=`%${R}%`;try{const[M,B,V,G,W]=await Promise.all([Le.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${D},description.ilike.${D}`).limit(5),Le.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${D},description.ilike.${D}`).limit(5),Le.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${D},description.ilike.${D}`).limit(5),Le.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${D},description.ilike.${D}`).limit(5),Le.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${D},description.ilike.${D}`).limit(5)]),X=[];M.data&&M.data.forEach(Q=>{X.push({id:Q.id,title:Q.title,description:Q.description,type:"event",date:Q.event_date,path:`/event/${Q.id}`})}),B.data&&B.data.forEach(Q=>{X.push({id:Q.id,title:Q.name,description:Q.description,type:"template",date:Q.publish_date,path:`/templates/${Q.id}`})}),V.data&&V.data.forEach(Q=>{X.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=>{X.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=>{X.push({id:Q.id,title:Q.title,description:Q.description,type:"social-swag",date:Q.publish_date,path:`/social-swag/${Q.id}`})}),a(X)}catch(M){console.error("Search error:",M)}finally{s(!1)}},[]);P.useEffect(()=>{const R=setTimeout(()=>{E(r)},300);return()=>clearTimeout(R)},[r,E]);const C=R=>{e(!1),n(""),f(R)},N=i.reduce((R,D)=>(R[D.type]||(R[D.type]=[]),R[D.type].push(D),R),{});return o.jsxs(o.Fragment,{children:[o.jsxs(Ut,{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:[o.jsx($y,{className:"h-4 w-4 xl:mr-2"}),o.jsx("span",{className:"hidden xl:inline-flex text-muted-foreground text-sm",children:"Search..."}),o.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:[o.jsx("span",{className:"text-xs",children:"⌘"}),"K"]})]}),o.jsxs(AWe,{open:t,onOpenChange:e,children:[o.jsx(gk,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:r,onValueChange:n}),o.jsxs(yk,{children:[T.length>0&&o.jsx(T1,{heading:"Go to",children:T.map(R=>{const D=R.icon;return o.jsxs(xy,{value:`nav-${R.id}-${R.label}`,onSelect:()=>{const M=_(R);R.external||R.openInNewTab?(e(!1),n(""),window.open(M,"_blank","noopener,noreferrer")):C(M)},className:"flex items-start gap-3 py-3 cursor-pointer",children:[o.jsx("div",{className:"p-2 rounded-md bg-primary/10 text-primary",children:o.jsx(D,{className:"h-4 w-4"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"font-medium truncate flex items-center gap-1.5",children:[R.label,x(R)&&o.jsx(kL,{className:"h-3 w-3 fill-current text-primary"})]}),R.description&&o.jsx("div",{className:"text-sm text-muted-foreground truncate",children:R.description})]}),o.jsx(us,{variant:"secondary",className:"text-xs shrink-0",children:R.section})]},`nav-${R.id}`)})}),c&&o.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!c&&r&&i.length===0&&T.length===0&&o.jsxs(xk,{children:['No results found for "',r,'"']}),!c&&!r&&o.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search pages, apps and content..."}),Object.entries(N).map(([R,D])=>{const M=CWe[R],B=M.icon;return o.jsx(T1,{heading:M.label,children:D.map(V=>o.jsxs(xy,{value:`${V.type}-${V.id}-${V.title}`,onSelect:()=>C(V.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[o.jsx("div",{className:`p-2 rounded-md ${M.color}`,children:o.jsx(B,{className:"h-4 w-4"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:"font-medium truncate",children:V.title}),V.description&&o.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:V.description})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[o.jsx(us,{variant:"secondary",className:"text-xs",children:M.label}),o.jsx("span",{className:"text-xs text-muted-foreground",children:Jxe(new Date(V.date),{addSuffix:!0})})]})]},`${V.type}-${V.id}`))},R)})]})]})]})},jWe=({expiresAt:t,className:e,showUpgradeButton:r=!0})=>{const[n,i]=P.useState(null),a=ma();if(P.useEffect(()=>{const m=()=>{const _=new Date().getTime(),E=new Date(t).getTime()-_;if(E<=0){i({days:0,hours:0,minutes:0});return}const C=Math.floor(E/(1e3*60*60*24)),N=Math.floor(E%(1e3*60*60*24)/(1e3*60*60)),R=Math.floor(E%(1e3*60*60)/(1e3*60));i({days:C,hours:N,minutes:R})};m();const x=setInterval(m,6e4);return()=>clearInterval(x)},[t]),!n)return null;const c=n.days===0&&n.hours===0&&n.minutes===0,s=n.days<=1,f=n.days<=3&&!s;return c?o.jsxs("div",{className:sr("flex items-center justify-between gap-3 px-4 py-2 rounded-lg bg-destructive/10 border border-destructive/20",e),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(CC,{className:"h-4 w-4 text-destructive"}),o.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),r&&o.jsxs(Ut,{size:"sm",onClick:()=>a("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[o.jsx(Ss,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):o.jsxs("div",{className:sr("flex items-center justify-between gap-3 px-4 py-2 rounded-lg border transition-colors",s?"bg-destructive/10 border-destructive/20":f?"bg-amber-500/10 border-amber-500/20":"bg-primary/10 border-primary/20",e),children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(mc,{className:sr("h-4 w-4",s?"text-destructive":f?"text-amber-500":"text-primary")}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:sr("text-sm font-medium",s?"text-destructive":f?"text-amber-600":"text-primary"),children:"Free Trial:"}),o.jsxs("div",{className:"flex items-center gap-1",children:[n.days>0&&o.jsxs("span",{className:sr("text-sm font-bold",s?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.days,"d"]}),o.jsxs("span",{className:sr("text-sm font-bold",s?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.hours,"h"]}),o.jsxs("span",{className:sr("text-sm font-bold",s?"text-destructive":f?"text-amber-600":"text-primary"),children:[n.minutes,"m"]}),o.jsx("span",{className:sr("text-xs",s?"text-destructive/70":f?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),r&&o.jsxs(Ut,{size:"sm",onClick:()=>a("/subscription"),variant:s?"destructive":f?"default":"outline",className:sr("text-xs h-7 px-3",f&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[o.jsx(Ss,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},IWe=()=>{const t=ma();return o.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:o.jsxs(Hn,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[o.jsxs(Ju,{className:"text-center pb-2",children:[o.jsx("div",{className:"mx-auto mb-4 h-16 w-16 rounded-full bg-destructive/10 flex items-center justify-center",children:o.jsx(CC,{className:"h-8 w-8 text-destructive"})}),o.jsx(ed,{className:"text-2xl",children:"Your Free Trial Has Ended"}),o.jsx(dk,{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!"})]}),o.jsxs(ii,{className:"space-y-6",children:[o.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[o.jsx(Hn,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>t("/subscription"),children:o.jsxs(ii,{className:"p-5 text-center",children:[o.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:o.jsx(Al,{className:"h-6 w-6 text-primary"})}),o.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),o.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",o.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),o.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),o.jsxs(Ut,{className:"w-full",onClick:e=>{e.stopPropagation(),t("/subscription")},children:[o.jsx(Ss,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),o.jsx(Hn,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>t("/subscription"),children:o.jsxs(ii,{className:"p-5 text-center",children:[o.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-amber-500/10 flex items-center justify-center",children:o.jsx(Eo,{className:"h-6 w-6 text-amber-600"})}),o.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Brokerage"}),o.jsxs("p",{className:"text-2xl font-bold text-amber-600 mb-2",children:["$299",o.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),o.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"For teams and brokerages"}),o.jsxs(Ut,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:e=>{e.stopPropagation(),t("/subscription")},children:[o.jsx(Eo,{className:"h-4 w-4 mr-2"}),"Choose Brokerage"]})]})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"With a full membership, you'll get:"}),o.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground grid sm:grid-cols-2 gap-x-4",children:[o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"✓"})," Unlimited access to all marketing templates"]}),o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"✓"})," Complete Academy training library"]}),o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"✓"})," AI-powered tools and resources"]}),o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"✓"})," Community forums and support"]}),o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"✓"})," Exclusive member events and workshops"]}),o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"✓"})," Deal pipeline & scorecard tracking"]})]})]}),o.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3",children:[o.jsx("p",{className:"text-sm font-medium text-center",children:"Questions? Contact us:"}),o.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[o.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[o.jsx(zi,{className:"h-4 w-4"}),o.jsx("span",{children:"1-866-527-8668"})]}),o.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[o.jsx(Bi,{className:"h-4 w-4"}),o.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},PWe=({hasUnseenBrief:t,onClick:e,className:r})=>o.jsxs(PFe,{children:[o.jsx(NFe,{asChild:!0,children:o.jsxs(Ut,{variant:"ghost",size:"icon",onClick:e,className:sr("relative transition-colors",t&&"text-primary hover:text-primary",r),children:[o.jsx(AC,{className:"h-5 w-5"}),t&&o.jsx("span",{className:"absolute top-1 right-1 h-2 w-2 rounded-full bg-primary animate-pulse"})]})}),o.jsx(Ipe,{children:o.jsx("p",{children:"The LevelUp Brief"})})]});var WM="Checkbox",[NWe,QUt]=Ho(WM),[RWe,W9]=NWe(WM);function LWe(t){const{__scopeCheckbox:e,checked:r,children:n,defaultChecked:i,disabled:a,form:c,name:s,onCheckedChange:f,required:m,value:x="on",internal_do_not_use_render:_}=t,[T,E]=ad({prop:r,defaultProp:i??!1,onChange:f,caller:WM}),[C,N]=P.useState(null),[R,D]=P.useState(null),M=P.useRef(!1),B=C?!!c||!!C.closest("form"):!0,V={checked:T,disabled:a,setChecked:E,control:C,setControl:N,name:s,form:c,value:x,hasConsumerStoppedPropagationRef:M,required:m,defaultChecked:Py(i)?!1:i,isFormControl:B,bubbleInput:R,setBubbleInput:D};return o.jsx(RWe,{scope:e,...V,children:DWe(_)?_(V):n})}var y_e="CheckboxTrigger",x_e=P.forwardRef(({__scopeCheckbox:t,onKeyDown:e,onClick:r,...n},i)=>{const{control:a,value:c,disabled:s,checked:f,required:m,setControl:x,setChecked:_,hasConsumerStoppedPropagationRef:T,isFormControl:E,bubbleInput:C}=W9(y_e,t),N=Wn(i,x),R=P.useRef(f);return P.useEffect(()=>{const D=a==null?void 0:a.form;if(D){const M=()=>_(R.current);return D.addEventListener("reset",M),()=>D.removeEventListener("reset",M)}},[a,_]),o.jsx(rn.button,{type:"button",role:"checkbox","aria-checked":Py(f)?"mixed":f,"aria-required":m,"data-state":S_e(f),"data-disabled":s?"":void 0,disabled:s,value:c,...n,ref:N,onKeyDown:Or(e,D=>{D.key==="Enter"&&D.preventDefault()}),onClick:Or(r,D=>{_(M=>Py(M)?!0:!M),C&&E&&(T.current=D.isPropagationStopped(),T.current||D.stopPropagation())})})});x_e.displayName=y_e;var K9=P.forwardRef((t,e)=>{const{__scopeCheckbox:r,name:n,checked:i,defaultChecked:a,required:c,disabled:s,value:f,onCheckedChange:m,form:x,..._}=t;return o.jsx(LWe,{__scopeCheckbox:r,checked:i,defaultChecked:a,disabled:s,required:c,onCheckedChange:m,name:n,form:x,value:f,internal_do_not_use_render:({isFormControl:T})=>o.jsxs(o.Fragment,{children:[o.jsx(x_e,{..._,ref:e,__scopeCheckbox:r}),T&&o.jsx(w_e,{__scopeCheckbox:r})]})})});K9.displayName=WM;var __e="CheckboxIndicator",v_e=P.forwardRef((t,e)=>{const{__scopeCheckbox:r,forceMount:n,...i}=t,a=W9(__e,r);return o.jsx(dl,{present:n||Py(a.checked)||a.checked===!0,children:o.jsx(rn.span,{"data-state":S_e(a.checked),"data-disabled":a.disabled?"":void 0,...i,ref:e,style:{pointerEvents:"none",...t.style}})})});v_e.displayName=__e;var b_e="CheckboxBubbleInput",w_e=P.forwardRef(({__scopeCheckbox:t,...e},r)=>{const{control:n,hasConsumerStoppedPropagationRef:i,checked:a,defaultChecked:c,required:s,disabled:f,name:m,value:x,form:_,bubbleInput:T,setBubbleInput:E}=W9(b_e,t),C=Wn(r,E),N=HC(a),R=DC(n);P.useEffect(()=>{const M=T;if(!M)return;const B=window.HTMLInputElement.prototype,G=Object.getOwnPropertyDescriptor(B,"checked").set,W=!i.current;if(N!==a&&G){const X=new Event("click",{bubbles:W});M.indeterminate=Py(a),G.call(M,Py(a)?!1:a),M.dispatchEvent(X)}},[T,N,a,i]);const D=P.useRef(Py(a)?!1:a);return o.jsx(rn.input,{type:"checkbox","aria-hidden":!0,defaultChecked:c??D.current,required:s,disabled:f,name:m,value:x,form:_,...e,tabIndex:-1,ref:C,style:{...e.style,...R,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});w_e.displayName=b_e;function DWe(t){return typeof t=="function"}function Py(t){return t==="indeterminate"}function S_e(t){return Py(t)?"indeterminate":t?"checked":"unchecked"}const ZC=P.forwardRef(({className:t,...e},r)=>o.jsx(K9,{ref:r,className:sr("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:o.jsx(v_e,{className:sr("flex items-center justify-center text-current"),children:o.jsx(Ao,{className:"h-4 w-4"})})}));ZC.displayName=K9.displayName;var Y9="Radio",[OWe,T_e]=Ho(Y9),[MWe,FWe]=OWe(Y9),E_e=P.forwardRef((t,e)=>{const{__scopeRadio:r,name:n,checked:i=!1,required:a,disabled:c,value:s="on",onCheck:f,form:m,...x}=t,[_,T]=P.useState(null),E=Wn(e,R=>T(R)),C=P.useRef(!1),N=_?m||!!_.closest("form"):!0;return o.jsxs(MWe,{scope:r,checked:i,disabled:c,children:[o.jsx(rn.button,{type:"button",role:"radio","aria-checked":i,"data-state":j_e(i),"data-disabled":c?"":void 0,disabled:c,value:s,...x,ref:E,onClick:Or(t.onClick,R=>{i||f==null||f(),N&&(C.current=R.isPropagationStopped(),C.current||R.stopPropagation())})}),N&&o.jsx(C_e,{control:_,bubbles:!C.current,name:n,value:s,checked:i,required:a,disabled:c,form:m,style:{transform:"translateX(-100%)"}})]})});E_e.displayName=Y9;var A_e="RadioIndicator",k_e=P.forwardRef((t,e)=>{const{__scopeRadio:r,forceMount:n,...i}=t,a=FWe(A_e,r);return o.jsx(dl,{present:n||a.checked,children:o.jsx(rn.span,{"data-state":j_e(a.checked),"data-disabled":a.disabled?"":void 0,...i,ref:e})})});k_e.displayName=A_e;var BWe="RadioBubbleInput",C_e=P.forwardRef(({__scopeRadio:t,control:e,checked:r,bubbles:n=!0,...i},a)=>{const c=P.useRef(null),s=Wn(c,a),f=HC(r),m=DC(e);return P.useEffect(()=>{const x=c.current;if(!x)return;const _=window.HTMLInputElement.prototype,E=Object.getOwnPropertyDescriptor(_,"checked").set;if(f!==r&&E){const C=new Event("click",{bubbles:n});E.call(x,r),x.dispatchEvent(C)}},[f,r,n]),o.jsx(rn.input,{type:"radio","aria-hidden":!0,defaultChecked:r,...i,tabIndex:-1,ref:s,style:{...i.style,...m,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});C_e.displayName=BWe;function j_e(t){return t?"checked":"unchecked"}var zWe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],KM="RadioGroup",[$We,JUt]=Ho(KM,[bS,T_e]),I_e=bS(),P_e=T_e(),[UWe,VWe]=$We(KM),N_e=P.forwardRef((t,e)=>{const{__scopeRadioGroup:r,name:n,defaultValue:i,value:a,required:c=!1,disabled:s=!1,orientation:f,dir:m,loop:x=!0,onValueChange:_,...T}=t,E=I_e(r),C=$0(m),[N,R]=ad({prop:a,defaultProp:i??null,onChange:_,caller:KM});return o.jsx(UWe,{scope:r,name:n,required:c,disabled:s,value:N,onValueChange:R,children:o.jsx(e9,{asChild:!0,...E,orientation:f,dir:C,loop:x,children:o.jsx(rn.div,{role:"radiogroup","aria-required":c,"aria-orientation":f,"data-disabled":s?"":void 0,dir:C,...T,ref:e})})})});N_e.displayName=KM;var R_e="RadioGroupItem",L_e=P.forwardRef((t,e)=>{const{__scopeRadioGroup:r,disabled:n,...i}=t,a=VWe(R_e,r),c=a.disabled||n,s=I_e(r),f=P_e(r),m=P.useRef(null),x=Wn(e,m),_=a.value===i.value,T=P.useRef(!1);return P.useEffect(()=>{const E=N=>{zWe.includes(N.key)&&(T.current=!0)},C=()=>T.current=!1;return document.addEventListener("keydown",E),document.addEventListener("keyup",C),()=>{document.removeEventListener("keydown",E),document.removeEventListener("keyup",C)}},[]),o.jsx(t9,{asChild:!0,...s,focusable:!c,active:_,children:o.jsx(E_e,{disabled:c,required:a.required,checked:_,...f,...i,name:a.name,ref:x,onCheck:()=>a.onValueChange(i.value),onKeyDown:Or(E=>{E.key==="Enter"&&E.preventDefault()}),onFocus:Or(i.onFocus,()=>{var E;T.current&&((E=m.current)==null||E.click())})})})});L_e.displayName=R_e;var qWe="RadioGroupIndicator",D_e=P.forwardRef((t,e)=>{const{__scopeRadioGroup:r,...n}=t,i=P_e(r);return o.jsx(k_e,{...i,...n,ref:e})});D_e.displayName=qWe;var O_e=N_e,M_e=L_e,GWe=D_e;const F_e=P.forwardRef(({className:t,...e},r)=>o.jsx(O_e,{className:sr("grid gap-2",t),...e,ref:r}));F_e.displayName=O_e.displayName;const B_e=P.forwardRef(({className:t,...e},r)=>o.jsx(M_e,{ref:r,className:sr("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:o.jsx(GWe,{className:"flex items-center justify-center",children:o.jsx(d1,{className:"h-2.5 w-2.5 fill-current text-current"})})}));B_e.displayName=M_e.displayName;const HWe=({brief:t,open:e,onClose:r,onDismiss:n})=>{const{user:i}=qn(),[a,c]=P.useState({}),[s,f]=P.useState({}),[m,x]=P.useState([]);P.useEffect(()=>{e&&i&&t.polls.length>0&&_()},[e,i,t.polls]);const _=async()=>{if(!i)return;const R=t.polls.map(M=>M.id),{data:D}=await Le.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",i.id).in("poll_id",R);if(D){const M={};D.forEach(B=>{M[B.poll_id]||(M[B.poll_id]=[]),M[B.poll_id].push(B.option_id)}),f(M)}},T=(R,D)=>{c(M=>({...M,[R]:D}))},E=(R,D,M)=>{c(B=>{const V=B[R]||[];return M?{...B,[R]:[...V,D]}:{...B,[R]:V.filter(G=>G!==D)}})},C=async R=>{if(!i)return;const D=a[R];if(!D||Array.isArray(D)&&D.length===0){Jt.error("Please select an option");return}x(M=>[...M,R]);try{await Le.from("levelup_brief_poll_responses").delete().eq("poll_id",R).eq("user_id",i.id);const M=Array.isArray(D)?D:[D],B=M.map(G=>({poll_id:R,option_id:G,user_id:i.id})),{error:V}=await Le.from("levelup_brief_poll_responses").insert(B);if(V)throw V;f(G=>({...G,[R]:M})),Jt.success("Response submitted!")}catch(M){console.error("Error submitting poll response:",M),Jt.error("Failed to submit response")}finally{x(M=>M.filter(B=>B!==R))}},N=R=>(R.includes("mediadelivery.net")||R.includes("bunny"),R);return o.jsx(ro,{open:e,onOpenChange:R=>!R&&r(),children:o.jsxs($a,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[o.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[o.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:o.jsx(Ks,{className:"h-5 w-5 text-white"})}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"p-2 bg-white/20 rounded-lg",children:o.jsx(AC,{className:"h-6 w-6"})}),o.jsxs("div",{children:[o.jsx(us,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),o.jsx(Go,{className:"text-xl font-bold text-white",children:t.brief.title})]})]})]}),o.jsx(pp,{className:"max-h-[calc(90vh-240px)]",children:o.jsxs("div",{className:"p-6 space-y-6",children:[t.brief.description&&o.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:t.brief.description}}),t.brief.video_url&&o.jsx("div",{className:"relative w-full aspect-video rounded-lg overflow-hidden bg-muted",children:o.jsx("iframe",{src:N(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&&o.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:t.brief.graphic_link_url?o.jsx("a",{href:t.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:o.jsx("img",{src:t.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):o.jsx("img",{src:t.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),t.links.length>0&&o.jsxs("div",{className:"space-y-3",children:[o.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),o.jsx("div",{className:"flex flex-wrap gap-2",children:t.links.map(R=>o.jsxs(Ut,{variant:"outline",size:"sm",onClick:()=>window.open(R.url,"_blank"),className:"gap-2",children:[o.jsx(cS,{className:"h-4 w-4"}),R.title]},R.id))})]}),t.polls.map(R=>{var B,V;const D=((B=s[R.id])==null?void 0:B.length)>0,M=m.includes(R.id);return o.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("h4",{className:"font-semibold text-foreground",children:R.question}),D&&o.jsxs(us,{variant:"secondary",className:"gap-1",children:[o.jsx(xc,{className:"h-3 w-3"}),"Responded"]})]}),R.poll_type==="single"?o.jsx(F_e,{value:a[R.id]||((V=s[R.id])==null?void 0:V[0])||"",onValueChange:G=>T(R.id,G),className:"space-y-2",children:R.options.map(G=>o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx(B_e,{value:G.id,id:G.id}),o.jsx(Mr,{htmlFor:G.id,className:"cursor-pointer",children:G.option_text})]},G.id))}):o.jsx("div",{className:"space-y-2",children:R.options.map(G=>{const X=(a[R.id]||s[R.id]||[]).includes(G.id);return o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx(ZC,{id:G.id,checked:X,onCheckedChange:Q=>E(R.id,G.id,Q)}),o.jsx(Mr,{htmlFor:G.id,className:"cursor-pointer",children:G.option_text})]},G.id)})}),o.jsx(Ut,{size:"sm",onClick:()=>C(R.id),disabled:M,children:M?"Submitting...":D?"Update Response":"Submit"})]},R.id)})]})}),o.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:[o.jsx(Ut,{onClick:r,className:"w-full max-w-xs",children:"Got it!"}),o.jsx(Ut,{variant:"ghost",size:"sm",onClick:n,children:"Don't show again"})]})]})})},WWe=()=>{const{user:t}=qn(),[e,r]=P.useState(null),[n,i]=P.useState(!1),[a,c]=P.useState(!0),[s,f]=P.useState(!1),m=P.useCallback(async()=>{if(!t){c(!1);return}try{const{data:C,error:N}=await Le.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(N||!C){c(!1);return}const{data:R}=await Le.from("levelup_brief_views").select("*").eq("brief_id",C.id).eq("user_id",t.id).maybeSingle(),[D,M]=await Promise.all([Le.from("levelup_brief_links").select("*").eq("brief_id",C.id).order("sort_order"),Le.from("levelup_brief_polls").select("*").eq("brief_id",C.id).order("sort_order")]),B=[];if(M.data)for(const Q of M.data){const{data:re}=await Le.from("levelup_brief_poll_options").select("*").eq("poll_id",Q.id).order("sort_order");B.push({...Q,options:re||[]})}const V={brief:C,links:D.data||[],polls:B};r(V);const G=!!R,W=(R==null?void 0:R.dismissed_at)!=null,X=localStorage.getItem(`brief-dismissed-${C.id}`)==="true";if(W||X)f(!1),i(!1);else if(!G)i(!0),f(!0);else if(C.show_frequency==="every_login")i(!0),f(!0);else if(C.show_frequency==="daily"){const Q=new Date(R.viewed_at);(new Date().getTime()-Q.getTime())/(1e3*60*60)>=24&&(i(!0),f(!0))}else f(!1)}catch(C){console.error("Error fetching brief:",C)}finally{c(!1)}},[t]);P.useEffect(()=>{m()},[m]);const x=async()=>{if(!(!t||!e))try{const{data:C}=await Le.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();C?await Le.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",C.id):await Le.from("levelup_brief_views").insert({brief_id:e.brief.id,user_id:t.id})}catch(C){console.error("Error marking brief as viewed:",C)}};return{currentBrief:e,shouldShowPopup:n,hasUnseenBrief:s,loading:a,openBrief:()=>{i(!0)},closeBrief:()=>{i(!1),x()},dismissBrief:async()=>{if(!(!t||!e)){i(!1),f(!1);try{const{data:C,error:N}=await Le.from("levelup_brief_views").select("id").eq("brief_id",e.brief.id).eq("user_id",t.id).maybeSingle();if(N&&console.error("Error checking existing brief view:",N),C){const{error:R}=await Le.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",C.id).eq("user_id",t.id);R&&console.error("Error updating brief dismiss:",R)}else{const{error:R}=await Le.from("levelup_brief_views").insert({brief_id:e.brief.id,user_id:t.id,dismissed_at:new Date().toISOString()});R&&console.error("Error inserting brief dismiss:",R)}localStorage.setItem(`brief-dismissed-${e.brief.id}`,"true")}catch(C){console.error("Error dismissing brief:",C),e&&localStorage.setItem(`brief-dismissed-${e.brief.id}`,"true")}}},refetch:m}};function KWe(){const[t,e]=P.useState(!1),[r,n]=P.useState(!1),[i,a]=P.useState(null);P.useEffect(()=>{const f=localStorage.getItem("install-banner-dismissed"),m=localStorage.getItem("install-banner-shown");if(f||m)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 T=/iPhone|iPad|iPod/i.test(navigator.userAgent);n(T),e(!0),localStorage.setItem("install-banner-shown","true");const E=C=>{C.preventDefault(),a(C)};return window.addEventListener("beforeinstallprompt",E),()=>{window.removeEventListener("beforeinstallprompt",E)}},[]);const c=()=>{localStorage.setItem("install-banner-dismissed","true"),localStorage.setItem("install-banner-shown","true"),e(!1)},s=async()=>{if(i){await i.prompt();const{outcome:f}=await i.userChoice;f==="accepted"&&c(),a(null)}};return t?o.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:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[o.jsx("div",{className:"flex-shrink-0 p-2 bg-primary-foreground/10 rounded-full",children:o.jsx(Xl,{className:"h-5 w-5"})}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"font-medium text-sm",children:"Add LevelUp to your home screen"}),r?o.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",o.jsx(yLe,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):o.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!r&&i&&o.jsx(Ut,{size:"sm",variant:"secondary",onClick:s,className:"text-xs",children:"Install"}),o.jsx(Ut,{size:"sm",variant:"secondary",onClick:c,className:"text-xs",children:"Got it"}),o.jsx("button",{onClick:c,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:o.jsx(Ks,{className:"h-4 w-4"})})]})]})}):null}const YWe=({children:t,onRefresh:e})=>{const[r,n]=P.useState(!1),[i,a]=P.useState(0),[c,s]=P.useState(!1),f=P.useRef(null),m=P.useRef(0),x=Nr(),_=80,T=120,E=P.useCallback(M=>{const B=f.current;B&&B.scrollTop<=0&&(m.current=M.touches[0].clientY,n(!0))},[]),C=P.useCallback(M=>{if(!r||c)return;const B=f.current;if(!B||B.scrollTop>0){n(!1),a(0);return}const G=M.touches[0].clientY-m.current;if(G>0){const X=Math.min(G*.5,T);a(X),X>10&&M.preventDefault()}},[r,c]),N=P.useCallback(async()=>{if(r)if(n(!1),i>=_&&!c){s(!0),a(_);try{e?await e():await x.invalidateQueries()}catch(M){console.error("Refresh failed:",M)}finally{s(!1),a(0)}}else a(0)},[r,i,c,e,x]),R=Math.min(i/_,1),D=R*180;return o.jsxs("div",{ref:f,className:"h-full overflow-auto",onTouchStart:E,onTouchMove:C,onTouchEnd:N,children:[o.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:i>0?i:0,opacity:R},children:o.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${c?"animate-spin":""}`,style:{transform:c?void 0:`rotate(${D}deg)`,transition:c?void 0:"transform 0.1s ease-out"},children:o.jsx(mLe,{className:"h-5 w-5 text-primary"})})}),o.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})]})},ZWe=()=>{const{user:t}=qn(),[e,r]=P.useState(!1),[n,i]=P.useState(!1),[a,c]=P.useState(0),[s,f]=P.useState(!0);P.useEffect(()=>{(async()=>{if(!t){f(!1);return}try{const{data:E}=await Le.from("membership_reviews").select("id").eq("user_id",t.id).maybeSingle();if(E){i(!0),r(!1),f(!1);return}const{data:C}=await Le.from("profiles").select("login_count").eq("id",t.id).single(),N=(C==null?void 0:C.login_count)||0;c(N);const R=sessionStorage.getItem("review-prompt-dismissed");r(N>=4&&!R)}catch(E){console.error("Error checking review eligibility:",E)}finally{f(!1)}})()},[t]);const m=P.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),r(!1)},[]),x=P.useCallback(async(T,E)=>{if(!t)return{success:!1,error:"Not authenticated"};try{const{error:C}=await Le.from("membership_reviews").insert({user_id:t.id,rating:T,review_text:E});if(C)throw C;return i(!0),r(!1),{success:!0,pointsAwarded:25}}catch(C){return console.error("Error submitting review:",C),{success:!1,error:C.message}}},[t]),_=P.useCallback(async()=>{if(t)try{await Le.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",t.id)}catch(T){console.error("Error updating Google review status:",T)}},[t]);return{shouldShowPrompt:e,hasSubmittedReview:n,loginCount:a,isLoading:s,dismissPrompt:m,submitReview:x,markPostedToGoogle:_}},XWe="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",QWe=()=>{const{shouldShowPrompt:t,isLoading:e,dismissPrompt:r,submitReview:n,markPostedToGoogle:i}=ZWe(),[a,c]=P.useState(!1),[s,f]=P.useState("review"),[m,x]=P.useState(0),[_,T]=P.useState(0),[E,C]=P.useState(""),[N,R]=P.useState(!1),[D,M]=P.useState(!1);if(e||!t&&!D)return null;const B=async()=>{if(m===0){Ts({title:"Please select a rating",variant:"destructive"});return}R(!0);const W=await n(m,E);R(!1),W.success?(M(!0),Ts({title:"Thank you for your feedback!",description:"Your review helps us improve."}),f("google")):Ts({title:"Error submitting review",description:W.error,variant:"destructive"})},V=async W=>{W&&(await navigator.clipboard.writeText(E||`${m} star rating for LevelUp!`),Ts({title:"Review copied!",description:"Paste it on Google Reviews."}),await i(),window.open(XWe,"_blank")),c(!1),r()},G=()=>{c(!1),r()};return o.jsxs(o.Fragment,{children:[o.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:[o.jsx(Xc,{className:"h-3.5 w-3.5 fill-current"}),o.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),o.jsx(ro,{open:a,onOpenChange:G,children:o.jsx($a,{className:"sm:max-w-md",children:s==="review"?o.jsxs(o.Fragment,{children:[o.jsxs(ul,{children:[o.jsx(Go,{className:"text-center",children:"How are you enjoying LevelUp?"}),o.jsx(ld,{className:"text-center",children:"Your feedback helps us improve the experience for all members."})]}),o.jsxs("div",{className:"space-y-6 py-4",children:[o.jsx("div",{className:"flex justify-center gap-1",children:[1,2,3,4,5].map(W=>o.jsx("button",{type:"button",onClick:()=>x(W),onMouseEnter:()=>T(W),onMouseLeave:()=>T(0),className:"p-1 transition-transform hover:scale-110",children:o.jsx(Xc,{className:sr("h-8 w-8 transition-colors",(_||m)>=W?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},W))}),o.jsx(hd,{placeholder:"Tell us about your experience (optional)",value:E,onChange:W=>C(W.target.value),rows:4,className:"resize-none"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ut,{variant:"outline",onClick:G,className:"flex-1",children:"Maybe Later"}),o.jsx(Ut,{onClick:B,disabled:N||m===0,className:"flex-1",children:N?"Submitting...":"Submit Review"})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsxs(ul,{children:[o.jsx(Go,{className:"text-center",children:"🎉 Thank you!"}),o.jsx(ld,{className:"text-center",children:"Would you mind sharing your review on Google? It really helps other agents discover LevelUp!"})]}),o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"We'll copy your review so you can easily paste it."}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ut,{variant:"outline",onClick:()=>V(!1),className:"flex-1",children:"No Thanks"}),o.jsx(Ut,{onClick:()=>V(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function JWe(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(!_){c(!1);return}(async()=>{try{const N="vapid_public_key";let R=localStorage.getItem(N);if(!R){const{data:B,error:V}=await Le.functions.invoke("get-vapid-public-key",{body:{}});if(V)throw V;if(R=(B==null?void 0:B.vapidPublicKey)??null,!R)throw new Error("Missing VAPID public key");localStorage.setItem(N,R)}x(R);const D=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});f(D),r(Notification.permission);const M=await D.pushManager.getSubscription();i(!!M)}catch(N){console.error("Error initializing push notifications:",N)}finally{c(!1)}})()},[_]);const T=P.useCallback(async()=>{if(!_||!s||!t)return console.error("Push notifications not supported or user not logged in"),!1;if(!m)return Jt.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{c(!0);const C=await s.pushManager.getSubscription();if(C){try{await C.unsubscribe()}catch(V){console.warn("Failed to unsubscribe existing push subscription:",V)}const{error:B}=await Le.from("push_subscriptions").delete().eq("user_id",t.id);B&&console.warn("Failed to cleanup push_subscriptions rows:",B)}if(Notification.permission!=="granted"){const B=await Notification.requestPermission();if(r(B),B!=="granted")return B==="denied"?Jt.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):Jt.error("Notification permission was dismissed. Please try again."),!1}const N=JWe(m);let R;try{R=await s.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:N})}catch(B){console.error("PushManager.subscribe() failed:",B);const V=(B==null?void 0:B.message)||String(B);return V.includes("permission")?Jt.error("Push permission denied. Check your browser notification settings."):V.includes("key")||V.includes("VAPID")?Jt.error("Push configuration error. Please contact support."):V.includes("AbortError")?Jt.error("Push subscription was cancelled. Please try again."):Jt.error(`Failed to subscribe: ${V}`),!1}const D=R.toJSON(),{error:M}=await Le.from("push_subscriptions").upsert({user_id:t.id,endpoint:D.endpoint,p256dh_key:D.keys.p256dh,auth_key:D.keys.auth},{onConflict:"user_id,endpoint"});if(M)throw console.error("Error saving subscription:",M),Jt.error("Failed to save notification preferences. Please try again."),M;return i(!0),Jt.success("Push notifications enabled!"),!0}catch(C){if(console.error("Error subscribing to push notifications:",C),!(C instanceof Error&&C.message.includes("toast"))){const N=C instanceof Error?C.message:"Unknown error";Jt.error("Failed to enable push notifications: "+N)}return!1}finally{c(!1)}},[_,s,t,m]),E=P.useCallback(async()=>{if(!s||!t)return!1;try{c(!0);const C=await s.pushManager.getSubscription();return C&&await C.unsubscribe(),await Le.from("push_subscriptions").delete().eq("user_id",t.id),i(!1),Jt.success("Push notifications disabled"),!0}catch(C){console.error("Error unsubscribing:",C);const N=C instanceof Error?C.message:"Unknown error";return Jt.error("Failed to disable push notifications: "+N),!1}finally{c(!1)}},[s,t]);return{isSupported:_,permission:e,isSubscribed:n,isLoading:a,vapidPublicKey:m,subscribe:T,unsubscribe:E}}const zB="push_notification_prompt_dismissed",tKe=["/dashboard","/admin"],rKe=()=>{const{user:t}=qn(),{isSupported:e,isSubscribed:r,isLoading:n,subscribe:i}=eKe(),a=Wi(),[c,s]=P.useState(!1),[f,m]=P.useState(!1),x=tKe.some(E=>a.pathname===E||a.pathname.startsWith(`${E}/`));P.useEffect(()=>{if(x){s(!1);return}if(!t||!e||r||n||localStorage.getItem(`${zB}_${t.id}`))return;const C=setTimeout(()=>{s(!0)},2e3);return()=>clearTimeout(C)},[t,e,r,n,x]);const _=async()=>{m(!0);const E=await i();m(!1),E&&(t&&localStorage.setItem(`${zB}_${t.id}`,"true"),s(!1))},T=()=>{t&&localStorage.setItem(`${zB}_${t.id}`,"true"),s(!1)};return!e||r||x?null:o.jsx(ro,{open:c,onOpenChange:E=>!E&&T(),children:o.jsxs($a,{className:"sm:max-w-md",children:[o.jsxs(ul,{children:[o.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:o.jsx(EC,{className:"h-6 w-6 text-primary"})}),o.jsx(Go,{className:"text-center",children:"Stay in the Loop!"}),o.jsx(ld,{className:"text-center",children:"Enable push notifications to get alerted when:"})]}),o.jsxs("ul",{className:"my-4 space-y-2 text-sm text-muted-foreground",children:[o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"•"})," New events go live"]}),o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"•"})," Fresh templates are added"]}),o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"•"})," New toolbox resources drop"]}),o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"•"})," Social swag updates"]}),o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"•"})," New newsletters arrive"]}),o.jsxs("li",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-primary",children:"•"})," Posts in your community groups"]})]}),o.jsxs("div",{className:"flex flex-col gap-2",children:[o.jsx(Ut,{onClick:_,disabled:f,className:"w-full",children:f?"Enabling...":"Enable Notifications"}),o.jsx(Ut,{variant:"ghost",onClick:T,className:"w-full",children:"Not Now"})]}),o.jsx("p",{className:"text-center text-xs text-muted-foreground",children:"You can always change this in your Profile settings."})]})})},Nte=t=>{let e;const r=new Set,n=(m,x)=>{const _=typeof m=="function"?m(e):m;if(!Object.is(_,e)){const T=e;e=x??(typeof _!="object"||_===null)?_:Object.assign({},e,_),r.forEach(E=>E(e,T))}},i=()=>e,s={setState:n,getState:i,getInitialState:()=>f,subscribe:m=>(r.add(m),()=>r.delete(m))},f=e=t(n,i,s);return s},nKe=t=>t?Nte(t):Nte,iKe=t=>t;function sKe(t,e=iKe){const r=Xe.useSyncExternalStore(t.subscribe,Xe.useCallback(()=>e(t.getState()),[t,e]),Xe.useCallback(()=>e(t.getInitialState()),[t,e]));return Xe.useDebugValue(r),r}const Rte=t=>{const e=nKe(t),r=n=>sKe(e,n);return Object.assign(r,e),r},aKe=t=>t?Rte(t):Rte;function oKe(t,e){let r;try{r=t()}catch{return}return{getItem:i=>{var a;const c=f=>f===null?null:JSON.parse(f,void 0),s=(a=r.getItem(i))!=null?a:null;return s instanceof Promise?s.then(c):c(s)},setItem:(i,a)=>r.setItem(i,JSON.stringify(a,void 0)),removeItem:i=>r.removeItem(i)}}const L6=t=>e=>{try{const r=t(e);return r instanceof Promise?r:{then(n){return L6(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return L6(n)(r)}}}},lKe=(t,e)=>(r,n,i)=>{let a={storage:oKe(()=>window.localStorage),partialize:R=>R,version:0,merge:(R,D)=>({...D,...R}),...e},c=!1,s=0;const f=new Set,m=new Set;let x=a.storage;if(!x)return t((...R)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),r(...R)},n,i);const _=()=>{const R=a.partialize({...n()});return x.setItem(a.name,{state:R,version:a.version})},T=i.setState;i.setState=(R,D)=>(T(R,D),_());const E=t((...R)=>(r(...R),_()),n,i);i.getInitialState=()=>E;let C;const N=()=>{var R,D;if(!x)return;const M=++s;c=!1,f.forEach(V=>{var G;return V((G=n())!=null?G:E)});const B=((D=a.onRehydrateStorage)==null?void 0:D.call(a,(R=n())!=null?R:E))||void 0;return L6(x.getItem.bind(x))(a.name).then(V=>{if(V)if(typeof V.version=="number"&&V.version!==a.version){if(a.migrate){const G=a.migrate(V.state,V.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,V.state];return[!1,void 0]}).then(V=>{var G;if(M!==s)return;const[W,X]=V;if(C=a.merge(X,(G=n())!=null?G:E),r(C,!0),W)return _()}).then(()=>{M===s&&(B==null||B(n(),void 0),C=n(),c=!0,m.forEach(V=>V(C)))}).catch(V=>{M===s&&(B==null||B(void 0,V))})};return i.persist={setOptions:R=>{a={...a,...R},R.storage&&(x=R.storage)},clearStorage:()=>{x==null||x.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>N(),hasHydrated:()=>c,onHydrate:R=>(f.add(R),()=>{f.delete(R)}),onFinishHydration:R=>(m.add(R),()=>{m.delete(R)})},a.skipHydration||N(),C||E},cKe=lKe,z_e=aKe()(cKe((t,e)=>({cartItems:[],addToCart:(r,n,i=1,a)=>{t(c=>{const s=c.cartItems.findIndex(f=>{var m;return f.product.id===r.id&&((m=f.variant)==null?void 0:m.id)===(n==null?void 0:n.id)});if(s>=0){const f=[...c.cartItems];return f[s].quantity+=i,a&&(f[s].artworkUrl=a),{cartItems:f}}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 s;return c.product.id===r&&((s=c.variant)==null?void 0:s.id)===n?{...c,quantity:Math.max(1,i)}:c})}))},updateArtwork:(r,n,i)=>{t(a=>({cartItems:a.cartItems.map(c=>{var s;return c.product.id===r&&((s=c.variant)==null?void 0:s.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})})),uKe="/admin/beta/boost",dKe=P.lazy(()=>Be(()=>import("./BoostCompanion-8vMfNIQL.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])));function hKe(){const{user:t,isAdmin:e}=qn(),{isFeatureEnabled:r}=jM(),{pathname:n}=Wi();return!!t&&(e||r("boost_mascot"))&&n!==uKe?o.jsx(P.Suspense,{fallback:null,children:o.jsx(dKe,{userId:t.id})}):null}function fKe({activeCategory:t,currentCategory:e,onSelect:r,onHover:n,badgeCounts:i,categories:a=GM}){return o.jsx("nav",{"aria-label":"Primary",className:"flex flex-col gap-1 p-2",children:a.map(c=>{const s=c.icon,f=t===c.id,m=e===c.id,x=(i==null?void 0:i[c.id])??0,_=`hsl(var(--${c.accent}))`,T=f||m;return o.jsxs("button",{type:"button",onClick:()=>r(c.id),onMouseEnter:()=>n==null?void 0:n(c.id),"aria-expanded":c.route?void 0:f,"aria-controls":c.route?void 0:"primary-nav-flyout","aria-current":m?"page":void 0,style:{color:T?_:void 0,backgroundColor:T?`hsl(var(--${c.accent}) / 0.12)`:void 0},className:sr("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:[m&&o.jsx("span",{className:"absolute left-0 top-1/2 h-6 w-1 -translate-y-1/2 rounded-r",style:{backgroundColor:_}}),o.jsxs("span",{className:"relative",children:[o.jsx(s,{className:"h-5 w-5 transition-colors",style:{color:_}}),x>0&&o.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:_},children:x>9?"9+":x})]}),o.jsx("span",{className:"leading-tight",children:c.label})]},c.id)})})}function pKe({category:t,top:e,left:r,onClose:n,onNavigate:i,isFavorite:a,favorites:c,onToggleFavorite:s,isCurrent:f,badgeCounts:m}){const x=P.useRef(null);P.useEffect(()=>{const T=C=>{C.key==="Escape"&&n()},E=C=>{var R;if(!x.current)return;const N=C.target;!x.current.contains(N)&&!((R=N==null?void 0:N.closest)!=null&&R.call(N,"[data-nav-rail]"))&&n()};return document.addEventListener("keydown",T),document.addEventListener("mousedown",E),()=>{document.removeEventListener("keydown",T),document.removeEventListener("mousedown",E)}},[n]);const _=T=>{const E=T.icon,C=T.badgeKey?(m==null?void 0:m[T.badgeKey])??0:0;return o.jsxs("div",{className:sr("group flex items-start gap-3 rounded-lg border border-transparent p-2 transition-colors hover:bg-muted/60",f(T)&&"border-primary/30 bg-primary/5"),children:[o.jsxs("button",{type:"button",onClick:()=>i(T),className:"flex flex-1 items-start gap-3 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md",children:[o.jsx("span",{className:sr("mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",T.iconTone==="red"?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"),children:o.jsx(E,{className:sr("h-4 w-4",T.iconTone==="red"&&"fill-destructive/20")})}),o.jsxs("span",{className:"min-w-0",children:[o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:"text-sm font-medium text-foreground",children:T.label}),T.badge==="new"&&o.jsx("span",{className:"rounded bg-primary px-1 py-px text-[9px] font-bold uppercase tracking-wide text-primary-foreground",children:"New"}),T.badge==="beta"&&o.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"}),T.locked&&o.jsx(zy,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),C>0&&o.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:C>9?"9+":C})]}),T.description&&o.jsx("span",{className:"mt-0.5 block text-xs leading-snug text-muted-foreground line-clamp-2",children:T.description})]})]}),o.jsx("button",{type:"button","aria-label":a(T)?`Remove ${T.label} from favorites`:`Add ${T.label} to favorites`,onClick:N=>{N.stopPropagation(),s(T)},className:sr("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(T)&&"opacity-100 text-primary",!a(T)&&"text-muted-foreground/60 hover:text-primary"),children:o.jsx(kL,{className:sr("h-4 w-4",a(T)&&"fill-current")})})]},T.id)};return o.jsxs("div",{id:"primary-nav-flyout",ref:x,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:[o.jsx("div",{className:"flex items-center justify-between border-b border-border px-5 py-3",children:o.jsx("h2",{className:"text-sm font-semibold text-foreground",children:t.label})}),o.jsxs("div",{className:"max-h-[70vh] overflow-y-auto p-4",children:[c.length>0&&o.jsxs("section",{className:"mb-4",children:[o.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[o.jsx(kL,{className:"h-3 w-3 fill-current text-primary"})," My Favorites"]}),o.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:c.map(_)})]}),t.sections.map(T=>o.jsxs("section",{className:"mb-4 last:mb-0",children:[o.jsx("h3",{className:"mb-2 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:T.title}),o.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:T.items.map(_)})]},T.title)),t.sections.length===0&&o.jsx("p",{className:"px-2 py-6 text-sm text-muted-foreground",children:"Nothing here yet."})]})]})}function mKe({categories:t,railCategories:e=GM,currentCategory:r,onNavigate:n,onNavigateRoute:i,isCurrent:a,badgeCounts:c,isFavorite:s,onToggleFavorite:f}){const[m,x]=P.useState(r);return o.jsx("nav",{"aria-label":"Primary",className:"p-2",children:e.map(_=>{const T=_.icon;if(_.route)return o.jsxs("button",{type:"button",onClick:()=>i(_.route),className:sr("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===_.id&&"bg-sidebar-accent"),children:[o.jsx(T,{className:"h-4 w-4",style:{color:`hsl(var(--${_.accent}))`}}),_.label]},_.id);const E=t.find(N=>N.id===_.id),C=m===_.id;return o.jsxs("div",{children:[o.jsxs("button",{type:"button","aria-expanded":C,onClick:()=>x(C?null:_.id),className:sr("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===_.id&&"text-primary"),children:[o.jsx(T,{className:"h-4 w-4",style:{color:`hsl(var(--${_.accent}))`}}),_.label,o.jsx(od,{className:sr("ml-auto h-4 w-4 transition-transform",C&&"rotate-180")})]}),C&&E&&o.jsx("div",{className:"space-y-3 pb-3 pl-4 pr-1",children:E.sections.map(N=>o.jsxs("div",{children:[o.jsx("p",{className:"px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:N.title}),N.items.map(R=>{const D=R.icon,M=R.badgeKey?(c==null?void 0:c[R.badgeKey])??0:0,B=(s==null?void 0:s(R))??!1;return o.jsxs("div",{className:sr("flex w-full items-center gap-2 rounded-md pr-1 hover:bg-sidebar-accent",a(R)&&"bg-sidebar-accent"),children:[o.jsxs("button",{type:"button",onClick:()=>n(R),className:"flex flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-sidebar-foreground",children:[o.jsx(D,{className:sr("h-4 w-4 shrink-0",R.iconTone==="red"&&"text-destructive")}),o.jsx("span",{className:"truncate",children:R.label}),M>0&&o.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-xs text-muted-foreground",children:M>9?"9+":M})]}),f&&o.jsx("button",{type:"button","aria-label":B?`Remove ${R.label} from favorites`:`Add ${R.label} to favorites`,onClick:()=>f(R),className:sr("rounded p-2",B?"text-primary":"text-muted-foreground/60"),children:o.jsx(kL,{className:sr("h-4 w-4",B&&"fill-current")})})]},R.id)})]},N.title))})]},_.id)})})}function $_e(){const t=ma(),e=Wi(),r=l_e(),n=P.useCallback(s=>o_e(s,r.ctx),[r.ctx]),i=P.useMemo(()=>{if(e.pathname.startsWith("/apps"))return"apps";if(e.pathname==="/dashboard")return"home";let s=null;for(const f of r.destinations){if(f.external)continue;const m=n(f);m!=="/"&&e.pathname.startsWith(m)&&(!s||m.length>s.len)&&(s={id:f.primaryCategory,len:m.length})}return(s==null?void 0:s.id)??null},[e.pathname,r.destinations,n]),a=P.useCallback(s=>!s.external&&e.pathname===n(s),[e.pathname,n]),c=P.useCallback(s=>{const f=n(s);if(s.external||s.openInNewTab){window.open(f,"_blank","noopener,noreferrer");return}t(f)},[t,n]);return{nav:r,navigate:t,currentCategory:i,isCurrent:a,go:c}}function gKe({communityUnreadCount:t=0,wishlistOpenCount:e=0,flyoutTop:r=64,flyoutLeft:n=80}){const{nav:i,navigate:a,currentCategory:c,isCurrent:s,go:f}=$_e(),[m,x]=P.useState(null),_=P.useRef(null),T=N=>{const R=GM.find(D=>D.id===N);if(R!=null&&R.route){x(null),a(R.route);return}x(D=>D===N?null:N)},E=m?i.categoryMap.get(m):void 0,C={more:t+e};return o.jsxs("div",{"data-nav-rail":!0,className:"flex h-full flex-col",onMouseLeave:()=>{_.current&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>x(null),250)},onMouseEnter:()=>{_.current&&window.clearTimeout(_.current)},children:[o.jsx(fKe,{activeCategory:m,currentCategory:c,onSelect:T,categories:i.railCategories,badgeCounts:C}),E&&o.jsx(pKe,{category:E,top:r,left:n,onClose:()=>x(null),onNavigate:N=>{x(null),f(N)},isFavorite:i.isFavorite,favorites:i.favoritesFor(E.id),onToggleFavorite:N=>i.toggleFavorite(i.favoriteKey(N)),isCurrent:s,badgeCounts:{community:t,wishlist:e}})]})}function yKe({communityUnreadCount:t=0,wishlistOpenCount:e=0,onNavigated:r}){const{nav:n,navigate:i,currentCategory:a,isCurrent:c,go:s}=$_e();return o.jsx(mKe,{categories:n.categories,railCategories:n.railCategories,currentCategory:a,isCurrent:c,isFavorite:n.isFavorite,onToggleFavorite:f=>n.toggleFavorite(n.favoriteKey(f)),badgeCounts:{community:t,wishlist:e},onNavigate:f=>{s(f),r==null||r()},onNavigateRoute:f=>{i(f),r==null||r()}})}const xKe=({bannerHeight:t,communityUnreadCount:e,wishlistOpenCount:r,isTrial:n,isExpired:i})=>{const a=ma();return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsx("div",{className:"flex h-16 shrink-0 items-center justify-center border-b border-sidebar-border",children:o.jsx("button",{type:"button",onClick:()=>a("/dashboard"),"aria-label":"LevelUp home",children:o.jsx("img",{src:IUe,alt:"LevelUp",className:"h-8 w-auto"})})}),o.jsxs(pp,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[o.jsx(gKe,{communityUnreadCount:e,wishlistOpenCount:r,flyoutTop:t+64,flyoutLeft:80}),n&&!i&&o.jsx("div",{className:"p-2",children:o.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:[o.jsx(Ss,{className:"h-4 w-4"}),"Upgrade"]})})]})]})},_Ke=({isTrial:t,isExpired:e,expiresAt:r,communityUnreadCount:n,wishlistOpenCount:i,pathname:a,onSignOut:c,onNavigated:s})=>{const f=ma();return o.jsxs("div",{className:"flex h-full flex-col",children:[o.jsx("div",{className:"flex items-center gap-2 border-b border-sidebar-border p-3",children:o.jsx("img",{src:jUe,alt:"LevelUp",className:"h-8 w-auto"})}),o.jsxs(pp,{className:"flex-1",children:[t&&!e&&o.jsx("div",{className:"p-2",children:o.jsx("button",{type:"button",onClick:()=>{f("/subscription"),s==null||s()},className:sr("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:o.jsxs("span",{className:"flex items-center gap-2 rounded-[5px] bg-sidebar px-3 py-2 text-sm font-semibold text-sidebar-foreground",children:[o.jsx(Ss,{className:"h-4 w-4 text-amber-500"}),o.jsx("span",{className:"flex-1 text-left",children:"Ready to Upgrade?"}),r&&o.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"]})]})})}),o.jsx(yKe,{communityUnreadCount:n,wishlistOpenCount:i,onNavigated:s})]}),o.jsxs("div",{className:"border-t border-sidebar-border p-3",children:[o.jsxs(Ut,{variant:"ghost",size:"sm",className:sr("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:()=>{f("/profile"),s==null||s()},children:[o.jsx(gc,{className:"h-4 w-4"}),"Profile"]}),o.jsxs(Ut,{variant:"ghost",size:"sm",className:sr("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:()=>{f("/credits"),s==null||s()},children:[o.jsx(xG,{className:"h-4 w-4"}),"Credits & Wallet"]}),o.jsxs(Ut,{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:[o.jsx(YO,{className:"h-4 w-4"}),"Sign Out"]})]})]})},E1=({children:t,title:e})=>{var at;const{user:r,signOut:n,isAdmin:i,isBrokerageManager:a,isCoach:c,brokerageId:s}=qn(),{isAssistant:f,actingAsAgent:m,hasPermission:x}=EM();u9();const{isImpersonating:_}=Dme(),E=(f&&!!m?40:0)+(_?40:0),{avatarUrl:C}=oUe(r==null?void 0:r.id),{isTrial:N,isExpired:R,expiresAt:D}=lUe(r==null?void 0:r.id),{isInnerCircleEnabled:M,isMarketplaceEnabled:B}=jM(),{currentBrief:V,shouldShowPopup:G,hasUnseenBrief:W,openBrief:X,closeBrief:Q,dismissBrief:re}=WWe(),{unreadCount:se}=cUe(),{openCount:ue}=uUe();SS();const Se=z_e(Et=>Et.cartItems).reduce((Et,_t)=>Et+_t.quantity,0),{leadSite:ve,hasLeadSite:Oe,siteUrl:Ae}=s_e();a_e(!Oe);const we=ma(),ge=Wi(),[Ne,Ie]=P.useState(null);P.useEffect(()=>{r!=null&&r.id&&Le.from("profiles").select("name").eq("id",r.id).single().then(({data:Et})=>{Et!=null&&Et.name&&Ie(Et.name)})},[r==null?void 0:r.id]);const Te=Ne||((at=r==null?void 0:r.user_metadata)==null?void 0:at.name)||(r==null?void 0:r.email)||"User",[be,We]=P.useState(!1),rt=Et=>Et.split(" ").map(_t=>_t[0]).join("").toUpperCase().slice(0,2);return o.jsx(jpe,{children:o.jsxs("div",{className:"min-h-screen bg-background flex",children:[N&&R&&ge.pathname!=="/subscription"&&o.jsx(IWe,{}),typeof document<"u"&&zm.createPortal(o.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:`${E}px`,height:`calc(100vh - ${E}px)`},children:o.jsx(xKe,{bannerHeight:E,communityUnreadCount:se,wishlistOpenCount:ue,isTrial:N,isExpired:R})}),document.body),o.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden md:ml-20",style:{height:`calc(100vh - ${E}px)`,marginTop:`${E}px`},children:[o.jsx("header",{className:"sticky top-0 z-40 bg-card border-b border-border flex-shrink-0",children:o.jsxs("div",{className:"flex items-center justify-between px-6 py-3",children:[o.jsxs(Xge,{open:be,onOpenChange:We,children:[o.jsx(hUe,{asChild:!0,children:o.jsx(Ut,{variant:"ghost",size:"icon",className:"md:hidden",children:o.jsx(ZO,{className:"h-5 w-5"})})}),o.jsx(d9,{side:"left",className:"w-72 p-0 bg-card",children:o.jsx(_Ke,{isTrial:N,isExpired:R,expiresAt:D,communityUnreadCount:se,wishlistOpenCount:ue,pathname:ge.pathname,onSignOut:n,onNavigated:()=>We(!1)})})]}),o.jsx("div",{className:"flex-1 md:hidden",children:o.jsx("img",{src:PUe,alt:"LevelUp",className:"h-8 w-auto"})}),o.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:o.jsx(Pte,{})}),o.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[N&&!R&&D&&o.jsx(jWe,{expiresAt:D,className:"hidden lg:flex"}),o.jsx("div",{className:"md:hidden",children:o.jsx(Pte,{})}),V&&o.jsx(PWe,{hasUnseenBrief:W,onClick:X}),B&&o.jsxs(Ut,{variant:"ghost",size:"icon",className:"relative",onClick:()=>we("/marketplace/cart"),children:[o.jsx(Zhe,{className:"h-5 w-5"}),Se>0&&o.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:Se>99?"99+":Se})]}),o.jsx(Ut,{variant:"ghost",size:"icon","aria-label":"My Calendar",title:"My Calendar",onClick:()=>we("/mission-control/calendar"),children:o.jsx(Zf,{className:"h-5 w-5"})}),o.jsx(ZHe,{}),o.jsx(b9e,{}),o.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",Te.split(" ")[0],"!"]}),o.jsxs(UC,{children:[o.jsx(VC,{asChild:!0,children:o.jsx("button",{className:"focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-full",children:o.jsxs(Zd,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[o.jsx(Xd,{src:C||void 0}),o.jsx(Qd,{className:"bg-primary text-primary-foreground font-medium text-sm",children:rt(Te)})]})})}),o.jsxs(wS,{align:"end",className:"w-48",children:[o.jsxs(vu,{onClick:()=>we("/profile"),className:"cursor-pointer",children:[o.jsx(gc,{className:"h-4 w-4 mr-2"}),"Profile"]}),o.jsxs(vu,{onClick:()=>we("/credits"),className:"cursor-pointer",children:[o.jsx(xG,{className:"h-4 w-4 mr-2"}),"Credits & Wallet"]}),o.jsxs(vu,{onClick:()=>we("/mission-control/integrations"),className:"cursor-pointer",children:[o.jsx(CL,{className:"h-4 w-4 mr-2"}),"Integrations"]}),o.jsxs(vu,{onClick:()=>we("/mission-control/browser-extension"),className:"cursor-pointer",children:[o.jsx(CL,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),o.jsx(uk,{}),o.jsxs(vu,{onClick:n,className:"cursor-pointer text-destructive focus:text-destructive",children:[o.jsx(YO,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),o.jsx(YWe,{children:o.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:t})}),V&&o.jsx(HWe,{brief:V,open:G,onClose:Q,onDismiss:re}),o.jsx(KWe,{}),o.jsx(QWe,{}),o.jsx(rKe,{}),o.jsx(hKe,{})]})]})})},ut=({children:t,requireAdmin:e=!1,requireBrokerageManager:r=!1})=>{const{user:n,loading:i,rolesLoading:a,isAdmin:c,isBrokerageManager:s}=qn(),f=Wi(),m=Wge();if(i||(e||r)&&a)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),o.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})});if(!n){const x=f.pathname+f.search+f.hash;return x&&x!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",x),o.jsx(ki,{to:"/auth",replace:!0})}if(e&&!c)return o.jsx(ki,{to:"/dashboard",replace:!0});if(r&&!s&&!c)return o.jsx(ki,{to:"/dashboard",replace:!0});if(m.isRestricted&&!m.isLoading){const x=nUe(f.pathname);if(x&&!m.hasFeature(x))return o.jsx(E1,{title:"Upgrade required",children:o.jsx(aUe,{featureKey:x})})}return o.jsx(o.Fragment,{children:t})};function $B({children:t}){const{isAdmin:e,loading:r,rolesLoading:n}=qn(),{isFeatureEnabled:i,isLoading:a}=jM();return r||n||a?o.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):!e&&!i("staging_studio_enabled")?o.jsx(ki,{to:"/apps",replace:!0}):o.jsx(E1,{title:"Staging Studio",children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:t})})}var Z9={};(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",s=function(){if(!e.OffscreenCanvas)return!1;try{var Ie=new OffscreenCanvas(1,1),Te=Ie.getContext("2d");Te.fillRect(0,0,1,1);var be=Ie.transferToImageBitmap();Te.createPattern(be,"no-repeat")}catch{return!1}return!0}();function f(){}function m(Ie){var Te=r.exports.Promise,be=Te!==void 0?Te:e.Promise;return typeof be=="function"?new be(Ie):(Ie(f,f),null)}var x=function(Ie,Te){return{transform:function(be){if(Ie)return be;if(Te.has(be))return Te.get(be);var We=new OffscreenCanvas(be.width,be.height),rt=We.getContext("2d");return rt.drawImage(be,0,0),Te.set(be,We),We},clear:function(){Te.clear()}}}(s,new Map),_=function(){var Ie=Math.floor(16.666666666666668),Te,be,We={},rt=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(Te=function(at){var Et=Math.random();return We[Et]=requestAnimationFrame(function _t(Vt){rt===Vt||rt+Ie-1{const{data:e,error:r}=await Le.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 bKe(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["celebrations"]})}})}function e6t(){const t=Nr(),{user:e}=qn();return Cr({mutationFn:async r=>{const{error:n}=await Le.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 wKe={points_earned:PL,listing_created:Ma,deal_closed:ym,custom:Xc},Dte={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"},Ote=()=>{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 SKe(){const{user:t}=qn(),e=Nr(),{data:r}=vKe(),n=bKe(),[i,a]=P.useState(null),[c,s]=P.useState(!1),f=P.useCallback(()=>{const E=Date.now()+3e3,C={startVelocity:30,spread:360,ticks:60,zIndex:9999},N=(D,M)=>Math.random()*(M-D)+D,R=setInterval(()=>{const D=E-Date.now();if(D<=0){clearInterval(R);return}const M=50*(D/3e3);Lte({...C,particleCount:M,origin:{x:N(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),Lte({...C,particleCount:M,origin:{x:N(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);P.useEffect(()=>{Ote()||r&&r.length>0&&!i&&(a(r[0]),s(!0),setTimeout(f,100))},[r,i,f]);const m=async()=>{if(i){const T=i.id;s(!1),a(null),e.setQueryData(["celebrations","pending",t==null?void 0:t.id],E=>(E==null?void 0:E.filter(C=>C.id!==T))??[]),await n.mutateAsync(T)}};if(Ote()||!i)return null;const x=wKe[i.celebration_type]||Xc,_=Dte[i.celebration_type]||Dte.custom;return o.jsx(ro,{open:c,onOpenChange:T=>!T&&m(),children:o.jsxs($a,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[o.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${_} opacity-10`}),o.jsxs("div",{className:"relative z-10 py-6",children:[o.jsx("div",{className:"flex justify-center mb-4",children:o.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${_} flex items-center justify-center animate-bounce`,children:o.jsx(x,{className:"w-10 h-10 text-white"})})}),o.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[o.jsx(Ss,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),o.jsx(Ss,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),o.jsx(Ss,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),o.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&&o.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",i.points_amount," points!"]}),i.message&&o.jsx("p",{className:"text-muted-foreground mb-6",children:i.message}),o.jsx(Ut,{onClick:m,className:"w-full",size:"lg",children:"Awesome! 🙌"}),r&&r.length>1&&o.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",r.length-1," more celebration",r.length>2?"s":""," waiting"]})]})]})})}function ol({className:t,...e}){return o.jsx("div",{className:sr("animate-pulse rounded-md bg-muted",t),...e})}var YM="Tabs",[TKe,t6t]=Ho(YM,[bS]),U_e=bS(),[EKe,X9]=TKe(YM),V_e=P.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,onValueChange:i,defaultValue:a,orientation:c="horizontal",dir:s,activationMode:f="automatic",...m}=t,x=$0(s),[_,T]=ad({prop:n,onChange:i,defaultProp:a??"",caller:YM});return o.jsx(EKe,{scope:r,baseId:Cl(),value:_,onValueChange:T,orientation:c,dir:x,activationMode:f,children:o.jsx(rn.div,{dir:x,"data-orientation":c,...m,ref:e})})});V_e.displayName=YM;var q_e="TabsList",G_e=P.forwardRef((t,e)=>{const{__scopeTabs:r,loop:n=!0,...i}=t,a=X9(q_e,r),c=U_e(r);return o.jsx(e9,{asChild:!0,...c,orientation:a.orientation,dir:a.dir,loop:n,children:o.jsx(rn.div,{role:"tablist","aria-orientation":a.orientation,...i,ref:e})})});G_e.displayName=q_e;var H_e="TabsTrigger",W_e=P.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,disabled:i=!1,...a}=t,c=X9(H_e,r),s=U_e(r),f=Z_e(c.baseId,n),m=X_e(c.baseId,n),x=n===c.value;return o.jsx(t9,{asChild:!0,...s,focusable:!i,active:x,children:o.jsx(rn.button,{type:"button",role:"tab","aria-selected":x,"aria-controls":m,"data-state":x?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:f,...a,ref:e,onMouseDown:Or(t.onMouseDown,_=>{!i&&_.button===0&&_.ctrlKey===!1?c.onValueChange(n):_.preventDefault()}),onKeyDown:Or(t.onKeyDown,_=>{[" ","Enter"].includes(_.key)&&c.onValueChange(n)}),onFocus:Or(t.onFocus,()=>{const _=c.activationMode!=="manual";!x&&!i&&_&&c.onValueChange(n)})})})});W_e.displayName=H_e;var K_e="TabsContent",Y_e=P.forwardRef((t,e)=>{const{__scopeTabs:r,value:n,forceMount:i,children:a,...c}=t,s=X9(K_e,r),f=Z_e(s.baseId,n),m=X_e(s.baseId,n),x=n===s.value,_=P.useRef(x);return P.useEffect(()=>{const T=requestAnimationFrame(()=>_.current=!1);return()=>cancelAnimationFrame(T)},[]),o.jsx(dl,{present:i||x,children:({present:T})=>o.jsx(rn.div,{"data-state":x?"active":"inactive","data-orientation":s.orientation,role:"tabpanel","aria-labelledby":f,hidden:!T,id:m,tabIndex:0,...c,ref:e,style:{...t.style,animationDuration:_.current?"0s":void 0},children:T&&a})})});Y_e.displayName=K_e;function Z_e(t,e){return`${t}-trigger-${e}`}function X_e(t,e){return`${t}-content-${e}`}var AKe=V_e,Q_e=G_e,J_e=W_e,e0e=Y_e;const Q9=AKe,ZM=P.forwardRef(({className:t,...e},r)=>o.jsx(Q_e,{ref:r,className:sr("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...e}));ZM.displayName=Q_e.displayName;const _m=P.forwardRef(({className:t,...e},r)=>o.jsx(J_e,{ref:r,className:sr("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}));_m.displayName=J_e.displayName;const Ny=P.forwardRef(({className:t,...e},r)=>o.jsx(e0e,{ref:r,className:sr("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...e}));Ny.displayName=e0e.displayName;const _k="#0d0d0d",oD="#1a1a1a",Gl="#c9a84c",XC="#f0d78c",ip={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function XM(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 Le.functions.invoke("public-site-lead",{body:e});if(n)throw n;try{localStorage.setItem(ip.captured,JSON.stringify({email:t.email,ts:Date.now()}))}catch{}return r}function J9(){try{return!!localStorage.getItem(ip.captured)}catch{return!1}}function kKe(){try{const t=localStorage.getItem(ip.captured);return t?JSON.parse(t).email??null:null}catch{return null}}function e7({open:t,onClose:e,children:r}){return P.useEffect(()=>{if(!t)return;const n=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=n}},[t]),t?zm.createPortal(o.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:o.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, ${oD} 0%, ${_k} 100%)`,border:`1px solid ${Gl}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${Gl}22 inset`},children:[o.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:o.jsx(Ks,{className:"h-4 w-4"})}),r]})}),document.body):null}function t7(){const[t,e]=P.useState({first_name:"",email:"",phone:"",area:""}),[r,n]=P.useState(!1),[i,a]=P.useState("");return{values:t,setValues:e,loading:r,setLoading:n,honeypot:i,setHoneypot:a}}function r7({values:t,setValues:e,honeypot:r,setHoneypot:n,showPhone:i=!0,showArea:a=!0,areaPlaceholder:c="City, ZIP, or neighborhood"}){const s="w-full rounded-lg px-11 py-3 text-sm text-white placeholder:text-white/40 border transition focus:outline-none",f={background:"rgba(255,255,255,0.04)",borderColor:"rgba(255,255,255,0.12)"};return o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"relative",children:[o.jsx(gc,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),o.jsx("input",{type:"text",placeholder:"First name",value:t.first_name,onChange:m=>e({...t,first_name:m.target.value}),className:s,style:f})]}),o.jsxs("div",{className:"relative",children:[o.jsx(Bi,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),o.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:t.email,onChange:m=>e({...t,email:m.target.value}),className:s,style:f})]}),i&&o.jsxs("div",{className:"relative",children:[o.jsx(zi,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),o.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:t.phone,onChange:m=>e({...t,phone:m.target.value}),className:s,style:f})]}),a&&o.jsxs("div",{className:"relative",children:[o.jsx(na,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),o.jsx("input",{type:"text",placeholder:c,value:t.area,onChange:m=>e({...t,area:m.target.value}),className:s,style:f})]}),o.jsx("input",{type:"text",value:r,onChange:m=>n(m.target.value),tabIndex:-1,autoComplete:"off",className:"absolute -left-[9999px] w-0 h-0 opacity-0","aria-hidden":"true"})]})}function n7({children:t,disabled:e,onClick:r,type:n="button"}){return o.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, ${XC} 0%, ${Gl} 100%)`,color:_k,boxShadow:`0 8px 24px ${Gl}55`},children:t})}function Mte({open:t,onClose:e,initialCriteria:r}){const{values:n,setValues:i,loading:a,setLoading:c,honeypot:s,setHoneypot:f}=t7(),[m,x]=P.useState(!1),_=async T=>{if(T.preventDefault(),!!n.email){c(!0);try{await XM({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()}:{}}}),x(!0);try{localStorage.setItem(ip.stickyDismissed,"1")}catch{}setTimeout(e,2200)}catch{Jt.error("Something went wrong. Please try again.")}finally{c(!1)}}};return o.jsx(e7,{open:t,onClose:e,children:o.jsxs("div",{className:"p-8",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[o.jsx(EC,{className:"h-4 w-4",style:{color:Gl}}),o.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:XC},children:"New Listing Alerts"})]}),o.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"Be the first to know."}),o.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."}),m?o.jsxs("div",{className:"py-6 text-center",children:[o.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full flex items-center justify-center",style:{background:`${Gl}22`,border:`1px solid ${Gl}55`},children:o.jsx(Ss,{className:"h-5 w-5",style:{color:Gl}})}),o.jsx("div",{className:"text-white font-medium",children:"You're on the list."}),o.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Check your inbox for confirmation."})]}):o.jsxs("form",{onSubmit:_,className:"space-y-4",children:[o.jsx(r7,{values:n,setValues:i,honeypot:s,setHoneypot:f}),o.jsx(n7,{type:"submit",disabled:a||!n.email,children:a?"Activating…":"Activate Alerts"}),o.jsx("p",{className:"text-[10px] text-white/40 text-center leading-relaxed",children:"We respect your inbox. Unsubscribe any time."})]})]})})}function CKe(){const[t,e]=P.useState(!0),[r,n]=P.useState(!1);P.useEffect(()=>{try{const a=!!localStorage.getItem(ip.stickyDismissed)||J9();e(a)}catch{e(!1)}},[]);const i=()=>{e(!0);try{localStorage.setItem(ip.stickyDismissed,"1")}catch{}};return t?o.jsx(Mte,{open:r,onClose:()=>n(!1)}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-40 animate-in slide-in-from-bottom",style:{background:`linear-gradient(180deg, ${oD} 0%, ${_k} 100%)`,borderTop:`1px solid ${Gl}44`,boxShadow:"0 -8px 30px rgba(0,0,0,0.5)"},children:o.jsxs("div",{className:"max-w-6xl mx-auto px-4 sm:px-6 py-3 flex items-center gap-3",children:[o.jsx("div",{className:"hidden sm:flex h-9 w-9 rounded-full items-center justify-center flex-shrink-0",style:{background:`${Gl}22`,border:`1px solid ${Gl}55`},children:o.jsx(EC,{className:"h-4 w-4",style:{color:Gl}})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:"text-white text-sm font-medium truncate",children:"Be the first to know when new homes hit the market"}),o.jsx("div",{className:"text-white/50 text-xs hidden sm:block",children:"Instant alerts. No spam. Unsubscribe anytime."})]}),o.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, ${XC} 0%, ${Gl} 100%)`,color:_k},children:"Get Alerts"}),o.jsx("button",{onClick:i,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:o.jsx(Ks,{className:"h-4 w-4"})})]})}),o.jsx(Mte,{open:r,onClose:()=>n(!1)})]})}function jKe(){const[t,e]=P.useState(!1),r=P.useRef(!1);P.useEffect(()=>{try{if(sessionStorage.getItem(ip.exitShown)||J9())return}catch{}const T=setTimeout(()=>{r.current=!0},8e3),E=C=>{if(r.current&&!(C.clientY>0)){e(!0);try{sessionStorage.setItem(ip.exitShown,"1")}catch{}window.removeEventListener("mouseleave",E),document.removeEventListener("mouseleave",E)}};return document.addEventListener("mouseleave",E),()=>{clearTimeout(T),document.removeEventListener("mouseleave",E)}},[]);const{values:n,setValues:i,loading:a,setLoading:c,honeypot:s,setHoneypot:f}=t7(),[m,x]=P.useState(!1),_=async T=>{if(T.preventDefault(),!!n.email){c(!0);try{await XM({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}),x(!0),setTimeout(()=>e(!1),2200)}catch{Jt.error("Something went wrong. Please try again.")}finally{c(!1)}}};return o.jsx(e7,{open:t,onClose:()=>e(!1),children:o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"h-32 w-full",style:{background:`linear-gradient(135deg, ${_k} 0%, ${oD} 60%, ${Gl} 130%)`},children:o.jsx("div",{className:"absolute top-4 left-6",children:o.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:XC},children:"Before You Go"})})}),o.jsxs("div",{className:"p-8 -mt-10",children:[o.jsx("div",{className:"mx-auto mb-5 h-16 w-16 rounded-full flex items-center justify-center",style:{background:oD,border:`1px solid ${Gl}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:o.jsx(Ss,{className:"h-6 w-6",style:{color:Gl}})}),o.jsx("h2",{className:"text-2xl font-serif text-white text-center leading-tight mb-2",children:"Wait — get a fresh list of homes."}),o.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."}),m?o.jsxs("div",{className:"py-4 text-center",children:[o.jsx("div",{className:"text-white font-medium",children:"Sent — check your inbox."}),o.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Your list is on its way."})]}):o.jsxs("form",{onSubmit:_,className:"space-y-4",children:[o.jsx(r7,{values:n,setValues:i,honeypot:s,setHoneypot:f,showPhone:!1}),o.jsx(n7,{type:"submit",disabled:a||!n.email,children:a?"Sending…":"Send My List"})]})]})]})})}function IKe(){const[t,e]=P.useState([]);P.useEffect(()=>{try{const s=localStorage.getItem(ip.savedListings);s&&e(JSON.parse(s))}catch{}},[]);const r=s=>{e(s);try{localStorage.setItem(ip.savedListings,JSON.stringify(s))}catch{}},n=P.useCallback(s=>t.includes(s),[t]),i=s=>{t.includes(s)||r([...t,s])},a=s=>r(t.filter(f=>f!==s));return{ids:t,has:n,add:i,remove:a,toggle:s=>t.includes(s)?a(s):i(s)}}function PKe({listingId:t,listingAddress:e,className:r}){const{has:n,add:i,remove:a}=IKe(),c=n(t),[s,f]=P.useState(!1),m=()=>{if(c){a(t);return}if(J9()){i(t),Jt.success("Saved to your favorites"),XM({lead_type:"saved_listing",email:kKe()||"unknown@local",listing_id:t,listing_address:e}).catch(()=>{});return}f(!0)};return o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:m,className:r,"aria-label":c?"Remove from favorites":"Save to favorites",children:o.jsx(tp,{className:`h-5 w-5 ${c?"fill-current":""}`})}),o.jsx(NKe,{open:s,onClose:()=>f(!1),listingId:t,listingAddress:e,onSaved:()=>i(t)})]})}function NKe({open:t,onClose:e,listingId:r,listingAddress:n,onSaved:i}){const{values:a,setValues:c,loading:s,setLoading:f,honeypot:m,setHoneypot:x}=t7(),_=async T=>{if(T.preventDefault(),!!a.email){f(!0);try{await XM({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(),Jt.success("Saved to your favorites"),e()}catch{Jt.error("Something went wrong. Please try again.")}finally{f(!1)}}};return o.jsx(e7,{open:t,onClose:e,children:o.jsxs("div",{className:"p-8",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[o.jsx(tp,{className:"h-4 w-4",style:{color:Gl}}),o.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:XC},children:"Save This Home"})]}),o.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"One click to save."}),o.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."}),o.jsxs("form",{onSubmit:_,className:"space-y-4",children:[o.jsx(r7,{values:a,setValues:c,honeypot:m,setHoneypot:x}),o.jsx(n7,{type:"submit",disabled:s||!a.email,children:s?"Saving…":"Save Home"})]})]})})}var t0e=["PageUp","PageDown"],r0e=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],n0e={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},AS="Slider",[D6,RKe,LKe]=wC(AS),[i0e,r6t]=Ho(AS,[LKe]),[DKe,QM]=i0e(AS),s0e=P.forwardRef((t,e)=>{const{name:r,min:n=0,max:i=100,step:a=1,orientation:c="horizontal",disabled:s=!1,minStepsBetweenThumbs:f=0,defaultValue:m=[n],value:x,onValueChange:_=()=>{},onValueCommit:T=()=>{},inverted:E=!1,form:C,...N}=t,R=P.useRef(new Set),D=P.useRef(0),B=c==="horizontal"?OKe:MKe,[V=[],G]=ad({prop:x,defaultProp:m,onChange:ue=>{var Se;(Se=[...R.current][D.current])==null||Se.focus(),_(ue)}}),W=P.useRef(V);function X(ue){const _e=UKe(V,ue);se(ue,_e)}function Q(ue){se(ue,D.current)}function re(){const ue=W.current[D.current];V[D.current]!==ue&&T(V)}function se(ue,_e,{commit:Se}={commit:!1}){const ve=HKe(a),Oe=WKe(Math.round((ue-n)/a)*a+n,ve),Ae=hk(Oe,[n,i]);G((we=[])=>{const ge=zKe(we,Ae,_e);if(GKe(ge,f*a)){D.current=ge.indexOf(Ae);const Ne=String(ge)!==String(we);return Ne&&Se&&T(ge),Ne?ge:we}else return we})}return o.jsx(DKe,{scope:t.__scopeSlider,name:r,disabled:s,min:n,max:i,valueIndexToChangeRef:D,thumbs:R.current,values:V,orientation:c,form:C,children:o.jsx(D6.Provider,{scope:t.__scopeSlider,children:o.jsx(D6.Slot,{scope:t.__scopeSlider,children:o.jsx(B,{"aria-disabled":s,"data-disabled":s?"":void 0,...N,ref:e,onPointerDown:Or(N.onPointerDown,()=>{s||(W.current=V)}),min:n,max:i,inverted:E,onSlideStart:s?void 0:X,onSlideMove:s?void 0:Q,onSlideEnd:s?void 0:re,onHomeKeyDown:()=>!s&&se(n,0,{commit:!0}),onEndKeyDown:()=>!s&&se(i,V.length-1,{commit:!0}),onStepKeyDown:({event:ue,direction:_e})=>{if(!s){const Oe=t0e.includes(ue.key)||ue.shiftKey&&r0e.includes(ue.key)?10:1,Ae=D.current,we=V[Ae],ge=a*Oe*_e;se(we+ge,Ae,{commit:!0})}}})})})})});s0e.displayName=AS;var[a0e,o0e]=i0e(AS,{startEdge:"left",endEdge:"right",size:"width",direction:1}),OKe=P.forwardRef((t,e)=>{const{min:r,max:n,dir:i,inverted:a,onSlideStart:c,onSlideMove:s,onSlideEnd:f,onStepKeyDown:m,...x}=t,[_,T]=P.useState(null),E=Wn(e,B=>T(B)),C=P.useRef(void 0),N=$0(i),R=N==="ltr",D=R&&!a||!R&&a;function M(B){const V=C.current||_.getBoundingClientRect(),G=[0,V.width],X=i7(G,D?[r,n]:[n,r]);return C.current=V,X(B-V.left)}return o.jsx(a0e,{scope:t.__scopeSlider,startEdge:D?"left":"right",endEdge:D?"right":"left",direction:D?1:-1,size:"width",children:o.jsx(l0e,{dir:N,"data-orientation":"horizontal",...x,ref:E,style:{...x.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:B=>{const V=M(B.clientX);c==null||c(V)},onSlideMove:B=>{const V=M(B.clientX);s==null||s(V)},onSlideEnd:()=>{C.current=void 0,f==null||f()},onStepKeyDown:B=>{const G=n0e[D?"from-left":"from-right"].includes(B.key);m==null||m({event:B,direction:G?-1:1})}})})}),MKe=P.forwardRef((t,e)=>{const{min:r,max:n,inverted:i,onSlideStart:a,onSlideMove:c,onSlideEnd:s,onStepKeyDown:f,...m}=t,x=P.useRef(null),_=Wn(e,x),T=P.useRef(void 0),E=!i;function C(N){const R=T.current||x.current.getBoundingClientRect(),D=[0,R.height],B=i7(D,E?[n,r]:[r,n]);return T.current=R,B(N-R.top)}return o.jsx(a0e,{scope:t.__scopeSlider,startEdge:E?"bottom":"top",endEdge:E?"top":"bottom",size:"height",direction:E?1:-1,children:o.jsx(l0e,{"data-orientation":"vertical",...m,ref:_,style:{...m.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:N=>{const R=C(N.clientY);a==null||a(R)},onSlideMove:N=>{const R=C(N.clientY);c==null||c(R)},onSlideEnd:()=>{T.current=void 0,s==null||s()},onStepKeyDown:N=>{const D=n0e[E?"from-bottom":"from-top"].includes(N.key);f==null||f({event:N,direction:D?-1:1})}})})}),l0e=P.forwardRef((t,e)=>{const{__scopeSlider:r,onSlideStart:n,onSlideMove:i,onSlideEnd:a,onHomeKeyDown:c,onEndKeyDown:s,onStepKeyDown:f,...m}=t,x=QM(AS,r);return o.jsx(rn.span,{...m,ref:e,onKeyDown:Or(t.onKeyDown,_=>{_.key==="Home"?(c(_),_.preventDefault()):_.key==="End"?(s(_),_.preventDefault()):t0e.concat(r0e).includes(_.key)&&(f(_),_.preventDefault())}),onPointerDown:Or(t.onPointerDown,_=>{const T=_.target;T.setPointerCapture(_.pointerId),_.preventDefault(),x.thumbs.has(T)?T.focus():n(_)}),onPointerMove:Or(t.onPointerMove,_=>{_.target.hasPointerCapture(_.pointerId)&&i(_)}),onPointerUp:Or(t.onPointerUp,_=>{const T=_.target;T.hasPointerCapture(_.pointerId)&&(T.releasePointerCapture(_.pointerId),a(_))})})}),c0e="SliderTrack",u0e=P.forwardRef((t,e)=>{const{__scopeSlider:r,...n}=t,i=QM(c0e,r);return o.jsx(rn.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...n,ref:e})});u0e.displayName=c0e;var O6="SliderRange",d0e=P.forwardRef((t,e)=>{const{__scopeSlider:r,...n}=t,i=QM(O6,r),a=o0e(O6,r),c=P.useRef(null),s=Wn(e,c),f=i.values.length,m=i.values.map(T=>p0e(T,i.min,i.max)),x=f>1?Math.min(...m):0,_=100-Math.max(...m);return o.jsx(rn.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...n,ref:s,style:{...t.style,[a.startEdge]:x+"%",[a.endEdge]:_+"%"}})});d0e.displayName=O6;var M6="SliderThumb",h0e=P.forwardRef((t,e)=>{const r=RKe(t.__scopeSlider),[n,i]=P.useState(null),a=Wn(e,s=>i(s)),c=P.useMemo(()=>n?r().findIndex(s=>s.ref.current===n):-1,[r,n]);return o.jsx(FKe,{...t,ref:a,index:c})}),FKe=P.forwardRef((t,e)=>{const{__scopeSlider:r,index:n,name:i,...a}=t,c=QM(M6,r),s=o0e(M6,r),[f,m]=P.useState(null),x=Wn(e,M=>m(M)),_=f?c.form||!!f.closest("form"):!0,T=DC(f),E=c.values[n],C=E===void 0?0:p0e(E,c.min,c.max),N=$Ke(n,c.values.length),R=T==null?void 0:T[s.size],D=R?VKe(R,C,s.direction):0;return P.useEffect(()=>{if(f)return c.thumbs.add(f),()=>{c.thumbs.delete(f)}},[f,c.thumbs]),o.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${C}% + ${D}px)`},children:[o.jsx(D6.ItemSlot,{scope:t.__scopeSlider,children:o.jsx(rn.span,{role:"slider","aria-label":t["aria-label"]||N,"aria-valuemin":c.min,"aria-valuenow":E,"aria-valuemax":c.max,"aria-orientation":c.orientation,"data-orientation":c.orientation,"data-disabled":c.disabled?"":void 0,tabIndex:c.disabled?void 0:0,...a,ref:x,style:E===void 0?{display:"none"}:t.style,onFocus:Or(t.onFocus,()=>{c.valueIndexToChangeRef.current=n})})}),_&&o.jsx(f0e,{name:i??(c.name?c.name+(c.values.length>1?"[]":""):void 0),form:c.form,value:E},n)]})});h0e.displayName=M6;var BKe="RadioBubbleInput",f0e=P.forwardRef(({__scopeSlider:t,value:e,...r},n)=>{const i=P.useRef(null),a=Wn(i,n),c=HC(e);return P.useEffect(()=>{const s=i.current;if(!s)return;const f=window.HTMLInputElement.prototype,x=Object.getOwnPropertyDescriptor(f,"value").set;if(c!==e&&x){const _=new Event("input",{bubbles:!0});x.call(s,e),s.dispatchEvent(_)}},[c,e]),o.jsx(rn.input,{style:{display:"none"},...r,ref:a,defaultValue:e})});f0e.displayName=BKe;function zKe(t=[],e,r){const n=[...t];return n[r]=e,n.sort((i,a)=>i-a)}function p0e(t,e,r){const a=100/(r-e)*(t-e);return hk(a,[0,100])}function $Ke(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}function UKe(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)}function VKe(t,e,r){const n=t/2,a=i7([0,50],[0,n]);return(n-a(e)*r)*r}function qKe(t){return t.slice(0,-1).map((e,r)=>t[r+1]-e)}function GKe(t,e){if(e>0){const r=qKe(t);return Math.min(...r)>=e}return!0}function i7(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])}}function HKe(t){return(String(t).split(".")[1]||"").length}function WKe(t,e){const r=Math.pow(10,e);return Math.round(t*r)/r}var m0e=s0e,KKe=u0e,YKe=d0e,ZKe=h0e;const xA=P.forwardRef(({className:t,...e},r)=>o.jsxs(m0e,{ref:r,className:sr("relative flex w-full touch-none select-none items-center",t),...e,children:[o.jsx(KKe,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:o.jsx(YKe,{className:"absolute h-full bg-primary"})}),o.jsx(ZKe,{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"})]}));xA.displayName=m0e.displayName;const XKe=t=>wr({queryKey:["public-listings",t],queryFn:async()=>{let e=Le.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}}),QKe=()=>wr({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:t,error:e}=await Le.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(),s=a.state?`${a.city}, ${a.state}`:a.city,f=r.get(c);f?f.count++:r.set(c,{label:s,city:a.city,state:a.state,count:1})}if(a.neighborhood){const c=`${a.neighborhood}|${a.city||""}`.toLowerCase(),s=a.city?`${a.neighborhood} — ${a.city}`:a.neighborhood,f=n.get(c);f?f.count++:n.set(c,{label:s,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 s=c[1],f=i.get(s);f?f.count++:i.set(s,{label:s,zip:s,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)}}}),JKe=t=>wr({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=Le.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,s)=>(c.sort_order??0)-(s.sort_order??0)||(s.is_primary?1:0)-(c.is_primary?1:0))),a},enabled:!!t}),eYe=()=>Cr({mutationFn:async({listingId:t,agentId:e,firstName:r,lastName:n,email:i,phone:a,shareToken:c,leadType:s="info_request",preferredDate:f,preferredTime:m,showingMode:x,message:_})=>{let T=null,E=null;if(c){const{data:M}=await Le.from("listing_shares").select("id, sharing_agent_id").eq("share_token",c).eq("listing_id",t).maybeSingle();M&&(T=M.id,E=M.sharing_agent_id)}const C=crypto.randomUUID(),N={id:C},{error:R}=await Le.from("listing_leads").insert({id:C,listing_id:t,agent_id:E||e,first_name:r,last_name:n,email:i,phone:a,share_id:T,referred_by_agent_id:E,lead_type:s,preferred_date:f||null,preferred_time:m||null,showing_mode:x||null,message:_||null});if(R)throw R;const{error:D}=await Le.functions.invoke("process-listing-lead",{body:{leadId:N.id}});return D&&console.error("Error processing lead:",D),N}}),tYe=()=>Cr({mutationFn:async t=>{const{error:e}=await Le.rpc("increment_listing_share_click",{p_share_token:t});if(e)throw e}});function rYe({title:t,subtitle:e,areaLabel:r,sections:n,agent:i,tone:a="light"}){const c=a==="dark",s=c?"text-white/65":"text-muted-foreground",f=c?"border-white/10":"border-border";return o.jsxs("div",{className:c?"text-white":"text-foreground",id:"community-guide-print",children:[o.jsxs("header",{className:`border-b ${f} pb-6 mb-8`,children:[o.jsxs("div",{className:`flex items-center gap-2 text-[11px] uppercase tracking-[0.22em] ${s} mb-3`,children:[o.jsx(u1,{className:"h-3.5 w-3.5"}),"Insider's Community Guide"]}),o.jsx("h1",{className:"font-display text-3xl sm:text-4xl font-semibold leading-tight",children:t}),e&&o.jsx("p",{className:`mt-3 text-base leading-relaxed ${s}`,children:e}),r&&o.jsxs("p",{className:`mt-3 flex items-center gap-1.5 text-sm ${s}`,children:[o.jsx(na,{className:"h-3.5 w-3.5"}),r]})]}),o.jsx("div",{className:"space-y-10",children:n.map((m,x)=>o.jsxs("section",{children:[o.jsxs("div",{className:"flex items-baseline gap-3 mb-2",children:[o.jsx("span",{className:"font-display text-2xl text-primary font-semibold",children:String(x+1).padStart(2,"0")}),o.jsx("h2",{className:"font-display text-xl sm:text-2xl font-semibold",children:m.heading})]}),m.intro&&o.jsx("p",{className:`text-sm sm:text-base leading-relaxed ${s} mb-4`,children:m.intro}),o.jsx("ul",{className:"space-y-3",children:(m.items??[]).map((_,T)=>o.jsxs("li",{className:`rounded-xl border ${f} ${c?"bg-white/[0.03]":"bg-muted/40"} px-4 py-3`,children:[o.jsx("p",{className:"font-medium text-sm sm:text-base",children:_.name}),_.note&&o.jsx("p",{className:`text-sm mt-1 leading-relaxed ${s}`,children:_.note})]},T))})]},x))}),(i==null?void 0:i.name)&&o.jsxs("footer",{className:`mt-10 pt-6 border-t ${f}`,children:[o.jsxs("div",{className:"flex items-center gap-4",children:[i.avatar_url?o.jsx("img",{src:i.avatar_url,alt:i.name,className:"h-14 w-14 rounded-full object-cover border border-primary/30"}):null,o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:`text-[11px] uppercase tracking-[0.2em] ${s}`,children:"Prepared for you by"}),o.jsx("p",{className:"font-display text-lg font-semibold leading-tight",children:i.name}),i.brokerage&&o.jsx("p",{className:`text-sm ${s}`,children:i.brokerage}),o.jsxs("div",{className:`flex flex-wrap gap-4 mt-1.5 text-sm ${s}`,children:[i.phone&&o.jsxs("a",{href:`tel:${i.phone}`,className:"flex items-center gap-1.5 hover:text-primary",children:[o.jsx(zi,{className:"h-3.5 w-3.5"}),i.phone]}),i.email&&o.jsxs("a",{href:`mailto:${i.email}`,className:"flex items-center gap-1.5 hover:text-primary",children:[o.jsx(Bi,{className:"h-3.5 w-3.5"}),i.email]})]})]})]}),o.jsxs("p",{className:`mt-4 text-sm ${s}`,children:["Thinking about a move in ",r||"the area","? Reach out any time — happy to share what never makes it online."]})]})]})}const _N="border-white/15 bg-white/5 text-white placeholder:text-white/40";function nYe({listingId:t}){const[e,r]=P.useState(null),[n,i]=P.useState({firstName:"",lastName:"",email:"",phone:""}),[a,c]=P.useState(!1),[s,f]=P.useState(null),[m,x]=P.useState(!1);if(P.useEffect(()=>{let T=!1;return Le.functions.invoke("community-guide-public",{body:{action:"teaser",listingId:t}}).then(({data:E})=>{!T&&E&&r(E)}).catch(()=>{}),()=>{T=!0}},[t]),!(e!=null&&e.available))return null;const _=async T=>{if(T.preventDefault(),!n.firstName.trim()||!n.email.trim()){Jt.error("Please add your name and email.");return}c(!0);try{const{data:E,error:C}=await Le.functions.invoke("community-guide-public",{body:{action:"unlock",listingId:t,...n}});if(C||E!=null&&E.error)throw new Error((E==null?void 0:E.error)||"Something went wrong.");f(E),x(!0),Jt.success("Your guide is ready!")}catch(E){Jt.error((E==null?void 0:E.message)||"We could not send your guide. Please try again.")}finally{c(!1)}};return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[o.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.2em] text-white/60 mb-3",children:[o.jsx(u1,{className:"h-3.5 w-3.5"}),"Free Community Guide"]}),o.jsx("h3",{className:"font-display text-xl text-white font-medium leading-snug",children:e.title}),e.subtitle&&o.jsx("p",{className:"text-sm text-white/60 mt-2 leading-relaxed",children:e.subtitle}),(e.teaser??[]).length>0&&o.jsx("ul",{className:"mt-4 space-y-2",children:e.teaser.map((T,E)=>o.jsxs("li",{className:"flex gap-2 text-sm text-white/70",children:[o.jsx(Ao,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),T]},E))}),s?o.jsxs(Ut,{className:"w-full mt-5",onClick:()=>x(!0),children:[o.jsx(u1,{className:"h-4 w-4 mr-2"}),"Read your guide"]}):o.jsxs("form",{onSubmit:_,className:"mt-5 space-y-3",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{htmlFor:"cg-first",className:"text-xs text-white/60",children:"First name"}),o.jsx(Ur,{id:"cg-first",value:n.firstName,onChange:T=>i({...n,firstName:T.target.value}),className:_N,required:!0})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{htmlFor:"cg-last",className:"text-xs text-white/60",children:"Last name"}),o.jsx(Ur,{id:"cg-last",value:n.lastName,onChange:T=>i({...n,lastName:T.target.value}),className:_N})]})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{htmlFor:"cg-email",className:"text-xs text-white/60",children:"Email"}),o.jsx(Ur,{id:"cg-email",type:"email",value:n.email,onChange:T=>i({...n,email:T.target.value}),className:_N,required:!0})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{htmlFor:"cg-phone",className:"text-xs text-white/60",children:"Cell phone"}),o.jsx(Ur,{id:"cg-phone",type:"tel",value:n.phone,onChange:T=>i({...n,phone:T.target.value}),className:_N})]}),o.jsxs(Ut,{type:"submit",className:"w-full",disabled:a,children:[a?o.jsx(Cu,{className:"h-4 w-4 mr-2 animate-spin"}):o.jsx(Xl,{className:"h-4 w-4 mr-2"}),a?"Preparing your guide…":"Get the free guide"]}),o.jsxs("p",{className:"text-[11px] text-white/50 flex items-center gap-1.5 justify-center",children:[o.jsx(zy,{className:"h-3 w-3"}),"Instant access. We never share your details."]})]})]}),o.jsx(ro,{open:m,onOpenChange:x,children:o.jsx($a,{className:"max-w-2xl p-0 gap-0",children:o.jsx(pp,{className:"max-h-[82vh]",children:o.jsxs("div",{className:"p-6 sm:p-8",children:[o.jsx("div",{id:"community-guide-print",children:s&&o.jsx(rYe,{title:s.title,subtitle:s.subtitle,areaLabel:s.area_label,sections:s.sections??[],agent:s.agent})}),o.jsx("div",{className:"mt-8 flex justify-end print:hidden",children:o.jsxs(Ut,{variant:"outline",onClick:()=>iYe(s==null?void 0:s.title),children:[o.jsx(Xl,{className:"h-4 w-4 mr-2"}),"Save as PDF"]})})]})})})})]})}function iYe(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 Fte={sale:"For Sale",lease:"For Lease",sale_or_lease:"For Sale or Lease",investment:"Investment Offering"},g0e={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"},n6t=["NNN","Modified Gross","Full Service","Gross","Absolute Net","Ground Lease"],sYe={sf_year:"/SF/YR",sf_month:"/SF/MO",month:"/MO"},aYe={om:"Offering Memorandum",flyer:"Flyer",rent_roll:"Rent Roll",financials:"Financials",survey:"Survey",site_plan:"Site Plan",lease:"Lease Documents",other:"Other"},i6t={public:"Open download",email:"Email required",nda:"NDA required"},oYe={principal:"Principal / Investor",broker:"Broker",tenant:"Tenant / User",lender:"Lender",other:"Other"},s6t=[{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"}],UB=[{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"}],a6t=[{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 Uh(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 Bte(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`:Uh(e)}function F6(t){return t==null?null:`${new Intl.NumberFormat("en-US").format(Number(t))} SF`}function y0e(t,e=2){return t==null?null:`${Number(t).toFixed(e).replace(/\.?0+$/,"")}%`}function B6(t){if(!(t!=null&&t.lease_rate))return null;const e=sYe[t.lease_rate_unit||"sf_year"]??"";return`${t.lease_rate_unit==="month"?Uh(t.lease_rate):`$${Number(t.lease_rate).toFixed(2).replace(/\.00$/,"")}`}${e}${t.lease_type?` ${t.lease_type}`:""}`}function zte(t,e){if(!t)return Uh(e)??"Price on request";if(t.deal_type==="lease")return B6(t)??"Rate on request";const r=t.asking_price??e;if(t.deal_type==="sale_or_lease"){const n=[Uh(r),B6(t)].filter(Boolean);return n.length?n.join(" · "):"Price on request"}return Uh(r)??"Price on request"}function lYe(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?g0e[e.commercial_type]:"Commercial"} Opportunity`:t.property_address||`${t.city??""}, ${t.state??""}`}function cYe(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 o6t(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 UB)(i[c.key]||r[c.key])&&n.push(c.key);return{done:n,total:UB.length,score:Math.round(n.length/UB.length*100)}}const l6t={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 c6t(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 u6t="https://commercial.relevelup.com",sp=Le;function d6t(t){return wr({queryKey:["commercial-details",t],queryFn:async()=>{const{data:e,error:r}=await sp.from("commercial_listing_details").select("*").eq("listing_id",t).maybeSingle();if(r)throw r;return e??null},enabled:!!t})}function h6t(){const t=Nr(),{user:e}=qn();return Cr({mutationFn:async({listingId:r,values:n})=>{const{data:i,error:a}=await sp.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 f6t(t){return wr({queryKey:["commercial-pitch",t],queryFn:async()=>{const{data:e,error:r}=await sp.from("commercial_pitch_details").select("*").eq("listing_id",t).maybeSingle();if(r)throw r;return e??null},enabled:!!t})}function p6t(){const t=Nr(),{user:e}=qn();return Cr({mutationFn:async({listingId:r,values:n})=>{const{data:i,error:a}=await sp.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 m6t(){const t=Nr();return Cr({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:s}=await sp.from("listings").update(c).eq("id",e);if(s)throw s;return(i||a)&&await sp.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 g6t(){const t=Nr();return Cr({mutationFn:async({listingId:e,values:r})=>{const{error:n}=await sp.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 y6t(t,e=90){return wr({queryKey:["commercial-engagement",t,e],queryFn:async()=>{const r=new Date(Date.now()-e*864e5).toISOString(),{data:n,error:i}=await sp.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 x6t(t){return wr({queryKey:["commercial-leads",t],queryFn:async()=>{const{data:e,error:r}=await sp.from("listing_leads").select("*").eq("listing_id",t).order("created_at",{ascending:!1});if(r)throw r;return e??[]},enabled:!!t})}const $te="lu_commercial_session";function x0e(){try{let t=localStorage.getItem($te);return t||(t=crypto.randomUUID(),localStorage.setItem($te,t)),t}catch{return"anonymous"}}async function Mb(t,e,r={}){try{await sp.from("commercial_engagement_events").insert({listing_id:t,event_type:e,session_id:x0e(),source:typeof document<"u"&&document.referrer||null,metadata:r})}catch{}}const uYe={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 dYe({open:t,onOpenChange:e,listingId:r,kind:n,documentId:i,requiresNda:a,brokerName:c}){const s=uYe[n],[f,m]=P.useState({firstName:"",lastName:"",email:"",phone:"",company:"",role:"principal",message:""}),[x,_]=P.useState(!1),[T,E]=P.useState(!1),[C,N]=P.useState(null),R=async()=>{if(!f.firstName.trim()||!f.email.trim()){Jt.error("Name and email are required");return}if(a&&n==="om_request"&&!x){Jt.error("Please acknowledge the confidentiality terms");return}E(!0);try{const{data:D,error:M}=await Le.functions.invoke("commercial-lead",{body:{listingId:r,documentId:i??null,leadType:n,firstName:f.firstName,lastName:f.lastName,email:f.email,phone:f.phone||null,company:f.company||null,role:f.role,message:f.message||null,ndaAccepted:x,sessionId:x0e()}});if(M)throw M;if(D!=null&&D.error)throw new Error(D.error);N({signedUrl:(D==null?void 0:D.signedUrl)??null,fileName:(D==null?void 0:D.fileName)??null}),D!=null&&D.signedUrl&&window.open(D.signedUrl,"_blank")}catch(D){Jt.error(D.message||"Something went wrong. Please try again.")}finally{E(!1)}};return o.jsx(ro,{open:t,onOpenChange:D=>{e(D),D||N(null)},children:o.jsxs($a,{className:"max-w-lg overflow-hidden border-white/10 bg-[#0b0f14] p-0 text-white",children:[o.jsxs("div",{className:"border-b border-white/10 bg-gradient-to-b from-white/[0.06] to-transparent px-7 py-6",children:[o.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:s.eyebrow}),o.jsx("h2",{className:"mt-2 font-serif text-2xl",children:C?"Access granted":s.title}),o.jsx("p",{className:"mt-1.5 text-sm text-white/60",children:C?C.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.`:s.blurb})]}),C?o.jsxs("div",{className:"space-y-4 px-7 py-7",children:[o.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-400/20 bg-emerald-400/10 px-4 py-3",children:[o.jsx(xc,{className:"h-5 w-5 text-emerald-400"}),o.jsx("p",{className:"text-sm text-white/80",children:C.fileName??"Request received"})]}),C.signedUrl&&o.jsx(Ut,{className:"w-full",onClick:()=>window.open(C.signedUrl,"_blank"),children:"Download again"}),o.jsx(Ut,{variant:"ghost",className:"w-full text-white/60 hover:text-white",onClick:()=>e(!1),children:"Close"})]}):o.jsxs("div",{className:"space-y-4 px-7 py-6",children:[o.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[o.jsx(A_,{label:"First name *",children:o.jsx(Ur,{value:f.firstName,onChange:D=>m({...f,firstName:D.target.value}),className:"border-white/15 bg-white/5 text-white"})}),o.jsx(A_,{label:"Last name",children:o.jsx(Ur,{value:f.lastName,onChange:D=>m({...f,lastName:D.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),o.jsx(A_,{label:"Email *",children:o.jsx(Ur,{type:"email",value:f.email,onChange:D=>m({...f,email:D.target.value}),className:"border-white/15 bg-white/5 text-white"})}),o.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[o.jsx(A_,{label:"Company",children:o.jsx(Ur,{value:f.company,onChange:D=>m({...f,company:D.target.value}),className:"border-white/15 bg-white/5 text-white"})}),o.jsx(A_,{label:"Phone",children:o.jsx(Ur,{value:f.phone,onChange:D=>m({...f,phone:D.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),o.jsx(A_,{label:"I am a *",children:o.jsxs(Ba,{value:f.role,onValueChange:D=>m({...f,role:D}),children:[o.jsx(ja,{className:"border-white/15 bg-white/5 text-white",children:o.jsx(za,{})}),o.jsx(Ia,{children:Object.entries(oYe).map(([D,M])=>o.jsx(wn,{value:D,children:M},D))})]})}),n!=="om_request"&&o.jsx(A_,{label:"Message",children:o.jsx(hd,{rows:3,value:f.message,onChange:D=>m({...f,message:D.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"&&o.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-xl border border-white/10 bg-white/[0.04] p-3",children:[o.jsx(ZC,{checked:x,onCheckedChange:D=>_(!!D),className:"mt-0.5 border-white/30"}),o.jsxs("span",{className:"text-xs leading-relaxed text-white/65",children:[o.jsx(mG,{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."]})]}),o.jsxs(Ut,{className:"w-full",size:"lg",onClick:R,disabled:T,children:[T?o.jsx(Cu,{className:"mr-2 h-4 w-4 animate-spin"}):o.jsx(zy,{className:"mr-2 h-4 w-4"}),s.cta]}),o.jsx("p",{className:"text-center text-[11px] text-white/40",children:"Your information is shared only with the listing broker."})]})]})})}function A_({label:t,children:e}){return o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{className:"text-[11px] font-medium uppercase tracking-wider text-white/50",children:t}),e]})}function _0e(t){if(!t)return[];const e=[],r=(n,i)=>{i&&e.push({label:n,value:i})};return r("Cap Rate",y0e(t.cap_rate)),r("NOI",Bte(t.noi)),r("Occupancy",t.occupancy_pct!=null?`${Math.round(Number(t.occupancy_pct))}%`:null),r("Building SF",F6(t.building_sf)),r("Available SF",F6(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?Uh(t.price_per_sf,2):null),r("Price / Unit",Bte(t.price_per_unit)),r("Lease Rate",t.deal_type!=="sale"?B6(t):null),r("Year Built",null),r("Zoning",t.zoning??null),e}function _6t({details:t,className:e="",tone:r="light"}){const n=_0e(t).slice(0,8);if(!n.length)return null;const i=r==="dark";return o.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=>o.jsxs("div",{className:`${i?"bg-[#0b0f14]":"bg-card"} px-5 py-4`,children:[o.jsx("p",{className:`text-[10px] font-semibold uppercase tracking-[0.18em] ${i?"text-white/45":"text-muted-foreground"}`,children:a.label}),o.jsx("p",{className:`mt-1.5 text-xl font-semibold tabular-nums ${i?"text-white":""}`,children:a.value})]},a.label))})}function hYe(t){return wr({queryKey:["commercial-microsite",t],queryFn:async()=>{const{data:e,error:r}=await Le.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 fYe({slug:t}){var ue,_e;const{data:e,isLoading:r,error:n}=hYe(t),[i,a]=P.useState(null),[c,s]=P.useState(null),f=e==null?void 0:e.listing,m=(e==null?void 0:e.details)??void 0,x=(e==null?void 0:e.documents)??[],_=(f==null?void 0:f.photos)??[],T=f==null?void 0:f.agent,E=!!(m!=null&&m.is_confidential||m!=null&&m.hide_address),C=P.useMemo(()=>_0e(m).slice(0,8),[m]);if(P.useEffect(()=>{f!=null&&f.id&&Mb(f.id,"page_view",{slug:t})},[f==null?void 0:f.id,t]),P.useEffect(()=>{if(i===null)return;const Se=ve=>{ve.key==="Escape"&&a(null),ve.key==="ArrowRight"&&a(Oe=>Oe===null?Oe:(Oe+1)%_.length),ve.key==="ArrowLeft"&&a(Oe=>Oe===null?Oe:(Oe-1+_.length)%_.length)};return window.addEventListener("keydown",Se),()=>window.removeEventListener("keydown",Se)},[i,_.length]),r)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14]",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/70"})});if(n||!f)return o.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 N=lYe(f,m),R=cYe(f,m),D=f.latitude&&f.longitude?`${f.latitude},${f.longitude}`:E?[m==null?void 0:m.submarket,f.city,f.state].filter(Boolean).join(", ")||null:[f.property_address,f.city,f.state].filter(Boolean).join(", ")||null,M=(ue=_[0])==null?void 0:ue.photo_url,B=(m==null?void 0:m.tenants)??[],V=(m==null?void 0:m.spaces)??[],G=(m==null?void 0:m.demographics)??{},W=(m==null?void 0:m.traffic_counts)??[],X=(m==null?void 0:m.investment_highlights)??[],Q=(m==null?void 0:m.property_highlights)??[],re=["radius_1","radius_3","radius_5"].some(Se=>(G==null?void 0:G[Se])&&Object.values(G[Se]).some(Boolean)),se=(Se,ve)=>{s({kind:Se,documentId:ve}),Mb(f.id,Se==="om_request"?"om_request":Se,{})};return o.jsxs("div",{className:"min-h-screen bg-[#0b0f14] text-white antialiased",children:[o.jsxs(jl,{children:[o.jsx("title",{children:`${N} | ${R}`}),o.jsx("meta",{name:"description",content:(f.description??"").slice(0,155)||`${Fte[(m==null?void 0:m.deal_type)??"sale"]} — ${R}`}),E&&o.jsx("meta",{name:"robots",content:"noindex,nofollow"}),o.jsx("meta",{property:"og:title",content:N}),o.jsx("meta",{property:"og:type",content:"website"})]}),o.jsx("header",{className:"fixed inset-x-0 top-0 z-40 border-b border-white/10 bg-[#0b0f14]/80 backdrop-blur",children:o.jsxs("div",{className:"mx-auto flex max-w-7xl items-center justify-between px-6 py-3.5 md:px-10",children:[o.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:[o.jsx("span",{"aria-hidden":!0,children:"←"})," All opportunities"]}),o.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.22em] text-white/45",children:"LevelUp Commercial"})]})}),o.jsxs("section",{className:"relative min-h-[86vh] w-full overflow-hidden",children:[M?o.jsx("img",{src:M,alt:N,className:"absolute inset-0 h-full w-full object-cover"}):o.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/60 to-[#0b0f14]/30"}),o.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:[o.jsxs("div",{className:"mb-5 flex flex-wrap items-center gap-2.5",children:[o.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:Fte[(m==null?void 0:m.deal_type)??"sale"]}),(m==null?void 0:m.commercial_type)&&o.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:g0e[m.commercial_type]}),E&&o.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:[o.jsx(zy,{className:"h-3 w-3"})," Confidential offering"]})]}),o.jsx("h1",{className:"max-w-4xl font-serif text-4xl leading-[1.05] tracking-tight md:text-6xl lg:text-7xl",children:N}),o.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/60",children:[o.jsx(na,{className:"h-4 w-4"})," ",R]}),o.jsxs("div",{className:"mt-8 flex flex-wrap items-end gap-x-10 gap-y-5",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:(m==null?void 0:m.deal_type)==="lease"?"Lease rate":"Asking price"}),o.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:zte(m,f.price)})]}),(m==null?void 0:m.cap_rate)!=null&&o.jsxs("div",{children:[o.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:"Cap rate"}),o.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:y0e(m.cap_rate)})]})]}),o.jsxs("div",{className:"mt-9 flex flex-wrap gap-3",children:[o.jsxs(Ut,{size:"lg",className:"rounded-full px-7",onClick:()=>{var Se;return se("om_request",((Se=x.find(ve=>ve.doc_kind==="om"))==null?void 0:Se.id)??null)},children:["Request Offering Memorandum ",o.jsx(pc,{className:"ml-2 h-4 w-4"})]}),o.jsx(Ut,{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:()=>se("tour_request"),children:"Schedule a tour"})]})]})]}),C.length>0&&o.jsx("section",{className:"border-y border-white/10 bg-white/[0.02]",children:o.jsx("div",{className:"mx-auto grid max-w-7xl gap-px bg-white/10",style:{gridTemplateColumns:`repeat(${Math.min(C.length,4)}, minmax(0, 1fr))`},children:C.map(Se=>o.jsxs("div",{className:"bg-[#0b0f14] px-6 py-8",children:[o.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:Se.label}),o.jsx("p",{className:"mt-2 text-2xl font-semibold tabular-nums md:text-3xl",children:Se.value})]},Se.label))})}),X.length>0&&o.jsx(Fg,{eyebrow:"The opportunity",title:"Investment highlights",children:o.jsx("div",{className:"grid gap-x-12 gap-y-8 md:grid-cols-2",children:X.map((Se,ve)=>o.jsxs("div",{className:"flex gap-5 border-t border-white/10 pt-6",children:[o.jsx("span",{className:"font-serif text-2xl text-white/25 tabular-nums",children:String(ve+1).padStart(2,"0")}),o.jsx("p",{className:"text-lg leading-relaxed text-white/85",children:Se})]},ve))})}),(f.description||Q.length>0)&&o.jsx(Fg,{eyebrow:"Property",title:"The asset",children:o.jsxs("div",{className:"grid gap-12 lg:grid-cols-[1.4fr_1fr]",children:[f.description&&o.jsx("div",{className:"space-y-5 text-lg leading-relaxed text-white/70",children:String(f.description).split(/\n{2,}/).map((Se,ve)=>o.jsx("p",{children:Se},ve))}),Q.length>0&&o.jsx("ul",{className:"space-y-3 self-start rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:Q.map((Se,ve)=>o.jsxs("li",{className:"flex gap-3 text-sm text-white/75",children:[o.jsx("span",{className:"mt-2 h-1 w-1 shrink-0 rounded-full bg-white/50"})," ",Se]},ve))})]})}),_.length>1&&o.jsx(Fg,{eyebrow:"Gallery",title:"Property imagery",children:o.jsx("div",{className:"grid gap-3 md:grid-cols-3",children:_.slice(1,10).map((Se,ve)=>o.jsx("button",{onClick:()=>{a(ve+1),Mb(f.id,"gallery_view",{})},className:`group relative overflow-hidden rounded-xl ${ve===0?"md:col-span-2 md:row-span-2":""}`,children:o.jsx("img",{src:Se.photo_url,alt:`${N} — image ${ve+2}`,loading:"lazy",className:`w-full object-cover transition-transform duration-700 group-hover:scale-[1.04] ${ve===0?"h-full min-h-[280px] md:min-h-[560px]":"h-[180px] md:h-[275px]"}`})},Se.id))})}),((m==null?void 0:m.noi)||(m==null?void 0:m.gross_income)||(m==null?void 0:m.operating_expenses)||(m==null?void 0:m.occupancy_pct)!=null)&&o.jsxs(Fg,{eyebrow:"Financials",title:"Offering snapshot",children:[o.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:Uh(m==null?void 0:m.noi)},{l:"Gross income",v:Uh(m==null?void 0:m.gross_income)},{l:"Operating expenses",v:Uh(m==null?void 0:m.operating_expenses)},{l:"Occupancy",v:(m==null?void 0:m.occupancy_pct)!=null?`${Math.round(Number(m.occupancy_pct))}%`:null},{l:"Price per SF",v:(m==null?void 0:m.price_per_sf)!=null?Uh(m.price_per_sf,2):null},{l:"Price per unit",v:Uh(m==null?void 0:m.price_per_unit)},{l:"Tenancy",v:m!=null&&m.tenancy?`${m.tenancy[0].toUpperCase()}${m.tenancy.slice(1)} tenant`:null},{l:"Broker co-op",v:(m==null?void 0:m.broker_coop_pct)!=null?`${m.broker_coop_pct}%`:null}].filter(Se=>Se.v).map(Se=>o.jsxs("div",{className:"bg-[#0b0f14] px-6 py-7",children:[o.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:Se.l}),o.jsx("p",{className:"mt-2 text-xl font-semibold tabular-nums",children:Se.v})]},Se.l))}),(m==null?void 0:m.call_for_offers_at)&&o.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(m.call_for_offers_at).toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"})]})]}),(B.length>0||V.length>0)&&o.jsx(Fg,{eyebrow:"Occupancy",title:V.length?"Space availability":"Tenant roster",children:o.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:o.jsxs("table",{className:"w-full text-left text-sm",children:[o.jsx("thead",{className:"bg-white/[0.04] text-[10px] uppercase tracking-[0.18em] text-white/45",children:o.jsxs("tr",{children:[o.jsx("th",{className:"px-6 py-4",children:V.length?"Suite":"Tenant"}),o.jsx("th",{className:"px-6 py-4",children:"SF"}),o.jsx("th",{className:"px-6 py-4",children:V.length?"Rate":"Rent"}),o.jsx("th",{className:"px-6 py-4",children:V.length?"Availability":"Lease expiry"})]})}),o.jsx("tbody",{className:"divide-y divide-white/5",children:(V.length?V:B).map((Se,ve)=>o.jsxs("tr",{className:"text-white/80",children:[o.jsx("td",{className:"px-6 py-4 font-medium text-white",children:Se.suite??Se.name??"—"}),o.jsx("td",{className:"px-6 py-4 tabular-nums",children:Se.sf?F6(Number(Se.sf)):"—"}),o.jsx("td",{className:"px-6 py-4",children:Se.rate??Se.rent??"—"}),o.jsx("td",{className:"px-6 py-4",children:Se.availability??Se.lease_expiry??"—"})]},ve))})]})})}),o.jsx(Fg,{eyebrow:"Location",title:m!=null&&m.submarket?`${m.submarket} submarket`:R,children:o.jsxs("div",{className:"grid gap-8 lg:grid-cols-[1.2fr_1fr]",children:[D?o.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:o.jsx("iframe",{title:"Property location",className:"h-[420px] w-full",loading:"lazy",src:`https://www.google.com/maps?q=${encodeURIComponent(D)}&z=${f.latitude&&f.longitude?15:12}&output=embed`,onLoad:()=>Mb(f.id,"map_view",{})})}):o.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:E?"Exact location released with the Offering Memorandum.":R}),o.jsxs("div",{className:"space-y-5",children:[(m==null?void 0:m.zoning)&&o.jsx(Fb,{label:"Zoning",value:m.zoning}),(m==null?void 0:m.lot_acres)!=null&&o.jsx(Fb,{label:"Site size",value:`${m.lot_acres} acres`}),(m==null?void 0:m.parking_spaces)!=null&&o.jsx(Fb,{label:"Parking",value:`${m.parking_spaces} spaces`}),(m==null?void 0:m.opportunity_zone)&&o.jsx(Fb,{label:"Opportunity Zone",value:"Qualified"}),W.filter(Se=>Se.road||Se.count).map((Se,ve)=>o.jsx(Fb,{label:`Traffic count — ${Se.road??"Adjacent road"}`,value:`${Se.count??"—"} VPD`},ve)),!(m!=null&&m.zoning)&&(m==null?void 0:m.lot_acres)==null&&(m==null?void 0:m.parking_spaces)==null&&!(m!=null&&m.opportunity_zone)&&o.jsx(Fb,{label:"Submarket",value:(m==null?void 0:m.submarket)||R})]})]})}),re&&o.jsx(Fg,{eyebrow:"Market",title:"Demographics",children:o.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[["radius_1","1 mile"],["radius_3","3 miles"],["radius_5","5 miles"]].map(([Se,ve])=>{const Oe=G==null?void 0:G[Se];return!Oe||!Object.values(Oe).some(Boolean)?null:o.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:[o.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:ve}),o.jsx("dl",{className:"mt-5 space-y-3 text-sm",children:[["Population",Oe.population],["Households",Oe.households],["Avg. income",Oe.avg_income],["Daytime pop.",Oe.daytime_pop]].filter(([,Ae])=>Ae).map(([Ae,we])=>o.jsxs("div",{className:"flex justify-between gap-4",children:[o.jsx("dt",{className:"text-white/50",children:Ae}),o.jsx("dd",{className:"font-medium tabular-nums",children:we})]},Ae))})]},Se)})})}),x.length>0&&o.jsx(Fg,{eyebrow:"Deal room",title:"Offering documents",children:o.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:x.map(Se=>{const ve=Se.gate_level==="public";return o.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:[o.jsx("div",{className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/5",children:ve?o.jsx(Xl,{className:"h-5 w-5"}):Se.gate_level==="nda"?o.jsx(mG,{className:"h-5 w-5"}):o.jsx(zy,{className:"h-5 w-5"})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("p",{className:"truncate font-medium",children:Se.title||aYe[Se.doc_kind||"other"]}),o.jsx("p",{className:"text-xs text-white/45",children:ve?"Available to download":Se.gate_level==="nda"?"Confidentiality acknowledgement required":"Registration required"})]}),o.jsx(Ut,{size:"sm",variant:"outline",className:"border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>se("om_request",Se.id),children:ve?"Download":"Request"})]},Se.id)})})}),T&&o.jsx("section",{className:"border-t border-white/10 bg-white/[0.02]",children:o.jsx("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10",children:o.jsxs("div",{className:"flex flex-col items-start gap-8 md:flex-row md:items-center md:justify-between",children:[o.jsxs("div",{className:"flex items-center gap-6",children:[T.avatar_url&&o.jsx("img",{src:T.avatar_url,alt:T.name,className:"h-24 w-24 rounded-full object-cover ring-1 ring-white/15"}),o.jsxs("div",{children:[o.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.22em] text-white/40",children:"Exclusively listed by"}),o.jsx("p",{className:"mt-2 font-serif text-2xl",children:T.name}),o.jsx("p",{className:"text-sm text-white/55",children:((_e=T.brokerage)==null?void 0:_e.name)||T.brokerage_name})]})]}),o.jsxs("div",{className:"flex flex-wrap gap-3",children:[T.email&&o.jsxs(Ut,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{Mb(f.id,"contact_click",{}),window.location.href=`mailto:${T.email}`},children:[o.jsx(Bi,{className:"mr-2 h-4 w-4"})," Email"]}),T.phone&&o.jsxs(Ut,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{Mb(f.id,"contact_click",{}),window.location.href=`tel:${T.phone}`},children:[o.jsx(zi,{className:"mr-2 h-4 w-4"})," Call"]}),o.jsx(Ut,{className:"rounded-full",onClick:()=>se("investor_inquiry"),children:"Request information"})]})]})})}),o.jsx("footer",{className:"border-t border-white/10 py-10 text-center text-xs text-white/35",children:o.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."})}),o.jsx("div",{className:"sticky bottom-0 z-30 border-t border-white/10 bg-[#0b0f14]/90 backdrop-blur-xl",children:o.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:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"truncate text-sm font-medium",children:N}),o.jsxs("p",{className:"truncate text-xs text-white/50",children:[zte(m,f.price)," · ",R]})]}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ut,{size:"sm",variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>se("tour_request"),children:"Tour"}),o.jsx(Ut,{size:"sm",className:"rounded-full",onClick:()=>{var Se;return se("om_request",((Se=x.find(ve=>ve.doc_kind==="om"))==null?void 0:Se.id)??null)},children:"Request OM"})]})]})}),o.jsx(ro,{open:i!==null,onOpenChange:Se=>!Se&&a(null),children:o.jsx($a,{className:"max-w-[96vw] border-none bg-transparent p-0 shadow-none",children:i!==null&&_[i]&&o.jsxs("div",{className:"relative",children:[o.jsx("img",{src:_[i].photo_url,alt:"",className:"max-h-[88vh] w-full rounded-xl object-contain"}),o.jsx("button",{className:"absolute right-3 top-3 rounded-full bg-black/60 p-2",onClick:()=>a(null),children:o.jsx(Ks,{className:"h-5 w-5"})}),o.jsx("button",{className:"absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>a(Se=>(Se-1+_.length)%_.length),children:o.jsx($m,{className:"h-6 w-6"})}),o.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-black/60 p-2",onClick:()=>a(Se=>(Se+1)%_.length),children:o.jsx(th,{className:"h-6 w-6"})})]})})}),c&&o.jsx(dYe,{open:!0,onOpenChange:Se=>!Se&&s(null),listingId:f.id,kind:c.kind,documentId:c.documentId,requiresNda:!!(m!=null&&m.requires_nda)||(m==null?void 0:m.om_gate_mode)==="nda",brokerName:T==null?void 0:T.name})]})}function Fg({eyebrow:t,title:e,children:r}){return o.jsx("section",{className:"border-t border-white/10",children:o.jsxs("div",{className:"mx-auto max-w-7xl px-6 py-20 md:px-10 md:py-24",children:[o.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:t}),o.jsx("h2",{className:"mt-3 font-serif text-3xl tracking-tight md:text-4xl",children:e}),o.jsx("div",{className:"mt-12",children:r})]})})}function Fb({label:t,value:e}){return o.jsxs("div",{className:"border-t border-white/10 pt-4",children:[o.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.2em] text-white/40",children:t}),o.jsx("p",{className:"mt-1 text-lg",children:e})]})}const Ute="/assets/levelup-logo-color-BeKd2k_g.png",pYe={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"},VB={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"},Vte={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},qB=t=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(t),w2=t=>new Intl.NumberFormat("en-US").format(t);function v0e(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 s7({slugOverride:t}={}){var ia,jr,Mn,As,xa,go,Yr;const e=hp(),r=t||e.slugOrId,[n]=B0(),{data:i,isLoading:a}=JKe(r||""),c=eYe(),s=tYe(),f=n.get("ref"),[m,x]=P.useState(""),[_,T]=P.useState(""),[E,C]=P.useState(""),[N,R]=P.useState(""),[D,M]=P.useState(""),[B,V]=P.useState(""),[G,W]=P.useState(""),[X,Q]=P.useState("in_person"),[re,se]=P.useState("info"),[ue,_e]=P.useState(!1),[Se,ve]=P.useState(!1),[Oe,Ae]=P.useState(null),[we,ge]=P.useState(!1);P.useState(!1);const[Ne,Ie]=P.useState(!1),[Te,be]=P.useState(20),[We,rt]=P.useState(6.5),[at,Et]=P.useState(30),_t=P.useRef(null),[Vt,mt]=P.useState(!1);P.useEffect(()=>{const hn=()=>mt(window.scrollY>300);return window.addEventListener("scroll",hn,{passive:!0}),()=>window.removeEventListener("scroll",hn)},[]),P.useEffect(()=>{f&&s.mutate(f)},[f]),P.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[r]);const Pt=(i==null?void 0:i.photos)||[],er=Pt.find(hn=>hn.is_primary)||Pt[0],wt=P.useMemo(()=>{if(!(i!=null&&i.price))return 0;const hn=i.price*(1-Te/100),gn=We/100/12,Zr=at*12;return gn===0?hn/Zr:hn*gn/(1-Math.pow(1+gn,-Zr))},[i==null?void 0:i.price,Te,We,at]),or=async()=>{const hn=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:hn})}catch{}else await navigator.clipboard.writeText(hn),Jt.success("Link copied to clipboard")},Sr=async hn=>{if(hn.preventDefault(),!m.trim()||!E.trim()||!i)return;const gn=re==="showing";if(gn&&!B){Jt.error("Please pick a preferred date for your showing");return}_e(!0);try{await c.mutateAsync({listingId:i.id,agentId:i.agent_id,firstName:m.trim(),lastName:_.trim(),email:E.trim(),phone:N.trim(),shareToken:f,leadType:gn?"showing_request":"info_request",preferredDate:gn?B:null,preferredTime:gn&&G||null,showingMode:gn?X:null,message:D.trim()||null}),ve(!0),Jt.success(gn?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(Zr){console.error("Lead submission error:",Zr),Jt.error(`Failed to submit: ${Zr.message||"Please try again"}`)}finally{_e(!1)}},nn=()=>{Oe!==null&&Ae(Oe===0?Pt.length-1:Oe-1)},lr=()=>{Oe!==null&&Ae(Oe===Pt.length-1?0:Oe+1)};if((i==null?void 0:i.listing_class)==="commercial")return o.jsx(fYe,{slug:r});if(a)return o.jsx("div",{className:"min-h-screen bg-neutral-950",children:o.jsx(ol,{className:"h-[100svh] w-full rounded-none bg-neutral-900"})});if(!i)return o.jsxs("div",{className:"min-h-screen bg-background",children:[o.jsx("header",{className:"border-b bg-card",children:o.jsx("div",{className:"container mx-auto px-4 py-4",children:o.jsx(cs,{to:"/public/listings",className:"flex items-center gap-2",children:o.jsx("img",{src:Ute,alt:"LevelUp",className:"h-8"})})})}),o.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[o.jsx(Ma,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),o.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),o.jsx("p",{className:"text-muted-foreground mb-6",children:"This listing may no longer be available."}),o.jsx(Ut,{asChild:!0,children:o.jsx(cs,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const yr=i.property_address?`${i.property_address} — ${i.city}, ${i.state}`:`${i.city}, ${i.state} Home for Sale`,tr=((jr=(ia=i.agent)==null?void 0:ia.brokerage)==null?void 0:jr.name)||((Mn=i.agent)==null?void 0:Mn.brokerage_name),yn=((As=i.agent)==null?void 0:As.name)||"",lt=v0e(i.video_link),At=tr||yn||"",Ot=VB[i.status]==="Sold"?"Just Sold":VB[i.status],dr=Ot?`${Ot}: ${yr}`:yr,cr=[`${qB(i.price)} · ${i.city}, ${i.state}`,yn?`Presented by ${yn}${tr?`, ${tr}`:""}.`:""].filter(Boolean).join(" · "),hr=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,Zt=i.description||"",Pr=Zt.length>420,Nn=Ne||!Pr?Zt:Zt.slice(0,420).trimEnd()+"…",ai=i.page_config||{},ei=hn=>{var gn;return(((gn=ai.sections)==null?void 0:gn[hn])??!0)!==!1},Oi=Array.isArray(ai.addons)?ai.addons:[],ya=ai.custom_note||"",mi=ai.accent_color||null;return o.jsxs(o.Fragment,{children:[o.jsxs(jl,{children:[o.jsx("title",{children:At?`${yr} | ${At}`:yr}),o.jsx("meta",{name:"description",content:`${qB(i.price)} · ${i.bedrooms||""}BD ${i.bathrooms||""}BA ${i.square_footage?i.square_footage.toLocaleString()+" sqft · ":""}${Vte[i.property_type]} in ${i.city}, ${i.state}. ${Zt.slice(0,140)}`}),o.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${i.slug||i.id}`}),o.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),o.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:""}),o.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"}),o.jsx("meta",{property:"og:title",content:dr}),o.jsx("meta",{property:"og:description",content:cr}),o.jsx("meta",{property:"og:type",content:"website"}),o.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${i.slug||i.id}`}),er&&o.jsx("meta",{property:"og:image",content:er.photo_url}),At&&o.jsx("meta",{property:"og:site_name",content:At}),o.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),o.jsx("meta",{name:"twitter:title",content:dr}),o.jsx("meta",{name:"twitter:description",content:cr}),er&&o.jsx("meta",{name:"twitter:image",content:er.photo_url}),o.jsx("meta",{name:"robots",content:"index, follow"}),o.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:Zt,url:`https://listings.relevelup.com/${i.slug||i.id}`,datePosted:i.created_at,image:Pt.map(hn=>hn.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})}),o.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; } `})]}),o.jsxs("div",{className:"bg-neutral-950 text-neutral-100 min-h-screen",children:[o.jsx("header",{className:`fixed inset-x-0 top-0 z-40 transition-all duration-300 ${Vt?"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:o.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 flex items-center justify-between gap-3",children:[o.jsxs(cs,{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:[o.jsx(By,{className:"h-4 w-4"}),o.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),Vt&&o.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(([hn,gn])=>o.jsx("a",{href:`#${hn}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:gn},hn))}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(PKe,{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"}),o.jsx("button",{onClick:or,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:o.jsx(kC,{className:"h-4 w-4 text-white"})}),o.jsx(Ut,{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"})]})]})}),o.jsxs("section",{ref:_t,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[er?o.jsx("img",{src:er.photo_url,alt:i.property_address||`${i.city}, ${i.state}`,className:"absolute inset-0 h-full w-full object-cover kb-zoom"}):o.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-neutral-800 to-neutral-950"}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black via-black/50 to-black/20"}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/40 via-transparent to-transparent"}),o.jsxs("div",{className:"absolute top-24 right-4 sm:right-8 z-10 flex flex-col items-end gap-2",children:[o.jsx(us,{className:`${pYe[i.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:VB[i.status]}),Pt.length>0&&o.jsxs("button",{onClick:()=>Ae(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:[o.jsx(bJ,{className:"h-3.5 w-3.5"}),Pt.length," photos"]})]}),o.jsx("div",{className:"absolute inset-x-0 bottom-0 z-10 px-4 sm:px-8 pb-10 sm:pb-14",children:o.jsxs("div",{className:"max-w-7xl mx-auto",children:[o.jsxs("div",{className:"flex items-end justify-between gap-6 flex-wrap",children:[o.jsxs("div",{className:"max-w-3xl",children:[i.neighborhood&&o.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&&o.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&&o.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]}),o.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[o.jsx("p",{className:"font-display text-white text-3xl sm:text-4xl md:text-5xl font-medium",children:qB(i.price)}),o.jsx("div",{className:"h-8 w-px bg-white/30 hidden sm:block"}),o.jsxs("div",{className:"flex items-center gap-4 text-white/80 text-sm sm:text-base",children:[i.bedrooms&&o.jsxs("span",{children:[o.jsx("span",{className:"font-semibold text-white",children:i.bedrooms})," bd"]}),i.bathrooms&&o.jsxs("span",{children:[o.jsx("span",{className:"font-semibold text-white",children:i.bathrooms})," ba"]}),i.square_footage&&o.jsxs("span",{children:[o.jsx("span",{className:"font-semibold text-white",children:w2(i.square_footage)})," sqft"]})]})]})]}),o.jsxs("div",{className:"hidden md:flex flex-col gap-2",children:[i.agent&&o.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?o.jsx("img",{src:i.agent.avatar_url,alt:i.agent.name,className:"h-12 w-12 rounded-full object-cover"}):o.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 flex items-center justify-center",children:o.jsx(gc,{className:"h-6 w-6 text-white"})}),o.jsxs("div",{className:"pr-2 flex-1",children:[o.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Listing Agent"}),o.jsx("p",{className:"text-white font-medium leading-tight",children:i.agent.name}),tr&&o.jsx("p",{className:"text-xs text-white/60",children:tr})]}),o.jsx(Ut,{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&&o.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?o.jsx("img",{src:i.co_agent_photo_url,alt:i.co_agent_name,className:"h-12 w-12 rounded-full object-cover"}):o.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 flex items-center justify-center",children:o.jsx(gc,{className:"h-6 w-6 text-white"})}),o.jsxs("div",{className:"pr-2 flex-1",children:[o.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Co-Listing Agent"}),o.jsx("p",{className:"text-white font-medium leading-tight",children:i.co_agent_name}),i.co_agent_brokerage&&o.jsx("p",{className:"text-xs text-white/60",children:i.co_agent_brokerage})]}),(i.co_agent_phone||i.co_agent_email)&&o.jsx(Ut,{asChild:!0,size:"sm",className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:o.jsx("a",{href:i.co_agent_phone?`tel:${i.co_agent_phone}`:`mailto:${i.co_agent_email}`,children:"Contact"})})]})]})]}),o.jsxs("div",{className:"mt-10 flex items-center gap-2 text-white/50 text-xs uppercase tracking-widest",children:[o.jsx("span",{className:"h-px w-8 bg-white/30"}),"Scroll to explore"]})]})})]}),ei("stats")&&o.jsx("section",{className:"border-b border-white/10 bg-neutral-950",children:o.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:TC,label:"Bedrooms",value:i.bedrooms},i.bathrooms&&{icon:lS,label:"Bathrooms",value:i.bathrooms},i.square_footage&&{icon:gG,label:"Interior",value:`${w2(i.square_footage)} sqft`},i.lot_size&&{icon:QO,label:"Lot Size",value:i.lot_size},i.year_built&&{icon:po,label:"Year Built",value:i.year_built},!i.year_built&&i.square_footage&&{icon:Fhe,label:"Price / sqft",value:`$${w2(Math.round(i.price/i.square_footage))}`}].filter(Boolean).slice(0,5).map((hn,gn)=>o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"h-10 w-10 rounded-full bg-white/5 border border-white/10 flex items-center justify-center shrink-0",children:o.jsx(hn.icon,{className:"h-4 w-4 text-white/70"})}),o.jsxs("div",{children:[o.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/50",children:hn.label}),o.jsx("p",{className:"font-display text-2xl text-white font-light",children:hn.value})]})]},gn))})}),o.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-16 grid lg:grid-cols-3 gap-12",children:[o.jsxs("div",{className:"lg:col-span-2 space-y-20",children:[ei("story")&&Zt&&o.jsxs("section",{id:"story",children:[o.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-3",children:"The Story"}),o.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light mb-6 text-white",children:"A closer look at this home"}),o.jsx("div",{className:"prose prose-invert prose-lg max-w-none",children:o.jsx("p",{className:"text-white/75 leading-relaxed whitespace-pre-wrap",children:Nn})}),Pr&&o.jsx("button",{onClick:()=>Ie(!Ne),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:Ne?"Show less":"Read more"}),o.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[o.jsxs(us,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[o.jsx(Eo,{className:"h-3 w-3 mr-1.5"}),Vte[i.property_type]]}),i.has_hoa&&o.jsx(us,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),i.mls_link&&o.jsx(Ut,{variant:"outline",size:"sm",asChild:!0,className:"ml-2 border-white/20 bg-white/5 text-white hover:bg-white/15",children:o.jsxs("a",{href:i.mls_link,target:"_blank",rel:"noopener noreferrer",children:[o.jsx(cS,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(ya||i.agent_notes&&i.agent_notes_public)&&o.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[o.jsx(Ss,{className:"h-4 w-4 text-amber-300"}),o.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),o.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',ya||i.agent_notes,'"']})]})]}),ei("gallery")&&Pt.length>1&&o.jsxs("section",{id:"gallery",children:[o.jsxs("div",{className:"flex items-end justify-between mb-6",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),o.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),o.jsxs("button",{onClick:()=>Ae(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Pt.length]})]}),o.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Pt.slice(0,7).map((hn,gn)=>{const Zr=["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"],oi=gn===6&&Pt.length>7;return o.jsxs("button",{onClick:()=>Ae(gn),className:`${Zr[gn]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[o.jsx("img",{src:hn.photo_url,alt:`Photo ${gn+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),oi&&o.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[o.jsx(bJ,{className:"h-6 w-6 mb-1"}),o.jsxs("span",{className:"font-medium",children:["+",Pt.length-7," more"]})]})]},hn.id)})})]}),ei("video")&&!((xa=i.video)!=null&&xa.playback_url)&<&&o.jsxs("section",{id:"video",children:[o.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),o.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),o.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:o.jsx("iframe",{src:lt,className:"absolute inset-0 h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Video Tour"})})]}),ei("video")&&((go=i.video)==null?void 0:go.playback_url)&&o.jsxs("section",{id:"video",children:[o.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),o.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),o.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:o.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"})})]}),ei("map")&&hr&&o.jsxs("section",{id:"map",children:[o.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Location"}),o.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]}),o.jsx("div",{className:"rounded-2xl overflow-hidden border border-white/10 shadow-2xl aspect-[16/10]",children:o.jsx("iframe",{src:hr,className:"w-full h-full grayscale-[.2] contrast-[1.05]",loading:"lazy",title:"Map"})}),o.jsxs("div",{className:"mt-4 flex items-center gap-2 text-white/60 text-sm",children:[o.jsx(na,{className:"h-4 w-4"}),i.property_address?`${i.property_address}, `:"",i.city,", ",i.state]})]}),ei("payment")&&o.jsxs("section",{id:"payment",children:[o.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Payment"}),o.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Estimate your monthly"}),o.jsxs("div",{className:"rounded-2xl border border-white/10 bg-gradient-to-br from-white/5 to-transparent p-6 sm:p-8",children:[o.jsxs("div",{className:"flex items-baseline gap-3 mb-8",children:[o.jsxs("p",{className:"font-display text-5xl sm:text-6xl font-light text-white",children:["$",w2(Math.round(wt))]}),o.jsx("p",{className:"text-white/60",children:"/ month"})]}),o.jsxs("div",{className:"grid sm:grid-cols-3 gap-8",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx(Mr,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),o.jsxs("span",{className:"text-white font-medium",children:[Te,"%"]})]}),o.jsx(xA,{value:[Te],onValueChange:hn=>be(hn[0]),min:0,max:50,step:1}),o.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",w2(Math.round(i.price*Te/100))," down"]})]}),o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx(Mr,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),o.jsxs("span",{className:"text-white font-medium",children:[We.toFixed(2),"%"]})]}),o.jsx(xA,{value:[We],onValueChange:hn=>rt(hn[0]),min:2,max:10,step:.125})]}),o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx(Mr,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),o.jsxs("span",{className:"text-white font-medium",children:[at," yr"]})]}),o.jsx(xA,{value:[at],onValueChange:hn=>Et(hn[0]),min:10,max:30,step:5})]})]}),o.jsx("p",{className:"text-xs text-white/40 mt-6",children:"Estimated principal & interest only. Taxes, insurance, and HOA not included."})]})]}),Oi.map(hn=>{const gn=hn.type,Zr=hn.data||{};if(gn==="extra_video"&&Zr.url){const oi=String(Zr.url).includes("youtu")?`https://www.youtube.com/embed/${String(Zr.url).split(/[/=]/).pop()}`:Zr.url;return o.jsxs("section",{children:[o.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:Zr.eyebrow||"Featured Video"}),o.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Zr.title||"Watch"}),o.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:o.jsx("iframe",{src:oi,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:Zr.title||"Video"})})]},hn.id)}return gn==="3d_tour"&&Zr.url?o.jsxs("section",{children:[o.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"3D Tour"}),o.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Zr.title||"Step inside"}),o.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:o.jsx("iframe",{src:Zr.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},hn.id):gn==="floor_plan"&&Zr.image_url?o.jsxs("section",{children:[o.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Floor Plan"}),o.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Zr.title||"Layout"}),o.jsx("img",{src:Zr.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},hn.id):gn==="testimonial"&&Zr.quote?o.jsxs("section",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-8",children:[o.jsxs("p",{className:"font-display italic text-2xl text-white/90 leading-relaxed",children:['"',Zr.quote,'"']}),Zr.author&&o.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",Zr.author]})]},hn.id):gn==="custom_cta"&&Zr.label?o.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:mi?`${mi}22`:"rgba(255,255,255,0.05)",border:`1px solid ${mi||"rgba(255,255,255,0.1)"}`},children:[Zr.title&&o.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:Zr.title}),o.jsx(Ut,{asChild:!0,size:"lg",style:mi?{background:mi}:void 0,children:o.jsx("a",{href:Zr.url||"#agent",children:Zr.label})})]},hn.id):null})]}),o.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[o.jsx(nYe,{listingId:i.id}),i.agent&&o.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[o.jsxs("div",{className:"flex items-start gap-4",children:[i.agent.avatar_url?o.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"}):o.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:o.jsx(gc,{className:"h-7 w-7 text-white/70"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Listing Agent"}),o.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:i.agent.name}),tr&&o.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:tr})]})]}),o.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[i.agent.phone&&o.jsx(Ut,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:o.jsxs("a",{href:`tel:${i.agent.phone}`,children:[o.jsx(zi,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),i.agent.email&&o.jsx(Ut,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:o.jsxs("a",{href:`mailto:${i.agent.email}`,children:[o.jsx(Bi,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),i.co_agent_name&&o.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[o.jsxs("div",{className:"flex items-start gap-4",children:[i.co_agent_photo_url?o.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"}):o.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:o.jsx(gc,{className:"h-7 w-7 text-white/70"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Co-Listing Agent"}),o.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:i.co_agent_name}),i.co_agent_brokerage&&o.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:i.co_agent_brokerage})]})]}),(i.co_agent_phone||i.co_agent_email)&&o.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[i.co_agent_phone&&o.jsx(Ut,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:o.jsxs("a",{href:`tel:${i.co_agent_phone}`,children:[o.jsx(zi,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),i.co_agent_email&&o.jsx(Ut,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:o.jsxs("a",{href:`mailto:${i.co_agent_email}`,children:[o.jsx(Bi,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),o.jsx("div",{id:"contact",className:"rounded-2xl border border-white/10 bg-white text-neutral-900 p-6 shadow-2xl",children:o.jsx(qte,{submitted:Se,activeTab:re,setActiveTab:se,firstName:m,setFirstName:x,lastName:_,setLastName:T,email:E,setEmail:C,phone:N,setPhone:R,message:D,setMessage:M,preferredDate:B,setPreferredDate:V,preferredTime:G,setPreferredTime:W,showingMode:X,setShowingMode:Q,isSubmitting:ue,onSubmit:Sr})})]})]}),o.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:[((Yr=i.agent)==null?void 0:Yr.phone)&&o.jsx(Ut,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15 flex-1",children:o.jsxs("a",{href:`tel:${i.agent.phone}`,children:[o.jsx(zi,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),o.jsxs(Ut,{onClick:()=>ge(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[o.jsx(Bhe,{className:"h-4 w-4 mr-1.5"}),"Request Tour"]})]}),o.jsx("footer",{className:"border-t border-white/10 py-10 mt-24 mb-16 lg:mb-0",children:o.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:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("img",{src:Ute,alt:"LevelUp",className:"h-6 opacity-80"}),o.jsxs("span",{children:["© ",new Date().getFullYear()," LevelUp"]})]}),o.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-white",children:"relevelup.com"})]})}),o.jsx(ro,{open:Oe!==null,onOpenChange:()=>Ae(null),children:o.jsxs($a,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[o.jsx(ul,{className:"sr-only",children:o.jsx(Go,{children:"Photo Gallery"})}),o.jsx("button",{onClick:()=>Ae(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:o.jsx(Ks,{className:"h-5 w-5"})}),Oe!==null&&Pt[Oe]&&o.jsxs("div",{className:"relative",children:[o.jsx("img",{src:Pt[Oe].photo_url,alt:`Photo ${Oe+1}`,className:"w-full max-h-[85vh] object-contain"}),Pt.length>1&&o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:nn,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:o.jsx($m,{className:"h-6 w-6"})}),o.jsx("button",{onClick:lr,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:o.jsx(th,{className:"h-6 w-6"})}),o.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:[Oe+1," / ",Pt.length]})]})]})]})}),o.jsx(ro,{open:we,onOpenChange:ge,children:o.jsxs($a,{className:"max-w-md p-0 bg-white text-neutral-900",children:[o.jsx(ul,{className:"sr-only",children:o.jsx(Go,{children:"Contact the agent"})}),o.jsx("div",{className:"p-6",children:o.jsx(qte,{submitted:Se,activeTab:re,setActiveTab:se,firstName:m,setFirstName:x,lastName:_,setLastName:T,email:E,setEmail:C,phone:N,setPhone:R,message:D,setMessage:M,preferredDate:B,setPreferredDate:V,preferredTime:G,setPreferredTime:W,showingMode:X,setShowingMode:Q,isSubmitting:ue,onSubmit:Sr})})]})})]})]})}function qte(t){const{submitted:e,activeTab:r,setActiveTab:n,firstName:i,setFirstName:a,lastName:c,setLastName:s,email:f,setEmail:m,phone:x,setPhone:_,message:T,setMessage:E,preferredDate:C,setPreferredDate:N,preferredTime:R,setPreferredTime:D,showingMode:M,setShowingMode:B,isSubmitting:V,onSubmit:G}=t;return e?o.jsxs("div",{className:"text-center py-6",children:[o.jsx("div",{className:"h-14 w-14 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:o.jsx(Ao,{className:"h-7 w-7 text-emerald-600"})}),o.jsx("p",{className:"font-display text-2xl font-medium mb-1",children:r==="showing"?"Showing request sent!":"Thanks — you're all set!"}),o.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."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"mb-4",children:[o.jsx("p",{className:"text-[10px] uppercase tracking-[0.25em] text-neutral-500 mb-1",children:"Interested?"}),o.jsx("h3",{className:"font-display text-2xl font-medium",children:"Talk to the listing agent"})]}),o.jsxs(Q9,{value:r,onValueChange:W=>n(W),children:[o.jsxs(ZM,{className:"grid w-full grid-cols-2 mb-4",children:[o.jsxs(_m,{value:"info",className:"gap-1.5",children:[o.jsx(rp,{className:"h-3.5 w-3.5"})," Get Info"]}),o.jsxs(_m,{value:"showing",className:"gap-1.5",children:[o.jsx(Bhe,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),o.jsxs("form",{onSubmit:G,className:"space-y-3",children:[o.jsxs(Ny,{value:"showing",className:"mt-0 space-y-3",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"preferredDate",children:"Preferred Date *"}),o.jsx(Ur,{id:"preferredDate",type:"date",value:C,onChange:W=>N(W.target.value),min:new Date().toISOString().split("T")[0],required:r==="showing"})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"preferredTime",children:"Preferred Time"}),o.jsxs(Ba,{value:R,onValueChange:D,children:[o.jsx(ja,{id:"preferredTime",children:o.jsx(za,{placeholder:"Any time"})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"morning",children:"Morning (9am–12pm)"}),o.jsx(wn,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),o.jsx(wn,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"showingMode",children:"Tour Type"}),o.jsxs(Ba,{value:M,onValueChange:W=>B(W),children:[o.jsx(ja,{id:"showingMode",children:o.jsx(za,{})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"in_person",children:"🏡 In-person showing"}),o.jsx(wn,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),o.jsx(wn,{value:"either",children:"Either works for me"})]})]})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"firstName",children:"First Name *"}),o.jsx(Ur,{id:"firstName",value:i,onChange:W=>a(W.target.value),required:!0})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"lastName",children:"Last Name"}),o.jsx(Ur,{id:"lastName",value:c,onChange:W=>s(W.target.value)})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"email",children:"Email *"}),o.jsx(Ur,{id:"email",type:"email",value:f,onChange:W=>m(W.target.value),required:!0})]}),o.jsxs("div",{children:[o.jsxs(Mr,{htmlFor:"phone",children:["Phone ",r==="showing"&&"*"]}),o.jsx(Ur,{id:"phone",type:"tel",value:x,onChange:W=>_(W.target.value),required:r==="showing"})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"message",children:r==="showing"?"Anything else?":"Message (optional)"}),o.jsx(hd,{id:"message",value:T,onChange:W=>E(W.target.value),rows:2})]}),o.jsx(Ut,{type:"submit",disabled:V,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:V?"Sending…":r==="showing"?"Request Showing":"Get More Info"}),o.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const mYe=Object.freeze(Object.defineProperty({__proto__:null,default:s7,toVideoEmbedUrl:v0e},Symbol.toStringTag,{value:"Module"})),Gte="/assets/levelup-logo-white-C2RAgAoG.png",gYe="/assets/listings-hero-noir-BHCJrhvU.jpg";var b0e={exports:{}};(function(t,e){(function(r,n){t.exports=n()})(Wl,function(){let r,n,i;function a(s,f){if(!r)r=f;else if(!n)n=f;else{const m={};r(m),i=f(m);const x="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 = {}; ("+r+")(sharedChunk); ("+n+")(undefined, sharedChunk); self.onerror = null;";typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(i.workerUrl=window.URL.createObjectURL(new Blob([x],{type:"text/javascript"})))}}a(["exports"],function(s){var f=1e-6,m=typeof Float32Array<"u"?Float32Array:Array;function x(h,l){var u=l[0],p=l[1],y=l[2],b=l[3],S=u*b-y*p;return S?(h[0]=b*(S=1/S),h[1]=-p*S,h[2]=-y*S,h[3]=u*S,h):null}function _(){var h=new m(9);return m!=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 T(h,l){var u=l[0],p=l[1],y=l[2],b=l[3],S=l[4],k=l[5],j=l[6],O=l[7],z=l[8];return h[0]=S*z-k*O,h[1]=y*O-p*z,h[2]=p*k-y*S,h[3]=k*j-b*z,h[4]=u*z-y*j,h[5]=y*b-u*k,h[6]=b*O-S*j,h[7]=p*j-u*O,h[8]=u*S-p*b,h}function E(h,l,u){var p=l[0],y=l[1],b=l[2],S=l[3],k=l[4],j=l[5],O=l[6],z=l[7],U=l[8],q=u[0],K=u[1],Z=u[2],J=u[3],ne=u[4],ae=u[5],he=u[6],ce=u[7],ye=u[8];return h[0]=q*p+K*S+Z*O,h[1]=q*y+K*k+Z*z,h[2]=q*b+K*j+Z*U,h[3]=J*p+ne*S+ae*O,h[4]=J*y+ne*k+ae*z,h[5]=J*b+ne*j+ae*U,h[6]=he*p+ce*S+ye*O,h[7]=he*y+ce*k+ye*z,h[8]=he*b+ce*j+ye*U,h}function C(){var h=new m(16);return m!=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 N(h){var l=new m(16);return l[0]=h[0],l[1]=h[1],l[2]=h[2],l[3]=h[3],l[4]=h[4],l[5]=h[5],l[6]=h[6],l[7]=h[7],l[8]=h[8],l[9]=h[9],l[10]=h[10],l[11]=h[11],l[12]=h[12],l[13]=h[13],l[14]=h[14],l[15]=h[15],l}function R(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 D(h,l){var u=l[0],p=l[1],y=l[2],b=l[3],S=l[4],k=l[5],j=l[6],O=l[7],z=l[8],U=l[9],q=l[10],K=l[11],Z=l[12],J=l[13],ne=l[14],ae=l[15],he=u*k-p*S,ce=u*j-y*S,ye=u*O-b*S,Ee=p*j-y*k,Ce=p*O-b*k,He=y*O-b*j,$e=z*J-U*Z,Ge=z*ne-q*Z,Ue=z*ae-K*Z,Ve=U*ne-q*J,yt=U*ae-K*J,bt=q*ae-K*ne,kt=he*bt-ce*yt+ye*Ve+Ee*Ue-Ce*Ge+He*$e;return kt?(h[0]=(k*bt-j*yt+O*Ve)*(kt=1/kt),h[1]=(y*yt-p*bt-b*Ve)*kt,h[2]=(J*He-ne*Ce+ae*Ee)*kt,h[3]=(q*Ce-U*He-K*Ee)*kt,h[4]=(j*Ue-S*bt-O*Ge)*kt,h[5]=(u*bt-y*Ue+b*Ge)*kt,h[6]=(ne*ye-Z*He-ae*ce)*kt,h[7]=(z*He-q*ye+K*ce)*kt,h[8]=(S*yt-k*Ue+O*$e)*kt,h[9]=(p*Ue-u*yt-b*$e)*kt,h[10]=(Z*Ce-J*ye+ae*he)*kt,h[11]=(U*ye-z*Ce-K*he)*kt,h[12]=(k*Ge-S*Ve-j*$e)*kt,h[13]=(u*Ve-p*Ge+y*$e)*kt,h[14]=(J*ce-Z*Ee-ne*he)*kt,h[15]=(z*Ee-U*ce+q*he)*kt,h):null}function M(h,l,u){var p=l[0],y=l[1],b=l[2],S=l[3],k=l[4],j=l[5],O=l[6],z=l[7],U=l[8],q=l[9],K=l[10],Z=l[11],J=l[12],ne=l[13],ae=l[14],he=l[15],ce=u[0],ye=u[1],Ee=u[2],Ce=u[3];return h[0]=ce*p+ye*k+Ee*U+Ce*J,h[1]=ce*y+ye*j+Ee*q+Ce*ne,h[2]=ce*b+ye*O+Ee*K+Ce*ae,h[3]=ce*S+ye*z+Ee*Z+Ce*he,h[4]=(ce=u[4])*p+(ye=u[5])*k+(Ee=u[6])*U+(Ce=u[7])*J,h[5]=ce*y+ye*j+Ee*q+Ce*ne,h[6]=ce*b+ye*O+Ee*K+Ce*ae,h[7]=ce*S+ye*z+Ee*Z+Ce*he,h[8]=(ce=u[8])*p+(ye=u[9])*k+(Ee=u[10])*U+(Ce=u[11])*J,h[9]=ce*y+ye*j+Ee*q+Ce*ne,h[10]=ce*b+ye*O+Ee*K+Ce*ae,h[11]=ce*S+ye*z+Ee*Z+Ce*he,h[12]=(ce=u[12])*p+(ye=u[13])*k+(Ee=u[14])*U+(Ce=u[15])*J,h[13]=ce*y+ye*j+Ee*q+Ce*ne,h[14]=ce*b+ye*O+Ee*K+Ce*ae,h[15]=ce*S+ye*z+Ee*Z+Ce*he,h}function B(h,l,u){var p,y,b,S,k,j,O,z,U,q,K,Z,J=u[0],ne=u[1],ae=u[2];return l===h?(h[12]=l[0]*J+l[4]*ne+l[8]*ae+l[12],h[13]=l[1]*J+l[5]*ne+l[9]*ae+l[13],h[14]=l[2]*J+l[6]*ne+l[10]*ae+l[14],h[15]=l[3]*J+l[7]*ne+l[11]*ae+l[15]):(y=l[1],b=l[2],S=l[3],k=l[4],j=l[5],O=l[6],z=l[7],U=l[8],q=l[9],K=l[10],Z=l[11],h[0]=p=l[0],h[1]=y,h[2]=b,h[3]=S,h[4]=k,h[5]=j,h[6]=O,h[7]=z,h[8]=U,h[9]=q,h[10]=K,h[11]=Z,h[12]=p*J+k*ne+U*ae+l[12],h[13]=y*J+j*ne+q*ae+l[13],h[14]=b*J+O*ne+K*ae+l[14],h[15]=S*J+z*ne+Z*ae+l[15]),h}function V(h,l,u){var p=u[0],y=u[1],b=u[2];return h[0]=l[0]*p,h[1]=l[1]*p,h[2]=l[2]*p,h[3]=l[3]*p,h[4]=l[4]*y,h[5]=l[5]*y,h[6]=l[6]*y,h[7]=l[7]*y,h[8]=l[8]*b,h[9]=l[9]*b,h[10]=l[10]*b,h[11]=l[11]*b,h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15],h}function G(h,l,u){var p=Math.sin(u),y=Math.cos(u),b=l[4],S=l[5],k=l[6],j=l[7],O=l[8],z=l[9],U=l[10],q=l[11];return l!==h&&(h[0]=l[0],h[1]=l[1],h[2]=l[2],h[3]=l[3],h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15]),h[4]=b*y+O*p,h[5]=S*y+z*p,h[6]=k*y+U*p,h[7]=j*y+q*p,h[8]=O*y-b*p,h[9]=z*y-S*p,h[10]=U*y-k*p,h[11]=q*y-j*p,h}function W(h,l,u){var p=Math.sin(u),y=Math.cos(u),b=l[0],S=l[1],k=l[2],j=l[3],O=l[8],z=l[9],U=l[10],q=l[11];return l!==h&&(h[4]=l[4],h[5]=l[5],h[6]=l[6],h[7]=l[7],h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15]),h[0]=b*y-O*p,h[1]=S*y-z*p,h[2]=k*y-U*p,h[3]=j*y-q*p,h[8]=b*p+O*y,h[9]=S*p+z*y,h[10]=k*p+U*y,h[11]=j*p+q*y,h}function X(h,l,u){var p=Math.sin(u),y=Math.cos(u),b=l[0],S=l[1],k=l[2],j=l[3],O=l[4],z=l[5],U=l[6],q=l[7];return l!==h&&(h[8]=l[8],h[9]=l[9],h[10]=l[10],h[11]=l[11],h[12]=l[12],h[13]=l[13],h[14]=l[14],h[15]=l[15]),h[0]=b*y+O*p,h[1]=S*y+z*p,h[2]=k*y+U*p,h[3]=j*y+q*p,h[4]=O*y-b*p,h[5]=z*y-S*p,h[6]=U*y-k*p,h[7]=q*y-j*p,h}function Q(h,l){return h[0]=l[0],h[1]=0,h[2]=0,h[3]=0,h[4]=0,h[5]=l[1],h[6]=0,h[7]=0,h[8]=0,h[9]=0,h[10]=l[2],h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,h}function re(h,l,u){var p,y,b,S=u[0],k=u[1],j=u[2],O=Math.sqrt(S*S+k*k+j*j);return O0&&(b=1/Math.sqrt(b)),h[0]=l[0]*b,h[1]=l[1]*b,h[2]=l[2]*b,h}function Pt(h,l){return h[0]*l[0]+h[1]*l[1]+h[2]*l[2]}function er(h,l,u){var p=l[0],y=l[1],b=l[2],S=u[0],k=u[1],j=u[2];return h[0]=y*j-b*k,h[1]=b*S-p*j,h[2]=p*k-y*S,h}function wt(h,l,u,p){var y=l[0],b=l[1],S=l[2];return h[0]=y+p*(u[0]-y),h[1]=b+p*(u[1]-b),h[2]=S+p*(u[2]-S),h}function or(h,l,u){var p=l[0],y=l[1],b=l[2],S=u[3]*p+u[7]*y+u[11]*b+u[15];return h[0]=(u[0]*p+u[4]*y+u[8]*b+u[12])/(S=S||1),h[1]=(u[1]*p+u[5]*y+u[9]*b+u[13])/S,h[2]=(u[2]*p+u[6]*y+u[10]*b+u[14])/S,h}function Sr(h,l,u){var p=l[0],y=l[1],b=l[2];return h[0]=p*u[0]+y*u[3]+b*u[6],h[1]=p*u[1]+y*u[4]+b*u[7],h[2]=p*u[2]+y*u[5]+b*u[8],h}function nn(h,l,u){var p=u[0],y=u[1],b=u[2],S=u[3],k=l[0],j=l[1],O=l[2],z=y*O-b*j,U=b*k-p*O,q=p*j-y*k;return h[0]=k+S*(z+=z)+y*(q+=q)-b*(U+=U),h[1]=j+S*U+b*z-p*q,h[2]=O+S*q+p*U-y*z,h}function lr(h){return h[0]=0,h[1]=0,h[2]=0,h}function yr(h,l){return h[0]===l[0]&&h[1]===l[1]&&h[2]===l[2]}var tr=Ne,yn=Ie,lt=Oe;function At(){var h=new m(4);return m!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0,h[3]=0),h}function Ot(h,l,u){return h[0]=l[0]*u,h[1]=l[1]*u,h[2]=l[2]*u,h[3]=l[3]*u,h}function dr(h,l){var u=l[0],p=l[1],y=l[2],b=l[3],S=u*u+p*p+y*y+b*b;return S>0&&(S=1/Math.sqrt(S)),h[0]=u*S,h[1]=p*S,h[2]=y*S,h[3]=b*S,h}function cr(h,l){return h[0]*l[0]+h[1]*l[1]+h[2]*l[2]+h[3]*l[3]}function hr(h,l,u){var p=l[0],y=l[1],b=l[2],S=l[3];return h[0]=u[0]*p+u[4]*y+u[8]*b+u[12]*S,h[1]=u[1]*p+u[5]*y+u[9]*b+u[13]*S,h[2]=u[2]*p+u[6]*y+u[10]*b+u[14]*S,h[3]=u[3]*p+u[7]*y+u[11]*b+u[15]*S,h}function Zt(){var h=new m(4);return m!=Float32Array&&(h[0]=0,h[1]=0,h[2]=0),h[3]=1,h}function Pr(h){return h[0]=0,h[1]=0,h[2]=0,h[3]=1,h}function Nn(h,l,u){u*=.5;var p=l[0],y=l[1],b=l[2],S=l[3],k=Math.sin(u),j=Math.cos(u);return h[0]=p*j+S*k,h[1]=y*j+b*k,h[2]=b*j-y*k,h[3]=S*j-p*k,h}function ai(h,l,u){u*=.5;var p=l[0],y=l[1],b=l[2],S=l[3],k=Math.sin(u),j=Math.cos(u);return h[0]=p*j-b*k,h[1]=y*j+S*k,h[2]=b*j+p*k,h[3]=S*j-y*k,h}Se(),At();var ei,Oi,ya,mi=dr,ia=(ei=Se(),Oi=Ae(1,0,0),ya=Ae(0,1,0),function(h,l,u){var p=Pt(l,u);return p<-.999999?(er(ei,Oi,l),lt(ei)<1e-6&&er(ei,ya,l),mt(ei,ei),function(y,b,S){S*=.5;var k=Math.sin(S);y[0]=k*b[0],y[1]=k*b[1],y[2]=k*b[2],y[3]=Math.cos(S)}(h,ei,Math.PI),h):p>.999999?(h[0]=0,h[1]=0,h[2]=0,h[3]=1,h):(er(ei,l,u),h[0]=ei[0],h[1]=ei[1],h[2]=ei[2],h[3]=1+p,mi(h,h))});function jr(){var h=new m(2);return m!=Float32Array&&(h[0]=0,h[1]=0),h}function Mn(h,l){var u=new m(2);return u[0]=h,u[1]=l,u}function As(h,l,u){return h[0]=l,h[1]=u,h}function xa(h,l,u){return h[0]=l[0]+u[0],h[1]=l[1]+u[1],h}function go(h,l,u){return h[0]=l[0]-u[0],h[1]=l[1]-u[1],h}function Yr(h,l,u){return h[0]=l[0]*u,h[1]=l[1]*u,h}function hn(h){var l=h[0],u=h[1];return Math.sqrt(l*l+u*u)}function gn(h,l){var u=l[0],p=l[1],y=u*u+p*p;return y>0&&(y=1/Math.sqrt(y)),h[0]=l[0]*y,h[1]=l[1]*y,h}function Zr(h,l){return h[0]*l[0]+h[1]*l[1]}Zt(),Zt(),_();var oi,Jr,Fn=go;function es(h){return h&&h.__esModule&&Object.prototype.hasOwnProperty.call(h,"default")?h.default:h}jr();var fl=function(){if(Jr)return oi;function h(l,u,p,y){this.cx=3*l,this.bx=3*(p-l)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*u,this.by=3*(y-u)-this.cy,this.ay=1-this.cy-this.by,this.p1x=l,this.p1y=u,this.p2x=p,this.p2y=y}return Jr=1,oi=h,h.prototype={sampleCurveX:function(l){return((this.ax*l+this.bx)*l+this.cx)*l},sampleCurveY:function(l){return((this.ay*l+this.by)*l+this.cy)*l},sampleCurveDerivativeX:function(l){return(3*this.ax*l+2*this.bx)*l+this.cx},solveCurveX:function(l,u){if(u===void 0&&(u=1e-6),l<0)return 0;if(l>1)return 1;for(var p=l,y=0;y<8;y++){var b=this.sampleCurveX(p)-l;if(Math.abs(b)b?k=p:j=p,p=.5*(j-k)+k;return p},solve:function(l,u){return this.sampleCurveY(this.solveCurveX(l,u))}},oi}(),Wo=es(fl);function Mt(h,l){this.x=h,this.y=l}function Po(h,l){if(Array.isArray(h)){if(!Array.isArray(l)||h.length!==l.length)return!1;for(let u=0;u=1)return 1;const l=h*h,u=l*h;return 4*(h<.5?u:3*(h-l)+u-.75)}function ct(h,l,u,p){const y=new Wo(h,l,u,p);return function(b){return y.solve(b)}}const de=ct(.25,.1,.25,1);function fe(h,l,u){return Math.min(u,Math.max(l,h))}function Me(h,l,u){return(u=fe((u-h)/(l-h),0,1))*u*(3-2*u)}function Ye(h,l,u){const p=u-l,y=((h-l)%p+p)%p+l;return y===l?u:y}function Je(h,l,u){if(!h.length)return u(null,[]);let p=h.length;const y=new Array(h.length);let b=null;h.forEach((S,k)=>{l(S,(j,O)=>{j&&(b=j),y[k]=O,--p===0&&u(b,y)})})}let tt=1;function dt(){return tt++}function it(h){return h<=1?1:Math.pow(2,Math.ceil(Math.log2(h)))}function ht(h,l){h.forEach(u=>{l[u]&&(l[u]=l[u].bind(l))})}function zt(h,l,u){const p={};for(const y in h)p[y]=l.call(this,h[y],y,h);return p}function Nt(h,l,u){const p={};for(const y in h)l.call(this,h[y],y,h)&&(p[y]=h[y]);return p}function fr(h){return Array.isArray(h)?h.map(fr):typeof h=="object"&&h?zt(h,fr):h}function Fr(h,l){for(let u=0;u=0)return!0;return!1}const qr={};function Br(h){qr[h]||(typeof console<"u"&&console.warn(h),qr[h]=!0)}function an(h,l,u){return(u.y-h.y)*(l.x-h.x)>(l.y-h.y)*(u.x-h.x)}function kn(h){let l=0;for(let u,p,y=0,b=h.length,S=b-1;y@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(u,p,y,b)=>{const S=y||b;return l[p]=!S||S.toLowerCase(),""}),l["max-age"]){const u=parseInt(l["max-age"],10);isNaN(u)?delete l["max-age"]:l["max-age"]=u}return l}let Cs,gs=null;function yi(h,l){return[h[4*l],h[4*l+1],h[4*l+2],h[4*l+3]]}function is(h,l,u,p){for(;l>1;h[y]>1;h[y]<=p?l=y+1:u=y}return l}function ji(h){return h>0?1/(1.001-h):1+h}function ss(h){return h>0?1-1/(1.001-h):-h}function ys(h,l,u){return(h-l.min)*(u.max-u.min)/(l.max-l.min)+u.min}const Dn={API_URL:"https://api.mapbox.com",get API_URL_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/|\?|$)/i},get API_TILEJSON_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/v[0-9]*\/.*\.json.*$)/i},get API_SPRITE_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*\/sprite.*\..*$)/i},get API_FONTS_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/fonts\/v[0-9]*\/)(.*\.pbf.*$)/i},get API_STYLE_REGEX(){return/^((https?:)?\/\/)?([^\/]+\.)?mapbox\.c(n|om)(\/styles\/v[0-9]*\/)(.*$)/i},get API_CDN_URL_REGEX(){return/^((https?:)?\/\/)?api\.mapbox\.c(n|om)(\/mapbox-gl-js\/)(.*$)/i},get EVENTS_URL(){if(!Dn.API_URL)return null;try{const h=new URL(Dn.API_URL);return h.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":h.hostname==="api.mapbox.com"?"https://events.mapbox.com/events/v2":null}catch{return null}},SESSION_PATH:"/map-sessions/v1",FEEDBACK_URL:"https://apps.mapbox.com/feedback",TILE_URL_VERSION:"v4",RASTER_URL_PREFIX:"raster/v1",RASTERARRAYS_URL_PREFIX:"rasterarrays/v1",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,DEFAULT_STYLE:"mapbox://styles/mapbox/standard",MAX_PARALLEL_IMAGE_REQUESTS:16,DRACO_URL:"/mapbox-gl-js/draco_decoder_gltf_v1.5.6.wasm",MESHOPT_URL:"/mapbox-gl-js/meshopt_base_v0.20.wasm",MESHOPT_SIMD_URL:"/mapbox-gl-js/meshopt_simd_v0.20.wasm",BUILDING_GEN_URL:"/mapbox-gl-js/building-gen/building_gen_v1.2.4.wasm",GLYPHS_URL:"mapbox://fonts/mapbox/{fontstack}/{range}.pbf",TILES3D_URL_PREFIX:"3dtiles/v1",TILE_PROVIDER_URLS:Object.assign(Object.create(null),{pmtiles:"/mapbox-gl-js/mapbox-gl-pmtiles-provider-v0.0.1.js"})};function _a(){return new URL(Dn.DRACO_URL,Dn.API_URL).href}function yo(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(Cs===void 0){if(typeof WebAssembly!="object")return!1;const h=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]);Cs=WebAssembly.validate(h)}return Cs}()?Dn.MESHOPT_SIMD_URL:Dn.MESHOPT_URL,Dn.API_URL).href}function oo(){return new URL(Dn.BUILDING_GEN_URL,Dn.API_URL).href}function Jl(h){return Dn.API_URL_REGEX.test(h)}function ec(h){return Dn.API_SPRITE_REGEX.test(h)}let fd,pl,tc,pd,vc,md;function ru(){return fd==null&&(fd=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),fd}const Pl={now:()=>pd!==void 0?pd:performance.now(),setNow(h){pd=h},restoreNow(){pd=void 0},frame(h){const l=requestAnimationFrame(h);return{cancel:()=>cancelAnimationFrame(l)}},getImageData(h,l=0){const{width:u,height:p}=h;vc||(vc=document.createElement("canvas"));const y=vc.getContext("2d",{willReadFrequently:!0});if(!y)throw new Error("failed to create canvas 2d context");return(u>vc.width||p>vc.height)&&(vc.width=u,vc.height=p),y.clearRect(-l,-l,u+2*l,p+2*l),y.drawImage(h,0,0,u,p),y.getImageData(-l,-l,u+2*l,p+2*l)},resolveURL:h=>(pl||(pl=document.createElement("a")),pl.href=h,pl.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(tc==null&&(tc=window.matchMedia("(prefers-reduced-motion: reduce)")),tc.matches)},hasCanvasFingerprintNoise(){if(md!==void 0)return md;if(!ru())return md=!1,!1;const h=new OffscreenCanvas(85,1),l=h.getContext("2d",{willReadFrequently:!0});let u=0;for(let y=0;y0?`?${b}`:""}`}const yp="mapbox-tiles";let Z0=500,X0=50;const WS=["language","worldview","jobid"];let gd;function mj(){try{return caches}catch{}}function Q0(){const h=mj();h&&gd==null&&(gd=h.open(yp))}let KS=1/0;const J0={supported:!1,testSupport:function(h){!YS&&Km&&(nu?Ym(h):xp=h)}};let xp,Km,YS=!1,nu=!1;const ZS=typeof self<"u"?self:{};function Ym(h){const l=h.createTexture();h.bindTexture(h.TEXTURE_2D,l);try{if(h.texImage2D(h.TEXTURE_2D,0,h.RGBA,h.RGBA,h.UNSIGNED_BYTE,Km),h.isContextLost())return;J0.supported=!0}catch{}h.deleteTexture(l),YS=!0}ZS.document&&(Km=ZS.document.createElement("img"),Km.onload=function(){xp&&Ym(xp),xp=null,nu=!0},Km.onerror=function(){YS=!0,xp=null},Km.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const _x={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(_x);class XS extends Error{constructor(l,u,p){u===401&&Jl(p)&&(l+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(l),this.status=u,this.url=p}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function QS(h){return typeof h=="object"&&h!==null&&"status"in h&&h.status===404}const Xn=Ci()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Zm=function(h,l){return/^file:/.test(u=h.url)||/^file:/.test(Xn())&&!/^\w+:/.test(u)?function(p,y){const b=new XMLHttpRequest;b.open(p.method||"GET",p.url,!0),p.type==="arrayBuffer"&&(b.responseType="arraybuffer");for(const S in p.headers)b.setRequestHeader(S,p.headers[S]);return p.type==="json"&&(b.responseType="text",b.setRequestHeader("Accept","application/json")),b.withCredentials=p.credentials==="include",b.onerror=()=>{y(new Error(b.statusText))},b.onload=()=>{if((b.status>=200&&b.status<300||b.status===0)&&b.response!==null){let S=b.response;if(p.type==="json")try{S=JSON.parse(b.response)}catch(j){return y(j)}const k=new Headers;b.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(j=>{const O=j.split(": "),z=O.shift(),U=O.join(": ");k.append(z,U)}),y(null,S,k)}else y(new XS(b.statusText,b.status,p.url))},b.send(p.body),{cancel:()=>b.abort()}}(h,l):function(p,y){const b=new AbortController,S=new Request(p.url,{method:p.method||"GET",body:p.body,credentials:p.credentials,headers:p.headers,referrer:Xn(),referrerPolicy:p.referrerPolicy,signal:b.signal});let k=!1,j=!1;const O=(z=S.url).indexOf("sku=")>0&&Jl(z);var z;p.type==="json"&&S.headers.set("Accept","application/json");const U=(K,Z,J)=>{if(j)return;if(K&&K.message!=="SecurityError"&&Br(K.toString()),Z&&J)return q(Z);const ne=Date.now();fetch(S).then(ae=>{if(ae.ok){const he=O?ae.clone():null;return q(ae,he,ne)}return y(new XS(ae.statusText,ae.status,p.url))}).catch(ae=>{ae.name!=="AbortError"&&y(new Error(`${ae.message} ${p.url}`))})},q=(K,Z,J)=>{(p.type==="arrayBuffer"?K.arrayBuffer():p.type==="json"?K.json():K.text()).then(ne=>{j||(Z&&J&&function(ae,he,ce){if(Q0(),gd==null)return;const ye=Ds(he.headers.get("cache-control")||"");if(ye["no-store"])return;const Ee={status:he.status,statusText:he.statusText,headers:new Headers};he.headers.forEach((Ue,Ve)=>Ee.headers.set(Ve,Ue)),ye["max-age"]&&Ee.headers.set("Expires",new Date(ce+1e3*ye["max-age"]).toUTCString());const Ce=Ee.headers.get("expires");if(!Ce||new Date(Ce).getTime()-ce<42e4)return;let He=HS(ae.url,{persistentParams:WS});if(he.status===206){const Ue=ae.headers.get("Range");if(!Ue)return;Ee.status=200,He=xx(He,{range:Ue})}const $e=new Response((Ge=he.status)!==200&&Ge!==404&&[101,103,204,205,304].includes(Ge)?null:he.body,Ee);var Ge;Q0(),gd!=null&&gd.then(Ue=>Ue.put(He,$e)).catch(Ue=>Br(Ue.message))}(S,Z,J),k=!0,y(null,ne,K.headers))}).catch(ne=>{j||y(new Error(ne.message))})};return O?function(K,Z){if(Q0(),gd==null)return Z(null);gd.then(J=>{let ne=HS(K.url,{persistentParams:WS});const ae=K.headers.get("Range");ae&&(ne=xx(ne,{range:ae})),J.match(ne).then(he=>{const ce=function(ye){if(!ye)return!1;const Ee=new Date(ye.headers.get("expires")||0),Ce=Ds(ye.headers.get("cache-control")||"");return Number(Ee)>Date.now()&&!Ce["no-cache"]}(he);J.delete(ne).catch(Z),ce&&J.put(ne,he.clone()).catch(Z),Z(null,he,ce)}).catch(Z)}).catch(Z)}(S,U):U(null,null),{cancel:()=>{j=!0,k||b.abort()}}}(h,l);var u},Xm=function(h,l){return Zm(Object.assign(h,{type:"arrayBuffer"}),l)};function f3(h){const l=document.createElement("a");return l.href=h,l.protocol===location.protocol&&l.host===location.host}let ev,sf;ev=[],sf=0;const Qm=function(h,l){if(J0.supported&&(h.headers||(h.headers={}),h.headers.accept="image/webp,*/*"),sf>=Dn.MAX_PARALLEL_IMAGE_REQUESTS){const b={requestParameters:h,callback:l,cancelled:!1,cancel(){this.cancelled=!0}};return ev.push(b),b}sf++;let u=!1;const p=()=>{if(!u)for(u=!0,sf--;ev.length&&sf{p(),b?l(b):S&&function(j,O){const z=new Blob([new Uint8Array(j)],{type:"image/png"});createImageBitmap(z).then(U=>{O(null,U)}).catch(U=>{O(new Error(`Could not load image because of ${U.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(S,(j,O)=>l(j,O,k))});return{cancel:()=>{y.cancel(),p()}}};var vx,tv,gj,_p={exports:{}},yj={exports:{}},JS={exports:{}},p3=function(){if(gj)return _p.exports;gj=1;var h=(vx||(vx=1,yj.exports=function(u,p){var y,b,S,k,j,O,z,U;for(b=u.length-(y=3&u.length),S=p,j=3432918353,O=461845907,U=0;U>>16)*j&65535)<<16)&4294967295)<<15|z>>>17))*O+(((z>>>16)*O&65535)<<16)&4294967295)<<13|S>>>19))+((5*(S>>>16)&65535)<<16)&4294967295))+(((k>>>16)+58964&65535)<<16);switch(z=0,y){case 3:z^=(255&u.charCodeAt(U+2))<<16;case 2:z^=(255&u.charCodeAt(U+1))<<8;case 1:S^=z=(65535&(z=(z=(65535&(z^=255&u.charCodeAt(U)))*j+(((z>>>16)*j&65535)<<16)&4294967295)<<15|z>>>17))*O+(((z>>>16)*O&65535)<<16)&4294967295}return S^=u.length,S=2246822507*(65535&(S^=S>>>16))+((2246822507*(S>>>16)&65535)<<16)&4294967295,S=3266489909*(65535&(S^=S>>>13))+((3266489909*(S>>>16)&65535)<<16)&4294967295,(S^=S>>>16)>>>0}),yj.exports),l=(tv||(tv=1,JS.exports=function(u,p){for(var y,b=u.length,S=p^b,k=0;b>=4;)y=1540483477*(65535&(y=255&u.charCodeAt(k)|(255&u.charCodeAt(++k))<<8|(255&u.charCodeAt(++k))<<16|(255&u.charCodeAt(++k))<<24))+((1540483477*(y>>>16)&65535)<<16),S=1540483477*(65535&S)+((1540483477*(S>>>16)&65535)<<16)^(y=1540483477*(65535&(y^=y>>>24))+((1540483477*(y>>>16)&65535)<<16)),b-=4,++k;switch(b){case 3:S^=(255&u.charCodeAt(k+2))<<16;case 2:S^=(255&u.charCodeAt(k+1))<<8;case 1:S=1540483477*(65535&(S^=255&u.charCodeAt(k)))+((1540483477*(S>>>16)&65535)<<16)}return S=1540483477*(65535&(S^=S>>>13))+((1540483477*(S>>>16)&65535)<<16),(S^=S>>>15)>>>0}),JS.exports);return _p.exports=h,_p.exports.murmur3=h,_p.exports.murmur2=l,_p.exports}(),af=es(p3);class Nu{constructor(l,...u){Object.assign(this,u[0]||{}),this.type=l}}class Jm extends Nu{constructor(l,u={}){super("error",Object.assign({error:l},u))}}function iu(h,l,u){u[h]&&u[h].indexOf(l)!==-1||(u[h]=u[h]||[],u[h].push(l))}function rv(h,l,u){if(u&&u[h]){const p=u[h].indexOf(l);p!==-1&&u[h].splice(p,1)}}class bx{on(l,u){return this._listeners=this._listeners||{},iu(l,u,this._listeners),this}off(l,u){return rv(l,u,this._listeners),rv(l,u,this._oneTimeListeners),this}once(l,u){return u?(this._oneTimeListeners=this._oneTimeListeners||{},iu(l,u,this._oneTimeListeners),this):new Promise(p=>{this.once(l,p)})}fire(l,u){const p=typeof l=="string"?new Nu(l,u):l,y=p.type;if(this.listens(y)){p.target=this;const b=this._listeners&&this._listeners[y]?this._listeners[y].slice():[];for(const j of b)j.call(this,p);const S=this._oneTimeListeners&&this._oneTimeListeners[y]?this._oneTimeListeners[y].slice():[];for(const j of S)rv(y,j,this._oneTimeListeners),j.call(this,p);const k=this._eventedParent;if(k){const j=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(p,j),k.fire(p)}}else p instanceof Jm&&console.error(p.error);return this}listens(l){return!!(this._listeners&&this._listeners[l]&&this._listeners[l].length>0||this._oneTimeListeners&&this._oneTimeListeners[l]&&this._oneTimeListeners[l].length>0||this._eventedParent&&this._eventedParent.listens(l))}setEventedParent(l,u){return this._eventedParent=l,this._eventedParentData=u,this}}class rc{constructor(l){typeof l=="string"?this.name=l:(this.name=l.name,this.iconsetId=l.iconsetId)}static from(l){return new rc(l)}static toString(l){return l.iconsetId?`${l.name}${l.iconsetId}`:l.name}static parse(l){const[u,p]=l.split("");return new rc({name:u,iconsetId:p})}static isEqual(l,u){return l.name===u.name&&l.iconsetId===u.iconsetId}toString(){return rc.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var eT,nv={},tT=function(){if(eT)return nv;eT=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 l(b){return(b=Math.round(b))<0?0:b>255?255:b}function u(b){return l(b[b.length-1]==="%"?parseFloat(b)/100*255:parseInt(b))}function p(b){return(S=b[b.length-1]==="%"?parseFloat(b)/100:parseFloat(b))<0?0:S>1?1:S;var S}function y(b,S,k){return k<0?k+=1:k>1&&(k-=1),6*k<1?b+(S-b)*k*6:2*k<1?S:3*k<2?b+(S-b)*(2/3-k)*6:b}try{nv.parseCSSColor=function(b){var S,k=b.replace(/ /g,"").toLowerCase();if(k in h)return h[k].slice();if(k[0]==="#")return k.length===4?(S=parseInt(k.substr(1),16))>=0&&S<=4095?[(3840&S)>>4|(3840&S)>>8,240&S|(240&S)>>4,15&S|(15&S)<<4,1]:null:k.length===7&&(S=parseInt(k.substr(1),16))>=0&&S<=16777215?[(16711680&S)>>16,(65280&S)>>8,255&S,1]:null;var j=k.indexOf("("),O=k.indexOf(")");if(j!==-1&&O+1===k.length){var z=k.substr(0,j),U=k.substr(j+1,O-(j+1)).split(","),q=1;switch(z){case"rgba":if(U.length!==4)return null;q=p(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=p(U.pop());case"hsl":if(U.length!==3)return null;var K=(parseFloat(U[0])%360+360)%360/360,Z=p(U[1]),J=p(U[2]),ne=J<=.5?J*(Z+1):J+Z-J*Z,ae=2*J-ne;return[l(255*y(ae,ne,K+1/3)),l(255*y(ae,ne,K)),l(255*y(ae,ne,K-1/3)),q];default:return null}}return null}}catch{}return nv}();class Yn{constructor(l,u,p,y=1){this.r=l,this.g=u,this.b=p,this.a=y}static parse(l){if(!l)return;if(l instanceof Yn)return l;if(typeof l!="string")return;const u=tT.parseCSSColor(l);return u?new Yn(u[0]/255,u[1]/255,u[2]/255,u[3]):void 0}toString(){const[l,u,p,y]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*l)},${Math.round(255*u)},${Math.round(255*p)},${y})`}toNonPremultipliedRenderColor(l){const{r:u,g:p,b:y,a:b}=this;return new iv(l,u,p,y,b)}toPremultipliedRenderColor(l){const{r:u,g:p,b:y,a:b}=this;return new eg(l,u*b,p*b,y*b,b)}clone(){return new Yn(this.r,this.g,this.b,this.a)}}class rT{constructor(l,u,p,y,b,S=!1){if(this.premultiplied=!1,this.premultiplied=S,l){const k=l.image.height,j=k*k;this.premultiplied?(u=b===0?0:u/b*(k-1),p=b===0?0:p/b*(k-1),y=b===0?0:y/b*(k-1)):(u*=k-1,p*=k-1,y*=k-1),u=Math.max(0,Math.min(k-1,u)),p=Math.max(0,Math.min(k-1,p)),y=Math.max(0,Math.min(k-1,y));const O=Math.floor(u),z=Math.floor(p),U=Math.floor(y),q=Math.ceil(u),K=Math.ceil(p),Z=Math.ceil(y),J=u-O,ne=p-z,ae=y-U,he=l.image.data,ce=4*(O+z*j+U*k),ye=4*(O+z*j+Z*k),Ee=4*(O+K*j+U*k),Ce=4*(O+K*j+Z*k),He=4*(q+z*j+U*k),$e=4*(q+z*j+Z*k),Ge=4*(q+K*j+U*k),Ue=4*(q+K*j+Z*k);this.r=Xr(Xr(Xr(he[ce],he[ye],ae),Xr(he[Ee],he[Ce],ae),ne),Xr(Xr(he[He],he[$e],ae),Xr(he[Ge],he[Ue],ae),ne),J)/255*(this.premultiplied?b:1),this.g=Xr(Xr(Xr(he[ce+1],he[ye+1],ae),Xr(he[Ee+1],he[Ce+1],ae),ne),Xr(Xr(he[He+1],he[$e+1],ae),Xr(he[Ge+1],he[Ue+1],ae),ne),J)/255*(this.premultiplied?b:1),this.b=Xr(Xr(Xr(he[ce+2],he[ye+2],ae),Xr(he[Ee+2],he[Ce+2],ae),ne),Xr(Xr(he[He+2],he[$e+2],ae),Xr(he[Ge+2],he[Ue+2],ae),ne),J)/255*(this.premultiplied?b:1),this.a=b}else this.r=u,this.g=p,this.b=y,this.a=b}toArray(){const{r:l,g:u,b:p,a:y}=this;return[255*l,255*u,255*p,y]}toHslaArray(){let{r:l,g:u,b:p,a:y}=this;if(this.premultiplied){if(y===0)return[0,0,0,0];const Z=1/y;l*=Z,u*=Z,p*=Z}const b=Math.min(Math.max(l,0),1),S=Math.min(Math.max(u,0),1),k=Math.min(Math.max(p,0),1),j=Math.min(b,S,k),O=Math.max(b,S,k),z=O-j,U=.5*(j+O);if(z===0)return[0,0,100*U,y];const q=U>.5?z/(2-O-j):z/(O+j);let K;switch(O){case b:K=60*((S-k)/z+(SXr(p,l[y],u))}Yn.black=new Yn(0,0,0,1),Yn.white=new Yn(1,1,1,1),Yn.transparent=new Yn(0,0,0,0),Yn.red=new Yn(1,0,0,1),Yn.blue=new Yn(0,0,1,1);var sv=Object.freeze({__proto__:null,array:Ru,color:function(h,l,u){return new Yn(Xr(h.r,l.r,u),Xr(h.g,l.g,u),Xr(h.b,l.b,u),Xr(h.a,l.a,u))},number:Xr});class su extends Error{constructor(l,u){super(u),this.message=u,this.key=l}}class vp{constructor(l,u=[]){this.parent=l,this.bindings={};for(const[p,y]of u)this.bindings[p]=y}concat(l){return new vp(this,l)}get(l){if(this.bindings[l])return this.bindings[l];if(this.parent)return this.parent.get(l);throw new Error(`${l} not found in scope.`)}has(l){return!!this.bindings[l]||!!this.parent&&this.parent.has(l)}}const oh={kind:"null"},Dr={kind:"number"},li={kind:"string"},di={kind:"boolean"},ml={kind:"color"},of={kind:"object"},hi={kind:"value"},bp={kind:"collator"},wx={kind:"formatted"},Sx={kind:"resolvedImage"};function Ko(h,l){return{kind:"array",itemType:h,N:l}}function aa(h){if(h.kind==="array"){const l=aa(h.itemType);return typeof h.N=="number"?`array<${l}, ${h.N}>`:h.itemType.kind==="value"?"array":`array<${l}>`}return h.kind}const m3=[oh,Dr,li,di,ml,wx,of,Ko(hi),Sx];function Tx(h,l){if(l.kind==="error")return null;if(h.kind==="array"){if(l.kind==="array"&&(l.N===0&&l.itemType.kind==="value"||!Tx(h.itemType,l.itemType))&&(typeof h.N!="number"||h.N===l.N))return null}else{if(h.kind===l.kind)return null;if(h.kind==="value"){for(const u of m3)if(!Tx(u,l))return null}}return`Expected ${aa(h)} but found ${aa(l)} instead.`}function nT(h,l){return l.some(u=>u.kind===h.kind)}function tg(h,l){return l.some(u=>u==="null"?h===null:u==="array"?Array.isArray(h):u==="object"?h&&!Array.isArray(h)&&typeof h=="object":u===typeof h)}function lh(h,l){return h.kind==="array"&&l.kind==="array"?h.N===l.N&&lh(h.itemType,l.itemType):h.kind===l.kind}class iT{constructor(l,u,p){this.sensitivity=l?u?"variant":"case":u?"accent":"base",this.locale=p,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(l,u){return this.collator.compare(l,u)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class Ex{constructor(l,u,p,y,b){this.text=l.normalize?l.normalize():l,this.image=u,this.scale=p,this.fontStack=y,this.textColor=b}}class No{constructor(l){this.sections=l}static fromString(l){return new No([new Ex(l,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(l=>l.text.length!==0||!!l.image&&l.image.hasPrimary())}static factory(l){return l instanceof No?l:No.fromString(l)}toString(){return this.sections.length===0?"":this.sections.map(l=>l.text).join("")}serialize(){const l=["format"];for(const u of this.sections){if(u.image){const y=u.image.getPrimary().id.toString();l.push(["image",y]);continue}l.push(u.text);const p={};u.fontStack&&(p["text-font"]=["literal",u.fontStack.split(",")]),u.scale&&(p["font-scale"]=u.scale),u.textColor&&(p["text-color"]=["rgba"].concat(u.textColor.toNonPremultipliedRenderColor(null).toArray())),l.push(p)}return l}}class au{constructor(l,u={}){this.id=rc.from(l),this.params=u.params,this.sx=u.sx||1,this.sy=u.sy||1}toString(){return JSON.stringify(this)}static parse(l){let u,p,y,b;try{({id:u,params:p,sx:y,sy:b}=JSON.parse(l)||{})}catch{return null}return u?new au(u,{params:p,sx:y,sy:b}):null}scaleSelf(l,u=l){return this.sx*=l,this.sy*=u,this}}class Nl{constructor(l,u,p,y,b=!1){this.primaryId=rc.from(l),this.primaryOptions=u,p&&(this.secondaryId=rc.from(p)),this.secondaryOptions=y,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 au(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new au(this.secondaryId,this.secondaryOptions):null}static from(l){return typeof l=="string"?Nl.build({name:l}):l}static build(l,u,p,y){return!l||typeof l=="object"&&!("name"in l)?null:new Nl(l,p,u,y)}}function xj(h,l,u,p){return typeof h=="number"&&h>=0&&h<=255&&typeof l=="number"&&l>=0&&l<=255&&typeof u=="number"&&u>=0&&u<=255?p===void 0||typeof p=="number"&&p>=0&&p<=1?null:`Invalid rgba value [${[h,l,u,p].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof p=="number"?[h,l,u,p]:[h,l,u]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function rg(h){if(h===null||typeof h=="string"||typeof h=="boolean"||typeof h=="number"||h instanceof Yn||h instanceof iT||h instanceof No||h instanceof Nl)return!0;if(Array.isArray(h)){for(const l of h)if(!rg(l))return!1;return!0}if(typeof h=="object"){for(const l in h)if(!rg(h[l]))return!1;return!0}return!1}function js(h){if(h===null)return oh;if(typeof h=="string")return li;if(typeof h=="boolean")return di;if(typeof h=="number")return Dr;if(h instanceof Yn)return ml;if(h instanceof iT)return bp;if(h instanceof No)return wx;if(h instanceof Nl)return Sx;if(Array.isArray(h)){const l=h.length;let u;for(const p of h){const y=js(p);if(u){if(u===y)continue;u=hi;break}u=y}return Ko(u||hi,l)}return of}function Kr(h){const l=typeof h;return h===null?"":l==="string"||l==="number"||l==="boolean"?String(h):h instanceof No||h instanceof Nl||h instanceof Yn?h.toString():JSON.stringify(h)}class Ir{constructor(l,u){this.type=l,this.value=u}static parse(l,u){if(l.length!==2)return u.error(`'literal' expression requires exactly one argument, but found ${l.length-1} instead.`);if(!rg(l[1]))return u.error("invalid value");const p=l[1];let y=js(p);const b=u.expectedType;return y.kind!=="array"||y.N!==0||!b||b.kind!=="array"||typeof b.N=="number"&&b.N!==0||(y=b),new Ir(y,p)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Yn?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof No?this.value.serialize():this.value}}class Zs{constructor(l){this.name="ExpressionEvaluationError",this.message=l}toJSON(){return this.message}}const Qr={string:li,number:Dr,boolean:di,object:of};class bc{constructor(l,u){this.type=l,this.args=u}static parse(l,u){if(l.length<2)return u.error("Expected at least one argument.");let p,y=1;const b=l[0];if(b==="array"){let k,j;if(l.length>2){const O=l[1];if(typeof O!="string"||!(O in Qr)||O==="object")return u.error('The item type argument of "array" must be one of string, number, boolean',1);k=Qr[O],y++}else k=hi;if(l.length>3){if(l[2]!==null&&(typeof l[2]!="number"||l[2]<0||l[2]!==Math.floor(l[2])))return u.error('The length argument to "array" must be a positive integer literal',2);j=l[2],y++}p=Ko(k,j)}else p=Qr[b];const S=[];for(;yl.outputDefined())}serialize(){const l=this.type,u=[l.kind];if(l.kind==="array"){const p=l.itemType;if(p.kind==="string"||p.kind==="number"||p.kind==="boolean"){u.push(p.kind);const y=l.N;(typeof y=="number"||this.args.length>1)&&u.push(y)}}return u.concat(this.args.map(p=>p.serialize()))}}class wp{constructor(l){this.type=wx,this.sections=l}static parse(l,u){if(l.length<2)return u.error("Expected at least one argument.");const p=l[1];if(!Array.isArray(p)&&typeof p=="object")return u.error("First argument must be an image or text section.");const y=[];let b=!1;for(let S=1;S<=l.length-1;++S){const k=l[S];if(b&&typeof k=="object"&&!Array.isArray(k)){b=!1;let j=null;if(k["font-scale"]&&(j=u.parseObjectValue(k["font-scale"],S,"font-scale",Dr),!j))return null;let O=null;if(k["text-font"]&&(O=u.parseObjectValue(k["text-font"],S,"text-font",Ko(li)),!O))return null;let z=null;if(k["text-color"]&&(z=u.parseObjectValue(k["text-color"],S,"text-color",ml),!z))return null;const U=y[y.length-1];U.scale=j,U.font=O,U.textColor=z}else{const j=u.parse(l[S],S,hi);if(!j)return null;const O=j.type.kind;if(O!=="string"&&O!=="value"&&O!=="null"&&O!=="resolvedImage")return u.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");b=!0,y.push({content:j,scale:null,font:null,textColor:null})}}return new wp(y)}evaluate(l){return new No(this.sections.map(u=>{const p=u.content.evaluate(l);return lh(js(p),Sx)?new Ex("",p,null,null,null):new Ex(Kr(p),null,u.scale?u.scale.evaluate(l):null,u.font?u.font.evaluate(l).join(","):null,u.textColor?u.textColor.evaluate(l):null)}))}eachChild(l){for(const u of this.sections)l(u.content),u.scale&&l(u.scale),u.font&&l(u.font),u.textColor&&l(u.textColor)}outputDefined(){return!1}serialize(){const l=["format"];for(const u of this.sections){l.push(u.content.serialize());const p={};u.scale&&(p["font-scale"]=u.scale.serialize()),u.font&&(p["text-font"]=u.font.serialize()),u.textColor&&(p["text-color"]=u.textColor.serialize()),l.push(p)}return l}}class Gr{constructor(l,u,p,y){this._imageWarnHistory={},this.type=Sx,this.namePrimary=l,this.nameSecondary=u,p&&(this.paramsPrimary=p.params,this.iconsetIdPrimary=p.iconset?p.iconset.id:void 0),y&&(this.paramsSecondary=y.params,this.iconsetIdSecondary=y.iconset?y.iconset.id:void 0)}static parse(l,u){if(l.length<2)return u.error("Expected two or more arguments.");let p=1;const y=[];function b(){if(prc.isEqual(S,b)),y.available){const S=y.getSecondary()?y.getSecondary().id:null;S&&(y.available=l.availableImages.some(k=>rc.isEqual(k,S)))}}return y}eachChild(l){if(l(this.namePrimary),this.paramsPrimary)for(const u in this.paramsPrimary)this.paramsPrimary[u]&&l(this.paramsPrimary[u]);if(this.nameSecondary&&(l(this.nameSecondary),this.paramsSecondary))for(const u in this.paramsSecondary)this.paramsSecondary[u]&&l(this.paramsSecondary[u])}outputDefined(){return!1}serializeOptions(l,u){const p={};if(u&&(p.iconset={id:u}),l){p.params={};for(const y in l)l[y]&&(p.params[y]=l[y].serialize())}return Object.keys(p).length>0?p:void 0}serialize(){const l=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const u=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);u&&l.push(u)}if(this.nameSecondary&&(l.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const u=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);u&&l.push(u)}return l}}function Ax(h){return ov(h)?"string":kx(h)?"number":Cx(h)?"boolean":Array.isArray(h)?"array":h===null?"null":av(h)?"object":typeof h}function av(h){return h!=null&&!Array.isArray(h)&&typeof h!="function"&&!(h instanceof String||h instanceof Number||h instanceof Boolean)&&typeof h=="object"}function ov(h){return typeof h=="string"||h instanceof String}function kx(h){return typeof h=="number"||h instanceof Number}function Cx(h){return typeof h=="boolean"||h instanceof Boolean}const g3={"to-boolean":di,"to-color":ml,"to-number":Dr,"to-string":li};class Lu{constructor(l,u){this.type=l,this.args=u}static parse(l,u){if(l.length<2)return u.error("Expected at least one argument.");const p=l[0],y=[];let b=oh;if(p==="to-array"){if(!Array.isArray(l[1]))return null;const S=l[1].length;if(u.expectedType){if(u.expectedType.kind!=="array")return u.error(`Expected ${u.expectedType.kind} but found array.`);b=Ko(u.expectedType.itemType,S)}else{if(!(S>0&&rg(l[1][0])))return null;b=Ko(js(l[1][0]),S)}for(let k=0;k4?`Invalid rbga value ${JSON.stringify(u)}: expected an array containing either three or four numeric values.`:xj(u[0],u[1],u[2],u[3]),!p))return new Yn(u[0]/255,u[1]/255,u[2]/255,u[3])}throw new Zs(p||`Could not parse color from value '${typeof u=="string"?u:String(JSON.stringify(u))}'`)}if(this.type.kind==="number"){let u=null;for(const p of this.args){if(u=p.evaluate(l),u===null)return 0;const y=Number(u);if(!isNaN(y))return y}throw new Zs(`Could not convert ${JSON.stringify(u)} to number.`)}return this.type.kind==="formatted"?No.fromString(Kr(this.args[0].evaluate(l))):this.type.kind==="resolvedImage"?Nl.build(Kr(this.args[0].evaluate(l))):this.type.kind==="array"?this.args.map(u=>u.evaluate(l)):Kr(this.args[0].evaluate(l))}eachChild(l){this.args.forEach(l)}outputDefined(){return this.args.every(l=>l.outputDefined())}serialize(){if(this.type.kind==="formatted")return new wp([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new Gr(this.args[0]).serialize();const l=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(u=>{l.push(u.serialize())}),l}}const Sp=["Unknown","Point","LineString","Polygon"];class jx{constructor(l,u,p){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=l,this.options=u,this.iconImageUseTheme=p}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?Sp[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(l){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const l=this.featureDistanceData.center,u=this.featureDistanceData.scale,{x:p,y}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(p*u-l[0])+this.featureDistanceData.bearing[1]*(y*u-l[1])}return 0}parseColor(l){let u=this._parseColorCache[l];return u||(u=this._parseColorCache[l]=Yn.parse(l)),u}getConfig(l){return this.options?this.options.get(l):null}}class Pa{constructor(l,u,p,y,b){this.name=l,this.type=u,this._evaluate=p,this.args=y,this._overloadIndex=b}evaluate(l){if(!this._evaluate){const u=Pa.definitions[this.name];this._evaluate=Array.isArray(u)?u[2]:u.overloads[this._overloadIndex][1]}return this._evaluate(l,this.args)}eachChild(l){this.args.forEach(l)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(l=>l.serialize()))}static parse(l,u){const p=l[0],y=Pa.definitions[p];if(!y)return u.error(`Unknown expression "${p}". If you wanted a literal array, use ["literal", [...]].`,0);const b=Array.isArray(y)?y[0]:y.type,S=Array.isArray(y)?[[y[1],y[2]]]:y.overloads,k=[];let j=null,O=-1;for(const[z,U]of S){if(Array.isArray(z)&&z.length!==l.length-1)continue;k.push(z),O++,j=new mv(u.registry,u.path,null,u.scope,void 0,u._scope,u.options,u.iconImageUseTheme);const q=[];let K=!1;for(let Z=1;Zq)).map(lf).join(" | "),U=[];for(let q=1;qu;){if(p-u>600){const j=p-u+1,O=l-u+1,z=Math.log(j),U=.5*Math.exp(2*z/3),q=.5*Math.sqrt(z*U*(j-U)/j)*(O-j/2<0?-1:1);_j(h,l,Math.max(u,Math.floor(l-O*U/j+q)),Math.min(p,Math.floor(l+(j-O)*U/j+q)),y)}const b=h[l];let S=u,k=p;for(Ix(h,u,l),y(h[p],b)>0&&Ix(h,u,p);S0;)k--}y(h[u],b)===0?Ix(h,u,k):(k++,Ix(h,k,p)),k<=l&&(u=k+1),l<=k&&(p=k-1)}}function Ix(h,l,u){const p=h[l];h[l]=h[u],h[u]=p}function cv(h,l){return hl?1:0}function vj(h){let l=0;for(let u,p,y=0,b=h.length,S=b-1;y=l[2]||h[1]<=l[1]||h[3]>=l[3])}function y3(h,l,u){const p=h[0]-l[0],y=h[1]-l[1],b=h[0]-u[0],S=h[1]-u[1];return p*S-b*y===0&&p*b<=0&&y*S<=0}function sT(h,l,u){return l[1]>h[1]!=u[1]>h[1]&&h[0]<(u[0]-l[0])*(h[1]-l[1])/(u[1]-l[1])+l[0]}function ng(h,l,u=!1){let p=!1;for(let y=0,b=l.length;y0&&k<0||S<0&&k>0}function Nx(h,l,u,p){return(y=[p[0]-u[0],p[1]-u[1]])[0]*(b=[l[0]-h[0],l[1]-h[1]])[1]-y[1]*b[0]!==0&&!(!bj(h,l,u,p)||!bj(u,p,h,l));var y,b}function aT(h){const l=new Mt(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),u=new Mt(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const p of h[0])l.x>p.x&&(l.x=p.x),l.y>p.y&&(l.y=p.y),u.xu[2]){const y=.5*p;let b=h[0]-u[0]>y?-p:u[0]-h[0]>y?p:0;b===0&&(b=h[0]-u[2]>y?-p:u[2]-h[0]>y?p:0),h[0]+=b}Du(l,h)}function cT(h,l,u,p){const y=Math.pow(2,p.z)*cf,b=[p.x*cf,p.y*cf],S=[];if(!h)return S;for(const k of h)for(const j of k){const O=[j.x+b[0],j.y+b[1]];ou(O,l,u,y),S.push(O)}return S}function uT(h,l,u,p){const y=Math.pow(2,p.z)*cf,b=[p.x*cf,p.y*cf],S=[];if(!h)return S;for(const j of h){const O=[];for(const z of j){const U=[z.x+b[0],z.y+b[1]];Du(l,U),O.push(U)}S.push(O)}if(l[2]-l[0]<=y/2){(k=l)[0]=k[1]=1/0,k[2]=k[3]=-1/0;for(const j of S)for(const O of j)ou(O,l,u,y)}var k;return S}class uf{constructor(l,u){this.type=di,this.geojson=l,this.geometries=u}static parse(l,u){if(l.length!==2)return u.error(`'within' expression requires exactly one argument, but found ${l.length-1} instead.`);if(rg(l[1])){const p=l[1];if(p.type==="FeatureCollection")for(let y=0;yu)return dv(b,S,(u-(p-k))/k)}return l[l.length-1]}pointToSegmentDistance(l,u,p){let[y,b]=u,S=wc(p[0]-y)*this.kx,k=(p[1]-b)*this.ky;if(S!==0||k!==0){const j=(wc(l[0]-y)*this.kx*S+(l[1]-b)*this.ky*k)/(S*S+k*k);j>1?(y=p[0],b=p[1]):j>0&&(y+=S/this.kx*j,b+=k/this.ky*j)}return S=wc(l[0]-y)*this.kx,k=(l[1]-b)*this.ky,Math.sqrt(S*S+k*k)}pointOnLine(l,u){let p=1/0,y=l[0][0],b=l[0][1],S=0,k=0;for(let j=0;j1?(O=l[j+1][0],z=l[j+1][1]):K>0&&(O+=U/this.kx*K,z+=q/this.ky*K)),U=wc(u[0]-O)*this.kx,q=(u[1]-z)*this.ky;const Z=U*U+q*q;Zb.index||y.index===b.index&&y.t>b.t){const O=y;y=b,b=O}const S=[y.point],k=y.index+1,j=b.index;!fT(p[k],S[0])&&k<=j&&S.push(p[k]);for(let O=k+1;O<=j;O++)S.push(p[O]);return fT(p[j],b.point)||S.push(b.point),S}lineSliceAlong(l,u,p){let y=0;const b=[];for(let S=0;Sl&&b.length===0&&b.push(dv(k,j,(l-(y-O))/O)),y>=u)return b.push(dv(k,j,(u-(y-O))/O)),b;y>l&&b.push(j)}return b}bufferPoint(l,u){const p=u/this.ky,y=u/this.kx;return[l[0]-y,l[1]-p,l[0]+y,l[1]+p]}bufferBBox(l,u){const p=u/this.ky,y=u/this.kx;return[l[0]-y,l[1]-p,l[2]+y,l[3]+p]}insideBBox(l,u){return wc(l[0]-u[0])>=0&&wc(l[0]-u[2])<=0&&l[1]>=u[1]&&l[1]<=u[3]}}function fT(h,l){return h[0]===l[0]&&h[1]===l[1]}function dv(h,l,u){const p=wc(l[0]-h[0]);return[h[0]+p*u,h[1]+(l[1]-h[1])*u]}function wc(h){for(;h<-180;)h+=360;for(;h>180;)h-=360;return h}class Lx{constructor(l=[],u=(p,y)=>py?1:0){if(this.data=l,this.length=this.data.length,this.compare=u,this.length>0)for(let p=(this.length>>1)-1;p>=0;p--)this._down(p)}push(l){this.data.push(l),this._up(this.length++)}pop(){if(this.length===0)return;const l=this.data[0],u=this.data.pop();return--this.length>0&&(this.data[0]=u,this._down(0)),l}peek(){return this.data[0]}_up(l){const{data:u,compare:p}=this,y=u[l];for(;l>0;){const b=l-1>>1,S=u[b];if(p(y,S)>=0)break;u[l]=S,l=b}u[l]=y}_down(l){const{data:u,compare:p}=this,y=this.length>>1,b=u[l];for(;l=0)break;u[l]=u[S],l=S}u[l]=b}}var ar=8192;function Sj(h,l){return l.dist-h.dist}function Tj(h){const l=[1/0,1/0,-1/0,-1/0];if(l.length!==h.length)return!1;for(let u=0;u=h[0]&&h[1]h[1])return[null,null];const u=Ep(h);if(l){if(u===2)return[h,null];const p=Math.floor(u/2);return[[h[0],h[0]+p],[h[0]+p,h[1]]]}{if(u===1)return[h,null];const p=Math.floor(u/2)-1;return[[h[0],h[0]+p],[h[0]+p+1,h[1]]]}}function df(h,l){const u=[1/0,1/0,-1/0,-1/0];if(!Ou(l,h.length))return u;for(let p=l[0];p<=l[1];++p)Du(u,h[p]);return u}function Dx(h){const l=[1/0,1/0,-1/0,-1/0];for(let u=0;ul[2]&&(p=h[0]-l[2]),h[1]>l[3]&&(y=h[1]-l[3]),h[3]=p)return p;if(Px(y,b)){if(jj(h,l))return 0}else if(jj(l,h))return 0;let S=p;for(const k of h)for(let j=0,O=k.length,z=O-1;j=b)continue;const z=O.range1;if(Ep(z)<=k){if(!Ou(z,h.length))return NaN;if(l){const U=as(h,z,u,p);if((b=Math.min(b,U))===0)return b}else for(let U=z[0];U<=z[1];++U){const q=w3(h[U],u,p);if((b=Math.min(b,q))===0)return b}}else{const U=ag(z,l);if(U[0]!==null){const q=og(df(h,U[0]),j,p);q=S)continue;const U=z.range1,q=z.range2;if(Ep(U)<=j&&Ep(q)<=O){if(!Ou(U,h.length)||!Ou(q,u.length))return NaN;if(l&&p?S=Math.min(S,b3(h,U,u,q,y)):l||p?l&&!p?S=Math.min(S,kj(u,q,h,U,y)):!l&&p&&(S=Math.min(S,kj(h,U,u,q,y))):S=Math.min(S,Cj(h,U,u,q,y)),S===0)return S}else{const K=ag(U,l),Z=ag(q,p);hv(k,S,y,h,u,K[0],Z[0]),hv(k,S,y,h,u,K[0],Z[1]),hv(k,S,y,h,u,K[1],Z[0]),hv(k,S,y,h,u,K[1],Z[1])}}return S}function mT(h,l,u,p,y=1/0){let b=y;const S=df(h,[0,h.length-1]);for(const k of u)if(!(b!==1/0&&og(S,df(k,[0,k.length-1]),p)>=b)&&(b=Math.min(b,Ij(h,l,k,!0,p,b)),b===0))return b;return b}function fv(h,l,u,p,y=1/0){let b=y;const S=df(h,[0,h.length-1]);for(const k of u){if(b!==1/0&&og(S,Dx(k),p)>=b)continue;const j=T3(h,l,k,p,b);if(isNaN(j))return j;if((b=Math.min(b,j))===0)return b}return b}function gT(h){return h==="Point"||h==="MultiPoint"||h==="LineString"||h==="MultiLineString"||h==="Polygon"||h==="MultiPolygon"}class Ap{constructor(l,u){this.type=Dr,this.geojson=l,this.geometries=u}static parse(l,u){if(l.length!==2)return u.error(`'distance' expression requires either one argument, but found ' ${l.length-1} instead.`);if(rg(l[1])){const p=l[1];if(p.type==="FeatureCollection"){for(let y=0;y{l&&!kp(u)&&(l=!1)}),l}function lg(h){if(h instanceof Pa&&h.name==="feature-state")return!1;let l=!0;return h.eachChild(u=>{l&&!lg(u)&&(l=!1)}),l}function yd(h,l){if(h instanceof Pa&&l.indexOf(h.name)>=0)return!1;let u=!0;return h.eachChild(p=>{u&&!yd(p,l)&&(u=!1)}),u}function Pj(h,l,u){return[h,l,u].filter(Boolean).join("")}function yT(h,l){switch(h){case"string":return Kr(l);case"number":return+l;case"boolean":return!!l;case"color":return Yn.parse(l);case"formatted":return No.fromString(Kr(l));case"resolvedImage":return Nl.build(Kr(l))}return l}function Nj(h,l,u,p){return p!==void 0&&(h=p*Math.round(h/p)),l!==void 0&&hu&&(h=u),h}class cg{constructor(l,u,p,y=!1){this.type=l,this.key=u,this.scope=p,this.featureConstant=y}static parse(l,u){let p=u.expectedType;if(p==null&&(p=hi),l.length<2||l.length>3)return u.error("Invalid number of arguments for 'config' expression.");const y=u.parse(l[1],1);if(!(y instanceof Ir))return u.error("Key name of 'config' expression must be a string literal.");let b,S=!0;const k=Kr(y.value);if(l.length>=3){const j=u.parse(l[2],2);if(!(j instanceof Ir))return u.error("Scope of 'config' expression must be a string literal.");b=Kr(j.value)}if(u.options){const j=Pj(k,b,u._scope),O=u.options.get(j);O&&(S=kp(O.value||O.default))}return new cg(p,k,b,S)}evaluate(l){const u=Pj(this.key,this.scope,l.scope),p=l.getConfig(u);if(!p)return null;const{type:y,value:b,values:S,minValue:k,maxValue:j,stepValue:O}=p,z=p.default.evaluate(l);let U=z;if(b){const q=l.scope;l.scope=(q||"").split("").slice(1).join(""),U=b.evaluate(l),l.scope=q}return y&&(U=yT(y,U)),U===void 0||k===void 0&&j===void 0&&O===void 0||(typeof U=="number"?U=Nj(U,k,j,O):Array.isArray(U)&&(U=U.map(q=>typeof q=="number"?Nj(q,k,j,O):q))),b!==void 0&&U!==void 0&&S&&!S.includes(U)&&(U=z,y&&(U=yT(y,U))),(y&&y!==this.type||U!==void 0&&!lh(js(U),this.type))&&(U=yT(this.type.kind,U)),U}eachChild(){}outputDefined(){return!1}serialize(){const l=["config",this.key];return this.scope&&l.concat(this.scope),l}}class pv{constructor(l,u){this.type=u.type,this.name=l,this.boundExpression=u}static parse(l,u){if(l.length!==2||typeof l[1]!="string")return u.error("'var' expression requires exactly one string literal argument.");const p=l[1];return u.scope.has(p)?new pv(p,u.scope.get(p)):u.error(`Unknown variable "${p}". Make sure "${p}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(l){return this.boundExpression.evaluate(l)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class mv{constructor(l,u=[],p,y=new vp,b=[],S,k,j){this.registry=l,this.path=u,this.key=u.map(O=>typeof O=="string"?`['${O}']`:`[${O}]`).join(""),this.scope=y,this.errors=b,this.expectedType=p,this._scope=S,this.options=k,this.iconImageUseTheme=j}parse(l,u,p,y,b={}){return u||p?this.concat(u,null,p,y)._parse(l,b):this._parse(l,b)}parseObjectValue(l,u,p,y,b,S={}){return this.concat(u,p,y,b)._parse(l,S)}_parse(l,u){function p(y,b,S){return S==="assert"?new bc(b,[y]):S==="coerce"?new Lu(b,[y]):y}if(l!==null&&typeof l!="string"&&typeof l!="boolean"&&typeof l!="number"||(l=["literal",l]),Array.isArray(l)){if(l.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const y=typeof l[0]=="string"?this.registry[l[0]]:void 0;if(y){let b=y.parse(l,this);if(!b)return null;if(this.expectedType){const S=this.expectedType,k=b.type;if(S.kind!=="string"&&S.kind!=="number"&&S.kind!=="boolean"&&S.kind!=="object"&&S.kind!=="array"||k.kind!=="value")if(S.kind!=="color"&&S.kind!=="formatted"&&S.kind!=="resolvedImage"||k.kind!=="value"&&k.kind!=="string"){if(this.checkSubtype(S,k))return null}else b=p(b,S,u.typeAnnotation||"coerce");else b=p(b,S,u.typeAnnotation||"assert")}if(!(b instanceof Ir)&&b.type.kind!=="resolvedImage"&&xT(b)){const S=new jx(this._scope,this.options,this.iconImageUseTheme);try{b=new Ir(b.type,b.evaluate(S))}catch(k){return this.error(k.message),null}}return b}return Lu.parse(["to-array",l],this)}return this.error(l===void 0?"'undefined' value invalid. Use null instead.":typeof l=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof l} instead.`)}concat(l,u,p,y){let b=typeof l=="number"?this.path.concat(l):this.path;b=typeof u=="string"?b.concat(u):b;const S=y?this.scope.concat(y):this.scope;return new mv(this.registry,b,p||null,S,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(l,...u){const p=`${this.key}${u.map(y=>`[${y}]`).join("")}`;this.errors.push(new su(p,l))}checkSubtype(l,u){const p=Tx(l,u);return p&&this.error(p),p}}function xT(h){if(h instanceof pv)return xT(h.boundExpression);if(h instanceof Pa&&h.name==="error"||h instanceof lv||h instanceof uf||h instanceof Ap||h instanceof cg)return!1;const l=h instanceof Lu||h instanceof bc;let u=!0;return h.eachChild(p=>{u=l?u&&xT(p):u&&p instanceof Ir}),!!u&&kp(h)&&yd(h,["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 gv(h,l){const u=h.length-1;let p,y,b=0,S=u,k=0;for(;b<=S;)if(k=Math.floor((b+S)/2),p=h[k],y=h[k+1],p<=l){if(k===u||ll))throw new Zs("Input is not a number.");S=k-1}return 0}class Ox{constructor(l,u,p){this.type=l,this.input=u,this.labels=[],this.outputs=[];for(const[y,b]of p)this.labels.push(y),this.outputs.push(b)}static parse(l,u){if(l.length-1<4)return u.error(`Expected at least 4 arguments, but found only ${l.length-1}.`);if((l.length-1)%2!=0)return u.error("Expected an even number of arguments.");const p=u.parse(l[1],1,Dr);if(!p)return null;const y=[];let b=null;u.expectedType&&u.expectedType.kind!=="value"&&(b=u.expectedType);for(let S=1;S=k)return u.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',O);const U=u.parse(j,z,b);if(!U)return null;b=b||U.type,y.push([k,U])}return new Ox(b,p,y)}evaluate(l){const u=this.labels,p=this.outputs;if(u.length===1)return p[0].evaluate(l);const y=this.input.evaluate(l);if(y<=u[0])return p[0].evaluate(l);const b=u.length;return y>=u[b-1]?p[b-1].evaluate(l):p[gv(u,y)].evaluate(l)}eachChild(l){l(this.input);for(const u of this.outputs)l(u)}outputDefined(){return this.outputs.every(l=>l.outputDefined())}serialize(){const l=["step",this.input.serialize()];for(let u=0;u0&&l.push(this.labels[u]),l.push(this.outputs[u].serialize());return l}}const Rj=.95047,Lj=1.08883,Dj=4/29,ug=6/29,Oj=3*ug*ug,E3=ug*ug*ug,A3=Math.PI/180,k3=180/Math.PI;function _T(h){return h>E3?Math.pow(h,1/3):h/Oj+Dj}function vT(h){return h>ug?h*h*h:Oj*(h-Dj)}function Mx(h){return 255*(h<=.0031308?12.92*h:1.055*Math.pow(h,1/2.4)-.055)}function dg(h){return(h/=255)<=.04045?h/12.92:Math.pow((h+.055)/1.055,2.4)}function bT(h){const l=dg(h.r),u=dg(h.g),p=dg(h.b),y=_T((.4124564*l+.3575761*u+.1804375*p)/Rj),b=_T((.2126729*l+.7151522*u+.072175*p)/1);return{l:116*b-16,a:500*(y-b),b:200*(b-_T((.0193339*l+.119192*u+.9503041*p)/Lj)),alpha:h.a}}function Mj(h){let l=(h.l+16)/116,u=isNaN(h.a)?l:l+h.a/500,p=isNaN(h.b)?l:l-h.b/200;return l=1*vT(l),u=Rj*vT(u),p=Lj*vT(p),new Yn(Mx(3.2404542*u-1.5371385*l-.4985314*p),Mx(-.969266*u+1.8760108*l+.041556*p),Mx(.0556434*u-.2040259*l+1.0572252*p),h.alpha)}function C3(h,l,u){const p=l-h;return h+u*(p>180||p<-180?p-360*Math.round(p/360):p)}const Fx={forward:bT,reverse:Mj,interpolate:function(h,l,u){return{l:Xr(h.l,l.l,u),a:Xr(h.a,l.a,u),b:Xr(h.b,l.b,u),alpha:Xr(h.alpha,l.alpha,u)}}},hg={forward:function(h){const{l,a:u,b:p}=bT(h),y=Math.atan2(p,u)*k3;return{h:y<0?y+360:y,c:Math.sqrt(u*u+p*p),l,alpha:h.a}},reverse:function(h){const l=h.h*A3,u=h.c;return Mj({l:h.l,a:Math.cos(l)*u,b:Math.sin(l)*u,alpha:h.alpha})},interpolate:function(h,l,u){return{h:C3(h.h,l.h,u),c:Xr(h.c,l.c,u),l:Xr(h.l,l.l,u),alpha:Xr(h.alpha,l.alpha,u)}}};var wT=Object.freeze({__proto__:null,hcl:hg,lab:Fx});class Ro{constructor(l,u,p,y,b){this.type=l,this.operator=u,this.interpolation=p,this.input=y,this.labels=[],this.outputs=[];for(const[S,k]of b)this.labels.push(S),this.outputs.push(k)}static interpolationFactor(l,u,p,y){let b=0;if(l.name==="exponential")b=yv(u,l.base,p,y);else if(l.name==="linear")b=yv(u,1,p,y);else if(l.name==="cubic-bezier"){const S=l.controlPoints;b=new Wo(S[0],S[1],S[2],S[3]).solve(yv(u,1,p,y))}return b}static parse(l,u){let[p,y,b,...S]=l;if(!Array.isArray(y)||y.length===0)return u.error("Expected an interpolation type expression.",1);if(y[0]==="linear")y={name:"linear"};else if(y[0]==="exponential"){const O=y[1];if(typeof O!="number")return u.error("Exponential interpolation requires a numeric base.",1,1);y={name:"exponential",base:O}}else{if(y[0]!=="cubic-bezier")return u.error(`Unknown interpolation type ${String(y[0])}`,1,0);{const O=y.slice(1);if(O.length!==4||O.some(z=>typeof z!="number"||z<0||z>1))return u.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);y={name:"cubic-bezier",controlPoints:O}}}if(l.length-1<4)return u.error(`Expected at least 4 arguments, but found only ${l.length-1}.`);if(l.length-1>3&&(l.length-1)%2!=0)return u.error("Expected an even number of arguments.");if(b=u.parse(b,2,Dr),!b)return null;const k=[];let j=null;p==="interpolate-hcl"||p==="interpolate-lab"?j=ml:u.expectedType&&u.expectedType.kind!=="value"&&(j=u.expectedType);for(let O=0;O=z)return u.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',q);const Z=u.parse(U,K,j);if(!Z)return null;j=j||Z.type,k.push([z,Z])}return j.kind==="number"||j.kind==="color"||j.kind==="array"&&j.itemType.kind==="number"&&typeof j.N=="number"?new Ro(j,p,y,b,k):u.error(`Type ${aa(j)} is not interpolatable.`)}evaluate(l){const u=this.labels,p=this.outputs;if(u.length===1)return p[0].evaluate(l);const y=this.input.evaluate(l);if(y<=u[0])return p[0].evaluate(l);const b=u.length;if(y>=u[b-1])return p[b-1].evaluate(l);const S=gv(u,y),k=Ro.interpolationFactor(this.interpolation,y,u[S],u[S+1]),j=p[S].evaluate(l),O=p[S+1].evaluate(l);return this.operator==="interpolate"?sv[this.type.kind.toLowerCase()](j,O,k):this.operator==="interpolate-hcl"?hg.reverse(hg.interpolate(hg.forward(j),hg.forward(O),k)):Fx.reverse(Fx.interpolate(Fx.forward(j),Fx.forward(O),k))}eachChild(l){l(this.input);for(const u of this.outputs)l(u)}outputDefined(){return this.outputs.every(l=>l.outputDefined())}serialize(){let l;l=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,l,this.input.serialize()];for(let p=0;pTx(y,k.type));return new Bx(S?hi:p,b)}evaluate(l){let u,p=null,y=0;for(const b of this.args){if(y++,p=b.evaluate(l),p&&p instanceof Nl&&!p.available&&(u||(u=p),p=null,y===this.args.length))return u;if(p!==null)break}return p}eachChild(l){this.args.forEach(l)}outputDefined(){return this.args.every(l=>l.outputDefined())}serialize(){const l=["coalesce"];return this.eachChild(u=>{l.push(u.serialize())}),l}}class xv{constructor(l,u){this.type=u.type,this.bindings=[].concat(l),this.result=u}evaluate(l){return this.result.evaluate(l)}eachChild(l){for(const u of this.bindings)l(u[1]);l(this.result)}static parse(l,u){if(l.length<4)return u.error(`Expected at least 3 arguments, but found ${l.length-1} instead.`);const p=[];for(let b=1;b=p.length)throw new Zs("Array index out of bounds: index exceeds array size");if(u!==Math.floor(u))throw new Zs("Array index must be an integer. Use at-interpolated for fractional indices");return p[u]}eachChild(l){l(this.index),l(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class $x{constructor(l,u,p){this.type=l,this.index=u,this.input=p}static parse(l,u){if(l.length!==3)return u.error(`Expected 2 arguments, but found ${l.length-1} instead.`);const p=u.parse(l[1],1,Dr),y=u.parse(l[2],2,Ko(u.expectedType||hi));return p&&y?new $x(y.type.itemType,p,y):null}evaluate(l){const u=this.index.evaluate(l),p=this.input.evaluate(l);if(u<0)throw new Zs(`Array index out of bounds: ${u} < 0.`);if(u>p.length-1)throw new Zs(`Array index out of bounds: ${u} > ${p.length-1}.`);if(u===Math.floor(u))return p[u];const y=Math.floor(u),b=Math.ceil(u),S=p[y],k=p[b];if(typeof S!="number"||typeof k!="number")throw new Zs(`Cannot interpolate between non-number values at index ${u}.`);const j=u-y;return S*(1-j)+k*j}eachChild(l){l(this.index),l(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class Ux{constructor(l,u){this.type=di,this.needle=l,this.haystack=u}static parse(l,u){if(l.length!==3)return u.error(`Expected 2 arguments, but found ${l.length-1} instead.`),null;const p=u.parse(l[1],1,hi),y=u.parse(l[2],2,hi);return p&&y?nT(p.type,[di,li,Dr,oh,hi])?new Ux(p,y):(u.error(`Expected first argument to be of type boolean, string, number or null, but found ${aa(p.type)} instead`),null):null}evaluate(l){const u=this.needle.evaluate(l),p=this.haystack.evaluate(l);if(p==null)return!1;if(!tg(u,["boolean","string","number","null"]))throw new Zs(`Expected first argument to be of type boolean, string, number or null, but found ${aa(js(u))} instead.`);if(!tg(p,["string","array"]))throw new Zs(`Expected second argument to be of type array or string, but found ${aa(js(p))} instead.`);return p.indexOf(u)>=0}eachChild(l){l(this.needle),l(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class _v{constructor(l,u,p){this.type=Dr,this.needle=l,this.haystack=u,this.fromIndex=p}static parse(l,u){if(l.length<=2||l.length>=5)return u.error(`Expected 3 or 4 arguments, but found ${l.length-1} instead.`),null;const p=u.parse(l[1],1,hi),y=u.parse(l[2],2,hi);if(!p||!y)return null;if(!nT(p.type,[di,li,Dr,oh,hi]))return u.error(`Expected first argument to be of type boolean, string, number or null, but found ${aa(p.type)} instead`),null;if(l.length===4){const b=u.parse(l[3],3,Dr);return b?new _v(p,y,b):null}return new _v(p,y)}evaluate(l){const u=this.needle.evaluate(l),p=this.haystack.evaluate(l);if(!tg(u,["boolean","string","number","null"]))throw new Zs(`Expected first argument to be of type boolean, string, number or null, but found ${aa(js(u))} instead.`);if(!tg(p,["string","array"]))throw new Zs(`Expected second argument to be of type array or string, but found ${aa(js(p))} instead.`);if(this.fromIndex){const y=this.fromIndex.evaluate(l);return p.indexOf(u,y)}return p.indexOf(u)}eachChild(l){l(this.needle),l(this.haystack),this.fromIndex&&l(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const l=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),l]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class ST{constructor(l,u,p,y,b,S){this.inputType=l,this.type=u,this.input=p,this.cases=y,this.outputs=b,this.otherwise=S}static parse(l,u){if(l.length<5)return u.error(`Expected at least 4 arguments, but found only ${l.length-1}.`);if(l.length%2!=1)return u.error("Expected an even number of arguments.");let p,y;u.expectedType&&u.expectedType.kind!=="value"&&(y=u.expectedType);const b={},S=[];for(let O=2;ONumber.MAX_SAFE_INTEGER)return q.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof Z=="number"&&Math.floor(Z)!==Z)return q.error("Numeric branch labels must be integer values.");if(p){if(q.checkSubtype(p,js(Z)))return null}else p=js(Z);if(b[String(Z)]!==void 0)return q.error("Branch labels must be unique.");b[String(Z)]=S.length}const K=u.parse(U,O,y);if(!K)return null;y=y||K.type,S.push(K)}const k=u.parse(l[1],1,hi);if(!k)return null;const j=u.parse(l[l.length-1],l.length-1,y);return j?k.type.kind!=="value"&&u.concat(1).checkSubtype(p,k.type)?null:new ST(p,y,k,b,S,j):null}evaluate(l){const u=this.input.evaluate(l);return(lh(js(u),this.inputType)&&this.outputs[this.cases[u]]||this.otherwise).evaluate(l)}eachChild(l){l(this.input),this.outputs.forEach(l),l(this.otherwise)}outputDefined(){return this.outputs.every(l=>l.outputDefined())&&this.otherwise.outputDefined()}serialize(){const l=["match",this.input.serialize()],u=Object.keys(this.cases).sort(),p=[],y={};for(const S of u){const k=y[this.cases[S]];k===void 0?(y[this.cases[S]]=p.length,p.push([this.cases[S],[S]])):p[k][1].push(S)}const b=S=>this.inputType.kind==="number"?Number(S):S;for(const[S,k]of p)l.push(k.length===1?b(k[0]):k.map(b)),l.push(this.outputs[S].serialize());return l.push(this.otherwise.serialize()),l}}class vv{constructor(l,u,p){this.type=l,this.branches=u,this.otherwise=p}static parse(l,u){if(l.length<4)return u.error(`Expected at least 3 arguments, but found only ${l.length-1}.`),null;if(l.length%2!=0)return u.error("Expected an odd number of arguments."),null;let p;u.expectedType&&u.expectedType.kind!=="value"&&(p=u.expectedType);const y=[];for(let S=1;Su.outputDefined())&&this.otherwise.outputDefined()}serialize(){const l=["case"];return this.eachChild(u=>{l.push(u.serialize())}),l}}class Vx{constructor(l,u,p,y){this.type=l,this.input=u,this.beginIndex=p,this.endIndex=y}static parse(l,u){if(l.length<=2||l.length>=5)return u.error(`Expected 3 or 4 arguments, but found ${l.length-1} instead.`),null;const p=u.parse(l[1],1,hi),y=u.parse(l[2],2,Dr);if(!p||!y)return null;if(!nT(p.type,[Ko(hi),li,hi]))return u.error(`Expected first argument to be of type array or string, but found ${aa(p.type)} instead`),null;if(l.length===4){const b=u.parse(l[3],3,Dr);return b?new Vx(p.type,p,y,b):null}return new Vx(p.type,p,y)}evaluate(l){const u=this.input.evaluate(l),p=this.beginIndex.evaluate(l);if(!tg(u,["string","array"]))throw new Zs(`Expected first argument to be of type array or string, but found ${aa(js(u))} instead.`);if(this.endIndex){const y=this.endIndex.evaluate(l);return u.slice(p,y)}return u.slice(p)}eachChild(l){l(this.input),l(this.beginIndex),this.endIndex&&l(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const l=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),l]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class TT{constructor(l,u){this.type=Ko(li),this.str=l,this.delimiter=u}static parse(l,u){if(l.length!==3)return u.error(`Expected 2 arguments, but found ${l.length-1} instead.`);const p=u.parse(l[1],1,li),y=u.parse(l[2],2,li);return p&&y?new TT(p,y):void 0}evaluate(l){const u=this.str.evaluate(l),p=this.delimiter.evaluate(l);return u.split(p)}eachChild(l){l(this.str),l(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function Fj(h,l){return h==="=="||h==="!="?l.kind==="boolean"||l.kind==="string"||l.kind==="number"||l.kind==="null"||l.kind==="value":l.kind==="string"||l.kind==="number"||l.kind==="value"}function Bj(h,l,u,p){return p.compare(l,u)===0}function Cp(h,l,u){const p=h!=="=="&&h!=="!=";return class w0e{constructor(b,S,k){this.type=di,this.lhs=b,this.rhs=S,this.collator=k,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 k=b[0];let j=S.parse(b[1],1,hi);if(!j)return null;if(!Fj(k,j.type))return S.concat(1).error(`"${k}" comparisons are not supported for type '${aa(j.type)}'.`);let O=S.parse(b[2],2,hi);if(!O)return null;if(!Fj(k,O.type))return S.concat(2).error(`"${k}" comparisons are not supported for type '${aa(O.type)}'.`);if(j.type.kind!==O.type.kind&&j.type.kind!=="value"&&O.type.kind!=="value")return S.error(`Cannot compare types '${aa(j.type)}' and '${aa(O.type)}'.`);p&&(j.type.kind==="value"&&O.type.kind!=="value"?j=new bc(O.type,[j]):j.type.kind!=="value"&&O.type.kind==="value"&&(O=new bc(j.type,[O])));let z=null;if(b.length===4){if(j.type.kind!=="string"&&O.type.kind!=="string"&&j.type.kind!=="value"&&O.type.kind!=="value")return S.error("Cannot use collator to compare non-string types.");if(z=S.parse(b[3],3,bp),!z)return null}return new w0e(j,O,z)}evaluate(b){const S=this.lhs.evaluate(b),k=this.rhs.evaluate(b);if(p&&this.hasUntypedArgument){const j=js(S),O=js(k);if(j.kind!==O.kind||j.kind!=="string"&&j.kind!=="number")throw new Zs(`Expected arguments for "${h}" to be (string, string) or (number, number), but found (${j.kind}, ${O.kind}) instead.`)}if(this.collator&&!p&&this.hasUntypedArgument){const j=js(S),O=js(k);if(j.kind!=="string"||O.kind!=="string")return l(b,S,k)}return this.collator?u(b,S,k,this.collator.evaluate(b)):l(b,S,k)}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 zj=Cp("==",function(h,l,u){return l===u},Bj),bv=Cp("!=",function(h,l,u){return l!==u},function(h,l,u,p){return!Bj(0,l,u,p)}),j3=Cp("<",function(h,l,u){return l",function(h,l,u){return l>u},function(h,l,u,p){return p.compare(l,u)>0}),I3=Cp("<=",function(h,l,u){return l<=u},function(h,l,u,p){return p.compare(l,u)<=0}),P3=Cp(">=",function(h,l,u){return l>=u},function(h,l,u,p){return p.compare(l,u)>=0});class wv{constructor(l,u,p,y,b,S){this.type=li,this.number=l,this.locale=u,this.currency=p,this.unit=y,this.minFractionDigits=b,this.maxFractionDigits=S}static parse(l,u){if(l.length!==3)return u.error("Expected two arguments.");const p=u.parse(l[1],1,Dr);if(!p)return null;const y=l[2];if(typeof y!="object"||Array.isArray(y))return u.error("NumberFormat options argument must be an object.");let b=null;if(y.locale&&(b=u.parseObjectValue(y.locale,2,"locale",li),!b))return null;let S=null;if(y.currency&&(S=u.parseObjectValue(y.currency,2,"currency",li),!S))return null;let k=null;if(y.unit&&(k=u.parseObjectValue(y.unit,2,"unit",li),!k))return null;let j=null;if(y["min-fraction-digits"]&&(j=u.parseObjectValue(y["min-fraction-digits"],2,"min-fraction-digits",Dr),!j))return null;let O=null;return y["max-fraction-digits"]&&(O=u.parseObjectValue(y["max-fraction-digits"],2,"max-fraction-digits",Dr),!O)?null:new wv(p,b,S,k,j,O)}evaluate(l){return new Intl.NumberFormat(this.locale?this.locale.evaluate(l):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(l):void 0,unit:this.unit?this.unit.evaluate(l):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(l):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(l):void 0}).format(this.number.evaluate(l))}eachChild(l){l(this.number),this.locale&&l(this.locale),this.currency&&l(this.currency),this.unit&&l(this.unit),this.minFractionDigits&&l(this.minFractionDigits),this.maxFractionDigits&&l(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const l={};return this.locale&&(l.locale=this.locale.serialize()),this.currency&&(l.currency=this.currency.serialize()),this.unit&&(l.unit=this.unit.serialize()),this.minFractionDigits&&(l["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(l["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),l]}}class Sv{constructor(l){this.type=Dr,this.input=l}static parse(l,u){if(l.length!==2)return u.error(`Expected 1 argument, but found ${l.length-1} instead.`),null;const p=u.parse(l[1],1);return p?p.type.kind!=="array"&&p.type.kind!=="string"&&p.type.kind!=="value"?(u.error(`Expected argument of type string or array, but found ${aa(p.type)} instead.`),null):new Sv(p):null}evaluate(l){const u=this.input.evaluate(l);if(typeof u=="string"||Array.isArray(u))return u.length;throw new Zs(`Expected value to be of type string or array, but found ${aa(js(u))} instead.`)}eachChild(l){l(this.input)}outputDefined(){return!1}serialize(){const l=["length"];return this.eachChild(u=>{l.push(u.serialize())}),l}}function Uj(h){return function(){h=1831565813+(h|=0)|0;let l=Math.imul(h^h>>>15,1|h);return l=l+Math.imul(l^l>>>7,61|l)^l,((l^l>>>14)>>>0)/4294967296}}const fg={"==":zj,"!=":bv,">":$j,"<":j3,">=":P3,"<=":I3,array:bc,at:zx,"at-interpolated":$x,boolean:bc,case:vv,coalesce:Bx,collator:lv,format:wp,image:Gr,in:Ux,"index-of":_v,interpolate:Ro,"interpolate-hcl":Ro,"interpolate-lab":Ro,length:Sv,let:xv,literal:Ir,match:ST,number:bc,"number-format":wv,object:bc,slice:Vx,step:Ox,string:bc,"to-boolean":Lu,"to-color":Lu,"to-number":Lu,"to-string":Lu,var:pv,within:uf,distance:Ap,config:cg,split:TT};function Vj(h,[l,u,p,y]){l=l.evaluate(h),u=u.evaluate(h),p=p.evaluate(h);const b=y?y.evaluate(h):1,S=xj(l,u,p,b);if(S)throw new Zs(S);return new Yn(l/255,u/255,p/255,b)}function qj(h,[l,u,p,y]){l=l.evaluate(h),u=u.evaluate(h),p=p.evaluate(h);const b=y?y.evaluate(h):1,S=function(O,z,U,q){return typeof O=="number"&&O>=0&&O<=360?typeof z=="number"&&z>=0&&z<=100&&typeof U=="number"&&U>=0&&U<=100?q===void 0||typeof q=="number"&&q>=0&&q<=1?null:`Invalid hsla value [${[O,z,U,q].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof q=="number"?[O,z,U,q]:[O,z,U]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof q=="number"?[O,z,U,q]:[O,z,U]).join(", ")}]: 'h' must be between 0 and 360.`}(l,u,p,b);if(S)throw new Zs(S);const k=`hsla(${l}, ${u}%, ${p}%, ${b})`,j=Yn.parse(k);if(!j)throw new Zs(`Failed to parse HSLA color: ${k}`);return j}function qx(h,l){return h in l}function Tv(h,l){const u=l[h];return u===void 0?null:u}function hf(h){return{type:h}}function Ev(h){if(h instanceof cg)return new Set([h.key]);let l=new Set;return h.eachChild(u=>{l=new Set([...l,...Ev(u)])}),l}function Av(h){if(h instanceof Pa&&h.name==="is-active-floor")return!0;let l=!1;return h.eachChild(u=>{!l&&Av(u)&&(l=!0)}),l}function Gj(h){return{result:"success",value:h}}function ff(h){return{result:"error",value:h}}function Gx(h,l){return!!h&&!!h.parameters&&h.parameters.indexOf(l)>-1}function kv(h){return h["property-type"]==="data-driven"}function Hj(h){return Gx(h.expression,"measure-light")}function ET(h){return Gx(h.expression,"zoom")}function Cv(h){return!!h.expression&&h.expression.interpolated}function AT(h){return typeof h=="object"&&h!==null&&!Array.isArray(h)}function Wj(h){return h}function Kj(h,l){const u=l.type==="color",p=h.stops&&typeof h.stops[0][0]=="object",y=p||!(p||h.property!==void 0),b=h.type||(Cv(l)?"exponential":"interval");if(u&&((h=Object.assign({},h)).stops&&(h.stops=h.stops.map(O=>[O[0],Yn.parse(O[1])])),h.default=Yn.parse(h.default?h.default:l.default)),h.colorSpace&&h.colorSpace!=="rgb"&&!wT[h.colorSpace])throw new Error(`Unknown color space: ${h.colorSpace}`);let S,k,j;if(b==="exponential")S=Yj;else if(b==="interval")S=R3;else if(b==="categorical"){S=N3,k=Object.create(null);for(const O of h.stops)k[O[0]]=O[1];j=typeof h.stops[0][0]}else{if(b!=="identity")throw new Error(`Unknown function type "${b}"`);S=Zj}if(p){const O={},z=[];for(let K=0;KK[0]),evaluate:({zoom:K},Z)=>Yj({stops:U,base:h.base},l,K).evaluate(K,Z)}}if(y){const O=b==="exponential"?{name:"exponential",base:h.base!==void 0?h.base:1}:null;return{kind:"camera",interpolationType:O,interpolationFactor:Ro.interpolationFactor.bind(void 0,O),zoomStops:h.stops.map(z=>z[0]),evaluate:({zoom:z})=>S(h,l,z,k,j)}}return{kind:"source",evaluate(O,z){const U=z&&z.properties?z.properties[h.property]:void 0;return U===void 0?xd(h.default,l.default):S(h,l,U,k,j)}}}function xd(h,l,u){return h!==void 0?h:l!==void 0?l:u!==void 0?u:void 0}function N3(h,l,u,p,y){return xd(typeof u===y?p[u]:void 0,h.default,l.default)}function R3(h,l,u){if(!kx(u))return xd(h.default,l.default);const p=h.stops.length;if(p===1||u<=h.stops[0][0])return h.stops[0][1];if(u>=h.stops[p-1][0])return h.stops[p-1][1];const y=gv(h.stops.map(b=>b[0]),u);return h.stops[y][1]}function Yj(h,l,u){const p=h.base!==void 0?h.base:1;if(!kx(u))return xd(h.default,l.default);const y=h.stops.length;if(y===1||u<=h.stops[0][0])return h.stops[0][1];if(u>=h.stops[y-1][0])return h.stops[y-1][1];const b=gv(h.stops.map(z=>z[0]),u),S=function(z,U,q,K){const Z=K-q,J=z-q;return Z===0?0:U===1?J/Z:(Math.pow(U,J)-1)/(Math.pow(U,Z)-1)}(u,p,h.stops[b][0],h.stops[b+1][0]),k=h.stops[b][1],j=h.stops[b+1][1];let O=sv[l.type]||Wj;if(h.colorSpace&&h.colorSpace!=="rgb"){const z=wT[h.colorSpace];O=(U,q)=>z.reverse(z.interpolate(z.forward(U),z.forward(q),S))}return typeof k.evaluate=="function"?{evaluate(...z){const U=k.evaluate.apply(void 0,z),q=j.evaluate.apply(void 0,z);if(U!==void 0&&q!==void 0)return O(U,q,S)}}:O(k,j,S)}function Zj(h,l,u){return l.type==="color"?u=Yn.parse(u):l.type==="formatted"?u=No.fromString(u.toString()):l.type==="resolvedImage"?u=Nl.build(u.toString()):Ax(u)===l.type||l.type==="enum"&&l.values[u]||(u=void 0),xd(u,h.default,l.default)}Pa.register(fg,{error:[{kind:"error"},[li],(h,[l])=>{throw new Zs(l.evaluate(h))}],typeof:[li,[hi],(h,[l])=>aa(js(l.evaluate(h)))],"to-rgba":[Ko(Dr,4),[ml],(h,[l])=>l.evaluate(h).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Ko(Dr,4),[ml],(h,[l])=>l.evaluate(h).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[ml,[Dr,Dr,Dr],Vj],rgba:[ml,[Dr,Dr,Dr,Dr],Vj],hsl:[ml,[Dr,Dr,Dr],qj],hsla:[ml,[Dr,Dr,Dr,Dr],qj],has:{type:di,overloads:[[[li],(h,[l])=>qx(l.evaluate(h),h.properties())],[[li,of],(h,[l,u])=>qx(l.evaluate(h),u.evaluate(h))]]},get:{type:hi,overloads:[[[li],(h,[l])=>Tv(l.evaluate(h),h.properties())],[[li,of],(h,[l,u])=>Tv(l.evaluate(h),u.evaluate(h))]]},"feature-state":[hi,[li],(h,[l])=>Tv(l.evaluate(h),h.featureState||{})],properties:[of,[],h=>h.properties()],"geometry-type":[li,[],h=>h.geometryType()],worldview:[li,[],h=>h.globals.worldview||""],"is-active-floor":[di,hf(li),(h,l)=>{if(!(h.globals&&h.globals.activeFloors&&h.globals.activeFloors.size>0))return!1;if(l.length===0)return!0;const u=h.globals.activeFloors;return l.some(p=>{const y=p.evaluate(h);return u.has(y)})}],id:[hi,[],h=>h.id()],zoom:[Dr,[],h=>h.globals.zoom],pitch:[Dr,[],h=>h.globals.pitch||0],"distance-from-center":[Dr,[],h=>h.distanceFromCenter()],"measure-light":[Dr,[li],(h,[l])=>h.measureLight(l.evaluate(h))],"heatmap-density":[Dr,[],h=>h.globals.heatmapDensity||0],"line-progress":[Dr,[],h=>h.globals.lineProgress||0],"raster-value":[Dr,[],h=>h.globals.rasterValue||0],"raster-particle-speed":[Dr,[],h=>h.globals.rasterParticleSpeed||0],"sky-radial-progress":[Dr,[],h=>h.globals.skyRadialProgress||0],accumulated:[hi,[],h=>h.globals.accumulated===void 0?null:h.globals.accumulated],"+":[Dr,hf(Dr),(h,l)=>{let u=0;for(const p of l)u+=p.evaluate(h);return u}],"*":[Dr,hf(Dr),(h,l)=>{let u=1;for(const p of l)u*=p.evaluate(h);return u}],"-":{type:Dr,overloads:[[[Dr,Dr],(h,[l,u])=>l.evaluate(h)-u.evaluate(h)],[[Dr],(h,[l])=>-l.evaluate(h)]]},"/":[Dr,[Dr,Dr],(h,[l,u])=>l.evaluate(h)/u.evaluate(h)],"%":[Dr,[Dr,Dr],(h,[l,u])=>l.evaluate(h)%u.evaluate(h)],ln2:[Dr,[],()=>Math.LN2],pi:[Dr,[],()=>Math.PI],e:[Dr,[],()=>Math.E],"^":[Dr,[Dr,Dr],(h,[l,u])=>Math.pow(l.evaluate(h),u.evaluate(h))],sqrt:[Dr,[Dr],(h,[l])=>Math.sqrt(l.evaluate(h))],log10:[Dr,[Dr],(h,[l])=>Math.log(l.evaluate(h))/Math.LN10],ln:[Dr,[Dr],(h,[l])=>Math.log(l.evaluate(h))],log2:[Dr,[Dr],(h,[l])=>Math.log2(l.evaluate(h))],sin:[Dr,[Dr],(h,[l])=>Math.sin(l.evaluate(h))],cos:[Dr,[Dr],(h,[l])=>Math.cos(l.evaluate(h))],tan:[Dr,[Dr],(h,[l])=>Math.tan(l.evaluate(h))],asin:[Dr,[Dr],(h,[l])=>Math.asin(l.evaluate(h))],acos:[Dr,[Dr],(h,[l])=>Math.acos(l.evaluate(h))],atan:[Dr,[Dr],(h,[l])=>Math.atan(l.evaluate(h))],min:[Dr,hf(Dr),(h,l)=>Math.min(...l.map(u=>u.evaluate(h)))],max:[Dr,hf(Dr),(h,l)=>Math.max(...l.map(u=>u.evaluate(h)))],abs:[Dr,[Dr],(h,[l])=>Math.abs(l.evaluate(h))],round:[Dr,[Dr],(h,[l])=>{const u=l.evaluate(h);return u<0?-Math.round(-u):Math.round(u)}],floor:[Dr,[Dr],(h,[l])=>Math.floor(l.evaluate(h))],ceil:[Dr,[Dr],(h,[l])=>Math.ceil(l.evaluate(h))],"filter-==":[di,[li,hi],(h,[l,u])=>h.properties()[l.value]===u.value],"filter-id-==":[di,[hi],(h,[l])=>h.id()===l.value],"filter-type-==":[di,[li],(h,[l])=>h.geometryType()===l.value],"filter-<":[di,[li,hi],(h,[l,u])=>{const p=h.properties()[l.value],y=u.value;return typeof p==typeof y&&p{const u=h.id(),p=l.value;return typeof u==typeof p&&u":[di,[li,hi],(h,[l,u])=>{const p=h.properties()[l.value],y=u.value;return typeof p==typeof y&&p>y}],"filter-id->":[di,[hi],(h,[l])=>{const u=h.id(),p=l.value;return typeof u==typeof p&&u>p}],"filter-<=":[di,[li,hi],(h,[l,u])=>{const p=h.properties()[l.value],y=u.value;return typeof p==typeof y&&p<=y}],"filter-id-<=":[di,[hi],(h,[l])=>{const u=h.id(),p=l.value;return typeof u==typeof p&&u<=p}],"filter->=":[di,[li,hi],(h,[l,u])=>{const p=h.properties()[l.value],y=u.value;return typeof p==typeof y&&p>=y}],"filter-id->=":[di,[hi],(h,[l])=>{const u=h.id(),p=l.value;return typeof u==typeof p&&u>=p}],"filter-has":[di,[hi],(h,[l])=>l.value in h.properties()],"filter-has-id":[di,[],h=>h.id()!==null&&h.id()!==void 0],"filter-type-in":[di,[Ko(li)],(h,[l])=>l.value.indexOf(h.geometryType())>=0],"filter-id-in":[di,[Ko(hi)],(h,[l])=>l.value.indexOf(h.id())>=0],"filter-in-small":[di,[li,Ko(hi)],(h,[l,u])=>u.value.indexOf(h.properties()[l.value])>=0],"filter-in-large":[di,[li,Ko(hi)],(h,[l,u])=>function(p,y,b,S){for(;b<=S;){const k=b+S>>1;if(y[k]===p)return!0;y[k]>p?S=k-1:b=k+1}return!1}(h.properties()[l.value],u.value,0,u.value.length-1)],all:{type:di,overloads:[[[di,di],(h,[l,u])=>l.evaluate(h)&&u.evaluate(h)],[hf(di),(h,l)=>{for(const u of l)if(!u.evaluate(h))return!1;return!0}]]},any:{type:di,overloads:[[[di,di],(h,[l,u])=>l.evaluate(h)||u.evaluate(h)],[hf(di),(h,l)=>{for(const u of l)if(u.evaluate(h))return!0;return!1}]]},"!":[di,[di],(h,[l])=>!l.evaluate(h)],"is-supported-script":[di,[li],(h,[l])=>{const u=h.globals&&h.globals.isSupportedScript;return!u||u(l.evaluate(h))}],upcase:[li,[li],(h,[l])=>l.evaluate(h).toUpperCase()],downcase:[li,[li],(h,[l])=>l.evaluate(h).toLowerCase()],concat:[li,hf(hi),(h,l)=>l.map(u=>Kr(u.evaluate(h))).join("")],"resolved-locale":[li,[bp],(h,[l])=>l.evaluate(h).resolvedLocale()],random:[Dr,[Dr,Dr,hi],(h,l)=>{const[u,p,y]=l.map(S=>S.evaluate(h));if(u>p||u===p)return u;let b;if(typeof y=="string")b=function(S){let k=0;if(S.length===0)return k;for(let j=0;jJSON.stringify(U)).join(", ")}, but found ${JSON.stringify(z)} instead.`);return z}catch(z){const U=z;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 Hx(h){return Array.isArray(h)&&h.length>0&&typeof h[0]=="string"&&h[0]in fg}function pf(h,l,u,p,y){const b=new mv(fg,[],l?function(k){const j={color:ml,string:li,number:Dr,enum:li,boolean:di,formatted:wx,resolvedImage:Sx};return k.type==="array"?Ko(j[k.value]||hi,k.length):j[k.type]}(l):void 0,void 0,void 0,u,p,y),S=b.parse(h,void 0,void 0,void 0,l&&l.type==="string"?{typeAnnotation:"coerce"}:void 0);return S?Gj(new jv(S,l,u,p,y)):ff(b.errors)}class pg{constructor(l,u,p,y){this.kind=l,this._styleExpression=u,this.isLightConstant=p,this.isLineProgressConstant=y,this.isStateDependent=l!=="constant"&&!lg(u.expression),this.configDependencies=Ev(u.expression),this.isIndoorDependent=Av(u.expression)}evaluateWithoutErrorHandling(l,u,p,y,b,S){return this._styleExpression.evaluateWithoutErrorHandling(l,u,p,y,b,S)}evaluate(l,u,p,y,b,S,k){return this._styleExpression.evaluate(l,u,p,y,b,S,void 0,void 0,k)}}class jp{constructor(l,u,p,y,b,S){this.kind=l,this.zoomStops=p,this._styleExpression=u,this.isStateDependent=l!=="camera"&&!lg(u.expression),this.isIndoorDependent=Av(u.expression),this.isLightConstant=b,this.isLineProgressConstant=S,this.configDependencies=Ev(u.expression),this.interpolationType=y}evaluateWithoutErrorHandling(l,u,p,y,b,S){return this._styleExpression.evaluateWithoutErrorHandling(l,u,p,y,b,S)}evaluate(l,u,p,y,b,S){return this._styleExpression.evaluate(l,u,p,y,b,S)}interpolationFactor(l,u,p){return this.interpolationType?Ro.interpolationFactor(this.interpolationType,l,u,p):0}}function kT(h,l,u,p,y){if((h=pf(h,l,u,p,y)).result==="error")return h;const b=h.value.expression,S=kp(b);if(!S&&!kv(l))return ff([new su("","data expressions not supported")]);const k=yd(b,["zoom","pitch","distance-from-center"]);if(!k&&!ET(l))return ff([new su("","zoom expressions not supported")]);const j=yd(b,["measure-light"]);if(!j&&!Hj(l))return ff([new su("","measure-light expression not supported")]);const O=yd(b,["line-progress"]);if(!O&&!function(q){return Gx(q.expression,"line-progress")}(l))return ff([new su("","line-progress expression not supported")]);const z=l.expression&&l.expression.relaxZoomRestriction,U=Mu(b);return U||k||z?U instanceof su?ff([U]):U instanceof Ro&&!Cv(l)?ff([new su("",'"interpolate" expressions cannot be used with this property')]):Gj(U?new jp(S&&O?"camera":"composite",h.value,U.labels,U instanceof Ro?U.interpolation:void 0,j,O):new pg(S&&O?"constant":"source",h.value,j,O)):ff([new su("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class Iv{constructor(l,u){this._parameters=l,this._specification=u,Object.assign(this,Kj(this._parameters,this._specification))}static deserialize(l){return new Iv(l._parameters,l._specification)}static serialize(l){return{_parameters:l._parameters,_specification:l._specification}}}function Mu(h){let l=null;if(h instanceof xv)l=Mu(h.result);else if(h instanceof Bx){for(const u of h.args)if(l=Mu(u),l)break}else(h instanceof Ox||h instanceof Ro)&&h.input instanceof Pa&&h.input.name==="zoom"&&(l=h);return l instanceof su||h.eachChild(u=>{const p=Mu(u);p instanceof su?l=p:l&&p&&l!==p&&(l=new su("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),l}var CT,Xj,Wx=function(){if(Xj)return CT;Xj=1,CT=l;var h=3;function l(u,p,y){var b=this.cells=[];if(u instanceof ArrayBuffer){this.arrayBuffer=u;var S=new Int32Array(this.arrayBuffer);u=S[0],this.d=(p=S[1])+2*(y=S[2]);for(var k=0;k=q[J+0]&&b>=q[J+1])?(j[Z]=!0,k.push(U[Z])):j[Z]=!1}}},l.prototype._forEachCell=function(u,p,y,b,S,k,j,O){for(var z=this._convertToCellCoord(u),U=this._convertToCellCoord(p),q=this._convertToCellCoord(y),K=this._convertToCellCoord(b),Z=z;Z<=q;Z++)for(var J=U;J<=K;J++){var ne=this.d*J+Z;if((!O||O(this._convertFromCellCoord(Z),this._convertFromCellCoord(J),this._convertFromCellCoord(Z+1),this._convertFromCellCoord(J+1)))&&S.call(this,u,p,y,b,ne,k,j,O))return}},l.prototype._convertFromCellCoord=function(u){return(u-this.padding)/this.scale},l.prototype._convertToCellCoord=function(u){return Math.max(0,Math.min(this.d-1,Math.floor(u*this.scale)+this.padding))},l.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var u=this.cells,p=h+this.cells.length+1+1,y=0,b=0;b=0||(y[b]=uh(h[b],l)));h instanceof Error&&(y.message=h.message)}if(y.$name)throw new Error("$name property is reserved for worker serialization logic.");return p!=="Object"&&(y.$name=p),y}throw new Error("can't serialize object of type "+typeof h)}function mf(h){if(h==null||typeof h=="boolean"||typeof h=="number"||typeof h=="string"||h instanceof Boolean||h instanceof Number||h instanceof String||h instanceof Date||h instanceof RegExp||Kx(h)||h instanceof ImageBitmap||ArrayBuffer.isView(h)||h instanceof ImageData)return h;if(Array.isArray(h))return h.map(mf);if(typeof h=="object"){const l=h.$name||"Object";if(l==="Map"){const y=h.entries||[],b=new Map;for(let S=0;Sh>=1536&&h<=1791,Pv=h=>h>=1872&&h<=1919,Nv=h=>h>=2208&&h<=2303,Rv=h=>h>=11904&&h<=12031,dh=h=>h>=12032&&h<=12255,jT=h=>h>=12272&&h<=12287,Yx=h=>h>=12288&&h<=12351,Zx=h=>h>=12352&&h<=12447,Pp=h=>h>=12448&&h<=12543,IT=h=>h>=12544&&h<=12591,Lv=h=>h>=12704&&h<=12735,_d=h=>h>=12736&&h<=12783,Jj=h=>h>=12784&&h<=12799,eI=h=>h>=12800&&h<=13055,tI=h=>h>=13056&&h<=13311,PT=h=>h>=13312&&h<=19903,Dv=h=>h>=19968&&h<=40959,Xx=h=>h>=40960&&h<=42127,NT=h=>h>=42128&&h<=42191,RT=h=>h>=44032&&h<=55215,Ov=h=>h>=63744&&h<=64255,LT=h=>h>=64336&&h<=65023,rI=h=>h>=65040&&h<=65055,DT=h=>h>=65072&&h<=65103,nI=h=>h>=65104&&h<=65135,OT=h=>h>=65136&&h<=65279,MT=h=>h>=65280&&h<=65519;function FT(h){for(const l of h)if(BT(l.charCodeAt(0)))return!0;return!1}function L3(h){for(const l of h)if(!D3(l.charCodeAt(0)))return!1;return!0}function D3(h){return!(Qj(h)||Pv(h)||Nv(h)||LT(h)||OT(h))}function O3(h){return!(h<11904||!(Lv(h)||IT(h)||DT(h)||Ov(h)||tI(h)||Rv(h)||_d(h)||Yx(h)||PT(h)||Dv(h)||eI(h)||MT(h)||Zx(h)||jT(h)||dh(h)||Jj(h)||Pp(h)||rI(h)||NT(h)||Xx(h)))}function BT(h){return!(h!==746&&h!==747&&(h<4352||!(Lv(h)||IT(h)||DT(h)&&!(h>=65097&&h<=65103)||Ov(h)||tI(h)||Rv(h)||_d(h)||!(!Yx(h)||h>=12296&&h<=12305||h>=12308&&h<=12319||h===12336)||PT(h)||Dv(h)||eI(h)||(l=>l>=12592&&l<=12687)(h)||(l=>l>=43360&&l<=43391)(h)||(l=>l>=55216&&l<=55295)(h)||(l=>l>=4352&&l<=4607)(h)||RT(h)||Zx(h)||jT(h)||(l=>l>=12688&&l<=12703)(h)||dh(h)||Jj(h)||Pp(h)&&h!==12540||!(!MT(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)||!(!nI(h)||h>=65112&&h<=65118||h>=65123&&h<=65126)||(l=>l>=5120&&l<=5759)(h)||(l=>l>=6320&&l<=6399)(h)||rI(h)||(l=>l>=19904&&l<=19967)(h)||Xx(h)||NT(h))))}function iI(h){return h===12312||h===12313||h===12316||h===12540||h===12448}function Np(h){return!(BT(h)||function(l){return!!((u=>u>=128&&u<=255)(l)&&(l===167||l===169||l===174||l===177||l===188||l===189||l===190||l===215||l===247)||(u=>u>=8192&&u<=8303)(l)&&(l===8214||l===8224||l===8225||l===8240||l===8241||l===8251||l===8252||l===8258||l===8263||l===8264||l===8265||l===8273)||(u=>u>=8448&&u<=8527)(l)||(u=>u>=8528&&u<=8591)(l)||(u=>u>=8960&&u<=9215)(l)&&(l>=8960&&l<=8967||l>=8972&&l<=8991||l>=8996&&l<=9e3||l===9003||l>=9085&&l<=9114||l>=9150&&l<=9165||l===9167||l>=9169&&l<=9179||l>=9186&&l<=9215)||(u=>u>=9216&&u<=9279)(l)&&l!==9251||(u=>u>=9280&&u<=9311)(l)||(u=>u>=9312&&u<=9471)(l)||(u=>u>=9632&&u<=9727)(l)||(u=>u>=9728&&u<=9983)(l)&&!(l>=9754&&l<=9759)||(u=>u>=11008&&u<=11263)(l)&&(l>=11026&&l<=11055||l>=11088&&l<=11097||l>=11192&&l<=11243)||Yx(l)||Pp(l)||(u=>u>=57344&&u<=63743)(l)||DT(l)||nI(l)||MT(l)||l===8734||l===8756||l===8757||l>=9984&&l<=10087||l>=10102&&l<=10131||l===65532||l===65533)}(h))}function sI(h){return Qj(h)||Pv(h)||Nv(h)||LT(h)||OT(h)}function zT(h){return h>=1424&&h<=2303||LT(h)||OT(h)}function Mv(h,l){return!(!l&&zT(h)||h>=2304&&h<=3583||h>=3840&&h<=4255||(u=>u>=6016&&u<=6143)(h))}function M3(h){for(const l of h)if(zT(l.charCodeAt(0)))return!0;return!1}const nc={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let vd=null,Yo=nc.unavailable,Sc=null;const aI=function(h){h&&typeof h=="string"&&h.indexOf("NetworkError")>-1&&(Yo=nc.error),vd&&vd(h)};function $T(){UT.fire(new Nu("pluginStateChange",{pluginStatus:Yo,pluginURL:Sc}))}const UT=new bx,VT=function(){return Yo},oI=function(){if(Yo!==nc.deferred||!Sc)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Yo=nc.loading,$T(),Sc&&Xm({url:Sc},h=>{h?aI(h):(Yo=nc.loaded,$T())})},hh={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Yo===nc.loaded||hh.applyArabicShaping!=null,isLoading:()=>Yo===nc.loading,setState(h){Yo=h.pluginStatus,Sc=h.pluginURL},isParsing:()=>Yo===nc.parsing,isParsed:()=>Yo===nc.parsed,getPluginURL:()=>Sc},lI=function(){hh.isLoading()||hh.isLoaded()||VT()!=="deferred"||oI()};class ti{constructor(l,u){this.zoom=l,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(l){return function(u,p){for(const y of u)if(!Mv(y.charCodeAt(0),p))return!1;return!0}(l,hh.isLoaded())}}class gg{constructor(l,u,p,y,b){this.property=l,this.value=u,this.expression=function(S,k,j,O,z){if(AT(S))return new Iv(S,k);if(Hx(S)||Array.isArray(S)&&S.length>0){const U=kT(S,k,j,O,z);if(U.result==="error")throw new Error(U.value.map(q=>`${q.key}: ${q.message}`).join(", "));return U.value}{let U=S;return typeof S=="string"&&k.type==="color"&&(U=Yn.parse(S)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>U}}}(u===void 0?l.specification.default:u,l.specification,p,y,b)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(l,u,p,y){return this.property.possiblyEvaluate(this,l,u,p,y)}}class Fv{constructor(l,u,p,y){this.property=l,this.value=new gg(l,void 0,u,p,y)}transitioned(l,u){return new yg(this.property,this.value,u,Object.assign({},l.transition,this.transition),l.now)}untransitioned(){return new yg(this.property,this.value,null,{},0)}}class Bv{constructor(l,u,p,y){this._properties=l,this._values=Object.create(l.defaultTransitionablePropertyValues),this._scope=u,this._options=p,this._iconImageUseTheme=y,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(l){return fr(this._values[l].value.value)}setValue(l,u){this._values.hasOwnProperty(l)||(this._values[l]=new Fv(this._values[l].property,this._scope,this._options,this._iconImageUseTheme)),this._values[l].value=new gg(this._values[l].property,u===null?void 0:fr(u),this._scope,this._options,this._iconImageUseTheme),this._values[l].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[l].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[l].value.isIndoorDependent())}setTransitionOrValue(l,u){u&&(this._options=u);const p=this._properties.properties;if(l)for(const y in l){const b=l[y];if(y.endsWith("-transition")){const S=y.slice(0,-11);p[S]&&this.setTransition(S,b)}else p.hasOwnProperty(y)&&this.setValue(y,b)}}getTransition(l){return fr(this._values[l].transition)}setTransition(l,u){this._values.hasOwnProperty(l)||(this._values[l]=new Fv(this._values[l].property)),this._values[l].transition=fr(u)||void 0}serialize(){const l={};for(const u of Object.keys(this._values)){const p=this.getValue(u);p!==void 0&&(l[u]=p);const y=this.getTransition(u);y!==void 0&&(l[`${u}-transition`]=y)}return l}transitioned(l,u){const p=new qT(this._properties);for(const y of Object.keys(this._values))p._values[y]=this._values[y].transitioned(l,u._values[y]);return p}untransitioned(){const l=new qT(this._properties);for(const u of Object.keys(this._values))l._values[u]=this._values[u].untransitioned();return l}isIndoorDependent(){return this._isIndoorDependent}}class yg{constructor(l,u,p,y,b){const S=y.delay||0,k=y.duration||0;b=b||0,this.property=l,this.value=u,this.begin=b+S,this.end=this.begin+k,l.specification.transition&&(y.delay||y.duration)&&(this.prior=p)}possiblyEvaluate(l,u,p){const y=l.now||0,b=this.value.possiblyEvaluate(l,u,p),S=this.prior;if(S){if(y>this.end)return this.prior=null,b;if(this.value.isDataDriven())return this.prior=null,b;if(y":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":{"expression":{"type":"expression"},"stops":{"type":"array","value":"function_stop"},"base":{"type":"number","default":1,"minimum":0},"property":{"type":"string","default":"$zoom"},"type":{"type":"enum","values":{"identity":1,"exponential":1,"interval":1,"categorical":1},"default":"exponential"},"colorSpace":{"type":"enum","values":{"rgb":1,"lab":1,"hcl":1},"default":"rgb"},"default":{"type":"*"}},"function_stop":{"type":"array","minimum":0,"maximum":24,"value":["number","color"],"length":2},"expression":{"type":"array","value":"*","minimum":1},"fog":{"range":{"type":"array","default":[0.5,10],"minimum":-20,"maximum":20,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"high-color":{"type":"color","default":"#245cdf","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"space-color":{"type":"color","default":["interpolate",["linear"],["zoom"],4,"#010b19",7,"#367ab9"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"horizon-blend":{"type":"number","default":["interpolate",["linear"],["zoom"],4,0.2,7,0.1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"star-intensity":{"type":"number","default":["interpolate",["linear"],["zoom"],5,0.35,6,0],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vertical-range":{"type":"array","default":[0,0],"minimum":0,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}}},"snow":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.85],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.3],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.4,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,50],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"flake-size":{"type":"number","default":0.71,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"rain":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.5],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#03113d",0.3,"#a8adbc"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"opacity":{"type":"number","default":["interpolate",["linear"],["measure-light","brightness"],0,0.88,1,0.7],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,1],"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"vignette-color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#001736",0.3,"#464646"],"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"use-theme":true,"transition":true},"center-thinning":{"type":"number","default":0.57,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true},"direction":{"type":"array","default":[0,80],"minimum":0,"maximum":360,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"droplet-size":{"type":"array","default":[2.6,18.2],"minimum":0,"maximum":50,"length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true}},"distortion-strength":{"type":"number","default":0.7,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"],"relaxZoomRestriction":true},"transition":true}},"camera":{"camera-projection":{"type":"enum","values":{"perspective":1,"orthographic":1},"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]},"default":"perspective"}},"colorTheme":{"data":{"type":"string","expression":{}}},"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","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":true,"parameters":["zoom"]},"use-theme":true,"transition":true},"intensity":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"projection":{"name":{"type":"enum","values":{"albers":1,"equalEarth":1,"equirectangular":1,"lambertConformalConic":1,"mercator":1,"naturalEarth":1,"winkelTripel":1,"globe":1},"default":"mercator"},"center":{"type":"array","length":2,"value":"number","minimum":[-180,-90],"maximum":[180,90]},"parallels":{"type":"array","length":2,"value":"number","minimum":[-90,-90],"maximum":[90,90]}},"terrain":{"source":{"type":"string"},"exaggeration":{"type":"number","default":1,"minimum":0,"maximum":1000,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true}},"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,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-outline-color":{"type":"color","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-bridge-guard-rail-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"},"fill-tunnel-structure-color":{"type":"color","default":"rgba(241, 236, 225, 255)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature"]},"property-type":"data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"fill-extrusion-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"fill-extrusion-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-height":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-height-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"flat"},"fill-extrusion-base-alignment":{"type":"enum","values":{"terrain":1,"flat":1},"default":"terrain"},"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":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-wall-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"fill-extrusion-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"fill-extrusion-flood-light-wall-radius":{"property-type":"data-driven","type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-radius":{"property-type":"data-driven","type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state"]}},"fill-extrusion-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"fill-extrusion-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"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":{}},"fill-extrusion-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"fill-extrusion-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"property-type":"data-driven"},"fill-extrusion-line-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"fill-extrusion-cast-shadows":{"type":"boolean","default":true}},"paint_building":{"building-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"parameters":[]},"transition":true},"building-ambient-occlusion-ground-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"building-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-vertical-scale":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"building-cast-shadows":{"type":"boolean","default":true},"building-color":{"type":"color","default":"rgba(193, 154, 127, 1)","use-theme":true,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"property-type":"data-driven"},"building-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"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":true,"parameters":["measure-light","zoom"]}},"building-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"building-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"building-flood-light-color":{"type":"color","default":"#ffffff","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"building-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_line":{"line-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"line-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"line-width":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light","line-progress"]},"property-type":"data-driven"},"line-gap-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-offset":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"line-dasharray":{"type":"array","value":"number","minimum":0,"expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom","feature"]},"property-type":"data-driven"},"line-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-gradient":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["line-progress"]}},"line-trim-offset":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1]},"line-trim-fade-range":{"type":"array","value":"number","length":2,"default":[0,0],"minimum":[0,0],"maximum":[1,1],"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-trim-color":{"type":"color","default":"transparent","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"line-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]},"property-type":"data-driven"},"line-border-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-border-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom"]},"transition":true},"line-blend-mode":{"type":"enum","values":{"default":1,"multiply":1,"additive":1},"default":"default","expression":{"parameters":["zoom"]}}},"paint_circle":{"circle-radius":{"type":"number","default":5,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-blur":{"type":"number","default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"circle-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"circle-pitch-scale":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"circle-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]}},"circle-stroke-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-stroke-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"circle-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_heatmap":{"heatmap-radius":{"type":"number","default":30,"minimum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-weight":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"property-type":"data-driven"},"heatmap-intensity":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"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"],"use-theme":true,"expression":{"interpolated":true,"parameters":["heatmap-density"]}},"heatmap-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_symbol":{"icon-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"appearance":true,"property-type":"data-driven"},"text-emissive-strength":{"type":"number","default":1,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light","feature-state"]},"appearance":true,"property-type":"data-driven"},"icon-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"icon-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"icon-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"icon-image-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"text-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-occlusion-opacity":{"type":"number","minimum":0,"maximum":1,"default":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"overridable":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-width":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-halo-blur":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","feature","feature-state","measure-light"]},"appearance":true,"property-type":"data-driven"},"text-translate":{"type":"array","value":"number","length":2,"default":[0,0],"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"text-translate-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":["zoom"]}},"icon-color-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{}},"icon-color-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{}},"icon-color-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"icon-color-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{}},"symbol-z-offset":{"type":"number","default":0,"minimum":0,"transition":true,"appearance":true,"expression":{"interpolated":true,"parameters":["zoom","feature"]},"property-type":"data-driven"}},"paint_raster":{"raster-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-color":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["raster-value"]}},"raster-color-mix":{"type":"array","default":[0.2126,0.7152,0.0722,0],"length":4,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-color-range":{"type":"array","length":2,"value":"number","transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-hue-rotate":{"type":"number","default":0,"period":360,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-resampling":{"type":"enum","values":{"linear":1,"nearest":1},"default":"linear","expression":{"parameters":["zoom"]}},"raster-fade-duration":{"type":"number","default":300,"minimum":0,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"raster-array-band":{"type":"string"},"raster-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-elevation-reference":{"type":"enum","values":{"sea":1,"ground":1},"default":"sea","expression":{}}},"paint_raster-particle":{"raster-particle-array-band":{"type":"string"},"raster-particle-count":{"type":"number","default":512,"minimum":1},"raster-particle-color":{"type":"color","use-theme":true,"expression":{"interpolated":true,"parameters":["raster-particle-speed"]}},"raster-particle-max-speed":{"type":"number","default":1,"minimum":1},"raster-particle-speed-factor":{"type":"number","default":0.2,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-particle-fade-opacity-factor":{"type":"number","default":0.98,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"raster-particle-reset-rate-factor":{"type":"number","default":0.8,"minimum":0,"maximum":1},"raster-particle-elevation":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_hillshade":{"hillshade-illumination-direction":{"type":"number","default":335,"minimum":0,"maximum":359,"expression":{"interpolated":true,"parameters":["zoom"]}},"hillshade-illumination-anchor":{"type":"enum","values":{"map":1,"viewport":1},"default":"viewport","expression":{"parameters":["zoom"]}},"hillshade-exaggeration":{"type":"number","default":0.5,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"hillshade-shadow-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-highlight-color":{"type":"color","default":"#FFFFFF","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-accent-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"hillshade-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_background":{"background-pitch-alignment":{"type":"enum","values":{"map":1,"viewport":1},"default":"map","expression":{"parameters":[]}},"background-color":{"type":"color","default":"#000000","use-theme":true,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}},"background-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom"]}},"background-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}},"background-emissive-strength":{"type":"number","default":0,"minimum":0,"transition":true,"expression":{"interpolated":true,"parameters":["zoom","measure-light"]}}},"paint_sky":{"sky-type":{"type":"enum","values":{"gradient":1,"atmosphere":1},"default":"atmosphere","expression":{"parameters":["zoom"]}},"sky-atmosphere-sun":{"type":"array","value":"number","length":2,"minimum":[0,0],"maximum":[360,180],"expression":{"parameters":["zoom"]}},"sky-atmosphere-sun-intensity":{"type":"number","default":10,"minimum":0,"maximum":100},"sky-gradient-center":{"type":"array","value":"number","default":[0,0],"length":2,"minimum":[0,0],"maximum":[360,180],"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"],"use-theme":true,"expression":{"interpolated":true,"parameters":["sky-radial-progress"]}},"sky-atmosphere-halo-color":{"type":"color","default":"white","use-theme":true},"sky-atmosphere-color":{"type":"color","default":"white","use-theme":true},"sky-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["zoom"]}}},"paint_model":{"model-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"transition":true,"expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"property-type":"data-driven"},"model-rotation":{"type":"array","value":"number","length":3,"default":[0,0,0],"period":360,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-scale":{"type":"array","value":"number","length":3,"default":[1,1,1],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-translation":{"type":"array","value":"number","length":3,"default":[0,0,0],"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","zoom"]},"transition":true},"model-color":{"type":"color","default":"#ffffff","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light","zoom"]},"use-theme":true,"transition":true},"model-color-mix-intensity":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-type":{"type":"enum","values":{"common-3d":1,"location-indicator":1},"default":"common-3d"},"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":true,"parameters":["zoom"]},"transition":true},"model-emissive-strength":{"type":"number","property-type":"data-driven","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-roughness":{"type":"number","default":1,"minimum":0,"maximum":1,"property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state"]},"transition":true},"model-height-based-emissive-strength-multiplier":{"type":"array","default":[1,1,1,1,0],"length":5,"value":"number","property-type":"data-driven","expression":{"interpolated":true,"parameters":["feature","feature-state","measure-light"]},"transition":true},"model-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{}},"model-front-cutoff":{"type":"array","value":"number","expression":{"interpolated":true,"parameters":["zoom"]},"length":3,"default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1]},"model-elevation-reference":{"type":"enum","values":{"sea":1,"ground":1,"hd-road-markup":1},"default":"ground","expression":{}},"model-ignore-line-cutout":{"type":"boolean","default":false,"expression":{}}},"transition":{"duration":{"type":"number","default":300,"minimum":0},"delay":{"type":"number","default":0,"minimum":0}},"promoteId":{"*":{"type":"*"}}}');function cI(h){return h instanceof Number||h instanceof String||h instanceof Boolean?h.valueOf():h}function zv(h){if(Array.isArray(h))return h.map(zv);if(h instanceof Object&&!(h instanceof Number||h instanceof String||h instanceof Boolean)){const l={};for(const u in h)l[u]=zv(h[u]);return l}return cI(h)}function HT(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 l of h.slice(1))if(!HT(l)&&typeof l!="boolean")return!1;return!0;default:return!0}}function $v(h,l="",u=null,p="fill"){if(h==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};HT(h)||(h=Uv(h));const y=h;let b=!0;try{b=function(z){if(!_g(z))return z;let U=zv(z);return dI(U),U=uI(U),U}(y)}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(y,null,2)} `)}let S=null,k=null;if(p!=="background"&&p!=="sky"&&p!=="slot"){k=nt[`filter_${p}`];const z=pf(b,k,l,u);if(z.result==="error")throw new Error(z.value.map(U=>`${U.key}: ${U.message}`).join(", "));S=(U,q,K)=>z.value.evaluate(U,q,{},K)}let j=null,O=null;if(b!==y){const z=pf(y,k,l,u);if(z.result==="error")throw new Error(z.value.map(U=>`${U.key}: ${U.message}`).join(", "));j=(U,q,K,Z,J)=>z.value.evaluate(U,q,{},K,void 0,void 0,Z,J),O=!kp(z.value.expression)}return{filter:S,dynamicFilter:j||void 0,needGeometry:fI(b),needFeature:!!O}}function uI(h){if(!Array.isArray(h))return h;const l=function(u){if(hI.has(u[0])){for(let p=1;puI(u))}function dI(h){let l=!1;const u=[];if(h[0]==="case"){for(let p=1;p",">=","<","<=","to-boolean"]);function F3(h,l){return hl?1:0}function fI(h){if(!Array.isArray(h))return!1;if(h[0]==="within"||h[0]==="distance")return!0;for(let l=1;l"||l==="<="||l===">="?Vv(h[1],h[2],l):l==="any"?(u=h.slice(1),["any"].concat(u.map(Uv))):l==="all"?["all"].concat(h.slice(1).map(Uv)):l==="none"?["all"].concat(h.slice(1).map(Uv).map(Qx)):l==="in"?WT(h[1],h.slice(2)):l==="!in"?Qx(WT(h[1],h.slice(2))):l==="has"?ph(h[1]):l!=="!has"||Qx(ph(h[1]));var u}function Vv(h,l,u){switch(h){case"$type":return[`filter-type-${u}`,l];case"$id":return[`filter-id-${u}`,l];default:return[`filter-${u}`,h,l]}}function WT(h,l){if(l.length===0)return!1;switch(h){case"$type":return["filter-type-in",["literal",l]];case"$id":return["filter-id-in",["literal",l]];default:return l.length>200&&!l.some(u=>typeof u!=typeof l[0])?["filter-in-large",h,["literal",l.sort(F3)]]:["filter-in-small",h,["literal",l]]}}function ph(h){switch(h){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",h]}}function Qx(h){return["!",h]}const Jx="";function Lp(h,l){return l?`${h}${Jx}${l}`:h}function pI(h){const l=h.indexOf(Jx);return l>=0?h.slice(l+1):""}let mI;const KT=()=>mI||(mI=new ts({"icon-size":new qt(nt.layout_symbol["icon-size"]),"icon-image":new qt(nt.layout_symbol["icon-image"]),"icon-rotate":new qt(nt.layout_symbol["icon-rotate"]),"icon-offset":new qt(nt.layout_symbol["icon-offset"]),"text-size":new qt(nt.layout_symbol["text-size"]),"text-rotate":new qt(nt.layout_symbol["text-rotate"]),"text-offset":new qt(nt.layout_symbol["text-offset"])}));let YT;const ZT=()=>YT||(YT=new ts({"icon-opacity":new qt(nt.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new qt(nt.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new qt(nt.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new qt(nt.paint_symbol["text-emissive-strength"]),"icon-color":new qt(nt.paint_symbol["icon-color"]),"icon-halo-color":new qt(nt.paint_symbol["icon-halo-color"]),"icon-halo-width":new qt(nt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new qt(nt.paint_symbol["icon-halo-blur"]),"icon-translate":new qt(nt.paint_symbol["icon-translate"]),"text-opacity":new qt(nt.paint_symbol["text-opacity"]),"text-occlusion-opacity":new qt(nt.paint_symbol["text-occlusion-opacity"]),"text-color":new qt(nt.paint_symbol["text-color"],{runtimeType:ml,getOverride:h=>h.textColor,hasOverride:h=>!!h.textColor}),"text-halo-color":new qt(nt.paint_symbol["text-halo-color"]),"text-halo-width":new qt(nt.paint_symbol["text-halo-width"]),"text-halo-blur":new qt(nt.paint_symbol["text-halo-blur"]),"text-translate":new qt(nt.paint_symbol["text-translate"]),"symbol-z-offset":new qt(nt.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"})}));class B3{constructor(l,u,p,y,b,S){this._conditionSpec=l,this._propertiesSpec=p;const k=pf(l,nt.appearance.condition);if(k.result==="success"&&(this.condition=k.value),this.name=u,p){this.layoutProperties=new fh(KT()),this.unevaluatedLayout=new GT(KT(),y,b,S),this.paintProperties=new fh(ZT()),this.unevaluatedPaint=new GT(ZT(),y,b,"");for(const j in p)j in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(j,p[j]):j in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(j,p[j])}}isActive(l){return!(this.condition||!l.isHidden||this.name!=="hidden")||this.condition.evaluate(l.globals,l.feature,l.featureState,l.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(l){return this.layoutProperties.get(l)}getPaintProperty(l){return this.paintProperties.get(l)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(l){return this.unevaluatedLayout._values[l]}getUnevaluatedPaintProperty(l){return this.unevaluatedPaint._values[l]}recalculate(l,u,p){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(l,void 0,u,p)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(l,void 0,u,""))}serialize(){const l={};l.condition=this.condition.expression.serialize(),this.name&&(l.name=this.name);const u=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},p=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},y=Object.assign({},u,p);return Object.keys(y).length>0&&(l.properties=y),l}hasIconLayoutProperties(){const l=this.hasLayoutProperty("icon-image"),u=this.hasLayoutProperty("icon-size"),p=this.hasLayoutProperty("icon-offset"),y=this.hasLayoutProperty("icon-rotate");return l||u||p||y}hasTextLayoutProperties(){const l=this.hasLayoutProperty("text-size"),u=this.hasLayoutProperty("text-offset"),p=this.hasLayoutProperty("text-rotate");return l||u||p}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(l=>!l.endsWith("-use-theme")).some(l=>(l.startsWith("icon-")||l==="symbol-z-offset")&&this.hasPaintProperty(l))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(l=>!l.endsWith("-use-theme")).some(l=>(l.startsWith("text-")||l==="symbol-z-offset")&&this.hasPaintProperty(l))}hasLayoutProperty(l){return this.unevaluatedLayout&&this.unevaluatedLayout._values[l].value!==void 0}hasPaintProperty(l){return this.unevaluatedPaint&&this.unevaluatedPaint._values[l].value!==void 0}}const XT="-transition",z3=new Set(["fill","line","background","hillshade","raster"]);class Zo extends bx{constructor(l,u,p,y,b,S){if(super(),this.id=l.id,this.fqid=Lp(this.id,p),this.type=l.type,this.scope=p,this.lut=y,this.options=b,this.iconImageUseTheme=S,this.appearances=new Array,this.appearancesVersion=0,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,this.expressionDependencies={isIndoorDependent:!1,configDependencies:new Set},l.type!=="custom"){if(this.metadata=l.metadata,this.minzoom=l.minzoom,this.maxzoom=l.maxzoom,l.type&&l.type!=="background"&&l.type!=="sky"&&l.type!=="slot"){this.source=l.source,this.sourceLayer=l["source-layer"],this.filter=l.filter;const k=pf(this.filter,nt[`filter_${l.type}`]);k.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...k.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||k.value.isIndoorDependent)}if(l.slot&&(this.slot=l.slot),l.appearances&&this.setAppearances(l.appearances),u.layout&&(this._unevaluatedLayout=new GT(u.layout,this.scope,b,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),u.paint){this._transitionablePaint=new Bv(u.paint,this.scope,b);for(const k in l.paint)this.setPaintProperty(k,l.paint[k]);for(const k in l.layout)this.setLayoutProperty(k,l.layout[k]);this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._transitionablePaint.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._transitionablePaint.isIndoorDependent(),this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new fh(u.paint)}}}onAdd(l){}onRemove(l){}isDraped(l){return!this.is3D(!0)&&z3.has(this.type)}getLayoutProperty(l){return l==="visibility"?this.visibility:this._unevaluatedLayout.getValue(l)}setLayoutProperty(l,u){if(this.type==="custom"&&l==="visibility")return void(this.visibility=u);const p=this._unevaluatedLayout;p._properties.properties[l]&&(p.setValue(l,u),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...p.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||p.isIndoorDependent(),l==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(l){this.appearances=[],l.forEach(u=>{this.appearances.push(new B3(u.condition,u.name,u.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(l){return l.endsWith(XT)?this._transitionablePaint.getTransition(l.slice(0,-11)):this._transitionablePaint.getValue(l)}isPaintProperty(l){return!!this._transitionablePaint._properties.properties[l]}setPaintProperty(l,u){const p=this._transitionablePaint,y=p._properties.properties;if(l.endsWith(XT)){const U=l.slice(0,-11);return y[U]&&p.setTransition(U,u||void 0),!1}if(!y[l])return!1;const b=p._values[l],S=b.value.isDataDriven(),k=b.value;p.setValue(l,u),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...p.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||p.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(l);const j=p._values[l].value,O=j.isDataDriven(),z=l.endsWith("pattern")||l==="line-dasharray";return O||S||z||this._handleOverridablePaintPropertyUpdate(l,k,j)}_handleSpecialPaintPropertyUpdate(l){}getProgramIds(){return null}getDefaultProgramParams(l,u,p){return null}_handleOverridablePaintPropertyUpdate(l,u,p){return!1}isHidden(l){return!!(this.minzoom&&l=this.maxzoom)||this.visibility==="none"}updateTransitions(l){this._transitioningPaint=this._transitionablePaint.transitioned(l,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(l,u){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(l,void 0,u,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(l,void 0,u)}serialize(){const l={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._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.appearances.length!==0&&(l.appearances=this.appearances.map(u=>u.serialize())),Nt(l,(u,p)=>!(u===void 0||p==="layout"&&!Object.keys(u).length||p==="paint"&&!Object.keys(u).length))}is3D(l){return!1}hasElevation(){return!1}isSky(){return!1}isTileClipped(){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 l in this.paint._values){const u=this.paint.get(l);if(u instanceof Rp&&kv(u.property.specification)&&(u.value.kind==="source"||u.value.kind==="composite")&&u.value.isStateDependent)return!0}for(const l of this.appearances)if(!lg(l.condition.expression))return!0;return!1}compileFilter(l){this._filterCompiled||(this._featureFilter=$v(this.filter,this.scope,l),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(l){this._stats&&(l.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(l,u,p){return{}}queryRadius(l){}queryIntersectsFeature(l,u,p,y,b,S,k,j,O,z){}}const qv={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class e_{constructor(l,u){this._structArray=l,this._pos1=u*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const $3=new ArrayBuffer(0);class $i{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(l,u){return l._trim(),u&&l.arrayBuffer&&u.add(l.arrayBuffer),{length:l.length,arrayBuffer:l.arrayBuffer}}static deserialize(l){const u=Object.create(this.prototype);return u.arrayBuffer=l.arrayBuffer,u.length=l.length,l.arrayBuffer?u.capacity=l.arrayBuffer.byteLength/u.bytesPerElement:(u.capacity=0,u.arrayBuffer=$3),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(l){this.reserve(l),this.length=l}reserve(l){if(l>this.capacity){this._reallocCount++,this.capacity=Math.max(l,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const u=this.uint8;this._refreshViews(),u&&this.uint8.set(u)}}reserveForAdditional(l){this.reserve(this.length+l)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...l){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...l){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 Pn(h,l=1){let u=0,p=0;return{members:h.map(y=>{const b=qv[y.type].BYTES_PER_ELEMENT,S=u=gI(u,Math.max(l,b)),k=y.components||1;return p=Math.max(p,b),u+=b*k,{name:y.name,type:y.type,components:k,offset:S}}),size:gI(u,Math.max(p,l)),alignment:l}}function gI(h,l){return Math.ceil(h/l)*l}class ic extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u){const p=this.length;return this.resize(p+1),this.emplace(p,l,u)}emplace(l,u,p){const y=2*l;return this.int16[y+0]=u,this.int16[y+1]=p,l}}ic.prototype.bytesPerElement=4,vr(ic,"StructArrayLayout2i4");class bd extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p){const y=this.length;return this.resize(y+1),this.emplace(y,l,u,p)}emplace(l,u,p,y){const b=3*l;return this.int16[b+0]=u,this.int16[b+1]=p,this.int16[b+2]=y,l}}bd.prototype.bytesPerElement=6,vr(bd,"StructArrayLayout3i6");class xo extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,p,y){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,p,y)}emplace(l,u,p,y,b){const S=4*l;return this.int16[S+0]=u,this.int16[S+1]=p,this.uint16[S+2]=y,this.uint16[S+3]=b,l}}xo.prototype.bytesPerElement=8,vr(xo,"StructArrayLayout2i2ui8");class Tc extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l){const u=this.length;return this.resize(u+1),this.emplace(u,l)}emplace(l,u){return this.float32[1*l+0]=u,l}}Tc.prototype.bytesPerElement=4,vr(Tc,"StructArrayLayout1f4");class QT extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p){const y=this.length;return this.resize(y+1),this.emplace(y,l,u,p)}emplace(l,u,p,y){const b=4*l,S=2*l;return this.int16[b+0]=u,this.int16[b+1]=p,this.float32[S+1]=y,l}}QT.prototype.bytesPerElement=8,vr(QT,"StructArrayLayout2i1f8");class JT extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p){const y=this.length;return this.resize(y+1),this.emplace(y,l,u,p)}emplace(l,u,p,y){const b=4*l;return this.int16[b+0]=u,this.int16[b+1]=p,this.int16[b+2]=y,l}}JT.prototype.bytesPerElement=8,vr(JT,"StructArrayLayout3i8");class eE extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p,y){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,p,y)}emplace(l,u,p,y,b){const S=4*l;return this.int16[S+0]=u,this.int16[S+1]=p,this.int16[S+2]=y,this.int16[S+3]=b,l}}eE.prototype.bytesPerElement=8,vr(eE,"StructArrayLayout4i8");class tE extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,p,y,b)}emplace(l,u,p,y,b,S){const k=5*l;return this.int16[k+0]=u,this.int16[k+1]=p,this.int16[k+2]=y,this.int16[k+3]=b,this.int16[k+4]=S,l}}tE.prototype.bytesPerElement=10,vr(tE,"StructArrayLayout5i10");class t_ extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S,k){const j=this.length;return this.resize(j+1),this.emplace(j,l,u,p,y,b,S,k)}emplace(l,u,p,y,b,S,k,j){const O=6*l,z=12*l,U=3*l;return this.int16[O+0]=u,this.int16[O+1]=p,this.uint8[z+4]=y,this.uint8[z+5]=b,this.uint8[z+6]=S,this.uint8[z+7]=k,this.float32[U+2]=j,l}}t_.prototype.bytesPerElement=12,vr(t_,"StructArrayLayout2i4ub1f12");class lu extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p){const y=this.length;return this.resize(y+1),this.emplace(y,l,u,p)}emplace(l,u,p,y){const b=3*l;return this.float32[b+0]=u,this.float32[b+1]=p,this.float32[b+2]=y,l}}lu.prototype.bytesPerElement=12,vr(lu,"StructArrayLayout3f12");class wd extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,p,y,b)}emplace(l,u,p,y,b,S){const k=6*l,j=3*l;return this.uint16[k+0]=u,this.uint16[k+1]=p,this.uint16[k+2]=y,this.uint16[k+3]=b,this.float32[j+2]=S,l}}wd.prototype.bytesPerElement=12,vr(wd,"StructArrayLayout4ui1f12");class vg extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,p,y){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,p,y)}emplace(l,u,p,y,b){const S=4*l;return this.uint16[S+0]=u,this.uint16[S+1]=p,this.uint16[S+2]=y,this.uint16[S+3]=b,l}}vg.prototype.bytesPerElement=8,vr(vg,"StructArrayLayout4ui8");class Gv extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S){const k=this.length;return this.resize(k+1),this.emplace(k,l,u,p,y,b,S)}emplace(l,u,p,y,b,S,k){const j=6*l;return this.int16[j+0]=u,this.int16[j+1]=p,this.int16[j+2]=y,this.int16[j+3]=b,this.int16[j+4]=S,this.int16[j+5]=k,l}}Gv.prototype.bytesPerElement=12,vr(Gv,"StructArrayLayout6i12");class rE extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S,k,j,O,z,U,q){const K=this.length;return this.resize(K+1),this.emplace(K,l,u,p,y,b,S,k,j,O,z,U,q)}emplace(l,u,p,y,b,S,k,j,O,z,U,q,K){const Z=12*l;return this.int16[Z+0]=u,this.int16[Z+1]=p,this.int16[Z+2]=y,this.int16[Z+3]=b,this.uint16[Z+4]=S,this.uint16[Z+5]=k,this.uint16[Z+6]=j,this.uint16[Z+7]=O,this.int16[Z+8]=z,this.int16[Z+9]=U,this.int16[Z+10]=q,this.int16[Z+11]=K,l}}rE.prototype.bytesPerElement=24,vr(rE,"StructArrayLayout4i4ui4i24");class nE extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S){const k=this.length;return this.resize(k+1),this.emplace(k,l,u,p,y,b,S)}emplace(l,u,p,y,b,S,k){const j=10*l,O=5*l;return this.int16[j+0]=u,this.int16[j+1]=p,this.int16[j+2]=y,this.float32[O+2]=b,this.float32[O+3]=S,this.float32[O+4]=k,l}}nE.prototype.bytesPerElement=20,vr(nE,"StructArrayLayout3i3f20");class mh extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,p,y)}emplace(l,u,p,y,b){const S=4*l;return this.float32[S+0]=u,this.float32[S+1]=p,this.float32[S+2]=y,this.float32[S+3]=b,l}}mh.prototype.bytesPerElement=16,vr(mh,"StructArrayLayout4f16");class r_ extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(l){const u=this.length;return this.resize(u+1),this.emplace(u,l)}emplace(l,u){return this.uint32[1*l+0]=u,l}}r_.prototype.bytesPerElement=4,vr(r_,"StructArrayLayout1ul4");class cu extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u){const p=this.length;return this.resize(p+1),this.emplace(p,l,u)}emplace(l,u,p){const y=2*l;return this.uint16[y+0]=u,this.uint16[y+1]=p,l}}cu.prototype.bytesPerElement=4,vr(cu,"StructArrayLayout2ui4");class Hv extends $i{_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(l,u,p,y,b,S,k,j,O,z,U,q,K){const Z=this.length;return this.resize(Z+1),this.emplace(Z,l,u,p,y,b,S,k,j,O,z,U,q,K)}emplace(l,u,p,y,b,S,k,j,O,z,U,q,K,Z){const J=20*l,ne=10*l;return this.int16[J+0]=u,this.int16[J+1]=p,this.int16[J+2]=y,this.int16[J+3]=b,this.int16[J+4]=S,this.float32[ne+3]=k,this.float32[ne+4]=j,this.float32[ne+5]=O,this.float32[ne+6]=z,this.int16[J+14]=U,this.uint32[ne+8]=q,this.uint16[J+18]=K,this.uint16[J+19]=Z,l}}Hv.prototype.bytesPerElement=40,vr(Hv,"StructArrayLayout5i4f1i1ul2ui40");class n_ extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S,k){const j=this.length;return this.resize(j+1),this.emplace(j,l,u,p,y,b,S,k)}emplace(l,u,p,y,b,S,k,j){const O=8*l;return this.int16[O+0]=u,this.int16[O+1]=p,this.int16[O+2]=y,this.int16[O+4]=b,this.int16[O+5]=S,this.int16[O+6]=k,this.int16[O+7]=j,l}}n_.prototype.bytesPerElement=16,vr(n_,"StructArrayLayout3i2i2i16");class iE extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,p,y,b)}emplace(l,u,p,y,b,S){const k=4*l,j=8*l;return this.float32[k+0]=u,this.float32[k+1]=p,this.float32[k+2]=y,this.int16[j+6]=b,this.int16[j+7]=S,l}}iE.prototype.bytesPerElement=16,vr(iE,"StructArrayLayout2f1f2i16");class i_ extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S){const k=this.length;return this.resize(k+1),this.emplace(k,l,u,p,y,b,S)}emplace(l,u,p,y,b,S,k){const j=20*l,O=5*l;return this.uint8[j+0]=u,this.uint8[j+1]=p,this.float32[O+1]=y,this.float32[O+2]=b,this.float32[O+3]=S,this.float32[O+4]=k,l}}i_.prototype.bytesPerElement=20,vr(i_,"StructArrayLayout2ub4f20");class _s extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,p){const y=this.length;return this.resize(y+1),this.emplace(y,l,u,p)}emplace(l,u,p,y){const b=3*l;return this.uint16[b+0]=u,this.uint16[b+1]=p,this.uint16[b+2]=y,l}}_s.prototype.bytesPerElement=6,vr(_s,"StructArrayLayout3ui6");class Wv extends $i{_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(l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne,ae,he,ce,ye,Ee){const Ce=this.length;return this.resize(Ce+1),this.emplace(Ce,l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne,ae,he,ce,ye,Ee)}emplace(l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne,ae,he,ce,ye,Ee,Ce){const He=30*l,$e=15*l,Ge=60*l;return this.int16[He+0]=u,this.int16[He+1]=p,this.int16[He+2]=y,this.float32[$e+2]=b,this.float32[$e+3]=S,this.uint16[He+8]=k,this.uint16[He+9]=j,this.uint32[$e+5]=O,this.uint32[$e+6]=z,this.uint32[$e+7]=U,this.uint16[He+16]=q,this.uint16[He+17]=K,this.uint16[He+18]=Z,this.float32[$e+10]=J,this.float32[$e+11]=ne,this.uint8[Ge+48]=ae,this.uint8[Ge+49]=he,this.uint8[Ge+50]=ce,this.uint32[$e+13]=ye,this.int16[He+28]=Ee,this.uint8[Ge+58]=Ce,l}}Wv.prototype.bytesPerElement=60,vr(Wv,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class sE extends $i{_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(l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne,ae,he,ce,ye,Ee,Ce,He,$e,Ge,Ue,Ve,yt,bt,kt,It,Ct,Bt){const pt=this.length;return this.resize(pt+1),this.emplace(pt,l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne,ae,he,ce,ye,Ee,Ce,He,$e,Ge,Ue,Ve,yt,bt,kt,It,Ct,Bt)}emplace(l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne,ae,he,ce,ye,Ee,Ce,He,$e,Ge,Ue,Ve,yt,bt,kt,It,Ct,Bt,pt){const jt=20*l,Lt=40*l,$t=80*l;return this.float32[jt+0]=u,this.float32[jt+1]=p,this.int16[Lt+4]=y,this.int16[Lt+5]=b,this.int16[Lt+6]=S,this.int16[Lt+7]=k,this.int16[Lt+8]=j,this.int16[Lt+9]=O,this.int16[Lt+10]=z,this.int16[Lt+11]=U,this.int16[Lt+12]=q,this.uint16[Lt+13]=K,this.uint16[Lt+14]=Z,this.uint16[Lt+15]=J,this.uint16[Lt+16]=ne,this.uint16[Lt+17]=ae,this.uint16[Lt+18]=he,this.uint16[Lt+19]=ce,this.uint16[Lt+20]=ye,this.uint16[Lt+21]=Ee,this.uint16[Lt+22]=Ce,this.uint16[Lt+23]=He,this.uint16[Lt+24]=$e,this.uint16[Lt+25]=Ge,this.uint16[Lt+26]=Ue,this.uint16[Lt+27]=Ve,this.uint32[jt+14]=yt,this.float32[jt+15]=bt,this.float32[jt+16]=kt,this.float32[jt+17]=It,this.float32[jt+18]=Ct,this.uint8[$t+76]=Bt,this.uint16[Lt+39]=pt,l}}sE.prototype.bytesPerElement=80,vr(sE,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class Kv extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S){const k=this.length;return this.resize(k+1),this.emplace(k,l,u,p,y,b,S)}emplace(l,u,p,y,b,S,k){const j=6*l;return this.float32[j+0]=u,this.float32[j+1]=p,this.float32[j+2]=y,this.float32[j+3]=b,this.float32[j+4]=S,this.float32[j+5]=k,l}}Kv.prototype.bytesPerElement=24,vr(Kv,"StructArrayLayout6f24");class Dp extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b){const S=this.length;return this.resize(S+1),this.emplace(S,l,u,p,y,b)}emplace(l,u,p,y,b,S){const k=5*l;return this.float32[k+0]=u,this.float32[k+1]=p,this.float32[k+2]=y,this.float32[k+3]=b,this.float32[k+4]=S,l}}Dp.prototype.bytesPerElement=20,vr(Dp,"StructArrayLayout5f20");class s_ extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S,k){const j=this.length;return this.resize(j+1),this.emplace(j,l,u,p,y,b,S,k)}emplace(l,u,p,y,b,S,k,j){const O=7*l;return this.float32[O+0]=u,this.float32[O+1]=p,this.float32[O+2]=y,this.float32[O+3]=b,this.float32[O+4]=S,this.float32[O+5]=k,this.float32[O+6]=j,l}}s_.prototype.bytesPerElement=28,vr(s_,"StructArrayLayout7f28");class aE extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S,k,j,O,z,U){const q=this.length;return this.resize(q+1),this.emplace(q,l,u,p,y,b,S,k,j,O,z,U)}emplace(l,u,p,y,b,S,k,j,O,z,U,q){const K=11*l;return this.float32[K+0]=u,this.float32[K+1]=p,this.float32[K+2]=y,this.float32[K+3]=b,this.float32[K+4]=S,this.float32[K+5]=k,this.float32[K+6]=j,this.float32[K+7]=O,this.float32[K+8]=z,this.float32[K+9]=U,this.float32[K+10]=q,l}}aE.prototype.bytesPerElement=44,vr(aE,"StructArrayLayout11f44");class oE extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S,k,j,O){const z=this.length;return this.resize(z+1),this.emplace(z,l,u,p,y,b,S,k,j,O)}emplace(l,u,p,y,b,S,k,j,O,z){const U=9*l;return this.float32[U+0]=u,this.float32[U+1]=p,this.float32[U+2]=y,this.float32[U+3]=b,this.float32[U+4]=S,this.float32[U+5]=k,this.float32[U+6]=j,this.float32[U+7]=O,this.float32[U+8]=z,l}}oE.prototype.bytesPerElement=36,vr(oE,"StructArrayLayout9f36");class Op extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u){const p=this.length;return this.resize(p+1),this.emplace(p,l,u)}emplace(l,u,p){const y=2*l;return this.float32[y+0]=u,this.float32[y+1]=p,l}}Op.prototype.bytesPerElement=8,vr(Op,"StructArrayLayout2f8");class lE extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l,u,p,y){const b=this.length;return this.resize(b+1),this.emplace(b,l,u,p,y)}emplace(l,u,p,y,b){const S=6*l;return this.uint32[3*l+0]=u,this.uint16[S+2]=p,this.uint16[S+3]=y,this.uint16[S+4]=b,l}}lE.prototype.bytesPerElement=12,vr(lE,"StructArrayLayout1ul3ui12");class Mp extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(l){const u=this.length;return this.resize(u+1),this.emplace(u,l)}emplace(l,u){return this.uint16[1*l+0]=u,l}}Mp.prototype.bytesPerElement=2,vr(Mp,"StructArrayLayout1ui2");class cE extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne){const ae=this.length;return this.resize(ae+1),this.emplace(ae,l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne)}emplace(l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne,ae){const he=16*l;return this.float32[he+0]=u,this.float32[he+1]=p,this.float32[he+2]=y,this.float32[he+3]=b,this.float32[he+4]=S,this.float32[he+5]=k,this.float32[he+6]=j,this.float32[he+7]=O,this.float32[he+8]=z,this.float32[he+9]=U,this.float32[he+10]=q,this.float32[he+11]=K,this.float32[he+12]=Z,this.float32[he+13]=J,this.float32[he+14]=ne,this.float32[he+15]=ae,l}}cE.prototype.bytesPerElement=64,vr(cE,"StructArrayLayout16f64");class Yv extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(l,u,p,y,b,S,k){const j=this.length;return this.resize(j+1),this.emplace(j,l,u,p,y,b,S,k)}emplace(l,u,p,y,b,S,k,j){const O=10*l,z=5*l;return this.uint16[O+0]=u,this.uint16[O+1]=p,this.uint16[O+2]=y,this.uint16[O+3]=b,this.float32[z+2]=S,this.float32[z+3]=k,this.float32[z+4]=j,l}}Yv.prototype.bytesPerElement=20,vr(Yv,"StructArrayLayout4ui3f20");class Zv extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(l){const u=this.length;return this.resize(u+1),this.emplace(u,l)}emplace(l,u){return this.int16[1*l+0]=u,l}}Zv.prototype.bytesPerElement=2,vr(Zv,"StructArrayLayout1i2");class Xv extends $i{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(l){const u=this.length;return this.resize(u+1),this.emplace(u,l)}emplace(l,u){return this.uint8[1*l+0]=u,l}}Xv.prototype.bytesPerElement=1,vr(Xv,"StructArrayLayout1ub1");class yI extends e_{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]}}yI.prototype.size=40;class uE extends Hv{get(l){return new yI(this,l)}}vr(uE,"CollisionBoxArray");class xI extends e_{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(l){this._structArray.uint8[this._pos1+49]=l}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(l){this._structArray.uint8[this._pos1+50]=l}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(l){this._structArray.uint32[this._pos4+13]=l}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(l){this._structArray.uint8[this._pos1+58]=l}}xI.prototype.size=60;class _I extends Wv{get(l){return new xI(this,l)}}vr(_I,"PlacedSymbolArray");class a_ extends e_{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(l){this._structArray.uint32[this._pos4+14]=l}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(l){this._structArray.float32[this._pos4+18]=l}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}a_.prototype.size=80;class vI extends sE{get(l){return new a_(this,l)}}vr(vI,"SymbolInstanceArray");class bI extends Tc{getoffsetX(l){return this.float32[1*l+0]}}vr(bI,"GlyphOffsetArray");class o_ extends ic{getx(l){return this.int16[2*l+0]}gety(l){return this.int16[2*l+1]}}vr(o_,"SymbolLineVertexArray");class wI extends e_{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]}}wI.prototype.size=12;class dE extends lE{get(l){return new wI(this,l)}}vr(dE,"FeatureIndexArray");class SI extends cu{geta_centroid_pos0(l){return this.uint16[2*l+0]}geta_centroid_pos1(l){return this.uint16[2*l+1]}}vr(SI,"FillExtrusionCentroidArray");class hE extends e_{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]}}hE.prototype.size=6;class fE extends bd{get(l){return new hE(this,l)}}vr(fE,"FillExtrusionWallArray");const TI=Pn([{name:"a_pos",components:2,type:"Int16"}],4),U3=Pn([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),V3=Pn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Si{constructor(l=[]){this.segments=l}_prepareSegment(l,u,p,y,b){let S=this.segments[this.segments.length-1];return l>Si.MAX_VERTEX_ARRAY_LENGTH&&Br(`Max vertices per segment is ${Si.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${l}`),(!S||S.vertexLength+l>Si.MAX_VERTEX_ARRAY_LENGTH||S.sortKey!==y||b!==void 0&&S&&S.batchIndex!==void 0&&S.batchIndex!==b)&&(S={vertexOffset:u,primitiveOffset:p,vertexLength:0,primitiveLength:0},y!==void 0&&(S.sortKey=y),b!==void 0&&(S.batchIndex=b),this.segments.push(S)),S}prepareSegment(l,u,p,y,b){return this._prepareSegment(l,u.length,p.length,y,b)}get(){return this.segments}destroy(){for(const l of this.segments)for(const u in l.vaos)l.vaos[u].destroy()}static simpleSegment(l,u,p,y){return new Si([{vertexOffset:l,primitiveOffset:u,vertexLength:p,primitiveLength:y,vaos:{},sortKey:0}])}}function Qv(h,l){return 256*(h=fe(Math.floor(h),0,255))+fe(Math.floor(l),0,255)}Si.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,vr(Si,"SegmentVector");const q3=Pn([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),G3=Pn([{name:"a_pattern_b",components:4,type:"Uint16"}]),H3=Pn([{name:"a_dash",components:4,type:"Uint16"}]);class l_{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(l,u,p,y){this.ids.push(pE(l)),this.positions.push(u,p,y)}eachPosition(l,u){const p=pE(l);let y=0,b=this.ids.length-1;for(;y>1;this.ids[S]>=p?b=S:y=S+1}for(;this.ids[y]===p;)u(this.positions[3*y],this.positions[3*y+1],this.positions[3*y+2]),y++}static serialize(l,u){const p=new Float64Array(l.ids),y=new Uint32Array(l.positions);return c_(p,y,0,p.length-1),u&&(u.add(p.buffer),u.add(y.buffer)),{ids:p,positions:y}}static deserialize(l){const u=new l_;let p;u.ids=l.ids,u.positions=l.positions;for(const y of u.ids)y!==p&&u.uniqueIds.push(y),p=y;return u.indexed=!0,u}}function pE(h){const l=+h;return Number.isSafeInteger(l)?l:af(String(h))}function c_(h,l,u,p){for(;u>1];let b=u-1,S=p+1;for(;;){do b++;while(h[b]y);if(b>=S)break;Ec(h,b,S),Ec(l,3*b,3*S),Ec(l,3*b+1,3*S+1),Ec(l,3*b+2,3*S+2)}S-u`u_${b}`),this.type=p,this.context=y}setUniform(l,u,p,y,b){const S=y.constantOr(this.value);u.set(l,b,S instanceof Yn?S.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):S)}getBinding(l,u){return this.type==="color"?new K3(l):new oa(l)}}class ${constructor(l,u){this.uniformNames=u.map(p=>`u_${p}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(l,u){this.pixelRatio=l.pixelRatio||1,this.pattern=l.tl.concat(l.br),this.patternTransition=u?u.tl.concat(u.br):this.pattern}setUniform(l,u,p,y,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(l,b,S)}getBinding(l,u){return u==="u_pattern"||u==="u_pattern_b"||u==="u_dash"?new W3(l):new oa(l)}}class H{constructor(l,u,p,y){this.expression=l,this.type=p,this.maxValue=0,this.paintVertexAttributes=u.map(b=>({name:`a_${b}`,type:"Float32",components:p==="color"?2:1,offset:0})),this.paintVertexArray=new y}populatePaintArray(l,u,p,y,b,S,k,j){const O=this.paintVertexArray.length,z=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new ti(0,{brightness:S,worldview:j}),u,{},b,y,k):this.expression.kind==="constant"&&this.expression.value,U=L(this.lutExpression,u,{},y,b,S,k,j);this.paintVertexArray.resize(l),this._setPaintValue(O,l,z,U?null:this.context.lut)}updatePaintArray(l,u,p,y,b,S,k,j){const O=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:k,worldview:j},p,y,void 0,b):this.expression.kind==="constant"&&this.expression.value,z=L(this.lutExpression,p,y,b,void 0,k,void 0,j);this._setPaintValue(l,u,O,z?null:this.context.lut)}_setPaintValue(l,u,p,y){if(this.type==="color"){const b=I(p.toPremultipliedRenderColor(y));for(let S=l;S`u_${k}_t`),this.type=p,this.useIntegerZoom=y,this.context=b,this.maxValue=0,this.paintVertexAttributes=u.map(k=>({name:`a_${k}`,type:"Float32",components:p==="color"?4:2,offset:0})),this.paintVertexArray=new S}populatePaintArray(l,u,p,y,b,S,k,j){const O=this.expression.evaluate(new ti(this.context.zoom,{brightness:S,worldview:j}),u,{},b,y,k),z=this.expression.evaluate(new ti(this.context.zoom+1,{brightness:S,worldview:j}),u,{},b,y,k),U=L(this.lutExpression,u,{},y,b,S,k,j),q=this.paintVertexArray.length;this.paintVertexArray.resize(l),this._setPaintValue(q,l,O,z,U?null:this.context.lut)}updatePaintArray(l,u,p,y,b,S,k,j){const O=this.expression.evaluate({zoom:this.context.zoom,brightness:k,worldview:j},p,y,void 0,b),z=this.expression.evaluate({zoom:this.context.zoom+1,brightness:k,worldview:j},p,y,void 0,b),U=L(this.lutExpression,p,y,b,void 0,k,void 0,j);this._setPaintValue(l,u,O,z,U?null:this.context.lut)}_setPaintValue(l,u,p,y,b){if(this.type==="color"){const S=I(p.toPremultipliedRenderColor(b)),k=I(y.toPremultipliedRenderColor(b));for(let j=l;j!0){this.binders={},this._buffers=[],this.context=u;const y=[],b=l;for(const S in l.paint._values){const k=b.paint.get(S);if(S.endsWith("-use-theme")||!p(S)||!(k instanceof Rp&&kv(k.property.specification)))continue;const j=oe(S,l.type),O=k.value,z=k.property.specification.type,U=!!k.property.useIntegerZoom,q=S==="line-dasharray"||S.endsWith("pattern"),K=b.paint.get(`${S}-use-theme`),Z=S==="line-dasharray"&&b.layout.get("line-cap").value.kind!=="constant"||K&&K.value.kind!=="constant";if(O.kind!=="constant"||Z)if(O.kind==="source"||Z||q){const J=je(S,z,"source");this.binders[S]=q?new te(O,j,z,J,l.id):new H(O,j,z,J),y.push(`/a_${S}`)}else{const J=je(S,z,"composite");this.binders[S]=new Y(O,j,z,U,u,J),y.push(`/z_${S}`)}else this.binders[S]=q?new $(O.value,j):new F(O.value,j,z,u),y.push(`/u_${S}`);K&&(this.binders[S].lutExpression=K.value)}this.cacheKey=y.sort().join("")}getMaxValue(l){const u=this.binders[l];return u instanceof H||u instanceof Y?u.maxValue:0}populatePaintArrays(l,u,p,y,b,S,k,j){for(const O in this.binders){const z=this.binders[O];z.context=this.context,(z instanceof H||z instanceof Y||z instanceof te)&&z.populatePaintArray(l,u,p,y,b,S,k,j)}}setConstantPatternPositions(l,u){for(const p in this.binders){const y=this.binders[p];y instanceof $&&y.setConstantPatternPositions(l,u)}}getPatternTransitionVertexBuffer(l){const u=this.binders[l];return u instanceof te?u.paintTransitionVertexBuffer:null}updatePaintArrays(l,u,p,y,b,S,k,j,O,z){let U=!1;const q=Object.keys(l),K=q.length!==0&&!j,Z=K?q:u.uniqueIds;this.context.lut=b.lut;for(const J in this.binders){const ne=this.binders[J];if(ne.context=this.context,(ne instanceof H||ne instanceof Y||ne instanceof te)&&ne.expression&&ne.expression.kind&&ne.expression.kind!=="constant"&&(ne.expression.isStateDependent===!0||ne.expression.isLightConstant===!1)){const ae=b.paint.get(J);ne.expression=ae.value;for(const he of Z){const ce=l[he.toString()];u.eachPosition(he,(ye,Ee,Ce)=>{const He=y.feature(ye);ne.updatePaintArray(Ee,Ce,He,ce,S,k,O,z)})}if(!K)for(const he of p.uniqueIds){const ce=l[he.toString()];p.eachPosition(he,(ye,Ee,Ce)=>{const He=y.feature(ye);ne.updatePaintArray(Ee,Ce,He,ce,S,k,O,z)})}U=!0}}return U}defines(){const l=[];for(const u in this.binders){const p=this.binders[u];(p instanceof F||p instanceof $)&&l.push(...p.uniformNames.map(y=>`#define HAS_UNIFORM_${y}`))}return l}getPaintVertexBuffers(){return this._buffers}getUniforms(l){const u=[];for(const p in this.binders){const y=this.binders[p];if(y instanceof F||y instanceof $||y instanceof Y)for(const b of y.uniformNames)u.push({name:b,property:p,binding:y.getBinding(l,b)})}return u}setUniforms(l,u,p,y,b){for(const{name:S,property:k,binding:j}of p)this.binders[k].setUniform(l,j,b,y.get(k),S)}updatePaintBuffers(){this._buffers=[];for(const l in this.binders){const u=this.binders[l];(u instanceof H||u instanceof Y||u instanceof te)&&u.paintVertexBuffer&&this._buffers.push(u.paintVertexBuffer),u instanceof te&&u.paintTransitionVertexBuffer&&this._buffers.push(u.paintTransitionVertexBuffer)}}upload(l){for(const u in this.binders){const p=this.binders[u];(p instanceof H||p instanceof Y||p instanceof te)&&p.upload(l)}this.updatePaintBuffers()}destroy(){for(const l in this.binders){const u=this.binders[l];(u instanceof H||u instanceof Y||u instanceof te)&&u.destroy()}}}class ie{constructor(l,u,p=()=>!0){this.programConfigurations={};for(const y of l)this.programConfigurations[y.id]=new ee(y,u,p);this.needsUpload=!1,this._featureMap=new l_,this._featureMapWithoutIds=new l_,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(l,u,p,y,b,S,k,j,O){for(const z in this.programConfigurations)this.programConfigurations[z].populatePaintArrays(l,u,y,b,S,k,j,O);u.id!==void 0?this._featureMap.add(u.id,p,this._bufferOffset,l):(this._featureMapWithoutIds.add(this._idlessCounter,p,this._bufferOffset,l),this._idlessCounter+=1),this._bufferOffset=l,this.needsUpload=!0}updatePaintArrays(l,u,p,y,b,S,k,j){for(const O of p)this.needsUpload=this.programConfigurations[O.id].updatePaintArrays(l,this._featureMap,this._featureMapWithoutIds,u,O,y,b,S,k||0,j)||this.needsUpload}get(l){return this.programConfigurations[l]}upload(l){if(this.needsUpload){for(const u in this.programConfigurations)this.programConfigurations[u].upload(l);this.needsUpload=!1}}destroy(){for(const l in this.programConfigurations)this.programConfigurations[l].destroy()}}const le={"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 oe(h,l){return le[h]||[h.replace(`${l}-`,"").replace(/-/g,"_")]}const me={"line-pattern":{source:wd,composite:wd},"fill-pattern":{source:wd,composite:wd},"fill-extrusion-pattern":{source:wd,composite:wd},"line-dasharray":{source:vg,composite:vg}},pe={color:{source:Op,composite:mh},number:{source:Tc,composite:Op}};function je(h,l,u){const p=me[h];return p&&p[u]||pe[l][u]}vr(F,"ConstantBinder"),vr($,"PatternConstantBinder"),vr(H,"SourceExpressionBinder"),vr(te,"PatternCompositeBinder"),vr(Y,"CompositeExpressionBinder"),vr(ee,"ProgramConfiguration",{omit:["_buffers"]}),vr(ie,"ProgramConfigurationSet");const Re=ar/Math.PI/2,xe=64,Ze=[xe,32,16],ze=-Re,Ke=Re;function De(h,l,u,p=Re){return u=Kn(u),[h*Math.sin(u)*p,-l*p,h*Math.cos(u)*p]}function Fe(h,l,u){return De(Math.cos(Kn(h)),Math.sin(Kn(h)),l,u)}const qe=63710088e-1,st=2*Math.PI*qe;class Qe{constructor(l,u){if(isNaN(l)||isNaN(u))throw new Error(`Invalid LngLat object: (${l}, ${u})`);if(this.lng=+l,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 Qe(Ye(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(l){const u=Math.PI/180,p=this.lat*u,y=l.lat*u,b=Math.sin(p)*Math.sin(y)+Math.cos(p)*Math.cos(y)*Math.cos((l.lng-this.lng)*u);return qe*Math.acos(Math.min(b,1))}toBounds(l=0){const u=360*l/40075017,p=u/Math.cos(Math.PI/180*this.lat);return new xt({lng:this.lng-p,lat:this.lat-u},{lng:this.lng+p,lat:this.lat+u})}toEcef(l){return Fe(this.lat,this.lng,Re+l*Re/qe)}static convert(l){if(l instanceof Qe)return l;if(Array.isArray(l)&&(l.length===2||l.length===3))return new Qe(Number(l[0]),Number(l[1]));if(!Array.isArray(l)&&typeof l=="object"&&l!==null)return new Qe(Number("lng"in l?l.lng:l.lon),Number(l.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 xt{constructor(l,u){l&&(u?this.setSouthWest(l).setNorthEast(u):Array.isArray(l)&&l.length===4?this.setSouthWest([l[0],l[1]]).setNorthEast([l[2],l[3]]):this.setSouthWest(l[0]).setNorthEast(l[1]))}setNorthEast(l){return this._ne=l instanceof Qe?new Qe(l.lng,l.lat):Qe.convert(l),this}setSouthWest(l){return this._sw=l instanceof Qe?new Qe(l.lng,l.lat):Qe.convert(l),this}extend(l){const u=this._sw,p=this._ne;let y,b;if(l instanceof Qe)y=l,b=l;else{if(!(l instanceof xt))return Array.isArray(l)?l.length===4||l.every(Array.isArray)?this.extend(xt.convert(l)):this.extend(Qe.convert(l)):typeof l=="object"&&l!==null&&l.hasOwnProperty("lat")&&(l.hasOwnProperty("lon")||l.hasOwnProperty("lng"))?this.extend(Qe.convert(l)):this;if(y=l._sw,b=l._ne,!y||!b)return this}return u||p?(u.lng=Math.min(y.lng,u.lng),u.lat=Math.min(y.lat,u.lat),p.lng=Math.max(b.lng,p.lng),p.lat=Math.max(b.lat,p.lat)):(this._sw=new Qe(y.lng,y.lat),this._ne=new Qe(b.lng,b.lat)),this}getCenter(){return new Qe((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 Qe(this.getWest(),this.getNorth())}getSouthEast(){return new Qe(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(l){const{lng:u,lat:p}=Qe.convert(l);let y=this._sw.lng<=u&&u<=this._ne.lng;return this._sw.lng>this._ne.lng&&(y=this._sw.lng>=u&&u>=this._ne.lng),this._sw.lat<=p&&p<=this._ne.lat&&y}static convert(l){if(l)return l instanceof xt?l:new xt(l)}}function ft(h){return st*Math.cos(h*Math.PI/180)}function Rt(h){return(180+h)/360}function Ft(h){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+h*Math.PI/360)))/360}function ot(h,l){return h/ft(l)}function et(h){return 360*h-180}function gt(h){return 360/Math.PI*Math.atan(Math.exp((180-360*h)*Math.PI/180))-90}function vt(h,l){return h*ft(gt(l))}const St=85.051129;function rr(h){return Math.cos(Kn(fe(h,-85.051129,St)))}function Gt(h,l){const u=fe(l,0,25.5),p=Math.pow(2,u);return rr(h)*st/(512*p)}function Ht(h){return 1/Math.cos(h*Math.PI/180)}function Dt(h,l=0){const u=Math.exp(Math.PI*(1-(h.y+l/ar)/(1<=j?(Lr(h,l,u,O,z,b,U,k,j),Lr(h,O,z,p,y,U,S,k,j)):h.push(S)}function gr(h,l,u){let p=h[0],y=p.x,b=p.y;l(p);const S=[p];for(let k=1;kh.x+1||ph.y+1)&&Br("Geometry exceeds allowed extent, reduce your vector tile buffer size"),h}function $r(h,l,u){const p=h.loadGeometry(),y=h.extent,b=ar/y;if(l&&u&&u.projection.isReprojectedInTileSpace){const S=1<{const K=et((l.x+q.x/y)/S),Z=gt((l.y+q.y/y)/S),J=z.project(K,Z);q.x=(J.x*k-j)*y,q.y=(J.y*k-O)*y};for(let q=0;q=y||Z.y<0||Z.y>=y||(U(Z),K.push(Z));p[q]=K}}for(const S of p)for(const k of S)_n(k,b);return p}function vn(h,l){return{type:h.type,id:h.id,properties:h.properties,geometry:l?$r(h):[]}}class tn{constructor(l,u,p,y,b){this.properties={},this.extent=p,this.type=0,this.id=void 0,this._pbf=l,this._geometry=-1,this._keys=y,this._values=b,l.readFields(Vn,this,u)}loadGeometry(){const l=this._pbf;l.pos=this._geometry;const u=l.readVarint()+l.pos,p=[];let y,b=1,S=0,k=0,j=0;for(;l.pos>3}if(S--,b===1||b===2)k+=l.readSVarint(),j+=l.readSVarint(),b===1&&(y&&p.push(y),y=[]),y&&y.push(new Mt(k,j));else{if(b!==7)throw new Error(`unknown command ${b}`);y&&y.push(y[0].clone())}}return y&&p.push(y),p}bbox(){const l=this._pbf;l.pos=this._geometry;const u=l.readVarint()+l.pos;let p=1,y=0,b=0,S=0,k=1/0,j=-1/0,O=1/0,z=-1/0;for(;l.pos>3}if(y--,p===1||p===2)b+=l.readSVarint(),S+=l.readSVarint(),bj&&(j=b),Sz&&(z=S);else if(p!==7)throw new Error(`unknown command ${p}`)}return[k,O,j,z]}toGeoJSON(l,u,p){const y=this.extent*Math.pow(2,p),b=this.extent*l,S=this.extent*u,k=this.loadGeometry();function j(q){return[360*(q.x+b)/y-180,360/Math.PI*Math.atan(Math.exp((1-2*(q.y+S)/y)*Math.PI))-90]}function O(q){return q.map(j)}let z;if(this.type===1){const q=[];for(const Z of k)q.push(Z[0]);const K=O(q);z=q.length===1?{type:"Point",coordinates:K[0]}:{type:"MultiPoint",coordinates:K}}else if(this.type===2){const q=k.map(O);z=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(Z){const J=Z.length;if(J<=1)return[Z];const ne=[];let ae,he;for(let ce=0;ce=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[l];const u=this._pbf.readVarint()+this._pbf.pos;return new tn(this._pbf,u,this.extent,this._keys,this._values)}}function Ti(h,l,u){h===15?l.version=u.readVarint():h===1?l.name=u.readString():h===5?l.extent=u.readVarint():h===2?l._features.push(u.pos):h===3?l._keys.push(u.readString()):h===4&&l._values.push(function(p){let y=null;const b=p.readVarint()+p.pos;for(;p.pos>3;y=S===1?p.readString():S===2?p.readFloat():S===3?p.readDouble():S===4?p.readVarint64():S===5?p.readVarint():S===6?p.readSVarint():S===7?p.readBoolean():null}if(y==null)throw new Error("unknown feature value");return y}(u))}class Qn{constructor(l,u){this.layers=l.readFields(pn,{},u)}}function pn(h,l,u){if(h===3){const p=new Ki(u,u.readVarint()+u.pos);p.length&&(l[p.name]=p)}}const mn="3d_elevation_id",Ei="level";class rs{constructor(){this._valid=!1}reset(l){return this.feature=l,this._valid=!0,this._geometry=l.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(l,u){return this._valid&&l(u(this._geometry)),this}require(l,u,p){return this.get(l,!0,u,p)}optional(l,u,p){return this.get(l,!1,u,p)}success(){return this._valid}get(l,u,p,y){const b=this.feature.properties.hasOwnProperty(l)?+this.feature.properties[l]:void 0;return this._valid&&b!==void 0&&!Number.isNaN(b)?p(y?y(b):b):u&&(this._valid=!1),this}}class Jn{constructor(l,u){this.featureFunc=l,this.vertexFunc=u}parseFeature(l,u,p){return this.featureFunc(l,u,p)}parseVertex(l,u,p){return this.vertexFunc(l,u,p)}}const on=new Jn((h,l,u)=>h.reset(l).require(mn,p=>{u.id=p}).optional("fixed_height_relative",p=>{u.constantHeight=p},_i.decodeRelativeHeight).geometry(p=>{u.bounds=p},aT).success(),(h,l,u)=>h.reset(l).require(mn,p=>{u.id=p}).require("elevation_idx",p=>{u.idx=p}).require("extent",p=>{u.extent=p}).require("height_relative",p=>{u.height=p},_i.decodeRelativeHeight).geometry(p=>{u.position=p},_i.getPoint).success()),Gi=new Jn((h,l,u)=>h.reset(l).require(mn,p=>{u.id=p}).optional("fixed_height",p=>{u.constantHeight=p},_i.decodeMetricHeight).geometry(p=>{u.bounds=p},aT).success(),(h,l,u)=>h.reset(l).require(mn,p=>{u.id=p}).require("elevation_idx",p=>{u.idx=p}).require("extent",p=>{u.extent=p}).require("height",p=>{u.height=p},_i.decodeMetricHeight).geometry(p=>{u.position=p},_i.getPoint).success());class _i{static getPoint(l){return Mn(l[0][0].x,l[0][0].y)}static decodeRelativeHeight(l){return 1e-4*l*5}static decodeMetricHeight(l){return 1e-4*l}static getVersionSchema(l){return l?l==="1.0.1"?Gi:void 0:on}static parse(l){const u=[],p=[],y=l.length,b=new rs;for(let S=0;S=0);if(b===0)return 0;b!==l.length&&(u=!1)}return u?2:1}function la(h,l){for(const u of h.projections){const p=Xs(l,h.points[0],u.axis);if(u.projection[1]p[1])return 0}return 1}function Va(h,l){let u=0;const p=[0,0,0,0];for(let y=0;y=0&&u++;return u}class sc{constructor(l,u){this.points=l||new Array(8).fill([0,0,0]),this.planes=u||new Array(6).fill([0,0,0,0]),this.bounds=si.fromPoints(this.points),this.projections=[],this.frustumEdges=[tr([],this.points[2],this.points[3]),tr([],this.points[0],this.points[3]),tr([],this.points[4],this.points[0]),tr([],this.points[5],this.points[1]),tr([],this.points[6],this.points[2]),tr([],this.points[7],this.points[3])];for(const p of this.frustumEdges){const y=[0,-p[2],p[1]],b=[p[2],0,-p[0]];this.projections.push({axis:y,projection:Xs(this.points,this.points[0],y)}),this.projections.push({axis:b,projection:Xs(this.points,this.points[0],b)})}}static fromInvProjectionMatrix(l,u,p,y){const b=Math.pow(2,p),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(O=>{const z=hr([],O,l),U=1/z[3]/u*b;return(q=z)[0]=(K=z)[0]*(Z=[U,U,y?1/z[3]:U,U])[0],q[1]=K[1]*Z[1],q[2]=K[2]*Z[2],q[3]=K[3]*Z[3],q;var q,K,Z}),k=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(O=>{const z=mt([],er([],tr([],S[O[0]],S[O[1]]),tr([],S[O[2]],S[O[1]]))),U=-Pt(z,S[O[1]]);return z.concat(U)}),j=[];for(let O=0;OO[1]||O[0]>j[1])return 0}return 1}containsPoint(l){for(const u of this.planes){const p=u[3];if(Pt([u[0],u[1],u[2]],l)+p<0)return!1}return!0}}class si{static fromPoints(l){const u=[1/0,1/0,1/0],p=[-1/0,-1/0,-1/0];for(const y of l)Te(u,u,y),be(p,p,y);return new si(u,p)}static fromTileIdAndHeight(l,u,p){const y=1<l.max[u]||l.min[u]>this.max[u])return!1;return!0}intersectsAabbXY(l){return!(this.min[0]>l.max[0]||l.min[0]>this.max[0]||this.min[1]>l.max[1]||l.min[1]>this.max[1])}encapsulate(l){for(let u=0;u<3;u++)this.min[u]=Math.min(this.min[u],l.min[u]),this.max[u]=Math.max(this.max[u],l.max[u])}encapsulatePoint(l){for(let u=0;u<3;u++)this.min[u]=Math.min(this.min[u],l[u]),this.max[u]=Math.max(this.max[u],l[u])}closestPoint(l){return[Math.max(Math.min(this.max[0],l[0]),this.min[0]),Math.max(Math.min(this.max[1],l[1]),this.min[1]),Math.max(Math.min(this.max[2],l[2]),this.min[2])]}}vr(si,"Aabb");class Ac{constructor(l,u){this.feature=l,this.metersToTile=u,this.index=0}get(){const l=this.feature.vertices[this.index],u=this.feature.vertexProps[this.index].dir,p=u[1],y=-u[0],b=(l.extent+1)*this.metersToTile;return[new Mt(Math.trunc(l.position[0]+p*b),Math.trunc(l.position[1]+y*b)),new Mt(Math.trunc(l.position[0]-p*b),Math.trunc(l.position[1]-y*b))]}next(){this.index++}valid(){return this.index{return k.a0?We(j,j,1/O):we(j,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(l){if(this.edges.length===0)return;let u=0,p=Number.POSITIVE_INFINITY,y=0;const[b,S,k,j,O,z,U]=this._tmpVec2;As(U,l.x,l.y);const q=new Os(U,null);for(let K=0;K0?Zr(j,k)/ye:0,Ce=fe(Ee,0,1),He=Math.abs((Ee-Ce)*this.edgeProps[K].len);go(O,U,ne),As(z,J[1],-J[0]);const $e=He+Math.abs(Zr(O,z));$e=0;--S){const k=this.edges[S].a,j=this.edges[S].b,{position:O,height:z,extent:U}=this.vertices[k],{position:q,height:K,extent:Z}=this.vertices[j],J=this.vertexProps[k].dir,ne=this.vertexProps[j].dir;if(we(u,O[0]/l,O[1]/l,z),we(p,q[0]/l,q[1]/l,K),we(y,J[1],-J[0],0),We(y,y,U),we(b,ne[1],-ne[0],0),We(b,b,Z),this.distSqLines(Ae(u[0]+.5*y[0],u[1]+.5*y[1],u[2]+.5*y[2]),Ae(p[0]-.5*b[0],p[1]-.5*b[1],p[2]-.5*b[2]),Ae(u[0]-.5*y[0],u[1]-.5*y[1],u[2]-.5*y[2]),Ae(p[0]+.5*b[0],p[1]+.5*b[1],p[2]+.5*b[2]))<=.0025000000000000005)continue;const ae=this.vertices.length,he=xa(jr(),O,q);this.vertices.push({position:Yr(he,he,.5),height:.5*(z+K),extent:.5*(U+Z)});const ce=xa(jr(),J,ne);this.vertexProps.push({dir:gn(ce,ce)}),this.edges.splice(S,1),this.edgeProps.splice(S,1),this.edges.push({a:k,b:ae}),this.edges.push({a:ae,b:j});const ye=go(jr(),this.vertices[ae].position,O),Ee=hn(ye),Ce={vec:ye,dir:Yr(jr(),ye,1/Ee),len:Ee};this.edgeProps.push(Ce),this.edgeProps.push(Ce)}}distSqLines(l,u,p,y){const b=Ne(Se(),u,l),S=Ne(Se(),y,p),k=Ne(Se(),l,p),j=Pt(b,b),O=Pt(b,S),z=Pt(b,k),U=Pt(S,S),q=Pt(S,k),K=j*U-O*O;if(K===0)return Et(wt(b,p,y,Pt(k,S)/Pt(S,S)),l);const Z=(j*q-O*z)/K;return Et(wt(b,l,u,(O*q-z*U)/K),wt(S,p,y,Z))}}class Ii{static parseFrom(l,u){const p=_i.parse(l);if(!p)return[];let{vertices:y,features:b}=p;const S=1/Dt(u);b.sort((z,U)=>z.id-U.id),y.sort((z,U)=>z.id-U.id||z.idx-U.idx),y=y.filter((z,U,q)=>U===q.findIndex(K=>K.id===z.id&&K.idx===z.idx));const k=new Array;let j=0;const O=y.length;for(const z of b){if(z.constantHeight){k.push(new kc(z.id,z.bounds,z.constantHeight));continue}for(;j!==O&&y[j].idy.id===p)}}class Mi{constructor(l,u){this.zScale=1,this.xOffset=0,this.yOffset=0,l.equals(u)||(this.zScale=Math.pow(2,u.z-l.z),this.xOffset=(l.x*this.zScale-u.x)*ar,this.yOffset=(l.y*this.zScale-u.y)*ar)}constantElevation(l,u){if(l.constantHeight!=null)return this.computeBiasedHeight(l.constantHeight,u)}pointElevation(l,u,p){const y=this.constantElevation(u,p);return y??(l.x=l.x*this.zScale+this.xOffset,l.y=l.y*this.zScale+this.yOffset,this.computeBiasedHeight(u.pointElevation(l),p))}computeBiasedHeight(l,u){return u<=0?l:l+u*Me(0,u,l>=0?l:Math.abs(.5*l))}}vr(kc,"ElevationFeature");class fi{constructor(l){this.zoom=l.zoom,this.overscaling=l.overscaling,this.layers=l.layers,this.layerIds=this.layers.map(u=>u.fqid),this.index=l.index,this.hasPattern=!1,this.projection=l.projection,this.layoutVertexArray=new ic,this.indexArray=new _s,this.segments=new Si,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut}),this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new Tc),this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,p,y){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,y){const b=this.layers[0],S=[];let k=null;b.type==="circle"&&(k=b.layout.get("circle-sort-key"));for(const{feature:O,id:z,index:U,sourceLayerIndex:q}of l){const K=this.layers[0]._featureFilter.needGeometry,Z=vn(O,K);if(!this.layers[0]._featureFilter.filter(new ti(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),Z,p))continue;const J=k?k.evaluate(Z,{},p):void 0,ne={id:z,properties:O.properties,type:O.type,sourceLayerIndex:q,index:U,geometry:K?Z.geometry:$r(O,p,y),patterns:{},sortKey:J};S.push(ne)}k&&S.sort((O,z)=>O.sortKey-z.sortKey);let j=null;y.projection.name==="globe"&&(this.globeExtVertexArray=new Gv,j=y.projection);for(const O of S){const{geometry:z,index:U,sourceLayerIndex:q}=O,K=l[U].feature;this.addFeature(O,z,U,u.availableImages,p,j,u.brightness,u.elevationFeatures),u.featureIndex.insert(K,z,U,q,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(l,u,p,y,b,S,k){this.programConfigurations.updatePaintArrays(l,u,b,p,y,S,k,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,TI.members),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=l.createVertexBuffer(this.globeExtVertexArray,V3.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=l.createVertexBuffer(this.elevatedLayoutVertexArray,U3.members))),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy())}addFeature(l,u,p,y,b,S,k,j){let O;this.elevationMode!=="none"&&(O=Ii.getElevationFeature(l,j));for(const z of u)for(const U of z){const q=U.x,K=U.y;if(q<0||q>=ar||K<0||K>=ar)continue;if(S){const ne=S.projectTilePoint(q,K,b),ae=S.upVector(b,q,K);this.addGlobeExtVertex(ne,ae),this.addGlobeExtVertex(ne,ae),this.addGlobeExtVertex(ne,ae),this.addGlobeExtVertex(ne,ae)}const Z=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,l.sortKey),J=Z.vertexLength;if(this.addCircleVertex(q,K,-1,-1),this.addCircleVertex(q,K,1,-1),this.addCircleVertex(q,K,1,1),this.addCircleVertex(q,K,-1,1),this.elevationMode!=="none"){const ne=O?O.pointElevation(new Mt(q,K)):0;this.hasElevation=this.hasElevation||ne!==0;for(let ae=0;ae<4;ae++)this.elevatedLayoutVertexArray.emplaceBack(ne)}this.indexArray.emplaceBack(J,J+1,J+2),this.indexArray.emplaceBack(J,J+2,J+3),Z.vertexLength+=4,Z.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,p,{},y,b,k,void 0,this.worldview)}addCircleVertex(l,u,p,y){this.layoutVertexArray.emplaceBack(2*l+(p+1)/2,2*u+(y+1)/2)}addGlobeExtVertex(l,u){this.globeExtVertexArray.emplaceBack(l.x,l.y,l.z,u[0]*16384,u[1]*16384,u[2]*16384)}}function Is(h,l){for(let u=0;u1){if(gf(h,l))return!0;for(let p=0;p1?u:u.sub(l)._mult(y)._add(l))}function wg(h,l){let u,p,y,b=!1;for(let S=0;Sl.y!=y.y>l.y&&l.x<(y.x-p.x)*(l.y-p.y)/(y.y-p.y)+p.x&&(b=!b)}return b}function Rl(h,l){let u=!1;for(let p=0,y=h.length-1;pl.y!=S.y>l.y&&l.x<(S.x-b.x)*(l.y-b.y)/(S.y-b.y)+b.x&&(u=!u)}return u}function yf(h,l,u,p,y){for(const S of h)if(l<=S.x&&u<=S.y&&p>=S.x&&y>=S.y)return!0;const b=[new Mt(l,u),new Mt(l,y),new Mt(p,y),new Mt(p,u)];if(h.length>2){for(const S of b)if(Rl(h,S))return!0}for(let S=0;Sy.x&&l.x>y.x||h.yy.y&&l.y>y.y)return!1;const b=an(h,l,u[0]);return b!==an(h,l,u[1])||b!==an(h,l,u[2])||b!==an(h,l,u[3])}function _f(h,l,u,p,y,b){let S=l.y-h.y,k=h.x-l.x;if(b=b||0){const j=S*S+k*k;if(j===0)return!0;const O=Math.sqrt(j);S/=O,k/=O}return!((u.x-h.x)*S+(u.y-h.y)*k-b<0||(p.x-h.x)*S+(p.y-h.y)*k-b<0||(y.x-h.x)*S+(y.y-h.y)*k-b<0)}function eb(h,l,u,p,y,b,S){return!(_f(h,l,p,y,b,S)||_f(l,u,p,y,b,S)||_f(u,h,p,y,b,S)||_f(p,y,h,l,u,S)||_f(y,b,h,l,u,S)||_f(b,p,h,l,u,S))}function Sg(h,l,u){const p=l.paint.get(h).value;return p.kind==="constant"?p.value:u.programConfigurations.get(l.id).getMaxValue(h)}function EI(h){return Math.sqrt(h[0]*h[0]+h[1]*h[1])}function qW(h,l,u,p,y){if(!l[0]&&!l[1])return h;const b=Mt.convert(l)._mult(y);u==="viewport"&&b._rotate(-p);const S=[];for(let k=0;k>u&&l.y===this.y>>u}url(l,u){const p=function(b,S,k){const j=2**k,O=2*Math.PI*6378137,z=O*(b/j-.5),U=O*(.5-(S+1)/j);return`${z},${U},${z+O/j},${U+O/j}`}(this.x,this.y,this.z),y=function(b,S,k){let j,O="";for(let z=b;z>0;z--)j=1<this.canonical.z?new gl(l,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new gl(l,this.wrap,l,this.canonical.x>>u,this.canonical.y>>u)}calculateScaledKey(l,u=!0){if(this.overscaledZ===l&&u)return this.key;if(l>this.canonical.z)return tb(this.wrap*+u,l,this.canonical.z,this.canonical.x,this.canonical.y);{const p=this.canonical.z-l;return tb(this.wrap*+u,l,l,this.canonical.x>>p,this.canonical.y>>p)}}isChildOf(l){if(l.wrap!==this.wrap)return!1;const u=this.canonical.z-l.canonical.z;return l.overscaledZ===0||l.overscaledZ>u&&l.canonical.y===this.canonical.y>>u}children(l){if(this.overscaledZ>=l)return[new gl(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const u=this.canonical.z+1,p=2*this.canonical.x,y=2*this.canonical.y;return[new gl(u,this.wrap,u,p,y),new gl(u,this.wrap,u,p+1,y),new gl(u,this.wrap,u,p,y+1),new gl(u,this.wrap,u,p+1,y+1)]}isLessThan(l){return this.wrapl.wrap)&&(this.overscaledZl.overscaledZ)&&(this.canonical.xl.canonical.x)&&this.canonical.y{let l=h.canonical.x-1,u=h.wrap;return l<0&&(l=(1<{let l=h.canonical.x+1,u=h.wrap;return l===1<new gl(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,(h.canonical.y===0?1<new gl(h.overscaledZ,h.wrap,h.canonical.z,h.canonical.x,h.canonical.y===(1<1?null:function(p,y,b,S){const k=Math.sin(b);return p*(Math.sin((1-S)*b)/k)+y*(Math.sin(S*b)/k)}(h.a[l],h.b[l],h.angle,fe(u,0,1))+h.center[l]}function vf(h){if(h.z<=1)return dAe[h.z+2*h.y+h.x];const l=Z3(CI(h));return si.fromPoints(l)}function zp(h,l,u){return We(h,h,1-u),rt(h,h,l,u)}function XW(h,l){const u=$p(l.zoom);if(u===0)return vf(h);const p=CI(h),y=Z3(p),b=Rt(p.getWest())*l.worldSize,S=Rt(p.getEast())*l.worldSize,k=Ft(p.getNorth())*l.worldSize,j=Ft(p.getSouth())*l.worldSize,O=[b,k,0],z=[S,k,0],U=[b,j,0],q=[S,j,0],K=D([],l.globeMatrix);return or(O,O,K),or(z,z,K),or(U,U,K),or(q,q,K),y[0]=zp(y[0],U,u),y[1]=zp(y[1],q,u),y[2]=zp(y[2],z,u),y[3]=zp(y[3],O,u),si.fromPoints(y)}function QW(h,l,u){for(const p of h)or(p,p,l),We(p,p,u)}function JW(h,l,u,p){const y=l/h.worldSize,b=h.globeMatrix;if(u.z<=1){const Ge=vf(u).getCorners();return QW(Ge,b,y),si.fromPoints(Ge)}const S=CI(u,p),k=Z3(S,Re+kI(h._tileCoverLift));QW(k,b,y);const j=Number.MAX_VALUE,O=[-j,-j,-j],z=[j,j,j];if(S.contains(h.center)){for(const Ve of k)Te(z,z,Ve),be(O,O,Ve);O[2]=0;const Ge=h.point,Ue=[Ge.x*y,Ge.y*y,0];return Te(z,z,Ue),be(O,O,Ue),new si(z,O)}if(h._tileCoverLift>0){for(const Ge of k)Te(z,z,Ge),be(O,O,Ge);return new si(z,O)}const U=[b[12]*y,b[13]*y,b[14]*y],q=S.getCenter(),K=fe(h.center.lat,-85.051129,St),Z=fe(q.lat,-85.051129,St),J=Rt(h.center.lng),ne=Ft(K);let ae=J-Rt(q.lng);const he=ne-Ft(Z);ae>.5?ae-=1:ae<-.5&&(ae+=1);let ce=0;Math.abs(ae)>Math.abs(he)?ce=ae>=0?1:3:(ce=he>=0?0:2,rt(U,U,[b[4]*y,b[5]*y,b[6]*y],-Math.sin(Kn(he>=0?S.getSouth():S.getNorth()))*Re));const ye=k[ce],Ee=k[(ce+1)%4],Ce=new hAe(ye,Ee,U),He=[Y3(Ce,0)||ye[0],Y3(Ce,1)||ye[1],Y3(Ce,2)||ye[2]],$e=$p(h.zoom);if($e>0){const Ge=function({x:Ve,y:yt,z:bt},kt,It,Ct,Bt){const pt=1/(1<.5?xr=-1:ir<-.5&&(xr=1),jt=((jt+xr)*kt-(Ct*=kt))*It+Ct,Lt=((Lt+xr)*kt-Ct)*It+Ct,$t=($t*kt-(Bt*=kt))*It+Bt,Wt=(Wt*kt-Bt)*It+Bt,[[jt,Wt,0],[Lt,Wt,0],[Lt,$t,0],[jt,$t,0]]}(u,l,h._pixelsPerMercatorPixel,J,ne);for(let Ve=0;VeMath.PI/2*1.01}const iK=Kn(85),fAe=Math.cos(iK),pAe=Math.sin(iK),mAe=C(),sK=h=>{const l=[];return h.paint.get("circle-pitch-alignment")==="map"&&l.push("PITCH_WITH_MAP"),h.paint.get("circle-pitch-scale")==="map"&&l.push("SCALE_WITH_MAP"),l};function aK(h,l,u,p,y,b,S,k,j){if(b&&h.queryGeometry.isAboveHorizon)return!1;b&&(j*=h.pixelToTileUnitsFactor);const O=h.tileID.canonical,z=u.projection.upVectorScale(O,u.center.lat,u.worldSize).metersToTile;for(const U of l)for(const q of U){const K=q.add(k),Z=y&&u.elevation?u.elevation.exaggeration()*y.getElevationAt(K.x,K.y,!0):0,J=u.projection.projectTilePoint(K.x,K.y,O);if(Z>0){const ce=u.projection.upVector(O,K.x,K.y);J.x+=ce[0]*z*Z,J.y+=ce[1]*z*Z,J.z+=ce[2]*z*Z}const ne=b?K:gAe(J.x,J.y,J.z,p),ae=b?h.tilespaceRays.map(ce=>xAe(ce,Z)):h.queryGeometry.screenGeometry,he=hr([],[J.x,J.y,J.z,1],p);if(!S&&b?j*=he[3]/u.cameraToCenterDistance:S&&!b&&(j*=u.cameraToCenterDistance/he[3]),b){const ce=gt((q.y/ar+O.y)/(1<h.width||y.height>h.height||u.x>h.width-y.width||u.y>h.height-y.height)throw new RangeError("out of range source coordinates for image copy");if(y.width>l.width||y.height>l.height||p.x>l.width-y.width||p.y>l.height-y.height)throw new RangeError("out of range destination coordinates for image copy");const j=h.data,O=l.data,z=b===4&&k;for(let U=0;U{l[h.evaluationKey]=j;const O=h.expression.evaluate(l),z=O?O.toNonPremultipliedRenderColor(null):null;z&&(y.data[S+k+0]=Math.floor(255*z.r),y.data[S+k+1]=Math.floor(255*z.g),y.data[S+k+2]=Math.floor(255*z.b),y.data[S+k+3]=Math.floor(255*z.a))};if(h.clips)for(let S=0,k=0;S80*u){k=h[0],j=h[1];let z=k,U=j;for(let q=u;qz&&(z=K),Z>U&&(U=Z)}O=Math.max(z-k,U-j),O=O!==0?32767/O:0}return _E(b,S,u,k,j,O,0),S}function gK(h,l,u,p,y){let b;if(y===function(S,k,j,O){let z=0;for(let U=k,q=j-O;U0)for(let S=l;S=l;S-=p)b=vK(S/p|0,h[S],h[S+1],b);return b&&nb(b,b.next)&&(wE(b),b=b.next),b}function f_(h,l){if(!h)return h;l||(l=h);let u,p=h;do if(u=!1,p.steiner||!nb(p,p.next)&&qa(p.prev,p,p.next)!==0)p=p.next;else{if(wE(p),p=l=p.prev,p===p.next)break;u=!0}while(u||p!==l);return l}function _E(h,l,u,p,y,b,S){if(!h)return;!S&&b&&function(j,O,z,U){let q=j;do q.z===0&&(q.z=t5(q.x,q.y,O,z,U)),q.prevZ=q.prev,q.nextZ=q.next,q=q.next;while(q!==j);q.prevZ.nextZ=null,q.prevZ=null,function(K){let Z,J=1;do{let ne,ae=K;K=null;let he=null;for(Z=0;ae;){Z++;let ce=ae,ye=0;for(let Ce=0;Ce0||Ee>0&&ce;)ye!==0&&(Ee===0||!ce||ae.z<=ce.z)?(ne=ae,ae=ae.nextZ,ye--):(ne=ce,ce=ce.nextZ,Ee--),he?he.nextZ=ne:K=ne,ne.prevZ=he,he=ne;ae=ce}he.nextZ=null,J*=2}while(Z>1)}(q)}(h,p,y,b);let k=h;for(;h.prev!==h.next;){const j=h.prev,O=h.next;if(b?TAe(h,p,y,b):SAe(h))l.push(j.i,h.i,O.i),wE(h),h=O.next,k=O.next;else if((h=O)===k){S?S===1?_E(h=EAe(f_(h),l),l,u,p,y,b,2):S===2&&AAe(h,l,u,p,y,b):_E(f_(h),l,u,p,y,b,1);break}}}function SAe(h){const l=h.prev,u=h,p=h.next;if(qa(l,u,p)>=0)return!1;const y=l.x,b=u.x,S=p.x,k=l.y,j=u.y,O=p.y,z=Math.min(y,b,S),U=Math.min(k,j,O),q=Math.max(y,b,S),K=Math.max(k,j,O);let Z=p.next;for(;Z!==l;){if(Z.x>=z&&Z.x<=q&&Z.y>=U&&Z.y<=K&&vE(y,k,b,j,S,O,Z.x,Z.y)&&qa(Z.prev,Z,Z.next)>=0)return!1;Z=Z.next}return!0}function TAe(h,l,u,p){const y=h.prev,b=h,S=h.next;if(qa(y,b,S)>=0)return!1;const k=y.x,j=b.x,O=S.x,z=y.y,U=b.y,q=S.y,K=Math.min(k,j,O),Z=Math.min(z,U,q),J=Math.max(k,j,O),ne=Math.max(z,U,q),ae=t5(K,Z,l,u,p),he=t5(J,ne,l,u,p);let ce=h.prevZ,ye=h.nextZ;for(;ce&&ce.z>=ae&&ye&&ye.z<=he;){if(ce.x>=K&&ce.x<=J&&ce.y>=Z&&ce.y<=ne&&ce!==y&&ce!==S&&vE(k,z,j,U,O,q,ce.x,ce.y)&&qa(ce.prev,ce,ce.next)>=0||(ce=ce.prevZ,ye.x>=K&&ye.x<=J&&ye.y>=Z&&ye.y<=ne&&ye!==y&&ye!==S&&vE(k,z,j,U,O,q,ye.x,ye.y)&&qa(ye.prev,ye,ye.next)>=0))return!1;ye=ye.nextZ}for(;ce&&ce.z>=ae;){if(ce.x>=K&&ce.x<=J&&ce.y>=Z&&ce.y<=ne&&ce!==y&&ce!==S&&vE(k,z,j,U,O,q,ce.x,ce.y)&&qa(ce.prev,ce,ce.next)>=0)return!1;ce=ce.prevZ}for(;ye&&ye.z<=he;){if(ye.x>=K&&ye.x<=J&&ye.y>=Z&&ye.y<=ne&&ye!==y&&ye!==S&&vE(k,z,j,U,O,q,ye.x,ye.y)&&qa(ye.prev,ye,ye.next)>=0)return!1;ye=ye.nextZ}return!0}function EAe(h,l){let u=h;do{const p=u.prev,y=u.next.next;!nb(p,y)&&xK(p,u,u.next,y)&&bE(p,y)&&bE(y,p)&&(l.push(p.i,u.i,y.i),wE(u),wE(u.next),u=h=y),u=u.next}while(u!==h);return f_(u)}function AAe(h,l,u,p,y,b){let S=h;do{let k=S.next.next;for(;k!==S.prev;){if(S.i!==k.i&&PAe(S,k)){let j=_K(S,k);return S=f_(S,S.next),j=f_(j,j.next),_E(S,l,u,p,y,b,0),void _E(j,l,u,p,y,b,0)}k=k.next}S=S.next}while(S!==h)}function kAe(h,l){let u=h.x-l.x;return u===0&&(u=h.y-l.y,u===0)&&(u=(h.next.y-h.y)/(h.next.x-h.x)-(l.next.y-l.y)/(l.next.x-l.x)),u}function CAe(h,l){const u=function(y,b){let S=b;const k=y.x,j=y.y;let O,z=-1/0;if(nb(y,S))return S;do{if(nb(y,S.next))return S.next;if(j<=S.y&&j>=S.next.y&&S.next.y!==S.y){const J=S.x+(j-S.y)*(S.next.x-S.x)/(S.next.y-S.y);if(J<=k&&J>z&&(z=J,O=S.x=S.x&&S.x>=q&&k!==S.x&&yK(jO.x||S.x===O.x&&jAe(O,S)))&&(O=S,Z=J)}S=S.next}while(S!==U);return O}(h,l);if(!u)return l;const p=_K(u,h);return f_(p,p.next),f_(u,u.next)}function jAe(h,l){return qa(h.prev,h,l.prev)<0&&qa(l.next,h,h.next)<0}function t5(h,l,u,p,y){return(h=1431655765&((h=858993459&((h=252645135&((h=16711935&((h=(h-u)*y|0)|h<<8))|h<<4))|h<<2))|h<<1))|(l=1431655765&((l=858993459&((l=252645135&((l=16711935&((l=(l-p)*y|0)|l<<8))|l<<4))|l<<2))|l<<1))<<1}function IAe(h){let l=h,u=h;do(l.x=(h-S)*(b-k)&&(h-S)*(p-k)>=(u-S)*(l-k)&&(u-S)*(b-k)>=(y-S)*(p-k)}function vE(h,l,u,p,y,b,S,k){return!(h===S&&l===k)&&yK(h,l,u,p,y,b,S,k)}function PAe(h,l){return h.next.i!==l.i&&h.prev.i!==l.i&&!function(u,p){let y=u;do{if(y.i!==u.i&&y.next.i!==u.i&&y.i!==p.i&&y.next.i!==p.i&&xK(y,y.next,u,p))return!0;y=y.next}while(y!==u);return!1}(h,l)&&(bE(h,l)&&bE(l,h)&&function(u,p){let y=u,b=!1;const S=(u.x+p.x)/2,k=(u.y+p.y)/2;do y.y>k!=y.next.y>k&&y.next.y!==y.y&&S<(y.next.x-y.x)*(k-y.y)/(y.next.y-y.y)+y.x&&(b=!b),y=y.next;while(y!==u);return b}(h,l)&&(qa(h.prev,h,l.prev)||qa(h,l.prev,l))||nb(h,l)&&qa(h.prev,h,h.next)>0&&qa(l.prev,l,l.next)>0)}function qa(h,l,u){return(l.y-h.y)*(u.x-l.x)-(l.x-h.x)*(u.y-l.y)}function nb(h,l){return h.x===l.x&&h.y===l.y}function xK(h,l,u,p){const y=PI(qa(h,l,u)),b=PI(qa(h,l,p)),S=PI(qa(u,p,h)),k=PI(qa(u,p,l));return y!==b&&S!==k||!(y!==0||!II(h,u,l))||!(b!==0||!II(h,p,l))||!(S!==0||!II(u,h,p))||!(k!==0||!II(u,l,p))}function II(h,l,u){return l.x<=Math.max(h.x,u.x)&&l.x>=Math.min(h.x,u.x)&&l.y<=Math.max(h.y,u.y)&&l.y>=Math.min(h.y,u.y)}function PI(h){return h>0?1:h<0?-1:0}function bE(h,l){return qa(h.prev,h,h.next)<0?qa(h,l,h.next)>=0&&qa(h,h.prev,l)>=0:qa(h,l,h.prev)<0||qa(h,h.next,l)<0}function _K(h,l){const u=r5(h.i,h.x,h.y),p=r5(l.i,l.x,l.y),y=h.next,b=l.prev;return h.next=l,l.prev=h,u.next=y,y.prev=u,p.next=u,u.prev=p,b.next=p,p.prev=b,p}function vK(h,l,u,p){const y=r5(h,l,u);return p?(y.next=p.next,y.prev=p,p.next.prev=y,p.next=y):(y.prev=y,y.next=y),y}function wE(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 r5(h,l,u){return{i:h,x:l,y:u,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function SE(h,l){const u=h.length;if(u<=1)return[h];const p=[];let y,b;for(let S=0;S1)for(let S=0;S=ar&&u>=ar}static evaluate(l){if(l.length===0)return new Up;let u=[];for(const j of l)u.push(...j.portals);if(u.length===0)return new Up;for(const j of u){const O=j.va,z=j.vb;(Up.isOnBorder(O.x,z.x)||Up.isOnBorder(O.y,z.y))&&(j.type="border")}const p=u.filter(j=>j.type!=="unevaluated"),y=u.filter(j=>j.type==="unevaluated");if(y.length===0)return new Up;y.sort((j,O)=>j.hash===O.hash?j.isTunnel===O.isTunnel?0:j.isTunnel?-1:1:j.hashj.hashb!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new ie(u,{zoom:p,lut:y},b=>b!=="fill-bridge-guard-rail-color")}addVertices(l,u){const p=this.unevalVertices.length;for(let y=0;y=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||xf(U,q,k))||this.isOnBorder(U.x,q.x)||this.isOnBorder(U.y,q.y))continue;const K=Cc.computeEdgeHash(this.unevalVertices[O],this.unevalVertices[z]);let Z,J=this.vertexHashLookup.get(Cc.computePosHash(U));J!=null?Z=J.next:(J=this.vertexHashLookup.get(Cc.computePosHash(q)),Z=J!=null?J.prev:K),this.unevalEdges.push({polygonIdx:l,a:O,b:z,hash:K,portalHash:Z,isTunnel:y,type:"unevaluated",featureInfo:S})}}addPortalCandidates(l,u,p,y,b){if(u.length!==0){this.vertexHashLookup.clear();for(const S of u){if(S.length===0)continue;const k=S[0];let j=Cc.computeEdgeHash(k[k.length-2],k[k.length-1]);for(let O=0;O({vertexOffset:0,primitiveOffset:this.indexArray.length}),p=q=>{q.primitiveLength=this.indexArray.length-q.primitiveOffset},y=new RAe(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(l.portals,this.unevalEdges);const b=u(),S=u(),k=u(),j=(q,K)=>{q.sort((J,ne)=>J.type===K&&ne.type!==K?-1:J.type!==K&&ne.type===K?1:0);const Z=q.findIndex(J=>J.type!==K);return Z>=0?Z:q.length};let O=0;this.unevalEdges.length>0&&(O=j(this.unevalEdges,"none"),this.constructBridgeStructures(y,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:O},this.tileToMeters)),p(k);const z=u(),U=u();if(this.unevalEdges.length>0){const q=this.unevalEdges.splice(O),K=j(q,"tunnel")+O;this.unevalEdges.push(...q),this.constructTunnelStructures(y,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:O},{min:O,max:K})}p(z),y.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),p(U),y.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),p(S),y.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),p(b),this.maskSegments=Si.simpleSegment(0,U.primitiveOffset,0,U.primitiveLength),this.depthSegments=Si.simpleSegment(0,S.primitiveOffset,0,S.primitiveLength),this.renderableBridgeSegments=Si.simpleSegment(0,k.primitiveOffset,0,k.primitiveLength),this.renderableTunnelSegments=Si.simpleSegment(0,z.primitiveOffset,0,z.primitiveLength),this.shadowCasterSegments=Si.simpleSegment(0,b.primitiveOffset,0,b.primitiveLength)}update(l,u,p,y,b,S,k,j){this.bridgeProgramConfigurations.updatePaintArrays(l,u,b,p,y,S,k,j),this.tunnelProgramConfigurations.updatePaintArrays(l,u,b,p,y,S,k,j)}upload(l){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=l.createVertexBuffer(this.vertexPositions,bAe.members),this.vertexBufferNormal=l.createVertexBuffer(this.vertexNormals,wAe.members),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(l),this.tunnelProgramConfigurations.upload(l))}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(l,u,p,y,b){const S=(k,j)=>{for(let O=0;Owe(It,u[Ct].x,u[Ct].y,p[Ct]*j),U=Se(),q=Se(),K=Se(),Z=Se(),J=Se(),ne=(It,Ct)=>{const Bt=k.get(Cc.computePosHash(u[Ct])),pt=Bt.from,jt=Bt.to;if(!pt||!jt)return;z(U,pt),z(q,Ct),z(K,jt),lr(Z),yr(U,q)||(tr(J,q,U),mt(Z,J)),yr(K,q)||(tr(J,K,q),ge(Z,Z,mt(J,J)));const Lt=lt(Z);return Lt>0?We(It,Z,1/Lt):void 0};let ae=Number.POSITIVE_INFINITY;this.sortSubarray(y,b.min,b.max,(It,Ct)=>It.featureInfo.featureIndex-Ct.featureInfo.featureIndex);const he=Se(),ce=Se(),ye=Se(),Ee=Se(),Ce=Se(),He=Se(),$e=Se(),Ge=Se(),Ue=Se(),Ve=[Se(),Se(),Se(),Se()],yt=[Se(),Se(),Se(),Se()],bt=[{coord:new Mt(0,0),height:0},{coord:new Mt(0,0),height:0}],kt=(It,Ct)=>It>Ct;for(let It=b.min;Itae.featureInfo.featureIndex-he.featureInfo.featureIndex;this.sortSubarray(y,b.min,b.max,j),this.sortSubarray(y,S.min,S.max,j);const O=ae=>mt(ae,ae),z=[{coord:new Mt(0,0),height:0},{coord:new Mt(0,0),height:0}],U=(ae,he)=>aek.hash===j.hash?j.polygonIdx-k.polygonIdx:j.hash>k.hash?1:-1);let p=0,y=0,b=0,S=u[p].polygonIdx;do y++,(y===u.length||u[p].hash!==u[y].hash)&&((y-p===1||u[y-1].polygonIdx!==S)&&(bO.portalHashz.hash?k++:z.hash>O.portalHash?j++:(O.type=z.type,k++)}}}isOnBorder(l,u){return l<=0&&u<=0||l>=ar&&u>=ar}addFeatureSection(l,u,p,y){return l!==u&&(u=l,p.push({featureIndex:l,vertexStart:y.getVertexCount()}),y.clearVertexLookup()),u}sortSubarray(l,u,p,y){const b=l.slice(u,p);b.sort(y),l.splice(u,b.length,...b)}static computeEdgeHash(l,u){return(l.y===u.y&&l.x>u.x||l.y>u.y)&&([l,u]=[u,l]),BigInt(Cc.computePosHash(l))<<32n|BigInt(Cc.computePosHash(u))}static computePosHash(l){return((65535&l.x)<<16|65535&l.y)>>>0}}function LAe(h,l){return h>l?1:h0))return u;u=u.left}}return null}contains(l){for(var u=this._root,p=this._compare;u;){var y=p(l,u.key);if(y===0)return!0;u=y<0?u.left:u.right}return!1}remove(l){var u=this.find(l);if(!u)return!1;if(this.splay(u),u.left)if(u.right){var p=this.minNode(u.right);p.parent!==u&&(this.replace(p,p.right),p.right=u.right,p.right.parent=p),this.replace(u,p),p.left=u.left,p.left.parent=p}else this.replace(u,u.left);else this.replace(u,u.right);return this._size--,!0}removeNode(l){if(!l)return!1;if(this.splay(l),l.left)if(l.right){var u=this.minNode(l.right);u.parent!==l&&(this.replace(u,u.right),u.right=l.right,u.right.parent=u),this.replace(l,u),u.left=l.left,u.left.parent=u}else this.replace(l,l.left);else this.replace(l,l.right);return this._size--,!0}erase(l){var u=this.find(l);if(u){this.splay(u);var p=u.left,y=u.right,b=null;p&&(p.parent=null,b=this.maxNode(p),this.splay(b),this._root=b),y&&(p?b.right=y:this._root=y,y.parent=b),this._size--}}pop(){var l=this._root,u=null;if(l){for(;l.left;)l=l.left;u={key:l.key,data:l.data},this.remove(l.key)}return u}next(l){var u=l;if(u)if(u.right)for(u=u.right;u&&u.left;)u=u.left;else for(u=l.parent;u&&u.right===l;)l=u,u=u.parent;return u}prev(l){var u=l;if(u)if(u.left)for(u=u.left;u&&u.right;)u=u.right;else for(u=l.parent;u&&u.left===l;)l=u,u=u.parent;return u}forEach(l){for(var u=this._root,p=[],y=!1,b=0;!y;)u?(p.push(u),u=u.left):p.length>0?(l(u=p.pop(),b++),u=u.right):y=!0;return this}range(l,u,p,y){const b=[],S=this._compare;let k,j=this._root;for(;b.length!==0||j;)if(j)b.push(j),j=j.left;else{if(j=b.pop(),k=S(j.key,u),k>0)break;if(S(j.key,l)>=0&&p.call(y,j))return this;j=j.right}return this}keys(){for(var l=this._root,u=[],p=[],y=!1;!y;)l?(u.push(l),l=l.left):u.length>0?(l=u.pop(),p.push(l.key),l=l.right):y=!0;return p}values(){for(var l=this._root,u=[],p=[],y=!1;!y;)l?(u.push(l),l=l.left):u.length>0?(l=u.pop(),p.push(l.data),l=l.right):y=!0;return p}at(l){for(var u=this._root,p=[],y=!1,b=0;!y;)if(u)p.push(u),u=u.left;else if(p.length>0){if(u=p.pop(),b===l)return u;b++,u=u.right}else y=!0;return null}load(l=[],u=[],p=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const y=l.length;return p&&o5(l,u,0,y-1,this._compare),this._root=a5(null,l,u,0,y),this._size=y,this}min(){var l=this.minNode(this._root);return l?l.key:null}max(){var l=this.maxNode(this._root);return l?l.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(l,u,p,y,b){return new s5(p,b).load(l,u,y)}}function a5(h,l,u,p,y){const b=y-p;if(b>0){const S=p+Math.floor(b/2),k={key:l[S],data:u[S],parent:h};return k.left=a5(k,l,u,p,S),k.right=a5(k,l,u,S+1,y),k}return null}function o5(h,l,u,p,y){if(u>=p)return;const b=h[u+p>>1];let S=u-1,k=p+1;for(;;){do S++;while(y(h[S],b)<0);do k--;while(y(h[k],b)>0);if(S>=k)break;let j=h[S];h[S]=h[k],h[k]=j,j=l[S],l[S]=l[k],l[k]=j}o5(h,l,u,k,y),o5(h,l,k+1,p,y)}const wK=11102230246251565e-32,oc=134217729,DAe=(3+8*wK)*wK;function l5(h,l,u,p,y){let b,S,k,j,O=l[0],z=p[0],U=0,q=0;z>O==z>-O?(b=O,O=l[++U]):(b=z,z=p[++q]);let K=0;if(UO==z>-O?(S=O+b,k=b-(S-O),O=l[++U]):(S=z+b,k=b-(S-z),z=p[++q]),b=S,k!==0&&(y[K++]=k);UO==z>-O?(S=b+O,j=S-b,k=b-(S-j)+(O-j),O=l[++U]):(S=b+z,j=S-b,k=b-(S-j)+(z-j),z=p[++q]),b=S,k!==0&&(y[K++]=k);for(;U0:(p[0]-l[0])*(u[1]-l[1])-(u[0]-l[0])*(p[1]-l[1])>0}isAbove(l){return!this.isBelow(l)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const l=new sb(this.point,this.left,this.otherEvent,this.isSubject,this.type);return l.contourId=this.contourId,l.resultTransition=this.resultTransition,l.prevInResult=this.prevInResult,l.isExteriorRing=this.isExteriorRing,l.inOut=this.inOut,l.otherInOut=this.otherInOut,l}}function bf(h,l){return h[0]===l[0]&&h[1]===l[1]}function c5(h,l,u){const p=function(y,b,S,k,j,O){const z=(b-O)*(S-j),U=(y-j)*(k-O),q=z-U;if(z===0||U===0||z>0!=U>0)return q;const K=Math.abs(z+U);return Math.abs(q)>=33306690738754716e-32*K?q:-function(Z,J,ne,ae,he,ce,ye){let Ee,Ce,He,$e,Ge,Ue,Ve,yt,bt,kt,It,Ct,Bt,pt,jt,Lt,$t,Wt;const xr=Z-he,ir=ne-he,nr=J-ce,Kt=ae-ce;pt=xr*Kt,Ue=oc*xr,Ve=Ue-(Ue-xr),yt=xr-Ve,Ue=oc*Kt,bt=Ue-(Ue-Kt),kt=Kt-bt,jt=yt*kt-(pt-Ve*bt-yt*bt-Ve*kt),Lt=nr*ir,Ue=oc*nr,Ve=Ue-(Ue-nr),yt=nr-Ve,Ue=oc*ir,bt=Ue-(Ue-ir),kt=ir-bt,$t=yt*kt-(Lt-Ve*bt-yt*bt-Ve*kt),It=jt-$t,Ge=jt-It,ib[0]=jt-(It+Ge)+(Ge-$t),Ct=pt+It,Ge=Ct-pt,Bt=pt-(Ct-Ge)+(It-Ge),It=Bt-Lt,Ge=Bt-It,ib[1]=Bt-(It+Ge)+(Ge-Lt),Wt=Ct+It,Ge=Wt-Ct,ib[2]=Ct-(Wt-Ge)+(It-Ge),ib[3]=Wt;let mr=function(zn,cn){let Un=cn[0];for(let bn=1;bn<4;bn++)Un+=cn[bn];return Un}(0,ib),kr=22204460492503146e-32*ye;if(mr>=kr||-mr>=kr||(Ge=Z-xr,Ee=Z-(xr+Ge)+(Ge-he),Ge=ne-ir,He=ne-(ir+Ge)+(Ge-he),Ge=J-nr,Ce=J-(nr+Ge)+(Ge-ce),Ge=ae-Kt,$e=ae-(Kt+Ge)+(Ge-ce),Ee===0&&Ce===0&&He===0&&$e===0)||(kr=11093356479670487e-47*ye+DAe*Math.abs(mr),mr+=xr*$e+Kt*Ee-(nr*He+ir*Ce),mr>=kr||-mr>=kr))return mr;pt=Ee*Kt,Ue=oc*Ee,Ve=Ue-(Ue-Ee),yt=Ee-Ve,Ue=oc*Kt,bt=Ue-(Ue-Kt),kt=Kt-bt,jt=yt*kt-(pt-Ve*bt-yt*bt-Ve*kt),Lt=Ce*ir,Ue=oc*Ce,Ve=Ue-(Ue-Ce),yt=Ce-Ve,Ue=oc*ir,bt=Ue-(Ue-ir),kt=ir-bt,$t=yt*kt-(Lt-Ve*bt-yt*bt-Ve*kt),It=jt-$t,Ge=jt-It,jc[0]=jt-(It+Ge)+(Ge-$t),Ct=pt+It,Ge=Ct-pt,Bt=pt-(Ct-Ge)+(It-Ge),It=Bt-Lt,Ge=Bt-It,jc[1]=Bt-(It+Ge)+(Ge-Lt),Wt=Ct+It,Ge=Wt-Ct,jc[2]=Ct-(Wt-Ge)+(It-Ge),jc[3]=Wt;const zr=l5(4,ib,4,jc,SK);pt=xr*$e,Ue=oc*xr,Ve=Ue-(Ue-xr),yt=xr-Ve,Ue=oc*$e,bt=Ue-(Ue-$e),kt=$e-bt,jt=yt*kt-(pt-Ve*bt-yt*bt-Ve*kt),Lt=nr*He,Ue=oc*nr,Ve=Ue-(Ue-nr),yt=nr-Ve,Ue=oc*He,bt=Ue-(Ue-He),kt=He-bt,$t=yt*kt-(Lt-Ve*bt-yt*bt-Ve*kt),It=jt-$t,Ge=jt-It,jc[0]=jt-(It+Ge)+(Ge-$t),Ct=pt+It,Ge=Ct-pt,Bt=pt-(Ct-Ge)+(It-Ge),It=Bt-Lt,Ge=Bt-It,jc[1]=Bt-(It+Ge)+(Ge-Lt),Wt=Ct+It,Ge=Wt-Ct,jc[2]=Ct-(Wt-Ge)+(It-Ge),jc[3]=Wt;const Rr=l5(zr,SK,4,jc,TK);pt=Ee*$e,Ue=oc*Ee,Ve=Ue-(Ue-Ee),yt=Ee-Ve,Ue=oc*$e,bt=Ue-(Ue-$e),kt=$e-bt,jt=yt*kt-(pt-Ve*bt-yt*bt-Ve*kt),Lt=Ce*He,Ue=oc*Ce,Ve=Ue-(Ue-Ce),yt=Ce-Ve,Ue=oc*He,bt=Ue-(Ue-He),kt=He-bt,$t=yt*kt-(Lt-Ve*bt-yt*bt-Ve*kt),It=jt-$t,Ge=jt-It,jc[0]=jt-(It+Ge)+(Ge-$t),Ct=pt+It,Ge=Ct-pt,Bt=pt-(Ct-Ge)+(It-Ge),It=Bt-Lt,Ge=Bt-It,jc[1]=Bt-(It+Ge)+(Ge-Lt),Wt=Ct+It,Ge=Wt-Ct,jc[2]=Ct-(Wt-Ge)+(It-Ge),jc[3]=Wt;const ln=l5(Rr,TK,4,jc,EK);return EK[ln-1]}(y,b,S,k,j,O,K)}(h[0],h[1],l[0],l[1],u[0],u[1]);return p>0?-1:p<0?1:0}function Eg(h,l){const u=h.point,p=l.point;return u[0]>p[0]?1:u[0]p[1]?1:-1:function(y,b,S){return y.left!==b.left?y.left?1:-1:c5(S,y.otherEvent.point,b.otherEvent.point)!==0?y.isBelow(b.otherEvent.point)?-1:1:!y.isSubject&&b.isSubject?1:-1}(h,l,u)}function Ag(h,l,u){const p=new sb(l,!1,h,h.isSubject),y=new sb(l,!0,h.otherEvent,h.isSubject);return bf(h.point,h.otherEvent.point)&&console.warn("what is that, a collapsed segment?",h),p.contourId=y.contourId=h.contourId,Eg(y,h.otherEvent)>0&&(h.otherEvent.left=!0,y.left=!1),h.otherEvent.otherEvent=y,h.otherEvent=p,u.push(y),u.push(p),u}function NI(h,l){return h[0]*l[1]-h[1]*l[0]}function u5(h,l){return h[0]*l[0]+h[1]*l[1]}function d5(h,l,u){const p=function(j,O,z,U){const q=[O[0]-j[0],O[1]-j[1]],K=[U[0]-z[0],U[1]-z[1]];function Z(He,$e,Ge){return[He[0]+$e*Ge[0],He[1]+$e*Ge[1]]}const J=[z[0]-j[0],z[1]-j[1]];let ne=NI(q,K),ae=ne*ne;const he=u5(q,q);if(ae>0){const He=NI(J,K)/ne;if(He<0||He>1)return null;const $e=NI(J,q)/ne;return $e<0||$e>1?null:He===0||He===1?[Z(j,He,q)]:$e===0||$e===1?[Z(z,$e,K)]:[Z(j,He,q)]}if(ne=NI(J,q),ae=ne*ne,ae>0)return null;const ce=u5(q,J)/he,ye=ce+u5(q,K)/he,Ee=Math.min(ce,ye),Ce=Math.max(ce,ye);return Ee<=1&&Ce>=0?Ee===1?[Z(j,Ee>0?Ee:0,q)]:Ce===0?[Z(j,Ce<1?Ce:1,q)]:[Z(j,Ee>0?Ee:0,q),Z(j,Ce<1?Ce:1,q)]:null}(h.point,h.otherEvent.point,l.point,l.otherEvent.point),y=p?p.length:0;if(y===0||y===1&&(bf(h.point,l.point)||bf(h.otherEvent.point,l.otherEvent.point))||y===2&&h.isSubject===l.isSubject)return 0;if(y===1)return!bf(h.point,p[0])&&!bf(h.otherEvent.point,p[0])&&Ag(h,p[0],u),!bf(l.point,p[0])&&!bf(l.otherEvent.point,p[0])&&Ag(l,p[0],u),1;const b=[];let S=!1,k=!1;return bf(h.point,l.point)?S=!0:Eg(h,l)===1?b.push(l,h):b.push(h,l),bf(h.otherEvent.point,l.otherEvent.point)?k=!0:Eg(h.otherEvent,l.otherEvent)===1?b.push(l.otherEvent,h.otherEvent):b.push(h.otherEvent,l.otherEvent),S&&k||S?(l.type=1,h.type=l.inOut===h.inOut?2:3,S&&!k&&Ag(b[1].otherEvent,b[0].point,u),2):k?(Ag(b[0],b[1].point,u),3):b[0]!==b[3].otherEvent?(Ag(b[0],b[1].point,u),Ag(b[1],b[2].point,u),3):(Ag(b[0],b[1].point,u),Ag(b[3].otherEvent,b[2].point,u),3)}function OAe(h,l){if(h===l)return 0;if(c5(h.point,h.otherEvent.point,l.point)!==0||c5(h.point,h.otherEvent.point,l.otherEvent.point)!==0)return bf(h.point,l.point)?h.isBelow(l.otherEvent.point)?-1:1:h.point[0]===l.point[0]?h.point[1](l.contourId??0)?1:-1}return Eg(h,l)===1?1:-1}class MAe{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function FAe(h,l,u,p){let y,b=h+1,S=l[h].point;const k=l.length;for(bp;)b--;return b}function BAe(h,l,u){const p=new MAe;if(h.prevInResult!=null){const y=h.prevInResult,b=y.outputContourId;if(y.resultTransition>0){const S=l[b];if(S.holeOf!=null){const k=S.holeOf;l[k].holeIds.push(u),p.holeOf=k,p.depth=l[b].depth}else l[b].holeIds.push(u),p.holeOf=b,p.depth=l[b].depth+1}else p.holeOf=null,p.depth=l[b].depth}else p.holeOf=null,p.depth=0;return p}const kK=Math.max,CK=Math.min;let RI=0;function jK(h,l,u,p,y,b){let S,k,j,O,z,U;for(S=0,k=h.length-1;S0?U.left=!0:z.left=!0;const q=j[0],K=j[1];y[0]=CK(y[0],q),y[1]=CK(y[1],K),y[2]=kK(y[2],q),y[3]=kK(y[3],K),p.push(z),p.push(U)}}const LI=[];function IK(h,l,u){let p=h,y=l;typeof h[0][0][0]=="number"&&(p=[h]),typeof l[0][0][0]=="number"&&(y=[l]);let b=function(q,K,Z){let J=null;return q.length*K.length===0&&(Z===0?J=LI:Z===2?J=q:(Z===1||Z===3)&&(J=q.length===0?K:q)),J}(p,y,u);if(b)return b===LI?null:b;const S=[1/0,1/0,-1/0,-1/0],k=[1/0,1/0,-1/0,-1/0],j=function(q,K,Z,J,ne){const ae=new Lx(void 0,Eg);let he,ce,ye,Ee,Ce,He;for(ye=0,Ee=q.length;yeJ[2]||J[0]>Z[2]||Z[1]>J[3]||J[1]>Z[3])&&(ne===0?ae=LI:ne===2?ae=q:(ne===1||ne===3)&&(ae=q.concat(K))),ae}(p,y,S,k,u),b)return b===LI?null:b;const O=function(q,K,Z,J,ne,ae){const he=new s5(OAe),ce=[],ye=Math.min(J[2],ne[2]);let Ee,Ce,He;for(;q.length!==0;){let $e=q.pop();if(ce.push($e),ae===0&&$e.point[0]>ye||ae===2&&$e.point[0]>J[2])break;if($e.left){Ce=Ee=he.insert($e),He=he.minNode(),Ee=Ee!==He?he.prev(Ee):null,Ce=he.next(Ce);const Ge=Ee?Ee.key:null;let Ue;if(EE($e,Ge,ae),Ce&&d5($e,Ce.key,q)===2&&(EE($e,Ge,ae),EE(Ce.key,$e,ae)),Ee&&d5(Ee.key,$e,q)===2){let Ve=Ee;Ve=Ve!==He?he.prev(Ve):null,Ue=Ve?Ve.key:null,EE(Ge,Ue,ae),EE($e,Ge,ae)}}else $e=$e.otherEvent,Ce=Ee=he.find($e),Ee&&Ce&&(Ee=Ee!==He?he.prev(Ee):null,Ce=he.next(Ce),he.remove($e),Ce&&Ee&&d5(Ee.key,Ce.key,q))}return ce}(j,0,0,S,k,u),z=function(q){let K,Z;const J=function(he){let ce,ye,Ee,Ce,He;const $e=[];for(ye=0,Ee=he.length;ye{ne[He]=!0,He=J.length)&&J[Ee];);ae.push(ce)}return ae}(O),U=[];for(let q=0;q{S.push(new Mt(U,j+(U-k)/(O-k)*(z-j)))}:(S,k,j,O,z,U)=>{S.push(new Mt(k+(U-j)/(z-j)*(O-k),U))};for(const S of h){const k=[];for(const j of S){if(j.length<=2)continue;const O=[];for(let q=0;ql&&b(O,K,Z,J,ne,l):ae>u?he=l&&b(O,K,Z,J,ne,l),he>u&&ae<=u&&b(O,K,Z,J,ne,u)}let z=j[j.length-1];const U=p===0?z.x:z.y;U>=l&&U<=u&&O.push(z),O.length&&(z=O[O.length-1],O[0].x===z.x&&O[0].y===z.y||O.push(O[0]),k.push(O))}k.length&&y.push(k)}return y}function zAe(h,l){const u=IK(h5(h),h5([l]),0);return u==null?[]:PK(u)}function $Ae(h,l,u=0){let y=h5(h,65536);const b=[];for(;l.valid();l.next()){const[S,k]=l.get();let j=S.x*65536,O=S.y*65536,z=k.x*65536,U=k.y*65536;const q=z-j,K=U-O,Z=Math.hypot(q,K);if(Z===0)continue;j-=q*u,O-=K*u,z+=q*u,U+=K*u;const J=Math.trunc(K/Z*3),ne=-Math.trunc(q/Z*3);b.push([[[j,O],[z,U],[z+J,U+ne],[j+J,O+ne],[j,O]]])}return b.length>0&&(y=IK(y,b,2)),PK(y,1/65536,128)}function h5(h,l=1){return[h.map(u=>u.map(p=>[p.x*l,p.y*l]))]}function PK(h,l=1,u){return h.map(p=>p.map((y,b)=>{const S=y.map(k=>{let j=k[0],O=k[1];return u&&(j=Math.round(j/u)*u,O=Math.round(O/u)*u),new Mt(j*l,O*l)._round()});return b>0&&S.reverse(),S}))}class f5{constructor(l,u){this.layoutVertexArray=new ic,this.indexArray=new _s,this.lineIndexArray=new cu,this.triangleSegments=new Si,this.lineSegments=new Si,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut}),this.uploaded=!1,u&&(this.elevatedLayoutVertexArray=new Tc)}update(l,u,p,y,b,S,k,j){this.programConfigurations.updatePaintArrays(l,u,b,p,y,S,k,j)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,_Ae.members),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.lineIndexBuffer=l.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=l.createVertexBuffer(this.elevatedLayoutVertexArray,vAe.members))),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(l,u,p,y,b,S,k){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,u,p,y,b,S,void 0,k)}}class OI{constructor(l){this.zoom=l.zoom,this.pixelRatio=l.pixelRatio,this.overscaling=l.overscaling,this.layers=l.layers,this.layerIds=this.layers.map(u=>u.fqid),this.index=l.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=l.lut,this.bufferData=new f5(l,!1),this.elevationBufferData=new f5(l,!0),this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.projection=l.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=l.sourceLayerIndex,this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,p,y){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,y){this.hasPattern=n5("fill",this.layers,this.pixelRatio,u);const b=this.layers[0].layout.get("fill-sort-key"),S=[];for(const{feature:k,id:j,index:O,sourceLayerIndex:z}of l){const U=this.layers[0]._featureFilter.needGeometry,q=vn(k,U);if(!this.layers[0]._featureFilter.filter(new ti(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),q,p))continue;const K=b?b.evaluate(q,{},p,u.availableImages):void 0,Z={id:j,properties:k.properties,type:k.type,sourceLayerIndex:z,index:O,geometry:U?q.geometry:$r(k,p,y),patterns:{},sortKey:K};S.push(Z)}b&&S.sort((k,j)=>k.sortKey-j.sortKey);for(const k of S){const{geometry:j,index:O,sourceLayerIndex:z}=k;if(this.hasPattern){const U=i5("fill",this.layers,k,this.zoom,this.pixelRatio,u);this.patternFeatures.push(U)}else this.addFeature(k,j,O,p,{},u.availableImages,u.brightness,u.elevationFeatures);u.featureIndex.insert(l[O].feature,j,O,z,this.index)}}update(l,u,p,y,b,S,k){this.bufferData.update(l,u,p,y,b,S,k,this.worldview),this.elevationBufferData.update(l,u,p,y,b,S,k,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(l,u,p,y,b,S,k,this.worldview)}addFeatures(l,u,p,y,b,S){for(const k of this.patternFeatures)this.addFeature(k,k.geometry,k.index,u,p,y,S,l.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(l){this.bufferData.upload(l),this.elevationBufferData.upload(l),this.elevatedStructures&&this.elevatedStructures.upload(l)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(l,u,p,y,b,S=[],k,j){const O=SE(u,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(l,O,y,p,j):this.addGeometry(O,this.bufferData),this.bufferData.populatePaintArrays(l,p,b,S,y,k,this.worldview),this.elevationBufferData.populatePaintArrays(l,p,b,S,y,k,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(l,u,p,y,b){this.elevatedStructures&&(this.elevatedStructures.construct(l),this.elevatedStructures.populatePaintArrays(u,p,y,b,this.worldview))}addElevatedRoadFeature(l,u,p,y,b){const S=new Array,k=Ii.getElevationFeature(l,b);if(!k)return void this.addGeometry(u,this.bufferData);{const O=this.clipPolygonsToTile(u,1);O.length>0&&S.push({polygons:O,elevationFeature:k,elevationTileID:p})}const j={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(l,{},p),featureIndex:y};for(const O of S)if(O.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new Cc(O.elevationTileID,this.layers,this.zoom,this.lut));const U=O.elevationFeature.isTunnel();let q=0;l.properties.hasOwnProperty(Ei)&&(q=+l.properties[Ei]),this.elevatedStructures.addPortalCandidates(O.elevationFeature.id,O.polygons,U,O.elevationFeature,q)}O.elevationFeature.constantHeight==null&&(O.polygons=this.prepareElevatedPolygons(O.polygons,O.elevationFeature,O.elevationTileID));const z=new Mi(p,O.elevationTileID);this.addElevatedGeometry(O.polygons,z,O.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,y,j)}}addElevatedGeometry(l,u,p,y,b,S){const k={elevation:p,elevationSampler:u,bias:y,index:b,featureInfo:S},[j,O]=this.addGeometry(l,this.elevationBufferData,k);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:j,max:O}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,j),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,O))}addGeometry(l,u,p){let y=Number.POSITIVE_INFINITY,b=Number.NEGATIVE_INFINITY,S=null;p&&(S=p.elevationSampler.constantElevation(p.elevation,p.bias),S!=null&&(y=S,b=S));const k=(j,O,z)=>{if(p!=null)if(O.push(j),S!=null)u.elevatedLayoutVertexArray.emplaceBack(S),z.push(S);else{const U=p.elevationSampler.pointElevation(j,p.elevation,p.bias);u.elevatedLayoutVertexArray.emplaceBack(U),z.push(U),y=Math.min(y,U),b=Math.max(b,U)}};for(const j of l){let O=0;for(const ce of j)O+=ce.length;const z=u.triangleSegments.prepareSegment(O,u.layoutVertexArray,u.indexArray),U=z.vertexLength,q=[],K=[],Z=[],J=[],ne=[],ae=u.layoutVertexArray.length;for(const ce of j){if(ce.length===0)continue;ce!==j[0]&&K.push(q.length/2);const ye=u.lineSegments.prepareSegment(ce.length,u.layoutVertexArray,u.lineIndexArray),Ee=ye.vertexLength;p&&ne.push(u.layoutVertexArray.length-ae),k(ce[0],Z,J),u.layoutVertexArray.emplaceBack(ce[0].x,ce[0].y),u.lineIndexArray.emplaceBack(Ee+ce.length-1,Ee),q.push(ce[0].x),q.push(ce[0].y);for(let Ce=1;Ce0&&p&&this.elevationMode==="hd-road-base"){const ce=p.elevation.isTunnel(),ye=p.elevation.safeArea,Ee=this.elevatedStructures.addVertices(Z,J);this.elevatedStructures.addTriangles(he,Ee,ce);const Ce=ne.length;if(Ce>0){for(let He=0;He=p&&K.max.x<=b&&K.min.y>=y&&K.max.y<=S?j:O).push(q)}if(j.length===l.length)return l;const z=[new Mt(p,y),new Mt(b,y),new Mt(b,S),new Mt(p,S),new Mt(p,y)],U=j;for(const q of O)U.push(...zAe(q,z));return U}}let NK,RK,LK,DK;vr(OI,"FillBucket",{omit:["layers","patternFeatures"]}),vr(f5,"FillBufferData"),vr(Cc,"ElevatedStructures");class MI{constructor(l,u,p,y){if(this.triangleCount=u.length/3,this.min=new Mt(0,0),this.max=new Mt(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||l.length===0)return;const[b,S]=[l[0].clone(),l[0].clone()];for(let U=1;UU.cellIdx-q.cellIdx||U.triIdx-q.triIdx);let z=0;for(;zthis.max.x||this.min.x>l.x||l.y>this.max.y||this.min.y>l.y)return;const p=wf(l.x-this.min.x,this.xScale,this.cellsX),y=wf(l.y-this.min.y,this.yScale,this.cellsY),b=this.cells[y*this.cellsX+p];if(b){this._lazyInitLookup();for(let S=0;Sthis.max.x||this.min.x>u.x||l.y>this.max.y||this.min.y>u.y)return;this._lazyInitLookup();const y=wf(l.x-this.min.x,this.xScale,this.cellsX),b=wf(u.x-this.min.x,this.xScale,this.cellsX),S=wf(l.y-this.min.y,this.yScale,this.cellsY),k=wf(u.y-this.min.y,this.yScale,this.cellsY);for(let j=S;j<=k;j++)for(let O=y;O<=b;O++){const z=this.cells[j*this.cellsX+O];if(z)for(let U=0;Uu.fqid),this.index=l.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.footprints=[],this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){for(const p of this.footprints)u.push({footprint:p,id:l})}updateAppearances(l,u,p,y){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,y){const b=[];for(const{feature:S,id:k,index:j,sourceLayerIndex:O}of l){const z=this.layers[0]._featureFilter.needGeometry,U=vn(S,z);if(!this.layers[0]._featureFilter.filter(new ti(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),U,p))continue;const q={id:k,properties:S.properties,type:S.type,sourceLayerIndex:O,index:j,geometry:z?U.geometry:$r(S,p,y),patterns:{}};b.push(q)}for(const S of b){const{geometry:k,index:j,sourceLayerIndex:O}=S;this.addFeature(S,k,j,p,{},u.availableImages,u.brightness),u.featureIndex.insert(l[j].feature,k,j,O,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(l){}update(l,u,p,y,b,S,k){}destroy(){}addFeature(l,u,p,y,b,S=[],k){for(const j of SE(u,2)){const O=[],z=[],U=[],q=new Mt(1/0,1/0),K=new Mt(-1/0,-1/0);for(const ne of j)if(ne.length!==0){ne!==j[0]&&U.push(z.length/2);for(let ae=0;ael.max.x||h.max.xl.max.y||h.max.ynew Mt((j.x+b.x*ar)*k-S.x*ar,(j.y+b.y*ar)*k-S.y*ar))}return m5(u,y,h.indices,0,h.indices.length,0,0)}function $K(h,l,u,p){const y=Math.pow(2,p.z-u.z);return new Mt((h+u.x*ar)*y-p.x*ar,(l+u.y*ar)*y-p.y*ar)}function UK(h,l){const u=[];l.grid.queryPoint(h,u);const p=l.indices,y=l.vertices;for(let b=0;b0&&(p.length>1&&u.push(p),p=[])}return p.length>1&&u.push(p),u}const y5=tn.types,QAe=["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"],JAe=["fill-extrusion-flood-light-ground-radius"],eke=Math.pow(2,13),tke=Math.pow(2,15)-1,$I=new Mt(0,1),Vp=2147483648,UI=1073741824;function kE(h,l,u,p,y,b,S,k){h.emplaceBack((l<<1)+S,(u<<1)+b,(Math.floor(p*eke)<<1)+y,Math.round(k))}function CE(h,l,u){h.emplaceBack(l.x*ar,l.y*ar,u?1:0)}function VI(h,l,u,p,y,b){h.emplaceBack(l.x,l.y,(u.x<<1)+p,(u.y<<1)+y,b)}function jE(h,l,u){h.emplaceBack(l.x,l.y,l.z,u[0]*16384,u[1]*16384,u[2]*16384)}class qK{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class x5{constructor(){this.centroidXY=new Mt(0,0),this.vertexArrayOffset=0,this.vertexCount=0,this.groundVertexArrayOffset=0,this.groundVertexCount=0,this.flags=0,this.footprintSegIdx=-1,this.footprintSegLen=0,this.polygonSegIdx=-1,this.polygonSegLen=0,this.min=new Mt(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Mt(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new Mt(0,0)}span(){return new Mt(this.max.x-this.min.x,this.max.y-this.min.y)}}class _5{constructor(){this.acc=new Mt(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(l,u){l.min.x===Number.MAX_VALUE&&(l.min.x=l.max.x=u.x,l.min.y=l.max.y=u.y)}appendEdge(l,u,p){this.accCount++,this.acc._add(u);let y=!!this.borders;u.xl.max.x&&(l.max.x=u.x,y=!0),u.yl.max.y&&(l.max.y=u.y,y=!0),((u.x===0||u.x===ar)&&u.x===p.x)!=((u.y===0||u.y===ar)&&u.y===p.y)&&this.processBorderOverlap(u,p),y&&this.checkBorderIntersection(u,p)}checkBorderIntersection(l,u){u.x<0!=l.x<0&&this.addBorderIntersection(0,Xr(u.y,l.y,(0-u.x)/(l.x-u.x))),u.x>ar!=l.x>ar&&this.addBorderIntersection(1,Xr(u.y,l.y,(ar-u.x)/(l.x-u.x))),u.y<0!=l.y<0&&this.addBorderIntersection(2,Xr(u.x,l.x,(0-u.y)/(l.y-u.y))),u.y>ar!=l.y>ar&&this.addBorderIntersection(3,Xr(u.x,l.x,(ar-u.y)/(l.y-u.y)))}addBorderIntersection(l,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 p=this.borders[l];up[1]&&(p[1]=u)}processBorderOverlap(l,u){if(l.x===u.x){if(l.y===u.y)return;const p=l.x===0?0:1;this.addBorderIntersection(p,u.y),this.addBorderIntersection(p,l.y)}else{const p=l.y===0?2:3;this.addBorderIntersection(p,u.x),this.addBorderIntersection(p,l.x)}}centroid(){return this.accCount===0?new Mt(0,0):new Mt(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((l,u)=>l+ +(u[0]!==Number.MAX_VALUE),0):0}}function GK(h,l){const u=h.add(l)._unit(),p=fe(h.x*u.x+h.y*u.y,-1,1);var y,b,S;return S=Math.acos(p),Math.min(4,Math.max(-4,Math.tan(S)))/4*tke*((y=h).x*(b=l).y-y.y*b.x<0?-1:1)}const rke=[h=>h.x<0,h=>h.x>ar,h=>h.y<0,h=>h.y>ar];function nke(h,l,u,p){const y=[4];if(p===0)return y;u._mult(p);const b=h.sub(u),S=l.sub(u),k=[h,l,b,S];for(let j=0;j<4;j++)for(const O of k)if(rke[j](O)){y.push(j);break}return y}class v5{constructor(l){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new tE,this.indexArray=new _s,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut},u=>JAe.includes(u)),this._segments=new Si,this.hiddenByLandmarkVertexArray=new Xv,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Si}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(l,u,p,y=!1){const b=l.length;if(b>2){let S=Math.max(0,this._segments.get().length-1);const k=this._segments._prepareSegment(4*b,this.vertexArray.length,2*this._segmentToGroundQuads[S].length);let j;S!==this._segments.get().length-1&&(S++,this._segmentToGroundQuads[S]=[],this._segmentToRegionTriCounts[S]=[0,0,0,0,0]);{const O=l[0],z=l[1];j=GK(O.sub(l[b-1])._perp()._unit(),z.sub(O)._perp()._unit())}for(let O=0;Oy.region-b.region);for(let p=0;pj+O,0);let k=0;for(let j=0;j<=4;j++){const O=S[j];if(O!==0){let z=this.regionSegments[j];z||(z=this.regionSegments[j]=new Si);const U={vertexOffset:b.vertexOffset,primitiveOffset:b.primitiveOffset+k,vertexLength:b.vertexLength,primitiveLength:O};z.get().push(U)}k+=O}for(let j=0;j0?this.hiddenByLandmarkVertexBuffer=l.createVertexBuffer(this.hiddenByLandmarkVertexArray,WAe.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 l=0;l<=4;l++){const u=this.regionSegments[l];u&&u.destroy()}}}}class qI{constructor(l){this.zoom=l.zoom,this.canonical=l.canonical,this.overscaling=l.overscaling,this.layers=l.layers,this.pixelRatio=l.pixelRatio,this.layerIds=this.layers.map(u=>u.fqid),this.index=l.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=l.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new _s,this.footprintVertices=new ic,this.footprintSegments=[],this.layoutVertexArray=new eE,this.centroidVertexArray=new SI,this.wallVertexArray=new fE,this.indexArray=new _s,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut},u=>QAe.includes(u)),this.segments=new Si,this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.groundEffect=new v5(l),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,p,y){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,y){this.features=[],this.hasPattern=n5("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=Dt(p),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;for(const{feature:b,id:S,index:k,sourceLayerIndex:j}of l){const O=this.layers[0]._featureFilter.needGeometry,z=vn(b,O);if(!this.layers[0]._featureFilter.filter(new ti(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),z,p))continue;const U={id:S,sourceLayerIndex:j,index:k,geometry:O?z.geometry:$r(b,p,y),properties:b.properties,type:b.type,patterns:{}},q=this.layoutVertexArray.length,K=y5[U.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:b.id,feature:i5("fill-extrusion",this.layers,U,this.zoom,this.pixelRatio,u)});else if(this.wallMode)for(const Z of U.geometry)for(const J of VK(Z,K))this.addFeature(b.id,U,[J],k,p,{},u.availableImages,y,u.brightness);else this.addFeature(b.id,U,U.geometry,k,p,{},u.availableImages,y,u.brightness);u.featureIndex.insert(b,U.geometry,k,j,this.index,q)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(l,u,p,y,b,S){for(const{featureId:k,feature:j}of this.features){const O=y5[j.type]==="Polygon",{geometry:z}=j;if(this.wallMode)for(const U of z)for(const q of VK(U,O))this.addFeature(k,j,[q],j.index,u,p,y,b,S);else this.addFeature(k,j,z,j.index,u,p,y,b,S)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(l,u,p,y,b,S,k){this.programConfigurations.updatePaintArrays(l,u,b,p,y,S,k,this.worldview),this.groundEffect.update(l,u,b,p,y,S,k,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,YAe),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.wallVertexBuffer=l.createVertexBuffer(this.wallVertexArray,HAe.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=l.createVertexBuffer(this.layoutVertexExtArray,KAe.members,!0)),this.groundEffect.upload(l)),this.groundEffect.uploadPaintProperties(l),this.programConfigurations.upload(l),this.uploaded=!0}uploadCentroid(l){this.groundEffect.uploadHiddenByLandmark(l),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=l.createVertexBuffer(this.centroidVertexArray,GAe.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())}addFeature(l,u,p,y,b,S,k,j,O){const z=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(u,{})/this.tileToMeter,U=[new Mt(0,0),new Mt(ar,ar)],q=j.projection,K=q.name==="globe",Z=this.wallMode||y5[u.type]==="Polygon",J=new _5;J.centroidDataIndex=this.centroidData.length;const ne=new x5;ne.buildingId=l,u.properties&&u.properties.hasOwnProperty("building_id")&&(ne.buildingId=Number(u.properties.building_id)),J.buildingId=ne.buildingId;const ae=this.layers[0].paint.get("fill-extrusion-base").evaluate(u,{},b)<=0,he=this.layers[0].paint.get("fill-extrusion-height").evaluate(u,{},b);let ce;if(ne.height=he,ne.vertexArrayOffset=this.layoutVertexArray.length,ne.groundVertexArrayOffset=this.groundEffect.vertexArray.length,K&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new Gv),this.wallMode){if(K)return void Br("Non zero fill-extrusion-line-width is not yet supported on globe.");if(p.length!==1)return;ce=function(Ue){const Ve=Ue[0].x===Ue[Ue.length-1].x&&Ue[0].y===Ue[Ue.length-1].y;(function(nr){let Kt=0;const mr=nr.length;for(let kr=0;kr=0})(Ue)||(Ue=Ue.reverse());const bt={geometry:[],joinNormals:[],indices:[]},kt=[],It=[],Ct=[];let Bt=Ue.length;for(;Bt>=2&&Ue[Bt-1].equals(Ue[Bt-2]);)Bt--;if(Bt<(Ve?3:2))return bt;let pt,jt,Lt,$t,Wt,xr=0;for(;xr0;let Rr="miter";const ln=2;Rr==="miter"&&kr>ln&&(Rr="bevel"),Rr==="bevel"&&(kr>100&&(Rr="flipbevel"),kr{const ri=new Mt(cn.x,cn.y),Gn=new Mt(cn.x,cn.y);ri.x+=Un.x*fs,ri.y+=Un.y*fs,Gn.x-=Un.x*Math.max(bn,1),Gn.y-=Un.y*Math.max(bn,1),Ct.push(Un),kt.push(ri),It.push(Gn)};if(Rr==="miter")Kt._mult(kr),zn(pt,Kt,0,0);else if(Rr==="flipbevel")Kt=Wt.mult(-1),zn(pt,Kt,0,0),zn(pt,Kt.mult(-1),0,0);else{const cn=-Math.sqrt(kr*kr-1),Un=zr?cn:0,bn=zr?0:cn;jt&&zn(pt,$t,Un,bn),Lt&&zn(pt,Wt,Un,bn)}}bt.geometry=[...kt,...It.reverse(),kt[0]],bt.joinNormals=[...Ct,...Ct.reverse(),Ct[Ct.length-1]];const ir=bt.geometry.length-1;for(let nr=0;nrUe<(Ve.length-1)/2||Ue===Ve.length-1,Ee=this.wallMode?[p]:SE(p,500);for(let Ue=Ee.length-1;Ue>=0;Ue--){const Ve=Ee[Ue];(Ve.length===0||ske(Ve[0]))&&Ee.splice(Ue,1)}let Ce;if(K)Ce=QK(Ee,U,b);else{Ce=[];for(const Ue of Ee)Ce.push({polygon:Ue,bounds:U})}const He=Z?this.edgeRadius:0,$e=He>0&&this.zoom<17,Ge=(Ue,Ve)=>{if(Ue.length===0)return!1;const yt=Ue[Ue.length-1];return Ve.x===yt.x&&Ve.y===yt.y};for(const{polygon:Ue,bounds:Ve}of Ce){let yt=0,bt=0;for(const Bt of Ue)Z&&!Bt[0].equals(Bt[Bt.length-1])&&Bt.push(Bt[0]),bt+=Z?Bt.length-1:Bt.length;const kt=this.segments.prepareSegment((Z?5:4)*bt,this.layoutVertexArray,this.indexArray);ne.footprintSegIdx<0&&(ne.footprintSegIdx=this.footprintSegments.length),ne.polygonSegIdx<0&&(ne.polygonSegIdx=this.polygonSegments.length);const It={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},Ct=new qK;if(Ct.vertexOffset=this.footprintVertices.length,Ct.indexOffset=3*this.footprintIndices.length,Ct.ringIndices=[],Z){const Bt=[],pt=[];yt=kt.vertexLength;for(let Lt=0;Lt4&&YK(pt[pt.length-2],pt[0],pt[1]),Lt=He?ike(pt[pt.length-2],pt[0],pt[1],He):0;const $t=[];let Wt,xr,ir;xr=pt[1].sub(pt[0])._perp()._unit();let nr=!0;for(let Kt=1,mr=0;Kt0?1:0,Un=kr.dist(zr);if(mr+Un>32768&&(mr=0),He){ir=Rr.sub(zr)._perp()._unit();let Gn=WK(kr,zr,Rr,HK(xr,ir),He);isNaN(Gn)&&(Gn=0);const Ai=zr.sub(kr)._unit();kr=kr.add(Ai.mult(Lt))._round(),zr=zr.add(Ai.mult(-Gn))._round(),Lt=Gn,xr=ir,ae&&this.zoom>=17&&(Ge($t,kr)||$t.push(kr),Ge($t,zr)||$t.push(zr))}const bn=kt.vertexLength,fs=pt.length>4&&YK(kr,zr,Rr);let ri=ZK(mr,jt,nr);if(kE(this.layoutVertexArray,kr.x,kr.y,zn,cn,0,0,ri),kE(this.layoutVertexArray,kr.x,kr.y,zn,cn,0,1,ri),this.wallMode){const Gn=ye(Kt-1,pt),Ai=ce.joinNormals[Kt-1];CE(this.wallVertexArray,Ai,Gn),CE(this.wallVertexArray,Ai,Gn)}if(mr+=Un,ri=ZK(mr,fs,!nr),jt=fs,kE(this.layoutVertexArray,zr.x,zr.y,zn,cn,0,0,ri),kE(this.layoutVertexArray,zr.x,zr.y,zn,cn,0,1,ri),this.wallMode){const Gn=ye(Kt,pt),Ai=ce.joinNormals[Kt];CE(this.wallVertexArray,Ai,Gn),CE(this.wallVertexArray,Ai,Gn)}if(kt.vertexLength+=4,this.indexArray.emplaceBack(bn+0,bn+1,bn+2),this.indexArray.emplaceBack(bn+1,bn+3,bn+2),kt.primitiveLength+=2,He){const Gn=yt+(Kt===1?pt.length-2:Kt-2),Ai=Kt===1?yt:Gn+1;if(this.indexArray.emplaceBack(bn+1,Gn,bn+3),this.indexArray.emplaceBack(Gn,Ai,bn+3),kt.primitiveLength+=2,Wt===void 0&&(Wt=bn),!b5(Rr,pt[Kt],Ve)){const os=Kt===pt.length-1?Wt:kt.vertexLength;this.indexArray.emplaceBack(bn+2,bn+3,os),this.indexArray.emplaceBack(bn+3,os+1,os),this.indexArray.emplaceBack(bn+3,Ai,os+1),kt.primitiveLength+=3}nr=!nr}if(K){const Gn=this.layoutVertexExtArray,Ai=q.projectTilePoint(kr.x,kr.y,b),os=q.projectTilePoint(zr.x,zr.y,b),Ra=q.upVector(b,kr.x,kr.y),ls=q.upVector(b,zr.x,zr.y);jE(Gn,Ai,Ra),jE(Gn,Ai,Ra),jE(Gn,os,ls),jE(Gn,os,ls)}}Z&&(yt+=pt.length-1),ae&&He&&this.zoom>=17&&($t.length!==0&&Ge($t,$t[0])&&$t.pop(),this.groundEffect.addData($t,Ve,z,He>0))}this.footprintSegments.push(Ct),It.triangleCount=this.indexArray.length-It.triangleArrayOffset,this.polygonSegments.push(It),++ne.footprintSegLen,++ne.polygonSegLen}if(ne.vertexCount=this.layoutVertexArray.length-ne.vertexArrayOffset,ne.groundVertexCount=this.groundEffect.vertexArray.length-ne.groundVertexArrayOffset,ne.vertexCount!==0){if(ne.centroidXY=J.borders?$I:this.encodeCentroid(J,ne),u.properties&&u.properties.hasOwnProperty("building_id")){const Ue=ne.buildingId;let Ve=this.buildingGroups.get(Ue);Ve||(Ve={accX:0,accY:0,accCount:0,mergedMin:new Mt(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Mt(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Ue,Ve)),Ve.accX+=J.acc.x,Ve.accY+=J.acc.y,Ve.accCount+=J.accCount,Ve.mergedMin.x=Math.min(Ve.mergedMin.x,ne.min.x),Ve.mergedMin.y=Math.min(Ve.mergedMin.y,ne.min.y),Ve.mergedMax.x=Math.max(Ve.mergedMax.x,ne.max.x),Ve.mergedMax.y=Math.max(Ve.mergedMax.y,ne.max.y),Ve.partIndices.push(this.centroidData.length)}if(this.centroidData.push(ne),J.borders){this.featuresOnBorder.push(J);const Ue=this.featuresOnBorder.length-1;for(let Ve=0;Vethis.featuresOnBorder[u].borders[l][0]-this.featuresOnBorder[p].borders[l][0])}splitToSubtiles(){const l=[];for(let k=0;kar),z=2*O+(+(j.min.x+j.max.x>ar)^O);for(let U=0;Uk.triangleSegmentIdx===j.triangleSegmentIdx?k.subtile-j.subtile:k.triangleSegmentIdx-j.triangleSegmentIdx);let p=0,y=0,b=0;for(const k of l){if(k.triangleSegmentIdx!==p)break;b++}const S=l.length;for(;y!==l.length;){p=l[y].triangleSegmentIdx;let k=0,j=y,O=y;for(let z=j;z0&&this.triangleSubSegments.push({segment:K,min:U,max:q}),j=O;for(let Z=j;Z[J[0]*(1-ae[0])+ne[0]*ae[0],J[1]*(1-ae[1])+ne[1]*ae[1]],K=[],Z=[];for(const J of this.triangleSubSegments){K[0]=J.min.x/ar,K[1]=J.min.y/ar,Z[0]=J.max.x/ar,Z[1]=J.max.y/ar;const ne=q(z,U,K),ae=q(z,U,Z);if(new si([ne[0],ne[1],b],[ae[0],ae[1],S]).intersectsPrecise(p)===0){O&&(y.segments.push(O),O=void 0);continue}const he=J.segment;O&&O.vertexOffset!==he.vertexOffset&&(y.segments.push(O),O=void 0),O?(O.vertexLength+=he.vertexLength,O.primitiveLength+=he.primitiveLength):O={vertexOffset:he.vertexOffset,primitiveLength:he.primitiveLength,vertexLength:he.vertexLength,primitiveOffset:he.primitiveOffset,sortKey:void 0,vaos:{}}}return O&&y.segments.push(O),y}encodeCentroid(l,u){const p=l.centroid(),y=u.span(),b=Math.min(7,Math.round(y.x*this.tileToMeter/10)),S=Math.min(6,Math.round(y.y*this.tileToMeter/10));return new Mt(fe(p.x,1,8191)<<3|b,fe(p.y,1,8191)<<3|S)}encodeBorderCentroid(l){if(!l.borders)return new Mt(0,0);const u=l.borders,p=Number.MAX_VALUE;if(u[0][0]!==p||u[1][0]!==p){const y=u[0][0]!==p?0:1;return new Mt(6|(u[0][0]!==p?0:65528),(u[y][0]+u[y][1])/2<<3|6)}{const y=u[2][0]!==p?2:3;return new Mt((u[y][0]+u[y][1])/2<<3|6,6|(u[2][0]!==p?0:65528))}}showCentroid(l){const u=this.centroidData[l.centroidDataIndex];if(u.flags&=Vp,u.groupCentroidPos.x!==0||u.groupCentroidPos.y!==0){const p=u.span(),y=Math.min(7,Math.round(p.x*this.tileToMeter/10)),b=Math.min(6,Math.round(p.y*this.tileToMeter/10));u.centroidXY=new Mt(fe(u.groupCentroidPos.x,1,8191)<<3|y,fe(u.groupCentroidPos.y,1,8191)<<3|b)}else u.centroidXY=new Mt(0,0);this.writeCentroidToBuffer(u)}writeCentroidToBuffer(l){this.groundEffect.updateHiddenByLandmark(l);const u=l.vertexArrayOffset,p=l.vertexCount+l.vertexArrayOffset,y=-1073741824&l.flags?$I:l.centroidXY,b=this.centroidVertexArray.geta_centroid_pos0(u);if(this.centroidVertexArray.geta_centroid_pos1(u)!==y.y||b!==y.x){for(let S=u;Sj.max.x||j.min.x>S.max.x||S.min.y>j.max.y||j.min.y>S.max.y||S.footprint.buildingIds.has(j.buildingId)&&(j.flags|=S.clipMask!==zI.None?-1073741824:Vp);else for(const j of this.centroidData)if(!(j.flags&Vp||j.flags&UI||S.min.x>j.max.x||j.min.x>S.max.x||S.min.y>j.max.y||j.min.y>S.max.y))for(let O=0;Ou!=K>u&&l<(this.footprintVertices.int16[2*(z+S.vertexOffset)+0]-U)*(u-q)/(K-q)+U&&(y=!y)}k=j}}return y}getHeightAtTileCoord(l,u){let p=Number.NEGATIVE_INFINITY,y=!0;const b=4*(l+ar)*ar+(u+ar);if(this.partLookup.hasOwnProperty(b)){const S=this.partLookup[b];return S?{height:S.height,hidden:!!(S.flags&Vp)}:void 0}for(const S of this.centroidData)l>S.max.x||S.min.x>l||u>S.max.y||S.min.y>u||S.height<=p||this.footprintContainsPoint(l,u,S)&&(p=S.height,this.partLookup[b]=S,y=!!(S.flags&Vp));if(p!==Number.NEGATIVE_INFINITY)return{height:p,hidden:y};this.partLookup[b]=void 0}}function HK(h,l){const u=h.add(l)._unit();return h.x*u.x+h.y*u.y}function ike(h,l,u,p){const y=l.sub(h)._perp()._unit(),b=u.sub(l)._perp()._unit();return WK(h,l,u,HK(y,b),p)}function WK(h,l,u,p,y){const b=Math.sqrt(1-p*p);return Math.min(h.dist(l)/3,l.dist(u)/3,y*b/p)}function b5(h,l,u){return h.xu[1].x&&l.x>u[1].x||h.yu[1].y&&l.y>u[1].y}function KK(h,l){return h.xl[1].x||h.yl[1].y}function ske(h){return h.every(l=>l.x<=0)||h.every(l=>l.x>=ar)||h.every(l=>l.y<=0)||h.every(l=>l.y>=ar)}function YK(h,l,u){if(h.x<0||h.x>=ar||l.x<0||l.x>=ar||u.x<0||u.x>=ar)return!1;const p=u.sub(l),y=p.perp(),b=h.sub(l);return(p.x*b.x+p.y*b.y)/Math.sqrt((p.x*p.x+p.y*p.y)*(b.x*b.x+b.y*b.y))>-.866&&y.x*b.x+y.y*b.y<0}function ZK(h,l,u){const p=l?2|h:-3&h;return u?1|p:-2&p}function XK(){const h=Math.PI/32,l=Math.tan(h),u=qe;return u*Math.sqrt(1+2*l*l)-u}function QK(h,l,u){const p=1<{for(const $e of Ce)Z.push({polygon:$e,bounds:He})},ne=Math.ceil(Math.log2(z)),ae=Math.ceil(Math.log2(U)),he=ne-ae,ce=[];for(let Ce=0;Ce0?0:1);for(let Ce=0;CeHe+1?Ee.push({polygons:kt,bounds:Ct,depth:He+1}):J(kt,Ct)}if(It.length){const Ct=[new Mt($e===0?bt:Ge.x,$e===1?bt:Ge.y),Ue];ce.length>He+1?Ee.push({polygons:It,bounds:Ct,depth:He+1}):J(It,Ct)}}return Z}(h,l,Math.ceil((b-y)/11.25),Math.ceil((S-k)/11.25),1,(j,O,z)=>{if(j===0)return .5*(O+z);{const U=gt((u.y+O/ar)/p);return(Ft(.5*(gt((u.y+z/ar)/p)+U))*p-u.y)*ar}})}function ake(h,l,u,p,y,b){const S=Math.pow(2,p.z-y.z);for(let k=0;k=j[S]&&(k=l,j=h),k[S]y&&rY(k,j,S,y),k[S]b&&rY(j,k,S,b)}}function GI(h,l,u,p,y,b){const S=[];for(let k=0;k=p&&Z.x>=p||(K.x>=p?K=new Mt(p,K.y+(p-K.x)/(Z.x-K.x)*(Z.y-K.y))._round():Z.x>=p&&(Z=new Mt(p,K.y+(p-K.x)/(Z.x-K.x)*(Z.y-K.y))._round()),K.y>=y&&Z.y>=y||(K.y>=y?K=new Mt(K.x+(y-K.y)/(Z.y-K.y)*(Z.x-K.x),y)._round():Z.y>=y&&(Z=new Mt(K.x+(y-K.y)/(Z.y-K.y)*(Z.x-K.x),y)._round()),O&&K.equals(O[O.length-1])||(O=[K],S.push(O),b&&b.push({progress:{min:ne+iY(ae,he,K)*J,max:1},parentIndex:k,prevPoint:ae,nextPoint:he})),O.push(Z),b&&(b[b.length-1].progress.max=ne+iY(ae,he,Z)*J,b[b.length-1].nextPoint=he)))))}if(b&&U>0)for(let q=z;qO.t-z.t);let S=0,k=0,j=[];for(p.push(j);S!==h.length;){if(k===b.length){for(;S!==h.length;)j.length!==0&&j[j.length-1].equals(h[S])||j.push(h[S]),S++;break}b[k].t<=S?(j.length!==0&&j[j.length-1].equals(b[k].point)||j.push(b[k].point),Math.trunc(b[k].t),k++):(j.length!==0&&j[j.length-1].equals(h[S])||j.push(h[S]),S++)}}function iY(h,l,u){return h.x!==l.x?(u.x-h.x)/(l.x-h.x):h.y!==l.y?(u.y-h.y)/(l.y-h.y):0}function IE(h,l){return h.x*l.x+h.y*l.y}function sY(h,l){if(h.length===1){let u=0;const p=l[u++];let y;for(;!y||p.equals(y);)if(y=l[u++],!y)return 1/0;for(;u{bt[0]=kt,bt[1]=It,bt[2]=Ct,bt[3]=1},yt=XK();K>0&&(K+=yt),Z+=yt;for(const bt of q){const kt=[],It=[];for(const Ct of bt){const Bt=Ct.x+J.x,pt=Ct.y+J.y,jt=U.projection.projectTilePoint(Bt,pt,Ee),Lt=U.projection.upVector(Ee,Ct.x,Ct.y);let $t=K,Wt=Z;if(ae){const xr=lY(Bt,pt,K,Z,ae,he,ce,ye);$t+=xr.base,Wt+=xr.top}K!==0?Ve(Ge,jt.x+Lt[0]*$e*$t,jt.y+Lt[1]*$e*$t,jt.z+Lt[2]*$e*$t):Ve(Ge,jt.x,jt.y,jt.z),Ve(Ue,jt.x+Lt[0]*$e*Wt,jt.y+Lt[1]*$e*Wt,jt.z+Lt[2]*$e*Wt),or(Ge,Ge,ne),or(Ue,Ue,ne),kt.push(new p_(Ge[0],Ge[1],Ge[2])),It.push(new p_(Ue[0],Ue[1],Ue[2]))}Ce.push(kt),He.push(It)}return[Ce,He]}(h,l,u,p,y,b,S,k,j,O,z):S?function(U,q,K,Z,J,ne,ae,he,ce){const ye=[],Ee=[],Ce=[0,0,0,1];for(const He of U){const $e=[],Ge=[];for(const Ue of He){const Ve=Ue.x+Z.x,yt=Ue.y+Z.y,bt=lY(Ve,yt,q,K,ne,ae,he,ce);Ce[0]=Ve,Ce[1]=yt,Ce[2]=bt.base,Ce[3]=1,hr(Ce,Ce,J),Ce[3]=Math.max(Ce[3],1e-5);const kt=new p_(Ce[0]/Ce[3],Ce[1]/Ce[3],Ce[2]/Ce[3]);Ce[0]=Ve,Ce[1]=yt,Ce[2]=bt.top,Ce[3]=1,hr(Ce,Ce,J),Ce[3]=Math.max(Ce[3],1e-5);const It=new p_(Ce[0]/Ce[3],Ce[1]/Ce[3],Ce[2]/Ce[3]);$e.push(kt),Ge.push(It)}ye.push($e),Ee.push(Ge)}return[ye,Ee]}(l,u,p,y,b,S,k,j,O):function(U,q,K,Z,J){const ne=[],ae=[],he=J[8]*q,ce=J[9]*q,ye=J[10]*q,Ee=J[11]*q,Ce=J[8]*K,He=J[9]*K,$e=J[10]*K,Ge=J[11]*K;for(const Ue of U){const Ve=[],yt=[];for(const bt of Ue){const kt=bt.x+Z.x,It=bt.y+Z.y,Ct=J[0]*kt+J[4]*It+J[12],Bt=J[1]*kt+J[5]*It+J[13],pt=J[2]*kt+J[6]*It+J[14],jt=J[3]*kt+J[7]*It+J[15],Lt=Ct+he,$t=Bt+ce,Wt=pt+ye,xr=Math.max(jt+Ee,1e-5),ir=Ct+Ce,nr=Bt+He,Kt=pt+$e,mr=Math.max(jt+Ge,1e-5);Ve.push(new p_(Lt/xr,$t/xr,Wt/xr)),yt.push(new p_(ir/mr,nr/mr,Kt/mr))}ne.push(Ve),ae.push(yt)}return[ne,ae]}(l,u,p,y,b)}function lY(h,l,u,p,y,b,S,k){const j=S*y.getElevationAt(h,l,!0,!0),O=b[0]!==0,z=O?b[1]===0?S*(b[0]/7-450):S*function(U,q,K){const Z=Math.floor(q[0]/8),J=Math.floor(q[1]/8),ne=10*(q[0]-8*Z),ae=10*(q[1]-8*J),he=U.getElevationAt(Z,J,!0,!0),ce=U.getMeterToDEM(K),ye=Math.floor(.5*(ne*ce-1)),Ee=Math.floor(.5*(ae*ce-1)),Ce=U.tileCoordToPixel(Z,J),He=2*ye+1,$e=2*Ee+1,Ge=function(It,Ct,Bt,pt,jt){return[It.getElevationAtPixel(Ct,Bt,!0),It.getElevationAtPixel(Ct+jt,Bt,!0),It.getElevationAtPixel(Ct,Bt+jt,!0),It.getElevationAtPixel(Ct+pt,Bt+jt,!0)]}(U,Ce.x-ye,Ce.y-Ee,He,$e),Ue=Math.abs(Ge[0]-Ge[1]),Ve=Math.abs(Ge[2]-Ge[3]),yt=Math.abs(Ge[0]-Ge[2])+Math.abs(Ge[1]-Ge[3]),bt=Math.min(.25,.5*ce*(Ue+Ve)/He),kt=Math.min(.25,.5*ce*yt/$e);return he+Math.max(bt*ne,kt*ae)}(y,b,k):j;return{base:j+(u===0?-1:u),top:O?Math.max(z+p,j+u+2):j+p}}const w5=4096;class lke{constructor(l){this.module=l,this.memoryStack=this.module.malloc(w5),this.memoryStackNextFree=this.memoryStack}createIntArray(l){const u=this.memoryStackNextFree;return this.memoryStackNextFree+=l.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>w5?-1:(new Int32Array(this.module.heap32.buffer,u,l.length).set(l),u)}createFloatArray(l){const u=this.memoryStackNextFree;return this.memoryStackNextFree+=l.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>w5?-1:(new Float32Array(this.module.heapF32.buffer,u,l.length).set(l),u)}readStringBuffer(l){let u="";for(;this.module.heapU8[l]!==0;)u+=String.fromCharCode(this.module.heapU8[l]),++l;return u}setStyle(l){const u=l.normalScale;this.module.setStyle(u[0],u[1],u[2],l.tileToMeters)}setAOOptions(l,u){this.module.setAOOptions(l?1:0,u)}setMetricOptions(l,u){this.module.setMetricOptions(l?1:0,u)}setStructuralOptions(l){this.module.setStructuralOptions(l?1:0)}setFacadeOptions(l,u){this.module.setFacadeOptions(l,u?1:0)}setFauxFacadeOptions(l,u,p){this.module.setFauxFacadeOptions(l?1:0,u?1:0,p)}setFacadeClassifierOptions(l){this.module.setFacadeClassifierOptions(l)}generateMesh(l,u){this.memoryStackNextFree=this.memoryStack;for(const k of l){const j=this.createIntArray(k.ringIndices),O=this.createFloatArray(k.coordinates);if(j===-1||O===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(k.id,k.sourceId,k.minHeight,k.height,k.roofType,O,j,k.ringIndices.length-1)}for(const k of u){let j;j=k.entrances?JSON.parse(k.entrances):[];const O=this.createFloatArray(j),z=this.createFloatArray(k.coordinates);if(O===-1||z===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(k.sourceId,k.crossPerc,k.distanceToRoad,O,j.length,z,k.coordinates.length)}if(!this.module.generateMesh()){const k=this.module.getLastError();return this.readStringBuffer(k)}const p=this.module.getMeshCount(),y=new Array(p);for(let k=0;k>2)-3,ne=K[Z++]>>2;if(Z++,y.json=JSON.parse(xY.decode(K.subarray(Z,Z+ne))),Z+=ne,Z>>0,Math.ceil(1.2*ye)),Ce=Math.ceil((Ee-ye)/65536);try{return J.grow(Ce),ne(),!0}catch{return!1}},b:ae}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(K,he):K.then(ce=>ce.arrayBuffer()).then(ce=>WebAssembly.instantiate(ce,he))).then(ce=>{const{Rb:ye,Qb:Ee,P:Ce,T:He,X:$e,Ja:Ge,La:Ue,Qa:Ve,Va:yt,Wa:bt,eb:kt,jb:It,f:Ct,e:Bt,yb:pt,zb:jt,Ab:Lt,Bb:$t,Db:Wt,Gb:xr}=ce.instance.exports;J=Bt;const ir=(()=>{let nr=0,Kt=0,mr=0,kr=0;return zr=>{mr&&(ye(kr),ye(nr),Kt+=mr,mr=nr=0),nr||(Kt+=128,nr=Ee(Kt));const Rr=zr.length+7&-8;let ln=nr;Rr>=Kt&&(mr=Rr,ln=kr=Ee(Rr));for(let zn=0;zn{yh=K,PE=void 0}))}()),q&&z.push(function(){if(S5)return;const K=function(Z){let J;const ne=WebAssembly.instantiateStreaming(Z,{}).then(ce=>{J=ce.instance,J.exports.__wasm_call_ctors()}),ae={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},he={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:ne,supported:!0,decodeGltfBuffer(ce,ye,Ee,Ce,He,$e){(function(Ge,Ue,Ve,yt,bt,kt,It){const Ct=Ge.exports.sbrk,Bt=yt+3&-4,pt=Ct(Bt*bt),jt=Ct(kt.length),Lt=new Uint8Array(Ge.exports.memory.buffer);Lt.set(kt,jt);const $t=Ue(pt,yt,bt,jt,kt.length);if($t===0&&It&&It(pt,Bt,bt),Ve.set(Lt.subarray(pt,pt+yt*bt)),Ct(pt-Ct(0)),$t!==0)throw new Error(`Malformed buffer data: ${$t}`)})(J,J.exports[he[He]],ce,ye,Ee,Ce,J.exports[ae[$e]])}}}(fetch(yo()));return K.ready.then(()=>{S5=K})}()),S)for(let K=0;K{const k=Zm(p,(j,O)=>{j?S(j):b(O)});y&&y.addEventListener("abort",()=>{k.cancel(),S(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:h,type:"arrayBuffer"},l);return bY(u,0,h,l)}function E5(h){switch(h){case WebGL2RenderingContext.RGBA8:case WebGL2RenderingContext.RGBA16F:return WebGL2RenderingContext.RGBA;case WebGL2RenderingContext.DEPTH_COMPONENT16:return WebGL2RenderingContext.DEPTH_COMPONENT;case WebGL2RenderingContext.DEPTH24_STENCIL8:return WebGL2RenderingContext.DEPTH_STENCIL;case WebGL2RenderingContext.R8:case WebGL2RenderingContext.R32F:return WebGL2RenderingContext.RED}}function A5(h){switch(h){case WebGL2RenderingContext.RGBA8:return WebGL2RenderingContext.UNSIGNED_BYTE;case WebGL2RenderingContext.RGBA16F:return WebGL2RenderingContext.HALF_FLOAT;case WebGL2RenderingContext.DEPTH_COMPONENT16:return WebGL2RenderingContext.UNSIGNED_SHORT;case WebGL2RenderingContext.DEPTH24_STENCIL8:return WebGL2RenderingContext.UNSIGNED_INT_24_8;case WebGL2RenderingContext.R8:return WebGL2RenderingContext.UNSIGNED_BYTE;case WebGL2RenderingContext.R32F:return WebGL2RenderingContext.FLOAT}}class Sf{constructor(l,u,p,y){this.context=l,this.format=p,this.useMipmap=y&&y.useMipmap,this.texture=l.gl.createTexture(),this.update(u,{premultiply:y&&y.premultiply})}update(l,u){const p=l&&l instanceof HTMLVideoElement&&l.width===0?l.videoWidth:l.width,y=l&&l instanceof HTMLVideoElement&&l.height===0?l.videoHeight:l.height,{context:b}=this,{gl:S}=b,{x:k,y:j}=u&&u.position?u.position:{x:0,y:0},O=k+p,z=j+y;this.size&&(this.size[0]!==O||this.size[1]!==z)&&(!u||u.recreateWhenResize===void 0||u.recreateWhenResize)&&(S.bindTexture(S.TEXTURE_2D,null),S.deleteTexture(this.texture),this.texture=S.createTexture(),this.size=null),S.bindTexture(S.TEXTURE_2D,this.texture),b.pixelStoreUnpackFlipY.set(!1),b.pixelStoreUnpack.set(1),b.pixelStoreUnpackPremultiplyAlpha.set(this.format===S.RGBA8&&(!u||u.premultiply!==!1));const U=l instanceof HTMLImageElement||l instanceof HTMLCanvasElement||l instanceof HTMLVideoElement||l instanceof ImageData||ImageBitmap&&l instanceof ImageBitmap;if(!this.size&&O>0&&z>0){const q=this.useMipmap?Math.floor(Math.log2(Math.max(O,z)))+1:1;S.texStorage2D(S.TEXTURE_2D,q,this.format,O,z),this.size=[O,z]}this.size&&(U?S.texSubImage2D(S.TEXTURE_2D,0,k,j,E5(this.format),A5(this.format),l):"data"in l&&l.data&&S.texSubImage2D(S.TEXTURE_2D,0,k,j,p,y,E5(this.format),A5(this.format),l.data)),this.useMipmap&&S.generateMipmap(S.TEXTURE_2D)}bind(l,u,p=!1){const{context:y}=this,{gl:b}=y;b.bindTexture(b.TEXTURE_2D,this.texture),l!==this.minFilter&&(b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,l),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,this.useMipmap&&!p?l===b.NEAREST?b.NEAREST_MIPMAP_NEAREST:b.LINEAR_MIPMAP_LINEAR:l),this.minFilter=l),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(l,u,p,y,b){const{context:S}=this,{gl:k}=S;k.bindTexture(k.TEXTURE_2D,this.texture),u!==this.magFilter&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_MAG_FILTER,u),this.magFilter=u),l!==this.minFilter&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_MIN_FILTER,this.useMipmap?l===k.NEAREST?k.NEAREST_MIPMAP_NEAREST:k.LINEAR_MIPMAP_LINEAR:l),this.minFilter=l),p!==this.wrapS&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_WRAP_S,p),this.wrapS=p),y!==this.wrapT&&(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_WRAP_T,y),this.wrapT=y),b!==this.compareMode&&(b?(k.texParameteri(k.TEXTURE_2D,k.TEXTURE_COMPARE_MODE,k.COMPARE_REF_TO_TEXTURE),k.texParameteri(k.TEXTURE_2D,k.TEXTURE_COMPARE_FUNC,b)):k.texParameteri(k.TEXTURE_2D,k.TEXTURE_COMPARE_MODE,k.NONE),this.compareMode=b)}destroy(){const{gl:l}=this.context;l.deleteTexture(this.texture),this.texture=null}}class RE{constructor(l,u){this.context=l,this.texture=u}bind(l,u){const{context:p}=this,{gl:y}=p;y.bindTexture(y.TEXTURE_2D,this.texture),l!==this.minFilter&&(y.texParameteri(y.TEXTURE_2D,y.TEXTURE_MAG_FILTER,l),y.texParameteri(y.TEXTURE_2D,y.TEXTURE_MIN_FILTER,l),this.minFilter=l),u!==this.wrapS&&(y.texParameteri(y.TEXTURE_2D,y.TEXTURE_WRAP_S,u),y.texParameteri(y.TEXTURE_2D,y.TEXTURE_WRAP_T,u),this.wrapS=u)}}const mke=Pn([{name:"a_pos_3f",components:3,type:"Float32"}]),gke=Pn([{name:"a_color_3f",components:3,type:"Float32"}]),yke=Pn([{name:"a_color_4f",components:4,type:"Float32"}]),xke=Pn([{name:"a_uv_2f",components:2,type:"Float32"}]),_ke=Pn([{name:"a_normal_3f",components:3,type:"Float32"}]),vke=Pn([{name:"a_normal_matrix0",components:4,type:"Float32"},{name:"a_normal_matrix1",components:4,type:"Float32"},{name:"a_normal_matrix2",components:4,type:"Float32"},{name:"a_normal_matrix3",components:4,type:"Float32"}]),bke=Pn([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function SY(h,l){const u=YI(h.projection,h.zoom,h.width,h.height),p=function(b,S,k,j,O){const z=new Qe(k.lng-180*kg,k.lat),U=new Qe(k.lng+180*kg,k.lat),q=b.project(z.lng,z.lat),K=b.project(U.lng,U.lat),Z=-Math.atan2(K.y-q.y,K.x-q.x),J=Ar.fromLngLat(k);J.y=fe(J.y,-1+kg,1-kg);const ne=J.toLngLat(),ae=b.project(ne.lng,ne.lat),he=Ar.fromLngLat(ne);he.x+=kg;const ce=he.toLngLat(),ye=b.project(ce.lng,ce.lat),Ee=EY(ye.x-ae.x,ye.y-ae.y,Z),Ce=Ar.fromLngLat(ne);Ce.y+=kg;const He=Ce.toLngLat(),$e=b.project(He.lng,He.lat),Ge=EY($e.x-ae.x,$e.y-ae.y,Z),Ue=Math.abs(Ee.x)/Math.abs(Ge.y),Ve=R([]);X(Ve,Ve,-Z*(1-(O?0:j)));const yt=R([]);return V(yt,yt,[1,1-(1-Ue)*j,1]),yt[4]=-Ge.x/Ge.y*j,X(yt,yt,Z),M(yt,Ve,yt),yt}(h.projection,0,h.center,u,l),y=TY(h);return V(p,p,[y,y,1]),p}function TY(h){const l=h.projection,u=YI(h.projection,h.zoom,h.width,h.height),p=k5(l,h.center),y=k5(l,Qe.convert(l.center));return Math.pow(2,p*u+(1-u)*y)}function YI(h,l,u,p,y=1/0){const b=h.range;if(!b)return 0;const S=Math.min(y,Math.max(u,p)),k=Math.log2(S/1024);return Me(b[0]+k,b[1]+k,l)}const kg=1/4e4;function k5(h,l){const u=fe(l.lat,-85.051129,St),p=new Qe(l.lng-180*kg,u),y=new Qe(l.lng+180*kg,u),b=h.project(p.lng,u),S=h.project(y.lng,u),k=Ar.fromLngLat(p),j=Ar.fromLngLat(y),O=S.x-b.x,z=S.y-b.y,U=j.x-k.x,q=j.y-k.y,K=Math.sqrt((U*U+q*q)/(O*O+z*z));return Math.log2(K)}function EY(h,l,u){const p=Math.cos(u),y=Math.sin(u);return{x:h*p-l*y,y:h*y+l*p}}function AY(h,l,u){R(h),X(h,h,Kn(l[2])),G(h,h,Kn(l[0])),W(h,h,Kn(l[1])),V(h,h,u),M(h,h,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function ZI(h,l,u,p,y,b,S,k){const j=[u[0]-l[0],u[1]-l[1],0],O=[p[0]-l[0],p[1]-l[1],0];if(Oe(j)<1e-12||Oe(O)<1e-12)return Pr(h);const z=er([],j,O);mt(z,z),Ne(O,p,l),j[2]=(b-y)*k,O[2]=(S-y)*k;const U=j;return er(U,j,O),mt(U,U),ia(h,z,U)}function XI(h,l,u=!1){const p=$p(l.zoom),y=function(b,S,k){const j=S.worldSize,O=[b[12],b[13],b[14]],z=gt(O[1]/j),U=et(O[0]/j),q=R([]),K=ot(1,z)*j,Z=ot(1,0)*j*Gt(z,S.zoom),J=1/Q3(j);let ne=Z*J;if(k){const ye=YI(S.projection,S.zoom,S.width,S.height,1024);ne=J*S.projection.pixelSpaceConversion(S.center.lat,j,ye)}const ae=Fe(z,U);ge(ae,ae,We([],mt([],ae),K*ne*O[2]));const he=function(ye){const Ee=[ye[0],ye[1],ye[2]];let Ce=[0,1,0];const He=er([],Ce,Ee);return er(Ce,Ee,He),_t(Ce)===0&&(Ce=[0,1,0],er(He,Ee,Ce)),mt(He,He),mt(Ce,Ce),mt(Ee,Ee),[He[0],He[1],He[2],0,Ce[0],Ce[1],Ce[2],0,Ee[0],Ee[1],Ee[2],0,ye[0],ye[1],ye[2],1]}(ae);V(q,q,[ne,ne,ne*K]),B(q,q,[-O[0],-O[1],-O[2]]);const ce=M([],S.globeMatrix,he);return M(ce,ce,q),M(ce,ce,b),ce}(h,l,u);if(p>0){const b=function(S,k){const j=k.worldSize,O=ot(1,0)*j*Gt(k.center.lat,k.zoom)/Q3(j),z=ot(1,k.center.lat)*j,U=R([]);W(U,U,Kn(k.center.lng)),G(U,U,Kn(k.center.lat)),B(U,U,[0,0,Re]),V(U,U,[O,O,O*z]);const q=k.point;return B(U,U,[-q.x,-q.y,0]),M(U,U,S),M(U,k.globeMatrix,U)}(h,l);return function(S,k,j){const O=(Z,J,ne)=>{const ae=Oe(Z),he=Oe(J),ce=zp(Z,J,ne);return We(ce,ce,1/Oe(ce)*Xr(ae,he,ne))},z=O([S[0],S[1],S[2]],[k[0],k[1],k[2]],j),U=O([S[4],S[5],S[6]],[k[4],k[5],k[6]],j),q=O([S[8],S[9],S[10]],[k[8],k[9],k[10]],j),K=zp([S[12],S[13],S[14]],[k[12],k[13],k[14]],j);return[z[0],z[1],z[2],0,U[0],U[1],U[2],0,q[0],q[1],q[2],0,K[0],K[1],K[2],1]}(y,b,p)}return y}function C5(h,l,u,p){const y=si.projectAabbCorners(p,u);let b=Number.MAX_VALUE;for(let k=0;k0||ne===0&&Z[0]*J[0]+Z[1]*J[1]>=0&&Z[0]*Z[0]+Z[1]*Z[1]>J[0]*J[0]+J[1]*J[1])&&(z=K)}U=z}while(U!==O);return j.length>0&&j.push(j[0]),j}(y);if(Is(h,S))return b}const m_=64,ob={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function QI(h,l,u,p,y,b,S,k,j,O=!1){const z=u.zoom,U=u.project(p),q=Gt(p.lat,z),K=1/q;R(h),B(h,h,[U.x+S[0]*K,U.y+S[1]*K,S[2]]);let Z=1,J=1;const ne=u.worldSize;if(O){if(u.projection.name==="mercator"){let ye=0;u.elevation&&(ye=u.elevation.getAtPointOrZero(new Ar(U.x/ne,U.y/ne),0));const Ee=hr([],[U.x,U.y,ye,1],u.projMatrix)[3]/u.cameraToCenterDistance;Z=Ee,J=Ee*Gt(u.center.lat,z)}else if(u.projection.name==="globe"){const ye=XI(h,u),Ee=[0,0,0,1];hr(Ee,Ee,M([],u.projMatrix,ye));const Ce=Ee[3]/u.cameraToCenterDistance,He=$p(z),$e=u.projection.pixelsPerMeter(p.lat,ne)*Gt(p.lat,z),Ge=u.projection.pixelsPerMeter(u.center.lat,ne)*Gt(u.center.lat,z);Z=Ce/Xr($e,rr(u.center.lat),He),J=Ce*q/$e,Z*=Ge,J*=Ge}}else Z=K;V(h,h,[Z,Z,J]);const ae=[...h],he=l.orientation,ce=[];if(AY(ce,[he[0]+(y?y[0]:0),he[1]+(y?y[1]:0),he[2]+(y?y[2]:0)],b),M(h,ae,ce),k&&u.elevation){let ye=0;const Ee=[];if(j&&u.elevation){ye=function(He,$e,Ge,Ue,Ve){const yt=$e.elevation;if(!yt)return 0;const bt=si.projectAabbCorners(Ge,Ue),kt=ot(1,Ve.lat)*$e.worldSize,It=function(Kt,mr){const kr=[0,0,1],zr=[{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 Rr of zr){const ln=Kt[Rr.corners[0]],zn=Kt[Rr.corners[1]],cn=Kt[Rr.corners[2]],Un=[zn[0]-ln[0],zn[1]-ln[1],mr*(zn[2]-ln[2])],bn=er(Un,Un,[cn[0]-ln[0],cn[1]-ln[1],mr*(cn[2]-ln[2])]);mt(bn,bn),Rr.dotProductWithUp=Pt(bn,kr)}return zr.sort((Rr,ln)=>Rr.dotProductWithUp-ln.dotProductWithUp),zr[0].corners}(bt,kt),Ct=bt[It[0]],Bt=bt[It[1]],pt=bt[It[2]],jt=bt[It[3]],Lt=yt.getAtPointOrZero(new Ar(Ct[0]/$e.worldSize,Ct[1]/$e.worldSize),0),$t=yt.getAtPointOrZero(new Ar(Bt[0]/$e.worldSize,Bt[1]/$e.worldSize),0),Wt=yt.getAtPointOrZero(new Ar(pt[0]/$e.worldSize,pt[1]/$e.worldSize),0),xr=yt.getAtPointOrZero(new Ar(jt[0]/$e.worldSize,jt[1]/$e.worldSize),0),ir=(Lt+xr)/2,nr=($t+Wt)/2;return ir>nr?$t=l.gl.NEAREST_MIPMAP_NEAREST}),h.uploaded=!0,h.image=null)}function wke(h,l,u){h.indexBuffer=l.createIndexBuffer(h.indexArray,!1,!0),h.vertexBuffer=l.createVertexBuffer(h.vertexArray,mke.members,!1,!0),h.normalArray&&(h.normalBuffer=l.createVertexBuffer(h.normalArray,_ke.members,!1,!0)),h.texcoordArray&&(h.texcoordBuffer=l.createVertexBuffer(h.texcoordArray,xke.members,!1,!0)),h.colorArray&&(h.colorBuffer=l.createVertexBuffer(h.colorArray,(h.colorArray.bytesPerElement===12?gke:yke).members,!1,!0)),h.featureArray&&(h.pbrBuffer=l.createVertexBuffer(h.featureArray,bke.members,!0)),h.segments=Si.simpleSegment(0,0,h.vertexArray.length,h.indexArray.length);const p=h.material;p.pbrMetallicRoughness.baseColorTexture&&LE(p.pbrMetallicRoughness.baseColorTexture,l),p.pbrMetallicRoughness.metallicRoughnessTexture&&LE(p.pbrMetallicRoughness.metallicRoughnessTexture,l),p.normalTexture&&LE(p.normalTexture,l),p.occlusionTexture&&LE(p.occlusionTexture,l,u),p.emissionTexture&&LE(p.emissionTexture,l)}function j5(h,l,u){if(h.meshes)for(const p of h.meshes)wke(p,l,u);if(h.children)for(const p of h.children)j5(p,l,u)}function JI(h){if(h.meshes)for(const l of h.meshes)l.indexArray.destroy(),l.vertexArray.destroy(),l.colorArray&&l.colorArray.destroy(),l.normalArray&&l.normalArray.destroy(),l.texcoordArray&&l.texcoordArray.destroy(),l.featureArray&&l.featureArray.destroy();if(h.children)for(const l of h.children)JI(l)}function Ske(h){h.pbrMetallicRoughness.baseColorTexture&&h.pbrMetallicRoughness.baseColorTexture.gfxTexture&&h.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),h.pbrMetallicRoughness.metallicRoughnessTexture&&h.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&h.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),h.normalTexture&&h.normalTexture.gfxTexture&&h.normalTexture.gfxTexture.destroy(),h.emissionTexture&&h.emissionTexture.gfxTexture&&h.emissionTexture.gfxTexture.destroy(),h.occlusionTexture&&h.occlusionTexture.gfxTexture&&h.occlusionTexture.gfxTexture.destroy()}function I5(h){if(h.meshes)for(const l of h.meshes)l.vertexBuffer&&(l.vertexBuffer.destroy(),l.indexBuffer.destroy(),l.normalBuffer&&l.normalBuffer.destroy(),l.texcoordBuffer&&l.texcoordBuffer.destroy(),l.colorBuffer&&l.colorBuffer.destroy(),l.pbrBuffer&&l.pbrBuffer.destroy(),l.segments.destroy(),l.material&&Ske(l.material));if(h.footprintDebugMesh&&(h.footprintDebugMesh.vertexBuffer.destroy(),h.footprintDebugMesh.indexBuffer.destroy(),h.footprintDebugMesh.segments.destroy()),h.children)for(const l of h.children)I5(l)}function g_(h,l){const u=h.json.bufferViews[l.bufferView],p=WI[l.componentType];return new p(h.buffers[u.buffer],(l.byteOffset||0)+(u.byteOffset||0),l.count*(u.byteStride&&u.byteStride!==NE[l.type]*p.BYTES_PER_ELEMENT?u.byteStride/p.BYTES_PER_ELEMENT:NE[l.type]))}function P5(h,l,u,p){const y=WI[l.componentType],b=function(z){switch(z){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(y),S=h.json.bufferViews[l.bufferView],k=S.byteStride?S.byteStride/y.BYTES_PER_ELEMENT:NE[l.type],j=u.float32,O=j.length/u.capacity;for(let z=0,U=0;z0){for(let ne=0;ne0){b.texcoordArray=new Op;const q=l.json.accessors[y.TEXCOORD_0];b.texcoordArray.resize(q.count);const K=g_(l,q);P5(l,q,b.texcoordArray,K)}if(y._FEATURE_ID_RGBA4444!==void 0){const q=l.json.accessors[y._FEATURE_ID_RGBA4444];l.json.extensionsUsed&&l.json.extensionsUsed.includes("EXT_meshopt_compression")&&(b.featureData=g_(l,q))}y._FEATURE_RGBA4444!==void 0&&(b.featureData=new Uint32Array(g_(l,l.json.accessors[y._FEATURE_RGBA4444]).buffer));const U=h.material;return b.material=function(q,K){const{emissiveFactor:Z=[0,0,0],alphaMode:J="OPAQUE",alphaCutoff:ne=.5,normalTexture:ae,occlusionTexture:he,emissiveTexture:ce,doubleSided:ye,name:Ee}=q,{baseColorFactor:Ce=[1,1,1,1],metallicFactor:He=1,roughnessFactor:$e=1,baseColorTexture:Ge,metallicRoughnessTexture:Ue}=q.pbrMetallicRoughness||{},Ve=he?K[he.index]:void 0;if(he&&he.extensions&&he.extensions.KHR_texture_transform&&Ve){const yt=he.extensions.KHR_texture_transform;Ve.offsetScale=[yt.offset[0],yt.offset[1],yt.scale[0],yt.scale[1]]}return{name:Ee,pbrMetallicRoughness:{baseColorFactor:new Yn(...Ce),metallicFactor:He,roughnessFactor:$e,baseColorTexture:Ge?K[Ge.index]:void 0,metallicRoughnessTexture:Ue?K[Ue.index]:void 0},doubleSided:ye,emissiveFactor:new Yn(...Z),alphaMode:J,alphaCutoff:ne,normalTexture:ae?K[ae.index]:void 0,occlusionTexture:Ve,emissionTexture:ce?K[ce.index]:void 0,defined:q.defined===void 0}}(U!==void 0?l.json.materials[U]:{defined:!1},u),b}function CY(h,l,u){const{matrix:p,rotation:y,translation:b,scale:S,mesh:k,extras:j,children:O,name:z}=h,U={};if(U.name=z,U.localMatrix=p||function(q,K,Z,J){var ne=K[0],ae=K[1],he=K[2],ce=K[3],ye=ne+ne,Ee=ae+ae,Ce=he+he,He=ne*ye,$e=ne*Ee,Ge=ne*Ce,Ue=ae*Ee,Ve=ae*Ce,yt=he*Ce,bt=ce*ye,kt=ce*Ee,It=ce*Ce,Ct=J[0],Bt=J[1],pt=J[2];return q[0]=(1-(Ue+yt))*Ct,q[1]=($e+It)*Ct,q[2]=(Ge-kt)*Ct,q[3]=0,q[4]=($e-It)*Bt,q[5]=(1-(He+yt))*Bt,q[6]=(Ve+bt)*Bt,q[7]=0,q[8]=(Ge+kt)*pt,q[9]=(Ve-bt)*pt,q[10]=(1-(He+Ue))*pt,q[11]=0,q[12]=Z[0],q[13]=Z[1],q[14]=Z[2],q[15]=1,q}([],y||[0,0,0,1],b||[0,0,0],S||[1,1,1]),U.globalMatrix=N(U.localMatrix),k!==void 0){U.meshes=u[k];const q=U.anchor=[0,0];for(const K of U.meshes){const{min:Z,max:J}=K.aabb;q[0]+=Z[0]+J[0],q[1]+=Z[1]+J[1]}q[0]=Math.floor(q[0]/U.meshes.length/2),q[1]=Math.floor(q[1]/U.meshes.length/2)}if(j&&(j.id&&(U.id=j.id),j.lights&&(U.lights=function(q){if(!q.length)return[];const K=function(he){const ce=atob(he),ye=new Uint8Array(ce.length);for(let Ee=0;Ee1&&p[p.length-1].equals(p[0])&&p.pop();let y=0;for(let S=0;S0&&p.reverse();const b=rb(p.flatMap(S=>[S.x,S.y]),[]);return b.length===0?null:{vertices:p,indices:b}}function kke(h,l){const u=[],p=[];let y=0;const b=[];for(const S of h){y=u.length;const k=S.vertexArray.float32,j=S.indexArray.uint16;for(let O=0;O0&&([p[S+1],p[S+2]]=[p[S+2],p[S+1]])}return{vertices:u,indices:p}}function N5(h){const l=function(j,O){const z=[],U=WebGL2RenderingContext;if(j.json.textures)for(const q of j.json.textures){const K={magFilter:U.LINEAR,minFilter:U.NEAREST,wrapS:U.REPEAT,wrapT:U.REPEAT};q.sampler!==void 0&&Object.assign(K,j.json.samplers[q.sampler]),z.push({image:O[q.source],sampler:K,uploaded:!1})}return z}(h,h.images),u=function(j,O){const z=[];for(const U of j.json.meshes){const q=[];for(const K of U.primitives)q.push(Tke(K,j,O));z.push(q)}return z}(h,l),{scenes:p,scene:y,nodes:b}=h.json,S=p?p[y||0].nodes:[...b.keys()],k=[];for(const j of S)k.push(CY(b[j],h,u));return function(j,O,z){const U={},q=new Set;for(let K=0;K0){const K=Array.from(q.values()).sort((Z,J)=>Z-J);for(let Z=K.length-1;Z>=0;Z--)j.splice(K[Z],1)}}(k,S,h.json.nodes),k}function Cke(h){h.heightmap=new Float32Array(4096),h.heightmap.fill(-1);const l=h.vertexArray.float32,u=h.aabb.min[0]-1,p=h.aabb.min[1]-1,y=m_/(h.aabb.max[0]-u+2),b=m_/(h.aabb.max[1]-p+2);for(let S=0;Sh.heightmap[O*m_+j]&&(h.heightmap[O*m_+j]=k)}}function jY(h,l,u,p,y){u.reserve(u.length+4*h.length),p.reserve(p.length+10*h.length),y.reserve(y.length+10*h.length);let b=p.length;for(const S of h){const k=Math.min(10,Math.max(4,1.3*S.height))*l,j=[-S.normal[1],S.normal[0],0],O=Math.min(.29,.1*S.width/S.depth),z=S.width-2*S.depth*l*(O+.01),U=rt([],S.pos,j,z/2),q=rt([],S.pos,j,-z/2),K=[U[0],U[1],U[2]+S.height],Z=[q[0],q[1],q[2]+S.height],J=rt([],S.normal,j,O);We(J,J,k);const ne=rt([],S.normal,j,-O);We(ne,ne,k),ge(J,U,J),ge(ne,q,ne),U[2]+=.1,q[2]+=.1,p.emplaceBack(J[0],J[1],J[2]),p.emplaceBack(ne[0],ne[1],ne[2]),p.emplaceBack(U[0],U[1],U[2]),p.emplaceBack(q[0],q[1],q[2]),p.emplaceBack(K[0],K[1],K[2]),p.emplaceBack(Z[0],Z[1],Z[2]),p.emplaceBack(U[0],U[1],U[2]),p.emplaceBack(q[0],q[1],q[2]),p.emplaceBack(J[0],J[1],J[2]),p.emplaceBack(ne[0],ne[1],ne[2]);const ae=z/k/2;y.emplaceBack(-ae-O,-1,ae,.8),y.emplaceBack(ae+O,-1,ae,.8),y.emplaceBack(-ae,0,ae,1.3),y.emplaceBack(ae,0,ae,1.3),y.emplaceBack(ae+O,-.8,ae,.7),y.emplaceBack(ae+O,-.8,ae,.7),y.emplaceBack(0,0,ae,1.3),y.emplaceBack(0,0,ae,1.3),y.emplaceBack(ae+O,-1.2,ae,.8),y.emplaceBack(ae+O,-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 jke(h,l){const u={};u.indexArray=new _s,u.vertexArray=new lu,u.colorArray=new mh,jY(h,l,u.indexArray,u.vertexArray,u.colorArray);const p={defined:!0};p.emissiveFactor=Yn.black;const y={};return y.baseColorFactor=Yn.white,p.pbrMetallicRoughness=y,u.material=p,u.aabb=new si([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),u}const IY=Pn([{name:"a_pos_3f",components:3,type:"Float32"}]),Ike=Pn([{name:"a_normal_3",components:3,type:"Int16"}]),Pke=Pn([{name:"a_centroid_3",components:3,type:"Int16"}]),PY=Pn([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),Nke=Pn([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),Rke=Pn([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),Lke=Pn([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),Dke=Pn([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),Oke=Pn([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),NY=tn.types,eP=32767;function Mke(h,l){const u=ar+l;for(const p of h)for(const y of p)if(y.x<-l||y.x>u||y.y<-l||y.y>u)return!1;return!0}function Fke(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}`)}}class R5{constructor(){this.layoutVertexArray=new lu,this.layoutAttenuationArray=new mh,this.layoutColorArray=new cu,this.indexArray=new _s,this.indexArrayForConflation=new _s,this.segmentsBucket=new Si}}class L5{constructor(l){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Si,this.entranceBloom=new R5;const u=66560;this.layoutVertexArray=new lu,this.layoutVertexArray.reserve(u),this.layoutNormalArray=new bd,this.layoutNormalArray.reserve(u),this.layoutCentroidArray=new bd,this.layoutCentroidArray.reserve(u),this.layoutColorArray=new cu,this.layoutColorArray.reserve(u),this.layoutFloodLightDataArray=new Zv,this.layoutFloodLightDataArray.reserve(u),this.layoutAOArray=new Xv,this.layoutAOArray.reserve(u),this.indexArray=new _s,this.indexArray.reserve(66560),this.indexArrayForConflation=new _s,this.segmentsBucket=new Si,this.entranceBloom=new R5,l&&(this.layoutFacadePaintArray=new cu,this.layoutFacadeDataArray=new vg,this.layoutFacadeVerticalRangeArray=new cu)}reserve(l,u,p){this.layoutVertexArray.reserveForAdditional(l),this.layoutCentroidArray.reserveForAdditional(l),this.layoutFloodLightDataArray.reserveForAdditional(l),this.layoutNormalArray.reserveForAdditional(l),this.layoutAOArray.reserveForAdditional(l),this.layoutColorArray.reserveForAdditional(l),this.indexArray.reserveForAdditional(u),p&&(this.layoutFacadePaintArray.reserveForAdditional(l),this.layoutFacadeDataArray.reserveForAdditional(l),this.layoutFacadeVerticalRangeArray.reserveForAdditional(l))}}class RY{constructor(l){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new Op,this.footprintsIndices=new Mp,this.footprintsMin=new Mt(1/0,1/0),this.footprintsMax=new Mt(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new L5(!1),this.buildingWithFacade=new L5(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=l.zoom,this.canonical=l.canonical,this.layers=l.layers,this.layerIds=this.layers.map(u=>u.fqid),this.index=l.index,this.hasPattern=!1,this.worldview=l.worldview,this.lut=l.lut,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut}),this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.projection=l.projection,this.groundEffect=new v5(l),this.groundEffect.groundRadiusArray=new Tc,this.hasAppearances=null}updateFootprints(l,u){const p=new MI([],[],1),y={vertices:[],indices:new Uint32Array(0),grid:p,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};u.push({footprint:y,id:l})}updateAppearances(l,u,p,y){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(HI!=null||cY!=null)return null;if(ab!=null)return ab;const l=fetch(oo());return ab=function(u){let p,y,b,S,k;function j(){p=new Uint8Array(k.buffer),y=new Int16Array(k.buffer),b=new Int32Array(k.buffer),S=new Float32Array(k.buffer)}function O(){throw new Error("Unexpected BuildingGen error.")}const z=()=>{},U={a:{a:O,f:function(q){const K=p.length,Z=Math.max(q>>>0,Math.ceil(1.2*K)),J=Math.ceil((Z-K)/65536);try{return k.grow(J),j(),!0}catch{return!1}},g:O,b:z,c:z,d:z,e:z}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(u,U):u.then(q=>q.arrayBuffer()).then(q=>WebAssembly.instantiate(q,U))).then(q=>{const K=q.instance.exports;return(0,K.g)(),k=K.f,j(),new lke({setStyle:K.h,setAOOptions:K.i,setMetricOptions:K.j,setStructuralOptions:K.k,setFacadeOptions:K.l,setFauxFacadeOptions:K.m,setFacadeClassifierOptions:K.n,addFeature:K.o,addFacade:K.p,generateMesh:K.q,getLastError:K.r,getOuterRingLength:K.s,getMeshCount:K.t,getPositionsPtr:K.u,getPositionsLength:K.v,getNormalsPtr:K.w,getNormalsLength:K.x,getAOPtr:K.y,getAOLength:K.z,getUVPtr:K.A,getUVLength:K.B,getFauxFacadePtr:K.C,getFauxFacadeLength:K.D,getIndicesPtr:K.E,getIndicesLength:K.F,getBuildingPart:K.G,getRingCount:K.H,getRingPtr:K.I,getRingLength:K.J,malloc:K.K,free:K.L,heapU8:p,heap16:y,heap32:b,heapF32:S})})}(l).then(u=>(ab=null,HI=u,HI)).catch(u=>{Br("Could not load building-gen"),ab=null,cY=u instanceof Error?u:new Error("Unknown error")}),ab}()}populate(l,u,p,y){const b=cke();if(!b)return;const S=Dt(p);this.tileToMeter=S,this.brightness=u.brightness,b.setStyle({normalScale:[1,-1,S],tileToMeters:S}),b.setAOOptions(!1,.3),b.setMetricOptions(!1,16),b.setStructuralOptions(!0),b.setFacadeClassifierOptions(3);const k=new Map,j=new Map;let O=0;for(const{feature:ae}of l){if(NY[ae.type]!=="LineString"){k.set(ae.id,ae.properties.source_id);continue}const he=this.layers[0]._featureFilter.needGeometry;if(he&&!this.layers[0]._featureFilter.filter(new ti(this.zoom),ae,p))continue;const ce=vn(ae,he);if(!he&&!this.layers[0]._featureFilter.filter(new ti(this.zoom),ce,p))continue;const ye=he?ce.geometry:$r(ae,p,y),Ee=[];for(const Ge of ye)for(const Ue of Ge)Ee.push(Ue.x),Ee.push(Ue.y);const Ce={coordinates:Ee,crossPerc:ae.properties.cross_perc,distanceToRoad:ae.properties.distance_to_road,entrances:ae.properties.entrances,sourceId:0},He=ae.properties.source_id;let $e=j.get(He);$e||($e=[],j.set(He,$e)),$e.push(Ce),++O}this.maxHeight=0;const z=new Array,U=new Set,q=ae=>{ae!=null&&U.add(ae)},K=(ae,he)=>{ae!=null&&z.push({buildingId:ae,footprintIndex:he})},Z=64*(l.length-O),J=Z/2;this.buildingWithFacade.reserve(Z,J,!0),this.buildingWithoutFacade.reserve(2*Z,2*J,!1),this.footprintsIndices.reserve(16*(l.length-O)),this.footprintsVertices.reserve(8*(l.length-O));for(const{feature:ae,id:he,index:ce,sourceLayerIndex:ye}of l){if(NY[ae.type]==="LineString")continue;const Ee=this.layers[0]._featureFilter.needGeometry;if(Ee&&!this.layers[0]._featureFilter.filter(new ti(this.zoom),ae,p))continue;let Ce=null;if(ae.properties&&ae.properties.hasOwnProperty("building_id")&&(Ce=Number(ae.properties.building_id),U.has(Ce)))continue;const He=vn(ae,Ee);if(!Ee&&!this.layers[0]._featureFilter.filter(new ti(this.zoom),He,p))continue;const $e=Ee?He.geometry:$r(ae,p,y),Ge=SE($e,500);let Ue=!1;for(const Cn of Ge)if(Cn.length!==1){Ue=!0;break}if(Ue){q(Ce);continue}if(!Mke($e,163)){q(Ce);continue}const Ve=this.layers[0],yt=Fke(Ve.layout.get("building-roof-shape").evaluate(ae,{},p)),bt=Ve.layout.get("building-base").evaluate(ae,{},p),kt=Ve.layout.get("building-height").evaluate(ae,{},p),It=Ve.layout.get("building-flood-light-ground-radius").evaluate(ae,{},p),Ct=Ve.paint.get("building-ambient-occlusion-intensity"),Bt=It/this.tileToMeter;ae.properties["building-part"]="roof";const pt=Ve.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),jt=Ve.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);ae.properties["building-part"]="wall";const Lt=Ve.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),$t=Ve.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);ae.properties["building-part"]="window";const Wt=Ve.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),xr=Ve.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);ae.properties["building-part"]="door";const ir=Ve.paint.get("building-color").evaluate(ae,{},this.canonical).toPremultipliedRenderColor(this.lut),nr=Ve.paint.get("building-emissive-strength").evaluate(ae,{},this.canonical);let Kt=Ve.layout.get("building-flood-light-wall-radius").evaluate(ae,{},p);Kt=fe(Kt,0,2048);const mr=Kt/2048*eP,kr=k.get(he),zr=j.get(kr)||[],Rr=zr.length!==0&&Ve.layout.get("building-facade").evaluate(ae,{},p);b.setFacadeOptions(4,!0),b.setFauxFacadeOptions(Rr,!1,1);let ln=0,zn=0,cn=0,Un=0,bn=0,fs=0,ri=0,Gn=0,Ai=0,os=0,Ra=0;if(Rr){let Cn=Math.round(Ve.layout.get("building-facade-floors").evaluate(ae,{},p));if(bt===0){Cn=Math.max(1,Cn-(zr.length>0?1:0));let ws=4;if(kt>100){const ba=[10,13,15];ws=ba[ae.id?ae.id%ba.length:0]}else kt<=10&&(ws=3);b.setFacadeOptions(ws,!0),bn=(kt<15?1.3:1.61803)*ws/S}else bn=bt/S;fs=kt/S,bn=Math.min(bn,fs),cn=Ve.layout.get("building-facade-unit-width").evaluate(ae,{},p)/S,Un=(fs-bn)/Cn,b.setFauxFacadeOptions(!0,!0,cn);const Wa=Ve.layout.get("building-facade-window").evaluate(ae,{},p);ln=Wa[0],zn=Wa[1],ri=Math.floor(65535*Math.min(1,bn/ar)),Gn=Math.floor(65535*Math.min(1,fs/ar)),Ai=Math.floor(255*ln)<<8|Math.floor(255*zn),os=Math.floor(65535*Math.min(1,cn/ar)),Ra=Math.floor(65535*Math.min(1,Un/ar))}const ls=Array(Ge.length),vs={x:1/0,y:1/0},qs={x:-1/0,y:-1/0},bs={x:0,y:0};let vo=0;for(let Cn=0;Cn0){const ws=[],ba=Array(Wa.length+1);ba[0]=0;for(let $u=0;$uar||vs.y<0||qs.y>ar)&&this.featuresOnBorder.push({featureId:ae.id,footprintIndex:this.footprints.length});{const Cn=rb(Wp,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+Cn.length),this.footprintsIndices.uint16.set(Cn,vb),this.buildingIds.add(Ce??ae.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,Bu.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,Bu.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,zu.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,zu.y);const Wa={footprintVertexOffset:Hp,footprintVertexLength:this.footprintsVertices.length-Hp,footprintIndexOffset:vb,footprintIndexLength:this.footprintsIndices.length-vb,min:Bu,max:zu,hiddenFlags:0,indicesOffset:jP,indicesLength:T4,bloomIndicesOffset:bo,bloomIndicesLength:ps,groundEffectVertexOffset:S_,groundEffectVertexLength:bb,hasFauxFacade:Rr,height:_b,promoteId:he,feature:He,parts:Ga,buildingBloom:xl},ws=this.footprints.length;ae.id!==void 0&&this.featureFootprintLookup.set(ae.id,ws),K(Ce,ws),this.footprints.push(Wa)}this.programConfigurations.populatePaintArrays(Tn.layoutVertexArray.length,ae,ce,{},u.availableImages,p,u.brightness),this.groundEffect.addPaintPropertiesData(ae,ce,{},u.availableImages,p,u.brightness),u.featureIndex.insert(ae,$e,ce,ye,this.index,Xo)}z.forEach(({buildingId:ae,footprintIndex:he})=>{U.has(ae)&&(this.footprints[he].hiddenFlags|=4)});const ne=new Set;this.buildingIds.forEach((ae,he,ce)=>{U.has(ae)||ne.add(ae)}),this.buildingIds=ne,this.groundEffect.prepareBorderSegments()}update(l,u,p,y,b,S,k){this.programConfigurations.updatePaintArrays(l,u,b,p,y,S,k),this.groundEffect.update(l,u,b,p,y,S,k),this.evaluate(this.layers[0],l),this.colorBufferUploaded=!1}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(l){const u=p=>{p.layoutVertexBuffer=l.createVertexBuffer(p.layoutVertexArray,IY.members),p.layoutNormalBuffer=l.createVertexBuffer(p.layoutNormalArray,Ike.members),p.layoutCentroidBuffer=l.createVertexBuffer(p.layoutCentroidArray,Pke.members),p.layoutFloodLightDataBuffer=l.createVertexBuffer(p.layoutFloodLightDataArray,Oke.members),p.layoutFacadeDataArray&&p.layoutFacadeDataArray.length&&(p.layoutFacadeDataBuffer=l.createVertexBuffer(p.layoutFacadeDataArray,Rke.members)),p.layoutFacadeVerticalRangeArray&&p.layoutFacadeVerticalRangeArray.length&&(p.layoutFacadeVerticalRangeBuffer=l.createVertexBuffer(p.layoutFacadeVerticalRangeArray,Lke.members)),p.entranceBloom.layoutVertexArray.length&&(p.entranceBloom.layoutVertexBuffer=l.createVertexBuffer(p.entranceBloom.layoutVertexArray,IY.members),p.entranceBloom.layoutAttenuationBuffer=l.createVertexBuffer(p.entranceBloom.layoutAttenuationArray,Dke.members)),this.uploadUpdatedColorBuffer(l),this.uploadUpdatedIndexBuffer(l)};this.uploaded||(u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.groundEffect.upload(l)),this.groundEffect.uploadPaintProperties(l),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){const l=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()))};l(this.buildingWithoutFacade),l(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(l,u,p=!0){let y=!1;const b=p?u:0,S=0|(p?-1:~u);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const k of l){const j=this.footprints[k],O=j.hiddenFlags&S|b;j.hiddenFlags!==O&&(j.hiddenFlags=O,y=!0,this.groundEffect.updateHiddenByLandmarkRange(j.groundEffectVertexOffset,j.groundEffectVertexLength,j.hiddenFlags!==0))}return y&&(this.indexArrayForConflationUploaded=!1),y}uploadUpdatedIndexBuffer(l){if(this.groundEffect.uploadHiddenByLandmark(l),this.indexArrayForConflationUploaded)return;const u=y=>{y.indexArray.length!==0&&(y.indexArrayForConflation.resize(y.indexArray.length),y.indexArrayForConflation.uint16.set(y.indexArray.uint16),y.entranceBloom.indexArrayForConflation.resize(y.entranceBloom.indexArray.length),y.entranceBloom.indexArrayForConflation.uint16.set(y.entranceBloom.indexArray.uint16))};u(this.buildingWithoutFacade),u(this.buildingWithFacade);for(const y of this.footprints){const b=y.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,S=y.indicesOffset+y.indicesLength;if(y.hiddenFlags!==0){for(let j=y.indicesOffset;j{y.indexArray.length!==0&&(y.indexBuffer?y.indexBuffer.updateData(y.indexArrayForConflation):y.indexBuffer=l.createIndexBuffer(y.indexArrayForConflation,!0),y.entranceBloom.indexBuffer?y.entranceBloom.indexBuffer.updateData(y.entranceBloom.indexArrayForConflation):y.entranceBloom.indexBuffer=l.createIndexBuffer(y.entranceBloom.indexArrayForConflation,!0))};p(this.buildingWithoutFacade),p(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(l){const u=p=>{p.layoutColorBuffer?p.layoutColorBuffer.updateData(p.layoutColorArray):p.layoutColorBuffer=l.createVertexBuffer(p.layoutColorArray,PY.members,!0),p.layoutFacadePaintArray&&(p.layoutFacadePaintBuffer?p.layoutFacadePaintBuffer.updateData(p.layoutFacadePaintArray):p.layoutFacadePaintBuffer=l.createVertexBuffer(p.layoutFacadePaintArray,Nke.members,!0)),p.entranceBloom.layoutColorBuffer?p.entranceBloom.layoutColorBuffer.updateData(p.entranceBloom.layoutColorArray):p.entranceBloom.layoutColorBuffer=l.createVertexBuffer(p.entranceBloom.layoutColorArray,PY.members,!0)};u(this.buildingWithoutFacade),u(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(l,u){const p=l.paint.get("building-ambient-occlusion-intensity");for(const y of this.footprints){if(4&y.hiddenFlags)continue;const b=u[y.promoteId],S=y.feature;S.properties["building-part"]="roof";const k=l.paint.get("building-color").evaluate(S,b,this.canonical).toPremultipliedRenderColor(this.lut),j=l.paint.get("building-emissive-strength").evaluate(S,b,this.canonical);S.properties["building-part"]="wall";const O=l.paint.get("building-color").evaluate(S,b,this.canonical).toPremultipliedRenderColor(this.lut),z=l.paint.get("building-emissive-strength").evaluate(S,b,this.canonical);S.properties["building-part"]="window";const U=l.paint.get("building-color").evaluate(S,b,this.canonical).toPremultipliedRenderColor(this.lut),q=l.paint.get("building-emissive-strength").evaluate(S,b,this.canonical);S.properties["building-part"]="door";const K=l.paint.get("building-color").evaluate(S,b,this.canonical).toPremultipliedRenderColor(this.lut),Z=l.paint.get("building-emissive-strength").evaluate(S,b,this.canonical),J=y.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const ae of y.parts){let he,ce=k;ae.part===1?(ce=k,he=j):ae.part===0?(ce=O,he=z):ae.part===2?(ce=U,he=q):ae.part===3&&(ce=K,he=Z),he=fe(he,0,1);for(let ye=0;yeS.max.x||j.max.xS.max.y||j.max.yk.max.x||k.min.x>l||u>k.max.y||k.min.y>u||k.height<=p||Bke(S,this.footprintsVertices.float32.subarray(2*k.footprintVertexOffset,2*(k.footprintVertexOffset+k.footprintVertexLength)),this.footprintsIndices.uint16.subarray(k.footprintIndexOffset,k.footprintIndexOffset+k.footprintIndexLength))&&(p=k.height,this.footprintLookup[b]=k,y=k.hiddenFlags!==0);if(p!==Number.NEGATIVE_INFINITY)return{height:p,hidden:y};this.footprintLookup[b]=void 0}}function Bke(h,l,u){for(let p=0;p1&&(j=l[++k]);const z=Math.abs(O-j.left),U=Math.abs(O-j.right),q=Math.min(z,U);let K;const Z=b/p*(y+1);if(j.isDash){const J=y-Math.abs(Z);K=Math.sqrt(q*q+J*J)}else K=y-Math.sqrt(q*q+Z*Z);this.image.data[S+O]=Math.max(0,Math.min(255,K+128))}}}addRegularDash(l,u){for(let j=l.length-1;j>=0;--j){const O=l[j],z=l[j+1];O.zeroLength?l.splice(j,1):z&&z.isDash===O.isDash&&(z.left=O.left,l.splice(j,1))}const p=l[0],y=l[l.length-1];p.isDash===y.isDash&&(p.left=y.left-this.width,y.right=p.right+this.width);const b=this.width*this.nextRow;let S=0,k=l[S];for(let j=0;j1&&(k=l[++S]);const O=Math.abs(j-k.left),z=Math.abs(j-k.right),U=Math.min(O,z);this.image.data[b+j]=Math.max(0,Math.min(255,(k.isDash?U:-U)+u+128))}}addDash(l,u){const p=this.getKey(l,u);if(this.positions[p])return this.positions[p];const y=u==="round",b=y?7:0,S=2*b+1;if(this.nextRow+S>this.height)return Br("LineAtlas out of space"),null;l.length===0&&l.push(1);let k=0;for(let U=0;Uu.fqid),this.index=l.index,this.projection=l.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(u=>{this.gradients[u.id]={}}),this.layoutVertexArray=new t_,this.layoutVertexArray2=new lu,this.patternVertexArray=new lu,this.indexArray=new _s,this.programConfigurations=new ie(l.layers,{zoom:l.zoom,lut:l.lut}),this.segments=new Si,this.maxLineLength=0,this.zOffsetVertexArray=new lu,this.elevationGroundScaleVertexArray=new Tc,this.stateDependentLayerIds=this.layers.filter(u=>u.isStateDependent()).map(u=>u.id),this.tessellationStep=l.tessellationStep?l.tessellationStep:128,this.worldview=l.worldview,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,p,y){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,y){this.hasPattern=n5("line",this.layers,this.pixelRatio,u);const b=this.layers[0].layout.get("line-sort-key");this.tileToMeter=Dt(p);const S=this.layers[0].layout.get("line-elevation-reference");if(S==="hd-road-markup")this.elevationType="road";else{const q=this.layers[0].layout.get("line-z-offset"),K=q.isConstant()&&!q.constantOr(0);this.elevationType=S!=="sea"&&S!=="ground"&&K?"none":"offset",this.elevationType==="offset"&&S==="none"&&Br(`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 k=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&k!==void 0;const j=[];for(const{feature:q,id:K,index:Z,sourceLayerIndex:J}of l){const ne=this.layers[0]._featureFilter.needGeometry,ae=vn(q,ne);if(!this.layers[0]._featureFilter.filter(new ti(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),ae,p))continue;const he=b?b.evaluate(ae,{},p):void 0,ce={id:K,properties:q.properties,type:q.type,sourceLayerIndex:J,index:Z,geometry:ne?ae.geometry:$r(q,p,y),patterns:{},sortKey:he};j.push(ce)}b&&j.sort((q,K)=>q.sortKey-K.sortKey);const{lineAtlas:O,featureIndex:z}=u,U=this.addConstantDashes(O);for(const q of j){const{geometry:K,index:Z,sourceLayerIndex:J}=q;if(U&&this.addFeatureDashes(q,O),this.hasPattern){const ne=i5("line",this.layers,q,this.zoom,this.pixelRatio,u);this.patternFeatures.push(ne)}else this.addFeature(q,K,Z,p,O.positions,u.availableImages,u.brightness,u.elevationFeatures);z.insert(l[Z].feature,K,Z,J,this.index)}}addConstantDashes(l){let u=!1;for(const p of this.layers){const y=p.paint.get("line-dasharray").value,b=p.layout.get("line-cap").value;if(y.kind!=="constant"||b.kind!=="constant")u=!0;else{const S=b.value,k=y.value;if(!k)continue;l.addDash(k,S)}}return u}addFeatureDashes(l,u){const p=this.zoom;for(const y of this.layers){const b=y.paint.get("line-dasharray").value,S=y.layout.get("line-cap").value;if(b.kind==="constant"&&S.kind==="constant")continue;let k,j;if(b.kind==="constant"){if(k=b.value,!k)continue}else k=b.evaluate({zoom:p},l);j=S.kind==="constant"?S.value:S.evaluate({zoom:p},l),u.addDash(k,j),l.patterns[y.id]=[u.getKey(k,j)]}}update(l,u,p,y,b,S,k,j,O){this.programConfigurations.updatePaintArrays(l,u,b,p,y,S,k,O)}addFeatures(l,u,p,y,b,S){for(const k of this.patternFeatures)this.addFeature(k,k.geometry,k.index,u,p,y,S,l.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(l){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=l.createVertexBuffer(this.layoutVertexArray2,Hke)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=l.createVertexBuffer(this.patternVertexArray,Kke)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=l.createVertexBuffer(this.zOffsetVertexArray,Uke.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=l.createVertexBuffer(this.elevationGroundScaleVertexArray,Vke.members,!0)),this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,qke),this.indexBuffer=l.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(l),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(l,u){let p,y;if(u&&u>0?(p=`mapbox_clip_start_${u}`,y=`mapbox_clip_end_${u}`):(p="mapbox_clip_start",y="mapbox_clip_end"),l.properties&&l.properties.hasOwnProperty(p)&&l.properties.hasOwnProperty(y))return{start:+l.properties[p],end:+l.properties[y]}}addFeature(l,u,p,y,b,S,k,j){const O=this.layers[0].layout,z=O.get("line-join").evaluate(l,{}),U=O.get("line-cap").evaluate(l,{}),q=O.get("line-miter-limit"),K=O.get("line-round-limit");this.lineClips=this.lineFeatureClips(l),this.lineFeature=l;const Z=!(!l.properties||!l.properties.hasOwnProperty("mapbox_line_metrics"))&&l.properties.mapbox_line_metrics;this.zOffsetValue=O.get("line-z-offset").value;const J=this.layers[0].paint.get("line-width").value;if(J.kind!=="constant"&&J.isLineProgressConstant===!1&&(this.variableWidthValue=J),this.isSeaLevelReference){const ne=O.get("line-elevation-ground-scale").value;ne.kind==="constant"&&ne.value===0||(this.elevationGroundScaleValue=ne)}if(this.elevationType==="road"){const ne=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(l,u,y,j,z,U,q,K)){const[ae,he]=this.clipRuntimeLinesToTile(u,1);for(let ce=0;ce0?Ee.parentIndex:null)}this.fillNonElevatedRoadSegment(ne)}}else for(let ne=0;ne0?ne:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,l,p,b,S,y,k,void 0,this.worldview)}computeSegNextDir(l,u){return l.nextPoint.sub(u.at(-2)).unit()}computeSegPrevDir(l,u){return u[1].sub(l.prevPoint).unit()}clipLinesToTile(l,u){return GI(l,-u,-u,ar+u,ar+u)}clipRuntimeLinesToTile(l,u){const p=[];return[GI(l,-u,-u,ar+u,ar+u,p),p]}addElevatedRoadFeature(l,u,p,y,b,S,k,j){const O=[],z=Ii.getElevationFeature(l,y);if(z){const U=this.clipLinesToTile(u,1),q=this.prepareElevatedLines(U,z,p);for(const K of q)O.push({geometry:K,elevation:z,elevationTileID:p,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(O.length===0)return!1;for(const U of O){const q=this.layoutVertexArray.length;this.addLine(U.geometry,l,p,b,S,k,j);const K=new Mi(p,U.elevationTileID);if(U.elevation)for(let Z=q;Z>1,this.layoutVertexArray.int16[6*Z+1]>>1),ne=K.pointElevation(J,U.elevation,.05);this.updateHeightRange(ne),this.zOffsetVertexArray.emplaceBack(ne,0,0)}else this.fillNonElevatedRoadSegment(q)}return!0}prepareElevatedLines(l,u,p){if(u.constantHeight!=null)return l;const y=[],b=1/Dt(p);for(const S of l)oke(S,new Ac(u,b),0,y);return y}fillNonElevatedRoadSegment(l){for(let u=l;u0,q=j&&j.progress.max<1;if(this.lineClips){let Ge={min:this.lineClips.start,max:this.lineClips.end},Ue=1;if(j){const bt=this.lineClips.end-this.lineClips.start;Ge=function(kt,It,Ct){return{min:ys(kt.min,It,Ct),max:ys(kt.max,It,Ct)}}(j.progress,{min:0,max:1},Ge),bt>0&&(Ue=(Ge.max-Ge.min)/bt)}const Ve=+u.properties.mapbox_clip_feature_len,yt=+u.properties.mapbox_clip_seg_len;if(Number.isNaN(Ve)||Number.isNaN(yt)){for(let kt=0;kt=2&&l[Z-1].equals(l[Z-2]);)Z--;let J=0;for(;J0,jt=this.overscaling<=16?122880/(512*this.overscaling):0;if(Ue&&Ve==="round"){if(ItS&&(Ve="bevel"),Ve==="bevel"&&(It>2&&(Ve="flipbevel"),It2*jt){const Wt=ae.sub(ae.sub(he)._mult(jt/Lt)._round());this.updateDistance(he,Wt),this.addCurrentVertex(Wt,ye,0,0,ne,$e),he=Wt}this.updateDistance(he,ae),bt._mult(It),this.addCurrentVertex(ae,bt,0,0,ne,$e);const $t=ae.dist(ce);if($t>2*jt){const Wt=ae.add(ce.sub(ae)._mult(jt/$t)._round());this.updateDistance(ae,Wt),this.addCurrentVertex(Wt,Ee,0,0,ne,$e),ae=Wt}}else bt._mult(It),this.addCurrentVertex(ae,bt,0,0,ne,$e);else if(Ve==="flipbevel"){if(It>100)bt=Ee.mult(-1);else{const Lt=It*ye.add(Ee).mag()/ye.sub(Ee).mag();bt._perp()._mult(Lt*(pt?-1:1))}this.addCurrentVertex(ae,bt,0,0,ne,$e),this.addCurrentVertex(ae,bt.mult(-1),0,0,ne,$e)}else if(Ve==="bevel"||Ve==="fakeround"){const Lt=ae.dist(he);let $t=1;if(this.elevationType==="offset"&&Ve==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&$e!=null&&he&&ce){const mr=4*jt;Lt1){this.lineSoFar=l.w;const J=(u.x-l.x)/U,ne=(u.y-l.y)/U,ae=(u.z-l.z)/U,he=(u.w-l.w)/U,ce=u.x-l.x,ye=u.y-l.y,Ee=Math.sqrt(ce*ce+ye*ye);if(Ee===0)return;const Ce=-ye/Ee,He=ce/Ee,$e=Ce,Ge=He,Ue=-Ce,Ve=-He;for(let yt=1;yt=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,z),j.primitiveLength++),S?this.e2=z:this.e1=z,O!=null&&this.zOffsetVertexArray.emplaceBack(O.zOffset,O.variableWidth,O.variableWidth),this.elevationGroundScaleValue){const U=O?O.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(l,u){this.prevDistance=this.distance,this.distance+=l.dist(u),this.updateScaledDistance()}}function D5(h,l,u){return h.xu||h.yu}let MY,FY;function BY(h,l,u){return l*(ar/(h.tileSize*Math.pow(2,u-h.tileID.overscaledZ)))}vr(tP,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const zY=(h,l,u)=>(1-u)*h+u*l;function $Y(h,l){return 1/BY(h,1,l.tileZoom)}function UY(h,l,u,p){return h.translatePosMatrix(p||l.tileID.projMatrix,l,u.paint.get("line-translate"),u.paint.get("line-translate-anchor"))}const VY=h=>{const l=[];qY(h)&&l.push("RENDER_LINE_DASH"),h.paint.get("line-gradient")&&l.push("RENDER_LINE_GRADIENT"),h.paint.get("line-blend-mode")==="multiply"&&l.push("LINE_BLEND_MULTIPLY");const u=h.paint.get("line-trim-offset");u[0]===0&&u[1]===0||l.push("RENDER_LINE_TRIM_OFFSET"),h.paint.get("line-border-width").constantOr(1)!==0&&l.push("RENDER_LINE_BORDER");const p=h.layout.get("line-join").constantOr("miter")==="none",y=!!h.paint.get("line-pattern").constantOr(1);return p&&y&&l.push("LINE_JOIN_NONE"),l};function qY(h){const l=h.paint.get("line-dasharray").value;return l.kind!=="constant"||l.value}let O5;const GY=()=>O5||(O5={layout:MY||(MY=new ts({"line-cap":new qt(nt.layout_line["line-cap"]),"line-join":new qt(nt.layout_line["line-join"]),"line-miter-limit":new Xt(nt.layout_line["line-miter-limit"]),"line-round-limit":new Xt(nt.layout_line["line-round-limit"]),"line-sort-key":new qt(nt.layout_line["line-sort-key"]),"line-z-offset":new qt(nt.layout_line["line-z-offset"]),"line-elevation-reference":new Xt(nt.layout_line["line-elevation-reference"]),"line-cross-slope":new Xt(nt.layout_line["line-cross-slope"]),visibility:new Xt(nt.layout_line.visibility),"line-width-unit":new Xt(nt.layout_line["line-width-unit"]),"line-elevation-ground-scale":new qt(nt.layout_line["line-elevation-ground-scale"])})),paint:FY||(FY=new ts({"line-opacity":new qt(nt.paint_line["line-opacity"]),"line-color":new qt(nt.paint_line["line-color"]),"line-translate":new Xt(nt.paint_line["line-translate"]),"line-translate-anchor":new Xt(nt.paint_line["line-translate-anchor"]),"line-width":new qt(nt.paint_line["line-width"]),"line-gap-width":new qt(nt.paint_line["line-gap-width"]),"line-offset":new qt(nt.paint_line["line-offset"]),"line-blur":new qt(nt.paint_line["line-blur"]),"line-dasharray":new qt(nt.paint_line["line-dasharray"]),"line-pattern":new qt(nt.paint_line["line-pattern"]),"line-pattern-cross-fade":new Xt(nt.paint_line["line-pattern-cross-fade"]),"line-gradient":new xg(nt.paint_line["line-gradient"]),"line-trim-offset":new Xt(nt.paint_line["line-trim-offset"]),"line-trim-fade-range":new Xt(nt.paint_line["line-trim-fade-range"]),"line-trim-color":new Xt(nt.paint_line["line-trim-color"]),"line-emissive-strength":new qt(nt.paint_line["line-emissive-strength"]),"line-border-width":new qt(nt.paint_line["line-border-width"]),"line-border-color":new qt(nt.paint_line["line-border-color"]),"line-occlusion-opacity":new Xt(nt.paint_line["line-occlusion-opacity"]),"line-blend-mode":new Xt(nt.paint_line["line-blend-mode"]),"line-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"})}))},O5);class Qke extends qt{possiblyEvaluate(l,u){return u=new ti(Math.floor(u.zoom),{now:u.now,fadeDuration:u.fadeDuration,transition:u.transition,worldview:u.worldview}),super.possiblyEvaluate(l,u)}evaluate(l,u,p,y){return u=Object.assign({},u,{zoom:Math.floor(u.zoom)}),super.evaluate(l,u,p,y)}}let DE;function HY(h,l){return l>0?l+2*h:h}const Jke=Pn([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),eCe=Pn([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),tCe=Pn([{name:"a_projected_pos",components:4,type:"Float32"}],4);Pn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const rCe=Pn([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),nCe=Pn([{name:"a_feature_index",components:1,type:"Float32"}],4),iCe=Pn([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),sCe=Pn([{name:"a_texb",components:2,type:"Uint16"}]),aCe=Pn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),oCe=Pn([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);Pn([{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 WY=Pn([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),lCe=Pn([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);Pn([{name:"triangle",components:3,type:"Uint16"}]),Pn([{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"}]),Pn([{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"}]),Pn([{type:"Float32",name:"offsetX"}]),Pn([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const M5=class RR{constructor(l=null,u=0,p=4096){this.batchIndex=u,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=l||null,this.propsDwords=p,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(RR.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let y=0;yl.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${l.maxUniformBlockSize}`);if(this.headerBuffer=u.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(u.bindBuffer(u.UNIFORM_BUFFER,this.headerBuffer),u.bufferData(u.UNIFORM_BUFFER,RR.HEADER_BYTES,u.DYNAMIC_DRAW),this.propertiesBuffer=u.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(u.bindBuffer(u.UNIFORM_BUFFER,this.propertiesBuffer),u.bufferData(u.UNIFORM_BUFFER,this.totalBytes,u.DYNAMIC_DRAW),this.blockIndicesBuffer=u.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");u.bindBuffer(u.UNIFORM_BUFFER,this.blockIndicesBuffer),u.bufferData(u.UNIFORM_BUFFER,this.totalBytes,u.DYNAMIC_DRAW),u.bindBuffer(u.UNIFORM_BUFFER,null)}writeHeader(l){const u=this.headerData;u[0]=l.dataDrivenMask,u[1]=l.zoomDependentMask,u[2]=l.dataDrivenBlockSizeVec4,u[3]=l.offsets[0],u[4]=l.offsets[1],u[5]=l.offsets[2],u[6]=l.offsets[3],u[7]=l.offsets[4],u[8]=l.offsets[5],u[9]=l.offsets[6],u[10]=l.offsets[7],u[11]=l.offsets[8]}writeDataDrivenBlock(l,u,p){const y=4*p.dataDrivenBlockSizeVec4;if(y===0)return;const b=u*y;if(b+y>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${u} exceeds propertiesData capacity`);for(let S=0;S<9;S++)p.dataDrivenMask&1<{if(!k)return;const O=p.getUniformBlockIndex(u,S);O!==p.INVALID_INDEX&&(p.uniformBlockBinding(u,O,j),p.bindBufferBase(p.UNIFORM_BUFFER,j,k))},b=3*this.batchIndex;y("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,b),y("SymbolPaintPropertiesUniform",this.propertiesBuffer,b+1),y("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,b+2)}destroy(){if(this.context){const l=this.context.gl;this.headerBuffer&&(l.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(l.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(l.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};M5.HEADER_DWORDS=12,M5.HEADER_BYTES=48;let F5=M5;function B5(h,l,u,p){return[Qv(255*h,255*l),Qv(255*u,255*p)]}function KY(h,l,u,p,y,b,S,k){return!!h&&(h.kind==="constant"?h.value==="none":h.kind==="composite"||h.kind==="source"?h.evaluate({zoom:0,brightness:b,worldview:k},l,u,y,p,S)==="none":typeof h=="string"&&h==="none")}vr(F5,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class z5{constructor(l,u,p,y,b="",S,k){this.layer=l,this.zoom=u,this.lut=p,this.isText=y,this.propDefs=this._getPropDefs(),this.worldview=b,this.maxUniformBufferBindings=S||24,this.uboSizeDwords=k||4096,this.featureVertexRangesFromId=new Map,this.allFeatures=[],this.ubos=[],this.featureCount=0,this.cachedHeader=null,this.maxFeaturesPerBatch=0,this.propertyHashToUBOIndex=new Map,this.canDeduplicate=this._checkIfAllPropertiesAreConstant(l,y),this.cachedParams=null,this.cachedParamsNext=null,this.cachedBrightness=void 0,this.cachedConstantUniforms=null,this.cachedConstantRenderZoom=null,this.cachedConstantBrightness=void 0,this.activeAppearanceByVtIndex=new Map}_getPropDefs(){const l=this.isText?"text":"icon";return[{name:`${l}-color`,useThemeName:`${l}-color-use-theme`,isColor:!0},{name:`${l}-halo-color`,useThemeName:`${l}-halo-color-use-theme`,isColor:!0},{name:`${l}-opacity`,useThemeName:null,isColor:!1},{name:`${l}-halo-width`,useThemeName:null,isColor:!1},{name:`${l}-halo-blur`,useThemeName:null,isColor:!1},{name:`${l}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${l}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${l}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const l=this.layer.paint,u=this.propDefs;let p=0,y=0,b=0,S=0;const k=[0,0,0,0,0,0,0,0,0];for(let j=0;j<9;j++){const{name:O,isColor:z,isVec2:U}=u[j],q=l.get(O),K=!(!q||typeof q.isConstant!="function"||q.isConstant()),Z=this._appearancesHavePaintProperties(O),J=K||Z,ne=!(!q||!q.value||q.value.kind!=="composite"),ae=this.layer._transitionablePaint._values[O],he=!J&&(ae&&ae.value&&ae.value.expression&&ae.value.expression.kind)==="camera";J?(p|=1<u.hasPaintProperty(l):this.isText?u=>u.hasTextPaintProperties():u=>u.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(l,u){const p=l.paint,y=u?"text":"icon",b=[`${y}-color`,`${y}-halo-color`,`${y}-opacity`,`${y}-halo-width`,`${y}-halo-blur`,`${y}-emissive-strength`,`${y}-occlusion-opacity`,"symbol-z-offset",`${y}-translate`];for(const S of b){const k=p.get(S);if(k&&typeof k=="object"&&"isConstant"in k&&!k.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(l,u){if(u.dataDrivenMask===0)return"";const p=[];for(let y=0;y<9;y++){if(!(u.dataDrivenMask&1<=Z){Br(`Too many symbol features: batch ${q} requires binding points up to ${3*q+2}, device limit ${Z}. Some features will render incorrectly.`);const ne={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:u,featureId:j};return this.allFeatures.push(ne),j!=null&&(this.featureVertexRangesFromId.has(j)||this.featureVertexRangesFromId.set(j,[]),this.featureVertexRangesFromId.get(j).push(ne)),0}this.ubos[q]||(this.ubos[q]=new F5(k,q,this.uboSizeDwords),this.ubos[q].writeHeader(O)),this.ubos[q].writeDataDrivenBlock(z,K,O);const J={batchIndex:q,localFeatureIndex:K,vtFeatureIndex:u,featureId:j};return this.allFeatures.push(J),j!=null&&(this.featureVertexRangesFromId.has(j)||this.featureVertexRangesFromId.set(j,[]),this.featureVertexRangesFromId.get(j).push(J)),K}updateFeatures(l,u,p,y,b,S,k){if(this.layer=u,this.cachedConstantUniforms=null,!this.cachedHeader)return;const j=this.cachedHeader;for(const O of l){const z=this.featureVertexRangesFromId.get(O);if(!z)continue;const U=S[O]||{};for(const q of z){if(!p)continue;const K=p.feature(q.vtFeatureIndex);if(!K)continue;const Z={type:K.type,id:O,properties:K.properties||{},geometry:[]},J=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(q.vtFeatureIndex):void 0,ne=this.evaluateAllProperties(Z,U,y,b,k,void 0,J);this.ubos[q.batchIndex]&&this.ubos[q.batchIndex].writeDataDrivenBlock(ne,q.localFeatureIndex,j)}}}updateDynamicExpressions(l,u,p,y,b,S){if(this.layer=l,this.cachedConstantUniforms=null,!this.cachedHeader)return;const k=this.cachedHeader;for(const j of this.allFeatures){if(!u)continue;const O=u.feature(j.vtFeatureIndex);if(!O)continue;const z=j.featureId!=null&&b[j.featureId]||{},U={type:O.type,id:j.featureId,properties:O.properties||{},geometry:[]},q=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(j.vtFeatureIndex):void 0,K=this.evaluateAllProperties(U,z,p,y,S,void 0,q);this.ubos[j.batchIndex]&&this.ubos[j.batchIndex].writeDataDrivenBlock(K,j.localFeatureIndex,k)}}updateFeaturePaintForAppearance(l,u,p,y,b,S,k){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(l,k||null),!this.cachedHeader))return!1;const j=this.cachedHeader;if(j.dataDrivenMask===0)return!1;let O=!1;for(const z of this.allFeatures){if(z.vtFeatureIndex!==l)continue;const U=this.evaluateAllProperties(u,p,y,b,S,void 0,k);this.ubos[z.batchIndex]&&(this.ubos[z.batchIndex].writeDataDrivenBlock(U,z.localFeatureIndex,j),O=!0)}return O}getConstantUniformValues(l,u){const p=this.cachedHeader,y=!(!p||!p.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===u&&(!y||this.cachedConstantRenderZoom===l))return this.cachedConstantUniforms;const b=this.layer.paint,S=this.propDefs,k=y?new ti(l,{brightness:u,worldview:this.worldview}):null,j={type:1,id:void 0,properties:{},geometry:[]},O=q=>{const K=S[q],Z=b.get(K.name);if(!Z)return[0,0,0,1];const J=K.useThemeName?b.get(K.useThemeName):void 0,ne=KY(J&&typeof J!="string"?J.value:void 0,j,{},[],void 0,u,void 0,this.worldview)?null:this.lut;let ae;ae=p&&p.cameraMask&1<{const Z=b.get(S[q].name);if(!Z)return K;if(p&&p.cameraMask&1<{p.text=function(y,b,S){const k=b.layout.get("text-transform").evaluate(S,{});return k==="uppercase"?y=y.toLocaleUpperCase():k==="lowercase"&&(y=y.toLocaleLowerCase()),hh.applyArabicShaping&&(y=hh.applyArabicShaping(y)),y}(p.text,l,u)}),h}const OE={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function uCe(h){return h==="︶"||h==="﹈"||h==="︸"||h==="﹄"||h==="﹂"||h==="︾"||h==="︼"||h==="︺"||h==="︘"||h==="﹀"||h==="︐"||h==="︓"||h==="︔"||h==="`"||h===" ̄"||h==="︑"||h==="︒"}function dCe(h){return h==="︵"||h==="﹇"||h==="︷"||h==="﹃"||h==="﹁"||h==="︽"||h==="︻"||h==="︹"||h==="︗"||h==="︿"}const $5=4294967296,YY=1/$5,ZY=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let rP=class{constructor(h=new Uint8Array(16)){this.buf=ArrayBuffer.isView(h)?h:new Uint8Array(h),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(h,l,u=this.length){for(;this.pos>3,b=this.pos;this.type=7&p,h(y,l,this),this.pos===b&&this.skip(p)}return l}readMessage(h,l){return this.readFields(h,l,this.readVarint()+this.pos)}readFixed32(){const h=this.dataView.getUint32(this.pos,!0);return this.pos+=4,h}readSFixed32(){const h=this.dataView.getInt32(this.pos,!0);return this.pos+=4,h}readFixed64(){const h=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*$5;return this.pos+=8,h}readSFixed64(){const h=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*$5;return this.pos+=8,h}readFloat(){const h=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,h}readDouble(){const h=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,h}readVarint(h){const l=this.buf;let u,p;return p=l[this.pos++],u=127&p,p<128?u:(p=l[this.pos++],u|=(127&p)<<7,p<128?u:(p=l[this.pos++],u|=(127&p)<<14,p<128?u:(p=l[this.pos++],u|=(127&p)<<21,p<128?u:(p=l[this.pos],u|=(15&p)<<28,function(y,b,S){const k=S.buf;let j,O;if(O=k[S.pos++],j=(112&O)>>4,O<128||(O=k[S.pos++],j|=(127&O)<<3,O<128)||(O=k[S.pos++],j|=(127&O)<<10,O<128)||(O=k[S.pos++],j|=(127&O)<<17,O<128)||(O=k[S.pos++],j|=(127&O)<<24,O<128)||(O=k[S.pos++],j|=(1&O)<<31,O<128))return lb(y,j,b);throw new Error("Expected varint not more than 10 bytes")}(u,h,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const h=this.readVarint();return h%2==1?(h+1)/-2:h/2}readBoolean(){return!!this.readVarint()}readString(){const h=this.readVarint()+this.pos,l=this.pos;return this.pos=h,h-l>=12&&ZY?ZY.decode(this.buf.subarray(l,h)):function(u,p,y){let b="",S=p;for(;S239?4:k>223?3:k>191?2:1;if(S+q>y)break;q===1?k<128&&(U=k):q===2?(j=u[S+1],(192&j)==128&&(U=(31&k)<<6|63&j,U<=127&&(U=null))):q===3?(j=u[S+1],O=u[S+2],(192&j)==128&&(192&O)==128&&(U=(15&k)<<12|(63&j)<<6|63&O,(U<=2047||U>=55296&&U<=57343)&&(U=null))):q===4&&(j=u[S+1],O=u[S+2],z=u[S+3],(192&j)==128&&(192&O)==128&&(192&z)==128&&(U=(15&k)<<18|(63&j)<<12|(63&O)<<6|63&z,(U<=65535||U>=1114112)&&(U=null))),U===null?(U=65533,q=1):U>65535&&(U-=65536,b+=String.fromCharCode(U>>>10&1023|55296),U=56320|1023&U),b+=String.fromCharCode(U),S+=q}return b}(this.buf,l,h)}readBytes(){const h=this.readVarint()+this.pos,l=this.buf.subarray(this.pos,h);return this.pos=h,l}readPackedVarint(h=[],l){const u=this.readPackedEnd();for(;this.pos127;);else if(l===2)this.pos=this.readVarint()+this.pos;else if(l===5)this.pos+=4;else{if(l!==1)throw new Error(`Unimplemented type: ${l}`);this.pos+=8}}writeTag(h,l){this.writeVarint(h<<3|l)}realloc(h){let l=this.length||16;for(;l268435455||h<0?function(l,u){let p,y;if(l>=0?(p=l%4294967296|0,y=l/4294967296|0):(p=~(-l%4294967296),y=~(-l/4294967296),4294967295^p?p=p+1|0:(p=0,y=y+1|0)),l>=18446744073709552e3||l<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");u.realloc(10),function(b,S,k){k.buf[k.pos++]=127&b|128,b>>>=7,k.buf[k.pos++]=127&b|128,b>>>=7,k.buf[k.pos++]=127&b|128,b>>>=7,k.buf[k.pos++]=127&b|128,k.buf[k.pos]=127&(b>>>=7)}(p,0,u),function(b,S){const k=(7&b)<<4;S.buf[S.pos++]|=k|((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)))))}(y,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 l=this.pos;this.pos=function(p,y,b){for(let S,k,j=0;j55295&&S<57344){if(!k){S>56319||j+1===y.length?(p[b++]=239,p[b++]=191,p[b++]=189):k=S;continue}if(S<56320){p[b++]=239,p[b++]=191,p[b++]=189,k=S;continue}S=k-55296<<10|S-56320|65536,k=null}else k&&(p[b++]=239,p[b++]=191,p[b++]=189,k=null);S<128?p[b++]=S:(S<2048?p[b++]=S>>6|192:(S<65536?p[b++]=S>>12|224:(p[b++]=S>>18|240,p[b++]=S>>12&63|128),p[b++]=S>>6&63|128),p[b++]=63&S|128)}return b}(this.buf,h,this.pos);const u=this.pos-l;u>=128&&XY(l,u,this),this.pos=l-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 l=h.length;this.writeVarint(l),this.realloc(l);for(let u=0;u=128&&XY(u,p,this),this.pos=u-1,this.writeVarint(p),this.pos+=p}writeMessage(h,l,u){this.writeTag(h,2),this.writeRawMessage(l,u)}writePackedVarint(h,l){l.length&&this.writeMessage(h,hCe,l)}writePackedSVarint(h,l){l.length&&this.writeMessage(h,fCe,l)}writePackedBoolean(h,l){l.length&&this.writeMessage(h,gCe,l)}writePackedFloat(h,l){l.length&&this.writeMessage(h,pCe,l)}writePackedDouble(h,l){l.length&&this.writeMessage(h,mCe,l)}writePackedFixed32(h,l){l.length&&this.writeMessage(h,yCe,l)}writePackedSFixed32(h,l){l.length&&this.writeMessage(h,xCe,l)}writePackedFixed64(h,l){l.length&&this.writeMessage(h,_Ce,l)}writePackedSFixed64(h,l){l.length&&this.writeMessage(h,vCe,l)}writeBytesField(h,l){this.writeTag(h,2),this.writeBytes(l)}writeFixed32Field(h,l){this.writeTag(h,5),this.writeFixed32(l)}writeSFixed32Field(h,l){this.writeTag(h,5),this.writeSFixed32(l)}writeFixed64Field(h,l){this.writeTag(h,1),this.writeFixed64(l)}writeSFixed64Field(h,l){this.writeTag(h,1),this.writeSFixed64(l)}writeVarintField(h,l){this.writeTag(h,0),this.writeVarint(l)}writeSVarintField(h,l){this.writeTag(h,0),this.writeSVarint(l)}writeStringField(h,l){this.writeTag(h,2),this.writeString(l)}writeFloatField(h,l){this.writeTag(h,5),this.writeFloat(l)}writeDoubleField(h,l){this.writeTag(h,1),this.writeDouble(l)}writeBooleanField(h,l){this.writeVarintField(h,+l)}};function lb(h,l,u){return u?4294967296*l+(h>>>0):4294967296*(l>>>0)+(h>>>0)}function XY(h,l,u){const p=l<=16383?1:l<=2097151?2:l<=268435455?3:Math.floor(Math.log(l)/(7*Math.LN2));u.realloc(p);for(let y=u.pos-1;y>=h;y--)u.buf[y+p]=u.buf[y]}function hCe(h,l){for(let u=0;u=0&&p>=l&&nP[this.text.charCodeAt(p)];p--)u--;this.text=this.text.substring(l,u),this.sectionIndex=this.sectionIndex.slice(l,u)}substring(l,u){const p=new cb;return p.text=this.text.substring(l,u),p.sectionIndex=this.sectionIndex.slice(l,u),p.sections=this.sections,p}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((l,u)=>Math.max(l,this.sections[u].scale),0)}addTextSection(l,u){this.text+=l.text,this.sections.push(ME.forText(l.scale,l.fontStack||u));const p=this.sections.length-1;for(let y=0;y=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function U5(h,l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J=1,ne=1){const ae=cb.fromFeature(h,y,J,ne);U===Ic.vertical&&ae.verticalizePunctuation(q);let he=[];const ce=function($e,Ge,Ue,Ve,yt,bt,kt=1){if(!$e)return[];const It=[],Ct=function(jt,Lt,$t,Wt,xr,ir,nr=1){let Kt=0;for(let mr=0;mr=0;let pt=0;for(let jt=0;jt<$e.length();jt++){const Lt=$e.getSection(jt),$t=$e.getCodePoint(jt);if(nP[$t]||(pt+=QY($t,Lt,Ve,yt,Ge,bt,kt)),jt<$e.length()-1){const Wt=O3($t);(TCe[$t]||Wt||Lt.image)&&It.push(eZ(jt+1,pt,Ct,It,ECe($t,$e.getCodePoint(jt+1),Wt&&Bt),!1))}}return tZ(eZ($e.length(),pt,Ct,It,0,!0))}(ae,O,b,l,p,K,ne),{processBidirectionalText:ye,processStyledBidirectionalText:Ee}=hh;if(ye&&ae.sections.length===1){const $e=ye(ae.toString(),ce);for(const Ge of $e){const Ue=new cb;Ue.text=Ge,Ue.sections=ae.sections;for(let Ve=0;Ve0&&Xo>bn&&(bn=Xo)}else{const Ga=Ue[os.fontStack];if(!Ga)continue;Ga[ls]&&(bs=Ga[ls]);const xl=Ge[os.fontStack];if(!xl)continue;const bo=xl.glyphs[ls];if(!bo)continue;if(qs=bo.metrics,La=ls!==8203?Na:0,nr){const ps=xl.ascender!==void 0?Math.abs(xl.ascender):0,Xo=xl.descender!==void 0?Math.abs(xl.descender):0,Ha=(ps+Xo)*vs;fs-u/2;){if(S--,S<0)return!1;k-=h[S].dist(b),b=h[S]}k+=h[S].dist(h[S+1]),S++;const j=[];let O=0;for(;kp;)O-=j.shift().angleDelta;if(O>y)return!1;S++,k+=z.dist(U)}return!0}function oZ(h){let l=0;for(let u=0;uO){const Z=(O-j)/K,J=Xr(U.x,q.x,Z),ne=Xr(U.y,q.y,Z),ae=new Gp(J,ne,0,q.angleTo(U),z);return!S||aZ(h,ae,k,S,l)?ae:void 0}j+=K}}function kCe(h,l,u,p,y,b,S,k,j){const O=lZ(p,b,S),z=cZ(p,y),U=z*S,q=h[0].x===0||h[0].x===j||h[0].y===0||h[0].y===j;return l-U=0&&ye=0&&Ee=0&&q+O<=z){const Ce=new Gp(ye,Ee,0,he,Z);p&&!aZ(h,Ce,b,p,y)||K.push(Ce)}}U+=ae}return k||K.length||S||(K=uZ(h,U/2,u,p,y,b,S,!0,j)),K}function dZ(h){let l=0,u=0;for(const S of h)l+=S.w*S.h,u=Math.max(u,S.w);h.sort((S,k)=>k.h-S.h);const p=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(l/.95)),u),h:1/0}];let y=0,b=0;for(const S of h)for(let k=p.length-1;k>=0;k--){const j=p[k];if(!(S.w>j.w||S.h>j.h)){if(S.x=j.x,S.y=j.y,b=Math.max(b,S.y+S.h),y=Math.max(y,S.x+S.w),S.w===j.w&&S.h===j.h){const O=p.pop();O&&kl.id?1:h.versionl.version?1:h.sxl.sx?1:h.syl.sy?1:0}function W5(h){let l=0;for(let u=0;u0,hZ(l,p,this.iconDescriptors,b),hZ(u,p,this.patternDescriptors,b),this.iconDescriptors.sort(sP),this.patternDescriptors.sort(sP);let S=0;const k=y?y.data:"";k&&(S=xh(S,W5(k))),S=xh(S,1);for(const j of this.iconDescriptors)S=xh(S,W5(j.id)),S=xh(S,j.version),S=xh(S,j.sx),S=xh(S,j.sy);S=xh(S,1);for(const j of this.patternDescriptors)S=xh(S,W5(j.id)),S=xh(S,j.version),S=xh(S,j.sx),S=xh(S,j.sy);this.hash=S}subsetOf(l){return this.isSubsetArray(this.iconDescriptors,l.iconDescriptors,sP)&&this.isSubsetArray(this.patternDescriptors,l.patternDescriptors,sP)}isSubsetArray(l,u,p){let y=0,b=0;if(l.length>u.length)return!1;for(;y{const S=y.variant.id.toString().localeCompare(b.variant.id.toString());return S!==0?S:y.variant.sx!==b.variant.sx?y.variant.sx-b.variant.sx:y.variant.sy!==b.variant.sy?y.variant.sy-b.variant.sy:0});const p=new Map;for(const y of u)p.set(y.key,y.value);return p}class fZ{constructor(l){this.sourceAtlasHash=l}}class pZ{constructor(l,u,p,y){const b=new Map,S=new Map;this.haveRenderCallbacks=[];const k=[],j=y!==void 0,O=j?new Map:void 0,z=j?Z5(l,O):l,U=j?Z5(u,O):u;this.addImages(z,b,1,k),this.addImages(U,S,2,k);const{w:q,h:K}=dZ(k),Z=new Do({width:q||1,height:K||1});for(const[J,ne]of z.entries()){const ae=b.get(J).paddedRect;Do.copy(ne.data,Z,{x:0,y:0},{x:ae.x+1,y:ae.y+1},ne.data,null,ne.sdf)}for(const[J,ne]of U.entries()){const ae=S.get(J),he=ae.paddedRect;let ce=ae.padding;const ye=he.x+ce,Ee=he.y+ce,Ce=ne.data.width,He=ne.data.height;ce=ce>1?ce-1:ce,Do.copy(ne.data,Z,{x:0,y:0},{x:ye,y:Ee},ne.data,p),Do.copy(ne.data,Z,{x:0,y:He-ce},{x:ye,y:Ee-ce},{width:Ce,height:ce},p),Do.copy(ne.data,Z,{x:0,y:0},{x:ye,y:Ee+He},{width:Ce,height:ce},p),Do.copy(ne.data,Z,{x:Ce-ce,y:0},{x:ye-ce,y:Ee},{width:ce,height:He},p),Do.copy(ne.data,Z,{x:0,y:0},{x:ye+Ce,y:Ee},{width:ce,height:He},p),Do.copy(ne.data,Z,{x:Ce-ce,y:He-ce},{x:ye-ce,y:Ee-ce},{width:ce,height:ce},p),Do.copy(ne.data,Z,{x:0,y:He-ce},{x:ye+Ce,y:Ee-ce},{width:ce,height:ce},p),Do.copy(ne.data,Z,{x:0,y:0},{x:ye+Ce,y:Ee+He},{width:ce,height:ce},p),Do.copy(ne.data,Z,{x:Ce-ce,y:0},{x:ye-ce,y:Ee+He},{width:ce,height:ce},p)}this.lut=p,this.image=Z,this.iconPositions=b,this.patternPositions=S,j&&(this.contentDescriptor=new K5(z,U,y,p,O))}addImages(l,u,p,y){for(const[b,S]of l.entries()){const{bin:k,imagePosition:j,imageVariant:O}=Y5(b,S,p);u.set(b,j),y.push(k),S.hasRenderCallback&&this.haveRenderCallbacks.push(O.id)}}patchUpdatedImages(l,u,p,y){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(b=>l.hasImage(b,p)),l.dispatchRenderCallbacks(this.haveRenderCallbacks,p);for(const b of l.getUpdatedImages(p)){for(const S of this.iconPositions.keys()){const k=au.parse(S);if(rc.isEqual(k.id,b)){const j=l.getImage(b,p);this.patchUpdatedImage(this.iconPositions.get(S),j,u,null)}}for(const S of this.patternPositions.keys()){const k=au.parse(S);if(rc.isEqual(k.id,b)){const j=l.getImage(b,p);this.patchUpdatedImage(this.patternPositions.get(S),j,u,y||this.lut)}}}}patchUpdatedImage(l,u,p,y=null){if(!l||!u||l.version===u.version)return;l.version=u.version;const[b,S]=l.tl,k=l.sdf;if(this.lut||k){const j={width:u.data.width,height:u.data.height},O=new Do(j);Do.copy(u.data,O,{x:0,y:0},{x:0,y:0},j,y,k),p.update(O,{position:{x:b,y:S},recreateWhenResize:!1})}else p.update(u.data,{position:{x:b,y:S},recreateWhenResize:!1})}}vr(FE,"ImagePosition"),vr(pZ,"ImageAtlas",{omit:["lut"]}),vr(fZ,"ImageAtlasReference");class BE{constructor(l){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!l||l.useServerFontComposition===void 0||l.useServerFontComposition}loadGlyphRange(l,u,p,y,b){if(this.useServerFontComposition)return void BE.loadGlyphRange(l,u,p,y,b);const S=l.split(",").map(k=>k.trim()).filter(k=>k.length>0);S.length!==0?S.length!==1?this._loadMultipleFonts(S,u,p,y,b):this._loadFont(S[0],u,p,y,b):b(new Error("Empty fontstack"))}_loadMultipleFonts(l,u,p,y,b){const S=l.map(()=>null),k={completed:0,firstError:null,callbackCalled:!1},j=(O,z,U)=>{if(!k.callbackCalled&&(z&&!k.firstError&&(k.firstError=z),U&&(S[O]=U),k.completed++,k.completed===l.length)){k.callbackCalled=!0;const q=S.filter(Z=>Z!==null);if(q.length===0)return void b(k.firstError||new Error("All fonts failed to load"));const K=this._composeGlyphs(q);b(null,K)}};for(let O=0;O{j(O,z,U)})}_loadFont(l,u,p,y,b){const S=`${l}:${u}`;if(this.cachedRanges.has(S)){const j=this.cachedRanges.get(S);return void Pl.frame(()=>b(null,j))}const k=this.pendingRequests.get(S);k?k.push(b):(this.pendingRequests.set(S,[b]),BE.loadGlyphRange(l,u,p,y,(j,O)=>{j||this.cachedRanges.set(S,O||null);const z=this.pendingRequests.get(S);if(this.pendingRequests.delete(S),z)for(const U of z)U(j,O)}))}_composeGlyphs(l){const u={};let p,y;for(const b of l)if(p===void 0&&b.ascender!==void 0&&(p=b.ascender),y===void 0&&b.descender!==void 0&&(y=b.descender),b.glyphs)for(const S in b.glyphs)u[S]===void 0&&(u[S]=b.glyphs[S]);return{glyphs:u,ascender:p,descender:y}}}BE.loadGlyphRange=function(h,l,u,p,y){const b=256*l,S=b+255,k=p.transformRequest(p.normalizeGlyphsURL(u).replace("{fontstack}",h).replace("{range}",`${b}-${S}`),_x.Glyphs);Xm(k,(j,O)=>{if(j)y(j);else if(O){const z={},U=function(q){return new rP(q).readFields(bCe,{})}(O);for(const q of U.glyphs)z[q.id]=q;y(null,{glyphs:z,ascender:U.ascender,descender:U.descender})}})};const zE=1e20;function mZ(h,l,u,p,y,b,S,k,j){for(let O=l;O-1);j++,b[j]=k,S[j]=O,S[j+1]=zE}for(let k=0,j=0;k{if(S){y.ascender=S.ascender,y.descender=S.descender;for(const k in S.glyphs)this._doesCharSupportLocalGlyph(+k)||(y.glyphs[+k]=S.glyphs[+k]);y.ranges[u]=!0}for(const k of y.requests[u]||[])k(b,S);delete y.requests[u]}))}getGlyphs(l,u){const p=[],y=this.url||Dn.GLYPHS_URL;for(const b in l)for(const S of l[b])p.push({stack:b,id:S});Je(p,({stack:b,id:S},k)=>{let j=this.entries[b];j||(j=this.entries[b]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let O=j.glyphs[S];if(O!==void 0)return void k(null,{stack:b,id:S,glyph:O});if(O=this._tinySDF(j,b,S),O)return j.glyphs[S]=O,void k(null,{stack:b,id:S,glyph:O});const z=Math.floor(S/256);if(256*z>65535)return Br("glyphs > 65535 not supported"),void k(null,{stack:b,id:S,glyph:O});if(j.ranges[z])return void k(null,{stack:b,id:S,glyph:O});let U=j.requests[z];U||(U=j.requests[z]=[],this.glyphLoader.loadGlyphRange(b,z,y,this.requestManager,(q,K)=>{if(K){j.ascender=K.ascender,j.descender=K.descender;for(const Z in K.glyphs)this._doesCharSupportLocalGlyph(+Z)||(j.glyphs[+Z]=K.glyphs[+Z]);j.ranges[z]=!0}for(const Z of U)Z(q,K);delete j.requests[z]})),U.push((q,K)=>{q?k(q):K&&k(null,{stack:b,id:S,glyph:K.glyphs[S]||null})})},(b,S)=>{if(b)u(b);else if(S){const k={};for(const{stack:j,id:O,glyph:z}of S)k[j]===void 0&&(k[j]={}),k[j].glyphs===void 0&&(k[j].glyphs={}),k[j].glyphs[O]=z&&{id:z.id,bitmap:z.bitmap.clone(),metrics:z.metrics},k[j].ascender=this.entries[j].ascender,k[j].descender=this.entries[j].descender;u(null,k)}})}_doesCharSupportLocalGlyph(l){return this.localGlyphMode!==X5.none&&(this.localGlyphMode===X5.all?!!this.localFontFamily:!!this.localFontFamily&&(Dv(l)||RT(l)||Zx(l)||Pp(l)||Yx(l)||PT(l)||(u=l)>=131072&&u<=173791||(p=>p>=66736&&p<=66815)(l)));var u}_tinySDF(l,u,p){const y=this.localFontFamily;if(!y||!this._doesCharSupportLocalGlyph(p))return;let b=l.tinySDF;if(!b){let ne="400";/bold/i.test(u)?ne="900":/medium/i.test(u)?ne="500":/light/i.test(u)&&(ne="200"),b=l.tinySDF=new aP.TinySDF({fontFamily:y,fontWeight:ne,fontSize:48,buffer:6,radius:16}),b.fontWeight=ne}const S=b.fontWeight;if(this.localGlyphs[S][p])return this.localGlyphs[S][p];const k=String.fromCodePoint(p),{data:j,width:O,height:z,glyphWidth:U,glyphHeight:q,glyphLeft:K,glyphTop:Z,glyphAdvance:J}=b.draw(k);return this.localGlyphs[S][p]={id:p,bitmap:new Tg({width:O,height:z},j),metrics:{width:U/2,height:q/2,left:K/2,top:Z/2-27,advance:J/2,localGlyph:!0}}}}function yZ(h,l){return h+l[1]-l[0]}function Q5(h,l,u,p,y=1){const b=[],S=h.imagePrimary,k=S.pixelRatio,j=S.paddedRect.w-2,O=S.paddedRect.h-2,z=(h.right-h.left)*y,U=(h.bottom-h.top)*y,q=S.stretchX||[[0,j]],K=S.stretchY||[[0,O]],Z=q.reduce(yZ,0),J=K.reduce(yZ,0),ne=j-Z,ae=O-J;let he=0,ce=Z,ye=0,Ee=J,Ce=0,He=ne,$e=0,Ge=ae;if(S.content&&p){const Ve=S.content;he=oP(q,0,Ve[0]),ye=oP(K,0,Ve[1]),ce=oP(q,Ve[0],Ve[2]),Ee=oP(K,Ve[1],Ve[3]),Ce=Ve[0]-he,$e=Ve[1]-ye,He=Ve[2]-Ve[0]-ce,Ge=Ve[3]-Ve[1]-Ee}const Ue=(Ve,yt,bt,kt)=>{const It=lP(Ve.stretch-he,ce,z,h.left*y),Ct=cP(Ve.fixed-Ce,He,Ve.stretch,Z),Bt=lP(yt.stretch-ye,Ee,U,h.top*y),pt=cP(yt.fixed-$e,Ge,yt.stretch,J),jt=lP(bt.stretch-he,ce,z,h.left*y),Lt=cP(bt.fixed-Ce,He,bt.stretch,Z),$t=lP(kt.stretch-ye,Ee,U,h.top*y),Wt=cP(kt.fixed-$e,Ge,kt.stretch,J),xr=new Mt(It,Bt),ir=new Mt(jt,Bt),nr=new Mt(jt,$t),Kt=new Mt(It,$t),mr=new Mt(Ct/k,pt/k),kr=new Mt(Lt/k,Wt/k),zr=l*Math.PI/180;if(zr){const bn=Math.sin(zr),fs=Math.cos(zr),ri=[fs,-bn,bn,fs];xr._matMult(ri),ir._matMult(ri),Kt._matMult(ri),nr._matMult(ri)}const Rr=Ve.stretch+Ve.fixed,ln=bt.stretch+bt.fixed,zn=yt.stretch+yt.fixed,cn=kt.stretch+kt.fixed,Un=h.imageSecondary;return{tl:xr,tr:ir,bl:Kt,br:nr,texPrimary:{x:S.paddedRect.x+1+Rr,y:S.paddedRect.y+1+zn,w:ln-Rr,h:cn-zn},texSecondary:Un?{x:Un.paddedRect.x+1+Rr,y:Un.paddedRect.y+1+zn,w:ln-Rr,h:cn-zn}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:mr,pixelOffsetBR:kr,minFontScaleX:He/k/z,minFontScaleY:Ge/k/U,isSDF:u}};if(S.stretchX||S.stretchY){const Ve=xZ(q,ne,Z),yt=xZ(K,ae,J);for(let bt=0;bt0?[he,-ce]:ye<0?[-he,ce]:he===0?[ce,he]:[ce,-he]}(u);let K=Math.abs(l.top-l.bottom);for(const ae of l.positionedLines)K-=ae.lineOffset;const Z=l.positionedLines.length,J=K/Z;let ne=l.top-u[1];for(let ae=0;aeb)&&(b=Z.x),(!K||Z.y>S)&&(S=Z.y)}const j=Math.min(b-p,S-y);let O=j/2;const z=new Lx([],PCe);if(j===0)return new Mt(p,y);for(let K=p;KU.d||!U.d)&&(U=K,u&&console.log("found best %d after %d probes",Math.round(1e4*K.d)/1e4,q)),K.max-U.d<=l||(O=K.h/2,z.push(new db(K.p.x-O,K.p.y-O,O,h)),z.push(new db(K.p.x+O,K.p.y-O,O,h)),z.push(new db(K.p.x-O,K.p.y+O,O,h)),z.push(new db(K.p.x+O,K.p.y+O,O,h)),q+=4)}return u&&(console.log(`num probes: ${q}`),console.log(`best distance: ${U.d}`)),U.p}function PCe(h,l){return l.max-h.max}aP.TinySDF=class{constructor({fontSize:h=24,buffer:l=3,radius:u=8,cutoff:p=.25,fontFamily:y="sans-serif",fontWeight:b="normal",fontStyle:S="normal",lang:k=null}={}){this.buffer=l,this.cutoff=p,this.radius=u,this.lang=k;const j=this.size=h+4*l,O=this._createCanvas(j),z=this.ctx=O.getContext("2d",{willReadFrequently:!0});z.font=`${S} ${b} ${h}px ${y}`,z.textBaseline="alphabetic",z.textAlign="left",z.fillStyle="black",this.gridOuter=new Float64Array(j*j),this.gridInner=new Float64Array(j*j),this.f=new Float64Array(j),this.z=new Float64Array(j+1),this.v=new Uint16Array(j)}_createCanvas(h){const l=document.createElement("canvas");return l.width=l.height=h,l}draw(h){const{width:l,actualBoundingBoxAscent:u,actualBoundingBoxDescent:p,actualBoundingBoxLeft:y,actualBoundingBoxRight:b}=this.ctx.measureText(h),S=Math.ceil(u),k=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(b-y))),j=Math.min(this.size-this.buffer,S+Math.ceil(p)),O=k+2*this.buffer,z=j+2*this.buffer,U=Math.max(O*z,0),q=new Uint8ClampedArray(U),K={data:q,width:O,height:z,glyphWidth:k,glyphHeight:j,glyphTop:S,glyphLeft:0,glyphAdvance:l};if(k===0||j===0)return K;const{ctx:Z,buffer:J,gridInner:ne,gridOuter:ae}=this;this.lang&&(Z.lang=this.lang),Z.clearRect(J,J,k,j),Z.fillText(h,J,J+S);const he=Z.getImageData(J,J,k,j);ae.fill(zE,0,U),ne.fill(0,0,U);for(let ce=0;ce0?He*He:0,ne[Ce]=He<0?He*He:0}}mZ(ae,0,0,O,z,O,this.f,this.v,this.z),mZ(ne,J,J,k,j,O,this.f,this.v,this.z);for(let ce=0;ceb.y!=J.y>b.y&&b.x<(J.x-Z.x)*(b.y-Z.y)/(J.y-Z.y)+Z.x&&(k=!k),j=Math.min(j,Sd(b,Z,J))}}return(k?1:-1)*Math.sqrt(j)}(this.p,y),this.max=this.d+this.h*Math.SQRT2}}const NCe=Object.keys,J5=Number.POSITIVE_INFINITY,RCe=Math.sqrt(2);function Cg(h,l,u,p,y,b){const S=q5(h)&&h.collisionPadding?h.collisionPadding:[0,0,0,0],k={top:h.top-S[1],bottom:h.bottom+S[3],left:h.left-S[0],right:h.right+S[2],scaled:!1};return p!==void 0&&function(j,O){j.top*=O,j.bottom*=O,j.left*=O,j.right*=O,j.scaled=!0}(k,p),b&&(k.left+=b[0],k.right+=b[0],k.top+=b[1],k.bottom+=b[1]),u&&function(j,O,z){if(!O)return;const U=Kn(O),q=new Mt(z?z[0]:0,z?z[1]:0),K=new Mt(j.left,j.top),Z=new Mt(j.right,j.top),J=new Mt(j.left,j.bottom),ne=new Mt(j.right,j.bottom);K._rotateAround(U,q),Z._rotateAround(U,q),J._rotateAround(U,q),ne._rotateAround(U,q),j.left=Math.min(K.x,Z.x,J.x,ne.x),j.right=Math.max(K.x,Z.x,J.x,ne.x),j.top=Math.min(K.y,Z.y,J.y,ne.y),j.bottom=Math.max(K.y,Z.y,J.y,ne.y)}(k,u,y),l?{top:Math.min(l.top,k.top),bottom:Math.max(l.bottom,k.bottom),left:Math.min(l.left,k.left),right:Math.max(l.right,k.right),scaled:l.scaled||k.scaled}:k}function bZ(h,[l,u]){let p=0,y=0;if(u===J5){l<0&&(l=0);const b=l/RCe;switch(h){case"top-right":case"top-left":y=b-7;break;case"bottom-right":case"bottom-left":y=7-b;break;case"bottom":y=7-l;break;case"top":y=l-7}switch(h){case"top-right":case"bottom-right":p=-b;break;case"top-left":case"bottom-left":p=b;break;case"left":p=l;break;case"right":p=-l}}else{switch(l=Math.abs(l),u=Math.abs(u),h){case"top-right":case"top-left":case"top":y=u-7;break;case"bottom-right":case"bottom-left":case"bottom":y=7-u}switch(h){case"top-right":case"bottom-right":case"right":p=-l;break;case"top-left":case"bottom-left":case"left":p=l}}return[p,y]}function LCe(h,l,u,p,y,b,S,k,j,O,z,U,q,K,Z){const J=h.layers[0],ne=J.appearances;if(ne.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const ae={iconBBox:null,iconVerticalBBox:null},he={textBBox:null,textVerticalBBox:null},{baseIconRotate:ce,baseTextRotate:ye,iconScaleFactor:Ee}=function(He,$e,Ge){const Ue=He.get("icon-rotate").evaluate($e,{},Ge),Ve=He.get("text-rotate").evaluate($e,{},Ge),[yt,bt]=He.get("icon-size-scale-range");return{baseIconRotate:Ue,baseTextRotate:Ve,iconScaleFactor:fe(1,yt,bt)}}(p,y,b);l&&(ae.iconBBox=Cg(l,ae.iconBBox,ce),u)&&(ae.iconVerticalBBox=Cg(u,ae.iconVerticalBBox,ce+90));const Ce=dP(U.horizontal);Ce&&(he.textBBox=Cg(Ce,he.textBBox,ye,1,K)),U.vertical&&(he.textVerticalBBox=Cg(U.vertical,he.textVerticalBBox,ye+90,1,K));for(const He of ne)He.hasIconLayoutProperties()&&DCe(ae,h,J,He,y,b,k,ce,S,j,l,O,Ee,z,Z),He.hasTextLayoutProperties()&&OCe(he,J,He,y,b,K,ye,q,Ce,U.vertical);return{iconBBox:ae.iconBBox,iconVerticalBBox:ae.iconVerticalBBox,textBBox:he.textBBox,textVerticalBBox:he.textVerticalBBox}}function DCe(h,l,u,p,y,b,S,k,j,O,z,U,q,K,Z){const{appearanceIconOffset:J,appearanceIconRotate:ne,appearanceIconSize:ae}=wZ(p,u,y,b,S,k,j,O.iconScaleFactor);let he=null,ce=null,ye=null;p.hasLayoutProperty("icon-image")?ye=function(Ce,He,$e,Ge,Ue,Ve,yt,bt){let kt=null;const It=He.getAppearanceValueAndResolveTokens($e,"icon-image",Ge,Ue,bt);if(It){const Ct=Ce.getResolvedImageFromTokens(It),Bt=$e.hasLayoutProperty("icon-size")?$e.getUnevaluatedLayoutProperty("icon-size"):He._unevaluatedLayout._values["icon-size"],pt=$E(Ct,y_(Ce.zoom,Bt,Ce.worldview,bt),Bt,Ue,Ce.zoom,Ge,Ce.pixelRatio,yt,Ce.worldview,bt);kt=Ve.get(pt.iconPrimary.toString())}return kt}(l,u,p,y,b,U,q,Z):z&&(ye=z.imagePrimary),ye&&(he=iP(ye,null,J,K),l.allowVerticalPlacement&&(ce=iP(ye,null,J,K)));const Ee=j>0?ae/j:1;he&&(h.iconBBox=Cg(he,h.iconBBox,ne,Ee!==1?Ee:void 0)),ce&&(h.iconVerticalBBox=Cg(ce,h.iconVerticalBBox,ne+90,Ee!==1?Ee:void 0))}function wZ(h,l,u,p,y,b,S,k){const j=h.hasLayoutProperty("icon-offset")?l.getAppearanceValueAndResolveTokens(h,"icon-offset",u,p,[]):null,O=j&&Array.isArray(j)?j:y,z=h.hasLayoutProperty("icon-rotate")?l.getAppearanceValueAndResolveTokens(h,"icon-rotate",u,p,[]):null,U=typeof z=="number"?z:b,q=h.hasLayoutProperty("icon-size")?l.getAppearanceValueAndResolveTokens(h,"icon-size",u,p,[]):null;return{appearanceIconOffset:O,appearanceIconRotate:U,appearanceIconSize:typeof q=="number"?q*k:S}}function OCe(h,l,u,p,y,b,S,k,j,O){const{appearanceTextOffset:z,appearanceTextRotate:U,appearanceTextSize:q}=SZ(u,l,p,y,b,S,k),K=q/k,Z=[(z[0]-b[0])*K,(z[1]-b[1])*K],J=Z[0]!==0||Z[1]!==0;j&&(h.textBBox=Cg(j,h.textBBox,U,K,z,J?Z:void 0)),O&&(h.textVerticalBBox=Cg(O,h.textVerticalBBox,U+90,K,z,J?Z:void 0))}function SZ(h,l,u,p,y,b,S){const k=h.hasLayoutProperty("text-offset")?l.getAppearanceValueAndResolveTokens(h,"text-offset",u,p,[]):null,j=k&&Array.isArray(k)?[k[0]*Na,k[1]*Na]:y,O=h.hasLayoutProperty("text-rotate")?l.getAppearanceValueAndResolveTokens(h,"text-rotate",u,p,[]):null,z=typeof O=="number"?O:b,U=h.hasLayoutProperty("text-size")?l.getAppearanceValueAndResolveTokens(h,"text-size",u,p,[]):null;return{appearanceTextOffset:j,appearanceTextRotate:z,appearanceTextSize:typeof U=="number"?U:S}}function uP(h,l,u,p,y,b,S,k,j){if(!l||!l.usvg)return;const O=sZ(p),z=sZ(y),U=b!=="both"&&b!=="width"||!nZ(p)?1:z.width/O.width,q=b!=="both"&&b!=="height"||!iZ(p)?1:z.height/O.height;u.scaleSelf(U,q);const K=u.toString();S.set(K,u),k.set(K,l);const{imagePosition:Z}=Y5(K,l,1);j.set(K,Z)}function TZ(h,l,u,p,y,b,S,k,j,O){if(!h)return;const z=function(U,q,K,Z,J,ne,ae){if(U.kind==="camera")return U.maxSize;if(U.kind==="composite"){const he=q.possiblyEvaluate(new ti(U.maxZoom,{worldview:ne}),K,ae).evaluate(J,{},K,ae),ce=q.possiblyEvaluate(new ti(U.minZoom,{worldview:ne}),K,ae).evaluate(J,{},K,ae);return Math.max(he,ce)}return q.possiblyEvaluate(new ti(Z,{worldview:ne}),K,ae).evaluate(J,{},K,ae)}(l,u,p,y,b,j,O);return h.scaleSelf(z*k*S)}function $E(h,l,u,p,y,b,S,k,j,O){return{iconPrimary:TZ(h.getPrimary(),l,u,p,y,b,S,k,j,O),iconSecondary:TZ(h.getSecondary(),l,u,p,y,b,S,k,j,O)}}function MCe(h,l,u){if(!l)return;const p=u.get(h.toString()),y=u.get(l.toString());p&&y&&(p.paddedRect.w===y.paddedRect.w&&p.paddedRect.h===y.paddedRect.h||Br(`Mismatch in icon variant sizes: ${h.toString()} and ${l.toString()}`),p.usvg!==y.usvg&&Br(`Mismatch in icon variant image types: ${h.id} and ${l.id}`))}function EZ(h,l,u,p){if(!h)return;const y=l.get(u.toString());if(y&&(h.imagePrimary=y),p){const b=l.get(p.toString());h.imageSecondary=b}}function FCe(h,l){for(const u in h.horizontal)AZ(h.horizontal[u],l);AZ(h.vertical,l)}function AZ(h,l){if(h){for(const u of h.positionedLines)for(const p of u.positionedGlyphs)if(p.image!==null){const y=p.image.toString();p.rect=l.get(y).paddedRect}}}function e4(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"}function BCe(h,l,u,p,y,b,S,k,j){const O=dP(b.horizontal)||b.vertical,z=u.get("icon-text-fit-padding").evaluate(p,{},y);let U,q=l;return l&&j!=="none"&&(h.allowVerticalPlacement&&b.vertical&&(U=G5(l,b.vertical,j,z,k,S)),O&&(q=G5(l,O,j,z,k,S))),{defaultShapedIcon:q,verticallyShapedIcon:U}}function kZ(h,l){return h*l/24}function zCe(h,l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne,ae,he,ce,ye,Ee,Ce,He){let $e=S.textMaxSize.evaluate(l,{},q);$e===void 0?$e=k*S.textScaleFactor:$e*=S.textScaleFactor;const Ge=h.layers[0].layout,Ue=kZ(k,S.textScaleFactor),Ve=dP(u.horizontal)||u.vertical,yt=h.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),bt=h.getAppearanceFeatureData(l.index);(ne!=="none"||yt)&&bt&&(bt.textShaping=Ve,bt.iconTextFitPadding=Ge.get("icon-text-fit-padding").evaluate(l,{},q),bt.fontScale=Ue,bt.textScaleFactor=S.textScaleFactor);const kt=K.name==="globe",It=h.tilePixelRatio*$e/24,Ct=(Wt=h.overscaling,h.zoom>18&&Wt>2&&(Wt>>=1),Math.max(ar/(512*Wt),1)*Ge.get("symbol-spacing")),Bt=Ge.get("text-padding")*h.tilePixelRatio,pt=Ge.get("icon-padding")*h.tilePixelRatio,jt=Kn(Ge.get("text-max-angle")),Lt=Ge.get("icon-rotation-alignment")==="map"&&ce!=="point",$t=Ct/2;var Wt;h.hasAnyIconTextFit===!1&&ne!=="none"&&(h.hasAnyIconTextFit=!0);const xr=l.properties?+l.properties[mn]:null,ir=xr&&h.elevationFeatureIdToIndex?h.elevationFeatureIdToIndex.get(xr):65535,nr=(Kt,mr,kr)=>{if(mr.x<0||mr.x>=ar||mr.y<0||mr.y>=ar)return;let zr=null;if(kt){const{x:Rr,y:ln,z:zn}=K.projectTilePoint(mr.x,mr.y,kr);zr={anchor:new Gp(Rr,ln,zn,0,void 0),up:K.upVector(kr,mr.x,mr.y)}}(function(Rr,ln,zn,cn,Un,bn,fs,ri,Gn,Ai,os,Ra,ls,vs,qs,bs,vo,La,Tn,yl,Ps,Ga,xl,bo,ps,Xo,Ha,jP,_b,Ll,T4,vb){const Hp=Rr.addToLineVertexArray(ln,cn);let Wp,Bu,zu,S_,bb,Cn,Wa,ws=0,ba=0,$u=0,Pc=0,Nc=-1,Rc=-1;const Ad={};let IP=af("");const wh=zn?zn.anchor:ln,wb=jP!=="none";let Sb=0,ca=0;if(Gn._unevaluatedLayout.getValue("text-radial-offset")===void 0){const Ns=Gn.layout.get("text-offset").evaluate(Ps,{},ps);Sb=Ns[0]*Na,ca=Ns[1]*Na}else Sb=Gn.layout.get("text-radial-offset").evaluate(Ps,{},ps)*Na,ca=J5;if(Rr.allowVerticalPlacement&&Un.vertical){const Ns=Un.vertical;if(qs)Cn=n4(Ns),ri&&(Wa=n4(ri));else{const _l=Gn.layout.get("text-rotate").evaluate(Ps,{},ps)+90;zu=hP(Ai,wh,ln,os,Ra,ls,Ns,vs,_l,bs,vb),ri&&(S_=hP(Ai,wh,ln,os,Ra,ls,ri,La,_l,null,T4))}}if(bn){const Ns=Gn.layout.get("icon-rotate").evaluate(Ps,{},ps),_l=Q5(bn,Ns,xl,wb,Ga.iconScaleFactor),Dl=ri?Q5(ri,Ns,xl,wb,Ga.iconScaleFactor):void 0;Bu=hP(Ai,wh,ln,os,Ra,ls,bn,La,Ns,null,Ll);const Cd=function(Sh,r2,Tb,tIe,rIe,KX,YX,nIe,z$t,A4){const ZX=Sh.layers[0],XX=ZX.appearances;let Eb=r2.length;if(Tb&&(Eb=Math.max(Eb,Tb.length)),XX.length===0)return Eb;const[iIe,sIe]=tIe.get("icon-size-scale-range"),aIe=fe(1,iIe,sIe);for(const LP of XX)if(LP.hasLayoutProperty("icon-image")){const QX=ZX.getAppearanceValueAndResolveTokens(LP,"icon-image",KX,YX,A4);if(QX){const JX=Sh.getResolvedImageFromTokens(QX);if(JX){const eQ=LP.hasLayoutProperty("icon-size")?LP.getUnevaluatedLayoutProperty("icon-size"):rIe._values["icon-size"],oIe=$E(JX,y_(Sh.zoom,eQ,Sh.worldview,A4),eQ,YX,Sh.zoom,KX,Sh.pixelRatio,aIe,Sh.worldview,A4),tQ=nIe.get(oIe.iconPrimary.toString());tQ&&(Eb=Math.max(Eb,CCe(tQ)))}}}return Eb}(Rr,_l,Dl,Gn.layout,Gn._unevaluatedLayout,Ps,ps,Rr.iconAtlasPositions,0,bo);ws=4*Cd;const PP=Gn.layout.get("icon-size").evaluate(Ps,{},ps,bo),NP=Ga.compositeIconSizes?Ga.compositeIconSizes[0].evaluate(Ps,{},ps,bo):0,E4=Ga.compositeIconSizes?Ga.compositeIconSizes[1].evaluate(Ps,{},ps,bo):0,RP=r4(Rr.layerIds[0],Rr.iconSizeData,PP,Ga.iconScaleFactor,NP,E4);Rr.addSymbols(Rr.icon,_l,RP,yl,Tn,Ps,void 0,zn,ln,Hp.lineStartIndex,Hp.lineLength,-1,bo,ps,Xo,Ha,Rr.symbolInstances.length,Cd),Nc=Rr.icon.placedSymbolArray.length-1,Dl&&(ba=4*Cd,Rr.addSymbols(Rr.icon,Dl,RP,yl,Tn,Ps,Ic.vertical,zn,ln,Hp.lineStartIndex,Hp.lineLength,-1,bo,ps,Xo,Ha,Rr.symbolInstances.length,Cd),Rc=Rr.icon.placedSymbolArray.length-1)}for(const Ns in Un.horizontal){const _l=Ns,Dl=Un.horizontal[_l];Wp||(IP=af(Dl.text),qs?bb=n4(Dl):Wp=hP(Ai,wh,ln,os,Ra,ls,Dl,vs,Gn.layout.get("text-rotate").evaluate(Ps,{},ps),bs,vb));const Cd=Dl.positionedLines.length===1;if($u+=CZ(Rr,zn,ln,Dl,fs,Gn,qs,Ps,bs,Hp,Un.vertical?Ic.horizontal:Ic.horizontalOnly,Cd?NCe(Un.horizontal):[_l],Ad,Nc,Ga,bo,ps,Rr.symbolInstances.length,Xo),Cd)break}Un.vertical&&(Pc+=CZ(Rr,zn,ln,Un.vertical,fs,Gn,qs,Ps,bs,Hp,Ic.vertical,["vertical"],Ad,Rc,Ga,bo,ps,Rr.symbolInstances.length,Xo));let Qs=-1;const wa=(Ns,_l)=>Ns?Math.max(Ns,_l):_l;Qs=wa(bb,Qs),Qs=wa(Cn,Qs),Qs=wa(Wa,Qs);const kd=Qs>-1?1:0;Rr.glyphOffsetArray.length>=65535&&Br("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),Ps.sortKey!==void 0&&Rr.addToSortKeyRanges(Rr.symbolInstances.length,Ps.sortKey),Rr.symbolInstances.emplaceBack(ln.x,ln.y,wh.x,wh.y,wh.z,Ad.right>=0?Ad.right:-1,Ad.center>=0?Ad.center:-1,Ad.left>=0?Ad.left:-1,Ad.vertical>=0?Ad.vertical:-1,Nc,Rc,IP,Wp!==void 0?Wp:Rr.collisionBoxArray.length,Wp!==void 0?Wp+1:Rr.collisionBoxArray.length,zu!==void 0?zu:Rr.collisionBoxArray.length,zu!==void 0?zu+1:Rr.collisionBoxArray.length,Bu!==void 0?Bu:Rr.collisionBoxArray.length,Bu!==void 0?Bu+1:Rr.collisionBoxArray.length,S_||Rr.collisionBoxArray.length,S_?S_+1:Rr.collisionBoxArray.length,os,$u,Pc,ws,ba,kd,0,Sb,ca,Qs,0,wb?1:0,_b)})(h,mr,zr,Kt,u,p,b,y,h.layers[0],h.collisionBoxArray,l.index,l.sourceLayerIndex,h.index,Bt,he,O,0,pt,Lt,ae,l,S,z,U,q,Z,J,ne,ir,ye,Ee,Ce)};if(ce==="line")for(const Kt of GI(l.geometry,0,0,ar,ar)){const mr=kCe(Kt,Ct,jt,u.vertical||Ve,p,24,It,h.overscaling,ar);for(const kr of mr)Ve&&$Ce(h,Ve.text,$t,kr)||nr(Kt,kr,q)}else if(ce==="line-center"){for(const Kt of l.geometry)if(Kt.length>1){const mr=ACe(Kt,jt,u.vertical||Ve,p,24,It);mr&&nr(Kt,mr,q)}}else if(l.type==="Polygon")for(const Kt of SE(l.geometry,0)){const mr=ICe(Kt,16);nr(Kt[0],new Gp(mr.x,mr.y,0,0,void 0),q)}else if(l.type==="LineString")for(const Kt of l.geometry)nr(Kt,new Gp(Kt[0].x,Kt[0].y,0,0,void 0),q);else if(l.type==="Point")for(const Kt of l.geometry)for(const mr of Kt)nr([mr],new Gp(mr.x,mr.y,0,0,void 0),q)}const t4=255,x_=t4*qp;function CZ(h,l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne,ae,he){const ce=vZ(0,p,j,b,S,k,y,h.allowVerticalPlacement,void 0,Z.textScaleFactor),ye=b.layout.get("text-size").evaluate(k,{},ne),Ee=Z.compositeTextSizes?Z.compositeTextSizes[0].evaluate(k,{},ne):0,Ce=Z.compositeTextSizes?Z.compositeTextSizes[1].evaluate(k,{},ne):0,He=r4(h.layerIds[0],h.textSizeData,ye,Z.textScaleFactor,Ee,Ce);h.addSymbols(h.text,ce,He,j,S,k,z,l,u,O.lineStartIndex,O.lineLength,K,J,ne,he,!1,ae,ce.length);for(const $e of U)q[$e]=h.text.placedSymbolArray.length-1;return 4*ce.length}function r4(h,l,u,p,y,b){const S=l;let k=null;return S.kind==="source"?(k=[qp*u*p],k[0]>x_&&Br(`${h}: Value for "text-size" is >= ${t4}. Reduce your "text-size".`)):S.kind==="composite"&&(k=[qp*y*p,qp*b*p],(k[0]>x_||k[1]>x_)&&Br(`${h}: Value for "text-size" is >= ${t4}. Reduce your "text-size".`)),k}function dP(h){for(const l in h)return h[l];return null}function hP(h,l,u,p,y,b,S,k,j,O,z){let U,q,K,Z;if(U=z?z.top:S.top,q=z?z.bottom:S.bottom,K=z?z.left:S.left,Z=z?z.right:S.right,q5(S)&&S.collisionPadding){const J=S.collisionPadding;K-=J[0],U-=J[1],Z+=J[2],q+=J[3]}if(j){const J=new Mt(K,U),ne=new Mt(Z,U),ae=new Mt(K,q),he=new Mt(Z,q),ce=Kn(j);let ye=new Mt(0,0);O&&(ye=new Mt(O[0],O[1])),J._rotateAround(ce,ye),ne._rotateAround(ce,ye),ae._rotateAround(ce,ye),he._rotateAround(ce,ye),K=Math.min(J.x,ne.x,ae.x,he.x),Z=Math.max(J.x,ne.x,ae.x,he.x),U=Math.min(J.y,ne.y,ae.y,he.y),q=Math.max(J.y,ne.y,ae.y,he.y)}return h.emplaceBack(l.x,l.y,l.z,u.x,u.y,K,U,Z,q,k,p,y,b),h.length-1}function n4(h){q5(h)&&h.collisionPadding&&(h.top-=h.collisionPadding[1],h.bottom+=h.collisionPadding[3]);const l=h.bottom-h.top;return l>0?Math.max(10,l):null}function $Ce(h,l,u,p){const y=h.compareText;if(l in y){const b=y[l];for(let S=b.length-1;S>=0;S--)if(p.dist(b[S])ce&&(ye(Ce,kt,$e,Ge,yt,bt),ye(kt,He,yt,bt,Ue,Ve))}ye(U,q,p,b,y,b),ye(q,K,y,b,y,S),ye(K,Z,y,S,p,S),ye(Z,U,p,S,p,b),J-=ce,ne-=ce,ae+=ce,he+=ce;const Ee=1/Math.max(ae-J,he-ne);return{scale:Ee,x:J*Ee,y:ne*Ee,x2:ae*Ee,y2:he*Ee,projection:l}}function IZ(h,{x:l,y:u},p=0){return new Mt(((l-p)*h.scale-h.x)*ar,(u*h.scale-h.y)*ar)}const UCe=R(new Float32Array(16));class jg{constructor(l){this.spec=l,this.name=l.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(l,u){return{x:0,y:0,z:0}}unproject(l,u){return new Qe(0,0)}projectTilePoint(l,u,p){return{x:l,y:u,z:0}}locationPoint(l,u,p,y=!0){return l._coordinatePoint(l.locationCoordinate(u,p),y)}pixelsPerMeter(l,u){return ot(1,l)*u}pixelSpaceConversion(l,u,p){return 1}farthestPixelDistance(l){return jZ(l,l.pixelsPerMeter)}pointCoordinate(l,u,p,y){const b=l.horizonLineFromTop(!1),S=new Mt(u,Math.max(b,p));return l.rayIntersectionCoordinate(l.pointRayIntersection(S,y))}pointCoordinate3D(l,u,p){const y=new Mt(u,p);if(l.elevation)return l.elevation.pointCoordinate(y);{const b=this.pointCoordinate(l,y.x,y.y,0);return[b.x,b.y,b.z]}}isPointAboveHorizon(l,u){if(l.elevation&&l.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(l,u.x,u.y);const p=l.horizonLineFromTop();return u.y0?u<-hb+p&&(u=-hb+p):u>hb-p&&(u=hb-p);const S=b/Math.pow(pP(u),y);let k=S*Math.sin(y*l),j=b-S*Math.cos(y*l);return k=.5*(k/Math.PI+.5),j=.5*(j/Math.PI+.5),{x:k,y:this.southernCenter?j:1-j,z:0}}unproject(l,u){l=(2*l-.5)*Math.PI,this.southernCenter&&(u=1-u),u=(2*(1-u)-.5)*Math.PI;const{n:p,f:y}=this,b=y-u,S=Math.sign(b),k=Math.sign(p)*Math.sqrt(l*l+b*b);let j=Math.atan2(l,Math.abs(b))*S;b*p<0&&(j-=Math.PI*Math.sign(l)*S);const O=fe(ao(j/p)+this.center[0],-180,180),z=fe(ao(2*Math.atan(Math.pow(y/k,1/p))-hb),-85.051129,St);return new Qe(O,this.southernCenter?-z:z)}}class PZ extends jg{constructor(l){super(l),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(l,u){return{x:Rt(l),y:Ft(u),z:0}}unproject(l,u){const p=et(l),y=gt(u);return new Qe(p,y)}}const NZ=Kn(St);class WCe extends jg{project(l,u){const p=(u=Kn(u))*u,y=p*p;return{x:.5*((l=Kn(l))*(.8707-.131979*p+y*(y*(.003971*p-.001529*y)-.013791))/Math.PI+.5),y:1-.5*(u*(1.007226+p*(.015085+y*(.028874*p-.044475-.005916*y)))/Math.PI+1),z:0}}unproject(l,u){l=(2*l-.5)*Math.PI;let p=u=(2*(1-u)-1)*Math.PI,y=25,b=0,S=p*p;do{S=p*p;const O=S*S;b=(p*(1.007226+S*(.015085+O*(.028874*S-.044475-.005916*O)))-u)/(1.007226+S*(.045255+O*(.259866*S-.311325-.005916*11*O))),p=fe(p-b,-NZ,NZ)}while(Math.abs(b)>1e-6&&--y>0);S=p*p;const k=fe(ao(l/(.8707+S*(S*(S*S*S*(.003971-.001529*S)-.013791)-.131979))),-180,180),j=ao(p);return new Qe(k,j)}}const RZ=Kn(St);class KCe extends jg{project(l,u){u=Kn(u),l=Kn(l);const p=Math.cos(u),y=2/Math.PI,b=Math.acos(p*Math.cos(l/2)),S=Math.sin(b)/b,k=.5*(l*y+2*p*Math.sin(l/2)/S)||0,j=.5*(u+Math.sin(u)/S)||0;return{x:.5*(k/Math.PI+.5),y:1-.5*(j/Math.PI+1),z:0}}unproject(l,u){let p=l=(2*l-.5)*Math.PI,y=u=(2*(1-u)-1)*Math.PI,b=25;const S=1e-6;let k=0,j=0;do{const O=Math.cos(y),z=Math.sin(y),U=2*z*O,q=z*z,K=O*O,Z=Math.cos(p/2),J=Math.sin(p/2),ne=2*Z*J,ae=J*J,he=1-K*Z*Z,ce=he?1/he:0,ye=he?Math.acos(O*Z)*Math.sqrt(1/he):0,Ee=.5*(2*ye*O*J+2*p/Math.PI)-l,Ce=.5*(ye*z+y)-u,He=.5*ce*(K*ae+ye*O*Z*q)+1/Math.PI,$e=ce*(ne*U/4-ye*z*J),Ge=.125*ce*(U*J-ye*z*K*ne),Ue=.5*ce*(q*Z+ye*ae*O)+.5,Ve=$e*Ge-Ue*He;k=(Ce*$e-Ee*Ue)/Ve,j=(Ee*Ge-Ce*He)/Ve,p=fe(p-k,-Math.PI,Math.PI),y=fe(y-j,-RZ,RZ)}while((Math.abs(k)>S||Math.abs(j)>S)&&--b>0);return new Qe(ao(p),ao(y))}}class LZ extends jg{constructor(l){super(l),this.center=l.center||[0,0],this.parallels=l.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Kn(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(l,u){const{scale:p,cosPhi:y}=this;return{x:Kn(l)*y*p+.5,y:-Math.sin(Kn(u))/y*p+.5,z:0}}unproject(l,u){const{scale:p,cosPhi:y}=this,b=-(u-.5)/p,S=fe(ao((l-.5)/p)/y,-180,180),k=Math.asin(fe(b*y,-1,1)),j=fe(ao(k),-85.051129,St);return new Qe(S,j)}}class YCe extends PZ{constructor(l){super(l),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(l,u,p){const y=gE(l,u,p);return or(y,y,yE(vf(p))),{x:y[0],y:y[1],z:y[2]}}locationPoint(l,u,p){const y=Fe(u.lat,u.lng),b=mt([],y),S=p?l._centerAltitude+p:l.elevation?l.elevation.getAtPointOrZero(l.locationCoordinate(u),l._centerAltitude):l._centerAltitude;rt(y,y,b,ot(1,0)*ar*S);const k=R(new Float64Array(16));return M(k,l.pixelMatrix,l.globeMatrix),or(y,y,k),new Mt(y[0],y[1])}pixelsPerMeter(l,u){return ot(1,0)*u}pixelSpaceConversion(l,u,p){const y=ot(1,l)*u,b=Xr(ot(1,45)*u,y,p);return this.pixelsPerMeter(l,u)/b}createTileMatrix(l,u,p){const y=X3(vf(p.canonical));return M(new Float64Array(16),l.globeMatrix,y)}createInversionMatrix(l,u){const{center:p}=l,y=yE(vf(u));return W(y,y,Kn(p.lng)),G(y,y,Kn(p.lat)),V(y,y,[l._pixelsPerMercatorPixel,l._pixelsPerMercatorPixel,1]),Float32Array.from(y)}pointCoordinate(l,u,p,y){return ZW(l,u,p,!0)||new Ar(0,0)}pointCoordinate3D(l,u,p){const y=this.pointCoordinate(l,u,p,0);return[y.x,y.y,y.z]}isPointAboveHorizon(l,u){return!ZW(l,u.x,u.y,!1)}farthestPixelDistance(l){const u=function(y,b){const S=y.cameraToCenterDistance,k=y._centerAltitude*b,j=y._camera,O=y._camera.forward(),z=ge([],We([],O,-S),[0,0,k]),U=y.worldSize/(2*Math.PI),q=[0,0,-U],K=y.width/y.height,Z=Math.tan(y.fovAboveCenter),J=We([],j.up(),Z),ne=We([],j.right(),Z*K),ae=mt([],ge([],ge([],O,J),ne)),he=[];let ce;if(new jn(z,ae).closestPointOnSphere(q,U,he)){const ye=ge([],he,q),Ee=tr([],ye,z);ce=Math.cos(y.fovAboveCenter)*Oe(Ee)}else{const ye=tr([],z,q),Ee=tr([],q,z);mt(Ee,Ee);const Ce=Oe(ye)-U;ce=Math.sqrt(Ce*(Ce+2*U));const He=Math.acos(ce/(U+Ce))-Math.acos(Pt(O,Ee));ce*=Math.cos(He)}return 1.01*ce}(l,this.pixelsPerMeter(l.center.lat,l.worldSize)),p=$p(l.zoom);if(p>0){const y=jZ(l,ot(1,l.center.lat)*l.worldSize),b=l.worldSize/(2*Math.PI),S=Math.max(l.width,l.height)/l.worldSize*Math.PI;return Xr(u,y+b*(1-Math.cos(S)),Math.pow(p,10))}return u}upVector(l,u,p){return gE(u,p,l,1)}upVectorScale(l){return{metersToTile:kI(jI(vf(l)))}}}function DZ(h){const l=h.parallels,u=!!l&&Math.abs(l[0]+l[1])<.01;switch(h.name){case"mercator":return new PZ(h);case"equirectangular":return new GCe(h);case"naturalEarth":return new WCe(h);case"equalEarth":return new qCe(h);case"winkelTripel":return new KCe(h);case"albers":return u?new LZ(h):new VCe(h);case"lambertConformalConic":return u?new LZ(h):new HCe(h);case"globe":return new YCe(h)}throw new Error(`Invalid projection name: ${h.name}`)}class ZCe{constructor(l,u){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=u,this.appearances=l;const p=l.map(y=>function(b){if(!b.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const S=b.condition.expression;return{featureDependent:!kp(S),stateDependent:!lg(S),zoomDependent:!yd(S,["zoom"]),pitchDependent:!yd(S,["pitch"]),brightnessDependent:!yd(S,["brightness","measure-light"]),worldviewDependent:!yd(S,["worldview"])}}(y));this.anyFeatureDependent=p.some(y=>y.featureDependent),this.anyStateDependent=p.some(y=>y.stateDependent)}update(l,u){const p=this.lastParams,y=!p||p.zoom!==l.zoom||p.pitch!==(l.pitch||0)||p.brightness!==(l.brightness||0)||p.worldview!==l.worldview;this.lastParams={zoom:l.zoom,pitch:l.pitch||0,brightness:l.brightness||0,worldview:l.worldview};const b=u&&this.anyStateDependent;if(!y&&!b&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!b){const S=this.evaluateAllFeatures(l);return S===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=S,{kind:"all-features",appearanceIndex:S})}return{kind:"per-feature"}}evaluateAllFeatures(l){for(let u=0;u{for(let y=0;yS-k),b=new Map;for(const S of y){const k=p.get(S);b.set(S,new Si(k))}return u&&(this.cachedBatchIndices=y,this.cachedBatchSegments=b),{batchIndices:y,batchSegments:b}}snapshotSymbolVertexData(l,u){const p=l*pb;return this.layoutVertexArray.uint16.slice(p,p+u*pb)}restoreSymbolVertexData(l,u){this.layoutVertexArray.uint16.set(u,l*pb)}updateSymbolVertexData(l,u,p,y,b,S,k,j,O,z,U,q,K){const Z=this.layoutVertexArray.uint16,J=l*pb;Z[J]=u,Z[J+1]=p,Z[J+2]=y,Z[J+3]=b,Z[J+4]=S,Z[J+5]=k,Z[J+6]=j,Z[J+7]=O,Z[J+8]=z,Z[J+9]=U,Z[J+10]=q,Z[J+11]=K}upload(l,u,p,y,b,S){this.isEmpty()||(p&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,Jke.members,!!S),this.indexBuffer=l.createIndexBuffer(this.indexArray,u),this.dynamicLayoutVertexBuffer=l.createVertexBuffer(this.dynamicLayoutVertexArray,tCe.members,!0),this.opacityVertexBuffer=l.createVertexBuffer(this.opacityVertexArray,QCe,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=l.createVertexBuffer(this.iconTransitioningVertexArray,sCe.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=l.createVertexBuffer(this.globeExtVertexArray,eCe.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||b)&&(this.zOffsetVertexBuffer=l.createVertexBuffer(this.zOffsetVertexArray,rCe.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=l.createVertexBuffer(this.orientationVertexArray,iCe.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=l.createVertexBuffer(this.featureIdArray,nCe.members,!1))),(p||y)&&(this.programConfigurations.upload(l),this.uboBinder&&this.uboBinder.upload(l)))}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.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(i4,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class s4{constructor(l,u,p){this.layoutVertexArray=new l,this.layoutAttributes=u,this.indexArray=new p,this.segments=new Si,this.collisionVertexArray=new i_,this.collisionVertexArrayExt=new mh}upload(l){this.layoutVertexBuffer=l.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=l.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=l.createVertexBuffer(this.collisionVertexArray,aCe.members,!0),this.collisionVertexBufferExt=l.createVertexBuffer(this.collisionVertexArrayExt,oCe.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}vr(s4,"CollisionBuffers");class _h{constructor(l){this.collisionBoxArray=l.collisionBoxArray,this.zoom=l.zoom,this.overscaling=l.overscaling,this.layers=l.layers,this.layerIds=this.layers.map(S=>S.fqid),this.index=l.index,this.pixelRatio=l.pixelRatio,this.sourceLayerIndex=l.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=R([]),this.placementViewportMatrix=R([]);const u=this.layers[0]._unevaluatedLayout._values;this.worldview=l.worldview,this.localizable=l.localizable,this.maxUniformBufferBindings=l.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=l.maxUniformBlockSizeDwords,this.disableSymbolUBO=l.disableSymbolUBO,this.textSizeData=y_(this.zoom,u["text-size"],this.worldview,l.availableImages),this.iconSizeData=y_(this.zoom,u["icon-size"],this.worldview,l.availableImages);const p=this.layers[0].layout,y=p.get("symbol-sort-key"),b=p.get("symbol-z-order");this.lut=l.lut,this.canOverlap=p.get("text-allow-overlap")||p.get("icon-allow-overlap")||p.get("text-ignore-placement")||p.get("icon-ignore-placement"),this.sortFeaturesByKey=b!=="viewport-y"&&y.constantOr(1)!==void 0,this.sortFeaturesByY=(b==="viewport-y"||b==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=p.get("text-writing-mode").map(S=>Ic[S]),this.stateDependentLayerIds=this.layers.filter(S=>S.isStateDependent()).map(S=>S.id),this.sourceID=l.sourceID,this.projection=l.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.elevationStateComplete=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(l){const u=this.layers[0].getAppearances();if(!u||u.length===0)return!1;const p=Array.isArray(l)?l:[l];return u.some(y=>p.some(b=>y.hasLayoutProperty(b)))}getAppearanceFeatureData(l){return this.featureAppearanceData.get(l)}createArrays(){this.text=new i4(new ie(this.layers,{zoom:this.zoom,lut:this.lut},l=>l.startsWith("text")||l.startsWith("symbol"))),this.icon=new i4(new ie(this.layers,{zoom:this.zoom,lut:this.lut},l=>l.startsWith("icon")||l.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new z5(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new z5(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new bI,this.lineVertexArray=new o_,this.symbolInstances=new vI}calculateGlyphDependencies(l,u,p,y,b){for(const S of l){const k=S.codePointAt(0);if(k===void 0)break;if(u[k]=!0,y&&b&&k<=65535){const j=OE[S];j&&(u[j.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(l,u,p,y,b,S,k){if(!l.hasLayoutProperty("icon-size"))return k*S;let j=1;const O=l.getUnevaluatedLayoutProperty("icon-size"),z=y_(this.zoom,O,this.worldview,b),U=ub(z,u);if(z.kind!=="constant"&&z.kind!=="camera"||(j=U.uSize),z.kind==="composite"){const{minZoom:q,maxZoom:K}=z,Z=O.possiblyEvaluate(new ti(q,{worldview:this.worldview}),y),J=O.possiblyEvaluate(new ti(K,{worldview:this.worldview}),y),ne=Z.evaluate(p,{},y,b);j=ne+(J.evaluate(p,{},y,b)-ne)*U.uSizeT}return z.kind==="source"&&(j=O.possiblyEvaluate(new ti(this.zoom,{worldview:this.worldview}),y).evaluate(p,{},y,b)),j*S}updateFootprints(l,u){}updateReplacement(l,u){if(u.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=u.updateTime;const p=u.getReplacementRegionsForTile(l.toUnwrapped(),!0);return!BI(this.activeReplacements,p)&&(this.activeReplacements=p,!0)}getResolvedImageFromTokens(l){return typeof l=="string"?Nl.build(l):l}populate(l,u,p,y){const b=this.layers[0],S=b.layout,k=this.projection.name==="globe",j=S.get("text-font"),O=S.get("text-field"),z=S.get("icon-image"),[U,q]=S.get("icon-size-scale-range"),K=fe(u.scaleFactor||1,U,q),[Z,J]=S.get("text-size-scale-range"),ne=fe(u.scaleFactor||1,Z,J),ae=(O.value.kind!=="constant"||O.value.value instanceof No&&!O.value.value.isEmpty()||O.value.value.toString().length>0)&&(j.value.kind!=="constant"||j.value.value.length>0),he=z.value.kind!=="constant"||!!z.value.value||Object.keys(z.parameters).length>0,ce=this.hasAnyAppearanceLayoutProperty("icon-image"),ye=S.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!ae&&!he&&!ce)return;const Ee=u.iconDependencies,Ce=u.glyphDependencies,He=u.availableImages,$e=new ti(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),Ge=Ue=>{const Ve=Ue.id.toString();Ee.has(Ve)?Ee.get(Ve).push(Ue):Ee.set(Ve,[Ue])};for(const Ue of l){const{feature:Ve,id:yt,index:bt,sourceLayerIndex:kt}=Ue,It=b._featureFilter.needGeometry,Ct=vn(Ve,It);if(!b._featureFilter.filter($e,Ct,p))continue;if(It||(Ct.geometry=$r(Ve,p,y)),k&&Ve.type!==1&&p.z<=5){const ir=Ct.geometry,nr=.98078528056,Kt=(mr,kr)=>Pt(gE(mr.x,mr.y,p,1),gE(kr.x,kr.y,p,1)){if(!ir.getLayoutProperty("icon-image"))return;const nr=this.getCombinedIconPrimary(ir,jt,Ct,p,He,Wt,K);nr&&Ge(nr)}),Bt){const ir=j.evaluate(Ct,{},p).join(","),nr=S.get("text-rotation-alignment")==="map"&&S.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(Ic.vertical)>=0;for(const Kt of Bt.sections)if(Kt.image){const mr=Kt.image.getPrimary().scaleSelf(this.pixelRatio*ne),kr=mr.id.toString(),zr=Ee.get(kr)||[];zr.push(mr),Ee.set(kr,zr)}else{const mr=FT(Bt.toString()),kr=Kt.fontStack||ir,zr=Ce[kr]=Ce[kr]||{};this.calculateGlyphDependencies(Kt.text,zr,nr,this.allowVerticalPlacement,mr)}}}if(S.get("symbol-placement")==="line"&&(this.features=function(Ue){const Ve={},yt={},bt=[];let kt=0;function It(jt){bt.push(Ue[jt]),kt++}function Ct(jt,Lt,$t){const Wt=yt[jt];return delete yt[jt],yt[Lt]=Wt,bt[Wt].geometry[0].pop(),bt[Wt].geometry[0]=bt[Wt].geometry[0].concat($t[0]),Wt}function Bt(jt,Lt,$t){const Wt=Ve[Lt];return delete Ve[Lt],Ve[jt]=Wt,bt[Wt].geometry[0].shift(),bt[Wt].geometry[0]=$t[0].concat(bt[Wt].geometry[0]),Wt}function pt(jt,Lt,$t){const Wt=$t?Lt[0][Lt[0].length-1]:Lt[0][0];return`${jt}:${Wt.x}:${Wt.y}`}for(let jt=0;jtjt.geometry)}(this.features)),S.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",u.elevationFeatures){!this.elevationFeatures&&u.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const Ue of u.elevationFeatures)this.elevationFeatureIdToIndex.set(Ue.id,this.elevationFeatures.length),this.elevationFeatures.push(Ue)}}else S.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Ue,Ve)=>Ue.sortKey-Ve.sortKey)}getCombinedIconPrimary(l,u,p,y,b,S,k){let j,O;if(l.hasLayoutProperty("icon-image")){const z=u.getAppearanceValueAndResolveTokens(l,"icon-image",p,y,b);j=this.getResolvedImageFromTokens(z)}else{const z=u.getValueAndResolveTokens("icon-image",p,y,b);j=this.getResolvedImageFromTokens(z)}if(j){const z=l.hasLayoutProperty("icon-size")?l.getUnevaluatedLayoutProperty("icon-size"):u._unevaluatedLayout._values["icon-size"];O=$E(j,y_(this.zoom,z,this.worldview,b),z,y,this.zoom,S,this.pixelRatio,k,this.worldview,b).iconPrimary}return O}updateSymbolInstanceIconVertices(l,u,p,y,b,S){const{canonical:k,availableImages:j,globalProperties:O,layer:z,iconScaleFactor:U,featureState:q,layoutIconOffset:K,layoutIconSize:Z,layoutIconRotate:J}=S;if(l.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(u.activeAppearanceIndex===p)return{vertexOffsetDelta:l.numIconVertices,hasChanges:!1};const ne=p>=0?z.appearances[p]:null;if(ne){const ae=this.getCombinedIconPrimary(ne,z,y,k,j,{sortKey:void 0,text:void 0,icon:null,index:l.featureIndex,sourceLayerIndex:l.featureIndex,geometry:[],properties:u.properties,type:"Point",id:u.id},U);if(!ae)return{vertexOffsetDelta:0,hasChanges:!1};const he=ae.toString(),ce=this.iconAtlasPositions&&this.iconAtlasPositions.get(he);if(ce){const{appearanceIconOffset:ye,appearanceIconRotate:Ee}=wZ(ne,z,y,k,K,J,Z,U);let Ce=iP(ce,void 0,ye,z.layout.get("icon-anchor").evaluate(y,q,k));const He=ce.sdf,$e=z.layout.get("icon-text-fit").constantOr("none");$e!=="none"&&u.textShaping&&u.iconTextFitPadding&&u.fontScale&&(Ce=G5(Ce,u.textShaping,$e,u.iconTextFitPadding,ye,u.fontScale));const Ge=this.calculateEffectiveAppearanceIconSize(ne,O.zoom,y,k,j,U,Z),Ue=0,Ve=1+(Math.min(x_,Math.round(Ge*qp))<<1),yt=Q5(Ce,Ee,He,$e!=="none",U);u.isUsingAppearanceIconVertexData||(u.isUsingAppearanceIconVertexData=!0,u.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(b,l.numIconVertices));const bt=Math.floor(l.numIconVertices/4),kt=Math.min(yt.length,bt);let It=b;for(let Bt=0;Bt0||l.numVerticalGlyphVertices>0;if(!ye)return{vertexOffsetDelta:ye?l.numHorizontalGlyphVertices+l.numVerticalGlyphVertices:0,hasChanges:!1};if(u.activeAppearanceIndex===p)return{vertexOffsetDelta:l.numHorizontalGlyphVertices+l.numVerticalGlyphVertices,hasChanges:!1};const Ee=p>=0?j.appearances[p]:null;if(Ee&&u.textShaping){const{appearanceTextOffset:Ce,appearanceTextRotate:He,appearanceTextSize:$e}=SZ(Ee,j,y,k,q,Z,K);u.fontScale=kZ($e,u.textScaleFactor);const Ge=Ee.getUnevaluatedLayoutProperty("text-size");let Ue=this.textSizeData,Ve=ae,yt=he;Ee.hasLayoutProperty("text-size")&&(Ue=y_(this.zoom,Ge,this.worldview,ce),Ve=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,yt=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const bt=u.textShaping.bottom-q[1],kt=u.textShaping.left-q[0],It=u.textShaping.right-q[0];u.textShaping.top=Ce[1]+(u.textShaping.top-q[1]),u.textShaping.bottom=Ce[1]+bt,u.textShaping.left=Ce[0]+kt,u.textShaping.right=Ce[0]+It;const Ct=vZ(0,u.textShaping,Ce,j,!1,y,z,this.allowVerticalPlacement,He),Bt=$e&&Ue.kind==="composite"?Ge.possiblyEvaluate(new ti(Ve,{}),k).evaluate(y,U,k):J,pt=$e&&Ue.kind==="composite"?Ge.possiblyEvaluate(new ti(yt,{}),k).evaluate(y,U,k):ne,jt=r4(Ee.name,Ue,$e,O,Bt,pt),Lt=Array.isArray(jt)?jt[1]:$e,$t=0,Wt=1+(Math.min(x_,Math.round(Lt*qp))<<1);u.isUsingAppearanceTextVertexData||(u.isUsingAppearanceTextVertexData=!0,u.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(b,l.numHorizontalGlyphVertices+l.numVerticalGlyphVertices));for(let xr=0;xr0){const O=new Set(Object.keys(l).map(z=>{const U=Number(z);return!isNaN(U)&&Number.isSafeInteger(U)&&String(U)===z?U:z}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(O,b[0],u,j,p,l,k),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(O,b[0],u,j,p,l,k)}}}updateRoadElevation(l){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let u=!1;const p=Dt(l),y=1/p;let b=!1,S=!1;for(let k=0;k0||q>0,ne=K>0,ae=this.elevationFeatures[j.elevationFeatureIndex];if(ae){const he=new Mt(j.tileAnchorX,j.tileAnchorY),ce=.075+ae.pointElevation(he);j.zOffset!==ce&&(u=!0,j.zOffset=ce),ce!==0&&(this.hasAnyZOffset=!0);const ye=ae.computeSlopeNormal(he,y),Ee=ia(Zt(),Ae(0,0,1),ye);nn(O,O,Ee),nn(z,z,Ee),O[2]*=p,z[2]*=p,O[0]===1&&O[1]===0&&O[2]===0&&z[0]===0&&z[1]===1&&z[2]===0||(b=b||J,S=S||ne)}if(J&&(mP(this.text.orientationVertexArray,U,O,z),mP(this.text.orientationVertexArray,q,O,z)),ne){const{placedIconSymbolIndex:he,verticalPlacedIconSymbolIndex:ce}=j;he>=0&&mP(this.icon.orientationVertexArray,K,O,z),ce>=0&&mP(this.icon.orientationVertexArray,Z,O,z)}}b||(this.text.orientationVertexArray=void 0),S||(this.icon.orientationVertexArray=void 0),u&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const l=(b,S,k)=>{p+=S,p>b.length&&b.resize(p);for(let j=-S;j<0;j++)b.emplace(j+p,k)},u=(b,S,k)=>{y+=S,y>b.length&&b.resize(y);for(let j=-S;j<0;j++)b.emplace(j+y,k)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let p=0,y=0;for(let b=0;b0;if((k>0||j>0)&&(l(this.text.zOffsetVertexArray,k,z),l(this.text.zOffsetVertexArray,j,z)),U){const{placedIconSymbolIndex:q,verticalPlacedIconSymbolIndex:K}=S;q>=0&&u(this.icon.zOffsetVertexArray,O,z),K>=0&&u(this.icon.zOffsetVertexArray,S.numVerticalIconVertices,z)}}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(l,u,p,y,b){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(l),this.iconCollisionBox.upload(l)),this.text.upload(l,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(l,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(l,u,p,y,b,S=!1){const k={hasLayoutChanges:!1,hasUboChanges:!1};if(!l||!p||!this.featureAppearanceData)return k;const j=u||{},O=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,z=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!O&&!z)return k;const U=this.layers[0],q=U.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===U.appearancesVersion||(this.featureAppearances=new ZCe(U.appearances,U.appearancesVersion));const K=this.featureAppearances.update(y,S);if(K.kind==="no-changes")return k;let Z=1,J=0,ne=!1,ae=!1;if(O){const[Ce,He]=q.get("icon-size-scale-range");Z=fe(1,Ce,He)}let he=1,ce=0,ye=!1;if(z){const[Ce,He]=q.get("text-size-scale-range");he=fe(1,Ce,He)}const Ee=new Map;if(b&&p)for(const Ce of p){const He=b.getImage(Ce,U.scope);if(He){const $e=new au(Ce.toString());Ee.set($e.toString(),He)}}for(let Ce=0;CeIt.isActive({globals:y,feature:Ve,canonical:l,featureState:Ue})):-1;yt=kt>=0?kt:-1}const bt=$e.activeAppearanceIndex!==yt;if(z){const kt=q.get("text-size"),It=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Ct=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Bt={canonical:l,layer:U,featureState:Ue,availableImages:p,textScaleFactor:he,imageMap:Ee,layoutTextOffset:q.get("text-offset").evaluate(Ve,Ue,l).map(jt=>jt*Na),layoutTextSize:kt.evaluate(Ve,Ue,l),layoutTextRotate:q.get("text-rotate").evaluate(Ve,Ue,l),layoutMinZoomSize:kt.evaluate(Ve,{zoom:It},l),layoutMaxZoomSize:kt.evaluate(Ve,{zoom:Ct},l),layoutTextSizeMinZoom:It,layoutTextSizeMaxZoom:Ct},pt=this.updateSymbolInstanceTextVertices(He,$e,yt,Ve,ce,Bt);ce+=pt.vertexOffsetDelta,ye=ye||pt.hasChanges}if(O){const kt={canonical:l,layer:U,featureState:Ue,availableImages:p,globalProperties:y,iconScaleFactor:Z,layoutIconOffset:q.get("icon-offset").evaluate(Ve,Ue,l),layoutIconSize:q.get("icon-size").evaluate(Ve,Ue,l,p),layoutIconRotate:q.get("icon-rotate").evaluate(Ve,Ue,l)},It=this.updateSymbolInstanceIconVertices(He,$e,yt,Ve,J,kt);J+=It.vertexOffsetDelta,ne=ne||It.hasChanges}if(bt){const kt=He.featureIndex,It=y?y.brightness:null,Ct=Ue||{},Bt=yt>=0?U.appearances[yt]:null;this.text.uboBinder&&(this.text.uboBinder.layer=U,ae=this.text.uboBinder.updateFeaturePaintForAppearance(kt,Ve,Ct,l,p,It,Bt)||ae),this.icon.uboBinder&&(this.icon.uboBinder.layer=U,ae=this.icon.uboBinder.updateFeaturePaintForAppearance(kt,Ve,Ct,l,p,It,Bt)||ae)}$e.activeAppearanceIndex=yt}return ne&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),ye&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:ne||ye,hasUboChanges:ae}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=DZ(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(l,u){const p=this.lineVertexArray.length;if(l.segment!==void 0)for(const{x:y,y:b}of u)this.lineVertexArray.emplaceBack(y,b);return{lineStartIndex:p,lineLength:this.lineVertexArray.length-p}}addSymbols(l,u,p,y,b,S,k,j,O,z,U,q,K,Z,J,ne,ae,he){const ce=l.indexArray,ye=l.layoutVertexArray,Ee=l.globeExtVertexArray,Ce=he,He=l.uboBinder?l.uboBinder.getCurrentBatchIndex():void 0,$e=l.segments.prepareSegment(4*Ce,ye,ce,this.canOverlap?S.sortKey:void 0,He),Ge=this.glyphOffsetArray.length,Ue=$e.vertexLength,Ve=this.allowVerticalPlacement&&k===Ic.vertical?Math.PI/2:0,yt=S.text&&S.text.sections;let bt=ye.length,kt=-1;for(let Bt=0;Bt=0)){const Bt=4*It;for(let pt=0;pt=0?u.rightJustifiedTextSymbolIndex:u.centerJustifiedTextSymbolIndex>=0?u.centerJustifiedTextSymbolIndex:u.leftJustifiedTextSymbolIndex>=0?u.leftJustifiedTextSymbolIndex:u.verticalPlacedTextSymbolIndex>=0?u.verticalPlacedTextSymbolIndex:y),S=H5(this.textSizeData,l,b)/Na;return this.tilePixelRatio*S}getSymbolInstanceIconSize(l,u,p){const y=this.icon.placedSymbolArray.get(p),b=H5(this.iconSizeData,l,y);return this.tilePixelRatio*b}_commitDebugCollisionVertexUpdate(l,u,p,y){l.emplaceBack(u,-p,-p,y),l.emplaceBack(u,p,-p,y),l.emplaceBack(u,p,p,y),l.emplaceBack(u,-p,p,y)}_updateTextDebugCollisionBoxes(l,u,p,y,b,S,k){for(let j=y;j0}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(l,u){const p=l.placedSymbolArray.get(u),y=p.vertexStartIndex+4*p.numGlyphs;for(let b=p.vertexStartIndex;by[k]-y[j]||b[j]-b[k]),S}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let l=0;lthis.symbolInstances.get(u).zOffset-this.symbolInstances.get(l).zOffset)}addToSortKeyRanges(l,u){const p=this.sortKeyRanges[this.sortKeyRanges.length-1];p&&p.sortKey===u?p.symbolInstanceEnd=l+1:this.sortKeyRanges.push({sortKey:u,symbolInstanceStart:l,symbolInstanceEnd:l+1})}sortFeatures(l){if(this.sortFeaturesByY&&this.sortedAngle!==l)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(l),this.sortedAngle=l,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const u of this.symbolInstanceIndexes){const p=this.symbolInstances.get(u);this.featureSortOrder.push(p.featureIndex);const{rightJustifiedTextSymbolIndex:y,centerJustifiedTextSymbolIndex:b,leftJustifiedTextSymbolIndex:S,verticalPlacedTextSymbolIndex:k,placedIconSymbolIndex:j,verticalPlacedIconSymbolIndex:O}=p;y>=0&&this.addIndicesForPlacedSymbol(this.text,y),b>=0&&b!==y&&this.addIndicesForPlacedSymbol(this.text,b),S>=0&&S!==b&&S!==y&&this.addIndicesForPlacedSymbol(this.text,S),k>=0&&this.addIndicesForPlacedSymbol(this.text,k),j>=0&&this.addIndicesForPlacedSymbol(this.icon,j),O>=0&&this.addIndicesForPlacedSymbol(this.icon,O)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(l,u){const p=(this.text.uboBinder&&this.text.uboBinder.maxFeaturesPerBatch>0?this.text.uboBinder:this.icon.uboBinder&&this.icon.uboBinder.maxFeaturesPerBatch>0?this.icon.uboBinder:null).maxFeaturesPerBatch;if(this.symbolsByBatch)for(const y of this.symbolsByBatch.values())for(const b of y){const S=this.symbolInstances.get(b.index);b.rotatedY=0|Math.round(l*S.tileAnchorX+u*S.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let y=0;yb.rotatedY-S.rotatedY||S.featureIndex-b.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(l,u){for(const p of l){const y=p.batchIndex;if(y===void 0)continue;const b=u.get(y);if(!b){p.primitiveOffset=this.text.indexArray.length,p.primitiveLength=0;continue}p.primitiveOffset=this.text.indexArray.length;const S=this.text.indexArray.length;for(const{index:k}of b){const j=this.symbolInstances.get(k),{rightJustifiedTextSymbolIndex:O,centerJustifiedTextSymbolIndex:z,leftJustifiedTextSymbolIndex:U,verticalPlacedTextSymbolIndex:q}=j;O>=0&&this.addIndicesForPlacedSymbol(this.text,O),z>=0&&z!==O&&this.addIndicesForPlacedSymbol(this.text,z),U>=0&&U!==z&&U!==O&&this.addIndicesForPlacedSymbol(this.text,U),q>=0&&this.addIndicesForPlacedSymbol(this.text,q)}p.primitiveLength=this.text.indexArray.length-S}}rebuildIconSegmentIndices(l,u){for(const p of l){const y=p.batchIndex;if(y===void 0)continue;const b=u.get(y);if(!b){p.primitiveOffset=this.icon.indexArray.length,p.primitiveLength=0;continue}p.primitiveOffset=this.icon.indexArray.length;const S=this.icon.indexArray.length;for(const{index:k}of b){const j=this.symbolInstances.get(k),{placedIconSymbolIndex:O,verticalPlacedIconSymbolIndex:z}=j;O>=0&&this.addIndicesForPlacedSymbol(this.icon,O),z>=0&&this.addIndicesForPlacedSymbol(this.icon,z)}p.primitiveLength=this.icon.indexArray.length-S}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const l=Math.sin(this.sortedAngle),u=Math.cos(this.sortedAngle),p=this.getOrCreateSortedSymbolsByBatch(l,u),y=Array.from(p.keys()).sort((b,S)=>b-S);for(const b of y){const S=p.get(b);for(const{index:k}of S){const j=this.symbolInstances.get(k);this.featureSortOrder.push(j.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),p),this.rebuildIconSegmentIndices(this.icon.segments.get(),p),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(l){const u=this.symbolInstances.get(this.text.symbolInstanceIndices[l]).elevationFeatureIndex;let p;return this.elevationFeatures&&up in h?String(h[p]):"")}let MZ,FZ,a4;vr(_h,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),_h.addDynamicAttributes=fb;class BZ{constructor(l){this.type=l.property.overrides?l.property.overrides.runtimeType:oh,this.defaultValue=l}evaluate(l){if(l.formattedSection){const u=this.defaultValue.property.overrides;if(u&&u.hasOverride(l.formattedSection))return u.getOverride(l.formattedSection)}return l.feature&&l.featureState?this.defaultValue.evaluate(l.feature,l.featureState):this.defaultValue.property.specification.default}eachChild(l){this.defaultValue.isConstant()||l(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}vr(BZ,"FormatSectionOverride",{omit:["defaultValue"]});const o4=()=>a4||(a4={layout:MZ||(MZ=new ts({"symbol-placement":new Xt(nt.layout_symbol["symbol-placement"]),"symbol-spacing":new Xt(nt.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Xt(nt.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new qt(nt.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Xt(nt.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new Xt(nt.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new Xt(nt.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new Xt(nt.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new Xt(nt.layout_symbol["icon-ignore-placement"]),"icon-optional":new Xt(nt.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Xt(nt.layout_symbol["icon-rotation-alignment"]),"icon-size":new qt(nt.layout_symbol["icon-size"]),"icon-size-scale-range":new Xt(nt.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new qt(nt.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new qt(nt.layout_symbol["icon-text-fit-padding"]),"icon-image":new qt(nt.layout_symbol["icon-image"]),"icon-image-use-theme":new Xt({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new qt(nt.layout_symbol["icon-rotate"]),"icon-padding":new Xt(nt.layout_symbol["icon-padding"]),"icon-keep-upright":new Xt(nt.layout_symbol["icon-keep-upright"]),"icon-offset":new qt(nt.layout_symbol["icon-offset"]),"icon-anchor":new qt(nt.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Xt(nt.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Xt(nt.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Xt(nt.layout_symbol["text-rotation-alignment"]),"text-field":new qt(nt.layout_symbol["text-field"]),"text-font":new qt(nt.layout_symbol["text-font"]),"text-size":new qt(nt.layout_symbol["text-size"]),"text-size-scale-range":new Xt(nt.layout_symbol["text-size-scale-range"]),"text-max-width":new qt(nt.layout_symbol["text-max-width"]),"text-line-height":new qt(nt.layout_symbol["text-line-height"]),"text-letter-spacing":new qt(nt.layout_symbol["text-letter-spacing"]),"text-justify":new qt(nt.layout_symbol["text-justify"]),"text-radial-offset":new qt(nt.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Xt(nt.layout_symbol["text-variable-anchor"]),"text-anchor":new qt(nt.layout_symbol["text-anchor"]),"text-max-angle":new Xt(nt.layout_symbol["text-max-angle"]),"text-writing-mode":new Xt(nt.layout_symbol["text-writing-mode"]),"text-rotate":new qt(nt.layout_symbol["text-rotate"]),"text-padding":new Xt(nt.layout_symbol["text-padding"]),"text-keep-upright":new Xt(nt.layout_symbol["text-keep-upright"]),"text-transform":new qt(nt.layout_symbol["text-transform"]),"text-offset":new qt(nt.layout_symbol["text-offset"]),"text-allow-overlap":new Xt(nt.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new Xt(nt.layout_symbol["text-ignore-placement"]),"text-optional":new Xt(nt.layout_symbol["text-optional"]),visibility:new Xt(nt.layout_symbol.visibility)})),paint:FZ||(FZ=new ts({"icon-opacity":new qt(nt.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new qt(nt.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new qt(nt.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new qt(nt.paint_symbol["text-emissive-strength"]),"icon-color":new qt(nt.paint_symbol["icon-color"]),"icon-halo-color":new qt(nt.paint_symbol["icon-halo-color"]),"icon-halo-width":new qt(nt.paint_symbol["icon-halo-width"]),"icon-halo-blur":new qt(nt.paint_symbol["icon-halo-blur"]),"icon-translate":new Xt(nt.paint_symbol["icon-translate"]),"icon-translate-anchor":new Xt(nt.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new Xt(nt.paint_symbol["icon-image-cross-fade"]),"text-opacity":new qt(nt.paint_symbol["text-opacity"]),"text-occlusion-opacity":new qt(nt.paint_symbol["text-occlusion-opacity"]),"text-color":new qt(nt.paint_symbol["text-color"],{runtimeType:ml,getOverride:h=>h.textColor,hasOverride:h=>!!h.textColor}),"text-halo-color":new qt(nt.paint_symbol["text-halo-color"]),"text-halo-width":new qt(nt.paint_symbol["text-halo-width"]),"text-halo-blur":new qt(nt.paint_symbol["text-halo-blur"]),"text-translate":new Xt(nt.paint_symbol["text-translate"]),"text-translate-anchor":new Xt(nt.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new Xt(nt.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new Xt(nt.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new Xt(nt.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new Xt(nt.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new qt(nt.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"})}))},a4);class gP extends Zo{constructor(l,u,p,y){super(l,o4(),u,p,y,l.layout?l.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=R([]),this.hasOcclusionOpacityProperties=l.paint!==void 0&&("icon-occlusion-opacity"in l.paint||"text-occlusion-opacity"in l.paint)}_handleSpecialPaintPropertyUpdate(l){l!=="icon-occlusion-opacity"&&l!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(l,u){super.recalculate(l,u),this.appearances&&this.appearances.forEach(y=>{y.recalculate(l,u,this.iconImageUseTheme)}),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 p=this.layout.get("text-writing-mode");if(p){const y=[];for(const b of p)y.indexOf(b)<0&&y.push(b);this.layout._values["text-writing-mode"]=y}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(l,u,p,y){return this._saturation===l&&this._contrast===u&&this._brightnessMin===p&&this._brightnessMax===y||(this._colorAdjustmentMatrix=function(b,S,k,j){b=ss(b),S=ji(S);const O=C(),z=b/3,U=1-2*z,q=[U,z,z,0,z,U,z,0,z,z,U,0,0,0,0,1],K=.5-.5*S,Z=j-k;return M(O,[Z,0,0,0,0,Z,0,0,0,0,Z,0,k,k,k,1],[S,0,0,0,0,S,0,0,0,0,S,0,K,K,K,1]),M(O,O,q),O}(l,u,p,y),this._saturation=l,this._contrast=u,this._brightnessMin=p,this._brightnessMax=y),this._colorAdjustmentMatrix}getValueAndResolveTokens(l,u,p,y){const b=this.layout.get(l).evaluate(u,{},p,y),S=this._unevaluatedLayout._values[l];return S.isDataDriven()||Hx(S.value)||!b?b:OZ(u.properties,b)}getAppearanceValueAndResolveTokens(l,u,p,y,b){const S=l.getLayoutProperty(u);if(!S)return;const k=S.evaluate(p,{},y,b),j=l.getUnevaluatedLayoutProperties()._values[u];return j.isDataDriven()||Hx(j.value)||!k||typeof k!="string"?k:OZ(p.properties,k)}createBucket(l){return new _h(l)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const l of o4().paint.overridableProperties){if(!gP.hasPaintOverride(this.layout,l))continue;const u=this.paint.get(l),p=new BZ(u),y=new jv(p,u.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let b=null;b=u.value.kind==="constant"||u.value.kind==="source"?new pg("source",y):new jp("composite",y,u.value.zoomStops,u.value.interpolationType),this.paint._values[l]=new Rp(u.property,b,u.parameters)}}_handleOverridablePaintPropertyUpdate(l,u,p){return!(!this.layout||u.isDataDriven()||p.isDataDriven())&&gP.hasPaintOverride(this.layout,l)}static hasPaintOverride(l,u){const p=l.get("text-field"),y=o4().paint.properties[u];let b=!1;const S=k=>{for(const j of k)if(y.overrides&&y.overrides.hasOverride(j))return void(b=!0)};if(p.value.kind==="constant"&&p.value.value instanceof No)S(p.value.value.sections);else if(p.value.kind==="source"){const k=O=>{b||(O instanceof Ir&&js(O.value)===wx?S(O.value.sections):O instanceof wp?S(O.sections):O.eachChild(k))},j=p.value;j._styleExpression&&k(j._styleExpression.expression)}return b}getProgramIds(){return["symbol"]}getDefaultProgramParams(l,u,p){return{config:new ee(this,{zoom:u,lut:p}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let zZ,$Z,UZ,VZ;var yP=Pn([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function xP(h,l,u,p,y,b,S,k){const j=[h,l,1,u,p,1,y,b,1],O=[S,k,1],z=T([],j),[U,q,K]=Sr(O,O,z);return E(j,j,[U,0,0,0,q,0,0,0,K])}function qZ(h,l,u,p,y,b,S,k){const j=function(O,z,U,q,K,Z,J,ne){const ae=xP(0,0,1,0,1,1,0,1),he=xP(O,z,U,q,K,Z,J,ne);return E(he,he,T([],ae))}(h,l,u,p,y,b,S,k);return[j[2]/j[8]/ar,j[5]/j[8]/ar]}function _P(h){return[h[0],Math.min(Math.max(h[1],-85.051129),St)]}class GZ extends bx{constructor(l,u,p,y){super(),this.id=l,this.dispatcher=p,this.coordinates=u.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(y),this.options=u,this._dirty=!1}load(l,u){if(this._loaded=u||!1,this.fire(new Nu("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return l&&(this.coordinates=l),this._loaded=!0,void this._finishLoading();this._imageRequest=Qm(this.map._requestManager.transformRequest(this.url,_x.Image),(p,y)=>{this._imageRequest=null,this._loaded=!0,p?this.fire(new Jm(p)):y&&(this.image=y,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,l&&(this.coordinates=l),this._finishLoading())})}loaded(){return this._loaded}updateImage(l){return l.url?(this._imageRequest&&l.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=l.url,this.load(l.coordinates,this._loaded),this):this}setTexture(l){if(!(l.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new RE(this.map.painter.context,l.handle),this.width=l.dimensions[0],this.height=l.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Nu("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(l){this.map=l,this.load()}onRemove(l){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof RE||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(l){if(this.coordinates=l,this._boundsArray=void 0,this._unsupportedCoords=!1,!l.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let u=l[0][1],p=l[0][1];for(const b of l)b[1]>p&&(p=b[1]),b[1]St?this.onNorthPole=!0:y<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const b=l.map(Ar.fromLngLat);this.tileID=function(S){let k=1/0,j=1/0,O=-1/0,z=-1/0;for(const J of S)k=Math.min(k,J.x),j=Math.min(j,J.y),O=Math.max(O,J.x),z=Math.max(z,J.y);const U=Math.max(O-k,z-j),q=Math.max(0,Math.floor(-Math.log2(U))),K=Math.pow(2,q);let Z=Math.floor((k+O)/2*K);return Z>1&&(Z-=1),new h_(q,Z,Math.floor((j+z)/2*K))}(b),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Nu("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof RE||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(l){for(const ne in this.tiles){const ae=this.tiles[ne];ae.state!=="loaded"&&(ae.state="loaded",ae.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const u=__(new h_(0,0,0),this.map.transform.projection),p=[u.projection.project(this.coordinates[0][0],this.coordinates[0][1]),u.projection.project(this.coordinates[1][0],this.coordinates[1][1]),u.projection.project(this.coordinates[2][0],this.coordinates[2][1]),u.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(ne){const ae=ne[1].x-ne[0].x,he=ne[1].y-ne[0].y,ce=ne[2].x-ne[1].x,ye=ne[2].y-ne[1].y,Ee=ne[3].x-ne[2].x,Ce=ne[3].y-ne[2].y,He=ne[0].x-ne[3].x,$e=ne[0].y-ne[3].y,Ge=ae*ye-ce*he,Ue=ce*Ce-Ee*ye,Ve=Ee*$e-He*Ce,yt=He*he-ae*$e;return Ge>0&&Ue>0&&Ve>0&&yt>0||Ge<0&&Ue<0&&Ve<0&&yt<0}(p))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const y=__(this.tileID,this.map.transform.projection),[b,S,k,j]=this.coordinates.map(ne=>{const ae=y.projection.project(ne[0],ne[1]);return IZ(y,ae)._round()});this.perspectiveTransform=qZ(b.x,b.y,S.x,S.y,k.x,k.y,j.x,j.y);const O=this._boundsArray=new xo;O.emplaceBack(b.x,b.y,0,0),O.emplaceBack(S.x,S.y,ar,0),O.emplaceBack(j.x,j.y,0,ar),O.emplaceBack(k.x,k.y,ar,ar),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=l.createVertexBuffer(O,yP.members),this.boundsSegments=Si.simpleSegment(0,0,4,2);const z=[],U=function(ne){return[_P(ne[0]),_P(ne[1]),_P(ne[2]),_P(ne[3])]}(this.coordinates),[q,K,Z,J]=function(ne){let ae=ne[0][0],he=ae,ce=ne[0][1],ye=ce;for(let Ee=1;Eehe&&(he=ne[Ee][0]),ne[Ee][1]ye&&(ye=ne[Ee][1]);return[ae,ce,he-ae,ye-ce]}(U);{const ne=new xo,[ae,he,ce,ye]=function(Ct){let Bt=Ct[0].x,pt=Bt,jt=Ct[0].y,Lt=jt;for(let $t=1;$tpt&&(pt=Ct[$t].x),Ct[$t].yLt&&(Lt=Ct[$t].y);return[Bt,jt,pt-Bt,Lt-jt]}(p),Ee=Ct=>[(Ct.x-ae)/ce,(Ct.y-he)/ye],[Ce,He,$e,Ge]=p.map(Ee),Ue=function(Ct,Bt,pt,jt,Lt,$t,Wt,xr){const ir=xP(0,0,1,0,1,1,0,1);return E(ir,ir,T([],xP(Ct,Bt,pt,jt,Lt,$t,Wt,xr)))}(Ce[0],Ce[1],He[0],He[1],$e[0],$e[1],Ge[0],Ge[1]);this.elevatedGlobePerspectiveTransform=qZ(Ce[0],Ce[1],He[0],He[1],$e[0],$e[1],Ge[0],Ge[1]);const Ve=(Ct,Bt)=>{z.push(Ct.lng);const pt=Math.round((Ct.lng-q)/Z*ar),jt=Math.round((Ct.lat-K)/J*ar),Lt=Ee(Bt),$t=Sr([],[Lt[0],Lt[1],1],Ue),Wt=Math.round($t[0]/$t[2]*ar),xr=Math.round($t[1]/$t[2]*ar);ne.emplaceBack(pt,jt,Wt,xr)},yt=p[3].x-p[0].x,bt=p[3].y-p[0].y,kt=p[2].x-p[1].x,It=p[2].y-p[1].y;for(let Ct=0;Ct<65;Ct++){const Bt=Ct/64,pt=[p[0].x+Bt*yt,p[0].y+Bt*bt],jt=[p[1].x+Bt*kt,p[1].y+Bt*It],Lt=jt[0]-pt[0],$t=jt[1]-pt[1];for(let Wt=0;Wt<65;Wt++){const xr=Wt/64,ir={x:pt[0]+Lt*xr,y:pt[1]+$t*xr};Ve(u.projection.unproject(ir.x,ir.y),ir)}}this.elevatedGlobeVertexBuffer=l.createVertexBuffer(ne,yP.members)}{this.maxLongitudeTriangleSize=0;let ne=[],ae=new _s;const he=(ce,ye,Ee)=>{ae.emplaceBack(ce,ye,Ee);const Ce=z[ce],He=z[ye],$e=z[Ee],Ge=Math.min(Math.min(Ce,He),$e),Ue=Math.max(Math.max(Ce,He),$e)-Ge;Ue>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=Ue),ne.push(Ge+Ue/2)};for(let ce=0;ce<64;ce++)for(let ye=0;ye<64;ye++){const Ee=65*ce+ye,Ce=Ee+1,He=Ee+65,$e=He+1;he(Ee,He,Ce),he(Ce,He,$e)}[ne,ae]=function(ce,ye){const Ee=Array.from({length:ce.length},($e,Ge)=>Ge);Ee.sort(($e,Ge)=>ce[$e]-ce[Ge]);const Ce=[],He=new _s;for(let $e=0;$e{S.segments.push({vertexOffset:0,primitiveOffset:U,vertexLength:u.segments[0].vertexLength,primitiveLength:q,sortKey:void 0,vaos:{}})},j=.51*this.maxLongitudeTriangleSize;if(Math.abs(p[0]-y)<=j){const U=sa(p,0,p.length,y+j);return U===p.length||k(U,is(p,U+1,p.length,y+360-j)-U),S}y0}}let WZ,KZ,YZ,ZZ,XZ,QZ,JZ;class eX extends Zo{constructor(l,u,p,y){super(l,{layout:WZ||(WZ=new ts({visibility:new Xt(nt["layout_raster-particle"].visibility)})),paint:KZ||(KZ=new ts({"raster-particle-array-band":new Xt(nt["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new Xt(nt["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new xg(nt["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new Xt(nt["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new Xt(nt["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new Xt(nt["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new Xt(nt["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new Xt(nt["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"})}))},u,p,y),this._updateColorRamp(),this.lastInvalidatedAt=Pl.now()}_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(l){this.colorRampTexture&&this.colorRampTexture.destroy(),this.tileFramebuffer&&this.tileFramebuffer.destroy(),this.particleFramebuffer&&this.particleFramebuffer.destroy()}hasColorMap(){return!!this._transitionablePaint._values["raster-particle-color"].value.value}getProgramIds(){return["rasterParticle"]}hasOffscreenPass(){return this.visibility!=="none"}isDraped(l){return!1}_handleSpecialPaintPropertyUpdate(l){l!=="raster-particle-color"&&l!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),l==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const l=this._transitionablePaint._values["raster-particle-color"].value.expression,u=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=xE({expression:l,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:u}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=Pl.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class tje extends Zo{constructor(l,u){super(l,{},u,null),this.implementation=l,l.slot&&(this.slot=l.slot)}is3D(l){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(l){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(l){this.implementation.onAdd&&this.implementation.onAdd(l,l.painter.context.gl)}onRemove(l){this.implementation.onRemove&&this.implementation.onRemove(l,l.painter.context.gl)}}function c4(h,l,u){const p=[0,0,1],y=Pr([]);return ai(y,y,u?-Kn(h)+Math.PI:Kn(h)),Nn(y,y,-Kn(l)),nn(p,p,y),mt(p,p)}class vP{constructor(l,u,p,y){this.message=(l?`${l}: `:"")+p,y&&(this.identifier=y),u!=null&&u.__line__&&(this.line=u.__line__)}}function u4(h,l){const u=h.indexOf("://")===-1;try{return new URL(h,u&&l?"http://example.com":void 0),!0}catch{return!1}}class tX{constructor(l,u){this.feature=l,this.instancedDataOffset=u,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class rX{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new cE,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(l){const u=16*l,p=this.instancedDataArray.float32;let y=Math.floor(p[u+2]);const b=1.05*(p[u+2]-y);return y/=100,[p[u]%1*1.05,p[u+1]%1*1.05,b,y]}tileCoordinatesForInstance(l){const u=16*l,p=this.instancedDataArray.float32;let y=p[u+0];return y=y>ar?y-ar:y,new Mt(Math.trunc(y),Math.trunc(p[u+1]))}translationForInstance(l){const u=16*l,p=this.instancedDataArray.float32;return[p[u+4],p[u+5],p[u+6]]}rotationScaleForInstance(l){const u=16*l,p=this.instancedDataArray.float32;return[p[u+7],p[u+8],p[u+9],p[u+10],p[u+11],p[u+12],p[u+13],p[u+14],p[u+15]]}transformForInstance(l){const u=16*l,p=this.instancedDataArray.float32;return[p[u+7],p[u+8],p[u+9],p[u+4],p[u+10],p[u+11],p[u+12],p[u+5],p[u+13],p[u+14],p[u+15],p[u+6],0,0,0,1]}}class d4{constructor(l){this.zoom=l.zoom,this.canonical=l.canonical,this.overscaledZ=this.canonical.z+Math.log2(l.overscaling),this.layers=l.layers,this.layerIds=this.layers.map(u=>u.fqid),this.projection=l.projection,this.index=l.index,this.worldview=l.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=l.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(l,u){}updateAppearances(l,u,p,y){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(l,u,p,y){this.tileToMeter=Dt(p);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;for(const{feature:k,id:j,index:O,sourceLayerIndex:z}of l){const U=j??(k.properties&&k.properties.hasOwnProperty("id")?k.properties.id:void 0),q=vn(k,b);if(!this.layers[0]._featureFilter.filter(new ti(this.zoom,{worldview:this.worldview,activeFloors:u.activeFloors}),q,p))continue;const K={id:U,sourceLayerIndex:z,index:O,geometry:b?q.geometry:$r(k,p,y),properties:k.properties,type:k.type,patterns:{}},Z=this.addFeature(K,K.geometry,q,S,p);Z&&u.featureIndex.insert(k,K.geometry,O,z,this.index,this.instancesPerModel[Z].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const l=this.layers[0].modelManager,u=this.layers[0].scope;let p=0;for(const y of this.modelUris){const b=l.getModel(y,u);if(!b)continue;const S=this.instancesPerModel[y];if(S){const k=.5*at(b.aabb.max,b.aabb.min)*S.maxScale+S.maxXYTranslationDistance,j=Math.min(ar,Math.max(k/this.tileToMeter,256));p=Math.max(j,p)}}return p}update(l,u,p,y){for(const b in this.instancesPerModel){const S=this.instancesPerModel[b];for(const k in l)S.idToFeaturesIndex.hasOwnProperty(k)&&(this.evaluate(S.features[S.idToFeaturesIndex[k]],l[k],S,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let l=!1;for(const u in this.instancesPerModel){const p=this.instancesPerModel[u];for(const y of p.features){const b=this.layers[0],S=y.feature,k=this.canonical,j=b.paint.get("model-rotation").evaluate(S,{},k),O=b.paint.get("model-scale").evaluate(S,{},k),z=b.paint.get("model-translation").evaluate(S,{},k);yr(y.rotation,j)&&yr(y.scale,O)&&yr(y.translation,z)||(this.evaluate(y,y.featureStates,p,!0),l=!0)}}return l}updateReplacement(l,u,p,y){if(u.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=u.updateTime;const b=u.getReplacementRegionsForTile(l.toUnwrapped(),!0);if(BI(this.activeReplacements,b))return!1;this.activeReplacements=b;let S=!1;for(const k in this.instancesPerModel){const j=this.instancesPerModel[k],O=j.instancedDataArray;for(const z of j.features){const U=z.instancedDataOffset,q=z.instancedDataCount;for(let K=0;Kar;J=ne?J-ar:J;const ae=Math.floor(J),he=Math.floor(O.float32[Z+1]);let ce=!1;for(const ye of this.activeReplacements)if(!MK(ye,p,zI.Model,y)&&!(ye.min.x>ae||ae>ye.max.x||ye.min.y>he||he>ye.max.y)&&(ce=UK($K(ae,he,l.canonical,ye.footprintTileId.canonical),ye.footprint),ce))break;O.float32[Z]=ce?J+ar:J,S=S||ce!==ne}}}return S}isEmpty(){for(const l in this.instancesPerModel)if(this.instancesPerModel[l].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(l){if(!this.uploaded)for(const u in this.instancesPerModel){const p=this.instancesPerModel[u];p.instancedDataArray.length<0||p.instancedDataArray.length===0||(p.instancedDataBuffer?p.instancedDataBuffer.updateData(p.instancedDataArray):p.instancedDataBuffer=l.createVertexBuffer(p.instancedDataArray,vke.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(l){for(const p in this.instancesPerModel){const y=this.instancesPerModel[p];y.instancedDataArray.length!==0&&y.instancedDataBuffer&&y.instancedDataBuffer.destroy()}const u=this.layers[0].modelManager;if(l&&u&&this.modelUris&&this.modelsRequested)for(const p of this.modelUris)u.removeModel(p,"",!0)}addFeature(l,u,p,y,b){const S=this.layers[0],k=S.layout.get("model-id"),j=S.layout.get("model-allow-density-reduction"),O=k.evaluate(p,{},this.canonical);if(!O)return Br(`modelId is not evaluated for layer ${S.id} and it is not going to get rendered.`),O;(u4(O,!1)||this.styleDefinedModelURLs[O]!==void 0)&&(this.modelUris.includes(O)||this.modelUris.push(O)),this.instancesPerModel[O]||(this.instancesPerModel[O]=new rX);const z=this.instancesPerModel[O],U=z.instancedDataArray,q=new tX(p,U.length);let K;y&&(K=Ii.getElevationFeature(l,y));for(const Z of u)for(const J of Z){if(J.x<0||J.x>=ar||J.y<0||J.y>=ar)continue;if(this.lookupDim!==0&&j){const ae=(this.lookupDim-1)/ar,he=this.lookupDim*(J.y*ae|0)+J.x*ae|0;if(this.lookup){if(this.lookup[he]!==0)continue;this.lookup[he]=1}}this.instanceCount++;const ne=U.length;if(U.resize(ne+1),y){z.instancesRoadElevation||(z.instancesRoadElevation=[]);const ae=K?K.pointElevation(new Mt(J.x,J.y)):0;z.instancesRoadElevation.push(ae)}z.instancesEvaluatedElevation.push(0),U.float32[16*ne]=J.x,U.float32[16*ne+1]=J.y}return q.instancedDataCount=z.instancedDataArray.length-q.instancedDataOffset,q.instancedDataCount>0&&(l.id&&(z.idToFeaturesIndex[l.id]=z.features.length),z.features.push(q),this.evaluate(q,{},z,!1)),O}getModelUris(){return this.modelUris}evaluate(l,u,p,y){const b=this.layers[0],S=l.feature,k=this.canonical,j=l.rotation=b.paint.get("model-rotation").evaluate(S,u,k),O=l.scale=b.paint.get("model-scale").evaluate(S,u,k),z=l.translation=b.paint.get("model-translation").evaluate(S,u,k),U=Object.assign({},b.paint.get("model-color").evaluate(S,u,k));U.a=b.paint.get("model-color-mix-intensity").evaluate(S,u,k);const q=[];this.maxVerticalOffset0?Math.sqrt(K):0;p.maxScale=Math.max(Math.max(p.maxScale,O[0]),Math.max(O[1],O[2])),p.maxXYTranslationDistance=Math.max(p.maxXYTranslationDistance,Z),this.maxScale=Math.max(Math.max(this.maxScale,O[0]),Math.max(O[1],O[2])),AY(q,j,O);const J=Math.round(100*U.a)+U.b/1.05;for(let ne=0;ne10?this.tileToMeter:Dt(k,Ee)),ce[he+4]=z[0],ce[he+5]=z[1],ce[he+6]=z[2]+(p.instancesRoadElevation?p.instancesRoadElevation[ae]:0)+ye,ce[he+7]=q[0],ce[he+8]=q[1],ce[he+9]=q[2],ce[he+10]=q[4],ce[he+11]=q[5],ce[he+12]=q[6],ce[he+13]=q[8],ce[he+14]=q[9],ce[he+15]=q[10],p.instancesEvaluatedElevation[ae]=z[2]}}}vr(d4,"ModelBucket",{omit:["layers"]}),vr(rX,"PerModelAttributes"),vr(tX,"ModelFeature");class mb{constructor(l,u,p){this._demTile=l,this._dem=this._demTile.dem,this._scale=u,this._offset=p}static create(l,u,p){const y=p||l.findDEMTileFor(u);if(!y||!y.dem)return;const b=y.dem,S=y.tileID,k=1<O.fqid),this.stateDependentLayerIds=this.layers.filter(O=>O.isStateDependent()).map(O=>O.id),this.modelTraits|=ob.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,y&&(this.modelTraits|=ob.HasMapboxMeshFeatures),b&&(this.modelTraits|=ob.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=S,this.worldview=j,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const O of u)this.nodesInfo.push(new aX(O)),iX(O,k.featureIndexArray.length,k.grid),k.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,k.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(l,u){for(const p of this.getNodesInfo()){const y=p.node;y.footprint&&u.push({footprint:y.footprint,id:l})}}updateAppearances(l,u,p,y){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(l){const u=Object.keys(l).length!==0;if(u&&!this.stateDependentLayers.length)return;const p=u?this.stateDependentLayers:this.layers;if(!Po(l,this.states))for(const y of p)this.evaluate(y,l);this.states=structuredClone(l)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(l){if(!this.needsUpload)return;const u=this.getNodesInfo();for(const p of u){const y=p.node;this.uploaded?this.updatePbrBuffer(y):j5(y,l,!0)}for(const p of u)JI(p.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(l){let u=!1;if(!l.meshes)return u;for(const p of l.meshes)p.pbrBuffer&&(p.pbrBuffer.updateData(p.featureArray),u=!0);return u}needsReEvaluation(l,u,p){const y=l.transform.projectionOptions,b=l.style.getBrightness(),S=this.brightness!==b;if(!this.uploaded||this.dirty||y.name!==this.projection.name||YE(p.paint.get("model-color").value,S)||YE(p.paint.get("model-color-mix-intensity").value,S)||YE(p.paint.get("model-roughness").value,S)||YE(p.paint.get("model-emissive-strength").value,S)||YE(p.paint.get("model-height-based-emissive-strength-multiplier").value,S)){this.projection=y,this.brightness=b;const k=this.getNodesInfo();for(const j of k)j.state=null;return!0}return!1}evaluateTransform(l,u){if(l.transform.zoom===this.zoom)return;this.zoom=l.transform.zoom;const p=this.getNodesInfo(),y=this.id.canonical;for(const b of p){const S=b.feature;b.evaluatedTranslation=u.paint.get("model-translation").evaluate(S,{},y),b.evaluatedScale=u.paint.get("model-scale").evaluate(S,{},y)}}evaluate(l,u){const p=this.getNodesInfo();for(const y of p){if(!y.node.meshes)continue;const b=y.feature,S=u&&u[b.id];if(Po(S,y.state))continue;y.state=structuredClone(S);const k=y.node.meshes&&y.node.meshes[0].featureData,j=y.evaluatedColor[2],O=y.evaluatedRMEA[2],z=this.id.canonical;if(y.hasTranslucentParts=!1,k){for(let U=0;U=Ce)continue;const Bt=h4[Ct],pt=Math.abs(Bt);pt>Ve&&(Ue=Bt,Ve=pt,yt=It,bt=kt)}if(Ve>.1){const kt=1-(Ce+.5*Math.abs(yt*bt))/Z;let It=u._dem.get($e,He)+Ue*kt;const Ct=u._dem.get($e+yt,He+bt),Bt=u._dem.get($e-yt,He-bt,!0);(It-Ct)*(It-Bt)>0&&(It=(Ct+Bt)/2),h4[Ge]=u._dem.set($e,He,It),v_[Ge]=Ce}}}}}k&&(u._demTile.needsDEMTextureUpload=!0,u._dem._timestamp=Pl.now())}setFilter(l){this.filter=l?$v(l):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(l=>this.filter.filter(new ti(this.id.overscaledZ,{worldview:this.worldview}),l.feature,this.id.canonical)):this.nodesInfo}destroy(){const l=this.getNodesInfo();for(const u of l)JI(u.node),I5(u.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(l,u){if(u.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=u.updateTime;const p=u.getReplacementRegionsForTile(l.toUnwrapped());for(const y of this.getNodesInfo()){const b=y.node.footprint;y.hiddenByReplacement=!!b&&!p.find(S=>S.footprint===b)}}getHeightAtTileCoord(l,u){const p=[],y=[0,0,0],b=R([]);for(const S of this.getNodesInfo()){const k=S.node.meshes[0],j=k.transformedAabb;if(lj.max[0]||u>j.max[1])continue;if(S.node.hidden===!0)return{height:1/0,maxHeight:S.feature.properties.height,hidden:!1,verticalScale:S.evaluatedScale[2]};D(b,S.node.globalMatrix),y[0]=l,y[1]=u,or(y,y,b);const O=(y[0]-k.aabb.min[0])/(k.aabb.max[0]-k.aabb.min[0])*m_|0,z=Math.min(63,(y[1]-k.aabb.min[1])/(k.aabb.max[1]-k.aabb.min[1])*m_|0)*m_+Math.min(63,O),U=k.heightmap[z];if(!(U<0&&S.node.footprint))return S.hiddenByReplacement?void 0:{height:U,maxHeight:S.feature.properties.height,hidden:!1,verticalScale:S.evaluatedScale[2]};if(S.node.footprint.grid.query(new Mt(l,u),new Mt(l,u),p),p.length>0)return{height:void 0,maxHeight:S.feature.properties.height,hidden:S.hiddenByReplacement,verticalScale:S.evaluatedScale[2]}}}}function YE(h,l){return h instanceof pg&&!h.isLightConstant&&l}function rje(h,l,u,p,y,b,S,k){let j=(61440&l|(61440&l)>>4)>>8,O=(3840&l|(3840&l)>>4)>>4,z=240&l|(240&l)>>4;u[3]>0&&(j=Xr(j,255*u[0],u[3]),O=Xr(O,255*u[1],u[3]),z=Xr(z,255*u[2],u[3]));const U=j<<8|O,q=z<<8|Math.floor(255*p[3]),K=function(Ce){const He=fe(Ce,0,2);return Math.min(Math.round(.5*He*255),255)}(p[2])<<8|15*p[0]<<4|15*p[1],Z=fe(y[0],0,1),J=fe(y[1],0,1),ne=fe(y[2],0,1),ae=fe(y[3],0,1);let he,ce,ye,Ee;if(Z!==J&&S!==b&&J!==Z){const Ce=S-b;ce=1/(Ce*(J-Z)),ye=-(b+Ce*Z)/(Ce*(J-Z));const He=fe(y[4],-1,1);Ee=Math.pow(10,He),he=255*ne<<8|255*ae}else he=65535,ce=0,ye=1,Ee=1;if(h.emplaceBack(U,q,K,he,ce,ye,Ee),k){const Ce=k.length;k.clear();for(let He=0;He>16&65535,z=b?j>>16&65535:65535&j,U=(15&z)<8?15&z:0,q=h.evaluatedRMEA[U],K=h.evaluatedColor[U],Z=h.emissionHeightBasedParams[U];let J;if(k&&U===2&&p.lights&&(J=new Yv,J.resize(10*p.lights.length)),rje(S.featureArray,O,K,q,Z,S.aabb.min[2],S.aabb.max[2],J),J&&k){k=!1;const ne=p.meshes[p.lightMeshIndex];ne.featureArray=J,ne.featureArray._trim()}}S.featureArray._trim(),y++}}vr(bP,"Tiled3dModelBucket",{omit:["layers"]}),vr(aX,"Tiled3dModelFeature");const ije=["id","tile","layer","source","sourceLayer","state"];class b_{constructor(l,u,p,y,b){this.type="Feature",this._vectorTileFeature=l,this._z=u,this._x=p,this._y=y,this.properties=l?l.properties:{},this.id=b}clone(){const l=new b_(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(l.state=Object.assign({},this.state)),this.layer&&(l.layer=Object.assign({},this.layer)),this.source&&(l.source=this.source),this.sourceLayer&&(l.sourceLayer=this.sourceLayer),l}get geometry(){return this._geometry===void 0&&this._vectorTileFeature&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._x,this._y,this._z).geometry),this._geometry}set geometry(l){this._geometry=l}toJSON(){const l={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const u of ije)this[u]!==void 0&&(l[u]=this[u]);return l}}class w_ extends bx{constructor(l,u,p,y){super(),this.id=l,this.type="model",this.models=[],this._options=u,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(l,u){return wY(this.map._requestManager.transformRequest(l,_x.Model).url,u)}async loadModel(l,u,p){try{const y=await this.loadGLTFFromURI(u.uri,p);if(p.aborted)return;const b=this._modelsInfo.get(l);if(!b)return;const S=N5(y),k=b.modelSpec,j=new kY(l,k.uri,k.position,k.orientation,S);w_.applyModelSpecification(j,k),j.computeBoundsAndApplyParent(),this.models.push(j),b.model=j}catch(y){if(y instanceof Error&&y.name==="AbortError")return;const b=y instanceof Error?y.message:"Unknown error";this.fire(new Jm(new Error(`Could not load model ${l} from ${u.uri}: ${b}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const l=this._abortController.signal,u=[];for(const p in this._options.models){const y=this._options.models[p],b=this._modelsInfo.get(p);if(b&&b.model){b.modelSpec=y;const S=b.model;S.position=y.position!=null?new Qe(y.position[0],y.position[1]):new Qe(0,0),S.orientation=y.orientation!=null?y.orientation:[0,0,0],w_.applyModelSpecification(S,y),S.computeBoundsAndApplyParent(),this.models.push(S)}else b?b.modelSpec=y:(this._modelsInfo.set(p,{modelSpec:y,model:null}),u.push(this.loadModel(p,y,l)))}u.length!==0?(await Promise.allSettled(u),l.aborted||this.fire(new Nu("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Nu("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(l,u){u.nodeOverrides&&w_.convertNodeOverrides(l,u.nodeOverrides),u.materialOverrides&&w_.convertMaterialOverrides(l,u.materialOverrides),u.nodeOverrideNames&&(l.nodeOverrideNames=[...u.nodeOverrideNames]),u.materialOverrideNames&&(l.materialOverrideNames=[...u.materialOverrideNames]),u.featureProperties&&(l.featureProperties=u.featureProperties)}static convertNodeOverrides(l,u){if(Array.isArray(u)&&u.every(p=>typeof p=="string")){l.nodeOverrideNames=[];for(const p of u)l.nodeOverrideNames.push(p)}else Object.entries(u).forEach(([p,y])=>{const b={orientation:[0,0,0]};if(y.hasOwnProperty("orientation")){const S=y.orientation;S&&(b.orientation=S)}l.nodeOverrides.set(p,b)})}static convertMaterialOverrides(l,u){if(Array.isArray(u)&&u.every(p=>typeof p=="string")){l.materialOverrideNames=[];for(const p of u)l.materialOverrideNames.push(p)}else Object.entries(u).forEach(([p,y])=>{const b={color:new Yn(1,1,1),colorMix:0,emissionStrength:0,opacity:1},S=y["model-color"];S!==void 0&&(b.color.r=S[0],b.color.g=S[1],b.color.b=S[2]);const k=y["model-color-mix-intensity"];k!==void 0&&(b.colorMix=k);const j=y["model-emissive-strength"];j!==void 0&&(b.emissionStrength=j);const O=y["model-opacity"];O!==void 0&&(b.opacity=O),l.materialOverrides.set(p,b)})}onAdd(l){this.map=l,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const l of this._modelsInfo.values())if(l.model==null)return!1;return!0}getModels(){return this.models}loadTile(l,u){}serialize(){return this._options}setProperty(l,u){return!1}reload(){this.cancelModelRequests();const l=Lp(this.id,this.scope);this.map.style.clearSource(l),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(l){this.cancelModelRequests()}setModels(l){this.models=[];const u=new Map;for(const p in l){const y=l[p],b=this._modelsInfo.get(p);b&&b.modelSpec.uri===y.uri&&u.set(p,b)}if(this._modelsInfo.size!==u.size){this.cancelModelRequests();for(const[p,y]of u)y.model||u.delete(p)}this._modelsInfo=u,this._options.models=l,this.load()}}function f4(h,l,u,p){const y=1<j>=Ee.vertexArrayOffset&&jye.polygon).flat());const ne=K?k:null,[ae,he]=oY(b,p,U,z,O,S,ne,q,Z,b.center.lat,h.tileID.canonical),ce=h.queryGeometry;return aY(ae,he,ce.isPointQuery()?ce.screenBounds:ce.screenGeometry)}},building:class extends Zo{constructor(h,l,u,p){super(h,{layout:LY||(LY=new ts({visibility:new Xt(nt.layout_building.visibility),"building-facade":new qt(nt.layout_building["building-facade"]),"building-facade-floors":new qt(nt.layout_building["building-facade-floors"]),"building-facade-unit-width":new qt(nt.layout_building["building-facade-unit-width"]),"building-facade-window":new qt(nt.layout_building["building-facade-window"]),"building-roof-shape":new qt(nt.layout_building["building-roof-shape"]),"building-height":new qt(nt.layout_building["building-height"]),"building-base":new qt(nt.layout_building["building-base"]),"building-flood-light-wall-radius":new qt(nt.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new qt(nt.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new qt(nt.layout_building["building-flip-roof-orientation"])})),paint:DY||(DY=new ts({"building-opacity":new Xt(nt.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new Xt(nt.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new Xt(nt.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new Xt(nt.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new Xt(nt.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new Xt(nt.paint_building["building-vertical-scale"]),"building-cast-shadows":new Xt(nt.paint_building["building-cast-shadows"]),"building-color":new qt(nt.paint_building["building-color"]),"building-emissive-strength":new qt(nt.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new Xt(nt.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new Xt(nt.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new Xt(nt.paint_building["building-front-cutoff"]),"building-flood-light-color":new Xt(nt.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new Xt(nt.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new Xt(nt.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new qt({type:"string",default:"default","property-type":"data-driven"})}))},l,u,p),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(h){return new RY(h)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(h){return!0}queryRadius(h){return 0}queryIntersectsFeature(h,l,u,p,y,b,S,k,j,O){let z=this.layout.get("building-height").evaluate(l,u);const U=this.layout.get("building-base").evaluate(l,u),q=h.tile.getBucket(this).getFootprint(l);if(q){if(q.hiddenFlags!==0)return!1;z=q.height}const[K,Z]=oY(b,p,U,z,new Mt(0,0),S,null,[0,0],1,b.center.lat,h.tileID.canonical),J=h.queryGeometry;return aY(K,Z,J.isPointQuery()?J.screenBounds:J.screenGeometry)}},line:class extends Zo{constructor(h,l,u,p){const y=GY();super(h,y,l,u,p),y.layout&&(this.layout=new fh(y.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(h){if(h==="line-gradient"){const l=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=l._styleExpression&&l._styleExpression.expression instanceof Ox,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}widthExpression(){return this._transitionablePaint._values["line-width"].value.expression}emissiveStrengthExpression(){return this._transitionablePaint._values["line-emissive-strength"].value.expression}recalculate(h,l){super.recalculate(h,l),this.paint._values["line-floorwidth"]=(()=>{if(DE)return DE;const u=GY();return DE=new Qke(u.paint.properties["line-width"].specification),DE.useIntegerZoom=!0,DE})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,h)}createBucket(h){return new tP(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,l,u){if(h==="lineBlendComposite")return{};const p=VY(this);return{config:new ee(this,{zoom:l,lut:u}),defines:p,overrideFog:!1}}queryRadius(h){const l=h,u=HY(Sg("line-width",this,l),Sg("line-gap-width",this,l)),p=Sg("line-offset",this,l);return u/2+Math.abs(p)+EI(this.paint.get("line-translate"))}queryIntersectsFeature(h,l,u,p,y,b){if(h.queryGeometry.isAboveHorizon)return!1;const S=qW(h.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),b.angle,h.pixelToTileUnitsFactor),k=h.pixelToTileUnitsFactor/2*HY(this.paint.get("line-width").evaluate(l,u),this.paint.get("line-gap-width").evaluate(l,u)),j=this.paint.get("line-offset").evaluate(l,u);return j&&(p=function(O,z){const U=[],q=new Mt(0,0);for(let K=0;K=3){for(let Z=0;Z{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=void 0,this._callback=()=>{}}}class oX{constructor(l){this._stringToNumber={},this._numberToString=[];for(let u=0;u=0&&q[3]>=0&&O.insert(j,q[0],q[1],q[2],q[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new Qn(new rP(this.rawTileData)).layers,this.sourceLayerCoder=new oX(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const l in this.vtLayers)this.vtFeatures[l]=[]}return this.vtLayers}query(l,u){const{tilespaceGeometry:p,transform:y,tileTransform:b,pixelPosMatrix:S,availableImages:k,worldview:j}=u;this.loadVTLayers(),this.serializedLayersCache.clear();const O=u.queryRadius?u.queryRadius:0,z=p.bufferedTilespaceBounds,U=this.grid.query(z.min.x,z.min.y,z.max.x,z.max.y,(J,ne,ae,he)=>yf(p.bufferedTilespaceGeometry,J-O,ne-O,ae+O,he+O));U.sort(lje);let q=null;y.elevation&&U.length>0&&(q=mb.create(y.elevation,this.tileID));const K={};let Z;for(let J=0;J(he||(he=$r(ce,this.tileID.canonical,b)),ye.queryIntersectsFeature(p,ce,Ee,he,this.z,y,S,q,Ce,u.scope)))}return K}loadMatchingFeature(l,u,p,y,b,S){const{featureIndex:k,bucketIndex:j,sourceLayerIndex:O,layoutVertexArrayOffset:z}=u,U=this.bucketLayerIDs[j],q=p.layers,K=Object.keys(q);if(K.length&&!Fr(K,U))return;const Z=p.sourceCache,J=this.sourceLayerCoder.decode(O),ne=this.vtLayers[J].feature(k),ae=this.getId(ne,J);for(let he=0;he`${k.key}: ${k.message}`).join(", ");return void Br(`Failed to create expression for promoteId: ${S}`)}this.promoteIdExpression=b.value}p=this.promoteIdExpression.evaluate({zoom:0},l)}else p=l.properties[y];typeof p=="boolean"&&(p=Number(p))}return p}}function cX(h,l,u,p,y){return zt(h,(b,S)=>{const k=l instanceof fh?l.get(S):null;return k&&k.evaluate?k.evaluate(u,p,void 0,y):k})}function lje(h,l){return l-h}function uX(h,l){const u={};if(!l)return u;for(const p of h){const y=p.layerIds.map(b=>l.getLayer(b)).filter(Boolean);if(y.length!==0){p.layers=y,p.stateDependentLayerIds&&(p.stateDependentLayers=p.stateDependentLayerIds.map(b=>y.filter(S=>S.id===b)[0]));for(const b of y)u[b.fqid]=p}}return u}vr(lX,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const Td=32,Tf=33,Ig=new Uint16Array(8184);for(let h=0;h<2046;h++){let l=h+2,u=0,p=0,y=0,b=0,S=0,k=0;for(1&l?y=b=S=Td:u=p=k=Td;(l>>=1)>1;){const O=u+y>>1,z=p+b>>1;1&l?(y=u,b=p,u=S,p=k):(u=y,p=b,y=S,b=k),S=O,k=z}const j=4*h;Ig[j+0]=u,Ig[j+1]=p,Ig[j+2]=y,Ig[j+3]=b}const Ef=new Uint16Array(2178),Pg=new Uint8Array(1089),wP=new Uint16Array(1089);function dX(h){return h===0?-.03125:h===32?.03125:0}const hX={Other:0,Symbol:1,FillExtrusion:2},fX={type:2,extent:ar,loadGeometry:()=>[[new Mt(0,0),new Mt(8193,0),new Mt(8193,8193),new Mt(0,8193),new Mt(0,0)]]};class cje{constructor(){this.tasks={},this.taskQueue=[],ht(["process"],this),this.invoker=new oje(this.process),this.nextId=0}add(l,u){const p=this.nextId++,y=function({type:b,renderSourceType:S,zoom:k}){k=k||0;const j=S===hX.Symbol;return b==="message"?0:b!=="maybePrepare"||j?b!=="parseTile"||j?b==="parseTile"&&j?300-k:b==="maybePrepare"&&j?400-k:500:200-k:100-k}(u);if(y===0){try{l()}finally{}return null}return this.tasks[p]={fn:l,metadata:u,priority:y,id:p},this.taskQueue.push(p),this.invoker.trigger(),{cancel:()=>{delete this.tasks[p]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(p=>!!this.tasks[p]),!this.taskQueue.length)return;const l=this.pick();if(l===null)return;const u=this.tasks[l];if(delete this.tasks[l],this.taskQueue.length&&this.invoker.trigger(),!u)return;u.fn()}finally{}}pick(){let l=null,u=1/0;for(let y=0;y>16&255)/255,(h>>8&255)/255,(255&h)/255,1)}function bje(h,l,u){h===1?(l.rgb_color=EP(u.readVarint()),l.paint="rgb_color"):h===2?(l.linear_gradient_idx=u.readVarint(),l.paint="linear_gradient_idx"):h===3?(l.radial_gradient_idx=u.readVarint(),l.paint="radial_gradient_idx"):h===5?u.readPackedFloat(l.dasharray):h===6?l.dashoffset=u.readFloat():h===7?l.miterlimit=u.readFloat():h===8?l.opacity=u.readVarint():h===9?l.width=u.readFloat():h===10?l.linecap=u.readVarint():h===11&&(l.linejoin=u.readVarint())}function wje(h,l,u){h===1?l.transform=TP(u,u.readVarint()+u.pos):h===2?l.spread_method=u.readVarint():h===3?l.stops.push(gX(u,u.readVarint()+u.pos)):h===4?l.x1=u.readFloat():h===5?l.y1=u.readFloat():h===6?l.x2=u.readFloat():h===7&&(l.y2=u.readFloat())}function gX(h,l){return h.readFields(Sje,{offset:0,opacity:255,rgb_color:p4},l)}function Sje(h,l,u){h===1?l.offset=u.readFloat():h===2?l.opacity=u.readVarint():h===3&&(l.rgb_color=EP(u.readVarint()))}function Tje(h,l,u){h===1?l.transform=TP(u,u.readVarint()+u.pos):h===2?l.spread_method=u.readVarint():h===3?l.stops.push(gX(u,u.readVarint()+u.pos)):h===4?l.cx=u.readFloat():h===5?l.cy=u.readFloat():h===6?l.r=u.readFloat():h===7?l.fx=u.readFloat():h===8?l.fy=u.readFloat():h===9&&(l.fr=u.readFloat())}function Eje(h,l,u){h===1?l.transform=TP(u,u.readVarint()+u.pos):h===2?l.clip_path_idx=u.readVarint():h===3&&l.children.push(SP(u,u.readVarint()+u.pos))}function Aje(h,l,u){h===1?l.left=l.top=u.readFloat():h===2?l.width=l.height=u.readFloat():h===3?l.top=u.readFloat():h===4?l.height=u.readFloat():h===5?l.mask_type=u.readVarint():h===6?l.mask_idx=u.readVarint():h===7&&l.children.push(SP(u,u.readVarint()+u.pos))}class kje{static calculate(l={},u=[]){const p=new Map,y=new Map;if(Object.keys(l).length===0)return p;u.forEach(b=>{y.set(b.name,b.rgb_color||new Yn(0,0,0))});for(const[b,S]of Object.entries(l))y.has(b)?p.set(y.get(b).toString(),S):console.warn(`Ignoring unknown image variable "${b}"`);return p}}function gb(h,l=255,u){const p=l/255,y=h.toString(),b=u.has(y)?u.get(y).clone():h.clone();return b.a*=p,b.toString()}function ZE(h,l){if(!ru()){const u=document.createElement("canvas");return u.width=h,u.height=l,u}return new OffscreenCanvas(h,l)}let m4,XE=null;function g4(h,l,u,p,y){for(const b of p.children)yX(h,l,u,b,y)}function yX(h,l,u,p,y){p.group?(h.save(),function(b,S,k,j,O){const z=j.mask_idx!=null?k.masks[j.mask_idx]:null,U=j.clip_path_idx!=null?k.clip_paths[j.clip_path_idx]:null;if(j.transform&&(S=yb(j.transform).preMultiplySelf(S)),!function(Z,J,ne){return Z.opacity!==255||J||ne}(j,U!=null,z!=null))return void g4(b,S,k,j,O);const q=ZE(b.canvas.width,b.canvas.height),K=q.getContext("2d");g4(K,S,k,j,O),U&&TX(K,S,k,U),z&&EX(K,S,k,z,O),b.globalAlpha=j.opacity/255,b.drawImage(q,0,0)}(h,l,u,p.group,y),h.restore()):p.path&&(h.save(),function(b,S,k,j,O){b.setTransform(S),j.paint_order===1?(xX(b,k,j,O),vX(b,k,j,O)):(vX(b,k,j,O),xX(b,k,j,O))}(h,l,u,p.path,y),h.restore())}function xX(h,l,u,p){const y=u.fill;if(!y)return;const b=y.opacity/255;switch(h.save(),h.beginPath(),AX(u,h),y.paint){case"rgb_color":h.fillStyle=gb(y.rgb_color,y.opacity,p);break;case"linear_gradient_idx":{const S=l.linear_gradients[y.linear_gradient_idx];S.transform&&h.setTransform(yb(S.transform).preMultiplySelf(h.getTransform())),h.fillStyle=bX(h,S,b,p);break}case"radial_gradient_idx":{const S=l.radial_gradients[y.radial_gradient_idx];S.transform&&h.setTransform(yb(S.transform).preMultiplySelf(h.getTransform())),h.fillStyle=wX(h,S,b,p)}}h.fill(_X(u)),h.restore()}function _X(h){return h.rule===1?"nonzero":h.rule===2?"evenodd":void 0}function vX(h,l,u,p){const y=u.stroke;if(!y)return;const b=kX(u);h.lineWidth=y.width,h.miterLimit=y.miterlimit,h.setLineDash(y.dasharray),h.lineDashOffset=y.dashoffset;const S=y.opacity/255;switch(y.paint){case"rgb_color":h.strokeStyle=gb(y.rgb_color,y.opacity,p);break;case"linear_gradient_idx":h.strokeStyle=bX(h,l.linear_gradients[y.linear_gradient_idx],S,p,!0);break;case"radial_gradient_idx":h.strokeStyle=wX(h,l.radial_gradients[y.radial_gradient_idx],S,p,!0)}switch(y.linejoin){case 2:case 1:h.lineJoin="miter";break;case 3:h.lineJoin="round";break;case 4:h.lineJoin="bevel"}switch(y.linecap){case 1:h.lineCap="butt";break;case 2:h.lineCap="round";break;case 3:h.lineCap="square"}h.stroke(b)}function bX(h,l,u,p,y=!1){if(l.stops.length===1){const q=l.stops[0];return gb(q.rgb_color,q.opacity*u,p)}const{x1:b,y1:S,x2:k,y2:j}=l;let O=new DOMPoint(b,S),z=new DOMPoint(k,j);if(y){const q=yb(l.transform);O=q.transformPoint(O),z=q.transformPoint(z)}const U=h.createLinearGradient(O.x,O.y,z.x,z.y);for(const q of l.stops)U.addColorStop(q.offset,gb(q.rgb_color,q.opacity*u,p));return U}function wX(h,l,u,p,y=!1){if(l.stops.length===1){const ae=l.stops[0];return gb(ae.rgb_color,ae.opacity*u,p)}const b=yb(l.transform),{fx:S,fy:k,fr:j,cx:O,cy:z,r:U}=l;let q=new DOMPoint(S,k),K=new DOMPoint(O,z),Z=j,J=U;if(y){q=b.transformPoint(q),K=b.transformPoint(K);const ae=(b.a+b.d)/2;Z=j*ae,J=l.r*ae}const ne=h.createRadialGradient(q.x,q.y,Z,K.x,K.y,J);for(const ae of l.stops)ne.addColorStop(ae.offset,gb(ae.rgb_color,ae.opacity*u,p));return ne}function SX(h,l,u,p){const y=p.transform?yb(p.transform).preMultiplySelf(l):l,b=ZE(h.canvas.width,h.canvas.height),S=b.getContext("2d");for(const j of p.children)if(j.group)SX(S,y,u,j.group);else if(j.path){const O=j.path,z=new Path2D;z.addPath(kX(O),y),S.fill(z,_X(O))}const k=p.clip_path_idx!=null?u.clip_paths[p.clip_path_idx]:null;k&&TX(S,y,u,k),h.globalCompositeOperation="source-over",h.drawImage(b,0,0)}function TX(h,l,u,p){const y=ZE(h.canvas.width,h.canvas.height);SX(y.getContext("2d"),l,u,p),h.globalCompositeOperation="destination-in",h.drawImage(y,0,0)}function EX(h,l,u,p,y){if(p.children.length===0)return;const b=p.mask_idx!=null?u.masks[p.mask_idx]:null;b&&EX(h,l,u,b,y);const S=h.canvas.width,k=h.canvas.height,j=ZE(S,k),O=j.getContext("2d"),z=p.width,U=p.height,q=p.left,K=p.top,Z=new Path2D,J=new Path2D;J.rect(q,K,z,U),Z.addPath(J,l),O.clip(Z);for(const he of p.children)yX(O,l,u,he,y);const ne=O.getImageData(0,0,S,k),ae=ne.data;if(p.mask_type===1)for(let he=0;hel[S])return null}else{const k=1/p[S];let j=(h[S]-u[S])*k,O=(l[S]-u[S])*k;if(j>O){const z=j;j=O,O=z}if(j>y&&(y=j),Ob)return null}return y}function IX(h,l,u,p,y,b,S,k,j,O,z){const U=p-h,q=y-l,K=b-u,Z=S-h,J=k-l,ne=j-u,ae=z[1]*ne-z[2]*J,he=z[2]*Z-z[0]*ne,ce=z[0]*J-z[1]*Z,ye=U*ae+q*he+K*ce;if(Math.abs(ye)<1e-15)return null;const Ee=1/ye,Ce=O[0]-h,He=O[1]-l,$e=O[2]-u,Ge=(Ce*ae+He*he+$e*ce)*Ee;if(Ge<0||Ge>1)return null;const Ue=He*K-$e*q,Ve=$e*U-Ce*K,yt=Ce*q-He*U,bt=(z[0]*Ue+z[1]*Ve+z[2]*yt)*Ee;return bt<0||Ge+bt>1?null:(Z*Ue+J*Ve+ne*yt)*Ee}function PX(h,l,u){return(h-l)/(u-l)}function NX(h,l,u,p,y,b,S,k,j){const O=1<{const he=ne?1:0,ce=(K+1)*J-he,ye=Z*J,Ee=(Z+1)*J-he;ae[0]=K*J,ae[1]=ye,ae[2]=ce,ae[3]=Ee};let U=new CX(j);const q=[];for(let K=0;K=1;j/=2){const K=k[k.length-1];U=new CX(j);for(let Z=0;Z0;){const{idx:Z,t:J,nodex:ne,nodey:ae,depth:he}=K.pop();if(this.leaves[Z]){NX(ne,ae,he,l,u,p,y,U,q);const ye=1<=Ct[2])return J}continue}let ce=0;for(let ye=0;ye=O[z[$e]]&&(z.splice($e,0,ye),He=!0);He||(z[ce]=ye),ce++}}for(let ye=0;ye=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+(l+1)}static pack(l,u){const p=[0,0,0,0],y=kP.getUnpackVector(u);let b=Math.floor((l+y[3])/y[2]);return p[2]=b%256,b=Math.floor(b/256),p[1]=b%256,b=Math.floor(b/256),p[0]=b,p}getPixels(){return new mK({width:this.stride,height:this.stride},this.pixels)}backfillBorder(l,u,p){if(this.dim!==l.dim)throw new Error("dem dimension mismatch");let y=u*this.dim,b=u*this.dim+this.dim,S=p*this.dim,k=p*this.dim+this.dim;switch(u){case-1:y=b-1;break;case 1:b=y+1}switch(p){case-1:S=k-1;break;case 1:k=S+1}const j=-u*this.dim,O=-p*this.dim;for(let z=S;z=1;p--){const y=p===1?1:0,b=p===2?1:0;for(let S=0;S>>1^-(1&h[l]);return h}function $je(h,l){switch(l){case"uint32":return h;case"uint16":for(let u=0;u>4|(61440&p)>>8|(240&y)<<4|61440&y,h[u+1]=15&p|(3840&p)>>4|(15&y)<<8|(3840&y)<<4}return h;case"uint8":for(let u=0;u>6|(192&y)>>4|(192&b)>>2|192&S,h[u+1]=(48&p)>>4|(48&y)>>2|48&b|(48&S)<<2,h[u+2]=(12&p)>>2|12&y|(12&b)<<2|(12&S)<<4,h[u+3]=3&p|(3&y)<<2|(3&b)<<4|(3&S)<<6}return h;default:throw new Error(`Invalid pixel format, "${l}"`)}}vr(kP,"DEMData"),vr(RX,"DemMinMaxQuadTree",{omit:["dem"]});var Fu=Uint8Array,QE=Uint16Array,Uje=Int32Array,DX=new Fu([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]),OX=new Fu([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]),Vje=new Fu([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),MX=function(h,l){for(var u=new QE(31),p=0;p<31;++p)u[p]=l+=1<>1|(21845&va)<<1;zX[va]=((65280&(xb=(61680&(xb=(52428&xb)>>2|(13107&xb)<<2))>>4|(3855&xb)<<4))>>8|(255&xb)<<8)>>1}var JE=function(h,l,u){for(var p=h.length,y=0,b=new QE(l);y>j]=O;return S},e2=new Fu(288);for(va=0;va<144;++va)e2[va]=8;for(va=144;va<256;++va)e2[va]=9;for(va=256;va<280;++va)e2[va]=7;for(va=280;va<288;++va)e2[va]=8;var $X=new Fu(32);for(va=0;va<32;++va)$X[va]=5;var Hje=JE(e2,9),Wje=JE($X,5),x4=function(h){for(var l=h[0],u=1;ul&&(l=h[u]);return l},vh=function(h,l,u){var p=l/8|0;return(h[p]|h[p+1]<<8)>>(7&l)&u},_4=function(h,l){var u=l/8|0;return(h[u]|h[u+1]<<8|h[u+2]<<16)>>(7&l)},Kje=function(h){return(h+7)/8|0},Yje=["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"],bh=function(h,l,u){var p=new Error(l||Yje[h]);if(p.code=h,Error.captureStackTrace&&Error.captureStackTrace(p,bh),!u)throw p;return p},Zje=new Fu(0),Xje=typeof TextDecoder<"u"&&new TextDecoder;try{Xje.decode(Zje,{stream:!0})}catch{}const Qje={gzip_data:"gzip"};class Ed extends Error{constructor(l){super(l),this.name="MRTError"}}const Jje={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},UX={uint32:1,uint16:2,uint8:4},eIe={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let v4;class CP{constructor(l=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=l}getLayer(l){const u=this.layers[l];if(!u)throw new Ed(`Layer '${l}' not found`);return u}getHeaderLength(l){const u=new Uint8Array(l),p=new DataView(l);if(u[0]!==13)throw new Ed("File is not a valid MRT.");return p.getUint32(1,!0)}parseHeader(l){const u=new Uint8Array(l),p=this.getHeaderLength(l);if(u.length= ${p} but got buffer of length ${u.length}`);const y=new v4(u.subarray(0,p)).readFields(Pje,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==y.x||this.y!==y.y||this.z!==y.z))throw new Ed(`Invalid attempt to parse header ${y.z}/${y.x}/${y.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=y.x,this.y=y.y,this.z=y.z;for(const b of y.layers)this.layers[b.name]=new VX(b,{cacheSize:this._cacheSize});return this}createDecodingTask(l){const u=[],p=this.getLayer(l.layerName);for(let y of l.blockIndices){const b=p.dataIndex[y],S=b.firstByte-l.firstByte,k=b.lastByte-l.firstByte;if(p._blocksInProgress.has(y))continue;const j={layerName:p.name,firstByte:S,lastByte:k,pixelFormat:p.pixelFormat,blockIndex:y,blockShape:[b.bands.length].concat(p.bandShape),buffer:p.buffer,codec:b.codec.codec,filters:b.filters.map(O=>O.filter)};p._blocksInProgress.add(y),u.push(j)}return new qX(u,()=>{u.forEach(y=>p._blocksInProgress.delete(y.blockIndex))},(y,b)=>{if(u.forEach(S=>p._blocksInProgress.delete(S.blockIndex)),y)throw y;b.forEach(S=>{this.getLayer(S.layerName).processDecodedData(S)})})}}class VX{constructor({version:l,name:u,units:p,tileSize:y,pixelFormat:b,buffer:S,dataIndex:k},j){if(this.version=l,this.version!==1)throw new Ed(`Cannot parse raster layer encoded with MRT version ${l}`);this.name=u,this.units=p,this.tileSize=y,this.buffer=S,this.pixelFormat=Jje[b],this.dataIndex=k,this.bandShape=[y+2*S,y+2*S,UX[this.pixelFormat]],this._decodedBlocks=new AP(j?j.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return UX[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:l})=>l).flat()}processDecodedData(l){const u=l.blockIndex.toString();this._decodedBlocks.get(u)||this._decodedBlocks.put(u,l.data)}getBlockForBand(l){let u=0;switch(typeof l){case"string":for(const[p,y]of this.dataIndex.entries()){for(const[b,S]of y.bands.entries())if(S===l)return{bandIndex:u+b,blockIndex:p,blockBandIndex:b};u+=y.bands.length}break;case"number":for(const[p,y]of this.dataIndex.entries()){if(l>=u&&lthis.cacheSize)throw new Ed(`Number of blocks to decode (${b.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:u,lastByte:p,blockIndices:y}}hasBand(l){const{blockIndex:u}=this.getBlockForBand(l);return u>=0}hasDataForBand(l){const{blockIndex:u}=this.getBlockForBand(l);return u>=0&&!!this._decodedBlocks.get(u.toString())}getBandView(l){const{blockIndex:u,blockBandIndex:p}=this.getBlockForBand(l);if(u<0)throw new Ed(`Band not found: ${JSON.stringify(l)}`);const y=this._decodedBlocks.get(u.toString());if(!y)throw new Ed(`Data for band ${JSON.stringify(l)} of layer "${this.name}" not decoded.`);const b=this.dataIndex[u],S=this.bandShape.reduce((O,z)=>O*z,1),k=p*S,j=y.subarray(k,k+S);return{data:j,bytes:new Uint8Array(j.buffer).subarray(j.byteOffset,j.byteOffset+j.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:b.offset,scale:b.scale}}}CP.setPbf=function(h){v4=h};class qX{constructor(l,u,p){this.tasks=l,this._onCancel=u,this._onComplete=p,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(l,u){this._finalized||(this._onComplete(l,u),this._finalized=!0)}}CP.performDecoding=function(h,l){const u=new Uint8Array(h);return Promise.all(l.tasks.map(p=>{const{layerName:y,firstByte:b,lastByte:S,pixelFormat:k,blockShape:j,blockIndex:O,filters:z,codec:U}=p,q=u.subarray(b,S+1),K=new Uint32Array(j[0]*j[1]*j[2]);let Z;if(U!=="gzip_data")throw new Ed(`Unhandled codec: ${U}`);return Z=function(J,ne){if(!globalThis.DecompressionStream&&ne==="gzip_data")return Promise.resolve((Ee=function($e){$e[0]==31&&$e[1]==139&&$e[2]==8||bh(6,"invalid gzip data");var Ge=$e[3],Ue=10;4&Ge&&(Ue+=2+($e[10]|$e[11]<<8));for(var Ve=(Ge>>3&1)+(Ge>>4&1);Ve>0;Ve-=!$e[Ue++]);return Ue+(2&Ge)}(ae=J),Ee+8>ae.length&&bh(6,"invalid gzip data"),function($e,Ge,Ue,Ve){var yt=$e.length;if(!yt||Ge.f&&!Ge.l)return Ue||new Fu(0);var bt=!Ue,kt=bt||Ge.i!=2,It=Ge.i;bt&&(Ue=new Fu(3*yt));var Ct=function(ps){var Xo=Ue.length;if(ps>Xo){var Ha=new Fu(Math.max(2*Xo,ps));Ha.set(Ue),Ue=Ha}},Bt=Ge.f||0,pt=Ge.p||0,jt=Ge.b||0,Lt=Ge.l,$t=Ge.d,Wt=Ge.m,xr=Ge.n,ir=8*yt;do{if(!Lt){Bt=vh($e,pt,1);var nr=vh($e,pt+1,3);if(pt+=3,!nr){var Kt=$e[(ri=Kje(pt)+4)-4]|$e[ri-3]<<8,mr=ri+Kt;if(mr>yt){It&&bh(0);break}kt&&Ct(jt+Kt),Ue.set($e.subarray(ri,mr),jt),Ge.b=jt+=Kt,Ge.p=pt=8*mr,Ge.f=Bt;continue}if(nr==1)Lt=Hje,$t=Wje,Wt=9,xr=5;else if(nr==2){var kr=vh($e,pt,31)+257,zr=vh($e,pt+10,15)+4,Rr=kr+vh($e,pt+5,31)+1;pt+=14;for(var ln=new Fu(Rr),zn=new Fu(19),cn=0;cn>4)<16)ln[cn++]=ri;else{var Ai=0,os=0;for(ri==16?(os=3+vh($e,pt,3),pt+=2,Ai=ln[cn-1]):ri==17?(os=3+vh($e,pt,7),pt+=3):ri==18&&(os=11+vh($e,pt,127),pt+=7);os--;)ln[cn++]=Ai}}var Ra=ln.subarray(0,kr),ls=ln.subarray(kr);Wt=x4(Ra),xr=x4(ls),Lt=JE(Ra,Wt),$t=JE(ls,xr)}else bh(1);if(pt>ir){It&&bh(0);break}}kt&&Ct(jt+131072);for(var vs=(1<>4;if((pt+=15&Ai)>ir){It&&bh(0);break}if(Ai||bh(2),vo<256)Ue[jt++]=vo;else{if(vo==256){bs=pt,Lt=null;break}var La=vo-254;vo>264&&(La=vh($e,pt,(1<<(Ps=DX[cn=vo-257]))-1)+BX[cn],pt+=Ps);var Tn=$t[_4($e,pt)&qs],yl=Tn>>4;if(Tn||bh(3),pt+=15&Tn,ls=Gje[yl],yl>3){var Ps=OX[yl];ls+=_4($e,pt)&(1<ir){It&&bh(0);break}kt&&Ct(jt+131072);var Ga=jt+La;if(jtps.length)&&(Ha=ps.length),new Fu(ps.subarray(0,Ha))}(Ue,0,jt):Ue.subarray(0,jt)}(ae.subarray(Ee,-8),{i:2},new Fu(((ce=ae)[(ye=ce.length)-4]|ce[ye-3]<<8|ce[ye-2]<<16|ce[ye-1]<<24)>>>0),he)));var ae,he,ce,ye,Ee;const Ce=Qje[ne];if(!Ce)throw new Error(`Unhandled codec: ${ne}`);const He=new globalThis.DecompressionStream(Ce);return new Response(new Blob([J]).stream().pipeThrough(He)).arrayBuffer().then($e=>new Uint8Array($e))}(q,U).then(J=>(function(ne,ae){ne.readFields(Mje,ae)}(new v4(J),K),new eIe[k](K.buffer))),Z.then(J=>{for(let ne=z.length-1;ne>=0;ne--)switch(z[ne]){case"delta_filter":Bje(J,j);break;case"zigzag_filter":zje(J);break;case"bitshuffle_filter":$je(J,k);break;default:throw new Ed(`Unhandled filter "${z[ne]}"`)}return{layerName:y,blockIndex:O,data:J}}).catch(J=>{throw J})}))},vr(qX,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),vr(CP,"MapboxRasterTile"),vr(VX,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const GX=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class b4{static from(l){if(!(l instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[u,p]=new Uint8Array(l,0,2);if(u!==219)throw new Error("Data does not appear to be in a KDBush format.");const y=p>>4;if(y!==1)throw new Error(`Got v${y} data when expected v1.`);const b=GX[15&p];if(!b)throw new Error("Unrecognized array type.");const[S]=new Uint16Array(l,2,1),[k]=new Uint32Array(l,4,1);return new b4(k,S,b,l)}constructor(l,u=64,p=Float64Array,y){if(isNaN(l)||l<0)throw new Error(`Unpexpected numItems value: ${l}.`);this.numItems=+l,this.nodeSize=Math.min(Math.max(+u,2),65535),this.ArrayType=p,this.IndexArrayType=l<65536?Uint16Array:Uint32Array;const b=GX.indexOf(this.ArrayType),S=2*l*this.ArrayType.BYTES_PER_ELEMENT,k=l*this.IndexArrayType.BYTES_PER_ELEMENT,j=(8-k%8)%8;if(b<0)throw new Error(`Unexpected typed array class: ${p}.`);y&&y instanceof ArrayBuffer?(this.data=y,this.ids=new this.IndexArrayType(this.data,8,l),this.coords=new this.ArrayType(this.data,8+k+j,2*l),this._pos=2*l,this._finished=!0):(this.data=new ArrayBuffer(8+S+k+j),this.ids=new this.IndexArrayType(this.data,8,l),this.coords=new this.ArrayType(this.data,8+k+j,2*l),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+b]),new Uint16Array(this.data,2,1)[0]=u,new Uint32Array(this.data,4,1)[0]=l)}add(l,u){const p=this._pos>>1;return this.ids[p]=p,this.coords[this._pos++]=l,this.coords[this._pos++]=u,p}finish(){const l=this._pos>>1;if(l!==this.numItems)throw new Error(`Added ${l} items when expected ${this.numItems}.`);return w4(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(l,u,p,y){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:b,coords:S,nodeSize:k}=this,j=[0,b.length-1,0],O=[];for(;j.length;){const z=j.pop()||0,U=j.pop()||0,q=j.pop()||0;if(U-q<=k){for(let ne=q;ne<=U;ne++){const ae=S[2*ne],he=S[2*ne+1];ae>=l&&ae<=p&&he>=u&&he<=y&&O.push(b[ne])}continue}const K=q+U>>1,Z=S[2*K],J=S[2*K+1];Z>=l&&Z<=p&&J>=u&&J<=y&&O.push(b[K]),(z===0?l<=Z:u<=J)&&(j.push(q),j.push(K-1),j.push(1-z)),(z===0?p>=Z:y>=J)&&(j.push(K+1),j.push(U),j.push(1-z))}return O}within(l,u,p){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:y,coords:b,nodeSize:S}=this,k=[0,y.length-1,0],j=[],O=p*p;for(;k.length;){const z=k.pop()||0,U=k.pop()||0,q=k.pop()||0;if(U-q<=S){for(let ne=q;ne<=U;ne++)WX(b[2*ne],b[2*ne+1],l,u)<=O&&j.push(y[ne]);continue}const K=q+U>>1,Z=b[2*K],J=b[2*K+1];WX(Z,J,l,u)<=O&&j.push(y[K]),(z===0?l-p<=Z:u-p<=J)&&(k.push(q),k.push(K-1),k.push(1-z)),(z===0?l+p>=Z:u+p>=J)&&(k.push(K+1),k.push(U),k.push(1-z))}return j}}function w4(h,l,u,p,y,b){if(y-p<=u)return;const S=p+y>>1;HX(h,l,S,p,y,b),w4(h,l,u,p,S-1,1-b),w4(h,l,u,S+1,y,1-b)}function HX(h,l,u,p,y,b){for(;y>p;){if(y-p>600){const O=y-p+1,z=u-p+1,U=Math.log(O),q=.5*Math.exp(2*U/3),K=.5*Math.sqrt(U*q*(O-q)/O)*(z-O/2<0?-1:1);HX(h,l,u,Math.max(p,Math.floor(u-z*q/O+K)),Math.min(y,Math.floor(u+(O-z)*q/O+K)),b)}const S=l[2*u+b];let k=p,j=y;for(t2(h,l,p,u),l[2*y+b]>S&&t2(h,l,p,y);kS;)j--}l[2*p+b]===S?t2(h,l,p,j):(j++,t2(h,l,j,y)),j<=u&&(p=j+1),u<=j&&(y=j-1)}}function t2(h,l,u,p){S4(h,u,p),S4(l,2*u,2*p),S4(l,2*u+1,2*p+1)}function S4(h,l,u){const p=h[l];h[l]=h[u],h[u]=p}function WX(h,l,u,p){const y=h-u,b=l-p;return y*y+b*b}s.$=lg,s.A=class{constructor(h,l,u){this.target=h,this.parent=l,this.mapId=u,this.callbacks={},this.cancelCallbacks={},ht(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new cje}send(h,l,u,p,y=!1,b){const S=Math.round(1e18*Math.random()).toString(36).substring(0,10);u&&(u.metadata=b,this.callbacks[S]=u);const k=new Set;return this.target.postMessage({id:S,type:h,hasCallback:!!u,targetMapId:p,mustQueue:y,sourceMapId:this.mapId,data:uh(l,k)},k),{cancel:()=>{u&&delete this.callbacks[S],this.target.postMessage({id:S,type:"",targetMapId:p,sourceMapId:this.mapId})}}}receive(h){const l=h.data;if(!l)return;const u=l.id;if(u&&(!l.targetMapId||this.mapId===l.targetMapId))if(l.type===""){const p=this.cancelCallbacks[u];delete this.cancelCallbacks[u],p&&p.cancel()}else if(l.mustQueue||Ci(self)){const p=this.callbacks[u],y=this.scheduler.add(()=>this.processTask(u,l),p&&p.metadata||{type:"message"});y&&(this.cancelCallbacks[u]=y)}else this.processTask(u,l)}processTask(h,l){if(delete this.cancelCallbacks[h],l.type===""){const u=this.callbacks[h];delete this.callbacks[h],u&&(l.error?u(mf(l.error)):u(null,mf(l.data)))}else{const u=new Set,p=l.hasCallback?(b,S)=>{this.target.postMessage({id:h,type:"",sourceMapId:this.mapId,error:b?uh(b):null,data:uh(S,u)},u)}:()=>{},y=mf(l.data);if(this.parent[l.type])this.parent[l.type](l.sourceMapId,y,p);else if(this.parent.getWorkerSource){const b=l.type.split("."),{source:S,scope:k}=y;this.parent.getWorkerSource(l.sourceMapId,{type:b[0],source:S,scope:k,uid:0})[b[1]](y,p)}else p(new Error(`Could not find function ${l.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},s.B=Jm,s.C=Nu,s.D=au,s.E=bx,s.F=Lp,s.G=2,s.H=FE,s.I=rc,s.J=dZ,s.K=av,s.L=cI,s.M=Ax,s.N=kx,s.O=Cv,s.P=Mt,s.Q=kv,s.R=_x,s.S=ET,s.T=Sf,s.U=Hx,s.V=vP,s.W=zv,s.X=pf,s.Y=kT,s.Z=yd,s._=kp,s.a=function(h){return Dn.API_CDN_URL_REGEX.test(h)},s.a$=rP,s.a0=Pa,s.a1=Cx,s.a2=ov,s.a3=tT,s.a4=HT,s.a5=class extends vP{},s.a6=AT,s.a7=Hj,s.a8=nt,s.a9=function(h){const l=h.value;return l?ov(l)?u4(l,!0)?[]:[new vP(h.key,l,`invalid url "${l}"`)]:[new vP(h.key,l,`string expected, "${Ax(l)}" found`)]:[]},s.aA=BY,s.aB=function(h){let l=1/0,u=1/0,p=-1/0,y=-1/0;for(const b of h)l=Math.min(l,b.x),u=Math.min(u,b.y),p=Math.max(p,b.x),y=Math.max(y,b.y);return{min:new Mt(l,u),max:new Mt(p,y)}},s.aC=fe,s.aD=M,s.aE=hr,s.aF=Re,s.aG=Rl,s.aH=Rt,s.aI=gr,s.aJ=function(h,l){const u={};for(let p=0;p=0?l.slice(u+1):""}catch{return""}},s.aN=class{constructor(h){this.entries={},this.scheduler=h}request(h,l,u,p){const y=this.entries[h]=this.entries[h]||{callbacks:[]};if(y.result){const[b,S]=y.result;return this.scheduler?this.scheduler.add(()=>{p(b,S)},l):p(b,S),()=>{}}return y.callbacks.push(p),y.cancel||(y.cancel=u((b,S)=>{y.result=[b,S];for(const k of y.callbacks)this.scheduler?this.scheduler.add(()=>{k(b,S)},l):k(b,S);setTimeout(()=>delete this.entries[h],3e3)})),()=>{y.result||(y.callbacks=y.callbacks.filter(b=>b!==p),y.callbacks.length||(y.cancel(),delete this.entries[h]))}}},s.aO=function(h,l,u){const p=JSON.stringify(h.request);return h.data&&(this.deduped.entries[p]={result:[null,h.data]}),this.deduped.request(p,{type:"parseTile",renderSourceType:h.renderSourceType,zoom:h.tileZoom},y=>{const b=Xm(h.request,(S,k,j)=>{S?QS(S)?y(null,null):y(S):k&&y(null,{rawData:k,vectorTile:u?void 0:new Qn(new rP(k)),responseHeaders:new Map(j.entries())})});return()=>{b.cancel(),y(null,null)}},l)},s.aP=function(h){return h?{cacheControl:h.get("cache-control"),expires:h.get("expires")}:{cacheControl:void 0,expires:void 0}},s.aQ=function(h){KS++,KS>X0&&(h.getActor().send("enforceCacheSizeLimit",Z0),KS=0)},s.aR=gl,s.aS=HZ,s.aT=eX,s.aU=Qe,s.aV=GZ,s.aW=function(h,l){const u=document.createElement("video");u.muted=!0,u.onloadstart=function(){l(null,u)};for(let p=0;p{}}},s.aX=RE,s.aY=w_,s.aZ=ht,s.a_=CP,s.aa=Bv,s.ab=ts,s.ac=Xt,s.ad=class{constructor(h){this.specification=h}possiblyEvaluate(h,l){return Rn(h.expression.evaluate(l))}interpolate(h,l,u){return{x:Xr(h.x,l.x,u),y:Xr(h.y,l.y,u),z:Xr(h.z,l.z,u),azimuthal:Xr(h.azimuthal,l.azimuthal,u),polar:Xr(h.polar,l.polar,u)}}},s.ae=ti,s.af=jp,s.ag=Ar,s.ah=or,s.ai=Oe,s.aj=Me,s.ak=fh,s.al=$p,s.am=Xr,s.an=ar,s.ao=Ru,s.ap=Kn,s.aq=Yn,s.ar=class{constructor(h){this.specification=h}possiblyEvaluate(h,l){return function([u,p]){const y=Rn([1,u,p]);return{x:y.x,y:y.y,z:y.z}}(h.expression.evaluate(l))}interpolate(h,l,u){return{x:Xr(h.x,l.x,u),y:Xr(h.y,l.y,u),z:Xr(h.z,l.z,u)}}},s.as=function(h,l,u=0,p=!0){const y=new Mt(u,u),b=h.sub(y),S=l.add(y),k=[b,new Mt(S.x,b.y),S,new Mt(b.x,S.y)];return p&&k.push(b.clone()),k},s.at=function(h,l){const u=[];for(let p=0;pthis.buckets[U].layers.some(q=>S.has(q.fqid))),j=Object.keys(this.buckets).some(U=>this.buckets[U].layers.some(q=>q.hasTransition&&q.hasTransition())),O=this._firstPrepareComplete&&b!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(l));const z=this._lastUpdatedBrightness!==p;this._lastAvailableImagesCount=b,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||p||this._hasAppearances||k||j||O)&&(!(this._hasAppearances||k||j||O)&&this._lastUpdatedBrightness&&p&&Math.abs(this._lastUpdatedBrightness-p)<.001||(this.updateBuckets(l,z,void 0,O||k||j,S,y),this._lastUpdatedBrightness=p))}evaluateQueryRenderedFeaturePadding(){let h=0;for(const l in this.buckets){const u=this.buckets[l];u.evaluateQueryRenderedFeaturePadding&&(h=Math.max(h,u.evaluateQueryRenderedFeaturePadding()))}return h}queryRenderedFeatures(h,l,u,p,y,b,S){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const k=this.evaluateQueryRenderedFeaturePadding(),j=function(O,z){const U=Q([],[.5*O.width,.5*-O.height,1]);return B(U,U,[1,-1,0]),M(U,U,O.calculateProjMatrix(z.toUnwrapped())),Float32Array.from(U)}(y,this.tileID);return this.latestFeatureIndex.query(h,{tilespaceGeometry:l,pixelPosMatrix:j,transform:p,availableImages:u,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:k,scope:S})}querySourceFeatures(h,l){const u=this.latestFeatureIndex;if(!u||!u.rawTileData)return;const p=u.loadVTLayers(),y=l?l.sourceLayer:"",b=p._geojsonTileLayer||p[y];if(!b)return;const S=$v(l&&l.filter),{z:k,x:j,y:O}=this.tileID.canonical,z={z:k,x:j,y:O};for(let U=0;Uu)p=!1;else if(l)if(this.expirationTimeu.appearances&&u.appearances.length>0))return!0;return!1}updateBuckets(h,l,u,p,y,b){if(!this.latestFeatureIndex||!h.style)return;const S=b||h.style.listImages(),k=h.style.getBrightness(),j=y||new Set;for(const O in this.buckets){if(!h.style.hasLayer(O))continue;const z=this.buckets[O],U=z.layers[0],q=U.sourceLayer||"_geojsonTileLayer",K=h.style.getLayerSourceCache(U),Z=z.layers.some(Ee=>j.has(Ee.fqid)),J=(p||Z)&&z instanceof _h?h.style.getOwnLayer(O):void 0;let ne=u&&u[q]||{};K&&!u&&(ne=K._state.getState(q,void 0));const ae=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},he=Object.keys(ne).length>0&&!l;z.hasAppearances=z.layers.some(Ee=>Ee.appearances&&Ee.appearances.length>0);const ce=he?z.stateDependentLayers:z.layers;if(he&&z.stateDependentLayers.length!==0||l||Z||p){const Ee=this.latestFeatureIndex.loadVTLayers()[q];if(z.update(ne,Ee,S,ae,ce,l,k,this.tileID.canonical),(p||Z)&&!l&&z instanceof _h&&J&&J.type==="symbol"){const Ce=z;Ce.text&&Ce.text.uboBinder&&Ce.text.uboBinder.updateDynamicExpressions(J,Ee,this.tileID.canonical,S,ne,k),Ce.icon&&Ce.icon.uboBinder&&Ce.icon.uboBinder.updateDynamicExpressions(J,Ee,this.tileID.canonical,S,ne,k)}if(z instanceof _h){const Ce=z,He=h.context;Ce.text&&Ce.text.uboBinder&&Ce.text.uboBinder.upload(He),Ce.icon&&Ce.icon.uboBinder&&Ce.icon.uboBinder.upload(He)}}if(he&&z.stateDependentLayers.length!==0||l||z.hasAppearances){const Ee={zoom:h.transform.zoom,pitch:h.transform.pitch,brightness:h.style.getBrightness()||0,worldview:h.worldview},Ce=z.updateAppearances(this.tileID.canonical,ne,S,Ee,h.imageManager,he&&z.stateDependentLayers.length!==0);if(Ce&&Ce.hasUboChanges){const He=h.context;z instanceof _h&&z.text&&z.text.uboBinder&&z.text.uboBinder.upload(He),z instanceof _h&&z.icon&&z.icon.uboBinder&&z.icon.uboBinder.upload(He)}}(z instanceof tP||z instanceof OI)&&h._terrain&&h._terrain.enabled&&K&&z.uploadPending()&&h._terrain._clearRenderCacheForTile(K.id,this.tileID);const ye=h&&h.style&&h.style.getOwnLayer(O);ye&&(this.queryPadding=Math.max(this.queryPadding,ye.queryRadius(z)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;J--){const ne=4*J,ae=Ig[ne+0],he=Ig[ne+1],ce=Ig[ne+2],ye=Ig[ne+3],Ee=ae+ce>>1,Ce=he+ye>>1,He=Ee+Ce-he,$e=Ce+ae-Ee,Ge=he*Tf+ae,Ue=ye*Tf+ce,Ve=Ce*Tf+Ee,yt=Math.hypot((Ef[2*Ge+0]+Ef[2*Ue+0])/2-Ef[2*Ve+0],(Ef[2*Ge+1]+Ef[2*Ue+1])/2-Ef[2*Ve+1])>=16;Pg[Ve]=Pg[Ve]||(yt?1:0),J<1022&&(Pg[Ve]=Pg[Ve]||Pg[(he+$e>>1)*Tf+(ae+He>>1)]||Pg[(ye+$e>>1)*Tf+(ce+He>>1)])}const z=new xo,U=new _s;let q=0;function K(J,ne){const ae=ne*Tf+J;return wP[ae]===0&&(z.emplaceBack(Ef[2*ae+0],Ef[2*ae+1],J*ar/Td,ne*ar/Td),wP[ae]=++q),wP[ae]-1}function Z(J,ne,ae,he,ce,ye){const Ee=J+ae>>1,Ce=ne+he>>1;if(Math.abs(J-ce)+Math.abs(ne-ye)>1&&Pg[Ce*Tf+Ee])Z(ce,ye,J,ne,Ee,Ce),Z(ae,he,ce,ye,Ee,Ce);else{const He=K(J,ne),$e=K(ae,he),Ge=K(ce,ye);U.emplaceBack(He,$e,Ge)}}return Z(0,0,Td,Td,Td,0),Z(Td,Td,0,0,0,Td),{vertices:z,indices:U}}(this.tileID.canonical,l);p=b.vertices,y=b.indices}else{p=new xo,y=new _s;for(const{x:S,y:k}of u)p.emplaceBack(S,k,0,0);const b=rb(p.int16.subarray(0,4*p.length),void 0,4);for(let S=0;S0&&(S=D(new Float64Array(16),l.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(h,p,l,y,S,b),this._makeGlobeTileDebugTextBuffer(h,p,l,y,S,b)}_globePoint(h,l,u,p,y,b,S){let k=gE(h,l,u);if(b){const j=1<.5?q=-1:U<-.5&&(q=1);let K=(h/ar+u.x)/j+q,Z=(l/ar+u.y)/j;K=(K-O)*p._pixelsPerMercatorPixel+O,Z=(Z-z)*p._pixelsPerMercatorPixel+z;const J=[K*p.worldSize,Z*p.worldSize,0];or(J,J,b),k=zp(k,J,S)}return or(k,k,y)}_makeGlobeTileDebugBorderBuffer(h,l,u,p,y,b){const S=new ic,k=new Mp,j=new bd,O=(U,q,K,Z,J)=>{const ne=(K-U)/(J-1),ae=(Z-q)/(J-1),he=S.length;for(let ce=0;ceO*U+q;for(let U=0;U1)return!1;const u=l.getSource().maxzoom,p=1<1)return l;const y=p.getSource().maxzoom,b=1<{const k=this.getAtTileOffset(h,y,b,S),j=p.upVector(h.canonical,y.x,y.y);return We(j,j,k*p.upVectorScale(h.canonical,l,u).metersToTile),j}}getForTilePoints(h,l,u,p){if(this.isUsingMockSource())return!1;const y=mb.create(this,h,p);return!!y&&(l.forEach(b=>{b[2]=this.exaggeration()*y.getElevationAt(b[0],b[1],u)}),!0)}getMinMaxForTile(h){if(this.isUsingMockSource())return null;const l=this.findDEMTileFor(h);if(!l||!l.dem)return null;const u=l.dem.tree,p=l.tileID,y=1<0&&(p+=(h[y]-0)*(h[y]-0)),l[y]<0&&(p+=(0-l[y])*(0-l[y]));return p},s.cL=function(h){return h*h*h*h*h},s.cM=ft,s.cN=45,s.cO=Jv,s.cP=function(h,l,u){const p=Math.sqrt(h*h+l*l+u*u),y=p>0?Math.acos(u/p)*ks:0;let b=h!==0||l!==0?Math.atan2(-l,-h)*ks+90:0;return b<0&&(b+=360),[p,b,y]},s.cQ=Ae,s.cR=Rn,s.cS=Dt,s.cT=ge,s.cU=si,s.cV=Ne,s.cW=function(h){return[Math.pow(h[0],1/2.2),Math.pow(h[1],1/2.2),Math.pow(h[2],1/2.2)]},s.cX=wY,s.cY=N5,s.cZ=kY,s.c_=u4,s.ca=2,s.cb=7,s.cc=6,s.cd=wt,s.ce=Se,s.cf=ve,s.cg=0,s.ch=1,s.ci=4,s.cj=5,s.ck=tb,s.cl=sc,s.cm=TY,s.cn=h_,s.co=JW,s.cp=function(h,l,u,p,y,b,S,k,j){if(j.name==="globe")return JW(h,l,new h_(u,p,y),!1);const O=__({z:u,x:p,y},j);return new si([(b+O.x/O.scale)*l,l*(O.y/O.scale),S],[(b+O.x2/O.scale)*l,l*(O.y2/O.scale),k])},s.cq=function(h,l,u){return h[0]=Math.min(l[0],u[0]),h[1]=Math.min(l[1],u[1]),h[2]=Math.min(l[2],u[2]),h[3]=Math.min(l[3],u[3]),h},s.cr=function(h,l,u){return h[0]=Math.max(l[0],u[0]),h[1]=Math.max(l[1],u[1]),h[2]=Math.max(l[2],u[2]),h[3]=Math.max(l[3],u[3]),h},s.cs=function(h){const l=Math.round((h+45+360)%360/90)%4;return tu[l]},s.ct=St,s.cu=Ot,s.cv=6,s.cw=function(h){const l=R(new Float64Array(16));M(l,h.pixelMatrix,h.globeMatrix);const u=[0,ze,0],p=[0,Ke,0];return or(u,u,l),or(p,p,l),[u[0]>0&&u[0]<=h.width&&u[1]>0&&u[1]<=h.height&&!J3(h,new Qe(h.center.lat,90)),p[0]>0&&p[0]<=h.width&&p[1]>0&&p[1]<=h.height&&!J3(h,new Qe(h.center.lat,-90))]},s.cx=function(h,l){const{scale:u}=h.tileTransform,p=u*ar/(h.tileSize*Math.pow(2,l.zoom-h.tileID.overscaledZ+h.tileID.canonical.z));return function(y,b,S){var k=b[1],j=b[2],O=b[3],z=S[0],U=S[1];return y[0]=b[0]*z,y[1]=k*z,y[2]=j*U,y[3]=O*U,y}(new Float32Array(4),l.inverseAdjustmentMatrix,[p,p])},s.cy=YI,s.cz=_e,s.d=function(h){return Dn.API_TILEJSON_REGEX.test(h)},s.d$=cAe,s.d0=hs,s.d1=class{static calculate(h,l,u){const p=new Set,y=new Map,b=new Set,S=new Set;for(const j of Object.values(h))for(const[O,z]of Object.entries(j.floors)){b.add(O),z.isDefault&&S.add(O),z.conflicts&&y.set(O,z.conflicts);const U=O===l,q=z.connections&&l&&z.connections.has(l);(U||q)&&p.add(O)}const k=j=>{const O=y.get(j)||new Set;for(const z of p)if((y.get(z)||new Set).has(j)||O.has(z))return!0;return!1};if(u)for(const j of u)b.has(j)&&(k(j)||p.add(j));for(const j of S)p.has(j)||k(j)||p.add(j);return p}},s.d2=aP,s.d3=X5,s.d4=Xn,s.d5=function(){return{API_URL:Dn.API_URL,DRACO_URL:Dn.DRACO_URL,MESHOPT_URL:Dn.MESHOPT_URL,MESHOPT_SIMD_URL:Dn.MESHOPT_SIMD_URL,BUILDING_GEN_URL:Dn.BUILDING_GEN_URL}},s.d6=aI,s.d7=HS,s.d8=af,s.d9=fr,s.dA=kI,s.dB=ic,s.dC=_s,s.dD=function(h,l){return[Math.pow(h[0],2.2)*l,Math.pow(h[1],2.2)*l,Math.pow(h[2],2.2)*l]},s.dE=_,s.dF=function(h,l){var u=Math.sin(l),p=Math.cos(l);return h[0]=p,h[1]=u,h[2]=0,h[3]=-u,h[4]=p,h[5]=0,h[6]=0,h[7]=0,h[8]=1,h},s.dG=Sr,s.dH=tK,s.dI=ji,s.dJ=ss,s.dK=l4,s.dL=function(h,l){const u=[0,0,0];return or(u,u,yE(vf(l.canonical))),or(u,u,h),u},s.dM=h=>({u_matrix:new d(h),u_texsize:new du(h),u_pixels_to_tile_units:new A(h),u_device_pixel_ratio:new oa(h),u_width_scale:new oa(h),u_floor_width_scale:new oa(h),u_image:new u_(h),u_units_to_pixels:new du(h),u_tile_units_to_pixels:new oa(h),u_alpha_discard_threshold:new oa(h),u_trim_offset:new du(h),u_trim_fade_range:new du(h),u_trim_gradient_mix_range:new du(h),u_trim_color:new Jv(h),u_zbias_factor:new oa(h),u_tile_to_meter:new oa(h),u_ground_shadow_factor:new d_(h),u_pattern_transition:new oa(h)}),s.dN=h=>({u_matrix:new d(h),u_pixels_to_tile_units:new A(h),u_device_pixel_ratio:new oa(h),u_width_scale:new oa(h),u_floor_width_scale:new oa(h),u_units_to_pixels:new du(h),u_dash_image:new u_(h),u_gradient_image:new u_(h),u_image_height:new oa(h),u_texsize:new du(h),u_tile_units_to_pixels:new oa(h),u_alpha_discard_threshold:new oa(h),u_trim_offset:new du(h),u_trim_fade_range:new du(h),u_trim_gradient_mix_range:new du(h),u_trim_color:new Jv(h),u_zbias_factor:new oa(h),u_tile_to_meter:new oa(h),u_ground_shadow_factor:new d_(h)}),s.dO=h=>({u_camera_to_center_distance:new oa(h),u_extrude_scale:new A(h),u_device_pixel_ratio:new oa(h),u_matrix:new d(h),u_inv_rot_matrix:new d(h),u_merc_center:new du(h),u_tile_id:new d_(h),u_zoom_transition:new oa(h),u_up_dir:new d_(h),u_emissive_strength:new oa(h)}),s.dP=iE,s.dQ=lCe,s.dR=class{constructor(h,l,u,p){this.context=h,this.format=p,this.size=u,this.texture=h.gl.createTexture();const[y,b,S]=this.size,{gl:k}=h;k.bindTexture(k.TEXTURE_3D,this.texture),h.pixelStoreUnpackFlipY.set(!1),h.pixelStoreUnpack.set(1),h.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in l&&l.data&&k.texImage3D(k.TEXTURE_3D,0,this.format,y,b,S,0,E5(this.format),A5(this.format),l.data)}bind(h,l){const{context:u}=this,{gl:p}=u;p.bindTexture(p.TEXTURE_3D,this.texture),h!==this.minFilter&&(p.texParameteri(p.TEXTURE_3D,p.TEXTURE_MAG_FILTER,h),p.texParameteri(p.TEXTURE_3D,p.TEXTURE_MIN_FILTER,h),this.minFilter=h),l!==this.wrapS&&(p.texParameteri(p.TEXTURE_3D,p.TEXTURE_WRAP_S,l),p.texParameteri(p.TEXTURE_3D,p.TEXTURE_WRAP_T,l),this.wrapS=l)}destroy(){const{gl:h}=this.context;h.deleteTexture(this.texture),this.texture=null}},s.dS=sK,s.dT=(h,l,u,p,y,b)=>{const S=h.transform,k=S.projection.name==="globe";let j;if(b.paint.get("circle-pitch-alignment")==="map")if(k){const z=tK(S.zoom,l.canonical)*S._pixelsPerMercatorPixel;j=Float32Array.from([z,0,0,z])}else j=S.calculatePixelsToTileUnitsMatrix(u);else j=new Float32Array([S.pixelsToGLUnits[0],0,0,S.pixelsToGLUnits[1]]);const O={u_camera_to_center_distance:h.transform.getCameraToCenterDistance(S.projection),u_matrix:h.translatePosMatrix(l.projMatrix,u,b.paint.get("circle-translate"),b.paint.get("circle-translate-anchor")),u_device_pixel_ratio:Pl.devicePixelRatio,u_extrude_scale:j,u_inv_rot_matrix:mAe,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(k){O.u_inv_rot_matrix=p,O.u_merc_center=y,O.u_tile_id=[l.canonical.x,l.canonical.y,1<{const z=h.transform,U=z.pitch<15?zY(.07,.7,fe((14-z.zoom)/5,0,1)):.07,q=u.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:UY(h,l,u,p),u_texsize:l.imageAtlasTexture?l.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:z.calculatePixelsToTileUnitsMatrix(l),u_device_pixel_ratio:y,u_width_scale:b,u_floor_width_scale:S,u_image:0,u_tile_units_to_pixels:$Y(l,z),u_units_to_pixels:[1/z.pixelsToGLUnits[0],1/z.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:k,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:Dt(l.tileID.canonical,0),u_ground_shadow_factor:j,u_pattern_transition:O}},s.dX=(h,l,u,p,y,b,S,k,j,O)=>{const z=h.transform,U=z.calculatePixelsToTileUnitsMatrix(l),q=u.paint.get("line-trim-color-use-theme").constantOr("default")==="none",K=z.pitch<15?zY(.07,.7,fe((14-z.zoom)/5,0,1)):.07;return{u_matrix:UY(h,l,u,p),u_pixels_to_tile_units:U,u_device_pixel_ratio:b,u_width_scale:S,u_floor_width_scale:k,u_units_to_pixels:[1/z.pixelsToGLUnits[0],1/z.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:y,u_texsize:qY(u)&&l.lineAtlasTexture?l.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:$Y(l,h.transform),u_alpha_discard_threshold:0,u_trim_offset:j,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_tile_to_meter:Dt(l.tileID.canonical,0),u_ground_shadow_factor:O}},s.dY=it,s.dZ=xE,s.d_=vt,s.da=function(h){const l=h.indexOf(Jx);return l>=0?h.slice(0,l):h},s.db=function(h){return h.indexOf(Jx)>=0},s.dc=function(h){const l=h.lastIndexOf(Jx);return l>=0?h.slice(l+1):""},s.dd=function(h){const l=[],u=h.id;return u===void 0&&l.push({message:`layers.${u}: missing required property "id"`}),h.render===void 0&&l.push({message:`layers.${u}: missing required method "render"`}),h.renderingMode&&h.renderingMode!=="2d"&&h.renderingMode!=="3d"&&l.push({message:`layers.${u}: property "renderingMode" must be either "2d" or "3d"`}),l},s.de=function(h,l,u,p){return h.type==="custom"?new tje(h,l):new aje[h.type](h,l,u,p)},s.df=Nt,s.dg=$v,s.dh=pI,s.di=class extends b_{constructor(h,l){super(h._vectorTileFeature,h._z,h._x,h._y,h.id),h.state&&(this.state=Object.assign({},h.state)),this.target=l.target,this.namespace=l.namespace,l.properties&&(this.properties=l.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}},s.dj=UT,s.dk=function(h){return h({pluginStatus:Yo,pluginURL:Sc}),UT.on("pluginStateChange",h),h},s.dl=K3,s.dm=class extends uu{constructor(h){super(h),this.current=g}set(h,l,u){if(this.fetchUniformLocation(h,l)){for(let p=0;p<9;p++)if(u[p]!==this.current[p]){this.current=u,this.gl.uniformMatrix3fv(this.location,!1,u);break}}}},s.dn=yx,s.dp=function(h,l,u){const p=$p(u.zoom),y=h.style.map._antialias,b=h.terrain&&h.terrain.exaggeration()>0;return p===0&&!y&&!b},s.dq=function(h){const l=h.pixelsPerMeter,u=l/ot(1,h.center.lat),p=R(new Float64Array(16));return B(p,p,[h.point.x,h.point.y,0]),V(p,p,[u,u,l]),Float32Array.from(p)},s.dr=CI,s.ds=function(h){const l=80.051129;h=fe(h,-80.051129,l)/l*90;const u=Math.pow(Math.abs(Math.sin(Kn(h))),3);return Math.round(u*(Ze.length-1))},s.dt=function(h,l,u,p){const y=l.getNorth(),b=l.getSouth(),S=l.getWest(),k=l.getEast(),j=1<0){const Z=180/p;E(K,K,[Z/O+1,0,0,0,Z/z+1,0,-.5*Z/U,.5*Z/q,1])}return K[2]=j,K[5]=h.x,K[8]=h.y,K},s.du=yE,s.dv=vf,s.dw=function(h,l,u){const p=R(new Float64Array(16)),y=(l/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(h,l=!1){const u=BK(new Mt(0,0),new Mt(ar,ar),h),p=[];if(l&&!p5(u,this._globalClipBounds))return p;for(const y of this._activeRegions){if(y.hiddenByOverlap||!p5(u,y))continue;const b=XAe(y.min,y.max,h);p.push({min:b.min,max:b.max,sourceId:this._sourceIds[y.priority],footprint:y.footprint,footprintTileId:y.tileId,order:y.order,clipMask:y.clipMask,clipScope:y.clipScope})}return p}setSources(h){this._setSources(h.map(l=>({getSourceId:()=>l.cache.id,getFootprints:()=>{const u=[];for(const p of l.cache.getVisibleCoordinates()){const y=l.cache.getTile(p).buckets[l.layer];y&&y.updateFootprints(p.toUnwrapped(),u)}return u},getOrder:()=>l.order,getClipMask:()=>l.clipMask,getClipScope:()=>l.clipScope})))}_addSource(h){const l=h.getFootprints();if(l.length===0)return;const u=h.getOrder(),p=h.getClipMask(),y=h.getClipScope();for(const b of l){if(!b.footprint)continue;const S=BK(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:p,clipScope:y})}this._sourceIds.push(h.getSourceId())}_computeReplacement(){this._activeRegions.sort((l,u)=>l.priority-u.priority||FI(l.min,u.min)||FI(l.max,u.max)||l.order-u.order||l.clipMask-u.clipMask||function(p,y){const b=(S,k)=>S+k;return p.length-y.length||p.reduce(b,"").localeCompare(y.reduce(b,""))}(l.clipScope,u.clipScope));let h=this._activeRegions.length!==this._prevRegions.length;if(!h){let l=0;for(;!h&&l!==this._activeRegions.length;){const u=this._activeRegions[l],p=this._prevRegions[l];h=u.priority!==p.priority||!FK(u,p)||u.order!==p.order||u.clipMask!==p.clipMask||!Po(u.clipScope,p.clipScope),this._activeRegions[l].hiddenByOverlap=p.hiddenByOverlap,++l}}if(h){++this._updateTime;for(const u of this._activeRegions)u.order!==AE&&(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 l=u=>{const p=this._activeRegions;if(u>=p.length)return u;const y=p[u].priority;for(;u1){let u=0,p=l(u);for(;u!==p;){let y=u;const b=u;for(;y!==p;){const S=this._activeRegions[y];S.hiddenByOverlap=!1;for(let k=0;k=0;l--)this._addSource(h[l]);this._computeReplacement()}},s.eH=xo,s.eI=yP,s.eJ=Mp,s.eK=AE,s.eL=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,l){const u=new ic,p=new _s,y=[],b=h+1+2,S=l[0]+1,k=l[0]+1+(1+l.length),j=(O,z,U)=>{let q=O===b-1?O-2:O===0?O:O-1;return q+=U?24575:0,[q,z]};for(let O=0;O>>=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},s.ec=XW,s.ed=X3,s.ee=lu,s.ef=W,s.eg=function(h,l){return h[0]=l[0],h[1]=l[1],h[2]=l[2],h[3]=l[4],h[4]=l[5],h[5]=l[6],h[6]=l[8],h[7]=l[9],h[8]=l[10],h},s.eh=Dp,s.ei=s_,s.ej=function(h,l,u,p,y){return fe((h-l)/(u-l)*(y-p)+p,p,y)},s.ek=ai,s.el=function(h,l){var u=l[0],p=l[1],y=l[2],b=l[3],S=l[4],k=l[5],j=l[6],O=l[7],z=l[8],U=z*S-k*O,q=-z*b+k*j,K=O*b-S*j,Z=u*U+p*q+y*K;return Z?(h[0]=U*(Z=1/Z),h[1]=(-z*p+y*O)*Z,h[2]=(k*p-y*S)*Z,h[3]=q*Z,h[4]=(z*u-y*j)*Z,h[5]=(-k*u+y*b)*Z,h[6]=K*Z,h[7]=(-O*u+p*j)*Z,h[8]=(S*u-p*b)*Z,h):null},s.em=Uj,s.en=2,s.eo=Vt,s.ep=Zt,s.eq=se,s.er=function(h,l){var u=new m(3);se(u,l);var p=1/u[0],y=1/u[1],b=1/u[2],S=l[0]*p,k=l[1]*y,j=l[2]*b,O=l[4]*p,z=l[5]*y,U=l[6]*b,q=l[8]*p,K=l[9]*y,Z=l[10]*b,J=S+z+Z,ne=0;return J>0?(ne=2*Math.sqrt(J+1),h[3]=.25*ne,h[0]=(U-K)/ne,h[1]=(q-j)/ne,h[2]=(k-O)/ne):S>z&&S>Z?(ne=2*Math.sqrt(1+S-z-Z),h[3]=(U-K)/ne,h[0]=.25*ne,h[1]=(k+O)/ne,h[2]=(q+j)/ne):z>Z?(ne=2*Math.sqrt(1+z-S-Z),h[3]=(q-j)/ne,h[0]=(k+O)/ne,h[1]=.25*ne,h[2]=(U+K)/ne):(ne=2*Math.sqrt(1+Z-S-z),h[3]=(k-O)/ne,h[0]=(q+j)/ne,h[1]=(U+K)/ne,h[2]=.25*ne),h},s.es=function(h,l){var u=2*Math.acos(l[3]),p=Math.sin(u/2);return p>f?(h[0]=l[0]/p,h[1]=l[1]/p,h[2]=l[2]/p):(h[0]=1,h[1]=0,h[2]=0),u},s.et=f4,s.eu=QI,s.ev=XI,s.ew=[1,1,1],s.ex=mb,s.ey=function(h,l,u,p){var y=l[0],b=l[1],S=l[2],k=l[3];return h[0]=y+p*(u[0]-y),h[1]=b+p*(u[1]-b),h[2]=S+p*(u[2]-S),h[3]=k+p*(u[3]-k),h},s.ez=ob,s.f=Jl,s.f0=nK,s.f1=function(h){const l=[0,0,0],u=R(new Float64Array(16));return M(u,h.pixelMatrix,h.globeMatrix),or(l,l,u),new Mt(l[0],l[1])},s.f2=VT,s.f3=function(h,l,u=!1){if(Yo===nc.deferred||Yo===nc.loading||Yo===nc.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");Sc=Pl.resolveURL(h),Yo=nc.deferred,vd=l,$T(),u||oI()},s.f4=oo,s.f5=yo,s.f6=_a,s.f7=function(h){const l=mj();if(!l)return;const u=l.delete(yp);h&&u.then(()=>h()).catch(h)},s.f8=vr,s.f9=Tg,s.fA=tn,s.fB=function(h){let l=0;if(new Uint32Array(h,0,1)[0]!==yY){const u=new Uint32Array(h,0,7),[,,p,y,b,S]=u;l=u.byteLength+y+b+S+b,(p!==h.byteLength||l>=h.byteLength)&&Br("Invalid b3dm header information.")}return bY(h,l)},s.fC=function(h,l){const u=N5(h);for(const p of u){for(const y of p.meshes)Cke(y);p.lights&&(p.lightMeshIndex=p.meshes.length,p.meshes.push(jke(p.lights,l)))}return u},s.fD=bP,s.fE=Ci,s.fF=hh,s.fG=nc,s.fH=function(h){Q0(),gd!=null&&gd.then(l=>{l.keys().then(u=>{for(let p=0;pBr(y.message))}).catch(u=>Br(u.message))}).catch(l=>Br(l.message))},s.fa=2,s.fb=ch,s.fc=__,s.fd=uE,s.fe=oX,s.ff=lX,s.fg=OY,s.fh=mn,s.fi="hd_road_elevation",s.fj=Ii,s.fk=zt,s.fl=OI,s.fm=Up,s.fn=Y5,s.fo=1,s.fp=_h,s.fq=function(h,l,u,p,y,b,S,k=1,j,O,z,U){h.createArrays(),h.tilePixelRatio=ar/(512*h.overscaling),h.compareText={},h.iconsNeedLinear=!1;const q=h.layers[0].layout,K=h.layers[0]._unevaluatedLayout._values,Z={};Z.scaleFactor=k,Z.textSizeScaleRange=q.get("text-size-scale-range"),Z.iconSizeScaleRange=q.get("icon-size-scale-range");const[J,ne]=Z.textSizeScaleRange,[ae,he]=Z.iconSizeScaleRange;Z.textScaleFactor=fe(Z.scaleFactor,J,ne),Z.iconScaleFactor=fe(Z.scaleFactor,ae,he);const ce=K["text-size"],ye=K["icon-size"];if(h.textSizeData.kind==="composite"){const{minZoom:Ue,maxZoom:Ve}=h.textSizeData;Z.compositeTextSizes=[ce.possiblyEvaluate(new ti(Ue,{worldview:z}),b),ce.possiblyEvaluate(new ti(Ve,{worldview:z}),b)]}if(h.iconSizeData.kind==="composite"){const{minZoom:Ue,maxZoom:Ve}=h.iconSizeData;Z.compositeIconSizes=[ye.possiblyEvaluate(new ti(Ue,{worldview:z}),b,U),ye.possiblyEvaluate(new ti(Ve,{worldview:z}),b,U)]}Z.layoutTextSize=ce.possiblyEvaluate(new ti(S+1,{worldview:z}),b),Z.layoutIconSize=ye.possiblyEvaluate(new ti(S+1,{worldview:z}),b,U),Z.textMaxSize=ce.possiblyEvaluate(new ti(18,{worldview:z}),b);const Ee=q.get("symbol-placement"),Ce=q.get("text-rotation-alignment")==="map"&&Ee!=="point",He=q.get("text-size");let $e=!1;const Ge=[];for(const Ue of h.features){const Ve=q.get("text-font").evaluate(Ue,{},b).join(","),yt=He.evaluate(Ue,{},b)*Z.textScaleFactor,bt=Z.layoutTextSize.evaluate(Ue,{},b)*Z.textScaleFactor,kt=Z.layoutIconSize.evaluate(Ue,{},b,U)*Z.iconScaleFactor,It={horizontal:{},vertical:void 0},Ct=Ue.text;let Bt,pt=[0,0];if(Ct){const bn=Ct.toString(),fs=q.get("text-letter-spacing").evaluate(Ue,{},b)*Na,ri=q.get("text-line-height").evaluate(Ue,{},b)*Na,Gn=L3(bn)?fs:0,Ai=q.get("text-anchor").evaluate(Ue,{},b),os=q.get("text-variable-anchor");if(!os){const bs=q.get("text-radial-offset").evaluate(Ue,{},b);if(bs)pt=bZ(Ai,[bs*Na,J5]);else{const vo=q.get("text-offset").evaluate(Ue,{},b);pt=[vo[0]*Na,vo[1]*Na]}}let Ra=Ce?"center":q.get("text-justify").evaluate(Ue,{},b);const ls=Ee==="point",vs=ls?q.get("text-max-width").evaluate(Ue,{},b)*Na:1/0,qs=bs=>{h.allowVerticalPlacement&&FT(bn)&&(It.vertical=U5(Ct,l,u,y,Ve,vs,ri,Ai,bs,Gn,pt,Ic.vertical,!0,bt,yt,j,Z.textScaleFactor))};if(!Ce&&os){const bs=Ra==="auto"?os.map(La=>e4(La)):[Ra];let vo=!1;for(let La=0;La=0||!FT(bn)){const bs=U5(Ct,l,u,y,Ve,vs,ri,Ai,Ra,Gn,pt,Ic.horizontal,!1,bt,yt,j,Z.textScaleFactor);bs&&(It.horizontal[Ra]=bs)}qs(ls?"left":Ra)}}let jt,Lt,$t,Wt,xr,ir,nr=!1;const Kt=q.get("icon-text-fit").evaluate(Ue,{},b);if(Ue.icon&&Ue.icon.hasPrimary()){const bn=$E(Ue.icon,h.iconSizeData,K["icon-size"],b,h.zoom,Ue,j,Z.iconScaleFactor,z,U);jt=bn.iconPrimary,$t=bn.iconSecondary;const fs=jt.toString();if(Lt=p.get(fs),Lt&&(xr=q.get("icon-offset").evaluate(Ue,{},b),ir=q.get("icon-anchor").evaluate(Ue,{},b),Bt=iP(y.get(fs),$t?y.get($t.toString()):void 0,xr,ir),nr=Lt.sdf,h.sdfIcons===void 0?h.sdfIcons=Lt.sdf:h.sdfIcons!==Lt.sdf&&Br("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(Lt.pixelRatio!==h.pixelRatio||q.get("icon-rotate").constantOr(1)!==0)&&(h.iconsNeedLinear=!0)),$t){const ri=$t.toString();Wt=p.get(ri)}}$e=$e||!(!Ue.icon||!Ue.icon.hasSecondary());const mr=dP(It.horizontal)||It.vertical;h.iconsInText||(h.iconsInText=!!mr&&mr.iconsInText);const kr=bt*Z.textScaleFactor/Na,{defaultShapedIcon:zr,verticallyShapedIcon:Rr}=BCe(h,Bt,q,Ue,b,It,kr,xr,Kt);Kt!=="none"&&Bt&&(nZ(Bt)||iZ(Bt))&&(uP(0,Lt,jt,Bt,zr,Kt,O,p,y),uP(0,Wt,$t,Bt,zr,Kt,O,p,y),Rr&&(uP(0,Lt,jt,Bt,Rr,Kt,O,p,y),uP(0,Wt,$t,Bt,Rr,Kt,O,p,y))),Bt=zr;const{iconBBox:ln,iconVerticalBBox:zn,textBBox:cn,textVerticalBBox:Un}=LCe(h,Bt,Rr,q,Ue,b,kt,xr,Z,y,ir,It,bt,pt,U);Ge.push({feature:Ue,shapedTextOrientations:It,shapedText:mr,shapedIcon:Bt,iconPrimary:jt,iconSecondary:$t,iconOffset:xr,iconAnchor:ir,verticallyShapedIcon:Rr,layoutTextSize:bt,layoutIconSize:kt,textOffset:pt,isSDFIcon:nr,iconTextFit:Kt,iconCollisionBounds:ln,iconVerticalCollisionBounds:zn,textCollisionBounds:cn,textVerticalCollisionBounds:Un})}return{featureData:Ge,sizes:Z,hasAnySecondaryIcon:$e,textAlongLine:Ce,symbolPlacement:Ee}},s.fr=Z5,s.fs=K5,s.ft=fZ,s.fu=pZ,s.fv=function(h,l,u,p,y,b,S,k,j,O){h.iconAtlasPositions=O.iconPositions;const{featureData:z,hasAnySecondaryIcon:U,sizes:q,textAlongLine:K,symbolPlacement:Z}=l;for(const J of z){const{shapedIcon:ne,verticallyShapedIcon:ae,feature:he,shapedTextOrientations:ce,shapedText:ye,layoutTextSize:Ee,textOffset:Ce,isSDFIcon:He,iconPrimary:$e,iconSecondary:Ge,iconTextFit:Ue,iconOffset:Ve,iconCollisionBounds:yt,iconVerticalCollisionBounds:bt,textCollisionBounds:kt}=J;EZ(ne,O.iconPositions,$e,Ge),EZ(ae,O.iconPositions,$e,Ge),FCe(ce,O.iconPositions),MCe($e,Ge,O.iconPositions),(ye||ne)&&zCe(h,he,ce,ne,ae,j,q,Ee,0,Ce,He,p,y,S,k,U,Ue,Ve,K,Z,yt,bt,kt)}u&&h.generateCollisionDebugBuffers(b,h.collisionBoxArray,q.textScaleFactor)},s.fw=tP,s.fx=Qn,s.fy=function(h){return h<=1?1:Math.pow(2,Math.floor(Math.log2(h)))},s.fz=kP,s.g=Dn,s.h=function(h,l){return Zm(Object.assign(h,{method:"GET"}),l)},s.i=function(h){return Dn.API_STYLE_REGEX.test(h)&&!ec(h)},s.j=function(h){return btoa(encodeURIComponent(h).replace(/%([0-9A-F]{2})/g,(l,u)=>String.fromCharCode(+("0x"+u))))},s.k=J0,s.l=function(h){return decodeURIComponent(atob(h).split("").map(l=>"%"+("00"+l.charCodeAt(0).toString(16)).slice(-2)).join(""))},s.m=function(h,l){return Zm(Object.assign(h,{type:"json"}),l)},s.n=Qm,s.o=Pl,s.p=function(h,l){return Zm(Object.assign(h,{method:"POST"}),l)},s.q=Do,s.r=dt,s.s=function(h){try{const l=self[h];return l.setItem("_mapbox_test_",1),l.removeItem("_mapbox_test_"),!0}catch{return!1}},s.t=Je,s.u=function(){return function h(l){return l?(l^Math.random()*(16>>l/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,h)}()},s.v=function(h){return!!h&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(h)},s.w=Br,s.x=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.finalizationRegistry=new FinalizationRegistry(l=>{this.cache.delete(l),this.clearExpiredTextures()})}calculateTextureMemory(h){return h.image?Math.ceil(h.image.width*h.image.height*4*(h.patternPositions.size>0?1.33:1)):0}evictTexture(h){const l=this.textures.get(h);if(l){const u=this.calculateTextureMemory(h);l.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 l=null,u=1/0;for(const[p]of this.textures.entries()){const y=this.textureAccessTimes.get(p)||0;ythis._layers[fr.id]),dt=tt[0];if(dt.visibility==="none")continue;const it=dt.source||"";let ht=this.familiesBySource[it];ht||(ht=this.familiesBySource[it]=Object.create(null));const zt=dt.sourceLayer||"_geojsonTileLayer";let Nt=ht[zt];Nt||(Nt=ht[zt]=[]),Nt.push(tt)}}}const C=1*f.fa;class N{constructor(de){const fe={},Me=[];for(const dt in de){const it=de[dt],ht=fe[dt]={};for(const zt in it.glyphs){const Nt=it.glyphs[+zt];if(!Nt||Nt.bitmap.width===0||Nt.bitmap.height===0)continue;const fr=Nt.metrics.localGlyph?C:1,Fr={x:0,y:0,w:Nt.bitmap.width+2*fr,h:Nt.bitmap.height+2*fr};Me.push(Fr),ht[zt]=Fr}}const{w:Ye,h:Je}=f.J(Me),tt=new f.f9({width:Ye||1,height:Je||1});for(const dt in de){const it=de[dt];for(const ht in it.glyphs){const zt=it.glyphs[+ht];if(!zt||zt.bitmap.width===0||zt.bitmap.height===0)continue;const Nt=fe[dt][ht],fr=zt.metrics.localGlyph?C:1;f.f9.copy(zt.bitmap,tt,{x:0,y:0},{x:Nt.x+fr,y:Nt.y+fr},zt.bitmap)}}this.image=tt,this.positions=fe}}function R(ct,de,fe){ct[de]?fe&&(ct[de].center=fe):ct[de]={floorIds:new Set,center:fe||[0,0],floors:{}}}function D(ct,de,fe,Me){for(const Ye of de)R(ct,Ye),ct[Ye].floors[fe]=Me,ct[Ye].floorIds.add(fe)}function M(ct){return{id:ct.properties.id.toString(),center:[ct.properties.center_lon||0,ct.properties.center_lat||0]}}function B(ct,de){const fe=ct.properties.id.toString(),Me=!!ct.properties.is_default&&ct.properties.is_default,Ye=ct.properties.connected_floor_ids?new Set(ct.properties.connected_floor_ids.toString().split(";")):new Set,Je=ct.properties.conflicted_floor_ids?new Set(ct.properties.conflicted_floor_ids.toString().split(";")):new Set,tt=ct.properties.structure_ids?new Set(ct.properties.structure_ids.toString().split(";")):new Set,dt=ct.properties.name.toString(),it=ct.properties.z_index,ht=function(zt,Nt){const fr=zt.loadGeometry();if(!fr||fr.length===0)return;const Fr=fr.map(qr=>qr.map(Br=>f.fb(Br,Nt,zt.extent)));return Fr.length===0?void 0:{type:"Polygon",coordinates:[Fr[0]]}}(ct,de);return{id:fe,isDefault:Me,connections:Ye,conflicts:Je,buildings:tt,name:dt,zIndex:it,geometry:ht}}function V(ct,de){return de.every(fe=>ct.properties&&ct.properties[fe]!=null)}function G(ct){return V(ct,["type","id","name"])&&ct.properties.type==="structure"}function W(ct){return V(ct,["type","id","name","z_index"])&&ct.properties.type==="floor"}f.f8(N,"GlyphAtlas");class X{constructor(de){this.tileID=new f.aR(de.tileID.overscaledZ,de.tileID.wrap,de.tileID.canonical.z,de.tileID.canonical.x,de.tileID.canonical.y),this.tileZoom=de.tileZoom,this.uid=de.uid,this.zoom=de.zoom,this.lut=de.lut,this.canonical=de.tileID.canonical,this.pixelRatio=de.pixelRatio,this.tileSize=de.tileSize,this.source=de.source,this.scope=de.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=de.showCollisionBoxes,this.collectResourceTiming=!!de.request&&de.request.collectResourceTiming,this.promoteId=de.promoteId,this.renderSourceType=de.renderSourceType,this.tileTransform=f.fc(de.tileID.canonical,de.projection),this.projection=de.projection,this.worldview=de.worldview,this.localizableLayerIds=de.localizableLayerIds,this.brightness=de.brightness,this.extraShadowCaster=!!de.extraShadowCaster,this.tessellationStep=de.tessellationStep,this.scaleFactor=de.scaleFactor,this.worldview=de.worldview,this.indoor=de.indoor}parse(de,fe,Me,Ye,Je,tt){this.status="parsing",this.data=de,this.collisionBoxArray=new f.fd;const dt=new f.fe(Object.keys(de.layers).sort()),it=new f.ff(this.tileID,this.promoteId);it.bucketLayerIDs=[];const ht={},zt=new f.fg(256,256),Nt={featureIndex:it,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:zt,availableImages:Me,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Nt.activeFloors=function(Br,an,kn,Rn){const Ci=an.indoorState.activeFloorsVisible;if(!an.sourceLayers)return Ci?an.indoorState.activeFloors:void 0;const Ds=function(yi,is){if(!yi)return f.w("No source layers defined in indoor specification"),is;if(yi.size===0)return is;const sa=yi.difference(is);for(const ji of sa)f.w(`Missing source layer required in indoor specification: ${ji}`);return is.intersection(is)}(an.sourceLayers,new Set(Object.keys(Br.layers))),Cs=an.indoorState,gs=function(yi,is,sa,ji,ss){const ys={};for(const Dn of is){const _a=yi.layers[Dn];if(_a)for(let yo=0;yo<_a.length;yo++){const oo=_a.feature(yo);if(G(oo)){const{id:Jl,center:ec}=M(oo);R(ys,Jl,ec);continue}if(W(oo)){const Jl=B(oo,ss);D(ys,Jl.buildings,Jl.id,Jl)}}else f.w(`indoor source layer not found: ${Dn}`)}return{buildings:ys,activeFloors:f.d1.calculate(ys,ji,sa)}}(Br,Ds,Cs.activeFloors,Cs.selectedFloorId,Rn);return kn.send("setIndoorData",gs),Ci?gs.activeFloors:void 0}(de,this.indoor,Je,this.canonical));const fr=[],Fr=fe.familiesBySource[this.source];for(const Br in Fr){const an=de.layers[Br];if(!an)continue;let kn=!1,Rn=!1,Ci=!1,Ds=!1;for(const sa of Fr[Br])sa[0].type==="symbol"?kn=!0:sa[0].type==="fill-extrusion"?Rn=!0:Ci=!0,sa[0].is3D()&&sa[0].type!=="model"&&(Ds=!0);if(this.extraShadowCaster&&!Ds||this.renderSourceType===f.b4.Symbol&&!kn||this.renderSourceType===f.b4.FillExtrusion&&!Rn||this.renderSourceType===f.b4.Other&&!Ci)continue;an.version===1&&f.w(`Vector tile source "${this.source}" layer "${Br}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const Cs=dt.encode(Br),gs=[],yi=this.localizableLayerIds&&this.localizableLayerIds.has(Br);let is=!1;for(let sa=0,ji=0;sa=ji.maxzoom||ji.visibility==="none")continue;Q(sa,this.zoom,Nt.brightness,Me,this.worldview,Nt.activeFloors);const ss=ht[ji.id]=ji.createBucket({index:it.bucketLayerIDs.length,layers:sa,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Cs,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Ye,worldview:this.worldview,localizable:yi,availableImages:Me,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});it.bucketLayerIDs.push(sa.map(Dn=>f.F(Dn.id,Dn.scope)));let ys=ss.prepare?ss.prepare():null;ys!=null?(ys=ys.then(()=>ss.populate(gs,Nt,this.tileID.canonical,this.tileTransform)),fr.push(ys)):ss.populate(gs,Nt,this.tileID.canonical,this.tileTransform)}}const qr=()=>{zt.trim();const Br=!(!Nt.elevationFeatures||!Nt.elevationFeatures.some(ji=>ji.heightRange.min<0));let an,kn,Rn,Ci,Ds,Cs,gs;const yi={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},is=()=>{if(an)return this.status="done",tt(an);if(this.extraShadowCaster)this.status="done",tt(null,{buckets:Object.values(ht).filter(ji=>!ji.isEmpty()),featureIndex:it,collisionBoxArray:null,hasTunnelGeometry:Br,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Nt.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(kn&&Rn&&Ci&&gs){const ss=new N(kn),ys=new Map;for(const[yo,oo]of Rn.entries()){const{imagePosition:Jl}=f.fn(yo,oo,f.fo);ys.set(yo,Jl)}const Dn={};for(const yo in ht){const oo=ht[yo];oo instanceof f.fp&&(Q(oo.layers,this.zoom,Nt.brightness,Me,this.worldview,Nt.activeFloors),Dn[yo]=f.fq(oo,kn,ss.positions,Rn,ys,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Ds,this.worldview,Me))}const _a={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Je,Rn,Ds,()=>{_a.iconsPending=!1,sa(Dn,ss,_a,void 0,gs)}),this.rasterizeIfNeeded(Je,Ci,Cs,()=>{_a.patternsPending=!1,sa(Dn,ss,_a,void 0,gs)})}},sa=(ji,ss,ys,Dn,_a)=>{if(ys.iconsPending||ys.patternsPending)return;const yo=Rn.size>0||Ci.size>0,oo=Object.keys(ji).length>0;if(!yo&&!oo)return this.status="done",void tt(null,{buckets:Object.values(ht).filter(ec=>!ec.isEmpty()),featureIndex:it,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Br,glyphAtlasImage:ss.image,lineAtlas:zt,imageAtlas:null,brightness:Nt.brightness});const Jl=(ec,fd)=>{for(const pl in ht){const tc=ht[pl];if(pl in ji)f.fv(tc,ji[pl],this.showCollisionBoxes,Me,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,Rn,fd);else if(tc.hasPattern&&(tc instanceof f.fw||tc instanceof f.fl||tc instanceof f.e0)){Q(tc.layers,this.zoom,Nt.brightness,Me,this.worldview,Nt.activeFloors);const pd=Object.fromEntries(fd.patternPositions);tc.addFeatures(Nt,this.tileID.canonical,pd,Me,this.tileTransform,this.brightness)}}this.status="done",tt(null,{buckets:Object.values(ht).filter(pl=>!pl.isEmpty()),featureIndex:it,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Br,glyphAtlasImage:ss.image,lineAtlas:zt,imageAtlas:ec,brightness:Nt.brightness})};if(yo){const ec=new Map,fd=f.fr(Rn,ec),pl=f.fr(Ci,ec),tc=new f.fs(fd,pl,_a,this.lut,ec);Je.send("checkAtlasCache",{descriptor:tc,scope:this.scope},(pd,vc)=>{let md,ru;if(pd&&f.w(`[Worker] Error checking atlas cache: ${pd.message}`),vc)md=new f.ft(vc.sourceHash),ru=vc;else{const Pl=new f.fu(Rn,Ci,this.lut,_a);md=Pl,ru=Pl}Jl(md,ru)})}else Jl(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const ji=f.fk(Nt.glyphDependencies,Dn=>Object.keys(Dn).map(Number));Object.keys(ji).length?Je.send("getGlyphs",{uid:this.uid,stacks:ji},(Dn,_a)=>{an||(an=Dn,kn=_a,is())},void 0,!1,yi):kn={},gs=new Map;const ss=Array.from(Nt.iconDependencies.keys()).map(Dn=>f.I.parse(Dn));ss.length?Je.send("getImages",{images:ss,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(Dn,_a)=>{if(!an){an=Dn,Rn=new Map,Ds=this.updateImageMapAndGetImageTaskQueue(Rn,_a.images,Nt.iconDependencies);for(const[yo,oo]of _a.versions.entries())gs.set(yo,oo);is()}},void 0,!1,yi):(Rn=new Map,Ds=new Map);const ys=Array.from(Nt.patternDependencies.keys()).map(Dn=>f.I.parse(Dn));ys.length?Je.send("getImages",{images:ys,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(Dn,_a)=>{if(!an){an=Dn,Ci=new Map,Cs=this.updateImageMapAndGetImageTaskQueue(Ci,_a.images,Nt.patternDependencies);for(const[yo,oo]of _a.versions.entries())gs.set(yo,oo);is()}},void 0,!1,yi):(Ci=new Map,Cs=new Map)}if(Nt.elevationFeatures&&Nt.elevationFeatures.length>0){const ji=[];for(const ys of Object.values(ht))if(ys instanceof f.fl){const Dn=ys.getUnevaluatedPortalGraph();Dn&&ji.push(Dn)}const ss=f.fm.evaluate(ji);for(const ys of Object.values(ht))if(ys instanceof f.fl){const Dn=de.layers[dt.decode(ys.sourceLayerIndex)];ys.setEvaluatedPortalGraph(ss,Dn,this.tileID.canonical,Nt.availableImages,Nt.brightness)}}is()};fr.length>0?Promise.allSettled(fr).then(qr).catch(tt):qr()}updateParameters(de){this.scaleFactor=de.scaleFactor,this.showCollisionBoxes=de.showCollisionBoxes,this.projection=de.projection,this.brightness=de.brightness,this.tileTransform=f.fc(de.tileID.canonical,de.projection),this.extraShadowCaster=de.extraShadowCaster,this.lut=de.lut,this.worldview=de.worldview,this.indoor=de.indoor}rasterizeIfNeeded(de,fe,Me,Ye){Array.from(fe.values()).some(Je=>Je.usvg)?this.rasterize(de,fe,Me,Ye):Ye()}updateImageMapAndGetImageTaskQueue(de,fe,Me){const Ye=new Map;for(const Je of fe.keys()){const tt=Me.get(Je)||[];for(const dt of tt){const it=dt.toString(),ht=fe.get(dt.id.toString());ht.usvg?Ye.has(it)||(Ye.set(it,dt),de.set(it,Object.assign({},ht))):de.set(it,ht)}}return Ye}rasterize(de,fe,Me,Ye){this.rasterizeTask=de.send("rasterizeImages",{scope:this.scope,tasks:Me},(Je,tt)=>{if(!Je)for(const[dt,it]of tt.entries()){const ht=Object.assign(fe.get(dt),{data:it});fe.set(dt,ht)}Ye()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function Q(ct,de,fe,Me,Ye,Je){const tt=new f.ae(de,{brightness:fe,worldview:Ye,activeFloors:Je});for(const dt of ct)dt.recalculate(tt,Me)}class re extends f.E{constructor({actor:de,layerIndex:fe,availableImages:Me,availableModels:Ye,isSpriteLoaded:Je,tileProvider:tt,brightness:dt,maxUniformBufferBindings:it,maxUniformBlockSizeDwords:ht,disableSymbolUBO:zt}){super(),this.actor=de,this.layerIndex=fe,this.availableImages=Me,this.availableModels=Ye,this.loadVectorData=f.aO,this.tileProvider=tt,this.loading={},this.loaded={},this.deduped=new f.aN(de.scheduler),this.isSpriteLoaded=Je,this.scheduler=de.scheduler,this.brightness=dt,this.maxUniformBufferBindings=it,this.maxUniformBlockSizeDwords=ht,this.disableSymbolUBO=zt}loadTileData(de,fe){if(!this.tileProvider)return this.loadVectorData(de,fe);const Me=new AbortController,{z:Ye,x:Je,y:tt}=de.tileID.canonical;return this.tileProvider.loadTile({z:Ye,x:Je,y:tt},{request:de.request,signal:Me.signal}).then(dt=>{if(Me.signal.aborted)return;if(dt==null){const ht=new Error("Tile not found");return ht.status=404,fe(ht)}if(dt.data===null)return fe(null,null);const it=new Map;dt.expires&&it.set("expires",dt.expires),dt.cacheControl&&it.set("cache-control",dt.cacheControl),fe(null,{rawData:dt.data,responseHeaders:it})}).catch(dt=>{Me.signal.aborted||fe(dt instanceof Error?dt:new Error(String(dt)))}),()=>Me.abort()}loadTile(de,fe){const Me=de.uid,Ye=de&&de.request,Je=Ye&&Ye.collectResourceTiming,tt=this.loading[Me]=new X(de);tt.maxUniformBufferBindings=this.maxUniformBufferBindings,tt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,tt.disableSymbolUBO=this.disableSymbolUBO,tt.abort=this.loadTileData(de,(dt,it)=>{const ht=!this.loading[Me];if(delete this.loading[Me],tt.cancelRasterize(),ht||dt||!it)return tt.status="done",ht||(this.loaded[Me]=tt),fe(dt);const zt=it.rawData,Nt={},fr=f.aP(it.responseHeaders);fr&&fr.expires&&(Nt.expires=fr.expires),fr&&fr.cacheControl&&(Nt.cacheControl=fr.cacheControl),tt.vectorTile=it.vectorTile||new f.fx(new f.a$(zt));const Fr=()=>{tt.parse(tt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(qr,Br)=>{if(qr||!Br)return fe(qr);const an={};if(Je){const kn=m(Ye);kn.length>0&&(an.resourceTiming=JSON.parse(JSON.stringify(kn)))}fe(null,Object.assign({rawTileData:zt.slice(0),responseHeaders:it.responseHeaders},Br,Nt,an))})};this.isSpriteLoaded?Fr():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(Fr,{type:"parseTile",renderSourceType:de.renderSourceType,zoom:de.tileZoom}):Fr()}),this.loaded=this.loaded||{},this.loaded[Me]=tt})}reloadTile(de,fe){const Me=this.loaded,Ye=de.uid;if(Me&&Me[Ye]){const Je=Me[Ye];Je.updateParameters(de);const tt=(dt,it)=>{const ht=Je.reloadCallback;ht&&(delete Je.reloadCallback,Je.parse(Je.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,ht)),fe(dt,it)};Je.status==="parsing"?Je.reloadCallback=tt:Je.status==="done"&&(Je.vectorTile?Je.parse(Je.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,tt):tt())}else fe(null,void 0)}abortTile(de,fe){const Me=de.uid,Ye=this.loading[Me];Ye&&(Ye.abort&&Ye.abort(),delete this.loading[Me]),fe()}removeTile(de,fe){const Me=this.loaded,Ye=de.uid;Me&&Me[Ye]&&delete Me[Ye],fe()}}class se{constructor(de){this.loading={}}loadTile(de,fe){const Me=de.uid,{cancel:Ye}=f.b1(de.request,(Je,tt,dt)=>{const it=!this.loading[Me];if(delete this.loading[Me],it||Je||!tt)return fe(Je);this.decodeTile(Me,tt,de.encoding).then(ht=>{const{expires:zt,cacheControl:Nt}=f.aP(dt);fe(null,Object.assign(ht,{expires:zt,cacheControl:Nt}))}).catch(ht=>fe(ht))});this.loading[Me]={cancel:Ye}}async decodeTile(de,fe,Me){const Ye=await createImageBitmap(new Blob([new Uint8Array(fe)],{type:"image/png"})),Je=1-(Ye.width-f.fy(Ye.width))/2,tt=Je<1,dt=this.getImageData(Ye,Je);return Ye.close(),{dem:new f.fz(de,dt,Me,tt),borderReady:tt}}reloadTile(de,fe){fe(null,null)}abortTile(de,fe){const Me=de.uid,Ye=this.loading[Me];Ye&&(Ye.cancel(),delete this.loading[Me]),fe()}removeTile(de,fe){fe()}getImageData(de,fe){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(de.width,de.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=de.width,this.offscreenCanvas.height=de.height,this.offscreenCanvasContext.drawImage(de,0,0,de.width,de.height);const Me=this.offscreenCanvasContext.getImageData(-fe,-fe,de.width+2*fe,de.height+2*fe);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),Me}}f.a_.setPbf(f.a$);class ue{constructor(de){this._mrt=new f.a_(de.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=de.uid,this.tileID=de.tileID,this.source=de.source}parse(de,fe){const Me=this._mrt;this.status="parsing",this._entireBuffer=de;try{Me.parseHeader(de),this._isHeaderLoaded=!0;const Ye=[];for(const Je in Me.layers){const tt=Me.getLayer(Je),dt=tt.getDataRange(tt.getBandList()),it=Me.createDecodingTask(dt),ht=de.slice(dt.firstByte,dt.lastByte+1),zt=f.a_.performDecoding(ht,it).then(Nt=>it.complete(null,Nt)).catch(Nt=>it.complete(Nt,null));Ye.push(zt)}Promise.allSettled(Ye).then(()=>fe(null,Me)).catch(Je=>fe(Je))}catch(Ye){fe(Ye)}}}class _e{constructor({actor:de}){this.actor=de,this.loading={},this.loaded={}}loadTile(de,fe){const Me=de.uid,Ye=de.request,Je=this.loading[Me]=new ue(de),{cancel:tt}=f.b1(Ye,(dt,it,ht)=>{const zt=!this.loading[Me];if(delete this.loading[Me],zt||dt||!it)return Je.status="done",zt||(this.loaded[Me]=Je),fe(dt);Je.parse(it,(Nt,fr)=>{if(Nt||!fr)return fe(Nt);fe(null,fr,ht)}),this.loaded[Me]=Je});Je.abort=tt}reloadTile(de,fe){fe(null,void 0)}abortTile(de,fe){const Me=de.uid,Ye=this.loading[Me];Ye&&(Ye.abort&&Ye.abort(),delete this.loading[Me]),fe()}removeTile(de,fe){const Me=de.uid;this.loaded[Me]&&delete this.loaded[Me],fe()}decodeRasterArray(de,fe){f.a_.performDecoding(de.buffer,de.task).then(Me=>fe(null,Me)).catch(Me=>fe(Me))}}const Se=f.fA.prototype.toGeoJSON;class ve{constructor(de){this._feature=de,this.extent=f.an,this.type=de.type,this.properties=de.tags,"id"in de&&!isNaN(de.id)&&(this.id=parseInt(de.id,10))}loadGeometry(){if(this._feature.type===1){const de=[];for(const fe of this._feature.geometry)de.push([new f.P(fe[0],fe[1])]);return de}{const de=[];for(const fe of this._feature.geometry){const Me=[];for(const Ye of fe)Me.push(new f.P(Ye[0],Ye[1]));de.push(Me)}return de}}toGeoJSON(de,fe,Me){return Se.call(this,de,fe,Me)}}class Oe{constructor(de,fe){this.name=de,this.extent=f.an,this.length=fe.length,this._jsonFeatures=fe}feature(de){return new ve(this._jsonFeatures[de])}}class Ae{constructor(de){this.layers={},this.extent=f.an;for(const fe of Object.keys(de))this.layers[fe]=new Oe(fe,de[fe])}}const we=64/4096;class ge{constructor(){this.features=new Map}clear(){this.features.clear()}load(de=[],fe){for(const Me of de){const Ye=Me.id;if(Ye==null)continue;let Je=this.features.get(Ye);Je&&this.updateCache(Je,fe),Me.geometry?(Je=Ie(Me),this.updateCache(Je,fe),this.features.set(Ye,Je)):this.features.delete(Ye),this.updateCache(Je,fe)}}updateCache(de,fe){for(const{canonical:Me,uid:Ye}of Object.values(fe)){const{z:Je,x:tt,y:dt}=Me;Ne(de,Math.pow(2,Je),tt,dt)&&delete fe[Ye]}}getTile(de,fe,Me){const Ye=Math.pow(2,de),Je=[];for(const tt of this.features.values())Ne(tt,Ye,fe,Me)&&Je.push(rt(tt,Ye,fe,Me));return{features:Je}}getFeatures(){return[...this.features.values()]}}function Ne({minX:ct,minY:de,maxX:fe,maxY:Me},Ye,Je,tt){return ct<(Je+1+we)/Ye&&de<(tt+1+we)/Ye&&fe>(Je-we)/Ye&&Me>(tt-we)/Ye}function Ie(ct){const{id:de,geometry:fe,properties:Me}=ct;if(!fe)return;if(fe.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Ye,coordinates:Je}=fe,tt={id:de,type:1,geometry:[],tags:Me,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},dt=tt.geometry;if(Ye==="Point")Te(Je,dt,tt);else if(Ye==="MultiPoint")for(const it of Je)Te(it,dt,tt);else if(Ye==="LineString")tt.type=2,be(Je,dt,tt);else if(Ye==="MultiLineString")tt.type=2,We(Je,dt,tt);else if(Ye==="Polygon")tt.type=3,We(Je,dt,tt,!0);else{if(Ye!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");tt.type=3;for(const it of Je)We(it,dt,tt,!0)}return tt}function Te([ct,de],fe,Me){const Ye=f.aH(ct);let Je=f.aL(de);Je=Je<0?0:Je>1?1:Je,fe.push(Ye,Je),Me.minX=Math.min(Me.minX,Ye),Me.minY=Math.min(Me.minY,Je),Me.maxX=Math.max(Me.maxX,Ye),Me.maxY=Math.max(Me.maxY,Je)}function be(ct,de,fe,Me=!1,Ye=!1){const Je=[];for(const tt of ct)Te(tt,Je,fe);de.push(Je),Me&&function(tt,dt){let it=0;for(let ht=0,zt=tt.length,Nt=zt-2;ht0===dt)for(let ht=0,zt=tt.length;ht=tt&&Nt>=tt||(ht>=tt?(zt+=Math.round(qr*((tt-ht)/Fr)),ht=tt):Nt>=tt&&(fr=zt+Math.round(qr*((tt-ht)/Fr)),Nt=tt),zt>=tt&&fr>=tt||(zt>=tt?(ht+=Math.round(Fr*((tt-zt)/qr)),zt=tt):fr>=tt&&(Nt=ht+Math.round(Fr*((tt-zt)/qr)),fr=tt),dt&&ht===dt[dt.length-1][0]&&zt===dt[dt.length-1][1]||(dt=[[ht,zt]],Ye.push(dt)),dt.push([Nt,fr])))))}}function Et(ct,de,fe,Me,Ye){const Je=(fe-we)/de,tt=(Me-we)/de,dt=(fe+1+we)/de,it=(Me+1+we)/de;function ht(fr,Fr){let qr=0;return frdt&&(qr|=2),Frit&&(qr|=8),qr}let zt=[];for(let fr=1;fr<=8;fr*=2){let Fr=ct[ct.length-2],qr=ct[ct.length-1],Br=!(ht(Fr,qr)&fr);for(let an=0;an>31}function wt(ct,de){const{geometry:fe,type:Me}=ct;let Ye=0,Je=0;if(Me===1){de.writeVarint(Pt(1,fe.length));for(const tt of fe){const dt=tt[0]-Ye,it=tt[1]-Je;de.writeVarint(er(dt)),de.writeVarint(er(it)),Ye+=dt,Je+=it}}else for(const tt of fe){if(tt.length===0)continue;de.writeVarint(Pt(1,1));const dt=tt.length-(Me===3?1:0);for(let it=0;itct},nn=Math.fround||(lr=new Float32Array(1),ct=>(lr[0]=+ct,lr[0]));var lr;class yr{constructor(de){this.options=Object.assign(Object.create(Sr),de),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(de){const{log:fe,minZoom:Me,maxZoom:Ye}=this.options;fe&&console.time("total time");const Je=`prepare ${de.length} points`;fe&&console.time(Je),this.points=de;const tt=[];for(let it=0;it=Me;it--){const ht=+Date.now();dt=this.trees[it]=this._createTree(this._cluster(dt,it)),fe&&console.log("z%d: %d clusters in %dms",it,dt.numItems,+Date.now()-ht)}return fe&&console.timeEnd("total time"),this}getClusters(de,fe){let Me=((de[0]+180)%360+360)%360-180;const Ye=Math.max(-90,Math.min(90,de[1]));let Je=de[2]===180?180:((de[2]+180)%360+360)%360-180;const tt=Math.max(-90,Math.min(90,de[3]));if(de[2]-de[0]>=360)Me=-180,Je=180;else if(Me>Je){const Nt=this.getClusters([Me,Ye,180,tt],fe),fr=this.getClusters([-180,Ye,Je,tt],fe);return Nt.concat(fr)}const dt=this.trees[this._limitZoom(fe)],it=dt.range(lt(Me),At(tt),lt(Je),At(Ye)),ht=dt.data,zt=[];for(const Nt of it){const fr=this.stride*Nt;zt.push(ht[fr+5]>1?tr(ht,fr,this.clusterProps):this.points[ht[fr+3]])}return zt}getChildren(de){const fe=this._getOriginId(de),Me=this._getOriginZoom(de),Ye="No cluster with the specified id.",Je=this.trees[Me];if(!Je)throw new Error(Ye);const tt=Je.data;if(fe*this.stride>=tt.length)throw new Error(Ye);const dt=this.options.radius/(this.options.extent*Math.pow(2,Me-1)),it=Je.within(tt[fe*this.stride],tt[fe*this.stride+1],dt),ht=[];for(const zt of it){const Nt=zt*this.stride;tt[Nt+4]===de&&ht.push(tt[Nt+5]>1?tr(tt,Nt,this.clusterProps):this.points[tt[Nt+3]])}if(ht.length===0)throw new Error(Ye);return ht}getLeaves(de,fe,Me){const Ye=[];return this._appendLeaves(Ye,de,fe=fe||10,Me=Me||0,0),Ye}getTile(de,fe,Me){const Ye=this.trees[this._limitZoom(de)],Je=Math.pow(2,de),{extent:tt,radius:dt}=this.options,it=dt/tt,ht=(Me-it)/Je,zt=(Me+1+it)/Je,Nt={features:[]};return this._addTileFeatures(Ye.range((fe-it)/Je,ht,(fe+1+it)/Je,zt),Ye.data,fe,Me,Je,Nt),fe===0&&this._addTileFeatures(Ye.range(1-it/Je,ht,1,zt),Ye.data,Je,Me,Je,Nt),fe===Je-1&&this._addTileFeatures(Ye.range(0,ht,it/Je,zt),Ye.data,-1,Me,Je,Nt),Nt.features.length?Nt:null}getClusterExpansionZoom(de){let fe=this._getOriginZoom(de)-1;for(;fe<=this.options.maxZoom;){const Me=this.getChildren(de);if(fe++,Me.length!==1)break;de=Me[0].properties.cluster_id}return fe}_appendLeaves(de,fe,Me,Ye,Je){const tt=this.getChildren(fe);for(const dt of tt){const it=dt.properties;if(it&&it.cluster?Je+it.point_count<=Ye?Je+=it.point_count:Je=this._appendLeaves(de,it.cluster_id,Me,Ye,Je):Je1;let zt,Nt,fr;if(ht)zt=yn(fe,it,this.clusterProps),Nt=fe[it],fr=fe[it+1];else{const Br=this.points[fe[it+3]];zt=Br.properties;const[an,kn]=Br.geometry.coordinates;Nt=lt(an),fr=At(kn)}const Fr={type:1,geometry:[[Math.round(this.options.extent*(Nt*Je-Me)),Math.round(this.options.extent*(fr*Je-Ye))]],tags:zt};let qr;qr=ht||this.options.generateId?fe[it+3]:this.points[fe[it+3]].id,qr!==void 0&&(Fr.id=qr),tt.features.push(Fr)}}_limitZoom(de){return Math.max(this.options.minZoom,Math.min(Math.floor(+de),this.options.maxZoom+1))}_cluster(de,fe){const{radius:Me,extent:Ye,reduce:Je,minPoints:tt}=this.options,dt=Me/(Ye*Math.pow(2,fe)),it=de.data,ht=[],zt=this.stride;for(let Nt=0;Ntfe&&(an+=it[Rn+5])}if(an>Br&&an>=tt){let kn,Rn=fr*Br,Ci=Fr*Br,Ds=-1;const Cs=(Nt/zt<<5)+(fe+1)+this.points.length;for(const gs of qr){const yi=gs*zt;if(it[yi+2]<=fe)continue;it[yi+2]=fe;const is=it[yi+5];Rn+=it[yi]*is,Ci+=it[yi+1]*is,it[yi+4]=Cs,Je&&(kn||(kn=this._map(it,Nt,!0),Ds=this.clusterProps.length,this.clusterProps.push(kn)),Je(kn,this._map(it,yi)))}it[Nt+4]=Cs,ht.push(Rn/an,Ci/an,1/0,Cs,-1,an),Je&&ht.push(Ds)}else{for(let kn=0;kn1)for(const kn of qr){const Rn=kn*zt;if(!(it[Rn+2]<=fe)){it[Rn+2]=fe;for(let Ci=0;Ci>5}_getOriginZoom(de){return(de-this.points.length)%32}_map(de,fe,Me){if(de[fe+5]>1){const tt=this.clusterProps[de[fe+6]];return Me?Object.assign({},tt):tt}const Ye=this.points[de[fe+3]].properties,Je=this.options.map(Ye);return Me&&Je===Ye?Object.assign({},Je):Je}}function tr(ct,de,fe){return{type:"Feature",id:ct[de+3],properties:yn(ct,de,fe),geometry:{type:"Point",coordinates:[(Me=ct[de],360*(Me-.5)),Ot(ct[de+1])]}};var Me}function yn(ct,de,fe){const Me=ct[de+5],Ye=Me>=1e4?`${Math.round(Me/1e3)}k`:Me>=1e3?Math.round(Me/100)/10+"k":Me,Je=ct[de+6],tt=Je===-1?{}:Object.assign({},fe[Je]);return Object.assign(tt,{cluster:!0,cluster_id:ct[de+3],point_count:Me,point_count_abbreviated:Ye})}function lt(ct){return ct/360+.5}function At(ct){const de=Math.sin(ct*Math.PI/180),fe=.5-.25*Math.log((1+de)/(1-de))/Math.PI;return fe<0?0:fe>1?1:fe}function Ot(ct){const de=(180-360*ct)*Math.PI/180;return 360*Math.atan(Math.exp(de))/Math.PI-90}function dr(ct,de,fe,Me){let Ye=Me;const Je=de+(fe-de>>1);let tt,dt=fe-de;const it=ct[de],ht=ct[de+1],zt=ct[fe],Nt=ct[fe+1];for(let fr=de+3;frYe)tt=fr,Ye=Fr;else if(Fr===Ye){const qr=Math.abs(fr-Je);qrMe&&(tt-de>3&&dr(ct,de,tt,Me),ct[tt+2]=Ye,fe-tt>3&&dr(ct,tt,fe,Me))}function cr(ct,de,fe,Me,Ye,Je){let tt=Ye-fe,dt=Je-Me;if(tt!==0||dt!==0){const it=((ct-fe)*tt+(de-Me)*dt)/(tt*tt+dt*dt);it>1?(fe=Ye,Me=Je):it>0&&(fe+=tt*it,Me+=dt*it)}return tt=ct-fe,dt=de-Me,tt*tt+dt*dt}function hr(ct,de,fe,Me){const Ye={id:ct??null,type:de,geometry:fe,tags:Me,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(de==="Point"||de==="MultiPoint"||de==="LineString")Zt(Ye,fe);else if(de==="Polygon")Zt(Ye,fe[0]);else if(de==="MultiLineString")for(const Je of fe)Zt(Ye,Je);else if(de==="MultiPolygon")for(const Je of fe)Zt(Ye,Je[0]);return Ye}function Zt(ct,de){for(let fe=0;fe0&&(tt+=Me?(Ye*zt-ht*Je)/2:Math.sqrt(Math.pow(ht-Ye,2)+Math.pow(zt-Je,2))),Ye=ht,Je=zt}const dt=de.length-3;de[2]=1,dr(de,0,dt,fe),de[dt+2]=1,de.size=Math.abs(tt),de.start=0,de.end=de.size}function ei(ct,de,fe,Me){for(let Ye=0;Ye1?1:fe}function mi(ct,de,fe,Me,Ye,Je,tt,dt){if(Me/=de,Je>=(fe/=de)&&tt=Me)return null;const it=[];for(const ht of ct){const zt=ht.geometry;let Nt=ht.type;const fr=Ye===0?ht.minX:ht.minY,Fr=Ye===0?ht.maxX:ht.maxY;if(fr>=fe&&Fr=Me)continue;let qr=[];if(Nt==="Point"||Nt==="MultiPoint")ia(zt,qr,fe,Me,Ye);else if(Nt==="LineString")jr(zt,qr,fe,Me,Ye,!1,dt.lineMetrics);else if(Nt==="MultiLineString")As(zt,qr,fe,Me,Ye,!1);else if(Nt==="Polygon")As(zt,qr,fe,Me,Ye,!0);else if(Nt==="MultiPolygon")for(const Br of zt){const an=[];As(Br,an,fe,Me,Ye,!0),an.length&&qr.push(an)}if(qr.length){if(dt.lineMetrics&&Nt==="LineString"){for(const Br of qr)it.push(hr(ht.id,Nt,Br,ht.tags));continue}Nt!=="LineString"&&Nt!=="MultiLineString"||(qr.length===1?(Nt="LineString",qr=qr[0]):Nt="MultiLineString"),Nt!=="Point"&&Nt!=="MultiPoint"||(Nt=qr.length===3?"Point":"MultiPoint"),it.push(hr(ht.id,Nt,qr,ht.tags))}}return it.length?it:null}function ia(ct,de,fe,Me,Ye){for(let Je=0;Je=fe&&tt<=Me&&xa(de,ct[Je],ct[Je+1],ct[Je+2])}}function jr(ct,de,fe,Me,Ye,Je,tt){let dt=Mn(ct);const it=Ye===0?go:Yr;let ht,zt,Nt=ct.start;for(let an=0;anfe&&(zt=it(dt,kn,Rn,Ds,Cs,fe),tt&&(dt.start=Nt+ht*zt)):gs>Me?yi=fe&&(zt=it(dt,kn,Rn,Ds,Cs,fe),is=!0),yi>Me&&gs<=Me&&(zt=it(dt,kn,Rn,Ds,Cs,Me),is=!0),!Je&&is&&(tt&&(dt.end=Nt+ht*zt),de.push(dt),dt=Mn(ct)),tt&&(Nt+=ht)}let fr=ct.length-3;const Fr=ct[fr],qr=ct[fr+1],Br=Ye===0?Fr:qr;Br>=fe&&Br<=Me&&xa(dt,Fr,qr,ct[fr+2]),fr=dt.length-3,Je&&fr>=3&&(dt[fr]!==dt[0]||dt[fr+1]!==dt[1])&&xa(dt,dt[0],dt[1],dt[2]),dt.length&&de.push(dt)}function Mn(ct){const de=[];return de.size=ct.size,de.start=ct.start,de.end=ct.end,de}function As(ct,de,fe,Me,Ye,Je){for(const tt of ct)jr(tt,de,fe,Me,Ye,Je,!1)}function xa(ct,de,fe,Me){ct.push(de,fe,Me)}function go(ct,de,fe,Me,Ye,Je){const tt=(Je-de)/(Me-de);return xa(ct,Je,fe+(Ye-fe)*tt,1),tt}function Yr(ct,de,fe,Me,Ye,Je){const tt=(Je-fe)/(Ye-fe);return xa(ct,de+(Me-de)*tt,Je,1),tt}function hn(ct,de){const fe=[];for(let Me=0;Me0&&de.size<(Ye?tt:Me))return void(fe.numPoints+=de.length/3);const dt=[];for(let it=0;ittt)&&(fe.numSimplified++,dt.push(de[it],de[it+1])),fe.numPoints++;Ye&&function(it,ht){let zt=0;for(let Nt=0,fr=it.length,Fr=fr-2;Nt0===ht)for(let Nt=0,fr=it.length;Nt24)throw new Error("maxZoom should be in the 0-24 range");if(fe.promoteId&&fe.generateId)throw new Error("promoteId and generateId cannot be used together.");let Ye=function(Je,tt){const dt=[];if(Je.type==="FeatureCollection")for(let it=0;it1&&console.time("creation"),Fr=this.tiles[fr]=Jr(de,fe,Me,Ye,ht),this.tileCoords.push({z:fe,x:Me,y:Ye}),zt)){zt>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",fe,Me,Ye,Fr.numFeatures,Fr.numPoints,Fr.numSimplified),console.timeEnd("creation"));const is=`z${fe}`;this.stats[is]=(this.stats[is]||0)+1,this.total++}if(Fr.source=de,Je==null){if(fe===ht.indexMaxZoom||Fr.numPoints<=ht.indexMaxPoints)continue}else{if(fe===ht.maxZoom||fe===Je)continue;if(Je!=null){const is=Je-fe;if(Me!==tt>>is||Ye!==dt>>is)continue}}if(Fr.source=null,de.length===0)continue;zt>1&&console.time("clipping");const qr=.5*ht.buffer/ht.extent,Br=.5-qr,an=.5+qr,kn=1+qr;let Rn=null,Ci=null,Ds=null,Cs=null,gs=mi(de,Nt,Me-qr,Me+an,0,Fr.minX,Fr.maxX,ht),yi=mi(de,Nt,Me+Br,Me+kn,0,Fr.minX,Fr.maxX,ht);de=null,gs&&(Rn=mi(gs,Nt,Ye-qr,Ye+an,1,Fr.minY,Fr.maxY,ht),Ci=mi(gs,Nt,Ye+Br,Ye+kn,1,Fr.minY,Fr.maxY,ht),gs=null),yi&&(Ds=mi(yi,Nt,Ye-qr,Ye+an,1,Fr.minY,Fr.maxY,ht),Cs=mi(yi,Nt,Ye+Br,Ye+kn,1,Fr.minY,Fr.maxY,ht),yi=null),zt>1&&console.timeEnd("clipping"),it.push(Rn||[],fe+1,2*Me,2*Ye),it.push(Ci||[],fe+1,2*Me,2*Ye+1),it.push(Ds||[],fe+1,2*Me+1,2*Ye),it.push(Cs||[],fe+1,2*Me+1,2*Ye+1)}}getTile(de,fe,Me){de=+de,fe=+fe,Me=+Me;const Ye=this.options,{extent:Je,debug:tt}=Ye;if(de<0||de>24)return null;const dt=1<1&&console.log("drilling down to z%d-%d-%d",de,fe,Me);let ht,zt=de,Nt=fe,fr=Me;for(;!ht&&zt>0;)zt--,Nt>>=1,fr>>=1,ht=this.tiles[Mt(zt,Nt,fr)];return ht&&ht.source?(tt>1&&(console.log("found parent tile z%d-%d-%d",zt,Nt,fr),console.time("drilling down")),this.splitTile(ht.source,zt,Nt,fr,de,fe,Me),tt>1&&console.timeEnd("drilling down"),this.tiles[it]?Zr(this.tiles[it],Je):null):null}}function Mt(ct,de,fe){return 32*((1<ht.tags&&"3d_elevation_id"in ht.tags&&"source"in ht.tags&&ht.tags.source==="elevation",Je=Me.features.filter(ht=>Ye(ht));let tt={_geojsonTileLayer:Me.features};Je.length>0&&(tt={_geojsonTileLayer:Me.features.filter(ht=>!Ye(ht)),hd_road_elevation:Je});const dt=new Ae(tt),it=function(ht){const zt=new f.a$;for(const Nt of Object.keys(ht))zt.writeMessage(3,_t,{name:Nt,features:ht[Nt]});return zt.finish()}(tt).buffer;de(null,{vectorTile:dt,rawData:it})}class bi extends re{constructor(de){super(de),this.loadVectorData=Po,this._dynamicIndex=new ge}loadData(de,fe){const Me=de&&de.request,Ye=Me&&Me.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(de,(Je,tt)=>{if(Je||!tt)return fe(Je);if(typeof tt!="object")return fe(new Error(`Input data given to '${de.source}' is not a valid GeoJSON object.`));{try{if(de.filter){const it=f.X(de.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(it.result==="error")throw new Error(it.value.map(ht=>`${ht.key}: ${ht.message}`).join(", "));tt.features=tt.features.filter(ht=>it.value.evaluate({zoom:0},ht))}de.dynamic?(tt.type==="Feature"&&(tt={type:"FeatureCollection",features:[tt]}),de.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(tt.features,this.loaded),de.cluster&&(tt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=de.cluster?new yr(function({superclusterOptions:it,clusterProperties:ht}){if(!ht||!it)return it;const zt={},Nt={},fr={accumulated:null,zoom:0},Fr={properties:null},qr=Object.keys(ht);for(const Br of qr){const[an,kn]=ht[Br],Rn=f.X(kn),Ci=f.X(typeof an=="string"?[an,["accumulated"],["get",Br]]:an);zt[Br]=Rn.value,Nt[Br]=Ci.value}return it.map=Br=>{Fr.properties=Br;const an={};for(const kn of qr)an[kn]=zt[kn].evaluate(fr,Fr);return an},it.reduce=(Br,an)=>{Fr.properties=an;for(const kn of qr)fr.accumulated=Br[kn],Br[kn]=Nt[kn].evaluate(fr,Fr)},it}(de)).load(tt.features):de.dynamic?this._dynamicIndex:function(it,ht){return new Wo(it,ht)}(tt,de.geojsonVtOptions)}catch(it){return fe(it)}const dt={};if(Ye){const it=m(Me);it&&(dt.resourceTiming={},dt.resourceTiming[de.source]=JSON.parse(JSON.stringify(it)))}fe(null,dt)}})}reloadTile(de,fe){const Me=this.loaded;return Me&&Me[de.uid]?de.partial?fe(null,void 0):super.reloadTile(de,fe):this.loadTile(de,fe)}loadGeoJSON(de,fe){if(de.request)f.m(de.request,fe);else{if(typeof de.data!="string")return fe(new Error(`Input data given to '${de.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return fe(null,JSON.parse(de.data))}catch{return fe(new Error(`Input data given to '${de.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(de,fe){try{fe(null,this._geoJSONIndex.getClusterExpansionZoom(de.clusterId))}catch(Me){fe(Me)}}getClusterChildren(de,fe){try{fe(null,this._geoJSONIndex.getChildren(de.clusterId))}catch(Me){fe(Me)}}getClusterLeaves(de,fe){try{fe(null,this._geoJSONIndex.getLeaves(de.clusterId,de.limit,de.offset))}catch(Me){fe(Me)}}}class ks{constructor(de,fe,Me){this.tileID=new f.aR(de.tileID.overscaledZ,de.tileID.wrap,de.tileID.canonical.z,de.tileID.canonical.x,de.tileID.canonical.y),this.tileZoom=de.tileZoom,this.uid=de.uid,this.zoom=de.zoom,this.canonical=de.tileID.canonical,this.pixelRatio=de.pixelRatio,this.tileSize=de.tileSize,this.source=de.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=de.projection,this.brightness=fe,this.worldview=Me}parse(de,fe,Me,Ye){this.status="parsing";const Je=new f.aR(Me.tileID.overscaledZ,Me.tileID.wrap,Me.tileID.canonical.z,Me.tileID.canonical.x,Me.tileID.canonical.y),tt=[],dt=fe.familiesBySource[Me.source],it=new f.ff(Je,Me.promoteId);it.bucketLayerIDs=[],it.is3DTile=!0,f.fB(de).then(ht=>{const zt=ht.json.extensionsUsed&&ht.json.extensionsUsed.includes("MAPBOX_mesh_features")||ht.json.asset.extras&&ht.json.asset.extras.MAPBOX_mesh_features,Nt=ht.json.extensionsUsed&&ht.json.extensionsUsed.includes("EXT_meshopt_compression"),fr=new f.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const Fr in dt)for(const qr of dt[Fr]){const Br=qr[0];it.bucketLayerIDs.push(qr.map(Rn=>f.F(Rn.id,Rn.scope))),Br.recalculate(fr,[]);const an=f.fC(ht,1/f.cS(Me.tileID.canonical)),kn=new f.fD(qr,an,Je,zt,Nt,this.brightness,it,this.worldview);zt||(kn.needsUpload=!0),tt.push(kn),kn.evaluate(Br)}this.status="done",Ye(null,{buckets:tt,featureIndex:it,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(ht=>Ye(new Error(ht.message)))}}class Kn{constructor({actor:de,layerIndex:fe,availableImages:Me,availableModels:Ye,brightness:Je,worldview:tt}){this.actor=de,this.layerIndex=fe,this.availableImages=Me,this.availableModels=Ye,this.brightness=Je,this.loading={},this.loaded={},this.worldview=tt}loadTile(de,fe){const Me=de.uid,Ye=this.loading[Me]=new ks(de,this.brightness,this.worldview);f.b1(de.request,(Je,tt)=>{const dt=!this.loading[Me];return delete this.loading[Me],dt||Je?(Ye.status="done",dt||(this.loaded[Me]=Ye),fe(Je)):tt&&tt.byteLength!==0?void Ye.parse(tt,this.layerIndex,de,(it,ht)=>{Ye.status="done",this.loaded=this.loaded||{},this.loaded[Me]=Ye,it||!ht?fe(it):fe(null,ht)}):(Ye.status="done",this.loaded[Me]=Ye,fe())})}reloadTile(de,fe){const Me=this.loaded,Ye=de.uid;if(Me&&Me[Ye]){const Je=Me[Ye];Je.projection=de.projection,Je.brightness=de.brightness;const tt=(dt,it)=>{Je.reloadCallback&&(delete Je.reloadCallback,this.loadTile(de,fe)),fe(dt,it)};Je.status==="parsing"?Je.reloadCallback=tt:Je.status==="done"&&this.loadTile(de,fe)}}abortTile(de,fe){const Me=de.uid;this.loading[Me]&&delete this.loading[Me],fe()}removeTile(de,fe){const Me=this.loaded,Ye=de.uid;Me&&Me[Ye]&&delete Me[Ye],fe()}}const ao=new Map,tu=new Map;class yx{constructor(de){this.self=de,this.actor=new f.A(de,this),this.layerIndexes={},this.availableImages={},this.availableModels={},this.isSpriteLoaded={},this.imageRasterizer=new f.z,this.rtlPluginParsingListeners=[],this.projections={},this.defaultProjection=f.c0({name:"mercator"}),this.workerSourceTypes={vector:re,geojson:bi,"raster-dem":se,"raster-array":_e,"batched-model":Kn},this.workerSources={},this.self.registerWorkerSource=(fe,Me)=>{if(this.workerSourceTypes[fe])throw new Error(`Worker source with name "${fe}" already registered.`);this.workerSourceTypes[fe]=Me},this.self.registerRTLTextPlugin=fe=>{if(f.fF.isParsed())throw new Error("RTL text plugin already registered.");f.fF.setState({pluginStatus:f.fG.parsed,pluginURL:f.fF.getPluginURL()}),f.fF.applyArabicShaping=fe.applyArabicShaping,f.fF.processBidirectionalText=fe.processBidirectionalText,f.fF.processStyledBidirectionalText=fe.processStyledBidirectionalText;for(const Me of this.rtlPluginParsingListeners)Me(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(de,fe,Me){delete this.layerIndexes[de],delete this.availableImages[de],delete this.availableModels[de],delete this.workerSources[de],Me()}checkIfReady(de,fe,Me){Me()}setReferrer(de,fe){this.referrer=fe}spriteLoaded(de,fe){this.isSpriteLoaded[de]||(this.isSpriteLoaded[de]={});const{scope:Me,isLoaded:Ye}=fe;if(this.isSpriteLoaded[de][Me]=Ye,this.workerSources[de]&&this.workerSources[de][Me])for(const Je in this.workerSources[de][Me]){const tt=this.workerSources[de][Me][Je];for(const dt in tt){const it=tt[dt];it instanceof re&&(it.isSpriteLoaded=Ye,it.fire(new f.C("isSpriteLoaded")))}}}setImages(de,fe,Me){this.availableImages[de]||(this.availableImages[de]={});const{scope:Ye,images:Je}=fe;if(this.availableImages[de][Ye]=Je,this.workerSources[de]&&this.workerSources[de][Ye]){for(const tt in this.workerSources[de][Ye]){const dt=this.workerSources[de][Ye][tt];for(const it in dt)dt[it].availableImages=Je}Me()}else Me()}setModels(de,{scope:fe,models:Me},Ye){if(this.availableModels[de]||(this.availableModels[de]={}),this.availableModels[de][fe]=Me,this.workerSources[de]&&this.workerSources[de][fe]){for(const Je in this.workerSources[de][fe]){const tt=this.workerSources[de][fe][Je];for(const dt in tt)tt[dt].availableModels=Me}Ye()}else Ye()}setProjection(de,fe){this.projections[de]=f.c0(fe)}setBrightness(de,fe,Me){this.brightness=fe,Me()}setContextParams(de,fe,Me){this.maxUniformBufferBindings=fe.maxBindingPoints,this.maxUniformBlockSizeDwords=fe.maxUniformBlockSizeDwords,this.disableSymbolUBO=fe.disableSymbolUBO,Me()}setWorldview(de,fe,Me){this.worldview=fe,Me()}setLayers(de,fe,Me){this.getLayerIndex(de,fe.scope).replace(fe.layers,fe.options),Me()}updateLayers(de,fe,Me){this.getLayerIndex(de,fe.scope).update(fe.layers,fe.removedIds,fe.options),Me()}loadTile(de,fe,Me){fe.projection=this.projections[de]||this.defaultProjection,this.getWorkerSource(de,fe).loadTile(fe,Me)}decodeRasterArray(de,fe,Me){this.getWorkerSource(de,fe).decodeRasterArray(fe,Me)}reloadTile(de,fe,Me){fe.projection=this.projections[de]||this.defaultProjection,this.getWorkerSource(de,fe).reloadTile(fe,Me)}abortTile(de,fe,Me){this.getWorkerSource(de,fe).abortTile(fe,Me)}removeTile(de,fe,Me){this.getWorkerSource(de,fe).removeTile(fe,Me)}removeSource(de,fe,Me){if(!(this.workerSources[de]&&this.workerSources[de][fe.scope]&&this.workerSources[de][fe.scope][fe.type]&&this.workerSources[de][fe.scope][fe.type][fe.source]))return;const Ye=this.workerSources[de][fe.scope][fe.type][fe.source];delete this.workerSources[de][fe.scope][fe.type][fe.source],Ye.removeSource!==void 0?Ye.removeSource(fe,Me):Me()}loadTileProvider(de,fe,Me){(async function(Ye,Je){const tt=tu.get(Ye);if(tt)return tt;const dt=ao.get(Ye);if(dt!==void 0)return dt;const it=import(Je).then(ht=>{const zt=ht.default;if(typeof zt!="function")throw new Error(`TileProvider "${Ye}" module must default-export a class`);if(typeof zt.prototype.loadTile!="function")throw new Error(`TileProvider "${Ye}" class must have a loadTile method`);return tu.set(Ye,zt),zt}).finally(()=>{ao.delete(Ye)});return ao.set(Ye,it),it})(fe.name,fe.url).then(Ye=>{const Je=new Ye(fe.options);return this.getWorkerSource(de,{type:fe.type,source:fe.source,scope:fe.scope},Je),Je.load&&fe.request?Je.load({request:fe.request}):null}).then(Ye=>Me(null,Ye)).catch(Ye=>Me(Ye instanceof Error?Ye:new Error(typeof Ye=="string"?Ye:"Unknown error")))}loadWorkerSource(de,fe,Me){try{this.self.importScripts(fe.url),Me()}catch(Ye){Me(Ye)}}syncRTLPluginState(de,fe,Me){if(f.fF.isParsed())Me(null,!0);else if(f.fF.isParsing())this.rtlPluginParsingListeners.push(Me);else try{f.fF.setState(fe);const Ye=f.fF.getPluginURL();!f.fF.isLoaded()||f.fF.isParsed()||f.fF.isParsing()||Ye==null||(f.fF.setState({pluginStatus:f.fG.parsing,pluginURL:f.fF.getPluginURL()}),this.self.importScripts(Ye),f.fF.isParsed()?Me(null,!0):this.rtlPluginParsingListeners.push(Me))}catch(Ye){Me(Ye)}}setConfig(de,fe){Object.assign(f.g,fe)}getAvailableImages(de,fe){this.availableImages[de]||(this.availableImages[de]={});let Me=this.availableImages[de][fe];return Me||(Me=[]),Me}getAvailableModels(de,fe){this.availableModels[de]||(this.availableModels[de]={});let Me=this.availableModels[de][fe];return Me||(Me={}),Me}getLayerIndex(de,fe){this.layerIndexes[de]||(this.layerIndexes[de]={});let Me=this.layerIndexes[de][fe];return Me||(Me=this.layerIndexes[de][fe]=new E,Me.scope=fe),Me}getWorkerSource(de,fe,Me){const{type:Ye,source:Je,scope:tt}=fe,dt=this.workerSources;if(dt[de]||(dt[de]={}),dt[de][tt]||(dt[de][tt]={}),dt[de][tt][Ye]||(dt[de][tt][Ye]={}),this.isSpriteLoaded[de]||(this.isSpriteLoaded[de]={}),!dt[de][tt][Ye][Je]){const it={send:(zt,Nt,fr,Fr,qr,Br)=>this.actor.send(zt,Nt,fr,de,qr,Br),scheduler:this.actor.scheduler},ht=this.workerSourceTypes[Ye];if(!ht)throw new Error(`Unknown worker source type "${Ye}".`);dt[de][tt][Ye][Je]=new ht({actor:it,layerIndex:this.getLayerIndex(de,tt),availableImages:this.getAvailableImages(de,tt),availableModels:this.getAvailableModels(de,tt),isSpriteLoaded:this.isSpriteLoaded[de][tt],tileProvider:Me,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return dt[de][tt][Ye][Je]}rasterizeImagesWorker(de,fe,Me){const Ye=new Map;for(const[Je,{image:tt,imageVariant:dt}]of fe.tasks.entries()){const it=this.imageRasterizer.rasterize(dt,tt,fe.scope,de);Ye.set(Je,it)}Me(void 0,Ye)}removeRasterizedImages(de,fe,Me){this.imageRasterizer.removeImagesFromCacheByIds(fe.imageIds,fe.scope,de),Me()}enforceCacheSizeLimit(de,fe){f.fH(fe)}getWorkerPerformanceMetrics(de,fe,Me){Me(void 0,void 0)}}return f.fE(self)&&(self.worker=new yx(self)),yx}),a(["./shared"],function(s){var f="3.22.0";const m={create:"create",load:"load",fullLoad:"fullLoad"},x={mark(v){performance.mark(v)},measure(v,d,g){performance.measure(v,d,g)}};function _(v){const d=v.name.split("?")[0];return s.a(d)&&d.includes("mapbox-gl.js")?"javascript":s.a(d)&&d.includes("mapbox-gl.css")?"css":s.b(d)?"fontRange":s.c(d)?"sprite":s.i(d)?"style":s.d(d)?"tilejson":"other"}var T,E={},C=function(){if(T)return E;function v(w){return!d(w)}function d(w){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var I,L,F=new Blob([""],{type:"text/javascript"}),$=URL.createObjectURL(F);try{L=new Worker($),I=!0}catch{I=!1}return L&&L.terminate(),URL.revokeObjectURL($),I}()?function(){var I=document.createElement("canvas");I.width=I.height=1;var L=I.getContext("2d");if(!L)return!1;var F=L.getImageData(0,0,1,1);return F&&F.width===I.width}()?(g[A=w&&w.failIfMajorPerformanceCaveat]===void 0&&(g[A]=function(I){var L,F=function($){var H=document.createElement("canvas"),Y=Object.create(v.webGLContextAttributes);return Y.failIfMajorPerformanceCaveat=$,H.getContext("webgl2",Y)}(I);if(!F)return!1;try{L=F.createShader(F.VERTEX_SHADER)}catch{return!1}return!(!L||F.isContextLost())&&(F.shaderSource(L,"void main() {}"),F.compileShader(L),F.getShaderParameter(L,F.COMPILE_STATUS)===!0)}(A)),g[A]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var A}T=1,E.supported=v,E.notSupportedReason=d;var g={};return v.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},E}();function N(v,d,g){const w=document.createElement(v);return d!=null&&(w.className=d),g&&g.appendChild(w),w}function R(v,d,g){const w=document.createElementNS("http://www.w3.org/2000/svg",v);for(const A of Object.keys(d))w.setAttributeNS(null,A,String(d[A]));return g&&g.appendChild(w),w}const D=typeof document<"u"?document.documentElement&&document.documentElement.style:null,M=D&&D.userSelect!==void 0?"userSelect":"WebkitUserSelect";let B;function V(){D&&M&&(B=D[M],D[M]="none")}function G(){D&&M&&(D[M]=B)}function W(v){v.preventDefault(),v.stopPropagation(),window.removeEventListener("click",W,!0)}function X(){window.addEventListener("click",W,!0),window.setTimeout(()=>{window.removeEventListener("click",W,!0)},0)}function Q(v,d){const g=v.getBoundingClientRect();return ue(v,g,d)}function re(v,d){const g=v.getBoundingClientRect(),w=[];for(let A=0;Athis._skuTokenExpiresAt}transformRequest(d,g){return this._transformRequestFn&&this._transformRequestFn(d,g)||{url:d}}normalizeStyleURL(d,g){if(!s.e(d))return d;const w=Ae(d);return w.params.push(`sdk=js-${f}`),w.path=`/styles/v1${w.path}`,this._makeAPIURL(w,this._customAccessToken||g)}normalizeGlyphsURL(d,g){if(!s.e(d))return d;const w=Ae(d);return w.path=`/fonts/v1${w.path}`,this._makeAPIURL(w,this._customAccessToken||g)}normalizeModelURL(d,g){if(!s.e(d))return d;const w=Ae(d);return w.path=`/models/v1${w.path}`,this._makeAPIURL(w,this._customAccessToken||g)}normalizeSourceURL(d,g,w,A){if(!s.e(d))return d;const I=Ae(d);return I.path=`/v4/${I.authority}.json`,I.params.push("secure"),w&&I.params.push(`language=${w}`),A&&I.params.push(`worldview=${A}`),this._makeAPIURL(I,this._customAccessToken||g)}normalizeIconsetURL(d,g){const w=Ae(d);return s.e(d)?(w.path=`/styles/v1${w.path}/iconset.pbf`,this._makeAPIURL(w,this._customAccessToken||g)):we(w)}normalizeSpriteURL(d,g,w,A){const I=Ae(d);return s.e(d)?(I.path=`/styles/v1${I.path}/sprite${g}${w}`,this._makeAPIURL(I,this._customAccessToken||A)):(I.path+=`${g}${w}`,we(I))}normalizeTileURL(d,g,w){if(this._isSkuTokenExpired()&&this._createSkuToken(),d&&!s.e(d))return d;const A=Ae(d);A.path=A.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${g||w&&A.authority!=="raster"&&w===512?"@2x":""}${s.k.supported?".webp":"$1"}`),A.authority==="raster"?A.path=`/${s.g.RASTER_URL_PREFIX}${A.path}`:A.authority==="rasterarrays"?A.path=`/${s.g.RASTERARRAYS_URL_PREFIX}${A.path}`:A.authority==="3dtiles"?A.path=`/${s.g.TILES3D_URL_PREFIX}${A.path}`:(A.path=A.path.replace(/^.+\/v4\//,"/"),A.path=`/${s.g.TILE_URL_VERSION}${A.path}`);const I=this._customAccessToken||function(L){for(const F of L){const $=F.match(/^access_token=(.*)$/);if($)return $[1]}return null}(A.params)||s.g.ACCESS_TOKEN;return s.g.REQUIRE_ACCESS_TOKEN&&I&&this._skuToken&&A.params.push(`sku=${this._skuToken}`),this._makeAPIURL(A,I)}canonicalizeTileURL(d,g){const w=Ae(d);if(!w.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!w.path.match(/\.[\w]+$/))return d;let A="mapbox://";w.path.match(/^\/raster\/v1\//)?A+=`raster/${w.path.replace(`/${s.g.RASTER_URL_PREFIX}/`,"")}`:w.path.match(/^\/rasterarrays\/v1\//)?A+=`rasterarrays/${w.path.replace(`/${s.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:A+=`tiles/${w.path.replace(`/${s.g.TILE_URL_VERSION}/`,"")}`;let I=w.params;return g&&(I=I.filter(L=>!L.match(/^access_token=/))),I.length&&(A+=`?${I.join("&")}`),A}canonicalizeTileset(d,g){const w=!!g&&s.e(g),A=[];for(const I of d.tiles||[])s.f(I)?A.push(this.canonicalizeTileURL(I,w)):A.push(I);return A}_makeAPIURL(d,g){const w="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",A=Ae(s.g.API_URL);if(d.protocol=A.protocol,d.authority=A.authority,d.protocol==="http"){const I=d.params.indexOf("secure");I>=0&&d.params.splice(I,1)}if(A.path!=="/"&&(d.path=`${A.path}${d.path}`),!s.g.REQUIRE_ACCESS_TOKEN)return we(d);if(g=g||s.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!g)throw new Error(`An API access token is required to use Mapbox GL. ${w}`);if(g[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${w}`)}return d.params=d.params.filter(I=>I.indexOf("access_token")===-1),d.params.push(`access_token=${g||""}`),we(d)}}const Oe=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function Ae(v){const d=v.match(Oe);if(!d)throw new Error("Unable to parse URL object");return{protocol:d[1],authority:d[2],path:d[3]||"/",params:d[4]?d[4].split("&"):[]}}function we(v){const d=v.params.length?`?${v.params.join("&")}`:"";return`${v.protocol}://${v.authority}${v.path}${d}`}const ge="mapbox.eventData";function Ne(v){if(!v)return null;const d=v.split(".");if(!d||d.length!==3)return null;try{return JSON.parse(s.l(d[1]))}catch{return null}}function Ie(v){return!(!s.g.EVENTS_URL||!v&&!s.g.ACCESS_TOKEN)}class Te{constructor(d){this.type=d,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(d){const g=Ne(s.g.ACCESS_TOKEN);let w="";return w=g&&g.u?s.j(g.u):s.g.ACCESS_TOKEN||"",d?`${ge}.${d}:${w}`:`${ge}:${w}`}fetchEventData(){const d=s.s("localStorage"),g=this.getStorageKey(),w=this.getStorageKey("uuid"),A=this.getStorageKey("uuidTimestamp");if(d)try{const I=localStorage.getItem(g);I&&(this.eventData=JSON.parse(I));const L=localStorage.getItem(w);L&&(this.anonId=L);const F=localStorage.getItem(A);F&&(this.anonIdTimestamp=Number(F));const $=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp<$)&&this.refreshUUID()}catch{s.w("Unable to read from LocalStorage")}}refreshUUID(){this.anonId=s.u(),this.anonIdTimestamp=Date.now()}saveEventData(){const d=s.s("localStorage"),g=this.getStorageKey(),w=this.getStorageKey("uuid"),A=this.getStorageKey("uuidTimestamp"),I=this.anonId,L=this.anonIdTimestamp;if(d&&I)try{localStorage.setItem(w,I),Object.keys(this.eventData).length>=1&&localStorage.setItem(g,JSON.stringify(this.eventData)),L&&localStorage.setItem(A,L.toString())}catch{s.w("Unable to write to LocalStorage")}}processRequests(d){}postEvent(d,g,w,A){if(!s.g.EVENTS_URL)return;const I=Ae(s.g.EVENTS_URL);I.params.push(`access_token=${A||s.g.ACCESS_TOKEN||""}`);const L={event:this.type,created:new Date(d).toISOString()},F=g?Object.assign(L,g):L,$={url:we(I),headers:{"Content-Type":"text/plain"},body:JSON.stringify([F])};this.pendingRequest=s.p($,H=>{this.pendingRequest=null,w(H),this.saveEventData(),this.processRequests(A)})}queueRequest(d,g){this.queue.push(d),this.processRequests(g)}}class be extends Te{constructor(d){super("metrics"),d&&(this.data=d)}postMetricsEvent(d){if(!Ie(d))return;this.anonId||this.fetchEventData(),s.v(this.anonId)||this.refreshUUID();const g=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:g},d)}processRequests(d){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:g,payload:w}=this.queue.shift();this.postEvent(g,w,()=>{},d)}}const We=new class extends Te{constructor(v){super("appUserTurnstile"),this._customAccessToken=v}postTurnstileEvent(v,d){Ie(d)&&Array.isArray(v)&&v.some(g=>s.e(g)||s.f(g))&&this.queueRequest(Date.now(),d)}processRequests(v){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const d=Ne(s.g.ACCESS_TOKEN),g=d?d.u:s.g.ACCESS_TOKEN;let w=g!==this.eventData.tokenU;s.v(this.anonId)||(this.refreshUUID(),w=!0);const A=this.queue.shift();if(this.eventData.lastSuccess){const I=new Date(this.eventData.lastSuccess),L=new Date(A),F=(A-this.eventData.lastSuccess)/864e5;w=w||F>=1||F<-1||I.getDate()!==L.getDate()}else w=!0;w?this.postEvent(A,{sdkIdentifier:"mapbox-gl-js",sdkVersion:f,skuId:_e,"enabled.telemetry":!1,userId:this.anonId},I=>{I||(this.eventData.lastSuccess=A,this.eventData.tokenU=g)},v):this.processRequests()}},rt=We.postTurnstileEvent.bind(We),at=new class extends Te{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(v,d,g,w){this.skuToken=d,this.errorCb=w,s.g.EVENTS_URL&&(g||s.g.ACCESS_TOKEN?this.queueRequest({id:v,timestamp:Date.now()},g):this.errorCb(new Error(Se)))}processRequests(v){if(this.pendingRequest||this.queue.length===0)return;const{id:d,timestamp:g}=this.queue.shift();d&&this.success[d]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),s.v(this.anonId)||this.refreshUUID(),this.postEvent(g,{sdkIdentifier:"mapbox-gl-js",sdkVersion:f,skuId:_e,skuToken:this.skuToken,userId:this.anonId},w=>{w?this.errorCb(w):d&&(this.success[d]=!0)},v))}remove(){this.errorCb=null}},Et=at.postMapLoadEvent.bind(at),_t=new class extends Te{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(v){let d=this.mapInstanceIdMap.get(v);return d||(d=s.u(),this.mapInstanceIdMap.set(v,d)),d}getEventId(v){const d=this.eventIdPerMapInstanceMap.get(v)||0;return this.eventIdPerMapInstanceMap.set(v,d+1),d}postStyleLoadEvent(v,d){const{map:g,style:w,importedStyles:A}=d;if(!Ie(v))return;const I=this.getMapInstanceId(g),L={mapInstanceId:I,eventId:this.getEventId(I),style:w};A.length&&(L.importedStyles=A),this.queueRequest({timestamp:Date.now(),payload:L},v)}processRequests(v){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:d,payload:g}=this.queue.shift();this.postEvent(d,g,()=>{},v)}},Vt=_t.postStyleLoadEvent.bind(_t),mt=new be({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Pt=mt.postMetricsEvent.bind(mt),er=new be({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),wt=er.postMetricsEvent.bind(er),or=new class extends Te{constructor(){super("gljs.performance")}postPerformanceEvent(v,d){Ie(v)&&this.queueRequest({timestamp:Date.now(),performanceData:d},v)}processRequests(v){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:d,performanceData:g}=this.queue.shift(),w=function(A){const I=performance.getEntriesByType("resource"),L=performance.getEntriesByType("mark"),F=function(ie){const le={};if(ie){for(const oe in ie)if(oe!=="other")for(const me of ie[oe]){const pe=`${oe}ResolveRangeMin`,je=`${oe}ResolveRangeMax`,Re=`${oe}RequestCount`,xe=`${oe}RequestCachedCount`;le[pe]=Math.min(le[pe]||1/0,me.startTime),le[je]=Math.max(le[je]||-1/0,me.responseEnd);const Ze=ze=>{le[ze]===void 0&&(le[ze]=0),++le[ze]};me.transferSize!==void 0&&me.transferSize===0&&Ze(xe),Ze(Re)}}return le}(function(ie,le){const oe={};if(ie)for(const me of ie){const pe=le(me);oe[pe]===void 0&&(oe[pe]=[]),oe[pe].push(me)}return oe}(I,_)),$=window.devicePixelRatio,H=navigator.connection||navigator.mozConnection||navigator.webkitConnection,Y=H?H.effectiveType:void 0,te={counters:[],metadata:[],attributes:[]},ee=(ie,le,oe)=>{oe!=null&&ie.push({name:le,value:oe.toString()})};for(const ie in F)ee(te.counters,ie,F[ie]);if(A.interactionRange[0]!==1/0&&A.interactionRange[1]!==-1/0&&(ee(te.counters,"interactionRangeMin",A.interactionRange[0]),ee(te.counters,"interactionRangeMax",A.interactionRange[1])),L)for(const ie of Object.values(m)){const le=L.find(oe=>oe.name===ie);le&&ee(te.counters,ie,le.startTime)}return ee(te.counters,"visibilityHidden",A.visibilityHidden),ee(te.attributes,"style",function(ie){if(ie)for(const le of ie){const oe=le.name.split("?")[0];if(s.i(oe)){const me=oe.split("/").slice(-2);if(me.length===2)return`mapbox://styles/${me[0]}/${me[1]}`}}}(I)),ee(te.attributes,"terrainEnabled",A.terrainEnabled?"true":"false"),ee(te.attributes,"fogEnabled",A.fogEnabled?"true":"false"),ee(te.attributes,"projection",A.projection),ee(te.attributes,"zoom",A.zoom),ee(te.metadata,"devicePixelRatio",$),ee(te.metadata,"connectionEffectiveType",Y),ee(te.metadata,"navigatorUserAgent",navigator.userAgent),ee(te.metadata,"screenWidth",window.screen.width),ee(te.metadata,"screenHeight",window.screen.height),ee(te.metadata,"windowWidth",window.innerWidth),ee(te.metadata,"windowHeight",window.innerHeight),ee(te.metadata,"mapWidth",A.width/$),ee(te.metadata,"mapHeight",A.height/$),ee(te.metadata,"webglRenderer",A.renderer),ee(te.metadata,"webglVendor",A.vendor),ee(te.metadata,"sdkVersion",f),ee(te.metadata,"sdkIdentifier","mapbox-gl-js"),te}(g);for(const A of w.metadata);for(const A of w.counters);for(const A of w.attributes);this.postEvent(d,w,()=>{},v)}},Sr=or.postPerformanceEvent.bind(or),nn=new class extends Te{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(v,d,g,w){if(!s.g.API_URL||!s.g.SESSION_PATH)return;const A=Ae(s.g.API_URL+s.g.SESSION_PATH);A.params.push(`sku=${d||""}`),A.params.push(`access_token=${w||s.g.ACCESS_TOKEN||""}`);const I={url:we(A),headers:{"Content-Type":"text/plain"}};this.pendingRequest=s.h(I,L=>{this.pendingRequest=null,g(L),this.saveEventData(),this.processRequests(w)})}getSessionAPI(v,d,g,w){this.skuToken=d,this.errorCb=w,s.g.EVENTS_URL&&s.g.SESSION_PATH&&s.g.API_URL&&(g||s.g.ACCESS_TOKEN?this.queueRequest({id:v,timestamp:Date.now()},g):this.errorCb(new Error(Se)))}processRequests(v){if(this.pendingRequest||this.queue.length===0)return;const{id:d,timestamp:g}=this.queue.shift();d&&this.success[d]||this.getSession(g,this.skuToken,w=>{w?this.errorCb(w):d&&(this.success[d]=!0)},v)}remove(){this.errorCb=null}},lr=nn.getSessionAPI.bind(nn),yr=new Set;function tr(v,d){d?yr.add(v):yr.delete(v)}class yn{constructor(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps=new Set,this._updatedImages={}}isDirty(){return this._changed}setDirty(){this._changed=!0}getUpdatedSourceCaches(){return this._updatedSourceCaches}updateSourceCache(d,g){this._updatedSourceCaches[d]=g,this.setDirty()}discardSourceCacheUpdate(d){delete this._updatedSourceCaches[d]}updateLayer(d){const g=d.scope;this._updatedLayers[g]=this._updatedLayers[g]||new Set,this._updatedLayers[g].add(d.id),this.setDirty()}removeLayer(d){const g=d.scope;this._removedLayers[g]=this._removedLayers[g]||{},this._updatedLayers[g]=this._updatedLayers[g]||new Set,this._removedLayers[g][d.id]=d,this._updatedLayers[g].delete(d.id),this._updatedPaintProps.delete(d.fqid),this.setDirty()}getRemovedLayer(d){return this._removedLayers[d.scope]?this._removedLayers[d.scope][d.id]:null}discardLayerRemoval(d){this._removedLayers[d.scope]&&delete this._removedLayers[d.scope][d.id]}getLayerUpdatesByScope(){const d={};for(const g in this._updatedLayers)d[g]=d[g]||{},d[g].updatedIds=Array.from(this._updatedLayers[g].values());for(const g in this._removedLayers)d[g]=d[g]||{},d[g].removedIds=Object.keys(this._removedLayers[g]);return d}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(d){this._updatedPaintProps.add(d.fqid),this.setDirty()}getUpdatedImages(d){return this._updatedImages[d]?Array.from(this._updatedImages[d].values()):[]}updateImage(d,g){this._updatedImages[g]=this._updatedImages[g]||new Set,this._updatedImages[g].add(s.I.toString(d)),this.setDirty()}resetUpdatedImages(d){this._updatedImages[d]&&this._updatedImages[d].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function lt(v){const{userImage:d}=v;return!!(d&&d.render&&d.render())&&(v.data.replace(new Uint8Array(d.data.buffer)),!0)}const At={workerUrl:"",workerClass:null,workerParams:void 0};function Ot(v){return At.workerClass!=null?new At.workerClass:new self.Worker(At.workerUrl,Object.assign({name:v},At.workerParams))}const dr="mapboxgl_preloaded_worker_pool";class cr{constructor(d){this.active={},this.name=d}acquire(d,g=cr.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{g.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[dr]}numActive(){return Object.keys(this.active).length}}cr.workerCount=2;class hr{constructor(d,g,w="Worker",A=cr.workerCount){this.workerPool=d,this.actors=[],this.currentActor=0,this.id=s.r();const I=this.workerPool.acquire(this.id,A);for(let L=0;L{this.ready=!0})}broadcast(d,g,w){s.t(this.actors,(A,I)=>{A.send(d,g,I)},w=w||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(d=>{d.remove()}),this.actors=[],this.workerPool.release(this.id)}}let Zt,Pr;function Nn(){return Zt||(Zt=new cr),Zt}hr.Actor=s.A;class ai extends s.E{constructor(d){super(),this.imageProviders=new Map,this.images=new Map,this.updatedImages=new Map,this.callbackDispatchedThisFrame=new Map,this.imageVersions=new Map,this.loaded=new Map,this.requestors=[],this.patterns=new Map,this.patternsInFlight=new Set,this.atlasImage=new Map,this.atlasTexture=new Map,this.imageAtlasCache=new s.x,this.dirty=!0,this.spriteFormat=d,d!=="raster"&&s.y()&&(this.imageRasterizerDispatcher=new hr((Pr||(Pr=new cr("ImageRasterizer")),Pr),this,"Image Rasterizer Worker",1))}addScope(d){this.loaded.set(d,!1),this.imageProviders.set(d,new Map),this.images.set(d,new Map),this.updatedImages.set(d,new Set),this.callbackDispatchedThisFrame.set(d,new Set),this.imageVersions.set(d,new Map),this.patterns.set(d,new Map),this.atlasImage.set(d,new s.q({width:1,height:1}))}removeScope(d){this.loaded.delete(d),this.imageProviders.delete(d),this.images.delete(d),this.updatedImages.delete(d),this.callbackDispatchedThisFrame.delete(d),this.imageVersions.delete(d),this.patterns.delete(d),this.atlasImage.delete(d);const g=this.atlasTexture.get(d);g&&(g.destroy(),this.atlasTexture.delete(d))}addImageProvider(d,g){this.imageProviders.has(g)||this.imageProviders.set(g,new Map),this.imageProviders.get(g).set(d.id,d)}removeImageProvider(d,g){this.imageProviders.has(g)&&this.imageProviders.get(g).delete(d)}getPendingImageProviders(){const d=[];for(const g of this.imageProviders.values())for(const w of g.values())w.hasPendingRequests()&&d.push(w);return d}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new s.z),this._imageRasterizer}isLoaded(){for(const d of this.loaded.keys())if(!this.loaded.get(d))return!1;return!0}setLoaded(d,g){if(this.loaded.get(g)!==d&&(this.loaded.set(g,d),d)){for(const{ids:w,callback:A}of this.requestors)this._notify(w,g,A);this.requestors=[]}}hasImage(d,g){return!!this.getImage(d,g)}getImage(d,g){return this.images.get(g).get(d.toString())}addImage(d,g,w){if(this._validate(d,w)){this.images.get(g).set(d.toString(),w);const A=this.imageVersions.get(g),I=A.get(d.toString())||0;A.set(d.toString(),I+1)}}_validate(d,g){let w=!0;return this._validateStretch(g.stretchX,g.data&&g.data.width)||(this.fire(new s.B(new Error(`Image "${d.name}" has invalid "stretchX" value`))),w=!1),this._validateStretch(g.stretchY,g.data&&g.data.height)||(this.fire(new s.B(new Error(`Image "${d.name}" has invalid "stretchY" value`))),w=!1),this._validateContent(g.content,g)||(this.fire(new s.B(new Error(`Image "${d.name}" has invalid "content" value`))),w=!1),w}_validateStretch(d,g){if(!d)return!0;let w=0;for(const A of d){if(A[0]s.I.from(g))}getImageVersions(d){const g=this.imageVersions.get(d);if(g)return g}getImages(d,g,w){const A=[],I=[],L=this.imageProviders.get(g);for(const Y of d){if(!Y.iconsetId){A.push(Y);continue}const te=L.get(Y.iconsetId);te&&(this.getImage(Y,g)?I.push(Y):te.addPendingRequest(Y))}if(A.length===0)return void this._notify(I,g,w);let F=!0;const $=!!this.loaded.get(g),H=this.images.get(g);if(!$)for(const Y of A)H.has(Y.toString())||(F=!1);$||F?this._notify(A,g,w):this.requestors.push({ids:A,scope:g,callback:w})}rasterizeImages(d,g){const w=new Map,{tasks:A,scope:I}=d;for(const[L,F]of A.entries()){const $=this.getImage(F.id,I);$&&w.set(L,{image:$,imageVariant:F})}this._rasterizeImages(I,w,g)}_rasterizeImages(d,g,w){if(s.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:g,scope:d},w);else{const A=new Map;for(const[I,{image:L,imageVariant:F}]of g.entries())A.set(I,this.imageRasterizer.rasterize(F,L,d,0));w(void 0,A)}}getUpdatedImages(d){return this.updatedImages.get(d)||new Set}_notify(d,g,w){const A=this.images.get(g),I=new Map;for(const L of d){if(!A.get(L.toString())){if(L.iconsetId)continue;this.fire(new s.C("styleimagemissing",{id:L.name}))}const F=A.get(L.toString());if(!F){s.w(`Image "${L.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 $={data:F.usvg?null:F.data.clone(),pixelRatio:F.pixelRatio,sdf:F.sdf,usvg:F.usvg,stretchX:F.stretchX,stretchY:F.stretchY,content:F.content,hasRenderCallback:!!(F.userImage&&F.userImage.render)};F.usvg&&Object.assign($,{width:F.icon.usvg_tree.width,height:F.icon.usvg_tree.height}),I.set(s.I.toString(L),$)}w(null,{images:I,versions:this.getImageVersions(g)})}getPixelSize(d){const{width:g,height:w}=this.atlasImage.get(d);return{width:g,height:w}}getPattern(d,g,w){const A=d.toString(),I=this.patterns.get(g),L=I.get(A),F=this.getImage(d,g);if(!F)return null;if(L){if(L.position.version===F.version)return L.position;L.position.version=F.version}else{if(F.usvg&&!F.data){const $=this.getPatternInFlightId(A,g);if(this.patternsInFlight.has($))return null;this.patternsInFlight.add($);const H=new s.D(d).scaleSelf(s.o.devicePixelRatio),Y=new Map([[H.toString(),{image:F,imageVariant:H}]]);return this._rasterizeImages(g,Y,(te,ee)=>this.storePatternImage(H,g,F,w,ee)),null}this.storePattern(d,g,F)}return this._updatePatternAtlas(g,w),I.get(A).position}getPatternInFlightId(d,g){return s.F(d,g)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(d,g,w,A,I){const L=d.toString(),F=I?I.get(L):void 0;F&&(w.data=F,this.storePattern(d.id,g,w),this._updatePatternAtlas(g,A),this.patternsInFlight.delete(this.getPatternInFlightId(d.id.toString(),g)))}storePattern(d,g,w){const A={w:w.data.width+2*s.G,h:w.data.height+2*s.G,x:0,y:0},I=new s.H(A,w,s.G);this.patterns.get(g).set(d.toString(),{bin:A,position:I})}destroyAtlasTextures(){for(const d of this.atlasTexture.values())d&&d.destroy();this.atlasTexture.clear()}bind(d,g){const w=d.gl;let A=this.atlasTexture.get(g);A?this.dirty&&(A.update(this.atlasImage.get(g)),this.dirty=!1):(A=new s.T(d,this.atlasImage.get(g),w.RGBA8),this.atlasTexture.set(g,A)),A.bind(w.LINEAR,w.CLAMP_TO_EDGE)}_updatePatternAtlas(d,g){const w=this.patterns.get(d),A=Array.from(w.values()).map(({bin:H})=>H),{w:I,h:L}=s.J(A),F=this.atlasImage.get(d);F.resize({width:I||1,height:L||1});const $=this.images.get(d);for(const[H,{bin:Y,position:te}]of w.entries()){let ee=te.padding;const ie=Y.x+ee,le=Y.y+ee,oe=$.get(H).data,me=oe.width,pe=oe.height;ee=ee>1?ee-1:ee,s.q.copy(oe,F,{x:0,y:0},{x:ie,y:le},{width:me,height:pe},g),s.q.copy(oe,F,{x:0,y:pe-ee},{x:ie,y:le-ee},{width:me,height:ee},g),s.q.copy(oe,F,{x:0,y:0},{x:ie,y:le+pe},{width:me,height:ee},g),s.q.copy(oe,F,{x:me-ee,y:0},{x:ie-ee,y:le},{width:ee,height:pe},g),s.q.copy(oe,F,{x:0,y:0},{x:ie+me,y:le},{width:ee,height:pe},g),s.q.copy(oe,F,{x:me-ee,y:pe-ee},{x:ie-ee,y:le-ee},{width:ee,height:ee},g),s.q.copy(oe,F,{x:0,y:pe-ee},{x:ie+me,y:le-ee},{width:ee,height:ee},g),s.q.copy(oe,F,{x:0,y:0},{x:ie+me,y:le+pe},{width:ee,height:ee},g),s.q.copy(oe,F,{x:me-ee,y:0},{x:ie-ee,y:le+pe},{width:ee,height:ee},g)}this.dirty=!0}beginFrame(){for(const d of this.images.keys())this.callbackDispatchedThisFrame.set(d,new Set)}dispatchRenderCallbacks(d,g){const w=this.images.get(g);for(const A of d){if(this.callbackDispatchedThisFrame.get(g).has(A.toString()))continue;this.callbackDispatchedThisFrame.get(g).add(A.toString());const I=w.get(A.toString());lt(I)&&this.updateImage(A,g,I)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function ei(v){const d=v.value,g=v.valueSpec,w=v.style,A=v.styleSpec,I=v.key,L=v.arrayElementValidator||bi;if(!Array.isArray(d))return[new s.V(I,d,`array expected, ${s.M(d)} found`)];if(g.length&&d.length!==g.length)return[new s.V(I,d,`array length ${g.length} expected, length ${d.length} found`)];if(g["min-length"]&&d.lengthA)return[new s.V(d,g,`${g} is greater than the maximum value ${A}`)]}return[]}function ya(v){const d=v.key,g=v.value;if(!s.K(g))return[new s.V(d,g,`object expected, ${s.M(g)} found`)];const w=v.valueSpec,A=s.L(g.type);let I,L,F,$={};const H=A!=="categorical"&&g.property===void 0,Y=!H,te=function(oe){const me=oe.stops;return Array.isArray(me)&&Array.isArray(me[0])&&s.K(me[0][0])}(g),ee=ks({key:v.key,value:v.value,valueSpec:v.styleSpec.function,style:v.style,styleSpec:v.styleSpec,objectElementValidators:{stops:function(oe){if(A==="identity")return[new s.V(oe.key,oe.value,'identity function may not have a "stops" property')];let me=[];const pe=oe.value;return me=me.concat(ei({key:oe.key,value:pe,valueSpec:oe.valueSpec,style:oe.style,styleSpec:oe.styleSpec,arrayElementValidator:ie})),Array.isArray(pe)&&pe.length===0&&me.push(new s.V(oe.key,pe,"array must have at least one stop")),me},default:function(oe){return bi({key:oe.key,value:oe.value,valueSpec:w,style:oe.style,styleSpec:oe.styleSpec})}}});return A==="identity"&&H&&ee.push(new s.V(v.key,v.value,'missing required property "property"')),A==="identity"||g.stops||ee.push(new s.V(v.key,v.value,'missing required property "stops"')),A==="exponential"&&w.expression&&!s.O(w)&&ee.push(new s.V(v.key,v.value,"exponential functions not supported")),v.styleSpec.$version>=8&&(Y&&!s.Q(w)?ee.push(new s.V(v.key,v.value,"property functions not supported")):H&&!s.S(w)&&ee.push(new s.V(v.key,v.value,"zoom functions not supported"))),A!=="categorical"&&!te||g.property!==void 0||ee.push(new s.V(v.key,v.value,'"property" property is required')),ee;function ie(oe){let me=[];const pe=oe.value,je=oe.key;if(!Array.isArray(pe))return[new s.V(je,pe,`array expected, ${s.M(pe)} found`)];if(pe.length!==2)return[new s.V(je,pe,`array length 2 expected, length ${pe.length} found`)];if(te){if(!s.K(pe[0]))return[new s.V(je,pe,`object expected, ${s.M(pe[0])} found`)];const Re=pe[0];if(Re.zoom===void 0)return[new s.V(je,pe,"object stop key must have zoom")];if(Re.value===void 0)return[new s.V(je,pe,"object stop key must have value")];const xe=s.L(Re.zoom);if(typeof xe!="number")return[new s.V(je,Re.zoom,"stop zoom values must be numbers")];if(F&&F>xe)return[new s.V(je,Re.zoom,"stop zoom values must appear in ascending order")];xe!==F&&(F=xe,L=void 0,$={}),me=me.concat(ks({key:`${je}[0]`,value:pe[0],valueSpec:{zoom:{}},style:oe.style,styleSpec:oe.styleSpec,objectElementValidators:{zoom:Oi,value:le}}))}else me=me.concat(le({key:`${je}[0]`,value:pe[0],style:oe.style,styleSpec:oe.styleSpec},pe));return s.U(s.W(pe[1]))?me.concat([new s.V(`${je}[1]`,pe[1],"expressions are not allowed in function stops.")]):me.concat(bi({key:`${je}[1]`,value:pe[1],valueSpec:w,style:oe.style,styleSpec:oe.styleSpec}))}function le(oe,me){const pe=s.M(oe.value),je=s.L(oe.value),Re=oe.value!==null?oe.value:me;if(I){if(pe!==I)return[new s.V(oe.key,Re,`${pe} stop domain type must match previous stop domain type ${I}`)]}else I=pe;if(pe!=="number"&&pe!=="string"&&pe!=="boolean"&&typeof je!="number"&&typeof je!="string"&&typeof je!="boolean")return[new s.V(oe.key,Re,"stop domain value must be a number, string, or boolean")];if(pe!=="number"&&A!=="categorical"){let xe=`number expected, ${pe} found`;return s.Q(w)&&A===void 0&&(xe+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new s.V(oe.key,Re,xe)]}return A!=="categorical"||pe!=="number"||typeof je=="number"&&isFinite(je)&&Math.floor(je)===je?A!=="categorical"&&pe==="number"&&typeof je=="number"&&typeof L=="number"&&L!==void 0&&jenew s.V(`${v.key}${w.key}`,v.value,w.message));const g=d.value.expression||d.value._styleExpression.expression;if(v.expressionContext==="property"&&v.propertyKey==="text-font"&&!g.outputDefined())return[new s.V(v.key,v.value,`Invalid data expression for "${v.propertyKey}". Output values must be contained as literals within the expression.`)];if(v.expressionContext==="property"&&v.propertyType==="layout"&&!s.$(g))return[new s.V(v.key,v.value,'"feature-state" data expressions are not supported with layout properties.')];if(v.expressionContext==="filter")return ia(g,v);if(v.expressionContext==="appearance")return jr(g,v);if(v.expressionContext&&v.expressionContext.indexOf("cluster")===0){if(!s.Z(g,["zoom","feature-state"]))return[new s.V(v.key,v.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(v.expressionContext==="cluster-initial"&&!s._(g))return[new s.V(v.key,v.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function ia(v,d){const g=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(d.valueSpec&&d.valueSpec.expression)for(const A of d.valueSpec.expression.parameters)g.delete(A);if(g.size===0)return[];const w=[];return v instanceof s.a0&&g.has(v.name)?[new s.V(d.key,d.value,`["${v.name}"] expression is not supported in a filter for a ${d.object.type} layer with id: ${d.object.id}`)]:(v.eachChild(A=>{w.push(...ia(A,d))}),w)}function jr(v,d){const g=new Set;if(d.valueSpec&&d.valueSpec.expression)for(const A of d.valueSpec.expression.parameters)g.add(A);if(g.size===0)return[];const w=[];return v instanceof s.a0&&!g.has(v.name)?[new s.V(d.key,d.value,`["${v.name}"] is not an allowed parameter`)]:(v.eachChild(A=>{w.push(...jr(A,d))}),w)}function Mn(v){const d=v.key,g=v.value,w=v.valueSpec,A=[];return Array.isArray(w.values)?w.values.indexOf(s.L(g))===-1&&A.push(new s.V(d,g,`expected one of [${w.values.join(", ")}], ${JSON.stringify(g)} found`)):Object.keys(w.values).indexOf(s.L(g))===-1&&A.push(new s.V(d,g,`expected one of [${Object.keys(w.values).join(", ")}], ${JSON.stringify(g)} found`)),A}function As(v){return s.a4(s.W(v.value))?mi(Object.assign({},v,{expressionContext:"filter",valueSpec:v.styleSpec[`filter_${v.layerType||"fill"}`]})):xa(v)}function xa(v){const d=v.value,g=v.key;if(!Array.isArray(d))return[new s.V(g,d,`array expected, ${s.M(d)} found`)];if(d.length<1)return[new s.V(g,d,"filter array must have at least 1 element")];const w=v.styleSpec;let A=Mn({key:`${g}[0]`,value:d[0],valueSpec:w.filter_operator});const I=()=>{d.length>=2&&(s.a2(d[1])||A.push(new s.V(`${g}[1]`,d[1],`string expected, ${s.M(d[1])} found`)));for(let L=2;L":case">=":d.length>=2&&s.L(d[1])==="$type"&&A.push(new s.V(g,d,`"$type" cannot be use with operator "${d[0]}"`)),d.length!==3&&A.push(new s.V(g,d,`filter array for operator "${d[0]}" must have 3 elements`)),I();break;case"==":case"!=":d.length!==3&&A.push(new s.V(g,d,`filter array for operator "${d[0]}" must have 3 elements`)),I();break;case"in":case"!in":I();break;case"any":case"all":case"none":for(let L=1;L{H in g&&d.push(new s.V(w,g[H],`"${H}" is prohibited for ref layers`))}),A.layers.forEach(H=>{s.L(H.id)===F&&($=H)}),$?$.ref?d.push(new s.V(w,g.ref,"ref cannot reference another ref layer")):L=s.L($.type):typeof F=="string"&&d.push(new s.V(w,g.ref,`ref layer "${F}" not found`))}else if(L!=="background"&&L!=="sky"&&L!=="slot")if(g.source)if(s.a2(g.source)){const $=A.sources&&A.sources[g.source],H=$&&s.L($.type);$?H==="vector"&&L==="raster"?d.push(new s.V(w,g.source,`layer "${g.id}" requires a raster source`)):H==="raster"&&L!=="raster"?d.push(new s.V(w,g.source,`layer "${g.id}" requires a vector source`)):H!=="vector"||g["source-layer"]?H==="raster-dem"&&L!=="hillshade"?d.push(new s.V(w,g.source,"raster-dem source can only be used with layer type 'hillshade'.")):H!=="raster-array"||["raster","raster-particle"].includes(L)?L==="line"&&g.paint&&(g.paint["line-gradient"]||g.paint["line-trim-offset"])&&H==="geojson"&&!$.lineMetrics?d.push(new s.V(w,g,`layer "${g.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):L==="raster-particle"&&H!=="raster-array"&&d.push(new s.V(w,g.source,`layer "${g.id}" requires a 'raster-array' source.`)):d.push(new s.V(w,g.source,"raster-array source can only be used with layer type 'raster'.")):d.push(new s.V(w,g,`layer "${g.id}" must specify a "source-layer"`)):d.push(new s.V(w,g.source,`source "${g.source}" not found`))}else d.push(new s.V(`${w}.source`,g.source,'"source" must be a string'));else d.push(new s.V(w,g,'missing required property "source"'));return d=d.concat(ks({key:w,value:g,valueSpec:I.layer,style:v.style,styleSpec:v.styleSpec,objectElementValidators:{"*":()=>[],type:()=>bi({key:`${w}.type`,value:g.type,valueSpec:I.layer.type,style:v.style,styleSpec:v.styleSpec,object:g,objectKey:"type"}),filter:$=>As(Object.assign({layerType:L},$)),layout:$=>ks({layer:g,key:$.key,value:$.value,valueSpec:{},style:$.style,styleSpec:$.styleSpec,objectElementValidators:{"*":H=>hn(Object.assign({layerType:L},H))}}),paint:$=>ks({layer:g,key:$.key,value:$.value,valueSpec:{},style:$.style,styleSpec:$.styleSpec,objectElementValidators:{"*":H=>Yr(Object.assign({layerType:L,layer:g},H))}}),appearances($){const H=ei({key:$.key,value:$.value,valueSpec:$.valueSpec,style:$.style,styleSpec:$.styleSpec,arrayElementValidator:ee=>function(ie){const{key:le,layer:oe,layerType:me}=ie,pe=s.L(ie.value),je=s.L(pe.name),Re=s.L(pe.condition),xe=ks({key:le,value:pe,valueSpec:ie.styleSpec.appearance,style:ie.style,styleSpec:ie.styleSpec,objectElementValidators:{condition:Ze=>function(ze){const Ke=[];return Ke.push(...mi({key:ze.key,value:ze.object.condition,valueSpec:s.a8.appearance.condition,expressionContext:"appearance"})),Ke}(Object.assign({layer:oe,layerType:me},Ze)),properties:Ze=>function(ze){const Ke=[],{styleSpec:De,layer:Fe,layerType:qe}=ze,st=De[`paint_${qe}`],Qe=De[`layout_${qe}`],xt=ze.object[ze.objectKey];for(const ft in xt){const Rt=ft in st?"paint":ft in Qe?"layout":void 0;if(!Rt){Ke.push(new s.V(ze.key,ft,`unknown property "${ft}" for layer type "${qe}"`));continue}const Ft=Object.assign({},ze,{key:`${ze.key}.${ft}`,object:xt,objectKey:ft,layer:Fe,layerType:qe,value:xt[ft],valueSpec:Rt==="paint"?st[ft]:Qe[ft]});Ke.push(...go(Ft,Rt))}return Ke}(Object.assign({layer:oe,layerType:me},Ze))}});return je!=="hidden"&&Re===void 0&&xe.push(new s.V(ie.key,"name",'Appearance with name different than "hidden" must have a condition')),xe}(Object.assign({layerType:L,layer:g},ee))}),Y=Array.isArray($.value)?$.value:[],te=new Set;return Y.forEach((ee,ie)=>{const le=s.L(ee.name);if(le)if(te.has(le)){const oe=s.L(g.id);H.push(new s.V($.key,le,`Duplicated appearance name "${le}" for layer "${oe}"`))}else te.add(le)}),H}}})),d}function Zr({key:v,value:d}){return s.a2(d)?[]:[new s.V(v,d,`string expected, ${s.M(d)} found`)]}const oi={promoteId:function v({key:d,value:g}){if(s.a2(g))return Zr({key:d,value:g});if(Array.isArray(g)){const A=[],I=s.W(g),L=s.X(I);return L.result==="error"?(L.value.forEach(F=>{A.push(new s.V(`${d}${F.key}`,null,`${F.message}`))}),A):(s.Z(L.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"])||A.push(new s.V(`${d}`,null,"promoteId expression should be only feature dependent")),A)}if(!s.K(g))return[new s.V(d,g,`string, expression or object expected, "${s.M(g)}" found`)];const w=[];for(const A in g)w.push(...v({key:`${d}.${A}`,value:g[A]}));return w}};function Jr(v){const d=v.value,g=v.key,w=v.styleSpec,A=v.style;if(!s.K(d))return[new s.V(g,d,`object expected, ${s.M(d)} found`)];if(!("type"in d))return[new s.V(g,d,'"type" is required')];const I=s.L(d.type);let L=[];switch(["vector","raster","raster-dem","raster-array"].includes(I)&&("url"in d||"tiles"in d||L.push(new s.a5(g,d,'Either "url" or "tiles" is required.'))),I){case"vector":case"raster":case"raster-dem":case"raster-array":return L=L.concat(ks({key:g,value:d,valueSpec:w[`source_${I.replace("-","_")}`],style:v.style,styleSpec:w,objectElementValidators:oi})),L;case"geojson":if(L=ks({key:g,value:d,valueSpec:w.source_geojson,style:A,styleSpec:w,objectElementValidators:oi}),"cluster"in d&&"clusterProperties"in d){if(!s.K(d.clusterProperties))return[new s.V(`${g}.clusterProperties`,d,`object expected, ${s.M(d)} found`)];for(const F in d.clusterProperties){const $=d.clusterProperties[F];if(!Array.isArray($))return[new s.V(`${g}.clusterProperties.${F}`,$,"array expected")];const[H,Y]=$,te=typeof H=="string"?[H,["accumulated"],["get",F]]:H;L.push(...mi({key:`${g}.${F}.map`,value:Y,expressionContext:"cluster-map"})),L.push(...mi({key:`${g}.${F}.reduce`,value:te,expressionContext:"cluster-reduce"}))}}return L;case"video":return ks({key:g,value:d,valueSpec:w.source_video,style:A,styleSpec:w});case"image":return ks({key:g,value:d,valueSpec:w.source_image,style:A,styleSpec:w});case"canvas":return[new s.V(g,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Mn({key:`${g}.type`,value:d.type,valueSpec:{values:Fn(w)}})}}function Fn(v){return v.source.reduce((d,g)=>{const w=v[g];return w.type.type==="enum"&&(d=d.concat(Object.keys(w.type.values||{}))),d},[])}function es(v){const d=v.value,g=v.styleSpec,w=g.light,A=v.style;if(d===void 0)return[];if(!s.K(d))return[new s.V("light",d,`object expected, ${s.M(d)} found`)];let I=[];for(const L in d){const F=L.match(/^(.*)-transition$/),$=L.match(/^(.*)-use-theme$/);I=I.concat($&&w[$[1]]?bi({key:L,value:d[L],valueSpec:{type:"string"},style:A,styleSpec:g}):F&&w[F[1]]&&w[F[1]].transition?bi({key:L,value:d[L],valueSpec:g.transition,style:A,styleSpec:g}):w[L]?bi({key:L,value:d[L],valueSpec:w[L],style:A,styleSpec:g}):[new s.V(L,d[L],`unknown property "${L}"`)])}return I}function fl(v){const d=v.value;if(!d)return[];const g=v.key;if(!s.K(d))return[new s.V(g,d,`object expected, ${s.M(d)} found`)];let w=[];const A=v.styleSpec,I=A["light-3d"],L=v.style,F=v.style.lights;for(const Y of["type","id"])if(!(Y in d))return w=w.concat([new s.V(g,d,`missing property "${Y}"`)]),w;if(!s.a2(d.type))return w=w.concat([new s.V(`${g}.type`,d.type,"string expected")]),w;if(F)for(let Y=0;Y[],array:ei,boolean:function(v){const d=v.value,g=v.key;return s.a1(d)?[]:[new s.V(g,d,`boolean expected, ${s.M(d)} found`)]},number:Oi,color:function({key:v,value:d}){return s.a2(d)?s.a3.parseCSSColor(d)===null?[new s.V(v,d,`color expected, "${d}" found`)]:[]:[new s.V(v,d,`color expected, ${s.M(d)} found`)]},enum:Mn,filter:As,function:ya,layer:gn,object:ks,source:Jr,model:s.a9,light:es,"light-3d":fl,terrain:Wo,fog:Mt,string:Zr,formatted:function(v){return Zr(v).length===0?[]:mi(v)},resolvedImage:function(v){return Zr(v).length===0?[]:mi(v)},projection:function(v){const d=v.value,g=v.styleSpec,w=g.projection,A=v.style;if(s.K(d)){let I=[];for(const L in d)I=I.concat(bi({key:L,value:d[L],valueSpec:w[L],style:A,styleSpec:g}));return I}return s.a2(d)?[]:[new s.V("projection",d,`object or string expected, ${s.M(d)} found`)]},import:function(v){const d=v.key,{value:g,styleSpec:w}=v;if(!s.K(g))return[new s.V(d,g,"import must be an object")];const{data:A,...I}=g;Object.defineProperty(I,"__line__",{value:g.__line__,enumerable:!1});let L=ks(Object.assign({},v,{value:I,valueSpec:w.import}));return s.L(I.id)===""&&L.push(new s.V(`${v.key}.id`,I,"import id can't be an empty string")),A&&(L=L.concat(ao(A,w,{key:`${v.key}.data`}))),L},iconset:function(v){const d=v.value,g=v.key,w=v.styleSpec,A=v.style;if(!s.K(d))return[new s.V(g,d,"object expected")];if(!d.type)return[new s.V(g,d,'"type" is required')];const I=s.L(d.type);let L=[];if(L=L.concat(ks({key:g,value:d,valueSpec:w[`iconset_${I}`],style:A,styleSpec:w})),function(F,$){return!(F!=="source"||!$.source)}(I,d)){const F=A.sources&&A.sources[d.source],$=F&&s.L(F.type);F?$!=="raster-array"&&L.push(new s.V(g,d.source,`iconset cannot be used with a source of type ${String($)}, it only be used with a "raster-array" source type`)):L.push(new s.V(g,d.source,`source "${d.source}" not found`))}return L}};function bi(v,d=!1){const g=v.value,w=v.valueSpec,A=v.styleSpec;if(w.expression){if(s.a6(s.L(g)))return ya(v);if(s.U(s.W(g)))return mi(v)}if(w.type&&Po[w.type]){const I=Po[w.type](v);return d===!0&&I.length>0&&Array.isArray(v.value)?mi(v):I}return ks(Object.assign({},v,{valueSpec:w.type?A[w.type]:w}))}function ks(v){const d=v.key,g=v.value,w=v.valueSpec||{},A=v.objectElementValidators||{},I=v.style,L=v.styleSpec;if(!s.K(g))return[new s.V(d,g,`object expected, ${s.M(g)} found`)];let F=[];for(const $ in g){const H=$.split(".")[0];let Y;A[H]?Y=A[H]:w[H]?Y=bi:A["*"]?Y=A["*"]:w["*"]&&(Y=bi),Y?F=F.concat(Y({key:(d&&`${d}.`)+$,value:g[$],valueSpec:w[H]||w["*"],style:I,styleSpec:L,object:g,objectKey:$},g)):F.push(new s.a5(d,g[$],`unknown property "${$}"`))}for(const $ in w){if(A[$])continue;const H=w[$];H.required&&H.default===void 0&&g[$]===void 0&&F.push(new s.V(d,g,`missing required property "${$}"`))}return F}function Kn({key:v,value:d}){const g=Zr({key:v,value:d});if(g.length)return g;const w=d;return w.indexOf("{fontstack}")===-1&&g.push(new s.V(v,d,'"glyphs" url must include a "{fontstack}" token')),w.indexOf("{range}")===-1&&g.push(new s.V(v,d,'"glyphs" url must include a "{range}" token')),g}function ao(v,d=s.a8,g={}){return ks({key:g.key||"",value:v,valueSpec:Object.assign(d.$root,{"*":{type:"*"}}),styleSpec:d,style:v,objectElementValidators:{glyphs:Kn}})}function tu(v,d=s.a8){return Nt(ao(v,d))}const yx=v=>Nt(Jr(v)),ct=v=>Nt(es(v)),de=v=>Nt(fl(v)),fe=v=>Nt(Wo(v)),Me=v=>Nt(Mt(v)),Ye=v=>Nt(function(d){const g=d.value,w=d.style,A=d.styleSpec,I=A.snow;if(g===void 0)return[];if(!s.K(g))return[new s.V("snow",g,`object expected, ${s.M(g)} found`)];let L=[];for(const F in g){const $=F.match(/^(.*)-transition$/);L=L.concat($&&I[$[1]]&&I[$[1]].transition?bi({key:F,value:g[F],valueSpec:A.transition,style:w,styleSpec:A}):I[F]?bi({key:F,value:g[F],valueSpec:I[F],style:w,styleSpec:A}):[new s.a5(F,g[F],`unknown property "${F}"`)])}return L}(v)),Je=v=>Nt(function(d){const g=d.value,w=d.style,A=d.styleSpec,I=A.rain;if(g===void 0)return[];if(!s.K(g))return[new s.V("rain",g,`object expected, ${s.M(g)} found`)];let L=[];for(const F in g){const $=F.match(/^(.*)-transition$/);L=L.concat($&&I[$[1]]&&I[$[1]].transition?bi({key:F,value:g[F],valueSpec:A.transition,style:w,styleSpec:A}):I[F]?bi({key:F,value:g[F],valueSpec:I[F],style:w,styleSpec:A}):[new s.a5(F,g[F],`unknown property "${F}"`)])}return L}(v)),tt=v=>Nt(gn(v)),dt=v=>Nt(As(v)),it=v=>Nt(Yr(v)),ht=v=>Nt(hn(v)),zt=v=>Nt(s.a9(v));function Nt(v){return v.slice().sort((d,g)=>d.line&&g.line?d.line-g.line:0)}function fr(v,d){let g=!1;if(d&&d.length)for(const w of d)w instanceof s.a5?s.w(w.message):(v.fire(new s.B(new Error(w.message))),g=!0);return g}const Fr=s.a8.light;let qr;class Br extends s.E{constructor(d,g="flat"){super(),this._transitionable=new s.aa(qr||(qr=new s.ab({anchor:new s.ac(Fr.anchor),position:new s.ad(Fr.position),color:new s.ac(Fr.color),intensity:new s.ac(Fr.intensity)}))),this.setLight(d,g),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(d,g,w={}){this._validate(ct,d,w)||(this._transitionable.setTransitionOrValue(d),this.id=g)}updateTransitions(d){this._transitioning=this._transitionable.transitioned(d,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(d){this.properties=this._transitioning.possiblyEvaluate(d)}_validate(d,g,w){return(!w||w.validate!==!1)&&fr(this,d.call(tu,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:s.a8})))}}const an=s.a8.terrain;let kn=class extends s.E{constructor(v,d,g,w,A){super(),this.scope=g,this._transitionable=new s.aa(new s.ab({source:new s.ac(an.source),exaggeration:new s.ac(an.exaggeration)}),g,w),this._transitionable.setTransitionOrValue(v,w),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=d,this.worldview=A}get(){return this._transitionable.serialize()}set(v,d){this._transitionable.setTransitionOrValue(v,d)}updateTransitions(v){this._transitioning=this._transitionable.transitioned(v,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(v){this.properties=this._transitioning.possiblyEvaluate(v)}getExaggeration(v){return this._transitioning.possiblyEvaluate(new s.ae(v,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const v=this._transitionable._values.exaggeration;if(!v)return null;const d=v.value.expression;if(!d)return null;let g=-1,w=-1,A=1;for(const I of d.zoomStops)A=d.evaluate(new s.ae(I,{worldview:this.worldview})),A>.01?(g=I,w=-1):w=I;return A<.01&&g>0&&w>g?[g,w]:null}isZoomDependent(){const v=this._transitionable._values.exaggeration;return v!=null&&v.value!=null&&v.value.expression!=null&&v.value.expression instanceof s.af}};const Rn=.05;function Ci(v,d,g,w){const A=s.aj(45,65,g),[I,L]=Ds(v,w);let F=1-Math.min(1,Math.exp((d-I)/(L-I)*-6));return F*=F*F,F=Math.min(1,1.00747*F),F*A*v.alpha}function Ds(v,d){const g=.5/Math.tan(.5*d);return[v.range[0]+g,v.range[1]+g]}function Cs(v,d,g,w,A){const I=s.ah([],[d,g,w],A.mercatorFogMatrix);return Ci(v,s.ai(I),A.pitch,A._fov)}function gs(v,d,g,w,A,I,L){const F=[[g,w,0],[A,w,0],[A,I,0],[g,I,0]];let $=Number.MAX_VALUE,H=-Number.MAX_VALUE;for(const Y of F){const te=s.ah([],Y,d),ee=s.ai(te);$=Math.min($,ee),H=Math.max(H,ee)}return[Ci(v,$,L.pitch,L._fov),Ci(v,H,L.pitch,L._fov)]}const yi=s.a8.fog;class is extends s.E{constructor(d,g,w,A){super();const I=new s.ab({range:new s.ac(yi.range),color:new s.ac(yi.color),"color-use-theme":new s.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new s.ac(yi["high-color"]),"high-color-use-theme":new s.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new s.ac(yi["space-color"]),"space-color-use-theme":new s.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new s.ac(yi["horizon-blend"]),"star-intensity":new s.ac(yi["star-intensity"]),"vertical-range":new s.ac(yi["vertical-range"])});this._transitionable=new s.aa(I,w,new Map(A)),this.set(d,A),this._transitioning=this._transitionable.untransitioned(),this._transform=g,this.properties=new s.ak(I),this.scope=w}get state(){const d=this._transform,g=d.projection.name==="globe",w=s.al(d.zoom),A=this.properties.get("range"),I=[.5,3];return{range:g?[s.am(I[0],A[0],w),s.am(I[1],A[1],w)]:A,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(d,g,w={}){if(this._validate(Me,d,w))return;const A=Object.assign({},d);for(const I of Object.keys(yi))A[I]===void 0&&(A[I]=yi[I].default);this._options=A,this._transitionable.setTransitionOrValue(this._options,g)}getOpacity(d){if(!this._transform.projection.supportsFog)return 0;const g=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:s.aj(45,65,d))*g.a}getOpacityAtLatLng(d,g){return this._transform.projection.supportsFog?function(w,A,I){const L=s.ag.fromLngLat(A),F=I.elevation?I.elevation.getAtPointOrZero(L):0;return Cs(w,L.x,L.y,F,I)}(this.state,d,g):0}getOpacityForTile(d){if(!this._transform.projection.supportsFog)return[1,1];const g=this._transform.calculateFogTileMatrix(d.toUnwrapped());return gs(this.state,g,0,0,s.an,s.an,this._transform)}getOpacityForBounds(d,g,w,A,I){return this._transform.projection.supportsFog?gs(this.state,d,g,w,A,I,this._transform):[1,1]}getFovAdjustedRange(d){return this._transform.projection.supportsFog?Ds(this.state,d):[0,1]}isVisibleOnFrustum(d){if(!this._transform.projection.supportsFog)return!1;const g=[4,5,6,7];for(const w of g){const A=d.points[w];let I;if(A[2]>=0)I=A;else{const L=d.points[w-4];I=s.ao(L,A,L[2]/(L[2]-A[2]))}if(Cs(this.state,I[0],I[1],0,this._transform)>=Rn)return!0}return!1}updateConfig(d){this._transitionable.setTransitionOrValue(this._options,new Map(d))}updateTransitions(d){this._transitioning=this._transitionable.transitioned(d,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(d){this.properties=this._transitioning.possiblyEvaluate(d)}_validate(d,g,w){return(!w||w.validate!==!1)&&fr(this,d.call(tu,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:s.a8})))}}let sa,ji,ss,ys=class extends s.E{constructor(v,d,g,w){super();const A=sa||(sa=new s.ab({density:new s.ac(s.a8.snow.density),intensity:new s.ac(s.a8.snow.intensity),color:new s.ac(s.a8.snow.color),opacity:new s.ac(s.a8.snow.opacity),vignette:new s.ac(s.a8.snow.vignette),"vignette-color":new s.ac(s.a8.snow["vignette-color"]),"center-thinning":new s.ac(s.a8.snow["center-thinning"]),direction:new s.ac(s.a8.snow.direction),"flake-size":new s.ac(s.a8.snow["flake-size"])}));this._transitionable=new s.aa(A,g,new Map(w)),this.set(v,w),this._transitioning=this._transitionable.untransitioned(),this.properties=new s.ak(A),this.scope=g}get state(){const v=this.properties.get("opacity"),d=this.properties.get("color"),g=this.properties.get("direction"),w=s.ap(g[0]),A=-Math.max(s.ap(g[1]),.01),I=[Math.cos(w)*Math.cos(A),Math.sin(w)*Math.cos(A),Math.sin(A)],L=this.properties.get("vignette"),F=this.properties.get("vignette-color");return F.a=L,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new s.aq(d.r,d.g,d.b,d.a*v),direction:I,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:F}}get(){return this._transitionable.serialize()}set(v,d,g={}){if(this._validate(Ye,v,g))return;const w=Object.assign({},v),A=s.a8.snow;for(const I of Object.keys(A))w[I]===void 0&&(w[I]=A[I].default);this._options=w,this._transitionable.setTransitionOrValue(this._options,d)}updateConfig(v){this._transitionable.setTransitionOrValue(this._options,new Map(v))}updateTransitions(v){this._transitioning=this._transitionable.transitioned(v,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(v){this.properties=this._transitioning.possiblyEvaluate(v)}_validate(v,d,g){return(!g||g.validate!==!1)&&fr(this,v.call(tu,Object.assign({value:d,style:{glyphs:!0,sprite:!0},styleSpec:s.a8})))}},Dn=class extends s.E{constructor(v,d,g,w){super();const A=ji||(ji=new s.ab({density:new s.ac(s.a8.rain.density),intensity:new s.ac(s.a8.rain.intensity),color:new s.ac(s.a8.rain.color),opacity:new s.ac(s.a8.rain.opacity),vignette:new s.ac(s.a8.rain.vignette),"vignette-color":new s.ac(s.a8.rain["vignette-color"]),"center-thinning":new s.ac(s.a8.rain["center-thinning"]),direction:new s.ac(s.a8.rain.direction),"droplet-size":new s.ac(s.a8.rain["droplet-size"]),"distortion-strength":new s.ac(s.a8.rain["distortion-strength"])}));this._transitionable=new s.aa(A,g,new Map(w)),this.set(v,w),this._transitioning=this._transitionable.untransitioned(),this.properties=new s.ak(A),this.scope=g}get state(){const v=this.properties.get("opacity"),d=this.properties.get("color"),g=this.properties.get("direction"),w=s.ap(g[0]),A=-Math.max(s.ap(g[1]),.01),I=[Math.cos(w)*Math.cos(A),Math.sin(w)*Math.cos(A),Math.sin(A)],L=this.properties.get("vignette-color");return L.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new s.aq(d.r,d.g,d.b,d.a*v),direction:I,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:L}}get(){return this._transitionable.serialize()}set(v,d,g={}){if(this._validate(Je,v,g))return;const w=Object.assign({},v),A=s.a8.rain;for(const I of Object.keys(A))w[I]===void 0&&(w[I]=A[I].default);this._options=w,this._transitionable.setTransitionOrValue(this._options,d)}updateConfig(v){this._transitionable.setTransitionOrValue(this._options,new Map(v))}updateTransitions(v){this._transitioning=this._transitionable.transitioned(v,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(v){this.properties=this._transitioning.possiblyEvaluate(v)}_validate(v,d,g){return(!g||g.validate!==!1)&&fr(this,v.call(tu,Object.assign({value:d,style:{glyphs:!0,sprite:!0},styleSpec:s.a8})))}};class _a extends s.E{constructor(d,g,w,A){super(),this.scope=w,this._options=d,this.properties=new s.ak(g),this._transitionable=new s.aa(g,w,new Map(A)),this._transitionable.setTransitionOrValue(d.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(d){this._transitionable.setTransitionOrValue(this._options.properties,new Map(d))}updateTransitions(d){this._transitioning=this._transitionable.transitioned(d,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(d){this.properties=this._transitioning.possiblyEvaluate(d)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(d,g){this._options=d,this._transitionable.setTransitionOrValue(d.properties,g)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const yo=()=>ss||(ss=new s.ab({color:new s.ac(s.a8.properties_light_ambient.color),"color-use-theme":new s.ac({type:"string",default:"default","property-type":"data-constant"}),intensity:new s.ac(s.a8.properties_light_ambient.intensity)}));let oo;const Jl=()=>oo||(oo=new s.ab({direction:new s.ar(s.a8.properties_light_directional.direction),color:new s.ac(s.a8.properties_light_directional.color),"color-use-theme":new s.ac({type:"string",default:"default","property-type":"data-constant"}),intensity:new s.ac(s.a8.properties_light_directional.intensity),"cast-shadows":new s.ac(s.a8.properties_light_directional["cast-shadows"]),"shadow-quality":new s.ac(s.a8.properties_light_directional["shadow-quality"]),"shadow-intensity":new s.ac(s.a8.properties_light_directional["shadow-intensity"]),"shadow-draw-before-layer":new s.ac(s.a8.properties_light_directional["shadow-draw-before-layer"])}));class ec{constructor(d,g,w){this.screenBounds=d,this.cameraPoint=w.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=g,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,w)}static createFromScreenPoints(d,g){let w,A;if(d instanceof s.P||typeof d[0]=="number"){const I=s.P.convert(d);w=[I],A=g.isPointAboveHorizon(I)}else{const I=s.P.convert(d[0]),L=s.P.convert(d[1]),F=I.add(L)._div(2);w=[I,L],A=s.as(I,L).every($=>g.isPointAboveHorizon($))&&g.isPointAboveHorizon(F)}return new ec(w,A,g)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(d){return s.as(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],d)}bufferedCameraGeometry(d){const g=this.screenBounds[0],w=this.screenBounds.length===1?this.screenBounds[0].add(new s.P(1,1)):this.screenBounds[1],A=s.as(g,w,0,!1);return this.cameraPoint.y>w.y&&(this.cameraPoint.x>g.x&&this.cameraPoint.x=w.x?A[2]=this.cameraPoint:this.cameraPoint.x<=g.x&&(A[3]=this.cameraPoint)),s.at(A,d)}bufferedCameraGeometryGlobe(d){const g=this.screenBounds[0],w=this.screenBounds.length===1?this.screenBounds[0].add(new s.P(1,1)):this.screenBounds[1],A=s.as(g,w,d),I=this.cameraPoint.clone(),L=+(I.x>g.x)+ +(I.x>w.x);switch(3*(+(I.y>g.y)+ +(I.y>w.y))+L){case 0:A[0]=I,A[4]=I.clone();break;case 1:A.splice(1,0,I);break;case 2:A[1]=I;break;case 3:A.splice(4,0,I);break;case 5:A.splice(2,0,I);break;case 6:A[3]=I;break;case 7:A.splice(3,0,I);break;case 8:A[2]=I}return A}containsTile(d,g,w,A=0){const I=Math.max(d.queryPadding,d.evaluateQueryRenderedFeaturePadding())/g._pixelsPerMercatorPixel+1,L=w?this._bufferedCameraMercator(I,g):this._bufferedScreenMercator(I,g);let F=d.tileID.wrap+(L.unwrapped?A:0);const $=L.polygon.map(me=>s.au(d.tileTransform,me,F));if(!s.av($,0,0,s.an,s.an))return;F=d.tileID.wrap+(this.screenGeometryMercator.unwrapped?A:0);const H=this.screenGeometryMercator.polygon.map(me=>s.aw(d.tileTransform,me,F)),Y=H.map(me=>new s.P(me[0],me[1])),te=g.getFreeCameraOptions().position||new s.ag(0,0,0),ee=s.aw(d.tileTransform,te,F),ie=H.map(me=>{const pe=s.ax(me,me,ee);return s.ay(pe,pe),new s.az(ee,pe)}),le=s.aA(d,1,g.zoom)*g._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Y,tilespaceRays:ie,bufferedTilespaceGeometry:$,bufferedTilespaceBounds:(oe=s.aB($),oe.min.x=s.aC(oe.min.x,0,s.an),oe.min.y=s.aC(oe.min.y,0,s.an),oe.max.x=s.aC(oe.max.x,0,s.an),oe.max.y=s.aC(oe.max.y,0,s.an),oe),tile:d,tileID:d.tileID,pixelToTileUnitsFactor:le};var oe}_bufferedScreenMercator(d,g){const w=tc(d);if(this._screenRaycastCache[w])return this._screenRaycastCache[w];{let A;return A=g.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(d),g):{polygon:this.bufferedScreenGeometry(d).map(I=>g.pointCoordinate3D(I)),unwrapped:!0},this._screenRaycastCache[w]=A,A}}_bufferedCameraMercator(d,g){const w=tc(d);if(this._cameraRaycastCache[w])return this._cameraRaycastCache[w];{let A;return A=g.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(d),g):{polygon:this.bufferedCameraGeometry(d).map(I=>g.pointCoordinate3D(I)),unwrapped:!0},this._cameraRaycastCache[w]=A,A}}_projectAndResample(d,g){const w=function(I,L){const F=s.aD([],L.pixelMatrix,L.globeMatrix),$=[0,-s.aF,0,1],H=[0,s.aF,0,1],Y=[0,0,0,1];s.aE($,$,F),s.aE(H,H,F),s.aE(Y,Y,F);const te=new s.P($[0]/$[3],$[1]/$[3]),ee=new s.P(H[0]/H[3],H[1]/H[3]),ie=s.aG(I,te)&&$[3]1?fd(I.slice(0,me),L):[],Re=menew s.P(pl(Ke.x),Ke.y)),Re=Re.map(Ke=>new s.P(pl(Ke.x),Ke.y));const xe=[...je];xe.length===0&&xe.push(Re[Re.length-1]);const Ze=s.am(xe[xe.length-1].y,(Re.length===0?je[0]:Re[0]).y,pe);let ze;return ze=ie?[new s.P(0,Ze),new s.P(0,0),new s.P(1,0),new s.P(1,Ze)]:[new s.P(1,Ze),new s.P(1,1),new s.P(0,1),new s.P(0,Ze)],xe.push(...ze),Re.length===0?xe.push(je[0]):xe.push(...Re),{polygon:xe.map(Ke=>new s.ag(Ke.x,Ke.y)),unwrapped:!1}}(d,g);if(w)return w;const A=function(I,L){let F=!1,$=-1/0,H=0;for(let te=0;te$&&($=I[te].x,H=te);for(let te=0;te.5&&(ie.x{te.x-=1}),{polygon:I,unwrapped:F}}(fd(d,g).map(I=>new s.P(pl(I.x),I.y)),g);return{polygon:A.polygon.map(I=>new s.ag(I.x,I.y)),unwrapped:A.unwrapped}}}function fd(v,d){return s.aI(v,g=>{const w=d.pointCoordinate3D(g);g.x=w.x,g.y=w.y},1/256)}function pl(v){return v<0?1+v%1:v%1}function tc(v){return 100*v|0}function pd(v,d,g){try{d=function(A){if(!A.variants)return A;if(!Array.isArray(A.variants))throw new Error("variants must be an array");for(const I of A.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");if(I.capabilities.length===1&&I.capabilities[0]==="meshopt")return Object.assign(A,I)}return A}(d)}catch(A){return new Error("Failed to process TileJSON variants",{cause:A})}const w=s.aJ(Object.assign({},d,v),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return v.url&&d.tiles&&v.tiles&&(w.tiles=d.tiles),w.tiles=g.canonicalizeTileset(w,v.url),w}function vc(v,d,g,w,A){const I=function(F,$){if(F)return A(F);if($){v.url&&$.tiles&&v.tiles&&delete v.tiles;const H=pd(v,$,d);if(H instanceof Error)return A(H);A(null,H)}},L=function(F,$,H){if(!F)return null;if(!$&&!H)return F;H=H||F.worldview_default;const Y=Object.values(F.language||{});if(Y.length===0)return null;const te=Object.values(F.worldview||{});if(te.length===0)return null;const ee=Y.every(le=>le===$),ie=te.every(le=>le===H);return ee&&ie?F:$ in(F.language_options||{})||H in(F.worldview_options||{})?null:F.language_options&&F.worldview_options?F:null}(v.data,g,w);return L?s.o.frame(()=>I(null,L)):v.url?s.m(d.transformRequest(d.normalizeSourceURL(v.url,null,g,w),s.R.Source),I):s.o.frame(()=>{const{data:F,...$}=v;I(null,$)})}function md(v,d){const g=Math.pow(2,d.z),w=Math.floor(s.aH(v.getWest())*g),A=Math.floor(s.aL(v.getNorth())*g),I=Math.ceil(s.aH(v.getEast())*g),L=Math.ceil(s.aL(v.getSouth())*g);return d.x>=w&&d.x=A&&d.ythis.maxzoom||d.z{this._tileJSONRequest=null,this._loaded=!0,L?(g&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${g}`),w&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${w}`),this.fire(new s.B(L))):F&&(this._setTileJSON(F),rt(F.tiles,this.map._requestManager._customAccessToken),this.fire(new s.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new s.C("data",{dataType:"source",sourceDataType:"content"}))),d&&d(L)};this.provider=this._options.provider;const I=function(L){if("provider"in L&&!L.provider)return null;let F=L.provider;if(!F&&"url"in L&&L.url&&(F=s.aM(L.url)),!F)return null;const $=s.g.TILE_PROVIDER_URLS[F];if(!$)return null;let H;try{H=new URL($,s.g.API_URL).href}catch{return s.w(`TileProvider "${F}" has an invalid URL: "${$}"`),null}return{name:F,url:H}}(this._options);if(this.provider&&!I)return this._loaded=!0,this.fire(new s.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(d&&d());this._tileJSONRequest=I?this._loadWithProvider(I,A):vc(this._options,this.map._requestManager,g,w,A)}_loadWithProvider(d,g){this.provider=d.name;const w=new AbortController,A=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,s.R.Source):void 0,I=A?Object.assign({},this._options,{url:A.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:d.name,url:d.url,source:this.id,scope:this.scope,type:this.type,options:I,request:A},(L,F)=>{if(w.signal.aborted)return;if(L)return void g(L);const $=F?F.find(H=>H!=null):null;if($){const H=pd(this._options,$,this.map._requestManager);H instanceof Error?g(H):g(null,H)}else g(null,{tiles:this._options.tiles})}),{cancel:()=>{w.abort()}}}_setTileJSON(d){if(Object.assign(this,d),this.hasWorldviews=!!d.worldview_options,d.worldview_default&&(this.worldviewDefault=d.worldview_default),d.vector_layers){this.vectorLayers=d.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const g of d.vector_layers)this.vectorLayerIds.push(g.id),d.worldview&&d.worldview[g.source]&&this.localizableLayerIds.add(g.id)}this.tileBounds=ru.fromTileJSON(d)}loaded(){return this._loaded}hasTile(d){return!this.tileBounds||this.tileBounds.contains(d.canonical)}onAdd(d){this.map=d,this.load()}reload(){this.cancelTileJSONRequest();const d=s.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(d))}setTiles(d){return this._options.tiles=d,this.reload(),this}setUrl(d){return this.url=d,this._options.url=d,this.reload(),this}onRemove(d){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(d,g){const w=d.tileID.canonical.url(this.tiles,this.scheme),A=this.map._requestManager.normalizeTileURL(w),I=this.map._requestManager.transformRequest(A,s.R.Tile),L=this.map.style?this.map.style.getLut(this.scope):null,F=L?{image:L.image.clone()}:null,$={request:I,data:void 0,uid:d.uid,tileID:d.tileID,tileZoom:d.tileZoom,zoom:d.tileID.overscaledZ,maxZoom:this.maxzoom,lut:F,tileSize:this.tileSize*d.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:s.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,renderSourceType:d.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:d.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&&s.e(w)&&($.localizableLayerIds=this.localizableLayerIds),$.request.collectResourceTiming=this._collectResourceTiming,d.actor&&d.state!=="expired")d.state==="loading"?d.reloadCallback=g:d.request=d.actor.send("reloadTile",$,H.bind(this));else if(d.actor=this._tileWorkers[A]=this._tileWorkers[A]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)d.request=d.actor.send("loadTile",$,H.bind(this),void 0,!0);else{const Y=s.aO.call({deduped:this._deduped},$,(te,ee)=>{if(te||!ee)H.call(this,te);else{const ie=s.aP(ee.responseHeaders);$.data={rawData:ee.rawData.slice(0),expires:ie.expires,cacheControl:ie.cacheControl},d.actor&&d.actor.send("loadTile",$,H.bind(this),void 0,!0)}},!0);d.request={cancel:Y}}function H(Y,te){return delete d.request,d.aborted?g(null):Y?g(Y):(te&&te.resourceTiming&&(d.resourceTiming=te.resourceTiming),this.map._refreshExpiredTiles&&te&&d.setExpiryData(te),d.loadVectorData(te,this.map.painter),s.aQ(this.dispatcher),g(null,te),void(d.reloadCallback&&(this.loadTile(d,d.reloadCallback),d.reloadCallback=null)))}}abortTile(d){d.request&&(d.request.cancel(),delete d.request),d.actor&&d.actor.send("abortTile",{uid:d.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(d,g){d.actor&&d.actor.send("removeTile",{uid:d.uid,type:this.type,source:this.id,scope:this.scope}),d.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class xx extends s.E{constructor(d,g,w,A){super(),this.id=d,this.dispatcher=w,this.setEventedParent(A),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=Object.assign({type:"raster"},g),Object.assign(this,s.aJ(g,["url","scheme","tileSize"]))}load(d){this._loaded=!1,this.fire(new s.C("dataloading",{dataType:"source"}));const g=this.map.getWorldview();this._tileJSONRequest=vc(this._options,this.map._requestManager,null,g,(w,A)=>{this._tileJSONRequest=null,this._loaded=!0,w?this.fire(new s.B(w)):A&&(Object.assign(this,A),A.raster_layers&&(this.rasterLayers=A.raster_layers,this.rasterLayerIds=this.rasterLayers.map(I=>I.id)),this.tileBounds=ru.fromTileJSON(A),rt(A.tiles),this.fire(new s.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new s.C("data",{dataType:"source",sourceDataType:"content"}))),d&&d(w)})}loaded(){return this._loaded}onAdd(d){this.map=d,this.load()}reload(){this.cancelTileJSONRequest();const d=s.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(d))}setTiles(d){return this._options.tiles=d,this.reload(),this}setUrl(d){return this.url=d,this._options.url=d,this.reload(),this}onRemove(d){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(d){return!this.tileBounds||this.tileBounds.contains(d.canonical)}loadTile(d,g){const w=s.o.devicePixelRatio>=2,A=this.map._requestManager.normalizeTileURL(d.tileID.canonical.url(this.tiles,this.scheme),w,this.tileSize);d.request=s.n(this.map._requestManager.transformRequest(A,s.R.Tile),(I,L,F)=>{if(delete d.request,d.aborted)return d.state="unloaded",g(null);if(I)return d.state="errored",g(I);if(!L)return g(null);const $=s.aP(F);this.map._refreshExpiredTiles&&d.setExpiryData($),d.setTexture(L,this.map.painter),d.state="loaded",s.aQ(this.dispatcher),g(null)})}abortTile(d,g){d.request&&(d.request.cancel(),delete d.request),g&&g()}unloadTile(d,g){d.texture&&d.texture instanceof s.T?(d.destroy(!1),d.texture&&d.texture instanceof s.T&&this.map.painter.saveTileTexture(d.texture)):d.destroy(),g&&g()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function HS([v,d],g,w,{scaled:A=!0}={}){const{tileSize:I,buffer:L}=w,{x:F,y:$,z:H}=g;if(!isFinite(F)||!isFinite($)||!isFinite(H))throw new Error("Invalid MRT header");const Y=2**H,te=Y*s.aH(v),ee=Y*s.aL(d);return function([ie,le],oe,{scaled:me=!0}={}){if(!oe)throw new Error("bandView is undefined");const{data:pe,tileSize:je,buffer:Re,offset:xe,scale:Ze,dimension:ze}=oe;if(ie<-Re||ie>je+Re||le<-Re||le>je+Re)throw new Error(`Point (${ie}, ${le}) out of bounds for tileSize=${je}, buffer=${Re}`);const Ke=(le+Re)*(je+2*Re)+(ie+Re);if(new Uint32Array(pe.buffer)[Ke]===4294967295)return null;let De=[];De=me?[]:new oe.data.constructor(ze);for(let Fe=0;Fe{if(delete d.request,d.aborted)return d.state="unloaded",g(null);if(F)return F.name==="AbortError"?void 0:(d.state="errored",g(F));if(this.map._refreshExpiredTiles&&$){const Y=s.aP(H);d.setExpiryData(Y)}if(this.partial&&d.state!=="expired")d.state="empty";else if(!this.partial){if(!$)return g(null);d.state="loaded",d._isHeaderLoaded=!0,d._mrt=$}g(null)};d.request=this.partial?d.fetchHeader(void 0,L.bind(this)):d.actor.send("loadTile",I,L.bind(this),void 0,!0)}abortTile(d){d.request&&(d.request.cancel(),delete d.request),d.actor&&d.actor.send("abortTile",{uid:d.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(d,g){const w=d.texturePerLayer;if(d.flushAllQueues(),w.size){d.destroy(!1);for(const A of w.values())this.map.painter.saveTileTexture(A)}else d.destroy()}prepareTile(d,g,w,A){d._isHeaderLoaded&&(d.state!=="empty"&&(d.state="reloading"),d.fetchBandForRender(g,w,A,(I,L)=>{I?(d.state="errored",this.fire(new s.B(I))):L&&(d._isHeaderLoaded=!0,d.setTexturePerLayer(w,L,this.map.painter),d.state="loaded"),this.triggerRepaint(d)}))}getInitialBand(d){if(!this.rasterLayers)return 0;const g=this.rasterLayers.find(({id:I})=>I===d),w=g&&g.fields,A=w&&w.bands&&w.bands;return A?A[0]:0}getTextureDescriptor(d,g,w){if(!d)return;const A=g.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!A)return;let I=null;g instanceof s.aS?I=g.paint.get("raster-array-band"):g instanceof s.aT&&(I=g.paint.get("raster-particle-array-band"));const L=I||this.getInitialBand(A);if(L==null)return;if(!d.textureDescriptorPerLayer.get(g.id))return void this.prepareTile(d,A,g.id,L);if(d.updateNeeded(g.id,L)&&!w)return;const F=d.textureDescriptorPerLayer.get(g.id);return Object.assign({},F,{texture:d.texturePerLayer.get(g.id)})}getImages(d,g){const w=new Map;for(const A of d)for(const I of g){const[L,F]=I.split("/"),$=A.getLayer(L);if(!$||!$.hasBand(F)||!$.hasDataForBand(F))continue;const{bytes:H,tileSize:Y,buffer:te}=$.getBandView(F),ee=Y+2*te,ie={data:new s.q({width:ee,height:ee},H),pixelRatio:2,sdf:!1,usvg:!1,version:0};w.set(I,ie)}return w}queryRasterArrayValueByBandId(d,g,w){const A=g._mrt;return new Promise(I=>{const L={},F=new Set;for(const[$,H]of Object.entries(A.layers)){if(w.layerName&&$!==w.layerName)continue;const Y={};L[$]=Y;for(const{bands:te}of H.dataIndex)for(const ee of te)w.bands&&!w.bands.includes(ee)||(F.add(s.F($,ee)),g.fetchBand($,null,ee,ie=>{s.o.frame(()=>{Y[ee]=ie?null:HS([d.lng,d.lat],A,H.getBandView(ee)),F.delete(s.F($,ee)),F.size===0&&I(L)})},!1))}F.size===0&&I(L)})}_loadTileForQuery(d,g){if(this._loadTileLoaded[d.uid])return void g(null,d._mrt);if(this._loadTilePending[d.uid])return void this._loadTilePending[d.uid].push(g);this._loadTilePending[d.uid]=[g];const w=this.map._requestManager.normalizeTileURL(d.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),A=this.map._requestManager.transformRequest(w,s.R.Tile);d.actor.send("loadTile",{request:A,uid:d.uid,tileID:d.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(I,L,F)=>{if(I)return this._loadTilePending[d.uid].forEach($=>$(I,null)),void delete this._loadTilePending[d.uid];if(!L)return this._loadTilePending[d.uid].forEach($=>$(null,null)),void delete this._loadTilePending[d.uid];if(this.map._refreshExpiredTiles&&L){const $=s.aP(F);d.setExpiryData($)}d._mrt=L,d._isHeaderLoaded=!0,d.state="loaded",this._loadTilePending[d.uid].forEach($=>$(null,L)),this._loadTileLoaded[d.uid]=!0,delete this._loadTilePending[d.uid]},void 0,!0)}queryRasterArrayValueByAllBands(d,g,w){return new Promise((A,I)=>{this._loadTileForQuery(g,(L,F)=>{L?I(L):A(F?this.queryRasterArrayValueByBandId(d,g,w):null)})})}queryRasterArrayValue(d,g){const w=s.aU.convert(d),A=this.findLoadedParent(w);return A&&A._mrt?g.bands||!this.partial?this.queryRasterArrayValueByBandId(w,A,g):this.queryRasterArrayValueByAllBands(w,A,g):Promise.resolve(null)}findLoadedParent(d){const g=s.ag.fromLngLat(d,this.map.transform.tileSize),w=this.maxzoom+1,A=1<0&&(F[new s.aR(v.overscaledZ,A,d.z,w,d.y-1).key]={backfilled:!1},F[new s.aR(v.overscaledZ,v.wrap,d.z,d.x,d.y-1).key]={backfilled:!1},F[new s.aR(v.overscaledZ,L,d.z,I,d.y-1).key]={backfilled:!1}),d.y+1{if(this._loaded=!0,this._pendingLoad=null,w)this.fire(new s.B(w));else{const I={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&A&&A.resourceTiming&&A.resourceTiming[this.id]&&(I.resourceTiming=A.resourceTiming[this.id]),v&&(this._partialReload=!0),this.fire(new s.C("data",I)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(v),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const v=s.F(this.id,this.scope);this.map.style.clearSource(v),this._updateWorkerData()}loadTile(v,d){const g=v.actor?"reloadTile":"loadTile";v.actor=this.actor;const w=this.map.style?this.map.style.getLut(this.scope):null,A=w?{image:w.image.clone()}:null,I=this._partialReload,L={type:this.type,uid:v.uid,tileID:v.tileID,tileZoom:v.tileZoom,zoom:v.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:A,scope:this.scope,pixelRatio:s.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:v.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:I,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};v.request=this.actor.send(g,L,(F,$)=>I&&!$?(v.state="loaded",d(null)):(delete v.request,v.destroy(!1),v.aborted?d(null):F?d(F):(v.loadVectorData($,this.map.painter,g==="reloadTile"),d(null))),void 0,g==="loadTile")}abortTile(v){v.request&&(v.request.cancel(),delete v.request),v.aborted=!0}unloadTile(v,d){this.actor.send("removeTile",{uid:v.uid,type:this.type,source:this.id,scope:this.scope}),v.destroy()}onRemove(v){this._pendingLoad&&this._pendingLoad.cancel()}serialize(){return Object.assign({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}},video:class extends s.aV{constructor(v,d,g,w){super(v,d,g,w),this.roundZoom=!0,this.type="video",this.options=d}load(){this._loaded=!1;const v=this.options;this.urls=[];for(const d of v.urls)this.urls.push(this.map._requestManager.transformRequest(d,s.R.Source).url);s.aW(this.urls,(d,g)=>{this._loaded=!0,d?this.fire(new s.B(d)):g&&(this.video=g,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading())})}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(v){if(this.video){const d=this.video.seekable;vd.end(0)?this.fire(new s.B(new s.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${d.start(0)} and ${d.end(0)}-second mark.`))):this.video.currentTime=v}}getVideo(){return this.video}onAdd(v){this.map||(this.map=v,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 v=this.map.painter.context,d=v.gl;this.texture?this.video.paused||(this.texture.bind(d.LINEAR,d.CLAMP_TO_EDGE),d.texSubImage2D(d.TEXTURE_2D,0,0,0,d.RGBA,d.UNSIGNED_BYTE,this.video)):(this.texture=new s.T(v,this.video,d.RGBA8),this.texture.bind(d.LINEAR,d.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(v)}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:s.aV,model:s.aY,"batched-model":class extends s.E{constructor(v,d,g,w){super(),this.type="batched-model",this.id=v,this.tileSize=512,this._options=d,this.tiles=this._options.tiles,this.maxzoom=d.maxzoom||19,this.minzoom=d.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=g,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(w)}onAdd(v){this.map=v,this.load()}reload(){this.cancelTileJSONRequest();const v=s.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(v))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(v){this._loaded=!1,this.fire(new s.C("dataloading",{dataType:"source"}));const d=Array.isArray(this.map._language)?this.map._language.join():this.map._language,g=this.map.getWorldview();this._tileJSONRequest=vc(this._options,this.map._requestManager,d,g,(w,A)=>{this._tileJSONRequest=null,this._loaded=!0,w?(d&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${d}`),g&&g.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${g}`),this.fire(new s.B(w))):A&&(Object.assign(this,A),A.bounds&&(this.tileBounds=new ru(A.bounds,this.minzoom,this.maxzoom)),rt(A.tiles,this.map._requestManager._customAccessToken),this.fire(new s.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new s.C("data",{dataType:"source",sourceDataType:"content"}))),v&&v(w)})}hasTransition(){return!1}hasTile(v){return!this.tileBounds||this.tileBounds.contains(v.canonical)}loaded(){return this._loaded}loadTile(v,d){const g=this.map._requestManager.normalizeTileURL(v.tileID.canonical.url(this.tiles,this.scheme)),w={request:this.map._requestManager.transformRequest(g,s.R.Tile),data:void 0,uid:v.uid,tileID:v.tileID,tileZoom:v.tileZoom,zoom:v.tileID.overscaledZ,tileSize:this.tileSize*v.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:v.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:s.o.devicePixelRatio,promoteId:this.promoteId};if(v.actor&&v.state!=="expired")if(v.state==="loading")v.reloadCallback=d;else{if(v.buckets){const I=Object.values(v.buckets);for(const L of I)L.dirty=!0;return void(v.state="loaded")}v.request=v.actor.send("reloadTile",w,A.bind(this))}else v.actor=this.dispatcher.getActor(),v.request=v.actor.send("loadTile",w,A.bind(this),void 0,!0);function A(I,L){return v.aborted?d(null):I&&I.status!==404?d(I):(this.map._refreshExpiredTiles&&L&&v.setExpiryData(L),v.loadModelData(L,this.map.painter),v.state="loaded",void d(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends s.aV{constructor(v,d,g,w){super(v,d,g,w),d.coordinates?Array.isArray(d.coordinates)&&d.coordinates.length===4&&!d.coordinates.some(A=>!Array.isArray(A)||A.length!==2||A.some(I=>typeof I!="number"))||this.fire(new s.B(new s.V(`sources.${v}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new s.B(new s.V(`sources.${v}`,null,'missing required property "coordinates"'))),d.animate&&typeof d.animate!="boolean"&&this.fire(new s.B(new s.V(`sources.${v}`,null,'optional "animate" property must be a boolean value'))),d.canvas?typeof d.canvas=="string"||d.canvas instanceof HTMLCanvasElement||this.fire(new s.B(new s.V(`sources.${v}`,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 s.B(new s.V(`sources.${v}`,null,'missing required property "canvas"'))),this.options=d,this.animate=d.animate===void 0||d.animate}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 s.B(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(v){this.map=v,this.load(),this.canvas&&this.animate&&this.play()}onRemove(v){this.pause()}prepare(){let v=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,v=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,v=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const d=this.map.painter.context;this.texture?!v&&!this._playing||this.texture instanceof s.aX||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new s.T(d,this.canvas,d.gl.RGBA8,{premultiply:!0}),this._prepareData(d)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const v of[this.canvas.width,this.canvas.height])if(isNaN(v)||v<=0)return!0;return!1}},custom:class extends s.E{constructor(v,d,g,w){super(),this.id=v,this.type="custom",this._dataType="raster",this._dispatcher=g,this._implementation=d,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 s.B(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new s.B(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new ru(this._implementation.bounds,this.minzoom,this.maxzoom));const A=d;A.update=this._update.bind(this),A.clearTiles=this._clearTiles.bind(this),A.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,s.aJ(d,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return s.aJ(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new s.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new s.C("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(v){this.map=v,this._loaded=!1,this.fire(new s.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(v),this.load()}onRemove(v){this._implementation.onRemove&&this._implementation.onRemove(v)}hasTile(v){if(this._implementation.hasTile){const{x:d,y:g,z:w}=v.canonical;return this._implementation.hasTile({x:d,y:g,z:w})}return!this.tileBounds||this.tileBounds.contains(v.canonical)}loadTile(v,d){const{x:g,y:w,z:A}=v.tileID.canonical,I=new AbortController,L=Promise.resolve(this._implementation.loadTile({x:g,y:w,z:A},{signal:I.signal})).then((function(F){return delete v.request,v.aborted?(v.state="unloaded",d(null)):F===void 0?(v.state="errored",d(null)):F===null?(this.loadTileData(v,{width:this.tileSize,height:this.tileSize,data:null}),v.state="loaded",d(null)):function($){return $ instanceof ImageData||$ instanceof HTMLCanvasElement||$ instanceof ImageBitmap||$ instanceof HTMLImageElement}(F)?(this.loadTileData(v,F),v.state="loaded",void d(null)):(v.state="errored",d(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(F=>{F.name!=="AbortError"&&(v.state="errored",d(F))});L.cancel=()=>I.abort(),v.request=L}loadTileData(v,d){v.setTexture(d,this.map.painter)}unloadTile(v,d){if(v.texture&&v.texture instanceof s.T?(v.destroy(!1),v.texture&&v.texture instanceof s.T&&this.map.painter.saveTileTexture(v.texture)):v.destroy(),this._implementation.unloadTile){const{x:g,y:w,z:A}=v.tileID.canonical;this._implementation.unloadTile({x:g,y:w,z:A})}d&&d()}abortTile(v,d){v.request&&v.request.cancel&&(v.request.cancel(),delete v.request),d&&d()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(v=>({x:v.canonical.x,y:v.canonical.y,z:v.canonical.z}))}_clearTiles(){const v=s.F(this.id,this.scope);this.map.style.clearSource(v)}_update(){this.fire(new s.C("data",{dataType:"source",sourceDataType:"content"}))}}},X0=function(v,d,g,w){const A=new Z0[d.type](v,d,g,w);if(A.id!==v)throw new Error(`Expected Source id to be ${v} instead of ${A.id}`);return s.aZ(["load","abort","unload","serialize","prepare"],A),A};function WS(v,d,g=""){return`${g}:${d.id||""}:${d.layer.id}:${function(w){if("layerId"in w)return`layer:${w.layerId}`;{const{featuresetId:A,importId:I}=w;return`featureset:${A}${I?`:import:${I}`:""}`}}(v.target)}`}function gd(v,d,g,w=""){if(v.uniqueFeatureID){const A=WS(v,d,w);if(g.has(A))return!0;g.add(A)}return!1}function mj(v,d,g,w,A=!1,I=void 0){const L=d.sourceCache.transform,F=d.sourceCache.tilesIn(v,d.has3DLayers,A);F.sort(J0);const $=[];for(const H of F){const Y=H.tile.queryRenderedFeatures(d,H,g,w,L,A,I);Object.keys(Y).length&&$.push({wrappedTileID:H.tile.tileID.wrapped().key,queryResults:Y})}for(const H in d.layers){const Y=d.layers[H];if(Y.styleLayer){const te=Y.styleLayer.queryRenderedFeatures(v,d.sourceCache,w);Object.keys(te).length&&$.push({wrappedTileID:0,queryResults:te})}}return $.length===0?{}:function(H){const Y={},te={};for(const ee of H){const ie=ee.queryResults,le=ee.wrappedTileID,oe=te[le]=te[le]||{};for(const me in ie){const pe=ie[me],je=oe[me]=oe[me]||{},Re=Y[me]=Y[me]||[];for(const xe of pe)je[xe.featureIndex]||(je[xe.featureIndex]=!0,Re.push(xe))}}return Y}($)}function Q0(v,d,g,w,A,I){const L={},F=w.queryRenderedSymbols(v),$=[];for(const H of Object.keys(F).map(Number))$.push(A[H]);$.sort(J0);for(const H of $){const Y=H.featureIndex.lookupSymbolFeatures(F[H.bucketInstanceId],H.bucketIndex,H.sourceLayerIndex,d,g,I);for(const te in Y){const ee=L[te]=L[te]||[],ie=Y[te];ie.sort((le,oe)=>{const me=H.featureSortOrder;if(me){const pe=me.indexOf(le.featureIndex);return me.indexOf(oe.featureIndex)-pe}return oe.featureIndex-le.featureIndex});for(const le of ie)ee.push(le)}}return L}function KS(v,d){const g=v.getRenderableIds().map(I=>v.getTileByID(I)),w=[],A={};for(let I=0;I{if(I)g(I);else try{const $=w.getHeaderLength(L);if($>d)return void(this.request=this.fetchHeader($,g));w.parseHeader(L),this._isHeaderLoaded=!0;let H=0;for(const Y of Object.values(w.layers))H=Math.max(H,Y.dataIndex[Y.dataIndex.length-1].lastByte);L.byteLength>=H&&(this.entireBuffer=L),g(null,this.entireBuffer||L,F)}catch($){g($)}}),this.request}fetchBandForRender(d,g,w,A){this.fetchBand(d,g,w,I=>{if(I)return void A(I);this.updateTextureDescriptor(d,g,w);const L=this.textureDescriptorPerLayer.get(g);A(null,L?L.img:null)})}fetchBand(d,g,w,A,I=!0){const L=this._mrt;if(!this._isHeaderLoaded||!L)return void A(new Error("Tile header is not ready"));const F=this.actor;if(!F)return void A(new Error("Can't fetch tile band without an actor"));let $;const H=s.F(String(w),s.F(this.tileID.key,d));let Y=this._taskQueue.get(H);Y?Y.add(A):(Y=new Set,Y.add(A),this._taskQueue.set(H,Y));const te=(oe,me)=>{$.complete(oe,me),oe?A(oe):(Y.forEach(pe=>pe(null,me)),this._taskQueue.delete(H))},ee=(oe,me)=>{if(oe)return A(oe);const pe=F.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:me,task:$},te,void 0,!0);if(g!==null){const je=this._workQueuePerLayer.get(g)||[];je.push(()=>{pe&&pe.cancel(),$.cancel()}),this._workQueuePerLayer.has(g)||this._workQueuePerLayer.set(g,je)}};let ie;try{ie=L.getLayer(d)}catch(oe){if(this.state==="reloading")return;throw oe}if(!ie)return void A(new Error(`Unknown sourceLayer "${d}"`));if(ie.hasDataForBand(w))return Y.forEach(oe=>oe(null,null)),void this._taskQueue.delete(H);const le=ie.getDataRange([w]);if($=L.createDecodingTask(le),!$||$.tasks.length)if(g!==null&&this.flushQueues(g),this.entireBuffer)ee(null,this.entireBuffer.slice(le.firstByte,le.lastByte+1));else{const oe=Object.assign({},this.requestParams,{headers:{Range:`bytes=${le.firstByte}-${le.lastByte}`}}),me=s.b1(oe,ee);if(g!==null){const pe=this._fetchQueuePerLayer.get(g)||[];pe.push(()=>{me.cancel(),$.cancel()}),this._fetchQueuePerLayer.has(g)||this._fetchQueuePerLayer.set(g,pe)}}}updateNeeded(d,g){return(!this.textureDescriptorPerLayer.get(d)||this.textureDescriptorPerLayer.get(d).band!==g||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(d,g,w){if(!this._mrt)return;const A=this._mrt.getLayer(d);if(!A||!A.hasBand(w)||!A.hasDataForBand(w))return;const{bytes:I,tileSize:L,buffer:F,offset:$,scale:H}=A.getBandView(w),Y=L+2*F,te=new s.q({width:Y,height:Y},I),ee=this.texturePerLayer.get(g);ee&&ee instanceof s.T&&ee.update(te,{premultiply:!1}),this.textureDescriptorPerLayer.set(g,{layer:d,band:w,img:te,buffer:F,offset:$,tileSize:L,format:A.pixelFormat,mix:[H,256*H,65536*H,16777216*H]})}destroy(d=!1){if(super.destroy(d),delete this._mrt,!d)for(const g of this.texturePerLayer.values())g&&g instanceof s.T&&g.destroy();this.texturePerLayer.clear(),this.textureDescriptorPerLayer.clear(),this.fbo&&(this.fbo.destroy(),delete this.fbo),delete this.request,delete this.requestParams,this._isHeaderLoaded=!1}}class Km{constructor(d,g){this.max=d,this.onRemove=g,this.reset()}reset(){for(const d in this.data)for(const g of this.data[d])g.timeout&&clearTimeout(g.timeout),this.onRemove(g.value);return this.data={},this.order=[],this}add(d,g,w){const A=d.wrapped().key;this.data[A]===void 0&&(this.data[A]=[]);const I={value:g,timeout:void 0};if(w!==void 0&&(I.timeout=setTimeout(()=>{this.remove(d,I)},w)),this.data[A].push(I),this.order.push(A),this.order.length>this.max){const L=this._getAndRemoveByKey(this.order[0]);L&&this.onRemove(L)}return this}has(d){return d.wrapped().key in this.data}getAndRemove(d){return this.has(d)?this._getAndRemoveByKey(d.wrapped().key):null}_getAndRemoveByKey(d){const g=this.data[d].shift();return g.timeout&&clearTimeout(g.timeout),this.data[d].length===0&&delete this.data[d],this.order.splice(this.order.indexOf(d),1),g.value}getByKey(d){const g=this.data[d];return g?g[0].value:null}get(d){return this.has(d)?this.data[d.wrapped().key][0].value:null}remove(d,g){if(!this.has(d))return this;const w=d.wrapped().key,A=g===void 0?0:this.data[w].indexOf(g),I=this.data[w][A];return this.data[w].splice(A,1),I.timeout&&clearTimeout(I.timeout),this.data[w].length===0&&delete this.data[w],this.onRemove(I.value),this.order.splice(this.order.indexOf(w),1),this}setMaxSize(d){for(this.max=d;this.order.length>this.max;){const g=this._getAndRemoveByKey(this.order[0]);g&&this.onRemove(g)}return this}filter(d){const g=[];for(const w in this.data)for(const A of this.data[w])d(A.value)||g.push(A);for(const w of g)this.remove(w.value.tileID,w)}}class YS{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(d,g,w){const A=String(g);if(this.stateChanges[d]=this.stateChanges[d]||{},this.stateChanges[d][A]=this.stateChanges[d][A]||{},Object.assign(this.stateChanges[d][A],w),this.deletedStates[d]===null){this.deletedStates[d]={};for(const I in this.state[d])I!==A&&(this.deletedStates[d][I]=null)}else if(this.deletedStates[d]&&this.deletedStates[d][A]===null){this.deletedStates[d][A]={};for(const I in this.state[d][A])w[I]||(this.deletedStates[d][A][I]=null)}else for(const I in w)this.deletedStates[d]&&this.deletedStates[d][A]&&this.deletedStates[d][A][I]===null&&delete this.deletedStates[d][A][I]}removeFeatureState(d,g,w){if(this.deletedStates[d]===null)return;const A=String(g);if(this.deletedStates[d]=this.deletedStates[d]||{},w&&g!==void 0)this.deletedStates[d][A]!==null&&(this.deletedStates[d][A]=this.deletedStates[d][A]||{},this.deletedStates[d][A][w]=null);else if(g!==void 0)if(this.stateChanges[d]&&this.stateChanges[d][A])for(w in this.deletedStates[d][A]={},this.stateChanges[d][A])this.deletedStates[d][A][w]=null;else this.deletedStates[d][A]=null;else this.deletedStates[d]=null}getState(d,g){const w=this.state[d]||{},A=this.stateChanges[d]||{},I=this.deletedStates[d];if(I===null)return{};if(g!==void 0){const F=String(g),$=Object.assign({},w[F],A[F]);if(I){const H=I[g];if(H===null)return{};for(const Y in H)delete $[Y]}return $}const L=Object.assign({},w,A);if(I)for(const F in I)delete L[F];return L}initializeTileState(d,g){d.refreshFeatureState(g)}coalesceChanges(d,g){const w={};for(const A in this.stateChanges){this.state[A]=this.state[A]||{};const I={};for(const L in this.stateChanges[A])this.state[A][L]||(this.state[A][L]={}),Object.assign(this.state[A][L],this.stateChanges[A][L]),I[L]=this.state[A][L];w[A]=I}for(const A in this.deletedStates){this.state[A]=this.state[A]||{};const I={};if(this.deletedStates[A]===null)for(const L in this.state[A])I[L]={},this.state[A][L]={};else for(const L in this.deletedStates[A]){if(this.deletedStates[A][L]===null)this.state[A][L]={};else if(this.state[A][L])for(const F of Object.keys(this.deletedStates[A][L]))delete this.state[A][L][F];I[L]=this.state[A][L]}w[A]=w[A]||{},Object.assign(w[A],I)}if(this.stateChanges={},this.deletedStates={},Object.keys(w).length!==0)for(const A in d)d[A].refreshFeatureState(g,w)}}class nu extends s.E{constructor(d,g,w){super(),this.id=d,this._renderSourceType=w,this._maxzoomOverride=null,g.on("data",A=>{A.dataType==="source"&&A.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&A.dataType==="source"&&A.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),g.on("error",()=>{this._sourceErrored=!0}),this._source=g,this._tiles={},this._cache=new Km(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=g.minTileCacheSize,this._maxTileCacheSize=g.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new YS,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(d){this.map=d,this._minTileCacheSize=this._minTileCacheSize===void 0&&d?d._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&d?d._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const d in this._tiles)if(!this._tiles[d].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const d=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,d&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(d){this._maxzoomOverride=d}_loadTile(d,g){return d.renderSourceType=this._renderSourceType,d.isExtraShadowCaster=this._shadowCasterTiles[d.tileID.key],this._source.loadTile(d,g)}_unloadTile(d){if(this._source.unloadTile)return this._source.unloadTile(d)}_abortTile(d){if(this._source.abortTile)return this._source.abortTile(d)}serialize(){return this._source.serialize()}prepare(d){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const g in this._tiles){const w=this._tiles[g];w.upload(d,this.map?this.map.painter:void 0),w.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(d=>d.tileID).sort(ZS).map(d=>d.key)}getRenderableIds(d,g){const w=[];for(const A in this._tiles)this._isIdRenderable(+A,d,g)&&w.push(this._tiles[A]);return d?w.sort((A,I)=>{const L=A.tileID,F=I.tileID,$=new s.P(L.canonical.x,L.canonical.y)._rotate(this.transform.angle),H=new s.P(F.canonical.x,F.canonical.y)._rotate(this.transform.angle);return L.overscaledZ-F.overscaledZ||H.y-$.y||H.x-$.x}).map(A=>A.tileID.key):w.map(A=>A.tileID).sort(ZS).map(A=>A.key)}hasRenderableParent(d){const g=this.findLoadedParent(d,0);return!!g&&this._isIdRenderable(g.tileID.key)}_isIdRenderable(d,g,w){return this._tiles[d]&&this._tiles[d].hasData()&&!this._coveredTiles[d]&&(g||!this._tiles[d].holdingForFade())&&(w||!this._shadowCasterTiles[d])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const d in this._tiles)this._tiles[d].state!=="errored"&&this._reloadTile(+d,"reloading")}}_reloadTile(d,g){const w=this._tiles[d];w&&(w.state!=="loading"&&(w.state=g),this._loadTile(w,this._tileLoaded.bind(this,w,d,g)))}_tileLoaded(d,g,w,A,I){if(A){if(d.state="errored",s.b2(A)){if(this._source.fire(new s.C("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:d})),!(d.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const F=this.map.painter.terrain;this.update(this.transform,F.getScaledDemTileSize(),!0),F.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new s.B(A,{tile:d}));return}d.timeAdded=s.o.now(),w==="expired"&&(d.refreshedUponExpiration=!0),this._setTileReloadTimer(g,d),this._source.type==="raster-dem"&&d.dem&&this._backfillDEM(d),this._state.initializeTileState(d,this.map?this.map.painter:null);let L=new Map;I&&I.responseHeaders&&(L=I.responseHeaders),this._source.fire(new s.C("data",{dataType:"source",tile:d,coord:d.tileID,sourceCacheId:this.id,responseHeaders:L}))}_hasTunnelGeometry(){for(const d in this._tiles){const g=this._tiles[d];if(g&&g.hasTunnelGeometry)return!0}return!1}_backfillDEM(d){const g=this.getRenderableIds();for(let A=0;A1||(Math.abs(L)>1&&(Math.abs(L+$)===1?L+=$:Math.abs(L-$)===1&&(L-=$)),I.dem&&A.dem&&(A.dem.backfillBorder(I.dem,L,F),A.neighboringTiles&&A.neighboringTiles[H]&&(A.neighboringTiles[H].backfilled=!0)))}}getTile(d){return this.getTileByID(d.key)}getTileByID(d){return this._tiles[d]}_retainLoadedChildren(d,g,w,A){for(const I in this._tiles){let L=this._tiles[I];if(A[I]||!L.hasData()||L.tileID.overscaledZ<=g||L.tileID.overscaledZ>w)continue;let F=L.tileID;for(;L&&L.tileID.overscaledZ>g+1;){const H=L.tileID.scaledTo(L.tileID.overscaledZ-1);L=this._tiles[H.key],L&&L.hasData()&&(F=H)}let $=F;for(;$.overscaledZ>g;)if($=$.scaledTo($.overscaledZ-1),d[$.key]){A[F.key]=F;break}}}findLoadedParent(d,g){if(d.key in this._loadedParentTiles){const w=this._loadedParentTiles[d.key];return w&&w.tileID.overscaledZ>=g?w:null}for(let w=d.overscaledZ-1;w>=g;w--){const A=d.scaledTo(w),I=this._getLoadedTile(A);if(I)return I}}_getLoadedTile(d){const g=this._tiles[d.key];return g&&g.hasData()?g:this._cache.getByKey(this._source.reparseOverscaled?d.wrapped().key:d.canonical.key)}updateCacheSize(d,g){g=g||this._source.tileSize;const w=Math.ceil(d.width/g)+1,A=Math.ceil(d.height/g)+1,I=Math.floor(w*A*5),L=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,I):I,F=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,L):L;this._cache.setMaxSize(F)}handleWrapJump(d){const g=Math.round((d-(this._prevLng===void 0?d:this._prevLng))/360);if(this._prevLng=d,g){const w={};for(const A in this._tiles){const I=this._tiles[A];I.tileID=I.tileID.unwrapTo(I.tileID.wrap+g),w[I.tileID.key]=I}this._tiles=w;for(const A in this._timers)clearTimeout(this._timers[A]),delete this._timers[A];for(const A in this._tiles)this._setTileReloadTimer(+A,this._tiles[A])}}update(d,g,w,A,I){if(this.transform=d,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!w)return;this.updateCacheSize(d,g),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const L=this._source.type==="batched-model";let F,$=this._source.maxzoom;this._maxzoomOverride!==null&&($=Math.min($,this._maxzoomOverride));const H=this.map&&this.map.painter?this.map.painter._terrain:null;if(H&&H.sourceCache===this&&H.attenuationRange()){const ie=H.attenuationRange()[0],le=Math.floor(ie)-Math.log2(H.getDemUpscale());$>le&&($=le)}const Y=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)F=d.getVisibleUnwrappedCoordinates(this._source.tileID).map(ie=>new s.aR(ie.canonical.z,ie.wrap,ie.canonical.z,ie.canonical.x,ie.canonical.y));else if(this.tileCoverLift!==0){const ie=d.clone();ie.tileCoverLift=this.tileCoverLift,F=ie.coveringTiles({tileSize:g||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:$,roundZoom:this._source.roundZoom&&!w,reparseOverscaled:Y,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:L}),this._source.minzoom<=1&&d.projection.name==="globe"&&(F.push(new s.aR(1,0,1,0,0)),F.push(new s.aR(1,0,1,1,0)),F.push(new s.aR(1,0,1,0,1)),F.push(new s.aR(1,0,1,1,1)))}else if(F=d.coveringTiles({tileSize:g||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:$,roundZoom:this._source.roundZoom&&!w,reparseOverscaled:Y,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:L}),this._source.hasTile){const ie=this._source.hasTile.bind(this._source);F=F.filter(le=>ie(le))}}else F=[];if(F.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const ie=d.coveringZoomLevel({tileSize:g||this._source.tileSize,roundZoom:this._source.roundZoom&&!w}),le=Math.min(ie,$);if(L){const oe=d.extendTileCover(F,le);for(const me of oe)F.push(me)}else if(I){const oe=this.transform.getFrustum(le),me=d.extendTileCoverToNearPlane(F,oe,le);for(const pe of me)F.push(pe);if(le>=18&&this._hasTunnelGeometry()){const pe=d.extendTileCoverForTunnels(F,oe,le,20);for(const je of pe)F.push(je)}}else if(this.castsShadows&&A){const oe=d.extendTileCover(F,le,A,16);for(const me of oe)this._shadowCasterTiles[me.key]=!0,F.push(me)}}const te=this._updateRetainedTiles(F);if(this._supportsFading&&F.length!==0){const ie={},le={},oe=s.o.now(),me=Object.keys(te);for(const je of me){const Re=te[je],xe=this._tiles[je];if(!xe||xe.fadeEndTime!==void 0&&xe.fadeEndTime<=oe)continue;const Ze=this.findLoadedParent(Re,Math.max(Re.overscaledZ-nu.maxOverzooming,this._source.minzoom));Ze&&(this._addTile(Ze.tileID),ie[Ze.tileID.key]=Ze.tileID),le[je]=Re}const pe=F[F.length-1].overscaledZ;for(const je in this._tiles){const Re=this._tiles[je];if(te[je]||!Re.hasData())continue;let xe=Re.tileID;for(;xe.overscaledZ>pe;){xe=xe.scaledTo(xe.overscaledZ-1);const Ze=this._tiles[xe.key];if(Ze&&Ze.hasData()&&le[xe.key]){te[je]=Re.tileID;break}}}for(const je in ie)te[je]||(this._coveredTiles[je]=!0,te[je]=ie[je])}for(const ie in te)this._tiles[ie].clearFadeHold();const ee=s.b3(this._tiles,te);for(const ie of ee){const le=this._tiles[ie];le.hasSymbolBuckets&&!le.holdingForFade()?le.setHoldDuration(this.map._fadeDuration):le.hasSymbolBuckets&&!le.symbolFadeFinished()||this._removeTile(+ie)}this._updateLoadedParentTileCache(),this._renderSourceType===s.b4.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const d in this._tiles)this._tiles[d].holdingForFade()&&this._removeTile(+d)}_updateRetainedTiles(d){const g={};if(d.length===0)return g;const w={},A=d.reduce((H,Y)=>Math.min(H,Y.overscaledZ),1/0),I=d[0].overscaledZ,L=Math.max(I-nu.maxOverzooming,this._source.minzoom),F=Math.max(I+nu.maxUnderzooming,this._source.minzoom),$={};for(const H of d){const Y=this._addTile(H);g[H.key]=H,Y.hasData()||A=this._source.maxzoom){const ee=H.children(this._source.maxzoom)[0],ie=this.getTile(ee);if(ie&&ie.hasData()){g[ee.key]=ee;continue}}else{const ee=H.children(this._source.maxzoom);if(g[ee[0].key]&&g[ee[1].key]&&g[ee[2].key]&&g[ee[3].key])continue}let te=Y.wasRequested();for(let ee=H.overscaledZ-1;ee>=L;--ee){const ie=H.scaledTo(ee);if(w[ie.key]||(w[ie.key]=!0,Y=this.getTile(ie),!Y&&te&&(Y=this._addTile(ie)),Y&&(g[ie.key]=ie,te=Y.wasRequested(),Y.hasData())))break}}return g}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const d in this._tiles){const g=[];let w,A=this._tiles[d].tileID;for(;A.overscaledZ>0;){if(A.key in this._loadedParentTiles){w=this._loadedParentTiles[A.key];break}g.push(A.key);const I=A.scaledTo(A.overscaledZ-1);if(w=this._getLoadedTile(I),w)break;A=I}for(const I of g)this._loadedParentTiles[I]=w}}_addTile(d){let g=this._tiles[d.key];if(g)return g.isExtraShadowCaster!==!0||this._shadowCasterTiles[d.key]||this._reloadTile(d.key,"reloading"),g;g=this._cache.getAndRemove(d),g&&(this._setTileReloadTimer(d.key,g),g.tileID=d,this._state.initializeTileState(g,this.map?this.map.painter:null),this._cacheTimers[d.key]&&(clearTimeout(this._cacheTimers[d.key]),delete this._cacheTimers[d.key],this._setTileReloadTimer(d.key,g)));const w=!!g;if(!w){const A=this.map?this.map.painter:null,I=this._source.tileSize*d.overscaleFactor();g=this._source.type==="raster-array"?new xp(d,I,this.transform.tileZoom,A,this._isRaster):new s.b0(d,I,this.transform.tileZoom,A,this._isRaster,this._source.worldview),this._loadTile(g,this._tileLoaded.bind(this,g,d.key,g.state))}return g.uses++,this._tiles[d.key]=g,w||this._source.fire(new s.C("dataloading",{tile:g,coord:g.tileID,dataType:"source"})),g}_setTileReloadTimer(d,g){d in this._timers&&(clearTimeout(this._timers[d]),delete this._timers[d]);const w=g.getExpiryTimeout();w&&(this._timers[d]=setTimeout(()=>{this._reloadTile(d,"expired"),delete this._timers[d]},w))}_removeTile(d){const g=this._tiles[d];g&&(g.uses--,delete this._tiles[d],this._timers[d]&&(clearTimeout(this._timers[d]),delete this._timers[d]),g.uses>0||(g.hasData()&&g.state!=="reloading"||g.state==="empty"?this._cache.add(g.tileID,g,g.getExpiryTimeout()):(g.aborted=!0,this._abortTile(g),this._unloadTile(g))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const d in this._tiles)this._removeTile(+d);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(d,g,w){const A=[],I=this.transform;if(!I)return A;const L=I.projection.name==="globe",F=s.aH(I.center.lng);for(const $ in this._tiles){const H=this._tiles[$];if(w&&H.clearQueryDebugViz(),H.holdingForFade())continue;let Y;if(L){const te=H.tileID.canonical;if(te.z===0){const ee=[Math.abs(s.aC(F,...Ym(te,-1))-F),Math.abs(s.aC(F,...Ym(te,1))-F)];Y=[0,2*ee.indexOf(Math.min(...ee))-1]}else{const ee=[Math.abs(s.aC(F,...Ym(te,-1))-F),Math.abs(s.aC(F,...Ym(te,0))-F),Math.abs(s.aC(F,...Ym(te,1))-F)];Y=[ee.indexOf(Math.min(...ee))-1]}}else Y=[0];for(const te of Y){const ee=d.containsTile(H,I,g,te);ee&&A.push(ee)}}return A}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(d){return this._getRenderableCoordinates(d)}_getRenderableCoordinates(d,g){const w=this.getRenderableIds(d,g).map(I=>this._tiles[I].tileID),A=this.transform.projection.name==="globe";for(const I of w)I.projMatrix=this.transform.calculateProjMatrix(I.toUnwrapped()),I.expandedProjMatrix=A?this.transform.calculateProjMatrix(I.toUnwrapped(),!1,!0):I.projMatrix;return w}sortCoordinatesByDistance(d){const g=d.slice(),w=this.transform._camera.position,A=this.transform._camera.forward(),I={};for(const L of g){const F=1/(1<I[L.key]-I[F.key]),g}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const d=s.o.now();for(const g in this._tiles){const w=this._tiles[g];if(w.fadeEndTime!==void 0&&w.fadeEndTime>=d)return!0}}return!1}setFeatureState(d,g,w){this._state.updateState(d=d||"_geojsonTileLayer",g,w)}removeFeatureState(d,g,w){this._state.removeFeatureState(d=d||"_geojsonTileLayer",g,w)}getFeatureState(d,g){return this._state.getState(d=d||"_geojsonTileLayer",g)}setDependencies(d,g,w){const A=this._tiles[d];A&&A.setDependencies(g,w)}reloadTilesForDependencies(d,g){for(const w in this._tiles)this._tiles[w].hasDependency(d,g)&&this._reloadTile(+w,"reloading");this._cache.filter(w=>!w.hasDependency(d,g))}_preloadTiles(d,g){if(!this._sourceLoaded){const $=()=>{this._sourceLoaded&&(this._source.off("data",$),this._preloadTiles(d,g))};return void this._source.on("data",$)}const w=new Map,A=Array.isArray(d)?d:[d],I=this.map.painter.terrain,L=this.usedForTerrain&&I?I.getScaledDemTileSize():this._source.tileSize;for(const $ of A){const H=$.coveringTiles({tileSize:L,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&&$.updateElevation(!1)}const F=Array.from(w.values());s.t(F,($,H)=>{const Y=new s.b0($,this._source.tileSize*$.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)})},g)}}function ZS(v,d){const g=Math.abs(2*v.wrap)-+(v.wrap<0),w=Math.abs(2*d.wrap)-+(d.wrap<0);return v.overscaledZ-d.overscaledZ||w-g||d.canonical.y-v.canonical.y||d.canonical.x-v.canonical.x}function Ym(v,d){const g=1<0:w.type==="building"?A=!w.isHidden(d)&&w.paint.get("building-opacity")>0:w.type==="model"&&(A=!w.isHidden(d)&&w.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!A&&g.visible,g.visible=A}}updateZOffset(d,g){this.currentBuildingBuckets=[];for(const A of this.layers){const I=A.layer,L=this.style.getLayerSourceCache(I);let F=1;I.type==="fill-extrusion"?F=A.visible?I.paint.get("fill-extrusion-vertical-scale"):0:I.type==="building"&&(F=A.visible?I.paint.get("building-vertical-scale"):0);let $=L?L.getTile(g):null;if(!$&&L)for(const H in L._tiles){const Y=L._tiles[H];if(g.canonical.isChildOf(Y.tileID.canonical)){$=Y;break}}this.currentBuildingBuckets.push({bucket:$?$.getBucket(I):null,tileID:$?$.tileID:g,verticalScale:F})}d.hasAnyZOffset=!1;let w=!1;for(let A=0;A{w in d&&(g[w]=d[w])}),g}function QS(v){v=v.slice();const d=Object.create(null);for(const g of v)d[g.id]=g;for(let g=0;g0?(A-L)/F:0;return this.points[I].mult(1-$).add(this.points[g].mult($))}}class JS{constructor(d,g,w){const A=this.boxCells=[],I=this.circleCells=[];this.xCellCount=Math.ceil(d/w),this.yCellCount=Math.ceil(g/w);for(let L=0;Lthis.width||A<0||g>this.height)return!I&&[];const F=[];if(d<=0&&g<=0&&this.width<=w&&this.height<=A){if(I)return!0;for(let $=0;$0:F}_queryCircle(d,g,w,A,I){const L=d-w,F=d+w,$=g-w,H=g+w;if(F<0||L>this.width||H<0||$>this.height)return!A&&[];const Y=[];return this._forEachCell(L,$,F,H,this._queryCellCircle,Y,{hitTest:A,circle:{x:d,y:g,radius:w},seenUids:{box:{},circle:{}}},I),A?Y.length>0:Y}query(d,g,w,A,I){return this._query(d,g,w,A,!1,I)}hitTest(d,g,w,A,I){return this._query(d,g,w,A,!0,I)}hitTestCircle(d,g,w,A){return this._queryCircle(d,g,w,!0,A)}_queryCell(d,g,w,A,I,L,F,$){const H=F.seenUids,Y=this.boxCells[I];if(Y!==null){const ee=this.bboxes;for(const ie of Y)if(!H.box[ie]){H.box[ie]=!0;const le=4*ie;if(d<=ee[le+2]&&g<=ee[le+3]&&w>=ee[le+0]&&A>=ee[le+1]&&(!$||$(this.boxKeys[ie]))){if(F.hitTest)return L.push(!0),!0;L.push({key:this.boxKeys[ie],x1:ee[le],y1:ee[le+1],x2:ee[le+2],y2:ee[le+3]})}}}const te=this.circleCells[I];if(te!==null){const ee=this.circles;for(const ie of te)if(!H.circle[ie]){H.circle[ie]=!0;const le=3*ie;if(this._circleAndRectCollide(ee[le],ee[le+1],ee[le+2],d,g,w,A)&&(!$||$(this.circleKeys[ie]))){if(F.hitTest)return L.push(!0),!0;{const oe=ee[le],me=ee[le+1],pe=ee[le+2];L.push({key:this.circleKeys[ie],x1:oe-pe,y1:me-pe,x2:oe+pe,y2:me+pe})}}}}}_queryCellCircle(d,g,w,A,I,L,F,$){const H=F.circle,Y=F.seenUids,te=this.boxCells[I];if(te!==null){const ie=this.bboxes;for(const le of te)if(!Y.box[le]){Y.box[le]=!0;const oe=4*le;if(this._circleAndRectCollide(H.x,H.y,H.radius,ie[oe+0],ie[oe+1],ie[oe+2],ie[oe+3])&&(!$||$(this.boxKeys[le])))return L.push(!0),!0}}const ee=this.circleCells[I];if(ee!==null){const ie=this.circles;for(const le of ee)if(!Y.circle[le]){Y.circle[le]=!0;const oe=3*le;if(this._circlesCollide(ie[oe],ie[oe+1],ie[oe+2],H.x,H.y,H.radius)&&(!$||$(this.circleKeys[le])))return L.push(!0),!0}}}_forEachCell(d,g,w,A,I,L,F,$){const H=this._convertToXCellCoord(d),Y=this._convertToYCellCoord(g),te=this._convertToXCellCoord(w),ee=this._convertToYCellCoord(A);for(let ie=H;ie<=te;ie++)for(let le=Y;le<=ee;le++)if(I.call(this,d,g,w,A,this.xCellCount*le+ie,L,F,$))return}_convertToXCellCoord(d){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(d*this.xScale)))}_convertToYCellCoord(d){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(d*this.yScale)))}_circlesCollide(d,g,w,A,I,L){const F=A-d,$=I-g,H=w+L;return H*H>F*F+$*$}_circleAndRectCollide(d,g,w,A,I,L,F){const $=(L-A)/2,H=Math.abs(d-(A+$));if(H>$+w)return!1;const Y=(F-I)/2,te=Math.abs(g-(I+Y));if(te>Y+w)return!1;if(H<=$||te<=Y)return!0;const ee=H-$,ie=te-Y;return ee*ee+ie*ie<=w*w}}const p3=Math.tan(85*Math.PI/180);function af(v,d,g,w,A,I,L){const F=s.bb();if(g)if(I.name==="globe"){const $=s.bc(A,d);s.aD(F,F,$)}else{const $=s.bd([],L);F[0]=$[0],F[1]=$[1],F[4]=$[2],F[5]=$[3],w||s.ba(F,F,A.angle)}else s.aD(F,A.labelPlaneMatrix,v);return F}function Nu(v,d,g,w,A,I,L){const F=af(v,d,g,w,A,I,L);return I.name==="globe"&&g||(F[2]=F[6]=F[10]=F[14]=0),F}function Jm(v,d,g,w,A,I,L){if(g){if(I.name==="globe"){const F=af(v,d,g,w,A,I,L);return s.b7(F,F),s.aD(F,v,F),F}{const F=s.b8(v),$=s.b9([]);return $[0]=L[0],$[1]=L[1],$[4]=L[2],$[5]=L[3],s.aD(F,F,$),w||s.ba(F,F,-A.angle),F}}return A.glCoordMatrix}function iu(v,d,g,w){const A=[v,d,g,1];g?s.aE(A,A,w):Xr(A,A,w);const I=A[3];return A[0]/=I,A[1]/=I,A[2]/=I,A}function rv(v,d){return Math.min(.5+v/d*.5,1.5)}function bx(v,d){const g=v[0]/v[3],w=v[1]/v[3];return g>=-d[0]&&g<=d[0]&&w>=-d[1]&&w<=d[1]}function rc(v,d,g,w,A,I,L,F,$,H,Y=1){const te=g.transform,ee=w?v.textSizeData:v.iconSizeData,ie=s.bj(ee,g.transform.zoom,Y),le=te.projection.name==="globe",oe=[256/g.width*2+1,256/g.height*2+1],me=w?v.text.dynamicLayoutVertexArray:v.icon.dynamicLayoutVertexArray;me.clear();let pe=null;le&&(pe=w?v.text.globeExtVertexArray:v.icon.globeExtVertexArray);const je=v.lineVertexArray,Re=w?v.text.placedSymbolArray:v.icon.placedSymbolArray,xe=g.transform.width/g.transform.height;let Ze,ze=!1;for(let Ke=0;KeMath.abs(g)?{useVertical:!0}:v===s.bk.vertical?w>0?{needsFlipping:!0}:null:d!==0&&function(A,I){return A===0||Math.abs(I/A)>p3}(g,w)?d===1?{needsFlipping:!0}:null:g<0?{needsFlipping:!0}:null}function tT(v,d,g,w,A,I,L,F,$,H,Y,te,ee,ie,le,oe,me,pe,je,Re){const xe=d/24,Ze=v.lineOffsetX*xe,ze=v.lineOffsetY*xe,{lineStartIndex:Ke,glyphStartIndex:De,numGlyphs:Fe,segment:qe,writingMode:st,flipState:Qe}=v,xt=Ke+v.lineLength,ft=Rt=>{if(Y){const[gt,vt,St]=Rt.up,rr=H.length;s.bm(Y,rr+0,gt,vt,St),s.bm(Y,rr+1,gt,vt,St),s.bm(Y,rr+2,gt,vt,St),s.bm(Y,rr+3,gt,vt,St)}const[Ft,ot,et]=Rt.point;s.bn(H,Ft,ot,et,Rt.angle)};if(Fe>1){const Rt=eT(xe,F,Ze,ze,g,te,ee,v,$,I,ie,oe,!1,me,pe,je,Re);if(!Rt)return{notEnoughRoom:!0};if(w&&!g){let[Ft,ot,et]=Rt.first.point,[gt,vt,St]=Rt.last.point;[Ft,ot]=iu(Ft,ot,et,L),[gt,vt]=iu(gt,vt,St,L);const rr=nv(st,Qe,(gt-Ft)*le,vt-ot);if(v.flipState=rr&&rr.needsFlipping?1:2,rr)return rr}ft(Rt.first);for(let Ft=De+1;Ft0?gt:rT(ee,et,Ft,1,A,void 0,me,pe.canonical),St=nv(st,Qe,(vt[0]-Ft[0])*le,vt[1]-Ft[1]);if(v.flipState=St&&St.needsFlipping?1:2,St)return St}const Rt=iv(xe*F.getoffsetX(De),Ze,ze,g,te,ee,qe,Ke,xt,$,I,ie,oe,!1,!1,me,pe,je,Re);if(!Rt)return{notEnoughRoom:!0};ft(Rt)}return{}}function Yn(v,d,g,w,A){const{x:I,y:L,z:F}=w.projectTilePoint(v.x,v.y,d);if(!A)return iu(I,L,F,g);const[$,H,Y]=A.getElevation(v,A.elevation,A.elevationFeature);return iu(I+$,L+H,F+Y,g)}function rT(v,d,g,w,A,I,L,F){const $=Yn(v.sub(d)._unit()._add(v),F,A,L,I);return s.ax($,g,$),s.ay($,$),s.bg($,g,$,w)}function iv(v,d,g,w,A,I,L,F,$,H,Y,te,ee,ie,le,oe,me,pe,je){const Re=w?v-d:v+d;let xe=Re>0?1:-1,Ze=0;w&&(xe*=-1,Ze=Math.PI),xe<0&&(Ze+=Math.PI);let ze=F+L+(xe>0?0:1)|0,Ke=A,De=A,Fe=0,qe=0;const st=Math.abs(Re),Qe=[],xt=[];let ft=I,Rt=ft,Ft=s.be([]);const ot=()=>rT(Rt,ft,De,st-Fe+1,Y,ee,oe,me.canonical);for(;Fe+qe<=st;){if(ze+=xe,ze=$)return null;if(De=Ke,Rt=ft,Qe.push(De),ie&&xt.push(Rt),ft=new s.P(H.getx(ze),H.gety(ze)),Ke=te[ze],!Ke){const Lr=Yn(ft,me.canonical,Y,oe,ee);Ke=Lr[3]>0?te[ze]=Lr:ot()}Fe+=qe;const Dt=s.ax([],Ke,De),Ar=s.bf(De,Ke);if(g&&Ar>0&&qe>0&&s.bi(Ft,Dt)/(qe*Ar)0,Re),Ke=H*ze.perspectiveRatio,De=(w.x1*g+F.x-w.padding)*Ke+ze.point.x,Fe=(w.y1*g+F.y-w.padding)*Ke+ze.point.y,qe=(w.x2*g+F.x+w.padding)*Ke+ze.point.x,st=(w.y2*g+F.y+w.padding)*Ke+ze.point.y,Qe=ze.perspectiveRatio<=.55||ze.occluded;return!this.isInsideGrid(De,Fe,qe,st)||!$&&this.grid.hitTest(De,Fe,qe,st,te)||Qe?{box:[],offscreen:!1,occluded:ze.occluded}:{box:[De,Fe,qe,st],offscreen:this.isOffscreen(De,Fe,qe,st),occluded:!1}}placeCollisionCircles(d,g,w,A,I,L,F,$,H,Y,te,ee,ie,le,oe,me){const pe=[],je=this.transform.elevation,Re=d.getProjection(),xe=d.elevationType==="road",Ze=!!je||xe,ze=s.bu.getAtTileOffsetFunc(me,this.transform.center.lat,this.transform.worldSize,Re),Ke=new s.P(w.tileAnchorX,w.tileAnchorY),De=new s.P(w.tileAnchorX,w.tileAnchorY);let{x:Fe,y:qe,z:st}=Re.projectTilePoint(De.x,De.y,me.canonical),Qe=null;if(Ze){const Ar=xe?d.getElevationFeatureForText(A):null;Qe={getElevation:ze,elevation:je,elevationFeature:Ar};const[Lr,gr,Tr]=ze(Ke,je,Ar);Fe+=Lr,qe+=gr,st+=Tr}const xt=Re.name==="globe",ft=this.projectAndGetPerspectiveRatio($,Fe,qe,st,me,xt||!!je||this.transform.pitch>0,Re),{perspectiveRatio:Rt}=ft,Ft=(ee?F/Rt:F*Rt)/s.by,ot=iu(Fe,qe,st,H),et=w.lineOffsetX*Ft,gt=w.lineOffsetY*Ft,vt=s.ap(d.layers[0].layout.get("text-max-angle")),St=Math.cos(vt),rr=ft.signedDistanceFromCamera>0?eT(Ft,L,et,gt,xe&&w.flipState===1,ot,De,w,I,H,{},Ze&&!ee?Qe:null,ee&&Ze,Re,me,ee,St):null;let Gt=!1,Ht=!1,Dt=!0;if(rr&&!ft.occluded){const Ar=.5*le*Rt+oe,Lr=new s.P(-100,-100),gr=new s.P(this.screenRightBoundary,this.screenBottomBoundary),Tr=new yj,{first:Hr,last:sn}=rr,en=Hr.path.length;let _n=[];for(let tn=en-1;tn>=1;tn--)_n.push(Hr.path[tn]);for(let tn=1;tn(Ze&&!xt&&(xi=ze(Kitn[3]<=0)&&(_n=[]));let vn=[];if(_n.length>0){let tn=1/0,Vn=-1/0,xi=1/0,Ki=-1/0;for(const Ti of _n)tn=Math.min(tn,Ti[0]),xi=Math.min(xi,Ti[1]),Vn=Math.max(Vn,Ti[0]),Ki=Math.max(Ki,Ti[1]);Vn>=Lr.x&&tn<=gr.x&&Ki>=Lr.y&&xi<=gr.y&&(vn=[_n.map(Ti=>new s.P(Ti[0],Ti[1]))],(tngr.x||xigr.y)&&(vn=s.bv(vn,Lr.x,Lr.y,gr.x,gr.y)))}for(const tn of vn){Tr.reset(tn,.25*Ar);let Vn=0;Vn=Tr.length<=.5*Ar?1:Math.ceil(Tr.paddedLength/$r)+1;for(let xi=0;xi0?(s.aE($,$,d),this.fogState&&I&&F.name!=="globe"&&(H=function(ee,ie,le,oe,me,pe){const je=pe.calculateFogTileMatrix(me),Re=[ie,le,oe];return s.ah(Re,Re,je),Ci(ee,s.ai(Re),pe.pitch,pe._fov)}(this.fogState,g,w,A,I.toUnwrapped(),this.transform)>.9)):Xr($,$,d);const Y=$[3];return{point:new s.P(($[0]/Y+1)/2*this.transform.width+Ru,(-$[1]/Y+1)/2*this.transform.height+Ru),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(F)/Y*.5,1.5),signedDistanceFromCamera:Y,occluded:L&&$[2]>Y||H}}isOffscreen(d,g,w,A){return w=this.screenRightBoundary||Athis.screenBottomBoundary}isInsideGrid(d,g,w,A){return w>=0&&d=0&&gw.collisionGroupID===g}}return this.collisionGroups[d]}}function ml(v,d,g,w,A){const{horizontalAlign:I,verticalAlign:L}=s.bF(v),F=-(I-.5)*d,$=-(L-.5)*g,H=s.bG(v,w);return new s.P(F+H[0]*A,$+H[1]*A)}function of(v,d,g,w,A){const I=new s.P(v,d);return g&&I._rotate(w?A:-A),I}class hi{constructor(d,g,w,A,I,L){this.transform=d.clone(),this.projection=d.projection.name,this.collisionIndex=new sv(this.transform,I),this.buildingIndex=L,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=g,this.retainedQueryData={},this.collisionGroups=new di(w),this.collisionCircleArrays={},this.prevPlacement=A,A&&(A.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(d,g,w,A,I=1){const L=w.getBucket(g),F=w.latestFeatureIndex;if(!L||!F||g.fqid!==L.layerIds[0])return;const $=L.layers[0].layout,H=L.layers[0].paint,Y=w.collisionBoxArray,te=Math.pow(2,this.transform.zoom-w.tileID.overscaledZ),ee=w.tileSize/s.an,ie=w.tileID.toUnwrapped();this.transform.setProjection(L.projection);const le=(oe=w.tileID,me=L.getProjection(),pe=this.transform,me.name===this.projection?pe.calculateProjMatrix(oe.toUnwrapped()):tv(pe,me,oe));var oe,me,pe;const je=$.get("text-pitch-alignment")==="map",Re=$.get("text-rotation-alignment")==="map";g.compileFilter(g.options);const xe=g.dynamicFilter(),Ze=g.dynamicFilterNeedsFeature(),ze=g.dynamicFilterNeedsGeometry(),Ke=this.transform.calculatePixelsToTileUnitsMatrix(w),De=Nu(le,w.tileID.canonical,je,Re,this.transform,L.getProjection(),Ke);let Fe=null;const qe=L.getProjection().createInversionMatrix(this.transform,w.tileID.canonical);if(je){const gt=Jm(le,w.tileID.canonical,je,Re,this.transform,L.getProjection(),Ke);Fe=s.aD([],this.transform.labelPlaneMatrix,gt)}let st=null;xe&&w.latestFeatureIndex&&(st={unwrappedTileID:ie,dynamicFilter:xe,dynamicFilterNeedsFeature:Ze,needGeometry:ze}),this.retainedQueryData[L.bucketInstanceId]=new li(L.bucketInstanceId,F,L.sourceLayerIndex,L.index,w.tileID);const[Qe,xt]=L.layers[0].layout.get("text-size-scale-range"),ft=s.aC(I,Qe,xt),[Rt,Ft]=$.get("icon-size-scale-range"),ot=s.aC(I,Rt,Ft),et={bucket:L,layout:$,paint:H,posMatrix:le,invMatrix:qe,mercatorCenter:[s.aH(this.transform.center.lng),s.aL(this.transform.center.lat)],textLabelPlaneMatrix:De,labelToScreenMatrix:Fe,clippingData:st,scale:te,textPixelRatio:ee,holdingForFade:w.holdingForFade(),collisionBoxArray:Y,partiallyEvaluatedTextSize:s.bj(L.textSizeData,this.transform.zoom,ft),partiallyEvaluatedIconSize:s.bj(L.iconSizeData,this.transform.zoom,ot),collisionGroup:this.collisionGroups.get(L.sourceID),latestFeatureIndex:w.latestFeatureIndex};if(A)for(const gt of L.sortKeyRanges){const{sortKey:vt,symbolInstanceStart:St,symbolInstanceEnd:rr}=gt;d.push({sortKey:vt,symbolInstanceStart:St,symbolInstanceEnd:rr,parameters:et})}else d.push({symbolInstanceStart:0,symbolInstanceEnd:L.symbolInstances.length,parameters:et})}attemptAnchorPlacement(d,g,w,A,I,L,F,$,H,Y,te,ee,ie,le,oe,me,pe,je,Re,xe,Ze){const{textOffset0:ze,textOffset1:Ke,crossTileID:De}=oe,Fe=[ze,Ke],qe=ml(d,L,F,Fe,$),st=this.collisionIndex.placeCollisionBox(pe,$,g,w,A,I,of(qe.x,qe.y,H,Y,this.transform.angle),le,te,ee,ie.predicate);if(Re){const Qe=pe.getSymbolInstanceIconSize(Ze,this.transform.zoom,oe.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(pe,Qe,Re,w,A,I,of(qe.x,qe.y,H,Y,this.transform.angle),le,te,ee,ie.predicate).box.length===0)return}if(st.box.length>0){let Qe;return this.prevPlacement&&this.prevPlacement.variableOffsets[De]&&this.prevPlacement.placements[De]&&this.prevPlacement.placements[De].text&&(Qe=this.prevPlacement.variableOffsets[De].anchor),this.variableOffsets[De]={textOffset:Fe,width:L,height:F,anchor:d,textScale:$,prevAnchor:Qe},this.markUsedJustification(pe,d,oe,je),pe.allowVerticalPlacement&&(this.markUsedOrientation(pe,je,oe),this.placedOrientations[De]=je),{shift:qe,placedGlyphBoxes:st}}}placeLayerBucketPart(d,g,w,A,I=1){const{bucket:L,layout:F,paint:$,posMatrix:H,textLabelPlaneMatrix:Y,labelToScreenMatrix:te,clippingData:ee,textPixelRatio:ie,mercatorCenter:le,invMatrix:oe,holdingForFade:me,collisionBoxArray:pe,partiallyEvaluatedTextSize:je,partiallyEvaluatedIconSize:Re,collisionGroup:xe,latestFeatureIndex:Ze}=d.parameters,ze=F.get("text-optional"),Ke=F.get("icon-optional"),De=F.get("text-allow-overlap"),Fe=F.get("icon-allow-overlap"),qe=F.get("text-rotation-alignment")==="map",st=F.get("icon-rotation-alignment")==="map",Qe=F.get("text-pitch-alignment")==="map",xt=$.get("symbol-z-offset"),ft=F.get("symbol-elevation-reference")==="sea",Rt=F.get("symbol-placement"),[Ft,ot]=F.get("text-size-scale-range"),[et,gt]=F.get("icon-size-scale-range"),vt=s.aC(I,Ft,ot),St=s.aC(I,et,gt),rr=F.get("text-variable-anchor"),Gt=qe&&Rt!=="point",Ht=st&&Rt!=="point",Dt=rr&&L.hasTextData(),Ar=L.hasIconTextFit()&&Dt&&L.hasIconData();this.transform.setProjection(L.projection);const Lr=Dt||Gt,gr=Ht||Ar;let Tr=De&&(Fe||!L.hasIconData()||Ke),Hr=Fe&&(De||!L.hasTextData()||ze);const sn=!xt.isConstant();!L.collisionArrays&&pe&&L.deserializeCollisionBoxes(pe),w&&A&&L.updateCollisionDebugBuffers(this.transform.zoom,pe,vt,St);const en=($r,vn,tn)=>{const{crossTileID:Vn,numVerticalGlyphVertices:xi}=$r;let Ki=null;if(ee&&ee.dynamicFilterNeedsFeature||sn){const Ii=this.retainedQueryData[L.bucketInstanceId],Mi=Ze.loadFeature({featureIndex:$r.featureIndex,bucketIndex:Ii.bucketIndex,sourceLayerIndex:Ii.sourceLayerIndex,layoutVertexArrayOffset:0}),fi=Mi.properties?Mi.properties.worldview:null;if(L.localizable&&L.worldview&&typeof fi=="string")if(fi==="all")Mi.properties.$localized=!0;else{if(!fi.split(",").includes(L.worldview))return;Mi.properties.$localized=!0,Mi.properties.worldview=L.worldview}Ki=ee&&ee.needGeometry?s.bD(Mi,!0):Mi}if(ee&&!(0,ee.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:L.worldview},Ki,this.retainedQueryData[L.bucketInstanceId].tileID.canonical,new s.P($r.tileAnchorX,$r.tileAnchorY),this.transform.calculateDistanceTileData(ee.unwrappedTileID)))return this.placements[Vn]=new oh(!1,!1,!1,!0),void g.add(Vn);const Ti=xt.evaluate(Ki,{});if(($r.zOffset||0)+(Ti||0)>0&&this.frontCutoffStart>0){const Ii=2*this.frontCutoffStart-1,Mi=[$r.tileAnchorX,$r.tileAnchorY,0,1],fi=s.aE(s.bE(),Mi,H);if(fi[1]/fi[3]{Ii.tileID=this.retainedQueryData[L.bucketInstanceId].tileID;const Mi=this.transform.elevation;Ii.elevation=ft?Ti:Ti+s.bu.getAtTileOffset(Ii.tileID,new s.P(Ii.tileAnchorX,Ii.tileAnchorY),Mi,la),Ii.elevation+=$r.zOffset},sc=tn.textBox;if(sc){Va(sc);const Ii=fi=>{let Is=s.bk.horizontal;if(L.allowVerticalPlacement&&!fi&&this.prevPlacement){const Lo=this.prevPlacement.placedOrientations[Vn];Lo&&(this.placedOrientations[Vn]=Lo,Is=Lo,this.markUsedOrientation(L,Is,$r))}return Is},Mi=(fi,Is)=>{if(L.allowVerticalPlacement&&xi>0&&tn.verticalTextBox){for(const Lo of L.writingModes)if(Lo===s.bk.vertical?(on=Is(),Gi=on):on=fi(),on&&on.box&&on.box.length)break}else on=fi()};if(rr){let fi=rr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Vn]){const hs=this.prevPlacement.variableOffsets[Vn];fi.indexOf(hs.anchor)>0&&(fi=fi.filter(ac=>ac!==hs.anchor),fi.unshift(hs.anchor))}const Is=(hs,ac,gf)=>{const Fp=L.getSymbolInstanceTextSize(je,$r,this.transform.zoom,vn),Bp=(hs.x2-hs.x1)*Fp+2*hs.padding,bg=(hs.y2-hs.y1)*Fp+2*hs.padding,gh=$r.hasIconTextFit&&!Fe?ac:null;gh&&Va(gh);let Sd={box:[],offscreen:!1,occluded:!1};const wg=De?2*fi.length:fi.length;for(let Rl=0;Rl=fi.length,$r,vn,L,gf,gh,je,Re);if(yf&&(Sd=yf.placedGlyphBoxes,Sd&&Sd.box&&Sd.box.length)){Qn=!0,Jn=yf.shift;break}}return Sd};Mi(()=>Is(sc,tn.iconBox,s.bk.horizontal),()=>{const hs=tn.verticalTextBox;return hs&&Va(hs),L.allowVerticalPlacement&&!(on&&on.box&&on.box.length)&&xi>0&&hs?Is(hs,tn.verticalIconBox,s.bk.vertical):{box:null,offscreen:null,occluded:null}}),on&&(Qn=on.box,mn=on.offscreen,Ei=on.occluded);const Lo=Ii(!(!on||!on.box));if(!Qn&&this.prevPlacement){const hs=this.prevPlacement.variableOffsets[Vn];hs&&(this.variableOffsets[Vn]=hs,this.markUsedJustification(L,hs.anchor,$r,Lo))}}else{const fi=(Is,Lo)=>{const hs=L.getSymbolInstanceTextSize(je,$r,this.transform.zoom,vn),ac=this.collisionIndex.placeCollisionBox(L,hs,Is,le,oe,Lr,new s.P(0,0),De,ie,H,xe.predicate);return ac&&ac.box&&ac.box.length&&(this.markUsedOrientation(L,Lo,$r),this.placedOrientations[Vn]=Lo),ac};Mi(()=>fi(sc,s.bk.horizontal),()=>{const Is=tn.verticalTextBox;return L.allowVerticalPlacement&&xi>0&&Is?(Va(Is),fi(Is,s.bk.vertical)):{box:null,offscreen:null,occluded:null}}),Ii(!!(on&&on.box&&on.box.length))}}if(_i=on,Qn=_i&&_i.box&&_i.box.length>0,mn=_i&&_i.offscreen,Ei=_i&&_i.occluded,$r.useRuntimeCollisionCircles){const Ii=$r.centerJustifiedTextSymbolIndex>=0?$r.centerJustifiedTextSymbolIndex:$r.verticalPlacedTextSymbolIndex,Mi=L.text.placedSymbolArray.get(Ii),fi=s.bl(L.textSizeData,je,Mi),Is=F.get("text-padding");Os=this.collisionIndex.placeCollisionCircles(L,De,Mi,Ii,L.lineVertexArray,L.glyphOffsetArray,fi,H,Y,te,w,Qe,xe.predicate,$r.collisionCircleDiameter*fi/s.by,Is,this.retainedQueryData[L.bucketInstanceId].tileID),Qn=De||Os.circles.length>0&&!Os.collisionDetected,mn=mn&&Os.offscreen,Ei=Os.occluded}if(tn.iconFeatureIndex&&(_o=tn.iconFeatureIndex),tn.iconBox){const Ii=Mi=>{Va(Mi);const fi=$r.hasIconTextFit&&Jn?of(Jn.x,Jn.y,qe,Qe,this.transform.angle):new s.P(0,0),Is=L.getSymbolInstanceIconSize(Re,this.transform.zoom,$r.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(L,Is,Mi,le,oe,gr,fi,Fe,ie,H,xe.predicate)};Gi&&Gi.box&&Gi.box.length&&tn.verticalIconBox?(jn=Ii(tn.verticalIconBox),pn=jn.box.length>0):(jn=Ii(tn.iconBox),pn=jn.box.length>0),mn=mn&&jn.offscreen,rs=jn.occluded}const si=ze||$r.numHorizontalGlyphVertices===0&&xi===0,Ac=Ke||$r.numIconVertices===0;if(si||Ac?Ac?si||(pn=pn&&Qn):Qn=pn&&Qn:pn=Qn=pn&&Qn,Qn&&_i&&_i.box&&this.collisionIndex.insertCollisionBox(_i.box,F.get("text-ignore-placement"),L.bucketInstanceId,Gi&&Gi.box&&Xs?Xs:wi,xe.ID),pn&&jn&&this.collisionIndex.insertCollisionBox(jn.box,F.get("icon-ignore-placement"),L.bucketInstanceId,_o,xe.ID),Os&&(Qn&&this.collisionIndex.insertCollisionCircles(Os.circles,F.get("text-ignore-placement"),L.bucketInstanceId,wi,xe.ID),w)){const Ii=L.bucketInstanceId;let Mi=this.collisionCircleArrays[Ii];Mi===void 0&&(Mi=this.collisionCircleArrays[Ii]=new Dr);for(let fi=0;fi=0;--vn){const tn=$r[vn];en(L.symbolInstances.get(tn),tn,L.collisionArrays[tn])}L.hasAnyZOffset&&s.w(`${L.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(L.hasAnyZOffset){const $r=L.getSortedIndexesByZOffset();for(let vn=0;vn<$r.length;++vn){const tn=$r[vn];en(L.symbolInstances.get(tn),tn,L.collisionArrays[tn])}}else for(let $r=d.symbolInstanceStart;$r=0&&(d.text.placedSymbolArray.get(I).crossTileID=te>=0&&I!==te?0:H),L>=0&&(d.text.placedSymbolArray.get(L).crossTileID=te>=0&&L!==te?0:H),F>=0&&(d.text.placedSymbolArray.get(F).crossTileID=te>=0&&F!==te?0:H),$>=0&&(d.text.placedSymbolArray.get($).crossTileID=te>=0&&$!==te?0:H)}markUsedOrientation(d,g,w){const A=g===s.bk.horizontal||g===s.bk.horizontalOnly?g:0,I=g===s.bk.vertical?g:0,{leftJustifiedTextSymbolIndex:L,centerJustifiedTextSymbolIndex:F,rightJustifiedTextSymbolIndex:$,verticalPlacedTextSymbolIndex:H}=w,Y=d.text.placedSymbolArray;L>=0&&(Y.get(L).placedOrientation=A),F>=0&&(Y.get(F).placedOrientation=A),$>=0&&(Y.get($).placedOrientation=A),H>=0&&(Y.get(H).placedOrientation=I)}commit(d){this.commitTime=d,this.zoomAtLastRecencyCheck=this.transform.zoom;const g=this.prevPlacement;let w=!1;this.prevZoomAdjustment=g?g.zoomAdjustment(this.transform.zoom):0;const A=g?g.symbolFadeChange(d):1,I=g?g.opacities:{},L=g?g.variableOffsets:{},F=g?g.placedOrientations:{};for(const $ in this.placements){const H=this.placements[$],Y=I[$];Y?(this.opacities[$]=new vp(Y,A,H.text,H.icon,null,H.clipped),w=w||H.text!==Y.text.placed||H.icon!==Y.icon.placed):(this.opacities[$]=new vp(null,A,H.text,H.icon,H.skipFade,H.clipped),w=w||H.text||H.icon)}for(const $ in I){const H=I[$];if(!this.opacities[$]){const Y=new vp(H,A,!1,!1);Y.isHidden()||(this.opacities[$]=Y,w=w||H.text.placed||H.icon.placed)}}for(const $ in L)this.variableOffsets[$]||!this.opacities[$]||this.opacities[$].isHidden()||(this.variableOffsets[$]=L[$]);for(const $ in F)this.placedOrientations[$]||!this.opacities[$]||this.opacities[$].isHidden()||(this.placedOrientations[$]=F[$]);w?this.lastPlacementChangeTime=d:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=g?g.lastPlacementChangeTime:d)}updateLayerOpacities(d,g,w,A){A&&(this.lastReplacementSourceUpdateTime=A.updateTime);const I=new Set;for(const L of g){const F=L.getBucket(d);F&&L.latestFeatureIndex&&d.fqid===F.layerIds[0]&&(this.updateBucketOpacities(F,I,L,L.collisionBoxArray,w,A,L.tileID,d.scope),F.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(F,L.tileID),F.elevationType==="road"&&F.updateRoadElevation(L.tileID.canonical),F.updateZOffset())}}updateBucketOpacities(d,g,w,A,I,L,F,$){d.hasTextData()&&d.text.opacityVertexArray.clear(),d.hasIconData()&&d.icon.opacityVertexArray.clear(),d.hasIconCollisionBoxData()&&d.iconCollisionBox.collisionVertexArray.clear(),d.hasTextCollisionBoxData()&&d.textCollisionBox.collisionVertexArray.clear();const H=d.layers[0].layout,Y=d.layers[0].paint,te=!!d.layers[0].dynamicFilter(),ee=new vp(null,0,!1,!1,!0),ie=H.get("text-allow-overlap"),le=H.get("icon-allow-overlap"),oe=H.get("text-variable-anchor"),me=H.get("text-rotation-alignment")==="map",pe=H.get("text-pitch-alignment")==="map",je=Y.get("symbol-z-offset"),Re=H.get("symbol-elevation-reference")==="sea",xe=!je.isConstant(),Ze=new vp(null,0,ie&&(le||!d.hasIconData()||H.get("icon-optional")),le&&(ie||!d.hasTextData()||H.get("text-optional")),!0);!d.collisionArrays&&A&&(d.hasIconCollisionBoxData()||d.hasTextCollisionBoxData())&&d.deserializeCollisionBoxes(A);const ze=(De,Fe,qe)=>{for(let st=0;st0||st>0,rr=xt>0,Gt=this.placedOrientations[Qe],Ht=Gt===s.bk.vertical,Dt=Gt===s.bk.horizontal||Gt===s.bk.horizontalOnly;!St&&!rr||vt.isHidden()||Ke++;let Ar=!1;if((St||rr)&&L)for(const Lr of d.activeReplacements){if(s.bz(Lr,I,s.bA.Symbol,$)||Lr.min.x>ft||ft>Lr.max.x||Lr.min.y>Rt||Rt>Lr.max.y)continue;const gr=s.bB(ft,Rt,F.canonical,Lr.footprintTileId.canonical);if(Ar=s.bC(gr,Lr.footprint),Ar)break}if(Ar&&this.collisionIndex.markSymbolAsClipped(d.bucketInstanceId,Fe.featureIndex),St){const Lr=Ar?lh:tg(vt.text);ze(d.text,qe,Ht?lh:Lr),ze(d.text,st,Dt?lh:Lr);const gr=vt.text.isHidden(),{leftJustifiedTextSymbolIndex:Tr,centerJustifiedTextSymbolIndex:Hr,rightJustifiedTextSymbolIndex:sn,verticalPlacedTextSymbolIndex:en}=Fe,_n=d.text.placedSymbolArray,$r=gr||Ht?1:0;Tr>=0&&(_n.get(Tr).hidden=$r),Hr>=0&&(_n.get(Hr).hidden=$r),sn>=0&&(_n.get(sn).hidden=$r),en>=0&&(_n.get(en).hidden=gr||Dt?1:0);const vn=this.variableOffsets[Qe];vn&&this.markUsedJustification(d,vn.anchor,Fe,Gt);const tn=this.placedOrientations[Qe];tn&&(this.markUsedJustification(d,"left",Fe,tn),this.markUsedOrientation(d,tn,Fe))}if(rr){const Lr=Ar?lh:tg(vt.icon),{placedIconSymbolIndex:gr,verticalPlacedIconSymbolIndex:Tr}=Fe,Hr=d.icon.placedSymbolArray,sn=vt.icon.isHidden()?1:0;gr>=0&&(ze(d.icon,xt,Ht?lh:Lr),Hr.get(gr).hidden=sn),Tr>=0&&(ze(d.icon,Fe.numVerticalIconVertices,Dt?lh:Lr),Hr.get(Tr).hidden=sn)}if(d.hasIconCollisionBoxData()||d.hasTextCollisionBoxData()){const Lr=d.collisionArrays[De];if(Lr){let gr=new s.P(0,0),Tr=!0;if(Lr.textBox||Lr.verticalTextBox){if(oe){const sn=this.variableOffsets[Qe];sn?(gr=ml(sn.anchor,sn.width,sn.height,sn.textOffset,sn.textScale),me&&gr._rotate(pe?this.transform.angle:-this.transform.angle)):Tr=!1}te&&(Tr=!vt.clipped),Lr.textBox&&bp(d.textCollisionBox.collisionVertexArray,vt.text.placed,!Tr||Ht,et,Re,gr.x,gr.y),Lr.verticalTextBox&&bp(d.textCollisionBox.collisionVertexArray,vt.text.placed,!Tr||Dt,et,Re,gr.x,gr.y)}const Hr=Tr&&!!(!Dt&&Lr.verticalIconBox);Lr.iconBox&&bp(d.iconCollisionBox.collisionVertexArray,vt.icon.placed,Hr,et,Re,Fe.hasIconTextFit?gr.x:0,Fe.hasIconTextFit?gr.y:0),Lr.verticalIconBox&&bp(d.iconCollisionBox.collisionVertexArray,vt.icon.placed,!Hr,et,Re,Fe.hasIconTextFit?gr.x:0,Fe.hasIconTextFit?gr.y:0)}}}if(d.fullyClipped=Ke===0,d.sortFeatures(this.transform.angle),this.retainedQueryData[d.bucketInstanceId]&&(this.retainedQueryData[d.bucketInstanceId].featureSortOrder=d.featureSortOrder),d.hasTextData()&&d.text.opacityVertexBuffer&&d.text.opacityVertexBuffer.updateData(d.text.opacityVertexArray),d.hasIconData()&&d.icon.opacityVertexBuffer&&d.icon.opacityVertexBuffer.updateData(d.icon.opacityVertexArray),d.hasIconCollisionBoxData()&&d.iconCollisionBox.collisionVertexBuffer&&d.iconCollisionBox.collisionVertexBuffer.updateData(d.iconCollisionBox.collisionVertexArray),d.hasTextCollisionBoxData()&&d.textCollisionBox.collisionVertexBuffer&&d.textCollisionBox.collisionVertexBuffer.updateData(d.textCollisionBox.collisionVertexArray),d.bucketInstanceId in this.collisionCircleArrays){const De=this.collisionCircleArrays[d.bucketInstanceId];d.placementInvProjMatrix=De.invProjMatrix,d.placementViewportMatrix=De.viewportMatrix,d.collisionCircleArray=De.circles,delete this.collisionCircleArrays[d.bucketInstanceId]}}symbolFadeChange(d){return this.fadeDuration===0?1:(d-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(d){return Math.max(0,(this.transform.zoom-d)/1.5)}hasTransitions(d){return d-this.lastPlacementChangeTimed}isStale(){return this.stale}setStale(){this.stale=!0}}function bp(v,d,g,w,A,I,L){v.emplaceBack(d?1:0,g?1:0,I||0,L||0,w,A?1:0),v.emplaceBack(d?1:0,g?1:0,I||0,L||0,w,A?1:0),v.emplaceBack(d?1:0,g?1:0,I||0,L||0,w,A?1:0),v.emplaceBack(d?1:0,g?1:0,I||0,L||0,w,A?1:0)}const wx=Math.pow(2,25),Sx=Math.pow(2,24),Ko=Math.pow(2,17),aa=Math.pow(2,16),m3=Math.pow(2,9),Tx=Math.pow(2,8),nT=Math.pow(2,1);function tg(v){if(v.opacity===0&&!v.placed)return 0;if(v.opacity===1&&v.placed)return 4294967295;const d=v.placed?1:0,g=Math.floor(127*v.opacity);return g*wx+d*Sx+g*Ko+d*aa+g*m3+d*Tx+g*nT+d}const lh=0;class iT{constructor(d){this._sortAcrossTiles=d.layout.get("symbol-z-order")!=="viewport-y"&&d.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(d,g,w,A,I,L){const F=this._bucketParts;for(;this._currentTileIndex$.sortKey-H.sortKey));this._currentPartIndex{const $=s.o.now()-L;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&$>2};for(;this._currentPlacementIndex>=0;){const $=g[d[this._currentPlacementIndex]],H=this.placement.collisionIndex.transform.zoom;if($.type==="symbol"&&$.visibility!=="none"&&(!$.minzoom||$.minzoom<=H)&&(!$.maxzoom||$.maxzoom>H)){const Y=$,te=Y.layout.get("symbol-z-elevate"),ee=Y.layout.get("symbol-sort-key").constantOr(1)!==void 0,ie=Y.layout.get("symbol-z-order"),le=ie==="viewport-y"||ie==="auto"&&!(ie!=="viewport-y"&&ee),oe=Y.layout.get("text-allow-overlap")||Y.layout.get("icon-allow-overlap")||Y.layout.get("text-ignore-placement")||Y.layout.get("icon-ignore-placement"),me=le&&oe,pe=this._inProgressLayer=this._inProgressLayer||new iT(Y),je=s.F($.source,$.scope);if(pe.continuePlacement(te||me?A[je]:w[je],this.placement,this._showCollisionBoxes,$,F,I))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(d){return this.placement.commit(d),this.placement}}const No=512/s.an/2;class au{constructor(d,g,w){this.tileID=d,this.bucketInstanceId=w,this.index=new s.bI(g.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const A=d.canonical.x*s.an,I=d.canonical.y*s.an;for(let L=0;Lme-pe);for(const me of oe){const pe=this.crossTileIDs[me];if(this.keys[me]===Y&&!w.has(pe)){w.add(pe),H.crossTileID=pe;break}}}}}class Nl{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class xj{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(d){const g=Math.round((d-this.lng)/360);if(g!==0)for(const w in this.indexes){const A=this.indexes[w],I={};for(const L in A){const F=A[L];F.tileID=F.tileID.unwrapTo(F.tileID.wrap+g),I[F.tileID.key]=F}this.indexes[w]=I}this.lng=d}addBucket(d,g,w){if(this.indexes[d.overscaledZ]&&this.indexes[d.overscaledZ][d.key]){if(this.indexes[d.overscaledZ][d.key].bucketInstanceId===g.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(d.overscaledZ,this.indexes[d.overscaledZ][d.key])}for(let I=0;Id.overscaledZ)for(const F in L){const $=L[F];$.tileID.isChildOf(d)&&$.findMatches(g.symbolInstances,d,A)}else{const F=L[d.scaledTo(Number(I)).key];F&&F.findMatches(g.symbolInstances,d,A)}}for(let I=0;I{g[w]=!0});for(const w in this.layerIndexes)g[w]||delete this.layerIndexes[w]}}const js=771;class Kr{constructor(d,g,w,A){this.blendFunction=d,this.blendColor=g.toNonPremultipliedRenderColor(null),this.mask=w,this.blendEquation=A}}Kr.Replace=[1,0,1,0],Kr.disabled=new Kr(Kr.Replace,s.aq.transparent,[!1,!1,!1,!1]),Kr.unblended=new Kr(Kr.Replace,s.aq.transparent,[!0,!0,!0,!0]),Kr.alphaBlended=new Kr([1,js,1,js],s.aq.transparent,[!0,!0,!0,!0]),Kr.alphaBlendedNonPremultiplied=new Kr([770,js,770,js],s.aq.transparent,[!0,!0,!0,!0]),Kr.multiply=new Kr([774,0,774,0],s.aq.transparent,[!0,!0,!0,!0]),Kr.multiplyAccumulateAlpha=new Kr([774,0,1,js],s.aq.transparent,[!0,!0,!0,!0]),Kr.additive=new Kr([1,1,1,1],s.aq.transparent,[!0,!0,!0,!0]);class Ir{constructor(d,g,w){this.func=d,this.mask=g,this.range=w}}Ir.ReadOnly=!1,Ir.ReadWrite=!0,Ir.disabled=new Ir(519,Ir.ReadOnly,[0,1]);const Zs=7680;class Qr{constructor(d,g,w,A,I,L){this.test=d,this.ref=g,this.mask=w,this.fail=A,this.depthFail=I,this.pass=L}}Qr.disabled=new Qr({func:519,mask:0},0,0,Zs,Zs,Zs);const bc=1029,wp=2305;class Gr{constructor(d,g,w){this.enable=d,this.mode=g,this.frontFace=w}}function Ax(v,d){const g=s.bO(v,3);s.bR(v,d),s.bW(v,3,g)}function av(v,d){const g=s.bL([]);return s.bM(g,g,-d),s.bN(g,g,-v),g}function ov(v,d){const g=[v[0],v[1],0],w=[d[0],d[1],0];if(s.ai(g)>=1e-15){const L=s.ay([],g);s.bJ(w,L,s.bi(w,L)),d[0]=w[0],d[1]=w[1]}const A=s.bh([],d,v);if(s.bK(A)<1e-15)return null;const I=Math.atan2(-A[1],A[0]);return av(Math.atan2(Math.sqrt(v[0]*v[0]+v[1]*v[1]),-v[2]),I)}Gr.disabled=new Gr(!1,bc,wp),Gr.backCCW=new Gr(!0,bc,wp),Gr.backCW=new Gr(!0,bc,2304),Gr.frontCW=new Gr(!0,1028,2304),Gr.frontCCW=new Gr(!0,1028,wp);class kx{constructor(d,g){this.position=d,this.orientation=g}get position(){return this._position}set position(d){if(d){const g=d instanceof s.ag?d:new s.ag(d[0],d[1],d[2]);this._renderWorldCopies&&(g.x=s.bs(g.x,0,1)),this._position=g}else this._position=null}lookAtPoint(d,g,w){if(this.orientation=null,!this.position)return;const A=this.position,I=w||(this._elevation?this._elevation.getAtPointOrZero(s.ag.fromLngLat(d)):0),L=s.ag.fromLngLat(d,I),F=[L.x-A.x,L.y-A.y,L.z-A.z];g||(g=[0,0,1]),g[2]=Math.abs(g[2]),this.orientation=ov(F,g)}setPitchBearing(d,g){this.orientation=av(s.ap(d),s.ap(-g))}}class Cx{constructor(d,g){this._transform=s.b9([]),this.orientation=g,this.position=d}get mercatorPosition(){const d=this.position;return new s.ag(d[0],d[1],d[2])}get position(){const d=s.bO(this._transform,3);return[d[0],d[1],d[2]]}set position(d){var g;d&&s.bW(this._transform,3,[(g=d)[0],g[1],g[2],1])}get orientation(){return this._orientation}set orientation(d){this._orientation=d||s.bL([]),d&&Ax(this._transform,this._orientation)}getPitchBearing(){const d=this.forward(),g=this.right();return{bearing:Math.atan2(-g[1],g[0]),pitch:Math.atan2(Math.sqrt(d[0]*d[0]+d[1]*d[1]),-d[2])}}setPitchBearing(d,g){this._orientation=av(d,g),Ax(this._transform,this._orientation)}forward(){const d=s.bO(this._transform,2);return[-d[0],-d[1],-d[2]]}up(){const d=s.bO(this._transform,1);return[-d[0],-d[1],-d[2]]}right(){const d=s.bO(this._transform,0);return[d[0],d[1],d[2]]}getCameraToWorld(d,g){const w=new Float64Array(16);return s.b7(w,this.getWorldToCamera(d,g)),w}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(d,g,w){const A=this.position;s.bJ(A,A,-d);const I=new Float64Array(16);return s.bP(I,[w,w,w]),s.bx(I,I,A),I[10]*=g,I}getWorldToCamera(d,g){const w=new Float64Array(16),A=new Float64Array(4),I=this.position;return s.bQ(A,this._orientation),s.bJ(I,I,-d),s.bR(w,A),s.bx(w,w,I),w[1]*=-1,w[5]*=-1,w[9]*=-1,w[13]*=-1,w[8]*=g,w[9]*=g,w[10]*=g,w[11]*=g,w}getCameraToClipPerspective(d,g,w,A){const I=new Float64Array(16);return s.bS(I,d,g,w,A),I}getCameraToClipOrthographic(d,g,w,A,I,L){const F=new Float64Array(16);return s.bT(F,d,g,w,A,I,L),F}getDistanceToElevation(d,g=!1){const w=d===0?0:s.bU(d,g?s.bV(this.position[1]):this.position[1]),A=this.forward();return(w-this.position[2])/A[2]}clone(){return new Cx([...this.position],[...this.orientation])}}const g3=(v,d)=>({u_matrix:v,u_ground_shadow_factor:d});class Lu{constructor(d=0,g=0,w=0,A=0){if(isNaN(d)||d<0||isNaN(g)||g<0||isNaN(w)||w<0||isNaN(A)||A<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=d,this.bottom=g,this.left=w,this.right=A}interpolate(d,g,w){return g.top!=null&&d.top!=null&&(this.top=s.am(d.top,g.top,w)),g.bottom!=null&&d.bottom!=null&&(this.bottom=s.am(d.bottom,g.bottom,w)),g.left!=null&&d.left!=null&&(this.left=s.am(d.left,g.left,w)),g.right!=null&&d.right!=null&&(this.right=s.am(d.right,g.right,w)),this}getCenter(d,g){const w=s.aC((this.left+d-this.right)/2,0,d),A=s.aC((this.top+g-this.bottom)/2,0,g);return new s.P(w,A)}equals(d){return this.top===d.top&&this.bottom===d.bottom&&this.left===d.left&&this.right===d.right}clone(){return new Lu(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const Sp=15;class jx{constructor(d,g,w,A,I,L,F){this.tileSize=512,this._renderWorldCopies=I===void 0||I,this._minZoom=d||0,this._maxZoom=g||22,this._minPitch=w??0,this._maxPitch=A??60,this.setProjection(L),this.setMaxBounds(F),this.width=0,this.height=0,this._center=new s.aU(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._nearZ=0,this._farZ=0,this._nearClipOffset=0,this._unmodified=!0,this._edgeInsets=new Lu,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new Cx,this._centerAltitude=0,this._averageElevation=0,this.cameraElevationReference="ground",this._pixelsPerMercatorPixel=1,this.globeRadius=0,this.globeCenterInViewSpace=[0,0,0],this._tileCoverLift=0,this.freezeTileCoverage=!1,this._horizonShift=.1,this._orthographicProjectionAtLowPitch=!1,this._allowWorldUnderZoom=!1}clone(){const d=new jx(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return d._elevation=this._elevation,d._centerAltitude=this._centerAltitude,d._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,d.tileSize=this.tileSize,d.mercatorFromTransition=this.mercatorFromTransition,d.width=this.width,d.height=this.height,d.cameraElevationReference=this.cameraElevationReference,d._center=this._center,d._setZoom(this.zoom),d._seaLevelZoom=this._seaLevelZoom,d.angle=this.angle,d._fov=this._fov,d._pitch=this._pitch,d._nearZ=this._nearZ,d._farZ=this._farZ,d._nearClipOffset=this._nearClipOffset,d._averageElevation=this._averageElevation,d._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,d._unmodified=this._unmodified,d._edgeInsets=this._edgeInsets.clone(),d._camera=this._camera.clone(),d._calcMatrices(),d.freezeTileCoverage=this.freezeTileCoverage,d.frustumCorners=this.frustumCorners,d._allowWorldUnderZoom=this._allowWorldUnderZoom,d}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||d===Number.NEGATIVE_INFINITY&&(!g||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const w=this._elevation;g||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&w.exaggeration()&&this._centerAltitudeValidForExaggeration!==w.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*w.exaggeration(),this._centerAltitudeValidForExaggeration=w.exaggeration()):(this._centerAltitude=d||0,this._centerAltitudeValidForExaggeration=w.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const d=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(d)}sampleAverageElevation(){if(!this._elevation)return 0;const d=this._elevation,g=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],w=this.horizonLineFromTop();let A=0,I=0;for(let L=0;L{const me=s.ck(ee,te,ie,le,oe);$.has(me)||(I.push(new s.aR(te,ee,ie,le,oe)),$.add(me))};for(let te=0;teee.canonical.z)continue;const ie=ee.canonical,le=ee.overscaledZ,oe=ee.wrap,me=1<0,Re=ie.y+10,Ze=ee.wrap-(je?0:1),ze=ee.wrap+(pe?0:1),Ke=je?ie.x-1:me-1,De=pe?ie.x+1:0;if(L)w[0]<0?(H(le,ze,ie.z,De,ie.y),w[1]<0&&Re&&(H(le,oe,ie.z,ie.x,ie.y+1),H(le,ze,ie.z,De,ie.y+1)),w[1]>0&&xe&&(H(le,oe,ie.z,ie.x,ie.y-1),H(le,ze,ie.z,De,ie.y-1))):w[0]>0?(H(le,Ze,ie.z,Ke,ie.y),w[1]<0&&Re&&(H(le,oe,ie.z,ie.x,ie.y+1),H(le,Ze,ie.z,Ke,ie.y+1)),w[1]>0&&xe&&(H(le,oe,ie.z,ie.x,ie.y-1),H(le,Ze,ie.z,Ke,ie.y-1))):w[1]<0&&Re?H(le,oe,ie.z,ie.x,ie.y+1):xe&&H(le,oe,ie.z,ie.x,ie.y-1);else{const Fe=ee.visibleQuadrants;1&Fe&&(H(le,Ze,ie.z,Ke,ie.y),xe&&(H(le,oe,ie.z,ie.x,ie.y-1),H(le,Ze,ie.z,Ke,ie.y-1))),2&Fe&&(H(le,ze,ie.z,De,ie.y),xe&&(H(le,oe,ie.z,ie.x,ie.y-1),H(le,ze,ie.z,De,ie.y-1))),4&Fe&&(H(le,Ze,ie.z,Ke,ie.y),Re&&(H(le,oe,ie.z,ie.x,ie.y+1),H(le,Ze,ie.z,Ke,ie.y+1))),8&Fe&&(H(le,ze,ie.z,De,ie.y),Re&&(H(le,oe,ie.z,ie.x,ie.y+1),H(le,ze,ie.z,De,ie.y+1)))}}const Y=[];for(const te of I)I.some(ee=>te.isChildOf(ee))||Y.push(te);if(I=Y.filter(te=>!d.some(ee=>!!(te.overscaledZ{const pe=me.canonical.x+.5-ie[0],je=me.canonical.y+.5-ie[1];return pe*pe+je*je{const Ke=s.ck(Re,je,xe,Ze,ze);I.has(Ke)||(A.push(new s.aR(je,Re,xe,Ze,ze)),I.add(Ke))},F=d.reduce((je,Re)=>Math.max(je,Re.overscaledZ),w),$=1<{const xe=Math.floor(je[0]),Ze=Math.floor(je[1]),ze=(je[0]-xe)*s.an,Ke=(je[1]-Ze)*s.an,De=Math.floor(Re[0]),Fe=Math.floor(Re[1]),qe=(Re[0]-De)*s.an,st=(Re[1]-Fe)*s.an;for(let Qe=-1;Qe<=1;Qe++){const xt=xe+Qe;if(!(xt<0||xt>=$)){Y.x=ze-Qe*s.an,te.x=qe-(xt-De)*s.an;for(let ft=-1;ft<=1;ft++){const Rt=Ze+ft;Y.y=Ke-ft*s.an,te.y=st-(Rt-Fe)*s.an,s.cI(Y,te,H)&&L(F,0,w,xt,Rt)}}}},ie=g.points,le=ie[s.c9],oe=ie[s.ca],me=this._projectToGround(le,ie[s.cb]),pe=this._projectToGround(oe,ie[s.cc]);return ee(le,me),ee(oe,pe),A}_projectToGround(d,g){return s.cd(s.ce(),d,g,d[2]/(d[2]-g[2]))}_projectToZ(d,g,w){const A=d[2]-g[2];return Math.abs(A)<1e-6?s.cf(d):s.cd(s.ce(),d,g,(d[2]-w)/A)}extendTileCoverForTunnels(d,g,w,A){if(w<18)return[];const I=g.points,L=I[s.cg],F=I[s.ch],$=I[s.ci],H=I[s.cj];if($[2]>=0&&H[2]>=0||L[2]<=0||F[2]<=0)return[];const Y=$[2]<0?this._projectToZ(L,$,0):$,te=H[2]<0?this._projectToZ(F,H,0):H,ee=-A,ie=$[2]3&&(oe.length=3),oe}_findExtensionTilesInQuad(d,g,w,A){const I=[],L=new Set;for(const De of d)L.add(De.key);const F=d.reduce((De,Fe)=>Math.max(De,Fe.overscaledZ),g),$=1<{const qe=De.canonical.x+.5-ze,st=De.canonical.y+.5-Ke,Qe=Fe.canonical.x+.5-ze,xt=Fe.canonical.y+.5-Ke;return qe*qe+st*st-(Qe*Qe+xt*xt)||De.canonical.x-Fe.canonical.x||De.canonical.y-Fe.canonical.y}),I}coveringTiles(d){let g=this.coveringZoomLevel(d);const w=g,A=this.elevation&&this.elevation.exaggeration(),I=A&&!d.isTerrainDEM,L=this.projection.name==="mercator";if(d.minzoom!==void 0&&gd.maxzoom&&(g=d.maxzoom);const F=this.locationCoordinate(this.center),$=this.center.lat,H=1<{const vt=new s.ag(et.x+25e-6,et.y,et.z),St=new s.ag(et.x,et.y+25e-6,et.z),rr=et.toLngLat(),Gt=vt.toLngLat(),Ht=St.toLngLat(),Dt=this.locationCoordinate(rr),Ar=this.locationCoordinate(Gt),Lr=this.locationCoordinate(Ht),gr=Math.hypot(Ar.x-Dt.x,Ar.y-Dt.y),Tr=Math.hypot(Lr.x-Dt.x,Lr.y-Dt.y);return Math.sqrt(gr*Tr)*Ke/25e-6},Fe=et=>{const gt=Ze,vt=ze;return{aabb:s.cp(this,H,0,0,0,et,vt,gt,this.projection),zoom:0,x:0,y:0,minZ:vt,maxZ:gt,wrap:et,fullyVisible:!1}},qe=[];let st=[];const Qe=g,xt=d.reparseOverscaled?w:g,ft=(me-this._centerAltitude)*oe,Rt=et=>{if(!this._elevation||!et.tileID||!L)return;const gt=this._elevation.getMinMaxForTile(et.tileID),vt=et.aabb;gt?(vt.min[2]=gt.min,vt.max[2]=gt.max,vt.center[2]=(vt.min[2]+vt.max[2])/2):(et.shouldSplit=ot(et),et.shouldSplit||(vt.min[2]=vt.max[2]=vt.center[2]=this._centerAltitude))},Ft=(et,gt)=>{if(.707*gt{if(et.zoom=.9)return!0}else if(I&&(St=et.aabb.distanceZ(pe)*oe),this.projection.isReprojectedInTileSpace&&w<=5){const Tr=Math.pow(2,et.zoom),Hr=De(new s.ag((et.x+.5)/Tr,(et.y+.5)/Tr));rr=Hr>.85?1:Hr}if(!L&&!te){const Tr=Math.sqrt(gt*gt+vt*vt+St*St);let Hr=(1<0;){const et=qe.pop(),gt=et.x,vt=et.y;let St=et.fullyVisible;const rr=()=>this.projection.name==="globe"&&(et.y===0||et.y===(1<Gt)continue;let Ht=0;if(!St){let gr=je?et.aabb.intersectsPrecise(ie):et.aabb.intersectsPreciseFlat(ie);if(gr===0&&rr()){const Tr=new s.cn(et.zoom,gt,vt);gr=s.co(this,H,Tr,!0).intersectsPrecise(ie)}if(gr===0)continue;if(d.calculateQuadrantVisibility)if(ie.containsPoint(et.aabb.center))Ht=15;else for(let Tr=0;Tr<4;Tr++)et.aabb.quadrant(Tr).intersects(ie)!==0&&(Ht|=1<>1),Ar={aabb:L?et.aabb.quadrant(Gt):s.cp(this,H,et.zoom+1,Ht,Dt,et.wrap,et.minZ,et.maxZ,this.projection),zoom:et.zoom+1,x:Ht,y:Dt,wrap:et.wrap,fullyVisible:St,tileID:void 0,shouldSplit:void 0,minZ:et.minZ,maxZ:et.maxZ};I&&!te&&(Ar.tileID=new s.aR(et.zoom+1===Qe?xt:et.zoom+1,et.wrap,et.zoom+1,Ht,Dt),Rt(Ar)),qe.push(Ar)}}if(this.fogCullDistSq){const et=this.fogCullDistSq,gt=this.horizonLineFromTop();st=st.filter(vt=>{const St=[0,0,0,1],rr=[s.an,s.an,0,1],Gt=this.calculateFogTileMatrix(vt.tileID.toUnwrapped());s.aE(St,St,Gt),s.aE(rr,rr,Gt);const Ht=s.cq([],St,rr),Dt=s.cr([],St,rr),Ar=s.cK(Ht,Dt);if(Ar===0)return!0;let Lr=!1;const gr=this._elevation;if(gr&&Ar>et&>!==0){const Tr=this.calculateProjMatrix(vt.tileID.toUnwrapped());let Hr;d.isTerrainDEM||(Hr=gr.getMinMaxForTile(vt.tileID)),Hr||(Hr={min:ze,max:Ze});const sn=s.cs(this.rotation),en=[sn[0]*s.an,sn[1]*s.an,Hr.max];s.ah(en,en,Tr),Lr=(1-en[1])*this.height*.5et.distanceSq-gt.distanceSq).map(et=>et.tileID)}resize(d,g){this.width=d,this.height=g,this.pixelsToGLUnits=[2/d,-2/g],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(d){return Math.pow(2,d)}scaleZoom(d){return Math.log2(d)}project(d){const g=s.aC(d.lat,-s.ct,s.ct),w=this.projection.project(d.lng,g);return new s.P(w.x*this.worldSize,w.y*this.worldSize)}unproject(d){return this.projection.unproject(d.x/this.worldSize,d.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/s.bU(1,this.center.lat)/this.worldSize}setLocationAtPoint(d,g){let w,A;const I=this.centerPoint;if(this.projection.name==="globe"){const F=this.worldSize;w=(g.x-I.x)/F,A=(g.y-I.y)/F}else{const F=this.pointCoordinate(g),$=this.pointCoordinate(I);w=F.x-$.x,A=F.y-$.y}const L=this.locationCoordinate(d);this.setLocation(new s.ag(L.x-w,L.y-A))}setLocation(d){this.center=this.coordinateLocation(d),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(d,g){return this.projection.locationPoint(this,d,g)}locationPoint3D(d,g){return this.projection.locationPoint(this,d,g,!0)}pointLocation(d){return this.coordinateLocation(this.pointCoordinate(d))}pointLocation3D(d,g){return this.coordinateLocation(this.pointCoordinate3D(d,g))}locationCoordinate(d,g){const w=g?s.bU(g,d.lat):void 0,A=this.projection.project(d.lng,d.lat);return new s.ag(A.x,A.y,w)}coordinateLocation(d){return this.projection.unproject(d.x,d.y)}pointRayIntersection(d,g){const w=g??this._centerAltitude,A=[d.x,d.y,0,1],I=[d.x,d.y,1,1];s.aE(A,A,this.pixelMatrixInverse),s.aE(I,I,this.pixelMatrixInverse);const L=I[3];s.cu(A,A,1/A[3]),s.cu(I,I,1/L);const F=A[2],$=I[2];return{p0:A,p1:I,t:F===$?0:(w-F)/($-F)}}screenPointToMercatorRay(d){const g=[d.x,d.y,0,1],w=[d.x,d.y,1,1];return s.aE(g,g,this.pixelMatrixInverse),s.aE(w,w,this.pixelMatrixInverse),s.cu(g,g,1/g[3]),s.cu(w,w,1/w[3]),g[2]=s.bU(g[2],this._center.lat)*this.worldSize,w[2]=s.bU(w[2],this._center.lat)*this.worldSize,s.cu(g,g,1/this.worldSize),s.cu(w,w,1/this.worldSize),new s.az([g[0],g[1],g[2]],s.ay([],s.ax([],w,g)))}rayIntersectionCoordinate(d){const{p0:g,p1:w,t:A}=d,I=s.bU(g[2],this._center.lat),L=s.bU(w[2],this._center.lat);return new s.ag(s.am(g[0],w[0],A)/this.worldSize,s.am(g[1],w[1],A)/this.worldSize,s.am(I,L,A))}pointCoordinate(d,g=this._centerAltitude){return this.projection.pointCoordinate(this,d.x,d.y,g)}pointCoordinate3D(d,g){if(!this.elevation)return this.pointCoordinate(d,g);let w=this.projection.pointCoordinate3D(this,d.x,d.y);if(w)return new s.ag(w[0],w[1],w[2]);let A=0,I=this.horizonLineFromTop();if(d.y>I)return this.pointCoordinate(d,g);const L=.02*I,F=d.clone();for(let $=0;$<10&&I-A>L;$++){F.y=s.am(A,I,.66);const H=this.projection.pointCoordinate3D(this,F.x,F.y);H?(I=F.y,w=H):A=F.y}return w?new s.ag(w[0],w[1],w[2]):this.pointCoordinate(d)}isPointAboveHorizon(d){return this.projection.isPointAboveHorizon(this,d)}isPointOnSurface(d){if(d.y<0||d.y>this.height||d.x<0||d.x>this.width)return!1;if(this.elevation||this.zoom>=s.cv)return!this.isPointAboveHorizon(d);const g=this.pointCoordinate(d);return g.y>=0&&g.y<=1}_coordinatePoint(d,g){const w=g&&this.elevation?this.elevation.getAtPointOrZero(d,this._centerAltitude):this._centerAltitude,A=[d.x*this.worldSize,d.y*this.worldSize,w+d.toAltitude(),1];return s.aE(A,A,this.pixelMatrix),A[3]>0?new s.P(A[0]/A[3],A[1]/A[3]):new s.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:d,left:g}=this._edgeInsets,w=this.height-this._edgeInsets.bottom,A=this.width-this._edgeInsets.right,I=this.pointLocation3D(new s.P(g,d)),L=this.pointLocation3D(new s.P(A,d)),F=this.pointLocation3D(new s.P(A,w)),$=this.pointLocation3D(new s.P(g,w));let H=Math.min(I.lng,L.lng,F.lng,$.lng),Y=Math.max(I.lng,L.lng,F.lng,$.lng),te=Math.min(I.lat,L.lat,F.lat,$.lat),ee=Math.max(I.lat,L.lat,F.lat,$.lat);const ie=Math.pow(2,-this.zoom)/16*270,le=this.projection.name==="globe"?1:4,oe=(me,pe,je,Re,xe)=>{const Ze=(me+je)/2,ze=(pe+Re)/2,Ke=new s.P(Ze,ze),{lng:De,lat:Fe}=this.pointLocation3D(Ke),qe=Math.max(0,H-De,te-Fe,De-Y,Fe-ee);H=Math.min(H,De),Y=Math.max(Y,De),te=Math.min(te,Fe),ee=Math.max(ee,Fe),(xeie)&&(oe(me,pe,Ze,ze,xe+1),oe(Ze,ze,je,Re,xe+1))};if(oe(g,d,A,d,1),oe(A,d,A,w,1),oe(A,w,g,w,1),oe(g,w,g,d,1),this.projection.name==="globe"){const[me,pe]=s.cw(this);me?(ee=90,Y=180,H=-180):pe&&(te=-90,Y=180,H=-180)}return new s.aK(new s.aU(H,te),new s.aU(Y,ee))}_getBoundsRectangular(d,g){const{top:w,left:A}=this._edgeInsets,I=this.height-this._edgeInsets.bottom,L=this.width-this._edgeInsets.right,F=new s.P(A,w),$=new s.P(L,w),H=new s.P(L,I),Y=new s.P(A,I);let te=this.pointCoordinate(F,d),ee=this.pointCoordinate($,d);const ie=this.pointCoordinate(H,g),le=this.pointCoordinate(Y,g),oe=(me,pe)=>(pe.y-me.y)/(pe.x-me.x);return te.y>1&&ee.y>=0?te=new s.ag((1-le.y)/oe(le,te)+le.x,1):te.y<0&&ee.y<=1&&(te=new s.ag(-le.y/oe(le,te)+le.x,0)),ee.y>1&&te.y>=0?ee=new s.ag((1-ie.y)/oe(ie,ee)+ie.x,1):ee.y<0&&te.y<=1&&(ee=new s.ag(-ie.y/oe(ie,ee)+ie.x,0)),new s.aK().extend(this.coordinateLocation(te)).extend(this.coordinateLocation(ee)).extend(this.coordinateLocation(le)).extend(this.coordinateLocation(ie))}_getBoundsRectangularTerrain(){const d=this.elevation;if(!d.visibleDemTiles.length||d.isUsingMockSource())return this._getBoundsRectangular(0,0);const g=d.visibleDemTiles.reduce((w,A)=>{if(A.dem){const I=A.dem.tree;w.min=Math.min(w.min,I.minimums[0]),w.max=Math.max(w.max,I.maximums[0])}return w},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(g.min*d.exaggeration(),g.max*d.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(d=!0){const g=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,w=this.height/2-g*(1-this._horizonShift);return d?Math.max(0,w):w}getMaxBounds(){return this.maxBounds}setMaxBounds(d){this.maxBounds=d,this.minLat=-s.ct,this.maxLat=s.ct,this.minLng=-180,this.maxLng=180,d&&(this.minLat=d.getSouth(),this.maxLat=d.getNorth(),this.minLng=d.getWest(),this.maxLng=d.getEast(),this.maxLngte&&(F=te-H),te-Yie&&(L=ie-$),ie-ee{for(let ot=0;ot<16;ot++)xt[ot]=s.am(ft[ot],Rt[ot],Ft)})(F,F,$,s.cL(this.pitch>=Sp?1:this.pitch/Sp))}else F=$;const H=s.cz([],$,L);let Y=s.cz([],F,L);if(this.projection.isReprojectedInTileSpace){const Fe=this.locationCoordinate(this.center),qe=s.b9([]);s.bx(qe,qe,[Fe.x*this.worldSize,Fe.y*this.worldSize,0]),s.aD(qe,qe,s.cA(this)),s.bx(qe,qe,[-Fe.x*this.worldSize,-Fe.y*this.worldSize,0]),s.aD(Y,Y,qe),s.aD(H,H,qe),this.inverseAdjustmentMatrix=s.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=s.cC([],Y,[this.worldSize,this.worldSize,this.worldSize/I,1]),this.projMatrix=Y,this.invProjMatrix=s.b7(new Float64Array(16),this.projMatrix),g){const Fe=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);Fe[8]=2*-d.x/this.width,Fe[9]=2*d.y/this.height,this.expandedFarZProjMatrix=s.cz([],Fe,L)}else this.expandedFarZProjMatrix=this.projMatrix;const te=s.b7([],F);this.frustumCorners=s.cD.fromInvProjectionMatrix(te,this.horizonLineFromTop(),this.height),this.cameraFrustum=s.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!g);const ee=new Float32Array(16);s.b9(ee),s.cC(ee,ee,[1,-1,1]),s.cE(ee,ee,this._pitch),s.ba(ee,ee,this.angle);const ie=s.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=s.b8(ie);const le=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;ie[8]=2*-d.x/this.width,ie[9]=2*(d.y+le)/this.height,this.skyboxMatrix=s.aD(ee,ie,ee);const oe=this.point,me=oe.x,pe=oe.y,je=this.width%2/2,Re=this.height%2/2,xe=Math.cos(this.angle),Ze=Math.sin(this.angle),ze=me-Math.round(me)+xe*je+Ze*Re,Ke=pe-Math.round(pe)+xe*Re+Ze*je,De=new Float64Array(Y);if(s.bx(De,De,[ze>.5?ze-1:ze,Ke>.5?Ke-1:Ke,0]),this.alignedProjMatrix=De,Y=s.bb(),s.cC(Y,Y,[this.width/2,-this.height/2,1]),s.bx(Y,Y,[1,-1,0]),this.labelPlaneMatrix=Y,Y=s.bb(),s.cC(Y,Y,[1,-1,1]),s.bx(Y,Y,[-1,-1,0]),s.cC(Y,Y,[2/this.width,2/this.height,1]),this.glCoordMatrix=Y,this.pixelMatrix=s.aD(new Float64Array(16),this.labelPlaneMatrix,H),this._calcFogMatrices(),this._distanceTileDataCache={},Y=s.b7(new Float64Array(16),this.pixelMatrix),!Y)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=Y,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=s.cF(this);const Fe=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=s.ah(Fe,Fe,L),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=Y;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const d=this.cameraWorldSizeForFog,g=this.cameraPixelsPerMeter,w=this._camera.position,A=1/this.height/this._pixelsPerMercatorPixel,I=[d,d,g];s.bJ(I,I,A),s.bJ(w,w,-1),s.cG(w,w,I);const L=s.bb();s.bx(L,L,w),s.cC(L,L,I),this.mercatorFogMatrix=L,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(d,g,A)}_computeCameraPosition(d){const g=(d=d||this.pixelsPerMeter)/this.pixelsPerMeter,w=this._camera.forward(),A=this.point,I=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*g-d/this.worldSize*this._centerAltitude;return[A.x/this.worldSize-w[0]*I,A.y/this.worldSize-w[1]*I,d/this.worldSize*this._centerAltitude-w[2]*I]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(d){const g=this._maxCameraBoundsDistance()*Math.cos(this._pitch),w=this._camera.position[2],A=d[2];let I=1;this.projection.wrap&&(this.center=this.center.wrap()),A>0&&(I=Math.min((g-w)/A,1)),this._camera.position=s.bg([],this._camera.position,d,I),this._updateStateFromCamera()}_updateStateFromCamera(){const d=this._camera.position,g=this._camera.forward(),{pitch:w,bearing:A}=this._camera.getPitchBearing(),I=s.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,L=this._mercatorZfromZoom(this._maxZoom)*Math.cos(s.ap(this._maxPitch)),F=Math.max((d[2]-I)/Math.cos(w),L),$=this._zoomFromMercatorZ(F);s.bg(d,d,g,F),this._pitch=s.aC(w,s.ap(this.minPitch),s.ap(this.maxPitch)),this.angle=s.bs(A,-Math.PI,Math.PI),this._setZoom(s.aC($,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new s.ag(d[0],d[1],d[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(d){return Math.pow(2,d)*this.tileSize}_mercatorZfromZoom(d){return this.cameraToCenterDistance/this._worldSizeFromZoom(d)}_minimumHeightOverTerrain(){const d=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(d)}_zoomFromMercatorZ(d){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,d)*this.tileSize))}zoomFromMercatorZAdjusted(d){let g=0,w=s.cv,A=0,I=1/0;for(;w-g>1e-6&&w>g;){const L=g+.5*(w-g),F=this.tileSize*Math.pow(2,L),$=this.getCameraToCenterDistance(this.projection,L,F),H=this.scaleZoom($/(Math.max(0,d)*this.tileSize)),Y=Math.abs(L-H);YH||ee.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+s.cH(this.fovAboveCenter)>88||this.anyCornerOffEdge(new s.P(0,0),new s.P(this.width,this.height))}zoomDeltaToMovement(d,g){const w=s.ai(s.ax([],this._camera.position,d)),A=this._zoomFromMercatorZ(w)+g;return w-this._mercatorZfromZoom(A)}getCameraPoint(){if(this.projection.name==="globe"){const d=function([g,w,A],I){const L=[g,w,A,1];s.aE(L,L,I);const F=L[3]=Math.max(L[3],1e-6);return L[0]/=F,L[1]/=F,L[2]/=F,L}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new s.P(d[0],d[1])}{const d=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new s.P(0,d))}}getCameraToCenterDistance(d,g=this.zoom,w=this.worldSize){const A=s.cy(d,g,this.width,this.height,1024),I=d.pixelSpaceConversion(this.center.lat,w,A);let L=.5/Math.tan(.5*this._fov)*this.height*I;return this.isOrthographic&&(L=s.am(1,L,s.cL(this.pitch>=Sp?1:this.pitch/Sp))),L}getWorldToCameraMatrix(){const d=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&s.aD(d,d,this.globeMatrix),d}getFrustum(d){return s.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,d,this.projection.zAxisUnit==="meters")}}const Pa=(v,d)=>{if(d>0&&v.terrain&&s.w("Cutoff is currently disabled on terrain"),d<=0||v.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const g=v.transform,w=g.pitch,A=g.isLODDisabled(!1)?60:30;if(w0,uniformValues:{u_cutoff_params:[g._nearZ,g._farZ,(Y-g._nearZ)/I,(Y-ee-g._nearZ)/I]}}},lf=2048;class lv{constructor(d,g){this.aabb=d,this.lastCascade=g}}class _j{add(d,g){const w=this.receivers[d.key];w!==void 0?(w.aabb.min[0]=Math.min(w.aabb.min[0],g.min[0]),w.aabb.min[1]=Math.min(w.aabb.min[1],g.min[1]),w.aabb.min[2]=Math.min(w.aabb.min[2],g.min[2]),w.aabb.max[0]=Math.max(w.aabb.max[0],g.max[0]),w.aabb.max[1]=Math.max(w.aabb.max[1],g.max[1]),w.aabb.max[2]=Math.max(w.aabb.max[2],g.max[2])):this.receivers[d.key]=new lv(g,null)}clear(){this.receivers={}}get(d){return this.receivers[d.key]}computeRequiredCascades(d,g,w){const A=s.cU.fromPoints(d.points);let I=0;for(const L in this.receivers){const F=this.receivers[L];if(!F||!A.intersectsAabb(F.aabb))continue;F.aabb.min=A.closestPoint(F.aabb.min),F.aabb.max=A.closestPoint(F.aabb.max);const $=F.aabb.getCorners();for(let H=0;H1||ee[1]<-1||ee[1]>1){Y=!1;break}}if(F.lastCascade=H,I=Math.max(I,H),Y)break}}return I+1}}class Ix{constructor(d){this.painter=d,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new _j,this._depthMode=new Ir(d.context.gl.LEQUAL,Ir.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.useNormalOffset=!1}destroy(){for(const d of this._cascades)d.texture.destroy(),d.framebuffer.destroy();this._cascades=[]}updateShadowParameters(d,g){const w=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!g||!g.properties)return;const A=g.properties.get("shadow-intensity"),I=g.properties.get("shadow-draw-before-layer");if(!g.shadowsEnabled()||A<=0)return;let L=-1,F=0;for(const pe of w.style.order){const je=w.style._mergedLayers[pe];je.hasShadowPass()&&!je.isHidden(d.zoom)&&(L=F),!I||I!==pe&&I!==je.slot||(this._drawShadowAfterLayer=F>0?F-1:0),F+=1}if(this._enabled=L>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=L);const $=w.context,H=lf,Y=lf;if(this._cascades.length===0||lf!==this._cascades[0].texture.size[0]){this._cascades=[];for(let pe=0;pe<2;++pe){const je=$.gl,Re=$.createFramebuffer(H,Y,0,"texture"),xe=new s.T($,{width:H,height:Y,data:null},je.DEPTH_COMPONENT16);Re.depthAttachment.set(xe.texture),this._cascades.push({framebuffer:Re,texture:xe,matrix:[],far:0,boundingSphereRadius:0,frustum:new s.cl,scale:0})}}this.shadowDirection=vj(g);let te=0;if(d.elevation){const pe=d.elevation,je=[1e4,-1e4];pe.visibleDemTiles.filter(Re=>Re.dem).forEach(Re=>{const xe=Re.dem.tree;je[0]=Math.min(je[0],xe.minimums[0]),je[1]=Math.max(je[1],xe.maximums[0])}),je[0]!==1e4&&(te=(je[1]-je[0])*pe.exaggeration())}const ee=1.5*d.cameraToCenterDistance,ie=3*ee,le=new Float64Array(16);for(let pe=0;pe=0)return{};const I=function($,H,Y){const te=Y/(1<<$.canonical.z);return new s.cU([$.canonical.x*te+$.wrap*Y,$.canonical.y*te+$.wrap*Y,0],[($.canonical.x+1)*te+$.wrap*Y,($.canonical.y+1)*te+$.wrap*Y,H])}(d,g,w).getCorners(),L=g/-A[2];A[0]<0?(s.cT(I[0],I[0],[A[0]*L,0,0]),s.cT(I[3],I[3],[A[0]*L,0,0])):A[0]>0&&(s.cT(I[1],I[1],[A[0]*L,0,0]),s.cT(I[2],I[2],[A[0]*L,0,0])),A[1]<0?(s.cT(I[0],I[0],[0,A[1]*L,0]),s.cT(I[1],I[1],[0,A[1]*L,0])):A[1]>0&&(s.cT(I[2],I[2],[0,A[1]*L,0]),s.cT(I[3],I[3],[0,A[1]*L,0]));const F={};return F.vertices=I,F.planes=[cv(I[1],I[0],I[4]),cv(I[2],I[1],I[5]),cv(I[3],I[2],I[6]),cv(I[0],I[3],I[7])],F}addShadowReceiver(d,g,w){this._receivers.add(d,s.cU.fromTileIdAndHeight(d,g,w))}getMaxCascadeForTile(d){const g=this._receivers.get(d);return g&&g.lastCascade?g.lastCascade:0}}function cv(v,d,g){const w=s.ax([],g,d),A=s.ax([],v,d),I=s.bh([],w,A),L=s.ai(I);return L===0?[0,0,1,0]:(s.bJ(I,I,1/L),[I[0],I[1],I[2],-s.bi(I,d)])}function vj(v){const d=v.properties.get("direction"),g=s.cP(d.x,d.y,d.z);g[2]=s.aC(g[2],0,75);const w=s.cR([g[0],g[1],g[2]]);return s.cQ(w.x,w.y,w.z)}function Du(v,d,g){const w=d.properties.get("color-use-theme")==="none",A=d.properties.get("color"),I=d.properties.get("intensity"),L=d.properties.get("direction"),F=[L.x,L.y,L.z],$=g.properties.get("color-use-theme")==="none",H=g.properties.get("color"),Y=g.properties.get("intensity"),te=Math.max(s.bi([0,0,1],F),0),ee=[0,0,0];s.bJ(ee,H.toPremultipliedRenderColor($?null:v.getLut(d.scope)).toArray01Linear().slice(0,3),Y);const ie=[0,0,0];return s.bJ(ie,A.toPremultipliedRenderColor(w?null:v.getLut(g.scope)).toArray01Linear().slice(0,3),te*I),s.cW([ee[0]>0?ee[0]/(ee[0]+ie[0]):0,ee[1]>0?ee[1]/(ee[1]+ie[1]):0,ee[2]>0?ee[2]/(ee[2]+ie[2]):0])}function Px(v,d,g,w,A,I){const L=v.zoom,F=v.scale,$=v.worldSize,H=1/$,Y=v.aspect,te=Math.sqrt(1+Y*Y)*Math.tan(.5*v.fovX),ee=te*te,ie=w-g,le=w+g;let oe,me;ee>ie/le?(oe=w,me=w*te):(oe=.5*le*(1+ee),me=.5*Math.sqrt(ie*ie+2*(w*w+g*g)*ee+le*le*ee*ee));const pe=v.projection.pixelsPerMeter(v.center.lat,$),je=v._camera.getCameraToWorldMercator(),Re=[0,0,-oe*H];s.ah(Re,Re,je);let xe=me*H;const Ze=function(St){return St[0]/=F,St[1]/=F,St[2]=s.bU(St[2],v._center.lat),St},ze=v._edgeInsets;if(!(ze.left===0&&ze.top===0&&ze.right===0&&ze.bottom===0||ze.left===ze.right&&ze.top===ze.bottom)){const St=v._camera.getWorldToCamera(v.worldSize,v.projection.zAxisUnit==="meters"?pe:1),rr=v._camera.getCameraToClipPerspective(v._fov,v.width/v.height,g,w);rr[8]=2*-v.centerOffset.x/v.width,rr[9]=2*v.centerOffset.y/v.height;const Gt=new Float64Array(16);s.cz(Gt,rr,St);const Ht=new Float64Array(16);s.b7(Ht,Gt);const Dt=s.cl.fromInvProjectionMatrix(Ht,$,L,!0);for(const Ar of Dt.points){const Lr=Ze(Ar);xe=Math.max(xe,s.bK(s.cV([],Re,Lr)))}}xe*=A/(A-1);const Ke=Math.acos(d[2]),De=Math.atan2(-d[0],-d[1]),Fe=new Cx;Fe.position=Re,Fe.setPitchBearing(Ke,De);const qe=Fe.getWorldToCamera($,pe),st=xe*$,Qe=Math.min(v._mercatorZfromZoom(17)*$*-2,-2*st),xt=Fe.getCameraToClipOrthographic(-st,st,-st,st,Qe,(st+I*pe)/d[2]),ft=new Float64Array(16);s.aD(ft,xt,qe);const Rt=s.cQ(Math.floor(1e6*Re[0])/1e6*$,Math.floor(1e6*Re[1])/1e6*$,0),Ft=.5*A,ot=[0,0,0];s.ah(ot,Rt,ft),s.bJ(ot,ot,Ft);const et=[Math.floor(ot[0]),Math.floor(ot[1]),Math.floor(ot[2])],gt=[0,0,0];s.ax(gt,ot,et),s.bJ(gt,gt,-1/Ft);const vt=new Float64Array(16);return s.b9(vt),s.bx(vt,vt,gt),s.aD(ft,vt,ft),[ft,st]}class y3 extends s.E{constructor(d){super(),this.requestManager=d,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(d,g){return s.cX(this.requestManager.transformRequest(g,s.R.Model).url).then(w=>{const A=s.cY(w),I=new s.cZ(d,g,void 0,void 0,A);return I.computeBoundsAndApplyParent(),I}).catch(w=>{if(w&&w.status===404)return null;this.fire(new s.B(new Error(`Could not load model ${d} from ${g}: ${w.message}`)))})}load(d,g,w={forceReload:!1}){this.models[g]||(this.models[g]={});const A=Object.keys(d),I=[],L=[];for(const F of A){const $=d[F];this.hasURLBeenRequested($)&&!w.forceReload||(this.modelByURL[$]={modelId:F,scope:g},I.push(this.loadModel(F,$)),L.push(F)),this.models[g][F]||(this.models[g][F]={model:null,numReferences:1})}this.numModelsLoading[g]=(this.numModelsLoading[g]||0)+L.length,Promise.allSettled(I).then(F=>{for(let $=0;${this.fire(new s.B(new Error(`Could not load models: ${F.message}`)))})}isLoaded(){for(const d in this.numModelsLoading)if(this.numModelsLoading[d]>0)return!1;return!0}hasModel(d,g,w={exactIdMatch:!1}){return!!(w.exactIdMatch?this.getModel(d,g):this.getModelByURL(this.modelUris[g][d]))}getModel(d,g){return this.models[g]||(this.models[g]={}),this.models[g][d]?this.models[g][d].model:void 0}getModelByURL(d){if(!d)return null;const g=this.modelByURL[d];return g?this.models[g.scope][g.modelId].model:null}hasModelBeenAdded(d,g){return this.models[g]&&this.models[g][d]!==void 0}getModelURIs(d){return this.modelUris[d]||{}}addModel(d,g,w){this.models[w]||(this.models[w]={}),this.modelUris[w]||(this.modelUris[w]={});const A=this.requestManager.normalizeModelURL(g);if((this.hasModel(d,w,{exactIdMatch:!0})||this.hasModelBeenAdded(d,w))&&this.modelUris[w][d]===A)this.models[w][d].numReferences++;else if(this.hasURLBeenRequested(A)){const{scope:I,modelId:L}=this.modelByURL[A];this.models[I][L].numReferences++}else this.modelUris[w][d]=A,this.load({[d]:this.modelUris[w][d]},w)}addModelURLs(d,g){this.models[g]||(this.models[g]={}),this.modelUris[g]||(this.modelUris[g]={});const w=this.modelUris[g];for(const A in d)w[A]=this.requestManager.normalizeModelURL(d[A])}reloadModels(d){this.load(this.modelUris[d],d,{forceReload:!0})}addModelsFromBucket(d,g){this.models[g]||(this.models[g]={}),this.modelUris[g]||(this.modelUris[g]={});const w={};for(const A of d)this.hasModel(A,g,{exactIdMatch:!0})||this.hasURLBeenRequested(A)?this.models[g][A].numReferences++:this.modelUris[g][A]&&!this.hasURLBeenRequested(A)?w[A]=this.modelUris[g][A]:!this.hasURLBeenRequested(A)&&s.c_(A,!1)&&(this.modelUris[g][A]=this.requestManager.normalizeModelURL(A),w[A]=this.modelUris[g][A]);this.load(w,g)}hasURLBeenRequested(d){return this.modelByURL[d]!==void 0}removeModel(d,g,w=!1,A=!1){if(this.models[g]&&this.models[g][d]&&(this.models[g][d].numReferences--,this.models[g][d].numReferences===0||A)){const I=this.modelUris[g][d];w||delete this.modelUris[g][d],delete this.modelByURL[I];const L=this.models[g][d].model;if(!L)return;delete this.models[g][d],L.destroy()}}destroy(){for(const d of Object.keys(this.models))for(const g of Object.keys(this.models[d])){const w=this.models[d][g].model;delete this.models[d][g],w&&w.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(d){return this.models[d]||(this.models[d]={}),Object.keys(this.models[d])}upload(d,g){this.models[g]||(this.models[g]={});for(const w in this.models[g])this.models[g][w].model&&this.models[g][w].model.upload(d.context)}}const sT=s.a8.colorTheme,ng=new s.ab({data:new s.ac(sT.data)});function bj(v){if(!v.metadata||!v.metadata.content_area)return;const d=s.o.devicePixelRatio,{left:g,top:w,width:A,height:I}=v.metadata.content_area,L=g*d,F=w*d;return[L,F,L+A*d,F+I*d]}function Nx(v){if(v)return v.map(([d,g])=>[d*s.o.devicePixelRatio,g*s.o.devicePixelRatio])}class aT{constructor(d,g,w){this.id=d,this.scope=g,this.sourceCache=w,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(d){this.missingRequests.has(d.name)||this.pendingRequests.has(d.name)||this.pendingRequests.add(d.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const d=new Map;if(!this.sourceCache.loaded())return d;const g=this.sourceCache.getVisibleCoordinates();if(g.length===0)return d;const w=this.sourceCache.getSource();if(!(w instanceof yp))return d;const A=g.map(L=>this.sourceCache.getTile(L)),I=w.getImages(A,Array.from(this.pendingRequests));for(const[L,F]of I)d.set(s.I.from({name:L,iconsetId:this.id}),F),this.pendingRequests.delete(L);for(const L of this.pendingRequests)this.missingRequests.add(L);return this.pendingRequests.clear(),d}}class cf{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(d,g,w,A,I){if(w$*this._hysteresisRatio&&(L=this._previousClosestBuildingId):H&&!L&&(L=this._previousClosestBuildingId),this._previousClosestBuildingId=L,L}_calculateDistance(d,g){if(!g.center)return Number.MAX_VALUE;const w=d.lat-g.center[1],A=d.lng-g.center[0];return w*w+A*A}_isBuildingVisible(d,g,w){if(!w)return!1;for(const A of d.floorIds){const I=d.floors[A];if(!I.geometry)continue;const L=I.geometry;if(L.type==="Polygon"){const F=this._convertRingToPoints(L.coordinates[0]);if(s.bw(F,w))return!0}else if(L.type==="MultiPolygon"){const F=this._convertMultiPolygonToPoints(L.coordinates);if(s.d0(w,F))return!0}}return!1}_convertRingToPoints(d){return d.map(g=>new s.P(g[0],g[1]))}_convertMultiPolygonToPoints(d){return d.map(g=>g.length===0?[]:g[0].map(w=>new s.P(w[0],w[1])))}}class x3 extends s.E{constructor(d){super(),this._style=d,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new cf,this._initialLoadDone=!1,s.aZ(["_updateUI"],this),this._style.on("style.load",()=>{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))})}destroy(){this._buildings={},this._activeFloors=new Set,this._indoorState=null}selectFloor(d){d===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=d,this._recalculateActiveFloors())}setActiveFloorsVisibility(d){this._updateActiveFloors(d),this._updateIndoorSelector()}setIndoorData(d){let g=!1;for(const[w,A]of Object.entries(d.buildings))if(this._buildings[w])for(const I of A.floorIds)this._buildings[w].floorIds.add(I),this._buildings[w].floors[I]?this._mergeFloors(this._buildings[w].floors[I],A.floors[I]):(this._buildings[w].floors[I]=A.floors[I],g=!0);else this._buildings[w]=A,g=!0;g&&this._recalculateActiveFloors()}getIndoorTileOptions(d,g){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(d,g),indoorState:this._indoorState}:null}getControlState(){const d=this._buildings,g=this._closestBuildingId,w=g&&d?d[g]:void 0;if(!w)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let A=null;for(const L of w.floorIds)if(this._activeFloors&&this._activeFloors.has(L)){A=L;break}const I=Array.from(w.floorIds).map(L=>({id:L,name:w.floors[L].name,zIndex:w.floors[L].zIndex})).sort((L,F)=>F.zIndex-L.zIndex).filter((L,F,$)=>F===0||L.zIndex!==$[F-1].zIndex);return{selectedFloorId:A,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:I}}_updateUI(){this._initialLoadDone=!0;const d=this._style.map.transform,g=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,d.center,d.zoom,d.getBounds(),this._makeViewportPolygon());if(g!==this._closestBuildingId){const w=this._closestBuildingId;this._closestBuildingId=g,this._onBuildingTransition(w,g),this._updateIndoorSelector()}}_onBuildingTransition(d,g){if(!this._indoorState)return;!g&&d?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!g&&!d&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new s.C("selector-update",this.getControlState()))}_updateActiveFloors(d){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:d,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const d=s.d1.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(g,w){if(g===w)return!0;if(!g||!w||g.size!==w.size)return!1;for(const A of g)if(!w.has(A))return!1;return!0})(d,this._activeFloors)||(this._activeFloors=d,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(d,g){g.geometry&&(d.geometry?(d.geometry.type==="Polygon"&&(d.geometry={type:"MultiPolygon",coordinates:[d.geometry.coordinates]}),g.geometry.type==="Polygon"?d.geometry.coordinates.push(g.geometry.coordinates):g.geometry.type==="MultiPolygon"&&d.geometry.coordinates.push(...g.geometry.coordinates)):d.geometry=g.geometry)}_makeViewportPolygon(){const d=this._style.map.transform,g=d.width,w=d.height;return[d.pointLocation(new s.P(0,0)),d.pointLocation(new s.P(g,0)),d.pointLocation(new s.P(g,w)),d.pointLocation(new s.P(0,w))].map(A=>new s.P(A.lng,A.lat))}}const Tp=(v,d)=>fr(v,d&&d.filter(g=>g.identifier!=="source.canvas")),_3=s.aJ(Xn,["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"]),wj=s.aJ(Xn,["setCenter","setZoom","setBearing","setPitch"]),oT=new Set(["background","sky","slot","custom"]),uv={version:8,layers:[],sources:{}},lT={duration:300,delay:0};class ou extends s.E{constructor(d,g={}){if(super(),this.map=d,this.scope=g.scope||"",this.globalId=null,this.fragments=[],this.importDepth=g.importDepth||0,this.importsCache=g.importsCache||new Map,this.resolvedImports=g.resolvedImports||new Set,this.transition=Object.assign({},lT),this._buildingIndex=new _x(this),this.crossTileSymbolIndex=new rg,this._mergedOrder=[],this._drapedFirstOrder=[],this._mergedLayers={},this._mergedIndoor={},this._mergedSourceCaches={},this._mergedOtherSourceCaches={},this._mergedSymbolSourceCaches={},this._mergedFillExtrusionSourceCaches={},this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=g.styleChanges||new yn,this._hasDataDrivenEmissive=!1,this.indoorManager=new x3(this),this.dispatcher=g.dispatcher?g.dispatcher:new hr(Nn(),this),this.map.painter&&this.map.painter.context){const A=this.map.painter.context.maxUniformBufferBindings,I=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:A,maxUniformBlockSizeDwords:I,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}g.imageManager?this.imageManager=g.imageManager:(this.imageManager=new ai(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=g.glyphManager?g.glyphManager:new s.d2(d._requestManager,g.localFontFamily?s.d3.all:g.localIdeographFontFamily?s.d3.ideographs:s.d3.none,g.localFontFamily||g.localIdeographFontFamily,g.useServerFontComposition),g.modelManager?this.modelManager=g.modelManager:(this.modelManager=new y3(d._requestManager),this.modelManager.setEventedParent(this)),this._layers={},this._sourceCaches={},this._otherSourceCaches={},this._symbolSourceCaches={},this._fillExtrusionSourceCaches={},this._loaded=!1,this._precompileDone=!1,this._shouldPrecompile=!1,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=g.configOptions?g.configOptions:new Map,this._configDependentLayers=g.configDependentLayers?g.configDependentLayers:new Set,this._indoorDependentLayers=g.indoorDependentLayers?g.indoorDependentLayers:new Set,this._config=g.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:g.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=g.initialConfig,this.dispatcher.broadcast("setReferrer",s.d4()),this.dispatcher.broadcast("setConfig",s.d5());const w=this;this._rtlTextPluginCallback=ou.registerForPluginStateChange(A=>{w.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:A.pluginStatus,pluginURL:A.pluginURL},(I,L)=>{if(s.d6(I),L&&L.every(F=>F))for(const F in w._sourceCaches){const $=w._sourceCaches[F],H=$.getSource().type;H!=="vector"&&H!=="geojson"||$.reload()}})}),this.on("data",A=>{if(A.dataType!=="source"||A.sourceDataType!=="metadata")return;const I=this.getOwnSource(A.sourceId);if(I&&I.vectorLayerIds)for(const L in this._layers){const F=this._layers[L];F.source===I.id&&this._validateLayer(F)}})}load(d){return d?(typeof d=="string"?this.loadURL(d):this.loadJSON(d),this):this}_getGlobalId(d){if(!d)return null;if(typeof d=="string"){if(s.e(d))return d;const g=s.d7(d);if(!g.startsWith("http"))try{return new URL(g,location.href).toString()}catch{return g}return g}return`json://${s.d8(JSON.stringify(d))}`}_diffStyle(d,g,w){this.globalId=this._getGlobalId(d);const A=(I,L)=>{try{L(null,this.setState(I,w))}catch(F){L(F,!1)}};if(typeof d=="string"){const I=this.map._requestManager.normalizeStyleURL(d),L=this.map._requestManager.transformRequest(I,s.R.Style);s.m(L,(F,$)=>{F?this.fire(new s.B(F)):$&&A($,g)})}else typeof d=="object"&&A(d,g)}loadURL(d,g={}){this.fire(new s.C("dataloading",{dataType:"style"}));const w=typeof g.validate=="boolean"?g.validate:!s.e(d);this.globalId=this._getGlobalId(d),d=this.map._requestManager.normalizeStyleURL(d,g.accessToken),this.resolvedImports.add(d);const A=this.importsCache.get(d);if(A)return this._load(A,w);const I=this.map._requestManager.transformRequest(d,s.R.Style);this._request=s.m(I,(L,F)=>{if(this._request=null,L)this.fire(new s.B(L));else if(F)return this.importsCache.set(d,F),this._load(F,w)})}loadJSON(d,g={}){this.fire(new s.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(d),this._request=s.o.frame(()=>{this._request=null,this._load(d,g.validate!==!1)})}loadEmpty(){this.fire(new s.C("dataloading",{dataType:"style"})),this._load(uv,!1)}_loadImports(d,g,w){if(this.importDepth>=4)return s.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const A=[];for(const I of d){const L=this._createFragmentStyle(I),F=new Promise(Y=>{L.once("style.import.load",Y),L.once("error",Y)}).then(()=>{this.mergeAll(),this.fire(new s.C("data",{dataType:"style"}))});if(A.push(F),this.resolvedImports.has(I.url)){L.loadEmpty();continue}const $=I.data||this.importsCache.get(I.url);$?(I.data?(L.fire(new s.C("dataloading",{dataType:"style"})),L.globalId=L._getGlobalId($),queueMicrotask(()=>L._load($,g))):L.loadJSON($,{validate:g}),this._isInternalStyle($)&&(L.globalId=null)):I.url?L.loadURL(I.url,{validate:g}):L.loadEmpty();const H={style:L,id:I.id,config:I.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(A)}getImportGlobalIds(d=this,g=new Set){for(const w of d.fragments)w.style.globalId&&g.add(w.style.globalId),this.getImportGlobalIds(w.style,g);return[...g.values()]}_createFragmentStyle(d){const g=this.scope?s.F(d.id,this.scope):d.id;let w;const A=this._initialConfig&&this._initialConfig[g];(d.config||A)&&(w=Object.assign({},d.config,A));const I=new ou(this.map,{scope:g,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:d["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return I.setEventedParent(this.map,{style:I}),I}_reloadImports(){this.mergeAll(),this._updateMapProjection(),this.updateConfigDependencies(),this._updateLayers(this._indoorDependentLayers),this.map._triggerCameraUpdate(this.camera),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),this._shouldPrecompile=this.map._precompilePrograms&&this.isRootStyle()}_isInternalStyle(d){return this.isRootStyle()&&(d.fragment||!!d.schema&&d.fragment!==!1)}_load(d,g){if(this._isInternalStyle(d)){const I=Object.assign({},uv,{imports:[{id:"basemap",data:d,url:""}]},d.center?{center:d.center}:{},d.bearing?{bearing:d.bearing}:{},d.pitch?{pitch:d.pitch}:{},d.zoom?{zoom:d.zoom}:{},d.light?{light:d.light}:{});return this._importedAsBasemap=!0,void this._load(I,g)}if(this.updateConfig(this._config,d.schema),g&&Tp(this,tu(d)))return;this._loaded=!0;for(const I in d.sources)this.addSource(I,d.sources[I],{validate:!1,isInitialLoad:!0});this.stylesheet=s.d9(d);const w=()=>{if(d.iconsets)for(const $ in d.iconsets)this.addIconset($,d.iconsets[$]);d.sprite?this._loadIconset(d.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&d.glyphs&&this.glyphManager.setURL(d.glyphs);const I=QS(this.stylesheet.layers);if(this._order=I.map($=>$.id),this.stylesheet.light&&s.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 $=this.stylesheet.lights[0];this.light=new Br($.properties,$.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Br(this.stylesheet.light)),this._layers={};for(const $ of I){const H=s.de($,this.scope,this._styleColorTheme.lut,this.options);H.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(H.fqid),H.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(H.fqid),this._hasAppearances=this._hasAppearances||H.getAppearances().length!==0,H.setEventedParent(this,{layer:{id:H.id}}),this._layers[H.id]=H;const Y=this.getOwnLayerSourceCache(H),te=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Y&&H.canCastShadows()&&te&&(Y.castsShadows=!0)}if(this.glyphManager.url){const $=new Set;for(const H in this._layers){const Y=this._layers[H];if(Y.type==="symbol"&&Y.layout){const te=Y.layout.get("text-font");te&&te.value&&te.value.kind==="constant"&&$.add(te.value.value.join(","))}}for(const H of $)this.glyphManager.prefetchRange(H,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const L=this.stylesheet.terrain;L&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(L,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 s.C("data",{dataType:"style"}));const F=this.isRootStyle();d.imports?this._loadImports(d.imports,g).then(()=>{this._reloadImports(),this.fire(new s.C(F?"style.load":"style.import.load"))}).catch($=>{this.fire(new s.B(new Error("Failed to load imports",$))),this.fire(new s.C(F?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new s.C(F?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const A=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(A){const I=this._evaluateColorThemeData(A);this._loadColorTheme(I).then(()=>{w()}).catch(L=>{s.w(`Couldn't load color theme from the stylesheet: ${L}`),w()})}else this._styleColorTheme.lut=null,w()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(d=>d.style.hasAppearances())}mergeAll(){let d,g,w,A,I,L,F,$,H,Y;const te={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(ee=>{if(ee.stylesheet){if(ee.light!=null&&(d=ee.light),ee.stylesheet.lights)for(const ie of ee.stylesheet.lights)ie.type==="ambient"&&ee.ambientLight!=null&&(g=ee.ambientLight),ie.type==="directional"&&ee.directionalLight!=null&&(w=ee.directionalLight);A=this._prioritizeTerrain(A,ee.terrain,ee.stylesheet.terrain),ee.stylesheet.fog&&ee.fog!=null&&(I=ee.fog),ee.stylesheet.snow&&ee.snow!=null&&(L=ee.snow),ee.stylesheet.rain&&ee.rain!=null&&(F=ee.rain),ee.stylesheet.camera!=null&&(Y=ee.stylesheet.camera),ee.stylesheet.projection!=null&&($=ee.stylesheet.projection),ee.stylesheet.transition!=null&&(H=ee.stylesheet.transition),te[ee.scope]=ee._styleColorTheme}}),this.light=d,this.ambientLight=g,this.directionalLight=w,this.fog=I,this.snow=L,this.rain=F,this._styleColorThemeForScope=te,A===null?delete this.terrain:this.terrain=A,this.camera=Y||{"camera-projection":"perspective"},this.projection=$||{name:"mercator"},this.transition=Object.assign({},lT,H),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(d){const g=w=>{for(const A of w.fragments)g(A.style);d(w)};g(this)}_prioritizeTerrain(d,g,w){const A=d&&d.drapeRenderMode===0;return w===null?g&&g.drapeRenderMode===0?g:A?d:null:g!=null&&(!d||A||g&&g.drapeRenderMode===1)?g:d}mergeTerrain(){let d;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(g=>{d=this._prioritizeTerrain(d,g.terrain,g.stylesheet.terrain)}),d===null?delete this.terrain:this.terrain=d}mergeProjection(){let d;this.forEachFragmentStyle(g=>{g.stylesheet.projection!=null&&(d=g.stylesheet.projection)}),this.projection=d||{name:"mercator"}}mergeSources(){const d={},g={},w={},A={};this.forEachFragmentStyle(I=>{for(const L in I._sourceCaches){const F=s.F(L,I.scope);d[F]=I._sourceCaches[L]}for(const L in I._otherSourceCaches){const F=s.F(L,I.scope);g[F]=I._otherSourceCaches[L]}for(const L in I._symbolSourceCaches){const F=s.F(L,I.scope);w[F]=I._symbolSourceCaches[L]}for(const L in I._fillExtrusionSourceCaches){const F=s.F(L,I.scope);A[F]=I._fillExtrusionSourceCaches[L]}}),this._mergedSourceCaches=d,this._mergedOtherSourceCaches=g,this._mergedSymbolSourceCaches=w,this._mergedFillExtrusionSourceCaches=A}mergeIndoor(){this.forEachFragmentStyle(d=>{if(d.stylesheet&&d.stylesheet.indoor)for(const g of Object.values(d.stylesheet.indoor)){const w=g,A=s.F(w.sourceId,d.scope);this._mergedIndoor[A]=new Set(w.sourceLayers||[])}})}mergeLayers(){const d={},g=[],w={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(L=>{for(const F of L._order){const $=L._layers[F];if($.type==="slot"){const H=s.da(F);if(d[H])continue;d[H]=[]}$.slot&&d[$.slot]?d[$.slot].push($):g.push($)}}),this._mergedOrder=[];let A=-1;const I=(L=[])=>{for(const F of L)if(F.type==="slot"){const $=s.da(F.id);d[$]&&I(d[$]),this._mergedSlots.push($)}else{const $=s.F(F.id,F.scope);this._mergedOrder.push($),w[$]=F,F.is3D(!!this.terrain)&&(this._has3DLayers=!0,A=this._mergedOrder.length-1),F.type==="circle"&&(this._hasCircleLayers=!0),F.type==="symbol"&&(this._hasSymbolLayers=!0),F.type==="clip"&&(this._clipLayerPresent=!0)}};if(I(g),this._has3DLayers){const L={};for(let F=0;FL[F]-L[$])}this._mergedLayers=w,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(d){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,d),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(d){return d.data?function(g,w,A){const I=Object.assign({},w);for(const F of Object.keys(sT))I[F]===void 0&&(I[F]=sT[F].default);const L=new s.aa(ng,g,new Map(A));return L.setTransitionOrValue(I,A),L.untransitioned().possiblyEvaluate(new s.ae(0,{worldview:void 0}))}(this.scope,d,this.options).get("data"):null}_loadColorTheme(d){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const g=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((w,A)=>{const I="data:image/png;base64,";if(!d||d.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void w();let L=d;L.startsWith(I)||(L=I+L);const F=s.I.from("mapbox-reserved-lut"),$=new Image;$.src=L,$.onerror=()=>{this._styleColorTheme.lutLoading=!1,A(new Error("Failed to load image data"))},$.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==g)return void w();this._styleColorTheme.lutLoading=!1;const{width:H,height:Y,data:te}=s.o.getImageData($);if(Y>32)return void A(new Error("The height of the image must be less than or equal to 32 pixels."));if(H!==Y*Y)return void A(new Error("The width of the image must be equal to the height squared."));this.getImage(F)&&this.removeImage(F),this.addImage(F,{data:new s.q({width:H,height:Y},te),pixelRatio:1,sdf:!1,usvg:!1,version:0});const ee=this.imageManager.getImage(F,this.scope);ee?(this._styleColorTheme.lut={image:ee.data,data:d},w()):A(new Error("Missing LUT image."))}})}getLut(d){const g=this._styleColorThemeForScope[d];return g?g.lut:null}setProjection(d){d?this.stylesheet.projection=d:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){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(d){this._spriteRequest=function(g,w,A){let I,L,F;const $=s.o.devicePixelRatio>1?"@2x":"";let H=s.m(w.transformRequest(w.normalizeSpriteURL(g,$,".json"),s.R.SpriteJSON),(ee,ie)=>{H=null,F||(F=ee,I=ie,te())}),Y=s.n(w.transformRequest(w.normalizeSpriteURL(g,$,".png"),s.R.SpriteImage),(ee,ie)=>{Y=null,F||(F=ee,L=ie,te())});function te(){if(F)A(F);else if(I&&L){const ee=s.o.getImageData(L),ie={};for(const le in I){const{width:oe,height:me,x:pe,y:je,sdf:Re,pixelRatio:xe,stretchX:Ze,stretchY:ze,content:Ke}=I[le],De=new s.q({width:oe,height:me});s.q.copy(ee,De,{x:pe,y:je},{x:0,y:0},{width:oe,height:me},null),ie[le]={data:De,pixelRatio:xe!==void 0?xe:1,sdf:Re!==void 0&&Re,stretchX:Ze,stretchY:ze,content:Ke,usvg:!1,version:0}}A(null,ie)}}return{cancel(){H&&(H.cancel(),H=null),Y&&(Y.cancel(),Y=null)}}}(d,this.map._requestManager,(g,w)=>{if(this._spriteRequest=null,g)this.fire(new s.B(g));else if(w){const A=new Map;for(const I in w)A.set(s.I.from(I),w[I]);this.addImages(A)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new s.C("data",{dataType:"style"}))})}addIconset(d,g){if(g.type==="sprite")return void this._loadSprite(g.url);const w=this.getOwnSourceCache(g.source);if(!w)return void this.fire(new s.B(new Error(`Source "${g.source}" as specified by iconset "${d}" does not exist and cannot be used as an iconset source`)));const A=w.getSource();if(A.type!=="raster-array")return void this.fire(new s.B(new Error(`Source "${g.source}" as specified by iconset "${d}" is not a "raster-array" source and cannot be used as an iconset source`)));A.partial=!1;const I=new aT(d,this.scope,w);this.imageManager.addImageProvider(I,this.scope)}removeIconset(d){this.imageManager.removeImageProvider(d,this.scope)}_loadIconset(d){if(!s.e(d)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(d);const g=this.map._spriteFormat==="auto";var w,A;this._spriteRequest=(A=(I,L)=>{if(this._spriteRequest=null,I)g?this._loadSprite(d):this.fire(new s.B(I));else if(L){const F=new Map;for(const $ in L)F.set(s.I.from($),L[$]);this.addImages(F)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new s.C("data",{dataType:"style"}))},s.b1((w=this.map._requestManager).transformRequest(w.normalizeIconsetURL(d),s.R.Iconset),(I,L)=>{if(I)return void A(I);const F={},$=s.c$(new s.a$(L));for(const H of $.icons){const Y={version:1,pixelRatio:s.o.devicePixelRatio,content:bj(H),stretchX:H.metadata?Nx(H.metadata.stretch_x_areas):void 0,stretchY:H.metadata?Nx(H.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:H};F[H.name]=Y}A(null,F)}))}_validateLayer(d){const g=this.getOwnSource(d.source);if(!g)return;const w=d.sourceLayer;w&&(g.type==="geojson"||g.vectorLayerIds&&g.vectorLayerIds.indexOf(w)===-1)&&this.fire(new s.B(new Error(`Source layer "${w}" does not exist on source "${g.id}" as specified by style layer "${d.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const d in this._sourceCaches)if(!this._sourceCaches[d].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:d}of this.fragments)if(!d.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((d,g)=>{const w=this.fragments[g];return w&&w.style&&(d.data=w.style.serialize()),d})}_serializeSources(){const d={};for(const g in this._sourceCaches){const w=this._sourceCaches[g].getSource();d[w.id]||(d[w.id]=w.serialize())}return d}_serializeLayers(d){const g=[];for(const w of d){const A=this._layers[w];A&&A.type!=="custom"&&g.push(A.serialize())}return g}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 d in this._sourceCaches)if(this._sourceCaches[d].hasTransition())return!0;for(const d in this._layers)if(this._layers[d].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const d in this._mergedLayers){const g=this._mergedLayers[d];if(g._transitionablePaint&&g._transitionablePaint._values){const w=g._transitionablePaint._values["line-emissive-strength"];if(w&&w.value&&w.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(d){return d?this.order:this._mergedOrder}isLayerDraped(d){return!!this.terrain&&d.isDraped(this.getLayerSourceCache(d))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(d){const g=this.getOwnLayer(d);if(g)return g;this.fire(new s.B(new Error(`The layer '${d}' does not exist in the map's style.`)))}_checkSource(d){const g=this.getOwnSource(d);if(g)return g;this.fire(new s.B(new Error(`The source '${d}' does not exist in the map's style.`)))}precompilePrograms(d,g){const w=this.map.painter;if(w)for(let A=d.minzoom||0;A<(d.maxzoom||25.5);A++){const I=d.getProgramIds();if(I)for(const L of I){const F=d.getDefaultProgramParams(L,g.zoom,this._styleColorTheme.lut);F&&(w.style=this,this.fog&&(w._fogVisible=!0,F.overrideFog=!0,w.getOrCreateProgram(L,F)),w._fogVisible=!1,F.overrideFog=!1,w.getOrCreateProgram(L,F),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(F.overrideRtt=!0,w.getOrCreateProgram(L,F)))}}}update(d){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(d),this.directionalLight&&this.directionalLight.recalculate(d);const g=this.calculateLightsBrightness();d.brightness=g||0,g!==this._brightness&&(this._brightness=g,this.dispatcher.broadcast("setBrightness",g)),d.worldview!==this._worldview&&(this._worldview=d.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const w=this._changes.isDirty();let A=!1;if(this._changes.isDirty()){const $=this._changes.getLayerUpdatesByScope();for(const H in $){const{updatedIds:Y,removedIds:te}=$[H];(Y||te)&&(this._updateWorkerLayers(H,Y,te),A=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(d),this.light&&this.light.updateTransitions(d),this.ambientLight&&this.ambientLight.updateTransitions(d),this.directionalLight&&this.directionalLight.updateTransitions(d),this.fog&&this.fog.updateTransitions(d),this.snow&&this.snow.updateTransitions(d),this.rain&&this.rain.updateTransitions(d),this._changes.reset()}const I={};for(const $ in this._mergedSourceCaches){const H=this._mergedSourceCaches[$];I[$]=H.used,H.used=!1,H.tileCoverLift=0}const L={};for(const $ of this._mergedOrder){const H=this._mergedLayers[$];if((H.visibility!=="none"||H.hasTransition())&&H.recalculate(d,this._availableImages),!H.isHidden(d.zoom)){const Y=this.getLayerSourceCache(H);Y&&(Y.used=!0,Y.tileCoverLift=Math.max(Y.tileCoverLift,H.tileCoverLift()))}if(H.type==="fill-extrusion"){const Y=s.F(H.source,H.scope);if(Y in this._mergedFillExtrusionSourceCaches){const te=H.layout&&H.layout.get("source-max-zoom");if(te!=null){const ee=L[Y];L[Y]=ee==null?te:Math.min(ee,te)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(H,d)}):this.precompilePrograms(H,d))}this._shouldPrecompile&&(this._precompileDone=!0);for(const $ in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[$].setMaxzoomOverride(L[$]!=null?L[$]:null);this.terrain&&A&&this.mergeLayers();const F=this.imageManager.getPendingImageProviders();for(const $ of F)$.sourceCache.used=!0;for(const $ in I){const H=this._mergedSourceCaches[$];I[$]!==H.used&&H.getSource().fire(new s.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:H.getSource().id}))}this.light&&this.light.recalculate(d),this.terrain&&this.terrain.recalculate(d),this.fog&&this.fog.recalculate(d),this.snow&&this.snow.recalculate(d),this.rain&&this.rain.recalculate(d),this.z=d.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),w&&this.fire(new s.C("data",{dataType:"style"}))}updateImageProviders(){const d=this.imageManager.getPendingImageProviders();for(const g of d){const w=g.resolvePendingRequests(),A=this.getFragmentStyle(g.scope);A&&A.addImages(w)}}_updateTilesForChangedImages(){const d={};for(const g in this._mergedSourceCaches){const w=this._mergedSourceCaches[g].getSource().scope;d[w]=d[w]||this._changes.getUpdatedImages(w),d[w].length!==0&&this._mergedSourceCaches[g].reloadTilesForDependencies(["icons","patterns"],d[w])}for(const g in d)this._changes.resetUpdatedImages(g)}_updateWorkerLayers(d,g,w){const A=this.getFragmentStyle(d);A&&this.dispatcher.broadcast("updateLayers",{layers:g?A._serializeLayers(g):[],scope:d,removedIds:w||[],options:A.options})}setState(d,g){if(this._checkLoaded(),Tp(this,tu(d)))return!1;(d=s.d9(d)).layers=QS(d.layers);const w=function(L,F){if(!L)return[{command:Xn.setStyle,args:[F]}];let $=[];try{if(!s.b6(L.version,F.version))return[{command:Xn.setStyle,args:[F]}];if(s.b6(L.center,F.center)||$.push({command:Xn.setCenter,args:[F.center]}),s.b6(L.zoom,F.zoom)||$.push({command:Xn.setZoom,args:[F.zoom]}),s.b6(L.bearing,F.bearing)||$.push({command:Xn.setBearing,args:[F.bearing]}),s.b6(L.pitch,F.pitch)||$.push({command:Xn.setPitch,args:[F.pitch]}),s.b6(L.sprite,F.sprite)||$.push({command:Xn.setSprite,args:[F.sprite]}),s.b6(L.glyphs,F.glyphs)||$.push({command:Xn.setGlyphs,args:[F.glyphs]}),s.b6(L.imports,F.imports)||function(ie=[],le=[],oe){le=le||[];const me=(ie=ie||[]).map(Qm),pe=le.map(Qm),je=ie.reduce(vx,{}),Re=le.reduce(vx,{}),xe=me.slice();let Ze,ze,Ke,De;for(Ze=0,ze=0;Ze{ie.source&&H[ie.source]?$.push({command:Xn.removeLayer,args:[ie.id]}):te.push(ie)});let ee=L.terrain;ee&&H[ee.source]&&($.push({command:Xn.setTerrain,args:[void 0]}),ee=void 0),$=$.concat(Y),s.b6(ee,F.terrain)||$.push({command:Xn.setTerrain,args:[F.terrain]}),function(ie,le,oe){le=le||[];const me=(ie=ie||[]).map(Qm),pe=le.map(Qm),je=ie.reduce(vx,{}),Re=le.reduce(vx,{}),xe=me.slice(),Ze=Object.create(null);let ze,Ke,De,Fe,qe,st,Qe;for(ze=0,Ke=0;ze!(L.command in wj));if(w.length===0)return!1;const A=w.filter(L=>!(L.command in _3));if(A.length>0)throw new Error(`Unimplemented: ${A.map(L=>L.command).join(", ")}.`);const I=[];return w.forEach(L=>{I.push(this[L.command](...L.args))}),g&&Promise.all(I).then(g).catch(g),this.stylesheet=d,this.mergeAll(),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}_updateWorkerImages(){this._availableImages=this.imageManager.listImages(this.scope),this.dispatcher.broadcast("setImages",{scope:this.scope,images:this._availableImages})}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(d){if(d.size===0)return this;for(const[g,w]of d.entries()){if(this.getImage(g))return this.fire(new s.B(new Error(`An image with the name "${g.name}" already exists.`)));this.imageManager.addImage(g,this.scope,w),this._changes.updateImage(g,this.scope)}return this._updateWorkerImages(),this.fire(new s.C("data",{dataType:"style"})),this}addImage(d,g){return this.getImage(d)?this.fire(new s.B(new Error(`An image with the name "${d.name}" already exists.`))):(this.imageManager.addImage(d,this.scope,g),this._changes.updateImage(d,this.scope),this._updateWorkerImages(),this.fire(new s.C("data",{dataType:"style"})),this)}updateImage(d,g,w=!1){this.imageManager.updateImage(d,this.scope,g),w&&(this._changes.updateImage(d,this.scope),this._updateWorkerImages(),this.fire(new s.C("data",{dataType:"style"})))}getImage(d){return this.imageManager.getImage(d,this.scope)}removeImage(d){return this.getImage(d)?(this.imageManager.removeImage(d,this.scope),this._changes.updateImage(d,this.scope),this._updateWorkerImages(),this.fire(new s.C("data",{dataType:"style"})),this):this.fire(new s.B(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(d){return this.modelManager.addModelURLs(d,this.getActualScope()),this._updateWorkerModels(),this.fire(new s.C("data",{dataType:"style"})),this}addModel(d,g,w={}){return this._checkLoaded(),this._validate(zt,`models.${d}`,g,null,w)||(this.modelManager.addModel(d,g,this.getActualScope()),this.fire(new s.C("data",{dataType:"style"}))),this}hasModel(d){return this.modelManager.hasModel(d,this.getActualScope())}removeModel(d){return this.hasModel(d)?(this.modelManager.removeModel(d,this.getActualScope(),!1,!0),this.fire(new s.C("data",{dataType:"style"})),this):this.fire(new s.B(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(d,g,w={}){if(this._checkLoaded(),this.getOwnSource(d)!==void 0)throw new Error(`There is already a source with ID "${d}".`);if(!g.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(g).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(g.type)>=0&&this._validate(yx,`sources.${d}`,g,null,w))return;this.map&&this.map._collectResourceTiming&&(g.collectResourceTiming=!0);const A=X0(d,g,this.dispatcher,this);A.scope=this.scope,A.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(A.id),source:A.serialize(),sourceId:A.id}));const I=L=>{const F=(L===s.b4.Symbol?"symbol:":L===s.b4.FillExtrusion?"fill-extrusion:":"other:")+A.id,$=s.F(F,this.scope),H=this._sourceCaches[F]=new nu($,A,L);L===s.b4.Symbol?this._symbolSourceCaches[A.id]=H:L===s.b4.FillExtrusion?this._fillExtrusionSourceCaches[A.id]=H:this._otherSourceCaches[A.id]=H,H.onAdd(this.map)};I(s.b4.Other),g.type!=="vector"&&g.type!=="geojson"||(I(s.b4.Symbol),g.type==="vector"&&I(s.b4.FillExtrusion)),A.onAdd&&A.onAdd(this.map),w.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(d){this._checkLoaded();const g=this.getOwnSource(d);if(!g)throw new Error("There is no source with this ID");for(const A in this._layers)if(this._layers[A].source===d)return this.fire(new s.B(new Error(`Source "${d}" cannot be removed while layer "${A}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===d)return this.fire(new s.B(new Error(`Source "${d}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const A=Object.entries(this.stylesheet.iconsets).find(([I,L])=>L.type==="source"&&L.source===d);if(A)return this.fire(new s.B(new Error(`Source "${d}" cannot be removed while iconset "${A[0]}" is using it.`)))}const w=this.getOwnSourceCaches(d);for(const A of w){const I=s.da(A.id);delete this._sourceCaches[I],this._changes.discardSourceCacheUpdate(A.id),A.fire(new s.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:A.getSource().id})),A.setEventedParent(null),A.clearTiles()}return delete this._otherSourceCaches[d],delete this._symbolSourceCaches[d],delete this._fillExtrusionSourceCaches[d],this.mergeSources(),g.setEventedParent(null),g.onRemove&&g.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(d,g){this._checkLoaded(),this.getOwnSource(d).setData(g),this._changes.setDirty()}getOwnSource(d){const g=this.getOwnSourceCache(d);return g&&g.getSource()}getOwnSources(){const d=[];for(const g in this._otherSourceCaches){const w=this.getOwnSourceCache(g);w&&d.push(w.getSource())}return d}areTilesLoaded(){const d=this._mergedSourceCaches;for(const g in d){const w=d[g]._tiles;for(const A in w){const I=w[A];if(I.state!=="loaded"&&I.state!=="errored")return!1}}return!0}setLights(d){if(this._checkLoaded(),!d)return delete this.ambientLight,void delete this.directionalLight;const g=this._getTransitionParameters();for(const I of d){if(this._validate(de,"lights",I))return;switch(I.type){case"ambient":if(this.ambientLight){const L=this.ambientLight;L.set(I),L.updateTransitions(g)}else this.ambientLight=new _a(I,yo(),this.scope,this.options);break;case"directional":if(this.directionalLight){const L=this.directionalLight;L.set(I),L.updateTransitions(g)}else this.directionalLight=new _a(I,Jl(),this.scope,this.options)}}const w=Object.assign(g,{worldview:this.map.getWorldview()}),A=new s.ae(this.z||0,w);this.ambientLight&&this.ambientLight.recalculate(A),this.directionalLight&&this.directionalLight.recalculate(A),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const d=this.directionalLight,g=this.ambientLight;if(!d||!g)return;const w=ee=>.2126*(ee[0]<=.03928?ee[0]/12.92:Math.pow((ee[0]+.055)/1.055,2.4))+.7152*(ee[1]<=.03928?ee[1]/12.92:Math.pow((ee[1]+.055)/1.055,2.4))+.0722*(ee[2]<=.03928?ee[2]/12.92:Math.pow((ee[2]+.055)/1.055,2.4)),A=d.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),I=d.properties.get("intensity"),L=d.properties.get("direction"),F=1-s.cP(L.x,L.y,L.z)[2]/90,$=w(A)*I*F,H=g.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Y=g.properties.get("intensity"),te=w(H)*Y;return Number((($+te)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const d=[];return this.directionalLight&&d.push(this.directionalLight.get()),this.ambientLight&&d.push(this.ambientLight.get()),d}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(d){if(d==null||d===""&&this.isRootStyle())return this;if(s.db(d)){const g=s.dc(d),w=this.fragments.find(({id:I})=>I===g);if(!w)return;const A=s.da(d);return w.style.getFragmentStyle(A)}{const g=this.fragments.find(({id:w})=>w===d);return g?g.style:void 0}}setFeaturesetSelectors(d){if(!d)return;const g=(w,A="")=>`${w}::${A}`;this._featuresetSelectors={};for(const w in d){const A={},I=this._featuresetSelectors[w]=[];for(const L of d[w].selectors){if(L.featureNamespace){const $=this.getOwnLayer(L.layer);if(!$){s.w(`Layer is undefined for selector: ${L.layer}`);continue}const H=g($.source,$.sourceLayer);if(H in A&&A[H]!==L.featureNamespace){s.w(`"featureNamespace ${L.featureNamespace} of featureset ${w}'s selector is not associated to the same source, skip this selector`);continue}A[H]=L.featureNamespace}let F;if(L.properties)for(const $ in L.properties){const H=s.X(L.properties[$]);H.result==="success"&&(F=F||{},F[$]=H.value)}I.push({layerId:L.layer,namespace:L.featureNamespace,properties:F,uniqueFeatureID:L._uniqueFeatureID})}}}getFeaturesetDescriptors(d){const g=this.getFragmentStyle(d);if(!g||!g.stylesheet.featuresets)return[];const w=[];for(const A in g.stylesheet.featuresets)w.push({featuresetId:A,importId:g.scope?g.scope:void 0});return w}getFeaturesetLayers(d,g){const w=this.getFragmentStyle(g),A=w.stylesheet.featuresets;if(!A||!A[d])return this.fire(new s.B(new Error(`The featureset '${d}' does not exist in the map's style and cannot be queried.`))),[];const I=[];for(const L of A[d].selectors){const F=w.getOwnLayer(L.layer);F&&I.push(F)}return I}getConfigProperty(d,g){const w=this.getFragmentStyle(d);if(!w)return null;const A=s.F(g,w.scope),I=w.options.get(A),L=I?I.value||I.default:null;return L?L.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(d,g){const w=s.F(d,g);return this._mergedIndoor[w]}setIndoorData(d,g){this.indoorManager.setIndoorData(g)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(d,g,w){const A=this.getFragmentStyle(d);if(!A)return;const I=A.stylesheet.schema;if(!I||!I[g])return;const L=s.X(w);if(L.result!=="success")return void Tp(this,L.value);const F=L.value.expression,$=s.F(g,A.scope),H=A.options.get($);if(!H)return;let Y;const{minValue:te,maxValue:ee,stepValue:ie,type:le,values:oe}=I[g],me=s.X(I[g].default);me.result==="success"&&(Y=me.value.expression),Y?(this.options.set($,Object.assign({},H,{value:F,default:Y,minValue:te,maxValue:ee,stepValue:ie,type:le,values:oe})),this.updateConfigDependencies(g)):this.fire(new s.B(new Error(`No schema defined for the config option "${g}" in the "${d}" fragment.`)))}getConfig(d){const g=this.getFragmentStyle(d);if(!g)return null;const w=g.stylesheet.schema;if(!w)return null;const A={};for(const I in w){const L=s.F(I,g.scope),F=g.options.get(L),$=F?F.value||F.default:null;A[I]=$?$.serialize():null}return A}setConfig(d,g){const w=this.getFragmentStyle(d);w&&(w.updateConfig(g,w.stylesheet.schema),this.updateConfigDependencies())}getSchema(d){const g=this.getFragmentStyle(d);return g?g.stylesheet.schema:null}setSchema(d,g){const w=this.getFragmentStyle(d);w&&(w.stylesheet.schema=g,w.updateConfig(w._config,g),this.updateConfigDependencies())}updateConfig(d,g){if(this._config=d,d||g)if(g)for(const w in g){let A,I;const L=s.X(g[w].default);if(L.result==="success"&&(A=L.value.expression),d&&d[w]!==void 0){const ee=s.X(d[w]);ee.result==="success"&&(I=ee.value.expression)}const{minValue:F,maxValue:$,stepValue:H,type:Y,values:te}=g[w];if(A){const ee=s.F(w,this.scope);this.options.set(ee,{default:A,value:I,minValue:F,maxValue:$,stepValue:H,type:Y,values:te})}else this.fire(new s.B(new Error(`No schema defined for config option "${w}".`)))}else this.fire(new s.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(d,g=()=>!0){for(const w of d){const A=this.getLayer(w);A&&g(A)&&(A.possiblyEvaluateVisibility(),this._updateLayer(A),this._changes.setDirty())}}updateConfigDependencies(d){this._updateLayers(this._configDependentLayers,g=>!d||g.expressionDependencies.configDependencies.has(d)),this.ambientLight&&this.ambientLight.updateConfig(this.options),this.directionalLight&&this.directionalLight.updateConfig(this.options),this.fog&&this.fog.updateConfig(this.options),this.snow&&this.snow.updateConfig(this.options),this.rain&&this.rain.updateConfig(this.options),this.forEachFragmentStyle(g=>{const w=g._styleColorTheme.colorThemeOverride?g._styleColorTheme.colorThemeOverride:g._styleColorTheme.colorTheme;if(w){const A=g._evaluateColorThemeData(w);(!g._styleColorTheme.lut&&A!==""||g._styleColorTheme.lut&&A!==g._styleColorTheme.lut.data)&&g.setColorTheme(w)}}),this._changes.setDirty()}addLayer(d,g,w={}){this._checkLoaded();const A=d.id;if(this._layers[A])return void this.fire(new s.B(new Error(`Layer with id "${A}" already exists on this map`)));let I;if(d.type==="custom"){if(Tp(this,s.dd(d)))return;I=s.de(d,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof d.source=="object"&&(this.addSource(A,d.source),d=s.d9(d),d=Object.assign(d,{source:A})),this._validate(tt,`layers.${A}`,d,{arrayIndex:-1},w))return;I=s.de(d,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(I),I.setEventedParent(this,{layer:{id:A}})}const L=s.F(I.source,I.scope);I.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(L),I.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(L);let F=this._order.length;if(g){const te=this._order.indexOf(g);if(te===-1)return void this.fire(new s.B(new Error(`Layer with id "${g}" does not exist on this map.`)));I.slot&&I.slot!==this._layers[g].slot?s.w(`Layer with id "${g}" has a different slot. Layers can only be rearranged within the same slot.`):F=te}this._order.splice(F,0,A),this._handleLayerOrderChange(),this._layers[A]=I;const $=this.getOwnLayerSourceCache(I),H=!!this.directionalLight&&this.directionalLight.shadowsEnabled();$&&I.canCastShadows()&&H&&($.castsShadows=!0);const Y=this._changes.getRemovedLayer(I);if(Y&&I.source&&$&&I.type!=="custom"){this._changes.discardLayerRemoval(I);const te=s.F(I.source,I.scope);Y.type!==I.type?this._changes.updateSourceCache(te,"clear"):(this._changes.updateSourceCache(te,"reload"),$.pause())}this._updateLayer(I),I.onAdd&&I.onAdd(this.map),I.scope=this.scope,this.mergeLayers()}moveLayer(d,g){this._checkLoaded();const w=this._checkLayer(d);if(!w||d===g)return;const A=this._order.indexOf(d);this._order.splice(A,1);let I=this._order.length;if(g){const L=this._order.indexOf(g);if(L===-1)return void this.fire(new s.B(new Error(`Layer with id "${g}" does not exist on this map.`)));w.slot&&w.slot!==this._layers[g].slot?s.w(`Layer with id "${g}" has a different slot. Layers can only be rearranged within the same slot.`):I=L}this._order.splice(I,0,d),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(d){this._checkLoaded();const g=this._checkLayer(d);if(!g)return;g.setEventedParent(null);const w=this._order.indexOf(d);this._order.splice(w,1),delete this._layers[d],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(g.fqid),this._indoorDependentLayers.delete(g.fqid),this._changes.removeLayer(g);const A=this.getOwnLayerSourceCache(g);if(A&&A.castsShadows){let I=!1;for(const L in this._layers)if(this._layers[L].source===g.source&&this._layers[L].canCastShadows()){I=!0;break}A.castsShadows=I}g.onRemove&&g.onRemove(this.map),this.mergeLayers()}getOwnLayer(d){return this._layers[d]}hasLayer(d){return d in this._mergedLayers}hasLayerType(d){for(const g in this._layers)if(this._layers[g].type===d)return!0;return!1}setLayerZoomRange(d,g,w){this._checkLoaded();const A=this._checkLayer(d);A&&(A.minzoom===g&&A.maxzoom===w||(g!=null&&(A.minzoom=g),w!=null&&(A.maxzoom=w),this._updateLayer(A)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(d,g){this._checkLoaded();const w=this._checkLayer(d);w&&w.slot!==g&&(w.slot=g,this._updateLayer(w))}setFilter(d,g,w={}){this._checkLoaded();const A=this._checkLayer(d);if(A&&!s.b6(A.filter,g))return g==null?(A.filter=void 0,void this._updateLayer(A)):void(this._validate(dt,`layers.${A.id}.filter`,g,{layerType:A.type},w)||(A.filter=s.d9(g),this._updateLayer(A)))}getFilter(d){const g=this._checkLayer(d);if(g)return s.d9(g.filter)}setLayoutProperty(d,g,w,A={}){this._checkLoaded();const I=this._checkLayer(d);if(I&&!s.b6(I.getLayoutProperty(g),w)){if(w!=null&&(!A||A.validate!==!1)&&Tp(I,ht.call(tu,{key:`layers.${d}.layout.${g}`,layerType:I.type,objectKey:g,value:w,styleSpec:s.a8,style:{glyphs:!0,sprite:!0}})))return;I.setLayoutProperty(g,w),I.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(I.fqid),I.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(I.fqid),this._updateLayer(I)}}setLayerProperty(d,g,w,A={}){this._checkLoaded();const I=this._checkLayer(d);I&&(g==="appearances"?(I.setAppearances(w),this._updateLayer(I)):I.isPaintProperty(g)?this.setPaintProperty(d,g,w,A):this.setLayoutProperty(d,g,w,A))}getLayoutProperty(d,g){const w=this._checkLayer(d);if(w)return w.getLayoutProperty(g)}setPaintProperty(d,g,w,A={}){this._checkLoaded();const I=this._checkLayer(d);if(!I||s.b6(I.getPaintProperty(g),w)||w!=null&&(!A||A.validate!==!1)&&Tp(I,it.call(tu,{key:`layers.${d}.paint.${g}`,layerType:I.type,objectKey:g,value:w,styleSpec:s.a8})))return;const L=I.setPaintProperty(g,w);I.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(I.fqid),I.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(I.fqid),L&&this._updateLayer(I),this._changes.updatePaintProperties(I)}getPaintProperty(d,g){const w=this._checkLayer(d);if(w)return w.getPaintProperty(g)}setFeatureState(d,g){if(this._checkLoaded(),"target"in d){if("featuresetId"in d.target){const{featuresetId:$,importId:H}=d.target,Y=this.getFragmentStyle(H),te=Y.getFeaturesetLayers($);for(const{source:ee,sourceLayer:ie}of te)Y.setFeatureState({id:d.id,source:ee,sourceLayer:ie},g)}else if("layerId"in d.target){const{layerId:$}=d.target,H=this.getLayer($);this.setFeatureState({id:d.id,source:H.source,sourceLayer:H.sourceLayer},g)}return}const w=d.source,A=d.sourceLayer,I=this._checkSource(w);if(!I)return;const L=I.type;if(L==="geojson"&&A)return void this.fire(new s.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(L==="vector"&&!A)return void this.fire(new s.B(new Error("The sourceLayer parameter must be provided for vector source types.")));d.id===void 0&&this.fire(new s.B(new Error("The feature id parameter must be provided.")));const F=this.getOwnSourceCaches(w);for(const $ of F)$.setFeatureState(A,d.id,g)}removeFeatureState(d,g){if(this._checkLoaded(),"target"in d){if("featuresetId"in d.target){const{featuresetId:$,importId:H}=d.target,Y=this.getFragmentStyle(H),te=Y.getFeaturesetLayers($);for(const{source:ee,sourceLayer:ie}of te)Y.removeFeatureState({id:d.id,source:ee,sourceLayer:ie},g)}else if("layerId"in d.target){const{layerId:$}=d.target,H=this.getLayer($);this.removeFeatureState({id:d.id,source:H.source,sourceLayer:H.sourceLayer},g)}return}const w=d.source,A=this._checkSource(w);if(!A)return;const I=A.type,L=I==="vector"?d.sourceLayer:void 0;if(I==="vector"&&!L)return void this.fire(new s.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(g&&typeof d.id!="string"&&typeof d.id!="number")return void this.fire(new s.B(new Error("A feature id is required to remove its specific state property.")));const F=this.getOwnSourceCaches(w);for(const $ of F)$.removeFeatureState(L,d.id,g)}getFeatureState(d){if(this._checkLoaded(),"target"in d){let I;if("featuresetId"in d.target){const{featuresetId:L,importId:F}=d.target,$=this.getFragmentStyle(F),H=$.getFeaturesetLayers(L);for(const{source:Y,sourceLayer:te}of H){const ee=$.getFeatureState({id:d.id,source:Y,sourceLayer:te});if(ee&&!I)I=ee;else if(!s.b6(I,ee))return void this.fire(new s.B(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 d.target){const{layerId:L}=d.target,F=this.getLayer(L);I=this.getFeatureState({id:d.id,source:F.source,sourceLayer:F.sourceLayer})}return I}const g=d.source,w=d.sourceLayer,A=this._checkSource(g);if(A){if(A.type!=="vector"||w)return d.id===void 0&&this.fire(new s.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(g)[0].getFeatureState(w,d.id);this.fire(new s.B(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(d){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,d),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(d){d!==this._worldview&&(this._worldview=d,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const d=this.getTerrain(),g=d&&this.terrain&&this.terrain.scope===this.scope?d:this.stylesheet.terrain;return s.df({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:g,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(d){for(const g of Object.values(this._mergedLayers))d(g)&&this._updateLayer(g)}_updateLayer(d){this._changes.updateLayer(d);const g=this.getLayerSourceCache(d),w=s.F(d.source,d.scope),A=this._changes.getUpdatedSourceCaches();d.source&&!A[w]&&g&&g.getSource().type!=="raster"&&(this._changes.updateSourceCache(w,"reload"),g.pause()),d.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(d){const g=F=>this._mergedLayers[F].is3D(!!this.terrain),w=this.order,A={},I=[];for(let F=w.length-1;F>=0;F--){const $=w[F];if(g($)){A[$]=F;for(const H of d){const Y=H[$];if(Y)for(const te of Y)I.push(te)}}}I.sort((F,$)=>$.intersectionZ-F.intersectionZ);const L=[];for(let F=w.length-1;F>=0;F--){const $=w[F];if(g($))for(let H=I.length-1;H>=0;H--){const Y=I[H].feature;if(Y.layer&&A[Y.layer.id]{if(oT.has(Y.type))return;const te=this.getOwnLayerSourceCache(Y),ee=I[te.id]=I[te.id]||{sourceCache:te,layers:{},has3DLayers:!1};Y.is3D(!!this.terrain)&&(ee.has3DLayers=!0),ee.layers[Y.fqid]=ee.layers[Y.fqid]||{styleLayer:Y,targets:[]},ee.layers[Y.fqid].targets.push({filter:A})};if(g&&g.layers){if(!Array.isArray(g.layers))return this.fire(new s.B(new Error("parameters.layers must be an Array."))),[];for(const Y of g.layers){const te=this._layers[Y];if(!te)return this.fire(new s.B(new Error(`The layer '${Y}' does not exist in the map's style and cannot be queried for features.`))),[];L(te)}}else for(const Y in this._layers)L(this._layers[Y]);const F=this._queryRenderedFeatures(d,I,w),$=this._flattenAndSortRenderedFeatures(F),H=[];for(const Y of $)s.dh(Y.layer.id)===this.scope&&H.push(Y);return H}queryRenderedFeatureset(d,g,w){let A;g&&!Array.isArray(g)&&g.filter&&(this._validate(dt,"queryRenderedFeatures.filter",g.filter,null,g),A=s.dg(g.filter));const I="mock",L=[];if(g&&g.target)L.push(Object.assign({},g,{targetId:I,filter:A}));else{const Y=this.getFeaturesetDescriptors();for(const te of Y)L.push({targetId:I,filter:A,target:te});for(const{style:te}of this.fragments){const ee=te.getFeaturesetDescriptors();for(const ie of ee)L.push({targetId:I,filter:A,target:ie})}}const F=this.queryRenderedTargets(d,L,w),$=[],H=new Set;for(const Y of F)for(const te of Y.variants[I])gd(te,Y,H)||$.push(new s.di(Y,te));return $}queryRenderedTargets(d,g,w){const A={},I=(F,$,H,Y)=>{const te=A[$.id]=A[$.id]||{sourceCache:$,layers:{},has3DLayers:!1};if(te.layers[F.fqid]=te.layers[F.fqid]||{styleLayer:F,targets:[]},F.is3D(!!this.terrain)&&(te.has3DLayers=!0),!Y)return H.uniqueFeatureID=!1,void te.layers[F.fqid].targets.push(H);te.layers[F.fqid].targets.push(Object.assign({},H,{namespace:Y.namespace,properties:Y.properties,uniqueFeatureID:Y.uniqueFeatureID}))};for(const F of g)if("featuresetId"in F.target){const{featuresetId:$,importId:H}=F.target,Y=this.getFragmentStyle(H);if(!Y||!Y._featuresetSelectors)continue;const te=Y._featuresetSelectors[$];if(!te){this.fire(new s.B(new Error(`The featureset '${$}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const ee of te){const ie=Y.getOwnLayer(ee.layerId);ie&&!oT.has(ie.type)&&I(ie,Y.getOwnLayerSourceCache(ie),F,ee)}}else if("layerId"in F.target){const{layerId:$}=F.target,H=this.getLayer($);if(!H||oT.has(H.type))continue;I(H,this.getLayerSourceCache(H),F)}const L=this._queryRenderedFeatures(d,A,w);return this._flattenAndSortRenderedFeatures(L)}_queryRenderedFeatures(d,g,w){const A=[],I=!!this.map._showQueryGeometry,L=ec.createFromScreenPoints(d,w);for(const F in g){const $=mj(L,g[F],this._availableImages,w,I,this.getActualScope());Object.keys($).length&&A.push($)}if(this.placement)for(const F in g){if(g[F].sourceCache._renderSourceType!==s.b4.Symbol)continue;const $=Q0(L.screenGeometry,g[F],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys($).length&&A.push($)}return A}querySourceFeatures(d,g){const w=g&&g.filter;w&&this._validate(dt,"querySourceFeatures.filter",w,null,g);let A=[];const I=this.getOwnSourceCaches(d);for(const L of I)A=A.concat(KS(L,g));return A}addSourceType(d,g,w){return ou.getSourceType(d)?w(new Error(`A source type called "${d}" already exists.`)):(ou.setSourceType(d,g),g.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:d,url:g.workerSourceURL},w):w(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(d,g,w={}){this._checkLoaded();const A=this.light.getLight();let I=!1;for(const F in d)if(!s.b6(d[F],A[F])){I=!0;break}if(!I)return;const L=this._getTransitionParameters();this.light.setLight(d,g,w),this.light.updateTransitions(L)}getTerrain(){return this.terrain&&this.terrain.drapeRenderMode===1?this.terrain.get():null}setTerrainForDraping(){this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){this.disableElevatedTerrain===void 0&&(this.disableElevatedTerrain=s.o.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&s.w("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(d,g=1){if(this._checkLoaded(),!d)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),g===0&&delete this.terrain,d===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let w=d;const A=!("source"in d)||d.source==null;if(g===1){if(this.disableElevatedTerrain)return;if("source"in w&&typeof w.source=="object"){const F="terrain-dem-src";this.addSource(F,w.source),w=s.d9(w),w=Object.assign(w,{source:F})}const I=Object.assign({},w),L={};if(this.terrain&&A){I.source=this.terrain.get().source;const F=this.terrain?this.getFragmentStyle(this.terrain.scope):null;F&&(L.style=F.serialize())}if(this._validate(fe,"terrain",I,L))return}if(!this.terrain||this.terrain.scope!==this.scope&&!A||this.terrain&&g!==this.terrain.drapeRenderMode){if(!w)return;this._createTerrain(w,g),this.fire(new s.C("data",{dataType:"style"}))}else{const I=this.terrain,L=I.get();for(const F of Object.keys(s.a8.terrain))!w.hasOwnProperty(F)&&s.a8.terrain[F].default&&(w[F]=s.a8.terrain[F].default);for(const F in d)if(!s.b6(d[F],L[F])){I.set(d,this.options),this.stylesheet.terrain=d;const $=this._getTransitionParameters({duration:0});I.updateTransitions($),this.fire(new s.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(d){const g=this.fog=new is(d,this.map.transform,this.scope,this.options);this.stylesheet.fog=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}_createSnow(d){const g=this.snow=new ys(d,this.map.transform,this.scope,this.options);this.stylesheet.snow=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}_createRain(d){const g=this.rain=new Dn(d,this.map.transform,this.scope,this.options);this.stylesheet.rain=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const d of this.map._markers)d._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(d){if(this._checkLoaded(),!d)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const g=this.fog;if(!s.b6(g.get(),d)){g.set(d,this.options),this.stylesheet.fog=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}}else this._createFog(d);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(d){if(this._checkLoaded(),!d)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const g=this.snow;if(!s.b6(g.get(),d)){g.set(d,this.options),this.stylesheet.snow=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}}else this._createSnow(d);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(d){if(this._checkLoaded(),!d)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const g=this.rain;if(!s.b6(g.get(),d)){g.set(d,this.options),this.stylesheet.rain=g.get();const w=this._getTransitionParameters({duration:0});g.updateTransitions(w)}}else this._createRain(d);this._markersNeedUpdate=!0}_reloadColorTheme(){const d=()=>{for(const A in this._layers)this._layers[A].lut=this._styleColorTheme.lut;for(const A in this._sourceCaches)this._sourceCaches[A].clearTiles()},g=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!g)return this._styleColorTheme.lut=null,void d();const w=this._evaluateColorThemeData(g);this._loadColorTheme(w).then(()=>{this.fire(new s.C("colorthemeset")),d()}).catch(A=>{s.w(`Couldn't set color theme: ${A}`)})}setColorTheme(d){this._checkLoaded(),this._styleColorTheme.colorThemeOverride&&s.w("Note: setColorTheme is called on a style with a color-theme override, the passed color-theme won't be visible."),this._styleColorTheme.colorTheme=d,this._reloadColorTheme()}setImportColorTheme(d,g){const w=this.getFragmentStyle(d);w&&(w._styleColorTheme.colorThemeOverride=g,w._reloadColorTheme())}_getTransitionParameters(d){return{now:s.o.now(),transition:Object.assign(this.transition,d)}}updateDrapeFirstLayers(){if(!this.terrain)return;const d=[],g=[];for(const w of this._mergedOrder)this.isLayerDraped(this._mergedLayers[w])?d.push(w):g.push(w);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...d),this._drapedFirstOrder.push(...g)}_createTerrain(d,g){const w=this.terrain=new kn(d,g,this.scope,this.options,this.map.getWorldview());g===1&&(this.stylesheet.terrain=d),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const A=this._getTransitionParameters({duration:0});w.updateTransitions(A)}_force3DLayerUpdate(){for(const d in this._layers){const g=this._layers[d];g.type==="fill-extrusion"&&this._updateLayer(g)}}_forceSymbolLayerUpdate(){for(const d in this._layers){const g=this._layers[d];g.type==="symbol"&&this._updateLayer(g)}}_validate(d,g,w,A,I={}){if(I&&I.validate===!1)return!1;const L=Object.assign({},this.serialize());return Tp(this,d.call(tu,Object.assign({key:g,style:L,value:w,styleSpec:s.a8},A)))}_remove(){this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),s.dj.off("pluginStateChange",this._rtlTextPluginCallback);for(const d in this._mergedLayers)this._mergedLayers[d].setEventedParent(null);for(const d in this._mergedSourceCaches)this._mergedSourceCaches[d].clearTiles(),this._mergedSourceCaches[d].setEventedParent(null);this.imageManager.removeScope(this.scope),this.imageManager.imageAtlasCache.clear(),this.setEventedParent(null),delete this.fog,delete this.snow,delete this.rain,delete this.terrain,delete this.ambientLight,delete this.directionalLight,this.indoorManager.destroy(),this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.imageManager.destroy(),this.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(d){const g=this.getSourceCaches(d);for(const w of g)w.clearTiles()}clearSources(){for(const d in this._mergedSourceCaches)this._mergedSourceCaches[d].clearTiles()}clearLayers(){for(const d in this._mergedLayers){const g=this._mergedLayers[d];g._clear&&g._clear()}}reloadSource(d){const g=this.getSourceCaches(d);for(const w of g)w.resume(),w.reload()}reloadSources(){for(const d of this.getSources())d.reload&&d.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(d=>{d.modelManager.reloadModels(d.scope)})}updateSources(d){let g;this.directionalLight&&(g=vj(this.directionalLight));const w=new Set,A=new Set,I=new Set;for(const L in this._mergedLayers){const F=this._mergedLayers[L];F.type==="building"?w.add(F.source):F.type==="raster"&&F.paint&&F.paint.get("raster-elevation-reference")==="ground"&&I.add(F.source),F.hasElevation()&&!A.has(F.source)&&A.add(F.source)}for(const L in this._mergedSourceCaches){const F=this._mergedSourceCaches[L],$=A.has(F._source.id);F._isRasterElevatedOverTerrain=I.has(F._source.id),w.has(F._source.id)&&(F._source.reparseOverscaled=!1),F.update(d,void 0,void 0,g,$)}}_generateCollisionBoxes(){for(const d in this._sourceCaches){const g=this._sourceCaches[d];g.resume(),g.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new s.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new Ex),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(d,g,w,A,I){this.pauseablePlacement||(this.pauseablePlacement=new Ex);let L=!1,F=!1;const $={},H={};for(const oe of this._mergedOrder){const me=this._mergedLayers[oe];if(me.type!=="symbol")continue;const pe=s.F(me.source,me.scope);let je=$[pe];if(!je){const xe=this.getLayerSourceCache(me);if(!xe)continue;const Ze=xe.getRenderableIds(!0).map(ze=>xe.getTileByID(ze));H[pe]=Ze.slice(),je=$[pe]=Ze.sort((ze,Ke)=>Ke.tileID.overscaledZ-ze.tileID.overscaledZ||(ze.tileID.isLessThan(Ke.tileID)?-1:1))}const Re=this.crossTileSymbolIndex.addLayer(me,je,d.center.lng,d.projection);L=L||Re}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const Y=!!(this.placement&&!d.equals(this.placement.transform)),te=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!I||this.placement.lastReplacementSourceUpdateTime!==I.updateTime)),ee=Y||te||L,ie=(ee||this.pauseablePlacement.isStale())&&w===0,le=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(s.o.now(),d.zoom)&&w!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||ie||le)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(d,this._mergedOrder,g,w,A,this.placement,this.fog&&d.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const oe=this.map.painter.maxFrontCutoffRawStart;if(oe>0){const me=180*d.pitch/Math.PI;if(me>=15){const pe=Math.min(1,Math.max(0,(me-15)/5)),je=pe*pe*(3-2*pe);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-je)+oe*je}}}if(this.pauseablePlacement.isDone()?ee&&w!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,$,H,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(s.o.now()),F=!0),L&&this.pauseablePlacement.setStale()),F||L){this._buildingIndex.onNewFrame(d.zoom);for(let oe=0;oeI===d.id)!==-1)return void this.fire(new s.B(new Error(`Import with id '${d.id}' already exists in the map's style.`)));if(!g)return w.push(d),this._loadImports([d],!0);const A=w.findIndex(({id:I})=>I===g);return A===-1&&this.fire(new s.B(new Error(`Import with id "${g}" does not exist on this map.`))),this.stylesheet.imports=w.slice(0,A).concat(d).concat(w.slice(A)),this._loadImports([d],!0,g)}updateImport(d,g){this._checkLoaded();const w=this.stylesheet.imports||[],A=this.getImportIndex(d);return A===-1?this:typeof g=="string"?(this.setImportUrl(d,g),this):(g.url&&g.url!==w[A].url&&this.setImportUrl(d,g.url),s.b6(g.config,w[A].config)||this.setImportConfig(d,g.config,g.data.schema),s.b6(g.data,w[A].data)||this.setImportData(d,g.data),this)}moveImport(d,g){this._checkLoaded();let w=this.stylesheet.imports||[];const A=this.getImportIndex(d);if(A===-1)return this;const I=this.getImportIndex(g);if(I===-1)return this;const L=w[A],F=this.fragments[A];return w=w.filter(({id:$})=>$!==d),this.fragments=this.fragments.filter(({id:$})=>$!==d),this.stylesheet.imports=w.slice(0,I).concat(L).concat(w.slice(I)),this.fragments=this.fragments.slice(0,I).concat(F).concat(this.fragments.slice(I)),this.mergeLayers(),this}setImportUrl(d,g){this._checkLoaded();const w=this.stylesheet.imports||[],A=this.getImportIndex(d);if(A===-1)return this;w[A].url=g;const I=this.fragments[A];return I.style=this._createFragmentStyle(w[A]),I.style.on("style.import.load",()=>this.mergeAll()),I.style.loadURL(g),this}setImportData(d,g){this._checkLoaded();const w=this.getImportIndex(d),A=this.stylesheet.imports||[];return w===-1?this:g?(this.fragments[w].style.setState(g),this._reloadImports(),this):(delete A[w].data,this.setImportUrl(d,A[w].url))}setImportConfig(d,g,w){this._checkLoaded();const A=this.getImportIndex(d),I=this.stylesheet.imports||[];if(A===-1)return this;g?I[A].config=g:delete I[A].config;const L=this.fragments[A];w&&L.style.stylesheet&&(L.style.stylesheet.schema=w);const F=L.style.stylesheet&&L.style.stylesheet.schema;return L.config=g,L.style.updateConfig(g,F),this.updateConfigDependencies(),this}removeImport(d){this._checkLoaded();const g=this.stylesheet.imports||[],w=this.getImportIndex(d);w!==-1&&(g.splice(w,1),this.fragments[w].style._remove(),this.fragments.splice(w,1),this._reloadImports())}getImportIndex(d){const g=(this.stylesheet.imports||[]).findIndex(w=>w.id===d);return g===-1&&this.fire(new s.B(new Error(`Import '${d}' does not exist in the map's style and cannot be updated.`))),g}getLayer(d){return this._mergedLayers[d]}getSources(){const d=[];for(const g in this._mergedOtherSourceCaches){const w=this._mergedOtherSourceCaches[g];w&&d.push(w.getSource())}return d}getSource(d,g){const w=this.getSourceCache(d,g);return w&&w.getSource()}getLayerSource(d){const g=this.getLayerSourceCache(d);return g&&g.getSource()}getSourceCache(d,g){const w=s.F(d,g);return this._mergedOtherSourceCaches[w]}getLayerSourceCache(d){const g=s.F(d.source,d.scope);return d.type==="symbol"?this._mergedSymbolSourceCaches[g]:d.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[g]||this._mergedOtherSourceCaches[g]}getSourceCaches(d){if(d==null)return Object.values(this._mergedSourceCaches);const g=[];return this._mergedOtherSourceCaches[d]&&g.push(this._mergedOtherSourceCaches[d]),this._mergedSymbolSourceCaches[d]&&g.push(this._mergedSymbolSourceCaches[d]),this._mergedFillExtrusionSourceCaches[d]&&g.push(this._mergedFillExtrusionSourceCaches[d]),g}updateSourceCaches(){const d=this._changes.getUpdatedSourceCaches();for(const g in d){const w=d[g];w==="reload"?this.reloadSource(g):w==="clear"&&this.clearSource(g)}}updateLayers(d){const g=this._changes.getUpdatedPaintProperties();for(const w of g){const A=this.getLayer(w);A&&A.updateTransitions(d)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(d){this.stylesheet.glyphs=d,this.glyphManager.setURL(d)}getImages(d,g,w){this.imageManager.getImages(g.images,g.scope,w),this._updateTilesForChangedImages();const A=L=>{if(L){const F=g.images.map($=>s.I.toString($));L.setDependencies(g.tileID.key,g.type,F)}},I=s.F(g.source,g.scope);A(this._mergedOtherSourceCaches[I]),A(this._mergedSymbolSourceCaches[I]),g.images.some(L=>L.iconsetId)&&this.fire(new s.C("data",{dataType:"style"}))}rasterizeImages(d,g,w){this.imageManager.rasterizeImages(g,w)}checkAtlasCache(d,g,w){const A=this.imageManager.imageAtlasCache.findCachedAtlas(g.descriptor);w(null,A&&A.contentDescriptor?{iconPositions:A.iconPositions,patternPositions:A.patternPositions,sourceHash:A.contentDescriptor.hash}:null)}getGlyphs(d,g,w){this.glyphManager.getGlyphs(g.stacks,w)}getOwnSourceCache(d){return this._otherSourceCaches[d]}getOwnLayerSourceCache(d){return d.type==="symbol"?this._symbolSourceCaches[d.source]:d.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[d.source]||this._otherSourceCaches[d.source]}getOwnSourceCaches(d){const g=[];return this._otherSourceCaches[d]&&g.push(this._otherSourceCaches[d]),this._symbolSourceCaches[d]&&g.push(this._symbolSourceCaches[d]),this._fillExtrusionSourceCaches[d]&&g.push(this._fillExtrusionSourceCaches[d]),g}_isSourceCacheLoaded(d){const g=this.getOwnSourceCaches(d);return g.length===0?(this.fire(new s.B(new Error(`There is no source with ID '${d}'`))),!1):g.every(w=>w.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(d,g){if(!this._clipLayerPresent&&d.type!=="fill-extrusion"&&d.type!=="building")return!1;const w=d.type==="fill-extrusion"&&(d.sourceLayer==="building"||d.sourceLayer==="procedural_buildings"),A=d.type==="building";if(d.is3D(!!this.terrain)){if(w||A||g&&g.type==="batched-model"||d.type==="model")return!0}else if(d.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(d=>{d.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}ou.getSourceType=function(v){return Z0[v]},ou.setSourceType=function(v,d){Z0[v]=d},ou.registerForPluginStateChange=s.dk;var cT=` #define EPSILON 0.0000001 #define PI 3.141592653589793 #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`,uT=` #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 dot(rgba_depth,bit_shift)*2.0-1.0;}highp vec4 pack_depth(highp float ndc_z) {highp float depth=ndc_z*0.5+0.5;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;} #ifdef INDICATOR_CUTOUT uniform vec3 u_indicator_cutout_centers;uniform vec4 u_indicator_cutout_params; #endif 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 );vec4 applyCutout(vec4 color,float height) { #ifdef INDICATOR_CUTOUT float verticalFadeRange=u_indicator_cutout_centers.z*0.25;float holeMinOpacity=mix(1.0,u_indicator_cutout_params.x,smoothstep(u_indicator_cutout_centers.z,u_indicator_cutout_centers.z+verticalFadeRange,height));float holeRadius=max(u_indicator_cutout_params.y,0.0);float holeAspectRatio=u_indicator_cutout_params.z;float fadeStart=u_indicator_cutout_params.w;float distA=distance(vec2(gl_FragCoord.x,gl_FragCoord.y*holeAspectRatio),vec2(u_indicator_cutout_centers[0],u_indicator_cutout_centers[1]*holeAspectRatio));return color*min(smoothstep(fadeStart,holeRadius,distA)+holeMinOpacity,1.0); #else return color; #endif }float cutoutGroundRoofOpacity(vec4 groundRoof) { #ifdef INDICATOR_CUTOUT float fadeStartX=u_indicator_cutout_params.w;float holeRadius=u_indicator_cutout_params.y;float holeMinOpacity=mix(u_indicator_cutout_params.x,1.0,smoothstep(u_indicator_cutout_params.z,u_indicator_cutout_centers.z,groundRoof.y));float distX=abs(u_indicator_cutout_centers.x-groundRoof.x);float roofOpacity=mix(holeMinOpacity,1.0,smoothstep(fadeStartX,holeRadius,u_indicator_cutout_centers.y-groundRoof.w));float groundOpacity=min(smoothstep(fadeStartX,holeRadius,distX)+holeMinOpacity,1.0);return max(roofOpacity,groundOpacity); #else return 1.0; #endif } #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 applyLUT(highp sampler3D lut,vec4 col) {vec3 size=vec3(textureSize(lut,0));vec3 uvw=(col.rbg*float(size-1.0)+0.5)/size;return vec4(texture(lut,uvw).rgb*col.a,col.a);}vec3 applyLUT(highp sampler3D lut,vec3 col) {return applyLUT(lut,vec4(col,1.0)).rgb;}`,uf=` #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);} #ifndef HAS_SHADER_STORAGE_BLOCK_material_buffer #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 #endif`,Rx="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;}",dT=` #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;vec3 elevationVector(vec2 pos) {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 vec3 elevationVector(vec2 pos) { return vec3(0,0,1); } #endif #ifdef TERRAIN uniform highp sampler2D u_dem;uniform highp sampler2D u_dem_prev;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 }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 } #ifdef TERRAIN_VERTEX_MORPHING float elevation(vec2 apos) { #ifdef ZERO_EXAGGERATION return 0.0; #endif float nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp);} #else float elevation(vec2 apos) { #ifdef ZERO_EXAGGERATION return 0.0; #endif return currentElevation(apos);} #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);} #else float elevation(vec2 pos) { 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*u_depth_range_unpack.x+u_depth_range_unpack.y;}vec4 unpack_depth4(vec4 depth) {return depth*u_depth_range_unpack.x+vec4(u_depth_range_unpack.y);} #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 dot(rgba_depth,bit_shift)*2.0-1.0;} #endif bool isOccluded(vec4 frag) {vec3 coord=frag.xyz/frag.w; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif #ifdef DEPTH_D24 float depth=unpack_depth(texture(u_depth,(coord.xy+1.0)*0.5).r); #else float depth=unpack_depth_rgba(texture(u_depth,(coord.xy+1.0)*0.5)); #endif return coord.z+u_occlusion_depth_offset > depth;}highp vec4 getCornerDepths(vec2 coord) {highp vec3 df=vec3(u_occluder_half_size*u_depth_size_inv,0.0);highp vec2 uv=0.5*coord.xy+0.5; #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=0.5*coord.xy+0.5; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif 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(300.0*(coord.z+u_occlusion_depth_offset-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; #ifdef CLIP_ZERO_TO_ONE coord.z=-1.0+2.0*coord.z; #endif highp vec4 depth=getCornerDepths(coord.xy);return dot(vec4(0.25),vec4(1.0)-clamp(300.0*(vec4(coord.z+u_occlusion_depth_offset)-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`,hT=`#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`,ig=`#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=gl_FragCoord.xy/u_viewport; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif 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`,sg=`#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`,fT=`#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;}`,dv=`#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`,wc=`#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;float shadow_sample(sampler2DShadow shadowmap,highp vec3 pos,highp float bias) { #ifdef CLIP_ZERO_TO_ONE highp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z-bias); #else highp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z*0.5+0.5-bias); #endif 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=light_view_pos0.xyz/light_view_pos0.w*0.5+0.5;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 Lx=/#include\s+"([^"]+)"/g,ar=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,Sj=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,Tj=new Set(["ifdef","ifndef","elif","if","defined"]),Ep=new Set;ch(cT,Ep),ch(uf,Ep),ch(uT,Ep);const Ou={"_prelude_fog.vertex.glsl":hT,"_prelude_terrain.vertex.glsl":dT,"_prelude_shadow.vertex.glsl":dv,"_prelude_material_table.vertex.glsl":`#ifdef HAS_SHADER_STORAGE_BLOCK_material_buffer #define MATERIAL_TABLE_DEBUG 0 uniform int u_material_offset;uniform int u_vertex_offset;layout(std140,binding=0)readonly buffer material_buffer{uvec4 material_data[];};struct MaterialInfo{uint dataOffset; #if MATERIAL_TABLE_DEBUG vec4 colorDebug; #endif };uint read_buf_no_offset(uint iDword) {return material_data[iDword/4u][iDword % 4u];}uint read_buf(uint iDword) {iDword+=uint(u_material_offset/4);return read_buf_no_offset(iDword);}float read_buf_float(uint iDword){return uintBitsToFloat(read_buf(iDword));}uint read_buf_uint8(uint iDword,uint iUint8){uint dwordOffset=iDword+(iUint8/4u);uint byteOffset=iUint8 & 3u;uint bitOffset=8u*byteOffset;uint mask=0xffu << bitOffset;uint dwordVal=read_buf(dwordOffset);return (dwordVal & mask) >> bitOffset;}uint read_buf_uint16(uint iDword,uint iUint16){uint dwordOffset=iDword+(iUint16 >> 1u);uint bitOffset=(iUint16 & 1u)*16u;uint mask=0xffffu << bitOffset;uint dwordVal=read_buf(dwordOffset);return (dwordVal & mask) >> bitOffset;}uint nrDwordsForVertexIdEntries(uint nrMaterialLookupEntries) {return nrMaterialLookupEntries;}uint nrDwordsForMaterialIdEntries(uint nrMaterialLookupEntries) {return (nrMaterialLookupEntries*2u+3u)/4u;}uint findRangeBinarySearch(uint vertexId,uint numRanges,uint dwordOffset) {uint left=0u;uint right=numRanges-1u;for (uint i=0u; i < 16u; i++) { if (left > right) {break;}uint mid=(left+right)/2u;uint start=read_buf(dwordOffset+mid);uint nextStart=(mid+1u < numRanges) ? read_buf(dwordOffset+mid+1u) : 0xffffffffu;if (vertexId >=start && vertexId < nextStart) {return mid;} else if (vertexId < start) {if (mid==0u) {break;}right=mid-1u;} else {left=mid+1u;}}return 0u; }uint readVertexId(uint dwordOffset,uint iMaterialLookupEntry) {return read_buf(dwordOffset+iMaterialLookupEntry);}uint findRange(uint vertexId,uint numRanges,uint dwordOffset) {uint iRange;if(numRanges <=64u){uint vertexBegin;for(iRange=0u; iRange < numRanges;++iRange) {vertexBegin=readVertexId(dwordOffset,iRange);if(vertexBegin > vertexId) {break;}}iRange=iRange==0u? 0u : iRange-1u;} else { iRange=findRangeBinarySearch(vertexId,numRanges,dwordOffset);}return iRange;}MaterialInfo read_material_info(uint vertex_id) {MaterialInfo info; #if MATERIAL_TABLE_DEBUG const vec4 red=vec4(1.0,0.0,0.0,1.0);const vec4 orange=vec4(1.0,0.5,0.0,1.0);const vec4 yellow=vec4(1.0,1.0,0.0,1.0);const vec4 green=vec4(0.0,1.0,0.0,1.0);const vec4 indigo=vec4(0.294,0.0,0.510,1.0);const vec4 blue=vec4(0.0,0.0,1.0,1.0);const vec4 purple=vec4(0.5,0.0,0.5,1.0);const vec4 pink=vec4(1.0,0.0,1.0,1.0);info.colorDebug=green; #endif uint offset=0u; #if MATERIAL_TABLE_DEBUG bool keepFinding=true;uint magic=read_buf(offset);if(magic !=0xCAFEBABEu) {info.colorDebug=red;keepFinding=false;return info;} #endif offset++; #if MATERIAL_TABLE_DEBUG uint nrMaterials=read_buf(offset);uint nrVertices=read_buf(offset+1u);if(keepFinding && vertex_id >=nrVertices) {info.colorDebug=red;keepFinding=false;} #endif offset+=2u;uint nrMaterialLookupEntries=read_buf(offset++);uint perMaterialEntrySizeDwords=read_buf(offset++); #if MATERIAL_TABLE_DEBUG if(keepFinding && perMaterialEntrySizeDwords !=1u) {info.colorDebug=red;keepFinding=false;} #endif uint iMaterialLookup=findRange(vertex_id,nrMaterialLookupEntries,offset); #if MATERIAL_TABLE_DEBUG if(keepFinding) {uint vertexBeginCheck=readVertexId(offset,iMaterialLookup);if(vertexBeginCheck > vertex_id) {info.colorDebug=red;keepFinding=false;}if(iMaterialLookup < nrMaterialLookupEntries-1u) {uint vertexEndCheck=readVertexId(offset,iMaterialLookup+1u);if(vertexEndCheck <=vertex_id) {info.colorDebug=red;keepFinding=false;}}} #endif offset+=nrDwordsForVertexIdEntries(nrMaterialLookupEntries);uint materialId=iMaterialLookup; #if MATERIAL_TABLE_DEBUG if(keepFinding) {if(materialId >=nrMaterialLookupEntries) {info.colorDebug=red;}} #endif info.dataOffset=offset+materialId*perMaterialEntrySizeDwords;return info;}uint get_data_location(const MaterialInfo matInfo,uint attribOffsetBytes) {uint attribFieldOffsetDwords=attribOffsetBytes/4u;return matInfo.dataOffset+attribFieldOffsetDwords;}vec4 read_material_vec4(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return vec4(read_buf_float(loc),read_buf_float(loc+1u),read_buf_float(loc+2u),read_buf_float(loc+3u));}vec2 read_material_vec2(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return vec2(read_buf_float(loc),read_buf_float(loc+1u));}float read_material_float(const MaterialInfo matInfo,uint attribOffsetBytes){uint loc=get_data_location(matInfo,attribOffsetBytes);return read_buf_float(loc);} #define GET_ATTRIBUTE_float(attrib,matInfo,attrib_offset) read_material_float(matInfo,attrib_offset) #define GET_ATTRIBUTE_vec4(attrib,matInfo,attrib_offset) read_material_vec4(matInfo,attrib_offset) #define GET_ATTRIBUTE_vec2(attrib,matInfo,attrib_offset) read_material_vec2(matInfo,attrib_offset) #define DECLARE_MATERIAL_TABLE_INFO MaterialInfo materialInfo=read_material_info(uint(gl_VertexID)); #define DECLARE_MATERIAL_TABLE_INFO_DEBUG(dbgColor) MaterialInfo materialInfo=read_material_info(uint(gl_VertexID)); dbgColor=materialInfo.colorDebug; #endif`,"_prelude_fog.fragment.glsl":ig,"_prelude_shadow.fragment.glsl":wc,"_prelude_lighting.glsl":` #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`,"_prelude_raster_array.glsl":sg,"_prelude_raster_particle.glsl":fT},ag={};Bn("",dT),Bn(ig,hT),Bn(wc,dv),Bn(sg,""),Bn(fT,"");const df=Bn(uT,uf),Dx=cT,og=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",Dx,df.fragmentSource].join(` `),v3=["precision highp float;",Dx,df.vertexSource].join(` `);var Ej={background:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.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 FEATURE_CUTOUT vec2 uv=gl_FragCoord.xy*u_inv_viewport_size.xy; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif float factorTex=min(texture(u_cutout_factor_image,uv).r,1.0);float cutoutFactor=(1.0-u_feature_cutout_params.x)*factorTex;out_color=u_color*(1.0-cutoutFactor); #else #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 #endif glFragColor=out_color*u_opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #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); #ifndef FEATURE_CUTOUT #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 #endif }`),backgroundPattern:Bn(`#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; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #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 }`),building:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.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; #ifdef RENDER_FRONT_CUTOFF in float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT in vec4 v_ground_roof; #endif #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 0 if (x_major) {out_color=v.x > 0.0 ? vec3(1.0,0.0,0.0) : vec3(0.0,1.0,1.0);} else if (y_major) {out_color=v.y > 0.0 ? vec3(0.0,1.0,0.0) : vec3(1.0,0.0,1.0);} else if (z_major) {out_color=v.z > 0.0 ? vec3(0.0,0.0,1.0) : vec3(1.0,1.0,0.0);}out_emissive=1.0; #else 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; #endif 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);if (v_cutoff_opacity==0.0) {discard;} #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; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT {float ditherOpacity=cutoutGroundRoofOpacity(v_ground_roof);if (ditherOpacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (ditherOpacity < DITHER_THRESHOLDS[index]) {discard;}}} #else color=applyCutout(color,v_pos.z); #endif #endif #ifdef RENDER_FRONT_CUTOFF if (v_front_cutoff_opacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (v_front_cutoff_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #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" in vec3 a_pos_3f;in ivec4 a_normal_3;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; #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params;out float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT out vec4 v_ground_roof; #endif #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 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 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);vec3 a_normal_3f=vec3(a_normal_3)/MAX_INT_16;v_normal=vec3(u_normal_matrix*vec4(a_normal_3f,0.0));float hidden=0.0;float depth_offset=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=a_pos_3f; #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,ground.z);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 v_front_cutoff_opacity=1.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;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);v_front_cutoff_opacity=mix(u_front_cutoff_params.z,1.0,t);} #endif gl_Position=mix(u_matrix*vec4(v_pos,1),AWAY,hidden);gl_Position.z-=depth_offset*gl_Position.w; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT vec4 ic_ground=u_matrix*vec4(v_pos.xy,0.0,1.0);vec4 ic_roof=u_matrix*vec4(v_pos.xy,v_pos.z,1.0);v_ground_roof=vec4(ic_ground.xy/ic_ground.w,ic_roof.xy/ic_roof.w); #endif #endif }`),buildingBloom:Bn(`in vec4 v_color_emissive; #pragma mapbox: define-attribute highp vec4 bloom_attenuation #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation float saturate(float val) {return clamp(val,0.0,1.0);}void main() {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,gl_Position.z); #endif }`),buildingDepth:Bn("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:Bn(`#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_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 view_scale) {return extrusion*(radius+stroke_width)*u_extrude_scale*view_scale;}float cantilevered_elevation(vec2 pos,float radius,float stroke_width,float view_scale) {vec2 c1=pos+calc_offset(vec2(-1.0,-1.0),radius,stroke_width,view_scale);vec2 c2=pos+calc_offset(vec2(1.0,-1.0),radius,stroke_width,view_scale);vec2 c3=pos+calc_offset(vec2(1.0,1.0),radius,stroke_width,view_scale);vec2 c4=pos+calc_offset(vec2(-1.0,1.0),radius,stroke_width,view_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 view_scale,mat3 surface_vectors) {vec2 sample_offset=calc_offset(extrusion,radius,stroke_width,view_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 }float get_sample_step() { #ifdef PITCH_WITH_MAP return 2.0*PI/float(NUM_SAMPLES_PER_RING); #else return PI/float(NUM_SAMPLES_PER_RING); #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 view_scale=0.0; #ifdef PITCH_WITH_MAP #ifdef SCALE_WITH_MAP view_scale=1.0; #else view_scale=projected_center.w/u_camera_to_center_distance; #endif #else #ifdef SCALE_WITH_MAP view_scale=u_camera_to_center_distance; #else view_scale=projected_center.w; #endif #endif gl_Position=project_vertex(extrude,world_center,projected_center,radius,stroke_width,view_scale,surface_vectors);float visibility=0.0; #ifdef TERRAIN float step=get_sample_step();vec4 occlusion_world_center;vec4 occlusion_projected_center; #ifdef PITCH_WITH_MAP float cantilevered_height=cantilevered_elevation(circle_center,radius,stroke_width,view_scale);occlusion_world_center=vec4(circle_center,cantilevered_height,1);occlusion_projected_center=u_matrix*occlusion_world_center; #else occlusion_world_center=world_center;occlusion_projected_center=projected_center; #endif for(int ring=0; ring < NUM_VISIBILITY_RINGS; ring++) {float scale=(float(ring)+1.0)/float(NUM_VISIBILITY_RINGS);for(int i=0; i < NUM_SAMPLES_PER_RING; i++) {vec2 extrusion=vec2(cos(step*float(i)),-sin(step*float(i)))*scale;vec4 frag_pos=project_vertex(extrusion,occlusion_world_center,occlusion_projected_center,radius,stroke_width,view_scale,surface_vectors);visibility+=float(!isOccluded(frag_pos));}}visibility/=float(NUM_VISIBILITY_RINGS)*float(NUM_SAMPLES_PER_RING); #else visibility=1.0; #endif #ifdef PROJECTION_GLOBE_VIEW visibility=1.0; #endif v_visibility=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:Bn("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:Bn(`#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_opacity;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:Bn(`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=vec2(a_pos)*0.5+0.5;}"),collisionBox:Bn("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:Bn("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 quadCenterPos=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(quadCenterPos);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);}`),debug:Bn("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 }`),elevatedStructuresDepth:Bn("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;}"),elevatedStructuresDepthReconstruct:Bn(`#ifdef DEPTH_RECONSTRUCTION in float v_height; #endif void main() { #ifdef DEPTH_RECONSTRUCTION if (v_height >=0.0) discard; #else #ifdef FEATURE_CUTOUT apply_feature_cutout(vec4(0.0,0.0,0.0,1.0),gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif #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;}`),elevatedStructures:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.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; #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 FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #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); #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_height); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif 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 }`),fill:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity uniform float u_emissive_strength; #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 INDICATOR_CUTOUT in highp float v_z_offset; #endif void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float opacity vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif 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; #ifdef INDICATOR_CUTOUT if (v_z_offset >=0.0) {out_color=applyCutout(out_color,v_z_offset);} #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #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 #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #endif uniform mat4 u_matrix; #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 #ifdef INDICATOR_CUTOUT v_z_offset=z_offset; #endif }`),fillOutline:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" in highp vec2 v_pos;uniform float u_emissive_strength; #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 FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #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 #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color*(alpha*opacity); #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #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; #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;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; #endif float hidden=float(opacity==0.0);gl_Position=mix(u_matrix*vec4(a_pos,z_offset,1),AWAY,hidden); #ifdef FLIP_Y v_pos=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world; #else v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #endif #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:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.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; #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 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=pattern_b.xy;vec2 pattern_b_br=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 FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #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 FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*(alpha*opacity); #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #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 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; #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; #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); #ifdef FLIP_Y v_pos_world=(vec2(gl_Position.x,-gl_Position.y)/gl_Position.w+1.0)/2.0*u_world; #else v_pos_world=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world; #endif #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:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.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; #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 FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #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 FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*opacity; #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #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_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:Bn(`uniform sampler2D u_image;uniform float u_opacity;uniform int u_blend_mode;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;}float density=color.a;vec3 avgColor=color.rgb/max(density,0.001);float t=density/(1.0+density);glFragColor=vec4(avgColor*t*u_opacity,t*u_opacity);} 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;}"),fillExtrusion:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" in vec4 v_color;in vec4 v_flat; #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 RENDER_FRONT_CUTOFF in float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT in vec4 v_ground_roof; #endif #endif #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 #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT {float ditherOpacity=cutoutGroundRoofOpacity(v_ground_roof);if (ditherOpacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (ditherOpacity < DITHER_THRESHOLDS[index]) {discard;}}} #else color=applyCutout(color,h); #endif #endif #ifdef RENDER_FRONT_CUTOFF if (v_front_cutoff_opacity < 1.0) {int index=(int(gl_FragCoord.x) % 4)*4+(int(gl_FragCoord.y) % 4);if (v_front_cutoff_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif #ifdef FEATURE_CUTOUT color=apply_feature_cutout(color,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #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" uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;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; #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params;out float v_front_cutoff_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; #endif #if defined(LIGHTING_3D_MODE) && defined(FLOOD_LIGHT) out float v_flood_radius;out float v_has_floodlight; #endif out float v_height; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT out vec4 v_ground_roof; #endif #endif 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) 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_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_decoded,ele,1.0); #endif #ifdef RENDER_CUTOFF #ifdef CLIP_ZERO_TO_ONE cutoff=cutoff_opacity(u_cutoff_params,ground.z*2.0-ground.w); #else cutoff=cutoff_opacity(u_cutoff_params,ground.z); #endif 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 v_front_cutoff_opacity=1.0;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);v_front_cutoff_opacity=mix(u_front_cutoff_params.z,1.0,t);} #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 gl_Position.z-=(0.0000006*(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 #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT vec4 pos_ground=u_matrix*vec4(pos.xy,ele,1.0);vec4 pos_roof=u_matrix*vec4(pos.xy,ele+height,1.0);v_ground_roof=vec4(pos_ground.xy/pos_ground.w,pos_roof.xy/pos_roof.w); #endif #endif }`),fillExtrusionDepth:Bn("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);}`),fillExtrusionPattern:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.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 #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,height); #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;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;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; #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 gl_Position.z-=(0.0000006*(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 }`),groundShadow:Bn(`#include "_prelude_shadow.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 #ifdef INDICATOR_CUTOUT shadow=mix(shadow,vec3(1.0),1.0-applyCutout(vec4(1.0),0.0).r); #endif #ifdef FEATURE_CUTOUT shadow=mix(shadow,vec3(1.0),get_cutout_factors(gl_FragCoord).y); #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 }`),fillExtrusionGroundEffect:Bn(`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,gl_Position.z); #endif }`),hillshadePrepare:Bn(`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:Bn(`#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 #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #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=vec2(a_texture_pos)/8192.0; #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),line:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_floor_width_scale;uniform float u_alpha_discard_threshold;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;uniform bool u_emissive_in_shadows;in vec4 v_width2_dilute;in vec2 v_normal;in float v_gamma_scale;in highp vec3 v_uv; #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH in float stub_side; #endif #ifdef RENDER_LINE_DASH uniform sampler2D u_dash_image;in vec2 v_tex; #endif #ifdef RENDER_LINE_GRADIENT uniform sampler2D u_gradient_image; #endif #ifdef INDICATOR_CUTOUT in highp float v_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 float luminance(vec3 c) {return (c.r+c.r+c.b+c.g+c.g+c.g)*0.1667;} #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float floorwidth #pragma mapbox: define mediump uvec4 dash #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define mediump float side_z_offset #pragma mapbox: define lowp float border_width #pragma mapbox: define lowp vec4 border_color #pragma mapbox: define lowp float emissive_strength float linearstep(float edge0,float edge1,float x) {return clamp((x-edge0)/(edge1-edge0),0.0,1.0);}void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float floorwidth #pragma mapbox: initialize mediump uvec4 dash #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump float side_z_offset #pragma mapbox: initialize lowp float border_width #pragma mapbox: initialize lowp vec4 border_color #pragma mapbox: initialize lowp float emissive_strength float dist=length(v_normal)*v_width2_dilute.x; #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=clamp(min(dist-(v_width2_dilute.y-blur2),v_width2_dilute.x-dist)/blur2,0.0,1.0); #ifdef VARIABLE_LINE_WIDTH alpha=mix(alpha,1.0,stub_side); #endif alpha=side_z_offset > 0.0 ? 1.0-alpha : alpha; #ifdef RENDER_LINE_DASH float sdfdist=texture(u_dash_image,v_tex).r;float sdfgamma=1.0/(2.0*u_device_pixel_ratio)/(float(dash.z)+float(dash.w)/65535.0);float scaled_floorwidth=(floorwidth*u_floor_width_scale);alpha*=linearstep(0.5-sdfgamma/scaled_floorwidth,0.5+sdfgamma/scaled_floorwidth,sdfdist); #endif 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 RENDER_LINE_BORDER #ifndef VARIABLE_LINE_WIDTH float edgeBlur=((border_width*u_width_scale)+1.0/u_device_pixel_ratio);float alpha2=clamp(min(dist-(v_width2_dilute.y-edgeBlur),v_width2_dilute.x-dist)/edgeBlur,0.0,1.0);if (alpha2 < 1.) {float smoothAlpha=smoothstep(0.6,1.0,alpha2);if (border_color.a==0.0) {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-smoothAlpha));} else {out_color.rgb*=(0.6 +0.4*smoothAlpha);}} else {out_color=mix(border_color*trim_alpha,out_color,smoothAlpha);}out_color*=v_width2_dilute.w;} #endif #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #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); #ifdef LINE_BLEND_MULTIPLY glFragColor=vec4(out_color.rgb+(1.0-out_color.a),1.0);HANDLE_WIREFRAME_DEBUG;return; #endif #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_z_offset); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #endif glFragColor=out_color; #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissive_strength); #else #ifdef USE_MRT1 out_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #endif #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 EXTRUDE_SCALE 0.015873016 in ivec2 a_pos_normal;in uvec4 a_data; #if defined(ELEVATED) || defined(ELEVATED_ROADS) || defined(VARIABLE_LINE_WIDTH) in vec3 a_z_offset_width; #endif #ifdef ELEVATION_GROUND_SCALE in float a_elevation_ground_scale; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) in highp vec3 a_packed; #endif #ifdef RENDER_LINE_DASH in float a_linesofar; #endif 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 highp float u_floor_width_scale; #ifdef RENDER_LINE_CURVE uniform mat3 u_curve_points_x;uniform mat3 u_curve_points_y;uniform mat3 u_curve_points_z;uniform float u_curve_point_count; #endif #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 vec3 v_uv; #ifdef ELEVATED_ROADS out highp float v_road_z_offset; #endif #ifdef VARIABLE_LINE_WIDTH out float stub_side; #endif #ifdef RENDER_LINE_DASH uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out vec2 v_tex; #endif #ifdef RENDER_LINE_GRADIENT uniform float u_image_height; #endif #ifdef INDICATOR_CUTOUT out highp float v_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 highp vec4 color #pragma mapbox: define lowp float floorwidth #pragma mapbox: define mediump uvec4 dash #pragma mapbox: define lowp float blur #pragma mapbox: define lowp float opacity #pragma mapbox: define mediump float gapwidth #pragma mapbox: define lowp float offset #pragma mapbox: define mediump float width #pragma mapbox: define mediump float side_z_offset #pragma mapbox: define lowp float border_width #pragma mapbox: define lowp vec4 border_color #pragma mapbox: define lowp float emissive_strength #ifdef RENDER_LINE_CURVE vec3 getCurvePoint(int index) {int row=index/3;int col=index-row*3;float x=u_curve_points_x[row][col];float y=u_curve_points_y[row][col];float z=u_curve_points_z[row][col];return vec3(x,y,z);}vec3 catmullRom(vec3 p0,vec3 p1,vec3 p2,vec3 p3,float t) {float t2=t*t;float t3=t2*t;return 0.5*( 2.0*p1+(-p0+p2)*t+(2.0*p0-5.0*p1+4.0*p2-p3)*t2+(-p0+3.0*p1-3.0*p2+p3)*t3 );}vec2 catmullRomTangent(vec2 p0,vec2 p1,vec2 p2,vec2 p3,float t) {float t2=t*t;return 0.5*( (-p0+p2)+(2.0*p0-5.0*p1+4.0*p2-p3)*2.0*t+(-p0+3.0*p1-3.0*p2+p3)*3.0*t2 );}struct CurveResult {vec3 point;vec2 tangent;};CurveResult calculateCurve(float line_progress) {float curve_progress=line_progress*(u_curve_point_count-1.0);float curve_progress_local=fract(curve_progress);float curve_segment=floor(curve_progress);int seg=int(curve_segment);vec3 p1=getCurvePoint(seg);vec3 p2=getCurvePoint(seg+1);float is_first_seg=step(curve_segment,0.5);vec3 p0_extrapolated=p1-(p2-p1);vec3 p0_fetched=getCurvePoint(max(seg-1,0));vec3 p0=mix(p0_fetched,p0_extrapolated,is_first_seg);int last_seg=int(u_curve_point_count)-2;float is_last_seg=step(float(last_seg)-0.5,curve_segment);vec3 p3_extrapolated=p2+(p2-p1);vec3 p3_fetched=getCurvePoint(min(seg+2,int(u_curve_point_count)-1));vec3 p3=mix(p3_fetched,p3_extrapolated,is_last_seg);vec3 point=catmullRom(p0,p1,p2,p3,curve_progress_local);vec2 tangent=catmullRomTangent(p0.xy,p1.xy,p2.xy,p3.xy,curve_progress_local)*(u_curve_point_count-1.0);CurveResult result;result.point=point;result.tangent=tangent;return result;} #endif void main() { #pragma mapbox: initialize highp vec4 color #pragma mapbox: initialize lowp float floorwidth #pragma mapbox: initialize mediump uvec4 dash #pragma mapbox: initialize lowp float blur #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize mediump float gapwidth #pragma mapbox: initialize lowp float offset #pragma mapbox: initialize mediump float width #pragma mapbox: initialize mediump float side_z_offset #pragma mapbox: initialize lowp float border_width #pragma mapbox: initialize lowp vec4 border_color #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 highp float line_progress=0.0; #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) || defined(RENDER_LINE_CURVE) line_progress=a_packed[2]; #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);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; #ifdef RENDER_LINE_CURVE CurveResult curve=calculateCurve(line_progress);pos=curve.point.xy*8192.0;a_extrude=length(a_extrude)*normalize(curve.tangent);a_extrude=left ? vec2(-a_extrude.y,a_extrude.x) : vec2(a_extrude.y,-a_extrude.x);a_z_offset+=curve.point.z; #endif gapwidth=gapwidth/2.0;float halfwidth;float dilute_scale=1.0;float dilute_border_scale=1.0; #ifdef VARIABLE_LINE_WIDTH float left_width=a_z_offset_width.y;float right_width=a_z_offset_width.z;halfwidth=(u_width_scale*(left ? left_width : right_width))/2.0;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*=left_f;}offset=border_width > 0.0 ? (left_width+right_width)*u_width_scale*0.5 : offset;halfwidth=border_width > 0.0 ? border_width*u_width_scale*0.5 : halfwidth;bool zero_right_width=border_width==0.0 && right_width==0.0;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 ? 0.0 : ANTIALIASING);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;gl_Position=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,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 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=u_matrix*vec4(pos+offset2*u_pixels_to_tile_units,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 { #ifdef RENDER_LINE_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 #endif #ifdef ELEVATED_ROADS gl_Position=gl_Position+projected_extrude; #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_TRIM_OFFSET) highp float a_uv_x=a_packed[0];float a_split_index=a_packed[1]; #ifdef RENDER_LINE_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 #ifdef RENDER_LINE_DASH vec4 dashf=vec4(dash);float totalLength=dashf.z+dashf.w/65535.0;float scale=totalLength==0.0 ? 0.0 : u_tile_units_to_pixels/totalLength;v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*dashf.y+dashf.x+0.5)/u_texsize.y); #endif v_width2_dilute=vec4(outset,inset,dilute_scale,dilute_border_scale); #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),linePattern:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" uniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;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 INDICATOR_CUTOUT in highp float v_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 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);if (u_alpha_discard_threshold !=0.0) {if (color.a < u_alpha_discard_threshold) {discard;}} #ifdef INDICATOR_CUTOUT color=applyCutout(color,v_z_offset); #endif glFragColor=color; #ifdef DUAL_SOURCE_BLENDING glFragColorSrc1=vec4(vec3(0.0),emissive_strength); #else #ifdef USE_MRT1 out_Target1=vec4(emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif #endif #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 vec3 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 #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #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 #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),raster:Bn(`#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; #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; #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 #ifdef USE_MRT1 out_Target1=vec4(u_emissive_strength*glFragColor.a,0.0,0.0,glFragColor.a); #endif 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=gl_Position.z; #endif }`),rasterParticle:Bn(`#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=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}`),rasterParticleDraw:Bn("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:Bn("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=uv;gl_Position=vec4(a_pos,0.0,1.0);}"),rasterParticleUpdate:Bn(`#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);}"),symbol:Bn(`#include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #define SDF_PX 8.0 #define SDF 1.0 #define ICON 0.0 uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_halo;uniform lowp float u_scale_factor; #ifdef ICON_TRANSITION uniform float u_icon_transition; #endif #ifdef COLOR_ADJUSTMENT uniform mat4 u_color_adj_mat; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #else #ifdef RENDER_SHADOWS in highp float v_z_offset; #endif #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 #ifdef USE_PAINT_PROPERTIES_UBO in lowp float v_opacity; #ifdef RENDER_SDF 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; #endif #ifdef LIGHTING_3D_MODE in lowp float v_emissive_strength; #endif #else #pragma mapbox: define highp vec4 fill_color #pragma mapbox: define highp vec4 halo_color #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp float halo_width #pragma mapbox: define lowp float halo_blur #pragma mapbox: define lowp float emissive_strength #endif void main() { #ifdef USE_PAINT_PROPERTIES_UBO 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; #ifdef RENDER_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; #endif lowp float emissive_strength=0.0; #ifdef LIGHTING_3D_MODE emissive_strength=v_emissive_strength; #endif #else #pragma mapbox: initialize highp vec4 fill_color #pragma mapbox: initialize highp vec4 halo_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize lowp float halo_width #pragma mapbox: initialize lowp float halo_blur #pragma mapbox: initialize lowp float 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;glFragColor=texture(u_texture_icon,tex_icon)*alpha; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif return;} #endif vec2 cutout_factors=vec2(0.0); #ifdef FEATURE_CUTOUT cutout_factors=get_cutout_factors(gl_FragCoord); #endif #ifdef RENDER_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 #endif out_color*=opacity*fade_opacity; #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 #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_z_offset); #endif #ifdef FEATURE_CUTOUT out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x); #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" #define USING_APPEARANCE 1.0 in ivec4 a_pos_offset;in uvec4 a_tex_size;in ivec4 a_pixeloffset;in vec4 a_projected_pos;in uint a_fade_opacity; #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 OCCLUSION_QUERIES in float a_occlusion_query_opacity; #endif #ifdef ELEVATED_ROADS in vec3 a_x_axis;in vec3 a_y_axis;uniform float u_normal_scale; #endif #ifdef INDICATOR_CUTOUT out highp float v_z_offset; #else #ifdef RENDER_SHADOWS out highp float v_z_offset; #endif #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;uniform mat4 u_inv_matrix;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;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec3 u_up_vector;uniform vec2 u_texsize_icon;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 #ifdef USE_PAINT_PROPERTIES_UBO #ifndef MAX_UBO_SIZE_VEC4 #define MAX_UBO_SIZE_VEC4 1024u #endif #define SPP_HEADER_SIZE_VEC4 3u #define DWORDS_PER_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;};struct PropertyType {bool isDataDriven;bool isZoomDependent;uint offsetDwords;};struct SymbolPropertyHeader {uint dataDrivenBlockSizeVec4;PropertyType fill_np_color;PropertyType halo_np_color;PropertyType opacity;PropertyType halo_width;PropertyType halo_blur;PropertyType emissive_strength;PropertyType occlusion_opacity;PropertyType z_offset;PropertyType translate;};uniform float u_zoom;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 lowp float u_spp_z_offset;uniform lowp vec2 u_spp_translate_rotation;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; #ifdef RENDER_SDF 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; #endif #ifdef LIGHTING_3D_MODE out lowp float v_emissive_strength; #endif PropertyType getPropertyType(uint propertyIndex,uint dataDrivenMask,uint zoomDependentMask,uint offsetDwords) {PropertyType type;type.isDataDriven=(dataDrivenMask & (1u << propertyIndex)) !=0u;type.isZoomDependent=(zoomDependentMask & (1u << propertyIndex)) !=0u;type.offsetDwords=offsetDwords;return type;}SymbolPropertyHeader readSymbolPropertiesHeader() {SymbolPropertyHeader header;uint dataDrivenMask=u_spp_header.header[0][0];uint zoomDependentMask=u_spp_header.header[0][1];header.dataDrivenBlockSizeVec4=u_spp_header.header[0][2];header.fill_np_color =getPropertyType(0u,dataDrivenMask,zoomDependentMask,u_spp_header.header[0][3]);header.halo_np_color =getPropertyType(1u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][0]);header.opacity =getPropertyType(2u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][1]);header.halo_width =getPropertyType(3u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][2]);header.halo_blur =getPropertyType(4u,dataDrivenMask,zoomDependentMask,u_spp_header.header[1][3]);header.emissive_strength =getPropertyType(5u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][0]);header.occlusion_opacity =getPropertyType(6u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][1]);header.z_offset =getPropertyType(7u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][2]);header.translate =getPropertyType(8u,dataDrivenMask,zoomDependentMask,u_spp_header.header[2][3]);return header;}uint uvec4At(uvec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}float vec4At(vec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}vec4 readVec4(uint baseOffsetVec4,uint propertyOffsetDwords) {return u_spp_properties.properties[baseOffsetVec4+propertyOffsetDwords/DWORDS_PER_VEC4];}float readFloat(vec4 slot,uint propertyOffsetDwords) {return slot[propertyOffsetDwords % DWORDS_PER_VEC4];}uint readUint(uvec4 slot,uint offset) {return slot[offset % DWORDS_PER_VEC4];}vec2 readVec2(vec4 slot,uint propertyOffsetDwords) {float x=vec4At(slot,propertyOffsetDwords % DWORDS_PER_VEC4);float y=vec4At(slot,propertyOffsetDwords % DWORDS_PER_VEC4+1u);return vec2(x,y);}uint getDataDrivenBlockOffsetVec4(uint dataDrivenBlockSizeVec4) {uint featureIndex=uint(a_feature_index);uvec4 slot=u_spp_index.block_indices[featureIndex/DWORDS_PER_VEC4];uint blockIndex=uvec4At(slot,featureIndex % DWORDS_PER_VEC4);return blockIndex*dataDrivenBlockSizeVec4;}vec4 readColorProperty(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 color=readVec4(blockOffsetVec4,propertyType.offsetDwords);if (propertyType.isZoomDependent) {color=unpack_mix_color(color,u_zoom);} else {vec2 packedColor=readVec2(color,propertyType.offsetDwords);color=decode_color(packedColor);}return color;}vec2 readVec2Property(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 slot=readVec4(blockOffsetVec4,propertyType.offsetDwords);if (propertyType.isZoomDependent) {vec2 minVal=slot.xy;vec2 maxVal=slot.zw;return mix(minVal,maxVal,u_zoom);}return readVec2(slot,propertyType.offsetDwords);}float readFloatProperty(PropertyType propertyType,uint dataDrivenBlockSizeVec4) {uint blockOffsetVec4=getDataDrivenBlockOffsetVec4(dataDrivenBlockSizeVec4);vec4 slot=readVec4(blockOffsetVec4,propertyType.offsetDwords);float value;if (propertyType.isZoomDependent) {vec2 packedValues=readVec2(slot,propertyType.offsetDwords);value=unpack_mix_vec2(packedValues,u_zoom);} else {value=readFloat(slot,propertyType.offsetDwords);}return value;}SymbolPaintProperties readSymbolPaintProperties() {SymbolPropertyHeader header=readSymbolPropertiesHeader();uint sizeVec4=header.dataDrivenBlockSizeVec4;SymbolPaintProperties props;props.fill_np_color =header.fill_np_color.isDataDriven ? readColorProperty(header.fill_np_color,sizeVec4) : u_spp_fill_np_color;props.halo_np_color =header.halo_np_color.isDataDriven ? readColorProperty(header.halo_np_color,sizeVec4) : u_spp_halo_np_color;props.opacity =header.opacity.isDataDriven ? readFloatProperty(header.opacity,sizeVec4) : u_spp_opacity;props.halo_width =header.halo_width.isDataDriven ? readFloatProperty(header.halo_width,sizeVec4) : u_spp_halo_width;props.halo_blur =header.halo_blur.isDataDriven ? readFloatProperty(header.halo_blur,sizeVec4) : u_spp_halo_blur;props.emissive_strength =header.emissive_strength.isDataDriven ? readFloatProperty(header.emissive_strength,sizeVec4) : u_spp_emissive_strength;props.occlusion_opacity =header.occlusion_opacity.isDataDriven ? readFloatProperty(header.occlusion_opacity,sizeVec4) : u_spp_occlusion_opacity;props.z_offset =header.z_offset.isDataDriven ? readFloatProperty(header.z_offset,sizeVec4) : u_spp_z_offset;props.translate =header.translate.isDataDriven ? readVec2Property(header.translate,sizeVec4) : vec2(0.0);return props;} #else #pragma mapbox: define highp vec4 fill_color #pragma mapbox: define highp vec4 halo_color #pragma mapbox: define lowp float opacity #pragma mapbox: define lowp float halo_width #pragma mapbox: define lowp float halo_blur #pragma mapbox: define lowp float emissive_strength #pragma mapbox: define lowp float occlusion_opacity #pragma mapbox: define lowp float z_offset #endif vec2 unpack_opacity(uint packedOpacity) {return vec2(float(packedOpacity/2u)/127.0,float(packedOpacity & 1u));}void main() { #ifdef USE_PAINT_PROPERTIES_UBO SymbolPaintProperties paint_properties=readSymbolPaintProperties();lowp float opacity=paint_properties.opacity;v_opacity=opacity; #ifdef RENDER_SDF 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; #endif #ifdef LIGHTING_3D_MODE v_emissive_strength=paint_properties.emissive_strength; #endif lowp float occlusion_opacity=paint_properties.occlusion_opacity;lowp float z_offset=paint_properties.z_offset; #else #pragma mapbox: initialize highp vec4 fill_color #pragma mapbox: initialize highp vec4 halo_color #pragma mapbox: initialize lowp float opacity #pragma mapbox: initialize lowp float halo_width #pragma mapbox: initialize lowp float halo_blur #pragma mapbox: initialize lowp float emissive_strength #pragma mapbox: initialize lowp float occlusion_opacity #pragma mapbox: initialize lowp float z_offset #endif 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;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float out_fade_opacity=max(0.0,min(occlusion_fade,fade_opacity[0]+fade_change)); #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 #ifdef OCCLUSION_QUERIES float occludedFadeMultiplier=mix(occlusion_opacity,1.0,a_occlusion_query_opacity);out_fade_opacity*=occludedFadeMultiplier; #endif #ifdef Z_TEST_OCCLUSION out_fade_opacity*=occlusion_opacity; #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); #ifdef USE_PAINT_PROPERTIES_UBO {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;} #endif 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 INDICATOR_CUTOUT v_z_offset=e; #else #ifdef RENDER_SHADOWS v_z_offset=e; #endif #endif }`),terrainRaster:Bn(`#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 float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;vec3 unlit_base=image_color.rgb*(1.0-emissive_strength);vec3 emissive_base=image_color.rgb*emissive_strength;float ndotl=u_shadow_direction.z;float occlusion=ndotl < 0.0 ? 1.0 : 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;color=apply_lighting(image_color,normal,lighting_factor); #ifdef LIGHTING_3D_ALPHA_EMISSIVENESS float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : image_color.a;color.rgb=mix(color.rgb,image_color.rgb,emissive_strength);color.a=1.0; #endif #endif #else color=image_color; #endif #ifdef FOG #ifdef ZERO_EXAGGERATION color=fog_dither(fog_apply_premultiplied(color,v_fog_pos)); #else color=fog_dither(fog_apply_from_vert(color,v_fog_opacity)); #endif #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=decodedPos/8192.0;gl_Position=u_matrix*vec4(decodedPos,elevation,1.0); #ifdef FOG #ifdef ZERO_EXAGGERATION v_fog_pos=fog_position(decodedPos); #else v_fog_opacity=fog(fog_position(vec3(decodedPos,elevation))); #endif #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:Bn("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;}`),skybox:Bn(`#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 }`,Rx),skyboxGradient:Bn(`#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 }`,Rx),skyboxCapture:Bn(` 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=pos.xyz;v_position.y*=-1.0;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);}"),globeRaster:Bn(`#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=gl_FragCoord.xy/u_viewport; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif 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 float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : raster.a;raster=apply_lighting_with_emission_ground(raster,emissive_strength);color=vec4(clamp(raster.rgb,vec3(0),vec3(1))*antialias,antialias); #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 float emissive_strength=u_emissive_texture_available > 0.5 ? texture(u_image1,v_pos0).r : color.a;color=apply_lighting_with_emission_ground(color,emissive_strength);color.a=1.0; #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;uniform mat4 u_merc_matrix;uniform float u_zoom_transition;uniform vec2 u_merc_center;uniform mat3 u_grid_matrix;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=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 }`),globeAtmosphere:Bn(`#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 #ifdef NATIVE glFragColor=vec4(1,1,1,1); #else glFragColor=vec4(0,0,0,1); #endif 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);}`),model:Bn(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" uniform float u_opacity; #ifdef DITHERED_DISCARD uniform float u_dithered_discard_threshold; #endif uniform vec3 u_lightcolor;uniform vec3 u_lightpos;uniform float u_lightintensity;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 vec3 normal_3f #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 vec3 normal_3f #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_pbr 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 #ifdef TERRAIN_FRAGMENT_OCCLUSION in highp float v_depth;uniform highp sampler2D u_depthTexture;uniform highp vec2 u_inv_depth_size;uniform highp vec2 u_depth_range_unpack; #ifdef DEPTH_D24 highp float unpack_depth(highp float depth) {return depth*u_depth_range_unpack.x+u_depth_range_unpack.y;} #else highp float unpack_depth_rgba(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 dot(rgba_depth,bit_shift)*2.0-1.0;} #endif bool isOccluded() {highp vec2 coord=gl_FragCoord.xy*u_inv_depth_size; #ifdef FLIP_Y coord.y=1.0-coord.y; #endif #ifdef DEPTH_D24 highp float depth=unpack_depth(texture(u_depthTexture,coord).r); #else highp float depth=unpack_depth_rgba(texture(u_depthTexture,coord)); #endif return v_depth > depth+0.0005;} #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_pbr #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 if(texColor.w > 0.0) {texColor.rgb/=texColor.w;}texColor.w=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=dp2perp*duv1.x+dp1perp*duv2.x;highp vec3 B=dp2perp*duv1.y+dp1perp*duv2.y; #ifdef FLIP_Y T=-T;B=-B; #endif 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_3f n=normalize(normal_3f); #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)); #ifdef FLIP_Y n=normalize(cross(fdx,fdy)); #else n=normalize(cross(fdx,fdy))*-1.0; #endif #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=normalize(-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_pbr 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() { #ifdef TERRAIN_FRAGMENT_OCCLUSION if (isOccluded()) {discard;} #endif vec3 lightDir=u_lightpos;vec3 lightColor=u_lightcolor; #ifdef LIGHTING_3D_MODE lightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color; #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_pbr 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 #ifdef INDICATOR_CUTOUT finalColor=applyCutout(finalColor,v_position_height.w); #endif #ifdef FEATURE_CUTOUT finalColor=apply_feature_cutout(finalColor,gl_FragCoord,get_cutout_factors(gl_FragCoord).x); #endif glFragColor=finalColor; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in vec3 a_pos_3f; #pragma mapbox: define-attribute highp vec3 normal_3f #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 uvec4 pbr #pragma mapbox: define-attribute-vertex-shader-only highp vec3 heightBasedEmissiveStrength 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 TERRAIN_FRAGMENT_OCCLUSION out highp float v_depth; #endif #ifdef HAS_ATTRIBUTE_a_pbr 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));}void main() { #pragma mapbox: initialize-attribute highp vec3 normal_3f #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 uvec4 pbr #pragma mapbox: initialize-attribute-custom highp vec3 heightBasedEmissiveStrength 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_pbr vec4 albedo_c=decode_color(vec2(pbr.xy));vec2 e_r_m=unpack_float(float(pbr.z));vec2 r_m= unpack_float(e_r_m.y*16.0);r_m.r=r_m.r*16.0;v_color_mix=vec4(albedo_c.rgb,1.0);v_roughness_metallic_emissive_alpha=vec4(vec3(r_m,e_r_m.x)/255.0,albedo_c.a);v_roughness_metallic_emissive_alpha.z*=2.0;float heightBasedRelativeIntepolation=a_pos_3f.z*heightBasedEmissiveStrength.x+heightBasedEmissiveStrength.y;v_height_based_emission_params.x=heightBasedRelativeIntepolation;v_height_based_emission_params.y=heightBasedEmissiveStrength.z;vec2 emissionMultiplierValues=unpack_float(float(pbr.w))/256.0;v_height_based_emission_params.z=emissionMultiplierValues.x;v_height_based_emission_params.w=emissionMultiplierValues.y-emissionMultiplierValues.x; #endif #ifdef FOG v_fog_pos=fog_position(local_pos); #endif #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif #ifdef TERRAIN_FRAGMENT_OCCLUSION v_depth=gl_Position.z/gl_Position.w; #ifdef CLIP_ZERO_TO_ONE v_depth=-1.0+2.0*v_depth; #endif #endif #ifdef HAS_ATTRIBUTE_a_normal_3f #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_3f=rs*((u_lighting_matrix*vec4(normal_3f,0.0)).xyz/squared_scale);normal_3f=normalize(normal_3f); #else normal_3f=vec3(normal_matrix*vec4(normal_3f,0)); #endif #endif #ifdef HAS_ATTRIBUTE_a_pbr #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_3f #ifdef MODEL_POSITION_ON_GPU vec3 offset=shadow_normal_offset(vec3(-normal_3f.xy,normal_3f.z));shadow_pos.xyz+=offset*shadow_normal_offset_multiplier0(); #else vec3 offset=shadow_normal_offset_model(normal_3f);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:Bn("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 }`),stars:Bn(`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);}`),snowParticle:Bn("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:Bn("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:Bn("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);}"),occlusion:Bn("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 ch(v,d){const g=v.split(` `);for(let w of g){if(w=w.trimStart(),w[0]!=="#"||!w.includes("if")||w.startsWith("#endif"))continue;const A=w.match(Sj);if(A)for(const I of A)Tj.has(I)||d.add(I)}}function Aj(v){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(v)}function Bn(v,d){const g=new Set,w=[],A=[];v=v.replace(Lx,(L,F)=>(A.push(F),"")),d=d.replace(Lx,(L,F)=>(w.push(F),""));let I=new Set(Ep);ch(v,I),ch(d,I);for(const L of[...w,...A])ag[L]||(ag[L]=new Set,ch(Ou[L],ag[L])),I=new Set([...I,...ag[L]]);return{fragmentSource:v=v.replace(ar,(L,F,$,H,Y)=>(g.add(Y),F==="define"?` #ifndef HAS_UNIFORM_u_${Y} ${Aj(H)?"flat ":""}in ${$} ${H} ${Y}; #else uniform ${$} ${H} u_${Y}; #endif `:F==="initialize"?` #ifdef HAS_UNIFORM_u_${Y} ${$} ${H} ${Y} = u_${Y}; #endif `:F==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Y} in ${$} ${H} ${Y}; #endif `:F==="initialize-attribute"?"":void 0)),vertexSource:d=d.replace(ar,(L,F,$,H,Y)=>{const te=`MATERIAL_ATTRIBUTE_OFFSET_${Y}`,ee=H==="float"?"vec2":H,ie=`GET_ATTRIBUTE_${ee}(a_${Y}, materialInfo, ${te})`,le=Y.match(/color/)?"color":ee;return F==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${Y} in ${$} ${H} a_${Y}; #endif `:g.has(Y)?F==="define"?` #ifndef HAS_UNIFORM_u_${Y} uniform lowp float u_${Y}_t; #if !defined(${te}) in ${$} ${ee} a_${Y}; #endif ${Aj(H)?"flat ":""}out ${$} ${H} ${Y}; #else uniform ${$} ${H} u_${Y}; #endif `:F==="initialize"?le==="vec4"||le==="uvec4"?` #ifndef HAS_UNIFORM_u_${Y} ${Y} = a_${Y}; #else ${$} ${H} ${Y} = u_${Y}; #endif `:` #if !defined(HAS_UNIFORM_u_${Y}) #ifdef ${te} ${Y} = unpack_mix_${le}(${ie}, u_${Y}_t); #else ${Y} = unpack_mix_${le}(a_${Y}, u_${Y}_t); #endif #else ${$} ${H} ${Y} = u_${Y}; #endif `:F==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Y} in ${$} ${H} a_${Y}; out ${$} ${H} ${Y}; #endif `:F==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Y} ${Y} = a_${Y}; #endif `:void 0:F==="define"?` #ifndef HAS_UNIFORM_u_${Y} uniform lowp float u_${Y}_t; #if !defined(${te}) in ${$} ${ee} a_${Y}; #endif #else uniform ${$} ${H} u_${Y}; #endif `:F==="define-instanced"?le==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${Y}0; in vec4 a_${Y}1; in vec4 a_${Y}2; in vec4 a_${Y}3; #else uniform ${$} ${H} u_${Y}; #endif `:` #ifdef INSTANCED_ARRAYS in ${$} ${ee} a_${Y}; #else uniform ${$} ${H} u_${Y}; #endif `:F==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${Y} ${$} ${H} ${Y} = a_${Y}; #endif `:le==="vec4"||le==="uvec4"?` #ifndef HAS_UNIFORM_u_${Y} #ifdef ${te} ${$} ${H} ${Y} = ${ie}; #else ${$} ${H} ${Y} = a_${Y}; #endif #else ${$} ${H} ${Y} = u_${Y}; #endif `:` #ifndef HAS_UNIFORM_u_${Y} #ifdef ${te} ${$} ${H} ${Y} = unpack_mix_${le}(${ie}, u_${Y}_t); #else ${$} ${H} ${Y} = unpack_mix_${le}(a_${Y}, u_${Y}_t); #endif #else ${$} ${H} ${Y} = u_${Y}; #endif `}),usedDefines:I,vertexIncludes:w,fragmentIncludes:A}}class kj{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(d,g,w,A,I,L,F,$){this.context=d;let H=this.boundPaintVertexBuffers.length!==A.length;for(let te=0;!H&&te{const Ze=Re.paint.get("hillshade-shadow-color"),ze=Re.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Ke=Re.paint.get("hillshade-highlight-color"),De=Re.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Fe=Re.paint.get("hillshade-accent-color"),qe=Re.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",st=Re.paint.get("hillshade-emissive-strength");let Qe=s.ap(Re.paint.get("hillshade-illumination-direction"));if(Re.paint.get("hillshade-illumination-anchor")==="viewport")Qe-=pe.transform.angle;else if(pe.style&&pe.style.enable3dLights()&&pe.style.directionalLight){const ft=pe.style.directionalLight.properties.get("direction"),Rt=s.cP(ft.x,ft.y,ft.z);Qe=s.ap(Rt[1])}const xt=!pe.options.moving;return{u_matrix:xe||pe.transform.calculateProjMatrix(je.tileID.toUnwrapped(),xt),u_image:0,u_latrange:pT(0,je.tileID),u_light:[Re.paint.get("hillshade-exaggeration"),Qe],u_shadow:Ze.toPremultipliedRenderColor(ze?null:Re.lut),u_highlight:Ke.toPremultipliedRenderColor(De?null:Re.lut),u_emissive_strength:st,u_accent:Fe.toPremultipliedRenderColor(qe?null:Re.lut)}})(v,g,w,v.terrain?d.projMatrix:null);v.uploadCommonUniforms(F,ee,d.toUnwrapped());const{tileBoundsBuffer:le,tileBoundsIndexBuffer:oe,tileBoundsSegments:me}=v.getTileBoundsBuffers(g);ee.draw(v,$.TRIANGLES,A,I,L,Gr.disabled,ie,w.id,le,oe,me)}function Cj(v,d,g){if(!d.needsDEMTextureUpload)return;const w=v.context,A=w.gl;w.pixelStoreUnpackPremultiplyAlpha.set(!1),d.demTexture=d.demTexture||v.getTileTexture(g.stride);const I=g.getPixels();d.demTexture?d.demTexture.update(I,{premultiply:!1}):d.demTexture=new s.T(w,I,A.R32F,{premultiply:!1}),d.needsDEMTextureUpload=!1}function w3(v,d,g){const w=v.context,A=w.gl;if(!d.dem)return;const I=d.dem;if(w.activeTexture.set(A.TEXTURE1),Cj(v,d,I),!d.demTexture)return;d.demTexture.bind(A.NEAREST,A.CLAMP_TO_EDGE);const L=I.dim;w.activeTexture.set(A.TEXTURE0);let F=d.hillshadeFBO;if(!F){const ee=new s.T(w,{width:L,height:L,data:null},A.RGBA8);ee.bind(A.LINEAR,A.CLAMP_TO_EDGE),F=d.hillshadeFBO=w.createFramebuffer(L,L,1,"renderbuffer"),F.colorAttachment0.set(ee.texture)}w.bindFramebuffer.set(F.framebuffer),w.viewport.set([0,0,L,L]);const{tileBoundsBuffer:$,tileBoundsIndexBuffer:H,tileBoundsSegments:Y}=v.getMercatorTileBoundsBuffers(),te=[];v.linearFloatFilteringSupported()&&te.push("TERRAIN_DEM_FLOAT_FORMAT"),v.terrain&&v.terrain.renderingToTexture&&v.emissiveMode==="mrt-fallback"&&te.push("USE_MRT1"),v.getOrCreateProgram("hillshadePrepare",{defines:te}).draw(v,A.TRIANGLES,Ir.disabled,Qr.disabled,Kr.unblended,Gr.disabled,((ee,ie)=>{const le=ie.stride,oe=s.bb();return s.bT(oe,0,s.an,-s.an,0,0,1),s.bx(oe,oe,[0,-s.an,0]),{u_matrix:oe,u_image:1,u_dimension:[le,le],u_zoom:ee.overscaledZ}})(d.tileID,I),g.id,$,H,Y),d.needsHillshadePrepare=!1}class as{constructor(d){this.gl=d.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(d){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class jj extends as{getDefault(){return s.aq.transparent.toNonPremultipliedRenderColor(null)}set(d){const g=this.current;(d.r!==g.r||d.g!==g.g||d.b!==g.b||d.a!==g.a||this.dirty)&&(this.gl.clearColor(d.r,d.g,d.b,d.a),this.current=d,this.dirty=!1)}}class S3 extends as{getDefault(){return 1}set(d){(d!==this.current||this.dirty)&&(this.gl.clearDepth(d),this.current=d,this.dirty=!1)}}class hv extends as{getDefault(){return 0}set(d){(d!==this.current||this.dirty)&&(this.gl.clearStencil(d),this.current=d,this.dirty=!1)}}class T3 extends as{getDefault(){return[!0,!0,!0,!0]}set(d){const g=this.current;(d[0]!==g[0]||d[1]!==g[1]||d[2]!==g[2]||d[3]!==g[3]||this.dirty)&&(this.gl.colorMask(d[0],d[1],d[2],d[3]),this.current=d,this.dirty=!1)}}class Ij extends as{getDefault(){return!0}set(d){(d!==this.current||this.dirty)&&(this.gl.depthMask(d),this.current=d,this.dirty=!1)}}class mT extends as{getDefault(){return 255}set(d){(d!==this.current||this.dirty)&&(this.gl.stencilMask(d),this.current=d,this.dirty=!1)}}class fv extends as{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(d){const g=this.current;(d.func!==g.func||d.ref!==g.ref||d.mask!==g.mask||this.dirty)&&(this.gl.stencilFunc(d.func,d.ref,d.mask),this.current=d,this.dirty=!1)}}class gT extends as{getDefault(){const d=this.gl;return[d.KEEP,d.KEEP,d.KEEP]}set(d){const g=this.current;(d[0]!==g[0]||d[1]!==g[1]||d[2]!==g[2]||this.dirty)&&(this.gl.stencilOp(d[0],d[1],d[2]),this.current=d,this.dirty=!1)}}class Ap extends as{getDefault(){return!1}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;d?g.enable(g.STENCIL_TEST):g.disable(g.STENCIL_TEST),this.current=d,this.dirty=!1}}class kp extends as{getDefault(){return[0,1]}set(d){const g=this.current;(d[0]!==g[0]||d[1]!==g[1]||this.dirty)&&(this.gl.depthRange(d[0],d[1]),this.current=d,this.dirty=!1)}}class lg extends as{getDefault(){return!1}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;d?g.enable(g.DEPTH_TEST):g.disable(g.DEPTH_TEST),this.current=d,this.dirty=!1}}class yd extends as{getDefault(){return this.gl.LESS}set(d){(d!==this.current||this.dirty)&&(this.gl.depthFunc(d),this.current=d,this.dirty=!1)}}class Pj extends as{getDefault(){return!1}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;d?g.enable(g.BLEND):g.disable(g.BLEND),this.current=d,this.dirty=!1}}class yT extends as{getDefault(){const d=this.gl;return[d.ONE,d.ZERO,d.ONE,d.ZERO]}set(d){const g=this.current;(d[0]!==g[0]||d[1]!==g[1]||d[2]!==g[2]||d[3]!==g[3]||this.dirty)&&(this.gl.blendFuncSeparate(d[0],d[1],d[2],d[3]),this.current=d,this.dirty=!1)}}class Nj extends as{getDefault(){return s.aq.transparent.toNonPremultipliedRenderColor(null)}set(d){const g=this.current;(d.r!==g.r||d.g!==g.g||d.b!==g.b||d.a!==g.a||this.dirty)&&(this.gl.blendColor(d.r,d.g,d.b,d.a),this.current=d,this.dirty=!1)}}class cg extends as{getDefault(){return this.gl.FUNC_ADD}set(d){(d!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(d,d),this.current=d,this.dirty=!1)}}class pv extends as{getDefault(){return!1}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;d?g.enable(g.CULL_FACE):g.disable(g.CULL_FACE),this.current=d,this.dirty=!1}}class mv extends as{getDefault(){return this.gl.BACK}set(d){(d!==this.current||this.dirty)&&(this.gl.cullFace(d),this.current=d,this.dirty=!1)}}class xT extends as{getDefault(){return this.gl.CCW}set(d){(d!==this.current||this.dirty)&&(this.gl.frontFace(d),this.current=d,this.dirty=!1)}}let gv=class extends as{getDefault(){return null}set(v){(v!==this.current||this.dirty)&&(this.gl.useProgram(v),this.current=v,this.dirty=!1)}};class Ox extends as{getDefault(){return this.gl.TEXTURE0}set(d){(d!==this.current||this.dirty)&&(this.gl.activeTexture(d),this.current=d,this.dirty=!1)}}class Rj extends as{getDefault(){const d=this.gl;return[0,0,d.drawingBufferWidth,d.drawingBufferHeight]}set(d){const g=this.current;(d[0]!==g[0]||d[1]!==g[1]||d[2]!==g[2]||d[3]!==g[3]||this.dirty)&&(this.gl.viewport(d[0],d[1],d[2],d[3]),this.current=d,this.dirty=!1)}}class Lj extends as{getDefault(){return null}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;g.bindFramebuffer(g.FRAMEBUFFER,d),this.current=d,this.dirty=!1}}class Dj extends as{getDefault(){return null}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;g.bindRenderbuffer(g.RENDERBUFFER,d),this.current=d,this.dirty=!1}}class ug extends as{getDefault(){return null}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;g.bindTexture(g.TEXTURE_2D,d),this.current=d,this.dirty=!1}}class Oj extends as{getDefault(){return null}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;g.bindBuffer(g.ARRAY_BUFFER,d),this.current=d,this.dirty=!1}}class E3 extends as{getDefault(){return null}set(d){const g=this.gl;g.bindBuffer(g.ELEMENT_ARRAY_BUFFER,d),this.current=d,this.dirty=!1}}class A3 extends as{getDefault(){return null}set(d){this.gl&&(d!==this.current||this.dirty)&&(this.gl.bindVertexArray(d),this.current=d,this.dirty=!1)}}class k3 extends as{getDefault(){return 4}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;g.pixelStorei(g.UNPACK_ALIGNMENT,d),this.current=d,this.dirty=!1}}class _T extends as{getDefault(){return!1}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;g.pixelStorei(g.UNPACK_PREMULTIPLY_ALPHA_WEBGL,d),this.current=d,this.dirty=!1}}class vT extends as{getDefault(){return!1}set(d){if(d===this.current&&!this.dirty)return;const g=this.gl;g.pixelStorei(g.UNPACK_FLIP_Y_WEBGL,d),this.current=d,this.dirty=!1}}class Mx extends as{constructor(d,g){super(d),this.context=d,this.parent=g}getDefault(){return null}}class dg extends Mx{constructor(d,g,w=0){super(d,g),this.attachmentPoint=d.gl.COLOR_ATTACHMENT0+w}setDirty(){this.dirty=!0}set(d){if(d===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const g=this.gl;g.framebufferTexture2D(g.FRAMEBUFFER,this.attachmentPoint,g.TEXTURE_2D,d,0),this.current=d,this.dirty=!1}}class bT extends Mx{attachment(){return this.gl.DEPTH_ATTACHMENT}set(d){if(d===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const g=this.gl;g.framebufferRenderbuffer(g.FRAMEBUFFER,this.attachment(),g.RENDERBUFFER,d),this.current=d,this.dirty=!1}}class Mj extends Mx{attachment(){return this.gl.DEPTH_ATTACHMENT}set(d){if(d===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const g=this.gl;g.framebufferTexture2D(g.FRAMEBUFFER,this.attachment(),g.TEXTURE_2D,d,0),this.current=d,this.dirty=!1}}class C3 extends bT{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const Fx=(v,d,g,w)=>({u_matrix:v,u_image0:0,u_image1:1,u_skirt_height:d,u_ground_shadow_factor:g,u_emissive_texture_available:w}),hg=(v,d,g,w,A,I,L,F,$,H,Y,te,ee,ie,le,oe,me)=>({u_proj_matrix:Float32Array.from(v),u_globe_matrix:d,u_normalize_matrix:Float32Array.from(w),u_merc_matrix:g,u_zoom_transition:A,u_merc_center:I,u_image0:0,u_image1:1,u_frustum_tl:L,u_frustum_tr:F,u_frustum_br:$,u_frustum_bl:H,u_globe_pos:Y,u_globe_radius:te,u_viewport:ee,u_grid_matrix:me?Float32Array.from(me):new Float32Array(9),u_skirt_height:ie,u_far_z_cutoff:le,u_emissive_texture_available:oe});function wT(v,d){return v!=null&&d!=null&&!(!v.hasData()||!d.hasData())&&v.demTexture!=null&&d.demTexture!=null&&v.tileID.key!==d.tileID.key}const Ro=new class{constructor(){this.operations={}}newMorphing(v,d,g,w,A){if(v in this.operations){const I=this.operations[v];I.to.tileID.key!==g.tileID.key&&(I.queued=g)}else this.operations[v]={startTime:w,phase:0,duration:A,from:d,to:g,queued:null}}getMorphValuesForProxy(v){if(!(v in this.operations))return null;const d=this.operations[v];return{from:d.from,to:d.to,phase:d.phase}}update(v){for(const d in this.operations){const g=this.operations[d];for(g.phase=(v-g.startTime)/g.duration;g.phase>=1||!this._validOp(g);)if(!this._nextOp(g,v)){delete this.operations[d];break}}}_nextOp(v,d){return!!v.queued&&(v.from=v.to,v.to=v.queued,v.queued=null,v.phase=0,v.startTime=d,!0)}_validOp(v){return v.from.hasData()&&v.to.hasData()}},yv={0:null,1:"TERRAIN_VERTEX_MORPHING"};function Bx(v,d,g){if(d===0)return 0;const w=d<1&&g===514?.25/d:1;return 6*Math.pow(1.5,22-v)*Math.max(d,1)*w}function xv(v,d){const g=1<({u_matrix:v});function Ux(v,d,g,w,A){if(A>0){const I=s.o.now(),L=(I-v.timeAdded)/A,F=d?(I-d.timeAdded)/A:-1,$=g.getSource(),H=w.coveringZoomLevel({tileSize:$.tileSize,roundZoom:$.roundZoom}),Y=!d||Math.abs(d.tileID.overscaledZ-H)>Math.abs(v.tileID.overscaledZ-H),te=Y&&v.refreshedUponExpiration?1:s.aC(Y?L:1-F,0,1);return d?{opacity:1,mix:1-te,isFading:L<1}:{opacity:te,mix:0,isFading:L<1}}return{opacity:1,mix:0,isFading:!1}}class _v extends nu{constructor(d){const g={type:"raster-dem",maxzoom:Math.ceil(d.transform.maxZoom)},w=X0("mock-dem",g,d.style.dispatcher,d.style);super("mock-dem",w,null),w.setEventedParent(this),this._sourceLoaded=!0}_loadTile(d,g){d.state="loaded",g(null)}}class ST extends nu{constructor(d){const g=X0("proxy",{type:"geojson",maxzoom:Math.ceil(d.transform.maxZoom)},d.style.dispatcher,d.style);super("proxy",g,null),g.setEventedParent(this),this.map=this.getSource().map=d,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(d,g,w){if(d.freezeTileCoverage)return;this.transform=d;const A=d.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((I,L)=>{if(I[L.key]="",!this._tiles[L.key]){const F=new s.b0(L,this._source.tileSize*L.overscaleFactor(),d.tileZoom,void 0,void 0,this._source.worldview);F.state="loaded",this._tiles[L.key]=F}return I},{});for(const I in this._tiles)I in A||(this.freeFBO(I),this._tiles[I].unloadVectorData(),delete this._tiles[I])}freeFBO(d){const g=this.proxyCachedFBO[d];if(g!==void 0){const w=Object.values(g);this.renderCachePool.push(...w),delete this.proxyCachedFBO[d]}}deallocRenderCache(){this.renderCache.forEach(d=>d.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class vv extends s.aR{constructor(d,g,w){super(d.overscaledZ,d.wrap,d.canonical.z,d.canonical.x,d.canonical.y),this.proxyTileKey=g,this.projMatrix=w}}class Vx extends s.bu{constructor(d,g){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=d,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[w,A,I]=function(){const $=new s.dB,H=new s.dC,Y=131;$.reserve(17161),H.reserve(33800);const te=s.an/128,ee=s.an+te/2,ie=ee+te;for(let oe=-te;oeee||oe<0||oe>ee?24575:0,je=s.aC(Math.round(me),0,s.an),Re=s.aC(Math.round(oe),0,s.an);$.emplaceBack(je+pe,Re)}const le=(oe,me)=>{const pe=me*Y+oe;H.emplaceBack(pe+1,pe,pe+Y),H.emplaceBack(pe+Y,pe+Y+1,pe+1)};for(let oe=1;oe<129;oe++)for(let me=1;me<129;me++)le(me,oe);return[0,129].forEach(oe=>{for(let me=0;me<130;me++)le(me,oe),le(oe,me)}),[$,H,32768]}(),L=d.context;this.gridBuffer=L.createVertexBuffer(w,s.dx.members),this.gridIndexBuffer=L.createIndexBuffer(A),this.gridSegments=s.dy.simpleSegment(0,0,w.length,A.length),this.gridNoSkirtSegments=s.dy.simpleSegment(0,0,w.length,I),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new ST(g.map),this.orthoMatrix=s.bb(),s.bT(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,s.an,0,s.an,0,1);const F=L.gl;this._overlapStencilMode=new Qr({func:F.GEQUAL,mask:255},0,255,F.KEEP,F.KEEP,F.REPLACE),this._previousZoom=d.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=g,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new _v(g.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(d){d.on("data",this._onStyleDataEvent.bind(this)),this._style=d,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(d,g,w){if(d&&d.terrain){this._style!==d&&(this.style=d,this._evaluationZoom=void 0);const A=d.terrain.properties,I=d.terrain.drapeRenderMode===0,L=d.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=s.o.now();const F=d.terrain&&d.terrain.scope,$=A.get("source"),H=I?this._mockSourceCache:d.getSourceCache($,F);if(!H)return void s.w(`Couldn't find terrain source "${$}".`);if(this.sourceCache=H,this._attenuationRange=d.terrain.getAttenuationRange(),this._exaggeration=L?this.calculateExaggeration(g):A.get("exaggeration"),!g.projection.requiresDraping&&L&&this._exaggeration===0)return void this._disable();this.enabled=!0;const Y=()=>{this.sourceCache.used&&s.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(g,te,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,Y(),this._initializing=!0),Y(),g.updateElevation(!0,w),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(g),this._emptyDEMTextureDirty=!0,this._previousZoom=g.zoom}else this._disable()}calculateExaggeration(d){if(this._attenuationRange&&d.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(d.zoom);const g=this._previousCameraAltitude,w=d.getFreeCameraOptions().position.z/d.pixelsPerMeter*d.worldSize;this._previousCameraAltitude=w;const A=g!=null?w-g:Number.MAX_VALUE;if(Math.abs(A)<2)return this._exaggeration;const I=d.zoom,L=this._style.terrain;if(!this._previousUpdateTimestamp)return L.getExaggeration(I);let F=I-this._previousZoom;const $=this._previousUpdateTimestamp;let H=I;this._evaluationZoom!=null&&(H=this._evaluationZoom,Math.abs(I-H)>.5&&(F=.5*(I-H+F)),F*A<0&&(H+=F)),this._evaluationZoom=H;const Y=L.getExaggeration(H),te=Y===L.getExaggeration(Math.max(0,H-.1));if(te&&Math.abs(Y-this._exaggeration)<.01)return Y;let ee=Math.min(.1,.00375*(this._updateTimestamp-$));return(te||Y<.1||Math.abs(F)<1e-4)&&(ee=Math.min(.2,4*ee)),s.am(this._exaggeration,Y,ee)}resetTileLookupCache(d){this._findCoveringTileCache[d]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(d){d.dataType==="source"&&d.coord?this._clearRenderCacheForTile(d.sourceCacheId,d.coord):d.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 d in this._style._mergedSourceCaches)this._style._mergedSourceCaches[d].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(d=>d.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 d=2*this.proxySourceCache.getSource().tileSize;return[d,d]}set useVertexMorphing(d){this._useVertexMorphing=d}updateTileBinding(d){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const g=this.proxySourceCache,w=this.painter.transform;this._initializing&&(this._initializing=w._centerAltitude===0&&this.getAtPointOrZero(s.ag.fromLngLat(w.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const A=this.proxyCoords=g.getIds().map($=>{const H=g.getTileByID($).tileID;return H.projMatrix=w.calculateProjMatrix(H.toUnwrapped()),H});(function($,H){const Y=H.transform.pointCoordinate(H.transform.getCameraPoint()),te=new s.P(Y.x,Y.y);$.sort((ee,ie)=>{if(ie.overscaledZ-ee.overscaledZ)return ie.overscaledZ-ee.overscaledZ;const le=new s.P(ee.canonical.x+(1<{this.proxyToSource[$.key]={}}),this.terrainTileForTile={};const L=this._style._mergedSourceCaches;for(const $ in L){const H=L[$];if(!H.used||(H!==this.sourceCache&&this.resetTileLookupCache(H.id),this._setupProxiedCoordsForOrtho(H,d[$],I),H.usedForTerrain))continue;const Y=d[$];(H.getSource().reparseOverscaled||H._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Y)}this.proxiedCoords[g.id]=A.map($=>new vv($,$.key,this.orthoMatrix)),this._assignTerrainTiles(A),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(I),this.renderingToTexture=!1;const F={};this._visibleDemTiles=[];for(const $ of this.proxyCoords){const H=this.terrainTileForTile[$.key];if(!H)continue;const Y=H.tileID.key;Y in F||(this._visibleDemTiles.push(H),F[Y]=Y)}}_assignTerrainTiles(d){this._initializing||d.forEach(g=>{if(this.terrainTileForTile[g.key])return;const w=this._findTileCoveringTileID(g,this.sourceCache);w&&(this.terrainTileForTile[g.key]=w)})}_prepareDEMTextures(){const d=this.painter.context,g=d.gl;for(const w in this.terrainTileForTile){const A=this.terrainTileForTile[w],I=A.dem;!I||A.demTexture&&!A.needsDEMTextureUpload||(d.activeTexture.set(g.TEXTURE1),Cj(this.painter,A,I))}}_prepareDemTileUniforms(d,g,w,A){if(!g||g.demTexture==null)return!1;const I=d.tileID.canonical,L=Math.pow(2,g.tileID.canonical.z-I.z),F=A||"";return w[`u_dem_tl${F}`]=[I.x*L%1,I.y*L%1],w[`u_dem_scale${F}`]=L,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let d=0;const g=this._visibleDemTiles.reduce((w,A)=>{if(!A.dem)return w;const I=A.dem.tree.minimums[0];return I>0&&d++,w+I},0);return d?g/d:0}_updateEmptyDEMTexture(){const d=this.painter.context,g=d.gl;d.activeTexture.set(g.TEXTURE2);const w=this._getLoadedAreaMinimum(),A=new s.dz({width:1,height:1},new Float32Array([w]));this._emptyDEMTextureDirty=!1;let I=this._emptyDEMTexture;return I?I.update(A,{premultiply:!1}):I=this._emptyDEMTexture=new s.T(d,A,g.R32F,{premultiply:!1}),I}setupElevationDraw(d,g,w){const A=this.painter.context,I=A.gl,L={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};L.u_exaggeration=this.exaggeration();let F=null,$=null,H=1;if(w&&w.morphing&&this._useVertexMorphing){const ie=w.morphing.srcDemTile,le=w.morphing.dstDemTile;H=w.morphing.phase,ie&&le&&(this._prepareDemTileUniforms(d,ie,L,"_prev")&&($=ie),this._prepareDemTileUniforms(d,le,L)&&(F=le))}const Y=ie=>ie&&ie.demTexture&&this.painter.linearFloatFilteringSupported()?I.LINEAR:I.NEAREST;let te=null;var ee;if(this.enabled?$&&F?(te=F.demTexture,A.activeTexture.set(I.TEXTURE4),$.demTexture.bind(Y($),I.CLAMP_TO_EDGE),L.u_dem_lerp=H):(F=this.terrainTileForTile[d.tileID.key],te=this._prepareDemTileUniforms(d,F,L)?F.demTexture:this.emptyDEMTexture):te=this.emptyDEMTexture,A.activeTexture.set(I.TEXTURE2),te&&(L.u_dem_size=(ee=te).size[0]===1?1:ee.size[0]-2,te.bind(Y(F),I.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(w&&w.useDepthForOcclusion,g,L),w&&w.useMeterToDem&&F){const ie=(1<{if(pe===ft)return;const Rt=[yv[ft],"PROJECTION_GLOBE_VIEW"];Re&&Rt.push("CUSTOM_ANTIALIASING");const Ft=H.isTileAffectedByFog(xt);me=H.getOrCreateProgram("globeRaster",{defines:Rt,overrideFog:Ft}),pe=ft},Ze=H.colorModeForRenderPass(),ze=new Ir(oe.LEQUAL,Ir.ReadWrite,H.depthRangeFor3D);Ro.update(ie);const Ke=s.dq(je),De=[s.aH(je.center.lng),s.aL(je.center.lat)],Fe=H.globeSharedBuffers,qe=[je.width*s.o.devicePixelRatio,je.height*s.o.devicePixelRatio],st=Float32Array.from(je.globeMatrix),Qe={useDenormalizedUpVectorScale:!0};{const xt=H.transform,ft=Bx(xt.zoom,Y.exaggeration(),Y.sourceCache._source.tileSize);pe=-1;const Rt=oe.TRIANGLES;for(const Ft of ee){const ot=te.getTile(Ft),et=Qr.disabled,gt=Y.prevTerrainTileForTile[Ft.key],vt=Y.terrainTileForTile[Ft.key];wT(gt,vt)&&Ro.newMorphing(Ft.key,gt,vt,ie,250),zx(H,ot.emissiveTexture),le.activeTexture.set(oe.TEXTURE0),ot.texture&&ot.texture.bind(oe.LINEAR,oe.CLAMP_TO_EDGE);const St=Ro.getMorphValuesForProxy(Ft.key),rr=St?1:0;St&&Object.assign(Qe,{morphing:{srcDemTile:St.from,dstDemTile:St.to,phase:s.dn(St.phase)}});const Gt=s.dr(Ft.canonical),Ht=s.ds(Gt.getCenter().lat),Dt=s.dt(Ft.canonical,Gt,Ht,xt.worldSize/xt._pixelsPerMercatorPixel),Ar=s.du(s.dv(Ft.canonical)),Lr=H.emissiveMode==="mrt-fallback"?1:0,gr=hg(xt.expandedFarZProjMatrix,st,Ke,Ar,s.al(xt.zoom),De,xt.frustumCorners.TL,xt.frustumCorners.TR,xt.frustumCorners.BR,xt.frustumCorners.BL,xt.globeCenterInViewSpace,xt.globeRadius,qe,ft,xt._farZ,Lr,Dt);if(xe(Ft,rr),me&&(Y.setupElevationDraw(ot,me,Qe),H.uploadCommonUniforms(le,me,Ft.toUnwrapped()),Fe)){const[Tr,Hr,sn]=Fe.getGridBuffers(Ht,ft!==0);me.draw(H,Rt,ze,et,Ze,Gr.backCCW,gr,"globe_raster",Tr,Hr,sn)}}}if(Fe&&(H.renderDefaultNorthPole||H.renderDefaultSouthPole)){const xt=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Re&&xt.push("CUSTOM_ANTIALIASING"),me=H.getOrCreateProgram("globeRaster",{defines:xt});for(const ft of ee){const{x:Rt,y:Ft,z:ot}=ft.canonical,et=Ft===0,gt=Ft===(1<Tr.draw(H,oe.TRIANGLES,ze,Qr.disabled,Ze,Gr.disabled,hg(je.expandedFarZProjMatrix,Dt,Dt,Ar,0,De,je.frustumCorners.TL,je.frustumCorners.TR,je.frustumCorners.BR,je.frustumCorners.BL,je.globeCenterInViewSpace,je.globeRadius,qe,0,je._farZ,Lr),"globe_pole_raster",Hr,rr,Gt);Y.setupElevationDraw(Ht,me,Qe),H.uploadCommonUniforms(le,me,ft.toUnwrapped()),et&&H.renderDefaultNorthPole&&gr(me,vt),gt&&H.renderDefaultSouthPole&&(Dt=s.cC(s.bb(),Dt,[1,-1,1]),gr(me,St))}}}})(A,I,L,F,$);else{const H=A.context,Y=H.gl;let te,ee;const ie=A.shadowRenderer,le=Pa(A,A.longestCutoffRange),oe=Ze=>{if(ee===Ze)return;const ze=[];ze.push(yv[Ze]),le.shouldRenderCutoff&&ze.push("RENDER_CUTOFF"),ie&&(ze.push("RENDER_SHADOWS"),ie.useNormalOffset&&ze.push("NORMAL_OFFSET")),te=A.getOrCreateProgram("terrainRaster",{defines:ze}),ee=Ze},me=A.colorModeForRenderPass(),pe=new Ir(Y.LEQUAL,Ir.ReadWrite,A.depthRangeFor3D);Ro.update($);const je=A.transform,Re=Bx(je.zoom,I.exaggeration(),I.sourceCache._source.tileSize);let xe=[0,0,0];if(ie){const Ze=A.style.directionalLight,ze=A.style.ambientLight;Ze&&ze&&(xe=Du(A.style,Ze,ze))}{ee=-1;const Ze=Y.TRIANGLES,[ze,Ke]=[I.gridIndexBuffer,I.gridSegments];for(const De of F){const Fe=L.getTile(De),qe=Qr.disabled,st=I.prevTerrainTileForTile[De.key],Qe=I.terrainTileForTile[De.key];wT(st,Qe)&&Ro.newMorphing(De.key,st,Qe,$,250),zx(A,Fe.emissiveTexture),H.activeTexture.set(Y.TEXTURE0),Fe.texture&&Fe.texture.bind(Y.LINEAR,Y.CLAMP_TO_EDGE);const xt=Ro.getMorphValuesForProxy(De.key),ft=xt?1:0;let Rt;xt&&(Rt={morphing:{srcDemTile:xt.from,dstDemTile:xt.to,phase:s.dn(xt.phase)}});const Ft=A.emissiveMode==="mrt-fallback"?1:0,ot=Fx(De.projMatrix,xv(De.canonical,je.renderWorldCopies)?Re/10:Re,xe,Ft);if(oe(ft),!te)continue;I.setupElevationDraw(Fe,te,Rt);const et=De.toUnwrapped();ie&&ie.setupShadows(et,te),A.uploadCommonUniforms(H,te,et,null,le),te.draw(A,Ze,pe,qe,me,Gr.backCCW,ot,"terrain_raster",I.gridBuffer,ze,Ke)}}}}(g,this,this.proxySourceCache,d,this._updateTimestamp),this.renderingToTexture=!0,g.gpuTimingDeferredRenderEnd(),d.splice(0,d.length))}renderBatch(d){if(this._drapedRenderBatches.length===0)return d+1;this.renderingToTexture=!0;const g=this.painter,w=this.painter.context,A=this.proxySourceCache,I=this.proxiedCoords[A.id],L=this._drapedRenderBatches.shift(),F=g.style.order,$=[];this._updateFBOs(g.emissiveMode==="mrt-fallback");let H=0;for(const Y of I){const te=A.getTileByID(Y.proxyTileKey),ee=A.proxyCachedFBO[Y.key]?A.proxyCachedFBO[Y.key][d]:void 0,ie=ee!==void 0?A.renderCache[ee]:this.pool[H++],le=ee!==void 0;if(te.texture=ie.tex,te.emissiveTexture=ie.emissiveTex,le&&!ie.dirty){$.push(te.tileID);continue}w.bindFramebuffer.set(ie.fb.framebuffer);const oe=w.gl;let me;oe.drawBuffers(g.emissiveMode==="mrt-fallback"?[oe.COLOR_ATTACHMENT0,oe.COLOR_ATTACHMENT1]:[oe.COLOR_ATTACHMENT0]),this.renderedToTile=!1,ie.dirty&&(w.clear({color:s.aq.transparent,stencil:0}),ie.dirty=!1);for(let pe=L.start;pe<=L.end;++pe){const je=g.style._mergedLayers[F[pe]];if(je.isHidden(g.transform.zoom))continue;const Re=g.style.getLayerSourceCache(je),xe=Re?this.proxyToSource[Y.key][Re.id]:[Y];if(!xe)continue;const Ze=xe;w.viewport.set([0,0,ie.fb.width,ie.fb.height]),me!==(Re?Re.id:null)&&(this._setupStencil(ie,xe,je,Re),me=Re?Re.id:null),g.renderLayer(g,Re,je,Ze)}if(oe.drawBuffers([oe.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const pe of this._pendingGroundEffectLayers){const je=g.style._mergedLayers[F[pe]];if(je.isHidden(g.transform.zoom))continue;const Re=g.style.getLayerSourceCache(je),xe=Re?this.proxyToSource[Y.key][Re.id]:[Y];if(!xe)continue;const Ze=xe;w.viewport.set([0,0,ie.fb.width,ie.fb.height]),me!==(Re?Re.id:null)&&(this._setupStencil(ie,xe,je,Re),me=Re?Re.id:null),g.renderLayer(g,Re,je,Ze)}this.renderedToTile?(ie.dirty=!0,$.push(te.tileID)):le||--H,H===5&&(H=0,this.renderToBackBuffer($))}return this.renderToBackBuffer($),this.renderingToTexture=!1,w.bindFramebuffer.set(null),w.viewport.set([0,0,g.width,g.height]),L.end+1}postRender(){}isLayerOrderingCorrect(d){const g=d.order.length;let w=-1,A=g;for(let I=0;Iw}getMinElevationBelowMSL(){let d=0;return this._visibleDemTiles.filter(g=>g.dem).forEach(g=>{d=Math.min(d,g.dem.tree.minimums[0])}),d===0?d:(d-30)*this._exaggeration}raycast(d,g,w){if(!this._visibleDemTiles)return null;const A=this._visibleDemTiles.filter(I=>I.dem).map(I=>{const L=I.tileID,F=1<(I.t!==null?I.t:Number.MAX_VALUE)-(L.t!==null?L.t:Number.MAX_VALUE));for(const I of A){if(I.t==null)return null;const L=I.tile.dem.tree.raycast(I.minx,I.miny,I.maxx,I.maxy,d,g,w);if(L!=null)return L}return null}_createFBO(){const d=this.painter.context,g=d.gl,w=this.drapeBufferSize;d.activeTexture.set(g.TEXTURE0);const A=new s.T(d,{width:w[0],height:w[1],data:null},g.RGBA8);A.bind(g.LINEAR,g.CLAMP_TO_EDGE);const I=d.createFramebuffer(w[0],w[1],1,null);let L;return I.colorAttachment0.set(A.texture),this._emissiveTexture&&(L=new s.T(d,{width:w[0],height:w[1],data:null},g.R8),L.bind(g.LINEAR,g.CLAMP_TO_EDGE),I.createColorAttachment(d,1),I.colorAttachment1.set(L.texture)),I.depthAttachment=new C3(d,I.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=d.createRenderbuffer(d.gl.DEPTH_STENCIL,w[0],w[1]),this._stencilRef=0,I.depthAttachment.set(this._sharedDepthStencil),d.clear({stencil:0})):I.depthAttachment.set(this._sharedDepthStencil),d.extTextureFilterAnisotropic&&g.texParameterf(g.TEXTURE_2D,d.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,d.extTextureFilterAnisotropicMax),{fb:I,tex:A,emissiveTex:L,dirty:!1}}_updateFBOs(d){if(this._emissiveTexture!==d){for(const g of this.pool)this._updateFBO(g,d);for(const g of this.proxySourceCache.renderCache)this._updateFBO(g,d);this._emissiveTexture=d}}_updateFBO(d,g){const w=d.fb,A=this.painter.context,I=A.gl,L=this.drapeBufferSize;if(g){const F=new s.T(A,{width:L[0],height:L[1],data:null},I.R8);F.bind(I.LINEAR,I.CLAMP_TO_EDGE),d.emissiveTex=F,w.createColorAttachment(A,1),w.colorAttachment1.set(F.texture)}else d.emissiveTex=void 0,w.removeColorAttachment(A,1);d.dirty=!0}_initFBOPool(){for(;this.pool.length{const g=this._style._mergedLayers[d],w=g.isHidden(this.painter.transform.zoom);return g.type==="hillshade"||g.type==="custom"?!w&&g.shouldRedrape():!w&&g.hasTransition()})}_clearLineLayersFromRenderCache(){let d=!1;for(const w of this._style.getSources())if(w instanceof Pl){d=!0;break}if(!d)return;const g={};for(let w=0;w$>F.end)||s.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(d){const g=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,g.renderCache.length>g.renderCachePool.length){const L=Object.values(g.proxyCachedFBO);g.proxyCachedFBO={};for(let F=0;F=0;L--){const F=w[L];if(g.getTileByID(F.key),g.proxyCachedFBO[F.key]!==void 0){const $=d[F.key],H=this.proxyToSource[F.key];let Y=0;for(const te in H){const ee=H[te],ie=$[te];if(!ie||ie.length!==ee.length||ee.some((le,oe)=>le!==ie[oe]||A[te]&&A[te].hasOwnProperty(le.key))){Y=-1;break}++Y}for(const te in g.proxyCachedFBO[F.key])g.renderCache[g.proxyCachedFBO[F.key][te]].dirty=Y<0||Y!==Object.values($).length}}const I=[...this._drapedRenderBatches];I.sort((L,F)=>F.end-F.start-(L.end-L.start));for(const L of I)for(const F of w){if(g.proxyCachedFBO[F.key])continue;let $=g.renderCachePool.pop();$===void 0&&g.renderCache.length<50&&($=g.renderCache.length,g.renderCache.push(this._createFBO())),$!==void 0&&(g.proxyCachedFBO[F.key]={},g.proxyCachedFBO[F.key][L.start]=$,g.renderCache[$].dirty=!0)}this._tilesDirty={}}_setupStencil(d,g,w,A){if(!A||!this._sourceTilesOverlap[A.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const I=this.painter.context,L=I.gl;if(g.length<=1)return void(this._overlapStencilType=!1);let F;if(w.isTileClipped())F=g.length,this._overlapStencilMode.test={func:L.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(g[0].overscaledZ>g[g.length-1].overscaledZ))return void(this._overlapStencilType=!1);F=1,this._overlapStencilMode.test={func:L.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+F>255&&(I.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=F,this._overlapStencilMode.ref=this._stencilRef,w.isTileClipped()&&this._renderTileClippingMasks(g,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(d){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[d.key]),this._overlapStencilMode):Qr.disabled}_renderTileClippingMasks(d,g){const w=this.painter,A=this.painter.context,I=A.gl;w._tileClippingMaskIDs={},A.setColorMode(Kr.disabled),A.setDepthMode(Ir.disabled);const L=w.getOrCreateProgram("clippingMask");for(const F of d){const $=w._tileClippingMaskIDs[F.key]=--g;L.draw(w,I.TRIANGLES,Ir.disabled,new Qr({func:I.ALWAYS,mask:0},$,255,I.KEEP,I.KEEP,I.REPLACE),Kr.disabled,Gr.disabled,$x(F.projMatrix),"$clipping",w.tileExtentBuffer,w.quadTriangleIndexBuffer,w.tileExtentSegments)}}pointCoordinate(d){const g=this.painter.transform;if(d.x<0||d.x>g.width||d.y<0||d.y>g.height)return null;const w=[d.x,d.y,1,1];s.aE(w,w,g.pixelMatrixInverse),s.cu(w,w,1/w[3]),w[0]/=g.worldSize,w[1]/=g.worldSize;const A=g._camera.position,I=s.bU(1,g.center.lat),L=[A[0],A[1],A[2]/I,0],F=s.cV([],w.slice(0,3),L);s.ay(F,F);const $=this.raycast(L,F,this._exaggeration);return $!==null&&$?(s.bg(L,L,F,$),L[3]=L[2],L[2]*=I,L):null}_setupProxiedCoordsForOrtho(d,g,w){if(d.getSource()instanceof s.aV)return this._setupProxiedCoordsForImageSource(d,g,w);this._findCoveringTileCache[d.id]=this._findCoveringTileCache[d.id]||{};const A=this.proxiedCoords[d.id]=[],I=this.proxyCoords;for(let $=0;$Y.overscaledZ-H.overscaledZ)}_setupProxiedCoordsForImageSource(d,g,w){if(!d.getSource().loaded())return;const A=this.proxiedCoords[d.id]=[],I=this.proxyCoords,L=d.getSource(),F=L.tileID;if(!F)return;const $=new s.P(F.x,F.y)._div(1<(te.min.x=Math.min(te.min.x,ee.x-$.x),te.min.y=Math.min(te.min.y,ee.y-$.y),te.max.x=Math.max(te.max.x,ee.x-$.x),te.max.y=Math.max(te.max.y,ee.y-$.y),te),{min:new s.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new s.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),Y=(te,ee)=>{const ie=te.wrap+te.canonical.x/(1<me+H.max.x||le+oepe+H.max.y};for(let te=0;teL.key===g.tileID.key);if(I)return I}if(g.tileID.key!==d.key){const I=d.canonical.z-g.tileID.canonical.z;let L,F,$;A=s.bb();const H=g.tileID.wrap-d.wrap<0?(L=s.an>>I,F=L*((g.tileID.canonical.x<=te){const ee=d.canonical.z-te;g.getSource().reparseOverscaled?(F=Math.max(d.canonical.z+2,g.transform.tileZoom),L=new s.aR(F,d.wrap,te,d.canonical.x>>ee,d.canonical.y>>ee)):ee!==0&&(F=te,L=new s.aR(F,d.wrap,te,d.canonical.x>>ee,d.canonical.y>>ee))}L.key!==d.key&&(H.push(L.key),w=g.getTile(L))}const Y=te=>{H.forEach(ee=>{A[ee]=te}),H.length=0};for(F-=1;F>=$&&(!w||!w.hasData());F--){w&&Y(w.tileID.key);const te=L.calculateScaledKey(F);if(w=g.getTileByID(te),w&&w.hasData())break;const ee=A[te];if(ee===null)break;ee===void 0?H.push(te):w=g.getTileByID(ee)}return Y(w?w.tileID.key:null),w&&w.hasData()?w:null}findDEMTileFor(d){return this.enabled?this._findTileCoveringTileID(d,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(d,g){let w=this._tilesDirty[d];w||(w=this._tilesDirty[d]={}),w[g.key]=!0}}function TT(v,d,g){const w=function(F,$,H){const Y=s.bi($,F),te=s.bi(H,[.2126,.7152,.0722]),ee=(le,oe,me)=>(1-me)*le+me*oe,ie=ee(1-.3*Math.min(te,1),1,Math.min(Y+1,1));return ee(.92,1,Math.asin(s.aC($[2],-1,1))/Math.PI+.5)*ie}(v,[0,0,1],d),A=[0,0,0];s.bJ(A,g.slice(0,3),w);const I=[0,0,0];s.bJ(I,d.slice(0,3),v[2]);const L=[0,0,0];return s.cT(L,A,I),s.cW(L)}const Fj=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],Bj=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Cp{static cacheKey(d,g,w,A){const I=[g];A&&I.push(A.cacheKey);for(const L of w)(typeof L=="string"&&L.includes(" ")||d.usedDefines.has(L))&&I.push(L);return I.join("/")}constructor(d,g,w,A,I,L){const F=d.gl;this.program=F.createProgram(),this.configuration=A,this.name=g,this.fixedDefines=[...L];const $=`#version 300 es ${(A?A.defines():[]).concat(L.map(oe=>`#define ${oe}`)).join(` `)}`,H=[$,og];for(const oe of w.fragmentIncludes)H.push(Ou[oe]);H.push(w.fragmentSource);const Y=H.join(` `),te=[$,v3];for(const oe of w.vertexIncludes)te.push(Ou[oe]);this.forceManualRenderingForInstanceIDShaders=d.forceManualRenderingForInstanceIDShaders&&w.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&te.push("uniform int u_instanceID;"),te.push(w.vertexSource);let ee=te.join(` `);this.forceManualRenderingForInstanceIDShaders&&(ee=ee.replaceAll("gl_InstanceID","u_instanceID"));const ie=F.createShader(F.FRAGMENT_SHADER);if(F.isContextLost())return void(this.failedToCreate=!0);F.shaderSource(ie,Y),F.compileShader(ie),F.attachShader(this.program,ie);const le=F.createShader(F.VERTEX_SHADER);F.isContextLost()?this.failedToCreate=!0:(F.shaderSource(le,ee),F.compileShader(le),F.attachShader(this.program,le),this.attributes={},F.linkProgram(this.program),F.deleteShader(le),F.deleteShader(ie),this.fixedUniforms=I(d),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=A?A.getUniforms(d):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(oe=>({u_instanceID:new s.bX(oe)}))(d)),(L.includes("TERRAIN")||L.includes("ELEVATED")||g.includes("symbol")||g.includes("circle"))&&(this.terrainUniforms=(oe=>({u_dem:new s.bX(oe),u_dem_prev:new s.bX(oe),u_dem_tl:new s.b_(oe),u_dem_scale:new s.bZ(oe),u_dem_tl_prev:new s.b_(oe),u_dem_scale_prev:new s.bZ(oe),u_dem_size:new s.bZ(oe),u_dem_lerp:new s.bZ(oe),u_exaggeration:new s.bZ(oe),u_depth:new s.bX(oe),u_depth_size_inv:new s.b_(oe),u_depth_range_unpack:new s.b_(oe),u_occluder_half_size:new s.bZ(oe),u_occlusion_depth_offset:new s.bZ(oe),u_meter_to_dem:new s.bZ(oe),u_label_plane_matrix_inv:new s.b$(oe)}))(d)),L.includes("GLOBE")&&(this.globeUniforms=(oe=>({u_tile_tl_up:new s.bY(oe),u_tile_tr_up:new s.bY(oe),u_tile_br_up:new s.bY(oe),u_tile_bl_up:new s.bY(oe),u_tile_up_scale:new s.bZ(oe)}))(d)),L.includes("FOG")&&(this.fogUniforms=(oe=>({u_fog_matrix:new s.b$(oe),u_fog_range:new s.b_(oe),u_fog_color:new s.cO(oe),u_fog_horizon_blend:new s.bZ(oe),u_fog_vertical_limit:new s.b_(oe),u_fog_temporal_offset:new s.bZ(oe),u_frustum_tl:new s.bY(oe),u_frustum_tr:new s.bY(oe),u_frustum_br:new s.bY(oe),u_frustum_bl:new s.bY(oe),u_globe_pos:new s.bY(oe),u_globe_radius:new s.bZ(oe),u_globe_transition:new s.bZ(oe),u_is_globe:new s.bX(oe),u_viewport:new s.b_(oe)}))(d)),L.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(oe=>({u_cutoff_params:new s.cO(oe)}))(d)),L.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(oe=>({u_lighting_ambient_color:new s.bY(oe),u_lighting_directional_dir:new s.bY(oe),u_lighting_directional_color:new s.bY(oe),u_ground_radiance:new s.bY(oe)}))(d)),L.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(oe=>({u_light_matrix_0:new s.b$(oe),u_light_matrix_1:new s.b$(oe),u_fade_range:new s.b_(oe),u_shadow_normal_offset:new s.bY(oe),u_shadow_intensity:new s.bZ(oe),u_shadow_texel_size:new s.bZ(oe),u_shadow_map_resolution:new s.bZ(oe),u_shadow_direction:new s.bY(oe),u_shadow_bias:new s.bY(oe),u_shadowmap_0:new s.bX(oe),u_shadowmap_1:new s.bX(oe)}))(d)))}getAttributeLocation(d,g){let w=this.attributes[g];return w===void 0&&(w=this.attributes[g]=d.getAttribLocation(this.program,g)),w}setTerrainUniformValues(d,g){if(!this.terrainUniforms)return;const w=this.terrainUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const A in g)w[A]&&w[A].set(this.program,A,g[A])}}setGlobeUniformValues(d,g){if(!this.globeUniforms)return;const w=this.globeUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const A in g)w[A]&&w[A].set(this.program,A,g[A])}}setFogUniformValues(d,g){if(!this.fogUniforms)return;const w=this.fogUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const A in g)w[A].set(this.program,A,g[A])}}setCutoffUniformValues(d,g){if(!this.cutoffUniforms)return;const w=this.cutoffUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const A in g)w[A].set(this.program,A,g[A])}}setLightsUniformValues(d,g){if(!this.lightsUniforms)return;const w=this.lightsUniforms;if(!this.failedToCreate){d.program.set(this.program);for(const A in g)w[A].set(this.program,A,g[A])}}setShadowUniformValues(d,g){if(this.failedToCreate||!this.shadowUniforms)return;const w=this.shadowUniforms;d.program.set(this.program);for(const A in g)w[A].set(this.program,A,g[A])}_drawDebugWireframe(d,g,w,A,I,L,F,$,H,Y){const te=d.options.wireframe;if(te.terrain===!1&&te.layers2D===!1&&te.layers3D===!1)return;const ee=d.context;if(!(!(!te.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!te.layers2D||d._terrain&&d._terrain.renderingToTexture||!Fj.includes(this.name))||!(!te.layers3D||!Bj.includes(this.name))))return;const ie=ee.gl,le=d.wireframeDebugCache.getLinesFromTrianglesBuffer(d.frameCounter,I,ee);if(!le)return;const oe=[...this.fixedDefines,"DEBUG_WIREFRAME"],me=d.getOrCreateProgram(this.name,{config:this.configuration,defines:oe});ee.program.set(me.program);const pe=(xe,Ze,ze)=>{if(Ze[xe]&&ze[xe])for(const Ke in Ze[xe])ze[xe][Ke]&&ze[xe][Ke].set(ze.program,Ke,Ze[xe][Ke].current)};H&&H.setUniforms(me.program,ee,me.binderUniforms,F,{zoom:$}),pe("fixedUniforms",this,me),pe("terrainUniforms",this,me),pe("globeUniforms",this,me),pe("fogUniforms",this,me),pe("lightsUniforms",this,me),pe("shadowUniforms",this,me),le.bind(),ee.setColorMode(new Kr([ie.ONE,ie.ONE_MINUS_SRC_ALPHA,ie.ZERO,ie.ONE],s.aq.transparent,[!0,!0,!0,!1])),ee.setDepthMode(new Ir(g.func===ie.LESS?ie.LEQUAL:g.func,Ir.ReadOnly,g.range)),ee.setStencilMode(Qr.disabled);const je=3*L.primitiveLength*2,Re=3*L.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const xe=Y||1;for(let Ze=0;Ze1?ie.drawElementsInstanced(ie.LINES,je,ie.UNSIGNED_SHORT,Re,Y):ie.drawElements(ie.LINES,je,ie.UNSIGNED_SHORT,Re);I.bind(),ee.program.set(this.program),ee.setDepthMode(g),ee.setStencilMode(w),ee.setColorMode(A)}checkUniforms(d,g,w){if(this.fixedDefines.includes(g)){for(const A of Object.keys(w))if(!w[A].initialized)throw new Error(`Program '${this.name}', from draw '${d}': uniform ${A} not set but required by ${g} being defined`)}}draw(d,g,w,A,I,L,F,$,H,Y,te,ee,ie,le,oe,me){const pe=d.context,je=pe.gl;if(this.failedToCreate)return;pe.program.set(this.program),pe.setDepthMode(w),pe.setStencilMode(A),pe.setColorMode(I),pe.setCullFace(L);for(const[De,Fe]of this.fixedUniformsEntries)Fe.set(this.program,De,F[De]);le&&le.setUniforms(this.program,pe,this.binderUniforms,ee,{zoom:ie});const Re={[je.POINTS]:1,[je.LINES]:2,[je.TRIANGLES]:3,[je.LINE_STRIP]:1}[g];this.checkUniforms($,"RENDER_SHADOWS",this.shadowUniforms);const xe=oe||[],Ze=le?le.getPaintVertexBuffers():[],ze=g===je.TRIANGLES&&Y,Ke=me&&me>0?1:void 0;for(const De of te.get()){const Fe=De.vaos||(De.vaos={});if((Fe[$]||(Fe[$]=new kj)).bind(pe,this,H,Ze,Y,De.vertexOffset,xe,Ke),this.forceManualRenderingForInstanceIDShaders){const qe=me||1;for(let st=0;st1?je.drawElementsInstanced(g,De.primitiveLength*Re,je.UNSIGNED_SHORT,De.primitiveOffset*Re*2,me):Y?je.drawElements(g,De.primitiveLength*Re,je.UNSIGNED_SHORT,De.primitiveOffset*Re*2):je.drawArrays(g,De.vertexOffset,De.vertexLength);ze&&this._drawDebugWireframe(d,w,A,I,Y,De,ee,ie,le,me)}}}function zj(v,d,g=0){const w=Math.pow(2,d.tileID.overscaledZ),A=d.tileSize*Math.pow(2,v.transform.tileZoom)/w,I=A*(d.tileID.canonical.x+d.tileID.wrap*w),L=A*d.tileID.canonical.y;return{u_image:0,u_texsize:d.imageAtlasTexture?d.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/s.aA(d,1,v.transform.tileZoom),u_pixel_coord_upper:[I>>16,L>>16],u_pixel_coord_lower:[65535&I,65535&L],u_pattern_transition:g}}const bv={terrain:0,flat:1},j3=s.bb(),$j=(v,d,g,w,A,I,L,F,$,H,Y,te,ee,ie,le,oe,me,pe,je=[0,0,1])=>{const Re=d.style.light,xe=Re.properties.get("position"),Ze=[xe.x,xe.y,xe.z],ze=s.dE();Re.properties.get("anchor")==="viewport"&&(s.dF(ze,-d.transform.angle),s.dG(Ze,Ze,ze));const Ke=Re.properties.get("color").toPremultipliedRenderColor(null),De=d.transform,Fe={u_matrix:v,u_lightpos:Ze,u_lightintensity:Re.properties.get("intensity"),u_lightcolor:[Ke.r,Ke.g,Ke.b],u_vertical_gradient:+g,u_opacity:w,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:j3,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:bv[H],u_base_type:bv[Y],u_ao:A,u_edge_radius:I,u_width_scale:L,u_flood_light_color:le,u_vertical_scale:oe,u_flood_light_intensity:me,u_ground_shadow_factor:pe,u_front_cutoff_params:je};return De.projection.name==="globe"&&(Fe.u_tile_id=[F.canonical.x,F.canonical.y,1<({u_matrix:v,u_edge_radius:d,u_width_scale:g,u_vertical_scale:w,u_height_type:bv[A],u_base_type:bv[I]}),P3=(v,d,g,w,A,I,L,F,$,H,Y,te,ee,ie,le,oe,me,pe)=>{const je=$j(v,d,g,w,A,I,L,F,H,Y,te,ee,ie,le,oe,me,1,[0,0,0]),Re={u_height_factor:-Math.pow(2,F.overscaledZ)/$.tileSize/8};return Object.assign(je,zj(d,$,pe),Re)},wv=(v,d,g)=>({u_matrix:v,u_emissive_strength:d,u_ground_shadow_factor:g}),Sv=(v,d,g,w,A,I=0)=>Object.assign(wv(v,d,A),zj(g,w,I)),Uj=(v,d,g,w)=>({u_matrix:v,u_world:g,u_emissive_strength:d,u_ground_shadow_factor:w}),fg=(v,d,g,w,A,I,L=0)=>Object.assign(Sv(v,d,g,w,I,L),{u_world:A}),Vj=(v,d)=>({u_matrix:v,u_depth_bias:d}),qj=(v,d)=>({u_matrix:v,u_ground_shadow_factor:d}),qx=(v,d,g,w,A)=>({u_matrix:v,u_camera_pos:[d[0],d[1],d[2]],u_depth_bias:g,u_height_scale:w,u_reset_depth:A}),Tv=(v,d,g)=>({u_image:v,u_opacity:d,u_blend_mode:g}),hf=(v,d,g,w,A,I,L,F,$,H=[0,0,1])=>({u_matrix:v,u_normal_matrix:d,u_opacity:g,u_faux_facade_ao_intensity:w,u_camera_pos:A,u_tile_to_meter:I,u_facade_emissive_chance:L,u_flood_light_color:F,u_flood_light_intensity:$,u_front_cutoff_params:H}),Ev=v=>({u_matrix:v}),Av=v=>({u_matrix:v}),Gj=(v,d,g,w,A,I,L,F)=>{const $=s.an/I.tileSize;return{u_matrix:v,u_inv_rot_matrix:d,u_camera_to_center_distance:g.getCameraToCenterDistance(F),u_extrude_scale:[g.pixelsToGLUnits[0]/$,g.pixelsToGLUnits[1]/$],u_zoom_transition:w,u_tile_id:L,u_merc_center:A}},ff=(v,d,g,w)=>({u_matrix:v,u_inv_matrix:d,u_camera_to_center_distance:g.getCameraToCenterDistance(w),u_viewport_size:[g.width,g.height]}),Gx=(v,d,g=1)=>({u_matrix:v,u_color:d,u_overlay:0,u_overlay_scale:g}),kv=s.bb(),Hj=(v,d,g,w,A,I,L)=>{const F=v.transform,$=F.projection.name==="globe",H=$?s.dH(F.zoom,d.canonical)*F._pixelsPerMercatorPixel:s.aA(g,1,I),Y={u_matrix:d.projMatrix,u_extrude_scale:H,u_intensity:L,u_inv_rot_matrix:kv,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if($){Y.u_inv_rot_matrix=w,Y.u_merc_center=A,Y.u_tile_id=[d.canonical.x,d.canonical.y,1<({u_matrix:d,u_normalize_matrix:g,u_globe_matrix:w,u_merc_matrix:A,u_grid_matrix:I,u_tl_parent:L,u_scale_parent:Y,u_fade_t:te.mix,u_opacity:te.opacity*ee.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:ee.paint.get("raster-brightness-min"),u_brightness_high:ee.paint.get("raster-brightness-max"),u_saturation_factor:s.dJ(ee.paint.get("raster-saturation")),u_contrast_factor:s.dI(ee.paint.get("raster-contrast")),u_spin_weights:Kj(ee.paint.get("raster-hue-rotate")),u_perspective_transform:ie,u_raster_elevation:le,u_zoom_transition:F,u_merc_center:$,u_cutoff_params:H,u_colorization_mix:ET(s.dK,me,je),u_colorization_offset:Cv(s.dK,pe,je),u_color_ramp:oe,u_texture_offset:[xe/(Re+2*xe),Re/(Re+2*xe)],u_texture_res:[Re+2*xe,Re+2*xe],u_emissive_strength:Ze,u_zbias_factor:AT(v)});function Kj(v){v*=Math.PI/180;const d=Math.sin(v),g=Math.cos(v);return[(2*g+1)/3,(-Math.sqrt(3)*d-g+1)/3,(Math.sqrt(3)*d-g+1)/3]}const xd=.05,N3=(v,d,g,w,A,I,L,F,$,H,Y,te)=>({u_matrix:v,u_normalize_matrix:d,u_globe_matrix:g,u_merc_matrix:w,u_grid_matrix:A,u_tl_parent:I,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:L,u_merc_center:F,u_cutoff_params:$}),R3=(v,d,g,w,A,I,L,F,$,H)=>({u_particle_texture:v,u_particle_texture_side_len:d,u_tile_offset:g,u_velocity:w,u_color_ramp:I,u_velocity_res:A,u_max_speed:L,u_uv_offset:F,u_data_scale:[255*$[0],255*$[1]],u_data_offset:H,u_particle_pos_scale:1.1,u_particle_pos_offset:[xd,xd]}),Yj=(v,d,g,w,A,I,L,F,$,H)=>({u_particle_texture:v,u_particle_texture_side_len:d,u_velocity:g,u_velocity_res:w,u_max_speed:A,u_speed_factor:I,u_reset_rate:L,u_rand_seed:Math.random(),u_uv_offset:F,u_data_scale:[255*$[0],255*$[1]],u_data_offset:H,u_particle_pos_scale:1.1,u_particle_pos_offset:[xd,xd]}),Zj=s.bb(),jv=(v,d,g,w,A,I,L,F,$,H,Y,te,ee,ie,le,oe,me,pe,je,Re,xe,Ze,ze,Ke)=>{const De=A.transform,Fe={u_is_size_zoom_constant:+(v==="constant"||v==="source"),u_is_size_feature_constant:+(v==="constant"||v==="camera"),u_size_t:d?d.uSizeT:0,u_size:d?d.uSize:0,u_camera_to_center_distance:De.getCameraToCenterDistance(je),u_rotate_symbol:+g,u_aspect_ratio:De.width/De.height,u_fade_change:A.options.fadeDuration?A.symbolFadeChange:1,u_matrix:I,u_label_plane_matrix:L,u_coord_matrix:F,u_is_text:+H,u_elevation_from_sea:$?1:0,u_pitch_with_map:+w,u_texsize:Y,u_texsize_icon:te,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Zj,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Zj,u_up_vector:[0,-1,0],u_color_adj_mat:Ze,u_icon_transition:ze||0,u_gamma_scale:w?A.transform.getCameraToCenterDistance(je)*Math.cos(A.terrain?0:A.transform._pitch):1,u_device_pixel_ratio:s.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Ke||1,u_ground_shadow_factor:Re,u_inv_matrix:s.b7(s.bb(),L),u_normal_scale:xe,u_lutTexture:10,u_zoom:De.zoom-Math.floor(De.zoom),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]};return je.name==="globe"&&(Fe.u_tile_id=[ie.canonical.x,ie.canonical.y,1<({u_matrix:v,u_emissive_strength:d,u_opacity:g,u_color:w}),pf=(v,d,g,w,A,I,L,F,$)=>Object.assign(function(H,Y,te,ee,ie,le){const{width:oe,height:me}=ee.imageManager.getPixelSize(Y),pe=Math.pow(2,le.tileID.overscaledZ),je=le.tileSize*Math.pow(2,ee.transform.tileZoom)/pe,Re=je*(le.tileID.canonical.x+le.tileID.wrap*pe),xe=je*le.tileID.canonical.y;return{u_image:0,u_pattern_tl:te.tl,u_pattern_br:te.br,u_texsize:[oe,me],u_pattern_size:te.displaySize,u_pattern_units_to_pixels:ie?[ee.transform.width,-1*ee.transform.height]:[1/s.aA(le,1,ee.transform.tileZoom),1/s.aA(le,1,ee.transform.tileZoom)],u_pixel_coord_upper:[Re>>16,xe>>16],u_pixel_coord_lower:[65535&Re,65535&xe]}}(0,I,L,w,F,$),{u_matrix:v,u_emissive_strength:d,u_opacity:g}),pg=new Float32Array(s.b9([])),jp=(v,d,g,w,A,I,L,F,$,H,Y,te,ee,ie=[0,0,0],le,oe,me)=>{const pe=A.style.light,je=pe.properties.get("position"),Re=[-je.x,-je.y,je.z],xe=s.dE();pe.properties.get("anchor")==="viewport"&&(s.dF(xe,-A.transform.angle),s.dG(Re,Re,xe));const Ze=Y.alphaMode==="MASK",ze=pe.properties.get("color").toNonPremultipliedRenderColor(null),Ke=ee.paint.get("model-ambient-occlusion-intensity"),De=ee.paint.get("model-color").constantOr(s.aq.white).toNonPremultipliedRenderColor(null);return De.a=ee.paint.get("model-color-mix-intensity").constantOr(0),me&&(De.r=me[0],De.g=me[1],De.b=me[2],De.a=me[3]),oe&&(De.r=oe.color.r,De.g=oe.color.g,De.b=oe.color.b,De.a=oe.colorMix,te=oe.emissionStrength,I*=oe.opacity),{u_matrix:v,u_lighting_matrix:d,u_normal_matrix:g,u_node_matrix:w||pg,u_lightpos:Re,u_lightintensity:pe.properties.get("intensity"),u_lightcolor:[ze.r,ze.g,ze.b],u_camera_pos:ie,u_opacity:I,u_baseTextureIsAlpha:0,u_alphaMask:+Ze,u_alphaCutoff:Y.alphaCutoff,u_baseColorFactor:L.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:F.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:$,u_roughnessFactor:H,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:De.toArray01(),u_aoIntensity:Ke,u_emissive_strength:te,u_occlusionTextureTransform:le||[0,0,0,0]}},kT=(v,d=pg,g=pg)=>({u_matrix:v,u_instance:d,u_node_matrix:g}),Iv={fillExtrusion:v=>({u_matrix:new s.b$(v),u_lightpos:new s.bY(v),u_lightintensity:new s.bZ(v),u_lightcolor:new s.bY(v),u_vertical_gradient:new s.bZ(v),u_opacity:new s.bZ(v),u_edge_radius:new s.bZ(v),u_width_scale:new s.bZ(v),u_ao:new s.b_(v),u_height_type:new s.bX(v),u_base_type:new s.bX(v),u_tile_id:new s.bY(v),u_zoom_transition:new s.bZ(v),u_inv_rot_matrix:new s.b$(v),u_merc_center:new s.b_(v),u_up_dir:new s.bY(v),u_height_lift:new s.bZ(v),u_flood_light_color:new s.bY(v),u_vertical_scale:new s.bZ(v),u_flood_light_intensity:new s.bZ(v),u_ground_shadow_factor:new s.bY(v),u_front_cutoff_params:new s.bY(v)}),fillExtrusionDepth:v=>({u_matrix:new s.b$(v),u_edge_radius:new s.bZ(v),u_width_scale:new s.bZ(v),u_vertical_scale:new s.bZ(v),u_height_type:new s.bX(v),u_base_type:new s.bX(v)}),fillExtrusionPattern:v=>({u_matrix:new s.b$(v),u_lightpos:new s.bY(v),u_lightintensity:new s.bZ(v),u_lightcolor:new s.bY(v),u_vertical_gradient:new s.bZ(v),u_height_factor:new s.bZ(v),u_edge_radius:new s.bZ(v),u_width_scale:new s.bZ(v),u_ao:new s.b_(v),u_height_type:new s.bX(v),u_base_type:new s.bX(v),u_tile_id:new s.bY(v),u_zoom_transition:new s.bZ(v),u_inv_rot_matrix:new s.b$(v),u_merc_center:new s.b_(v),u_up_dir:new s.bY(v),u_height_lift:new s.bZ(v),u_image:new s.bX(v),u_texsize:new s.b_(v),u_pixel_coord_upper:new s.b_(v),u_pixel_coord_lower:new s.b_(v),u_tile_units_to_pixels:new s.bZ(v),u_opacity:new s.bZ(v),u_pattern_transition:new s.bZ(v)}),fillExtrusionGroundEffect:v=>({u_matrix:new s.b$(v),u_opacity:new s.bZ(v),u_ao_pass:new s.bZ(v),u_meter_to_tile:new s.bZ(v),u_ao:new s.b_(v),u_flood_light_intensity:new s.bZ(v),u_flood_light_color:new s.bY(v),u_attenuation:new s.bZ(v),u_edge_radius:new s.bZ(v),u_fb:new s.bX(v),u_fb_size:new s.bZ(v),u_dynamic_offset:new s.bZ(v)}),fill:v=>({u_matrix:new s.b$(v),u_emissive_strength:new s.bZ(v),u_ground_shadow_factor:new s.bY(v)}),fillPattern:v=>({u_matrix:new s.b$(v),u_emissive_strength:new s.bZ(v),u_image:new s.bX(v),u_texsize:new s.b_(v),u_pixel_coord_upper:new s.b_(v),u_pixel_coord_lower:new s.b_(v),u_tile_units_to_pixels:new s.bZ(v),u_ground_shadow_factor:new s.bY(v),u_pattern_transition:new s.bZ(v)}),fillOutline:v=>({u_matrix:new s.b$(v),u_emissive_strength:new s.bZ(v),u_world:new s.b_(v),u_ground_shadow_factor:new s.bY(v)}),fillOutlinePattern:v=>({u_matrix:new s.b$(v),u_emissive_strength:new s.bZ(v),u_world:new s.b_(v),u_image:new s.bX(v),u_texsize:new s.b_(v),u_pixel_coord_upper:new s.b_(v),u_pixel_coord_lower:new s.b_(v),u_tile_units_to_pixels:new s.bZ(v),u_ground_shadow_factor:new s.bY(v),u_pattern_transition:new s.bZ(v)}),lineBlendComposite:v=>({u_image:new s.bX(v),u_opacity:new s.bZ(v),u_blend_mode:new s.bX(v)}),building:v=>({u_matrix:new s.b$(v),u_normal_matrix:new s.b$(v),u_opacity:new s.bZ(v),u_faux_facade_ao_intensity:new s.bZ(v),u_camera_pos:new s.bY(v),u_tile_to_meter:new s.bZ(v),u_facade_emissive_chance:new s.bZ(v),u_flood_light_color:new s.bY(v),u_flood_light_intensity:new s.bZ(v),u_front_cutoff_params:new s.bY(v)}),buildingBloom:v=>({u_matrix:new s.b$(v)}),buildingDepth:v=>({u_matrix:new s.b$(v)}),elevatedStructuresDepth:v=>({u_matrix:new s.b$(v),u_depth_bias:new s.bZ(v)}),elevatedStructures:v=>({u_matrix:new s.b$(v),u_ground_shadow_factor:new s.bY(v)}),elevatedStructuresDepthReconstruct:v=>({u_matrix:new s.b$(v),u_camera_pos:new s.bY(v),u_depth_bias:new s.bZ(v),u_height_scale:new s.bZ(v),u_reset_depth:new s.bZ(v)}),circle:s.dO,collisionBox:v=>({u_matrix:new s.b$(v),u_inv_rot_matrix:new s.b$(v),u_camera_to_center_distance:new s.bZ(v),u_extrude_scale:new s.b_(v),u_zoom_transition:new s.bZ(v),u_merc_center:new s.b_(v),u_tile_id:new s.bY(v)}),collisionCircle:v=>({u_matrix:new s.b$(v),u_inv_matrix:new s.b$(v),u_camera_to_center_distance:new s.bZ(v),u_viewport_size:new s.b_(v)}),debug:v=>({u_color:new s.dl(v),u_matrix:new s.b$(v),u_overlay:new s.bX(v),u_overlay_scale:new s.bZ(v)}),clippingMask:v=>({u_matrix:new s.b$(v)}),heatmap:v=>({u_extrude_scale:new s.bZ(v),u_intensity:new s.bZ(v),u_matrix:new s.b$(v),u_inv_rot_matrix:new s.b$(v),u_merc_center:new s.b_(v),u_tile_id:new s.bY(v),u_zoom_transition:new s.bZ(v),u_up_dir:new s.bY(v)}),heatmapTexture:v=>({u_image:new s.bX(v),u_color_ramp:new s.bX(v),u_opacity:new s.bZ(v)}),hillshade:v=>({u_matrix:new s.b$(v),u_image:new s.bX(v),u_latrange:new s.b_(v),u_light:new s.b_(v),u_shadow:new s.dl(v),u_highlight:new s.dl(v),u_emissive_strength:new s.bZ(v),u_accent:new s.dl(v)}),hillshadePrepare:v=>({u_matrix:new s.b$(v),u_image:new s.bX(v),u_dimension:new s.b_(v),u_zoom:new s.bZ(v)}),line:s.dN,linePattern:s.dM,raster:v=>({u_matrix:new s.b$(v),u_normalize_matrix:new s.b$(v),u_globe_matrix:new s.b$(v),u_merc_matrix:new s.b$(v),u_grid_matrix:new s.dm(v),u_tl_parent:new s.b_(v),u_scale_parent:new s.bZ(v),u_fade_t:new s.bZ(v),u_opacity:new s.bZ(v),u_image0:new s.bX(v),u_image1:new s.bX(v),u_brightness_low:new s.bZ(v),u_brightness_high:new s.bZ(v),u_saturation_factor:new s.bZ(v),u_contrast_factor:new s.bZ(v),u_spin_weights:new s.bY(v),u_perspective_transform:new s.b_(v),u_raster_elevation:new s.bZ(v),u_zoom_transition:new s.bZ(v),u_merc_center:new s.b_(v),u_cutoff_params:new s.cO(v),u_colorization_mix:new s.cO(v),u_colorization_offset:new s.bZ(v),u_color_ramp:new s.bX(v),u_texture_offset:new s.b_(v),u_texture_res:new s.b_(v),u_emissive_strength:new s.bZ(v),u_zbias_factor:new s.bZ(v)}),rasterParticle:v=>({u_matrix:new s.b$(v),u_normalize_matrix:new s.b$(v),u_globe_matrix:new s.b$(v),u_merc_matrix:new s.b$(v),u_grid_matrix:new s.dm(v),u_tl_parent:new s.b_(v),u_scale_parent:new s.bZ(v),u_fade_t:new s.bZ(v),u_opacity:new s.bZ(v),u_image0:new s.bX(v),u_image1:new s.bX(v),u_raster_elevation:new s.bZ(v),u_zoom_transition:new s.bZ(v),u_merc_center:new s.b_(v),u_cutoff_params:new s.cO(v)}),rasterParticleTexture:v=>({u_texture:new s.bX(v),u_opacity:new s.bZ(v)}),rasterParticleDraw:v=>({u_particle_texture:new s.bX(v),u_particle_texture_side_len:new s.bZ(v),u_tile_offset:new s.b_(v),u_velocity:new s.bX(v),u_color_ramp:new s.bX(v),u_velocity_res:new s.b_(v),u_max_speed:new s.bZ(v),u_uv_offset:new s.b_(v),u_data_scale:new s.b_(v),u_data_offset:new s.bZ(v),u_particle_pos_scale:new s.bZ(v),u_particle_pos_offset:new s.b_(v)}),rasterParticleUpdate:v=>({u_particle_texture:new s.bX(v),u_particle_texture_side_len:new s.bZ(v),u_velocity:new s.bX(v),u_velocity_res:new s.b_(v),u_max_speed:new s.bZ(v),u_speed_factor:new s.bZ(v),u_reset_rate:new s.bZ(v),u_rand_seed:new s.bZ(v),u_uv_offset:new s.b_(v),u_data_scale:new s.b_(v),u_data_offset:new s.bZ(v),u_particle_pos_scale:new s.bZ(v),u_particle_pos_offset:new s.b_(v)}),symbol:v=>({u_is_size_zoom_constant:new s.bX(v),u_is_size_feature_constant:new s.bX(v),u_size_t:new s.bZ(v),u_size:new s.bZ(v),u_camera_to_center_distance:new s.bZ(v),u_rotate_symbol:new s.bX(v),u_aspect_ratio:new s.bZ(v),u_fade_change:new s.bZ(v),u_matrix:new s.b$(v),u_label_plane_matrix:new s.b$(v),u_coord_matrix:new s.b$(v),u_is_text:new s.bX(v),u_elevation_from_sea:new s.bX(v),u_pitch_with_map:new s.bX(v),u_texsize:new s.b_(v),u_texsize_icon:new s.b_(v),u_texture:new s.bX(v),u_texture_icon:new s.bX(v),u_gamma_scale:new s.bZ(v),u_device_pixel_ratio:new s.bZ(v),u_tile_id:new s.bY(v),u_zoom_transition:new s.bZ(v),u_inv_rot_matrix:new s.b$(v),u_merc_center:new s.b_(v),u_camera_forward:new s.bY(v),u_tile_matrix:new s.b$(v),u_up_vector:new s.bY(v),u_ecef_origin:new s.bY(v),u_is_halo:new s.bX(v),u_icon_transition:new s.bZ(v),u_color_adj_mat:new s.b$(v),u_scale_factor:new s.bZ(v),u_ground_shadow_factor:new s.bY(v),u_inv_matrix:new s.b$(v),u_normal_scale:new s.bZ(v),u_lutTexture:new s.bX(v),u_zoom:new s.bZ(v),u_spp_fill_np_color:new s.cO(v),u_spp_halo_np_color:new s.cO(v),u_spp_opacity:new s.bZ(v),u_spp_halo_width:new s.bZ(v),u_spp_halo_blur:new s.bZ(v),u_spp_emissive_strength:new s.bZ(v),u_spp_occlusion_opacity:new s.bZ(v),u_spp_z_offset:new s.bZ(v),u_spp_translate_rotation:new s.b_(v)}),background:v=>({u_matrix:new s.b$(v),u_emissive_strength:new s.bZ(v),u_opacity:new s.bZ(v),u_color:new s.dl(v)}),backgroundPattern:v=>({u_matrix:new s.b$(v),u_emissive_strength:new s.bZ(v),u_opacity:new s.bZ(v),u_image:new s.bX(v),u_pattern_tl:new s.b_(v),u_pattern_br:new s.b_(v),u_texsize:new s.b_(v),u_pattern_size:new s.b_(v),u_pixel_coord_upper:new s.b_(v),u_pixel_coord_lower:new s.b_(v),u_pattern_units_to_pixels:new s.b_(v)}),terrainRaster:v=>({u_matrix:new s.b$(v),u_image0:new s.bX(v),u_image1:new s.bX(v),u_skirt_height:new s.bZ(v),u_ground_shadow_factor:new s.bY(v),u_emissive_texture_available:new s.bZ(v)}),skybox:v=>({u_matrix:new s.b$(v),u_sun_direction:new s.bY(v),u_cubemap:new s.bX(v),u_opacity:new s.bZ(v),u_temporal_offset:new s.bZ(v)}),skyboxGradient:v=>({u_matrix:new s.b$(v),u_color_ramp:new s.bX(v),u_center_direction:new s.bY(v),u_radius:new s.bZ(v),u_opacity:new s.bZ(v),u_temporal_offset:new s.bZ(v)}),skyboxCapture:v=>({u_matrix_3f:new s.dm(v),u_sun_direction:new s.bY(v),u_sun_intensity:new s.bZ(v),u_color_tint_r:new s.cO(v),u_color_tint_m:new s.cO(v),u_luminance:new s.bZ(v)}),globeRaster:v=>({u_proj_matrix:new s.b$(v),u_globe_matrix:new s.b$(v),u_normalize_matrix:new s.b$(v),u_merc_matrix:new s.b$(v),u_zoom_transition:new s.bZ(v),u_merc_center:new s.b_(v),u_image0:new s.bX(v),u_image1:new s.bX(v),u_grid_matrix:new s.dm(v),u_skirt_height:new s.bZ(v),u_far_z_cutoff:new s.bZ(v),u_frustum_tl:new s.bY(v),u_frustum_tr:new s.bY(v),u_frustum_br:new s.bY(v),u_frustum_bl:new s.bY(v),u_globe_pos:new s.bY(v),u_globe_radius:new s.bZ(v),u_viewport:new s.b_(v),u_emissive_texture_available:new s.bZ(v)}),globeAtmosphere:v=>({u_frustum_tl:new s.bY(v),u_frustum_tr:new s.bY(v),u_frustum_br:new s.bY(v),u_frustum_bl:new s.bY(v),u_horizon:new s.bZ(v),u_transition:new s.bZ(v),u_fadeout_range:new s.bZ(v),u_atmosphere_fog_color:new s.cO(v),u_high_color:new s.cO(v),u_space_color:new s.cO(v),u_temporal_offset:new s.bZ(v),u_horizon_angle:new s.bZ(v)}),model:v=>({u_matrix:new s.b$(v),u_lighting_matrix:new s.b$(v),u_normal_matrix:new s.b$(v),u_node_matrix:new s.b$(v),u_lightpos:new s.bY(v),u_lightintensity:new s.bZ(v),u_lightcolor:new s.bY(v),u_camera_pos:new s.bY(v),u_opacity:new s.bZ(v),u_baseColorFactor:new s.cO(v),u_emissiveFactor:new s.cO(v),u_metallicFactor:new s.bZ(v),u_roughnessFactor:new s.bZ(v),u_baseTextureIsAlpha:new s.bX(v),u_alphaMask:new s.bX(v),u_alphaCutoff:new s.bZ(v),u_baseColorTexture:new s.bX(v),u_metallicRoughnessTexture:new s.bX(v),u_normalTexture:new s.bX(v),u_occlusionTexture:new s.bX(v),u_emissionTexture:new s.bX(v),u_lutTexture:new s.bX(v),u_color_mix:new s.cO(v),u_aoIntensity:new s.bZ(v),u_emissive_strength:new s.bZ(v),u_occlusionTextureTransform:new s.cO(v)}),modelDepth:v=>({u_matrix:new s.b$(v),u_instance:new s.b$(v),u_node_matrix:new s.b$(v)}),groundShadow:v=>({u_matrix:new s.b$(v),u_ground_shadow_factor:new s.bY(v)}),stars:v=>({u_matrix:new s.b$(v),u_up:new s.bY(v),u_right:new s.bY(v),u_intensity_multiplier:new s.bZ(v)}),snowParticle:v=>({u_modelview:new s.b$(v),u_projection:new s.b$(v),u_time:new s.bZ(v),u_cam_pos:new s.bY(v),u_velocityConeAperture:new s.bZ(v),u_velocity:new s.bZ(v),u_horizontalOscillationRadius:new s.bZ(v),u_horizontalOscillationRate:new s.bZ(v),u_boxSize:new s.bZ(v),u_billboardSize:new s.bZ(v),u_simpleShapeParameters:new s.b_(v),u_screenSize:new s.b_(v),u_thinningCenterPos:new s.b_(v),u_thinningShape:new s.bY(v),u_thinningAffectedRatio:new s.bZ(v),u_thinningParticleOffset:new s.bZ(v),u_particleColor:new s.cO(v),u_direction:new s.bY(v)}),rainParticle:v=>({u_modelview:new s.b$(v),u_projection:new s.b$(v),u_time:new s.bZ(v),u_cam_pos:new s.bY(v),u_texScreen:new s.bX(v),u_velocityConeAperture:new s.bZ(v),u_velocity:new s.bZ(v),u_boxSize:new s.bZ(v),u_rainDropletSize:new s.b_(v),u_distortionStrength:new s.bZ(v),u_rainDirection:new s.bY(v),u_color:new s.cO(v),u_screenSize:new s.b_(v),u_thinningCenterPos:new s.b_(v),u_thinningShape:new s.bY(v),u_thinningAffectedRatio:new s.bZ(v),u_thinningParticleOffset:new s.bZ(v),u_shapeDirectionalPower:new s.bZ(v),u_shapeNormalPower:new s.bZ(v),u_mode:new s.bZ(v)}),vignette:v=>({u_vignetteShape:new s.bY(v),u_vignetteColor:new s.cO(v)}),occlusion:v=>({u_matrix:new s.b$(v),u_anchorPos:new s.bY(v),u_screenSizePx:new s.b_(v),u_occluderSizePx:new s.b_(v),u_color:new s.cO(v)})};class Mu{constructor(d,g,w,A){this.id=Mu.uniqueIdxCounter,Mu.uniqueIdxCounter++,this.context=d;const I=d.gl;this.buffer=I.createBuffer(),this.dynamicDraw=!!w,this.context.unbindVAO(),d.bindElementBuffer.set(this.buffer),I.bufferData(I.ELEMENT_ARRAY_BUFFER,g.arrayBuffer,this.dynamicDraw?I.DYNAMIC_DRAW:I.STATIC_DRAW),this.dynamicDraw||A||g.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(d){this.id=Mu.uniqueIdxCounter,Mu.uniqueIdxCounter++;const g=this.context.gl;this.context.unbindVAO(),this.bind(),g.bufferSubData(g.ELEMENT_ARRAY_BUFFER,0,d.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}Mu.uniqueIdxCounter=0;const CT={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Xj{constructor(d,g,w,A,I,L){this.length=g.length,this.attributes=w,this.itemSize=g.bytesPerElement,this.dynamicDraw=A,this.instanceCount=L,this.context=d;const F=d.gl;this.buffer=F.createBuffer(),d.bindVertexBuffer.set(this.buffer),F.bufferData(F.ARRAY_BUFFER,g.arrayBuffer,this.dynamicDraw?F.DYNAMIC_DRAW:F.STATIC_DRAW),this.dynamicDraw||I||g.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(d){const g=this.context.gl;this.bind(),g.bufferSubData(g.ARRAY_BUFFER,0,d.arrayBuffer)}enableAttributes(d,g){for(const w of this.attributes){const A=g.getAttributeLocation(d,w.name);A!==-1&&d.enableVertexAttribArray(A)}}setVertexAttribPointers(d,g,w){for(const A of this.attributes){const I=g.getAttributeLocation(d,A.name);if(I!==-1){const L=A.offset+this.itemSize*(w||0);A.type==="Float32"?d.vertexAttribPointer(I,A.components,d.FLOAT,!1,this.itemSize,L):d.vertexAttribIPointer(I,A.components,d[CT[A.type]],this.itemSize,L)}}}setVertexAttribDivisor(d,g,w){for(let A=0;A0&&d.vertexAttribDivisor(I,w)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Wx{constructor(d,g,w,A,I){this.context=d,this.width=g,this.height=w;const L=this.framebuffer=d.gl.createFramebuffer();A>0&&(this.colorAttachment0=new dg(d,L,0)),A>1&&(this.colorAttachment1=new dg(d,L,1)),I&&(this.depthAttachmentType=I,this.depthAttachment=I==="renderbuffer"?new bT(d,L):new Mj(d,L))}static createWithTexture(d,g,w,A,I){const L=d.gl;if(d.activeTexture.set(L.TEXTURE1),d.viewport.set([0,0,w,A]),g&&g.width===w&&g.height===A)return L.bindTexture(L.TEXTURE_2D,g.colorAttachment0.get()),d.bindFramebuffer.set(g.framebuffer),g;g&&g.destroy();const F=new s.T(d,{width:w,height:A,data:null},d.extRenderToTextureHalfFloat?d.gl.RGBA16F:d.gl.RGBA8);F.bind(L.LINEAR,L.CLAMP_TO_EDGE);const $=d.createFramebuffer(w,A,1,null);if($.colorAttachment0.set(F.texture),I){const H=d.createRenderbuffer(L.DEPTH24_STENCIL8,w,A);d.bindFramebuffer.set($.framebuffer),L.framebufferRenderbuffer(L.FRAMEBUFFER,L.DEPTH_STENCIL_ATTACHMENT,L.RENDERBUFFER,H),$._stencilRbo=H}return $}createColorAttachment(d,g){g===0?this.colorAttachment0=new dg(d,this.framebuffer,0):g===1&&(this.colorAttachment1=new dg(d,this.framebuffer,1))}removeColorAttachment(d,g){const w=this.context.gl;let A;g===0?(A=this.colorAttachment0.get(),this.colorAttachment0=void 0):g===1&&(A=this.colorAttachment1.get(),this.colorAttachment1=void 0),A&&w.deleteTexture(A)}destroy(){const d=this.context.gl;if(this.colorAttachment0){const g=this.colorAttachment0.get();g&&d.deleteTexture(g)}if(this.colorAttachment1){const g=this.colorAttachment1.get();g&&d.deleteTexture(g)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const g=this.depthAttachment.get();g&&d.deleteRenderbuffer(g)}else{const g=this.depthAttachment.get();g&&d.deleteTexture(g)}this._stencilRbo&&(d.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),d.deleteFramebuffer(this.framebuffer)}}class mg{constructor(d,g){this.gl=d,this.clearColor=new jj(this),this.clearDepth=new S3(this),this.clearStencil=new hv(this),this.colorMask=new T3(this),this.depthMask=new Ij(this),this.stencilMask=new mT(this),this.stencilFunc=new fv(this),this.stencilOp=new gT(this),this.stencilTest=new Ap(this),this.depthRange=new kp(this),this.depthTest=new lg(this),this.depthFunc=new yd(this),this.blend=new Pj(this),this.blendFunc=new yT(this),this.blendColor=new Nj(this),this.blendEquation=new cg(this),this.cullFace=new pv(this),this.cullFaceSide=new mv(this),this.frontFace=new xT(this),this.program=new gv(this),this.activeTexture=new Ox(this),this.viewport=new Rj(this),this.bindFramebuffer=new Lj(this),this.bindRenderbuffer=new Dj(this),this.bindTexture=new ug(this),this.bindVertexBuffer=new Oj(this),this.bindElementBuffer=new E3(this),this.bindVertexArrayOES=new A3(this),this.pixelStoreUnpack=new k3(this),this.pixelStoreUnpackPremultiplyAlpha=new _T(this),this.pixelStoreUnpackFlipY=new vT(this),this.options=g?Object.assign({},g):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=d.getExtension("EXT_texture_filter_anisotropic")||d.getExtension("MOZ_EXT_texture_filter_anisotropic")||d.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=d.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=d.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=d.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=d.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=g&&!!g.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=g&&!!g.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=d.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=d.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=d.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=d.getParameter(d.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(d.getParameter(d.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=d.getParameter(d.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=d.getExtension("WEBGL_blend_func_extended")}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(d,g,w){return new Mu(this,d,g,w)}createVertexBuffer(d,g,w,A,I){return new Xj(this,d,g,w,A,I)}createRenderbuffer(d,g,w){const A=this.gl,I=A.createRenderbuffer();return this.bindRenderbuffer.set(I),A.renderbufferStorage(A.RENDERBUFFER,d,g,w),this.bindRenderbuffer.set(null),I}createFramebuffer(d,g,w,A){return new Wx(this,d,g,w,A)}clear({color:d,depth:g,stencil:w,colorMask:A}){const I=this.gl;let L=0;d&&(L|=I.COLOR_BUFFER_BIT,this.clearColor.set(d.toNonPremultipliedRenderColor(null)),this.colorMask.set(A||[!0,!0,!0,!0])),g!==void 0&&(L|=I.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(g),this.depthMask.set(!0)),w!==void 0&&(L|=I.STENCIL_BUFFER_BIT,this.clearStencil.set(w),this.stencilMask.set(255)),I.clear(L)}setCullFace(d){d.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(d.mode),this.frontFace.set(d.frontFace))}setDepthMode(d){d.func!==this.gl.ALWAYS||d.mask?(this.depthTest.set(!0),this.depthFunc.set(d.func),this.depthMask.set(d.mask),this.depthRange.set(d.range)):this.depthTest.set(!1)}setStencilMode(d){d.test.func!==this.gl.ALWAYS||d.mask?(this.stencilTest.set(!0),this.stencilMask.set(d.mask),this.stencilOp.set([d.fail,d.depthFail,d.pass]),this.stencilFunc.set({func:d.test.func,ref:d.ref,mask:d.test.mask})):this.stencilTest.set(!1)}setColorMode(d){s.b6(d.blendFunction,Kr.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(d.blendFunction),this.blendColor.set(d.blendColor),d.blendEquation?this.blendEquation.set(d.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(d.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let Ip;function vr(v,d,g,w,A,I,L){const F=v.context,$=F.gl,H=v.transform,Y=[s.aH(H.center.lng),s.aL(H.center.lat)],te=g.layout.get("symbol-placement"),ee=g.layout.get("text-variable-anchor"),ie=g.layout.get("icon-rotation-alignment")==="map",le=g.layout.get("text-rotation-alignment")==="map",oe=te!=="point",me=[];let pe=0,je=0;for(let De=0;De0){const Lr=s.bb(),gr=Gt;s.cz(Lr,st.placementInvProjMatrix,H.glCoordMatrix),s.cz(Lr,Lr,st.placementViewportMatrix),me.push({circleArray:Dt,circleOffset:je,transform:gr,invTransform:Lr,projection:st.getProjection()}),pe+=Dt.length/4,je=pe}if(!Ht)continue;v.terrain&&v.terrain.setupElevationDraw(qe,rr);const Ar=vt?[Fe.canonical.x,Fe.canonical.y,1<=0&&(ie[Re.associatedIconIndex]={x:Qe,y:xt,z:ft,angle:gt})}else eg(ze,te)}if(H){ee.clear();const je=v.icon.placedSymbolArray;for(let Re=0;Re{let on=[0,0,0];if(Jn){const Gi=v.style.directionalLight,_i=v.style.ambientLight;Gi&&_i&&(on=Du(v.style,Gi,_i))}return on},vn=Jn=>{if(v.context.disableSymbolUBO)return;Jn.push("USE_PAINT_PROPERTIES_UBO");const on=Math.floor(v.context.maxUniformBlockSize/4),Gi=Math.floor(on/4);Jn.push(`MAX_UBO_SIZE_VEC4 ${Gi}u`)},tn=Jn=>{Fe.depthOcclusionForSymbolsAndCircles&&(g.hasOcclusionOpacityProperties||v.terrain)&&(Jn.push("DEPTH_D24"),Jn.push("DEPTH_OCCLUSION"))},Vn=Jn=>{g.lut&&!ze&&(g.lut.texture||(g.lut.texture=new s.dR(v.context,g.lut.image,[g.lut.image.height,g.lut.image.height,g.lut.image.height],Ke.gl.RGBA8)),Ke.activeTexture.set(Ke.gl.TEXTURE0+10),g.lut.texture&&g.lut.texture.bind(Ke.gl.LINEAR,Ke.gl.CLAMP_TO_EDGE),Jn.push("APPLY_LUT_ON_GPU"))},xi=()=>{const Jn=qe&&g.layout.get("symbol-placement")!=="point",on=[];tn(on),Vn(on);const Gi=Jn||sn,_i=Dt.elevationType==="road",Os=v.shadowRenderer,jn=_i&&Qe&&!!Os&&Os.enabled,wi=$r(jn),Xs=_i&&Qe&&!v.terrain?ot:Ft,_o=g.paint.get("icon-image-cross-fade");v.terrainRenderModeElevated()&&Qe&&on.push("PITCH_WITH_MAP_TERRAIN"),Ar&&(on.push("PROJECTION_GLOBE_VIEW"),Gi&&on.push("PROJECTED_POS_ON_VIEWPORT")),_o>0&&Dt.hasAnySecondaryIcon&&on.push("ICON_TRANSITION"),!Dt.icon.zOffsetVertexBuffer||_i&&v.terrain||on.push("Z_OFFSET"),pe===0&&je===0&&Re===0&&xe===1||on.push("COLOR_ADJUSTMENT"),Dt.sdfIcons&&on.push("RENDER_SDF"),jn&&on.push("RENDER_SHADOWS","NORMAL_OFFSET"),_i&&Qe&&!v.terrain&&Dt.icon.orientationVertexBuffer&&on.push("ELEVATED_ROADS"),vn(on);const la=Ke.disableSymbolUBO?Dt.icon.programConfigurations.get(g.id):null,Va=v.getOrCreateProgram("symbol",{config:la,defines:on}),sc=Ht.imageAtlasTexture?Ht.imageAtlasTexture.size:[0,0],si=Dt.iconSizeData,Ac=s.bj(si,Fe.zoom),kc=Qe||!Fe.isOrthographic,Ii=af(gr,Ht.tileID.canonical,Qe,qe,Fe,Dt.getProjection(),Tr),Mi=Jm(gr,Ht.tileID.canonical,Qe,qe,Fe,Dt.getProjection(),Tr),fi=Dt.icon.uboBinder&&Dt.icon.uboBinder.cachedHeader&&256&Dt.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:F,Is=v.translatePosMatrix(Mi,Ht,fi,H,!0),Lo=v.translatePosMatrix(gr,Ht,fi,H),hs=Gi?Kx:Ii,ac=qe&&!Qe&&!Jn;let gf=rr;!vt&&!Fe.mercatorFromTransition||qe||(gf=uh(Fe));const Fp=Ar?gf:rr,Bp=g.getColorAdjustmentMatrix(pe,je,Re,xe),bg=jv(si.kind,Ac,ac,Qe,v,Lo,hs,Is,Ze,!1,sc,[0,0],0,Gt,Lr,et,en,Fp,Dt.getProjection(),wi,_n,Bp,_o,null),gh=Ht.imageAtlasTexture?Ht.imageAtlasTexture:null,Sd=g.layout.get("icon-size").constantOr(0)!==1||Dt.iconsNeedLinear,wg=Dt.sdfIcons||v.options.rotating||v.options.zooming||Sd||kc?De.LINEAR:De.NEAREST,Rl=Dt.sdfIcons&&g.paint.get("icon-halo-width").constantOr(1)!==0,yf=v.terrain&&Qe&&Jn?s.b7(s.bb(),Ii):Kx;if(Jn&&Dt.icon){const xf=s.bu.getAtTileOffsetFunc(Gt,Fe.center.lat,Fe.worldSize,Dt.getProjection()),_f=Nu(gr,Ht.tileID.canonical,Qe,qe,Fe,Dt.getProjection(),Tr),eb=g.layout.get("icon-size-scale-range"),Sg=s.aC(v.scaleFactor,eb[0],eb[1]);rc(Dt,gr,v,!1,_f,Mi,Qe,oe,xf,Gt,Sg)}return{program:Va,buffers:Dt.icon,uniformValues:bg,atlasTexture:gh,atlasTextureIcon:null,atlasInterpolation:wg,atlasInterpolationIcon:null,isSDF:Dt.sdfIcons,hasHalo:Rl,depthMode:Xs,tile:Ht,renderWithShadows:jn,labelPlaneMatrixInv:yf}},Ki=()=>{const Jn=st&&g.layout.get("symbol-placement")!=="point",on=[],Gi=Jn||gt||sn,_i=Dt.elevationType==="road",Os=v.shadowRenderer,jn=_i&&xt&&!!Os&&Os.enabled,wi=$r(jn),Xs=_i&&xt&&!v.terrain?ot:Ft;v.terrainRenderModeElevated()&&xt&&on.push("PITCH_WITH_MAP_TERRAIN"),Ar&&(on.push("PROJECTION_GLOBE_VIEW"),Gi&&on.push("PROJECTED_POS_ON_VIEWPORT")),!Dt.text.zOffsetVertexBuffer||_i&&v.terrain||on.push("Z_OFFSET"),Dt.iconsInText&&on.push("RENDER_TEXT_AND_SYMBOL"),on.push("RENDER_SDF"),jn&&on.push("RENDER_SHADOWS","NORMAL_OFFSET"),_i&&xt&&!v.terrain&&Dt.text.orientationVertexBuffer&&on.push("ELEVATED_ROADS"),tn(on),vn(on);const _o=Ke.disableSymbolUBO?Dt.text.programConfigurations.get(g.id):null,la=v.getOrCreateProgram("symbol",{config:_o,defines:on});let Va,sc=[0,0],si=null;const Ac=Dt.textSizeData;Dt.iconsInText&&(sc=Ht.imageAtlasTexture?Ht.imageAtlasTexture.size:[0,0],si=Ht.imageAtlasTexture?Ht.imageAtlasTexture:null,Va=xt||!Fe.isOrthographic||v.options.rotating||v.options.zooming||Ac.kind==="composite"||Ac.kind==="camera"?De.LINEAR:De.NEAREST);const kc=Ht.glyphAtlasTexture?Ht.glyphAtlasTexture.size:[0,0],Ii=g.layout.get("text-size-scale-range"),Mi=s.aC(v.scaleFactor,Ii[0],Ii[1]),fi=s.bj(Ac,Fe.zoom,Mi),Is=af(gr,Ht.tileID.canonical,xt,st,Fe,Dt.getProjection(),Tr),Lo=Jm(gr,Ht.tileID.canonical,xt,st,Fe,Dt.getProjection(),Tr),hs=Dt.text.uboBinder&&Dt.text.uboBinder.cachedHeader&&256&Dt.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:$,ac=v.translatePosMatrix(Lo,Ht,hs,Y,!0),gf=v.translatePosMatrix(gr,Ht,hs,Y),Fp=Gi?Kx:Is,Bp=st&&!xt&&!Jn;let bg=rr;!vt&&!Fe.mercatorFromTransition||st||(bg=uh(Fe));const gh=jv(Ac.kind,fi,Bp,xt,v,gf,Fp,ac,Ze,!0,kc,sc,0,Gt,Lr,et,en,Ar?bg:rr,Dt.getProjection(),wi,_n,null,null,Mi),Sd=Ht.glyphAtlasTexture?Ht.glyphAtlasTexture:null,wg=De.LINEAR,Rl=g.paint.get("text-halo-width").constantOr(1)!==0,yf=v.terrain&&xt&&Jn?s.b7(s.bb(),Is):Kx;if(Jn&&Dt.text){const xf=s.bu.getAtTileOffsetFunc(Gt,Fe.center.lat,Fe.worldSize,Dt.getProjection()),_f=Nu(gr,Ht.tileID.canonical,xt,st,Fe,Dt.getProjection(),Tr);rc(Dt,gr,v,!0,_f,Lo,xt,me,xf,Gt,Mi)}return{program:la,buffers:Dt.text,uniformValues:gh,atlasTexture:Sd,atlasTextureIcon:si,atlasInterpolation:wg,atlasInterpolationIcon:Va,isSDF:!0,hasHalo:Rl,depthMode:Xs,tile:Ht,renderWithShadows:jn,labelPlaneMatrixInv:yf}},Ti=Dt.icon.segments.get().length,Qn=Dt.text.segments.get().length,pn=Ti&&!L.onlyText?xi():null,mn=Qn&&!L.onlyIcons?Ki():null,Ei=g.paint.get("icon-opacity").constantOr(1),rs=g.paint.get("text-opacity").constantOr(1);if(ft&&Dt.canOverlap){Rt=!0;const Jn=Ei&&!L.onlyText?Dt.icon.segments.get():[],on=rs&&!L.onlyIcons?Dt.text.segments.get():[];for(const Gi of Jn)St.push({segments:new s.dy([Gi]),sortKey:Gi.sortKey,state:pn});for(const Gi of on)St.push({segments:new s.dy([Gi]),sortKey:Gi.sortKey,state:mn})}else L.onlyText||St.push({segments:Ei?Dt.icon.segments:new s.dy([]),sortKey:0,state:pn}),L.onlyIcons||St.push({segments:rs?Dt.text.segments:new s.dy([]),sortKey:0,state:mn})}Rt&&St.sort((Gt,Ht)=>Gt.sortKey-Ht.sortKey);for(const Gt of St){const Ht=Gt.state;if(Ht)if(v.terrain?v.terrain.setupElevationDraw(Ht.tile,Ht.program,{useDepthForOcclusion:Fe.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:Ht.labelPlaneMatrixInv}):v.setupDepthForOcclusion(Fe.depthOcclusionForSymbolsAndCircles,Ht.program),Ke.activeTexture.set(De.TEXTURE0),Ht.atlasTexture&&Ht.atlasTexture.bind(Ht.atlasInterpolation,De.CLAMP_TO_EDGE,!0),Ht.atlasTextureIcon&&(Ke.activeTexture.set(De.TEXTURE1),Ht.atlasTextureIcon&&Ht.atlasTextureIcon.bind(Ht.atlasInterpolationIcon,De.CLAMP_TO_EDGE,!0)),Ht.renderWithShadows&&v.shadowRenderer.setupShadows(Ht.tile.tileID.toUnwrapped(),Ht.program,"vector-tile"),v.uploadCommonLightUniforms(v.context,Ht.program),Ht.hasHalo){const Dt=Ht.uniformValues;Dt.u_is_halo=1,Nv(Ht.buffers,Gt.segments,g,v,Ht.program,Ht.depthMode,A,I,Dt,2),Dt.u_is_halo=0}else{if(Ht.isSDF){const Dt=Ht.uniformValues;Ht.hasHalo&&(Dt.u_is_halo=1,Nv(Ht.buffers,Gt.segments,g,v,Ht.program,Ht.depthMode,A,I,Dt,1)),Dt.u_is_halo=0}Nv(Ht.buffers,Gt.segments,g,v,Ht.program,Ht.depthMode,A,I,Ht.uniformValues,1)}}}function Nv(v,d,g,w,A,I,L,F,$,H){const Y=w.context,te=Y.gl,ee=[v.dynamicLayoutVertexBuffer,v.opacityVertexBuffer,v.iconTransitioningVertexBuffer,v.globeExtVertexBuffer,v.zOffsetVertexBuffer,v.orientationVertexBuffer];v.featureIdBuffer&&ee.push(v.featureIdBuffer);const ie=v.uboBinder?null:v.programConfigurations.get(g.id);if(v.uboBinder){v.uboBinder.layer=g;const me=w.transform.zoom,pe=w.style.getBrightness?w.style.getBrightness():null,je=v.uboBinder.getConstantUniformValues(me,pe);$.u_spp_fill_np_color=je.fill_np_color,$.u_spp_halo_np_color=je.halo_np_color,$.u_spp_opacity=je.opacity,$.u_spp_halo_width=je.halo_width,$.u_spp_halo_blur=je.halo_blur,$.u_spp_emissive_strength=je.emissive_strength,$.u_spp_occlusion_opacity=je.occlusion_opacity,$.u_spp_z_offset=je.z_offset;const Re=g.paint.get(v.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),xe=v.uboBinder.cachedHeader&&256&v.uboBinder.cachedHeader.dataDrivenMask&&Re==="map"?w.transform.angle:0;$.u_spp_translate_rotation=[Math.cos(xe),Math.sin(xe)]}const{batchIndices:le,batchSegments:oe}=v.getBatchGrouping(d);for(const me of le){const pe=oe.get(me);v.uboBinder&&v.uboBinder.bind(Y,A.program,me),A.draw(w,te.TRIANGLES,I,L,F,Gr.disabled,$,g.id,v.layoutVertexBuffer,v.indexBuffer,pe,g.paint,w.transform.zoom,ie,ee,H)}}function Rv(v,d,g,w,A,I){const L=g.paint.get("line-width"),F=g.paint.get("line-emissive-strength").isConstant(),$=g.paint.get("line-emissive-strength").constantOr(0),H=g.paint.get("line-occlusion-opacity"),Y=g.layout.get("line-elevation-reference"),te=g.layout.get("line-width-unit")==="meters",ee=Y==="sea",ie=!(!v.terrain||!v.terrain.enabled),le=v.context,oe=le.gl;if(g.hasElevatedBuckets&&v.transform.projection.name==="globe")return;const me=g.layout.get("line-cross-slope"),pe=me!==void 0,je=me<1,Re=A||v.colorModeForDrapableLayerRenderPass(F?$:null),xe=v.terrain&&v.terrain.renderingToTexture||I,Ze=xe?1:s.o.devicePixelRatio,ze=g.paint.get("line-dasharray"),Ke=ze.constantOr(1),De=g.layout.get("line-cap"),Fe=ze.constantOr(null),qe=De.constantOr(null),st=g.paint.get("line-pattern"),Qe=st.constantOr(1),xt=g.paint.get("line-pattern-cross-fade"),ft=st.constantOr(null),Rt=g.paint.get("line-opacity").constantOr(1);let Ft=!Qe&&Rt!==1||v.depthOcclusion&&H>0&&H<1;const ot=g.paint.get("line-gradient"),et=Qe?"linePattern":"line",gt=s.dU(g);let vt;if(xe&&v.terrain&&v.terrain.clipOrMaskOverlapStencilType()&&(Ft=!1),H!==0&&v.depthOcclusion){const Dt=g.paint._values["line-opacity"];Dt&&Dt.value&&Dt.value.kind==="constant"?vt=Dt.value:s.w(`Occlusion opacity for layer ${g.id} is supported only when line-opacity isn't data-driven.`)}L.value.kind!=="constant"&&L.value.isLineProgressConstant===!1&>.push("VARIABLE_LINE_WIDTH"),xe&&(v.emissiveMode!=="dual-source-blending"||F?v.emissiveMode==="mrt-fallback"&>.push("USE_MRT1"):gt.push("DUAL_SOURCE_BLENDING"));const St={},rr=(Dt,Ar,Lr,gr,Tr,Hr)=>{for(const sn of Dt){const en=d.getTile(sn);if(Qe&&!en.patternsLoaded())continue;const _n=en.getBucket(g);if(!_n||_n.elevationType!=="none"&&!Tr||_n.elevationType==="none"&&Tr)continue;v.prepareDrawTile();const $r=[...Ar],vn=v.shadowRenderer,tn=_n.elevationType==="road"&&!!vn&&vn.enabled;let Vn=[0,0,0];if(tn){const jn=v.style.directionalLight,wi=v.style.ambientLight;jn&&wi&&(Vn=Du(v.style,jn,wi)),$r.push("RENDER_SHADOWS","NORMAL_OFFSET")}const xi=_n.programConfigurations.get(g.id);let Ki=!1;if(ft&&en.imageAtlas){const jn=s.dV.from(ft),wi=jn.getPrimary().scaleSelf(Ze).toString(),Xs=en.imageAtlas.patternPositions.get(wi),_o=jn.getSecondary(),la=_o?en.imageAtlas.patternPositions.get(_o.scaleSelf(Ze).toString()):null;Ki=!!Xs&&!!la,Xs&&xi.setConstantPatternPositions(Xs,la)}xt>0&&(Ki||xi.getPatternTransitionVertexBuffer("line-pattern"))&&$r.push("LINE_PATTERN_TRANSITION"),_n.elevationGroundScaleVertexBuffer&&$r.push("ELEVATION_GROUND_SCALE");const Ti=v.isTileAffectedByFog(sn),Qn=v.getOrCreateProgram(et,{config:xi,defines:$r,overrideFog:Ti});if(!Qe&&Fe&&qe&&en.lineAtlas){const jn=en.lineAtlas.getDash(Fe,qe);jn&&xi.setConstantPatternPositions(jn)}tn&&vn.setupShadows(en.tileID.toUnwrapped(),Qn,"vector-tile");let[pn,mn]=g.paint.get("line-trim-offset");(qe==="round"||qe==="square")&&pn!==mn&&(pn===0&&(pn-=1),mn===1&&(mn+=1));const Ei=xe?sn.projMatrix:null,rs=te?1/_n.tileToMeter/s.aA(en,1,v.transform.zoom):1,Jn=te?1/_n.tileToMeter/s.aA(en,1,Math.floor(v.transform.zoom)):1,on=Ke?g.paint._values["line-floorwidth"]:null;let Gi;if(on&&on.value.kind==="constant"){const jn=_n.zoom;jn in St||(St[jn]=Math.max(.01,g.widthExpression().evaluate({zoom:jn}))),Gi=on.value.value;const wi=Math.floor(v.transform.zoom);on.value.value=St[jn]*Math.pow(2,wi-en.tileID.overscaledZ)}const _i=Qe?s.dW(v,en,g,Ei,Ze,rs,Jn,[pn,mn],Vn,xt):s.dX(v,en,g,Ei,_n.lineClipsArray.length,Ze,rs,Jn,[pn,mn],Vn);if(ot){const jn=_n.gradients[g.id];let wi=jn.texture;if(g.gradientVersion!==jn.version){let Xs=256;if(g.stepInterpolant){const _o=d.getSource().maxzoom,la=sn.canonical.z===_o?Math.ceil(1<{vt!=null&&(vt.value=Rt*H),Qn.draw(v,oe.TRIANGLES,Lr,jn,Re,Gr.disabled,_i,g.id,_n.layoutVertexBuffer,_n.indexBuffer,_n.segments,g.paint,v.transform.zoom,xi,[_n.layoutVertexBuffer2,_n.patternVertexBuffer,_n.zOffsetVertexBuffer,_n.elevationGroundScaleVertexBuffer]),vt!=null&&(vt.value=Rt)};if(Ft&&!Tr){const jn=v.stencilModeForClipping(sn).ref;jn===0&&xe&&le.clear({stencil:0});const wi={func:oe.EQUAL,mask:255};_i.u_alpha_discard_threshold=.8,Os(new Qr(wi,jn,255,oe.KEEP,oe.KEEP,oe.INVERT)),_i.u_alpha_discard_threshold=0,Os(new Qr(wi,jn,255,oe.KEEP,oe.KEEP,oe.KEEP))}else _i.u_alpha_discard_threshold=Ft&&Tr&&Hr?.8:0,Os(Tr?gr:v.stencilModeForClipping(sn));Gi!==void 0&&(on.value.value=Gi)}};let Gt=v.depthModeForSublayer(0,Ir.ReadOnly);const Ht=new Ir(v.depthOcclusion?oe.GREATER:oe.LEQUAL,Ir.ReadOnly,v.depthRangeFor3D);if(g.hasNonElevatedBuckets){const Dt=!xe&&v.terrain;H!==0&&Dt?s.w(`Occlusion opacity for layer ${g.id} is supported on terrain only if the layer has line-z-offset enabled.`):Dt?s.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${g.id}.`):rr(w,gt,Gt,Qr.disabled,!1,!0)}if(g.hasElevatedBuckets){Y==="hd-road-markup"?ie||(Gt=Ht,gt.push("ELEVATED_ROADS")):(gt.push("ELEVATED"),Gt=Ht,pe&>.push(je?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),ee&>.push("ELEVATION_REFERENCE_SEA"));const Dt=Ft?v.stencilModeFor3D():Qr.disabled;v.forceTerrainMode=!0,rr(w,gt,Gt,Dt,!0,!0),Ft&&rr(w,gt,Gt,Dt,!0,!1),v.forceTerrainMode=!1}Ft&&(v.resetStencilClippingMasks(),xe&&le.clear({stencil:0})),H===0||v.depthOcclusion||xe||v.layersWithOcclusionOpacity.push(v.currentLayer)}const dh={additive:{clearColor:new s.aq(0,0,0,0),colorMode:Kr.additive,compositeUniformValue:1},multiply:{clearColor:new s.aq(1,1,1,1),colorMode:Kr.multiply,compositeUniformValue:0}};function jT(v,d){const g=1<=Sp?1:ie.pitch/Sp))),2*le}(v.transform),H=v.transform.getFreeCameraOptions().position,Y="elevatedStructuresDepthReconstruct",te=v.getOrCreateProgram(Y,{defines:["DEPTH_RECONSTRUCTION"]}),ee=v.getOrCreateProgram(Y);for(const ie of w){const le=d.getTile(ie),oe=le.getBucket(g);if(!oe)continue;const me=oe.elevatedStructures;if(!me)continue;const pe=oe.elevationBufferData.heightRange,je=jT(ie.toUnwrapped(),H),Re=v.translatePosMatrix(ie.projMatrix,le,g.paint.get("fill-translate"),g.paint.get("fill-translate-anchor"));let xe,Ze,ze,Ke;if(A==="initialize"){if(!pe||pe.min>=1||me.depthSegments.segments[0].primitiveLength===0)continue;xe=qx(Re,je,$,1,0),Ze=L,ze=me.depthSegments,Ke=te}else if(A==="reset"){if(!pe||pe.min>=0||me.maskSegments.segments[0].primitiveLength===0)continue;xe=qx(Re,je,0,0,1),Ze=F,ze=me.maskSegments,Ke=te}else if(A==="geometry"){if(me.depthSegments.segments[0].primitiveLength===0)continue;xe=qx(Re,je,$,1,0),Ze=L,ze=me.depthSegments,Ke=ee}Ke.draw(v,I.TRIANGLES,Ze,Qr.disabled,Kr.disabled,Gr.disabled,xe,g.id,me.vertexBuffer,me.indexBuffer,ze,g.paint,v.transform.zoom)}}function Zx(v,d,g,w){const{painter:A,sourceCache:I,layer:L,coords:F,colorMode:$,elevationType:H,terrainEnabled:Y,pass:te}=v,ee=A.context.gl,ie=L.paint.get("fill-pattern"),le=L.paint.get("fill-pattern-cross-fade"),oe=ie.constantOr(null);let me=H;H!=="road"||d&&!Y||(me="none");const pe=me==="road",je=v.painter.shadowRenderer,Re=pe&&!!je&&je.enabled,xe=new Ir(A.context.gl.LEQUAL,Ir.ReadOnly,A.depthRangeFor3D);let Ze=[0,0,0];if(Re){const Fe=A.style.directionalLight,qe=A.style.ambientLight;Fe&&qe&&(Ze=Du(A.style,Fe,qe))}const ze=ie&&ie.constantOr(1),Ke=A.terrain&&A.terrain.renderingToTexture,De=(Fe,qe)=>{let st,Qe,xt,ft,Rt;qe?(st=ze&&!L.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",xt=ee.LINES):(st=ze?"fillPattern":"fill",xt=ee.TRIANGLES);for(const Ft of F){const ot=I.getTile(Ft);if(ze&&!ot.patternsLoaded())continue;const et=ot.getBucket(L);if(!et)continue;const gt=d?et.elevationBufferData:et.bufferData;if(gt.isEmpty())continue;A.prepareDrawTile();const vt=gt.programConfigurations.get(L.id),St=A.isTileAffectedByFog(Ft),rr=[],Gt=[];pe&&(rr.push("ELEVATED_ROADS"),Gt.push(gt.elevatedLayoutVertexBuffer)),Re&&rr.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ke&&g&&rr.push("USE_MRT1"),ze&&(A.context.activeTexture.set(ee.TEXTURE0),ot.imageAtlasTexture&&ot.imageAtlasTexture.bind(ee.LINEAR,ee.CLAMP_TO_EDGE),vt.updatePaintBuffers());let Ht=!1;if(oe&&ot.imageAtlas){const Tr=ot.imageAtlas,Hr=s.dV.from(oe),sn=Hr.getPrimary().scaleSelf(s.o.devicePixelRatio).toString(),en=Hr.getSecondary(),_n=Tr.patternPositions.get(sn),$r=en?Tr.patternPositions.get(en.scaleSelf(s.o.devicePixelRatio).toString()):null;Ht=!!_n&&!!$r,_n&&vt.setConstantPatternPositions(_n,$r)}le>0&&(Ht||vt.getPatternTransitionVertexBuffer("fill-pattern"))&&rr.push("FILL_PATTERN_TRANSITION");const Dt=A.getOrCreateProgram(st,{config:vt,overrideFog:St,defines:rr}),Ar=A.translatePosMatrix(Ft.projMatrix,ot,L.paint.get("fill-translate"),L.paint.get("fill-translate-anchor"));Re&&je.setupShadows(ot.tileID.toUnwrapped(),Dt,"vector-tile");const Lr=L.paint.get("fill-emissive-strength");if(qe){ft=gt.lineIndexBuffer,Rt=gt.lineSegments;const Tr=A.terrain&&A.terrain.renderingToTexture?A.terrain.drapeBufferSize:[ee.drawingBufferWidth,ee.drawingBufferHeight];Qe=st==="fillOutlinePattern"&&ze?fg(Ar,Lr,A,ot,Tr,Ze,le):Uj(Ar,Lr,Tr,Ze)}else ft=gt.indexBuffer,Rt=gt.triangleSegments,Qe=ze?Sv(Ar,Lr,A,ot,Ze,le):wv(Ar,Lr,Ze);A.uploadCommonUniforms(A.context,Dt,Ft.toUnwrapped());let gr=Fe;(H==="road"&&!Y||H==="offset")&&(gr=xe),Dt.draw(A,xt,gr,w||A.stencilModeForClipping(Ft),$,Gr.disabled,Qe,L.id,gt.layoutVertexBuffer,ft,Rt,L.paint,A.transform.zoom,vt,Gt)}};A.renderPass===te&&De(A.depthModeForSublayer(1,A.renderPass==="opaque"?Ir.ReadWrite:Ir.ReadOnly),!1),me==="none"&&A.renderPass==="translucent"&&L.paint.get("fill-antialias")&&De(A.depthModeForSublayer(L.getPaintProperty("fill-outline-color")?2:0,Ir.ReadOnly),!0)}function Pp(v,d,g,w,A,I,L,F){g.resetLayerRenderingStats(v);const $=v.context,H=$.gl,Y=v.transform,te=g.paint.get("fill-extrusion-pattern"),ee=g.paint.get("fill-extrusion-pattern-cross-fade"),ie=te.constantOr(null),le=te.constantOr(1),oe=g.paint.get("fill-extrusion-opacity"),me=v.style.enable3dLights(),pe=g.paint.get(me&&!le?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),je=[g.paint.get("fill-extrusion-ambient-occlusion-intensity"),pe],Re=g.layout.get("fill-extrusion-edge-radius"),xe=Re>0&&!g.paint.get("fill-extrusion-rounded-roof"),Ze=xe?0:Re,ze=Y.projection.name==="globe"?s.e1():0,Ke=Y.projection.name==="globe",De=Ke?s.al(Y.zoom):0,Fe=[s.aH(Y.center.lng),s.aL(Y.center.lat)],qe=g.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",st=g.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(qe?null:g.lut).toArray01().slice(0,3),Qe=g.paint.get("fill-extrusion-flood-light-intensity"),xt=g.paint.get("fill-extrusion-vertical-scale"),ft=g.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Rt=g.paint.get("fill-extrusion-height-alignment"),Ft=g.paint.get("fill-extrusion-base-alignment"),ot=Pa(v,g.paint.get("fill-extrusion-cutoff-fade-range")),et=g.paint.get("fill-extrusion-front-cutoff"),gt=Lv(Y.pitch,et,!!v.terrain),vt=gt[2]<1;vt&&(v.maxFrontCutoffRawStart=Math.max(v.maxFrontCutoffRawStart,et[0]));const St=[];let rr;Ke&&St.push("PROJECTION_GLOBE_VIEW"),je[0]>0&&St.push("FAUX_AO"),xe&&St.push("ZERO_ROOF_RADIUS"),F&&St.push("HAS_CENTROID"),Qe>0&&St.push("FLOOD_LIGHT"),ot.shouldRenderCutoff&&St.push("RENDER_CUTOFF"),vt&&St.push("RENDER_FRONT_CUTOFF"),ft&&St.push("RENDER_WALL_MODE");const Gt=v.renderPass==="shadow",Ht=v.shadowRenderer,Dt=Gt&&!!Ht,Ar=Gt?Gr.disabled:Gr.backCCW;v.shadowRenderer&&(v.shadowRenderer.useNormalOffset=!0);let Lr=[0,0,0];if(Ht){const Hr=v.style.directionalLight,sn=v.style.ambientLight;Hr&&sn&&(Lr=Du(v.style,Hr,sn)),Gt||(St.push("RENDER_SHADOWS"),Ht.useNormalOffset&&St.push("NORMAL_OFFSET")),rr=St.concat(["SHADOWS_SINGLE_CASCADE"])}const gr=Dt?"fillExtrusionDepth":le?"fillExtrusionPattern":"fillExtrusion",Tr=g.getLayerRenderingStats();for(const Hr of w){const sn=d.getTile(Hr),en=sn.getBucket(g);if(!en||en.projection.name!==Y.projection.name)continue;let _n=!1;Ht&&(_n=Ht.getMaxCascadeForTile(Hr.toUnwrapped())===0);const $r=v.isTileAffectedByFog(Hr),vn=en.programConfigurations.get(g.id);let tn=!1;if(ie&&sn.imageAtlas){const mn=sn.imageAtlas,Ei=s.dV.from(ie),rs=Ei.getPrimary().scaleSelf(s.o.devicePixelRatio).toString(),Jn=Ei.getSecondary(),on=mn.patternPositions.get(rs),Gi=Jn?mn.patternPositions.get(Jn.scaleSelf(s.o.devicePixelRatio).toString()):null;tn=!!on&&!!Gi,on&&vn.setConstantPatternPositions(on,Gi)}ee>0&&(tn||vn.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&St.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Vn=v.getOrCreateProgram(gr,{config:vn,defines:_n?rr:St,overrideFog:$r});if(v.terrain&&v.terrain.setupElevationDraw(sn,Vn,{useMeterToDem:!0}),!en.centroidVertexBuffer){const mn=Vn.getAttributeLocation(H,"a_centroid_pos");mn!==-1&&H.vertexAttribI4ui(mn,0,0,0,0)}!Gt&&Ht&&Ht.setupShadows(sn.tileID.toUnwrapped(),Vn,"vector-tile"),le&&(v.context.activeTexture.set(H.TEXTURE0),sn.imageAtlasTexture&&sn.imageAtlasTexture.bind(H.LINEAR,H.CLAMP_TO_EDGE),vn.updatePaintBuffers());const xi=g.paint.get("fill-extrusion-vertical-gradient"),Ki=1/en.tileToMeter;let Ti;if(Gt&&Ht){if(Dv(sn.tileID,en.maxHeight,v))continue;const mn=Ht.calculateShadowPassMatrixFromTile(sn.tileID.toUnwrapped());Ti=I3(mn,Ze,Ki,xt,Rt,Ft)}else{const mn=v.translatePosMatrix(Hr.expandedProjMatrix,sn,g.paint.get("fill-extrusion-translate"),g.paint.get("fill-extrusion-translate-anchor")),Ei=Y.projection.createInversionMatrix(Y,Hr.canonical);Ti=le?P3(mn,v,xi,oe,je,Ze,Ki,Hr,sn,ze,Rt,Ft,De,Fe,Ei,st,xt,ee):$j(mn,v,xi,oe,je,Ze,Ki,Hr,ze,Rt,Ft,De,Fe,Ei,st,xt,Qe,Lr,gt)}v.uploadCommonUniforms($,Vn,Hr.toUnwrapped(),null,ot);let Qn=en.segments;if(Y.projection.name==="mercator"&&!Gt&&(Qn=en.getVisibleSegments(sn.tileID,v.terrain,v.transform.getFrustum(0)),!Qn.get().length))continue;if(Tr)if(Gt)for(const mn of Qn.get())Tr.numRenderedVerticesInShadowPass+=mn.primitiveLength;else for(const mn of Qn.get())Tr.numRenderedVerticesInTransparentPass+=mn.primitiveLength;const pn=[];(v.terrain||F)&&pn.push(en.centroidVertexBuffer),Ke&&pn.push(en.layoutVertexExtBuffer),ft&&pn.push(en.wallVertexBuffer),Vn.draw(v,$.gl.TRIANGLES,A,I,L,Ar,Ti,g.id,en.layoutVertexBuffer,en.indexBuffer,Qn,g.paint,v.transform.zoom,vn,pn)}v.shadowRenderer&&(v.shadowRenderer.useNormalOffset=!1)}class IT{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function Lv(v,d,g){if(!(d[2]<1)||g)return[0,0,1];const w=180*v/Math.PI;if(w<15)return[-.5,d[1],d[2]];const A=Math.min(1,Math.max(0,(w-15)/5)),I=A*A*(3-2*A);return[-.5*(1-I)+d[0]*I,d[1],d[2]]}function _d(v,d,g,w,A,I,L,F,$,H,Y,te,ee,ie,le,oe,me,pe,je,Re,xe){const Ze=d.context,ze=Ze.gl,Ke=d.transform,De=d.transform.zoom,Fe=[],qe=v.translate,st=v.translateAnchor,Qe=v.edgeRadius,xt=Pa(d,v.cutoffFadeRange);Y==="clear"?(Fe.push("CLEAR_SUBPASS"),Re&&(Fe.push("CLEAR_FROM_TEXTURE"),Ze.activeTexture.set(ze.TEXTURE0),Re.bind(ze.LINEAR,ze.CLAMP_TO_EDGE))):Y==="sdf"?Fe.push("SDF_SUBPASS"):Y==="emissive"&&(Fe.push("USE_MRT1"),Ze.activeTexture.set(ze.TEXTURE0),Re.bind(ze.LINEAR,ze.CLAMP_TO_EDGE)),pe&&Fe.push("HAS_CENTROID"),xt.shouldRenderCutoff&&Fe.push("RENDER_CUTOFF");const ft=(Rt,Ft,ot,et,gt)=>{let vt=Fe;Ft.groundRadiusBuffer!=null&&(vt=Fe.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const St=Ft.programConfigurations.get(w.id),rr=d.isTileAffectedByFog(Rt),Gt=d.getOrCreateProgram("fillExtrusionGroundEffect",{config:St,defines:vt,overrideFog:rr}),Ht=((Ar,Lr,gr,Tr,Hr,sn,en,_n,$r,vn,tn)=>({u_matrix:Lr,u_opacity:gr,u_ao_pass:Tr?1:0,u_meter_to_tile:Hr,u_ao:sn,u_flood_light_intensity:en,u_flood_light_color:_n,u_attenuation:$r,u_edge_radius:vn,u_fb:0,u_fb_size:tn,u_dynamic_offset:1}))(0,et,te,H,gt,[ee,ie*gt],le,oe,me,De>=17?0:Qe*gt,Re?Re.size[0]:0),Dt=[];pe&&Dt.push(Ft.hiddenByLandmarkVertexBuffer),Ft.groundRadiusBuffer!=null&&Dt.push(Ft.groundRadiusBuffer),d.uploadCommonUniforms(Ze,Gt,Rt.toUnwrapped(),null,xt),Gt.draw(d,Ze.gl.TRIANGLES,I,L,F,$,Ht,w.id,Ft.vertexBuffer,Ft.indexBuffer,ot,w.paint,De,St,Dt)};for(const Rt of A){const Ft=g.getTile(Rt),ot=Ft.getBucket(w);if(!ot||ot.projection.name!==Ke.projection.name||!ot.groundEffect||ot.groundEffect&&!ot.groundEffect.hasData())continue;const et=ot.groundEffect,gt=1/ot.tileToMeter;{const vt=d.translatePosMatrix(Rt.projMatrix,Ft,qe,st),St=et.getDefaultSegment();ft(Rt,et,St,vt,gt)}if(je)for(let vt=0;vt<4;vt++){const St=s.d$[vt](Rt),rr=g.getTile(St);if(!rr)continue;const Gt=rr.getBucket(w);if(!Gt||Gt.projection.name!==Ke.projection.name||!Gt.groundEffect||Gt.groundEffect&&!Gt.groundEffect.hasData())continue;const Ht=Gt.groundEffect;let Dt,Ar;vt===0?(Dt=[-s.an,0,0],Ar=1):vt===1?(Dt=[s.an,0,0],Ar=0):vt===2?(Dt=[0,-s.an,0],Ar=3):(Dt=[0,s.an,0],Ar=2);const Lr=Ht.regionSegments[Ar];if(!Lr)continue;const gr=new Float32Array(16);s.bx(gr,Rt.projMatrix,Dt),ft(Rt,Ht,Lr,d.translatePosMatrix(gr,Ft,qe,st),gt)}}}function Jj(v,d,g,w,A,I,L){w.centroidVertexArray.length===0&&w.createCentroidsBuffer();const F=I?I.findDEMTileFor(g):null;if(!(F&&F.dem||L))return;I&&F&&F.dem&&w.selfDEMTileTimestamp!==F.dem._timestamp&&(w.borderDoneWithNeighborZ=[-1,-1,-1,-1],w.selfDEMTileTimestamp=F.dem._timestamp);const $=(pe,je)=>{(pe.flags|je.flags)&s.e3?(pe.flags|=s.e3,je.flags|=s.e3):(pe.flags&=~s.e3,je.flags&=~s.e3)},H=pe=>new s.P(Math.ceil((pe+s.e4)*s.e5),0),Y=(pe,je,Re)=>{const xe=Math.ceil((pe+s.e4)*s.e5),Ze=Math.floor(Math.max(0,Math.min(s.an-1,Re))/4);return new s.P(xe,Ze<<5|(3&je)<<3|7)},te=pe=>{const je=d.getSource().minzoom,Re=Ze=>{const ze=d.getTileByID(Ze);if(ze&&ze.hasData())return ze.getBucket(A)},xe=[0,-1,1];for(const Ze of xe){if(pe.overscaledZ+Ze(ee[0]=Math.min(pe.min.y,je.min.y),ee[1]=Math.max(pe.max.y,je.max.y),ee[2]=s.an-je.min.x>pe.max.x?je.min.x-s.an:pe.max.x,ee),le=(pe,je)=>(ee[0]=Math.min(pe.min.x,je.min.x),ee[1]=Math.max(pe.max.x,je.max.x),ee[2]=s.an-je.min.y>pe.max.y?je.min.y-s.an:pe.max.y,ee),oe=[(pe,je)=>ie(pe,je),(pe,je)=>ie(je,pe),(pe,je)=>le(pe,je),(pe,je)=>le(je,pe)],me=(pe,je,Re,xe,Ze,ze,Ke)=>{if(!I)return 0;const De=[[ze?Re:pe,ze?pe:Re,0],[ze?Re:je,ze?je:Re,0]],Fe=Ke<0?s.an+Ke:Ke,qe=[ze?Fe:(pe+je)/2,ze?(pe+je)/2:Fe,0];return Re===0&&Ke<0||Re!==0&&Ke>0?I.getForTilePoints(Ze,[qe],!0,xe):De.push(qe),I.getForTilePoints(g,De,!0,F),Math.max(De[0][2],De[1][2],qe[2])/I.exaggeration()};for(let pe=0;pe<4;pe++){const je=w.borderFeatureIndices[pe];if(je.length===0)continue;const Re=s.d$[pe](g),xe=te(Re);if(!(xe&&xe instanceof s.e0))continue;const Ze=I?I.findDEMTileFor(Re):null;if(!(Ze&&Ze.dem||L)||(I&&Ze&&Ze.dem&&w.borderDEMTileTimestamp[pe]!==Ze.dem._timestamp&&(w.borderDoneWithNeighborZ[pe]=-1,w.borderDEMTileTimestamp[pe]=Ze.dem._timestamp),w.borderDoneWithNeighborZ[pe]===xe.canonical.z))continue;xe.centroidVertexArray.length===0&&xe.createCentroidsBuffer();const ze=(pe<2?1:5)-pe,Ke=xe.borderDoneWithNeighborZ[ze]!==w.canonical.z,De=xe.borderFeatureIndices[ze];let Fe=0;if(w.canonical.z!==xe.canonical.z){for(const xt of je)w.showCentroid(w.featuresOnBorder[xt]);if(Ke)for(const xt of De)xe.showCentroid(xe.featuresOnBorder[xt]);w.borderDoneWithNeighborZ[pe]=xe.canonical.z,xe.borderDoneWithNeighborZ[ze]=w.canonical.z;continue}const qe=new Map,st=new Set,Qe=new Set;for(let xt=0;xt1||ot.intersectsCount()>1;{let Gt=0;if(Ze&&Ze.dem&&!rr){const Ht=oe[pe](Rt,et),Dt=pe%2?s.an-1:0;Gt=me(Ht[0],Math.min(s.an-1,Ht[1]),Dt,Ze,Re,pe<2,Ht[2])}Rt.centroidXY=Y(Gt,pe,St),et.centroidXY=Y(Gt,ze,St)}if(w.writeCentroidToBuffer(Rt),xe.writeCentroidToBuffer(et),ft.buildingId!==void 0){for(const Gt of w.centroidData)Gt.buildingId===ft.buildingId&&Gt!==Rt&&(Gt.centroidXY=Rt.centroidXY,w.writeCentroidToBuffer(Gt));for(const Gt of xe.centroidData)Gt.buildingId===ft.buildingId&&Gt!==et&&(Gt.centroidXY=et.centroidXY,xe.writeCentroidToBuffer(Gt))}}for(const xt of je){if(st.has(xt))continue;const ft=w.featuresOnBorder[xt],Rt=w.centroidData[ft.centroidDataIndex],Ft=ft.borders[pe];let ot;for(;FeFt[0]+3||et[0]>Ft[0]-3)break;xe.showCentroid(ot),Fe++}if(ot&&FeFt[1]-3||(gt++,++Fe===De.length))break;ot=xe.featuresOnBorder[De[Fe]]}for(;et=De.length){w.showCentroid(ft);continue}ot=xe.featuresOnBorder[De[et]];let vt=!1;if(gt>=1){const Gt=ot.borders[ze];Math.abs(Ft[0]-Gt[0])<3&&Math.abs(Ft[1]-Gt[1])<3&&(gt=1,vt=!0,Fe=et+1)}else if(gt===0){w.showCentroid(ft);continue}const St=xe.centroidData[ot.centroidDataIndex];L&&vt&&$(Rt,St);const rr=ft.intersectsCount()>1||ot.intersectsCount()>1;if(gt>1)Fe=et,Rt.centroidXY=St.centroidXY=new s.P(0,0);else if(Ze&&Ze.dem&&!rr){const Gt=oe[pe](Rt,St),Ht=pe%2?s.an-1:0,Dt=me(Gt[0],Math.min(s.an-1,Gt[1]),Ht,Ze,Re,pe<2,Gt[2]);Rt.centroidXY=St.centroidXY=H(Dt)}else rr?Rt.centroidXY=St.centroidXY=new s.P(0,0):(Rt.centroidXY=w.encodeBorderCentroid(ft),St.centroidXY=xe.encodeBorderCentroid(ot));w.writeCentroidToBuffer(Rt),xe.writeCentroidToBuffer(St)}else w.showCentroid(ft)}w.borderDoneWithNeighborZ[pe]=xe.canonical.z,xe.borderDoneWithNeighborZ[ze]=w.canonical.z}(w.needsCentroidUpdate||!w.centroidVertexBuffer&&w.centroidVertexArray.length!==0)&&w.uploadCentroid(v)}const eI=[1,0,0],tI=[0,1,0],PT=[0,0,1];function Dv(v,d,g){const w=g.transform,A=g.shadowRenderer;if(!A)return!0;const I=v.toUnwrapped(),L=w.tileSize*A._cascades[g.currentShadowCascade].scale;let F=d;if(w.elevation){const le=w.elevation.getMinMaxForTile(v);le&&(F+=le.max)}const $=w.scaleZoom(L);F/=s.e2(w.center.lat,$);const H=[...A.shadowDirection];H[2]=-H[2];const Y=A.computeSimplifiedTileShadowVolume(I,F,L,H);if(!Y)return!1;const te=[eI,tI,PT,H,[H[0],0,H[2]],[0,H[1],H[2]]],ee=s.cl.fromInvProjectionMatrix(w.invProjMatrix,w.worldSize,$,w.projection.name!=="globe"),ie=A.getCurrentCascadeFrustum();return ee.intersectsPrecise(Y.vertices,Y.planes,te)===0||ie.intersectsPrecise(Y.vertices,Y.planes,te)===0}function Xx(v){const{painter:d,source:g,layer:w,coords:A}=v;let I=v.defines;const L=d.context,F=d.renderPass==="shadow",$=d.renderPass==="light-beam",H=d.shadowRenderer,Y=s.e2(d.transform.center.lat,d.transform.zoom),te=Pa(d,w.paint.get("building-cutoff-fade-range"));te.shouldRenderCutoff&&(I=I.concat("RENDER_CUTOFF"));const ee=w.paint.get("building-front-cutoff"),ie=ee[2]<1&&!d.terrain,le=Lv(d.transform.pitch,ee,!!d.terrain);ie&&(I=I.concat("RENDER_FRONT_CUTOFF"),d.maxFrontCutoffRawStart=Math.max(d.maxFrontCutoffRawStart,ee[0])),v.floodLightIntensity>0&&(I=I.concat("FLOOD_LIGHT"));for(const oe of A){const me=g.getTile(oe),pe=me.getBucket(w);if(!pe)continue;H&&H.getMaxCascadeForTile(oe.toUnwrapped())===0&&(I=I.concat("SHADOWS_SINGLE_CASCADE"));const je=pe.programConfigurations.get(w.id);let Re,xe,Ze,ze=d.translatePosMatrix(oe.expandedProjMatrix,me,[0,0],"map");if(ze=s.cC(s.bb(),ze,[1,1,v.verticalScale]),F&&H){if(Dv(me.tileID,pe.maxHeight*Y,d))continue;let De=H.calculateShadowPassMatrixFromTile(me.tileID.toUnwrapped());De=s.cC(s.bb(),De,[1,1,v.verticalScale]),Ze=Av(De),Re=xe=d.getOrCreateProgram("buildingDepth",{config:je,defines:I,overrideFog:!1})}else if($)Re=xe=d.getOrCreateProgram("buildingBloom",{config:je,defines:I,overrideFog:!1}),Ze=Ev(ze);else{const De=d.transform.calculatePosMatrix(oe.toUnwrapped(),d.transform.worldSize);s.cC(De,De,[1,1,v.verticalScale]);const Fe=s.bb();s.cC(Fe,De,[1,-1,1/Y]),s.b7(Fe,Fe),s.e6(Fe,Fe);const qe=d.transform.getFreeCameraOptions().position,st=1<{if($){const qe=De.entranceBloom;Fe.draw(d,L.gl.TRIANGLES,v.depthMode,Qr.disabled,v.blendMode,Gr.disabled,Ze,w.id,qe.layoutVertexBuffer,qe.indexBuffer,qe.segmentsBucket,w.paint,d.transform.zoom,je,[qe.layoutAttenuationBuffer,qe.layoutColorBuffer])}else{const qe=De.segmentsBucket;let st=[De.layoutNormalBuffer,De.layoutCentroidBuffer,De.layoutColorBuffer,De.layoutFloodLightDataBuffer];De.layoutFacadePaintBuffer&&(st=st.concat([De.layoutFacadeDataBuffer,De.layoutFacadeVerticalRangeBuffer,De.layoutFacadePaintBuffer])),Fe.draw(d,L.gl.TRIANGLES,v.depthMode,Qr.disabled,v.blendMode,F?Gr.disabled:Gr.backCW,Ze,w.id,De.layoutVertexBuffer,De.indexBuffer,qe,w.paint,d.transform.zoom,je,st)}};d.uploadCommonUniforms(L,xe,oe.toUnwrapped(),null,te),pe.buildingWithoutFacade&&Ke(pe.buildingWithoutFacade,xe),pe.buildingWithFacade&&(Re!==xe&&d.uploadCommonUniforms(L,Re,oe.toUnwrapped(),null,te),Ke(pe.buildingWithFacade,Re))}}function NT(v,d,g,w,A,I,L,F,$,H,Y,te,ee,ie){const le=v.context.gl,oe=v.depthModeForSublayer(1,Ir.ReadOnly,le.LEQUAL,!0),me=.1*(1-(pe=Y))+3*pe;var pe;const je=v._showOverdrawInspector,Re=te,xe=new IT;je||_d(xe,v,d,g,w,oe,new Qr({func:le.ALWAYS,mask:255},255,255,le.KEEP,le.KEEP,le.REPLACE),new Kr([le.ONE,le.ONE,le.ONE,le.ONE],s.aq.transparent,[!1,!1,!1,!0],le.MIN),Gr.disabled,A,"sdf",I,L,F,$,H,me,Re,!1,void 0);{const Ze=je?Qr.disabled:new Qr({func:le.EQUAL,mask:255},255,255,le.KEEP,le.DECR,le.DECR),ze=je?v.colorModeForRenderPass():new Kr([le.ONE_MINUS_DST_ALPHA,le.DST_ALPHA,le.ONE,le.ONE],s.aq.transparent,[!0,!0,!0,!0]);_d(xe,v,d,g,w,oe,Ze,ze,Gr.disabled,A,"color",I,L,F,$,H,me,Re,!1,void 0)}}function RT(v){return[v[0]*s.e7,v[1]*s.e7,v[2]*s.e7,0]}function Ov(v,d,g,w,A,I,L,F,$){const H=w.getSource(),Y=g.globeSharedBuffers;if(!Y)return;let te,ee,ie;if(d&&(te=w.getTile(d)),H instanceof s.aV?(ee=H.texture,ie=s.dw(0,0,g.transform)):te&&d&&(ee=te.texture,ie=s.dw(d.canonical.z,d.canonical.x,g.transform)),!ee||!ie)return;v||(ie=s.cC(s.bb(),ie,[1,-1,1]));const le=g.context,oe=le.gl,me=A.paint.get("raster-resampling")==="nearest"?oe.NEAREST:oe.LINEAR,pe=g.colorModeForDrapableLayerRenderPass(I),je=L.defines;je.push("GLOBE_POLES");const Re=new Ir(oe.LEQUAL,Ir.ReadWrite,g.depthRangeFor3D),xe=Float32Array.from(g.transform.expandedFarZProjMatrix),Ze=Float32Array.from(s.du(s.dv(new s.cn(0,0,0))));g.terrain&&g.terrain.prepareDrawTile(),le.activeTexture.set(oe.TEXTURE0),ee.bind(me,oe.CLAMP_TO_EDGE),le.activeTexture.set(oe.TEXTURE1),ee.bind(me,oe.CLAMP_TO_EDGE),"useMipmap"in ee&&le.extTextureFilterAnisotropic&&g.transform.pitch>20&&oe.texParameterf(oe.TEXTURE_2D,le.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,le.extTextureFilterAnisotropicMax);const[ze,Ke,De,Fe]=d?Y.getPoleBuffers(d.canonical.z,!1):Y.getPoleBuffers(0,!0),qe=A.paint.get("raster-elevation");let st;v?(st=ze,g.renderDefaultNorthPole=qe!==0):(st=Ke,g.renderDefaultSouthPole=qe!==0);const Qe=RT(L.mix),xt=((Rt,Ft,ot,et,gt,vt,St,rr,Gt,Ht,Dt,Ar,Lr,gr)=>Wj(Rt,Ft,ot,et,new Float32Array(16),new Float32Array(9),[0,0],gt,[0,0],[0,0,0,0],1,{opacity:1,mix:0},St,[0,0],Gt,2,Dt,Ar,Lr,1,0,gr))(g,xe,Ze,ie,s.al(g.transform.zoom),0,A,0,qe,0,Qe,L.offset,L.range,I),ft=g.getOrCreateProgram("raster",{defines:je});g.uploadCommonUniforms(le,ft,null),ft.draw(g,oe.TRIANGLES,Re,$,pe,F,xt,A.id,st,De,Fe)}function LT(v){if(v.isOrthographic)return[0,0,0,0];const d=v._nearZ,g=v.projection.farthestPixelDistance(v),w=g-d,A=.2*v.height,I=d+A;return[d,g,(I-A-d)/w,(I-d)/w]}function rI(v,d,g,w){if(v)return d instanceof yp&&v instanceof xp?d.getTextureDescriptor(v,g,!0):{texture:v.texture,mix:RT(w.mix),offset:w.offset,buffer:0,tileSize:1}}var DT=s.e8([{name:"a_index",type:"Int16",components:1}]);class nI{constructor(d,g,w,A){const I={width:w[0],height:w[1],data:null},L=d.gl;this.targetColorTexture=new s.T(d,I,L.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new s.T(d,I,L.RGBA8,{useMipmap:!1}),this.context=d,this.updateParticleTexture(g,A),this.lastInvalidatedAt=0}updateParticleTexture(d,g){if(this.particleTextureDimension===g.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,A=g.width*g.height;this.particleTexture0=new s.T(this.context,g,w.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new s.T(this.context,g,w.RGBA8,{premultiply:!1,useMipmap:!1});const I=new s.e9;I.reserve(A);for(let L=0;L0){const Qe=s.ec(g.canonical,$),xt=s.ed(Qe);ee=s.aD(new Float32Array(16),$.globeMatrix,xt),s.aD(ee,$.projMatrix,ee)}const ie=s.bb();ie[12]+=2*A/(s.o.devicePixelRatio*$.width),ie[13]+=2*I/(s.o.devicePixelRatio*$.height),s.aD(ee,ie,ee);const le=v.getOrCreateProgram("debug",{defines:te}),oe=d.getTileByID(g.key);v.terrain&&v.terrain.setupElevationDraw(oe,le);const me=Ir.disabled,pe=Qr.disabled,je=v.colorModeForRenderPass(),Re="$debug";F.activeTexture.set(H.TEXTURE0),v.emptyTexture.bind(H.LINEAR,H.CLAMP_TO_EDGE),Y?oe._makeGlobeTileDebugBuffers(v.context,$):oe._makeDebugTileBoundsBuffers(v.context,$.projection);const xe=oe._tileDebugBuffer||v.debugBuffer,Ze=oe._tileDebugIndexBuffer||v.debugIndexBuffer,ze=oe._tileDebugSegments||v.debugSegments;if(le.draw(v,H.LINE_STRIP,me,pe,je,Gr.disabled,Gx(ee,w.toPremultipliedRenderColor(null)),Re,xe,Ze,ze,null,null,null,[oe._globeTileDebugBorderBuffer]),L){const Qe=oe.latestRawTileData,xt=Math.floor((Qe&&Qe.byteLength||0)/1024);let ft=g.canonical.toString();g.overscaledZ!==g.canonical.z&&(ft+=` => ${g.overscaledZ}`),ft+=` ${oe.state}`,ft+=` ${xt}kb`,function(Rt,Ft){Rt.initDebugOverlayCanvas();const ot=Rt.debugOverlayCanvas,et=Rt.context.gl,gt=Rt.debugOverlayCanvas.getContext("2d");gt.clearRect(0,0,ot.width,ot.height),gt.shadowColor="white",gt.shadowBlur=2,gt.lineWidth=1.5,gt.strokeStyle="white",gt.textBaseline="top",gt.font="bold 36px Open Sans, sans-serif",gt.fillText(Ft,5,5),gt.strokeText(Ft,5,5),Rt.debugOverlayTexture.update(ot),Rt.debugOverlayTexture.bind(et.LINEAR,et.CLAMP_TO_EDGE)}(v,ft)}const Ke=d.getTile(g).tileSize,De=512/Math.min(Ke,512)*(g.overscaledZ/$.zoom)*.5,Fe=oe._tileDebugTextBuffer||v.debugBuffer,qe=oe._tileDebugTextIndexBuffer||v.quadTriangleIndexBuffer,st=oe._tileDebugTextSegments||v.debugSegments;le.draw(v,H.TRIANGLES,me,pe,Kr.alphaBlended,Gr.disabled,Gx(ee,s.aq.transparent.toPremultipliedRenderColor(null),De),Re,Fe,qe,st,null,null,null,[oe._globeTileDebugTextBuffer])}function sI(v,d,g,w){Mv(v,0,d+g/2,v.transform.width,g,w)}function zT(v,d,g,w){Mv(v,d-g/2,0,g,v.transform.height,w)}function Mv(v,d,g,w,A,I){const L=v.context,F=L.gl;F.enable(F.SCISSOR_TEST),F.scissor(d*s.o.devicePixelRatio,g*s.o.devicePixelRatio,w*s.o.devicePixelRatio,A*s.o.devicePixelRatio),L.clear({color:I}),F.disable(F.SCISSOR_TEST)}const M3=s.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:nc}=M3;function vd(v,d,g,w){v.emplaceBack(d,g,w)}class Yo{constructor(d){this.vertexArray=new s.ee,this.indices=new s.dC,vd(this.vertexArray,-1,-1,1),vd(this.vertexArray,1,-1,1),vd(this.vertexArray,-1,1,1),vd(this.vertexArray,1,1,1),vd(this.vertexArray,-1,-1,-1),vd(this.vertexArray,1,-1,-1),vd(this.vertexArray,-1,1,-1),vd(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=d.createVertexBuffer(this.vertexArray,nc),this.indexBuffer=d.createIndexBuffer(this.indices),this.segment=s.dy.simpleSegment(0,0,36,12)}}function Sc(v,d,g,w,A,I){const L=v.context.gl,F=d.paint.get("sky-atmosphere-color"),$=d.paint.get("sky-atmosphere-halo-color"),H=d.paint.get("sky-atmosphere-sun-intensity"),Y=((te,ee,ie,le,oe)=>({u_matrix_3f:te,u_sun_direction:ee,u_sun_intensity:ie,u_color_tint_r:[le.r,le.g,le.b,le.a],u_color_tint_m:[oe.r,oe.g,oe.b,oe.a],u_luminance:5e-5}))(s.eg(s.dE(),w),A,H,F.toPremultipliedRenderColor(null),$.toPremultipliedRenderColor(null));L.framebufferTexture2D(L.FRAMEBUFFER,L.COLOR_ATTACHMENT0,L.TEXTURE_CUBE_MAP_POSITIVE_X+I,d.skyboxTexture,0),g.draw(v,L.TRIANGLES,Ir.disabled,Qr.disabled,Kr.unblended,Gr.frontCW,Y,"skyboxCapture",d.skyboxGeometry.vertexBuffer,d.skyboxGeometry.indexBuffer,d.skyboxGeometry.segment)}const aI=s.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class $T{constructor(d){const g=new s.eh;g.emplaceBack(-1,1,1,0,0),g.emplaceBack(1,1,1,1,0),g.emplaceBack(1,-1,1,1,1),g.emplaceBack(-1,-1,1,0,1);const w=new s.dC;w.emplaceBack(0,1,2),w.emplaceBack(2,3,0),this.vertexBuffer=d.createVertexBuffer(g,aI.members),this.indexBuffer=d.createIndexBuffer(w),this.segments=s.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const UT=s.e8([{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 VT{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class oI{constructor(d){this.colorModeAlphaBlendedWriteRGB=new Kr([1,js,1,js],s.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new Kr([1,0,1,0],s.aq.transparent,[!1,!1,!1,!0]),this.params=new VT,this.updateNeeded=!0}update(d){const g=d.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new $T(g);const w=this.params.sizeRange,A=this.params.intensityRange,I=function(Y){const te=s.em(30),ee=[];for(let ie=0;ie{const De=I.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Ke&&De.push("ALPHA_PASS");const Fe=d.getOrCreateProgram("globeAtmosphere",{defines:De}),qe=((Qe,xt,ft,Rt,Ft,ot,et,gt,vt,St,rr,Gt)=>({u_frustum_tl:Qe,u_frustum_tr:xt,u_frustum_br:ft,u_frustum_bl:Rt,u_horizon:Ft,u_transition:ot,u_fadeout_range:et,u_atmosphere_fog_color:gt.toArray01(),u_high_color:vt.toArray01(),u_space_color:St.toArray01(),u_temporal_offset:rr,u_horizon_angle:Gt}))(I.frustumCorners.TL,I.frustumCorners.TR,I.frustumCorners.BR,I.frustumCorners.BL,I.frustumCorners.horizon,F,me,Y,ee,le,je,Ze);d.uploadCommonUniforms(w,Fe);const st=this.atmosphereBuffer;st&&Fe.draw(d,A.TRIANGLES,L,Qr.disabled,Ke?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,Gr.backCW,qe,Ke?"atmosphere_glow_alpha":"atmosphere_glow",st.vertexBuffer,st.indexBuffer,st.segments)};ze(!1),ze(!0)}drawStars(d,g){const w=s.aC(g.properties.get("star-intensity"),0,1);if(w===0)return;const A=d.context,I=A.gl,L=d.transform,F=d.getOrCreateProgram("stars"),$=s.bL([]);s.bN($,$,-L._pitch),s.bM($,$,-L.angle),s.bN($,$,s.ap(L._center.lat)),s.ek($,$,-s.ap(L._center.lng));const H=s.bR(new Float32Array(16),$),Y=s.aD([],L.starsProjMatrix,H),te=s.eg([],H),ee=s.el([],te),ie=[0,1,0];s.dG(ie,ie,ee),s.bJ(ie,ie,this.params.sizeMultiplier);const le=[1,0,0];s.dG(le,le,ee),s.bJ(le,le,this.params.sizeMultiplier);const oe=(me=ie,pe=le,je=w,{u_matrix:Float32Array.from(Y),u_up:me,u_right:pe,u_intensity_multiplier:je});var me,pe,je;d.uploadCommonUniforms(A,F),this.starsVx&&this.starsIdx&&F.draw(d,I.TRIANGLES,Ir.disabled,Qr.disabled,this.colorModeAlphaBlendedWriteRGB,Gr.disabled,oe,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class hh{constructor(){this.visibleTiles=[]}updateBorders(d,g){const w=[],A=[],I=d._getRenderableCoordinates(!1,!0);for(const $ of I){const H=d.getTile($);if(!H.hasData())continue;const Y=H.getBucket(g);Y&&(Y.isEmpty()||(w.push($.key),A.push({bucket:Y,tileID:$.canonical})))}let L=w.length!==this.visibleTiles.length;if(!L){w.sort();for(let $=0;$$.tileID.z-H.tileID.z||$.tileID.x-H.tileID.x||$.tileID.y-H.tileID.y);for(const $ of A){const H=new Array,Y=new Array,te=$.bucket;for(const ee of te.featuresOnBorder)F.has(ee.featureId)?Y.push(ee.footprintIndex):(F.add(ee.featureId),H.push(ee.footprintIndex));te.updateFootprintHiddenFlags(H,s.en,!1),te.updateFootprintHiddenFlags(Y,s.en,!0)}}}function lI(v,d){const g=[...v],w=d.cameraWorldSizeForFog/d.worldSize,A=s.b9([]);return s.cC(A,A,[w,w,1]),s.aD(g,A,g),s.aD(g,d.worldToFogMatrix,g),g}function ti(v,d,g,w,A){const I=g.material,L=w.context,{baseColorTexture:F,metallicRoughnessTexture:$}=I.pbrMetallicRoughness,{normalTexture:H,occlusionTexture:Y,emissionTexture:te}=I;function ee(le,oe,me){if(le&&(v.push(oe),L.activeTexture.set(L.gl.TEXTURE0+me),le.gfxTexture)){const{minFilter:pe,magFilter:je,wrapS:Re,wrapT:xe}=le.sampler;le.gfxTexture.bindExtraParam(pe,je,Re,xe)}}ee(F,"HAS_TEXTURE_u_baseColorTexture",5),ee($,"HAS_TEXTURE_u_metallicRoughnessTexture",6),ee(H,"HAS_TEXTURE_u_normalTexture",7),ee(Y,"HAS_TEXTURE_u_occlusionTexture",8),ee(te,"HAS_TEXTURE_u_emissionTexture",9),A&&(A.texture||(A.texture=new s.dR(w.context,A.image,[A.image.height,A.image.height,A.image.height],L.gl.RGBA8)),L.activeTexture.set(L.gl.TEXTURE0+10),A.texture&&A.texture.bind(L.gl.LINEAR,L.gl.CLAMP_TO_EDGE),v.push("APPLY_LUT_ON_GPU")),g.texcoordBuffer&&(v.push("HAS_ATTRIBUTE_a_uv_2f"),d.push(g.texcoordBuffer)),g.colorBuffer&&(v.push(g.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),d.push(g.colorBuffer)),g.normalBuffer&&(v.push("HAS_ATTRIBUTE_a_normal_3f"),d.push(g.normalBuffer)),g.pbrBuffer&&(v.push("HAS_ATTRIBUTE_a_pbr"),v.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),d.push(g.pbrBuffer)),I.alphaMode!=="OPAQUE"&&I.alphaMode!=="MASK"||v.push("UNPREMULT_TEXTURE_IN_SHADER"),I.defined||v.push("DIFFUSE_SHADED");const ie=w.shadowRenderer;ie&&(v.push("RENDER_SHADOWS"),ie.useNormalOffset&&v.push("NORMAL_OFFSET"))}function gg(v,d,g,w,A,I){const L=v.modelOpacity,F=d.context,$=new Ir(d.context.gl.LEQUAL,v.isLightMesh?Ir.ReadOnly:Ir.ReadWrite,d.depthRangeFor3D),H=d.transform,Y=v.mesh,te=Y.material,ee=te.pbrMetallicRoughness,ie=d.style.fog;let le;le=d.transform.projection.zAxisUnit==="pixels"?[...v.nodeModelMatrix]:s.aD([],w.zScaleMatrix,v.nodeModelMatrix),s.aD(le,w.negCameraPosMatrix,le);const oe=s.b7([],le);s.e6(oe,oe);const me=g.paint.get("model-color-use-theme").constantOr("default")==="none",pe=g.paint.get("model-emissive-strength").constantOr(0),je=jp(new Float32Array(v.worldViewProjection),new Float32Array(le),new Float32Array(oe),null,d,L,ee.baseColorFactor,te.emissiveFactor,ee.metallicFactor,ee.roughnessFactor,te,pe,g,void 0,void 0,v.materialOverride,v.modelColor),Re={defines:[]},xe=[],Ze=d.shadowRenderer;Ze&&(Ze.useNormalOffset=!1),ti(Re.defines,xe,Y,d,me?null:g.lut);let ze=null;if(ie){const Fe=lI(v.nodeModelMatrix,d.transform);if(ze=new Float32Array(Fe),H.projection.name!=="globe"){const qe=Y.aabb.min,st=Y.aabb.max,[Qe,xt]=ie.getOpacityForBounds(Fe,qe[0],qe[1],st[0],st[1]);Re.overrideFog=Qe>=Rn||xt>=Rn}}const Ke=Pa(d,g.paint.get("model-cutoff-fade-range"));Ke.shouldRenderCutoff&&Re.defines.push("RENDER_CUTOFF");const De=d.getOrCreateProgram("model",Re);d.uploadCommonUniforms(F,De,null,ze,Ke),d.renderPass!=="shadow"&&Ze&&Ze.setupShadowsFromMatrix(v.nodeModelMatrix,De),De.draw(d,F.gl.TRIANGLES,$,A,I,Y.material.doubleSided?Gr.disabled:Gr.backCCW,je,g.id,Y.vertexBuffer,Y.indexBuffer,Y.segments,g.paint,d.transform.zoom,void 0,xe)}function Fv(v,d){return v.style._importedAsBasemap?"basemap":d.scope}function Bv(v,d,g,w,A,I,L,F,$,H){const Y=v.transform,te=!!d.isGeometryBloom&&d.isGeometryBloom;if(te&&v.renderPass==="shadow")return;const ee=Y.projection.name==="globe"?s.ev(g,Y):[...g];s.aD(ee,ee,d.globalMatrix);const ie=s.aD([],w,ee);if(d.meshes)for(const le of d.meshes){const oe=F.get(le.material.name);if(oe&&oe.opacity<=0)continue;if(le.material.alphaMode!=="BLEND"){L.push({mesh:le,depth:0,modelIndex:A,worldViewProjection:ie,nodeModelMatrix:ee,isLightMesh:te,materialOverride:oe,modelOpacity:$,modelColor:H,node:d,modelMatrix:g});continue}const me=s.ah([],le.centroid,ie);!Y.isOrthographic&&me[2]<=0||I.push({mesh:le,depth:me[2],modelIndex:A,worldViewProjection:ie,nodeModelMatrix:ee,isLightMesh:te,materialOverride:oe,modelOpacity:$,modelColor:H,node:d,modelMatrix:g})}if(d.children)for(const le of d.children)Bv(v,le,g,w,A,I,L,F,$,H)}function yg(v,d,g,w){const A=g.shadowRenderer;if(!A)return;const I=A.getShadowPassDepthMode(),L=A.calculateShadowPassMatrixFromMatrix(d),F=kT(L);g.getOrCreateProgram("modelDepth").draw(g,g.context.gl.TRIANGLES,I,Qr.disabled,Kr.disabled,Gr.disabled,F,w.id,v.vertexBuffer,v.indexBuffer,v.segments,w.paint,g.transform.zoom,void 0,void 0)}function qT(v,d,g,w){const A=function(Y,te){if(te.footprintDebugMesh)return te.footprintDebugMesh;if(!te.footprint)return null;const ee=Y.context,ie=te.footprint.vertices,le=te.footprint.indices,oe=new s.dB;oe.reserve(ie.length);for(const qe of ie)oe.emplaceBack(qe.x,qe.y);const me=new s.dC;me.reserve(le.length);for(let qe=0;qe0){const ee=I.terrain,ie=ee.findDEMTileFor(F);ie&&ie.dem?$=s.ex.create(ee,F,ie):te=0}if(te===0&&(L.terrainElevationMin=0,L.terrainElevationMax=0),te===L.validForExaggeration&&(te===0||$&&$._demTile&&$._demTile.tileID===L.validForDEMTile.id&&$._dem._timestamp===L.validForDEMTile.timestamp))return!1;for(const ee in L.instancesPerModel){const ie=L.instancesPerModel[ee];for(let le=0;leH&&(H=ie.max)}const Y=s.aC(w.x,I,L)-w.x,te=s.aC(w.y,F,$)-w.y,ee=s.bU(H,d.center.lat)-w.z;return d._zoomFromMercatorZ(Math.sqrt(Y*Y+te*te+ee*ee))}function ts(v,d,g,w,A,I,L){const F=v.context,$=v.renderPass==="shadow",H=v.shadowRenderer,Y=$&&H?H.getShadowPassDepthMode():new Ir(F.gl.LEQUAL,Ir.ReadWrite,v.depthRangeFor3D),te=v.isTileAffectedByFog(I),ee=v.transform.projection.name==="globe";if(g.meshes)for(const ie of g.meshes){const le=ee?[]:["MODEL_POSITION_ON_GPU"],oe=[];let me,pe,je;const Re=!ee&&w.instancedDataArray.length>20;Re&&le.push("INSTANCED_ARRAYS");const xe=Pa(v,d.paint.get("model-cutoff-fade-range"));if(xe.shouldRenderCutoff&&le.push("RENDER_CUTOFF"),$&&H)me=v.getOrCreateProgram("modelDepth",{defines:le}),pe=kT(L.shadowTileMatrix,L.shadowTileMatrix,Float32Array.from(g.globalMatrix)),je=Kr.disabled;else{ti(le,oe,ie,v,d.paint.get("model-color-use-theme").constantOr("default")==="none"?null:d.lut),me=v.getOrCreateProgram("model",{defines:le,overrideFog:te});const ze=ie.material,Ke=ze.pbrMetallicRoughness,De=d.paint.get("model-opacity").constantOr(1),Fe=d.paint.get("model-emissive-strength").constantOr(0);pe=jp(I.expandedProjMatrix,Float32Array.from(g.globalMatrix),new Float32Array(16),null,v,De,Ke.baseColorFactor,ze.emissiveFactor,Ke.metallicFactor,Ke.roughnessFactor,ze,Fe,d,A),H&&(L.shadowUniformsInitialized?me.setShadowUniformValues(F,H.getShadowUniformValues()):(H.setupShadows(I.toUnwrapped(),me,"model-tile"),L.shadowUniformsInitialized=!0)),je=xe.shouldRenderCutoff||De<1||ze.alphaMode!=="OPAQUE"?Kr.alphaBlended:Kr.unblended}v.uploadCommonUniforms(F,me,I.toUnwrapped(),null,xe);const Ze=ie.material.doubleSided?Gr.disabled:Gr.backCCW;if(Re)oe.push(w.instancedDataBuffer),me.draw(v,F.gl.TRIANGLES,Y,Qr.disabled,je,Ze,pe,d.id,ie.vertexBuffer,ie.indexBuffer,ie.segments,d.paint,v.transform.zoom,void 0,oe,w.instancedDataArray.length);else{const ze=$?"u_instance":"u_normal_matrix";for(let Ke=0;Ke$[1]?L:$,I[0]=g.max[0],L=s.aE(s.bE(),I,A),F=L[1]$[1]?L:$,I[1]=g.min[1],L=s.aE(s.bE(),I,A),F=L[1]$[1]?L:$;const H=s.aC(w[0],0,1),Y=100*d.pixelsPerMeter*s.aC(w[1],0,1),te=s.aC(w[2],0,1),ee=s.ey(s.bE(),F,$,H),ie=Math.tan(.5*d.fovX),le=-ee[2]*ie;if(Y===0)return ee[1]<-Math.abs(le)?te:1;const oe=(-Math.abs(le)-ee[1])/Y,me=(je,Re,xe)=>(1-xe)*je+xe*Re,pe=s.aC(me(1,te,oe),te,1);return me(1,pe,s.aC((d.pitch-20)/20,0,1))}class $v{}class uI{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(d,g,w){{const te=this._storage.get(g.id);if(te)return te.lastUsedFrameIdx=d,te.buf}const A=w.gl,I=A.getBufferParameter(A.ELEMENT_ARRAY_BUFFER,A.BUFFER_SIZE),L=new ArrayBuffer(I),F=new Int16Array(L);A.getBufferSubData(A.ELEMENT_ARRAY_BUFFER,0,new Int16Array(L));const $=new s.eA;for(let te=0;te30&&(w.buf.destroy(),this._storage.delete(g))}destroy(){for(const[d,g]of this._storage)g.buf.destroy(),this._storage.delete(d)}}class dI{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const _g=s.e8([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]);class hI{constructor(d){this.revealStart=11,this.revealRange=2}}const F3=s.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class fI{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(d,g){const w=d.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const L=new s.eB,F=new s.dC;L.emplaceBack(-1,-1),L.emplaceBack(1,-1),L.emplaceBack(1,1),L.emplaceBack(-1,1),F.emplaceBack(0,1,2),F.emplaceBack(0,2,3),this.vignetteVx=d.context.createVertexBuffer(L,F3.members),this.vignetteIdx=d.context.createIndexBuffer(F)}const A=s.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){d.uploadCommonUniforms(d.context,w);const L={u_vignetteShape:(I={vignetteShape:[g.start,g.range,Math.pow(10,g.fadePower)],vignetteColor:[g.color.r,g.color.g,g.color.b,g.color.a*g.strength]}).vignetteShape,u_vignetteColor:I.vignetteColor};w.draw(d,d.context.gl.TRIANGLES,Ir.disabled,Qr.disabled,Kr.alphaBlended,Gr.disabled,L,"vignette",this.vignetteVx,this.vignetteIdx,A)}var I}}class Uv{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(d,g){const w=d.getFreeCameraOptions().position,A=w.toAltitude(),I=w.toLngLat(),L=s.ap(I.lng),F=s.ap(I.lat),$=d.pixelsPerMeter/g,H=L*s.eD,Y=s.eD*Math.log(Math.tan(Math.PI/4+F/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,ee=-this._elevationPrev+A;this._accumulatedOffsetX+=(-this._offsetXPrev+H)*$,this._accumulatedOffsetY+=te*$,this._accumulatedElevation+=ee*$,this._offsetXPrev=H,this._offsetYPrev=Y,this._elevationPrev=A}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Vv(v,d){return[-(v[0]-Math.floor(v[0]/d)*d),-(v[1]-Math.floor(v[1]/d)*d),-(v[2]-Math.floor(v[2]/d)*d)]}function WT(v){const d=s.em(1323123451230),g=[];for(let w=0;w Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(d){const g=d.context;if(!this.particlesVx){const w=WT(this.particlesCount),A=new s.eE,I=new s.dC;let L=0;const F=s.em(1323123451230);for(let $=0;$w)return;const A=ph(0,1,g.revealStart,g.revealStart+g.revealRange,w);if(!this.particlesVx||!this.particlesIdx)return;const I=structuredClone(this._params);let L=[-I.direction.x,I.direction.y,-100];s.ay(L,L);const F=structuredClone(this._vignetteParams);F.strength*=A,I.overrideStyleParameters||(I.intensity=d.style.rain.state.density,I.timeFactor=d.style.rain.state.intensity,I.color=structuredClone(d.style.rain.state.color),L=structuredClone(d.style.rain.state.direction),I.screenThinning.intensity=d.style.rain.state.centerThinning,I.dropletSizeX=d.style.rain.state.dropletSize[0],I.dropletSizeYScale=d.style.rain.state.dropletSize[1]/d.style.rain.state.dropletSize[0],I.distortionStrength=100*d.style.rain.state.distortionStrength,F.strength=1,F.color=structuredClone(d.style.rain.state.vignetteColor));const $=this.updateOnRender(d,I.timeFactor),H=d.context,Y=H.gl,te=d.transform;this.screenTexture&&this.screenTexture.size[0]===d.width&&this.screenTexture.size[1]===d.height||(this.screenTexture=new s.T(H,{width:d.width,height:d.height,data:null},Y.RGBA8)),I.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,d.width,d.height));const ee=d.getOrCreateProgram("rainParticle");d.uploadCommonUniforms(H,ee),H.activeTexture.set(Y.TEXTURE0),this.screenTexture.bind(Y.LINEAR,Y.CLAMP_TO_EDGE);const ie=[I.color.r,I.color.g,I.color.b,I.color.a],le=(oe,me)=>{const pe=Vv(this._movement.getPosition(),oe),je=I.dropletSizeX,Re=I.dropletSizeX*I.dropletSizeYScale,xe=d.width/2,Ze=d.height/2,ze=ph(0,I.screenThinning.start,0,1,I.screenThinning.intensity),Ke=ph(.001,I.screenThinning.range,0,1,I.screenThinning.intensity),De=ph(0,I.screenThinning.particleOffset,0,1,I.screenThinning.intensity),Fe=(qe={modelview:$.modelviewMatrix,projection:$.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:pe,velocityConeAperture:I.velocityConeAperture,velocity:I.velocity,boxSize:oe,rainDropletSize:[je,Re],distortionStrength:I.distortionStrength,rainDirection:L,color:ie,screenSize:[te.width,te.height],thinningCenterPos:[xe,Ze],thinningShape:[ze,Ke,Math.pow(10,I.screenThinning.fadePower)],thinningAffectedRatio:I.screenThinning.affectedRatio,thinningParticleOffset:De,shapeDirectionalPower:I.shapeDirPower,shapeNormalPower:I.shapeNormalPower,mode:me?0:1},{u_modelview:Float32Array.from(qe.modelview),u_projection:Float32Array.from(qe.projection),u_time:qe.time,u_cam_pos:qe.camPos,u_texScreen:0,u_velocityConeAperture:qe.velocityConeAperture,u_velocity:qe.velocity,u_boxSize:qe.boxSize,u_rainDropletSize:qe.rainDropletSize,u_distortionStrength:qe.distortionStrength,u_rainDirection:qe.rainDirection,u_color:qe.color,u_screenSize:qe.screenSize,u_thinningCenterPos:qe.thinningCenterPos,u_thinningShape:qe.thinningShape,u_thinningAffectedRatio:qe.thinningAffectedRatio,u_thinningParticleOffset:qe.thinningParticleOffset,u_shapeDirectionalPower:qe.shapeDirectionalPower,u_shapeNormalPower:qe.shapeNormalPower,u_mode:qe.mode});var qe;const st=Math.round(I.intensity*this.particlesCount),Qe=s.dy.simpleSegment(0,0,4*st,2*st);ee.draw(d,Y.TRIANGLES,Ir.disabled,Qr.disabled,Kr.alphaBlended,Gr.disabled,Fe,"rain_particles",this.particlesVx,this.particlesIdx,Qe)};I.distortionStrength>0&&le(I.boxSize,!0),le(I.boxSize,!1),this._vignette.draw(d,F)}}const Lp=s.e8([{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}]);class pI extends Qx{constructor(d){super(2.25),this._params={overrideStyleParameters:!1,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._revealParams=new hI("Precipitation > Snow"),this._vignetteParams={strength:.3,start:.78,range:.46,fadePower:.2,color:{r:1,g:1,b:1,a:1}},this.particlesCount=16e3}update(d){const g=d.context;if(!this.particlesVx){const w=WT(this.particlesCount),A=new s.eF,I=new s.dC;let L=0;const F=s.em(1323123451230);for(let $=0;$L)return;const F=ph(0,1,I.revealStart,I.revealStart+I.revealRange,L);A.strength*=F,g.overrideStyleParameters||(g.intensity=d.style.snow.state.density,g.timeFactor=d.style.snow.state.intensity,g.color=structuredClone(d.style.snow.state.color),w=structuredClone(d.style.snow.state.direction),g.screenThinning.intensity=d.style.snow.state.centerThinning,g.billboardSize=2.79*d.style.snow.state.flakeSize,A.strength=1,A.color=structuredClone(d.style.snow.state.vignetteColor));const $=this.updateOnRender(d,g.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const H=d.context,Y=H.gl,te=d.transform,ee=d.getOrCreateProgram("snowParticle");d.uploadCommonUniforms(H,ee),((ie,le,oe)=>{const me=Vv(this._movement.getPosition(),ie),pe=te.width/2,je=te.height/2,Re=ph(0,oe.screenThinning.start,0,1,oe.screenThinning.intensity),xe=ph(.001,oe.screenThinning.range,0,1,oe.screenThinning.intensity),Ze=ph(0,oe.screenThinning.particleOffset,0,1,oe.screenThinning.intensity),ze=(Ke={modelview:$.modelviewMatrix,projection:$.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:me,velocityConeAperture:oe.velocityConeAperture,velocity:oe.velocity,horizontalOscillationRadius:oe.horizontalOscillationRadius,horizontalOscillationRate:oe.horizontalOscillationRate,boxSize:ie,billboardSize:1*oe.billboardSize,simpleShapeParameters:[oe.shapeFadeStart,oe.shapeFadePower],screenSize:[te.width,te.height],thinningCenterPos:[pe,je],thinningShape:[Re,xe,Math.pow(10,oe.screenThinning.fadePower)],thinningAffectedRatio:oe.screenThinning.affectedRatio,thinningParticleOffset:Ze,color:[oe.color.r,oe.color.g,oe.color.b,oe.color.a],direction:w},{u_modelview:Float32Array.from(Ke.modelview),u_projection:Float32Array.from(Ke.projection),u_time:Ke.time,u_cam_pos:Ke.camPos,u_velocityConeAperture:Ke.velocityConeAperture,u_velocity:Ke.velocity,u_horizontalOscillationRadius:Ke.horizontalOscillationRadius,u_horizontalOscillationRate:Ke.horizontalOscillationRate,u_boxSize:Ke.boxSize,u_billboardSize:Ke.billboardSize,u_simpleShapeParameters:Ke.simpleShapeParameters,u_screenSize:Ke.screenSize,u_thinningCenterPos:Ke.thinningCenterPos,u_thinningShape:Ke.thinningShape,u_thinningAffectedRatio:Ke.thinningAffectedRatio,u_thinningParticleOffset:Ke.thinningParticleOffset,u_particleColor:Ke.color,u_direction:Ke.direction});var Ke;const De=Math.round(oe.intensity*this.particlesCount),Fe=s.dy.simpleSegment(0,0,4*De,2*De);this.particlesVx&&this.particlesIdx&&ee.draw(d,Y.TRIANGLES,Ir.disabled,Qr.disabled,Kr.alphaBlended,Gr.disabled,ze,"snow_particles",this.particlesVx,this.particlesIdx,Fe)})(g.boxSize,0,g),this._vignette.draw(d,A)}}const mI={symbol:function(v,d,g,w,A){if(v.renderPass!=="translucent")return;const I=Qr.disabled,L=v.colorModeForRenderPass(),F=g.layout.get("text-variable-anchor"),$=g.layout.get("text-size-scale-range"),H=s.aC(v.scaleFactor,$[0],$[1]);F&&function(ee,ie,le,oe,me,pe,je,Re){const xe=ie.transform,Ze=me==="map",ze=pe==="map";for(const Ke of ee){const De=oe.getTile(Ke),Fe=De.getBucket(le);if(!Fe||!Fe.text||!Fe.text.segments.get().length)continue;const qe=s.bj(Fe.textSizeData,xe.zoom,Re),st=_p(Ke,Fe.getProjection(),xe),Qe=xe.calculatePixelsToTileUnitsMatrix(De),xt=af(st,De.tileID.canonical,ze,Ze,xe,Fe.getProjection(),Qe),ft=Fe.hasIconTextFit()&&Fe.hasIconData();qe&&Qj(Fe,Ze,ze,je,xe,xt,Ke,Math.pow(2,xe.zoom-De.tileID.overscaledZ),qe,ft)}}(w,v,g,d,g.layout.get("text-rotation-alignment"),g.layout.get("text-pitch-alignment"),A,H);const Y=g.paint.get("icon-opacity").constantOr(1)!==0,te=g.paint.get("text-opacity").constantOr(1)!==0;g.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(Y||te)?Pv(v,d,g,w,I,L):(Y&&Pv(v,d,g,w,I,L,{onlyIcons:!0}),te&&Pv(v,d,g,w,I,L,{onlyText:!0})),d.map.showCollisionBoxes&&(vr(v,d,g,w,g.paint.get("text-translate"),g.paint.get("text-translate-anchor"),!0),vr(v,d,g,w,g.paint.get("icon-translate"),g.paint.get("icon-translate-anchor"),!1))},circle:function(v,d,g,w){if(v.renderPass!=="translucent")return;const A=g.paint.get("circle-opacity"),I=g.paint.get("circle-stroke-width"),L=g.paint.get("circle-stroke-opacity"),F=g.layout.get("circle-sort-key").constantOr(1)!==void 0,$=g.paint.get("circle-emissive-strength");if(A.constantOr(1)===0&&(I.constantOr(1)===0||L.constantOr(1)===0))return;const H=v.context,Y=H.gl,te=v.transform,ee=!(!v.terrain||!v.terrain.enabled),ie=g.layout.get("circle-elevation-reference"),le=v.depthModeForSublayer(0,Ir.ReadOnly),oe=new Ir(v.context.gl.LEQUAL,Ir.ReadOnly,v.depthRangeFor3D),me=ie==="none"||ee?le:oe,pe=Qr.disabled,je=v.colorModeForDrapableLayerRenderPass($),Re=te.projection.name==="globe",xe=[s.aH(te.center.lng),s.aL(te.center.lat)],Ze=[];for(let Ke=0;KeKe.sortKey-De.sortKey);const ze={useDepthForOcclusion:te.depthOcclusionForSymbolsAndCircles};for(const Ke of Ze){const{programConfiguration:De,program:Fe,layoutVertexBuffer:qe,dynamicBuffers:st,indexBuffer:Qe,uniformValues:xt,tile:ft}=Ke.state,Rt=Ke.segments;v.terrain&&v.terrain.setupElevationDraw(ft,Fe,ze),v.uploadCommonUniforms(H,Fe,ft.tileID.toUnwrapped()),Fe.draw(v,Y.TRIANGLES,me,pe,je,Gr.disabled,xt,g.id,qe,Qe,Rt,g.paint,te.zoom,De,st)}},heatmap:function(v,d,g,w){if(g.paint.get("heatmap-opacity")!==0)if(v.renderPass==="offscreen"){const A=v.context,I=A.gl,L=Qr.disabled,F=new Kr([I.ONE,I.ONE,I.ONE,I.ONE],s.aq.transparent,[!0,!0,!0,!0]),$=v.transform.projection.name==="globe"?.5:.25;g.heatmapFbo=Wx.createWithTexture(A,g.heatmapFbo,v.width*$,v.height*$),A.clear({color:s.aq.transparent});const H=v.transform,Y=H.projection.name==="globe",te=Y?["PROJECTION_GLOBE_VIEW"]:[],ee=Y?Gr.frontCCW:Gr.disabled,ie=[s.aH(H.center.lng),s.aL(H.center.lat)];for(let le=0;le({u_image:0,u_color_ramp:1,u_opacity:te.paint.get("heatmap-opacity")}))(0,I),I.id,A.viewportBuffer,A.quadTriangleIndexBuffer,A.viewportSegments,I.paint,A.transform.zoom)}(v,g))},line:function(v,d,g,w){const A=g.paint.get("line-opacity"),I=g.paint.get("line-width");if(A.constantOr(1)===0||I.constantOr(1)===0)return;const L=g.paint.get("line-blend-mode");if(L!=="default"&&v.transform.projection.name!=="globe")return v.terrain&&v.terrain.renderingToTexture?void function(F,$,H,Y,te){if(F.renderPass!=="translucent")return;const ee=F.context,ie=ee.gl,le=F.terrain;if(!le)return;const oe=ee.bindFramebuffer.current,me=F.emissiveMode==="mrt-fallback";H.lineBlendDrapeFbo=Wx.createWithTexture(ee,H.lineBlendDrapeFbo,le.drapeBufferSize[0],le.drapeBufferSize[1],!0),H.lineBlendDrapeStencil=H.lineBlendDrapeFbo._stencilRbo,me&&ie.drawBuffers([ie.COLOR_ATTACHMENT0]),ee.clear({color:dh[te].clearColor,depth:1,stencil:0});const pe=F.currentStencilSource,je=F._tileClippingMaskIDs,Re=F.nextStencilID;F.currentStencilSource=void 0,F._tileClippingMaskIDs={},F.nextStencilID=1;const xe=F._terrain;F._terrain=null,F._renderTileClippingMasks(H,$,Y),Rv(F,$,H,Y,dh[te].colorMode,!0),F._terrain=xe,F.currentStencilSource=pe,F._tileClippingMaskIDs=je,F.nextStencilID=Re,ee.bindFramebuffer.set(oe),me&&ie.drawBuffers([ie.COLOR_ATTACHMENT0,ie.COLOR_ATTACHMENT1]);const Ze=le.drapeBufferSize;ee.viewport.set([0,0,Ze[0],Ze[1]]);const ze=H.lineBlendDrapeFbo;if(!ze)return;ee.activeTexture.set(ie.TEXTURE0),ie.bindTexture(ie.TEXTURE_2D,ze.colorAttachment0.get());const Ke=te==="additive"?1:H.paint.get("line-opacity").constantOr(1),De=H.paint.get("line-emissive-strength").constantOr(0),Fe=te==="additive"?F.colorModeForDrapableLayerRenderPass(De):dh[te].colorMode;F.getOrCreateProgram("lineBlendComposite").draw(F,ie.TRIANGLES,Ir.disabled,Qr.disabled,Fe,Gr.disabled,Tv(0,Ke,dh[te].compositeUniformValue),H.id,F.viewportBuffer,F.quadTriangleIndexBuffer,F.viewportSegments,H.paint,F.transform.zoom)}(v,d,g,w,L):v.renderPass==="offscreen"?void function(F,$,H,Y,te){const ee=F.context,ie=Math.ceil(F.width),le=Math.ceil(F.height);H.lineBlendFbo=Wx.createWithTexture(ee,H.lineBlendFbo,ie,le,!0),H.lineBlendStencil=H.lineBlendFbo._stencilRbo,ee.clear({color:dh[te].clearColor,depth:1,stencil:0});const oe=F.currentStencilSource,me=F._tileClippingMaskIDs,pe=F.nextStencilID;F.currentStencilSource=void 0,F._tileClippingMaskIDs={},F.nextStencilID=1,F._renderTileClippingMasks(H,$,Y);const je=F.renderPass;F.renderPass="translucent",Rv(F,$,H,Y,dh[te].colorMode),F.renderPass=je,F.currentStencilSource=oe,F._tileClippingMaskIDs=me,F.nextStencilID=pe,ee.viewport.set([0,0,F.width,F.height])}(v,d,g,w,L):v.renderPass==="translucent"?void function(F,$,H){const Y=F.context,te=Y.gl,ee=$.lineBlendFbo;if(!ee)return;Y.activeTexture.set(te.TEXTURE0),te.bindTexture(te.TEXTURE_2D,ee.colorAttachment0.get());const ie=H==="additive"?1:$.paint.get("line-opacity").constantOr(1),le=H==="additive"?F.colorModeForDrapableLayerRenderPass($.paint.get("line-emissive-strength").constantOr(0)):dh[H].colorMode;F.getOrCreateProgram("lineBlendComposite").draw(F,te.TRIANGLES,Ir.disabled,Qr.disabled,le,Gr.disabled,Tv(0,ie,dh[H].compositeUniformValue),$.id,F.viewportBuffer,F.quadTriangleIndexBuffer,F.viewportSegments,$.paint,F.transform.zoom)}(v,g,L):void 0;v.renderPass==="translucent"&&Rv(v,d,g,w)},fill:function(v,d,g,w){const A=g.paint.get("fill-color"),I=g.paint.get("fill-opacity");if(I.constantOr(1)===0)return;const L=g.paint.get("fill-emissive-strength"),F=v.colorModeForDrapableLayerRenderPass(L),$=g.paint.get("fill-pattern"),H=v.opaquePassEnabledForLayer()&&!$.constantOr(1)&&A.constantOr(s.aq.transparent).a===1&&I.constantOr(0)===1?"opaque":"translucent";let Y="none";g.layout.get("fill-elevation-reference")!=="none"?Y="road":g.paint.get("fill-z-offset").constantOr(1)!==0&&(Y="offset");const te=!(!v.terrain||!v.terrain.enabled),ee={painter:v,sourceCache:d,layer:g,coords:w,colorMode:F,elevationType:Y,terrainEnabled:te,pass:H};if(v.renderPass==="shadow")return void(v.shadowRenderer&&Y==="road"&&!te&&function(le){const{painter:oe,sourceCache:me,layer:pe,coords:je}=le,Re=oe.context.gl,xe=le.painter.shadowRenderer;for(const Ze of je){const ze=me.getTile(Ze),Ke=ze.getBucket(pe);if(!Ke)continue;const De=Ke.elevatedStructures;if(!De||!De.shadowCasterSegments||De.shadowCasterSegments.segments[0].primitiveLength===0)continue;oe.prepareDrawTile();const Fe=Ke.bufferData.programConfigurations.get(pe.id),qe=oe.isTileAffectedByFog(Ze),st=oe.getOrCreateProgram("elevatedStructuresDepth",{config:Fe,overrideFog:qe}),Qe=xe.calculateShadowPassMatrixFromTile(ze.tileID.toUnwrapped());oe.uploadCommonUniforms(oe.context,st,Ze.toUnwrapped());const xt=Vj(Qe,0);st.draw(oe,Re.TRIANGLES,xe.getShadowPassDepthMode(),Qr.disabled,Kr.disabled,Gr.disabled,xt,pe.id,De.vertexBuffer,De.indexBuffer,De.shadowCasterSegments,pe.paint,oe.transform.zoom,Fe)}}(ee));const ie=v.emissiveMode==="mrt-fallback";if(Y!=="offset"){if(Zx(ee,!1,ie),Y==="road"){const le=!te&&v.renderPass==="translucent";le&&Yx(v,d,g,w,"geometry"),Zx(ee,!0,ie,Qr.disabled),le&&function(oe){const{painter:me,sourceCache:pe,layer:je,coords:Re,colorMode:xe}=oe,Ze=me.context.gl,ze=oe.painter.shadowRenderer,Ke=!!ze&&ze.enabled,De=new Ir(me.context.gl.LEQUAL,Ir.ReadOnly,me.depthRangeFor3D);let Fe=[0,0,0];if(Ke){const st=me.style.directionalLight,Qe=me.style.ambientLight;st&&Qe&&(Fe=Du(me.style,st,Qe))}const qe=st=>{for(const Qe of Re){const xt=pe.getTile(Qe),ft=xt.getBucket(je);if(!ft)continue;const Rt=ft.elevatedStructures;if(!Rt)continue;let Ft,ot;if(st?(Ft=Rt.renderableBridgeSegments,ot=Rt.bridgeProgramConfigurations.get(je.id)):(Ft=Rt.renderableTunnelSegments,ot=Rt.tunnelProgramConfigurations.get(je.id)),!Ft||Ft.segments[0].primitiveLength===0)continue;ot.updatePaintBuffers(),me.prepareDrawTile();const et=me.isTileAffectedByFog(Qe),gt=[];Ke&>.push("RENDER_SHADOWS","NORMAL_OFFSET");const vt=me.getOrCreateProgram("elevatedStructures",{config:ot,overrideFog:et,defines:gt}),St=me.translatePosMatrix(Qe.projMatrix,xt,je.paint.get("fill-translate"),je.paint.get("fill-translate-anchor"));Ke&&ze.setupShadows(xt.tileID.toUnwrapped(),vt,"vector-tile");const rr=qj(St,Fe);me.uploadCommonUniforms(me.context,vt,Qe.toUnwrapped()),vt.draw(me,Ze.TRIANGLES,De,Qr.disabled,xe,Gr.backCCW,rr,je.id,Rt.vertexBuffer,Rt.indexBuffer,Ft,je.paint,me.transform.zoom,ot,[Rt.vertexBufferNormal])}};qe(!0),qe(!1)}(ee)}}else Zx(ee,!1,ie,v.stencilModeFor3D())},"fill-extrusion":function(v,d,g,w){const A=g.paint.get("fill-extrusion-opacity"),I=v.context,L=I.gl,F=v.terrain,$=F&&F.renderingToTexture;if(A===0)return;const H=v.emissiveMode==="mrt-fallback",Y=v.conflationActive&&v.style.isLayerClipped(g,d.getSource()),te=v.style.order.indexOf(g.fqid);if(Y&&function(ee,ie,le,oe,me){for(const pe of oe){const je=ie.getTile(pe).getBucket(le);je&&(je.updateReplacement(pe,ee.replacementSource,me),je.uploadCentroid(ee.context))}}(v,d,g,w,te),F||Y)for(const ee of w){const ie=d.getTile(ee).getBucket(g);ie&&Jj(v.context,d,ee,ie,g,F,Y)}if(v.renderPass==="shadow"&&v.shadowRenderer){if(F&&A<.65&&g._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof s.af)return;const ee=v.shadowRenderer.getShadowPassDepthMode();Pp(v,d,g,w,ee,Qr.disabled,Kr.disabled,Y)}else if(v.renderPass==="translucent"){const ee=!g.paint.get("fill-extrusion-pattern").constantOr(1),ie=g.paint.get("fill-extrusion-color").constantOr(s.aq.white);if(!$&&ie.a!==0){const le=new Ir(v.context.gl.LEQUAL,Ir.ReadWrite,v.depthRangeFor3D);A===1&&ee?Pp(v,d,g,w,le,Qr.disabled,Kr.unblended,Y):(Pp(v,d,g,w,le,Qr.disabled,Kr.disabled,Y),Pp(v,d,g,w,le,v.stencilModeFor3D(),v.colorModeForRenderPass(),Y),v.resetStencilClippingMasks())}if(v.style.enable3dLights()&&ee&&(!F&&v.transform.projection.name!=="globe"||$)){const le=g.paint.get("fill-extrusion-opacity"),oe=g.paint.get("fill-extrusion-ambient-occlusion-intensity"),me=g.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),pe=g.paint.get("fill-extrusion-flood-light-intensity"),je=g.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Re=g.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(je?null:g.lut).toArray01().slice(0,3),xe=oe>0&&me>0,Ze=pe>0,ze=(Fe,qe,st)=>(1-st)*Fe+st*qe,Ke=new IT;Ke.translate=g.paint.get("fill-extrusion-translate"),Ke.translateAnchor=g.paint.get("fill-extrusion-translate-anchor"),Ke.edgeRadius=g.layout.get("fill-extrusion-edge-radius"),Ke.cutoffFadeRange=g.paint.get("fill-extrusion-cutoff-fade-range");const De=Fe=>{const qe=v.depthModeForSublayer(1,Ir.ReadOnly,L.LEQUAL,!0),st=g.paint.get(Fe?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Qe=ze(.1,3,st),xt=v._showOverdrawInspector;if(!xt){const ft=new Qr({func:L.ALWAYS,mask:255},255,255,L.KEEP,L.KEEP,L.REPLACE),Rt=new Kr([L.ONE,L.ONE,L.ONE,L.ONE],s.aq.transparent,[!1,!1,!1,!0],L.MIN);_d(Ke,v,d,g,w,qe,ft,Rt,Gr.disabled,Fe,"sdf",le,oe,me,pe,Re,Qe,Y,!1)}{const ft=xt?Qr.disabled:new Qr({func:L.EQUAL,mask:255},255,255,L.KEEP,L.DECR,L.DECR),Rt=xt?v.colorModeForRenderPass():new Kr([L.ONE_MINUS_DST_ALPHA,L.DST_ALPHA,L.ONE,L.ONE],s.aq.transparent,[!0,!0,!0,!0]);_d(Ke,v,d,g,w,qe,ft,Rt,Gr.disabled,Fe,"color",le,oe,me,pe,Re,Qe,Y,!1)}};if($){const Fe=()=>{const st=F.drapeBufferSize[0],Qe=F.drapeBufferSize[1];let xt=F.framebufferCopyTexture;return xt&&(!xt||xt.size[0]===st&&xt.size[1]===Qe)||(xt&&xt.destroy(),xt=F.framebufferCopyTexture=new s.T(I,new s.q({width:st,height:Qe}),L.RGBA8)),xt.bind(L.LINEAR,L.CLAMP_TO_EDGE),L.copyTexSubImage2D(L.TEXTURE_2D,0,0,0,0,0,st,Qe),xt},qe=(st,Qe,xt)=>{const ft=v.depthModeForSublayer(1,Ir.ReadOnly,L.LEQUAL,!1),Rt=g.paint.get(st?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Ft=ze(.1,3,Rt);{const ot=new Kr([L.ONE,L.ONE,L.ONE,L.ONE],s.aq.transparent,[!1,!1,!1,!0]);_d(Ke,v,d,g,w,ft,Qr.disabled,ot,Gr.disabled,st,"clear",le,oe,me,pe,Re,Ft,Y,Qe)}{const ot=new Qr({func:L.ALWAYS,mask:255},255,255,L.KEEP,L.KEEP,L.REPLACE),et=new Kr([L.ONE,L.ONE,L.ONE,L.ONE],s.aq.transparent,[!1,!1,!1,!0],L.MIN);_d(Ke,v,d,g,w,ft,ot,et,Gr.disabled,st,"sdf",le,oe,me,pe,Re,Ft,Y,Qe)}H&&!st&&(xt=Fe());{const ot=st?L.ZERO:L.ONE_MINUS_DST_ALPHA,et=new Qr({func:L.EQUAL,mask:255},255,255,L.KEEP,L.DECR,L.DECR),gt=new Kr([ot,L.DST_ALPHA,L.ONE_MINUS_DST_ALPHA,L.ZERO],s.aq.transparent,[!0,!0,!0,!0]);_d(Ke,v,d,g,w,ft,et,gt,Gr.disabled,st,"color",le,oe,me,pe,Re,Ft,Y,Qe)}if(!H||st){const ot=new Kr([L.ONE,L.ONE,L.ONE,st?L.ZERO:L.ONE],s.aq.transparent,[!1,!1,!1,!0],st?L.FUNC_ADD:L.MAX);_d(Ke,v,d,g,w,ft,Qr.disabled,ot,Gr.disabled,st,"clear",le,oe,me,pe,Re,Ft,Y,Qe,xt)}else{L.drawBuffers([L.NONE,L.COLOR_ATTACHMENT1]);const ot=new Qr({func:L.EQUAL,mask:255},254,255,L.KEEP,L.DECR,L.DECR),et=new Kr([L.ONE,L.ONE,L.ONE,L.ONE],s.aq.transparent,[!0,!1,!1,!1],L.MAX);_d(Ke,v,d,g,w,ft,ot,et,Gr.disabled,st,"emissive",le,oe,me,pe,Re,Ft,Y,Qe,xt),L.drawBuffers([L.COLOR_ATTACHMENT0])}};if(xe||Ze){let st;v.prepareDrawTile(),H&&!xe||(st=Fe()),xe&&qe(!0,!1,st),Ze&&qe(!1,!0,st)}}else xe&&De(!0),Ze&&De(!1),(xe||Ze)&&v.resetStencilClippingMasks()}}},building:function(v,d,g,w){v.currentLayer0&&I>0,H=!0;const Y=g.paint.get("building-vertical-scale");if(Y<=0)return;v.shadowRenderer||(H=!1);const te=v.conflationActive&&v.style.isLayerClipped(g,d.getSource()),ee=v.style.order.indexOf(g.fqid);if(function(ie,le,oe,me,pe,je){for(const Re of je){const xe=le.getTile(Re).getBucket(oe);xe&&(pe&&xe.updateReplacement(Re,ie.replacementSource,me),xe.uploadUpdatedIndexBuffer(ie.context))}}(v,d,g,ee,te,w),function(ie,le,oe,me){for(const pe of me){const je=le.getTile(pe).getBucket(oe);je&&je.needsEvaluation()&&je.uploadUpdatedColorBuffer(ie.context)}}(v,d,g,w),g.resetLayerRenderingStats(v),v.shadowRenderer&&(v.shadowRenderer.useNormalOffset=!0),v.renderPass==="shadow"&&v.shadowRenderer){const ie=[],le=v.shadowRenderer.getShadowPassDepthMode();Xx({painter:v,source:d,layer:g,coords:w,defines:ie,blendMode:Kr.disabled,depthMode:le,opacity:F,verticalScale:Y,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(v.renderPass==="translucent"){let ie=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];H&&(ie=ie.concat("RENDER_SHADOWS")),v.shadowRenderer&&v.shadowRenderer.useNormalOffset&&(ie=ie.concat("NORMAL_OFFSET"));const le=g.paint.get("building-facade-emissive-chance"),oe=g.paint.get("building-ambient-occlusion-intensity"),me=g.paint.get("building-flood-light-intensity"),pe=g.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",je=g.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(pe?null:g.lut).toArray01().slice(0,3),Re=g.paint.get("building-flood-light-ground-attenuation"),xe=me>0,Ze=new Ir(v.context.gl.LEQUAL,Ir.ReadWrite,v.depthRangeFor3D);F<1&&Xx({painter:v,source:d,layer:g,coords:w,defines:ie,blendMode:Kr.disabled,depthMode:Ze,opacity:F,verticalScale:Y,facadeEmissiveChance:le,facadeAOIntensity:oe,floodLightIntensity:me,floodLightColor:je,depthOnly:!0});const ze=v.colorModeForRenderPass();Xx({painter:v,source:d,layer:g,coords:w,defines:ie,blendMode:ze,depthMode:Ze,opacity:F,verticalScale:Y,facadeEmissiveChance:le,facadeAOIntensity:oe,floodLightIntensity:me,floodLightColor:je});const Ke=g.paint.get("building-front-cutoff");Lv(v.transform.pitch,Ke,!!v.terrain),$&&NT(v,d,g,w,!0,F,A,I,me,je,L,te),xe&&NT(v,d,g,w,!1,F,A,I,me,je,Re,te)}else if(v.renderPass==="light-beam"){const ie=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],le=new Ir(v.context.gl.LEQUAL,Ir.ReadOnly,v.depthRangeFor3D);Xx({painter:v,source:d,layer:g,coords:w,defines:ie,blendMode:Kr.alphaBlended,depthMode:le,opacity:F,verticalScale:Y,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}v.shadowRenderer&&(v.shadowRenderer.useNormalOffset=!1),v.resetStencilClippingMasks()},hillshade:function(v,d,g,w){if(v.renderPass!=="offscreen"&&v.renderPass!=="translucent"||v.style.disableElevatedTerrain)return;const A=v.context,I=v.terrain&&v.terrain.renderingToTexture,[L,F]=v.renderPass!=="translucent"||I?[{},w]:v.stencilConfigForOverlap(w);for(const $ of F){const H=d.getTile($);if(H.needsHillshadePrepare&&v.renderPass==="offscreen")w3(v,H,g);else if(v.renderPass==="translucent"){const Y=v.depthModeForSublayer(0,Ir.ReadOnly),te=g.paint.get("hillshade-emissive-strength"),ee=v.colorModeForDrapableLayerRenderPass(te),ie=I&&v.terrain?v.terrain.stencilModeForRTTOverlap($):L[$.overscaledZ];b3(v,$,H,g,Y,ie,ee)}}A.viewport.set([0,0,v.width,v.height]),v.resetStencilClippingMasks()},raster:function(v,d,g,w,A,I){if(v.renderPass!=="translucent")return;const L=g.paint.get("raster-opacity");if(L===0)return;const F=v.transform.projection.name==="globe",$=g.paint.get("raster-elevation")!==0,H=$&&F,Y=v.terrain&&v.terrain.exaggeration()>0&&$&&g.paint.get("raster-elevation-reference")==="ground",te=!F&&Y;if(v.renderElevatedRasterBackface&&!H)return;const ee=v.context,ie=ee.gl,le=d.getSource(),oe=function(Fe,qe,st,Qe,xt){const ft=qe.paint.get("raster-color"),Rt=Fe.type==="raster-array",Ft=[],ot=qe.paint.get("raster-resampling"),et=qe.paint.get("raster-color-mix");let gt=qe.paint.get("raster-color-range");const vt=[et[0],et[1],et[2],0],St=et[3];let rr=ot==="nearest"?Qe.NEAREST:Qe.LINEAR;if(Rt&&(Ft.push("RASTER_ARRAY"),ft||Ft.push("RASTER_COLOR"),ot==="linear"&&Ft.push("RASTER_ARRAY_LINEAR"),rr=Qe.NEAREST,!gt&&Fe.rasterLayers)){const Gt=Fe.rasterLayers.find(({id:Ht})=>Ht===qe.sourceLayer);Gt&&Gt.fields&&Gt.fields.range&&(gt=Gt.fields.range)}if(gt=gt||[0,1],ft){Ft.push("RASTER_COLOR"),st.activeTexture.set(Qe.TEXTURE2),qe.updateColorRamp(gt);let Gt=qe.colorRampTexture;Gt||(Gt=qe.colorRampTexture=new s.T(st,qe.colorRamp,Qe.RGBA8)),Gt.bind(rr,Qe.CLAMP_TO_EDGE)}return xt&&Ft.push("USE_MRT1"),{mix:vt,range:gt,offset:St,defines:Ft,resampling:rr}}(le,g,ee,ie,v.terrain&&v.terrain.renderingToTexture&&v.emissiveMode==="mrt-fallback");if(le instanceof s.aV&&!w.length&&!F)return;const me=g.paint.get("raster-emissive-strength"),pe=v.colorModeForDrapableLayerRenderPass(me),je=v.terrain&&v.terrain.renderingToTexture,Re=!v.options.moving,xe=g.paint.get("raster-resampling")==="nearest"?ie.NEAREST:ie.LINEAR;if(le instanceof s.aV&&!w.length&&(le.onNorthPole||le.onSouthPole)){const Fe=$?v.stencilModeFor3D():Qr.disabled;return void Ov(!!le.onNorthPole,null,v,d,g,me,oe,Gr.disabled,Fe)}if(!w.length)return;const[Ze,ze]=le instanceof s.aV||je?[{},w]:v.stencilConfigForOverlap(w),Ke=ze[ze.length-1].overscaledZ;H&&oe.defines.push("PROJECTION_GLOBE_VIEW"),$&&oe.defines.push("RENDER_CUTOFF","ELEVATED"),Y&&oe.defines.push("ELEVATION_REFERENCE_GROUND");const De=(Fe,qe,st)=>{for(const Qe of Fe){const xt=Qe.toUnwrapped(),ft=d.getTile(Qe);if(je&&(!ft||!ft.hasData()))continue;ee.activeTexture.set(ie.TEXTURE0);const Rt=rI(ft,le,g,oe);if(!Rt||!Rt.texture)continue;const{texture:Ft,mix:ot,offset:et,tileSize:gt,buffer:vt}=Rt;let St,rr;je?(St=Ir.disabled,rr=Qe.projMatrix):$?(St=new Ir(ie.LEQUAL,Ir.ReadWrite,v.depthRangeFor3D),rr=F?Float32Array.from(v.transform.expandedFarZProjMatrix):v.transform.calculateProjMatrix(xt,Re)):(St=v.depthModeForSublayer(Qe.overscaledZ-Ke,L===1?Ir.ReadWrite:Ir.ReadOnly,ie.LESS),rr=v.transform.calculateProjMatrix(xt,Re));const Gt=v.terrain&&je?v.terrain.stencilModeForRTTOverlap(Qe):Ze[Qe.overscaledZ],Ht=I?0:g.paint.get("raster-fade-duration");ft.registerFadeDuration(Ht);const Dt=d.findLoadedParent(Qe,0),Ar=Ux(ft,Dt,d,v.transform,Ht);let Lr,gr;!Ar.isFading&&ft.refreshedUponExpiration&&(ft.refreshedUponExpiration=!1),v.terrain&&v.terrain.prepareDrawTile(),ee.activeTexture.set(ie.TEXTURE0),Ft.bind(xe,ie.CLAMP_TO_EDGE),ee.activeTexture.set(ie.TEXTURE1),Dt?(Dt.texture&&Dt.texture.bind(xe,ie.CLAMP_TO_EDGE),Lr=Math.pow(2,Dt.tileID.overscaledZ-ft.tileID.overscaledZ),gr=[ft.tileID.canonical.x*Lr%1,ft.tileID.canonical.y*Lr%1]):Ft.bind(xe,ie.CLAMP_TO_EDGE),"useMipmap"in Ft&&ee.extTextureFilterAnisotropic&&v.transform.pitch>20&&ie.texParameterf(ie.TEXTURE_2D,ee.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,ee.extTextureFilterAnisotropicMax);const Tr=v.transform;let Hr;const sn=$?LT(Tr):[0,0,0,0];let en,_n,$r,vn,tn,Vn=0;if(H&&le instanceof s.aV&&le.coordinates.length>3)en=Float32Array.from(s.du(s.dv(new s.cn(0,0,0)))),_n=Float32Array.from(Tr.globeMatrix),$r=Float32Array.from(s.dq(Tr)),vn=[s.aH(Tr.center.lng),s.aL(Tr.center.lat)],Hr=le.elevatedGlobePerspectiveTransform,tn=le.elevatedGlobeGridMatrix||new Float32Array(9);else if(H){const Qn=s.dr(Qe.canonical);Vn=s.ds(Qn.getCenter().lat),en=Float32Array.from(s.du(s.dv(Qe.canonical))),_n=Float32Array.from(Tr.globeMatrix),$r=Float32Array.from(s.dq(Tr)),vn=[s.aH(Tr.center.lng),s.aL(Tr.center.lat)],Hr=[0,0],tn=Float32Array.from(s.dt(Qe.canonical,Qn,Vn,Tr.worldSize/Tr._pixelsPerMercatorPixel))}else Hr=le instanceof s.aV?le.perspectiveTransform:[0,0],en=new Float32Array(16),_n=new Float32Array(9),$r=new Float32Array(16),vn=[0,0],tn=new Float32Array(9);const xi=Wj(v,rr,en,_n,$r,tn,gr||[0,0],s.al(v.transform.zoom),vn,sn,Lr||1,Ar,g,Hr,$?g.paint.get("raster-elevation"):0,2,ot,et,oe.range,gt,vt,me),Ki=v.isTileAffectedByFog(Qe),Ti=v.getOrCreateProgram("raster",{defines:oe.defines,overrideFog:Ki});if(v.uploadCommonUniforms(ee,Ti,xt),le instanceof s.aV){const Qn=le.elevatedGlobeVertexBuffer,pn=le.elevatedGlobeIndexBuffer;if(je||!F)le.boundsBuffer&&le.boundsSegments&&Ti.draw(v,ie.TRIANGLES,St,Qr.disabled,pe,Gr.disabled,xi,g.id,le.boundsBuffer,v.quadTriangleIndexBuffer,le.boundsSegments);else if(Qn&&pn){const mn=Tr.zoom<=s.cJ?le.elevatedGlobeSegments:le.getSegmentsForLongitude(Tr.center.lng);mn&&Ti.draw(v,ie.TRIANGLES,St,Qr.disabled,pe,qe,xi,g.id,Qn,pn,mn)}}else if(H){St=new Ir(ie.LEQUAL,Ir.ReadOnly,v.depthRangeFor3D);const Qn=v.globeSharedBuffers;if(Qn){Y&&(v.terrain.setupElevationDraw(ft,Ti),v.uploadCommonUniforms(ee,Ti,ft.tileID.toUnwrapped()));const[pn,mn,Ei]=Qn.getGridBuffers(Vn,!1),rs=Ti.getAttributeLocation(ie,"a_texture_pos");rs!==-1&&ie.vertexAttribI4ui(rs,0,0,0,0),Ti.draw(v,ie.TRIANGLES,St,st||Gt,v.colorModeForRenderPass(),qe,xi,g.id,pn,mn,Ei)}}else if(te)St=new Ir(ie.LEQUAL,Ir.ReadWrite,v.depthRangeFor3D),v.terrain.setupElevationDraw(ft,Ti),v.uploadCommonUniforms(ee,Ti,ft.tileID.toUnwrapped()),Tr.pitch>20&&Ti.draw(v,ie.TRIANGLES,St,Qr.disabled,Kr.disabled,Gr.frontCCW,xi,g.id,v.terrain.gridBuffer,v.terrain.gridIndexBuffer,v.terrain.gridSegments),Ti.draw(v,ie.TRIANGLES,St,Gt,pe,Gr.backCCW,xi,g.id,v.terrain.gridBuffer,v.terrain.gridIndexBuffer,v.terrain.gridSegments);else{const{tileBoundsBuffer:Qn,tileBoundsIndexBuffer:pn,tileBoundsSegments:mn}=v.getTileBoundsBuffers(ft);Ti.draw(v,ie.TRIANGLES,St,Gt,pe,Gr.disabled,xi,g.id,Qn,pn,mn)}}if(!(le instanceof s.aV)&&H)for(const Qe of Fe){const xt=Qe.canonical.y===(1<s.d$[vt](xt));ot.push(xt);const et=xt.canonical.x,gt=xt.canonical.y;for(const vt of ot){const St=xe.getTile(qe?vt.wrapped():vt);if(!St)continue;const rr=St.rasterParticleState;if(!rr)continue;const Gt=vt.canonical.x+(1<Ke.tileID)),ie&&(H.activeTexture.set(Y.TEXTURE0),v.imageManager.bind(v.context,g.scope));const ze=[];if(v.terrain&&v.terrain.renderingToTexture&&v.emissiveMode==="mrt-fallback"&&ze.push("USE_MRT1"),$){const Ke=v.getOrCreateProgram(Re,{overrideFog:!1,overrideRtt:!0,defines:ze}),De=new Float32Array(s.b9([])),Fe=new s.aR(0,0,0,0,0),qe=ie?pf(De,F,L,v,0,g.scope,le,$,{tileID:Fe,tileSize:ee}):Hx(De,F,L,A.toPremultipliedRenderColor(I?null:g.lut));return void Ke.draw(v,Y.TRIANGLES,pe,me,je,Gr.disabled,qe,g.id,v.viewportBuffer,v.quadTriangleIndexBuffer,v.viewportSegments)}for(const Ke of Ze){const De=v.isTileAffectedByFog(Ke),Fe=v.getOrCreateProgram(Re,{overrideFog:De,defines:ze}),qe=Ke.toUnwrapped(),st=w?Ke.projMatrix:v.transform.calculateProjMatrix(qe);v.prepareDrawTile();const Qe=d?d.getTile(Ke):xe?xe[Ke.key]:new s.b0(Ke,ee,te.zoom,v),xt=ie?pf(st,F,L,v,0,g.scope,le,$,{tileID:Ke,tileSize:ee}):Hx(st,F,L,A.toPremultipliedRenderColor(I?null:g.lut));v.uploadCommonUniforms(H,Fe,qe);const{tileBoundsBuffer:ft,tileBoundsIndexBuffer:Rt,tileBoundsSegments:Ft}=v.getTileBoundsBuffers(Qe);Fe.draw(v,Y.TRIANGLES,pe,me,je,Gr.disabled,xt,g.id,ft,Rt,Ft)}},sky:function(v,d,g){const w=v._atmosphere?s.al(v.transform.zoom):1,A=g.paint.get("sky-opacity")*w;if(A===0)return;const I=v.context,L=g.paint.get("sky-type"),F=new Ir(I.gl.LEQUAL,Ir.ReadOnly,[0,1]),$=v.frameCounter/1e3%1;L==="atmosphere"?v.renderPass==="offscreen"?g.needsSkyboxCapture(v)&&(function(H,Y){const te=H.context,ee=te.gl;let ie=Y.skyboxFbo;if(!ie){ie=Y.skyboxFbo=te.createFramebuffer(32,32,1,null),Y.skyboxGeometry=new Yo(te),Y.skyboxTexture=te.gl.createTexture(),ee.bindTexture(ee.TEXTURE_CUBE_MAP,Y.skyboxTexture),ee.texParameteri(ee.TEXTURE_CUBE_MAP,ee.TEXTURE_WRAP_S,ee.CLAMP_TO_EDGE),ee.texParameteri(ee.TEXTURE_CUBE_MAP,ee.TEXTURE_WRAP_T,ee.CLAMP_TO_EDGE),ee.texParameteri(ee.TEXTURE_CUBE_MAP,ee.TEXTURE_MIN_FILTER,ee.LINEAR),ee.texParameteri(ee.TEXTURE_CUBE_MAP,ee.TEXTURE_MAG_FILTER,ee.LINEAR);for(let pe=0;pe<6;++pe)ee.texImage2D(ee.TEXTURE_CUBE_MAP_POSITIVE_X+pe,0,ee.RGBA,32,32,0,ee.RGBA,ee.UNSIGNED_BYTE,null)}te.bindFramebuffer.set(ie.framebuffer),te.viewport.set([0,0,32,32]);const le=Y.getCenter(H,!0),oe=H.getOrCreateProgram("skyboxCapture"),me=new Float64Array(16);s.b9(me),s.ef(me,me,.5*-Math.PI),Sc(H,Y,oe,me,le,0),s.b9(me),s.ef(me,me,.5*Math.PI),Sc(H,Y,oe,me,le,1),s.b9(me),s.cE(me,me,.5*-Math.PI),Sc(H,Y,oe,me,le,2),s.b9(me),s.cE(me,me,.5*Math.PI),Sc(H,Y,oe,me,le,3),s.b9(me),Sc(H,Y,oe,me,le,4),s.b9(me),s.ef(me,me,Math.PI),Sc(H,Y,oe,me,le,5),te.viewport.set([0,0,H.width,H.height])}(v,g),g.markSkyboxValid(v)):v.renderPass==="sky"&&function(H,Y,te,ee,ie){const le=H.context,oe=le.gl,me=H.transform,pe=H.getOrCreateProgram("skybox");le.activeTexture.set(oe.TEXTURE0),oe.bindTexture(oe.TEXTURE_CUBE_MAP,Y.skyboxTexture);const je=((Re,xe,Ze,ze,Ke)=>({u_matrix:Re,u_sun_direction:xe,u_cubemap:0,u_opacity:ze,u_temporal_offset:Ke}))(me.skyboxMatrix,Y.getCenter(H,!1),0,ee,ie);H.uploadCommonUniforms(le,pe),pe.draw(H,oe.TRIANGLES,te,Qr.disabled,H.colorModeForRenderPass(),Gr.backCW,je,"skybox",Y.skyboxGeometry.vertexBuffer,Y.skyboxGeometry.indexBuffer,Y.skyboxGeometry.segment)}(v,g,F,A,$):L==="gradient"&&v.renderPass==="sky"&&function(H,Y,te,ee,ie){const le=H.context,oe=le.gl,me=H.transform,pe=H.getOrCreateProgram("skyboxGradient");Y.skyboxGeometry||(Y.skyboxGeometry=new Yo(le)),le.activeTexture.set(oe.TEXTURE0);let je=Y.colorRampTexture;je||(je=Y.colorRampTexture=new s.T(le,Y.colorRamp,oe.RGBA8)),je.bind(oe.LINEAR,oe.CLAMP_TO_EDGE);const Re=((xe,Ze,ze,Ke,De)=>({u_matrix:xe,u_color_ramp:0,u_center_direction:Ze,u_radius:s.ap(ze),u_opacity:Ke,u_temporal_offset:De}))(me.skyboxMatrix,Y.getCenter(H,!1),Y.paint.get("sky-gradient-radius"),ee,ie);H.uploadCommonUniforms(le,pe),pe.draw(H,oe.TRIANGLES,te,Qr.disabled,H.colorModeForRenderPass(),Gr.backCW,Re,"skyboxGradient",Y.skyboxGeometry.vertexBuffer,Y.skyboxGeometry.indexBuffer,Y.skyboxGeometry.segment)}(v,g,F,A,$)},custom:function(v,d,g,w){const A=v.context,I=g.implementation;if(!v.transform.projection.unsupportedLayers||!v.transform.projection.unsupportedLayers.includes("custom")||v.terrain&&(v.terrain.renderingToTexture||v.renderPass==="offscreen")&&g.isDraped(d)){if(v.renderPass==="offscreen"){const L=I.prerender;if(L){if(v.setCustomLayerDefaults(),A.setColorMode(v.colorModeForRenderPass()),v.transform.projection.name==="globe"){const F=v.transform.pointMerc;L.call(I,A.gl,v.transform.customLayerMatrix(),v.transform.getProjection(),v.transform.globeToMercatorMatrix(),s.al(v.transform.zoom),[F.x,F.y],v.transform.pixelsPerMeterRatio)}else L.call(I,A.gl,v.transform.customLayerMatrix());A.setDirty(),v.setBaseState()}}else if(v.renderPass==="translucent"){if(v.terrain&&v.terrain.renderingToTexture){const F=I.renderToTile;if(F){const $=w[0].canonical,H={x:$.x+w[0].wrap*(I.wrapTileId?0:1<<$.z),y:$.y,z:$.z};A.setDepthMode(Ir.disabled),A.setStencilMode(Qr.disabled),A.setColorMode(v.colorModeForRenderPass()),v.setCustomLayerDefaults(),F.call(I,A.gl,H),A.setDirty(),v.setBaseState()}return}v.setCustomLayerDefaults(),A.setColorMode(v.colorModeForRenderPass()),A.setStencilMode(Qr.disabled);const L=I.renderingMode==="3d"?new Ir(v.context.gl.LEQUAL,Ir.ReadWrite,v.depthRangeFor3D):v.depthModeForSublayer(0,Ir.ReadOnly);if(A.setDepthMode(L),v.transform.projection.name==="globe"){const F=v.transform.pointMerc;I.render(A.gl,v.transform.customLayerMatrix(),v.transform.getProjection(),v.transform.globeToMercatorMatrix(),s.al(v.transform.zoom),[F.x,F.y],v.transform.pixelsPerMeterRatio)}else I.render(A.gl,v.transform.customLayerMatrix());A.setDirty(),v.setBaseState(),A.bindFramebuffer.set(null)}}else s.w("Custom layers are not yet supported with this projection. Use mercator or globe to enable usage of custom layers.")},model:function(v,d,g,w){if(v.renderPass==="opaque")return;const A=g.paint.get("model-opacity").constantOr(1),I=g.paint.get("model-elevation-reference"),L=I==="ground",F=I==="ground";if(A===0)return;const $=g.paint.get("model-cast-shadows");if(v.renderPass==="shadow"&&(!$||v.terrain&&A<.65&&g._transitionablePaint._values["model-opacity"].value.expression instanceof s.af))return;const H=v.shadowRenderer,Y=g.paint.get("model-receive-shadows");H&&(H.useNormalOffset=!0,Y||(H.enabled=!1));const te=()=>{H&&(H.useNormalOffset=!0,Y||(H.enabled=!0))},ee=d.getSource();if(v.renderPass==="light-beam"&&ee.type!=="batched-model")return;if(ee.type==="vector"||ee.type==="geojson")return function(xe,Ze,ze,Ke,De){const Fe=xe.transform,qe=Fe.projection.name==="globe",st=Fe.getFreeCameraOptions().position;if(!xe.modelManager)return;const Qe=xe.modelManager;ze.modelManager=Qe;const xt=xe.shadowRenderer;if(!ze._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const ft=ze._unevaluatedLayout._values["model-id"],Rt=Object.assign({},ze.layout.get("model-id").parameters),Ft=xe.style.order.indexOf(ze.fqid),ot=ze.paint.get("model-opacity").constantOr(1);for(const et of Ke){const gt=Ze.getTile(et).getBucket(ze);if(!gt||gt.projection.name!==Fe.projection.name)continue;const vt=gt.getModelUris();if(vt&&!gt.modelsRequested&&(Qe.addModelsFromBucket(vt,De),gt.modelsRequested=!0),qe)Rt.zoom=et.overscaledZ;else{const gr=xg(et,Fe);Rt.zoom=gr}const St=ft.possiblyEvaluate(Rt);if(Xt(xe,gt,et),qt.shadowUniformsInitialized=!1,qt.useSingleShadowCascade=!!xt&&xt.getMaxCascadeForTile(et.toUnwrapped())===0,xe.renderPass==="shadow"&&xt){if(xe.currentShadowCascade===1&>.isInsideFirstShadowMapFrustum)continue;const gr=Fe.calculatePosMatrix(et.toUnwrapped(),Fe.worldSize);if(qt.tileMatrix.set(gr),qt.shadowTileMatrix=Float32Array.from(xt.calculateShadowPassMatrixFromMatrix(gr)),qt.aabb.min=[0,0,0],qt.aabb.max[0]=qt.aabb.max[1]=s.an,qt.aabb.max[2]=0,cI(gt,qt,xe,ze.scope))continue}const rr=1<0&&xe.style.isLayerClipped(ze,Ze.getSource())&>.updateReplacement(et,xe.replacementSource,Ft,ze.scope)&&(gt.uploaded=!1,gt.upload(xe.context));let Ht=0;const Dt=new Array,Ar=new Array,Lr=new Array;for(let gr in gt.instancesPerModel){const Tr=gt.instancesPerModel[gr];Tr.features.length>0&&!qe&&(gr=St.evaluate(Tr.features[0].feature,{}));const Hr=Qe.getModel(gr,De);if(Hr||Qe.hasURLBeenRequested(gr)||gt.modelUris.includes(gr)||(gt.modelUris.push(gr),gt.modelsRequested=!1),Hr&&Hr.uploaded)if(qe){const sn=s.bJ([],[st.x,st.y,st.z],xe.transform.worldSize);s.eo(sn,sn);for(let en=0;en0&&vn.elevationUpdate(gr.terrain,en,$r,Hr.source),vn.needsReEvaluation(gr,_n,Hr)&&vn.evaluate(Hr))}})(xe,Ze,ze,Ke),function(){const gr=new Map;let Tr,Hr,sn;Dt?(Tr=Ke.length-1,Hr=-1,sn=-1):(Tr=0,Hr=Ke.length,sn=1);const en=new Float64Array(16),_n=s.ce(),$r=new s.P(0,0);for(let vn=Tr;vn!==Hr;vn+=sn){const tn=Ke[vn],Vn=Ze.getTile(tn).getBucket(ze);if(!Vn||!Vn.uploaded)continue;let xi=!1;st&&(xi=st.getMaxCascadeForTile(tn.toUnwrapped())===0);const Ki=Fe.calculatePosMatrix(tn.toUnwrapped(),Fe.worldSize),Ti=Vn.modelTraits;!rr&&Dt&&(s.b7(en,Ki),s.ah(_n,xt,en),$r.x=_n[0],$r.y=_n[1]);const Qn=[];Vn.setFilter(ze.filter);for(const pn of Vn.getNodesInfo()){if(pn.hiddenByReplacement||!pn.node.meshes)continue;const mn=pn.node;let Ei=0;xe.terrain&&mn.elevation&&(Ei=mn.elevation*xe.terrain.exaggeration());const rs=(()=>{const Va=pn.aabb;return St.min=[...Va.min],St.max=[...Va.max],St.min[2]+=Ei,St.max[2]+=Ei,s.ah(St.min,St.min,Ki),s.ah(St.max,St.max,Ki),St})(),Jn=pn.evaluatedScale;if(Jn[0]<=1&&Jn[1]<=1&&Jn[2]<=1&&rs.intersects(Gt)===0)continue;if(!rr&&Dt){const Va=.16666666666666666;pn.cameraCollisionOpacity=xt[0]>rs.min[0]&&xt[0]rs.min[1]&&xt[1]!Dt||pn.opacity===1&&mn.opacity===1?pn.depthmn.depth?-1:1);for(const pn of Qn){const mn=pn.nodeInfo,Ei=mn.node;if(xe._debugParams.show3DModelFootprints&&Ei.footprint){const jn=Ei.id||Ei.name||"footprint";gr.has(jn)||gr.set(jn,{node:Ei,mvp:pn.wvpForTile})}let rs=s.aD([],ot,pn.tileModelMatrix);s.aD(rs,Rt,rs);const Jn=s.b7([],rs);s.e6(Jn,Jn),s.cC(Jn,Jn,nt),rs=s.aD(rs,rs,Ei.globalMatrix);const on=xe.renderPass==="light-beam",Gi=ze.paint.get("model-color-use-theme").constantOr("default")==="none",_i=Ti&s.ez.HasMapboxMeshFeatures,Os=_i?0:mn.evaluatedRMEA[0][2];for(let jn=0;jn=Rn||ac>=Rn}}const si=wi.material;let Ac;si.occlusionTexture&&si.occlusionTexture.offsetScale&&(Ac=si.occlusionTexture.offsetScale,la.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const kc=xe.getOrCreateProgram("model",la);!rr&&st&&st.setupShadowsFromMatrix(pn.tileModelMatrix,kc,st.useNormalOffset),xe.uploadCommonUniforms(De,kc,null,sc);const Ii=si.pbrMetallicRoughness;Ii.metallicFactor=.9,Ii.roughnessFactor=.5;const Mi=jp(new Float32Array(_o),new Float32Array(rs),new Float32Array(Jn),new Float32Array(Ei.globalMatrix),xe,pn.opacity,Ii.baseColorFactor,si.emissiveFactor,Ii.metallicFactor,Ii.roughnessFactor,si,Os,ze,[0,0,0],Ac);!Xs&&(mn.hasTranslucentParts||pn.opacity<1)&&kc.draw(xe,De.gl.TRIANGLES,gt,Qr.disabled,Kr.disabled,Gr.backCCW,Mi,ze.id,wi.vertexBuffer,wi.indexBuffer,wi.segments,ze.paint,xe.transform.zoom,void 0,Va),kc.draw(xe,De.gl.TRIANGLES,Xs?vt:gt,Qr.disabled,Xs||pn.opacity<1||mn.hasTranslucentParts?Kr.alphaBlended:Kr.unblended,Gr.backCCW,Mi,ze.id,wi.vertexBuffer,wi.indexBuffer,wi.segments,ze.paint,xe.transform.zoom,void 0,Va)}}}if(xe._debugParams.show3DModelFootprints&&gr.size>0){const vn=Array.from(gr.keys()).sort();for(const tn of vn){const{node:Vn,mvp:xi}=gr.get(tn);qT(xe,0,Vn,xi)}}}()}(v,d,g,w),void te();if(ee.type!=="model")return;const ie=ee.getModels(),le=[],oe=v.transform.getFreeCameraOptions().position,me=s.bJ([],[oe.x,oe.y,oe.z],v.transform.worldSize);s.eo(me,me);const pe=[],je=[];let Re=0;for(const xe of ie){const Ze=d.getFeatureState("",xe.id),ze={type:"Unknown",id:xe.id,properties:xe.featureProperties},Ke=g.paint.get("model-rotation").evaluate(ze,Ze),De=g.paint.get("model-scale").evaluate(ze,Ze),Fe=g.paint.get("model-translation").evaluate(ze,Ze),qe=g.paint.get("model-opacity").evaluate(ze,Ze);GT(g,xe.id,Ze,xe.featureProperties,xe.nodeOverrideNames,xe.nodeOverrides),Rp(g,xe.id,Ze,xe.featureProperties,xe.materialOverrideNames,xe.materialOverrides),xe.nodeOverrides.size>0&&xe.computeBoundsAndApplyParent(),xe.computeModelMatrix(v,Ke,De,Fe,F,L,!1);const st=s.b9([]),Qe=s.e2(xe.position.lat,v.transform.zoom),xt=s.bP([],[1,1,1/Qe]);s.bx(st,st,me),le.push({zScaleMatrix:xt,negCameraPosMatrix:st});for(const ft of xe.nodes)Bv(v,ft,xe.matrix,v.transform.expandedFarZProjMatrix,Re,pe,je,xe.materialOverrides,qe);Re++}if(pe.sort((xe,Ze)=>Ze.depth-xe.depth),v.renderPass!=="shadow"){if(v._debugParams.show3DModelFootprints){const xe=v.transform.projMatrix,Ze=new Map,ze=(De,Fe)=>{if(De.footprint){const qe=De.id||De.name||"footprint";if(!Ze.has(qe)){const st=s.aD([],xe,Fe);Ze.set(qe,{node:De,mvp:st})}}};for(const De of je)ze(De.node,De.modelMatrix);for(const De of pe)ze(De.node,De.modelMatrix);const Ke=Array.from(Ze.keys()).sort();for(const De of Ke){const{node:Fe,mvp:qe}=Ze.get(De);qT(v,0,Fe,qe)}}fh(v,g,pe,je,le),te()}else{for(const xe of je)yg(xe.mesh,xe.nodeModelMatrix,v,g);for(const xe of pe)yg(xe.mesh,xe.nodeModelMatrix,v,g);te()}}},KT={line:function(v,d,g){if(v.hasElevatedBuckets=!1,v.hasNonElevatedBuckets=!1,v._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||v._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(d){const w=d.getVisibleCoordinates();for(const A of w){const I=d.getTile(A).getBucket(v);if(I&&(I.elevationType!=="none"?v.hasElevatedBuckets=!0:v.hasNonElevatedBuckets=!0,v.hasElevatedBuckets&&v.hasNonElevatedBuckets))break}}}else v.hasNonElevatedBuckets=!0},model:function(v,d,g){const w=d.getSource();if(!w.loaded())return;if(w.type==="vector"||w.type==="geojson")return void(g.modelManager&&g.modelManager.upload(g,Fv(g,v)));if(w.type==="batched-model"||w.type!=="model")return;const A=w.getModels();for(const I of A)I.upload(g.context)},raster:function(v,d,g){const w=d.getSource();if(!(w instanceof yp&&w.loaded()))return;const A=v.sourceLayer||w.rasterLayerIds&&w.rasterLayerIds[0];if(!A)return;const I=v.paint.get("raster-array-band")||w.getInitialBand(A);if(I==null)return;const L=d.getIds().map(F=>d.getTileByID(F));for(const F of L)F.updateNeeded(v.id,I)&&w.prepareTile(F,A,v.id,I)},"raster-particle":function(v,d,g){const w=d.getSource();if(!(w instanceof yp&&w.loaded()))return;const A=v.sourceLayer||w.rasterLayerIds&&w.rasterLayerIds[0];if(!A)return;const I=v.paint.get("raster-particle-array-band")||w.getInitialBand(A);if(I==null)return;const L=d.getIds().map(F=>d.getTileByID(F));for(const F of L)F.updateNeeded(v.id,I)&&w.prepareTile(F,A,v.id,I)}},YT={fill:Yx},ZT={fill:function(v,d,g,w){if(!g.layout||g.layout.get("fill-elevation-reference")==="none"||g.paint.get("fill-opacity").constantOr(1)===0)return;const A=v.context.gl,I=new Ir(A.LEQUAL,Ir.ReadOnly,v.depthRangeFor3D),L=new Qr({func:A.ALWAYS,mask:255},255,255,A.KEEP,A.KEEP,A.REPLACE),F=v.transform.getFreeCameraOptions().position,$=v.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const H of w){const Y=d.getTile(H),te=Y.getBucket(g);if(!te)continue;const ee=te.elevatedStructures;if(!ee||ee.depthSegments.segments[0].primitiveLength===0)continue;const ie=jT(H.toUnwrapped(),F),le=v.translatePosMatrix(H.projMatrix,Y,g.paint.get("fill-translate"),g.paint.get("fill-translate-anchor")),oe=qx(le,ie,0,1,0);$.draw(v,A.TRIANGLES,I,L,Kr.disabled,Gr.disabled,oe,g.id,ee.vertexBuffer,ee.indexBuffer,ee.depthSegments,g.paint,v.transform.zoom)}}};class B3{constructor(d,g,w,A,I){this.context=new mg(d,g),this.transform=w,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this._timeStamp=s.o.now(),this._averageFPS=0,this._fpsHistory=[],this._dt=0,this._debugParams={forceEnablePrecipitation:!1,showTerrainProxyTiles:!1,fpsWindow:30,continousRedraw:!1,show3DModelFootprints:!1,enabledLayers:{}};const L=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const $ of L)this._debugParams.enabledLayers[$]=!0;for(const $ of L);this.occlusionParams=new dI,this.setup(),this.numSublayers=nu.maxUnderzooming+nu.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new s.eG,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._shadowRenderer=new Ix(this),this._wireframeDebugCache=new uI,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const F=new s.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new s.T(this.context,F,d.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=A,this.maxFrontCutoffRawStart=0,this.worldview=I,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(d,g){const w=!!d&&!!d.terrain&&this.transform.projection.supportsTerrain;if(!(w||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new Vx(this,d));const A=this._terrain;this.transform.elevation=w?A:null,A.update(d,this.transform,g),this.transform.elevation&&!A.enabled&&(this.transform.elevation=null)}_updateFog(d){const g=d.fog;if(!g||this.transform.projection.name==="globe"||g.getOpacity(this.transform.pitch)<1||g.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[w,A]=g.getFovAdjustedRange(this.transform._fov);if(w>A)return void(this.transform.fogCullDistSq=null);const I=w+.78*(A-w);this.transform.fogCullDistSq=I*I}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(d){d&&!this._terrain&&(this._terrain=new Vx(this,this.style)),this._forceTerrainMode=d}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(d,g){if(this.width=d*s.o.devicePixelRatio,this.height=g*s.o.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 d=this.context,g=new s.dB;g.emplaceBack(0,0),g.emplaceBack(s.an,0),g.emplaceBack(0,s.an),g.emplaceBack(s.an,s.an),this.tileExtentBuffer=d.createVertexBuffer(g,s.dx.members),this.tileExtentSegments=s.dy.simpleSegment(0,0,4,2);const w=new s.dB;w.emplaceBack(0,0),w.emplaceBack(s.an,0),w.emplaceBack(0,s.an),w.emplaceBack(s.an,s.an),this.debugBuffer=d.createVertexBuffer(w,s.dx.members),this.debugSegments=s.dy.simpleSegment(0,0,4,5);const A=new s.dB;A.emplaceBack(-1,-1),A.emplaceBack(1,-1),A.emplaceBack(-1,1),A.emplaceBack(1,1),this.viewportBuffer=d.createVertexBuffer(A,s.dx.members),this.viewportSegments=s.dy.simpleSegment(0,0,4,2);const I=new s.eH;I.emplaceBack(0,0,0,0),I.emplaceBack(s.an,0,s.an,0),I.emplaceBack(0,s.an,0,s.an),I.emplaceBack(s.an,s.an,s.an,s.an),this.mercatorBoundsBuffer=d.createVertexBuffer(I,s.eI.members),this.mercatorBoundsSegments=s.dy.simpleSegment(0,0,4,2);const L=new s.dC;L.emplaceBack(0,1,2),L.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=d.createIndexBuffer(L);const F=new s.eJ;for(const H of[0,1,3,2,0])F.emplaceBack(H);this.debugIndexBuffer=d.createIndexBuffer(F),this.emptyTexture=new s.T(d,new s.q({width:1,height:1},Uint8Array.of(0,0,0,0)),d.gl.RGBA8),this.identityMat=s.bb();const $=this.context.gl;this.stencilClearMode=new Qr({func:$.ALWAYS,mask:0},0,255,$.ZERO,$.ZERO,$.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(d){return d._makeTileBoundsBuffers(this.context,this.transform.projection),d._tileBoundsBuffer?{tileBoundsBuffer:d._tileBoundsBuffer,tileBoundsIndexBuffer:d._tileBoundsIndexBuffer,tileBoundsSegments:d._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const d=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,d.TRIANGLES,Ir.disabled,this.stencilClearMode,Kr.disabled,Gr.disabled,$x(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(d,g,w){if(!g||this.currentStencilSource===g.id||!d.isTileClipped()||!w||w.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let F=!1;for(const $ of w)if(this._tileClippingMaskIDs[$.key]===void 0){F=!0;break}if(!F)return}this.currentStencilSource=g.id;const A=this.context,I=A.gl;this.nextStencilID+w.length>256&&this.clearStencil(),A.setColorMode(Kr.disabled),A.setDepthMode(Ir.disabled);const L=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const F of w){const $=g.getTile(F),H=this._tileClippingMaskIDs[F.key]=this.nextStencilID++,{tileBoundsBuffer:Y,tileBoundsIndexBuffer:te,tileBoundsSegments:ee}=this.getTileBoundsBuffers($);L.draw(this,I.TRIANGLES,Ir.disabled,new Qr({func:I.ALWAYS,mask:0},H,255,I.KEEP,I.KEEP,I.REPLACE),Kr.disabled,Gr.disabled,$x(F.projMatrix),"$clipping",Y,te,ee)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const d=this.nextStencilID++,g=this.context.gl;return new Qr({func:g.NOTEQUAL,mask:255},d,255,g.KEEP,g.KEEP,g.REPLACE)}stencilModeForClipping(d){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(d);const g=this.context.gl;return new Qr({func:g.EQUAL,mask:255},this._tileClippingMaskIDs[d.key],0,g.KEEP,g.KEEP,g.REPLACE)}stencilConfigForOverlap(d){const g=this.context.gl,w=d.sort((L,F)=>F.overscaledZ-L.overscaledZ),A=w[w.length-1].overscaledZ,I=w[0].overscaledZ-A+1;if(I>1){this.currentStencilSource=void 0,this.nextStencilID+I>256&&this.clearStencil();const L={};for(let F=0;Fthis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((d,g)=>d+g/this._fpsHistory.length,0))}render(d,g){const w=s.o.now();this._dt=w-this._timeStamp,this._timeStamp=w,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=d.map.repaint,this.style=d,this.options=g;const A=this.style._mergedLayers,I=!(!this.terrain||!this.terrain.enabled),L=()=>this.style._getOrder(I).filter(ot=>{const et=A[ot];return!(et.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[et.type]});let F=L(),$=!1,H=!1,Y=null,te=0,ee=!1;for(const ot of F){const et=A[ot];et.visibility!=="none"&&(et.type==="circle"?$=!0:et.type==="building"?(Y=et,++te):et.type==="symbol"&&(et.hasOcclusionOpacityProperties?H=!0:$=!0))}this.updateEmissiveMode();let ie=F.map(ot=>A[ot]);const le=this.style._mergedSourceCaches;this.imageManager=d.imageManager,this.modelManager=d.modelManager,this.symbolFadeChange=d.placement.symbolFadeChange(s.o.now()),this.imageManager.beginFrame();for(const ot in le){const et=le[ot];et.used&&(et.prepare(this.context),et.getSource().usedInConflation&&++te)}let oe=!1;for(const ot of ie)ot.isHidden(this.transform.zoom)||(ot.type==="clip"&&(oe=!0),this.prepareLayer(ot));const me={},pe={},je={},Re={},xe={};for(const ot in le){const et=le[ot];me[ot]=et.getVisibleCoordinates(),pe[ot]=me[ot].slice().reverse(),je[ot]=et.getVisibleCoordinates(!0).reverse(),Re[ot]=et.getShadowCasterCoordinates(),xe[ot]=et.sortCoordinatesByDistance(me[ot])}const Ze=ot=>{const et=this.style.getLayerSourceCache(ot);return et&&et.used?et.getSource():null};if(te||oe||this._clippingActiveLastFrame){const ot=[],et=[];let gt=0;for(const vt of ie)this.isSourceForClippingOrConflation(vt,Ze(vt))&&(ot.push(vt),et.push(gt)),gt++;if(ot&&(oe||ot.length>1)||this._clippingActiveLastFrame){oe=!1;const vt=[];for(let St=0;St0){const vt=Ze(et);vt&&(this.minCutoffZoom=Math.max(vt.minzoom,this.minCutoffZoom)),et.minzoom&&(this.minCutoffZoom=Math.max(et.minzoom,this.minCutoffZoom))}et.is3D(I)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=ot),this._lastOcclusionLayer=ot)}const ze=this.style&&this.style.fog;ze?(this._fogVisible=ze.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=ze.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(je),this.opaquePassCutoff=0,F=L(),ie=F.map(ot=>A[ot]));const Ke=this._shadowRenderer;if(Ke){Ke.updateShadowParameters(this.transform,this.style.directionalLight);for(const ot in le)for(const et of me[ot]){let gt={min:0,max:0};this.terrain&&(gt=this.terrain.getMinMaxForTile(et)||gt),Ke.addShadowReceiver(et.toUnwrapped(),gt.min,gt.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new s.eL(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new oI(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const De=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),Fe=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(De&&!this._snow&&(this._snow=new pI(this)),!De&&this._snow&&(this._snow.destroy(),delete this._snow),Fe&&!this._rain&&(this._rain=new Jx(this)),!Fe&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),Y){this.buildingTileBorderManager||(this.buildingTileBorderManager=new hh);const ot=this.style.getLayerSourceCache(Y);this.buildingTileBorderManager.updateBorders(ot,Y)}if(!yr.has(this.context.gl))return;this.renderPass="offscreen";for(const ot of ie){const et=d.getLayerSourceCache(ot);if(!ot.hasOffscreenPass()||ot.isHidden(this.transform.zoom))continue;const gt=et?pe[et.id]:void 0;(ot.type==="custom"||ot.type==="raster"||ot.type==="raster-particle"||ot.isSky()||gt&>.length)&&this.renderLayer(this,et,ot,gt)}this.depthRangeFor3D=[0,1-(ie.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Re)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const qe=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),st=(()=>{if(g.showOverdrawInspector)return s.aq.black;const ot=this.style.fog;if(ot&&this.transform.projection.supportsFog){const et=this.style.getLut(ot.scope);if(!qe){const gt=ot.properties.get("color-use-theme")==="none",vt=ot.properties.get("color").toNonPremultipliedRenderColor(gt?null:et).toArray01();return new s.aq(...vt)}if(qe){const gt=ot.properties.get("space-color-use-theme")==="none",vt=ot.properties.get("space-color").toNonPremultipliedRenderColor(gt?null:et).toArray01();return new s.aq(...vt)}}return s.aq.transparent})();if(this.context.clear({color:st,depth:1}),this.clearStencil(),this._showOverdrawInspector=g.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&qe&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=F.length-1;this.currentLayer>=0;this.currentLayer--){const ot=ie[this.currentLayer],et=d.getLayerSourceCache(ot);if(ot.isSky())continue;const gt=et?(ot.is3D(I)?xe:pe)[et.id]:void 0;this._renderTileClippingMasks(ot,et,gt),this.renderLayer(this,et,ot,gt)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&qe&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||s.al(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 gt=this.currentLayer;this.depthOcclusion=!0;for(const vt of this.layersWithOcclusionOpacity){this.currentLayer=vt;const St=ie[this.currentLayer],rr=d.getLayerSourceCache(St),Gt=rr?pe[rr.id]:void 0;this.terrain||this._renderTileClippingMasks(St,rr,rr?me[rr.id]:void 0),this.renderLayer(this,rr,St,Gt)}this.depthOcclusion=!1,this.currentLayer=gt,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 ot=null;ie.forEach(et=>{const gt=d.getLayerSourceCache(et);gt&&!et.isHidden(this.transform.zoom)&>.getVisibleCoordinates().length&&(!ot||ot.getSource().maxzoom0?g.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(d,g,w){const A=w===void 0?this.terrain&&this.terrain.renderingToTexture:w,I=[];return this.style&&this.style.enable3dLights()&&(d==="globeRaster"||d==="terrainRaster"?(I.push("LIGHTING_3D_MODE"),I.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):A||I.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(I.push("TERRAIN"),this.linearFloatFilteringSupported()&&I.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&I.push("GLOBE"),!this._fogVisible||A||g!==void 0&&!g||I.push("FOG"),A&&I.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&I.push("OVERDRAW_INSPECTOR"),I}getOrCreateProgram(d,g){this.cache=this.cache||{};const w=g&&g.defines||[],A=g&&g.config,I=this.currentGlobalDefines(d,g&&g.overrideFog,g&&g.overrideRtt).concat(w),L=Cp.cacheKey(Ej[d],d,I,A);return this.cache[L]||(this.cache[L]=new Cp(this.context,d,Ej[d],A,Iv[d],I)),this.cache[L]}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 d=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(d.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new s.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()}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(d,g){if(this.style.enable3dLights()){const w=this.style.directionalLight,A=this.style.ambientLight;if(w&&A){const I=((L,F,$)=>{const H=L.properties.get("direction"),Y=L.properties.get("color-use-theme")==="none",te=L.properties.get("color").toNonPremultipliedRenderColor(Y?null:$.getLut(L.scope)).toArray01(),ee=L.properties.get("intensity"),ie=F.properties.get("color-use-theme")==="none",le=F.properties.get("color").toNonPremultipliedRenderColor(ie?null:$.getLut(F.scope)).toArray01(),oe=F.properties.get("intensity"),me=[H.x,H.y,H.z],pe=s.dD(le,oe),je=s.dD(te,ee);return{u_lighting_ambient_color:pe,u_lighting_directional_dir:me,u_lighting_directional_color:je,u_ground_radiance:TT(me,je,pe)}})(w,A,this.style);g.setLightsUniformValues(d,I)}}}uploadCommonUniforms(d,g,w,A,I){if(this.uploadCommonLightUniforms(d,g),this.terrain&&this.terrain.renderingToTexture)return;const L=this.style.fog;if(L){const F=L.getOpacity(this.transform.pitch),$=((H,Y,te,ee,ie,le,oe,me,pe,je,Re,xe)=>{const Ze=H.transform,ze=Y.properties.get("color-use-theme")==="none",Ke=Y.properties.get("color").toNonPremultipliedRenderColor(ze?null:H.style.getLut(Y.scope)).toArray01();Ke[3]=ee;const De=H.frameCounter/1e3%1,[Fe,qe]=Y.properties.get("vertical-range");return{u_fog_matrix:te?Ze.calculateFogTileMatrix(te):xe||H.identityMat,u_fog_range:Y.getFovAdjustedRange(Ze._fov),u_fog_color:Ke,u_fog_horizon_blend:Y.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(Fe,qe),qe],u_fog_temporal_offset:De,u_frustum_tl:ie,u_frustum_tr:le,u_frustum_br:oe,u_frustum_bl:me,u_globe_pos:pe,u_globe_radius:je,u_viewport:Re,u_globe_transition:s.al(Ze.zoom),u_is_globe:+(Ze.projection.name==="globe")}})(this,L,w,F,this.transform.frustumCorners.TL,this.transform.frustumCorners.TR,this.transform.frustumCorners.BR,this.transform.frustumCorners.BL,this.transform.globeCenterInViewSpace,this.transform.globeRadius,[this.transform.width*s.o.devicePixelRatio,this.transform.height*s.o.devicePixelRatio],A);g.setFogUniformValues(d,$)}I&&g.setCutoffUniformValues(d,I.uniformValues)}setTileLoadedFlag(d){this.tileLoaded=d}saveCanvasCopy(){const d=this.canvasCopy();d&&(this.frameCopies.push(d),this.tileLoaded=!1)}canvasCopy(){const d=this.context.gl,g=d.createTexture();return d.bindTexture(d.TEXTURE_2D,g),d.copyTexImage2D(d.TEXTURE_2D,0,d.RGBA,0,0,d.drawingBufferWidth,d.drawingBufferHeight,0),g}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const d=this.style&&this.style.fog;return!!d&&d.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const d=this._backgroundTiles,g=this._backgroundTiles={},w=this.transform.coveringTiles({tileSize:512});for(const A of w)g[A.key]=d[A.key]||new s.b0(A,512,this.transform.tileZoom,this,void 0,this.worldview);return g}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(d,g){return!(!d.is3D(!(!this.terrain||!this.terrain.enabled))||d.type!=="clip"&&d.type!=="building"&&(d.minzoom&&d.minzoom>this.transform.zoom||(this.style._clipLayerPresent||d.sourceLayer!=="building"&&d.sourceLayer!=="procedural_buildings")&&(!g||g.type!=="batched-model")))}isTileAffectedByFog(d){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let g=this._cachedTileFogOpacities[d.key];return g||(this._cachedTileFogOpacities[d.key]=g=this.style.fog.getOpacityForTile(d)),g[0]>=Rn||g[1]>=Rn}setupDepthForOcclusion(d,g,w){const A=this.context,I=A.gl,L=!!w;var F;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}),A.activeTexture.set(I.TEXTURE3),d&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(I.NEAREST,I.CLAMP_TO_EDGE),w.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],w.u_depth_range_unpack=[2/((F=this.depthRangeFor3D)[1]-F[0]),-1-2*F[0]/(F[1]-F[0])],w.u_occluder_half_size=.5*this.occlusionParams.occluderSize,w.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(I.NEAREST,I.CLAMP_TO_EDGE),A.activeTexture.set(I.TEXTURE0),L||g.setTerrainUniformValues(A,w)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const d=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=d?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function XT(v,d){let g=!1,w=null;const A=()=>{w=null,g&&(v(),w=setTimeout(A,d),g=!1)};return()=>(g=!0,w||A(),w)}class z3{constructor(d){this._hashName=d&&encodeURIComponent(d),s.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=XT(this._updateHashUnthrottled.bind(this),300)}addTo(d){return this._map=d,window.addEventListener("hashchange",this._onHashChange,!1),d.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 d=this._map;if(!d)return"";const g=Zo(d);if(this._hashName){const w=this._hashName;let A=!1;const I=location.hash.slice(1).split("&").map(L=>{const F=L.split("=")[0];return F===w?(A=!0,`${F}=${g}`):L}).filter(L=>L);return A||I.push(`${w}=${g}`),`#${I.join("&")}`}return`#${g}`}_getCurrentHash(){const d=location.hash.replace("#","");if(this._hashName){let g;return d.split("&").map(w=>w.split("=")).forEach(w=>{w[0]===this._hashName&&(g=w)}),(g&&g[1]||"").split("/")}return d.split("/")}_onHashChange(){const d=this._map;if(!d)return!1;const g=this._getCurrentHash();if(g.length>=3&&!g.some(w=>isNaN(Number(w)))){const w=d.dragRotate.isEnabled()&&d.touchZoomRotate.isEnabled()?+(g[3]||0):d.getBearing();return d.jumpTo({center:[+g[2],+g[1]],zoom:+g[0],bearing:w,pitch:+(g[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function Zo(v,d){const g=v.getCenter(),w=Math.round(100*v.getZoom())/100,A=Math.ceil((w*Math.LN2+Math.log(512/360/.5))/Math.LN10),I=Math.pow(10,A),L=Math.round(g.lng*I)/I,F=Math.round(g.lat*I)/I,$=v.getBearing(),H=v.getPitch();let Y=d?`/${L}/${F}/${w}`:`${w}/${F}/${L}`;return($||H)&&(Y+="/"+Math.round(10*$)/10),H&&(Y+=`/${Math.round(H)}`),Y}const qv={linearity:.3,easing:s.eN(0,0,.3,1)},e_=Object.assign({deceleration:2500,maxSpeed:1400},qv),$3=Object.assign({deceleration:20,maxSpeed:1400},qv),$i=Object.assign({deceleration:1e3,maxSpeed:360},qv),Pn=Object.assign({deceleration:1e3,maxSpeed:90},qv);class gI{constructor(d){this._map=d,this.clear()}clear(){this._inertiaBuffer=[]}record(d){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:s.o.now(),settings:d})}_drainInertiaBuffer(){const d=this._inertiaBuffer,g=s.o.now();for(;d.length>0&&g-d[0].time>160;)d.shift()}_onMoveEnd(d){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const g={zoom:0,bearing:0,pitch:0,pan:new s.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:I}of this._inertiaBuffer)g.zoom+=I.zoomDelta||0,g.bearing+=I.bearingDelta||0,g.pitch+=I.pitchDelta||0,I.panDelta&&g.pan._add(I.panDelta),I.around&&(g.around=I.around),I.pinchAround&&(g.pinchAround=I.pinchAround);const w=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,A={};if(g.pan.mag()){const I=bd(g.pan.mag(),w,Object.assign({},e_,d||{}));A.offset=g.pan.mult(I.amount/g.pan.mag()),A.center=this._map.transform.center,ic(A,I)}if(g.zoom){const I=bd(g.zoom,w,$3);A.zoom=this._map.transform.zoom+I.amount,ic(A,I)}if(g.bearing){const I=bd(g.bearing,w,$i);A.bearing=this._map.transform.bearing+s.aC(I.amount,-179,179),ic(A,I)}if(g.pitch){const I=bd(g.pitch,w,Pn);A.pitch=this._map.transform.pitch+I.amount,ic(A,I)}if(A.zoom||A.bearing){const I=g.pinchAround===void 0?g.around:g.pinchAround;A.around=I?this._map.unproject(I):this._map.getCenter()}return this.clear(),A.noMoveStart=!0,A}}function ic(v,d){(!v.duration||v.durationg.unproject($)),F=I.reduce(($,H,Y,te)=>$.add(H.div(te.length)),new s.P(0,0));super(d,{points:I,point:F,lngLats:L,lngLat:g.unproject(F),originalEvent:w}),this._defaultPrevented=!1}}class QT extends s.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(d,g){super("wheel",{originalEvent:g}),this._defaultPrevented=!1}}class JT{constructor(d,g){this._map=d,this._clickTolerance=g.clickTolerance}reset(){this._mousedownPos=void 0}wheel(d){return this._firePreventable(new QT(this._map,d))}mousedown(d,g){return this._mousedownPos=g,this._firePreventable(new xo(d.type,this._map,d))}mouseup(d){this._map.fire(new xo(d.type,this._map,d))}preclick(d){const g=new MouseEvent("preclick",d);this._map.fire(new xo(g.type,this._map,g))}click(d,g){this._mousedownPos&&this._mousedownPos.dist(g)>=this._clickTolerance||(this.preclick(d),this._map.fire(new xo(d.type,this._map,d)))}dblclick(d){return this._firePreventable(new xo(d.type,this._map,d))}mouseover(d){this._map.fire(new xo(d.type,this._map,d))}mouseout(d){this._map.fire(new xo(d.type,this._map,d))}touchstart(d){return this._firePreventable(new Tc(d.type,this._map,d))}touchmove(d){this._map.fire(new Tc(d.type,this._map,d))}touchend(d){this._map.fire(new Tc(d.type,this._map,d))}touchcancel(d){this._map.fire(new Tc(d.type,this._map,d))}_firePreventable(d){if(this._map.fire(d),d.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class eE{constructor(d){this._map=d}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(d){this._map.fire(new xo(d.type,this._map,d))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new xo("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(d){this._delayContextMenu?this._contextMenuEvent=d:this._map.fire(new xo(d.type,this._map,d)),this._map.listens("contextmenu")&&d.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class tE{constructor(d,g){this._map=d,this._el=d.getCanvasContainer(),this._container=d.getContainer(),this._clickTolerance=g.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(d,g){this.isEnabled()&&d.shiftKey&&d.button===0&&(V(),this._startPos=this._lastPos=g,this._active=!0)}mousemoveWindow(d,g){if(!this._active)return;const w=g,A=this._startPos,I=this._lastPos;if(!A||!I||I.equals(w)||!this._box&&w.dist(A){this._box&&(this._box.style.transform=`translate(${L}px,${$}px)`,this._box.style.width=F-L+"px",this._box.style.height=H-$+"px")})}mouseupWindow(d,g){if(!this._active)return;const w=this._startPos,A=g;if(w&&d.button===0){if(this.reset(),X(),w.x!==A.x||w.y!==A.y)return this._map.fire(new s.C("boxzoomend",{originalEvent:d})),{cameraAnimation:I=>I.fitScreenCoordinates(w,A,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",d)}}keydown(d){this._active&&d.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",d))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),G(),delete this._startPos,delete this._lastPos}_fireEvent(d,g){return this._map.fire(new s.C(d,{originalEvent:g}))}}function t_(v,d){const g={};for(let w=0;wthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=d.timeStamp),w.length===this.numTouches&&(this.centroid=function(A){const I=new s.P(0,0);for(const L of A)I._add(L);return I.div(A.length)}(g),this.touches=t_(w,g)))}touchmove(d,g,w){if(this.aborted||!this.centroid)return;const A=t_(w,g);for(const I in this.touches){const L=A[I];(!L||L.dist(this.touches[I])>30)&&(this.aborted=!0)}}touchend(d,g,w){if((!this.centroid||d.timeStamp-this.startTime>500)&&(this.aborted=!0),w.length===0){const A=!this.aborted&&this.centroid;if(this.reset(),A)return A}}}class wd{constructor(d){this.singleTap=new lu(d),this.numTaps=d.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(d,g,w){this.singleTap.touchstart(d,g,w)}touchmove(d,g,w){this.singleTap.touchmove(d,g,w)}touchend(d,g,w){const A=this.singleTap.touchend(d,g,w);if(A){const I=d.timeStamp-this.lastTime<500,L=!this.lastTap||this.lastTap.dist(A)<30;if(I&&L||this.reset(),this.count++,this.lastTime=d.timeStamp,this.lastTap=A,this.count===this.numTaps)return this.reset(),A}}}class vg{constructor(){this._zoomIn=new wd({numTouches:1,numTaps:2}),this._zoomOut=new wd({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(d,g,w){this._zoomIn.touchstart(d,g,w),this._zoomOut.touchstart(d,g,w)}touchmove(d,g,w){this._zoomIn.touchmove(d,g,w),this._zoomOut.touchmove(d,g,w)}touchend(d,g,w){const A=this._zoomIn.touchend(d,g,w),I=this._zoomOut.touchend(d,g,w);return A?(this._active=!0,d.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:L=>L.easeTo({duration:300,zoom:L.getZoom()+1,around:L.unproject(A)},{originalEvent:d})}):I?(this._active=!0,d.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:L=>L.easeTo({duration:300,zoom:L.getZoom()-1,around:L.unproject(I)},{originalEvent:d})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const Gv=0,rE=2,nE={[Gv]:1,[rE]:2},mh={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class r_{constructor(d){this.reset(),this._clickTolerance=d.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(d,g){return!1}_move(d,g){return{}}mousedown(d,g){if(this._lastPoint)return;const w=se(d);this._correctButton(d,w)&&(this._lastPoint=g,this._eventButton=w)}mousemoveWindow(d,g){const w=this._lastPoint;if(w){if(d.preventDefault(),this._eventButton!=null&&function(A,I){const L=nE[I];return A.buttons===void 0||(A.buttons&L)!==L}(d,this._eventButton))this.reset();else if(this._moved||!(g.dist(w)0&&(this._active=!0);const A=t_(w,g),I=new s.P(0,0),L=new s.P(0,0);let F=0;for(const H in A){const Y=A[H],te=this._touches[H];te&&(I._add(Y),L._add(Y.sub(te)),F++,A[H]=Y)}if(this._touches=A,F{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class i_{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(d){}_move(d,g,w){return{}}touchstart(d,g,w){this._firstTwoTouches||w.length<2||(this._firstTwoTouches=[w[0].identifier,w[1].identifier],this._start([g[0],g[1]]))}touchmove(d,g,w){const A=this._firstTwoTouches;if(!A)return;d.preventDefault();const[I,L]=A,F=_s(w,g,I),$=_s(w,g,L);if(!F||!$)return;const H=this._aroundCenter?null:F.add($).div(2);return this._move([F,$],H,d)}touchend(d,g,w){if(!this._firstTwoTouches)return;const[A,I]=this._firstTwoTouches,L=_s(w,g,A),F=_s(w,g,I);L&&F||(this._active&&X(),this.reset())}touchcancel(){this.reset()}enable(d){this._enabled=!0,this._aroundCenter=!!d&&d.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function _s(v,d,g){for(let w=0;wMath.abs(v.x)}class aE extends i_{constructor(d){super(),this._map=d}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(d){this._lastPoints=d,s_(d[0].sub(d[1]))&&(this._valid=!1)}_move(d,g,w){const A=this._lastPoints;if(!A)return;const I=d[0].sub(A[0]),L=d[1].sub(A[1]);return this._map._cooperativeGestures&&!s.eO()&&w.touches.length<3||(this._valid=this.gestureBeginsVertically(I,L,w.timeStamp),!this._valid)?void 0:(this._lastPoints=d,this._active=!0,{pitchDelta:(I.y+L.y)/2*-.5})}gestureBeginsVertically(d,g,w){if(this._valid!==void 0)return this._valid;const A=d.mag()>=2,I=g.mag()>=2;if(!A&&!I)return;if(!A||!I)return this._firstMove==null&&(this._firstMove=w),w-this._firstMove<100&&void 0;const L=d.y>0==g.y>0;return s_(d)&&s_(g)&&L}}const oE={panStep:100,bearingStep:15,pitchStep:10};class Op{constructor(){const d=oE;this._panStep=d.panStep,this._bearingStep=d.bearingStep,this._pitchStep=d.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(d){if(d.altKey||d.ctrlKey||d.metaKey)return;let g=0,w=0,A=0,I=0,L=0;switch(d.keyCode){case 61:case 107:case 171:case 187:g=1;break;case 189:case 109:case 173:g=-1;break;case 37:d.shiftKey?w=-1:(d.preventDefault(),I=-1);break;case 39:d.shiftKey?w=1:(d.preventDefault(),I=1);break;case 38:d.shiftKey?A=1:(d.preventDefault(),L=-1);break;case 40:d.shiftKey?A=-1:(d.preventDefault(),L=1);break;default:return}return this._rotationDisabled&&(w=0,A=0),{cameraAnimation:F=>{const $=F.getZoom();F.easeTo({duration:300,easeId:"keyboardHandler",easing:lE,zoom:g?Math.round($)+g*(d.shiftKey?2:1):$,bearing:F.getBearing()+w*this._bearingStep,pitch:F.getPitch()+A*this._pitchStep,offset:[-I*this._panStep,-L*this._panStep],center:F.getCenter()},{originalEvent:d})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function lE(v){return v*(2-v)}const Mp=4.000244140625,cE=1/450;class Yv{constructor(d,g){this._map=d,this._el=d.getCanvasContainer(),this._handler=g,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=cE,s.aZ(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(d){this._defaultZoomRate=d}setWheelZoomRate(d){this._wheelZoomRate=d}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(d){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!d&&d.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(d){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(d.ctrlKey||d.metaKey||this.isZooming()||s.eO()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let g=d.deltaMode===WheelEvent.DOM_DELTA_LINE?40*d.deltaY:d.deltaY;const w=s.o.now(),A=w-(this._lastWheelEventTime||0);this._lastWheelEventTime=w,g!==0&&g%Mp===0?this._type="wheel":g!==0&&Math.abs(g)<4?this._type="trackpad":A>400?(this._type=null,this._lastValue=g,this._timeout=window.setTimeout(this._onTimeout,40,d)):this._type||(this._type=Math.abs(A*g)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,g+=this._lastValue)),d.shiftKey&&g&&(g/=4),this._type&&(this._lastWheelEvent=d,this._delta-=g,this._active||this._start(d)),d.preventDefault()}_onTimeout(d){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(d)}_start(d){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 g=Q(this._el,d);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:g,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 d=this._map.transform;this._type==="wheel"&&d.projection.wrap&&(d._center.lng>=180||d._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const g=()=>d._terrainEnabled()&&this._aroundCoord?d.computeZoomRelativeTo(this._aroundCoord):d.zoom;if(this._delta!==0){const H=this._type==="wheel"&&Math.abs(this._delta)>Mp?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=g(),ee=Math.pow(2,te),ie=typeof this._targetZoom=="number"?d.zoomScale(this._targetZoom):ee;this._targetZoom=Math.min(d.maxZoom,Math.max(d.minZoom,d.scaleZoom(ie*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:g(),A=this._startZoom,I=this._easing;let L,F=!1;if(this._type==="wheel"&&A&&I){const H=Math.min((s.o.now()-this._lastWheelEventTime)/200,1),Y=I(H);L=s.am(A,w,Y),H<1?this._frameId||(this._frameId=!0):F=!0}else L=w,F=!0;this._active=!0,F&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let $=L-g();return $*this._lastDelta<0&&($=0),{noInertia:!0,needsRenderFrame:!F,zoomDelta:$,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(d){let g=s.eP;if(this._prevEase){const w=this._prevEase,A=(s.o.now()-w.start)/w.duration,I=w.easing(A+.01)-w.easing(A),L=.27/Math.sqrt(I*I+1e-4)*.01,F=Math.sqrt(.0729-L*L);g=s.eN(L,F,.25,1)}return this._prevEase={start:s.o.now(),duration:d,easing:g},g}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=N("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=/(Mac|iPad)/i.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 Zv{constructor(d,g){this._clickZoom=d,this._tapZoom=g}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 Xv{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(d,g){return d.preventDefault(),{cameraAnimation:w=>{w.easeTo({duration:300,zoom:w.getZoom()+(d.shiftKey?-1:1),around:w.unproject(g)},{originalEvent:d})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class yI{constructor(){this._tap=new wd({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(d,g,w){this._swipePoint||(this._tapTime&&d.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?w.length>0&&(this._swipePoint=g[0],this._swipeTouch=w[0].identifier):this._tap.touchstart(d,g,w))}touchmove(d,g,w){if(this._tapTime){if(this._swipePoint){if(w[0].identifier!==this._swipeTouch)return;const A=g[0],I=A.y-this._swipePoint.y;return this._swipePoint=A,d.preventDefault(),this._active=!0,{zoomDelta:I/128}}}else this._tap.touchmove(d,g,w)}touchend(d,g,w){this._tapTime?this._swipePoint&&w.length===0&&this.reset():this._tap.touchend(d,g,w)&&(this._tapTime=d.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class uE{constructor(d,g,w){this._el=d,this._mousePan=g,this._touchPan=w}enable(d){this._inertiaOptions=d||{},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 xI{constructor(d,g,w){this._pitchWithRotate=d.pitchWithRotate,this._mouseRotate=g,this._mousePitch=w}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class _I{constructor(d,g,w,A){this._el=d,this._touchZoom=g,this._touchRotate=w,this._tapDragZoom=A,this._rotationDisabled=!1,this._enabled=!0}enable(d){this._touchZoom.enable(d),this._rotationDisabled||this._touchRotate.enable(d),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._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()}}const a_=v=>v.zoom||v.drag||v.pitch||v.rotate;class vI extends s.C{}class bI{constructor(){this.constants=[1,1,.01],this.radius=0}setup(d,g){const w=s.ax([],g,d);this.radius=s.ai(w[2]<0?s.eR([],w,this.constants):[w[0],w[1],0])}projectRay(d){s.eR(d,d,this.constants),s.ay(d,d),s.eS(d,d,this.constants);const g=s.bJ([],d,this.radius);if(g[2]>0){const w=s.bJ([],[0,0,1],s.bi(g,[0,0,1])),A=s.bJ([],s.ay([],[g[0],g[1],0]),this.radius),I=s.cT([],g,s.bJ([],s.ax([],s.cT([],A,w),g),2));g[0]=I[0],g[1]=I[1]}return g}}function o_(v){return v.panDelta&&v.panDelta.mag()||v.zoomDelta||v.bearingDelta||v.pitchDelta}class wI{constructor(d,g){this._map=d,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new gI(d),this._bearingSnap=g.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new bI,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(g),s.aZ(["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[A,I,L]of this._listeners){const F=A===document?this.handleWindowEvent:this.handleEvent;A.addEventListener(I,F,L)}}destroy(){for(const[d,g,w]of this._listeners){const A=d===document?this.handleWindowEvent:this.handleEvent;d.removeEventListener(g,A,w)}}_addDefaultHandlers(d){const g=this._map,w=g.getCanvasContainer();this._add("mapEvent",new JT(g,d));const A=g.boxZoom=new tE(g,d);this._add("boxZoom",A);const I=new vg,L=new Xv;g.doubleClickZoom=new Zv(L,I),this._add("tapZoom",I),this._add("clickZoom",L);const F=new yI;this._add("tapDragZoom",F);const $=g.touchPitch=new aE(g);this._add("touchPitch",$);const H=new Hv(d),Y=new n_(d);g.dragRotate=new xI(d,H,Y),this._add("mouseRotate",H,["mousePitch"]),this._add("mousePitch",Y,["mouseRotate"]);const te=new cu(d),ee=new iE(g,d);g.dragPan=new uE(w,te,ee),this._add("mousePan",te),this._add("touchPan",ee,["touchZoom","touchRotate"]);const ie=new Dp,le=new sE;g.touchZoomRotate=new _I(w,le,ie,F),this._add("touchRotate",ie,["touchPan","touchZoom"]),this._add("touchZoom",le,["touchPan","touchRotate"]),this._add("blockableMapEvent",new eE(g));const oe=g.scrollZoom=new Yv(g,this);this._add("scrollZoom",oe,["mousePan"]);const me=g.keyboard=new Op;this._add("keyboard",me);for(const pe of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])d.interactive&&d[pe]&&g[pe].enable(d[pe])}_add(d,g,w){this._handlers.push({handlerName:d,handler:g,allowed:w}),this._handlersById[d]=g}stop(d){if(!this._updatingCamera){for(const{handler:g}of this._handlers)g.reset();this._inertia.clear(),this._fireEvents({},{},d),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:d}of this._handlers)if(d.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!a_(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(d,g,w){for(const A in d)if(A!==w&&(!g||g.indexOf(A)<0))return!0;return!1}handleWindowEvent(d){this.handleEvent(d,`${d.type}Window`)}_getMapTouches(d){const g=[];for(const w of d)this._el.contains(w.target)&&g.push(w);return g}handleEvent(d,g){this._updatingCamera=!0;const w=d.type==="renderFrame",A=w?void 0:d,I={needsRenderFrame:!1},L={},F={},$=d.touches?this._getMapTouches(d.touches):void 0,H=$?re(this._el,$):w?void 0:Q(this._el,d);for(const{handlerName:ee,handler:ie,allowed:le}of this._handlers){if(!ie.isEnabled())continue;let oe;this._blockedByActive(F,le,ee)?ie.reset():ie[g||d.type]&&(oe=ie[g||d.type](d,H,$),this.mergeHandlerResult(I,L,oe,ee,A),oe&&oe.needsRenderFrame&&this._triggerRenderFrame()),(oe||ie.isActive())&&(F[ee]=ie)}const Y={};for(const ee in this._previousActiveHandlers)F[ee]||(Y[ee]=A);this._previousActiveHandlers=F,(Object.keys(Y).length||o_(I))&&(this._changes.push([I,L,Y]),this._triggerRenderFrame()),(Object.keys(F).length||o_(I))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:te}=I;te&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],te(this._map))}mergeHandlerResult(d,g,w,A,I){if(!w)return;Object.assign(d,w);const L={handlerName:A,originalEvent:w.originalEvent||I};w.zoomDelta!==void 0&&(g.zoom=L),w.panDelta!==void 0&&(g.drag=L),w.pitchDelta!==void 0&&(g.pitch=L),w.bearingDelta!==void 0&&(g.rotate=L)}_applyChanges(){const d={},g={},w={};for(const[A,I,L]of this._changes)A.panDelta&&(d.panDelta=(d.panDelta||new s.P(0,0))._add(A.panDelta)),A.zoomDelta&&(d.zoomDelta=(d.zoomDelta||0)+A.zoomDelta),A.bearingDelta&&(d.bearingDelta=(d.bearingDelta||0)+A.bearingDelta),A.pitchDelta&&(d.pitchDelta=(d.pitchDelta||0)+A.pitchDelta),A.around!==void 0&&(d.around=A.around),A.aroundCoord!==void 0&&(d.aroundCoord=A.aroundCoord),A.pinchAround!==void 0&&(d.pinchAround=A.pinchAround),A.noInertia&&(d.noInertia=A.noInertia),Object.assign(g,I),Object.assign(w,L);this._updateMapTransform(d,g,w),this._changes=[]}_updateMapTransform(d,g,w){const A=this._map,I=A.transform,L=je=>[je.x,je.y,je.z];if((()=>{const je=this._eventsInProgress.drag;return je&&!this._handlersById[je.handlerName].isActive()})()&&!o_(d)){const je=I.zoom;I.cameraElevationReference="sea",this._originalZoom!=null&&I._orthographicProjectionAtLowPitch&&I.projection.name!=="globe"&&I.pitch===0?(I.cameraElevationReference="ground",I.zoom=this._originalZoom):(I.recenterOnTerrain(),I.cameraElevationReference="ground"),je!==I.zoom&&this._map._update(!0)}if(I._isCameraConstrained&&A._stop(!0),!o_(d))return void this._fireEvents(g,w,!0);let{panDelta:F,zoomDelta:$,bearingDelta:H,pitchDelta:Y,around:te,aroundCoord:ee,pinchAround:ie}=d;I._isCameraConstrained&&($>0&&($=0),I._isCameraConstrained=!1),ie!==void 0&&(te=ie),($||(je=>g[je]&&!this._eventsInProgress[je])("drag"))&&te&&(this._dragOrigin=L(I.pointCoordinate3D(te)),this._originalZoom=I.zoom,this._trackingEllipsoid.setup(I._camera.position,this._dragOrigin)),I.cameraElevationReference="sea",A._stop(!0),te=te||A.transform.centerPoint,H&&(I.bearing+=H),Y&&(I.pitch+=Y),I._updateCameraState();const le=[0,0,0];if(F)if(I.projection.name==="mercator"){const je=this._trackingEllipsoid.projectRay(I.screenPointToMercatorRay(te).dir),Re=this._trackingEllipsoid.projectRay(I.screenPointToMercatorRay(te.sub(F)).dir);le[0]=Re[0]-je[0],le[1]=Re[1]-je[1]}else{const je=I.pointCoordinate(te);if(I.projection.name==="globe"){F=F.rotate(-I.angle);const Re=I._pixelsPerMercatorPixel/I.worldSize;le[0]=-F.x*s.eQ(s.bV(je.y))*Re,le[1]=-F.y*s.eQ(I.center.lat)*Re}else{const Re=I.pointCoordinate(te.sub(F));je&&Re&&(le[0]=Re.x-je.x,le[1]=Re.y-je.y)}}const oe=I.zoom,me=[0,0,0];if($){const je=L(ee||I.pointCoordinate3D(te)),Re={dir:s.ay([],s.ax([],je,I._camera.position))};if(Re.dir[2]<0){const xe=I.zoomDeltaToMovement(je,$);s.bJ(me,Re.dir,xe)}}const pe=s.cT(le,le,me);I._translateCameraConstrained(pe),$&&Math.abs(I.zoom-oe)>1e-4&&I.recenterOnTerrain(),I.cameraElevationReference="ground",this._map._update(),d.noInertia||this._inertia.record(d),this._fireEvents(g,w,!0)}_fireEvents(d,g,w){const A=a_(this._eventsInProgress),I=a_(d),L={};for(const Y in d){const{originalEvent:te}=d[Y];this._eventsInProgress[Y]||(L[`${Y}start`]=te),this._eventsInProgress[Y]=d[Y]}!A&&I&&this._fireEvent("movestart",I.originalEvent);for(const Y in L)this._fireEvent(Y,L[Y]);I&&this._fireEvent("move",I.originalEvent);for(const Y in d){const{originalEvent:te}=d[Y];this._fireEvent(Y,te)}const F={};let $;for(const Y in this._eventsInProgress){const{handlerName:te,originalEvent:ee}=this._eventsInProgress[Y];this._handlersById[te].isActive()||(delete this._eventsInProgress[Y],$=g[te]||ee,F[`${Y}end`]=$)}for(const Y in F)this._fireEvent(Y,F[Y]);const H=a_(this._eventsInProgress);if(w&&(A||I)&&!H){this._updatingCamera=!0;const Y=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),te=ee=>ee!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new vI("renderFrame",{timeStamp:d})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const dE="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class SI extends s.E{constructor(d,g){super(),this._moving=!1,this._zooming=!1,this.transform=d,this._bearingSnap=g.bearingSnap,this._respectPrefersReducedMotion=g.respectPrefersReducedMotion!==!1,s.aZ(["_renderFrameCallback"],this)}getCenter(){return new s.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(d,g){return this.jumpTo({center:d},g)}panBy(d,g,w){return d=s.P.convert(d).mult(-1),this.panTo(this.transform.center,Object.assign({offset:d},g),w)}panTo(d,g,w){return this.easeTo(Object.assign({center:d},g),w)}getZoom(){return this.transform.zoom}setZoom(d,g){return this.jumpTo({zoom:d},g),this}zoomTo(d,g,w){return this.easeTo(Object.assign({zoom:d},g),w)}zoomIn(d,g){return this.zoomTo(this.getZoom()+1,d,g),this}zoomOut(d,g){return this.zoomTo(this.getZoom()-1,d,g),this}getBearing(){return this.transform.bearing}setBearing(d,g){return this.jumpTo({bearing:d},g),this}getPadding(){return this.transform.padding}setPadding(d,g){return this.jumpTo({padding:d},g),this}rotateTo(d,g,w){return this.easeTo(Object.assign({bearing:d},g),w)}resetNorth(d,g){return this.rotateTo(0,Object.assign({duration:1e3},d),g),this}resetNorthPitch(d,g){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},d),g),this}snapToNorth(d,g){return Math.abs(this.getBearing())d.aspect?w/(2*Math.tan(.5*d.fovX)*d.aspect):A/(2*Math.tan(.5*d.fovY)*d.aspect)}_cameraForBoundsOnGlobe(d,g,w,A,I,L){const F=d.clone(),$=this._extendCameraOptions(L);F.bearing=A,F.pitch=I;const H=s.aU.convert(g),Y=s.aU.convert(w),te=.5*(H.lat+Y.lat),ee=.5*(H.lng+Y.lng),ie=s.eT(te,ee),le=s.ay([],ie),oe=s.ay([],s.bh([],le,[0,1,0])),me=s.bh([],oe,le),pe=[oe[0],oe[1],oe[2],0,me[0],me[1],me[2],0,le[0],le[1],le[2],0,0,0,0,1],je=[ie,s.eT(H.lat,H.lng),s.eT(Y.lat,H.lng),s.eT(Y.lat,Y.lng),s.eT(H.lat,Y.lng),s.eT(te,H.lng),s.eT(te,Y.lng),s.eT(H.lat,ee),s.eT(Y.lat,ee)];let Re=s.cU.fromPoints(je.map(vt=>[s.bi(oe,vt),s.bi(me,vt),s.bi(le,vt)]));const xe=s.ah([],Re.center,pe);s.eU(xe)===0&&s.eV(xe,0,0,1),s.ay(xe,xe),s.bJ(xe,xe,s.aF),F.center=s.eW(xe);const Ze=F.getWorldToCameraMatrix(),ze=s.b7(new Float64Array(16),Ze);Re=s.cU.applyTransform(Re,s.aD([],Ze,pe));const Ke=this._extendAABB(Re,F,$,A);if(!Ke)return void s.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Re=Ke,s.ah(xe,xe,Ze);const De=.5*(Re.max[2]-Re.min[2]),Fe=this._minimumAABBFrustumDistance(F,Re),qe=s.bJ([],[0,0,1],De),st=s.cT(qe,xe,qe),Qe=Fe+(F.pitch===0?0:s.bf(xe,st)),xt=F.globeCenterInViewSpace,ft=s.ax([],xe,[xt[0],xt[1],xt[2]]);s.ay(ft,ft),s.bJ(ft,ft,Qe);const Rt=s.cT([],xe,ft);s.ah(Rt,Rt,ze);const Ft=s.eD/s.aF,ot=s.ai(Rt),et=s.bU(Math.max(ot*Ft-s.eD,Number.EPSILON),0),gt=Math.min(F.zoomFromMercatorZAdjusted(et),$.maxZoom);return gt>.5*(s.cJ+s.cv)?(F.setProjection({name:"mercator"}),F.zoom=gt,this._cameraForBounds(F,g,w,A,I,L)):{center:F.center,zoom:gt,bearing:A,pitch:I}}_extendAABB(d,g,w,A){const I=.5*((w.padding.left||0)+(w.padding.right||0)),L=.5*((w.padding.top||0)+(w.padding.bottom||0)),F=L,$=I,H=I,Y=L,te=g.width-($+H),ee=g.height-(F+Y),ie=s.ax([],d.max,d.min),le=Math.min(te/ie[0],ee/ie[1]),oe=Math.min(g.scaleZoom(g.scale*le),w.maxZoom);if(isNaN(oe))return null;const me=g.scale/g.zoomScale(oe),pe=new s.cU([d.min[0]-$*me,d.min[1]-Y*me,d.min[2]],[d.max[0]+H*me,d.max[1]+F*me,d.max[2]]),je=(typeof w.offset.x=="number"&&typeof w.offset.y=="number"?new s.P(w.offset.x,w.offset.y):s.P.convert(w.offset)).rotate(-s.ap(A));return pe.center[0]-=je.x*me,pe.center[1]+=je.y*me,pe}queryTerrainElevation(d,g){const w=this.transform.elevation;return w?(g=Object.assign({},{exaggerated:!0},g),w.getAtPoint(s.ag.fromLngLat(d),null,g.exaggerated)):null}_cameraForBounds(d,g,w,A,I,L){if(d.projection.name==="globe")return this._cameraForBoundsOnGlobe(d,g,w,A,I,L);const F=d.clone(),$=this._extendCameraOptions(L);F.bearing=A,F.pitch=I;const H=s.aU.convert(g),Y=s.aU.convert(w),te=new s.aU(H.lng,Y.lat),ee=new s.aU(Y.lng,H.lat),ie=F.project(H),le=F.project(Y),oe=this.queryTerrainElevation(H),me=this.queryTerrainElevation(Y),pe=this.queryTerrainElevation(te),je=this.queryTerrainElevation(ee),Re=[[ie.x,ie.y,Math.min(oe||0,me||0,pe||0,je||0)],[le.x,le.y,Math.max(oe||0,me||0,pe||0,je||0)]];let xe=s.cU.fromPoints(Re);const Ze=F.getWorldToCameraMatrix(),ze=s.b7(new Float64Array(16),Ze);xe=s.cU.applyTransform(xe,Ze);const Ke=this._extendAABB(xe,F,$,A);if(!Ke)return void s.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");xe=Ke;const De=.5*s.ax([],xe.max,xe.min)[2],Fe=this._minimumAABBFrustumDistance(F,xe),qe=[0,0,1,0];s.aE(qe,qe,Ze),s.eX(qe,qe);const st=s.bJ([],qe,Fe+De),Qe=s.cT([],xe.center,st);s.ah(xe.center,xe.center,ze),s.ah(Qe,Qe,ze);const xt=F.unproject(new s.P(xe.center[0],xe.center[1])),ft=s.eY(F.projection,xt),Rt=Math.pow(2,ft),Ft=Math.min(F._zoomFromMercatorZ(Qe[2]*F.pixelsPerMeter*Rt/F.worldSize),$.maxZoom);return F.mercatorFromTransition&&Ft<.5*(s.cJ+s.cv)?(F.setProjection({name:"globe"}),F.zoom=Ft,this._cameraForBounds(F,g,w,A,I,L)):{center:xt,zoom:Ft,bearing:A,pitch:I}}fitBounds(d,g,w){const A=this.cameraForBounds(d,g);return this._fitInternal(A,g,w)}fitScreenCoordinates(d,g,w,A,I){const L=s.P.convert(d),F=s.P.convert(g),$=new s.P(Math.min(L.x,F.x),Math.min(L.y,F.y)),H=new s.P(Math.max(L.x,F.x),Math.max(L.y,F.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(L,F))return this;const Y=this.transform.pointLocation3D($),te=this.transform.pointLocation3D(H),ee=this.transform.pointLocation3D(new s.P($.x,H.y)),ie=this.transform.pointLocation3D(new s.P(H.x,$.y)),le=[Math.min(Y.lng,te.lng,ee.lng,ie.lng),Math.min(Y.lat,te.lat,ee.lat,ie.lat)],oe=[Math.max(Y.lng,te.lng,ee.lng,ie.lng),Math.max(Y.lat,te.lat,ee.lat,ie.lat)],me=A&&A.pitch?A.pitch:this.getPitch(),pe=this._cameraForBounds(this.transform,le,oe,w,me,A);return this._fitInternal(pe,A,I)}_fitInternal(d,g,w){return d?(g=Object.assign(d,g)).linear?this.easeTo(g,w):this.flyTo(g,w):this}jumpTo(d,g){this.stop();const w=d.preloadOnly?this.transform.clone():this.transform;let A=!1,I=!1,L=!1;"zoom"in d&&w.zoom!==+d.zoom&&(A=!0,w.zoom=+d.zoom),d.center!==void 0&&(w.center=s.aU.convert(d.center)),"bearing"in d&&w.bearing!==+d.bearing&&(I=!0,w.bearing=+d.bearing),"pitch"in d&&w.pitch!==+d.pitch&&(L=!0,w.pitch=+d.pitch);const F=typeof d.padding=="number"?this._extendPadding(d.padding):d.padding;if(d.padding!=null&&!w.isPaddingEqual(F))if(d.retainPadding===!1){const $=w.clone();$.padding=F,w.setLocationAtPoint(w.center,$.centerPoint)}else w.padding=F;return d.preloadOnly?(this._preloadTiles(w),this):(this.fire(new s.C("movestart",g)).fire(new s.C("move",g)),A&&this.fire(new s.C("zoomstart",g)).fire(new s.C("zoom",g)).fire(new s.C("zoomend",g)),I&&this.fire(new s.C("rotatestart",g)).fire(new s.C("rotate",g)).fire(new s.C("rotateend",g)),L&&this.fire(new s.C("pitchstart",g)).fire(new s.C("pitch",g)).fire(new s.C("pitchend",g)),this.fire(new s.C("moveend",g)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||s.w(dE),this.transform.getFreeCameraOptions()}setFreeCameraOptions(d,g){const w=this.transform;if(!w.projection.supportsFreeCamera)return s.w(dE),this;this.stop();const A=w.zoom,I=w.pitch,L=w.bearing;w.setFreeCameraOptions(d);const F=A!==w.zoom,$=I!==w.pitch,H=L!==w.bearing;return this.fire(new s.C("movestart",g)).fire(new s.C("move",g)),F&&this.fire(new s.C("zoomstart",g)).fire(new s.C("zoom",g)).fire(new s.C("zoomend",g)),H&&this.fire(new s.C("rotatestart",g)).fire(new s.C("rotate",g)).fire(new s.C("rotateend",g)),$&&this.fire(new s.C("pitchstart",g)).fire(new s.C("pitch",g)).fire(new s.C("pitchend",g)),this.fire(new s.C("moveend",g)),this}easeTo(d,g){this._stop(!1,d.easeId),((d=Object.assign({offset:[0,0],duration:500,easing:s.eP},d)).animate===!1||this._prefersReducedMotion(d))&&(d.duration=0);const w=this.transform,A=this.getZoom(),I=this.getBearing(),L=this.getPitch(),F=this.getPadding(),$="zoom"in d?+d.zoom:A,H="bearing"in d?this._normalizeBearing(d.bearing,I):I,Y="pitch"in d?+d.pitch:L,te=this._extendPadding(d.padding),ee=s.P.convert(d.offset);let ie,le,oe;if(w.projection.name==="globe"){const qe=s.ag.fromLngLat(w.center),st=ee.rotate(-w.angle);qe.x+=st.x/w.worldSize,qe.y+=st.y/w.worldSize;const Qe=qe.toLngLat(),xt=s.aU.convert(d.center||Qe);this._normalizeCenter(xt),ie=w.centerPoint.add(st),le=new s.P(qe.x,qe.y).mult(w.worldSize),oe=new s.P(s.aH(xt.lng),s.aL(xt.lat)).mult(w.worldSize).sub(le)}else{ie=w.centerPoint.add(ee);const qe=w.pointLocation(ie),st=s.aU.convert(d.center||qe);this._normalizeCenter(st),le=w.project(qe),oe=w.project(st).sub(le)}const me=w.zoomScale($-A);let pe,je;d.around&&(pe=s.aU.convert(d.around),je=w.locationPoint(pe));const Re=this._zooming||$!==A,xe=this._rotating||I!==H,Ze=this._pitching||Y!==L,ze=!w.isPaddingEqual(te),Ke=d.retainPadding===!1?w.clone():w,De=qe=>st=>{if(Re&&(qe.zoom=s.am(A,$,st)),xe&&(qe.bearing=s.am(I,H,st)),Ze&&(qe.pitch=s.am(L,Y,st)),ze&&(Ke.interpolatePadding(F,te,st),ie=Ke.centerPoint.add(ee)),pe)qe.setLocationAtPoint(pe,je);else{const Qe=qe.zoomScale(qe.zoom-A),xt=$>A?Math.min(2,me):Math.max(.5,me),ft=Math.pow(xt,1-st),Rt=qe.unproject(le.add(oe.mult(st*ft)).mult(Qe));qe.setLocationAtPoint(qe.renderWorldCopies?Rt.wrap():Rt,ie)}return d.preloadOnly||this._fireMoveEvents(g),qe};if(d.preloadOnly){const qe=this._emulate(De,d.duration,w);return this._preloadTiles(qe),this}const Fe={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Re,this._rotating=xe,this._pitching=Ze,this._padding=ze,this._easeId=d.easeId,this._prepareEase(g,d.noMoveStart,Fe),this._ease(De(w),qe=>{w.cameraElevationReference==="sea"&&w.recenterOnTerrain(),this._afterEase(g,qe)},d),this}_prepareEase(d,g,w={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),g||w.moving||this.fire(new s.C("movestart",d)),this._zooming&&!w.zooming&&this.fire(new s.C("zoomstart",d)),this._rotating&&!w.rotating&&this.fire(new s.C("rotatestart",d)),this._pitching&&!w.pitching&&this.fire(new s.C("pitchstart",d))}_fireMoveEvents(d){this.fire(new s.C("move",d)),this._zooming&&this.fire(new s.C("zoom",d)),this._rotating&&this.fire(new s.C("rotate",d)),this._pitching&&this.fire(new s.C("pitch",d))}_afterEase(d,g){if(this._easeId&&g&&this._easeId===g)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const w=this._zooming,A=this._rotating,I=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,w&&this.fire(new s.C("zoomend",d)),A&&this.fire(new s.C("rotateend",d)),I&&this.fire(new s.C("pitchend",d)),this.fire(new s.C("moveend",d))}flyTo(d,g){if(this._prefersReducedMotion(d)){const vt=s.aJ(d,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(vt,g)}this.stop(),d=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:s.eP},d);const w=this.transform,A=this.getZoom(),I=this.getBearing(),L=this.getPitch(),F=this.getPadding(),$="zoom"in d?s.aC(+d.zoom,w.minZoom,w.maxZoom):A,H="bearing"in d?this._normalizeBearing(d.bearing,I):I,Y="pitch"in d?+d.pitch:L,te=this._extendPadding(d.padding),ee=w.zoomScale($-A),ie=s.P.convert(d.offset);let le=w.centerPoint.add(ie);const oe=w.pointLocation(le),me=s.aU.convert(d.center||oe);this._normalizeCenter(me);const pe=w.project(oe),je=w.project(me).sub(pe);let Re=d.curve;const xe=Math.max(w.width,w.height),Ze=xe/ee,ze=je.mag();if("minZoom"in d){const vt=s.aC(Math.min(d.minZoom,A,$),w.minZoom,w.maxZoom),St=xe/w.zoomScale(vt-A);Re=Math.sqrt(St/ze*2)}const Ke=Re*Re;function De(vt){const St=(Ze*Ze-xe*xe+(vt?-1:1)*Ke*Ke*ze*ze)/(2*(vt?Ze:xe)*Ke*ze);return Math.log(Math.sqrt(St*St+1)-St)}function Fe(vt){return(Math.exp(vt)-Math.exp(-vt))/2}function qe(vt){return(Math.exp(vt)+Math.exp(-vt))/2}const st=De(0);let Qe=function(vt){return qe(st)/qe(st+Re*vt)},xt=function(vt){return xe*((qe(st)*(Fe(St=st+Re*vt)/qe(St))-Fe(st))/Ke)/ze;var St},ft=(De(1)-st)/Re;if(Math.abs(ze)<1e-6||!isFinite(ft)){if(Math.abs(xe-Ze)<1e-6)return this.easeTo(d,g);const vt=Zed.maxDuration&&(d.duration=0);const Rt=I!==H,Ft=Y!==L,ot=!w.isPaddingEqual(te),et=d.retainPadding===!1?w.clone():w,gt=vt=>St=>{const rr=St*ft,Gt=1/Qe(rr);vt.zoom=St===1?$:A+vt.scaleZoom(Gt),Rt&&(vt.bearing=s.am(I,H,St)),Ft&&(vt.pitch=s.am(L,Y,St)),ot&&(et.interpolatePadding(F,te,St),le=et.centerPoint.add(ie));const Ht=St===1?me:vt.unproject(pe.add(je.mult(xt(rr))).mult(Gt));return vt.setLocationAtPoint(vt.renderWorldCopies?Ht.wrap():Ht,le),vt._updateCameraOnTerrain(),d.preloadOnly||this._fireMoveEvents(g),vt};if(d.preloadOnly){const vt=this._emulate(gt,d.duration,w);return this._preloadTiles(vt),this}return this._zooming=!0,this._rotating=Rt,this._pitching=Ft,this._padding=ot,this._prepareEase(g,!1),this._ease(gt(w),()=>this._afterEase(g),d),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(d){}_cancelRenderFrame(d){}_stop(d,g){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const w=this._onEaseEnd;this._onEaseEnd=void 0,w.call(this,g)}if(!d){const w=this.handlers;w&&w.stop(!1)}return this}_ease(d,g,w){w.animate===!1||w.duration===0?(d(1),g()):(this._easeStart=s.o.now(),this._easeOptions=w,this._onEaseFrame=d,this._onEaseEnd=g,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const d=Math.min((s.o.now()-this._easeStart)/this._easeOptions.duration,1),g=this._onEaseFrame;g&&g(this._easeOptions.easing(d)),d<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(d,g){d=s.bs(d,-180,180);const w=Math.abs(d-g);return Math.abs(d-360-g)180?-360:w<-180?360:0}_prefersReducedMotion(d){return this._respectPrefersReducedMotion&&s.o.prefersReducedMotion&&!(d&&d.essential)}_emulate(d,g,w){const A=Math.ceil(15*g/1e3),I=[],L=d(w.clone());for(let F=0;F<=A;F++){const $=L(F/A);I.push($.clone())}return I}_preloadTiles(d,g){}}class hE{constructor(d={}){this.options=d,s.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(d){const g=this.options&&this.options.compact,w=d._getUIString("AttributionControl.ToggleAttribution");this._map=d,this._container=N("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=N("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",w);const A=N("span","mapboxgl-ctrl-icon",this._compactButton);return A.setAttribute("aria-hidden","true"),A.setAttribute("title",w),this._innerContainer=N("div","mapboxgl-ctrl-attrib-inner",this._container),g&&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),g===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 d=this._editLink;d||(d=this._editLink=this._container.querySelector(".mapbox-improve-map"));const g=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||s.g.ACCESS_TOKEN}];if(d){const w=g.reduce((A,I,L)=>(I.value&&(A+=`${I.key}=${I.value}${LA.length-I.length),d=d.filter((A,I)=>{for(let L=I+1;L=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?d=[...this.options.customAttribution,...d]:d.unshift(this.options.customAttribution));const w=d.map(A=>function(I){const L=new DOMParser().parseFromString(I,"text/html");return Array.from(L.body.querySelectorAll("*")).reverse().forEach(F=>{const $=F.textContent||"";if(F.tagName!=="A")return void F.replaceWith(...F.childNodes);const H=F.getAttribute("href");if(!H||!/^(https?:|mailto:)/i.test(H))return void F.replaceWith(L.createTextNode($));const Y=L.createElement("a");Y.href=H,Y.textContent=$,Y.rel="noopener nofollow";const te=F.getAttribute("class");te&&(Y.className=te),F.replaceWith(Y)}),L.body.innerHTML}(A)).join(" | ");w!==this._attribHTML&&(this._attribHTML=w,d.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 fE{constructor(){s.aZ(["_updateLogo","_updateCompact"],this)}onAdd(d){this._map=d,this._container=N("div","mapboxgl-ctrl");const g=N("a","mapboxgl-ctrl-logo");return g.target="_blank",g.rel="noopener nofollow",g.href="https://www.mapbox.com/",g.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),g.setAttribute("rel","noopener nofollow"),this._container.appendChild(g),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(d){d&&d.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const d=this._map.style._sourceCaches;if(Object.entries(d).length===0)return!0;for(const g in d){const w=d[g].getSource();if(w.hasOwnProperty("mapbox_logo")&&!w.mapbox_logo)return!1}return!0}_updateCompact(){const d=this._container.children;if(d.length){const g=d[0];this._map.getCanvasContainer().offsetWidth<250?g.classList.add("mapboxgl-compact"):g.classList.remove("mapboxgl-compact")}}}class TI{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(d){const g=++this._id;return this._queue.push({callback:d,id:g,cancelled:!1}),g}remove(d){const g=this._currentlyRunning,w=g?this._queue.concat(g):this._queue;for(const A of w)if(A.id===d)return void(A.cancelled=!0)}run(d=0){const g=this._currentlyRunning=this._queue;this._queue=[];for(const w of g)if(!w.cancelled&&(w.callback(d),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class U3{constructor(d){this.jumpTo(d)}getValue(d){if(d<=this._startTime)return this._start;if(d>=this._endTime)return this._end;const g=s.dn((d-this._startTime)/(this._endTime-this._startTime));return this._start*(1-g)+this._end*g}isEasing(d){return d>=this._startTime&&d<=this._endTime}jumpTo(d){this._startTime=-1/0,this._endTime=-1/0,this._start=d,this._end=d}easeTo(d,g,w){this._start=this.getValue(g),this._end=d,this._startTime=g,this._endTime=g+w}}const V3={"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 Si extends s.C{constructor(d,g,w,A){const{point:I,lngLat:L,originalEvent:F,target:$}=d;super(d.type,{point:I,lngLat:L,originalEvent:F,target:$}),this.preventDefault=()=>{d.preventDefault()},this.id=g,this.interaction=w,this.feature=A}}class Qv{constructor(d){this.map=d,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(d,g){if(this.typeById.has(d))throw new Error(`Interaction id "${d}" already exists.`);const w=g.filter;let A=g.type;w&&this.filters.set(d,s.dg(w)),A==="mouseover"&&(A="mouseenter"),A==="mouseout"&&(A="mouseleave");const I=this.interactionsByType.get(A)||new Map;A==="mouseenter"||A==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(d,g)):I.size===0&&this.map.on(A,this.handleType),I.size===0&&this.interactionsByType.set(A,I),I.set(d,g),this.typeById.set(d,A)}get(d){const g=this.typeById.get(d);if(!g)return;const w=this.interactionsByType.get(g);return w?w.get(d):void 0}remove(d){const g=this.typeById.get(d);if(!g)return;this.typeById.delete(d),this.filters.delete(d);const w=this.interactionsByType.get(g);w&&(w.delete(d),g==="mouseenter"||g==="mouseleave"?(this.delegatedInteractions.delete(d),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):w.size===0&&this.map.off(g,this.handleType))}queryTargets(d,g){const w=[];for(const[A,I]of g)I.target&&w.push({targetId:A,target:I.target,filter:this.filters.get(A)});return this.map.style.queryRenderedTargets(d,w,this.map.transform)}handleMove(d){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const g=this.queryTargets(d.point,Array.from(this.delegatedInteractions).reverse());g.length&&(d.type="mouseenter",this.handleType(d,g));const w=new Map;for(const[A,{feature:I}]of this.prevHoveredFeatures)this.hoveredFeatures.has(A)||w.set(I.id,I);w.size&&(d.type="mouseleave",this.handleType(d,Array.from(w.values())))}handleOut(d){const g=Array.from(this.hoveredFeatures.values()).map(({feature:w})=>w);g.length&&(d.type="mouseleave",this.handleType(d,g)),this.hoveredFeatures.clear()}handleType(d,g){const w=d.type==="mouseenter";if(w&&!this.interactionsByType.has(d.type))return void s.w("mouseenter interaction required for mouseleave to work.");const A=Array.from(this.interactionsByType.get(d.type)).reverse(),I=!!g;g=g||this.queryTargets(d.point,A);let L=!1;const F=new Set;for(const $ of g){for(const[H,Y]of A){if(!Y.target)continue;const te=$.variants?$.variants[H]:null;if(te){for(const ee of te){if(gd(ee,$,F,H))continue;const ie=new s.di($,ee),le=WS(ee,$,H);I&&ie.id!==void 0&&(ie.state=this.map.getFeatureState(ie));const oe=w?this.prevHoveredFeatures.get(le):null,me=new Si(d,H,Y,ie),pe=oe?oe.stop:Y.handler(me);if(w&&this.hoveredFeatures.set(le,{feature:$,stop:pe}),pe!==!1){L=!0;break}}if(L)break}}if(L)break}if(!L)for(const[$,H]of A){const{handler:Y,target:te}=H;if(!te&&Y(new Si(d,$,H,null))!==!1)break}}}function q3(v,d){if(Array.isArray(v)&&Array.isArray(d)){const g=new Set(v),w=new Set(d);return g.size===w.size&&v.every(A=>w.has(A))}return s.b6(v,d)}const G3={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,useServerFontComposition:!0,transformRequest:null,accessToken:null,fadeDuration:300,respectPrefersReducedMotion:!0,crossSourceCollisions:!0,collectResourceTiming:!1,testMode:!1,precompilePrograms:!0,scaleFactor:1},H3={showCompass:!0,showZoom:!0,visualizePitch:!1};class l_{constructor(d,g,w=!1){this._clickTolerance=10,this.element=g,this.mouseRotate=new Hv({clickTolerance:d.dragRotate._mouseRotate._clickTolerance}),this.map=d,w&&(this.mousePitch=new n_({clickTolerance:d.dragRotate._mousePitch._clickTolerance})),s.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),g.addEventListener("mousedown",this.mousedown),g.addEventListener("touchstart",this.touchstart,{passive:!1}),g.addEventListener("touchmove",this.touchmove),g.addEventListener("touchend",this.touchend),g.addEventListener("touchcancel",this.reset)}down(d,g){this.mouseRotate.mousedown(d,g),this.mousePitch&&this.mousePitch.mousedown(d,g),V()}move(d,g){const w=this.map,A=this.mouseRotate.mousemoveWindow(d,g),I=A&&A.bearingDelta;if(I&&w.setBearing(w.getBearing()+I),this.mousePitch){const L=this.mousePitch.mousemoveWindow(d,g),F=L&&L.pitchDelta;F&&w.setPitch(w.getPitch()+F)}}off(){const d=this.element;d.removeEventListener("mousedown",this.mousedown),d.removeEventListener("touchstart",this.touchstart),d.removeEventListener("touchmove",this.touchmove),d.removeEventListener("touchend",this.touchend),d.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){G(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(d){this.down(Object.assign({},d,{button:d.button,type:d.type,ctrlKey:!0,preventDefault:()=>d.preventDefault()}),Q(this.element,d)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(d){this.move(d,Q(this.element,d))}mouseup(d){this.mouseRotate.mouseupWindow(d),this.mousePitch&&this.mousePitch.mouseupWindow(d),this.offTemp()}touchstart(d){d.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=re(this.element,d.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>d.preventDefault()},this._startPos))}touchmove(d){d.targetTouches.length!==1?this.reset():(this._lastPos=re(this.element,d.targetTouches)[0],this.move({buttons:1,preventDefault:()=>d.preventDefault()},this._lastPos))}touchend(d){d.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)g.width||d.y>g.height;g.locationPoint3D(w).distSqr(d)180;){const w=g.locationPoint3D(v);if(w.x>=0&&w.y>=0&&w.x<=g.width&&w.y<=g.height)break;v.lng>g.center.lng?v.lng-=360:v.lng+=360}return v}const c_={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%)"},Ec={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class uu extends s.E{constructor(d,g){super(),(d instanceof HTMLElement||g)&&(d=Object.assign({element:d},g)),s.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:w="center",color:A="#3FB1CE",scale:I=1,draggable:L=!1,clickTolerance:F=0,rotation:$=Ec.rotation,rotationAlignment:H=Ec.rotationAlignment,pitchAlignment:Y=Ec.pitchAlignment,occludedOpacity:te=Ec.occludedOpacity,altitude:ee=Ec.altitude}=d||{};this._anchor=w,this._color=A,this._scale=I,this._draggable=L,this._clickTolerance=F,this._rotation=$,this._rotationAlignment=H,this._pitchAlignment=Y,this._occludedOpacity=te,this._altitude=ee,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),d&&d.element?(this._element=d.element,this._offset=s.P.convert(d&&d.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=s.P.convert(d&&d.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",oe=>{oe.preventDefault()}),this._element.addEventListener("mousedown",oe=>{oe.preventDefault()});const ie=this._element.classList;for(const oe in c_)ie.remove(`mapboxgl-marker-anchor-${oe}`);ie.add(`mapboxgl-marker-anchor-${this._anchor}`);const le=d&&d.className?d.className.trim().split(/\s+/):[];ie.add(...le),this._popup=null}_createDefaultMarker(){const d=N("div"),g=R("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},d);if(this._altitude===0){const w=R("radialGradient",{id:"shadowGradient"},R("defs",{},g));R("stop",{offset:"10%","stop-opacity":.4},w),R("stop",{offset:"100%","stop-opacity":.05},w),R("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},g)}return R("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"},g),R("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"},g),R("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},g),d}addTo(d){return d===this._map||(this.remove(),this._map=d,d.getCanvasContainer().appendChild(this._element),d.on("move",this._updateMoving),d.on("moveend",this._update),d.on("remove",this._clearFadeTimer),d._addMarker(this),this.setDraggable(this._draggable),this._update(),d.on("click",this._onMapClick)),this}remove(){const d=this._map;return d&&(d.off("click",this._onMapClick),d.off("move",this._updateMoving),d.off("moveend",this._update),d.off("mousedown",this._addDragHandler),d.off("touchstart",this._addDragHandler),d.off("mouseup",this._onUp),d.off("touchend",this._onUp),d.off("mousemove",this._onMove),d.off("touchmove",this._onMove),d.off("remove",this._clearFadeTimer),d._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(d){return this._lngLat=s.aU.convert(d),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(d){return d===this._altitude||(this._defaultMarker&&(this._altitude===0&&d!==0||this._altitude!==0&&d===0)&&(this._element=this._createDefaultMarker()),this._altitude=d||Ec.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(d){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")),d){if(!("offset"in d.options)){const A=Math.sqrt(Math.pow(13.5,2)/2);d.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[A,-1*(38.1-13.5+A)],"bottom-right":[-A,-1*(38.1-13.5+A)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=d,d._marker=this,d._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(d){const g=d.code,w=d.charCode||d.keyCode;g!=="Space"&&g!=="Enter"&&w!==32&&w!==13||this.togglePopup()}_onMapClick(d){const g=d.originalEvent.target,w=this._element;this._popup&&(g===w||w.contains(g))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const d=this._popup;return d?(d.isOpen()?(d.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(d.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const d=this._map,g=this._pos;if(!d||!g)return!1;const w=d.unproject(g,this._altitude),A=d.getFreeCameraOptions();if(!A.position)return!1;const I=A.position.toLngLat();return I.distanceTo(w)<.9*I.distanceTo(this._lngLat)}_evaluateOpacity(){const d=this._map;if(!d)return;const g=this._pos;if(!g||g.x<0||g.x>d.transform.width||g.y<0||g.y>d.transform.height)return void this._clearFadeTimer();const w=d.unproject(g,this._altitude);let A;d._showingGlobe()&&s.e$(d.transform,this._lngLat)?A=0:(A=1-d._queryFogOpacity(w),d.transform._terrainEnabled()&&d.getTerrain()&&this._behindTerrain()&&(A*=this._occludedOpacity)),this._element.style.opacity=`${A}`,this._element.style.pointerEvents=A>0?"auto":"none",this._popup&&this._popup._setOpacity(A),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const d=this._pos;if(!d||!this._map)return;const g=this._offset.mult(this._scale);this._element.style.transform=` translate(${d.x}px,${d.y}px) ${c_[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${g.x}px,${g.y}px) `}_calculateXYTransform(){const d=this._pos,g=this._map,w=this.getPitchAlignment();if(!g||!d||w!=="map")return"";if(!g._showingGlobe()){const $=g.getPitch();return $?`rotateX(${$}deg)`:""}const A=s.cH(s.f0(g.transform,this._lngLat)),I=d.sub(s.f1(g.transform)),L=Math.abs(I.x)+Math.abs(I.y);if(L===0)return"";const F=A/L;return`rotateX(${-I.y*F}deg) rotateY(${I.x*F}deg)`}_calculateZTransform(){const d=this._pos,g=this._map;if(!g||!d)return"";let w=0;const A=this.getRotationAlignment();if(A==="map")if(g._showingGlobe()){const I=g.project(new s.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),L=g.project(new s.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(I);w=s.cH(Math.atan2(L.y,L.x))-90}else w=-g.getBearing();else if(A==="horizon"){const I=s.aj(4,6,g.getZoom()),L=s.f1(g.transform);L.y+=I*g.transform.height;const F=d.sub(L),$=s.cH(Math.atan2(F.y,F.x));w=($>90?$-270:$+90)*(1-I)}return w+=this._rotation,w?`rotateZ(${w}deg)`:""}_update(d){cancelAnimationFrame(this._updateFrameId);const g=this._map;g&&(g.transform.renderWorldCopies&&(this._lngLat=pE(this._lngLat,this._pos,g.transform)),this._pos=g.project(this._lngLat,this._altitude),d===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),g._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(g._showingGlobe()||g.getTerrain()||g.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(d){return this._offset=s.P.convert(d),this._update(),this}addClassName(d){return this._element.classList.add(d),this}removeClassName(d){return this._element.classList.remove(d),this}toggleClassName(d){return this._element.classList.toggle(d)}_onMove(d){const g=this._map;if(!g)return;const w=this._pointerdownPos,A=this._positionDelta;if(w&&A){if(!this._isDragging){const I=this._clickTolerance||g._clickTolerance;if(d.point.dist(w)v.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(v.minPitch!=null&&v.maxPitch!=null&&v.minPitch>v.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(v.minPitch!=null&&v.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(v.maxPitch!=null&&v.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");v.antialias&&s.eZ(window)&&(v.antialias=!1,s.w("Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609")),super(new jx(v.minZoom,v.maxZoom,v.minPitch,v.maxPitch,v.renderWorldCopies,null,null),v),this._repaint=!!v.repaint,this._interactive=v.interactive,this._minTileCacheSize=v.minTileCacheSize,this._maxTileCacheSize=v.maxTileCacheSize,this._failIfMajorPerformanceCaveat=v.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=v.preserveDrawingBuffer,this._antialias=v.antialias,this._trackResize=v.trackResize,this._bearingSnap=v.bearingSnap,this._refreshExpiredTiles=v.refreshExpiredTiles,this._fadeDuration=v.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=v.crossSourceCollisions,this._collectResourceTiming=v.collectResourceTiming,this._language=this._parseLanguage(v.language),this._worldview=v.worldview,this._renderTaskQueue=new TI,this._domRenderTaskQueue=new TI,this._controls=[],this._markers=[],this._popups=[],this._mapId=s.r(),this._locale=Object.assign({},V3,v.locale),this._clickTolerance=v.clickTolerance,this._cooperativeGestures=v.cooperativeGestures,this._performanceMetricsCollection=v.performanceMetricsCollection,this._tessellationStep=v.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=v.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new U3(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=v.scaleFactor,this._requestManager=new ve(v.transformRequest,v.accessToken,v.testMode);const g=Ne(v.accessToken||s.g.ACCESS_TOKEN);if(g&&"atlas"in g&&typeof g.atlas=="number"&&(this._tokenExpiration=g.atlas),this._silenceAuthErrors=!!v.testMode,this._contextCreateOptions=v.contextCreateOptions?Object.assign({},v.contextCreateOptions):{},typeof v.container=="string"){const w=document.getElementById(v.container);if(!w)throw new Error(`Container '${v.container.toString()}' not found.`);this._container=w}else{if(!(v.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=v.container}if(this._container.childNodes.length>0&&s.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."),v.maxBounds&&this.setMaxBounds(v.maxBounds),this._spriteFormat="auto",s.aZ(["_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 wI(this,v),this._localFontFamily=v.localFontFamily,this._localIdeographFontFamily=v.localIdeographFontFamily,this._useServerFontComposition=v.useServerFontComposition,(v.style||!v.testMode)&&this.setStyle(v.style||s.g.DEFAULT_STYLE,{config:v.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),v.projection&&this.setProjection(v.projection),v.hash&&(this._hash=new z3(typeof v.hash=="string"&&v.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){d.center==null&&d.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:v.center,zoom:v.zoom,bearing:v.bearing,pitch:v.pitch});const w=v.bounds;w&&(this.resize(),this.fitBounds(w,Object.assign({},v.fitBoundsOptions,{duration:0})))}this.resize(),v.attributionControl&&this.addControl(new hE({customAttribution:v.customAttribution})),this._logoControl=new fE,this.addControl(this._logoControl,v.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 s.C(`${w.dataType}data`,w))}),this.on("dataloading",w=>{this.fire(new s.C(`${w.dataType}dataloading`,w))}),this._interactions=new Qv(this)}_getMapId(){return this._mapId}addControl(v,d){if(d===void 0&&(d=v.getDefaultPosition?v.getDefaultPosition():"top-right"),!v||!v.onAdd)return this.fire(new s.B(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const g=v.onAdd(this);this._controls.push(v);const w=this._controlPositions[d];return d.indexOf("bottom")!==-1?w.insertBefore(g,w.firstChild):w.appendChild(g),this}removeControl(v){if(!v||!v.onRemove)return this.fire(new s.B(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const d=this._controls.indexOf(v);return d>-1&&this._controls.splice(d,1),v.onRemove(this),this}hasControl(v){return this._controls.indexOf(v)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(v){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 d=!this._moving;return d&&this.fire(new s.C("movestart",v)).fire(new s.C("move",v)),this.fire(new s.C("resize",v)),d&&this.fire(new s.C("moveend",v)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(v){return this.transform.setMaxBounds(s.aK.convert(v)),this._update()}setMinZoom(v){if((v=v??-2)>=-2&&v<=this.transform.maxZoom)return this.transform.minZoom=v,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=v,this._update(),this.getZoom()>v?this.setZoom(v):this.fire(new s.C("zoomstart")).fire(new s.C("zoom")).fire(new s.C("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(v){if((v=v??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(v>=0&&v<=this.transform.maxPitch)return this.transform.minPitch=v,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(v>=this.transform.minPitch)return this.transform.maxPitch=v,this._update(),this.getPitch()>v?this.setPitch(v):this.fire(new s.C("pitchstart")).fire(new s.C("pitch")).fire(new s.C("pitchend")),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(v){return this._scaleFactor=v,this.painter.scaleFactor=v,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(d=>d.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(v){return this.transform.renderWorldCopies=v,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(v){return v==="auto"?navigator.language:Array.isArray(v)?v.length===0?void 0:v.map(d=>d==="auto"?navigator.language:d):v}setLanguage(v){const d=this._parseLanguage(v);if(!this.style||d===this._language)return this;this._language=d,this.style.reloadSources();for(const g of this._controls)g._setLanguage&&g._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(v){return this.style&&v!==this._worldview?(this._worldview=v,this._styleDirty=!0,this.style.setWorldview(v),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(v){return this._lazyInitEmptyStyle(),v?typeof v=="string"&&(v={name:v}):v=null,this._useExplicitProjection=!!v,this._prioritizeAndUpdateProjection(v,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const v=this.transform,d=v.projection.name;let g;d==="globe"&&v.zoom>=s.cv?(v.setMercatorFromTransition(),g=!0):d==="mercator"&&v.zoom=s.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(v),this.style.applyProjectionUpdate();const w=this.transform.getProjection().name==="mercator"&&g!==this.transform.mercatorFromTransition;return(d||w)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(v,d){return this.transform.locationPoint3D(s.aU.convert(v),d)}unproject(v,d){return this.transform.pointLocation3D(s.P.convert(v),d)}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(v,d,g){const w=A=>{let I=[];if(Array.isArray(d)){const L=d.filter(F=>this.getLayer(F));I=L.length?this.queryRenderedFeatures(A,{layers:L}):[]}else I=this.queryRenderedFeatures(A,{target:d});return I};if(v==="mouseenter"||v==="mouseover"){let A=!1;return{listener:g,targets:d,delegates:{mousemove:L=>{const F=w(L.point);F.length?A||(A=!0,g.call(this,new xo(v,this,L.originalEvent,{features:F}))):A=!1},mouseout:()=>{A=!1}}}}if(v==="mouseleave"||v==="mouseout"){let A=!1;return{listener:g,targets:d,delegates:{mousemove:F=>{w(F.point).length?A=!0:A&&(A=!1,g.call(this,new xo(v,this,F.originalEvent)))},mouseout:F=>{A&&(A=!1,g.call(this,new xo(v,this,F.originalEvent)))}}}}{const A=I=>{const L=w(I.point);L.length&&(I.features=L,g.call(this,I),delete I.features)};return{listener:g,targets:d,delegates:{[v]:A}}}}on(v,d,g){if(typeof d=="function"||g===void 0)return super.on(v,d);if(typeof d=="string"&&(d=[d]),!this._areTargetsValid(d))return this;const w=this._createDelegatedListener(v,d,g);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[v]=this._delegatedListeners[v]||[],this._delegatedListeners[v].push(w);for(const A in w.delegates)this.on(A,w.delegates[A]);return this}once(v,d,g){if(typeof d=="function"||g===void 0)return super.once(v,d);if(typeof d=="string"&&(d=[d]),!this._areTargetsValid(d))return this;const w=this._createDelegatedListener(v,d,g);for(const A in w.delegates)this.once(A,w.delegates[A]);return this}off(v,d,g){if(typeof d=="function"||g===void 0)return super.off(v,d);if(typeof d=="string"&&(d=[d]),!this._areTargetsValid(d))return this;const w=this._delegatedListeners?this._delegatedListeners[v]:void 0;return w&&(A=>{for(let I=0;I{if(g){const A=typeof g=="string"?g:g instanceof Error?g.message:g.error;s.w(`Unable to perform style diff: ${A}. Rebuilding the style from scratch.`),this._updateStyle(v,d)}else w&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=d.localIdeographFontFamily,this._localFontFamily=d.localFontFamily,this._updateStyle(v,d))}_getUIString(v){const d=this._locale[v];if(d==null)throw new Error(`Missing UI string '${v}'`);return d}_updateStyle(v,d){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),v){const g=Object.assign({},d);d&&d.config&&(g.initialConfig=d.config,delete g.config),this.style=new ou(this,g).load(v),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new ou(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():(s.w("There is no style added to the map."),!1)}_isValidId(v){return v==null?(this.fire(new s.B(new Error("IDs can't be empty."))),!1):!s.db(v)||(this.fire(new s.B(new Error(`IDs can't contain special symbols: "${v}".`))),!1)}_isTargetValid(v){return"featuresetId"in v?this._isValidId("importId"in v?v.importId:v.featuresetId):"layerId"in v&&this._isValidId(v.layerId)}_areTargetsValid(v){if(Array.isArray(v)){for(const d of v)if(!this._isValidId(d))return!1;return!0}return this._isTargetValid(v)}addSource(v,d){return this._isValidId(v)?(this._lazyInitEmptyStyle(),this.style.addSource(v,d),this._update(!0)):this}isSourceLoaded(v){return!!this._isValidId(v)&&!!this.style&&this.style._isSourceCacheLoaded(v)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(v,d,g){this._lazyInitEmptyStyle(),this.style.addSourceType(v,d,g)}removeSource(v){return this._isValidId(v)?(this.style.removeSource(v),this._updateTerrain(),this._update(!0)):this}getSource(v){return this._isValidId(v)?this.style.getOwnSource(v):null}addImage(v,d,{pixelRatio:g=1,sdf:w=!1,stretchX:A,stretchY:I,content:L}={}){this._lazyInitEmptyStyle();const F=s.I.from(v);if(d instanceof HTMLImageElement||ImageBitmap&&d instanceof ImageBitmap){const{width:$,height:H,data:Y}=s.o.getImageData(d);this.style.addImage(F,{data:new s.q({width:$,height:H},Y),pixelRatio:g,stretchX:A,stretchY:I,content:L,sdf:w,version:0,usvg:!1})}else if(d.width===void 0||d.height===void 0)this.fire(new s.B(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:$,height:H}=d,Y=d;this.style.addImage(F,{data:new s.q({width:$,height:H},new Uint8Array(Y.data)),pixelRatio:g,stretchX:A,stretchY:I,content:L,sdf:w,usvg:!1,version:0,userImage:Y}),Y.onAdd&&Y.onAdd(this,v)}}updateImage(v,d){this._lazyInitEmptyStyle();const g=s.I.from(v),w=this.style.getImage(g);if(!w)return void this.fire(new s.B(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const A=d instanceof HTMLImageElement||ImageBitmap&&d instanceof ImageBitmap?s.o.getImageData(d):d,{width:I,height:L,data:F}=A;if(I===void 0||L===void 0)return void this.fire(new s.B(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(I!==(w.usvg?w.icon.usvg_tree.width:w.data.width)||L!==(w.usvg?w.icon.usvg_tree.height:w.data.height))return void this.fire(new s.B(new Error(`The width and height of the updated image (${I}, ${L}) must be that same as the previous version of the image (${w.data.width}, ${w.data.height})`)));const $=!(d instanceof HTMLImageElement||ImageBitmap&&d instanceof ImageBitmap);let H=!1;w.usvg?(w.data=new s.q({width:I,height:L},new Uint8Array(F)),w.usvg=!1,w.icon=void 0,H=!0):w.data.replace(F,$),this.style.updateImage(g,w,H)}hasImage(v){return v?!!this.style&&!!this.style.getImage(s.I.from(v)):(this.fire(new s.B(new Error("Missing required image id"))),!1)}removeImage(v){this.style.removeImage(s.I.from(v))}loadImage(v,d){s.n(this._requestManager.transformRequest(v,s.R.Image),(g,w)=>{d(g,w)})}listImages(){return this.style.listImages().map(v=>v.name)}addModel(v,d){this._lazyInitEmptyStyle(),this.style.addModel(v,d)}hasModel(v){return v?this.style.hasModel(v):(this.fire(new s.B(new Error("Missing required model id"))),!1)}removeModel(v){this.style.removeModel(v)}listModels(){return this.style.listModels()}addLayer(v,d){return this._isValidId(v.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(v,d),this._update(!0)):this}getSlot(v){const d=this.getLayer(v);return d&&d.slot||null}setSlot(v,d){return this.style.setSlot(v,d),this.style.mergeLayers(),this._update(!0)}addImport(v,d){return this.style.addImport(v,d).catch(g=>this.fire(new s.B(new Error("Failed to add import",g)))),this}updateImport(v,d){return typeof d!="string"&&d.id!==v?(this.removeImport(v),this.addImport(d)):(this.style.updateImport(v,d),this._update(!0))}removeImport(v){return this.style.removeImport(v),this}moveImport(v,d){return this.style.moveImport(v,d),this._update(!0)}moveLayer(v,d){return this._isValidId(v)?(this.style.moveLayer(v,d),this._update(!0)):this}removeLayer(v){return this._isValidId(v)?(this.style.removeLayer(v),this._update(!0)):this}getLayer(v){if(!this._isValidId(v))return null;const d=this.style.getOwnLayer(v);return d?d.type==="custom"?d.implementation:d.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(v,d,g){return this._isValidId(v)?(this.style.setLayerZoomRange(v,d,g),this._update(!0)):this}setFilter(v,d,g={}){return this._isValidId(v)?(this.style.setFilter(v,d,g),this._update(!0)):this}getFilter(v){return this._isValidId(v)?this.style.getFilter(v):null}setPaintProperty(v,d,g,w={}){return this._isValidId(v)?(this.style.setPaintProperty(v,d,g,w),this._update(!0)):this}getPaintProperty(v,d){return this._isValidId(v)?this.style.getPaintProperty(v,d):null}setLayoutProperty(v,d,g,w={}){return this._isValidId(v)?(this.style.setLayoutProperty(v,d,g,w),this._update(!0)):this}getLayoutProperty(v,d){return this._isValidId(v)?this.style.getLayoutProperty(v,d):null}setLayerProperty(v,d,g,w={}){return this._isValidId(v)?(d==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(v,d,g,w),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(v){return this.style.setGlyphsUrl(v),this._update(!0)}getSchema(v){return this.style.getSchema(v)}setSchema(v,d){return this.style.setSchema(v,d),this._update(!0)}getConfig(v){return this.style.getConfig(v)}setConfig(v,d){return this.style.setConfig(v,d),this._update(!0)}getConfigProperty(v,d){return this.style.getConfigProperty(v,d)}setConfigProperty(v,d,g){return this.style.setConfigProperty(v,d,g),this._update(!0)}getFeaturesetDescriptors(v){return this.style.getFeaturesetDescriptors(v)}setLights(v){if(this._lazyInitEmptyStyle(),v&&v.length===1&&v[0].type==="flat"){const d=v[0];d.properties?this.style.setFlatLight(d.properties,d.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(v),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const v=this.style.getLights()||[];return v.length===0&&v.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),v}setLight(v,d={}){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:v}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(v){return this._lazyInitEmptyStyle(),!v&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(v),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(v){return this._lazyInitEmptyStyle(),this.style.setFog(v),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(v){return this._lazyInitEmptyStyle(),this.style.setSnow(v),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(v){return this._lazyInitEmptyStyle(),this.style.setRain(v),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(v){return this._lazyInitEmptyStyle(),this.style.setColorTheme(v),this._update(!0)}setImportColorTheme(v,d){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(v,d),this._update(!0)}setCamera(v){return this.style.setCamera(v),this._triggerCameraUpdate(v)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(v){const d=this.transform.nearClipOffset!==v;return this.transform.nearClipOffset=v,this._update(d)}_triggerCameraUpdate(v){return this._update(this.transform.setOrthographicProjectionAtLowPitch(v["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(v){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(s.aU.convert(v),this.transform):0}setFeatureState(v,d){return v.source&&!this._isValidId(v.source)?this:(this.style.setFeatureState(v,d),this._update())}removeFeatureState(v,d){return v.source&&!this._isValidId(v.source)?this:(this.style.removeFeatureState(v,d),this._update())}getFeatureState(v){return v.source&&!this._isValidId(v.source)?null:this.style.getFeatureState(v)}_selectIndoorFloor(v){this.style.indoorManager.selectFloor(v)}_setIndoorActiveFloorsVisibility(v){this.style.indoorManager.setActiveFloorsVisibility(v)}getIndoorTileOptions(v,d){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(v,d):null}_updateContainerDimensions(){if(!this._container)return;const v=this._container.getBoundingClientRect().width||400,d=this._container.getBoundingClientRect().height||300;let g,w,A,I=this._container;for(;I&&(!w||!A);){const L=window.getComputedStyle(I).transform;L&&L!=="none"&&(g=L.match(/matrix.*\((.+)\)/)[1].split(", "),g[0]&&g[0]!=="0"&&g[0]!=="1"&&(w=g[0]),g[3]&&g[3]!=="0"&&g[3]!=="1"&&(A=g[3])),I=I.parentElement}this._containerWidth=w?Math.abs(v/w):v,this._containerHeight=A?Math.abs(d/A):d}_detectMissingCSS(){window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")!=="rgb(250, 128, 114)"&&s.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 v=this._container;v.classList.add("mapboxgl-map"),(this._missingCSSCanary=N("div","mapboxgl-canary",v)).style.visibility="hidden",this._detectMissingCSS();const d=this._canvasContainer=N("div","mapboxgl-canvas-container",v);this._canvas=N("canvas","mapboxgl-canvas",d),this._interactive&&(d.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 g=this._controlContainer=N("div","mapboxgl-control-container",v),w=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(A=>{w[A]=N("div",`mapboxgl-ctrl-${A}`,g)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(v,d){const g=s.o.devicePixelRatio||1;this._canvas.width=g*Math.ceil(v),this._canvas.height=g*Math.ceil(d),this._canvas.style.width=`${v}px`,this._canvas.style.height=`${d}px`}_addMarker(v){this._markers.push(v)}_removeMarker(v){const d=this._markers.indexOf(v);d!==-1&&this._markers.splice(d,1)}_addPopup(v){this._popups.push(v)}_removePopup(v){const d=this._popups.indexOf(v);d!==-1&&this._popups.splice(d,1)}_setupPainter(){const v=Object.assign({},C.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),d=this._canvas.getContext("webgl2",v);d?(tr(d,!0),this.painter=new B3(d,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",g=>{if(g.dataType==="source"){const w=this.transform.elevation?this.transform.elevation._source():null;w&&g.sourceCacheId===w.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),s.k.testSupport(d)):this.fire(new s.B(new Error("Failed to initialize WebGL")))}_contextLost(v){v.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new s.C("webglcontextlost",{originalEvent:v}))}_contextRestored(v){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.destroyTextures(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new s.C("webglcontextrestored",{originalEvent:v}))}_onMapScroll(v){if(v.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(v){return this.style?(this._styleDirty=this._styleDirty||v,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(v){return this._update(),this._renderTaskQueue.add(v)}_cancelRenderFrame(v){this._renderTaskQueue.remove(v)}_requestDomTask(v){!this.loaded()||this.loaded()&&!this.isMoving()?v():this._domRenderTaskQueue.add(v)}_render(v){let d;this.fire(new s.C("renderstart")),++this._frameId;const g=this.painter.context.extTimerQuery,w=s.o.now(),A=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(d=A.createQuery(),A.beginQuery(g.TIME_ELAPSED_EXT,d)),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(v),this._domRenderTaskQueue.run(v),this._removed)return;this._updateProjectionTransition();const I=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const $=this.transform.zoom,H=this.transform.pitch,Y=s.o.now(),te=new s.ae($,{now:Y,fadeDuration:I,pitch:H,transition:this.style.transition,worldview:this._worldview});this.style.update(te)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let L=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),L=this._updateAverageElevation(w),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):L=this._updateAverageElevation(w),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,I,this._crossSourceCollisions,this.painter.replacementSource)),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:I,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming}),this.fire(new s.C("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,x.mark(m.load),this.fire(new s.C("load"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&(this.style.snow||this.style.rain)&&(this._styleDirty=!0),this.style&&this.style.imageManager.hasPatternsInFlight()&&(this._styleDirty=!0),this.style&&!this.style.modelManager.isLoaded()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),d){const $=s.o.now()-w;A.endQuery(g.TIME_ELAPSED_EXT),setTimeout(()=>{const H=A.getQueryParameter(d,A.QUERY_RESULT)/1e6;A.deleteQuery(d),this.fire(new s.C("gpu-timing-frame",{cpuTime:$,gpuTime:H}))},50)}if(this.listens("gpu-timing-layer")){const $=this.painter.collectGpuTimers();setTimeout(()=>{const H=this.painter.queryGpuTimers($);this.fire(new s.C("gpu-timing-layer",{layerTimes:H}))},50)}if(this.listens("gpu-timing-deferred-render")){const $=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const H=this.painter.queryGpuTimeDeferredRender($);this.fire(new s.C("gpu-timing-deferred-render",{gpuTime:H}))},50)}const F=this._sourcesDirty||this._styleDirty||this._placementDirty||L;if(F||this._repaint)this.triggerRepaint();else{const $=this.idle();if($&&(L=this._updateAverageElevation(w,!0)),L)this.triggerRepaint();else if(this._triggerFrame(!1),$&&(this.fire(new s.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const H=this._calculateSpeedIndex();this.fire(new s.C("speedindexcompleted",{speedIndex:H})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||F||(this._fullyLoaded=!0,x.mark(m.fullLoad),this._performanceMetricsCollection&&Sr(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:!!this.painter.style.getTerrain(),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(v){for(const d of this._markers)v&&!this.getRenderWorldCopies()&&(d._lngLat=d._lngLat.wrap()),d._update();for(const d of this._popups)!v||this.getRenderWorldCopies()||d._trackPointer||(d._lngLat=d._lngLat.wrap()),d._update()}_updateAverageElevation(v,d=!1){const g=A=>(this.transform.averageElevation=A,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&g(0);const w=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(w||(d||v-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(v)){const A=this.transform.averageElevation;let I=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(I)?I=0:this._averageElevationLastSampledAt=v;const L=Math.abs(A-I);if(L>1){if(this._isInitialLoad||w)return this._averageElevation.jumpTo(I),g(I);this._averageElevation.easeTo(I,v,300)}else if(L>1e-4)return this._averageElevation.jumpTo(I),g(I)}return!!this._averageElevation.isEasing(v)&&g(this._averageElevation.getValue(v))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const v=this.painter.context.gl;tr(v,!1),this._logoControl instanceof fE&&this._logoControl._updateLogo(),v&&v.clear(v.DEPTH_BUFFER_BIT|v.COLOR_BUFFER_BIT|v.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new s.B(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(){lr(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,v=>{v&&(v.message!==Se&&v.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),Et(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&Vt(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Pt(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){wt(this._requestManager._customAccessToken)}_updateTerrain(){const v=this._isDragging();this.painter.updateTerrain(this.style,v)}_calculateSpeedIndex(){const v=this.painter.canvasCopy(),d=this.painter.getCanvasCopiesAndTimestamps();d.timeStamps.push(performance.now());const g=this.painter.context.gl,w=g.createFramebuffer();function A(I){g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_2D,I,0);const L=new Uint8Array(g.drawingBufferWidth*g.drawingBufferHeight*4);return g.readPixels(0,0,g.drawingBufferWidth,g.drawingBufferHeight,g.RGBA,g.UNSIGNED_BYTE,L),L}return g.bindFramebuffer(g.FRAMEBUFFER,w),this._canvasPixelComparison(A(v),d.canvasCopies.map(A),d.timeStamps)}_canvasPixelComparison(v,d,g){let w=g[1]-g[0];const A=v.length/4;for(let I=0;I{const g=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,g&&this._render(d)}))}_preloadTiles(v){const d=this.style?this.style.getSourceCaches():[];return s.t(d,(g,w)=>g._preloadTiles(v,w),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(v){this._trackResize&&this.resize({originalEvent:v})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(v){this._showTileBoundaries!==v&&(this._showTileBoundaries=v,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(v){this._showParseStatus!==v&&(this._showParseStatus=v,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(v){this._showTerrainWireframe!==v&&(this._showTerrainWireframe=v,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(v){this._showLayers2DWireframe!==v&&(this._showLayers2DWireframe=v,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(v){this._showLayers3DWireframe!==v&&(this._showLayers3DWireframe=v,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(v){this._speedIndexTiming!==v&&(this._speedIndexTiming=v,this._update())}get showPadding(){return!!this._showPadding}set showPadding(v){this._showPadding!==v&&(this._showPadding=v,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(v){this._showCollisionBoxes!==v&&(this._showCollisionBoxes=v,this.style&&v?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(v){this._showOverdrawInspector!==v&&(this._showOverdrawInspector=v,this._update())}get repaint(){return!!this._repaint}set repaint(v){this._repaint!==v&&(this._repaint=v,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(v){this._vertices=v,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(v){this._showTileAABBs!==v&&(this._showTileAABBs=v,v&&this._update())}_setCacheLimits(v,d){s.e_(v,d)}get version(){return f}},NavigationControl:class{constructor(v={}){this.options=Object.assign({},H3,v),this._container=N("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",d=>d.preventDefault()),this.options.showZoom&&(s.aZ(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",d=>{this._map&&this._map.zoomIn({},{originalEvent:d})}),N("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",d=>{this._map&&this._map.zoomOut({},{originalEvent:d})}),N("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(s.aZ(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",d=>{const g=this._map;g&&(this.options.visualizePitch?g.resetNorthPitch({},{originalEvent:d}):g.resetNorth({},{originalEvent:d}))}),this._compassIcon=N("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const v=this._map;if(!v)return;const d=v.getZoom(),g=d===v.getMaxZoom(),w=d===v.getMinZoom();this._zoomInButton.disabled=g,this._zoomOutButton.disabled=w,this._zoomInButton.setAttribute("aria-disabled",g.toString()),this._zoomOutButton.setAttribute("aria-disabled",w.toString())}_rotateCompassArrow(){const v=this._map;if(!v)return;const d=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(v.transform.pitch*(Math.PI/180)),.5)}) rotateX(${v.transform.pitch}deg) rotateZ(${v.transform.angle*(180/Math.PI)}deg)`:`rotate(${v.transform.angle*(180/Math.PI)}deg)`;v._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=d)})}onAdd(v){return this._map=v,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),v.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&v.on("pitch",this._rotateCompassArrow),v.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new l_(v,this._compass,this.options.visualizePitch)),this._container}onRemove(){const v=this._map;v&&(this._container.remove(),this.options.showZoom&&v.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&v.off("pitch",this._rotateCompassArrow),v.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(v,d){const g=N("button",v,this._container);return g.type="button",g.addEventListener("click",d),g}_setButtonTitle(v,d){if(!this._map)return;const g=this._map._getUIString(`NavigationControl.${d}`);v.setAttribute("aria-label",g),v.firstElementChild&&v.firstElementChild.setAttribute("title",g)}},GeolocateControl:class extends s.E{constructor(v={}){super();const d=navigator.geolocation;this.options=Object.assign({geolocation:d},u_,v),s.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=XT(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(v){return this._map=v,this._container=N("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(v){const d=(g=!!this.options.geolocation)=>{this._supportsGeolocation=g,v(g)};this._supportsGeolocation!==void 0?v(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(g=>d(g.state!=="denied")).catch(()=>d()):d()}_isOutOfMapMaxBounds(v){const d=this._map.getMaxBounds(),g=v.coords;return!!d&&(g.longituded.getEast()||g.latituded.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}}_onSuccess(v){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(v))return this._setErrorState(),this.fire(new s.C("outofmaxbounds",v)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=v,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this.options.followUserLocation?(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active")):(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"));break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(v),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(v),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new s.C("geolocate",Object.assign({coords:v.coords,timestamp:v.timestamp},v.toJSON?{toJSON:v.toJSON.bind(v)}:{}))),this._finish()}}_updateCamera(v){const d=new s.aU(v.coords.longitude,v.coords.latitude),g=v.coords.accuracy,w=this._map.getBearing(),A=Object.assign({bearing:w},this.options.fitBoundsOptions);this._map.fitBounds(d.toBounds(g),A,{geolocateSource:!0})}_updateMarker(v){if(v){const d=new s.aU(v.coords.longitude,v.coords.latitude);this._accuracyCircleMarker.setLngLat(d).addTo(this._map),this._userLocationDotMarker.setLngLat(d).addTo(this._map),this._accuracy=v.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const v=this._map.transform,d=s.bU(1,v._center.lat)*v.worldSize,g=Math.ceil(2*this._accuracy*d);this._circleElement.style.width=`${g}px`,this._circleElement.style.height=`${g}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(v){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(v.code===1){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const d=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",d),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",d),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(v.code===3&&this._noTimeout)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new s.C("error",{code:v.code,message:v.message,PERMISSION_DENIED:v.PERMISSION_DENIED,POSITION_UNAVAILABLE:v.POSITION_UNAVAILABLE,TIMEOUT:v.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const v=this.options.positionOptions.timeout;v&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},v))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(v){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",d=>d.preventDefault()),this._geolocateButton=N("button","mapboxgl-ctrl-geolocate",this._container),N("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",v===!1){s.w("Geolocation support is not available so the GeolocateControl will be disabled.");const d=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",d),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",d)}else{const d=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",d),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",d)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=N("div","mapboxgl-user-location"),this._dotElement.appendChild(N("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(N("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new uu({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=N("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new uu({element:this._circleElement,pitchAlignment:"map"}),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",d=>{d.geolocateSource||this._watchState!=="ACTIVE_LOCK"||d.originalEvent&&d.originalEvent.type==="resize"||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this.fire(new s.C("trackuserlocationend")))})}}_onDeviceOrientation(v){this._userLocationDotMarker&&(v.webkitCompassHeading?this._heading=v.webkitCompassHeading:v.absolute===!0&&(this._heading=-1*v.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return s.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new s.C("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new s.C("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new s.C("trackuserlocationstart"))}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let v;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(v={maximumAge:6e5,timeout:0},this._noTimeout=!0):(v=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,v),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(v){return this.options.followUserLocation=v??u_.followUserLocation,this.options.trackUserLocation&&this._watchState!=="OFF"&&(this.options.followUserLocation?this._watchState!=="BACKGROUND"&&this._watchState!=="BACKGROUND_ERROR"||(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new s.C("trackuserlocationstart"))):this._watchState!=="ACTIVE_LOCK"&&this._watchState!=="ACTIVE_ERROR"||(this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this.fire(new s.C("trackuserlocationend")))),this}_addDeviceOrientationListener(){const v=()=>{const d="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(d,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(d=>{d==="granted"&&v()}).catch(console.error):v()}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:hE,ScaleControl:class{constructor(v={}){this.options=Object.assign({},oa,v),s.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const v=this.options.maxWidth||100,d=this._map,g=d._containerHeight/2,w=d._containerWidth/2-v/2,A=d.unproject([w,g]),I=d.unproject([w+v,g]),L=A.distanceTo(I);if(this.options.unit==="imperial"){const F=3.2808*L;F>5280?this._setScale(v,F/5280,"mile"):this._setScale(v,F,"foot")}else this.options.unit==="nautical"?this._setScale(v,L/1852,"nautical-mile"):L>=1e3?this._setScale(v,L/1e3,"kilometer"):this._setScale(v,L,"meter")}_setScale(v,d,g){this._map._requestDomTask(()=>{const w=function(I){const L=Math.pow(10,`${Math.floor(I)}`.length-1);let F=I/L;return F=F>=10?10:F>=5?5:F>=3?3:F>=2?2:F>=1?1:function($){const H=Math.pow(10,Math.ceil(-Math.log($)/Math.LN10));return Math.round($*H)/H}(F),L*F}(d),A=w/d;this._container.innerHTML=g!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:g}).format(w):`${w} ${du[g]}`,this._container.style.width=v*A+"px"})}onAdd(v){return this._map=v,this._language=v.getLanguage(),this._container=N("div","mapboxgl-ctrl mapboxgl-ctrl-scale",v.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(v){this._language=v,this._update()}setUnit(v){this.options.unit=v,this._update()}},FullscreenControl:class{constructor(v={}){this._fullscreen=!1,v&&v.container&&(v.container instanceof HTMLElement?this._container=v.container:s.w("Full screen control 'container' must be a DOM element.")),s.aZ(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(v){return this._map=v,this._container||(this._container=this._map.getContainer()),this._controlContainer=N("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",s.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 v=this._fullscreenButton=N("button","mapboxgl-ctrl-fullscreen",this._controlContainer);N("span","mapboxgl-ctrl-icon",v).setAttribute("aria-hidden","true"),v.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const v=this._getTitle();this._fullscreenButton.setAttribute("aria-label",v),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",v)}_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(){s.aZ(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(v){return this._map=v,this._container=N("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const v=this._map.style.indoorManager;v.off("selector-update",this._onIndoorUpdate),v.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(v.getControlState())}}_createButton(v,d){const g=N("button",v,this._container);return g.type="button",g.addEventListener("click",d),g}_setButtonTitle(v,d){v.setAttribute("aria-label",d),v.textContent=d}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.style&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(v){if(!v||!v.floors||v.floors.length===0)return this._model=v,void(this._container.style.display="none");const d=this._model;this._model=v,this._container.style.display="inline-block";const g=!d||d.floors.length!==v.floors.length||d.floors.some((w,A)=>w.id!==v.floors[A].id);if(g&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),v.selectedFloorId){if(v.selectedFloorId!==this._lastSelectedFloorId||g){const w=v.floors.findIndex(A=>A.id===v.selectedFloorId);if(w!==-1){const A=v.floors.length;let I,L;A<=5?(I=0,L=A-1):this._visibleFloorStart===0?(I=0,L=3):this._visibleFloorStart>=A-3?(I=A-3-1,L=A-1):(I=this._visibleFloorStart,L=this._visibleFloorStart+3-1),wL&&(this._visibleFloorStart=w-2)}}this._lastSelectedFloorId=v.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const v=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);N("span","mapboxgl-ctrl-icon",v).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||v.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(v);const d=this._model.floors,g=d.length;if(g<=5)return void d.forEach(L=>this._createFloorButton(L));const w=this._visibleFloorStart===0,A=this._visibleFloorStart>=g-3;if(w)this._createFloorButton(d[0]);else{const L=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);N("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),this._container.appendChild(L)}let I=[];if(I=w?d.slice(1,4):A?d.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):d.slice(this._visibleFloorStart,this._visibleFloorStart+3),I.forEach(L=>this._createFloorButton(L)),A)this._createFloorButton(d[g-1]);else{const L=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);N("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),this._container.appendChild(L)}}_createFloorButton(v){const d=this._createButton("mapboxgl-ctrl-level-button",()=>{const I=v.id;this._model&&this._model.selectedFloorId===I&&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(I))}),g=(v.name||"").trim(),w=v.zIndex.toString(),A=g?Array.from(g).slice(0,3).join(""):w;this._setButtonTitle(d,A),this._model&&this._model.activeFloorsVisible&&v.id===this._model.selectedFloorId&&d.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(d)}_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 v=this._model&&this._model.floors||[];if(v.length>3){const d=v.length-3;this._visibleFloorStart===d-1&&(this._visibleFloorStart=d-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const v=this._model.floors.length-3;this._visibleFloorStartv&&(this._visibleFloorStart=v),this._render())}}},Popup:class extends s.E{constructor(v){super(),this.options=Object.assign(Object.create(d_),v),this._altitude=this.options.altitude,s.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(v&&v.className?v.className.trim().split(/\s+/):[])}addTo(v){return this._map&&this.remove(),this._map=v,this.options.closeOnClick&&v.on("preclick",this._onClose),this.options.closeOnMove&&v.on("move",this._onClose),v.on("remove",this.remove),this._update(),v._addPopup(this),this._focusFirstElement(),this._trackPointer?(v.on("mousemove",this._onMouseEvent),v.on("mouseup",this._onMouseEvent),v._canvasContainer.classList.add("mapboxgl-track-pointer")):v.on("move",this._update),this.fire(new s.C("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const v=this._map;return v&&(v.off("move",this._update),v.off("move",this._onClose),v.off("preclick",this._onClose),v.off("click",this._onClose),v.off("remove",this.remove),v.off("mousemove",this._onMouseEvent),v.off("mouseup",this._onMouseEvent),v.off("drag",this._onMouseEvent),v._canvasContainer&&v._canvasContainer.classList.remove("mapboxgl-track-pointer"),v._removePopup(this),this._map=void 0),this.fire(new s.C("close")),this}getLngLat(){return this._lngLat}setLngLat(v){this._lngLat=s.aU.convert(v),this._pos=null,this._trackPointer=!1,this._update();const d=this._map;return d&&(d.on("move",this._update),d.off("mousemove",this._onMouseEvent),d._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(v){return this._altitude=v,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const v=this._map;return v&&(v.off("move",this._update),v.on("mousemove",this._onMouseEvent),v.on("drag",this._onMouseEvent),v._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(v){return this.setDOMContent(document.createTextNode(v))}setHTML(v){const d=document.createDocumentFragment(),g=document.createElement("body");let w;for(g.innerHTML=v;w=g.firstChild,w;)d.appendChild(w);return this.setDOMContent(d)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(v){return this.options.maxWidth=v,this._update(),this}setDOMContent(v){let d=this._content;if(d)for(;d.hasChildNodes();)d.firstChild&&d.removeChild(d.firstChild);else d=this._content=N("div","mapboxgl-popup-content",this._container||void 0);if(d.appendChild(v),this.options.closeButton){const g=this._closeButton=N("button","mapboxgl-popup-close-button",d);g.type="button",g.setAttribute("aria-label","Close popup"),g.innerHTML='',g.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(v){return this._classList.add(v),this._updateClassList(),this}removeClassName(v){return this._classList.delete(v),this._updateClassList(),this}setOffset(v){return this.options.offset=v,this._update(),this}toggleClassName(v){let d;return this._classList.delete(v)?d=!1:(this._classList.add(v),d=!0),this._updateClassList(),d}_onMouseEvent(v){this._update(v.point)}_getAnchor(v){if(this.options.anchor)return this.options.anchor;const d=this._map,g=this._container,w=this._pos;if(!d||!g||!w)return"bottom";const A=g.offsetWidth,I=g.offsetHeight,L=w.xd.transform.width-A/2;if(w.y+vd.transform.height-I){if(L)return"bottom-left";if(F)return"bottom-right"}return L?"left":F?"right":"bottom"}_updateClassList(){const v=this._container;if(!v)return;const d=[...this._classList];d.push("mapboxgl-popup"),this._anchor&&d.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&d.push("mapboxgl-popup-track-pointer"),v.className=d.join(" ")}_update(v){const d=this._map,g=this._content;if(!d||!this._lngLat&&!this._trackPointer||!g)return;let w=this._container;if(w||(w=this._container=N("div","mapboxgl-popup",d.getContainer()),this._tip=N("div","mapboxgl-popup-tip",w),w.appendChild(g)),this.options.maxWidth&&w.style.maxWidth!==this.options.maxWidth&&(w.style.maxWidth=this.options.maxWidth),d.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=pE(this._lngLat,this._pos,d.transform)),!this._trackPointer||v){const A=this._pos=this._trackPointer&&v instanceof s.P?v:d.project(this._lngLat,this._altitude),I=Jv(this.options.offset),L=this._anchor=this._getAnchor(I.y),F=Jv(this.options.offset,L),$=A.add(F).round();d._requestDomTask(()=>{this._container&&L&&(this._container.style.transform=`${c_[L]} translate(${$.x}px,${$.y}px)`)})}if(!this._marker&&d._showingGlobe()){const A=s.e$(d.transform,this._lngLat)?0:1;this._setOpacity(A)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const v=this._container.querySelector(W3);v&&v.focus()}_onClose(){this.remove()}_setOpacity(v){this._container&&(this._container.style.opacity=`${v}`),this._content&&(this._content.style.pointerEvents=v?"auto":"none")}},Marker:uu,Style:ou,LngLat:s.aU,LngLatBounds:s.aK,Point:s.P,MercatorCoordinate:s.ag,FreeCameraOptions:kx,Evented:s.E,config:s.g,prewarm:function(){Nn().acquire(dr)},clearPrewarmedResources:function(){const v=Zt;v&&(v.isPreloaded()&&v.numActive()===1?(v.release(dr),Zt=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 s.g.ACCESS_TOKEN},set accessToken(v){s.g.ACCESS_TOKEN=v},get baseApiUrl(){return s.g.API_URL},set baseApiUrl(v){s.g.API_URL=v},get workerCount(){return cr.workerCount},set workerCount(v){cr.workerCount=v},get maxParallelImageRequests(){return s.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(v){s.g.MAX_PARALLEL_IMAGE_REQUESTS=v},clearStorage(v){s.f7(v)},get workerUrl(){return At.workerUrl},set workerUrl(v){At.workerUrl=v},get workerClass(){return At.workerClass},set workerClass(v){At.workerClass=v},get workerParams(){return At.workerParams},set workerParams(v){At.workerParams=v},get dracoUrl(){return s.f6()},set dracoUrl(v){s.g.DRACO_URL=s.o.resolveURL(v)},get meshoptUrl(){return s.f5()},set meshoptUrl(v){const d=s.o.resolveURL(v);s.g.MESHOPT_URL=d,s.g.MESHOPT_SIMD_URL=d},get buildingGenUrl(){return s.f4()},set buildingGenUrl(v){s.g.BUILDING_GEN_URL=s.o.resolveURL(v)},setNow:s.o.setNow,restoreNow:s.o.restoreNow}});var c=i;return c})})(b0e);var yYe=b0e.exports;const Fd=ds(yYe),Hte={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"},Wte={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 xYe(t){return t>=1e6?`$${(t/1e6).toFixed(1)}M`:`$${(t/1e3).toFixed(0)}K`}function _Ye({listings:t,isLoading:e}){const r=ma(),n=P.useRef(null),i=P.useRef(null),a=P.useRef([]),[c,s]=P.useState(""),[f,m]=P.useState(!0);return P.useEffect(()=>{(async()=>{m(!0);try{const{data:T}=await Le.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();T!=null&&T.value&&s(T.value)}catch(T){console.error("Error fetching mapbox token:",T)}m(!1)})()},[]),P.useEffect(()=>{if(!n.current||!c||i.current)return;Fd.accessToken=c;const _=t.filter(C=>C.latitude!=null&&C.longitude!=null);let T=[-98.5795,39.8283],E=4;if(_.length>0){const C=_.reduce((R,D)=>R+D.longitude,0)/_.length,N=_.reduce((R,D)=>R+D.latitude,0)/_.length;T=[C,N],E=_.length===1?12:10}return i.current=new Fd.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:E,center:T}),i.current.addControl(new Fd.NavigationControl,"top-right"),()=>{var C;(C=i.current)==null||C.remove(),i.current=null}},[c]),P.useEffect(()=>{if(!i.current||!c)return;a.current.forEach(T=>T.remove()),a.current=[];const _=t.filter(T=>T.latitude!=null&&T.longitude!=null);if(_.forEach(T=>{var V,G,W;const E=Hte[T.status]||"#10B981",C=((V=T.photos)==null?void 0:V.find(X=>X.is_primary))||((G=T.photos)==null?void 0:G[0]),R=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${T.slug||T.id}`:`/public/listing/${T.slug||T.id}`,D=document.createElement("div");D.className="cursor-pointer",D.innerHTML=`
`;const M=new Fd.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${C!=null&&C.photo_url?``:""}
${xYe(T.price)}
${T.property_address||""}
${T.city}, ${T.state}
${Wte[T.status]||T.status} ${T.bedrooms?`${T.bedrooms} bed`:""} ${T.bathrooms?`${T.bathrooms} bath`:""}
${(W=T.agent)!=null&&W.name?`
Listed by ${T.agent.name}
`:""}
Click to view details →
`),B=new Fd.Marker(D).setLngLat([T.longitude,T.latitude]).setPopup(M).addTo(i.current);a.current.push(B)}),_.length>1){const T=new Fd.LngLatBounds;_.forEach(E=>T.extend([E.longitude,E.latitude])),i.current.fitBounds(T,{padding:60,maxZoom:13})}else _.length===1&&i.current.flyTo({center:[_[0].longitude,_[0].latitude],zoom:12})},[t,c]),P.useEffect(()=>(window.__navigateToPublicListing__=_=>{r(_)},()=>{delete window.__navigateToPublicListing__}),[r]),f||e?o.jsx(ol,{className:"w-full h-[500px] rounded-lg"}):!c||t.filter(_=>_.latitude!=null&&_.longitude!=null).length===0?null:o.jsxs("div",{className:"space-y-3",children:[o.jsx("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:Object.entries(Hte).map(([_,T])=>o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:T}}),o.jsx("span",{className:"text-xs text-gray-600",children:Wte[_]})]},_))}),o.jsx("div",{ref:n,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const GB={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"},vYe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},Bb="#0d0d0d",Kte="#1a1a1a",Yi="#c9a84c",Bg="#f0d78c";function S0e(){const[t,e]=P.useState(""),[r,n]=P.useState(!1),[i,a]=P.useState(!1),[c,s]=P.useState(!1),[f,m]=P.useState(-1),x=P.useRef(null),[_,T]=P.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:E}=QKe(),C=P.useMemo(()=>{if(!E)return[];const ue=t.trim().toLowerCase(),_e=[...E.cities.map(ve=>({label:ve.label,value:ve.city,type:"city",count:ve.count})),...E.neighborhoods.map(ve=>({label:ve.label,value:ve.neighborhood,type:"neighborhood",count:ve.count})),...E.zips.map(ve=>({label:`ZIP ${ve.label}`,value:ve.zip,type:"zip",count:ve.count}))];return(ue?_e.filter(ve=>ve.label.toLowerCase().includes(ue)||ve.value.toLowerCase().includes(ue)):_e).slice(0,8)},[E,t]);P.useEffect(()=>{const ue=_e=>{x.current&&!x.current.contains(_e.target)&&s(!1)};return document.addEventListener("mousedown",ue),()=>document.removeEventListener("mousedown",ue)},[]);const{data:N,isLoading:R}=XKe({city:t||void 0,status:_.status||void 0,propertyType:_.propertyType||void 0,minPrice:_.minPrice?Number(_.minPrice):void 0,maxPrice:_.maxPrice?Number(_.maxPrice):void 0}),D=ue=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(ue),M=()=>{T({status:"",propertyType:"",minPrice:"",maxPrice:""}),e("")},B=t||_.status||_.propertyType||_.minPrice||_.maxPrice,V=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),G=ue=>V?`/${ue.slug||ue.id}`:`/public/listing/${ue.slug||ue.id}`,{featured:W,restListings:X,luxeCount:Q,cities:re,activeCount:se}=P.useMemo(()=>{const ue=N||[],_e=ue.filter(rt=>rt.status==="active"),Se=_e.length>0?_e:ue,ve=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[Oe,Ae,we]=ve.split("-").map(Number),ge=Math.floor(Date.UTC(Oe,Ae-1,we)/864e5),Ne=Se.length>0?Se[ge%Se.length]:void 0,Ie=ue.filter(rt=>!Ne||rt.id!==Ne.id),Te=Array.from(new Set(ue.map(rt=>rt.city).filter(Boolean))).slice(0,8),be=ue.filter(rt=>(rt.price||0)>=1e6).length,We=_e.length;return{featured:Ne,restListings:Ie,luxeCount:be,cities:Te,activeCount:We}},[N]);return o.jsxs(o.Fragment,{children:[o.jsxs(jl,{children:[o.jsx("title",{children:"LevelUp Listings — Curated Homes for Sale"}),o.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."}),o.jsx("link",{rel:"canonical",href:"https://listings.relevelup.com"}),o.jsx("meta",{property:"og:title",content:"LevelUp Listings — Curated Homes for Sale"}),o.jsx("meta",{property:"og:description",content:"A curated collection of exclusive properties from LevelUp real estate agents."}),o.jsx("meta",{property:"og:type",content:"website"}),o.jsx("meta",{property:"og:url",content:"https://listings.relevelup.com"}),o.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),o.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"LevelUp Listings",url:"https://listings.relevelup.com"})})]}),o.jsxs("div",{className:"min-h-screen text-white",style:{backgroundColor:Bb,fontFamily:"'Fira Sans', system-ui, sans-serif"},children:[o.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: ${Yi}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Yi}, 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; } `}),o.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:[o.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between",children:[o.jsxs(cs,{to:"/",className:"flex items-center gap-3",children:[o.jsx("img",{src:Gte,alt:"LevelUp",className:"h-7"}),o.jsx("span",{className:"hidden sm:inline-block h-5 w-px",style:{background:"rgba(255,255,255,0.2)"}}),o.jsx("span",{className:"hidden sm:inline lu-eyebrow lu-gold",children:"Listings"})]}),o.jsxs("nav",{className:"hidden md:flex items-center gap-8",children:[o.jsx("a",{href:"#featured",className:"text-sm text-white/80 hover:text-white transition",children:"Featured"}),o.jsx("a",{href:"#collection",className:"text-sm text-white/80 hover:text-white transition",children:"Collection"}),o.jsx("a",{href:"#map",className:"text-sm text-white/80 hover:text-white transition",children:"Map"}),o.jsx(cs,{to:"/home-value",className:"text-sm text-white/80 hover:text-white transition",children:"Home Value"}),o.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 ${Yi}`,color:Yi},children:"About LevelUp"})]}),o.jsx("button",{type:"button",onClick:()=>a(ue=>!ue),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${Yi}`,color:Yi},"aria-label":"Toggle menu","aria-expanded":i,children:i?o.jsx(Ks,{className:"w-5 h-5"}):o.jsx(ZO,{className:"w-5 h-5"})})]}),i&&o.jsx("div",{className:"md:hidden border-t",style:{borderColor:"rgba(201,168,76,0.15)"},children:o.jsxs("nav",{className:"max-w-7xl mx-auto px-6 py-4 flex flex-col gap-1",children:[o.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"}),o.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"}),o.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"}),o.jsx(cs,{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"}),o.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 ${Yi}`,color:Yi},children:"About LevelUp"})]})})]}),o.jsxs("section",{className:"relative overflow-hidden lu-grain",style:{minHeight:"92vh"},children:[o.jsxs("div",{className:"absolute inset-0",children:[o.jsx("img",{src:gYe,alt:"Luxury home at dusk",className:"w-full h-full object-cover",style:{filter:"brightness(0.55) contrast(1.05)"}}),o.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%)"}})]}),o.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:[o.jsxs("div",{className:"max-w-4xl",children:[o.jsxs("div",{className:"lu-hero-title flex items-center gap-3 mb-6",children:[o.jsx("span",{className:"h-px w-10",style:{background:Yi}}),o.jsx("span",{className:"lu-eyebrow lu-gold",children:"The LevelUp Collection"})]}),o.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",o.jsx("br",{}),o.jsx("span",{className:"italic",style:{color:Bg},children:"quiet"})," kind of luxury."]}),o.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."}),o.jsxs("div",{className:"lu-hero-search max-w-3xl",ref:x,children:[o.jsxs("div",{className:"flex items-stretch rounded-full overflow-hidden shadow-2xl relative",style:{background:"rgba(13,13,13,0.7)",border:`1px solid ${Yi}`,backdropFilter:"blur(12px)"},children:[o.jsxs("div",{className:"relative flex-1",children:[o.jsx($y,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:Yi}}),o.jsx(Ur,{placeholder:"City, neighborhood, or ZIP",value:t,onChange:ue=>{e(ue.target.value),s(!0),m(-1)},onFocus:()=>s(!0),onKeyDown:ue=>{if(!(!c||C.length===0))if(ue.key==="ArrowDown")ue.preventDefault(),m(_e=>Math.min(_e+1,C.length-1));else if(ue.key==="ArrowUp")ue.preventDefault(),m(_e=>Math.max(_e-1,0));else if(ue.key==="Enter"&&f>=0){ue.preventDefault();const _e=C[f];e(_e.value),s(!1)}else ue.key==="Escape"&&s(!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"})]}),o.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:[o.jsx(xLe,{className:"h-4 w-4"}),"Filters"]}),o.jsxs("button",{className:"px-8 flex items-center gap-2 font-medium transition hover:brightness-110",style:{background:Yi,color:Bb},onClick:()=>s(!1),children:[o.jsx($y,{className:"h-5 w-5"}),o.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),c&&C.length>0&&o.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:[o.jsx("div",{className:"px-5 pt-3 pb-2 text-[10px] tracking-[0.2em] uppercase",style:{color:Yi},children:"Suggestions"}),o.jsx("ul",{className:"max-h-80 overflow-y-auto",children:C.map((ue,_e)=>o.jsx("li",{children:o.jsxs("button",{type:"button",onMouseEnter:()=>m(_e),onClick:()=>{e(ue.value),s(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:f===_e?"rgba(201,168,76,0.12)":"transparent"},children:[o.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[ue.type==="city"&&o.jsx(na,{className:"h-4 w-4 shrink-0",style:{color:Yi}}),ue.type==="neighborhood"&&o.jsx(Eo,{className:"h-4 w-4 shrink-0",style:{color:Yi}}),ue.type==="zip"&&o.jsx(Ma,{className:"h-4 w-4 shrink-0",style:{color:Yi}}),o.jsx("span",{className:"text-white/90 truncate",children:ue.label})]}),o.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[ue.count," ",ue.count===1?"listing":"listings"]})]})},`${ue.type}-${ue.value}-${_e}`))})]}),c&&t.trim()&&C.length===0&&o.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&&o.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:[o.jsxs("div",{children:[o.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),o.jsxs(Ba,{value:_.status||"all",onValueChange:ue=>T({..._,status:ue==="all"?"":ue}),children:[o.jsx(ja,{className:"lu-input-dark",children:o.jsx(za,{})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"all",children:"Any status"}),Object.entries(GB).map(([ue,_e])=>o.jsx(wn,{value:ue,children:_e},ue))]})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),o.jsxs(Ba,{value:_.propertyType||"all",onValueChange:ue=>T({..._,propertyType:ue==="all"?"":ue}),children:[o.jsx(ja,{className:"lu-input-dark",children:o.jsx(za,{})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"all",children:"Any type"}),Object.entries(vYe).map(([ue,_e])=>o.jsx(wn,{value:ue,children:_e},ue))]})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),o.jsx(Ur,{type:"number",placeholder:"No min",value:_.minPrice,onChange:ue=>T({..._,minPrice:ue.target.value}),className:"lu-input-dark"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Max Price"}),o.jsx(Ur,{type:"number",placeholder:"No max",value:_.maxPrice,onChange:ue=>T({..._,maxPrice:ue.target.value}),className:"lu-input-dark"})]}),B&&o.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:o.jsxs(Ut,{variant:"ghost",size:"sm",onClick:M,className:"text-white/70 hover:text-white gap-1",children:[o.jsx(Ks,{className:"h-4 w-4"})," Clear all"]})})]})]}),o.jsx("div",{className:"lu-hero-stats mt-14 grid grid-cols-3 gap-6 max-w-2xl",children:[{label:"Listings",value:((N==null?void 0:N.length)??0).toString()},{label:"Active Now",value:se.toString()},{label:"Luxury $1M+",value:Q.toString()}].map(ue=>o.jsxs("div",{children:[o.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:Bg},children:ue.value}),o.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:ue.label})]},ue.label))})]}),o.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2 text-white/60",children:[o.jsx("span",{className:"lu-eyebrow",children:"Scroll"}),o.jsx(od,{className:"h-4 w-4 animate-bounce"})]})]})]}),re.length>0&&o.jsx("section",{className:"py-8 overflow-hidden",style:{background:Kte,borderTop:"1px solid rgba(201,168,76,0.15)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:o.jsx("div",{className:"lu-marquee whitespace-nowrap",children:[...re,...re,...re].map((ue,_e)=>o.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[ue,o.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:Yi}})]},_e))})}),W&&o.jsx("section",{id:"featured",className:"py-20 md:py-28",children:o.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[o.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[o.jsx(Ss,{className:"h-4 w-4",style:{color:Yi}}),o.jsx("span",{className:"lu-eyebrow lu-gold",children:"Today's Featured Residence"})]}),o.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl",children:["Today's ",o.jsx("span",{className:"italic",style:{color:Bg},children:"standout"}),"."]})]}),o.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),o.jsx(cs,{to:G(W),className:"group block",children:o.jsxs("div",{className:"grid lg:grid-cols-5 gap-6 lg:gap-10 items-stretch",children:[o.jsxs("div",{className:"lg:col-span-3 relative overflow-hidden rounded-2xl aspect-[4/3] bg-black",children:[(()=>{var _e,Se;const ue=((_e=W.photos)==null?void 0:_e.find(ve=>ve.is_primary))||((Se=W.photos)==null?void 0:Se[0]);return ue?o.jsx("img",{src:ue.photo_url,alt:W.property_address||W.city,className:"w-full h-full object-cover lu-img-zoom"}):o.jsx("div",{className:"w-full h-full flex items-center justify-center",children:o.jsx(Ma,{className:"h-16 w-16 text-white/20"})})})(),o.jsx("div",{className:"absolute top-5 left-5 px-4 py-1.5 rounded-full lu-eyebrow",style:{background:Yi,color:Bb},children:GB[W.status]||"Featured"})]}),o.jsxs("div",{className:"lg:col-span-2 flex flex-col justify-center",children:[o.jsxs("div",{className:"lu-eyebrow text-white/60 mb-4 flex items-center gap-2",children:[o.jsx(na,{className:"h-3.5 w-3.5",style:{color:Yi}}),W.city,W.state?`, ${W.state}`:""]}),W.property_address&&o.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:W.property_address}),o.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:Bg},children:D(W.price)}),o.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[W.bedrooms&&o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(TC,{className:"h-4 w-4",style:{color:Yi}}),W.bedrooms," bd"]}),W.bathrooms&&o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(lS,{className:"h-4 w-4",style:{color:Yi}}),W.bathrooms," ba"]}),W.square_footage&&o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(gG,{className:"h-4 w-4",style:{color:Yi}}),W.square_footage.toLocaleString()," sf"]})]}),W.description&&o.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:W.description}),o.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:Yi},children:["View Residence ",o.jsx(pc,{className:"h-4 w-4"})]})]})]})})]})}),o.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:Kte},children:o.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[o.jsxs("div",{className:"text-center mb-14",children:[o.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[o.jsx("span",{className:"h-px w-10",style:{background:Yi}}),o.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),o.jsx("span",{className:"h-px w-10",style:{background:Yi}})]}),o.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl mb-4",children:["Every home, ",o.jsx("span",{className:"italic",style:{color:Bg},children:"carefully considered"}),"."]}),o.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."})]}),R?o.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((ue,_e)=>o.jsxs("div",{className:"space-y-3",children:[o.jsx(ol,{className:"aspect-[4/5] bg-white/5"}),o.jsx(ol,{className:"h-6 w-32 bg-white/5"}),o.jsx(ol,{className:"h-4 w-full bg-white/5"})]},_e))}):X.length>0?o.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:X.map(ue=>{var Se,ve,Oe,Ae,we;const _e=((Se=ue.photos)==null?void 0:Se.find(ge=>ge.is_primary))||((ve=ue.photos)==null?void 0:ve[0]);return o.jsxs(cs,{to:G(ue),className:"group lu-card-hover block",children:[o.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[_e?o.jsx("img",{src:_e.photo_url,alt:ue.property_address||ue.city,className:"w-full h-full object-cover lu-img-zoom"}):o.jsx("div",{className:"w-full h-full flex items-center justify-center",children:o.jsx(Ma,{className:"h-12 w-12 text-white/20"})}),o.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%)"}}),o.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:Yi,border:`1px solid ${Yi}`},children:GB[ue.status]}),o.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:[ue.bedrooms&&o.jsxs("span",{children:[ue.bedrooms," bd"]}),ue.bathrooms&&o.jsxs("span",{children:[ue.bathrooms," ba"]}),ue.square_footage&&o.jsxs("span",{children:[ue.square_footage.toLocaleString()," sf"]})]})]}),o.jsxs("div",{children:[o.jsxs("div",{className:"lu-eyebrow text-white/50 mb-2 flex items-center gap-2",children:[o.jsx(na,{className:"h-3 w-3",style:{color:Yi}}),ue.city,ue.state?`, ${ue.state}`:""]}),o.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:Bg},children:D(ue.price)}),ue.property_address&&o.jsx("p",{className:"text-white/70 text-sm truncate",children:ue.property_address}),((Oe=ue.agent)==null?void 0:Oe.name)&&o.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[o.jsx(Eo,{className:"h-3 w-3"}),ue.agent.name,(((Ae=ue.agent.brokerage)==null?void 0:Ae.name)||ue.agent.brokerage_name)&&o.jsxs("span",{className:"truncate",children:["· ",((we=ue.agent.brokerage)==null?void 0:we.name)||ue.agent.brokerage_name]})]})]})]},ue.id)})}):o.jsxs("div",{className:"text-center py-20",children:[o.jsx("div",{className:"w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center",style:{border:`1px solid ${Yi}`},children:o.jsx(Ma,{className:"h-8 w-8",style:{color:Yi}})}),o.jsx("h3",{className:"lu-serif text-2xl mb-2",children:"No listings match yet"}),o.jsx("p",{className:"text-white/60 mb-6",children:"Adjust your search — or check back soon for new arrivals."}),B&&o.jsx(Ut,{onClick:M,style:{background:Yi,color:Bb},className:"hover:brightness-110",children:"Clear filters"})]})]})}),N&&N.length>0&&o.jsx("section",{id:"map",className:"py-20 md:py-28",children:o.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[o.jsx("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-10",children:o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[o.jsx("span",{className:"h-px w-10",style:{background:Yi}}),o.jsx("span",{className:"lu-eyebrow lu-gold",children:"Explore"})]}),o.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl",children:["Every listing, ",o.jsx("span",{className:"italic",style:{color:Bg},children:"on the map"}),"."]})]})}),o.jsx("div",{className:"rounded-2xl overflow-hidden",style:{border:"1px solid rgba(201,168,76,0.2)"},children:o.jsx(_Ye,{listings:N,isLoading:R})})]})}),o.jsxs("section",{className:"relative py-24 md:py-32 overflow-hidden lu-grain",children:[o.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(ellipse at center, rgba(201,168,76,0.15) 0%, ${Bb} 70%)`}}),o.jsxs("div",{className:"relative max-w-4xl mx-auto px-6 text-center",children:[o.jsxs("div",{className:"flex items-center justify-center gap-3 mb-6",children:[o.jsx("span",{className:"h-px w-10",style:{background:Yi}}),o.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),o.jsx("span",{className:"h-px w-10",style:{background:Yi}})]}),o.jsxs("h2",{className:"lu-serif text-4xl md:text-6xl mb-6 leading-tight",children:["Your listings deserve a",o.jsx("br",{}),o.jsx("span",{className:"italic",style:{color:Bg},children:"stage this good"}),"."]}),o.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."}),o.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:Yi,color:Bb},children:["Explore LevelUp",o.jsx(pc,{className:"h-4 w-4"})]})]})]}),o.jsx("footer",{className:"py-14",style:{background:"#080808",borderTop:"1px solid rgba(201,168,76,0.15)"},children:o.jsxs("div",{className:"max-w-7xl mx-auto px-6 flex flex-col md:flex-row items-center justify-between gap-6",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("img",{src:Gte,alt:"LevelUp",className:"h-6"}),o.jsx("span",{className:"h-4 w-px bg-white/20"}),o.jsx("span",{className:"lu-eyebrow lu-gold",children:"Listings"})]}),o.jsxs("p",{className:"text-white/40 text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),o.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-white/60 hover:text-white text-sm transition",children:"relevelup.com →"})]})})]}),o.jsx(CKe,{}),o.jsx(jKe,{})]})}const bYe=Object.freeze(Object.defineProperty({__proto__:null,default:S0e},Symbol.toStringTag,{value:"Module"})),wYe=P.lazy(()=>Be(()=>import("./PublicHomeValue-BhuMaHOQ.js"),[]));function SYe(){const t=Wi(),e=window.location.hostname;if(!(e==="listings.relevelup.com"||e.startsWith("listings.")))return null;const n=t.pathname.slice(1);return!n||n===""?o.jsx(S0e,{}):n==="home-value"||n==="whats-my-home-worth"?o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(wYe,{})}):n.startsWith("public/")?null:o.jsx(s7,{slugOverride:n})}const TYe=P.lazy(()=>Be(()=>import("./CommercialMarketplace-K0IRjonM.js"),__vite__mapDeps([11,3])));function EYe(){const e=Wi().pathname.slice(1);return e?e.startsWith("public/")?null:o.jsx(s7,{slugOverride:e}):o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"min-h-screen bg-[#0a0d12]"}),children:o.jsx(TYe,{})})}function JM({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 o.jsx("div",{className:`rounded-2xl p-4 mb-6 ${i.container}`,children:o.jsxs("div",{className:`flex flex-col items-center gap-3 ${r&&n?"divide-y divide-current/10":""}`,children:[r&&o.jsxs("div",{className:"flex flex-col items-center gap-1.5 w-full",children:[t.brokerage_logo_url&&o.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&&o.jsx("p",{className:`text-sm font-medium ${i.text}`,children:t.brokerage_display_name})]}),n&&o.jsxs("div",{className:`flex flex-col items-center gap-1.5 w-full ${r?"pt-3":""}`,children:[t.team_logo_url&&o.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&&o.jsx("p",{className:`text-sm font-medium ${i.text}`,children:t.team_name})]})]})})}const AYe=t=>wr({queryKey:["agent-card-public",t],queryFn:async()=>{if(!t)throw new Error("No slug provided");const{data:e,error:r}=await Le.from("agent_cards").select("*").eq("slug",t).eq("is_published",!0).single();if(r)throw r;const{data:n}=await Le.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:s}=await Le.from("brokerages").select("name").eq("id",n.brokerage_id).single();i=(s==null?void 0:s.name)||null}let a=null;try{const{data:s}=await Le.from("profiles").select("avatar_url").eq("id",e.user_id).single();if(s!=null&&s.avatar_url)a=s.avatar_url;else{const{data:f}=await Le.storage.from("avatars").list(`${e.user_id}`);if(f&&f.length>0){const{data:m}=Le.storage.from("avatars").getPublicUrl(`${e.user_id}/${f[0].name}`);a=`${m.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}),v6t=()=>wr({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:t,error:e}=await Le.from("agent_cards").select("*").order("created_at",{ascending:!1});if(e)throw e;return t}}),b6t=t=>wr({queryKey:["agent-card",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Le.from("agent_cards").select("*").eq("user_id",t).maybeSingle();if(r)throw r;return e},enabled:!!t}),w6t=()=>{const t=Nr();return Cr({mutationFn:async e=>{const{data:r,error:n}=await Le.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"]}),Jt.success("Agent card created")},onError:e=>Jt.error(e.message)})},S6t=()=>{const t=Nr();return Cr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Le.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"]}),Jt.success("Agent card updated")},onError:e=>Jt.error(e.message)})},Qi=async(t,e,r,n)=>{const i=new URLSearchParams(window.location.search);await Le.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:{}})},kYe=async(t,e)=>{const{error:r}=await Le.from("agent_card_leads").insert({card_id:t,...e});if(r)throw r},T6t=t=>wr({queryKey:["agent-card-analytics",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Le.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 Le.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(f=>f.interaction_type==="card_view").length)||0,c=(e==null?void 0:e.filter(f=>f.interaction_type==="button_click").length)||0,s=(e==null?void 0:e.filter(f=>f.interaction_type==="contact_saved").length)||0;return{views:a,clicks:c,saves:s,leads:n||[],interactions:e||[]}},enabled:!!t});function eF({open:t,onOpenChange:e,cardId:r,type:n,agentName:i}){const[a,c]=P.useState(""),[s,f]=P.useState(""),[m,x]=P.useState(""),[_,T]=P.useState(""),[E,C]=P.useState(""),[N,R]=P.useState(!1),D=async M=>{if(M.preventDefault(),!a.trim()){Jt.error("Please enter your name");return}R(!0);try{await kYe(r,{lead_type:n,name:a.trim(),email:s.trim()||void 0,phone:m.trim()||void 0,message:E.trim()||void 0,intent:_||void 0}),Qi(r,"lead_submitted",n),Le.functions.invoke("card-lead-notify",{body:{cardId:r,leadType:n,name:a.trim(),email:s.trim()||void 0,phone:m.trim()||void 0,message:E.trim()||void 0,intent:_||void 0}}).catch(B=>console.error("Card lead notify failed:",B)),Jt.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(""),f(""),x(""),T(""),C("")}catch{Jt.error("Something went wrong. Please try again.")}finally{R(!1)}};return o.jsx(ro,{open:t,onOpenChange:e,children:o.jsxs($a,{className:"sm:max-w-md rounded-2xl",children:[o.jsxs(ul,{children:[o.jsx(Go,{children:n==="booking"?"Book a Call":n==="connect"?"Connect with Me":"Refer a Friend"}),o.jsx(ld,{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?`})]}),o.jsxs("form",{onSubmit:D,className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"lead-name",children:"Name *"}),o.jsx(Ur,{id:"lead-name",value:a,onChange:M=>c(M.target.value),placeholder:"Your name",required:!0})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"lead-phone",children:"Phone"}),o.jsx(Ur,{id:"lead-phone",type:"tel",value:m,onChange:M=>x(M.target.value),placeholder:"(555) 123-4567"})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"lead-email",children:"Email"}),o.jsx(Ur,{id:"lead-email",type:"email",value:s,onChange:M=>f(M.target.value),placeholder:"you@example.com"})]}),n==="booking"&&o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"lead-intent",children:"I'm looking to..."}),o.jsxs(Ba,{value:_,onValueChange:T,children:[o.jsx(ja,{children:o.jsx(za,{placeholder:"Select one"})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"buy",children:"Buy a home"}),o.jsx(wn,{value:"sell",children:"Sell my home"}),o.jsx(wn,{value:"both",children:"Buy & Sell"}),o.jsx(wn,{value:"other",children:"Something else"})]})]})]}),n!=="connect"&&o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"lead-message",children:n==="referral"?"Tell us about them":"Message (optional)"}),o.jsx(Ur,{id:"lead-message",value:E,onChange:M=>C(M.target.value),placeholder:n==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),o.jsx(Ut,{type:"submit",className:"w-full rounded-2xl",disabled:N,children:N?"Sending...":"Submit"})]})]})})}const CYe=t=>wr({queryKey:["card-blocks",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Le.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}),E6t=t=>wr({queryKey:["card-blocks-all",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Le.from("card_blocks").select("*").eq("card_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t}),A6t=()=>{const t=Nr();return Cr({mutationFn:async e=>{const{data:r,error:n}=await Le.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]}),Jt.success("Block added")},onError:e=>Jt.error(e.message)})},k6t=()=>{const t=Nr();return Cr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Le.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"]}),Jt.success("Block updated")},onError:e=>Jt.error(e.message)})},C6t=()=>{const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("card_blocks").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["card-blocks"]}),t.invalidateQueries({queryKey:["card-blocks-all"]}),Jt.success("Block removed")},onError:e=>Jt.error(e.message)})};function jYe(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 IYe(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 PYe={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 NYe({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=IYe(r.video_url),a=n||!!i,c=n?jYe(r.video_url):i||r.video_url;return o.jsx("div",{className:PYe[e],children:a?o.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:o.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})}):o.jsx("video",{src:r.video_url,controls:!0,className:"w-full",preload:"metadata"})})}const RYe={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 LYe({block:t,variant:e}){const n=t.config.testimonials||[],[i,a]=P.useState(0);if(n.length===0)return null;const c=RYe[e],s=n[i];return o.jsxs("div",{className:c.container,children:[o.jsxs("div",{className:c.card,children:[o.jsx(hLe,{className:"h-4 w-4 mb-2 opacity-30"}),o.jsxs("p",{className:`${c.quote} mb-3`,children:['"',s.quote,'"']}),o.jsxs("div",{children:[o.jsx("p",{className:c.name,children:s.name}),s.role&&o.jsx("p",{className:c.role,children:s.role})]})]}),n.length>1&&o.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[o.jsx("button",{onClick:()=>a(f=>(f-1+n.length)%n.length),className:c.nav,children:o.jsx($m,{className:"h-4 w-4"})}),o.jsx("div",{className:"flex gap-1.5",children:n.map((f,m)=>o.jsx("div",{className:`h-1.5 w-1.5 rounded-full transition-colors cursor-pointer ${m===i?c.dot:c.dotInactive}`,onClick:()=>a(m)},m))}),o.jsx("button",{onClick:()=>a(f=>(f+1)%n.length),className:c.nav,children:o.jsx(th,{className:"h-4 w-4"})})]})]})}const DYe={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 OYe({block:t,variant:e}){const n=t.config.tags||[];if(n.length===0)return null;const i=DYe[e];return o.jsx("div",{className:i.container,children:n.map((a,c)=>o.jsx("span",{className:i.tag,children:a},c))})}const MYe={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 FYe({block:t,cardId:e,variant:r}){const i=t.config.links||[];if(i.length===0)return null;const a=MYe[r];return o.jsx("div",{className:a.container,children:i.map((c,s)=>o.jsxs("a",{href:c.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Qi(e,"button_click",`custom_link_${c.label}`),className:a.link,children:[o.jsx("span",{children:c.label}),o.jsx(cS,{className:`h-4 w-4 ${a.icon}`})]},s))})}const BYe={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 zYe({path:t,color:e,size:r=20}){return o.jsx("svg",{viewBox:"0 0 24 24",width:r,height:r,fill:e,children:o.jsx("path",{d:t})})}const $Ye={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 UYe({block:t,cardId:e,variant:r}){const i=t.config.platforms||[],a=$Ye[r];return i.length===0?null:o.jsxs("div",{className:a.container,children:[o.jsx("h3",{className:a.title,children:"Follow Me"}),o.jsx("div",{className:"flex flex-wrap gap-3 justify-center",children:i.map((c,s)=>{const f=BYe[c.platform.toLowerCase()];return!f||!c.url?null:o.jsx("a",{href:c.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Qi(e,"button_click",`social_${c.platform}`),className:a.linkClass,title:f.label,children:o.jsx(zYe,{path:f.icon,color:f.color})},s)})})]})}function tF({cardId:t,variant:e}){const{data:r}=CYe(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"),o.jsxs(o.Fragment,{children:[i.map(c=>{switch(c.block_type){case"video_intro":return o.jsx(NYe,{block:c,variant:e},c.id);case"testimonials":return o.jsx(LYe,{block:c,variant:e},c.id);case"specialties":return o.jsx(OYe,{block:c,variant:e},c.id);case"custom_links":return o.jsx(FYe,{block:c,cardId:t,variant:e},c.id);default:return null}}),a&&o.jsx(UYe,{block:a,cardId:t,variant:e})]})}async function VYe(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 s=a.result.split(",")[1];i({base64:s,mimeType:n})},a.onerror=()=>i(null),a.readAsDataURL(r)})}catch{return null}}function qYe(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 rF(t){const{first:e,last:r}=qYe(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 s=await VYe(t.avatarUrl);if(s){const m={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[s.mimeType]||"JPEG";n.push(`PHOTO;ENCODING=b;TYPE=${m}:${s.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),Jt.success("Contact saved!")}function GYe({card:t}){var D;const[e,r]=P.useState(!1),[n,i]=P.useState("booking"),a=((D=t.profile)==null?void 0:D.name)||"Agent",c=a.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2),s=(M,B)=>{Qi(t.id,"button_click",M),B()},f=()=>s("call",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`tel:${t.profile.phone}`:Jt.error("Phone number not available")}),m=()=>s("text",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`sms:${t.profile.phone}`:Jt.error("Phone number not available")}),x=()=>s("email",()=>{var M;(M=t.profile)!=null&&M.email?window.location.href=`mailto:${t.profile.email}`:Jt.error("Email not available")}),_=()=>{t.booking_url?s("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),Qi(t.id,"button_click","book"))},T=()=>{var M,B;Qi(t.id,"contact_saved"),rF({name:a,phone:(M=t.profile)==null?void 0:M.phone,email:(B=t.profile)==null?void 0:B.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},E=async()=>{Qi(t.id,"share_event");const M=`https://cards.relevelup.com/${t.slug}`,B="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${a}`,text:B,url:M})}catch{}else await navigator.clipboard.writeText(M),Jt.success("Link copied!")},C=()=>{i("referral"),r(!0),Qi(t.id,"button_click","refer")},N=()=>{i("connect"),r(!0),Qi(t.id,"button_click","connect")},R={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return o.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-white to-slate-50",children:[o.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[o.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&o.jsxs(Zd,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[o.jsx(Xd,{src:t.avatar_url||void 0,alt:a}),o.jsx(Qd,{className:"text-2xl font-semibold bg-primary text-primary-foreground",children:c})]}),o.jsx("h1",{className:"text-2xl font-bold text-slate-900 mb-0.5",children:a}),t.title&&o.jsx("p",{className:"text-sm font-medium text-primary mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&o.jsx("p",{className:"text-sm font-medium text-slate-500 mb-1",children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&o.jsx("p",{className:"text-xs font-medium text-slate-400 mb-3",children:t.team_name}),t.positioning_statement&&o.jsxs("p",{className:"text-base text-slate-600 italic leading-relaxed max-w-xs mx-auto",children:['"',t.positioning_statement,'"']})]}),o.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[o.jsxs(Ut,{onClick:f,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:[o.jsx(zi,{className:"h-5 w-5"}),o.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),o.jsxs(Ut,{onClick:m,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:[o.jsx(rp,{className:"h-5 w-5"}),o.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),o.jsxs(Ut,{onClick:x,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:[o.jsx(Bi,{className:"h-5 w-5"}),o.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),o.jsxs(Ut,{onClick:_,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[o.jsx(po,{className:"h-5 w-5 mr-2"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&o.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm text-slate-600",children:o.jsxs("div",{className:"text-center flex items-center gap-1",children:[o.jsx(Xc,{className:"h-4 w-4 text-amber-500 fill-amber-500"}),o.jsx("span",{className:"font-bold text-slate-900",children:"5.0"})]})}),t.review_snippet&&o.jsx("div",{className:"bg-slate-50 rounded-2xl p-4 mb-6 border border-slate-100",children:o.jsxs("p",{className:"text-sm text-slate-600 italic text-center",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&o.jsxs("div",{className:"mb-6",children:[o.jsx("h2",{className:"text-sm font-semibold text-slate-800 mb-2",children:"About Me"}),o.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:t.bio})]}),o.jsx(JM,{card:t,variant:"standard"}),o.jsx(tF,{cardId:t.id,variant:"standard"}),o.jsxs("div",{className:"space-y-2 mb-6",children:[t.show_save_contact&&o.jsxs(Ut,{variant:"ghost",onClick:T,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[o.jsx(Xl,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),t.show_leave_review&&t.review_source_url&&o.jsxs(Ut,{variant:"ghost",onClick:()=>{Qi(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:[o.jsx(Xc,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),t.show_refer_friend&&o.jsxs(Ut,{variant:"ghost",onClick:C,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[o.jsx(Al,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),o.jsxs(Ut,{variant:"ghost",onClick:N,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[o.jsx(JO,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),o.jsxs(Ut,{variant:"ghost",onClick:E,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[o.jsx(kC,{className:"h-4 w-4 mr-3 text-primary"}),"Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&o.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((M,B)=>o.jsx("a",{href:M.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Qi(t.id,"button_click",`social_${M.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:R[M.platform.toLowerCase()]||"🔗"},B))}),o.jsx("div",{className:"text-center",children:o.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),o.jsx(eF,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:a})]})}function HYe({card:t}){var D;const[e,r]=P.useState(!1),[n,i]=P.useState("booking"),a=((D=t.profile)==null?void 0:D.name)||"Agent",c=a.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2),s=(M,B)=>{Qi(t.id,"button_click",M),B()},f=()=>s("call",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`tel:${t.profile.phone}`:Jt.error("Phone number not available")}),m=()=>s("text",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`sms:${t.profile.phone}`:Jt.error("Phone number not available")}),x=()=>s("email",()=>{var M;(M=t.profile)!=null&&M.email?window.location.href=`mailto:${t.profile.email}`:Jt.error("Email not available")}),_=()=>{t.booking_url?s("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),Qi(t.id,"button_click","book"))},T=()=>{var M,B;Qi(t.id,"contact_saved"),rF({name:a,phone:(M=t.profile)==null?void 0:M.phone,email:(B=t.profile)==null?void 0:B.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},E=async()=>{Qi(t.id,"share_event");const M=`https://cards.relevelup.com/${t.slug}`,B="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${a}`,text:B,url:M})}catch{}else await navigator.clipboard.writeText(M),Jt.success("Link copied!")},C=()=>{i("referral"),r(!0),Qi(t.id,"button_click","refer")},N=()=>{i("connect"),r(!0),Qi(t.id,"button_click","connect")},R={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return o.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-[#0f1419] via-[#1a1f2e] to-[#0f1419]",children:[o.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[o.jsx("div",{className:"w-16 h-0.5 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] mx-auto mb-8"}),o.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&o.jsxs(Zd,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[o.jsx(Xd,{src:t.avatar_url||void 0,alt:a}),o.jsx(Qd,{className:"text-2xl font-serif bg-[#c9a84c]/20 text-[#e8d48b]",children:c})]}),o.jsx("h1",{className:"text-2xl font-serif font-bold text-white tracking-wide mb-0.5",children:a}),t.title&&o.jsx("p",{className:"text-sm font-medium text-[#e8d48b] mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&o.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&&o.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:t.team_name}),t.positioning_statement&&o.jsxs("p",{className:"text-base text-[#a0aec0] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',t.positioning_statement,'"']})]}),o.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:zi,label:"Call",handler:f},{icon:rp,label:"Text",handler:m},{icon:Bi,label:"Email",handler:x}].map(({icon:M,label:B,handler:V})=>o.jsxs("button",{onClick:V,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:[o.jsx(M,{className:"h-5 w-5 text-[#c9a84c]"}),o.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:B})]},B))}),o.jsxs("button",{onClick:_,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:[o.jsx(po,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&o.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm",children:o.jsxs("div",{className:"text-center flex items-center gap-1",children:[o.jsx(Xc,{className:"h-4 w-4 text-[#c9a84c] fill-[#c9a84c]"}),o.jsx("span",{className:"font-bold text-white",children:"5.0"})]})}),t.review_snippet&&o.jsx("div",{className:"bg-[#1e2636] rounded-xl p-4 mb-6 border border-[#c9a84c]/10",children:o.jsxs("p",{className:"text-sm text-[#a0aec0] italic text-center font-serif",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&o.jsxs("div",{className:"mb-6",children:[o.jsx("h2",{className:"text-sm font-semibold text-[#c9a84c] mb-2 tracking-wide uppercase",children:"About"}),o.jsx("p",{className:"text-sm text-[#a0aec0] leading-relaxed",children:t.bio})]}),o.jsx(JM,{card:t,variant:"luxury"}),o.jsx(tF,{cardId:t.id,variant:"luxury"}),o.jsxs("div",{className:"space-y-1 mb-6",children:[t.show_save_contact&&o.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:[o.jsx(Xl,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&o.jsxs("button",{onClick:()=>{Qi(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:[o.jsx(Xc,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),t.show_refer_friend&&o.jsxs("button",{onClick:C,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[o.jsx(Al,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),o.jsxs("button",{onClick:N,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[o.jsx(JO,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),o.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:[o.jsx(kC,{className:"h-4 w-4 text-[#c9a84c]"})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&o.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((M,B)=>o.jsx("a",{href:M.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Qi(t.id,"button_click",`social_${M.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:R[M.platform.toLowerCase()]||"🔗"},B))}),o.jsx("div",{className:"text-center",children:o.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),o.jsx(eF,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:a})]})}function WYe({card:t}){var B,V,G,W;const[e,r]=P.useState(!1),[n,i]=P.useState("booking"),a=((B=t.profile)==null?void 0:B.name)||"Agent",c=a.split(" ").map(X=>X[0]).join("").toUpperCase().slice(0,2),s={accent:((V=t.bold_theme_colors)==null?void 0:V.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"},f=(X,Q)=>{const re=parseInt(X.replace("#",""),16),se=Math.max(0,(re>>16)-Q),ue=Math.max(0,(re>>8&255)-Q),_e=Math.max(0,(re&255)-Q);return`#${(se<<16|ue<<8|_e).toString(16).padStart(6,"0")}`};f(s.accent,25),f(s.dark,-20),f(s.button,25);const m=(X,Q)=>{Qi(t.id,"button_click",X),Q()},x=()=>m("call",()=>{var X;(X=t.profile)!=null&&X.phone?window.location.href=`tel:${t.profile.phone}`:Jt.error("Phone number not available")}),_=()=>m("text",()=>{var X;(X=t.profile)!=null&&X.phone?window.location.href=`sms:${t.profile.phone}`:Jt.error("Phone number not available")}),T=()=>m("email",()=>{var X;(X=t.profile)!=null&&X.email?window.location.href=`mailto:${t.profile.email}`:Jt.error("Email not available")}),E=()=>{t.booking_url?m("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),Qi(t.id,"button_click","book"))},C=()=>{var X,Q;Qi(t.id,"contact_saved"),rF({name:a,phone:(X=t.profile)==null?void 0:X.phone,email:(Q=t.profile)==null?void 0:Q.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},N=async()=>{Qi(t.id,"share_event");const X=`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:X})}catch{}else await navigator.clipboard.writeText(X),Jt.success("Link copied!")},R=()=>{i("referral"),r(!0),Qi(t.id,"button_click","refer")},D=()=>{i("connect"),r(!0),Qi(t.id,"button_click","connect")},M={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return o.jsxs("div",{className:"min-h-screen",style:{backgroundColor:s.accent},children:[o.jsxs("div",{className:"px-5 pt-10 pb-14 text-center relative",style:{backgroundColor:s.dark},children:[t.show_photo&&o.jsxs(Zd,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${s.accent}`},children:[o.jsx(Xd,{src:t.avatar_url||void 0,alt:a}),o.jsx(Qd,{className:"text-2xl font-black text-white",style:{backgroundColor:s.accent},children:c})]}),o.jsx("h1",{className:"text-3xl font-black text-white tracking-tight mb-0.5",children:a}),t.title&&o.jsx("p",{className:"text-sm font-bold mb-1",style:{color:`${s.accent}cc`},children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&o.jsx("p",{className:"text-sm font-bold uppercase tracking-wider mb-1",style:{color:s.accent},children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&o.jsx("p",{className:"text-xs font-bold text-white/60 uppercase tracking-wider",children:t.team_name})]}),o.jsxs("div",{className:"max-w-md mx-auto px-5 -mt-6",children:[o.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl px-5 py-8",children:[t.positioning_statement&&o.jsx("p",{className:"text-center font-bold text-lg leading-snug mb-6 max-w-xs mx-auto",style:{color:s.dark},children:t.positioning_statement}),o.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:zi,label:"Call",handler:x},{icon:rp,label:"Text",handler:_},{icon:Bi,label:"Email",handler:T}].map(({icon:X,label:Q,handler:re})=>o.jsxs("button",{onClick:re,className:"flex flex-col items-center gap-1.5 py-4 text-white rounded-2xl transition-opacity font-bold hover:opacity-85",style:{backgroundColor:s.dark},children:[o.jsx(X,{className:"h-5 w-5"}),o.jsx("span",{className:"text-xs",children:Q})]},Q))}),o.jsxs("button",{onClick:E,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:s.button},children:[o.jsx(po,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&o.jsx("div",{className:"flex items-center justify-center gap-5 mb-6",children:t.review_snippet&&o.jsxs("div",{className:"text-center flex items-center gap-1",children:[o.jsx(Xc,{className:"h-5 w-5",style:{color:s.accent,fill:s.accent}}),o.jsx("span",{className:"font-black text-2xl",style:{color:s.dark},children:"5.0"})]})}),t.review_snippet&&o.jsx("div",{className:"rounded-2xl p-4 mb-6",style:{backgroundColor:`${s.accent}15`},children:o.jsxs("p",{className:"text-sm font-medium text-center",style:{color:s.dark},children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&o.jsxs("div",{className:"mb-6",children:[o.jsx("h2",{className:"text-xs font-black mb-2 uppercase tracking-wider",style:{color:s.accent},children:"About Me"}),o.jsx("p",{className:"text-sm text-gray-600 leading-relaxed",children:t.bio})]}),o.jsx(JM,{card:t,variant:"bold"}),o.jsx(tF,{cardId:t.id,variant:"bold"}),o.jsxs("div",{className:"space-y-1 mb-6",children:[t.show_save_contact&&o.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:s.dark},children:[o.jsx(Xl,{className:"h-4 w-4",style:{color:s.accent}})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&o.jsxs("button",{onClick:()=>{Qi(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:s.dark},children:[o.jsx(Xc,{className:"h-4 w-4",style:{color:s.accent}})," Leave a Review"]}),t.show_refer_friend&&o.jsxs("button",{onClick:R,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:s.dark},children:[o.jsx(Al,{className:"h-4 w-4",style:{color:s.accent}})," Refer a Friend"]}),o.jsxs("button",{onClick:D,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:s.dark},children:[o.jsx(JO,{className:"h-4 w-4",style:{color:s.accent}})," Connect with Me"]}),o.jsxs("button",{onClick:N,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:s.dark},children:[o.jsx(kC,{className:"h-4 w-4",style:{color:s.accent}})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&o.jsx("div",{className:"flex justify-center gap-4 mb-6",children:t.social_links.slice(0,3).map((X,Q)=>o.jsx("a",{href:X.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Qi(t.id,"button_click",`social_${X.platform}`),className:"h-10 w-10 rounded-full flex items-center justify-center text-lg transition-opacity hover:opacity-85",style:{backgroundColor:s.dark},children:M[X.platform.toLowerCase()]||"🔗"},Q))})]}),o.jsx("div",{className:"text-center py-6",children:o.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),o.jsx(eF,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:a})]})}function KYe({card:t}){var D;const[e,r]=P.useState(!1),[n,i]=P.useState("booking"),a=((D=t.profile)==null?void 0:D.name)||"Agent",c=a.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2),s=(M,B)=>{Qi(t.id,"button_click",M),B()},f=()=>s("call",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`tel:${t.profile.phone}`:Jt.error("Phone number not available")}),m=()=>s("text",()=>{var M;(M=t.profile)!=null&&M.phone?window.location.href=`sms:${t.profile.phone}`:Jt.error("Phone number not available")}),x=()=>s("email",()=>{var M;(M=t.profile)!=null&&M.email?window.location.href=`mailto:${t.profile.email}`:Jt.error("Email not available")}),_=()=>{t.booking_url?s("book",()=>window.open(t.booking_url,"_blank")):(i("booking"),r(!0),Qi(t.id,"button_click","book"))},T=()=>{var M,B;Qi(t.id,"contact_saved"),rF({name:a,phone:(M=t.profile)==null?void 0:M.phone,email:(B=t.profile)==null?void 0:B.email,brokerage:t.brokerage_name,avatarUrl:t.avatar_url,cardUrl:window.location.href})},E=async()=>{Qi(t.id,"share_event");const M=`https://cards.relevelup.com/${t.slug}`,B="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${a}`,text:B,url:M})}catch{}else await navigator.clipboard.writeText(M),Jt.success("Link copied!")},C=()=>{i("referral"),r(!0),Qi(t.id,"button_click","refer")},N=()=>{i("connect"),r(!0),Qi(t.id,"button_click","connect")},R={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return o.jsxs("div",{className:"min-h-screen bg-[#f5f1eb]",children:[o.jsx("div",{className:"bg-[#1b3a4b] h-2"}),o.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[o.jsxs("div",{className:"text-center mb-8",children:[t.show_photo&&o.jsxs(Zd,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[o.jsx(Xd,{src:t.avatar_url||void 0,alt:a}),o.jsx(Qd,{className:"text-2xl font-serif bg-[#1b3a4b] text-white",children:c})]}),o.jsx("h1",{className:"text-2xl font-serif font-bold text-[#1b3a4b] mb-0.5",children:a}),t.title&&o.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:t.title}),t.brokerage_name&&!t.brokerage_logo_url&&o.jsx("p",{className:"text-sm font-medium text-[#5a7a6f] mb-1",children:t.brokerage_name}),t.team_name&&!t.team_logo_url&&o.jsx("p",{className:"text-xs font-medium text-[#a0aec0] mb-3",children:t.team_name}),t.positioning_statement&&o.jsxs("p",{className:"text-base text-[#4a5568] italic leading-relaxed max-w-xs mx-auto font-serif",children:['"',t.positioning_statement,'"']})]}),o.jsx("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[{icon:zi,label:"Call",handler:f},{icon:rp,label:"Text",handler:m},{icon:Bi,label:"Email",handler:x}].map(({icon:M,label:B,handler:V})=>o.jsxs("button",{onClick:V,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:[o.jsx(M,{className:"h-5 w-5 text-[#1b3a4b]"}),o.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:B})]},B))}),o.jsxs("button",{onClick:_,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:[o.jsx(po,{className:"h-5 w-5"}),t.custom_cta_label||"Book a Call"]}),t.show_credentials&&t.review_snippet&&o.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:o.jsx("div",{className:"flex items-center justify-center gap-6",children:o.jsxs("div",{className:"text-center flex items-center gap-1",children:[o.jsx(Xc,{className:"h-4 w-4 text-[#d4a843] fill-[#d4a843]"}),o.jsx("span",{className:"font-bold text-[#1b3a4b] font-serif",children:"5.0"})]})})}),t.review_snippet&&o.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:o.jsxs("p",{className:"text-sm text-[#4a5568] italic text-center font-serif",children:['"',t.review_snippet,'"']})}),t.show_bio&&t.bio&&o.jsxs("div",{className:"mb-6",children:[o.jsx("h2",{className:"text-sm font-semibold text-[#1b3a4b] mb-2 font-serif",children:"About"}),o.jsx("p",{className:"text-sm text-[#4a5568] leading-relaxed",children:t.bio})]}),o.jsx(JM,{card:t,variant:"classic"}),o.jsx(tF,{cardId:t.id,variant:"classic"}),o.jsxs("div",{className:"bg-white rounded-lg border border-[#d4cfc5] shadow-sm divide-y divide-[#e8e3db] mb-6",children:[t.show_save_contact&&o.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:[o.jsx(Xl,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),t.show_leave_review&&t.review_source_url&&o.jsxs("button",{onClick:()=>{Qi(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:[o.jsx(Xc,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),t.show_refer_friend&&o.jsxs("button",{onClick:C,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[o.jsx(Al,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),o.jsxs("button",{onClick:N,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[o.jsx(JO,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),o.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:[o.jsx(kC,{className:"h-4 w-4 text-[#5a7a6f]"})," Share My Card"]})]}),t.show_social_links&&t.social_links&&t.social_links.length>0&&o.jsx("div",{className:"flex justify-center gap-4 mb-8",children:t.social_links.slice(0,3).map((M,B)=>o.jsx("a",{href:M.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Qi(t.id,"button_click",`social_${M.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:R[M.platform.toLowerCase()]||"🔗"},B))}),o.jsx("div",{className:"text-center",children:o.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),o.jsx(eF,{open:e,onOpenChange:r,cardId:t.id,type:n,agentName:a})]})}function YYe({card:t}){switch(t.theme){case"luxury":return o.jsx(HYe,{card:t});case"bold":return o.jsx(WYe,{card:t});case"classic":return o.jsx(KYe,{card:t});case"standard":default:return o.jsx(GYe,{card:t})}}function ZYe(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 XYe(t){return`https://docs.google.com/gview?url=${encodeURIComponent(t)}&embedded=true`}function QYe(){if(typeof window>"u")return null;const t=ZYe(new URLSearchParams(window.location.search).get("oh_disclosure"));return t?o.jsx("div",{className:"sticky top-0 z-50 bg-primary text-primary-foreground shadow-md",children:o.jsxs("div",{className:"mx-auto flex max-w-md items-center justify-between gap-3 px-4 py-2.5",children:[o.jsx("span",{className:"text-sm font-medium",children:"Thanks for visiting the open house!"}),o.jsxs("a",{href:XYe(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:[o.jsx(ep,{className:"h-3.5 w-3.5"})," See Disclosures"]})]})}):null}function JYe(){const t=Wi();P.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]);const e=t.pathname.slice(1);return!e||e===""?o.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Agent Cards"}),o.jsx("p",{className:"text-slate-500",children:"Visit a specific agent's card URL to view their digital business card."})]})}):o.jsx(eZe,{slug:e})}function eZe({slug:t}){return o.jsx(tZe,{slug:t})}function tZe({slug:t}){var a;const{data:e,isLoading:r,error:n}=AYe(t);if(P.useEffect(()=>{e!=null&&e.id&&Qi(e.id,"card_view")},[e==null?void 0:e.id]),r)return o.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:o.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center gap-4",children:[o.jsx(ol,{className:"h-28 w-28 rounded-full"}),o.jsx(ol,{className:"h-6 w-48"}),o.jsx(ol,{className:"h-4 w-36"})]}),o.jsx(ol,{className:"h-12 w-full"}),o.jsx(ol,{className:"h-12 w-full"})]})});if(n||!e)return o.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),o.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 o.jsxs(o.Fragment,{children:[o.jsxs(jl,{children:[o.jsxs("title",{children:[i," | Real Estate Agent"]}),o.jsx("meta",{name:"description",content:e.positioning_statement||`Connect with ${i}, your trusted real estate professional.`}),o.jsx("meta",{property:"og:title",content:`${i} | Real Estate Agent`}),o.jsx("meta",{property:"og:description",content:e.positioning_statement||`Connect with ${i}`}),e.avatar_url&&o.jsx("meta",{property:"og:image",content:e.avatar_url})]}),o.jsx(QYe,{}),o.jsx(YYe,{card:e})]})}function rZe({presentationId:t,ctaLabel:e,agentName:r,prefillName:n,prefillEmail:i,prefillPhone:a}){const[c,s]=P.useState(n||""),[f,m]=P.useState(i||""),[x,_]=P.useState(a||""),[T,E]=P.useState(""),[C,N]=P.useState(""),[R,D]=P.useState(!1),[M,B]=P.useState(!1),V=async G=>{if(G.preventDefault(),!c.trim()){Jt.error("Please enter your name");return}D(!0);try{const{error:W}=await Le.from("smart_presentation_leads").insert({presentation_id:t,name:c.trim(),email:f.trim()||null,phone:x.trim()||null,intent:T||null,message:C.trim()||null});if(W)throw W;try{await Le.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{}Le.functions.invoke("presentation-lead-notify",{body:{presentationId:t,name:c.trim(),email:f.trim()||void 0,phone:x.trim()||void 0,intent:T||void 0,message:C.trim()||void 0}}).catch(X=>console.error("Presentation lead notify failed:",X)),B(!0)}catch{Jt.error("Something went wrong. Please try again.")}finally{D(!1)}};return M?o.jsxs("div",{className:"text-center py-8",children:[o.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-4",children:o.jsx(Ao,{className:"h-8 w-8 text-emerald-600"})}),o.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),o.jsx("p",{className:"text-gray-500",children:r?`${r} will be in touch soon.`:"We'll be in touch soon."})]}):o.jsxs("form",{onSubmit:V,className:"space-y-4 max-w-md mx-auto",children:[o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"pres-lead-name",children:"Name *"}),o.jsx(Ur,{id:"pres-lead-name",value:c,onChange:G=>s(G.target.value),placeholder:"Your name",required:!0})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"pres-lead-phone",children:"Phone"}),o.jsx(Ur,{id:"pres-lead-phone",type:"tel",value:x,onChange:G=>_(G.target.value),placeholder:"(555) 123-4567"})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"pres-lead-email",children:"Email"}),o.jsx(Ur,{id:"pres-lead-email",type:"email",value:f,onChange:G=>m(G.target.value),placeholder:"you@example.com"})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),o.jsxs(Ba,{value:T,onValueChange:E,children:[o.jsx(ja,{children:o.jsx(za,{placeholder:"Select one"})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"buy",children:"Buy a home"}),o.jsx(wn,{value:"sell",children:"Sell my home"}),o.jsx(wn,{value:"both",children:"Buy & Sell"}),o.jsx(wn,{value:"other",children:"Something else"})]})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"pres-lead-message",children:"Message (optional)"}),o.jsx(Ur,{id:"pres-lead-message",value:C,onChange:G=>N(G.target.value),placeholder:"Anything you'd like us to know"})]}),o.jsx(Ut,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:R,children:R?"Sending...":e})]})}function nZe(){const t=Wi();P.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]);const e=t.pathname.slice(1);return!e||e===""?o.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Smart Presentations"}),o.jsx("p",{className:"text-slate-500",children:"Visit a specific presentation URL to view it."})]})}):o.jsx(iZe,{shareToken:e})}function iZe({shareToken:t}){var C;const[e,r]=P.useState(null),[n,i]=P.useState(!0),[a,c]=P.useState(0),[s,f]=P.useState(!1);P.useEffect(()=>{m()},[t]);const m=async()=>{const{data:N,error:R}=await Le.from("smart_presentations").select("*").eq("share_token",t).eq("status","published").single();if(R||!N){f(!0),i(!1);return}const{data:D}=await Le.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",N.owner_user_id).single();let M;if(D!=null&&D.brokerage_id){const{data:V}=await Le.from("brokerages").select("name").eq("id",D.brokerage_id).single();M=(V==null?void 0:V.name)||void 0}let B=null;if(N.contact_id){const{data:V}=await Le.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",N.contact_id).single();B=V}r({...N,owner_name:D==null?void 0:D.name,owner_email:D==null?void 0:D.email,owner_phone:D==null?void 0:D.phone,owner_avatar:D==null?void 0:D.avatar_url,owner_title:(D==null?void 0:D.title)||void 0,brokerage_name:M,contact_name:B?[B.first_name,B.last_name].filter(Boolean).join(" "):void 0,contact_email:(B==null?void 0:B.email)||void 0,contact_phone:(B==null?void 0:B.phone)||void 0}),i(!1);try{await Le.rpc("log_presentation_view",{p_presentation_id:N.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},x=async()=>{if(e){try{await Le.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")}},_=N=>{const R=N.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(R)return`https://www.youtube.com/embed/${R[1]}?rel=0`;if(N.includes("iframe.mediadelivery.net/play/")){const B=N.replace("/play/","/embed/"),V=B.includes("?")?"&":"?";return`${B}${V}responsive=true`}if(N.includes("iframe.mediadelivery.net")){const B=N.includes("?")?"&":"?";return`${N}${B}responsive=true`}const D=N.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(D)return`https://www.loom.com/embed/${D[1]}`;const M=N.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return M?`https://iframe.mediadelivery.net/embed/${M[1]}/${M[2]}?responsive=true`:N};if(n)return o.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:o.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[o.jsx(ol,{className:"h-12 w-3/4 mx-auto"}),o.jsx(ol,{className:"h-64 w-full"}),o.jsx(ol,{className:"h-8 w-1/2 mx-auto"})]})});if(s||!e)return o.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),o.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const T=e.sections.filter(N=>N.is_visible!==!1),E=T[a];return o.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[o.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:o.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:o.jsxs("div",{className:"flex items-center gap-3",children:[e.owner_avatar&&o.jsx("img",{src:e.owner_avatar,alt:e.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),o.jsxs("div",{className:"text-right text-sm",children:[o.jsx("p",{className:"font-semibold text-gray-900",children:e.owner_name}),e.owner_title&&o.jsx("p",{className:"text-gray-500 text-xs",children:e.owner_title}),e.brokerage_name&&!e.owner_title&&o.jsx("p",{className:"text-gray-500 text-xs",children:e.brokerage_name})]})]})})}),o.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[o.jsxs("div",{className:"text-center mb-8",children:[o.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&&o.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",o.jsx("strong",{children:e.property_address}),"."]})]}),o.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[o.jsxs("div",{className:"md:col-span-3",children:[E!=null&&E.video_url?o.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:o.jsx("iframe",{src:_(E.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"})}):E!=null&&E.image_url?o.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:o.jsx("img",{src:E.image_url,alt:E.title,className:"w-full h-auto object-cover",loading:"lazy"})}):o.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:[o.jsx("span",{className:"text-5xl mb-3",children:E==null?void 0:E.icon}),o.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:E==null?void 0:E.title}),o.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:E==null?void 0:E.description})]}),(E==null?void 0:E.text)&&o.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:E.text}})]}),o.jsx("div",{className:"md:col-span-2 space-y-3",children:T.map((N,R)=>o.jsx("button",{onClick:()=>c(R),className:sr("w-full text-left p-4 rounded-xl border transition-all",a===R?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(R+1).padStart(2,"0"),"."]}),o.jsxs("div",{children:[o.jsx("span",{className:"mr-2",children:N.icon}),o.jsx("span",{className:"font-semibold text-gray-900",children:N.title}),o.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:N.description})]})]})},R))})]}),o.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&&o.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"}),o.jsx("h3",{className:"text-lg font-bold text-gray-900",children:e.owner_name}),e.owner_title&&o.jsx("p",{className:"text-sm text-gray-500",children:e.owner_title}),e.brokerage_name&&o.jsx("p",{className:"text-sm text-gray-500",children:e.brokerage_name}),o.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[e.owner_phone&&o.jsx("a",{href:`tel:${e.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:e.owner_phone}),e.owner_email&&o.jsx("a",{href:`mailto:${e.owner_email}`,className:"hover:text-blue-600 transition-colors",children:e.owner_email})]})]}),e.cta_label&&o.jsxs("div",{className:"text-center mt-8 py-8",children:[o.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(C=e.cta_url)!=null&&C.trim()?o.jsxs(Ut,{size:"lg",onClick:x,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[e.cta_label,o.jsx(cS,{className:"h-5 w-5 ml-2"})]}):o.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:o.jsx(rZe,{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})})]})]}),o.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 j6t(){const{user:t}=qn(),e=Ji(),{data:r}=SS();return wr({queryKey:["open-houses",e,r==null?void 0:r.teamId,r==null?void 0:r.role],queryFn:async()=>{const{data:n,error:i}=await Le.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:s}=await Le.rpc("get_team_open_houses",{_user_id:e});if(!s&&c){const f=[...new Set(c.map(_=>_.agent_id))],m={};if(f.length>0){const{data:_}=await Le.from("profiles").select("id, name").in("id",f);_==null||_.forEach(T=>{T.name&&(m[T.id]=T.name)})}const x=c.map(_=>({..._,agent_name:m[_.agent_id]||void 0}));a=[...a,...x]}}return a.sort((c,s)=>s.event_date.localeCompare(c.event_date)),a},enabled:!!t&&!!e})}function I6t(t){const{user:e}=qn();return wr({queryKey:["open-house",t],queryFn:async()=>{const{data:r,error:n}=await Le.from("open_houses").select("*").eq("id",t).single();if(n)throw n;return r},enabled:!!e&&!!t})}function P6t(t){const{user:e}=qn(),r=Nr();return P.useEffect(()=>{if(!t)return;const n=`visitors-${t}-${Math.random().toString(36).slice(2,10)}`,i=Le.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()=>{Le.removeChannel(i)}},[t,r]),wr({queryKey:["open-house-visitors",t],queryFn:async()=>{const{data:n,error:i}=await Le.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 N6t(){const t=Nr(),e=Ji();return Cr({mutationFn:async r=>{const{data:n,error:i}=await Le.from("open_houses").insert({...r,agent_id:e}).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["open-houses"]}),Ts({title:"Open house created!"})},onError:r=>{Ts({title:"Error",description:r.message,variant:"destructive"})}})}function R6t(){const t=Nr();return Cr({mutationFn:async({id:e,...r})=>{const{error:n}=await Le.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 L6t(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("open_houses").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["open-houses"]}),Ts({title:"Open house deleted"})}})}function T0e(t){return wr({queryKey:["public-open-house",t],queryFn:async()=>{const{data:e,error:r}=await Le.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 Le.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 D6t(t){const{user:e}=qn();return wr({queryKey:["survey-questions",t],queryFn:async()=>{const{data:r,error:n}=await Le.from("open_house_survey_questions").select("*").eq("open_house_id",t).order("sort_order");if(n)throw n;return r},enabled:!!e&&!!t})}function sZe(t){return wr({queryKey:["public-survey-questions",t],queryFn:async()=>{const{data:e,error:r}=await Le.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 aZe(){return Cr({mutationFn:async t=>{const{error:e}=await Le.from("open_house_survey_responses").insert(t);if(e)throw e}})}function O6t(t){const{user:e}=qn();return wr({queryKey:["survey-responses",t],queryFn:async()=>{const{data:r,error:n}=await Le.from("open_house_survey_questions").select("*").eq("open_house_id",t).order("sort_order");if(n)throw n;const i=(r||[]).map(s=>s.id);if(i.length===0)return{questions:[],responses:[]};const{data:a,error:c}=await Le.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 M6t(){const t=Nr();return Cr({mutationFn:async e=>{const{data:r,error:n}=await Le.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 F6t(){const t=Nr();return Cr({mutationFn:async({id:e,open_house_id:r,...n})=>{const{error:i}=await Le.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 B6t(){const t=Nr();return Cr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Le.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 z6t(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.rpc("seed_default_survey_questions",{_open_house_id:e});if(r)throw r},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["survey-questions",r]})}})}function oZe(){return Cr({mutationFn:async t=>{const e=crypto.randomUUID(),{error:r}=await Le.from("open_house_visitors").insert({...t,id:e});if(r)throw r;return{id:e}}})}function lZe(){return Cr({mutationFn:async({visitor_id:t,...e})=>{const{error:r}=await Le.from("open_house_visitors").update(e).eq("id",t);if(r)throw r}})}function cZe(){return Cr({mutationFn:async t=>{await Le.rpc("increment_open_house_scan",{_slug:t})}})}async function E0e(t){const{data:e,error:r}=await Le.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(f=>f.id),{data:a,error:c}=await Le.from("open_house_room_media").select("*").in("room_id",i).order("sort_order");if(c)throw c;const s={};return(a||[]).forEach(f=>{var x;const m=f;(s[x=m.room_id]||(s[x]=[])).push(m)}),n.map(f=>({...f,media:s[f.id]||[]}))}function $6t(t){const{user:e}=qn();return wr({queryKey:["open-house-rooms",t],queryFn:()=>E0e(t),enabled:!!e&&!!t})}function uZe(t){return wr({queryKey:["public-open-house-rooms",t],queryFn:()=>E0e(t),enabled:!!t})}function U6t(){const t=Nr();return Cr({mutationFn:async e=>{const{data:r,error:n}=await Le.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 V6t(){const t=Nr();return Cr({mutationFn:async({id:e,open_house_id:r,...n})=>{const{error:i}=await Le.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 q6t(){const t=Nr();return Cr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Le.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 G6t(){const t=Nr();return Cr({mutationFn:async({open_house_id:e,...r})=>{const{data:n,error:i}=await Le.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 H6t(){const t=Nr();return Cr({mutationFn:async({id:e,open_house_id:r})=>{const{error:n}=await Le.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 W6t(){const t=Nr();return Cr({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(s=>[s.id,s])),c=r.map((s,f)=>({...a.get(s),sort_order:f})).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 K6t(){const t=Nr();return Cr({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 s=new Map(c.media.map(f=>[f.id,f]));return{...c,media:n.map((f,m)=>{const x=s.get(f);return x?{...x,sort_order:m}: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 Y6t(t){const{user:e}=qn();return wr({queryKey:["open-house-leads",t],queryFn:async()=>{const{data:r,error:n}=await Le.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 Z6t(){const t=Nr();return Cr({mutationFn:async({id:e,status:r,open_house_id:n})=>{const{error:i}=await Le.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 nF="Switch",[dZe,X6t]=Ho(nF),[hZe,fZe]=dZe(nF),A0e=P.forwardRef((t,e)=>{const{__scopeSwitch:r,name:n,checked:i,defaultChecked:a,required:c,disabled:s,value:f="on",onCheckedChange:m,form:x,..._}=t,[T,E]=P.useState(null),C=Wn(e,B=>E(B)),N=P.useRef(!1),R=T?x||!!T.closest("form"):!0,[D,M]=ad({prop:i,defaultProp:a??!1,onChange:m,caller:nF});return o.jsxs(hZe,{scope:r,checked:D,disabled:s,children:[o.jsx(rn.button,{type:"button",role:"switch","aria-checked":D,"aria-required":c,"data-state":I0e(D),"data-disabled":s?"":void 0,disabled:s,value:f,..._,ref:C,onClick:Or(t.onClick,B=>{M(V=>!V),R&&(N.current=B.isPropagationStopped(),N.current||B.stopPropagation())})}),R&&o.jsx(j0e,{control:T,bubbles:!N.current,name:n,value:f,checked:D,required:c,disabled:s,form:x,style:{transform:"translateX(-100%)"}})]})});A0e.displayName=nF;var k0e="SwitchThumb",C0e=P.forwardRef((t,e)=>{const{__scopeSwitch:r,...n}=t,i=fZe(k0e,r);return o.jsx(rn.span,{"data-state":I0e(i.checked),"data-disabled":i.disabled?"":void 0,...n,ref:e})});C0e.displayName=k0e;var pZe="SwitchBubbleInput",j0e=P.forwardRef(({__scopeSwitch:t,control:e,checked:r,bubbles:n=!0,...i},a)=>{const c=P.useRef(null),s=Wn(c,a),f=HC(r),m=DC(e);return P.useEffect(()=>{const x=c.current;if(!x)return;const _=window.HTMLInputElement.prototype,E=Object.getOwnPropertyDescriptor(_,"checked").set;if(f!==r&&E){const C=new Event("click",{bubbles:n});E.call(x,r),x.dispatchEvent(C)}},[f,r,n]),o.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:r,...i,tabIndex:-1,ref:s,style:{...i.style,...m,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});j0e.displayName=pZe;function I0e(t){return t?"checked":"unchecked"}var P0e=A0e,mZe=C0e;const kS=P.forwardRef(({className:t,...e},r)=>o.jsx(P0e,{className:sr("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:o.jsx(mZe,{className:sr("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")})}));kS.displayName=P0e.displayName;const gZe=["Excellent","Good","Neutral","Bad","Very Bad"],yZe=[5,4,3,2,1];function xZe({questions:t,visitorId:e,onComplete:r,onSkip:n}){const i=aZe(),[a,c]=P.useState({}),s=t.filter(T=>T.question_type==="rating"),f=t.filter(T=>T.question_type!=="rating"),m=(T,E)=>{c(C=>({...C,[T]:{rating_value:E}}))},x=(T,E)=>{c(C=>({...C,[T]:{text_value:E}}))},_=async()=>{const T=Object.entries(a).filter(([,E])=>E.rating_value!=null||E.text_value&&E.text_value.trim()).map(([E,C])=>{var N;return{visitor_id:e,question_id:E,rating_value:C.rating_value??null,text_value:((N=C.text_value)==null?void 0:N.trim())||null}});if(T.length>0)try{await i.mutateAsync(T)}catch{}r()};return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Quick Feedback"}),o.jsx("button",{onClick:n,className:"text-sm text-slate-400 hover:text-slate-600 underline",children:"Skip"})]}),o.jsx("p",{className:"text-sm text-slate-500 -mt-2",children:"Your feedback helps the agent — totally optional!"}),s.length>0&&o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("div",{className:"flex-1"}),gZe.map(T=>o.jsx("div",{className:"w-12 text-center",children:o.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:T})},T))]}),s.map(T=>o.jsxs("div",{className:"flex items-center gap-1 py-1.5 border-b border-slate-100 last:border-0",children:[o.jsx("span",{className:"flex-1 text-sm text-slate-700 pr-2",children:T.question_text}),yZe.map(E=>{var C;return o.jsx("div",{className:"w-12 flex justify-center",children:o.jsx("button",{type:"button",onClick:()=>m(T.id,E),className:`w-6 h-6 rounded-full border-2 transition-all ${((C=a[T.id])==null?void 0:C.rating_value)===E?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},E)})]},T.id))]}),f.map(T=>{var E;return o.jsxs("div",{children:[o.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:T.question_text}),o.jsx(hd,{value:((E=a[T.id])==null?void 0:E.text_value)||"",onChange:C=>x(T.id,C.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},T.id)}),o.jsx(Ut,{onClick:_,disabled:i.isPending,className:"w-full h-12 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:i.isPending?o.jsx(Cu,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function z6(t){return/iframe\.mediadelivery\.net\/embed\//.test(t)}function _Ze({rooms:t}){var _;const[e,r]=P.useState(((_=t[0])==null?void 0:_.id)||""),[n,i]=P.useState(null),a=t.find(T=>T.id===e)||t[0],c=n!==null?a==null?void 0:a.media[n]:null,s=(a==null?void 0:a.media.length)??0,f=()=>i(null),m=()=>i(T=>T===null||s===0?T:(T-1+s)%s),x=()=>i(T=>T===null||s===0?T:(T+1)%s);return P.useEffect(()=>{if(n===null)return;const T=E=>{E.key==="Escape"?f():E.key==="ArrowLeft"?m():E.key==="ArrowRight"&&x()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[n,s]),t.length?o.jsxs("div",{className:"hidden md:block",children:[o.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:o.jsx("div",{className:"flex gap-2 min-w-max",children:t.map(T=>o.jsxs("button",{onClick:()=>r(T.id),className:sr("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",e===T.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[T.name,o.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:T.media.length})]},T.id))})}),a&&o.jsxs("div",{className:"mt-6",children:[o.jsx("h3",{className:"text-2xl font-bold",children:a.name}),a.description&&o.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:a.description}),a.media.length===0?o.jsx("p",{className:"text-white/40 text-sm mt-6 italic",children:"No media yet for this room."}):o.jsx("div",{className:"mt-5 grid grid-cols-2 lg:grid-cols-3 gap-3",children:a.media.map((T,E)=>o.jsx("button",{onClick:()=>i(E),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:T.kind==="video"?o.jsxs(o.Fragment,{children:[z6(T.url)?o.jsx("div",{className:"absolute inset-0 bg-slate-900"}):o.jsx("video",{src:T.url,className:"w-full h-full object-cover"}),o.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/50 transition",children:o.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:o.jsx(dA,{className:"h-5 w-5 text-slate-900"})})})]}):o.jsx("img",{src:T.url,alt:a.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},T.id))})]}),c&&a&&o.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:f,children:[o.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:[a.name," — ",(n??0)+1," / ",s]}),o.jsx("button",{onClick:T=>{T.stopPropagation(),f()},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:"×"}),s>1&&o.jsx("button",{onClick:T=>{T.stopPropagation(),m()},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:o.jsx($m,{className:"h-6 w-6"})}),c.kind==="video"?z6(c.url)?o.jsx("iframe",{src:`${c.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:T=>T.stopPropagation()},c.url):o.jsx("video",{src:c.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:T=>T.stopPropagation()},c.url):o.jsx("img",{src:c.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:T=>T.stopPropagation()}),s>1&&o.jsx("button",{onClick:T=>{T.stopPropagation(),x()},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:o.jsx(th,{className:"h-6 w-6"})})]})]}):null}function vZe({rooms:t}){var s;const e=[];t.forEach(f=>{e.push({type:"cover",roomId:f.id,roomName:f.name,description:f.description,mediaCount:f.media.length}),f.media.forEach((m,x)=>{e.push({type:"media",roomId:f.id,roomName:f.name,url:m.url,kind:m.kind,index:x,total:f.media.length})})});const r=P.useRef(null),[n,i]=P.useState(0);P.useEffect(()=>{const f=r.current;if(!f)return;let m=0;const x=()=>{cancelAnimationFrame(m),m=requestAnimationFrame(()=>{const _=Math.round(f.scrollLeft/f.clientWidth);i(_)})};return f.addEventListener("scroll",x,{passive:!0}),()=>{f.removeEventListener("scroll",x),cancelAnimationFrame(m)}},[]);const a=f=>{const m=r.current;m&&m.scrollTo({left:f*m.clientWidth,behavior:"smooth"})};if(!e.length)return null;const c=(s=e[n])==null?void 0:s.roomId;return o.jsxs("div",{className:"md:hidden -mx-5",children:[o.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:o.jsx("div",{className:"flex gap-2 min-w-max",children:t.map(f=>{const m=e.findIndex(_=>_.roomId===f.id),x=c===f.id;return o.jsx("button",{onClick:()=>a(m),className:sr("px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition",x?"bg-white text-slate-900":"bg-white/10 text-white/80"),children:f.name},f.id)})})}),o.jsx("div",{ref:r,className:"flex overflow-x-auto snap-x snap-mandatory scroll-smooth no-scrollbar",style:{scrollSnapType:"x mandatory"},children:e.map((f,m)=>o.jsx("div",{className:"shrink-0 w-screen snap-center",children:o.jsxs("div",{className:"w-full aspect-[9/16] max-h-[75vh] bg-slate-900 relative",children:[f.type==="cover"?o.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:[o.jsx("p",{className:"text-xs uppercase tracking-widest text-white/40 mb-2",children:"Next room"}),o.jsx("h3",{className:"text-3xl font-bold",children:f.roomName}),f.description&&o.jsx("p",{className:"text-white/70 text-sm mt-3 max-w-xs",children:f.description}),o.jsxs("p",{className:"text-white/40 text-xs mt-5",children:[f.mediaCount," ",f.mediaCount===1?"item":"items"," — swipe to view →"]})]}):f.kind==="video"?z6(f.url)?o.jsx("iframe",{src:f.url,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full h-full"}):o.jsx("video",{src:f.url,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):o.jsx("img",{src:f.url,alt:f.roomName,className:"w-full h-full object-cover"}),f.type==="media"&&o.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-center justify-between pointer-events-none",children:[o.jsx("div",{className:"px-3 py-1 rounded-full bg-black/50 backdrop-blur-sm text-xs text-white font-medium",children:f.roomName}),o.jsxs("div",{className:"px-2.5 py-1 rounded-full bg-black/50 backdrop-blur-sm text-[10px] text-white/80",children:[f.index+1," / ",f.total]})]})]})},m))}),o.jsxs("div",{className:"flex items-center justify-between px-5 mt-3",children:[o.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:[o.jsx($m,{className:"h-4 w-4"})," Prev"]}),o.jsxs("span",{className:"text-xs text-white/50",children:[n+1," / ",e.length]}),o.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 ",o.jsx(th,{className:"h-4 w-4"})]})]})]})}const HB={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:rp},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:po},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:ep},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:ym}},bZe=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function wZe(t){return t==null||t<=0?null:`$${t.toLocaleString("en-US")}`}function SZe({openHouse:t,visitorId:e,visitorName:r,visitorEmail:n,visitorPhone:i,previewMode:a=!1}){var er;const c=t.profiles,s=((er=c==null?void 0:c.name)==null?void 0:er.split(" ").map(wt=>wt[0]).join("").slice(0,2))||"?",f=t.brand_color_override||null,[m,x]=P.useState(null),[_,T]=P.useState(""),[E,C]=P.useState(n||""),[N,R]=P.useState(i||""),[D,M]=P.useState(!1),[B,V]=P.useState(null),[G,W]=P.useState(""),[X,Q]=P.useState(""),[re,se]=P.useState(""),[ue,_e]=P.useState([]),[Se,ve]=P.useState(""),[Oe,Ae]=P.useState(""),[we,ge]=P.useState(""),[Ne,Ie]=P.useState(""),Te=wZe(t.price),be=t.tour_mode==="rooms",{data:We=[]}=uZe(be?t.id:void 0),rt=[t.enable_question&&"question",t.enable_showing&&"showing",t.enable_disclosures&&"disclosure",t.enable_offer&&"offer"].filter(Boolean),at=wt=>{x(wt),T(""),W(""),Q(""),se(""),_e([]),ve(""),Ae(""),ge(""),Ie("")},Et=()=>{x(null)},_t=wt=>{_e(or=>or.includes(wt)?or.filter(Sr=>Sr!==wt):[...or,wt])},Vt=wt=>wt==="showing"?{preferred_date:G||null,preferred_time:X||null,alternate_date:re||null}:wt==="disclosure"?{requested_documents:ue}:wt==="offer"?{offer_amount:Se||null,financing:Oe||null,timeline:we||null,pre_approved:Ne||null}:{},mt=m?m==="showing"?!!G:m==="question"?_.trim().length>0:!0:!1,Pt=async()=>{if(m){if(a){Ts({title:"Preview mode",description:"Lead not sent — this is just a preview."}),V(m),setTimeout(()=>{x(null),V(null)},1500);return}M(!0);try{const wt=Vt(m),{error:or}=await Le.from("open_house_leads").insert({open_house_id:t.id,visitor_id:e,action_type:m,payload:{message:_.trim()||null,email:E.trim()||null,phone:N.trim()||null,visitor_name:r,...wt}});if(or)throw or;Le.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:t.id,visitor_id:e,action_type:m,message:_.trim()||null,visitor_name:r,visitor_email:E.trim()||null,visitor_phone:N.trim()||null,extras:wt}}).catch(()=>{}),V(m),Ts({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{Et(),V(null)},1400)}catch(wt){Ts({title:"Something went wrong",description:wt.message,variant:"destructive"})}finally{M(!1)}}};return o.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[o.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[t.hero_video_url?o.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?o.jsx("img",{src:t.photo_url,alt:t.property_address,className:"w-full h-full object-cover"}):o.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),o.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),o.jsxs("div",{className:"max-w-3xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[o.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[o.jsx("h1",{className:"text-2xl font-bold leading-tight",children:t.property_address}),t.city&&o.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[o.jsx(na,{className:"h-3.5 w-3.5"}),t.city,t.state?`, ${t.state}`:""," ",t.zip]}),Te&&o.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:Te}),o.jsxs("div",{className:"flex flex-wrap gap-4 mt-4 text-sm text-white/80",children:[t.beds!=null&&o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(TC,{className:"h-4 w-4"}),t.beds," bd"]}),t.baths!=null&&o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(lS,{className:"h-4 w-4"}),t.baths," ba"]}),t.sqft!=null&&o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(gG,{className:"h-4 w-4"}),t.sqft.toLocaleString()," sqft"]})]}),t.property_description?o.jsx("p",{className:"text-white/80 text-sm mt-5 whitespace-pre-wrap leading-relaxed",children:t.property_description}):t.agent_greeting&&o.jsxs("p",{className:"text-white/70 text-sm mt-5 border-l-2 border-white/20 pl-3 italic",children:['"',t.agent_greeting,'"']})]}),c&&o.jsxs("div",{className:"mt-5 flex items-center gap-3 bg-white/5 border border-white/10 rounded-xl p-4",children:[o.jsxs(Zd,{className:"h-12 w-12 ring-2 ring-white/20",style:f?{boxShadow:`0 0 0 2px ${f}`}:void 0,children:[o.jsx(Xd,{src:c.avatar_url||"",alt:c.name||""}),o.jsx(Qd,{className:"bg-white/10 text-white",children:s})]}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"font-semibold text-white truncate",children:c.name}),c.title&&o.jsx("p",{className:"text-xs text-white/60 truncate",children:c.title})]}),(c.phone||c.email)&&o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.phone&&o.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:f?{backgroundColor:`${f}33`,color:"white"}:void 0,children:o.jsx(zi,{className:"h-4 w-4"})}),c.email&&o.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:f?{backgroundColor:`${f}33`,color:"white"}:void 0,children:o.jsx(Bi,{className:"h-4 w-4"})})]})]}),be&&We.length>0&&o.jsxs("div",{className:"mt-8",children:[o.jsx(_Ze,{rooms:We}),o.jsx(vZe,{rooms:We})]}),rt.length>0&&o.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:rt.map(wt=>{const or=HB[wt],Sr=or.icon;return o.jsxs("button",{onClick:()=>at(wt),className:"flex items-center gap-3 p-4 rounded-xl bg-white text-slate-900 hover:bg-white/90 transition-colors text-left",children:[o.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:f?{backgroundColor:`${f}1a`,color:f}:{backgroundColor:"#f1f5f9",color:"#334155"},children:o.jsx(Sr,{className:"h-5 w-5"})}),o.jsx("span",{className:"font-medium text-sm",children:or.label})]},wt)})}),o.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),o.jsx(Xge,{open:!!m,onOpenChange:wt=>!wt&&Et(),children:o.jsx(d9,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:m&&o.jsxs(o.Fragment,{children:[o.jsxs(Jge,{className:"text-left",children:[o.jsx(eye,{children:HB[m].title}),o.jsxs(tye,{children:[(c==null?void 0:c.name)||"The agent"," will be notified by email."]})]}),B===m?o.jsxs("div",{className:"py-10 flex flex-col items-center gap-3",children:[o.jsx("div",{className:"w-14 h-14 rounded-full bg-green-100 flex items-center justify-center",children:o.jsx(xc,{className:"h-7 w-7 text-green-600"})}),o.jsx("p",{className:"font-medium",children:"Message sent!"})]}):o.jsxs("div",{className:"space-y-4 pt-4",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Email"}),o.jsx(Ur,{type:"email",value:E,onChange:wt=>C(wt.target.value),placeholder:"you@example.com",className:"mt-1"})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Phone"}),o.jsx(Ur,{type:"tel",value:N,onChange:wt=>R(wt.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),m==="showing"&&o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Preferred date *"}),o.jsx(Ur,{type:"date",value:G,onChange:wt=>W(wt.target.value),className:"mt-1"})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Preferred time"}),o.jsx(Ur,{type:"time",value:X,onChange:wt=>Q(wt.target.value),className:"mt-1"})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Alternate date (optional)"}),o.jsx(Ur,{type:"date",value:re,onChange:wt=>se(wt.target.value),className:"mt-1"})]})]}),m==="disclosure"&&o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Which documents? (select all that apply)"}),o.jsx("div",{className:"mt-2 space-y-2",children:bZe.map(wt=>o.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[o.jsx(ZC,{checked:ue.includes(wt),onCheckedChange:()=>_t(wt)}),o.jsx("span",{children:wt})]},wt))})]}),m==="offer"&&o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Estimated offer"}),o.jsx(Ur,{value:Se,onChange:wt=>ve(wt.target.value),placeholder:"$",className:"mt-1"})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Financing"}),o.jsxs(Ba,{value:Oe,onValueChange:Ae,children:[o.jsx(ja,{className:"mt-1",children:o.jsx(za,{placeholder:"Select..."})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"Cash",children:"Cash"}),o.jsx(wn,{value:"Conventional",children:"Conventional"}),o.jsx(wn,{value:"FHA",children:"FHA"}),o.jsx(wn,{value:"VA",children:"VA"}),o.jsx(wn,{value:"Other",children:"Other"})]})]})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Timeline"}),o.jsxs(Ba,{value:we,onValueChange:ge,children:[o.jsx(ja,{className:"mt-1",children:o.jsx(za,{placeholder:"Select..."})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"ASAP",children:"ASAP"}),o.jsx(wn,{value:"30 days",children:"30 days"}),o.jsx(wn,{value:"60 days",children:"60 days"}),o.jsx(wn,{value:"90+ days",children:"90+ days"})]})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Pre-approved?"}),o.jsxs(Ba,{value:Ne,onValueChange:Ie,children:[o.jsx(ja,{className:"mt-1",children:o.jsx(za,{placeholder:"Select..."})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"Yes",children:"Yes"}),o.jsx(wn,{value:"No",children:"No"}),o.jsx(wn,{value:"In progress",children:"In progress"})]})]})]})]})]}),o.jsxs("div",{children:[o.jsxs(Mr,{className:"text-xs",children:["Message",m==="question"?" *":" (optional)"]}),o.jsx(hd,{value:_,onChange:wt=>T(wt.target.value),placeholder:HB[m].placeholder,rows:4,className:"mt-1"})]}),o.jsx(Ut,{onClick:Pt,disabled:D||!mt,className:"w-full h-12 text-white hover:opacity-90",style:f?{backgroundColor:f}:void 0,children:D?o.jsx(Cu,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const TZe=ox({first_name:Xi().trim().min(1,"First name is required").max(50),last_name:Xi().trim().max(50).optional(),email:Xi().trim().email("Please enter a valid email").max(255).optional().or(iD("")),phone:Xi().trim().max(20).optional().or(iD(""))}),EZe=[{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 N0e({slug:t}={}){var hr;const e=hp(),r=t||e.slug,[n]=B0(),i=n.get("kiosk")==="1"||n.get("mode")==="kiosk",a=8,{data:c,isLoading:s,error:f}=T0e(r),m=oZe(),x=lZe(),_=cZe(),T=P.useRef(!1),[E,C]=P.useState("welcome"),[N,R]=P.useState(null),[D,M]=P.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[B,V]=P.useState(""),[G,W]=P.useState(!1),[X,Q]=P.useState(!1),[re,se]=P.useState(""),[ue,_e]=P.useState(""),[Se,ve]=P.useState(a),[Oe,Ae]=P.useState(!1),[we,ge]=P.useState(null),Ne=c==null?void 0:c.agent_card_slug,Ie=Ne?`https://cards.relevelup.com/${Ne}${c!=null&&c.disclosure_pdf_url?`?oh_disclosure=${encodeURIComponent(c.disclosure_pdf_url)}`:""}`:null,Te=E==="done"&&!i&&!!Ie&&!!(c!=null&&c.auto_forward_to_card);P.useEffect(()=>{if(!Te||Oe){ge(null);return}let Zt=c!=null&&c.disclosure_pdf_url?10:3;ge(Zt);const Pr=setInterval(()=>{if(Zt-=1,Zt<=0){clearInterval(Pr),window.location.href=Ie;return}ge(Zt)},1e3);return()=>clearInterval(Pr)},[Te,Oe,Ie,c==null?void 0:c.disclosure_pdf_url]);const be=P.useCallback(()=>{R(null),M({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),V(""),W(!1),Q(!1),se(""),_e(""),ve(a),C(i?"info":"welcome")},[i]),We=P.useCallback((Zt,Pr)=>{c!=null&&c.id&&Le.functions.invoke("guestbook-lead-notify",{body:{open_house_id:c.id,visitor_id:Zt,first_name:Pr.first_name??D.first_name,last_name:Pr.last_name??D.last_name,email:Pr.email??D.email,phone:Pr.phone??D.phone,visitor_intent:Pr.visitor_intent??B,message:Pr.message,wants_market_updates:Pr.wants_market_updates??G,has_agent:Pr.has_agent??X,working_with_agent_name:Pr.working_with_agent_name??re,visitor_address:Pr.visitor_address??D.visitor_address}}).catch(Nn=>console.error("Guest book lead notify failed:",Nn))},[c==null?void 0:c.id,D,B,G,X,re]);P.useEffect(()=>{if(!i||E!=="done")return;ve(a);const Zt=setInterval(()=>{ve(Pr=>Pr<=1?(clearInterval(Zt),be(),0):Pr-1)},1e3);return()=>clearInterval(Zt)},[i,E,be]),P.useEffect(()=>{if(!i)return;C(Pr=>Pr==="welcome"?"info":Pr);let Zt=null;return(async()=>{var Pr,Nn;try{Zt=await((Nn=(Pr=navigator.wakeLock)==null?void 0:Pr.request)==null?void 0:Nn.call(Pr,"screen"))}catch{}})(),()=>{var Pr;try{(Pr=Zt==null?void 0:Zt.release)==null||Pr.call(Zt)}catch{}}},[i]);const rt=P.useCallback(()=>{var Pr;const Zt=document.documentElement;document.fullscreenElement||(Pr=Zt.requestFullscreen||Zt.webkitRequestFullscreen)==null||Pr.call(Zt).catch(()=>{})},[]),{data:at,isLoading:Et}=sZe(c==null?void 0:c.id),_t=!!(c!=null&&c.enable_survey),Vt=(c==null?void 0:c.ask_visitor_intent)!==!1,mt=(c==null?void 0:c.ask_visitor_address)===!0;P.useEffect(()=>{if(!r||!(c!=null&&c.id)||T.current)return;const Zt=`oh_scan_${c.id}`;if(sessionStorage.getItem(Zt)){T.current=!0;return}T.current=!0,sessionStorage.setItem(Zt,"1"),_.mutate(r)},[r,c==null?void 0:c.id]),P.useEffect(()=>{E==="pending_survey"&&(Et||C(_t&&((at==null?void 0:at.length)??0)>0?"survey":"done"))},[E,Et,_t,at]);const Pt=Zt=>{if(!Zt)return"";const[Pr,Nn]=Zt.split(":"),ai=parseInt(Pr),ei=ai>=12?"PM":"AM";return`${ai>12?ai-12:ai||12}:${Nn} ${ei}`},er=async()=>{_e("");const Zt=TZe.safeParse(D);if(!Zt.success){_e(Zt.error.issues[0].message);return}if(!D.email&&!D.phone){_e("Please provide either an email or phone number");return}const Pr=(c==null?void 0:c.kind)==="virtual";let Nn=null;if(!N&&(c!=null&&c.id))try{const ai=await m.mutateAsync({open_house_id:c.id,first_name:D.first_name.trim(),last_name:D.last_name.trim()||void 0,email:D.email.trim()||void 0,phone:D.phone.trim()||void 0,visitor_address:mt&&D.visitor_address.trim()?D.visitor_address.trim():void 0,wants_market_updates:G,has_agent:X,working_with_agent_name:X&&re.trim()?re.trim():void 0,partial_signin:Pr?!1:Vt});Nn=ai.id,R(ai.id)}catch{if(Pr){_e("We could not start the virtual tour. Please try again.");return}}if(Pr){Vt?C("intent"):(Nn&&We(Nn,{}),C("done"));return}if(!Vt){Nn&&We(Nn,{}),_t?!Et&&at&&at.length>0?C("survey"):C("pending_survey"):C("done");return}C("intent")},wt=async Zt=>{V(Zt);try{let Pr=N;if(Pr?await x.mutateAsync({visitor_id:Pr,visitor_intent:Zt,wants_market_updates:G,has_agent:X,working_with_agent_name:X&&re.trim()?re.trim():null,partial_signin:!1}):(Pr=(await m.mutateAsync({open_house_id:c.id,first_name:D.first_name.trim(),last_name:D.last_name.trim()||void 0,email:D.email.trim()||void 0,phone:D.phone.trim()||void 0,visitor_address:mt&&D.visitor_address.trim()?D.visitor_address.trim():void 0,visitor_intent:Zt,wants_market_updates:G,has_agent:X,working_with_agent_name:X&&re.trim()?re.trim():void 0,partial_signin:!1})).id,R(Pr)),Pr&&We(Pr,{visitor_intent:Zt,wants_market_updates:G,has_agent:X,working_with_agent_name:X&&re.trim()?re.trim():null}),(c==null?void 0:c.kind)==="virtual"){C("done");return}_t?!Et&&at&&at.length>0?C("survey"):C("pending_survey"):C("done")}catch{_e("Something went wrong. Please try again.")}};if(s)return o.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:o.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})});if(f||!c)return o.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:o.jsxs("div",{className:"text-center text-white",children:[o.jsx(Ma,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),o.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Open House Not Found"}),o.jsx("p",{className:"text-white/60",children:"This sign-in page doesn't exist or is no longer active."})]})});const or=c.profiles,Sr=((hr=or==null?void 0:or.name)==null?void 0:hr.split(" ").map(Zt=>Zt[0]).join("").slice(0,2))||"?",nn=c.event_type==="community",lr=c.kind==="virtual",yr=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(lr&&(yr||E==="done"))return!yr&&!N?o.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:o.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})}):o.jsxs(o.Fragment,{children:[o.jsxs(jl,{children:[o.jsxs("title",{children:["Virtual Tour | ",c.property_address]}),o.jsx("meta",{name:"description",content:`Take a virtual tour of ${c.property_address}`}),o.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),yr&&o.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"}),o.jsx(SZe,{openHouse:c,visitorId:yr?"preview":N,visitorName:yr?"Preview Visitor":`${D.first_name} ${D.last_name}`.trim(),visitorEmail:yr?"":D.email,visitorPhone:yr?"":D.phone,previewMode:yr})]});const yn=`${lr?"Virtual Open House":nn?"Community Event":"Open House"} — ${c.property_address}`,At=[[c.city,c.state].filter(Boolean).join(", "),c.event_date?Ri(new Date(c.event_date+"T00:00:00"),"EEE, MMM d"):null,or!=null&&or.name?`Hosted by ${or.name}`:null].filter(Boolean).join(" · "),Ot=c.photo_url||"",dr=Ot&&Ot.includes("/storage/v1/object/public/")?Ot.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Ot||"https://dashboard.relevelup.com/og-image.png",cr=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${r}`;return o.jsxs(o.Fragment,{children:[o.jsxs(jl,{children:[o.jsx("title",{children:yn}),o.jsx("meta",{name:"description",content:At||`Sign in to ${c.property_address}`}),o.jsx("meta",{property:"og:type",content:"website"}),o.jsx("meta",{property:"og:title",content:yn}),o.jsx("meta",{property:"og:description",content:At||`Sign in to ${c.property_address}`}),o.jsx("meta",{property:"og:image",content:dr}),o.jsx("meta",{property:"og:image:width",content:"1200"}),o.jsx("meta",{property:"og:image:height",content:"630"}),o.jsx("meta",{property:"og:url",content:cr}),o.jsx("meta",{property:"og:site_name",content:"ReLevel Up"}),o.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),o.jsx("meta",{name:"twitter:title",content:yn}),o.jsx("meta",{name:"twitter:description",content:At||`Sign in to ${c.property_address}`}),o.jsx("meta",{name:"twitter:image",content:dr}),o.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),o.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:o.jsxs("div",{className:"w-full max-w-md",children:[o.jsxs("div",{className:"text-center mb-6",children:[o.jsxs(Zd,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[o.jsx(Xd,{src:(or==null?void 0:or.avatar_url)||"",alt:(or==null?void 0:or.name)||""}),o.jsx(Qd,{className:"bg-white/10 text-white text-lg",children:Sr})]}),o.jsx("p",{className:"text-white/60 text-sm",children:or==null?void 0:or.name}),(or==null?void 0:or.title)&&o.jsx("p",{className:"text-white/40 text-xs",children:or.title})]}),o.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[c.photo_url&&o.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[o.jsx("img",{src:c.photo_url,alt:c.property_address,className:"w-full h-full object-cover"}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),o.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[o.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:c.property_address}),o.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[c.city&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(na,{className:"h-3 w-3"}),c.city,c.state?`, ${c.state}`:""," ",c.zip]}),!lr&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(po,{className:"h-3 w-3"}),Ri(new Date(c.event_date+"T00:00:00"),"MMM d, yyyy")]}),c.start_time&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(mc,{className:"h-3 w-3"}),Pt(c.start_time),c.end_time?` – ${Pt(c.end_time)}`:""]})]})]})]})]}),!c.photo_url&&o.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:nn?o.jsx(Eo,{className:"h-5 w-5 text-white"}):o.jsx(Ma,{className:"h-5 w-5 text-white"})}),o.jsxs("div",{children:[o.jsx("h1",{className:"text-white font-bold text-lg leading-tight",children:c.property_address}),o.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-white/60 text-xs",children:[c.city&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(na,{className:"h-3 w-3"}),c.city,c.state?`, ${c.state}`:""," ",c.zip]}),!lr&&o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(po,{className:"h-3 w-3"}),Ri(new Date(c.event_date+"T00:00:00"),"MMM d, yyyy")]}),c.start_time&&o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(mc,{className:"h-3 w-3"}),Pt(c.start_time),c.end_time?` – ${Pt(c.end_time)}`:""]})]})]})]})]})}),o.jsxs("div",{className:"p-6",children:[E==="welcome"&&o.jsxs("div",{className:"text-center space-y-6",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),o.jsx("p",{className:"text-slate-500 text-sm",children:c.agent_greeting||"Please sign in below."})]}),o.jsxs(Ut,{onClick:()=>C("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",o.jsx(pc,{className:"h-5 w-5 ml-2"})]}),o.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),E==="info"&&o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[o.jsx("button",{onClick:()=>C("welcome"),className:"text-slate-400 hover:text-slate-600",children:o.jsx(By,{className:"h-4 w-4"})}),o.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Your Info"})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{className:"text-slate-600 text-xs",children:"First Name *"}),o.jsx(Ur,{value:D.first_name,onChange:Zt=>M(Pr=>({...Pr,first_name:Zt.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-slate-600 text-xs",children:"Last Name"}),o.jsx(Ur,{value:D.last_name,onChange:Zt=>M(Pr=>({...Pr,last_name:Zt.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-slate-600 text-xs",children:"Email"}),o.jsx(Ur,{type:"email",value:D.email,onChange:Zt=>M(Pr=>({...Pr,email:Zt.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-slate-600 text-xs",children:"Phone"}),o.jsx(Ur,{type:"tel",value:D.phone,onChange:Zt=>M(Pr=>({...Pr,phone:Zt.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),mt&&o.jsxs("div",{children:[o.jsx(Mr,{className:"text-slate-600 text-xs",children:"Your Home Address"}),o.jsx(Ur,{value:D.visitor_address,onChange:Zt=>M(Pr=>({...Pr,visitor_address:Zt.target.value})),placeholder:"Street, City, State ZIP",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoComplete:"street-address"})]}),o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[o.jsx("input",{type:"checkbox",checked:G,onChange:Zt=>W(Zt.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),o.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),o.jsxs("div",{className:"space-y-2 pt-1",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-xs font-medium text-slate-400",children:X?"Yes":"No"}),o.jsx(kS,{checked:X,onCheckedChange:Q})]})]}),X&&o.jsx(Ur,{value:re,onChange:Zt=>se(Zt.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),ue&&o.jsx("p",{className:"text-destructive text-sm",children:ue}),o.jsxs(Ut,{onClick:er,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",o.jsx(pc,{className:"h-5 w-5 ml-2"})]})]}),E==="intent"&&o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[o.jsx("button",{onClick:()=>C("info"),className:"text-slate-400 hover:text-slate-600",children:o.jsx(By,{className:"h-4 w-4"})}),o.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"What brings you here?"})]}),o.jsx("div",{className:"grid grid-cols-2 gap-3",children:EZe.map(Zt=>o.jsxs("button",{onClick:()=>wt(Zt.value),disabled:m.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:[o.jsx("span",{className:"text-2xl",children:Zt.emoji}),o.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Zt.label})]},Zt.value))}),ue&&o.jsx("p",{className:"text-destructive text-sm text-center",children:ue})]}),E==="pending_survey"&&o.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[o.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),o.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),E==="survey"&&N&&at&&o.jsx(xZe,{questions:at,visitorId:N,onComplete:()=>C("done"),onSkip:()=>C("done")}),E==="done"&&o.jsxs("div",{className:"text-center space-y-4 py-4",children:[o.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:o.jsx(xc,{className:"h-8 w-8 text-green-600"})}),o.jsxs("div",{children:[o.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"You're all set!"}),o.jsxs("p",{className:"text-slate-500 text-sm mt-1",children:["Thanks for signing in, ",D.first_name,". ",nn?"Enjoy the event!":"Enjoy the open house!"]})]}),o.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 justify-center",children:[(c==null?void 0:c.disclosure_pdf_url)&&o.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(c.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",onClick:()=>Ae(!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:[o.jsx(ep,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),Ie&&o.jsxs("a",{href:Ie,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:[o.jsx(pc,{className:"h-4 w-4"}),"View ",or!=null&&or.name?`${or.name.split(" ")[0]}'s`:"My"," Business Card"]})]}),Ie&&we!==null&&!Oe&&o.jsxs("p",{className:"text-xs text-slate-400",children:["Opening the business card in ",we,"s…"," ",o.jsx("button",{type:"button",className:"underline",onClick:()=>Ae(!0),children:"Stay here"})]}),(or==null?void 0:or.name)&&o.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",o.jsx("strong",{className:"text-slate-600",children:or.name})]}),i&&o.jsxs("div",{className:"pt-4 space-y-3",children:[o.jsx(Ut,{onClick:be,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),o.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",Se,"s…"]})]})]})]})]}),o.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),i&&o.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[o.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:[o.jsx(bLe,{className:"h-3 w-3"})," Tablet Mode"]}),o.jsx("button",{onClick:rt,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:o.jsx(nLe,{className:"h-3 w-3"})})]})]})})]})}const AZe=Object.freeze(Object.defineProperty({__proto__:null,default:N0e},Symbol.toStringTag,{value:"Module"}));function Q6t(t){return wr({queryKey:["open-house-rsvps",t],queryFn:async()=>{const{data:e,error:r}=await Le.from("open_house_rsvps").select("*").eq("open_house_id",t).order("created_at",{ascending:!1});if(r)throw r;return e||[]},enabled:!!t})}function kZe(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.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 J6t(t){const e=Nr();return Cr({mutationFn:async r=>{const{error:n}=await Le.from("open_house_rsvps").delete().eq("id",r);if(n)throw n},onSuccess:()=>e.invalidateQueries({queryKey:["open-house-rsvps",t]})})}function eVt(t){const e=Nr();return Cr({mutationFn:async({id:r,checkedIn:n})=>{const{error:i}=await Le.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 CZe=ox({first_name:Xi().trim().min(1,"First name is required").max(50),last_name:Xi().trim().max(50).optional(),email:Xi().trim().email("Please enter a valid email").max(255),phone:Xi().trim().max(20).optional().or(iD("")),message:Xi().trim().max(500).optional().or(iD(""))}),WB=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}`},jZe=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 R0e({slug:t}={}){const e=hp(),r=t||e.slug,{data:n,isLoading:i,error:a}=T0e(r),c=kZe(),[s,f]=P.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[m,x]=P.useState(!1),[_,T]=P.useState(""),[E,C]=P.useState(""),[N,R]=P.useState(!1),D=P.useMemo(()=>jZe(n==null?void 0:n.event_date),[n==null?void 0:n.event_date]),M=P.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]),B=n==null?void 0:n.profiles,V=[n==null?void 0:n.city,n==null?void 0:n.state].filter(Boolean).join(", "),G=async()=>{C("");const Q=CZe.safeParse(s);if(!Q.success){C(Q.error.issues[0].message);return}try{await c.mutateAsync({open_house_id:n.id,first_name:s.first_name.trim(),last_name:s.last_name.trim()||void 0,email:s.email.trim(),phone:s.phone.trim()||void 0,has_agent:m,working_with_agent_name:m&&_.trim()?_.trim():void 0,message:s.message.trim()||void 0}),R(!0)}catch(re){C((re==null?void 0:re.message)||"Something went wrong. Please try again.")}},W=P.useMemo(()=>{if(!n||!D)return"";const Q=ve=>String(ve).padStart(2,"0"),re=`${D.getFullYear()}${Q(D.getMonth()+1)}${Q(D.getDate())}`,se=(n.start_time||"12:00").slice(0,5).replace(":","")+"00",ue=(n.end_time||"14:00").slice(0,5).replace(":","")+"00",_e=encodeURIComponent(`Open House — ${n.property_address}`),Se=encodeURIComponent([n.property_address,V,n.zip].filter(Boolean).join(", "));return`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${_e}&dates=${re}T${se}/${re}T${ue}&location=${Se}`},[n,D,V]);if(i)return o.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22]",children:o.jsx("div",{className:"h-10 w-10 rounded-full border-2 border-white/20 border-t-white animate-spin"})});if(a||!n)return o.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22] p-6 text-center",children:o.jsxs("div",{className:"text-white/80",children:[o.jsx(Ma,{className:"h-8 w-8 mx-auto mb-3 opacity-50"}),o.jsx("h1",{className:"text-xl font-semibold mb-1",children:"Open house not found"}),o.jsx("p",{className:"text-sm text-white/50",children:"This RSVP link may have expired."})]})});const X=`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent([n.property_address,V,n.zip].filter(Boolean).join(", "))}`;return o.jsxs("div",{className:"min-h-screen bg-[#f6f2ee]",children:[o.jsxs(jl,{children:[o.jsx("title",{children:`RSVP — Open House at ${n.property_address}`}),o.jsx("meta",{name:"description",content:`Reserve your spot for the open house at ${n.property_address}${D?` on ${Ri(D,"EEEE, MMMM d")}`:""}.`})]}),o.jsxs("header",{className:"relative",children:[o.jsxs("div",{className:"relative h-[46vh] min-h-[320px] w-full overflow-hidden bg-[#1b3a4b]",children:[M&&o.jsx("img",{src:M,alt:n.property_address,className:"absolute inset-0 h-full w-full object-cover"}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0f1c22] via-[#0f1c22]/55 to-[#0f1c22]/25"}),o.jsx("div",{className:"absolute inset-x-0 bottom-0 p-6 sm:p-10",children:o.jsxs("div",{className:"mx-auto max-w-3xl",children:[o.jsx("p",{className:"text-[11px] uppercase tracking-[0.35em] text-[#d4b978] mb-3",children:"Open House"}),o.jsx("h1",{className:"font-serif text-3xl sm:text-4xl font-bold text-white leading-tight",children:n.property_address}),V&&o.jsxs("p",{className:"mt-1 text-white/70",children:[V," ",n.zip||""]}),o.jsxs("div",{className:"mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm text-white/85",children:[D&&o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(po,{className:"h-4 w-4 text-[#d4b978]"}),Ri(D,"EEEE, MMMM d, yyyy")]}),n.start_time&&o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(mc,{className:"h-4 w-4 text-[#d4b978]"}),WB(n.start_time),n.end_time?` – ${WB(n.end_time)}`:""]})]})]})})]}),o.jsx("div",{className:"h-1 bg-gradient-to-r from-[#b8975a] via-[#d4b978] to-[#b8975a]"})]}),o.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)&&o.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[n.price?o.jsx(vN,{icon:o.jsx(Ma,{className:"h-4 w-4"}),label:"Price",value:`$${Number(n.price).toLocaleString()}`}):null,n.beds?o.jsx(vN,{icon:o.jsx(BRe,{className:"h-4 w-4"}),label:"Beds",value:String(n.beds)}):null,n.baths?o.jsx(vN,{icon:o.jsx(lS,{className:"h-4 w-4"}),label:"Baths",value:String(n.baths)}):null,n.sqft?o.jsx(vN,{icon:o.jsx(QO,{className:"h-4 w-4"}),label:"Sq Ft",value:Number(n.sqft).toLocaleString()}):null]}),n.property_description&&o.jsx("p",{className:"text-[15px] leading-relaxed text-[#3a4a51] whitespace-pre-line",children:n.property_description}),o.jsx("section",{id:"rsvp",className:"rounded-2xl bg-white shadow-[0_10px_40px_rgba(15,28,34,0.08)] overflow-hidden",children:N?o.jsxs("div",{className:"p-8 sm:p-12 text-center",children:[o.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-emerald-500/10",children:o.jsx(xc,{className:"h-7 w-7 text-emerald-600"})}),o.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"You're on the list!"}),o.jsxs("p",{className:"mt-2 text-[#5b6b72]",children:["We'll see you ",D?Ri(D,"EEEE, MMMM d"):"soon",n.start_time?` at ${WB(n.start_time)}`:"",". A confirmation reminder will land in your inbox before the event."]}),o.jsxs("div",{className:"mt-6 flex flex-wrap justify-center gap-3",children:[W&&o.jsx(Ut,{asChild:!0,className:"bg-[#1b3a4b] hover:bg-[#25505f]",children:o.jsxs("a",{href:W,target:"_blank",rel:"noreferrer",children:[o.jsx(zhe,{className:"mr-2 h-4 w-4"}),"Add to calendar"]})}),o.jsx(Ut,{asChild:!0,variant:"outline",children:o.jsxs("a",{href:X,target:"_blank",rel:"noreferrer",children:[o.jsx(na,{className:"mr-2 h-4 w-4"}),"Get directions"]})})]})]}):o.jsxs("div",{className:"p-6 sm:p-8",children:[o.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"Reserve your spot"}),o.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."}),o.jsxs("div",{className:"mt-6 grid gap-4 sm:grid-cols-2",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{htmlFor:"rsvp-first",children:"First name *"}),o.jsx(Ur,{id:"rsvp-first",value:s.first_name,onChange:Q=>f(re=>({...re,first_name:Q.target.value})),className:"h-11"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{htmlFor:"rsvp-last",children:"Last name"}),o.jsx(Ur,{id:"rsvp-last",value:s.last_name,onChange:Q=>f(re=>({...re,last_name:Q.target.value})),className:"h-11"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{htmlFor:"rsvp-email",children:"Email *"}),o.jsx(Ur,{id:"rsvp-email",type:"email",value:s.email,onChange:Q=>f(re=>({...re,email:Q.target.value})),className:"h-11"})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{htmlFor:"rsvp-phone",children:"Phone"}),o.jsx(Ur,{id:"rsvp-phone",type:"tel",value:s.phone,onChange:Q=>f(re=>({...re,phone:Q.target.value})),className:"h-11"})]})]}),o.jsxs("div",{className:"mt-4 rounded-xl border border-[#e4dcd3] bg-[#faf7f4] p-4",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-sm font-medium text-[#1b3a4b]",children:"Are you working with an agent?"}),o.jsx("p",{className:"text-xs text-[#7a888e]",children:"So we can respect your existing representation."})]}),o.jsx(kS,{checked:m,onCheckedChange:x})]}),m&&o.jsx(Ur,{value:_,onChange:Q=>T(Q.target.value),placeholder:"Your agent's name (optional)",className:"mt-3 h-10 bg-white"})]}),o.jsxs("div",{className:"mt-4 space-y-1.5",children:[o.jsx(Mr,{htmlFor:"rsvp-msg",children:"Anything you'd like us to know?"}),o.jsx(hd,{id:"rsvp-msg",rows:3,value:s.message,onChange:Q=>f(re=>({...re,message:Q.target.value})),className:"resize-y"})]}),E&&o.jsx("p",{className:"mt-3 text-sm text-destructive",children:E}),o.jsx(Ut,{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…":o.jsxs(o.Fragment,{children:["RSVP for this open house",o.jsx(pc,{className:"ml-2 h-4 w-4"})]})}),o.jsx("p",{className:"mt-3 text-center text-xs text-[#8b979c]",children:"We'll only use your info to follow up about this property."})]})}),(B==null?void 0:B.name)&&o.jsxs("section",{className:"rounded-2xl bg-white/70 border border-[#e4dcd3] p-5 flex items-center gap-4",children:[o.jsxs(Zd,{className:"h-14 w-14",children:[o.jsx(Xd,{src:B.avatar_url||void 0,alt:B.name}),o.jsx(Qd,{children:B.name.slice(0,1)})]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-[#a08a5f]",children:"Hosted by"}),o.jsx("p",{className:"font-semibold text-[#1b3a4b]",children:B.name}),B.title&&o.jsx("p",{className:"text-sm text-[#5b6b72]",children:B.title}),o.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 text-sm text-[#406E71]",children:[B.phone&&o.jsx("a",{href:`tel:${B.phone}`,children:B.phone}),B.email&&o.jsx("a",{href:`mailto:${B.email}`,className:"truncate",children:B.email})]})]})]}),o.jsx("div",{className:"text-center",children:o.jsxs("a",{href:X,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-sm text-[#406E71] hover:underline",children:[o.jsx(na,{className:"h-4 w-4"}),"Get directions to ",n.property_address]})})]})]})}function vN({icon:t,label:e,value:r}){return o.jsxs("div",{className:"rounded-xl bg-white border border-[#e9e2da] px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-[#9aa5aa]",children:[t,e]}),o.jsx("div",{className:"mt-1 text-lg font-semibold text-[#1b3a4b]",children:r})]})}const IZe=Object.freeze(Object.defineProperty({__proto__:null,default:R0e},Symbol.toStringTag,{value:"Module"}));function tVt(t){const{user:e}=qn();return wr({queryKey:["cohost-tokens",t],queryFn:async()=>{const{data:r,error:n}=await Le.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 rVt(){const t=Nr(),{user:e}=qn();return Cr({mutationFn:async({openHouseId:r,label:n})=>{const{data:i,error:a}=await Le.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 nVt(){const t=Nr();return Cr({mutationFn:async({id:e,openHouseId:r})=>{const{error:n}=await Le.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 PZe(t){return wr({queryKey:["cohost-validate",t],queryFn:async()=>{const{data:e,error:r}=await Le.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 ap=(t,e,r)=>r>e?e:r{},A1=()=>{};const Yy={},D0e=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function O0e(t){return typeof t=="object"&&t!==null}const M0e=t=>/^0[^.\s]+$/u.test(t);function F0e(t){let e;return()=>(e===void 0&&(e=t()),e)}const Hd=t=>t,RZe=(t,e)=>r=>e(t(r)),QC=(...t)=>t.reduce(RZe),vk=(t,e,r)=>{const n=e-t;return n===0?1:(r-t)/n};class c7{constructor(){this.subscriptions=[]}add(e){return l7(this.subscriptions,e),()=>lD(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,$d=t=>t/1e3;function B0e(t,e){return e?t*(1e3/e):0}const z0e=(t,e,r)=>(((1-3*r+3*e)*t+(3*r-6*e))*t+3*e)*t,LZe=1e-7,DZe=12;function OZe(t,e,r,n,i){let a,c,s=0;do c=e+(r-e)/2,a=z0e(c,n,i)-t,a>0?r=c:e=c;while(Math.abs(a)>LZe&&++sOZe(a,0,1,t,r);return a=>a===0||a===1?a:z0e(i(a),e,n)}const $0e=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,U0e=t=>e=>1-t(1-e),V0e=JC(.33,1.53,.69,.99),u7=U0e(V0e),q0e=$0e(u7),G0e=t=>t>=1?1:(t*=2)<1?.5*u7(t):.5*(2-Math.pow(2,-10*(t-1))),d7=t=>1-Math.sin(Math.acos(t)),H0e=U0e(d7),W0e=$0e(d7),MZe=JC(.42,0,1,1),FZe=JC(0,0,.58,1),K0e=JC(.42,0,.58,1),BZe=t=>Array.isArray(t)&&typeof t[0]!="number",Y0e=t=>Array.isArray(t)&&typeof t[0]=="number",Yte={linear:Hd,easeIn:MZe,easeInOut:K0e,easeOut:FZe,circIn:d7,circInOut:W0e,circOut:H0e,backIn:u7,backInOut:q0e,backOut:V0e,anticipate:G0e},zZe=t=>typeof t=="string",Zte=t=>{if(Y0e(t)){A1(t.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[e,r,n,i]=t;return JC(e,r,n,i)}else if(zZe(t))return A1(Yte[t]!==void 0,`Invalid easing type '${t}'`,"invalid-easing-type"),Yte[t];return t},bN=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Xte={value:null,addProjectionMetrics:null};function $Ze(t,e){let r=new Set,n=new Set,i=!1,a=!1;const c=new WeakSet;let s={delta:0,timestamp:0,isProcessing:!1},f=0;function m(_){c.has(_)&&(x.schedule(_),t()),f++,_(s)}const x={schedule:(_,T=!1,E=!1)=>{const N=E&&i?r:n;return T&&c.add(_),N.add(_),_},cancel:_=>{n.delete(_),c.delete(_)},process:_=>{if(s=_,i){a=!0;return}i=!0;const T=r;r=n,n=T,r.forEach(m),e&&Xte.value&&Xte.value.frameloop[e].push(f),f=0,r.clear(),i=!1,a&&(a=!1,x.process(_))}};return x}const UZe=40;function Z0e(t,e){let r=!1,n=!0;const i={delta:0,timestamp:0,isProcessing:!1},a=()=>r=!0,c=bN.reduce((B,V)=>(B[V]=$Ze(a,e?V:void 0),B),{}),{setup:s,read:f,resolveKeyframes:m,preUpdate:x,update:_,preRender:T,render:E,postRender:C}=c,N=()=>{const B=Yy.useManualTiming,V=B?i.timestamp:performance.now();r=!1,B||(i.delta=n?1e3/60:Math.max(Math.min(V-i.timestamp,UZe),1)),i.timestamp=V,i.isProcessing=!0,s.process(i),f.process(i),m.process(i),x.process(i),_.process(i),T.process(i),E.process(i),C.process(i),i.isProcessing=!1,r&&e&&(n=!1,t(N))},R=()=>{r=!0,n=!0,i.isProcessing||t(N)};return{schedule:bN.reduce((B,V)=>{const G=c[V];return B[V]=(W,X=!1,Q=!1)=>(r||R(),G.schedule(W,X,Q)),B},{}),cancel:B=>{for(let V=0;V(LR===void 0&&Vc.set(Bl.isProcessing||Yy.useManualTiming?Bl.timestamp:performance.now()),LR),set:t=>{LR=t,queueMicrotask(VZe)}},X0e=t=>e=>typeof e=="string"&&e.startsWith(t),Q0e=X0e("--"),qZe=X0e("var(--"),h7=t=>qZe(t)?GZe.test(t.split("/*")[0].trim()):!1,GZe=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function Qte(t){return typeof t!="string"?!1:t.split("/*")[0].includes("var(--")}const CS={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},bk={...CS,transform:t=>ap(0,1,t)},wN={...CS,default:1},_A=t=>Math.round(t*1e5)/1e5,f7=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function HZe(t){return t==null}const WZe=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,p7=(t,e)=>r=>!!(typeof r=="string"&&WZe.test(r)&&r.startsWith(t)||e&&!HZe(r)&&Object.prototype.hasOwnProperty.call(r,e)),J0e=(t,e,r)=>n=>{if(typeof n!="string")return n;const[i,a,c,s]=n.match(f7);return{[t]:parseFloat(i),[e]:parseFloat(a),[r]:parseFloat(c),alpha:s!==void 0?parseFloat(s):1}},KZe=t=>ap(0,255,t),YB={...CS,transform:t=>Math.round(KZe(t))},K_={test:p7("rgb","red"),parse:J0e("red","green","blue"),transform:({red:t,green:e,blue:r,alpha:n=1})=>"rgba("+YB.transform(t)+", "+YB.transform(e)+", "+YB.transform(r)+", "+_A(bk.transform(n))+")"};function YZe(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 $6={test:p7("#"),parse:YZe,transform:K_.transform},ej=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Hg=ej("deg"),Xf=ej("%"),In=ej("px"),ZZe=ej("vh"),XZe=ej("vw"),Jte={...Xf,parse:t=>Xf.parse(t)/100,transform:t=>Xf.transform(t*100)},pw={test:p7("hsl","hue"),parse:J0e("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:r,alpha:n=1})=>"hsla("+Math.round(t)+", "+Xf.transform(_A(e))+", "+Xf.transform(_A(r))+", "+_A(bk.transform(n))+")"},$o={test:t=>K_.test(t)||$6.test(t)||pw.test(t),parse:t=>K_.test(t)?K_.parse(t):pw.test(t)?pw.parse(t):$6.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?K_.transform(t):pw.transform(t),getAnimatableNone:t=>{const e=$o.parse(t);return e.alpha=0,$o.transform(e)}},QZe=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function JZe(t){var e,r;return isNaN(t)&&typeof t=="string"&&(((e=t.match(f7))==null?void 0:e.length)||0)+(((r=t.match(QZe))==null?void 0:r.length)||0)>0}const eve="number",tve="color",eXe="var",tXe="var(",ere="${}",rXe=/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 k1(t){const e=t.toString(),r=[],n={color:[],number:[],var:[]},i=[];let a=0;const s=e.replace(rXe,f=>($o.test(f)?(n.color.push(a),i.push(tve),r.push($o.parse(f))):f.startsWith(tXe)?(n.var.push(a),i.push(eXe),r.push(f)):(n.number.push(a),i.push(eve),r.push(parseFloat(f))),++a,ere)).split(ere);return{values:r,split:s,indexes:n,types:i}}function nXe(t){return k1(t).values}function rve({split:t,types:e}){const r=t.length;return n=>{let i="";for(let a=0;atypeof t=="number"?0:$o.test(t)?$o.getAnimatableNone(t):t,aXe=(t,e)=>typeof t=="number"?e!=null&&e.trim().endsWith("/")?t:0:sXe(t);function oXe(t){const e=k1(t);return rve(e)(e.values.map((n,i)=>aXe(n,e.split[i])))}const Zh={test:JZe,parse:nXe,createTransformer:iXe,getAnimatableNone:oXe};function ZB(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 lXe({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 s=r<.5?r*(1+e):r+e-r*e,f=2*r-s;i=ZB(f,s,t+1/3),a=ZB(f,s,t),c=ZB(f,s,t-1/3)}return{red:Math.round(i*255),green:Math.round(a*255),blue:Math.round(c*255),alpha:n}}function cD(t,e){return r=>r>0?e:t}const ka=(t,e,r)=>t+(e-t)*r,XB=(t,e,r)=>{const n=t*t,i=r*(e*e-n)+n;return i<0?0:Math.sqrt(i)},cXe=[$6,K_,pw],uXe=t=>cXe.find(e=>e.test(t));function tre(t){const e=uXe(t);if(sF(!!e,`'${t}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!e)return!1;let r=e.parse(t);return e===pw&&(r=lXe(r)),r}const rre=(t,e)=>{const r=tre(t),n=tre(e);if(!r||!n)return cD(t,e);const i={...r};return a=>(i.red=XB(r.red,n.red,a),i.green=XB(r.green,n.green,a),i.blue=XB(r.blue,n.blue,a),i.alpha=ka(r.alpha,n.alpha,a),K_.transform(i))},U6=new Set(["none","hidden"]);function dXe(t,e){return U6.has(t)?r=>r<=0?t:e:r=>r>=1?e:t}function hXe(t,e){return r=>ka(t,e,r)}function m7(t){return typeof t=="number"?hXe:typeof t=="string"?h7(t)?cD:$o.test(t)?rre:mXe:Array.isArray(t)?nve:typeof t=="object"?$o.test(t)?rre:fXe:cD}function nve(t,e){const r=[...t],n=r.length,i=t.map((a,c)=>m7(a)(a,e[c]));return a=>{for(let c=0;c{for(const a in n)r[a]=n[a](i);return r}}function pXe(t,e){const r=[],n={color:0,var:0,number:0};for(let i=0;i{const r=Zh.createTransformer(e),n=k1(t),i=k1(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?U6.has(t)&&!i.values.length||U6.has(e)&&!n.values.length?dXe(t,e):QC(nve(pXe(n,i),i.values),r):(sF(!0,`Complex values '${t}' and '${e}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`,"complex-values-different"),cD(t,e))};function ive(t,e,r){return typeof t=="number"&&typeof e=="number"&&typeof r=="number"?ka(t,e,r):m7(t)(t,e)}const gXe=t=>{const e=({timestamp:r})=>t(r);return{start:(r=!0)=>ea.update(e,r),stop:()=>Zy(e),now:()=>Bl.isProcessing?Bl.timestamp:Vc.now()}},sve=(t,e,r=10)=>{let n="";const i=Math.max(Math.round(e/r),2);for(let a=0;a=uD?1/0:e}function yXe(t,e=100,r){const n=r({...t,keyframes:[0,e]}),i=Math.min(g7(n),uD);return{type:"keyframes",ease:a=>n.next(i*a).value/e,duration:$d(i)}}const Ya={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 V6(t,e){return t*Math.sqrt(1-e*e)}const xXe=12;function _Xe(t,e,r){let n=r;for(let i=1;i{const x=m*c,_=x*t,T=x-r,E=V6(m,c),C=Math.exp(-_);return QB-T/E*C},a=m=>{const _=m*c*t,T=_*r+r,E=Math.pow(c,2)*Math.pow(m,2)*t,C=Math.exp(-_),N=V6(Math.pow(m,2),c);return(-i(m)+QB>0?-1:1)*((T-E)*C)/N}):(i=m=>{const x=Math.exp(-m*t),_=(m-r)*t+1;return-QB+x*_},a=m=>{const x=Math.exp(-m*t),_=(r-m)*(t*t);return x*_});const s=5/t,f=_Xe(i,a,s);if(t=ku(t),isNaN(f))return{stiffness:Ya.stiffness,damping:Ya.damping,duration:t};{const m=Math.pow(f,2)*n;return{stiffness:m,damping:c*2*Math.sqrt(n*m),duration:t}}}const bXe=["duration","bounce"],wXe=["stiffness","damping","mass"];function nre(t,e){return e.some(r=>t[r]!==void 0)}function SXe(t){let e={velocity:Ya.velocity,stiffness:Ya.stiffness,damping:Ya.damping,mass:Ya.mass,isResolvedFromDuration:!1,...t};if(!nre(t,wXe)&&nre(t,bXe))if(e.velocity=0,t.visualDuration){const r=t.visualDuration,n=2*Math.PI/(r*1.2),i=n*n,a=2*ap(.05,1,1-(t.bounce||0))*Math.sqrt(i);e={...e,mass:Ya.mass,stiffness:i,damping:a}}else{const r=vXe({...t,velocity:0});e={...e,...r,mass:Ya.mass},e.isResolvedFromDuration=!0}return e}function dD(t=Ya.visualDuration,e=Ya.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],s={done:!1,value:a},{stiffness:f,damping:m,mass:x,duration:_,velocity:T,isResolvedFromDuration:E}=SXe({...r,velocity:-$d(r.velocity||0)}),C=T||0,N=m/(2*Math.sqrt(f*x)),R=c-a,D=$d(Math.sqrt(f/x)),M=Math.abs(R)<5;n||(n=M?Ya.restSpeed.granular:Ya.restSpeed.default),i||(i=M?Ya.restDelta.granular:Ya.restDelta.default);let B,V,G,W,X,Q;if(N<1)G=V6(D,N),W=(C+N*D*R)/G,B=se=>{const ue=Math.exp(-N*D*se);return c-ue*(W*Math.sin(G*se)+R*Math.cos(G*se))},X=N*D*W+R*G,Q=N*D*R-W*G,V=se=>Math.exp(-N*D*se)*(X*Math.sin(G*se)+Q*Math.cos(G*se));else if(N===1){B=ue=>c-Math.exp(-D*ue)*(R+(C+D*R)*ue);const se=C+D*R;V=ue=>Math.exp(-D*ue)*(D*se*ue-C)}else{const se=D*Math.sqrt(N*N-1);B=ve=>{const Oe=Math.exp(-N*D*ve),Ae=Math.min(se*ve,300);return c-Oe*((C+N*D*R)*Math.sinh(Ae)+se*R*Math.cosh(Ae))/se};const ue=(C+N*D*R)/se,_e=N*D*ue-R*se,Se=N*D*R-ue*se;V=ve=>{const Oe=Math.exp(-N*D*ve),Ae=Math.min(se*ve,300);return Oe*(_e*Math.sinh(Ae)+Se*Math.cosh(Ae))}}const re={calculatedDuration:E&&_||null,velocity:se=>ku(V(se)),next:se=>{if(!E&&N<1){const _e=Math.exp(-N*D*se),Se=Math.sin(G*se),ve=Math.cos(G*se),Oe=c-_e*(W*Se+R*ve),Ae=ku(_e*(X*Se+Q*ve));return s.done=Math.abs(Ae)<=n&&Math.abs(c-Oe)<=i,s.value=s.done?c:Oe,s}const ue=B(se);if(E)s.done=se>=_;else{const _e=ku(V(se));s.done=Math.abs(_e)<=n&&Math.abs(c-ue)<=i}return s.value=s.done?c:ue,s},toString:()=>{const se=Math.min(g7(re),uD),ue=sve(_e=>re.next(se*_e).value,se,30);return se+"ms "+ue},toTransition:()=>{}};return re}dD.applyToOptions=t=>{const e=yXe(t,100,dD);return t.ease=e.ease,t.duration=ku(e.duration),t.type="keyframes",t};const TXe=5;function ave(t,e,r){const n=Math.max(e-TXe,0);return B0e(r-t(n),e-n)}function q6({keyframes:t,velocity:e=0,power:r=.8,timeConstant:n=325,bounceDamping:i=10,bounceStiffness:a=500,modifyTarget:c,min:s,max:f,restDelta:m=.5,restSpeed:x}){const _=t[0],T={done:!1,value:_},E=Q=>s!==void 0&&Qf,C=Q=>s===void 0?f:f===void 0||Math.abs(s-Q)-N*Math.exp(-Q/n),B=Q=>D+M(Q),V=Q=>{const re=M(Q),se=B(Q);T.done=Math.abs(re)<=m,T.value=T.done?D:se};let G,W;const X=Q=>{E(T.value)&&(G=Q,W=dD({keyframes:[T.value,C(T.value)],velocity:ave(B,Q,T.value),damping:i,stiffness:a,restDelta:m,restSpeed:x}))};return X(0),{calculatedDuration:null,next:Q=>{let re=!1;return!W&&G===void 0&&(re=!0,V(Q),X(Q)),G!==void 0&&Q>=G?W.next(Q-G):(!re&&V(Q),T)}}}function EXe(t,e,r){const n=[],i=r||Yy.mix||ive,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 s=EXe(e,n,i),f=s.length,m=x=>{if(c&&x1)for(;_m(ap(t[0],t[a-1],x)):m}function kXe(t,e){const r=t[t.length-1];for(let n=1;n<=e;n++){const i=vk(0,e,n);t.push(ka(r,1,i))}}function CXe(t){const e=[0];return kXe(e,t.length-1),e}function jXe(t,e){return t.map(r=>r*e)}function IXe(t,e){return t.map(()=>e||K0e).splice(0,t.length-1)}function vA({duration:t=300,keyframes:e,times:r,ease:n="easeInOut"}){const i=BZe(n)?n.map(Zte):Zte(n),a={done:!1,value:e[0]},c=jXe(r&&r.length===e.length?r:CXe(e),t),s=AXe(c,e,{ease:Array.isArray(i)?i:IXe(e,i)});return{calculatedDuration:t,next:f=>(a.value=s(f),a.done=f>=t,a)}}const PXe=t=>t!==null;function aF(t,{repeat:e,repeatType:r="loop"},n,i=1){const a=t.filter(PXe),s=i<0||e&&r!=="loop"&&e%2===1?0:a.length-1;return!s||n===void 0?a[s]:n}const NXe={decay:q6,inertia:q6,tween:vA,keyframes:vA,spring:dD};function ove(t){typeof t.type=="string"&&(t.type=NXe[t.type])}class y7{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 RXe=t=>t/100;class hD extends y7{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!==Vc.now()&&this.tick(Vc.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;ove(e);const{type:r=vA,repeat:n=0,repeatDelay:i=0,repeatType:a,velocity:c=0}=e;let{keyframes:s}=e;const f=r||vA;f!==vA&&typeof s[0]!="number"&&(this.mixKeyframes=QC(RXe,ive(s[0],s[1])),s=[0,100]);const m=f({...e,keyframes:s});a==="mirror"&&(this.mirroredGenerator=f({...e,keyframes:[...s].reverse(),velocity:-c})),m.calculatedDuration===null&&(m.calculatedDuration=g7(m));const{calculatedDuration:x}=m;this.calculatedDuration=x,this.resolvedDuration=x+i,this.totalDuration=this.resolvedDuration*(n+1)-i,this.generator=m}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:s,calculatedDuration:f}=this;if(this.startTime===null)return n.next(0);const{delay:m=0,keyframes:x,repeat:_,repeatType:T,repeatDelay:E,type:C,onUpdate:N,finalKeyframe:R}=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 D=this.currentTime-m*(this.playbackSpeed>=0?1:-1),M=this.playbackSpeed>=0?D<0:D>i;this.currentTime=Math.max(D,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=i);let B=this.currentTime,V=n;if(_){const Q=Math.min(this.currentTime,i)/s;let re=Math.floor(Q),se=Q%1;!se&&Q>=1&&(se=1),se===1&&re--,re=Math.min(re,_+1),!!(re%2)&&(T==="reverse"?(se=1-se,E&&(se-=E/s)):T==="mirror"&&(V=c)),B=ap(0,1,se)*s}let G;M?(this.delayState.value=x[0],G=this.delayState):G=V.next(B),a&&!M&&(G.value=a(G.value));let{done:W}=G;!M&&f!==null&&(W=this.playbackSpeed>=0?this.currentTime>=i:this.currentTime<=0);const X=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&W);return X&&C!==q6&&(G.value=aF(x,this.options,R,this.speed)),N&&N(G.value),X&&this.finish(),G}then(e,r){return this.finished.then(e,r)}get duration(){return $d(this.calculatedDuration)}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+$d(e)}get time(){return $d(this.currentTime)}set time(e){e=ku(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 ave(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(Vc.now()),this.playbackSpeed=e,r&&this.driver&&(this.time=$d(this.currentTime))}play(){var i,a;if(this.isStopped)return;const{driver:e=gXe,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(Vc.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 LXe(t){for(let e=1;et*180/Math.PI,G6=t=>{const e=Y_(Math.atan2(t[1],t[0]));return H6(e)},DXe={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:G6,rotateZ:G6,skewX:t=>Y_(Math.atan(t[1])),skewY:t=>Y_(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},H6=t=>(t=t%360,t<0&&(t+=360),t),ire=G6,sre=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),are=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),OXe={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:sre,scaleY:are,scale:t=>(sre(t)+are(t))/2,rotateX:t=>H6(Y_(Math.atan2(t[6],t[5]))),rotateY:t=>H6(Y_(Math.atan2(-t[2],t[0]))),rotateZ:ire,rotate:ire,skewX:t=>Y_(Math.atan(t[4])),skewY:t=>Y_(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function W6(t){return t.includes("scale")?1:0}function K6(t,e){if(!t||t==="none")return W6(e);const r=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,i;if(r)n=OXe,i=r;else{const s=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=DXe,i=s}if(!i)return W6(e);const a=n[e],c=i[1].split(",").map(FXe);return typeof a=="function"?a(c):c[a]}const MXe=(t,e)=>{const{transform:r="none"}=getComputedStyle(t);return K6(r,e)};function FXe(t){return parseFloat(t.trim())}const jS=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],IS=new Set(jS),ore=t=>t===CS||t===In,BXe=new Set(["x","y","z"]),zXe=jS.filter(t=>!BXe.has(t));function $Xe(t){const e=[];return zXe.forEach(r=>{const n=t.getValue(r);n!==void 0&&(e.push([r,n.get()]),n.set(r.startsWith("scale")?1:0))}),e}const _y={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})=>K6(e,"x"),y:(t,{transform:e})=>K6(e,"y")};_y.translateX=_y.x;_y.translateY=_y.y;const h0=new Set;let Y6=!1,Z6=!1,X6=!1;function lve(){if(Z6){const t=Array.from(h0).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),r=new Map;e.forEach(n=>{const i=$Xe(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 s;(s=n.getValue(a))==null||s.set(c)})}),t.forEach(n=>n.measureEndState()),t.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}Z6=!1,Y6=!1,h0.forEach(t=>t.complete(X6)),h0.clear()}function cve(){h0.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Z6=!0)})}function UXe(){X6=!0,cve(),lve(),X6=!1}class x7{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?(h0.add(this),Y6||(Y6=!0,ea.read(cve),ea.resolveKeyframes(lve))):(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 s=n.readValue(r,c);s!=null&&(e[0]=s)}e[0]===void 0&&(e[0]=c),i&&a===void 0&&i.set(e[0])}LXe(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),h0.delete(this)}cancel(){this.state==="scheduled"&&(h0.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const VXe=t=>t.startsWith("--");function uve(t,e,r){VXe(e)?t.style.setProperty(e,r):t.style[e]=r}const qXe={};function dve(t,e){const r=F0e(t);return()=>qXe[e]??r()}const GXe=dve(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),hve=dve(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Z2=([t,e,r,n])=>`cubic-bezier(${t}, ${e}, ${r}, ${n})`,lre={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Z2([0,.65,.55,1]),circOut:Z2([.55,0,1,.45]),backIn:Z2([.31,.01,.66,-.59]),backOut:Z2([.33,1.53,.69,.99])};function fve(t,e){if(t)return typeof t=="function"?hve()?sve(t,e):"ease-out":Y0e(t)?Z2(t):Array.isArray(t)?t.map(r=>fve(r,e)||lre.easeOut):lre[t]}function HXe(t,e,r,{delay:n=0,duration:i=300,repeat:a=0,repeatType:c="loop",ease:s="easeOut",times:f}={},m=void 0){const x={[e]:r};f&&(x.offset=f);const _=fve(s,i);Array.isArray(_)&&(x.easing=_);const T={delay:n,duration:i,easing:Array.isArray(_)?"linear":_,fill:"both",iterations:a+1,direction:c==="reverse"?"alternate":"normal"};return m&&(T.pseudoElement=m),t.animate(x,T)}function pve(t){return typeof t=="function"&&"applyToOptions"in t}function WXe({type:t,...e}){return pve(t)&&hve()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class mve extends y7{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:s,onComplete:f}=e;this.isPseudoElement=!!a,this.allowFlatten=c,this.options=e,A1(typeof e.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const m=WXe(e);this.animation=HXe(r,n,i,m,a),m.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!a){const x=aF(i,this.options,s,this.speed);this.updateMotionValue&&this.updateMotionValue(x),uve(r,n,x),this.animation.cancel()}f==null||f(),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 $d(Number(e))}get iterationDuration(){const{delay:e=0}=this.options||{};return this.duration+$d(e)}get time(){return $d(Number(this.animation.currentTime)||0)}set time(e){const r=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=ku(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&&GXe()?(this.animation.timeline=e,r&&(this.animation.rangeStart=r),n&&(this.animation.rangeEnd=n),Hd):i(this)}}const gve={anticipate:G0e,backInOut:q0e,circInOut:W0e};function KXe(t){return t in gve}function YXe(t){typeof t.ease=="string"&&KXe(t.ease)&&(t.ease=gve[t.ease])}const JB=10;class ZXe extends mve{constructor(e){YXe(e),ove(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 s=new hD({...c,autoplay:!1}),f=Math.max(JB,Vc.now()-this.startTime),m=ap(0,JB,f-JB),x=s.sample(f).value,{name:_}=this.options;a&&_&&uve(a,_,x),r.setWithVelocity(s.sample(Math.max(0,f-m)).value,x,m),s.stop()}}const cre=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Zh.test(t)||t==="0")&&!t.startsWith("url("));function XXe(t){const e=t[0];if(t.length===1)return!0;for(let r=0;rObject.hasOwnProperty.call(Element.prototype,"animate"));function nQe(t){var _;const{motionValue:e,name:r,repeatDelay:n,repeatType:i,damping:a,type:c,keyframes:s}=t;if(!(((_=e==null?void 0:e.owner)==null?void 0:_.current)instanceof HTMLElement))return!1;const{onUpdate:m,transformTemplate:x}=e.owner.getProps();return rQe()&&r&&(yve.has(r)||tQe.has(r)&&eQe(s))&&(r!=="transform"||!x)&&!m&&!n&&i!=="mirror"&&a!==0&&c!=="inertia"}const iQe=40;class sQe extends y7{constructor({autoplay:e=!0,delay:r=0,type:n="keyframes",repeat:i=0,repeatDelay:a=0,repeatType:c="loop",keyframes:s,name:f,motionValue:m,element:x,..._}){var C;super(),this.stop=()=>{var N,R;this._animation&&(this._animation.stop(),(N=this.stopTimeline)==null||N.call(this)),(R=this.keyframeResolver)==null||R.cancel()},this.createdAt=Vc.now();const T={autoplay:e,delay:r,type:n,repeat:i,repeatDelay:a,repeatType:c,name:f,motionValue:m,element:x,..._},E=(x==null?void 0:x.KeyframeResolver)||x7;this.keyframeResolver=new E(s,(N,R,D)=>this.onKeyframesResolved(N,R,T,!D),f,m,x),(C=this.keyframeResolver)==null||C.scheduleResolve()}onKeyframesResolved(e,r,n,i){var D,M;this.keyframeResolver=void 0;const{name:a,type:c,velocity:s,delay:f,isHandoff:m,onUpdate:x}=n;this.resolvedAt=Vc.now();let _=!0;QXe(e,a,c,s)||(_=!1,(Yy.instantAnimations||!f)&&(x==null||x(aF(e,n,r))),e[0]=e[e.length-1],Q6(n),n.repeat=0);const E={startTime:i?this.resolvedAt?this.resolvedAt-this.createdAt>iQe?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:r,...n,keyframes:e},C=_&&!m&&nQe(E),N=(M=(D=E.motionValue)==null?void 0:D.owner)==null?void 0:M.current;let R;if(C)try{R=new ZXe({...E,element:N})}catch{R=new hD(E)}else R=new hD(E);R.finished.then(()=>{this.notifyFinished()}).catch(Hd),this.pendingTimeline&&(this.stopTimeline=R.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=R}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(),UXe()),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 xve(t,e,r,n=0,i=1){const a=Array.from(t).sort((m,x)=>m.sortNodePosition(x)).indexOf(e),c=t.size,s=(c-1)*n;return typeof r=="function"?r(a,c):i===1?a*n:s-a*n}const aQe=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function oQe(t){const e=aQe.exec(t);if(!e)return[,];const[,r,n,i]=e;return[`--${r??n}`,i]}const lQe=4;function _ve(t,e,r=1){A1(r<=lQe,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[n,i]=oQe(t);if(!n)return;const a=window.getComputedStyle(e).getPropertyValue(n);if(a){const c=a.trim();return D0e(c)?parseFloat(c):c}return h7(i)?_ve(i,e,r+1):i}const cQe={type:"spring",stiffness:500,damping:25,restSpeed:10},uQe=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),dQe={type:"keyframes",duration:.8},hQe={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},fQe=(t,{keyframes:e})=>e.length>2?dQe:IS.has(t)?t.startsWith("scale")?uQe(e[1]):cQe:hQe;function vve(t,e){if(t!=null&&t.inherit&&e){const{inherit:r,...n}=t;return{...e,...n}}return t}function _7(t,e){const r=(t==null?void 0:t[e])??(t==null?void 0:t.default)??t;return r!==t?vve(r,t):r}const pQe=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function mQe(t){for(const e in t)if(!pQe.has(e))return!0;return!1}const v7=(t,e,r,n={},i,a)=>c=>{const s=_7(n,t)||{},f=s.delay||n.delay||0;let{elapsed:m=0}=n;m=m-ku(f);const x={keyframes:Array.isArray(r)?r:[null,r],ease:"easeOut",velocity:e.getVelocity(),...s,delay:-m,onUpdate:T=>{e.set(T),s.onUpdate&&s.onUpdate(T)},onComplete:()=>{c(),s.onComplete&&s.onComplete()},name:t,motionValue:e,element:a?void 0:i};mQe(s)||Object.assign(x,fQe(t,x)),x.duration&&(x.duration=ku(x.duration)),x.repeatDelay&&(x.repeatDelay=ku(x.repeatDelay)),x.from!==void 0&&(x.keyframes[0]=x.from);let _=!1;if((x.type===!1||x.duration===0&&!x.repeatDelay)&&(Q6(x),x.delay===0&&(_=!0)),(Yy.instantAnimations||Yy.skipAnimations||i!=null&&i.shouldSkipAnimations)&&(_=!0,Q6(x),x.delay=0),x.allowFlatten=!s.type&&!s.ease,_&&!a&&e.get()!==void 0){const T=aF(x.keyframes,s);if(T!==void 0){ea.update(()=>{x.onUpdate(T),x.onComplete()});return}}return s.isSync?new hD(x):new sQe(x)};function ure(t){const e=[{},{}];return t==null||t.values.forEach((r,n)=>{e[0][n]=r.get(),e[1][n]=r.getVelocity()}),e}function b7(t,e,r,n){if(typeof e=="function"){const[i,a]=ure(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]=ure(n);e=e(r!==void 0?r:t.custom,i,a)}return e}function f0(t,e,r){const n=t.getProps();return b7(n,e,r!==void 0?r:n.custom,t)}const bve=new Set(["width","height","top","left","right","bottom",...jS]),dre=30,gQe=t=>!isNaN(parseFloat(t));class yQe{constructor(e,r={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=n=>{var a;const i=Vc.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=Vc.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=gQe(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 c7);const n=this.events[e].add(r);return e==="change"?()=>{n(),ea.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=Vc.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>dre)return 0;const r=Math.min(this.updatedAt-this.prevUpdatedAt,dre);return B0e(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 C1(t,e){return new yQe(t,e)}const J6=t=>Array.isArray(t);function xQe(t,e,r){t.hasValue(e)?t.getValue(e).set(r):t.addValue(e,C1(r))}function _Qe(t){return J6(t)?t[t.length-1]||0:t}function vQe(t,e){const r=f0(t,e);let{transitionEnd:n={},transition:i={},...a}=r||{};a={...a,...n};for(const c in a){const s=_Qe(a[c]);xQe(t,c,s)}}const Yl=t=>!!(t&&t.getVelocity);function bQe(t){return!!(Yl(t)&&t.add)}function eV(t,e){const r=t.getValue("willChange");if(bQe(r))return r.add(e);if(!r&&Yy.WillChange){const n=new Yy.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function w7(t){return t.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`)}const wQe="framerAppearId",wve="data-"+w7(wQe);function Sve(t){return t.props[wve]}function SQe({protectedKeys:t,needsAnimating:e},r){const n=t.hasOwnProperty(r)&&e[r]!==!0;return e[r]=!1,n}function Tve(t,e,{delay:r=0,transitionOverride:n,type:i}={}){let{transition:a,transitionEnd:c,...s}=e;const f=t.getDefaultTransition();a=a?vve(a,f):f;const m=a==null?void 0:a.reduceMotion;n&&(a=n);const x=[],_=i&&t.animationState&&t.animationState.getState()[i];for(const T in s){const E=t.getValue(T,t.latestValues[T]??null),C=s[T];if(C===void 0||_&&SQe(_,T))continue;const N={delay:r,..._7(a||{},T)},R=E.get();if(R!==void 0&&!E.isAnimating()&&!Array.isArray(C)&&C===R&&!N.velocity){ea.update(()=>E.set(C));continue}let D=!1;if(window.MotionHandoffAnimation){const V=Sve(t);if(V){const G=window.MotionHandoffAnimation(V,T,ea);G!==null&&(N.startTime=G,D=!0)}}eV(t,T);const M=m??t.shouldReduceMotion;E.start(v7(T,E,C,M&&bve.has(T)?{type:!1}:N,t,D));const B=E.animation;B&&x.push(B)}if(c){const T=()=>ea.update(()=>{c&&vQe(t,c)});x.length?Promise.all(x).then(T):T()}return x}function tV(t,e,r={}){var f;const n=f0(t,e,r.type==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);let{transition:i=t.getDefaultTransition()||{}}=n||{};r.transitionOverride&&(i=r.transitionOverride);const a=n?()=>Promise.all(Tve(t,n,r)):()=>Promise.resolve(),c=t.variantChildren&&t.variantChildren.size?(m=0)=>{const{delayChildren:x=0,staggerChildren:_,staggerDirection:T}=i;return TQe(t,e,m,x,_,T,r)}:()=>Promise.resolve(),{when:s}=i;if(s){const[m,x]=s==="beforeChildren"?[a,c]:[c,a];return m().then(()=>x())}else return Promise.all([a(),c(r.delay)])}function TQe(t,e,r=0,n=0,i=0,a=1,c){const s=[];for(const f of t.variantChildren)f.notify("AnimationStart",e),s.push(tV(f,e,{...c,delay:r+(typeof n=="function"?0:n)+xve(t.variantChildren,f,n,i,a)}).then(()=>f.notify("AnimationComplete",e)));return Promise.all(s)}function EQe(t,e,r={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const i=e.map(a=>tV(t,a,r));n=Promise.all(i)}else if(typeof e=="string")n=tV(t,e,r);else{const i=typeof e=="function"?f0(t,e,r.custom):e;n=Promise.all(Tve(t,i,r))}return n.then(()=>{t.notify("AnimationComplete",e)})}const AQe={test:t=>t==="auto",parse:t=>t},Eve=t=>e=>e.test(t),Ave=[CS,In,Xf,Hg,XZe,ZZe,AQe],hre=t=>Ave.find(Eve(t));function kQe(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||M0e(t):!0}const CQe=new Set(["brightness","contrast","saturate","opacity"]);function jQe(t){const[e,r]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=r.match(f7)||[];if(!n)return t;const i=r.replace(n,"");let a=CQe.has(e)?1:0;return n!==r&&(a*=100),e+"("+a+i+")"}const IQe=/\b([a-z-]*)\(.*?\)/gu,rV={...Zh,getAnimatableNone:t=>{const e=t.match(IQe);return e?e.map(jQe).join(" "):t}},nV={...Zh,getAnimatableNone:t=>{const e=Zh.parse(t);return Zh.createTransformer(t)(e.map(n=>typeof n=="number"?0:typeof n=="object"?{...n,alpha:1}:n))}},fre={...CS,transform:Math.round},PQe={rotate:Hg,rotateX:Hg,rotateY:Hg,rotateZ:Hg,scale:wN,scaleX:wN,scaleY:wN,scaleZ:wN,skew:Hg,skewX:Hg,skewY:Hg,distance:In,translateX:In,translateY:In,translateZ:In,x:In,y:In,z:In,perspective:In,transformPerspective:In,opacity:bk,originX:Jte,originY:Jte,originZ:In},S7={borderWidth:In,borderTopWidth:In,borderRightWidth:In,borderBottomWidth:In,borderLeftWidth:In,borderRadius:In,borderTopLeftRadius:In,borderTopRightRadius:In,borderBottomRightRadius:In,borderBottomLeftRadius:In,width:In,maxWidth:In,height:In,maxHeight:In,top:In,right:In,bottom:In,left:In,inset:In,insetBlock:In,insetBlockStart:In,insetBlockEnd:In,insetInline:In,insetInlineStart:In,insetInlineEnd:In,padding:In,paddingTop:In,paddingRight:In,paddingBottom:In,paddingLeft:In,paddingBlock:In,paddingBlockStart:In,paddingBlockEnd:In,paddingInline:In,paddingInlineStart:In,paddingInlineEnd:In,margin:In,marginTop:In,marginRight:In,marginBottom:In,marginLeft:In,marginBlock:In,marginBlockStart:In,marginBlockEnd:In,marginInline:In,marginInlineStart:In,marginInlineEnd:In,fontSize:In,backgroundPositionX:In,backgroundPositionY:In,...PQe,zIndex:fre,fillOpacity:bk,strokeOpacity:bk,numOctaves:fre},NQe={...S7,color:$o,backgroundColor:$o,outlineColor:$o,fill:$o,stroke:$o,borderColor:$o,borderTopColor:$o,borderRightColor:$o,borderBottomColor:$o,borderLeftColor:$o,filter:rV,WebkitFilter:rV,mask:nV,WebkitMask:nV},kve=t=>NQe[t],RQe=new Set([rV,nV]);function Cve(t,e){let r=kve(t);return RQe.has(r)||(r=Zh),r.getAnimatableNone?r.getAnimatableNone(e):void 0}const LQe=new Set(["auto","none","0"]);function DQe(t,e,r){let n=0,i;for(;n{e.getValue(f).set(m)}),this.resolveNoneKeyframes()}}function jve(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 Ive=(t,e)=>e&&typeof t=="number"?e.transform(t):t;function DR(t){return O0e(t)&&"offsetHeight"in t&&!("ownerSVGElement"in t)}const{schedule:T7,cancel:iVt}=Z0e(queueMicrotask,!1),Ih={x:!1,y:!1};function Pve(){return Ih.x||Ih.y}function MQe(t){return t==="x"||t==="y"?Ih[t]?null:(Ih[t]=!0,()=>{Ih[t]=!1}):Ih.x||Ih.y?null:(Ih.x=Ih.y=!0,()=>{Ih.x=Ih.y=!1})}function Nve(t,e){const r=jve(t),n=new AbortController,i={passive:!0,...e,signal:n.signal};return[r,i,()=>n.abort()]}function FQe(t){return!(t.pointerType==="touch"||Pve())}function BQe(t,e,r={}){const[n,i,a]=Nve(t,r);return n.forEach(c=>{let s=!1,f=!1,m;const x=()=>{c.removeEventListener("pointerleave",C)},_=R=>{m&&(m(R),m=void 0),x()},T=R=>{s=!1,window.removeEventListener("pointerup",T),window.removeEventListener("pointercancel",T),f&&(f=!1,_(R))},E=()=>{s=!0,window.addEventListener("pointerup",T,i),window.addEventListener("pointercancel",T,i)},C=R=>{if(R.pointerType!=="touch"){if(s){f=!0;return}_(R)}},N=R=>{if(!FQe(R))return;f=!1;const D=e(c,R);typeof D=="function"&&(m=D,c.addEventListener("pointerleave",C,i))};c.addEventListener("pointerenter",N,i),c.addEventListener("pointerdown",E,i)}),a}const Rve=(t,e)=>e?t===e?!0:Rve(t,e.parentElement):!1,E7=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,zQe=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function $Qe(t){return zQe.has(t.tagName)||t.isContentEditable===!0}const UQe=new Set(["INPUT","SELECT","TEXTAREA"]);function VQe(t){return UQe.has(t.tagName)||t.isContentEditable===!0}const OR=new WeakSet;function pre(t){return e=>{e.key==="Enter"&&t(e)}}function ez(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const qQe=(t,e)=>{const r=t.currentTarget;if(!r)return;const n=pre(()=>{if(OR.has(r))return;ez(r,"down");const i=pre(()=>{ez(r,"up")}),a=()=>ez(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 mre(t){return E7(t)&&!Pve()}const gre=new WeakSet;function GQe(t,e,r={}){const[n,i,a]=Nve(t,r),c=s=>{const f=s.currentTarget;if(!mre(s)||gre.has(s))return;OR.add(f),r.stopPropagation&&gre.add(s);const m=e(f,s),x=(E,C)=>{window.removeEventListener("pointerup",_),window.removeEventListener("pointercancel",T),OR.has(f)&&OR.delete(f),mre(E)&&typeof m=="function"&&m(E,{success:C})},_=E=>{x(E,f===window||f===document||r.useGlobalTarget||Rve(f,E.target))},T=E=>{x(E,!1)};window.addEventListener("pointerup",_,i),window.addEventListener("pointercancel",T,i)};return n.forEach(s=>{(r.useGlobalTarget?window:s).addEventListener("pointerdown",c,i),DR(s)&&(s.addEventListener("focus",m=>qQe(m,i)),!$Qe(s)&&!s.hasAttribute("tabindex")&&(s.tabIndex=0))}),a}function A7(t){return O0e(t)&&"ownerSVGElement"in t}const MR=new WeakMap;let Wg;const Lve=(t,e,r)=>(n,i)=>i&&i[0]?i[0][t+"Size"]:A7(n)&&"getBBox"in n?n.getBBox()[e]:n[r],HQe=Lve("inline","width","offsetWidth"),WQe=Lve("block","height","offsetHeight");function KQe({target:t,borderBoxSize:e}){var r;(r=MR.get(t))==null||r.forEach(n=>{n(t,{get width(){return HQe(t,e)},get height(){return WQe(t,e)}})})}function YQe(t){t.forEach(KQe)}function ZQe(){typeof ResizeObserver>"u"||(Wg=new ResizeObserver(YQe))}function XQe(t,e){Wg||ZQe();const r=jve(t);return r.forEach(n=>{let i=MR.get(n);i||(i=new Set,MR.set(n,i)),i.add(e),Wg==null||Wg.observe(n)}),()=>{r.forEach(n=>{const i=MR.get(n);i==null||i.delete(e),i!=null&&i.size||Wg==null||Wg.unobserve(n)})}}const FR=new Set;let mw;function QQe(){mw=()=>{const t={get width(){return window.innerWidth},get height(){return window.innerHeight}};FR.forEach(e=>e(t))},window.addEventListener("resize",mw)}function JQe(t){return FR.add(t),mw||QQe(),()=>{FR.delete(t),!FR.size&&typeof mw=="function"&&(window.removeEventListener("resize",mw),mw=void 0)}}function yre(t,e){return typeof t=="function"?JQe(t):XQe(t,e)}function eJe(t){return A7(t)&&t.tagName==="svg"}const tJe=[...Ave,$o,Zh],rJe=t=>tJe.find(Eve(t)),xre=()=>({translate:0,scale:1,origin:0,originPoint:0}),gw=()=>({x:xre(),y:xre()}),_re=()=>({min:0,max:0}),tl=()=>({x:_re(),y:_re()}),nJe=new WeakMap;function oF(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function wk(t){return typeof t=="string"||Array.isArray(t)}const k7=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],C7=["initial",...k7];function lF(t){return oF(t.animate)||C7.some(e=>wk(t[e]))}function Dve(t){return!!(lF(t)||t.variants)}function iJe(t,e,r){for(const n in e){const i=e[n],a=r[n];if(Yl(i))t.addValue(n,i);else if(Yl(a))t.addValue(n,C1(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,C1(c!==void 0?c:i,{owner:t}))}}for(const n in r)e[n]===void 0&&t.removeValue(n);return e}const iV={current:null},Ove={current:!1},sJe=typeof window<"u";function aJe(){if(Ove.current=!0,!!sJe)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>iV.current=t.matches;t.addEventListener("change",e),e()}else iV.current=!1}const vre=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let fD={};function Mve(t){fD=t}function oJe(){return fD}class lJe{scrapeMotionValuesFromProps(e,r,n){return{}}constructor({parent:e,props:r,presenceContext:n,reducedMotionConfig:i,skipAnimations:a,blockInitialAnimation:c,visualState:s},f={}){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=x7,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 E=Vc.now();this.renderScheduledAtthis.bindToMotionValue(a,i)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(Ove.current||aJe(),this.shouldReduceMotion=iV.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(),Zy(this.notifyUpdate),Zy(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&&yve.has(e)&&this.current instanceof HTMLElement){const{factory:c,keyframes:s,times:f,ease:m,duration:x}=r.accelerate,_=new mve({element:this.current,name:e,keyframes:s,times:f,ease:m,duration:ku(x)}),T=c(_);this.valueSubscriptions.set(e,()=>{T(),_.cancel()});return}const n=IS.has(e);n&&this.onBindTransform&&this.onBindTransform();const i=r.on("change",c=>{this.latestValues[e]=c,this.props.onUpdate&&ea.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(),r.owner&&r.stop()})}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 fD){const r=fD[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):tl()}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=C1(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"&&(D0e(n)||M0e(n))?n=parseFloat(n):!rJe(n)&&Zh.test(r)&&(n=Cve(e,r)),this.setBaseTarget(e,Yl(n)?n.get():n)),Yl(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=b7(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&&!Yl(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 c7),this.events[e].add(r)}notify(e,...r){this.events[e]&&this.events[e].notify(...r)}scheduleRenderMicrotask(){T7.render(this.render)}}class Fve extends lJe{constructor(){super(...arguments),this.KeyframeResolver=OQe}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;Yl(e)&&(this.childSubscription=e.on("change",r=>{this.current&&(this.current.textContent=`${r}`)}))}}class dx{constructor(e){this.isMounted=!1,this.node=e}update(){}}function Bve({top:t,left:e,right:r,bottom:n}){return{x:{min:e,max:r},y:{min:t,max:n}}}function cJe({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function uJe(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 tz(t){return t===void 0||t===1}function sV({scale:t,scaleX:e,scaleY:r}){return!tz(t)||!tz(e)||!tz(r)}function M_(t){return sV(t)||zve(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function zve(t){return bre(t.x)||bre(t.y)}function bre(t){return t&&t!=="0%"}function pD(t,e,r){const n=t-r,i=e*n;return r+i}function wre(t,e,r,n,i){return i!==void 0&&(t=pD(t,i,n)),pD(t,r,n)+e}function aV(t,e=0,r=1,n,i){t.min=wre(t.min,e,r,n,i),t.max=wre(t.max,e,r,n,i)}function $ve(t,{x:e,y:r}){aV(t.x,e.translate,e.scale,e.originPoint),aV(t.y,r.translate,r.scale,r.originPoint)}const Sre=.999999999999,Tre=1.0000000000001;function dJe(t,e,r,n=!1){var s;const i=r.length;if(!i)return;e.x=e.y=1;let a,c;for(let f=0;fSre&&(e.x=1),e.ySre&&(e.y=1)}function Mf(t,e){t.min+=e,t.max+=e}function Ere(t,e,r,n,i=.5){const a=ka(t.min,t.max,i);aV(t,e,r,a,n)}function Are(t,e){return typeof t=="string"?parseFloat(t)/100*(e.max-e.min):t}function BR(t,e,r){const n=r??t;Ere(t.x,Are(e.x,n.x),e.scaleX,e.scale,e.originX),Ere(t.y,Are(e.y,n.y),e.scaleY,e.scale,e.originY)}function Uve(t,e){return Bve(uJe(t.getBoundingClientRect(),e))}function hJe(t,e,r){const n=Uve(t,r),{scroll:i}=e;return i&&(Mf(n.x,i.offset.x),Mf(n.y,i.offset.y)),n}const fJe={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},pJe=jS.length;function mJe(t,e,r){let n="",i=!0;for(let a=0;a{if(!e.target)return t;if(typeof t=="string")if(In.test(t))t=parseFloat(t);else return t;const r=kre(t,e.target.x),n=kre(t,e.target.y);return`${r}% ${n}%`}},gJe={correct:(t,{treeScale:e,projectionDelta:r})=>{const n=t,i=Zh.parse(t);if(i.length>5)return n;const a=Zh.createTransformer(t),c=typeof i[0]!="number"?1:0,s=r.x.scale*e.x,f=r.y.scale*e.y;i[0+c]/=s,i[1+c]/=f;const m=ka(s,f,.5);return typeof i[2+c]=="number"&&(i[2+c]/=m),typeof i[3+c]=="number"&&(i[3+c]/=m),a(i)}},oV={borderRadius:{...S2,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:S2,borderTopRightRadius:S2,borderBottomLeftRadius:S2,borderBottomRightRadius:S2,boxShadow:gJe};function qve(t,{layout:e,layoutId:r}){return IS.has(t)||t.startsWith("origin")||(e||r!==void 0)&&(!!oV[t]||t==="opacity")}function I7(t,e,r){var c;const n=t.style,i=e==null?void 0:e.style,a={};if(!n)return a;for(const s in n)(Yl(n[s])||i&&Yl(i[s])||qve(s,t)||((c=r==null?void 0:r.getValue(s))==null?void 0:c.liveStyle)!==void 0)&&(a[s]=n[s]);return a}function yJe(t){return window.getComputedStyle(t)}class xJe extends Fve{constructor(){super(...arguments),this.type="html",this.renderInstance=Vve}readValueFromInstance(e,r){var n;if(IS.has(r))return(n=this.projection)!=null&&n.isProjecting?W6(r):MXe(e,r);{const i=yJe(e),a=(Q0e(r)?i.getPropertyValue(r):i[r])||0;return typeof a=="string"?a.trim():a}}measureInstanceViewportBox(e,{transformPagePoint:r}){return Uve(e,r)}build(e,r,n){j7(e,r,n.transformTemplate)}scrapeMotionValuesFromProps(e,r,n){return I7(e,r,n)}}const _Je={offset:"stroke-dashoffset",array:"stroke-dasharray"},vJe={offset:"strokeDashoffset",array:"strokeDasharray"};function bJe(t,e,r=1,n=0,i=!0){t.pathLength=1;const a=i?_Je:vJe;t[a.offset]=`${-n}`,t[a.array]=`${e} ${r}`}const wJe=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function Gve(t,{attrX:e,attrY:r,attrScale:n,pathLength:i,pathSpacing:a=1,pathOffset:c=0,...s},f,m,x){if(j7(t,s,m),f){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:_,style:T}=t;_.transform&&(T.transform=_.transform,delete _.transform),(T.transform||_.transformOrigin)&&(T.transformOrigin=_.transformOrigin??"50% 50%",delete _.transformOrigin),T.transform&&(T.transformBox=(x==null?void 0:x.transformBox)??"fill-box",delete _.transformBox);for(const E of wJe)_[E]!==void 0&&(T[E]=_[E],delete _[E]);e!==void 0&&(_.x=e),r!==void 0&&(_.y=r),n!==void 0&&(_.scale=n),i!==void 0&&bJe(_,i,a,c,!1)}const Hve=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"]),Wve=t=>typeof t=="string"&&t.toLowerCase()==="svg";function SJe(t,e,r,n){Vve(t,e,void 0,n);for(const i in e.attrs)t.setAttribute(Hve.has(i)?i:w7(i),e.attrs[i])}function Kve(t,e,r){const n=I7(t,e,r);for(const i in t)if(Yl(t[i])||Yl(e[i])){const a=jS.indexOf(i)!==-1?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i;n[a]=t[i]}return n}class TJe extends Fve{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=tl}getBaseTargetFromProps(e,r){return e[r]}readValueFromInstance(e,r){if(IS.has(r)){const n=kve(r);return n&&n.default||0}return r=Hve.has(r)?r:w7(r),e.getAttribute(r)}scrapeMotionValuesFromProps(e,r,n){return Kve(e,r,n)}build(e,r,n){Gve(e,r,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,r,n,i){SJe(e,r,n,i)}mount(e){this.isSVGTag=Wve(e.tagName),super.mount(e)}}const EJe=C7.length;function Yve(t){if(!t)return;if(!t.isControllingVariants){const r=t.parent?Yve(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})=>EQe(t,r,n)))}function jJe(t){let e=CJe(t),r=Cre(),n=!0,i=!1;const a=m=>(x,_)=>{var E;const T=f0(t,_,m==="exit"?(E=t.presenceContext)==null?void 0:E.custom:void 0);if(T){const{transition:C,transitionEnd:N,...R}=T;x={...x,...R,...N}}return x};function c(m){e=m(t)}function s(m){const{props:x}=t,_=Yve(t.parent)||{},T=[],E=new Set;let C={},N=1/0;for(let D=0;DN&&G,se=!1;const ue=Array.isArray(V)?V:[V];let _e=ue.reduce(a(M),{});W===!1&&(_e={});const{prevResolvedValues:Se={}}=B,ve={...Se,..._e},Oe=ge=>{re=!0,E.has(ge)&&(se=!0,E.delete(ge)),B.needsAnimating[ge]=!0;const Ne=t.getValue(ge);Ne&&(Ne.liveStyle=!1)};for(const ge in ve){const Ne=_e[ge],Ie=Se[ge];if(C.hasOwnProperty(ge))continue;let Te=!1;J6(Ne)&&J6(Ie)?Te=!Zve(Ne,Ie):Te=Ne!==Ie,Te?Ne!=null?Oe(ge):E.add(ge):Ne!==void 0&&E.has(ge)?Oe(ge):B.protectedKeys[ge]=!0}B.prevProp=V,B.prevResolvedValues=_e,B.isActive&&(C={...C,..._e}),(n||i)&&t.blockInitialAnimation&&(re=!1);const Ae=X&&Q;re&&(!Ae||se)&&T.push(...ue.map(ge=>{const Ne={type:M};if(typeof ge=="string"&&(n||i)&&!Ae&&t.manuallyAnimateOnMount&&t.parent){const{parent:Ie}=t,Te=f0(Ie,ge);if(Ie.enteringChildren&&Te){const{delayChildren:be}=Te.transition||{};Ne.delay=xve(Ie.enteringChildren,t,be)}}return{animation:ge,options:Ne}}))}if(E.size){const D={};if(typeof x.initial!="boolean"){const M=f0(t,Array.isArray(x.initial)?x.initial[0]:x.initial);M&&M.transition&&(D.transition=M.transition)}E.forEach(M=>{const B=t.getBaseTarget(M),V=t.getValue(M);V&&(V.liveStyle=!0),D[M]=B??null}),T.push({animation:D})}let R=!!T.length;return n&&(x.initial===!1||x.initial===x.animate)&&!t.manuallyAnimateOnMount&&(R=!1),n=!1,i=!1,R?e(T):Promise.resolve()}function f(m,x){var T;if(r[m].isActive===x)return Promise.resolve();(T=t.variantChildren)==null||T.forEach(E=>{var C;return(C=E.animationState)==null?void 0:C.setActive(m,x)}),r[m].isActive=x;const _=s(m);for(const E in r)r[E].protectedKeys={};return _}return{animateChanges:s,setActive:f,setAnimateFunction:c,getState:()=>r,reset:()=>{r=Cre(),i=!0}}}function IJe(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Zve(e,t):!1}function k_(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Cre(){return{animate:k_(!0),whileInView:k_(),whileHover:k_(),whileTap:k_(),whileDrag:k_(),whileFocus:k_(),exit:k_()}}function lV(t,e){t.min=e.min,t.max=e.max}function Ah(t,e){lV(t.x,e.x),lV(t.y,e.y)}function jre(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}const Xve=1e-4,PJe=1-Xve,NJe=1+Xve,Qve=.01,RJe=0-Qve,LJe=0+Qve;function qc(t){return t.max-t.min}function DJe(t,e,r){return Math.abs(t-e)<=r}function Ire(t,e,r,n=.5){t.origin=n,t.originPoint=ka(e.min,e.max,t.origin),t.scale=qc(r)/qc(e),t.translate=ka(r.min,r.max,t.origin)-t.originPoint,(t.scale>=PJe&&t.scale<=NJe||isNaN(t.scale))&&(t.scale=1),(t.translate>=RJe&&t.translate<=LJe||isNaN(t.translate))&&(t.translate=0)}function bA(t,e,r,n){Ire(t.x,e.x,r.x,n?n.originX:void 0),Ire(t.y,e.y,r.y,n?n.originY:void 0)}function Pre(t,e,r,n=0){const i=n?ka(r.min,r.max,n):r.min;t.min=i+e.min,t.max=t.min+qc(e)}function OJe(t,e,r,n){Pre(t.x,e.x,r.x,n==null?void 0:n.x),Pre(t.y,e.y,r.y,n==null?void 0:n.y)}function Nre(t,e,r,n=0){const i=n?ka(r.min,r.max,n):r.min;t.min=e.min-i,t.max=t.min+qc(e)}function mD(t,e,r,n){Nre(t.x,e.x,r.x,n==null?void 0:n.x),Nre(t.y,e.y,r.y,n==null?void 0:n.y)}function Rre(t,e,r,n,i){return t-=e,t=pD(t,1/r,n),i!==void 0&&(t=pD(t,1/i,n)),t}function MJe(t,e=0,r=1,n=.5,i,a=t,c=t){if(Xf.test(e)&&(e=parseFloat(e),e=ka(c.min,c.max,e/100)-c.min),typeof e!="number")return;let s=ka(a.min,a.max,n);t===a&&(s-=e),t.min=Rre(t.min,e,r,s,i),t.max=Rre(t.max,e,r,s,i)}function Lre(t,e,[r,n,i],a,c){MJe(t,e[r],e[n],e[i],e.scale,a,c)}const FJe=["x","scaleX","originX"],BJe=["y","scaleY","originY"];function Dre(t,e,r,n){Lre(t.x,e,FJe,r?r.x:void 0,n?n.x:void 0),Lre(t.y,e,BJe,r?r.y:void 0,n?n.y:void 0)}function Ore(t){return t.translate===0&&t.scale===1}function Jve(t){return Ore(t.x)&&Ore(t.y)}function Mre(t,e){return t.min===e.min&&t.max===e.max}function zJe(t,e){return Mre(t.x,e.x)&&Mre(t.y,e.y)}function Fre(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function ebe(t,e){return Fre(t.x,e.x)&&Fre(t.y,e.y)}function Bre(t){return qc(t.x)/qc(t.y)}function zre(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}function Nf(t){return[t("x"),t("y")]}function $Je(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:m,rotate:x,rotateX:_,rotateY:T,skewX:E,skewY:C}=r;m&&(n=`perspective(${m}px) ${n}`),x&&(n+=`rotate(${x}deg) `),_&&(n+=`rotateX(${_}deg) `),T&&(n+=`rotateY(${T}deg) `),E&&(n+=`skewX(${E}deg) `),C&&(n+=`skewY(${C}deg) `)}const s=t.x.scale*e.x,f=t.y.scale*e.y;return(s!==1||f!==1)&&(n+=`scale(${s}, ${f})`),n||"none"}const tbe=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],UJe=tbe.length,$re=t=>typeof t=="string"?parseFloat(t):t,Ure=t=>typeof t=="number"||In.test(t);function VJe(t,e,r,n,i,a){i?(t.opacity=ka(0,r.opacity??1,qJe(n)),t.opacityExit=ka(e.opacity??1,0,GJe(n))):a&&(t.opacity=ka(e.opacity??1,r.opacity??1,n));for(let c=0;cne?1:r(vk(t,e,n))}function HJe(t,e,r){const n=Yl(t)?t:C1(t);return n.start(v7("",n,e,r)),n.animation}function Sk(t,e,r,n={passive:!0}){return t.addEventListener(e,r,n),()=>t.removeEventListener(e,r)}const WJe=(t,e)=>t.depth-e.depth;class KJe{constructor(){this.children=[],this.isDirty=!1}add(e){l7(this.children,e),this.isDirty=!0}remove(e){lD(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(WJe),this.isDirty=!1,this.children.forEach(e)}}function YJe(t,e){const r=Vc.now(),n=({timestamp:i})=>{const a=i-r;a>=e&&(Zy(n),t(a-e))};return ea.setup(n,!0),()=>Zy(n)}function zR(t){return Yl(t)?t.get():t}class ZJe{constructor(){this.members=[]}add(e){l7(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&&(lD(this.members,n),n.unmount())}e.scheduleRender()}remove(e){if(lD(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 $R={hasAnimatedSinceResize:!0,hasEverUpdated:!1},rz=["","X","Y","Z"],XJe=1e3;let QJe=0;function nz(t,e,r,n){const{latestValues:i}=e;i[t]&&(r[t]=i[t],e.setStaticValue(t,0),n&&(n[t]=0))}function nbe(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const r=Sve(e);if(window.MotionHasOptimisedAnimation(r,"transform")){const{layout:i,layoutId:a}=t.options;window.MotionCancelOptimisedAnimation(r,"transform",ea,!(i||a))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&nbe(n)}function ibe({attachResizeListener:t,defaultParent:e,measureScroll:r,checkIsScrollRoot:n,resetTransform:i}){return class{constructor(c={},s=e==null?void 0:e()){this.id=QJe++,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(tet),this.nodes.forEach(oet),this.nodes.forEach(cet),this.nodes.forEach(ret)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=c,this.root=s?s.root||s:this,this.path=s?[...s.path,s]:[],this.parent=s,this.depth=s?s.depth+1:0;for(let f=0;fthis.root.updateBlockedByResize=!1;ea.read(()=>{_=window.innerWidth}),t(c,()=>{const E=window.innerWidth;E!==_&&(_=E,this.root.updateBlockedByResize=!0,x&&x(),x=YJe(T,250),$R.hasAnimatedSinceResize&&($R.hasAnimatedSinceResize=!1,this.nodes.forEach(Hre)))})}s&&this.root.registerSharedNode(s,this),this.options.animate!==!1&&m&&(s||f)&&this.addEventListener("didUpdate",({delta:x,hasLayoutChanged:_,hasRelativeLayoutChanged:T,layout:E})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const C=this.options.transition||m.getDefaultTransition()||pet,{onLayoutAnimationStart:N,onLayoutAnimationComplete:R}=m.getProps(),D=!this.targetLayout||!ebe(this.targetLayout,E),M=!_&&T;if(this.options.layoutRoot||this.resumeFrom||M||_&&(D||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const B={..._7(C,"layout"),onPlay:N,onComplete:R};(m.shouldReduceMotion||this.options.layoutRoot)&&(B.delay=0,B.type=!1),this.startAnimation(B),this.setAnimationOrigin(x,M)}else _||Hre(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=E})}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(),Zy(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(uet),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&&nbe(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let x=0;x{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!qc(this.snapshot.measuredBox.x)&&!qc(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 f=0;f{const G=V/1e3;Wre(_.x,c.x,G),Wre(_.y,c.y,G),this.setTargetDelta(_),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(mD(T,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),het(this.relativeTarget,this.relativeTargetOrigin,T,G),B&&zJe(this.relativeTarget,B)&&(this.isProjectionDirty=!1),B||(B=tl()),Ah(B,this.relativeTarget)),N&&(this.animationValues=x,VJe(x,m,this.latestValues,G,M,D)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=G},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(c){var s,f,m;this.notifyListeners("animationStart"),(s=this.currentAnimation)==null||s.stop(),(m=(f=this.resumingFrom)==null?void 0:f.currentAnimation)==null||m.stop(),this.pendingAnimation&&(Zy(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ea.update(()=>{$R.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=C1(0)),this.motionValue.jump(0,!1),this.currentAnimation=HJe(this.motionValue,[0,1e3],{...c,velocity:0,isSync:!0,onUpdate:x=>{this.mixTargetDelta(x),c.onUpdate&&c.onUpdate(x)},onStop:()=>{},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(XJe),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const c=this.getLead();let{targetWithTransforms:s,target:f,layout:m,latestValues:x}=c;if(!(!s||!f||!m)){if(this!==c&&this.layout&&m&&sbe(this.options.animationType,this.layout.layoutBox,m.layoutBox)){f=this.target||tl();const _=qc(this.layout.layoutBox.x);f.x.min=c.target.x.min,f.x.max=f.x.min+_;const T=qc(this.layout.layoutBox.y);f.y.min=c.target.y.min,f.y.max=f.y.min+T}Ah(s,f),BR(s,x),bA(this.projectionDeltaWithTransform,this.layoutCorrected,s,x)}}registerSharedNode(c,s){this.sharedNodes.has(c)||this.sharedNodes.set(c,new ZJe),this.sharedNodes.get(c).add(s);const m=s.options.initialPromotionConfig;s.promote({transition:m?m.transition:void 0,preserveFollowOpacity:m&&m.shouldPreserveFollowOpacity?m.shouldPreserveFollowOpacity(s):void 0})}isLead(){const c=this.getStack();return c?c.lead===this:!0}getLead(){var s;const{layoutId:c}=this.options;return c?((s=this.getStack())==null?void 0:s.lead)||this:this}getPrevLead(){var s;const{layoutId:c}=this.options;return c?(s=this.getStack())==null?void 0:s.prevLead:void 0}getStack(){const{layoutId:c}=this.options;if(c)return this.root.sharedNodes.get(c)}promote({needsReset:c,transition:s,preserveFollowOpacity:f}={}){const m=this.getStack();m&&m.promote(this,f),c&&(this.projectionDelta=void 0,this.needsReset=!0),s&&this.setOptions({transition:s})}relegate(){const c=this.getStack();return c?c.relegate(this):!1}resetSkewAndRotation(){const{visualElement:c}=this.options;if(!c)return;let s=!1;const{latestValues:f}=c;if((f.z||f.rotate||f.rotateX||f.rotateY||f.rotateZ||f.skewX||f.skewY)&&(s=!0),!s)return;const m={};f.z&&nz("z",c,m,this.animationValues);for(let x=0;x{var s;return(s=c.currentAnimation)==null?void 0:s.stop()}),this.root.nodes.forEach(qre),this.root.sharedNodes.clear()}}}function JJe(t){t.updateLayout()}function eet(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")Nf(_=>{const T=c?e.measuredBox[_]:e.layoutBox[_],E=qc(T);T.min=n[_].min,T.max=T.min+E});else if(a==="x"||a==="y"){const _=a==="x"?"y":"x";lV(c?e.measuredBox[_]:e.layoutBox[_],n[_])}else sbe(a,e.layoutBox,n)&&Nf(_=>{const T=c?e.measuredBox[_]:e.layoutBox[_],E=qc(n[_]);T.max=T.min+E,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[_].max=t.relativeTarget[_].min+E)});const s=gw();bA(s,n,e.layoutBox);const f=gw();c?bA(f,t.applyTransform(i,!0),e.measuredBox):bA(f,n,e.layoutBox);const m=!Jve(s);let x=!1;if(!t.resumeFrom){const _=t.getClosestProjectingParent();if(_&&!_.resumeFrom){const{snapshot:T,layout:E}=_;if(T&&E){const C=t.options.layoutAnchor||void 0,N=tl();mD(N,e.layoutBox,T.layoutBox,C);const R=tl();mD(R,n,E.layoutBox,C),ebe(N,R)||(x=!0),_.options.layoutRoot&&(t.relativeTarget=R,t.relativeTargetOrigin=N,t.relativeParent=_)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:f,layoutDelta:s,hasLayoutChanged:m,hasRelativeLayoutChanged:x})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function tet(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 ret(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function net(t){t.clearSnapshot()}function qre(t){t.clearMeasurements()}function iet(t){t.isLayoutDirty=!0,t.updateLayout()}function Gre(t){t.isLayoutDirty=!1}function set(t){t.isAnimationBlocked&&t.layout&&!t.isLayoutDirty&&(t.snapshot=t.layout,t.isLayoutDirty=!0)}function aet(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Hre(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function oet(t){t.resolveTargetDelta()}function cet(t){t.calcProjection()}function uet(t){t.resetSkewAndRotation()}function det(t){t.removeLeadSnapshot()}function Wre(t,e,r){t.translate=ka(e.translate,0,r),t.scale=ka(e.scale,1,r),t.origin=e.origin,t.originPoint=e.originPoint}function Kre(t,e,r,n){t.min=ka(e.min,r.min,n),t.max=ka(e.max,r.max,n)}function het(t,e,r,n){Kre(t.x,e.x,r.x,n),Kre(t.y,e.y,r.y,n)}function fet(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const pet={duration:.45,ease:[.4,0,.1,1]},Yre=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Zre=Yre("applewebkit/")&&!Yre("chrome/")?Math.round:Hd;function Xre(t){t.min=Zre(t.min),t.max=Zre(t.max)}function met(t){Xre(t.x),Xre(t.y)}function sbe(t,e,r){return t==="position"||t==="preserve-aspect"&&!DJe(Bre(e),Bre(r),.2)}function get(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const yet=ibe({attachResizeListener:(t,e)=>Sk(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}),iz={current:void 0},abe=ibe({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!iz.current){const t=new yet({});t.mount(window),t.setOptions({layoutScroll:!0}),iz.current=t}return iz.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),P7=P.createContext({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});function Qre(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function xet(...t){return e=>{let r=!1;const n=t.map(i=>{const a=Qre(i,e);return!r&&typeof a=="function"&&(r=!0),a});if(r)return()=>{for(let i=0;i{const{width:E,height:C,top:N,left:R,right:D,bottom:M}=f.current;if(e||a===!1||!s.current||!E||!C)return;const B=r==="left"?`left: ${R}`:`right: ${D}`,V=n==="bottom"?`bottom: ${M}`:`top: ${N}`;s.current.dataset.motionPopId=c;const G=document.createElement("style");m&&(G.nonce=m);const W=i??document.head;return W.appendChild(G),G.sheet&&G.sheet.insertRule(` [data-motion-pop-id="${c}"] { position: absolute !important; width: ${E}px !important; height: ${C}px !important; ${B}px !important; ${V}px !important; } `),()=>{var X;(X=s.current)==null||X.removeAttribute("data-motion-pop-id"),W.contains(G)&&W.removeChild(G)}},[e]),o.jsx(vet,{isPresent:e,childRef:s,sizeRef:f,pop:a,children:a===!1?t:P.cloneElement(t,{ref:_})})}const wet=({children:t,initial:e,isPresent:r,onExitComplete:n,custom:i,presenceAffectsLayout:a,mode:c,anchorX:s,anchorY:f,root:m})=>{const x=o7(Tet),_=P.useId();let T=!0,E=P.useMemo(()=>(T=!1,{id:_,initial:e,isPresent:r,custom:i,onExitComplete:C=>{x.set(C,!0);for(const N of x.values())if(!N)return;n&&n()},register:C=>(x.set(C,!1),()=>x.delete(C))}),[r,x,n]);return a&&T&&(E={...E}),P.useMemo(()=>{x.forEach((C,N)=>x.set(N,!1))},[r]),P.useEffect(()=>{!r&&!x.size&&n&&n()},[r]),t=o.jsx(bet,{pop:c==="popLayout",isPresent:r,anchorX:s,anchorY:f,root:m,children:t}),o.jsx(iF.Provider,{value:E,children:t})};function Tet(){return new Map}function obe(t=!0){const e=P.useContext(iF);if(e===null)return[!0,null];const{isPresent:r,onExitComplete:n,register:i}=e,a=P.useId();P.useEffect(()=>{if(t)return i(a)},[t]);const c=P.useCallback(()=>t&&n&&n(a),[a,n,t]);return!r&&n?[!1,c]:[!0]}const SN=t=>t.key||"";function Jre(t){const e=[];return P.Children.forEach(t,r=>{P.isValidElement(r)&&e.push(r)}),e}const lbe=({children:t,custom:e,initial:r=!0,onExitComplete:n,presenceAffectsLayout:i=!0,mode:a="sync",propagate:c=!1,anchorX:s="left",anchorY:f="top",root:m})=>{const[x,_]=obe(c),T=P.useMemo(()=>Jre(t),[t]),E=c&&!x?[]:T.map(SN),C=P.useRef(!0),N=P.useRef(T),R=o7(()=>new Map),D=P.useRef(new Set),[M,B]=P.useState(T),[V,G]=P.useState(T);L0e(()=>{C.current=!1,N.current=T;for(let Q=0;Q{const re=SN(Q),se=c&&!x?!1:T===V||E.includes(re),ue=()=>{if(D.current.has(re))return;if(R.has(re))D.current.add(re),R.set(re,!0);else return;let _e=!0;R.forEach(Se=>{Se||(_e=!1)}),_e&&(X==null||X(),G(N.current),c&&(_==null||_()),n&&n())};return o.jsx(wet,{isPresent:se,initial:!C.current||r?void 0:!1,custom:e,presenceAffectsLayout:i,mode:a,root:m,onExitComplete:se?void 0:ue,anchorX:s,anchorY:f,children:Q},re)})})},cbe=P.createContext({strict:!1}),ene={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 tne=!1;function Eet(){if(tne)return;const t={};for(const e in ene)t[e]={isEnabled:r=>ene[e].some(n=>!!r[n])};Mve(t),tne=!0}function ube(){return Eet(),oJe()}function Aet(t){const e=ube();for(const r in t)e[r]={...e[r],...t[r]};Mve(e)}const ket=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 gD(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||ket.has(t)}let dbe=t=>!gD(t);function Cet(t){typeof t=="function"&&(dbe=e=>e.startsWith("on")?!gD(e):t(e))}try{Cet(require("@emotion/is-prop-valid").default)}catch{}function jet(t,e,r){const n={};for(const i in t)i==="values"&&typeof t.values=="object"||Yl(t[i])||(dbe(i)||r===!0&&gD(i)||!e&&!gD(i)||t.draggable&&i.startsWith("onDrag"))&&(n[i]=t[i]);return n}const cF=P.createContext({});function Iet(t,e){if(lF(t)){const{initial:r,animate:n}=t;return{initial:r===!1||wk(r)?r:void 0,animate:wk(n)?n:void 0}}return t.inherit!==!1?e:{}}function Pet(t){const{initial:e,animate:r}=Iet(t,P.useContext(cF));return P.useMemo(()=>({initial:e,animate:r}),[rne(e),rne(r)])}function rne(t){return Array.isArray(t)?t.join(" "):t}const N7=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function hbe(t,e,r){for(const n in e)!Yl(e[n])&&!qve(n,r)&&(t[n]=e[n])}function Net({transformTemplate:t},e){return P.useMemo(()=>{const r=N7();return j7(r,e,t),Object.assign({},r.vars,r.style)},[e])}function Ret(t,e){const r=t.style||{},n={};return hbe(n,r,t),Object.assign(n,Net(t,e)),n}function Let(t,e){const r={},n=Ret(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 fbe=()=>({...N7(),attrs:{}});function Det(t,e,r,n){const i=P.useMemo(()=>{const a=fbe();return Gve(a,e,Wve(n),t.transformTemplate,t.style),{...a.attrs,style:{...a.style}}},[e]);if(t.style){const a={};hbe(a,t.style,t),i.style={...a,...i.style}}return i}const Oet=["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 R7(t){return typeof t!="string"||t.includes("-")?!1:!!(Oet.indexOf(t)>-1||/[A-Z]/u.test(t))}function Met(t,e,r,{latestValues:n},i,a=!1,c){const f=(c??R7(t)?Det:Let)(e,n,i,t),m=jet(e,typeof t=="string",a),x=t!==P.Fragment?{...m,...f,ref:r}:{},{children:_}=e,T=P.useMemo(()=>Yl(_)?_.get():_,[_]);return P.createElement(t,{...x,children:T})}function Fet({scrapeMotionValuesFromProps:t,createRenderState:e},r,n,i){return{latestValues:Bet(r,n,i,t),renderState:e()}}function Bet(t,e,r,n){const i={},a=n(t,{});for(const T in a)i[T]=zR(a[T]);let{initial:c,animate:s}=t;const f=lF(t),m=Dve(t);e&&m&&!f&&t.inherit!==!1&&(c===void 0&&(c=e.initial),s===void 0&&(s=e.animate));let x=r?r.initial===!1:!1;x=x||c===!1;const _=x?s:c;if(_&&typeof _!="boolean"&&!oF(_)){const T=Array.isArray(_)?_:[_];for(let E=0;E(e,r)=>{const n=P.useContext(cF),i=P.useContext(iF),a=()=>Fet(t,e,n,i);return r?a():o7(a)},zet=pbe({scrapeMotionValuesFromProps:I7,createRenderState:N7}),$et=pbe({scrapeMotionValuesFromProps:Kve,createRenderState:fbe}),Uet=Symbol.for("motionComponentSymbol");function Vet(t,e,r){const n=P.useRef(r);P.useInsertionEffect(()=>{n.current=r});const i=P.useRef(null);return P.useCallback(a=>{var s;a&&((s=t.onMount)==null||s.call(t,a));const c=n.current;if(typeof c=="function")if(a){const f=c(a);typeof f=="function"&&(i.current=f)}else i.current?(i.current(),i.current=null):c(a);else c&&(c.current=a);e&&(a?e.mount(a):e.unmount())},[e])}const mbe=P.createContext({});function Qb(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function qet(t,e,r,n,i,a){var B,V;const{visualElement:c}=P.useContext(cF),s=P.useContext(cbe),f=P.useContext(iF),m=P.useContext(P7),x=m.reducedMotion,_=m.skipAnimations,T=P.useRef(null),E=P.useRef(!1);n=n||s.renderer,!T.current&&n&&(T.current=n(t,{visualState:e,parent:c,props:r,presenceContext:f,blockInitialAnimation:f?f.initial===!1:!1,reducedMotionConfig:x,skipAnimations:_,isSVG:a}),E.current&&T.current&&(T.current.manuallyAnimateOnMount=!0));const C=T.current,N=P.useContext(mbe);C&&!C.projection&&i&&(C.type==="html"||C.type==="svg")&&Get(T.current,r,i,N);const R=P.useRef(!1);P.useInsertionEffect(()=>{C&&R.current&&C.update(r,f)});const D=r[wve],M=P.useRef(!!D&&typeof window<"u"&&!((B=window.MotionHandoffIsComplete)!=null&&B.call(window,D))&&((V=window.MotionHasOptimisedAnimation)==null?void 0:V.call(window,D)));return L0e(()=>{E.current=!0,C&&(R.current=!0,window.MotionIsMounted=!0,C.updateFeatures(),C.scheduleRenderMicrotask(),M.current&&C.animationState&&C.animationState.animateChanges())}),P.useEffect(()=>{C&&(!M.current&&C.animationState&&C.animationState.animateChanges(),M.current&&(queueMicrotask(()=>{var G;(G=window.MotionHandoffMarkAsComplete)==null||G.call(window,D)}),M.current=!1),C.enteringChildren=void 0)}),C}function Get(t,e,r,n){const{layoutId:i,layout:a,drag:c,dragConstraints:s,layoutScroll:f,layoutRoot:m,layoutAnchor:x,layoutCrossfade:_}=e;t.projection=new r(t.latestValues,e["data-framer-portal-id"]?void 0:gbe(t.parent)),t.projection.setOptions({layoutId:i,layout:a,alwaysMeasureLayout:!!c||s&&Qb(s),visualElement:t,animationType:typeof a=="string"?a:"both",initialPromotionConfig:n,crossfade:_,layoutScroll:f,layoutRoot:m,layoutAnchor:x})}function gbe(t){if(t)return t.options.allowProjection!==!1?t.projection:gbe(t.parent)}function sz(t,{forwardMotionProps:e=!1,type:r}={},n,i){n&&Aet(n);const a=r?r==="svg":R7(t),c=a?$et:zet;function s(m,x){let _;const T={...P.useContext(P7),...m,layoutId:Het(m)},{isStatic:E}=T,C=Pet(m),N=c(m,E);if(!E&&typeof window<"u"){Wet();const R=Ket(T);_=R.MeasureLayout,C.visualElement=qet(t,N,T,i,R.ProjectionNode,a)}return o.jsxs(cF.Provider,{value:C,children:[_&&C.visualElement?o.jsx(_,{visualElement:C.visualElement,...T}):null,Met(t,m,Vet(N,C.visualElement,x),N,E,e,a)]})}s.displayName=`motion.${typeof t=="string"?t:`create(${t.displayName??t.name??""})`}`;const f=P.forwardRef(s);return f[Uet]=t,f}function Het({layoutId:t}){const e=P.useContext(a7).id;return e&&t!==void 0?e+"-"+t:t}function Wet(t,e){P.useContext(cbe).strict}function Ket(t){const e=ube(),{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 Yet(t,e){if(typeof Proxy>"u")return sz;const r=new Map,n=(a,c)=>sz(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,sz(c,void 0,t,e)),r.get(c))})}const Zet=(t,e)=>e.isSVG??R7(t)?new TJe(e):new xJe(e,{allowProjection:t!==P.Fragment});class Xet extends dx{constructor(e){super(e),e.animationState||(e.animationState=jJe(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();oF(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 Qet=0;class Jet extends dx{constructor(){super(...arguments),this.id=Qet++,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:s}=this.node.getProps();if(typeof c=="string"){const f=f0(this.node,c,s);if(f){const{transition:m,transitionEnd:x,..._}=f;for(const T in _)(a=this.node.getValue(T))==null||a.jump(_[T])}}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 ett={animation:{Feature:Xet},exit:{Feature:Jet}};function tj(t){return{point:{x:t.pageX,y:t.pageY}}}const ttt=t=>e=>E7(e)&&t(e,tj(e));function wA(t,e,r,n){return Sk(t,e,ttt(r),n)}const ybe=({current:t})=>t?t.ownerDocument.defaultView:null,nne=(t,e)=>Math.abs(t-e);function rtt(t,e){const r=nne(t.x,e.x),n=nne(t.y,e.y);return Math.sqrt(r**2+n**2)}const ine=new Set(["auto","scroll"]);class xbe{constructor(e,r,{transformPagePoint:n,contextWindow:i=window,dragSnapToOrigin:a=!1,distanceThreshold:c=3,element:s}={}){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=E=>{this.handleScroll(E.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=TN(this.lastRawMoveEventInfo,this.transformPagePoint));const E=az(this.lastMoveEventInfo,this.history),C=this.startEvent!==null,N=rtt(E.offset,{x:0,y:0})>=this.distanceThreshold;if(!C&&!N)return;const{point:R}=E,{timestamp:D}=Bl;this.history.push({...R,timestamp:D});const{onStart:M,onMove:B}=this.handlers;C||(M&&M(this.lastMoveEvent,E),this.startEvent=this.lastMoveEvent),B&&B(this.lastMoveEvent,E)},this.handlePointerMove=(E,C)=>{this.lastMoveEvent=E,this.lastRawMoveEventInfo=C,this.lastMoveEventInfo=TN(C,this.transformPagePoint),ea.update(this.updatePoint,!0)},this.handlePointerUp=(E,C)=>{this.end();const{onEnd:N,onSessionEnd:R,resumeAnimation:D}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&D&&D(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const M=az(E.type==="pointercancel"?this.lastMoveEventInfo:TN(C,this.transformPagePoint),this.history);this.startEvent&&N&&N(E,M),R&&R(E,M)},!E7(e))return;this.dragSnapToOrigin=a,this.handlers=r,this.transformPagePoint=n,this.distanceThreshold=c,this.contextWindow=i||window;const f=tj(e),m=TN(f,this.transformPagePoint),{point:x}=m,{timestamp:_}=Bl;this.history=[{...x,timestamp:_}];const{onSessionStart:T}=r;T&&T(e,az(m,this.history)),this.removeListeners=QC(wA(this.contextWindow,"pointermove",this.handlePointerMove),wA(this.contextWindow,"pointerup",this.handlePointerUp),wA(this.contextWindow,"pointercancel",this.handlePointerUp)),s&&this.startScrollTracking(s)}startScrollTracking(e){let r=e.parentElement;for(;r;){const n=getComputedStyle(r);(ine.has(n.overflowX)||ine.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),ea.update(this.updatePoint,!0))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Zy(this.updatePoint)}}function TN(t,e){return e?{point:e(t.point)}:t}function sne(t,e){return{x:t.x-e.x,y:t.y-e.y}}function az({point:t},e){return{point:t,delta:sne(t,_be(e)),offset:sne(t,ntt(e)),velocity:itt(e,.1)}}function ntt(t){return t[0]}function _be(t){return t[t.length-1]}function itt(t,e){if(t.length<2)return{x:0,y:0};let r=t.length-1,n=null;const i=_be(t);for(;r>=0&&(n=t[r],!(i.timestamp-n.timestamp>ku(e)));)r--;if(!n)return{x:0,y:0};n===t[0]&&t.length>2&&i.timestamp-n.timestamp>ku(e)*2&&(n=t[1]);const a=$d(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 stt(t,{min:e,max:r},n){return e!==void 0&&tr&&(t=n?ka(r,t,n.max):Math.min(t,r)),t}function ane(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 att(t,{top:e,left:r,bottom:n,right:i}){return{x:ane(t.x,r,i),y:ane(t.y,e,n)}}function one(t,e){let r=e.min-t.min,n=e.max-t.max;return e.max-e.minn?r=vk(e.min,e.max-n,t.min):n>i&&(r=vk(t.min,t.max-i,e.min)),ap(0,1,r)}function ctt(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 cV=.35;function utt(t=cV){return t===!1?t=0:t===!0&&(t=cV),{x:lne(t,"left","right"),y:lne(t,"top","bottom")}}function lne(t,e,r){return{min:cne(t,e),max:cne(t,r)}}function cne(t,e){return typeof t=="number"?t:t[e]||0}const dtt=new WeakMap;class htt{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=tl(),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=_=>{r&&this.snapToCursor(tj(_).point),this.stopAnimation()},c=(_,T)=>{const{drag:E,dragPropagation:C,onDragStart:N}=this.getProps();if(E&&!C&&(this.openDragLock&&this.openDragLock(),this.openDragLock=MQe(E),!this.openDragLock))return;this.latestPointerEvent=_,this.latestPanInfo=T,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Nf(D=>{let M=this.getAxisMotionValue(D).get()||0;if(Xf.test(M)){const{projection:B}=this.visualElement;if(B&&B.layout){const V=B.layout.layoutBox[D];V&&(M=qc(V)*(parseFloat(M)/100))}}this.originPoint[D]=M}),N&&ea.update(()=>N(_,T),!1,!0),eV(this.visualElement,"transform");const{animationState:R}=this.visualElement;R&&R.setActive("whileDrag",!0)},s=(_,T)=>{this.latestPointerEvent=_,this.latestPanInfo=T;const{dragPropagation:E,dragDirectionLock:C,onDirectionLock:N,onDrag:R}=this.getProps();if(!E&&!this.openDragLock)return;const{offset:D}=T;if(C&&this.currentDirection===null){this.currentDirection=ptt(D),this.currentDirection!==null&&N&&N(this.currentDirection);return}this.updateAxis("x",T.point,D),this.updateAxis("y",T.point,D),this.visualElement.render(),R&&ea.update(()=>R(_,T),!1,!0)},f=(_,T)=>{this.latestPointerEvent=_,this.latestPanInfo=T,this.stop(_,T),this.latestPointerEvent=null,this.latestPanInfo=null},m=()=>{const{dragSnapToOrigin:_}=this.getProps();(_||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:x}=this.getProps();this.panSession=new xbe(e,{onSessionStart:a,onStart:c,onMove:s,onSessionEnd:f,resumeAnimation:m},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:x,distanceThreshold:n,contextWindow:ybe(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:s}=this.getProps();s&&ea.postRender(()=>s(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||!EN(e,i,this.currentDirection))return;const a=this.getAxisMotionValue(e);let c=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(c=stt(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&&Qb(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=att(n.layoutBox,e):this.constraints=!1,this.elastic=utt(r),i!==this.constraints&&!Qb(e)&&n&&this.constraints&&!this.hasMutatedConstraints&&Nf(c=>{this.constraints!==!1&&this.getAxisMotionValue(c)&&(this.constraints[c]=ctt(n.layoutBox[c],this.constraints[c]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:r}=this.getProps();if(!e||!Qb(e))return!1;const n=e.current;A1(n!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:i}=this.visualElement;if(!i||!i.layout)return!1;const a=hJe(n,i.root,this.visualElement.getTransformPagePoint());let c=ott(i.layout.layoutBox,a);if(r){const s=r(cJe(c));this.hasMutatedConstraints=!!s,s&&(c=Bve(s))}return c}startAnimation(e){const{drag:r,dragMomentum:n,dragElastic:i,dragTransition:a,dragSnapToOrigin:c,onDragTransitionEnd:s}=this.getProps(),f=this.constraints||{},m=Nf(x=>{if(!EN(x,r,this.currentDirection))return;let _=f&&f[x]||{};(c===!0||c===x)&&(_={min:0,max:0});const T=i?200:1e6,E=i?40:1e7,C={type:"inertia",velocity:n?e[x]:0,bounceStiffness:T,bounceDamping:E,timeConstant:750,restDelta:1,restSpeed:10,...a,..._};return this.startAxisValueAnimation(x,C)});return Promise.all(m).then(s)}startAxisValueAnimation(e,r){const n=this.getAxisMotionValue(e);return eV(this.visualElement,e),n.start(v7(e,n,0,r,this.visualElement,!1))}stopAnimation(){Nf(e=>this.getAxisMotionValue(e).stop())}getAxisMotionValue(e){const r=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps(),i=n[r];return i||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){Nf(r=>{const{drag:n}=this.getProps();if(!EN(r,n,this.currentDirection))return;const{projection:i}=this.visualElement,a=this.getAxisMotionValue(r);if(i&&i.layout){const{min:c,max:s}=i.layout.layoutBox[r],f=a.get()||0;a.set(e[r]-ka(c,s,.5)+f)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:r}=this.getProps(),{projection:n}=this.visualElement;if(!Qb(r)||!n||!this.constraints)return;this.stopAnimation();const i={x:0,y:0};Nf(c=>{const s=this.getAxisMotionValue(c);if(s&&this.constraints!==!1){const f=s.get();i[c]=ltt({min:f,max:f},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(),Nf(c=>{if(!EN(c,e,null))return;const s=this.getAxisMotionValue(c),{min:f,max:m}=this.constraints[c];s.set(ka(f,m,i[c]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;dtt.set(this.visualElement,this);const e=this.visualElement.current,r=wA(e,"pointerdown",m=>{const{drag:x,dragListener:_=!0}=this.getProps(),T=m.target,E=T!==e&&VQe(T);x&&_&&!E&&this.start(m)});let n;const i=()=>{const{dragConstraints:m}=this.getProps();Qb(m)&&m.current&&(this.constraints=this.resolveRefConstraints(),n||(n=ftt(e,m.current,()=>this.scalePositionWithinConstraints())))},{projection:a}=this.visualElement,c=a.addEventListener("measure",i);a&&!a.layout&&(a.root&&a.root.updateScroll(),a.updateLayout()),ea.read(i);const s=Sk(window,"resize",()=>this.scalePositionWithinConstraints()),f=a.addEventListener("didUpdate",({delta:m,hasLayoutChanged:x})=>{this.isDragging&&x&&(Nf(_=>{const T=this.getAxisMotionValue(_);T&&(this.originPoint[_]+=m[_].translate,T.set(T.get()+m[_].translate))}),this.visualElement.render())});return()=>{s(),r(),c(),f&&f(),n&&n()}}getProps(){const e=this.visualElement.getProps(),{drag:r=!1,dragDirectionLock:n=!1,dragPropagation:i=!1,dragConstraints:a=!1,dragElastic:c=cV,dragMomentum:s=!0}=e;return{...e,drag:r,dragDirectionLock:n,dragPropagation:i,dragConstraints:a,dragElastic:c,dragMomentum:s}}}function une(t){let e=!0;return()=>{if(e){e=!1;return}t()}}function ftt(t,e,r){const n=yre(t,une(r)),i=yre(e,une(r));return()=>{n(),i()}}function EN(t,e,r){return(e===!0||e===t)&&(r===null||r===t)}function ptt(t,e=10){let r=null;return Math.abs(t.y)>e?r="y":Math.abs(t.x)>e&&(r="x"),r}class mtt extends dx{constructor(e){super(e),this.removeGroupControls=Hd,this.removeListeners=Hd,this.controls=new htt(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Hd}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 oz=t=>(e,r)=>{t&&ea.update(()=>t(e,r),!1,!0)};class gtt extends dx{constructor(){super(...arguments),this.removePointerDownListener=Hd}onPointerDown(e){this.session=new xbe(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:ybe(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:r,onPan:n,onPanEnd:i}=this.node.getProps();return{onSessionStart:oz(e),onStart:oz(r),onMove:oz(n),onEnd:(a,c)=>{delete this.session,i&&ea.postRender(()=>i(a,c))}}}mount(){this.removePointerDownListener=wA(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 lz=!1;class ytt extends P.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),lz&&a.root.didUpdate(),a.addEventListener("animationComplete",()=>{this.safeToRemove()}),a.setOptions({...a.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),$R.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}),lz=!0,i||e.layoutDependency!==r||r===void 0||e.isPresent!==a?c.willUpdate():this.safeToRemove(),e.isPresent!==a&&(a?c.promote():c.relegate()||ea.postRender(()=>{const s=c.getStack();(!s||!s.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:e,layoutAnchor:r}=this.props,{projection:n}=e;n&&(n.options.layoutAnchor=r,n.root.didUpdate(),T7.postRender(()=>{!n.currentAnimation&&n.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:r,switchLayoutGroup:n}=this.props,{projection:i}=e;lz=!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 vbe(t){const[e,r]=obe(),n=P.useContext(a7);return o.jsx(ytt,{...t,layoutGroup:n,switchLayoutGroup:P.useContext(mbe),isPresent:e,safeToRemove:r})}const xtt={pan:{Feature:gtt},drag:{Feature:mtt,ProjectionNode:abe,MeasureLayout:vbe}};function dne(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&&ea.postRender(()=>a(e,tj(e)))}class _tt extends dx{mount(){const{current:e}=this.node;e&&(this.unmount=BQe(e,(r,n)=>(dne(this.node,n,"Start"),i=>dne(this.node,i,"End"))))}unmount(){}}class vtt extends dx{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=QC(Sk(this.node.current,"focus",()=>this.onFocus()),Sk(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function hne(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&&ea.postRender(()=>a(e,tj(e)))}class btt extends dx{mount(){const{current:e}=this.node;if(!e)return;const{globalTapTarget:r,propagate:n}=this.node.props;this.unmount=GQe(e,(i,a)=>(hne(this.node,a,"Start"),(c,{success:s})=>hne(this.node,c,s?"End":"Cancel")),{useGlobalTarget:r,stopPropagation:(n==null?void 0:n.tap)===!1})}unmount(){}}const uV=new WeakMap,cz=new WeakMap,wtt=t=>{const e=uV.get(t.target);e&&e(t)},Stt=t=>{t.forEach(wtt)};function Ttt({root:t,...e}){const r=t||document;cz.has(r)||cz.set(r,{});const n=cz.get(r),i=JSON.stringify(e);return n[i]||(n[i]=new IntersectionObserver(Stt,{root:t,...e})),n[i]}function Ett(t,e,r){const n=Ttt(e);return uV.set(t,r),n.observe(t),()=>{uV.delete(t),n.unobserve(t)}}const Att={some:0,all:1};class ktt extends dx{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){var f;(f=this.stopObserver)==null||f.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:Att[i]},s=m=>{const{isIntersecting:x}=m;if(this.isInView===x||(this.isInView=x,a&&!x&&this.hasEnteredView))return;x&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",x);const{onViewportEnter:_,onViewportLeave:T}=this.node.getProps(),E=x?_:T;E&&E(m)};this.stopObserver=Ett(this.node.current,c,s)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:r}=this.node;["amount","margin","root"].some(Ctt(e,r))&&this.startObserver()}unmount(){var e;(e=this.stopObserver)==null||e.call(this),this.hasEnteredView=!1,this.isInView=!1}}function Ctt({viewport:t={}},{viewport:e={}}={}){return r=>t[r]!==e[r]}const jtt={inView:{Feature:ktt},tap:{Feature:btt},focus:{Feature:vtt},hover:{Feature:_tt}},Itt={layout:{ProjectionNode:abe,MeasureLayout:vbe}},Ptt={...ett,...jtt,...xtt,...Itt},pr=Yet(Ptt,Zet);function Ntt(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 fne(t){return t.visitor_intent==="buying"&&!t.has_agent}function Rtt({token:t}={}){var E;const e=hp(),r=t||e.token,{data:n,isLoading:i,isError:a}=PZe(r);Nr();const c=(E=n==null?void 0:n.open_houses)==null?void 0:E.id,{data:s}=wr({queryKey:["cohost-visitors",r,c],queryFn:async()=>{const{data:C,error:N}=await Le.rpc("get_cohost_visitors",{_token:r});if(N)throw N;return C||[]},enabled:!!r&&!!c,refetchInterval:15e3});if(i)return o.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:o.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(a||!n)return o.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:o.jsxs("div",{className:"text-center text-white",children:[o.jsx("h1",{className:"text-xl font-bold mb-2",children:"Link Expired or Invalid"}),o.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 f=n.open_houses,m=(s==null?void 0:s.length)||0,x=(s==null?void 0:s.filter(C=>C.visitor_intent==="buying").length)||0,_=(s==null?void 0:s.filter(fne).length)||0,T=C=>{if(!C)return"";const[N,R]=C.split(":"),D=parseInt(N);return`${D>12?D-12:D||12}:${R} ${D>=12?"PM":"AM"}`};return o.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[o.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:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),o.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),o.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:f.property_address})]}),o.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(Al,{className:"h-4 w-4"}),o.jsx("span",{className:"font-bold text-white",children:m})]}),o.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[o.jsx(Vhe,{className:"h-4 w-4"}),o.jsx("span",{className:"font-bold text-white",children:_})]}),o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx(Ma,{className:"h-4 w-4"}),o.jsx("span",{className:"font-bold text-white",children:x})]})]})]}),o.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:[o.jsx("span",{children:Ri(new Date(f.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),f.start_time&&o.jsxs("span",{children:[T(f.start_time),f.end_time?` – ${T(f.end_time)}`:""]})]}),o.jsx(pp,{className:"flex-1 p-4 sm:p-6",children:s!=null&&s.length?o.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:o.jsx(lbe,{children:s.map((C,N)=>{var M;const R=Ntt(C.visitor_intent),D=fne(C);return o.jsxs(pr.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:N*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${D?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[o.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center text-lg font-bold shrink-0 ${D?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(M=C.first_name[0])==null?void 0:M.toUpperCase()}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsxs("span",{className:"font-semibold text-white truncate",children:[C.first_name," ",C.last_name||""]}),D&&o.jsx(us,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),C.has_agent&&o.jsx(us,{variant:"outline",className:"text-[10px] px-1.5 py-0 border-yellow-500/40 text-yellow-400",children:"⚠️ Has Agent"})]}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[o.jsxs(us,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${R.color}`,children:[R.emoji," ",R.label]}),o.jsx("span",{className:"text-white/30 text-xs",children:Ri(new Date(C.created_at),"h:mm a")})]})]})]},C.id)})})}):o.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-20",children:[o.jsx("div",{className:"w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mb-4",children:o.jsx(pLe,{className:"h-10 w-10 text-white/20"})}),o.jsx("h2",{className:"text-xl font-bold text-white/60 mb-1",children:"Waiting for visitors..."}),o.jsx("p",{className:"text-white/30 text-sm",children:"New sign-ins will appear here in real-time"})]})})]})}function Ltt(){const e=Wi().pathname.slice(1);if(P.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),e.startsWith("live/")){const r=e.slice(5);if(r)return o.jsx(Rtt,{token:r})}if(e.startsWith("rsvp/")){const r=e.slice(5);if(r)return o.jsx(R0e,{slug:r})}return!e||e===""?o.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:o.jsxs("div",{className:"text-center text-white",children:[o.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Guest Book"}),o.jsx("p",{className:"text-white/60",children:"The modern open house sign-in experience."}),o.jsx("p",{className:"text-white/40 text-sm mt-2",children:"Visit a specific open house link to sign in."})]})}):o.jsx(N0e,{slug:e})}function Dtt({dealData:t,agentProfile:e,welcomeMessage:r,isWon:n,branding:i}){var m;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,s=(i==null?void 0:i.cover_photo_url)||null,f=(i==null?void 0:i.tagline)||"Your Real Estate Concierge";return o.jsxs("div",{className:"relative overflow-hidden",children:[o.jsxs("div",{className:"relative px-4 pt-10 pb-20",children:[s&&o.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${s})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter-mobile)"}}),o.jsx("div",{className:"absolute inset-0",style:{background:s?"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%))"}}),o.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"}}),o.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[c&&o.jsx(pr.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},transition:{duration:.5},className:"mb-6 flex justify-center",children:o.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:o.jsx("img",{src:c,alt:"Brand",className:"h-9 max-w-[160px] object-contain"})})}),e&&o.jsxs(pr.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.5,delay:.05},className:"mb-6",children:[e.avatar_url?o.jsx("div",{className:"w-20 h-20 mx-auto mb-3 relative",children:o.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:o.jsx("img",{src:e.avatar_url,alt:e.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):o.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:((m=e.name)==null?void 0:m.charAt(0))||"?"}),o.jsx("p",{className:"portal-serif text-lg",style:{color:"var(--portal-hero-ink)"},children:e.name}),o.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"var(--portal-hero-ink-dim)"},children:f})]}),o.jsxs(pr.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6,delay:.1},children:[o.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:[o.jsx(Ma,{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&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"opacity-50",children:"·"}),"Complete"]})]}),o.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"}),o.jsx("div",{className:"portal-hairline w-24 mx-auto mb-4"}),a&&o.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-sm",style:{color:"var(--portal-hero-ink-muted)"},children:[o.jsx(na,{className:"w-3.5 h-3.5",style:{color:"var(--portal-hero-accent)"}}),o.jsx("span",{children:a})]}),r&&o.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&&o.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-10 relative z-10",children:o.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:o.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.phone&&o.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:[o.jsx(zi,{className:"w-4 h-4"}),o.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),e.email&&o.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:[o.jsx(Bi,{className:"w-4 h-4"}),o.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),e.phone&&o.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:[o.jsx(f1,{className:"w-4 h-4"}),o.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function bbe({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=I9e(i,new Date);if(S1(i)&&!Gd(i))return null;const s=Gd(i),f=s?"0":String(Math.max(0,c)),m=Math.max(4,Math.min(100,(60-Math.min(60,c))/60*100));return o.jsxs("div",{className:"portal-tile p-8 text-center",children:[o.jsx("p",{className:"portal-eyebrow mb-4",children:s?"The Moment Has Arrived":"Countdown to Closing"}),s?o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"portal-serif text-5xl mb-2",style:{color:"hsl(var(--portal-gold))"},children:"Closing Day"}),o.jsxs("p",{className:"text-sm mt-3",style:{color:"hsl(var(--portal-ink-muted))"},children:["Congratulations",r?`, ${r.split(" ")[0]}`:"","."]})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex items-baseline justify-center gap-3",children:[o.jsx(pr.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:f}),o.jsx("span",{className:"portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink-muted))"},children:c===1?"day":"days"})]}),o.jsx("div",{className:"portal-hairline w-16 mx-auto my-4"}),o.jsx("p",{className:"text-xs tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-muted))"},children:"Until you hold the keys"}),o.jsx("div",{className:"mt-6 mx-auto max-w-[260px]",children:o.jsx("div",{className:"h-[2px] rounded-full overflow-hidden",style:{background:"hsl(var(--portal-gold) / 0.15)"},children:o.jsx(pr.div,{initial:{width:0},animate:{width:`${m}%`},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 wbe({journeyStages:t,currentIndex:e}){return t.length===0?null:o.jsxs("div",{children:[o.jsx("p",{className:"portal-eyebrow mb-2",children:"The Journey"}),o.jsx("h2",{className:"portal-serif text-2xl mb-6",style:{color:"hsl(var(--portal-ink))"},children:"Your path to the keys"}),o.jsx("div",{className:"relative",children:t.map((r,n)=>{const i=ne;return o.jsxs(pr.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,s;if(a.includes("youtube.com/watch")){const f=new URL(a).searchParams.get("v");return f?`https://www.youtube.com/embed/${f}`:null}if(a.includes("youtu.be/")){const f=(c=a.split("youtu.be/")[1])==null?void 0:c.split("?")[0];return f?`https://www.youtube.com/embed/${f}`:null}if(a.includes("loom.com/share/")){const f=(s=a.split("loom.com/share/")[1])==null?void 0:s.split("?")[0];return f?`https://www.loom.com/embed/${f}`:null}return a};return o.jsxs("div",{children:[o.jsx("p",{className:"portal-eyebrow mb-2",children:"Right Now"}),o.jsx("h4",{className:"portal-serif text-3xl mb-2 portal-gold-underline",style:{color:"hsl(var(--portal-ink))"},children:t.label}),o.jsx("p",{className:"text-sm leading-relaxed mt-4",style:{color:"hsl(var(--portal-ink-muted))"},children:t.description}),e&&o.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:[o.jsx("p",{className:"portal-eyebrow mb-2",children:"Note From Your Agent"}),o.jsxs("p",{className:"text-sm leading-relaxed portal-serif italic",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:["“",e,"”"]})]}),r&&o.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:[o.jsx("p",{className:"portal-eyebrow mb-2",children:"What’s Next"}),o.jsx("p",{className:"text-sm leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:r})]}),n&&o.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:o.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 j1(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 aVt(t){const e=t.trim();if(!e)return;const r=e.split(/[-/]/).filter(Boolean);if(r.length<3)return;const n=r.map(f=>Number(f));if(n.some(f=>Number.isNaN(f)))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 s=new Date(c,i,a);if(!(s.getFullYear()!==c||s.getMonth()!==i||s.getDate()!==a))return s}const Ott=[{key:"contract_date",label:"Contract Accepted",icon:SU},{key:"earnest_money_due_date",label:"Earnest Money",icon:ym},{key:"inspection_date",label:"Inspection",icon:$y},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:ep},{key:"appraisal_date",label:"Appraisal",icon:Ma},{key:"loan_approval_date",label:"Loan Approval",icon:Hhe},{key:"title_docs_due_date",label:"Title & Disclosures",icon:ep},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:XRe},{key:"target_close_date",label:"Target Close",icon:po}];function Mtt(t,e){const r=Ri(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 Ftt(t,e){const r=Ri(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 Tbe({deal:t,portal:e,targetCloseDate:r,contractDate:n,inspectionDate:i,appraisalDate:a,actualCloseDate:c}){const s={...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},f=(t==null?void 0:t.actual_close_date)??c??null,m=Array.isArray(t==null?void 0:t.completed_key_dates)?t.completed_key_dates:[],x=Ott.map(E=>E.key==="target_close_date"&&f?{...E,label:"Closed",date:f,done:!0}:{...E,date:s[E.key],done:m.includes(E.key)}).filter(E=>!!E.date);if(x.length===0)return null;const _=(E,C,N)=>{const R=j1(C);if(N==="google")window.open(Mtt(E,R),"_blank");else{const D=Ftt(E,R),M=document.createElement("a");M.href=D,M.download=`${E.replace(/\s+/g,"-").toLowerCase()}.ics`,M.click()}},T=x.filter(E=>E.done).length;return o.jsxs("div",{children:[o.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),o.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-5 flex-wrap",children:[o.jsx("h2",{className:"portal-serif text-2xl",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),o.jsxs("span",{className:"text-[11px] tracking-[0.18em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[T," of ",x.length," complete"]})]}),o.jsxs("div",{className:"space-y-4 relative",children:[o.jsx("div",{className:"absolute left-[10px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.18)"}}),x.map(({label:E,date:C,done:N,icon:R})=>{const D=j1(C),M=S1(D)&&!Gd(D),B=Gd(D),V=!M&&!B,G=N?"Completed":B?"Today":M?"In progress":"Upcoming";return o.jsxs("div",{className:"flex items-start gap-3 relative",children:[o.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:N?"hsl(var(--portal-gold))":B?"hsl(var(--portal-gold) / 0.25)":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.7)",boxShadow:B?"0 0 12px hsl(var(--portal-gold) / 0.5)":"none"},children:N?o.jsx(Ao,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):o.jsx(R,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:E}),o.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:N?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:Ri(D,"MMM d, yyyy")}),o.jsx("span",{className:"inline-block mt-1 text-[9px] tracking-[0.2em] uppercase px-2 py-0.5 rounded-full",style:{color:N||B?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${N||B?.5:.18})`},children:G})]}),V&&o.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[o.jsx("button",{onClick:()=>_(E,C,"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:o.jsx(zhe,{className:"w-3.5 h-3.5"})}),o.jsx("button",{onClick:()=>_(E,C,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},E)})]})]})}function Ebe({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 Le.storage.from("deal-files").createSignedUrl(n.storage_path,300);i!=null&&i.signedUrl&&window.open(i.signedUrl,"_blank")};return o.jsxs("div",{children:[o.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),o.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),o.jsx("div",{className:"space-y-2",children:t.map(n=>o.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:[o.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:o.jsx(ep,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:n.file_name}),o.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:e(n.file_size)})]}),o.jsx(Xl,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},n.id))})]})}function Abe({slug:t,wrapper:e}){const r=ma(),[n,i]=P.useState(null),{data:a=[]}=wr({queryKey:["portal-signature-requests",t],enabled:!!t,queryFn:async()=>{const{data:x,error:_}=await Le.functions.invoke("forms-portal-public",{body:{action:"list",slug:t}});return _?[]:(x==null?void 0:x.envelopes)||[]}}),c=a.filter(x=>x.my_turn),s=a.filter(x=>!x.my_turn&&x.status!=="completed");if(!c.length&&!s.length)return null;const f=async x=>{i(x);try{const{data:_,error:T}=await Le.functions.invoke("forms-portal-public",{body:{action:"sign_link",slug:t,envelope_id:x}});if(T||_!=null&&_.error)throw new Error((_==null?void 0:_.error)||"Could not open the document");r(_.path)}catch(_){Jt.error((_==null?void 0:_.message)||"Could not open the document")}finally{i(null)}},m=o.jsxs("div",{children:[o.jsx("p",{className:"portal-eyebrow mb-2",children:"Needs you"}),o.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents to sign"}),o.jsxs("div",{className:"space-y-2",children:[c.map(x=>o.jsxs("button",{onClick:()=>f(x.id),disabled:n===x.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:[o.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===x.id?o.jsx(Cu,{className:"w-4 h-4 animate-spin",style:{color:"hsl(var(--portal-gold))"}}):o.jsx(aLe,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:x.title}),o.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-gold))"},children:"Tap to review & sign"})]})]},x.id)),s.map(x=>o.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:[o.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:x.my_status==="signed"?o.jsx(xc,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}}):o.jsx(mc,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1rem"},children:x.title}),o.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:x.my_status==="signed"?"You signed — waiting on others":"Waiting on another signer"})]})]},x.id))]})]});return e?e(m):m}function kbe({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 o.jsxs("div",{children:[o.jsx("p",{className:"portal-eyebrow mb-2",children:"Dispatch"}),o.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Updates from your agent"}),o.jsx("div",{className:"space-y-6",children:t.map((r,n)=>o.jsx("div",{className:n>0?"pt-6":"",style:n>0?{borderTop:"1px solid hsl(var(--portal-gold) / 0.1)"}:void 0,children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.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?o.jsx(FRe,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):o.jsx(EC,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[o.jsx("h3",{className:"portal-serif",style:{fontSize:n===0?"1.4rem":"1.15rem",color:"hsl(var(--portal-ink))"},children:r.title}),o.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase flex-shrink-0",style:{color:"hsl(var(--portal-ink-dim))"},children:Ri(new Date(r.created_at),"MMM d")})]}),r.content&&o.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&&o.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:o.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 Btt=[{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 pne(t){var r,n;const e=(r=t.custom_category)==null?void 0:r.trim();return e||((n=Btt.find(i=>i.value===t.category))==null?void 0:n.label)||t.category}function mne(t){var r;const e=(r=t.custom_category)==null?void 0:r.trim();return e?`custom:${e.toLowerCase()}`:t.category}const oVt=[{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 lVt(t){return wr({queryKey:["vendors","brokerage",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Le.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 cVt(){const t=Ji(),{brokerageId:e}=qn();return wr({queryKey:["vendors","library",t,e],queryFn:async()=>{if(!t)return{vendors:[],selections:[]};let r=Le.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}),Le.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 uVt(){const t=Nr();return Cr({mutationFn:async e=>{if(e.id){const{id:r,created_at:n,...i}=e,{data:a,error:c}=await Le.from("vendors").update(i).eq("id",r).select().single();if(c)throw c;return a}else{const{data:r,error:n}=await Le.from("vendors").insert(e).select().single();if(n)throw n;return r}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function dVt(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("vendors").delete().eq("id",e);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function hVt(){const t=Ji(),e=Nr();return Cr({mutationFn:async({vendorId:r,isVisible:n})=>{if(!t)throw new Error("No user");const{data:i}=await Le.from("agent_vendor_selections").select("id").eq("agent_user_id",t).eq("vendor_id",r).maybeSingle();if(i){const{error:a}=await Le.from("agent_vendor_selections").update({is_visible:n}).eq("id",i.id);if(a)throw a}else{const{error:a}=await Le.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 Cbe(t){return wr({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 Le.from("profiles").select("brokerage_id").eq("id",e).maybeSingle(),n=r==null?void 0:r.brokerage_id,i=Le.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:s},{data:f},{data:m}]=await Promise.all([a.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),Le.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",e),Le.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",t.id)]);if(s)throw s;const x=new Map;(f||[]).forEach(E=>x.set(E.vendor_id,{display_order:E.display_order,is_visible:E.is_visible}));const _=new Map;return(m||[]).forEach(E=>_.set(E.vendor_id,E.is_visible)),(c||[]).filter(E=>{if(_.get(E.id)===!1)return!1;const C=x.get(E.id);return!(C&&C.is_visible===!1&&!E.is_required)}).map(E=>{var C;return{...E,display_order:((C=x.get(E.id))==null?void 0:C.display_order)??E.sort_order??0}}).sort((E,C)=>(E.display_order||0)-(C.display_order||0))},enabled:!!(t!=null&&t.id)&&!!(t!=null&&t.owner_user_id)})}async function gne(t){try{await Le.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 fVt(t,e){return wr({queryKey:["vendor-clicks",t,e],queryFn:async()=>{if(!e)return{};const{data:r}=await Le.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 Le.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 jbe({portalId:t,ownerUserId:e,currentStage:r,brandingColor:n,layout:i="list"}){const{data:a=[],isLoading:c}=Cbe({id:t,owner_user_id:e});if(c||a.length===0)return null;const s=a.filter(D=>!D.stage_filter||D.stage_filter.length===0||!r?!0:D.stage_filter.includes(r));if(s.length===0)return null;const f=n||"#406E71",m=(D,M)=>{switch(M){case"book":return D.booking_url;case"website":return D.website;case"call":return D.phone?`tel:${D.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return D.email?`mailto:${D.email}`:null}},x=D=>{const M=m(D,D.action_type);gne({vendorId:D.id,portalId:t,agentUserId:e,actionTaken:D.action_type}),M&&window.open(M,D.action_type==="call"||D.action_type==="email"||D.action_type==="quote"?"_self":"_blank")},_=D=>{const M=m(D,D.action_type);return[{action:"website",label:"Website",icon:o.jsx(h1,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:o.jsx(Bi,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:o.jsx(zi,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:o.jsx(po,{className:"w-3.5 h-3.5"})}].filter(V=>V.action!==D.action_type).map(V=>{const G=m(D,V.action);return!G||G===M?null:o.jsxs("button",{onClick:()=>{gne({vendorId:D.id,portalId:t,agentUserId:e,actionTaken:V.action}),window.open(G,V.action==="call"||V.action==="email"?"_self":"_blank")},className:"inline-flex items-center gap-1 text-slate-500 hover:text-slate-700 hover:underline",title:V.label,children:[V.icon,o.jsx("span",{className:"text-xs",children:V.label})]},V.action)}).filter(Boolean)},T=D=>{switch(D.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"}},E=D=>{switch(D.action_type){case"book":return o.jsx(po,{className:"w-3.5 h-3.5"});case"call":return o.jsx(zi,{className:"w-3.5 h-3.5"});case"email":case"quote":return o.jsx(Bi,{className:"w-3.5 h-3.5"});case"website":return o.jsx(h1,{className:"w-3.5 h-3.5"})}},C=o.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[o.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{backgroundColor:`${f}15`,color:f},children:o.jsx(Ss,{className:"w-4 h-4"})}),o.jsxs("div",{children:[o.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),o.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),N=s.some(D=>D.disclosure_text)&&o.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:s.filter(D=>D.disclosure_text).map(D=>o.jsxs("p",{className:"text-[10px] text-slate-400",children:[o.jsxs("span",{className:"font-medium",children:[D.company||D.name,":"]})," ",D.disclosure_text]},D.id))});if(i==="grid")return o.jsxs(Hn,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[C,o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:s.map(D=>o.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:[o.jsxs("div",{className:"flex items-start gap-3",children:[o.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:D.logo_url?o.jsx("img",{src:D.logo_url,alt:D.name,className:"w-full h-full object-cover"}):o.jsx("span",{className:"text-base font-semibold text-slate-500",children:(D.company||D.name).charAt(0)})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("p",{className:"font-semibold text-sm text-slate-800 truncate",children:D.company||D.name}),D.company&&D.name&&o.jsx("p",{className:"text-xs text-slate-500 truncate",children:D.name}),o.jsx("span",{className:"inline-block mt-1 text-[10px] font-medium px-1.5 py-0.5 rounded",style:{backgroundColor:`${f}12`,color:f},children:pne(D)})]})]}),D.description&&o.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:D.description}),o.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[o.jsxs(Ut,{size:"sm",onClick:()=>x(D),style:{backgroundColor:f},className:"text-white hover:opacity-90 w-full",children:[E(D),o.jsx("span",{className:"ml-1.5 text-xs",children:T(D)})]}),_(D).length>0&&o.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:_(D)})]})]},D.id))}),N]});const R=s.reduce((D,M)=>((D[mne(M)]=D[mne(M)]||[]).push(M),D),{});return o.jsxs(Hn,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[C,o.jsx("div",{className:"space-y-4",children:Object.entries(R).map(([D,M])=>o.jsxs("div",{children:[o.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:pne(M[0])}),o.jsx("div",{className:"space-y-2",children:M.map(B=>o.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[o.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:B.logo_url?o.jsx("img",{src:B.logo_url,alt:B.name,className:"w-full h-full object-cover"}):o.jsx("span",{className:"text-sm font-semibold text-slate-500",children:B.name.charAt(0)})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:B.company||B.name}),B.company&&B.name&&o.jsx("p",{className:"text-xs text-slate-500 truncate",children:B.name}),B.description&&o.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:B.description})]}),o.jsxs(Ut,{size:"sm",onClick:()=>x(B),style:{backgroundColor:f},className:"text-white hover:opacity-90 shrink-0",children:[E(B),o.jsx("span",{className:"ml-1.5 text-xs",children:T(B)})]})]},B.id))})]},D))}),N]})}function ztt(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 $tt(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 Ibe({portalId:t,portalSlug:e,ownerUserId:r,rewardText:n,ctaHeadline:i,agentName:a,clientName:c,reviewUrl:s,hubVideoUrl:f}){const[m,x]=P.useState(!1),_=P.useRef(!1),T=ztt(e);P.useEffect(()=>{_.current||(_.current=!0,Le.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 E=async W=>{await Le.from("portal_referral_clicks").insert({portal_id:t,owner_user_id:r,click_type:W,user_agent:navigator.userAgent.slice(0,500)})},C=()=>`${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: ${T}`,N=async()=>{await navigator.clipboard.writeText(T),x(!0),E("copy_link"),setTimeout(()=>x(!1),2e3)},R=()=>{E("share_sms");const W=encodeURIComponent(C());window.location.href=`sms:?&body=${W}`},D=()=>{E("share_email");const W=encodeURIComponent("A referral you'll thank me for"),X=encodeURIComponent(C());window.location.href=`mailto:?subject=${W}&body=${X}`},M=()=>{E("open_form"),window.open(T,"_blank")},B=i||"Know someone buying or selling?",V=f?$tt(f):null,G=V==null?void 0:V.match(/\.(mp4|webm|mov)(\?|$)/i);return o.jsxs("div",{className:"space-y-4",children:[o.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:[o.jsx("div",{className:"text-5xl mb-2",children:"🎉"}),o.jsxs("h3",{className:"text-xl font-bold text-emerald-900 mb-1 font-serif",children:["Welcome Home",c?`, ${c.split(" ")[0]}`:"","!"]}),o.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."})]}),V&&o.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[o.jsx("div",{className:"px-4 pt-4 pb-2",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ss,{className:"w-4 h-4 text-[#406E71]"}),o.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",a||"your agent"]})]})}),o.jsx("div",{className:"aspect-video bg-slate-900",children:G?o.jsx("video",{src:V,controls:!0,className:"w-full h-full",playsInline:!0}):o.jsx("iframe",{src:V,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),o.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white shadow-xl",children:[o.jsx("div",{className:"absolute inset-0 opacity-[0.07]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"20px 20px"}}),o.jsxs("div",{className:"relative p-6",children:[o.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:[o.jsx(Yh,{className:"w-3 h-3"}),"Referral Program"]}),o.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:B}),n&&o.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[o.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",n]}),o.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."]}),o.jsxs("button",{onClick:M,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",o.jsx(pc,{className:"w-4 h-4"})]}),o.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[o.jsxs("button",{onClick:R,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:[o.jsx(f1,{className:"w-3.5 h-3.5"}),"Text"]}),o.jsxs("button",{onClick:D,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:[o.jsx(Bi,{className:"w-3.5 h-3.5"}),"Email"]}),o.jsxs("button",{onClick:N,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:[m?o.jsx(Ao,{className:"w-3.5 h-3.5"}):o.jsx(TU,{className:"w-3.5 h-3.5"}),m?"Copied":"Copy"]})]})]})]}),s&&o.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",onClick:()=>E("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:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"text-2xl",children:"⭐"}),o.jsxs("div",{className:"flex-1",children:[o.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),o.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),o.jsx(pc,{className:"w-4 h-4 text-slate-400"})]})})]})}function Utt(t){return wr({queryKey:["portal-messages",t],queryFn:async()=>{const{data:e,error:r}=await Le.from("portal_messages").select("*").eq("portal_id",t).order("created_at",{ascending:!0});if(r)throw r;return e||[]},enabled:!!t,refetchInterval:3e4})}function Vtt(){const t=Nr();return Cr({mutationFn:async({portalId:e,senderType:r,senderName:n,body:i,deviceFingerprint:a,portalUrl:c})=>{const{data:s,error:f}=await Le.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(f)throw f;try{await Le.functions.invoke("portal-message-notify",{body:{message_id:s.id,portal_url:c}})}catch(m){console.error("portal-message-notify failed",m)}return s},onSuccess:(e,r)=>{t.invalidateQueries({queryKey:["portal-messages",r.portalId]}),t.invalidateQueries({queryKey:["portal-unread-messages"]}),t.invalidateQueries({queryKey:["portal-conversations"]})}})}function pVt(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.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 mVt(){const t=Ji();return wr({queryKey:["portal-conversations",t],queryFn:async()=>{const{data:e,error:r}=await Le.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(f=>f.id),i=[],a=100,c=1e3;for(let f=0;f{const m=s.get(f.id)||[];return{portalId:f.id,slug:f.slug,clientName:f.client_name,clientEmail:f.client_email,lastMessage:m.length?m[m.length-1]:null,unreadCount:m.filter(x=>x.sender_type==="client"&&!x.read_at).length,messageCount:m.length}}).sort((f,m)=>{var T,E;const x=((T=f.lastMessage)==null?void 0:T.created_at)||"",_=((E=m.lastMessage)==null?void 0:E.created_at)||"";return x===_?(f.clientName||"").localeCompare(m.clientName||""):_.localeCompare(x)})},enabled:!!t,refetchInterval:3e4})}function Pbe({portalId:t,clientName:e,agentName:r,agentAvatar:n,deviceFingerprint:i}){const{data:a,isLoading:c}=Utt(t),s=Vtt(),[f,m]=P.useState(""),x=`portal_msg_name_${t}`,[_,T]=P.useState(()=>localStorage.getItem(x)||e||""),E=P.useRef(null);P.useEffect(()=>{var R;(R=E.current)==null||R.scrollIntoView({block:"nearest"})},[a==null?void 0:a.length]);const C=async()=>{const R=f.trim();if(!R)return;const D=(_||e||"").trim();if(!D){Jt.error("Please add your name first");return}try{localStorage.setItem(x,D),await s.mutateAsync({portalId:t,senderType:"client",senderName:D,body:R,deviceFingerprint:i,portalUrl:window.location.href}),m(""),Jt.success("Message sent")}catch(M){Jt.error((M==null?void 0:M.message)||"Could not send your message")}},N="hsl(var(--portal-gold))";return o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[o.jsx(rp,{className:"w-4 h-4",style:{color:N}}),o.jsx("h2",{className:"portal-serif",style:{fontSize:"1.35rem",color:"hsl(var(--portal-ink))"},children:"Messages"})]}),o.jsx("div",{className:"portal-hairline mb-4"}),o.jsxs("div",{className:"space-y-3 max-h-[340px] overflow-y-auto pr-1",children:[c&&o.jsx("div",{className:"flex justify-center py-6",children:o.jsx(Cu,{className:"w-4 h-4 animate-spin",style:{color:N}})}),!c&&(!a||a.length===0)&&o.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(R=>{const D=R.sender_type==="agent";return o.jsx("div",{className:`flex ${D?"justify-start":"justify-end"}`,children:o.jsxs("div",{className:"max-w-[85%] rounded-2xl px-4 py-3",style:{background:D?"hsl(var(--portal-surface-2))":"hsl(var(--portal-gold) / 0.12)",border:`1px solid ${D?"hsl(var(--portal-gold) / 0.12)":"hsl(var(--portal-gold) / 0.28)"}`},children:[o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[D&&n&&o.jsx("img",{src:n,alt:r||"Agent",className:"w-5 h-5 rounded-full object-cover"}),o.jsxs("span",{className:"text-[11px] uppercase tracking-[0.14em]",style:{color:"hsl(var(--portal-ink-dim))"},children:[D?r||"Your agent":R.sender_name||"You"," ·"," ",Ri(new Date(R.created_at),"MMM d, h:mm a")]})]}),o.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:R.body})]})},R.id)}),o.jsx("div",{ref:E})]}),o.jsxs("div",{className:"mt-4 space-y-2",children:[!e&&o.jsx("input",{value:_,onChange:R=>T(R.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))"}}),o.jsx("textarea",{value:f,onChange:R=>m(R.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))"}}),o.jsxs("button",{onClick:C,disabled:s.isPending||!f.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:N},children:[s.isPending?o.jsx(Cu,{className:"w-4 h-4 animate-spin"}):o.jsx(jL,{className:"w-4 h-4"}),"Send message"]})]})]})}function qtt(t){return t==="buy-side"?"Home Search in Progress":t==="listing"?"Your Home Is On The Market":"Active Phase"}function Gtt(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 Htt={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. 🎉"}},Nbe=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function Rbe(t){return Nbe.map(e=>{if(e==="Active")return{key:"Active",label:qtt(t),description:Gtt(t)};const r=Htt[e];return{key:e,label:r.label,description:r.description}})}function yD(t){if(!t)return 0;const e=Nbe.indexOf(t);return e>=0?e:0}function Wtt({portal:t,linkedPortal:e,activePortal:r,activeTab:n,onTabChange:i,agentProfile:a,branding:c,updates:s,documents:f}){var Oe,Ae,we;const m=(c==null?void 0:c.cover_photo_url)||null,x=(c==null?void 0:c.logo_url)||null,_=(c==null?void 0:c.tagline)||"Your Real Estate Concierge",T=r==null?void 0:r.deal_pipeline,E=T==null?void 0:T.deal_pipeline_stages,C=E==null?void 0:E.is_won_stage,N=T==null?void 0:T.deal_type,R=r==null?void 0:r.stage_mapping;let D=Rbe(N);R&&R.length>0&&(D=R.map((ge,Ne)=>{var Ie,Te;return{key:`custom-${Ne}`,label:ge.label||((Ie=D[Ne])==null?void 0:Ie.label)||`Stage ${Ne+1}`,description:ge.description||((Te=D[Ne])==null?void 0:Te.description)||"",video_url:ge.video_url||void 0}}));const M=R&&R.length>0?Math.min(yD(E==null?void 0:E.name),D.length-1):yD(E==null?void 0:E.name),B=D[M],V=B==null?void 0:B.video_url,G=C&&r.show_post_close_tips!==!1&&r.referral_enabled!==!1,W=T!=null&&T.property_address?`${T.property_address}, ${T.city||""}, ${T.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,X=!!e,Q=(Oe=t==null?void 0:t.deal_pipeline)==null?void 0:Oe.deal_type,re=(Ae=e==null?void 0:e.deal_pipeline)==null?void 0:Ae.deal_type,se=ge=>ge==="listing"?"Your Sale":ge==="buy-side"?"Your Purchase":"Transaction",ue=D.length>1?Math.round((M+1)/D.length*100):0,{data:_e=[]}=Cbe({id:r==null?void 0:r.id,owner_user_id:r==null?void 0:r.owner_user_id}),Se=_e.some(ge=>!ge.stage_filter||ge.stage_filter.length===0||!(E!=null&&E.name)?!0:ge.stage_filter.includes(E.name)),ve=()=>{var ge;(ge=document.getElementById("trusted-vendors"))==null||ge.scrollIntoView({behavior:"smooth",block:"start"})};return o.jsxs("div",{className:"min-h-screen relative",style:{background:"var(--portal-gradient-noir)"},children:[o.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%)"}}),o.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-8",children:[o.jsxs(pr.div,{initial:{opacity:0,y:-6},animate:{opacity:1,y:0},transition:{duration:.4},className:"flex items-center justify-between mb-8",children:[o.jsxs("div",{className:"flex items-center gap-4",children:[x?o.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:o.jsx("img",{src:x,alt:"Brand",className:"h-8 max-w-[140px] object-contain"})}):o.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:"✦"}),o.jsxs("div",{children:[o.jsx("p",{className:"portal-eyebrow",children:"Private Client Portal"}),o.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"})]})]}),o.jsxs("div",{className:"flex items-center gap-2 text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[o.jsx(QA,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),o.jsxs(pr.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:[m?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${m})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter)"}}),o.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-scrim)"}})]}):o.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-fallback)"}}),o.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)"}}),o.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-12",children:[o.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[o.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:[o.jsx(Ma,{className:"w-3 h-3"}),N==="listing"?"Sale":N==="buy-side"?"Purchase":"Transaction",C&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),o.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:(T==null?void 0:T.deal_name)||"Your Transaction"}),o.jsx("div",{className:"portal-hairline w-32 mb-5"}),W&&o.jsxs("div",{className:"flex items-center gap-2",style:{color:"var(--portal-hero-ink-muted)",textShadow:"var(--portal-hero-text-shadow)"},children:[o.jsx(na,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),o.jsx("span",{className:"text-base",children:W})]}),(r==null?void 0:r.welcome_message)&&o.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,"”"]})]}),o.jsxs("div",{className:"flex flex-col items-center justify-center",children:[o.jsx(Ktt,{pct:ue}),o.jsx("p",{className:"portal-eyebrow mt-4",style:{color:"var(--portal-hero-accent)"},children:"Journey Progress"}),o.jsxs("p",{className:"portal-serif mt-1",style:{fontSize:"1.1rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:["Stage ",M+1," of ",D.length]})]})]}),o.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)"}})]}),X&&o.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 Ne=ge==="primary"?Q:re,Ie=n===ge;return o.jsx("button",{onClick:()=>i(ge),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:Ie?"hsl(var(--portal-surface-3))":"transparent",color:Ie?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:Ie?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:se(Ne)},ge)})}),o.jsxs(pr.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.06}}},className:"grid grid-cols-12 gap-5",children:[o.jsx("aside",{className:"col-span-3 space-y-5",children:o.jsxs("div",{className:"sticky top-6 space-y-5",children:[o.jsxs(kf,{children:[o.jsxs("div",{className:"text-center pt-2 pb-1",children:[a!=null&&a.avatar_url?o.jsx("div",{className:"w-24 h-24 mx-auto relative",children:o.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:o.jsx("img",{src:a.avatar_url,alt:a.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):o.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:((we=a==null?void 0:a.name)==null?void 0:we.charAt(0))||"?"}),o.jsx("h3",{className:"mt-4 portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink))"},children:a==null?void 0:a.name}),o.jsx("div",{className:"portal-hairline w-12 mx-auto my-2"}),o.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:_})]}),o.jsxs("div",{className:"mt-5 space-y-2",children:[(a==null?void 0:a.phone)&&o.jsx(uz,{href:`tel:${a.phone}`,icon:zi,label:"Call",sub:a.phone}),(a==null?void 0:a.phone)&&o.jsx(uz,{href:`sms:${a.phone}`,icon:f1,label:"Text message"}),(a==null?void 0:a.email)&&o.jsx(uz,{href:`mailto:${a.email}`,icon:Bi,label:"Email",sub:a.email})]})]}),o.jsxs(kf,{children:[o.jsx("p",{className:"portal-eyebrow mb-4",children:"At a Glance"}),o.jsxs("div",{className:"space-y-4",children:[(T==null?void 0:T.target_close_date)&&o.jsx(dz,{icon:po,label:"Target close",value:yne(T.target_close_date)}),(T==null?void 0:T.contract_date)&&o.jsx(dz,{icon:mc,label:"Under contract",value:yne(T.contract_date)}),o.jsx(dz,{icon:od,label:"Progress",value:`${ue}%`})]})]})]})}),o.jsxs("main",{className:"col-span-6 space-y-5",children:[G&&o.jsx(Ibe,{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}),o.jsx(bbe,{targetCloseDate:T==null?void 0:T.target_close_date,actualCloseDate:T==null?void 0:T.actual_close_date,clientName:r.client_name}),B&&o.jsx(kf,{children:o.jsx(Sbe,{currentStage:B,nextStepText:r.next_step_text,nextStepVideoUrl:V||r.next_step_video_url})}),o.jsx(kf,{children:o.jsx(wbe,{journeyStages:D,currentIndex:M})}),s&&s.length>0&&o.jsx(kf,{children:o.jsx(kbe,{updates:s})}),(r==null?void 0:r.id)&&o.jsx(kf,{children:o.jsx(Pbe,{portalId:r.id,clientName:r.client_name,agentName:a==null?void 0:a.name,agentAvatar:a==null?void 0:a.avatar_url})})]}),o.jsxs("aside",{className:"col-span-3 space-y-5",children:[o.jsx(kf,{children:o.jsx(Tbe,{deal:T,portal:r})}),(r==null?void 0:r.slug)&&o.jsx(Abe,{slug:r.slug,wrapper:ge=>o.jsx(kf,{children:ge})}),f&&f.length>0&&o.jsx(kf,{children:o.jsx(Ebe,{documents:f})}),Se&&o.jsx(kf,{children:o.jsxs("button",{onClick:ve,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:[o.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:o.jsx(Xhe,{className:"w-4 h-4"})}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("p",{className:"portal-serif",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:"Trusted Vendors"}),o.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:"My hand-picked network"})]}),o.jsx(od,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})]})}),o.jsxs("div",{className:"text-center pt-2 space-y-2",children:[o.jsx("div",{className:"portal-hairline w-12 mx-auto"}),o.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)&&o.jsx("div",{id:"trusted-vendors",className:"mt-8 scroll-mt-10",children:o.jsx(jbe,{portalId:r.id,ownerUserId:r.owner_user_id,currentStage:E==null?void 0:E.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function kf({children:t}){return o.jsx(pr.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 uz({href:t,icon:e,label:r,sub:n}){return o.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:[o.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:o.jsx(e,{className:"w-4 h-4"})}),o.jsxs("div",{className:"min-w-0 text-left",children:[o.jsx("p",{className:"text-sm portal-serif",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:r}),n&&o.jsx("p",{className:"text-[10px] tracking-[0.15em] uppercase truncate mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:n})]})]})}function dz({icon:t,label:e,value:r}){return o.jsxs("div",{className:"flex items-center gap-3",children:[o.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:o.jsx(t,{className:"w-4 h-4"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:e}),o.jsx("p",{className:"portal-serif truncate",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:r})]})]})}function Ktt({pct:t}){const i=2*Math.PI*78,a=i-t/100*i;return o.jsxs("div",{className:"relative",style:{width:170,height:170},children:[o.jsxs("svg",{width:170,height:170,className:"-rotate-90",children:[o.jsx("defs",{children:o.jsxs("linearGradient",{id:"portal-progress-gold",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[o.jsx("stop",{offset:"0%",stopColor:"var(--portal-hero-accent)"}),o.jsx("stop",{offset:"100%",stopColor:"var(--portal-hero-ink)"})]})}),o.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(0 0% 100% / 0.22)",strokeWidth:2,fill:"none"}),o.jsx(pr.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))"}})]}),o.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[o.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}),o.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 yne(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 Ytt({portal:t,dealData:e,agentProfile:r,customQuestions:n,deviceFingerprint:i,onComplete:a}){var R,D;const[c,s]=P.useState({first_name:((R=t.client_name)==null?void 0:R.split(" ")[0])||"",last_name:((D=t.client_name)==null?void 0:D.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:""}),[f,m]=P.useState({}),[x,_]=P.useState(!1),T=Cr({mutationFn:async()=>{const{error:M}=await Le.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(f).length>0?f:null,spouse_first_name:x&&c.spouse_first_name||null,spouse_last_name:x&&c.spouse_last_name||null,spouse_email:x&&c.spouse_email||null,spouse_phone:x&&c.spouse_phone||null});if(M)throw M},onSuccess:a,onError:M=>{console.error("[PortalOnboarding] Submit failed:",M),Jt.error("Something went wrong. Please try again.")}}),E=e!=null&&e.property_address?`${e.property_address}, ${e.city||""}, ${e.state||""}`:null,C="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",N="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 o.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:o.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[o.jsxs("div",{className:"text-center mb-8",children:[(r==null?void 0:r.avatar_url)&&o.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"}),o.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),E&&o.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[o.jsx(na,{className:"w-3.5 h-3.5"}),o.jsx("span",{children:E.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),o.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),o.jsxs("form",{onSubmit:M=>{M.preventDefault(),T.mutate()},className:"space-y-4",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),o.jsx(Ur,{required:!0,value:c.first_name,onChange:M=>s(B=>({...B,first_name:M.target.value})),className:C,placeholder:"John"})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),o.jsx(Ur,{value:c.last_name,onChange:M=>s(B=>({...B,last_name:M.target.value})),className:C,placeholder:"Doe"})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Email"}),o.jsx(Ur,{type:"email",value:c.email,onChange:M=>s(B=>({...B,email:M.target.value})),className:C,placeholder:"john@example.com"})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Phone"}),o.jsx(Ur,{type:"tel",value:c.phone,onChange:M=>s(B=>({...B,phone:M.target.value})),className:C,placeholder:"(555) 123-4567"})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Preferred Contact Method"}),o.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(M=>o.jsx("button",{type:"button",onClick:()=>s(B=>({...B,preferred_contact_method:M.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c.preferred_contact_method===M.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:M.label},M.value))})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Your Role"}),o.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(M=>o.jsx("button",{type:"button",onClick:()=>s(B=>({...B,client_role:M})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c.client_role===M?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:M.charAt(0).toUpperCase()+M.slice(1)},M))})]}),n.map(M=>o.jsxs("div",{children:[o.jsxs(Mr,{className:"text-xs font-medium text-slate-700",children:[M.question_text," ",M.is_required&&"*"]}),M.field_type==="text"&&o.jsx(Ur,{required:M.is_required,value:f[M.id]||"",onChange:B=>m(V=>({...V,[M.id]:B.target.value})),className:C}),M.field_type==="textarea"&&o.jsx("textarea",{required:M.is_required,value:f[M.id]||"",onChange:B=>m(V=>({...V,[M.id]:B.target.value})),className:`${N} min-h-[80px]`}),M.field_type==="dropdown"&&o.jsxs("select",{required:M.is_required,value:f[M.id]||"",onChange:B=>m(V=>({...V,[M.id]:B.target.value})),className:`${N} h-10`,children:[o.jsx("option",{value:"",children:"Select..."}),(M.options||[]).map(B=>o.jsx("option",{value:B,children:B},B))]}),M.field_type==="toggle"&&o.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(B=>o.jsx("button",{type:"button",onClick:()=>m(V=>({...V,[M.id]:B})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${f[M.id]===B?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:B},B))})]},M.id)),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),o.jsx("textarea",{value:c.notes,onChange:M=>s(B=>({...B,notes:M.target.value})),className:`${N} min-h-[60px]`,placeholder:"Anything you'd like your agent to know..."})]}),t.allow_spouse&&o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>_(!x),className:"text-sm text-blue-600 hover:text-blue-700 font-medium",children:x?"− Remove spouse/partner":"+ Add spouse/partner"}),x&&o.jsxs("div",{className:"mt-3 p-4 bg-slate-50 rounded-xl border border-slate-200 space-y-3",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"First Name"}),o.jsx(Ur,{value:c.spouse_first_name,onChange:M=>s(B=>({...B,spouse_first_name:M.target.value})),className:C})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),o.jsx(Ur,{value:c.spouse_last_name,onChange:M=>s(B=>({...B,spouse_last_name:M.target.value})),className:C})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Email"}),o.jsx(Ur,{type:"email",value:c.spouse_email,onChange:M=>s(B=>({...B,spouse_email:M.target.value})),className:C})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs font-medium text-slate-700",children:"Phone"}),o.jsx(Ur,{type:"tel",value:c.spouse_phone,onChange:M=>s(B=>({...B,spouse_phone:M.target.value})),className:C})]})]})]}),o.jsx(Ut,{type:"submit",disabled:T.isPending||!c.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:T.isPending?"Submitting...":"Access My Portal"})]})]})})}function Ztt(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 gVt(){const t=Ji();return wr({queryKey:["agent-portal-branding",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Le.from("agent_portal_branding").select("*").eq("user_id",t).maybeSingle();if(r)throw r;return e},enabled:!!t})}function Xtt(t){return wr({queryKey:["agent-portal-branding-public",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Le.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 yVt(){const t=Ji(),e=Nr();return Cr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Le.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 xVt(t,e,r){var s;const n=((s=e.name.split(".").pop())==null?void 0:s.toLowerCase())||"png",i=`${t}/${r}-${Date.now()}.${n}`,{error:a}=await Le.storage.from("portal-branding").upload(i,e,{upsert:!0,cacheControl:"3600"});if(a)throw a;const{data:c}=Le.storage.from("portal-branding").getPublicUrl(i);return c.publicUrl}function Qtt(t,e){return wr({queryKey:["client-portal-public",t],queryFn:async()=>{if(!t)return null;const{data:r,error:n}=await Le.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 Jtt(t){return wr({queryKey:["client-portal-by-id",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Le.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 ert({slug:t}){var ge,Ne,Ie,Te,be,We;const[e,r]=P.useState(!1),[n,i]=P.useState("primary"),[a]=P.useState(()=>{const rt=`portal_fp_${t}`;let at=localStorage.getItem(rt);return at||(at=localStorage.getItem("portal_fp"),at?localStorage.setItem(rt,at):(at=crypto.randomUUID(),localStorage.setItem(rt,at),localStorage.setItem("portal_fp",at))),at});P.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:c,isLoading:s,error:f}=Qtt(t,!0),m=c==null?void 0:c.linked_portal_id,{data:x}=Jtt(m),_=(ge=c==null?void 0:c.deal_pipeline)==null?void 0:ge.owner_user_id;wr({queryKey:["portal-stages",_],queryFn:async()=>{const{data:rt,error:at}=await Le.from("deal_pipeline_stages").select("*").eq("owner_user_id",_).order("sort_order",{ascending:!0});if(at)throw at;return rt},enabled:!!_});const{data:T}=wr({queryKey:["portal-agent",_],queryFn:async()=>{const{data:rt,error:at}=await Le.from("profiles").select("id, name, avatar_url, phone, email").eq("id",_).single();if(at)throw at;return rt},enabled:!!_}),{data:E}=Xtt(_),C=n==="linked"&&x?x:c,N=C==null?void 0:C.id,R=Ztt(E,C==null?void 0:C.branding_override),D=R.portal_theme==="azure"?"azure":"noir";P.useEffect(()=>{const rt=`portal-theme-${D}`;return document.body.classList.add(rt),()=>document.body.classList.remove(rt)},[D]);const{data:M}=wr({queryKey:["portal-updates-public",N],queryFn:async()=>{const{data:rt,error:at}=await Le.from("portal_updates").select("*").eq("portal_id",N).order("created_at",{ascending:!1});if(at)throw at;return rt},enabled:!!N}),B=(Ne=C==null?void 0:C.deal_pipeline)==null?void 0:Ne.id,{data:V}=wr({queryKey:["portal-documents",B],queryFn:async()=>{const{data:rt,error:at}=await Le.from("deal_files").select("*").eq("deal_id",B).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(at)throw at;return rt},enabled:!!B}),G=c==null?void 0:c.id,W=G?`portal_onboarded_${G}_${a}`:null,X=W?localStorage.getItem(W)==="1":!1,{data:Q,isLoading:re}=wr({queryKey:["portal-onboarding-check",G,a],queryFn:async()=>{const{data:rt,error:at}=await Le.from("portal_onboarding_submissions").select("id").eq("portal_id",G).eq("device_fingerprint",a).maybeSingle();if(at)throw at;return rt&&W&&localStorage.setItem(W,"1"),rt},enabled:!!G&&!!(c!=null&&c.require_onboarding)&&!X,staleTime:5*60*1e3}),se=!!(c!=null&&c.require_onboarding)&&!X&&!Q&&!e,{data:ue}=wr({queryKey:["portal-custom-questions-public",_],queryFn:async()=>{const{data:rt,error:at}=await Le.from("portal_custom_questions").select("*").eq("owner_user_id",_).eq("is_active",!0).order("sort_order",{ascending:!0});if(at)throw at;return rt},enabled:!!_&&se}),_e=X||!!Q||e||!(c!=null&&c.require_onboarding);if(s||c!=null&&c.require_onboarding&&!X&&re)return o.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:o.jsx(Cu,{className:"w-6 h-6 animate-spin",style:{color:"hsl(var(--portal-gold))"}})});if(f||!c)return o.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",style:{background:"var(--portal-gradient-noir)"},children:o.jsxs("div",{className:"text-center max-w-md",children:[o.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:o.jsx(QA,{className:"w-6 h-6",style:{color:"hsl(var(--portal-gold))"}})}),o.jsx("h1",{className:"portal-serif text-4xl mb-3",style:{color:"hsl(var(--portal-ink))"},children:"Portal Not Available"}),o.jsx("div",{className:"portal-hairline mx-auto w-24 mb-4"}),o.jsx("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:"This portal is no longer active or doesn't exist."})]})});if(!_e){const rt=c==null?void 0:c.deal_pipeline;return o.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:o.jsx(Ytt,{portal:c,dealData:rt,agentProfile:T,customQuestions:ue||[],deviceFingerprint:a,onComplete:()=>{W&&localStorage.setItem(W,"1"),r(!0)}})})}const Se=(Ie=c==null?void 0:c.deal_pipeline)==null?void 0:Ie.deal_type,ve=(Te=x==null?void 0:x.deal_pipeline)==null?void 0:Te.deal_type,Oe=!!x,Ae=rt=>rt==="listing"?"Your Sale":rt==="buy-side"?"Your Purchase":"Transaction",we=rt=>rt==="listing"?o.jsx(Ma,{className:"w-3.5 h-3.5"}):o.jsx(Ghe,{className:"w-3.5 h-3.5"});return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"hidden lg:block",children:o.jsx(Wtt,{portal:c,linkedPortal:x,activePortal:C,activeTab:n,onTabChange:i,agentProfile:T,branding:R,updates:M,documents:V})}),o.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[o.jsx(Dtt,{dealData:C==null?void 0:C.deal_pipeline,agentProfile:T,welcomeMessage:(C==null?void 0:C.welcome_message)||R.welcome_message,isWon:(We=(be=C==null?void 0:C.deal_pipeline)==null?void 0:be.deal_pipeline_stages)==null?void 0:We.is_won_stage,branding:R}),o.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[Oe&&o.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(rt=>{const at=n===rt,Et=rt==="primary"?Se:ve;return o.jsxs("button",{onClick:()=>i(rt),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:at?"hsl(var(--portal-surface-3))":"transparent",color:at?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:at?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[we(Et),o.jsx("span",{style:{fontSize:"1rem"},children:Ae(Et)})]},rt)})}),o.jsx(trt,{portal:C,updates:M,documents:V,agentProfile:T}),N&&o.jsx("div",{className:"rounded-2xl p-5",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.14)"},children:o.jsx(Pbe,{portalId:N,clientName:C==null?void 0:C.client_name,agentName:T==null?void 0:T.name,agentAvatar:T==null?void 0:T.avatar_url,deviceFingerprint:a})}),o.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[o.jsx("div",{className:"portal-hairline w-16 mx-auto"}),o.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[o.jsx(QA,{className:"w-3 h-3"}),o.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase",children:"Secure Client Portal"})]}),T&&o.jsxs("p",{className:"text-xs",style:{color:"hsl(var(--portal-ink-muted))"},children:["Curated by ",o.jsx("span",{className:"portal-serif",style:{color:"hsl(var(--portal-gold))",fontSize:"0.95rem"},children:T.name})]})]})]})]})]})}function trt({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,s=c==null?void 0:c.is_won_stage,f=a==null?void 0:a.deal_type,m=t.stage_mapping;let x=Rbe(f);m&&m.length>0&&(x=m.map((N,R)=>{var D,M;return{key:`custom-${R}`,label:N.label||((D=x[R])==null?void 0:D.label)||`Stage ${R+1}`,description:N.description||((M=x[R])==null?void 0:M.description)||"",video_url:N.video_url||void 0}}));const _=m&&m.length>0?Math.min(yD(c==null?void 0:c.name),x.length-1):yD(c==null?void 0:c.name),T=x[_],E=T==null?void 0:T.video_url,C=s&&t.show_post_close_tips!==!1&&t.referral_enabled!==!1;return o.jsxs(o.Fragment,{children:[C&&o.jsx(Ibe,{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}),o.jsx(bbe,{targetCloseDate:a==null?void 0:a.target_close_date,actualCloseDate:a==null?void 0:a.actual_close_date,clientName:t.client_name}),o.jsx(wbe,{journeyStages:x,currentIndex:_}),T&&o.jsx(Sbe,{currentStage:T,nextStepText:t.next_step_text,nextStepVideoUrl:E||t.next_step_video_url}),o.jsx(Tbe,{deal:a,portal:t}),(t==null?void 0:t.slug)&&o.jsx(Abe,{slug:t.slug}),r&&r.length>0&&o.jsx(Ebe,{documents:r}),(t==null?void 0:t.id)&&(t==null?void 0:t.owner_user_id)&&o.jsx(jbe,{portalId:t.id,ownerUserId:t.owner_user_id,currentStage:c==null?void 0:c.name}),e&&e.length>0&&o.jsx(kbe,{updates:e})]})}function Lbe({slug:t}){const e=hp(),r=t||e.slug,[n,i]=P.useState(!1),[a,c]=P.useState(!1),[s,f]=P.useState(""),[m,x]=P.useState(""),[_,T]=P.useState(""),[E,C]=P.useState(""),[N,R]=P.useState(""),[D,M]=P.useState("buying"),[B,V]=P.useState("");P.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:G,isLoading:W,error:X}=wr({queryKey:["portal-referral-target",r],queryFn:async()=>{if(!r)return null;const{data:se,error:ue}=await Le.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(ue)throw ue;return se},enabled:!!r}),{data:Q}=wr({queryKey:["portal-referral-agent",G==null?void 0:G.owner_user_id],queryFn:async()=>{const{data:se}=await Le.from("profiles").select("id, name, avatar_url").eq("id",G.owner_user_id).single();return se},enabled:!!(G!=null&&G.owner_user_id)}),re=async se=>{if(se.preventDefault(),!G||!_.trim()){Jt.error("Please enter your friend's name");return}if(!E.trim()&&!N.trim()){Jt.error("Please add at least an email or phone for your friend");return}i(!0);try{const{error:ue}=await Le.from("portal_referrals").insert({portal_id:G.id,owner_user_id:G.owner_user_id,referrer_name:s.trim()||G.client_name||null,referrer_email:m.trim()||null,friend_name:_.trim(),friend_email:E.trim()||null,friend_phone:N.trim()||null,friend_interest:D,friend_message:B.trim()||null});if(ue)throw ue;c(!0)}catch(ue){Jt.error(ue.message||"Could not submit referral")}finally{i(!1)}};return W?o.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:o.jsx(ol,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):X||!G||!G.referral_enabled?o.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4",children:o.jsx("span",{className:"text-2xl",children:"🔒"})}),o.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Referral Page Unavailable"}),o.jsx("p",{className:"text-slate-500",children:"This referral link is no longer active."})]})}):a?o.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:o.jsxs("div",{className:"max-w-md w-full bg-white rounded-2xl shadow-xl p-8 text-center",children:[o.jsx("div",{className:"w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4",children:o.jsx(Ao,{className:"w-8 h-8 text-emerald-600"})}),o.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2 font-serif",children:"Thank you! 🙏"}),o.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"," ",o.jsx("span",{className:"font-semibold text-slate-800",children:_})," personally and treat them like family."]}),o.jsxs("button",{onClick:()=>window.history.back(),className:"inline-flex items-center gap-2 text-sm text-[#406E71] hover:text-[#2a4c64] font-medium",children:[o.jsx(By,{className:"w-4 h-4"}),"Back to your portal"]})]})}):o.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white pb-12",children:[o.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:[o.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"24px 24px"}}),o.jsxs("div",{className:"relative max-w-lg mx-auto text-center",children:[Q!=null&&Q.avatar_url?o.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"}):o.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:o.jsx(Yh,{className:"w-7 h-7 text-white/70"})}),o.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:[o.jsx(Yh,{className:"w-3 h-3"})," Referral"]}),o.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:G.referral_cta_headline||"Refer a Friend"}),o.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&&o.jsxs("p",{className:"text-xs text-white/60 mt-2",children:["You'll get: ",o.jsx("span",{className:"text-white font-medium",children:G.referral_reward_text})," when they close."]})]})]}),o.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-6 relative z-10",children:o.jsxs("form",{onSubmit:re,className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-5 space-y-5",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Tell us about your friend"}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsxs(Mr,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",o.jsx("span",{className:"text-red-500",children:"*"})]}),o.jsx(Ur,{id:"friend_name",value:_,onChange:se=>T(se.target.value),placeholder:"Jane Smith",required:!0,className:"mt-1"})]}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),o.jsx(Ur,{id:"friend_email",type:"email",value:E,onChange:se=>C(se.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),o.jsx(Ur,{id:"friend_phone",type:"tel",value:N,onChange:se=>R(se.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),o.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-sm",children:"They're interested in..."}),o.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(se=>o.jsx("button",{type:"button",onClick:()=>M(se.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${D===se.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:se.l},se.v))})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),o.jsx("textarea",{id:"friend_message",value:B,onChange:se=>V(se.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"})]})]})]}),o.jsxs("div",{className:"border-t pt-4",children:[o.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),o.jsx(Ur,{id:"referrer_name",value:s,onChange:se=>f(se.target.value),placeholder:G.client_name||"Your name",className:"mt-1"})]}),o.jsxs("div",{children:[o.jsx(Mr,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),o.jsx(Ur,{id:"referrer_email",type:"email",value:m,onChange:se=>x(se.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),o.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?o.jsx(Cu,{className:"w-4 h-4 animate-spin"}):o.jsx(Yh,{className:"w-4 h-4"}),n?"Sending...":"Send Referral"]}),o.jsx("p",{className:"text-[11px] text-center text-slate-400",children:"By submitting, you confirm your friend has agreed to be contacted."})]})})]})}const rrt=Object.freeze(Object.defineProperty({__proto__:null,default:Lbe},Symbol.toStringTag,{value:"Module"}));function nrt(){const e=Wi().pathname.slice(1).replace(/\/$/,"");if(P.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>{document.body.classList.remove("client-portal-page")}),[]),!e)return o.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Client Portal"}),o.jsx("p",{className:"text-slate-500",children:"Visit your personalized portal link to view your transaction details."})]})});const r=e.match(/^([^/]+)\/refer$/);return r?o.jsx(Lbe,{slug:r[1]}):e.includes("/")?o.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Page Not Found"}),o.jsx("p",{className:"text-slate-500",children:"This portal link doesn't look right."})]})}):o.jsx(ert,{slug:e})}function irt(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 dV({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=P.useMemo(()=>irt(Array.isArray(t)?t:[]),[t]),[c,s]=P.useState(0);return P.useEffect(()=>{s(0)},[a.join("|")]),!a.length||c>=a.length?o.jsx("div",{className:`${r} bg-muted flex items-center justify-center text-muted-foreground`,children:o.jsx(Ma,{className:`${i} opacity-40`})}):o.jsx("div",{className:`${r} overflow-hidden bg-muted`,children:o.jsx("img",{src:a[c],alt:e,className:n,onError:()=>s(f=>f+1)})})}function srt({comp:t,open:e,onClose:r}){var m;const[n,i]=P.useState(0);if(!t)return null;const a=Array.isArray(t.photos)?t.photos.filter(Boolean):[],c=t.soldPrice||t.price,s=t.sqft&&c?Math.round(c/t.sqft):null,f=x=>{if(!x)return null;const[_,T,E]=x.split(/[-/T]/);return _?`${T}/${E}/${_}`:null};return o.jsx(ro,{open:e,onOpenChange:x=>{x||r()},children:o.jsxs($a,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[o.jsxs(ul,{className:"px-6 pt-6 pb-2",children:[o.jsx(Go,{className:"text-xl",children:t.address}),o.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[o.jsx(na,{className:"w-3.5 h-3.5"}),t.city,", ",t.state," ",t.zip]})]}),a.length>0?o.jsxs("div",{className:"px-6",children:[o.jsx(dV,{photos:a.slice(n),className:"rounded-lg aspect-[16/10]"}),a.length>1&&o.jsx("div",{className:"flex gap-2 mt-2 overflow-x-auto pb-2",children:a.slice(0,24).map((x,_)=>o.jsx("button",{onClick:()=>i(_),className:`flex-none w-20 h-16 rounded overflow-hidden border-2 transition ${_===n?"border-primary":"border-transparent opacity-70 hover:opacity-100"}`,children:o.jsx(dV,{photos:[x],iconClassName:"w-5 h-5"})},_))})]}):o.jsx("div",{className:"px-6",children:o.jsx("div",{className:"rounded-lg bg-muted aspect-[16/10] flex items-center justify-center text-muted-foreground",children:o.jsx(Ma,{className:"w-12 h-12 opacity-40"})})}),o.jsxs("div",{className:"px-6 pt-4 flex items-center justify-between flex-wrap gap-2",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"text-3xl font-bold flex items-center gap-1",children:[o.jsx(ym,{className:"w-6 h-6 text-muted-foreground"}),(c||0).toLocaleString()]}),s&&o.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",s,"/sqft"]})]}),o.jsxs("div",{className:"flex flex-col items-end gap-1",children:[o.jsx(us,{variant:"outline",children:t.status}),t.daysOnMarket!=null&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.daysOnMarket," DOM"]})]})]}),(t.listDate||t.statusChangeDate||t.soldDate)&&o.jsxs("div",{className:"px-6 pt-4",children:[o.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Timeline"}),o.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[o.jsx(hz,{label:"Active",date:f(t.listDate),active:!0}),o.jsx(hz,{label:"Pending",date:/Pending|Contingent|Under Contract|Backup/i.test(String(t.status||""))?f(t.statusChangeDate):null,active:/Pending|Contingent|Under Contract|Backup/i.test(String(t.status||""))}),o.jsx(hz,{label:"Closed",date:f(t.soldDate)||(/Closed|Sold/i.test(String(t.status||""))?f(t.statusChangeDate):null),active:/Closed|Sold/i.test(String(t.status||""))})]})]}),o.jsxs("div",{className:"px-6 pt-4 grid grid-cols-2 md:grid-cols-4 gap-3",children:[o.jsx(AN,{icon:o.jsx(TC,{className:"w-4 h-4"}),label:"Beds",value:t.bedrooms??"—"}),o.jsx(AN,{icon:o.jsx(lS,{className:"w-4 h-4"}),label:"Baths",value:t.bathrooms??"—"}),o.jsx(AN,{icon:o.jsx(QO,{className:"w-4 h-4"}),label:"SqFt",value:((m=t.sqft)==null?void 0:m.toLocaleString())??"—"}),o.jsx(AN,{icon:o.jsx(po,{className:"w-4 h-4"}),label:"Year Built",value:t.yearBuilt??"—"})]}),o.jsxs("div",{className:"px-6 pt-4 grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:[o.jsx(Lc,{label:"MLS #",value:t.mlsNumber}),o.jsx(Lc,{label:"Property Type",value:t.propertySubType||t.propertyType}),o.jsx(Lc,{label:"Lot Size",value:t.lotSize}),o.jsx(Lc,{label:"Garage",value:t.garageSpaces}),o.jsx(Lc,{label:"Stories",value:t.stories}),o.jsx(Lc,{label:"HOA",value:t.hoaFee?`$${t.hoaFee}/${(t.hoaFrequency||"mo").toLowerCase()}`:null}),o.jsx(Lc,{label:"Tax (annual)",value:t.taxAmount?`$${t.taxAmount.toLocaleString()}`:null}),o.jsx(Lc,{label:"Heating",value:t.heating}),o.jsx(Lc,{label:"Cooling",value:t.cooling}),o.jsx(Lc,{label:"Parking",value:t.parking}),o.jsx(Lc,{label:"Elementary",value:t.elementarySchool}),o.jsx(Lc,{label:"Middle",value:t.middleSchool}),o.jsx(Lc,{label:"High",value:t.highSchool}),o.jsx(Lc,{label:"Listed By",value:t.listAgentFullName}),o.jsx(Lc,{label:"Office",value:t.listOfficeName})]}),t.description&&o.jsxs("div",{className:"px-6 pt-4",children:[o.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1",children:"Description"}),o.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:t.description})]}),o.jsx("div",{className:"px-6 py-4"})]})})}function AN({icon:t,label:e,value:r}){return o.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[o.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[t,e]}),o.jsx("div",{className:"text-lg font-semibold mt-0.5",children:r})]})}function Lc({label:t,value:e}){return e==null||e===""||e===0?null:o.jsxs("div",{className:"flex justify-between border-b border-dashed py-1",children:[o.jsx("span",{className:"text-muted-foreground",children:t}),o.jsx("span",{className:"font-medium text-right ml-3 truncate",children:String(e)})]})}function hz({label:t,date:e,active:r}){return o.jsxs("div",{className:`rounded-lg border p-2 text-center ${r?"bg-primary/5 border-primary/30":"bg-muted/30"}`,children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:t}),o.jsx("div",{className:`text-sm font-medium mt-0.5 ${e?"":"text-muted-foreground/60"}`,children:e||"—"})]})}function kN({to:t,durationMs:e=1400,prefix:r="",suffix:n="",className:i,delayMs:a=0}){const[c,s]=P.useState(0),f=P.useRef(null);return P.useEffect(()=>{if(!Number.isFinite(t))return;let m=0;const x=0,_=E=>1-Math.pow(1-E,3),T=setTimeout(()=>{const E=C=>{m||(m=C);const N=C-m,R=Math.min(1,N/e);s(Math.round(x+(t-x)*_(R))),R<1&&(f.current=requestAnimationFrame(E))};f.current=requestAnimationFrame(E)},a);return()=>{clearTimeout(T),f.current&&cancelAnimationFrame(f.current)}},[t,e,a]),o.jsxs("span",{className:i,children:[r,c.toLocaleString(),n]})}function art({low:t,likely:e,high:r,defaultMortgage:n=0,defaultCommissionPct:i=6,defaultClosingPct:a=1}){const[c,s]=P.useState(e),[f,m]=P.useState(n),[x,_]=P.useState(i),[T,E]=P.useState(a),{commission:C,closing:N,net:R}=P.useMemo(()=>{const B=Math.round(c*x/100),V=Math.round(c*T/100);return{commission:B,closing:V,net:Math.max(0,c-B-V-(f||0))}},[c,x,T,f]),D=B=>`$${B.toLocaleString()}`,M=r>t?(c-t)/(r-t)*100:50;return o.jsxs(Hn,{className:"overflow-hidden border-primary/20",children:[o.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:[o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx(uS,{className:"w-4 h-4 text-primary"}),o.jsx("span",{className:"text-xs uppercase tracking-widest font-semibold text-primary",children:"Your Price Story"})]}),o.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"What if you priced it at…"}),o.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Drag the price. Watch your estimated walk-away update in real-time."})]}),o.jsxs(ii,{className:"p-6 space-y-6",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-end justify-between mb-3",children:[o.jsx("span",{className:"text-xs text-muted-foreground",children:"List price"}),o.jsx("span",{className:"text-3xl font-bold tabular-nums",children:D(c)})]}),o.jsxs("div",{className:"relative",children:[o.jsx(xA,{value:[c],min:t,max:r,step:1e3,onValueChange:([B])=>s(B)}),o.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[o.jsx("span",{children:D(t)}),o.jsxs("span",{children:["Suggested ",D(e)]}),o.jsx("span",{children:D(r)})]})]}),o.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:o.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,M))}%`}})})]}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Mortgage payoff"}),o.jsx(Ur,{type:"number",inputMode:"numeric",value:f||"",placeholder:"$0",onChange:B=>m(Number(B.target.value)||0)})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Commission %"}),o.jsx(Ur,{type:"number",step:"0.25",value:x,onChange:B=>_(Number(B.target.value)||0)})]}),o.jsxs("div",{children:[o.jsx(Mr,{className:"text-xs",children:"Closing costs %"}),o.jsx(Ur,{type:"number",step:"0.25",value:T,onChange:B=>E(Number(B.target.value)||0)})]})]}),o.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[o.jsxs("div",{className:"px-5 py-4 grid grid-cols-2 gap-y-2 text-sm",children:[o.jsx("span",{className:"text-muted-foreground",children:"Sale price"}),o.jsx("span",{className:"text-right tabular-nums font-medium",children:D(c)}),o.jsxs("span",{className:"text-muted-foreground",children:["Commission (",x,"%)"]}),o.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",D(C)]}),o.jsxs("span",{className:"text-muted-foreground",children:["Closing (",T,"%)"]}),o.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",D(N)]}),f>0&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"text-muted-foreground",children:"Mortgage payoff"}),o.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",D(f)]})]})]}),o.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:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(xG,{className:"w-5 h-5 text-emerald-600"}),o.jsx("span",{className:"font-semibold",children:"Your estimated walk-away"})]}),o.jsx("span",{className:"text-2xl font-bold tabular-nums text-emerald-700",children:D(R)})]})]}),o.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 Dbe({tokenOverride:t}={}){var Pt,er,wt,or,Sr,nn,lr,yr,tr,yn,lt,At;const e=hp(),r=t??e.token,[n,i]=P.useState(null),[a,c]=P.useState(null),[s,f]=P.useState([]),[m,x]=P.useState(!0),[_,T]=P.useState(""),[E,C]=P.useState(""),[N,R]=P.useState(""),[D,M]=P.useState(!1),[B,V]=P.useState(!1),[G,W]=P.useState(null),[X,Q]=P.useState(null),[re,se]=P.useState(!1),{toast:ue}=lhe();P.useEffect(()=>{r&&(async()=>{const{data:Ot}=await Le.from("cmas").select("*").eq("share_token",r).eq("status","shared").maybeSingle();if(!Ot){x(!1);return}i(Ot);const[{data:dr},{data:cr}]=await Promise.all([Le.from("cma_comps").select("*").eq("cma_id",Ot.id).order("position"),Le.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",Ot.agent_id).maybeSingle()]);f((dr||[]).filter(Zt=>Zt.selected)),c(cr);const hr=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",hr),await Le.from("cma_views").insert({cma_id:Ot.id,visitor_token:hr,user_agent:navigator.userAgent}),x(!1)})()},[r]);const _e=async Ot=>{if(!n)return;const dr=localStorage.getItem("cma_visitor_token")||"";await Le.from("cma_views").insert({cma_id:n.id,visitor_token:dr,reactions:{[Ot]:!0}}),Le.functions.invoke("cma-reply-notify",{body:{shareToken:r,reaction:Ot,visitorToken:dr}}).catch(()=>{}),ue({title:"Thanks — your agent just got notified ✨"})},Se=!(n!=null&&n.contact_id),ve=async()=>{if(!n||!_.trim())return;if(Se&&(!E.trim()||!N.trim())){ue({title:"Please add your name and email",variant:"destructive"});return}M(!0);const Ot=localStorage.getItem("cma_visitor_token")||"",{data:dr,error:cr}=await Le.functions.invoke("cma-reply-notify",{body:{shareToken:r,message:_,visitorToken:Ot,viewerName:E.trim()||void 0,viewerEmail:N.trim()||void 0}});if(M(!1),cr||!(dr!=null&&dr.success)){ue({title:"Could not send",description:(cr==null?void 0:cr.message)||(dr==null?void 0:dr.error),variant:"destructive"});return}T(""),V(!0),ue({title:"Message sent to your agent"})},Oe=P.useMemo(()=>{const Ot=s.map(dr=>{const cr=dr.snapshot,hr=(cr==null?void 0:cr.soldPrice)||(cr==null?void 0:cr.price);return hr&&(cr!=null&&cr.sqft)?hr/cr.sqft:null}).filter(dr=>!!dr).sort((dr,cr)=>dr-cr);return Ot.length?Math.round(Ot[Math.floor(Ot.length/2)]):null},[s]);if(m)return o.jsx("div",{className:"min-h-screen flex items-center justify-center",children:o.jsx(Cu,{className:"w-8 h-8 animate-spin"})});if(!n)return o.jsx("div",{className:"min-h-screen flex items-center justify-center text-center p-6",children:o.jsxs("div",{children:[o.jsx(Ma,{className:"w-12 h-12 mx-auto text-muted-foreground mb-4"}),o.jsx("h1",{className:"text-xl font-semibold",children:"CMA not found"}),o.jsx("p",{className:"text-muted-foreground",children:"This report may have been removed or unpublished."})]})});const Ae=n.subject||{},we=(Pt=n.settings)==null?void 0:Pt.personalVideo,ge=(er=Ae.photos)==null?void 0:er[0],Ne=n.contact_first_name?n.contact_first_name:null,Ie=((a==null?void 0:a.name)||"A").split(" ").map(Ot=>Ot[0]).slice(0,2).join("").toUpperCase(),Te=a!=null&&a.phone?`tel:${String(a.phone).replace(/[^\d+]/g,"")}`:null,be=a!=null&&a.email?`mailto:${a.email}`:null,We=a!=null&&a.phone?`sms:${String(a.phone).replace(/[^\d+]/g,"")}`:null,rt=n.price_low??null,at=n.price_likely??null,Et=n.price_high??null,_t=rt&&at&&Et,Vt=at&&Ae.sqft?Math.round(at/Ae.sqft):null,mt=Vt&&Oe?Math.round((Vt-Oe)/Oe*100):null;return o.jsxs("div",{className:"min-h-screen bg-background pb-28 md:pb-0",children:[a&&o.jsx("div",{className:"border-b bg-card sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:o.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?o.jsx("img",{src:a.avatar_url,alt:a.name,className:"w-10 h-10 rounded-full object-cover ring-2 ring-primary/20"}):o.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center font-semibold text-primary text-sm",children:Ie}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:"font-semibold leading-tight truncate text-sm",children:a.name}),(a.title||a.brokerage_name)&&o.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-1 truncate",children:[a.brokerage_name&&o.jsx(Eo,{className:"w-3 h-3 shrink-0"}),o.jsx("span",{className:"truncate",children:[a.title,a.brokerage_name].filter(Boolean).join(" · ")})]})]}),o.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[Te&&o.jsx(Ut,{variant:"outline",size:"sm",asChild:!0,children:o.jsxs("a",{href:Te,children:[o.jsx(zi,{className:"w-4 h-4 mr-1"}),"Call"]})}),be&&o.jsx(Ut,{variant:"outline",size:"sm",asChild:!0,children:o.jsxs("a",{href:be,children:[o.jsx(Bi,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),o.jsxs("div",{className:"relative overflow-hidden",children:[ge?o.jsxs("div",{className:"absolute inset-0",children:[o.jsx("img",{src:ge,alt:Ae.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"}}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):o.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),o.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),o.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:o.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[o.jsxs("div",{className:`${we!=null&&we.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[o.jsxs(us,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[o.jsx(Ss,{className:"w-3 h-3 mr-1"}),Ne?`Prepared for ${Ne}`:n.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),o.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:Ae.address}),o.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[o.jsx(na,{className:"w-4 h-4"}),Ae.city,", ",Ae.state," ",Ae.zip]}),_t&&o.jsxs("div",{className:"mt-8 md:mt-10",children:[o.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-white/60 mb-2",children:"Estimated Value"}),o.jsx("div",{className:"flex items-baseline gap-4 flex-wrap",children:o.jsx("div",{className:"text-5xl md:text-7xl font-bold tabular-nums",children:o.jsx(kN,{to:at,prefix:"$",durationMs:1600,delayMs:250})})}),o.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[o.jsxs("div",{children:[o.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),o.jsx("span",{className:"tabular-nums font-medium",children:o.jsx(kN,{to:rt,prefix:"$",delayMs:500})})]}),o.jsx("div",{className:"h-8 w-px bg-white/20"}),o.jsxs("div",{children:[o.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Likely"}),o.jsx("span",{className:"tabular-nums font-medium",children:o.jsx(kN,{to:at,prefix:"$",delayMs:650})})]}),o.jsx("div",{className:"h-8 w-px bg-white/20"}),o.jsxs("div",{children:[o.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),o.jsx("span",{className:"tabular-nums font-medium",children:o.jsx(kN,{to:Et,prefix:"$",delayMs:800})})]})]})]})]}),(we==null?void 0:we.url)&&o.jsx("div",{className:"md:col-span-2 animate-scale-in",children:o.jsxs("button",{onClick:()=>se(!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:[we.thumb?o.jsx("img",{src:we.thumb,alt:"",className:"w-full h-full object-cover"}):o.jsx("video",{src:we.url,className:"w-full h-full object-cover",muted:!0,playsInline:!0,preload:"metadata"}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-black/10 group-hover:from-black/40 transition-colors"}),o.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white",children:[o.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:o.jsx(uLe,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),o.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((wt=a==null?void 0:a.name)==null?void 0:wt.split(" ")[0])||"your agent"]})]})]})})]})})]}),re&&(we==null?void 0:we.url)&&o.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>se(!1),children:o.jsxs("div",{className:"relative w-full max-w-4xl",onClick:Ot=>Ot.stopPropagation(),children:[o.jsx("video",{src:we.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),o.jsx(Ut,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>se(!1),children:"Close"})]})}),o.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:[o.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:Ae.bedrooms??"—"},{label:"Baths",value:Ae.bathrooms??"—"},{label:"Sq Ft",value:((or=Ae.sqft)==null?void 0:or.toLocaleString())??"—"},{label:"Year Built",value:Ae.yearBuilt??"—"}].map((Ot,dr)=>o.jsx(Hn,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${dr*80}ms`},children:o.jsxs(ii,{className:"p-4 md:p-6 text-center",children:[o.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:Ot.value}),o.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:Ot.label})]})},dr))}),((nn=(Sr=n.settings)==null?void 0:Sr.priceOverride)==null?void 0:nn.enabled)&&((yr=(lr=n.settings)==null?void 0:lr.priceOverride)==null?void 0:yr.note)&&o.jsx(Hn,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:o.jsxs(ii,{className:"p-6 md:p-8",children:[o.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"A note from your agent"}),o.jsx("p",{className:"text-base md:text-lg leading-relaxed whitespace-pre-wrap text-foreground/90",children:n.settings.priceOverride.note})]})}),_t&&o.jsx(art,{low:rt,likely:at,high:Et}),Oe&&Vt&&o.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[o.jsx(Hn,{className:"md:col-span-2",children:o.jsxs(ii,{className:"p-6 md:p-8",children:[o.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Why this price"}),o.jsx("h2",{className:"text-2xl md:text-3xl font-bold mb-3",children:"The market is talking."}),o.jsxs("p",{className:"text-muted-foreground leading-relaxed",children:["Based on ",o.jsxs("strong",{className:"text-foreground",children:[s.length," comparable ",s.length===1?"home":"homes"]})," in ",Ae.city,", the median sale rate is ",o.jsxs("strong",{className:"text-foreground",children:["$",Oe,"/sqft"]}),". Applied to your home's ",(tr=Ae.sqft)==null?void 0:tr.toLocaleString()," sqft, the comps support a value near ",o.jsxs("strong",{className:"text-foreground",children:["$",(Oe*(Ae.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),o.jsx(Hn,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:o.jsxs(ii,{className:"p-6 md:p-8 h-full flex flex-col justify-center",children:[o.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground mb-1",children:"Your home"}),o.jsxs("div",{className:"text-3xl font-bold tabular-nums",children:["$",Vt,o.jsx("span",{className:"text-base font-normal text-muted-foreground",children:"/sqft"})]}),o.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Neighborhood avg: ",o.jsxs("span",{className:"font-medium text-foreground",children:["$",Oe,"/sqft"]})]}),mt!==null&&mt!==0&&o.jsxs("p",{className:`text-sm font-medium mt-1 ${mt>0?"text-emerald-600":"text-rose-600"}`,children:[mt>0?"▲":"▼"," ",Math.abs(mt),"% ",mt>0?"above":"below"," the median"]})]})})]}),o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold",children:"Homes like yours"}),o.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"The Comparables"})]}),o.jsxs(us,{variant:"outline",className:"text-xs",children:[s.length," comps"]})]}),o.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map((Ot,dr)=>{var Zt;const cr=Ot.snapshot,hr=cr.soldPrice||cr.price;return o.jsxs(Hn,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${X===dr?"ring-2 ring-primary":""}`,style:{animationDelay:`${dr*60}ms`},onClick:()=>W(dr),onMouseEnter:()=>Q(dr),onMouseLeave:()=>Q(null),children:[o.jsxs("div",{className:"relative",children:[o.jsx(dV,{photos:cr.photos,className:"w-full h-44"}),o.jsxs(us,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",dr+1]}),o.jsx(us,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:cr.status})]}),o.jsxs(ii,{className:"p-4",children:[o.jsx("div",{className:"font-semibold leading-tight truncate",children:cr.address}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[cr.city,", ",cr.state]}),o.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:o.jsxs("span",{className:"text-muted-foreground",children:[cr.bedrooms??"?","bd · ",cr.bathrooms??"?","ba · ",((Zt=cr.sqft)==null?void 0:Zt.toLocaleString())??"?"," sqft"]})}),o.jsxs("div",{className:"flex justify-between items-center mt-3 pt-3 border-t",children:[o.jsxs("span",{className:"text-xl font-bold tabular-nums",children:["$",hr==null?void 0:hr.toLocaleString()]}),cr.sqft&&hr?o.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(hr/cr.sqft),"/sqft"]}):null]})]})]},dr)})})]}),o.jsx(srt,{comp:G!==null?(yn=s[G])==null?void 0:yn.snapshot:null,open:G!==null,onClose:()=>W(null)}),o.jsx(Hn,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:o.jsxs(ii,{className:"p-6 md:p-8 space-y-5",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-1",children:"Your turn"}),o.jsxs("h2",{className:"text-2xl md:text-3xl font-bold",children:["What do you think",Ne?`, ${Ne}`:"","?"]}),o.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((lt=a==null?void 0:a.name)==null?void 0:lt.split(" ")[0])||"Your agent"," hears you instantly."]})]}),o.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:tp,label:"I love this price"},{kind:"fair",icon:wLe,label:"Seems fair"},{kind:"lower",icon:Jhe,label:"I'd price lower"},{kind:"higher",icon:uS,label:"I'd price higher"},{kind:"ready_to_list",icon:EU,label:"Ready to list"},{kind:"want_walkthrough",icon:KO,label:"Want a walkthrough"},{kind:"need_time",icon:po,label:"Need more time"},{kind:"have_questions",icon:VRe,label:"I have questions"}].map(({kind:Ot,icon:dr,label:cr})=>o.jsxs(Ut,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>_e(Ot),children:[o.jsx(dr,{className:"w-4 h-4 mr-2"}),cr]},Ot))}),o.jsxs("div",{className:"pt-4 border-t",children:[o.jsxs("p",{className:"text-sm font-medium mb-2 flex items-center gap-1",children:[o.jsx(f1,{className:"w-4 h-4"}),"Ask your agent a question"]}),B?o.jsxs("div",{className:"rounded-md bg-emerald-50 border border-emerald-200 p-4 text-sm text-emerald-800 animate-fade-in",children:["✓ Sent! ",((At=a==null?void 0:a.name)==null?void 0:At.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):o.jsxs(o.Fragment,{children:[Se&&o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[o.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:E,onChange:Ot=>C(Ot.target.value)}),o.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:N,onChange:Ot=>R(Ot.target.value)})]}),o.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:_,onChange:Ot=>T(Ot.target.value)}),o.jsx(Ut,{onClick:ve,disabled:!_.trim()||D,className:"mt-2",children:D?"Sending…":"Send to agent"})]})]})]})}),a&&o.jsx(Hn,{className:"overflow-hidden border-primary/20",children:o.jsx("div",{className:"bg-gradient-to-br from-primary/10 to-primary/5 p-6 md:p-10",children:o.jsxs("div",{className:"flex flex-col md:flex-row gap-6 items-start",children:[a.avatar_url?o.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"}):o.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:Ie}),o.jsxs("div",{className:"flex-1",children:[o.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground",children:"Prepared by"}),o.jsx("h2",{className:"text-2xl md:text-3xl font-bold mt-1",children:a.name}),(a.title||a.brokerage_name)&&o.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:[a.title,a.brokerage_name].filter(Boolean).join(" · ")}),a.bio&&o.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:a.bio}),o.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[Te&&o.jsx(Ut,{asChild:!0,children:o.jsxs("a",{href:Te,children:[o.jsx(zi,{className:"w-4 h-4 mr-2"}),a.phone]})}),be&&o.jsx(Ut,{variant:"outline",asChild:!0,children:o.jsxs("a",{href:be,children:[o.jsx(Bi,{className:"w-4 h-4 mr-2"}),"Email"]})}),a.website_url&&o.jsx(Ut,{variant:"outline",asChild:!0,children:o.jsxs("a",{href:a.website_url,target:"_blank",rel:"noreferrer",children:[o.jsx(h1,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),a&&(Te||We||be)&&o.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:[Te&&o.jsx(Ut,{className:"flex-1",asChild:!0,children:o.jsxs("a",{href:Te,children:[o.jsx(zi,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),We&&o.jsx(Ut,{variant:"outline",className:"flex-1",asChild:!0,children:o.jsxs("a",{href:We,children:[o.jsx(f1,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),be&&o.jsx(Ut,{variant:"outline",className:"flex-1",asChild:!0,children:o.jsxs("a",{href:be,children:[o.jsx(Bi,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}const ort=Object.freeze(Object.defineProperty({__proto__:null,default:Dbe},Symbol.toStringTag,{value:"Module"}));function lrt(){const e=Wi().pathname.slice(1).replace(/\/$/,"");return!e||e.includes("/")?o.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"CMA Portal"}),o.jsx("p",{className:"text-slate-500",children:"Open your CMA link to view your personalized market analysis."})]})}):o.jsx(Dbe,{tokenOverride:e})}const hV="levelup_affiliate_ref",crt=30,urt=()=>{const[t]=B0();P.useEffect(()=>{const e=t.get("ref");if(e){const r={code:e.toUpperCase(),timestamp:Date.now()};localStorage.setItem(hV,JSON.stringify(r)),console.log("[Affiliate] Stored referral code:",e)}},[t])},drt=()=>{try{const t=localStorage.getItem(hV);if(!t)return null;const e=JSON.parse(t),r=crt*24*60*60*1e3;return Date.now()-e.timestamp>r?(localStorage.removeItem(hV),console.log("[Affiliate] Referral code expired"),null):e.code}catch{return null}},xne="/assets/levelup-logo-header-_ZX7DvlA.png",hrt="/assets/scale-your-team-ku4MPatU.png";function frt({open:t,onOpenChange:e}){return o.jsx(ro,{open:t,onOpenChange:e,children:o.jsxs($a,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[o.jsx(ul,{children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"p-2 bg-[#4a6b6d]/10 rounded-lg",children:o.jsx(Eo,{className:"h-5 w-5 text-[#4a6b6d]"})}),o.jsxs("div",{children:[o.jsx(Go,{children:"Schedule a Brokerage Interest Meeting"}),o.jsx(ld,{children:"Learn how LevelUp can empower your entire team"})]})]})}),t&&o.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 Obe="/assets/mission_control-BJ-Kz8rX.png",prt="/assets/crm-CsLftmB2.png",mrt="/assets/deal_pipeline-XYgypvwv.png",grt="/assets/staging_studio-5iLDjnv0.png",yrt="/assets/coaching-CSQEA81I.png",xrt="/assets/marketing_studio-Brx1ZOnN.png",_rt=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Obe},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:prt},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:mrt},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:grt},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:yrt},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:xrt}];function vrt({slot:t}){return o.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[o.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[o.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),o.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),o.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),o.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?o.jsx("img",{src:t.src,alt:`LevelUp ${t.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):o.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[o.jsx(Ss,{className:"h-8 w-8 text-white/40"}),o.jsx("p",{className:"text-sm font-medium text-white/60",children:t.label}),o.jsx("p",{className:"text-xs px-6 text-center text-white/40",children:"Screenshot placeholder"})]}),o.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[o.jsx("span",{className:"font-semibold text-white",children:t.label})," — ",t.caption]})]})}const jd={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",popular:!1},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"],popular:!1}},brt=[{icon:hG,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:XO,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:po,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:f1,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:ep,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Yh,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],wrt=[{category:"Marketing Studio",icon:AC,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:yG,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:rLe,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:ALe,items:["AI Staging Studio","Video library & sharing","Screen recording","Virtual backgrounds","AI blog writer","YouTube → Blog","Ask AI assistant"]},{category:"Growth & Coaching",icon:XA,items:["Academy courses","Live weekly coaching","Coaching programs","1:1 coaching booking","Private community","Live events & workshops"]},{category:"Brokerage Tools",icon:Eo,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],Srt=[{icon:Al,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:Ss,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:zi,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:$Re,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:na,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:ZA,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:tp,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:NL,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],Trt=[{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."}],Ert=()=>{const{user:t,loading:e}=qn(),r=ma(),[n]=B0();P.useEffect(()=>{const X=window.location.host==="listings.relevelup.com",Q=window.location.pathname==="/";if(X&&Q){r("/public/listings",{replace:!0});return}},[r]);const[i,a]=P.useState(null),[c,s]=P.useState(null),[f,m]=P.useState(!1),[x,_]=P.useState(""),[T,E]=P.useState(""),[C,N]=P.useState(""),[R,D]=P.useState(!1),[M,B]=P.useState(!1),V=(X,Q=!1)=>{s({tier:X,skipTrial:Q}),m(!0)};urt(),P.useEffect(()=>{const X=window.location.host==="listings.relevelup.com",Q=location.pathname.startsWith("/public/");!e&&t&&!X&&!Q&&r("/dashboard")},[t,e,r,location.pathname]),P.useEffect(()=>{n.get("canceled")==="true"&&Jt.error("Checkout was canceled. Feel free to try again when you're ready!")},[n]);const G=async(X,Q=!1)=>{if(!x){Jt.error("Please enter your email address");return}if(!T.trim()){Jt.error("Please enter your full name");return}D(!0),a(X+(Q?"_direct":""));const re=drt();try{const{data:se,error:ue}=await Le.functions.invoke("create-checkout",{body:{tier:X,email:x,name:T.trim(),couponCode:C.trim()||void 0,skipTrial:Q,referralCode:re}});if(ue)throw ue;if(se!=null&&se.url)window.open(se.url,"_blank","noopener,noreferrer"),Jt.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(se){console.error("Checkout error:",se),Jt.error(se.message||"Failed to start checkout. Please try again.")}finally{D(!1),a(null),m(!1),s(null)}},W=()=>{c&&G(c.tier,c.skipTrial)};return e?o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#4a6b6d]",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-white border-t-transparent"})}):o.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[o.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:o.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[o.jsx("div",{className:"flex items-center",children:o.jsx("img",{src:xne,alt:"LevelUp",className:"h-8 md:h-10"})}),o.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[o.jsx(Ut,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var X;return(X=document.getElementById("features"))==null?void 0:X.scrollIntoView({behavior:"smooth"})},children:"Features"}),o.jsx(Ut,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var X;return(X=document.getElementById("pricing"))==null?void 0:X.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),o.jsx(Ut,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>r("/brokerage-solutions"),children:"For Brokerages"}),o.jsx(Ut,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>r("/blog"),children:"Blog"}),o.jsx(Ut,{onClick:()=>r("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),o.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[o.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; } } `}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),o.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]"}),o.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),o.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),o.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)]"}),o.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),o.jsxs("div",{className:"container mx-auto px-4 relative",children:[o.jsxs("div",{className:"max-w-5xl mx-auto text-center pt-20 md:pt-28 pb-10 space-y-8",children:[o.jsx("div",{className:"flex justify-center animate-fade-in",children:o.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:[o.jsx(Ss,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"The Agent Operating System — coaching, CRM & marketing in one"]})}),o.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",o.jsx("br",{className:"hidden sm:block"})," to get it done.",o.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."})]}),o.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."}),o.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-2 animate-fade-in",children:[o.jsxs(Ut,{size:"lg",onClick:()=>{var X;return(X=document.getElementById("free-trial"))==null?void 0:X.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",o.jsx(pc,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),o.jsx(Ut,{size:"lg",variant:"outline",onClick:()=>{var X;return(X=document.getElementById("features"))==null?void 0:X.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"})]}),o.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:[o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx(Xc,{className:"h-4 w-4 text-[#e6c878] fill-[#e6c878]"})," Built with agents' direct input"]}),o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx(NL,{className:"h-4 w-4 text-[#7fd4cc]"})," New tools added every month"]}),o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx(QA,{className:"h-4 w-4 text-white/60"})," Cancel anytime"]})]})]}),o.jsxs("div",{className:"relative max-w-5xl mx-auto pb-20 md:pb-28 px-2",children:[o.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}),o.jsxs("div",{className:"relative animate-[hero-float-slow_8s_ease-in-out_infinite]",children:[o.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:[o.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2.5 border-b border-white/10 bg-white/5",children:[o.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),o.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),o.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),o.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),o.jsx("img",{src:Obe,alt:"LevelUp Agent Command Center dashboard",className:"w-full h-auto block"})]}),o.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:[o.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#4aa8a0]/20",children:o.jsx(uS,{className:"h-5 w-5 text-[#7fd4cc]"})}),o.jsxs("span",{children:[o.jsx("span",{className:"block text-sm font-semibold text-white",children:"Smart Queue ready"}),o.jsx("span",{className:"block text-xs text-white/55",children:"5 follow-ups due today"})]})]}),o.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:[o.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-[#e6c878]/15",children:o.jsx(hG,{className:"h-5 w-5 text-[#e6c878]"})}),o.jsxs("span",{children:[o.jsx("span",{className:"block text-sm font-semibold text-white",children:"Weekly Reels delivered"}),o.jsx("span",{className:"block text-xs text-white/55",children:"Fresh scripts every Monday"})]})]}),o.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:[o.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-white/10",children:o.jsx(po,{className:"h-5 w-5 text-white/80"})}),o.jsxs("span",{children:[o.jsx("span",{className:"block text-sm font-semibold text-white",children:"Coaching booked"}),o.jsx("span",{className:"block text-xs text-white/55",children:"Meet link added automatically"})]})]})]})]})]})]}),o.jsx("section",{className:"py-20 bg-background",children:o.jsx("div",{className:"container mx-auto px-4",children:o.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[o.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."}),o.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[o.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),o.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),o.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),o.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),o.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[o.jsxs(Ut,{size:"lg",variant:"outline",onClick:()=>{var X;return(X=document.getElementById("brokerage"))==null?void 0:X.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[o.jsx(Eo,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),o.jsxs(Ut,{size:"lg",onClick:()=>{var X;return(X=document.getElementById("pricing"))==null?void 0:X.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[o.jsx(gc,{className:"mr-2 h-5 w-5"}),"Individual Membership"]})]})]})})}),o.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:o.jsxs("div",{className:"container mx-auto px-4",children:[o.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[o.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:[o.jsx(QRe,{className:"w-4 h-4"}),"40+ tools & counting"]}),o.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),o.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:brt.map((X,Q)=>o.jsxs(Hn,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[o.jsxs(Ju,{children:[o.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:o.jsx(X.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),o.jsx(ed,{className:"text-xl font-sans",children:X.title})]}),o.jsx(ii,{children:o.jsx("p",{className:"text-muted-foreground leading-relaxed",children:X.description})})]},Q))}),o.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:[o.jsx("div",{className:"absolute inset-0 opacity-10",children:o.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),o.jsxs("div",{className:"relative",children:[o.jsxs("div",{className:"text-center mb-10",children:[o.jsx("h3",{className:"text-2xl md:text-3xl font-bold text-white font-sans",children:"...and that's just the beginning"}),o.jsx("p",{className:"text-white/60 mt-2",children:"Dozens of purpose-built tools, all included with membership."})]}),o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-8",children:wrt.map(X=>o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-2.5 mb-4",children:[o.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-white/10",children:o.jsx(X.icon,{className:"h-4 w-4 text-white"})}),o.jsx("span",{className:"text-sm font-bold uppercase tracking-wider text-white/90",children:X.category})]}),o.jsx("ul",{className:"space-y-2.5",children:X.items.map(Q=>o.jsxs("li",{className:"flex items-center gap-2.5 text-white/70 text-sm",children:[o.jsx(Ao,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),Q]},Q))})]},X.category))}),o.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[o.jsx(Ss,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),o.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[o.jsx("div",{className:"absolute inset-0 opacity-10",children:o.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),o.jsxs("div",{className:"container mx-auto px-4 relative",children:[o.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-14",children:[o.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-white/70",children:"See it in action"}),o.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"}),o.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto text-lg",children:"This is what members open every morning."})]}),o.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10 max-w-6xl mx-auto",children:_rt.map(X=>o.jsx(vrt,{slot:X},X.key))})]})]}),o.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[o.jsx("div",{className:"absolute inset-0 opacity-10",children:o.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),o.jsxs("div",{className:"container mx-auto px-4 relative",children:[o.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[o.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:[o.jsx(Ss,{className:"w-4 h-4"}),"Included with Membership"]}),o.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",o.jsx("span",{className:"italic",children:"Agent OS"})]}),o.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."})]}),o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:Srt.map((X,Q)=>o.jsxs(Hn,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[o.jsxs(Ju,{className:"pb-3",children:[o.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:o.jsx(X.icon,{className:"w-6 h-6 text-white"})}),o.jsx(ed,{className:"text-lg font-semibold text-white",children:X.title})]}),o.jsx(ii,{children:o.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:X.description})})]},Q))}),o.jsx("div",{className:"text-center mt-12",children:o.jsxs(Ut,{size:"lg",onClick:()=>{var X;return(X=document.getElementById("pricing"))==null?void 0:X.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",o.jsx(pc,{className:"ml-2 w-5 h-5"})]})})]})]}),o.jsx("section",{id:"brokerage",className:"py-20 bg-[#4a6b6d]/5",children:o.jsx("div",{className:"container mx-auto px-4",children:o.jsx("div",{className:"max-w-6xl mx-auto",children:o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",children:[o.jsxs("div",{className:"space-y-6",children:[o.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:[o.jsx(Eo,{className:"w-4 h-4"}),"For Brokerages"]}),o.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",o.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),o.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."}),o.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((X,Q)=>o.jsxs("li",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center flex-shrink-0",children:o.jsx(Ao,{className:"w-4 h-4 text-[#4a6b6d]"})}),o.jsx("span",{className:"text-foreground",children:X})]},Q))}),o.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[o.jsxs(Ut,{size:"lg",onClick:()=>{var X;return(X=document.getElementById("pricing"))==null?void 0:X.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",o.jsx(th,{className:"ml-2 w-5 h-5"})]}),o.jsxs(Ut,{size:"lg",variant:"outline",onClick:()=>B(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[o.jsx(po,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),o.jsx("div",{className:"relative hidden md:block",children:o.jsx("img",{src:hrt,alt:"Scale Your Team from 5 to 500 Agents",className:"w-full rounded-3xl shadow-lg"})})]})})})}),o.jsx("section",{className:"py-20 bg-background",children:o.jsxs("div",{className:"container mx-auto px-4",children:[o.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[o.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Agents Love ",o.jsx("span",{className:"italic text-[#4a6b6d]",children:"LevelUp"})]}),o.jsx("p",{className:"text-lg text-muted-foreground",children:"See what top producers are saying about the platform."})]}),o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto",children:Trt.map((X,Q)=>o.jsx(Hn,{className:"bg-muted/30 border-0",children:o.jsxs(ii,{className:"pt-8",children:[o.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(re=>o.jsx(Xc,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},re))}),o.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',X.quote,'"']}),o.jsxs("div",{children:[o.jsx("p",{className:"font-semibold",children:X.name}),o.jsx("p",{className:"text-sm text-muted-foreground",children:X.role})]})]})},Q))})]})}),o.jsxs("section",{id:"free-trial",className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[o.jsx("div",{className:"absolute inset-0 opacity-10",children:o.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),o.jsx("div",{className:"container mx-auto px-4 relative",children:o.jsxs("div",{className:"max-w-3xl mx-auto text-center space-y-8",children:[o.jsxs("h2",{className:"text-3xl md:text-5xl font-bold text-white",children:["Start Your Free Trial ",o.jsx("span",{className:"italic",children:"Today"})]}),o.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."}),o.jsx("div",{className:"pt-4",children:o.jsxs(Ut,{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:()=>V("individual_agent"),children:["Start Free Trial",o.jsx(pc,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),o.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:o.jsxs("div",{className:"container mx-auto px-4",children:[o.jsxs("div",{className:"text-center mb-16",children:[o.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",o.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),o.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."})]}),o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8 max-w-4xl mx-auto",children:[o.jsxs(Hn,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[o.jsxs(Ju,{className:"pb-4",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/10 flex items-center justify-center",children:o.jsx(gc,{className:"w-5 h-5 text-[#4a6b6d]"})}),o.jsx(ed,{className:"text-xl font-sans",children:jd.individual_agent.name})]}),o.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[o.jsx("span",{className:"text-5xl font-bold",children:jd.individual_agent.price}),o.jsx("span",{className:"text-muted-foreground text-lg",children:jd.individual_agent.period})]}),o.jsx(dk,{className:"text-base mt-2",children:jd.individual_agent.description}),o.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:[o.jsx(mc,{className:"w-4 h-4"}),jd.individual_agent.trial]})]}),o.jsx(ii,{className:"flex-1 pt-0",children:o.jsx("ul",{className:"space-y-3",children:jd.individual_agent.features.map((X,Q)=>o.jsxs("li",{className:"flex items-center gap-3",children:[o.jsx(Ao,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),o.jsx("span",{children:X})]},Q))})}),o.jsxs(y6,{className:"flex flex-col gap-3 pt-4",children:[o.jsx(Ut,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>V("individual_agent"),children:"Start Free Trial"}),o.jsx(Ut,{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:()=>V("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),o.jsxs(Hn,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl bg-background",children:[o.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"}),o.jsxs(Ju,{className:"pb-4 pt-8",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-[#4a6b6d]/20 flex items-center justify-center",children:o.jsx(Eo,{className:"w-5 h-5 text-[#4a6b6d]"})}),o.jsxs("div",{children:[o.jsx(ed,{className:"text-xl font-sans",children:jd.brokerage_over_25.name}),o.jsx("span",{className:"text-sm text-muted-foreground",children:jd.brokerage_over_25.subtitle})]})]}),o.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[o.jsx("span",{className:"text-5xl font-bold",children:jd.brokerage_over_25.price}),o.jsx("span",{className:"text-muted-foreground text-lg",children:jd.brokerage_over_25.period})]}),o.jsx(dk,{className:"text-base mt-2",children:jd.brokerage_over_25.description})]}),o.jsx(ii,{className:"flex-1 pt-0",children:o.jsx("ul",{className:"space-y-3",children:jd.brokerage_over_25.features.map((X,Q)=>o.jsxs("li",{className:"flex items-center gap-3",children:[o.jsx(Ao,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),o.jsx("span",{children:X})]},Q))})}),o.jsxs(y6,{className:"pt-4 flex flex-col gap-3",children:[o.jsx(Ut,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>V("brokerage_over_25"),children:"Get Started"}),o.jsxs(Ut,{variant:"link",className:"text-[#4a6b6d]",onClick:()=>r("/brokerage-solutions"),children:["Explore all brokerage management tools ",o.jsx(pc,{className:"ml-1 w-4 h-4"})]})]})]})]})]})}),o.jsx("section",{id:"neutrality",className:"py-20 bg-background",children:o.jsx("div",{className:"container mx-auto px-4",children:o.jsxs("div",{className:"max-w-4xl mx-auto",children:[o.jsxs("div",{className:"text-center mb-12",children:[o.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:[o.jsx(QA,{className:"w-4 h-4"}),"Our Commitment"]}),o.jsxs("h2",{className:"text-3xl md:text-4xl font-sans font-bold",children:["LevelUp Brokerage ",o.jsx("span",{className:"italic text-[#4a6b6d]",children:"Neutrality Policy"})]}),o.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."})]}),o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[o.jsx(Hn,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:o.jsxs(ii,{className:"p-6 flex items-start gap-4",children:[o.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:o.jsx(Eo,{className:"w-5 h-5 text-[#4a6b6d]"})}),o.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),o.jsx(Hn,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:o.jsxs(ii,{className:"p-6 flex items-start gap-4",children:[o.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:o.jsx(zy,{className:"w-5 h-5 text-[#4a6b6d]"})}),o.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not share member information with any brokerage."})]})}),o.jsx(Hn,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:o.jsxs(ii,{className:"p-6 flex items-start gap-4",children:[o.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:o.jsx(SLe,{className:"w-5 h-5 text-[#4a6b6d]"})}),o.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not recruit brokerage partners' agents."})]})}),o.jsx(Hn,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:o.jsxs(ii,{className:"p-6 flex items-start gap-4",children:[o.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:o.jsx(ep,{className:"w-5 h-5 text-[#4a6b6d]"})}),o.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."})]})})]})]})})}),o.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[o.jsx("div",{className:"absolute inset-0 opacity-10",children:o.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),o.jsx("div",{className:"container mx-auto px-4 relative",children:o.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[o.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),o.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."}),o.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[o.jsxs(Ut,{size:"lg",onClick:()=>{var X;return(X=document.getElementById("pricing"))==null?void 0:X.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",o.jsx(pc,{className:"ml-2 w-5 h-5"})]}),o.jsx(Ut,{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"})]})]})})]}),o.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:o.jsx("div",{className:"container mx-auto px-4",children:o.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[o.jsx("img",{src:xne,alt:"LevelUp",className:"h-8"}),o.jsxs("p",{className:"text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),o.jsxs("div",{className:"flex items-center gap-6",children:[o.jsx("a",{href:"/brokerage-solutions",className:"text-white/60 hover:text-white transition-colors text-sm",children:"For Brokerages"}),o.jsx("a",{href:"/blog",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Blog"}),o.jsx("a",{href:"/privacy-policy",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Privacy Policy"}),o.jsx("a",{href:"mailto:support@relevelup.com",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Contact Support"})]})]})})}),o.jsx(frt,{open:M,onOpenChange:B}),o.jsx(ro,{open:f,onOpenChange:m,children:o.jsxs($a,{className:"sm:max-w-md",children:[o.jsxs(ul,{children:[o.jsx(Go,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),o.jsx(ld,{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"})]}),o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsxs("div",{children:[o.jsxs(Mr,{htmlFor:"dialog-name",children:["Full Name ",o.jsx("span",{className:"text-red-500",children:"*"})]}),o.jsx(Ur,{id:"dialog-name",type:"text",placeholder:"John Smith",value:T,onChange:X=>E(X.target.value),className:"mt-1",required:!0})]}),o.jsxs("div",{children:[o.jsxs(Mr,{htmlFor:"dialog-email",children:["Email Address ",o.jsx("span",{className:"text-red-500",children:"*"})]}),o.jsx(Ur,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:x,onChange:X=>_(X.target.value),className:"mt-1",required:!0})]}),o.jsxs("div",{children:[o.jsxs(Mr,{htmlFor:"dialog-coupon",children:["Discount Code ",o.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),o.jsx(Ur,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:C,onChange:X=>N(X.target.value),className:"mt-1"})]})]}),o.jsx(Ut,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:W,disabled:R,children:R?"Loading...":"Continue to Checkout"})]})})]})},Art="/__l5e/assets-v1/68014836-514e-4076-834c-9b66112cd2a0/levelup-logo-horizontal.png",krt=ox({email:Xi().email("Invalid email address"),password:Xi().min(6,"Password must be at least 6 characters")}),Mbe="https://dashboard.relevelup.com",CN="/oauth-connect",Crt=`${Mbe}/profile?reset=true`,UR="levelupOAuthRouteHistory";function _ne(t){return t.startsWith("/")&&!t.startsWith("//")&&!t.includes("://")}function jrt(t){const e=Date.now(),r=15e3;try{const a=[...JSON.parse(sessionStorage.getItem(UR)??"[]").filter(s=>e-s.ats.route));return a.length>=6&&c.has("auth")&&c.has("consent")}catch{return sessionStorage.setItem(UR,JSON.stringify([{route:t,at:e}])),!1}}function Irt(){sessionStorage.removeItem(UR)}const vne=()=>{const{signIn:t,user:e,loading:r}=qn(),n=(e==null?void 0:e.id)??null,i=ma(),[a]=B0(),c=a.get("authorization_id")??"",s=a.get("next")??"",[f,m]=P.useState(!1),[x,_]=P.useState({}),[T,E]=P.useState(""),[C,N]=P.useState(!1),[R,D]=P.useState(!1),[M,B]=P.useState(null),[V,G]=P.useState(null),[W,X]=P.useState(!1),[Q,re]=P.useState(!1),[se,ue]=P.useState(()=>{if(a.get("paused")!=="1")return null;let Ae="";try{Ae=sessionStorage.getItem("accountPausedReason")||""}catch{}return Ae?`Your account is paused. ${Ae}`:"Your account is paused. Please contact LevelUp support to reactivate it."}),_e=P.useRef(!1);P.useEffect(()=>{if(c&&/(\.lovable\.app|\.lovableproject\.com)$/.test(window.location.hostname)){const Ae=new URL("/auth",Mbe);Ae.searchParams.set("next",`${CN}?authorization_id=${encodeURIComponent(c)}`),window.location.replace(Ae.toString());return}if(c){const Ae=`${CN}?authorization_id=${encodeURIComponent(c)}`;sessionStorage.setItem("redirectAfterLogin",Ae);return}s&&_ne(s)&&sessionStorage.setItem("redirectAfterLogin",s)},[c,s]),P.useEffect(()=>{if(r||!n||_e.current)return;const Ae=c?`${CN}?authorization_id=${encodeURIComponent(c)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!_ne(Ae)){sessionStorage.removeItem("redirectAfterLogin"),_e.current=!0,i("/dashboard",{replace:!0});return}const we=Ae.startsWith(CN)||Ae.startsWith("/oauth/consent")||Ae.startsWith("/.lovable/oauth/consent");if(we&&jrt("auth")){B("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}_e.current=!0,we||(Irt(),sessionStorage.removeItem("redirectAfterLogin")),i(Ae,{replace:!0})},[c,r,i,n]);const Se=async Ae=>{Ae.preventDefault(),_({}),ue(null),G(null),X(!1),m(!0);const we=new FormData(Ae.currentTarget),ge=we.get("email"),Ne=we.get("password");try{krt.parse({email:ge,password:Ne}),await t(ge,Ne)}catch(Ie){if(Ie instanceof Pqe){const Te={};Ie.issues.forEach(be=>{be.path[0]&&(Te[be.path[0]]=be.message)}),_(Te)}else if(Ie instanceof Error&&Ie.name==="AccountPaused")ue(Ie.message);else if(ge)try{const{data:Te}=await Le.functions.invoke("account-activation-status",{body:{email:ge}});Te!=null&&Te.needsActivation&&G(ge)}catch{}}finally{m(!1)}},ve=async()=>{if(V){re(!0);try{const{data:Ae,error:we}=await Le.functions.invoke("send-password-reset",{body:{email:V,variant:"activation"}});if(we)throw we;if((Ae==null?void 0:Ae.sent)===!1)throw new Error("We couldn't send the activation email. Please try again in a moment or contact support.");X(!0),Jt.success("Activation email sent! Check your inbox.")}catch(Ae){Jt.error(Ae instanceof Error?Ae.message:"Failed to send activation email")}finally{re(!1)}}},Oe=async()=>{if(!T){Jt.error("Please enter your email address");return}N(!0);try{const{data:Ae,error:we}=await Le.functions.invoke("send-password-reset",{body:{email:T.trim().toLowerCase(),redirectTo:Crt}});if(we)throw we;if((Ae==null?void 0:Ae.sent)===!1){Jt.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}Jt.success("Password reset email sent! Check your inbox."),D(!1),E("")}catch(Ae){Jt.error(Ae instanceof Error?Ae.message:"Failed to send reset email")}finally{N(!1)}};return o.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[o.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]",children:o.jsxs("div",{className:"absolute inset-0 opacity-30",children:[o.jsx("div",{className:"absolute top-0 left-0 w-96 h-96 bg-white/10 rounded-full blur-3xl animate-pulse"}),o.jsx("div",{className:"absolute bottom-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),o.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"}})]})}),o.jsxs("div",{className:"relative z-10 flex flex-col min-h-screen",children:[o.jsx("header",{className:"p-6",children:o.jsxs(cs,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[o.jsx(By,{className:"h-4 w-4"}),"Back to Home"]})}),o.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:o.jsxs("div",{className:"w-full max-w-md",children:[o.jsx("div",{className:"flex justify-center mb-8",children:o.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:o.jsx("img",{src:Art,alt:"LevelUp",className:"h-12 w-auto"})})}),o.jsxs(Hn,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[o.jsxs(Ju,{className:"space-y-1 text-center pb-4",children:[o.jsx(ed,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),o.jsx(dk,{className:"text-gray-600",children:M||"Sign in to access your dashboard"})]}),o.jsxs(ii,{children:[se&&o.jsxs("div",{className:"mb-4 rounded-lg border border-amber-300 bg-amber-50 p-4 text-left",children:[o.jsx("p",{className:"text-sm font-semibold text-amber-900",children:"Account paused"}),o.jsx("p",{className:"mt-1 text-sm text-amber-800",children:se}),o.jsx("a",{href:"mailto:support@relevelup.com",className:"mt-2 inline-block text-sm font-medium text-amber-900 underline",children:"Contact support"})]}),V&&o.jsxs("div",{className:"mb-4 rounded-lg border border-[#4a6b6d]/30 bg-[#f2f7f7] p-4 text-left",children:[o.jsx("p",{className:"text-sm font-semibold text-[#2a4347]",children:"You haven't set a password yet"}),o.jsx("p",{className:"mt-1 text-sm text-gray-700",children:W?`We just emailed ${V} a link to set your password and sign in. Check your inbox (and spam folder).`:`Your LevelUp account for ${V} is ready — it just needs a password. We'll email you a link to set one.`}),!W&&o.jsx(Ut,{type:"button",onClick:ve,disabled:Q,className:"mt-3 bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",children:Q?"Sending...":"Email me a set-password link"})]}),o.jsxs("form",{onSubmit:Se,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mr,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),o.jsx(Ur,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),x.email&&o.jsx("p",{className:"text-sm text-red-600",children:x.email})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mr,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),o.jsx(Ur,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),x.password&&o.jsx("p",{className:"text-sm text-red-600",children:x.password})]}),o.jsx(Ut,{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:f,children:f?"Signing in...":"Sign In"}),o.jsxs(ro,{open:R,onOpenChange:D,children:[o.jsx(Kge,{asChild:!0,children:o.jsx(Ut,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),o.jsxs($a,{className:"bg-white",children:[o.jsxs(ul,{children:[o.jsx(Go,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),o.jsx(ld,{className:"text-gray-600",children:"Enter your email address and we'll send you a link to reset your password."})]}),o.jsxs("div",{className:"space-y-4 pt-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mr,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),o.jsx(Ur,{id:"reset-email",type:"email",placeholder:"your@email.com",value:T,onChange:Ae=>E(Ae.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),o.jsx(Ut,{onClick:Oe,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:C,children:C?"Sending...":"Send Reset Link"})]})]})]})]})]})]}),o.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",o.jsx(cs,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},L7=()=>wr({queryKey:["lead-sources"],queryFn:async()=>{const{data:t,error:e}=await Le.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(e)throw e;return t}}),Prt=()=>{const t=Nr(),{user:e}=qn();return Cr({mutationFn:async r=>{const{data:n}=await Le.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",r.trim()),i=(n||[]).find(s=>s.name.toLowerCase()===r.trim().toLowerCase()&&!0);if(i)throw new Error(`Lead source "${i.name}" already exists`);const{data:a,error:c}=await Le.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"]}),Jt.success("Lead source added")},onError:r=>{Jt.error("Failed to add lead source"),console.error(r)}})},_Vt=()=>{const t=Nr();return Cr({mutationFn:async({id:e,name:r})=>{const{error:n}=await Le.from("lead_sources").update({name:r}).eq("id",e);if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),Jt.success("Lead source updated")},onError:e=>{Jt.error(e.message||"Failed to update lead source")}})},vVt=()=>{const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("lead_sources").update({is_active:!1}).eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["lead-sources"]}),Jt.success("Lead source removed")},onError:e=>{Jt.error(e.message||"Failed to remove lead source")}})},Fbe=(t,e)=>{const{user:r,isAdmin:n}=qn(),i=n&&e?e:r==null?void 0:r.id;return wr({queryKey:["scorecard-transactions",t,i],queryFn:async()=>{let a=Le.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:s}=await a;if(s)throw s;return c},enabled:!!i})},Nrt=t=>{const{user:e,isAdmin:r}=qn(),n=r&&t?t:e==null?void 0:e.id;return wr({queryKey:["scorecard-transactions-all",n],queryFn:async()=>{const{data:i,error:a}=await Le.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})},D7=()=>{const t=Nr(),{user:e}=qn();return Cr({mutationFn:async r=>{const{data:n,error:i}=await Le.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"]}),Jt.success("Transaction added")},onError:r=>{Jt.error("Failed to add transaction"),console.error(r)}})},Rrt=()=>{const t=Nr();return Cr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Le.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"]}),Jt.success("Transaction updated")},onError:e=>{Jt.error("Failed to update transaction"),console.error(e)}})},Lrt=()=>{const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("scorecard_transactions").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["scorecard-transactions"]}),t.invalidateQueries({queryKey:["scorecard-transactions-all"]}),Jt.success("Transaction deleted")},onError:e=>{Jt.error("Failed to delete transaction"),console.error(e)}})},Drt=(t,e)=>{const{user:r,isAdmin:n}=qn(),i=n&&e?e:r==null?void 0:r.id;return wr({queryKey:["scorecard-goals",t,i],queryFn:async()=>{const{data:a,error:c}=await Le.from("scorecard_goals").select("*").eq("owner_user_id",i).eq("year",t).maybeSingle();if(c)throw c;return a},enabled:!!i})},Ort=()=>{const t=Nr(),{user:e}=qn();return Cr({mutationFn:async r=>{const{data:n,error:i}=await Le.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]}),Jt.success("Goals saved")},onError:r=>{Jt.error("Failed to save goals"),console.error(r)}})},uF=()=>{const{user:t}=qn();return wr({queryKey:["scorecard-settings",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await Le.from("scorecard_settings").select("*").eq("user_id",t.id).maybeSingle();if(r)throw r;return e},enabled:!!(t!=null&&t.id)})},Mrt=()=>{const t=Nr(),{user:e}=qn();return Cr({mutationFn:async r=>{const{data:n,error:i}=await Le.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"]}),Jt.success("Settings saved")},onError:r=>{Jt.error("Failed to save settings"),console.error(r)}})},Frt=(t,e)=>{const{data:r,isLoading:n}=Fbe(t,e),{data:i,isLoading:a}=Nrt(e),{data:c}=uF(),s=(c==null?void 0:c.show_commission)??!0,f=m=>{if(!m||m.length===0)return{totalTransactions:0,buyerCount:0,sellerCount:0,totalVolume:0,averagePrice:0,totalCommission:0,totalNetToAgent:0,topLeadSource:null,transactionsByMonth:[],leadSourceBreakdown:[]};const x=m.filter(G=>G.transaction_type==="buyer").length,_=m.filter(G=>G.transaction_type==="seller").length,T=m.reduce((G,W)=>G+Number(W.sale_price),0),E=m.reduce((G,W)=>G+(Number(W.commission_amount)||0),0),C=m.reduce((G,W)=>{const X=Number(W.commission_amount)||0;if(!X)return G;let Q=X;return W.brokerage_split_pct&&(Q-=X*(W.brokerage_split_pct/100)),W.team_split_pct&&(Q-=X*(W.team_split_pct/100)),W.franchise_fee_pct&&(Q-=X*(W.franchise_fee_pct/100)),W.referral_fee_pct&&(Q-=X*(W.referral_fee_pct/100)),W.transaction_fee&&(Q-=W.transaction_fee),G+Math.max(0,Q)},0),N={};m.forEach(G=>{var X;const W=((X=G.lead_source)==null?void 0:X.name)||"Unknown";N[W]=(N[W]||0)+1});const R=Object.entries(N).map(([G,W])=>({name:G,count:W})).sort((G,W)=>W.count-G.count),D=R[0]||null,M={};m.forEach(G=>{const W=j1(G.close_date).toLocaleString("default",{month:"short"});M[W]=(M[W]||0)+1});const V=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(G=>({month:G,count:M[G]||0}));return{totalTransactions:m.length,buyerCount:x,sellerCount:_,totalVolume:T,averagePrice:m.length>0?T/m.length:0,totalCommission:s?E:0,totalNetToAgent:s?C:0,topLeadSource:D,transactionsByMonth:V,leadSourceBreakdown:R}};return{yearStats:f(r),lifetimeStats:f(i),isLoading:n||a,showCommission:s}},bVt=()=>{const{isAdmin:t}=qn();return wr({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:e,error:r}=await Le.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 Le.from("profiles").select("id, name, email").in("id",n);if(a)throw a;return i},enabled:t})},O7=P.forwardRef(({className:t,...e},r)=>o.jsx("div",{className:"relative w-full overflow-auto",children:o.jsx("table",{ref:r,className:sr("w-full caption-bottom text-sm",t),...e})}));O7.displayName="Table";const M7=P.forwardRef(({className:t,...e},r)=>o.jsx("thead",{ref:r,className:sr("[&_tr]:border-b",t),...e}));M7.displayName="TableHeader";const F7=P.forwardRef(({className:t,...e},r)=>o.jsx("tbody",{ref:r,className:sr("[&_tr:last-child]:border-0",t),...e}));F7.displayName="TableBody";const Brt=P.forwardRef(({className:t,...e},r)=>o.jsx("tfoot",{ref:r,className:sr("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...e}));Brt.displayName="TableFooter";const Tk=P.forwardRef(({className:t,...e},r)=>o.jsx("tr",{ref:r,className:sr("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",t),...e}));Tk.displayName="TableRow";const $l=P.forwardRef(({className:t,...e},r)=>o.jsx("th",{ref:r,className:sr("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",t),...e}));$l.displayName="TableHead";const Ul=P.forwardRef(({className:t,...e},r)=>o.jsx("td",{ref:r,className:sr("p-4 align-middle [&:has([role=checkbox])]:pr-0",t),...e}));Ul.displayName="TableCell";const zrt=P.forwardRef(({className:t,...e},r)=>o.jsx("caption",{ref:r,className:sr("mt-4 text-sm text-muted-foreground",t),...e}));zrt.displayName="TableCaption";const fV="boost";function G0(t,e){typeof window>"u"||window.dispatchEvent(new CustomEvent(fV,{detail:{type:t,requestId:e}}))}function wVt(t){const e=r=>{const n=r.detail;t(typeof n=="string"?{type:n}:n)};return window.addEventListener(fV,e),()=>window.removeEventListener(fV,e)}const SVt=["Idle","Thinking","Listening","Working","Success","Alert","Celebration","Pointing","Wave","Sleeping"],TVt=new Set(["Idle","Thinking","Listening","Working","Sleeping"]),EVt={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}},bne={hidden:!1,paused:!1,reduceMotion:!1,muteAnnouncements:!1},Bbe=new Map,zbe=t=>`boost:prefs:${t}`;function AVt(t){try{const e=window.localStorage.getItem(zbe(t));if(e)return{...bne,...JSON.parse(e)}}catch{}return Bbe.get(t)??bne}function kVt(t,e){Bbe.set(t,e);try{window.localStorage.setItem(zbe(t),JSON.stringify(e))}catch{}}let T2=null;function CVt(){var t;if(T2!==null)return T2;try{const e=document.createElement("canvas"),r=e.getContext("webgl2")||e.getContext("webgl");T2=!!r,(t=r==null?void 0:r.getExtension("WEBGL_lose_context"))==null||t.loseContext()}catch{T2=!1}return T2}const B7=()=>wr({queryKey:["relationship-types"],queryFn:async()=>{const{data:t,error:e}=await Le.from("relationship_types").select("*").order("sort_order");if(e)throw e;return t}}),jVt=()=>{const t=Ji(),e=1e3;return wr({queryKey:["innercircle-contacts-lite",t],queryFn:async()=>{const r=[];let n=0;for(;;){const{data:i,error:a}=await Le.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=Ji(),r=1e3,n=async i=>{const a=[];let c=0;for(;;){const{data:s,error:f}=await i.range(c,c+r-1);if(f)throw f;const m=s??[];if(a.push(...m),m.length{let i=Le.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(E=>E.id),s=Array.from(new Set(a.map(E=>E.lead_source_id).filter(E=>!!E))),f=(E,C=250)=>{const N=[];for(let R=0;R{const{data:C,error:N}=await Le.from("innercircle_contact_tags").select("id, contact_id, relationship_type_id, relationship_type:relationship_types(*)").in("contact_id",E);if(N)throw N;return C??[]})),Promise.all(f(s).map(async E=>{const{data:C,error:N}=await Le.from("lead_sources").select("id, name").in("id",E);if(N)throw N;return C??[]}))]),_=new Map;m.flat().forEach(E=>{const C=_.get(E.contact_id)??[];C.push(E),_.set(E.contact_id,C)});const T=new Map(x.flat().map(E=>[E.id,E]));return a.map(E=>({...E,lead_source_ref:E.lead_source_id?T.get(E.lead_source_id)??null:null,tags:_.get(E.id)??[]}))},enabled:!!e,staleTime:10*60*1e3})},IVt=t=>wr({queryKey:["innercircle-contact",t],queryFn:async()=>{const{data:e,error:r}=await Le.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}),PVt=()=>{const t=Ji();return wr({queryKey:["innercircle-contact-counts",t],queryFn:async()=>{const{data:e,error:r}=await Le.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})},$rt=()=>{const t=Nr(),e=Ji();return Cr({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:s}=await Le.from("innercircle_contacts").insert(a).select().single();if(s)throw s;if(n&&n.length>0){const{error:f}=await Le.from("innercircle_contact_tags").insert(n.map(m=>({contact_id:c.id,relationship_type_id:m})));if(f)throw f}return c},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),G0("contact_created"),Ts({title:"Contact created successfully"})},onError:r=>{Ts({title:"Error creating contact",description:r.message,variant:"destructive"})}})},NVt=()=>{const t=Nr();return Cr({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"],s={...a};for(const x of Object.keys(s)){const _=s[x];(_===""||typeof _=="string"&&c.includes(x)&&_.trim()==="")&&(s[x]=null)}const{data:f,error:m}=await Le.from("innercircle_contacts").update(s).eq("id",e).select().single();if(m)throw m;if(n!==void 0&&(await Le.from("innercircle_contact_tags").delete().eq("contact_id",e),n.length>0)){const{error:x}=await Le.from("innercircle_contact_tags").insert(n.map(_=>({contact_id:e,relationship_type_id:_})));if(x)throw x}return f},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),G0("contact_created"),Ts({title:"Contact updated successfully"})},onError:e=>{Ts({title:"Error updating contact",description:e.message,variant:"destructive"})}})},RVt=()=>{const t=Nr();return Cr({mutationFn:async({contactId:e,spouseContactId:r})=>{if(r){const{error:n}=await Le.from("innercircle_contacts").update({spouse_contact_id:r}).eq("id",e);if(n)throw n;const{error:i}=await Le.from("innercircle_contacts").update({spouse_contact_id:e}).eq("id",r);if(i)throw i}else{const{data:n}=await Le.from("innercircle_contacts").select("spouse_contact_id").eq("id",e).single(),i=n==null?void 0:n.spouse_contact_id,{error:a}=await Le.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",e);if(a)throw a;if(i){const{error:c}=await Le.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"]}),Ts({title:"Spouse link updated"})},onError:e=>{Ts({title:"Error linking spouse",description:e.message,variant:"destructive"})}})},LVt=()=>{const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("innercircle_contacts").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["innercircle-contacts"]}),t.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Ts({title:"Contact deleted successfully"})},onError:e=>{Ts({title:"Error deleting contact",description:e.message,variant:"destructive"})}})},DVt=()=>{const t=Nr();return Cr({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"]})}})},OVt=()=>wr({queryKey:["action-types"],queryFn:async()=>{const{data:t,error:e}=await Le.from("action_types").select("*").order("sort_order");if(e)throw e;return t}}),MVt=t=>wr({queryKey:["action-scripts",t],queryFn:async()=>{let e=Le.from("action_scripts").select("*, action_type:action_types(*)");const{data:r,error:n}=await e;if(n)throw n;return r}}),FVt=()=>wr({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:t,error:e}=await Le.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(e)throw e;return t}}),BVt=()=>{const t=Nr(),e=Ji();return Cr({mutationFn:async({name:r,description:n})=>{const{data:i,error:a}=await Le.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"]}),Ts({title:"Plan created successfully"})},onError:r=>{Ts({title:"Error creating plan",description:r.message,variant:"destructive"})}})},zVt=()=>{const t=Nr(),e=Ji();return Cr({mutationFn:async({sourcePlanId:r,newName:n})=>{const{data:i,error:a}=await Le.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:s}=await Le.from("touchpoint_plans").insert({name:n,description:i.description,owner_user_id:e,active:!0,is_template:!1}).select().single();if(s)throw s;if(i.items&&i.items.length>0){const f=i.items.map(x=>({plan_id:c.id,month_number:x.month_number,action_type_id:x.action_type_id,default_script_id:x.default_script_id,notes:x.notes})),{error:m}=await Le.from("touchpoint_plan_items").insert(f);if(m)throw m}return c},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),Ts({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:r=>{Ts({title:"Error duplicating plan",description:r.message,variant:"destructive"})}})},$Vt=()=>{const t=Nr();return Cr({mutationFn:async({id:e,name:r,description:n})=>{const{data:i,error:a}=await Le.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"]}),Ts({title:"Plan updated successfully"})}})},UVt=()=>{const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("touchpoint_plans").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["touchpoint-plans"]}),Ts({title:"Plan deleted successfully"})}})},VVt=()=>{const t=Nr();return Cr({mutationFn:async({planId:e,items:r})=>{if(await Le.from("touchpoint_plan_items").delete().eq("plan_id",e),r.length>0){const{error:n}=await Le.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"]}),Ts({title:"Plan schedule updated"})}})},qVt=()=>{const t=Nr();return Cr({mutationFn:async({actionTypeId:e,title:r,scriptBody:n,emailSubject:i,tone:a})=>{const{data:{user:c}}=await Le.auth.getUser(),{data:s,error:f}=await Le.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(f)throw f;return s},onSuccess:()=>{t.invalidateQueries({queryKey:["action-scripts"]}),Ts({title:"Script created successfully"})},onError:e=>{Ts({title:"Error creating script",description:e.message,variant:"destructive"})}})},GVt=()=>{const t=Ji();return wr({queryKey:["user-plan-enrollments",t],queryFn:async()=>{const{data:e,error:r}=await Le.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(r)throw r;return e},enabled:!!t})},HVt=()=>{const t=Nr(),e=Ji();return Cr({mutationFn:async({planId:r,relationshipTypeId:n,active:i})=>{const{data:a}=await Le.from("user_plan_enrollments").select("id").eq("plan_id",r).eq("relationship_type_id",n).maybeSingle();if(a){const{error:c}=await Le.from("user_plan_enrollments").update({active:i}).eq("id",a.id);if(c)throw c}else if(i){const{error:c}=await Le.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"]}),Ts({title:"Plan enrollment updated"})}})},Ube=(t=7)=>{const e=Ji();return wr({queryKey:["contact-touch-logs",e,t],queryFn:async()=>{const r=new Date;r.setDate(r.getDate()-t);const{data:n,error:i}=await Le.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})},Urt=()=>{const t=Ji();return wr({queryKey:["contacts-last-touch",t],queryFn:async()=>{const{data:e,error:r}=await Le.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})},WVt=(t=90)=>{const{data:e}=$be(),{data:r}=Urt();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=Nr(),e=Ji();return Cr({mutationFn:async({contactId:r,actionTypeId:n,scriptUsedId:i,notes:a,completedAt:c})=>{const{data:s,error:f}=await Le.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(f)throw f;return s},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"]}),G0("task_completed"),Ts({title:"Action completed!"});try{const[c,s]=await Promise.all([Le.from("innercircle_contacts").select("email").eq("id",n.contactId).single(),Le.from("action_types").select("name").eq("id",n.actionTypeId).single()]),f=(i=c.data)==null?void 0:i.email,m=((a=s.data)==null?void 0:a.name)||"Touch";/pop[\s-]?by/i.test(m)&&Le.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"]})}),f&&Le.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:f,touch_type:m,touch_notes:n.notes||null,touch_date:n.completedAt||r.completed_at}}).catch(()=>{})}catch{}}})},Vbe="agentos_weekly_touch_goal",wne=20,Vrt=()=>{if(typeof window>"u")return wne;const t=localStorage.getItem(Vbe);if(t){const e=parseInt(t,10);if(!isNaN(e)&&e>0)return e}return wne},YVt=t=>{localStorage.setItem(Vbe,t.toString())},ZVt=()=>{const{data:t}=Ube(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(f=>new Date(f.completed_at).toDateString()));let s=new Date(e);for(;c.has(s.toDateString());)i++,s.setDate(s.getDate()-1)}const a=Vrt();return{actionsThisWeek:n,weeklyGoal:a,streak:i,progress:Math.min(n/a*100,100)}},qrt=()=>{const t=Ji();return wr({queryKey:["contact-plan-cycles",t],queryFn:async()=>{const{data:e,error:r}=await Le.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})},XVt=()=>{const t=Nr();return Ji(),Cr({mutationFn:async()=>{var f;const{data:e}=await Le.from("user_plan_enrollments").select("*").eq("active",!0);if(!e||e.length===0)return;const{data:r}=await Le.auth.getUser(),n=(f=r==null?void 0:r.user)==null?void 0:f.id;if(!n)return;const{data:i}=await Le.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",n);if(!i)return;const{data:a}=await Le.from("contact_plan_cycles").select("contact_id, plan_id"),c=new Set((a==null?void 0:a.map(m=>`${m.contact_id}-${m.plan_id}`))||[]),s=[];for(const m of i)for(const x of m.tags||[]){const _=e.find(T=>T.relationship_type_id===x.relationship_type_id);_&&!c.has(`${m.id}-${_.plan_id}`)&&s.push({contact_id:m.id,plan_id:_.plan_id,relationship_type_id:x.relationship_type_id})}if(s.length>0){const{error:m}=await Le.from("contact_plan_cycles").insert(s);if(m)throw m}return s.length},onSuccess:e=>{t.invalidateQueries({queryKey:["contact-plan-cycles"]}),e&&e>0&&Ts({title:`${e} contact(s) enrolled in plans`})}})},QVt=()=>{const t=Ji(),{data:e}=qrt(),{data:r}=Ube(30);return wr({queryKey:["today-actions",t,e==null?void 0:e.length,r==null?void 0:r.length],queryFn:async()=>{var C;if(!e||e.length===0)return[];const{data:n}=await Le.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),i=new Set((n==null?void 0:n.map(N=>N.contact_id))||[]),a=new Date,c=[],s=new Date(a.getFullYear(),a.getMonth(),1),f=new Set((r==null?void 0:r.filter(N=>new Date(N.completed_at)>=s).map(N=>`${N.contact_id}-${N.action_type_id}`))||[]);for(const N of e){if(!((C=N.plan)!=null&&C.items)||N.plan.items.length===0||!N.contact||i.has(N.contact_id))continue;const R=new Date(N.cycle_start_date),M=Math.floor((a.getTime()-R.getTime())/(30.44*24*60*60*1e3))%12+1,B=N.plan.items.find(V=>V.month_number===M);if(B&&B.action_type){const V=`${N.contact_id}-${B.action_type_id}`;if(!f.has(V)){const{data:G}=await Le.from("relationship_types").select("name").eq("id",N.relationship_type_id).single();c.push({contact:N.contact,actionType:B.action_type,script:B.default_script||void 0,planName:N.plan.name,relationshipTypeName:(G==null?void 0:G.name)||"",monthNumber:M})}}}const m=5,x=a.getDate(),_=c.sort((N,R)=>N.contact.first_name.localeCompare(R.contact.first_name)),T=(x-1)%Math.max(1,_.length);return[..._.slice(T),..._.slice(0,T)].slice(0,m)},enabled:!!t&&!!e})};var dF="Popover",[qbe,JVt]=Ho(dF,[nx]),rj=nx(),[Grt,hx]=qbe(dF),Gbe=t=>{const{__scopePopover:e,children:r,open:n,defaultOpen:i,onOpenChange:a,modal:c=!1}=t,s=rj(e),f=P.useRef(null),[m,x]=P.useState(!1),[_,T]=ad({prop:n,defaultProp:i??!1,onChange:a,caller:dF});return o.jsx(cM,{...s,children:o.jsx(Grt,{scope:e,contentId:Cl(),triggerRef:f,open:_,onOpenChange:T,onOpenToggle:P.useCallback(()=>T(E=>!E),[T]),hasCustomAnchor:m,onCustomAnchorAdd:P.useCallback(()=>x(!0),[]),onCustomAnchorRemove:P.useCallback(()=>x(!1),[]),modal:c,children:r})})};Gbe.displayName=dF;var Hbe="PopoverAnchor",Hrt=P.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=hx(Hbe,r),a=rj(r),{onCustomAnchorAdd:c,onCustomAnchorRemove:s}=i;return P.useEffect(()=>(c(),()=>s()),[c,s]),o.jsx(OC,{...a,...n,ref:e})});Hrt.displayName=Hbe;var Wbe="PopoverTrigger",Kbe=P.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=hx(Wbe,r),a=rj(r),c=Wn(e,i.triggerRef),s=o.jsx(rn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":Jbe(i.open),...n,ref:c,onClick:Or(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?s:o.jsx(OC,{asChild:!0,...a,children:s})});Kbe.displayName=Wbe;var z7="PopoverPortal",[Wrt,Krt]=qbe(z7,{forceMount:void 0}),Ybe=t=>{const{__scopePopover:e,forceMount:r,children:n,container:i}=t,a=hx(z7,e);return o.jsx(Wrt,{scope:e,forceMount:r,children:o.jsx(dl,{present:r||a.open,children:o.jsx(aS,{asChild:!0,container:i,children:n})})})};Ybe.displayName=z7;var I1="PopoverContent",Zbe=P.forwardRef((t,e)=>{const r=Krt(I1,t.__scopePopover),{forceMount:n=r.forceMount,...i}=t,a=hx(I1,t.__scopePopover);return o.jsx(dl,{present:n||a.open,children:a.modal?o.jsx(Zrt,{...i,ref:e}):o.jsx(Xrt,{...i,ref:e})})});Zbe.displayName=I1;var Yrt=Fy("PopoverContent.RemoveScroll"),Zrt=P.forwardRef((t,e)=>{const r=hx(I1,t.__scopePopover),n=P.useRef(null),i=Wn(e,n),a=P.useRef(!1);return P.useEffect(()=>{const c=n.current;if(c)return rM(c)},[]),o.jsx(IC,{as:Yrt,allowPinchZoom:!0,children:o.jsx(Xbe,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Or(t.onCloseAutoFocus,c=>{var s;c.preventDefault(),a.current||(s=r.triggerRef.current)==null||s.focus()}),onPointerDownOutside:Or(t.onPointerDownOutside,c=>{const s=c.detail.originalEvent,f=s.button===0&&s.ctrlKey===!0,m=s.button===2||f;a.current=m},{checkForDefaultPrevented:!1}),onFocusOutside:Or(t.onFocusOutside,c=>c.preventDefault(),{checkForDefaultPrevented:!1})})})}),Xrt=P.forwardRef((t,e)=>{const r=hx(I1,t.__scopePopover),n=P.useRef(!1),i=P.useRef(!1);return o.jsx(Xbe,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:a=>{var c,s;(c=t.onCloseAutoFocus)==null||c.call(t,a),a.defaultPrevented||(n.current||(s=r.triggerRef.current)==null||s.focus(),a.preventDefault()),n.current=!1,i.current=!1},onInteractOutside:a=>{var f,m;(f=t.onInteractOutside)==null||f.call(t,a),a.defaultPrevented||(n.current=!0,a.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const c=a.target;((m=r.triggerRef.current)==null?void 0:m.contains(c))&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&i.current&&a.preventDefault()}})}),Xbe=P.forwardRef((t,e)=>{const{__scopePopover:r,trapFocus:n,onOpenAutoFocus:i,onCloseAutoFocus:a,disableOutsidePointerEvents:c,onEscapeKeyDown:s,onPointerDownOutside:f,onFocusOutside:m,onInteractOutside:x,..._}=t,T=hx(I1,r),E=rj(r);return eM(),o.jsx(jC,{asChild:!0,loop:!0,trapped:n,onMountAutoFocus:i,onUnmountAutoFocus:a,children:o.jsx(F0,{asChild:!0,disableOutsidePointerEvents:c,onInteractOutside:x,onEscapeKeyDown:s,onPointerDownOutside:f,onFocusOutside:m,onDismiss:()=>T.onOpenChange(!1),children:o.jsx(uM,{"data-state":Jbe(T.open),role:"dialog",id:T.contentId,...E,..._,ref:e,style:{..._.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)"}})})})}),Qbe="PopoverClose",Qrt=P.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=hx(Qbe,r);return o.jsx(rn.button,{type:"button",...n,ref:e,onClick:Or(t.onClick,()=>i.onOpenChange(!1))})});Qrt.displayName=Qbe;var Jrt="PopoverArrow",ent=P.forwardRef((t,e)=>{const{__scopePopover:r,...n}=t,i=rj(r);return o.jsx(dM,{...i,...n,ref:e})});ent.displayName=Jrt;function Jbe(t){return t?"open":"closed"}var tnt=Gbe,rnt=Kbe,nnt=Ybe,ewe=Zbe;const VR=tnt,qR=rnt,SA=P.forwardRef(({className:t,align:e="center",sideOffset:r=4,...n},i)=>o.jsx(nnt,{children:o.jsx(ewe,{ref:i,align:e,sideOffset:r,className:sr("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})}));SA.displayName=ewe.displayName;const int=ox({property_address:Xi().min(1,"Property address is required"),city:Xi().optional(),state:Xi().optional(),zip:Xi().optional(),transaction_type:MM(["buyer","seller"]),close_date:Xi().min(1,"Close date is required"),sale_price:yA().min(0,"Sale price must be positive"),commission_amount:yA().optional(),lead_source_id:Xi().optional(),client_type_id:Xi().optional(),contact_id:Xi().optional(),notes:Xi().optional(),is_win:uGe()});function twe({open:t,onOpenChange:e,transaction:r}){const[n,i]=P.useState(!1),[a,c]=P.useState(""),[s,f]=P.useState(!1),[m,x]=P.useState(""),_=D7(),T=Rrt(),{data:E}=L7(),{data:C}=B7(),{data:N}=$be(),R=$rt(),D=Prt(),{data:M}=uF(),B=(M==null?void 0:M.show_commission)??!0,V=S9({resolver:T9(int),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}});P.useEffect(()=>{r?V.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}):V.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,V]);const G=async re=>{const se={property_address:re.property_address,transaction_type:re.transaction_type,close_date:re.close_date,sale_price:re.sale_price,is_win:re.is_win,commission_amount:re.commission_amount||null,lead_source_id:re.lead_source_id||null,client_type_id:re.client_type_id||null,contact_id:re.contact_id||null,city:re.city||null,state:re.state||null,zip:re.zip||null,notes:re.notes||null};r?await T.mutateAsync({id:r.id,...se}):await _.mutateAsync(se),e(!1)},W=async()=>{if(!a.trim())return;const[re,...se]=a.trim().split(" "),ue=se.join(" ")||null,_e=await R.mutateAsync({first_name:re,last_name:ue,tagIds:[]});_e&&(V.setValue("contact_id",_e.id),c(""),f(!1),i(!1))},X=async()=>{if(!m.trim())return;const re=await D.mutateAsync(m.trim());re&&(V.setValue("lead_source_id",re.id),x(""))},Q=N==null?void 0:N.find(re=>re.id===V.watch("contact_id"));return o.jsx(ro,{open:t,onOpenChange:e,children:o.jsxs($a,{className:"max-w-lg max-h-[90vh]",children:[o.jsx(ul,{children:o.jsx(Go,{children:r?"Edit Transaction":"Add Transaction"})}),o.jsx(pp,{className:"max-h-[70vh] pr-4",children:o.jsx(R9,{...V,children:o.jsxs("form",{onSubmit:V.handleSubmit(G),className:"space-y-4",children:[o.jsx(rl,{control:V.control,name:"property_address",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Property Address *"}),o.jsx(zo,{children:o.jsx(Ur,{placeholder:"123 Main St",...re})}),o.jsx(Gh,{})]})}),o.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[o.jsx(rl,{control:V.control,name:"city",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"City"}),o.jsx(zo,{children:o.jsx(Ur,{placeholder:"City",...re})})]})}),o.jsx(rl,{control:V.control,name:"state",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"State"}),o.jsx(zo,{children:o.jsx(Ur,{placeholder:"TX",...re})})]})}),o.jsx(rl,{control:V.control,name:"zip",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Zip"}),o.jsx(zo,{children:o.jsx(Ur,{placeholder:"75001",...re})})]})})]}),o.jsx(rl,{control:V.control,name:"transaction_type",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Transaction Type *"}),o.jsxs(Ba,{onValueChange:re.onChange,value:re.value,children:[o.jsx(zo,{children:o.jsx(ja,{children:o.jsx(za,{placeholder:"Select type"})})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"buyer",children:"Buyer"}),o.jsx(wn,{value:"seller",children:"Seller"})]})]}),o.jsx(Gh,{})]})}),o.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[o.jsx(rl,{control:V.control,name:"close_date",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Close Date *"}),o.jsx(zo,{children:o.jsx(Ur,{type:"date",...re})}),o.jsx(Gh,{})]})}),o.jsx(rl,{control:V.control,name:"sale_price",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Sale Price *"}),o.jsx(zo,{children:o.jsx(Ur,{type:"number",placeholder:"0",...re,onChange:se=>re.onChange(Number(se.target.value))})}),o.jsx(Gh,{})]})})]}),B&&o.jsx(rl,{control:V.control,name:"commission_amount",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Commission"}),o.jsx(zo,{children:o.jsx(Ur,{type:"number",placeholder:"0",...re,value:re.value??"",onChange:se=>re.onChange(se.target.value?Number(se.target.value):void 0)})})]})}),o.jsx(rl,{control:V.control,name:"lead_source_id",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Lead Source"}),o.jsxs(Ba,{onValueChange:re.onChange,value:re.value||"",children:[o.jsx(zo,{children:o.jsx(ja,{children:o.jsx(za,{placeholder:"Select source"})})}),o.jsx(Ia,{children:E==null?void 0:E.map(se=>o.jsx(wn,{value:se.id,children:se.name},se.id))})]})]})}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ur,{placeholder:"Add custom source...",value:m,onChange:re=>x(re.target.value),className:"flex-1"}),o.jsx(Ut,{type:"button",variant:"outline",size:"icon",onClick:X,disabled:!m.trim(),children:o.jsx(xm,{className:"h-4 w-4"})})]}),o.jsx(rl,{control:V.control,name:"client_type_id",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Client Type"}),o.jsxs(Ba,{onValueChange:re.onChange,value:re.value||"",children:[o.jsx(zo,{children:o.jsx(ja,{children:o.jsx(za,{placeholder:"Select client type"})})}),o.jsx(Ia,{children:C==null?void 0:C.map(se=>o.jsx(wn,{value:se.id,children:se.name},se.id))})]})]})}),o.jsx(rl,{control:V.control,name:"contact_id",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Client Contact"}),o.jsxs(VR,{open:n,onOpenChange:i,children:[o.jsx(qR,{asChild:!0,children:o.jsx(zo,{children:o.jsxs(Ut,{variant:"outline",role:"combobox",className:sr("w-full justify-between",!re.value&&"text-muted-foreground"),children:[Q?`${Q.first_name} ${Q.last_name||""}`.trim():"Select contact",o.jsx(wU,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),o.jsxs(SA,{className:"w-full p-0",align:"start",children:[o.jsxs(mk,{children:[o.jsx(gk,{placeholder:"Search contacts..."}),o.jsxs(yk,{children:[o.jsx(xk,{children:o.jsxs("div",{className:"p-2 space-y-2",children:[o.jsx("p",{className:"text-sm text-muted-foreground",children:"No contact found."}),!s&&o.jsxs(Ut,{variant:"outline",size:"sm",className:"w-full",onClick:()=>f(!0),children:[o.jsx(xm,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),o.jsx(T1,{children:N==null?void 0:N.map(se=>o.jsxs(xy,{value:`${se.first_name} ${se.last_name||""}`,onSelect:()=>{re.onChange(se.id),i(!1)},children:[o.jsx(Ao,{className:sr("mr-2 h-4 w-4",se.id===re.value?"opacity-100":"opacity-0")}),se.first_name," ",se.last_name||""]},se.id))})]})]}),s&&o.jsxs("div",{className:"p-2 border-t space-y-2",children:[o.jsx(Ur,{placeholder:"Enter contact name...",value:a,onChange:se=>c(se.target.value)}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ut,{size:"sm",onClick:W,disabled:!a.trim()||R.isPending,children:"Add Contact"}),o.jsx(Ut,{size:"sm",variant:"outline",onClick:()=>{f(!1),c("")},children:"Cancel"})]})]})]})]})]})}),o.jsx(rl,{control:V.control,name:"notes",render:({field:re})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Notes"}),o.jsx(zo,{children:o.jsx(hd,{placeholder:"Any notes about this transaction...",...re})})]})}),o.jsx(rl,{control:V.control,name:"is_win",render:({field:re})=>o.jsxs(Fo,{className:"flex items-center justify-between rounded-lg border p-3",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsx(Bo,{children:"Mark as Win 🏆"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),o.jsx(zo,{children:o.jsx(kS,{checked:re.value,onCheckedChange:re.onChange})})]})}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(Ut,{type:"button",variant:"outline",onClick:()=>e(!1),children:"Cancel"}),o.jsxs(Ut,{type:"submit",disabled:_.isPending||T.isPending,children:[r?"Update":"Add"," Transaction"]})]})]})})})]})})}const fz=768;function snt(){const[t,e]=P.useState(void 0);return P.useEffect(()=>{const r=window.matchMedia(`(max-width: ${fz-1}px)`),n=()=>{e(window.innerWidthr.removeEventListener("change",n)},[]),!!t}function rwe({transactions:t,showCommission:e,isLoading:r,agentNameMap:n,readOnly:i}){const[a,c]=P.useState(null),[s,f]=P.useState(null),[m,x]=P.useState(""),[_,T]=P.useState("all"),[E,C]=P.useState("all"),[N,R]=P.useState("all"),[D,M]=P.useState(!1),B=Lrt(),V=D7(),{data:G}=L7();B7();const W=snt(),X=se=>{const{id:ue,created_at:_e,updated_at:Se,lead_source:ve,client_type:Oe,contact:Ae,...we}=se;V.mutate(we)},Q=()=>{s&&(B.mutate(s),f(null))},re=t.filter(se=>{var Ae,we,ge,Ne;const ue=m===""||se.property_address.toLowerCase().includes(m.toLowerCase())||((we=(Ae=se.contact)==null?void 0:Ae.first_name)==null?void 0:we.toLowerCase().includes(m.toLowerCase()))||((Ne=(ge=se.contact)==null?void 0:ge.last_name)==null?void 0:Ne.toLowerCase().includes(m.toLowerCase())),_e=_==="all"||se.transaction_type===_,Se=E==="all"||se.lead_source_id===E,ve=N==="all"||se.client_type_id===N,Oe=!D||se.is_win;return ue&&_e&&Se&&ve&&Oe});return r?o.jsx(Hn,{children:o.jsx(ii,{className:"p-6 space-y-4",children:[1,2,3].map(se=>o.jsx(ol,{className:"h-16 w-full"},se))})}):o.jsxs(o.Fragment,{children:[o.jsxs(Hn,{children:[o.jsx(Ju,{className:"pb-3",children:o.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[o.jsxs(ed,{children:["Transactions (",re.length,")"]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs("div",{className:"relative",children:[o.jsx($y,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),o.jsx(Ur,{placeholder:"Search...",value:m,onChange:se=>x(se.target.value),className:"pl-8 w-[150px]"})]}),o.jsxs(Ba,{value:_,onValueChange:T,children:[o.jsx(ja,{className:"w-[100px]",children:o.jsx(za,{placeholder:"Type"})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"all",children:"All Types"}),o.jsx(wn,{value:"buyer",children:"Buyer"}),o.jsx(wn,{value:"seller",children:"Seller"})]})]}),o.jsxs(Ba,{value:E,onValueChange:C,children:[o.jsx(ja,{className:"w-[130px]",children:o.jsx(za,{placeholder:"Lead Source"})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"all",children:"All Sources"}),G==null?void 0:G.map(se=>o.jsx(wn,{value:se.id,children:se.name},se.id))]})]}),o.jsxs(Ut,{variant:D?"default":"outline",size:"sm",onClick:()=>M(!D),children:[o.jsx(uA,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),o.jsx(ii,{children:re.length===0?o.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):W?o.jsx("div",{className:"space-y-3",children:re.map(se=>o.jsxs(Hn,{className:"p-4",children:[o.jsxs("div",{className:"flex items-start justify-between gap-2",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx("span",{className:"font-medium truncate",children:se.property_address}),se.is_win&&o.jsx(uA,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),o.jsxs("div",{className:"text-sm text-muted-foreground",children:[se.city,se.state?`, ${se.state}`:""]})]}),o.jsx(us,{variant:se.transaction_type==="buyer"?"default":"secondary",children:se.transaction_type})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3 text-sm",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Close Date: "}),PJ(se.close_date)]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Price: "}),Da(se.sale_price)]}),e&&se.commission_amount&&o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),Da(se.commission_amount)]}),se.lead_source&&o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"Source: "}),se.lead_source.name]}),se.contact&&o.jsxs("div",{className:"col-span-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Client: "}),se.contact.first_name," ",se.contact.last_name]}),n&&o.jsxs("div",{className:"col-span-2",children:[o.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),n[se.owner_user_id]||"Unknown"]})]}),!i&&o.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[o.jsx(Ut,{variant:"ghost",size:"sm",onClick:()=>c(se),children:o.jsx(kU,{className:"h-4 w-4"})}),o.jsx(Ut,{variant:"ghost",size:"sm",onClick:()=>X(se),children:o.jsx(TU,{className:"h-4 w-4"})}),o.jsx(Ut,{variant:"ghost",size:"sm",onClick:()=>f(se.id),children:o.jsx(IL,{className:"h-4 w-4 text-destructive"})})]})]},se.id))}):o.jsx("div",{className:"overflow-x-auto",children:o.jsxs(O7,{children:[o.jsx(M7,{children:o.jsxs(Tk,{children:[n&&o.jsx($l,{children:"Agent"}),o.jsx($l,{children:"Property"}),o.jsx($l,{children:"Type"}),o.jsx($l,{children:"Close Date"}),o.jsx($l,{children:"Sale Price"}),e&&o.jsx($l,{children:"Commission"}),o.jsx($l,{children:"Lead Source"}),o.jsx($l,{children:"Client"}),!i&&o.jsx($l,{className:"w-[50px]"})]})}),o.jsx(F7,{children:re.map(se=>{var ue;return o.jsxs(Tk,{children:[n&&o.jsx(Ul,{className:"font-medium text-sm",children:n[se.owner_user_id]||"Unknown"}),o.jsx(Ul,{children:o.jsxs("div",{className:"flex items-center gap-2",children:[se.is_win&&o.jsx(uA,{className:"h-4 w-4 text-yellow-500"}),o.jsxs("div",{children:[o.jsx("div",{className:"font-medium",children:se.property_address}),o.jsxs("div",{className:"text-sm text-muted-foreground",children:[se.city,se.state?`, ${se.state}`:""]})]})]})}),o.jsx(Ul,{children:o.jsx(us,{variant:se.transaction_type==="buyer"?"default":"secondary",children:se.transaction_type})}),o.jsx(Ul,{children:PJ(se.close_date)}),o.jsx(Ul,{children:Da(se.sale_price)}),e&&o.jsx(Ul,{children:se.commission_amount?Da(se.commission_amount):"-"}),o.jsx(Ul,{children:((ue=se.lead_source)==null?void 0:ue.name)||"-"}),o.jsx(Ul,{children:se.contact?`${se.contact.first_name} ${se.contact.last_name||""}`.trim():"-"}),!i&&o.jsx(Ul,{children:o.jsxs(UC,{children:[o.jsx(VC,{asChild:!0,children:o.jsx(Ut,{variant:"ghost",size:"icon",children:o.jsx(qRe,{className:"h-4 w-4"})})}),o.jsxs(wS,{align:"end",children:[o.jsxs(vu,{onClick:()=>c(se),children:[o.jsx(kU,{className:"h-4 w-4 mr-2"}),"Edit"]}),o.jsxs(vu,{onClick:()=>X(se),children:[o.jsx(TU,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),o.jsxs(vu,{onClick:()=>f(se.id),className:"text-destructive",children:[o.jsx(IL,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},se.id)})})]})})})]}),o.jsx(twe,{open:!!a,onOpenChange:se=>!se&&c(null),transaction:a||void 0}),o.jsx(tpe,{open:!!s,onOpenChange:se=>!se&&f(null),children:o.jsxs(EG,{children:[o.jsxs(AG,{children:[o.jsx(CG,{children:"Delete Transaction?"}),o.jsx(jG,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),o.jsxs(kG,{children:[o.jsx(PG,{children:"Cancel"}),o.jsx(IG,{onClick:Q,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}var $7="Progress",U7=100,[ant,e8t]=Ho($7),[ont,lnt]=ant($7),nwe=P.forwardRef((t,e)=>{const{__scopeProgress:r,value:n=null,max:i,getValueLabel:a=cnt,...c}=t;(i||i===0)&&!Sne(i)&&console.error(unt(`${i}`,"Progress"));const s=Sne(i)?i:U7;n!==null&&!Tne(n,s)&&console.error(dnt(`${n}`,"Progress"));const f=Tne(n,s)?n:null,m=xD(f)?a(f,s):void 0;return o.jsx(ont,{scope:r,value:f,max:s,children:o.jsx(rn.div,{"aria-valuemax":s,"aria-valuemin":0,"aria-valuenow":xD(f)?f:void 0,"aria-valuetext":m,role:"progressbar","data-state":awe(f,s),"data-value":f??void 0,"data-max":s,...c,ref:e})})});nwe.displayName=$7;var iwe="ProgressIndicator",swe=P.forwardRef((t,e)=>{const{__scopeProgress:r,...n}=t,i=lnt(iwe,r);return o.jsx(rn.div,{"data-state":awe(i.value,i.max),"data-value":i.value??void 0,"data-max":i.max,...n,ref:e})});swe.displayName=iwe;function cnt(t,e){return`${Math.round(t/e*100)}%`}function awe(t,e){return t==null?"indeterminate":t===e?"complete":"loading"}function xD(t){return typeof t=="number"}function Sne(t){return xD(t)&&!isNaN(t)&&t>0}function Tne(t,e){return xD(t)&&!isNaN(t)&&t<=e&&t>=0}function unt(t,e){return`Invalid prop \`max\` of value \`${t}\` supplied to \`${e}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${U7}\`.`}function dnt(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 ${U7} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var owe=nwe,hnt=swe;const GR=P.forwardRef(({className:t,value:e,...r},n)=>o.jsx(owe,{ref:n,className:sr("relative h-4 w-full overflow-hidden rounded-full bg-secondary",t),...r,children:o.jsx(hnt,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(e||0)}%)`}})}));GR.displayName=owe.displayName;function fnt({goals:t,stats:e,year:r,showCommission:n}){const i=new Date().getMonth()+1,a=new Date().getFullYear()===r?i:12,c=12-a,s=(T,E)=>{if(!E||E===0)return null;const C=Math.min(T/E*100,100),N=Math.max(E-T,0),R=c>0?N/c:0,D=a/12*100,M=C>=D?"ahead":C>=D*.8?"on-track":"behind";return{percent:C,remaining:N,pace:R,status:M}},f=s(e.totalTransactions,t.transactions_goal),m=s(e.totalVolume,t.volume_goal),x=n?s(e.totalCommission,t.gci_goal):null,_=T=>{switch(T){case"ahead":return o.jsxs(us,{className:"bg-green-500 text-white",children:[o.jsx(uS,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return o.jsxs(us,{variant:"secondary",children:[o.jsx(sLe,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return o.jsxs(us,{variant:"destructive",children:[o.jsx(Jhe,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!t.transactions_goal&&!t.volume_goal&&!t.gci_goal?null:o.jsxs(Hn,{children:[o.jsx(Ju,{className:"pb-3",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(yG,{className:"h-5 w-5 text-primary"}),o.jsxs(ed,{children:[r," Goals Progress"]})]})}),o.jsx(ii,{children:o.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[t.transactions_goal&&f&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm font-medium",children:"Transactions"}),_(f.status)]}),o.jsx(GR,{value:f.percent,className:"h-2"}),o.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[o.jsxs("span",{children:[e.totalTransactions," of ",t.transactions_goal]}),o.jsxs("span",{children:[Math.round(f.percent),"%"]})]}),f.remaining>0&&c>0&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Math.ceil(f.pace),"/month to hit goal"]})]}),t.volume_goal&&m&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm font-medium",children:"Volume"}),_(m.status)]}),o.jsx(GR,{value:m.percent,className:"h-2"}),o.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[o.jsxs("span",{children:[Da(e.totalVolume,!0)," of ",Da(t.volume_goal,!0)]}),o.jsxs("span",{children:[Math.round(m.percent),"%"]})]}),m.remaining>0&&c>0&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Da(m.pace,!0),"/month"]})]}),n&&t.gci_goal&&x&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-sm font-medium",children:"GCI"}),_(x.status)]}),o.jsx(GR,{value:x.percent,className:"h-2"}),o.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[o.jsxs("span",{children:[Da(e.totalCommission,!0)," of ",Da(t.gci_goal,!0)]}),o.jsxs("span",{children:[Math.round(x.percent),"%"]})]}),x.remaining>0&&c>0&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Da(x.pace,!0),"/month"]})]})]})})]})}var pnt=Array.isArray,Pu=pnt,mnt=typeof Wl=="object"&&Wl&&Wl.Object===Object&&Wl,lwe=mnt,gnt=lwe,ynt=typeof self=="object"&&self&&self.Object===Object&&self,xnt=gnt||ynt||Function("return this")(),mp=xnt,_nt=mp,vnt=_nt.Symbol,nj=vnt,Ene=nj,cwe=Object.prototype,bnt=cwe.hasOwnProperty,wnt=cwe.toString,E2=Ene?Ene.toStringTag:void 0;function Snt(t){var e=bnt.call(t,E2),r=t[E2];try{t[E2]=void 0;var n=!0}catch{}var i=wnt.call(t);return n&&(e?t[E2]=r:delete t[E2]),i}var Tnt=Snt,Ent=Object.prototype,Ant=Ent.toString;function knt(t){return Ant.call(t)}var Cnt=knt,Ane=nj,jnt=Tnt,Int=Cnt,Pnt="[object Null]",Nnt="[object Undefined]",kne=Ane?Ane.toStringTag:void 0;function Rnt(t){return t==null?t===void 0?Nnt:Pnt:kne&&kne in Object(t)?jnt(t):Int(t)}var qm=Rnt;function Lnt(t){return t!=null&&typeof t=="object"}var Gm=Lnt,Dnt=qm,Ont=Gm,Mnt="[object Symbol]";function Fnt(t){return typeof t=="symbol"||Ont(t)&&Dnt(t)==Mnt}var PS=Fnt,Bnt=Pu,znt=PS,$nt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Unt=/^\w*$/;function Vnt(t,e){if(Bnt(t))return!1;var r=typeof t;return r=="number"||r=="symbol"||r=="boolean"||t==null||znt(t)?!0:Unt.test(t)||!$nt.test(t)||e!=null&&t in Object(e)}var V7=Vnt;function qnt(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var fx=qnt;const NS=ds(fx);var Gnt=qm,Hnt=fx,Wnt="[object AsyncFunction]",Knt="[object Function]",Ynt="[object GeneratorFunction]",Znt="[object Proxy]";function Xnt(t){if(!Hnt(t))return!1;var e=Gnt(t);return e==Knt||e==Ynt||e==Wnt||e==Znt}var q7=Xnt;const gi=ds(q7);var Qnt=mp,Jnt=Qnt["__core-js_shared__"],eit=Jnt,pz=eit,Cne=function(){var t=/[^.]+$/.exec(pz&&pz.keys&&pz.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function tit(t){return!!Cne&&Cne in t}var rit=tit,nit=Function.prototype,iit=nit.toString;function sit(t){if(t!=null){try{return iit.call(t)}catch{}try{return t+""}catch{}}return""}var uwe=sit,ait=q7,oit=rit,lit=fx,cit=uwe,uit=/[\\^$.*+?()[\]{}|]/g,dit=/^\[object .+?Constructor\]$/,hit=Function.prototype,fit=Object.prototype,pit=hit.toString,mit=fit.hasOwnProperty,git=RegExp("^"+pit.call(mit).replace(uit,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function yit(t){if(!lit(t)||oit(t))return!1;var e=ait(t)?git:dit;return e.test(cit(t))}var xit=yit;function _it(t,e){return t==null?void 0:t[e]}var vit=_it,bit=xit,wit=vit;function Sit(t,e){var r=wit(t,e);return bit(r)?r:void 0}var H0=Sit,Tit=H0,Eit=Tit(Object,"create"),hF=Eit,jne=hF;function Ait(){this.__data__=jne?jne(null):{},this.size=0}var kit=Ait;function Cit(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var jit=Cit,Iit=hF,Pit="__lodash_hash_undefined__",Nit=Object.prototype,Rit=Nit.hasOwnProperty;function Lit(t){var e=this.__data__;if(Iit){var r=e[t];return r===Pit?void 0:r}return Rit.call(e,t)?e[t]:void 0}var Dit=Lit,Oit=hF,Mit=Object.prototype,Fit=Mit.hasOwnProperty;function Bit(t){var e=this.__data__;return Oit?e[t]!==void 0:Fit.call(e,t)}var zit=Bit,$it=hF,Uit="__lodash_hash_undefined__";function Vit(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=$it&&e===void 0?Uit:e,this}var qit=Vit,Git=kit,Hit=jit,Wit=Dit,Kit=zit,Yit=qit;function RS(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e-1}var hst=dst,fst=fF;function pst(t,e){var r=this.__data__,n=fst(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}var mst=pst,gst=Qit,yst=ast,xst=cst,_st=hst,vst=mst;function LS(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e0?1:-1},Z_=function(e){return j0(e)&&e.indexOf("%")===e.length-1},Wr=function(e){return Uat(e)&&!ij(e)},Hat=function(e){return Di(e)},cl=function(e){return Wr(e)||j0(e)},Wat=0,sj=function(e){var r=++Wat;return"".concat(e||"").concat(r)},Hc=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(!Wr(e)&&!j0(e))return n;var a;if(Z_(e)){var c=e.indexOf("%");a=r*parseFloat(e.slice(0,c))/100}else a=+e;return ij(a)&&(a=n),i&&a>r&&(a=r),a},iy=function(e){if(!e)return null;var r=Object.keys(e);return r&&r.length?e[r[0]]:null},Kat=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 tot(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 mV(t){"@babel/helpers - typeof";return mV=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},mV(t)}var One={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"},vm=function(e){return typeof e=="string"?e:e?e.displayName||e.name||"Component":""},Mne=null,gz=null,eH=function t(e){if(e===Mne&&Array.isArray(gz))return gz;var r=[];return P.Children.forEach(e,function(n){Di(n)||(Mat.isFragment(n)?r=r.concat(t(n.props.children)):r.push(n))}),gz=r,Mne=e,r};function Wd(t,e){var r=[],n=[];return Array.isArray(e)?n=e.map(function(i){return vm(i)}):n=[vm(e)],eH(t).forEach(function(i){var a=nd(i,"type.displayName")||nd(i,"type.name");n.indexOf(a)!==-1&&r.push(i)}),r}function Wu(t,e){var r=Wd(t,e);return r&&r[0]}var Fne=function(e){if(!e||!e.props)return!1;var r=e.props,n=r.width,i=r.height;return!(!Wr(n)||n<=0||!Wr(i)||i<=0)},rot=["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"],not=function(e){return e&&e.type&&j0(e.type)&&rot.indexOf(e.type)>=0},t8t=function(e){return e&&mV(e)==="object"&&"clipDot"in e},iot=function(e,r,n,i){var a,c=(a=mz==null?void 0:mz[i])!==null&&a!==void 0?a:[];return r.startsWith("data-")||!gi(e)&&(i&&c.includes(r)||Xat.includes(r))||n&&J7.includes(r)},ui=function(e,r,n){if(!e||typeof e=="function"||typeof e=="boolean")return null;var i=e;if(P.isValidElement(e)&&(i=e.props),!NS(i))return null;var a={};return Object.keys(i).forEach(function(c){var s;iot((s=i)===null||s===void 0?void 0:s[c],c,r,n)&&(a[c]=i[c])}),a},gV=function t(e,r){if(e===r)return!0;var n=P.Children.count(e);if(n!==P.Children.count(r))return!1;if(n===0)return!0;if(n===1)return Bne(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 cot(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 xV(t){var e=t.children,r=t.width,n=t.height,i=t.viewBox,a=t.className,c=t.style,s=t.title,f=t.desc,m=lot(t,oot),x=i||{width:r,height:n,x:0,y:0},_=Li("recharts-surface",a);return Xe.createElement("svg",yV({},ui(m,!0,"svg"),{className:_,width:r,height:n,style:c,viewBox:"".concat(x.x," ").concat(x.y," ").concat(x.width," ").concat(x.height)}),Xe.createElement("title",null,s),Xe.createElement("desc",null,f),e)}var uot=["children","className"];function _V(){return _V=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 hot(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 zs=Xe.forwardRef(function(t,e){var r=t.children,n=t.className,i=dot(t,uot),a=Li("recharts-layer",n);return Xe.createElement("g",_V({className:a},ui(i,!0),{ref:e}),r)}),Xh=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:mot(t,e,r)}var yot=got,xot="\\ud800-\\udfff",_ot="\\u0300-\\u036f",vot="\\ufe20-\\ufe2f",bot="\\u20d0-\\u20ff",wot=_ot+vot+bot,Sot="\\ufe0e\\ufe0f",Tot="\\u200d",Eot=RegExp("["+Tot+xot+wot+Sot+"]");function Aot(t){return Eot.test(t)}var vwe=Aot;function kot(t){return t.split("")}var Cot=kot,bwe="\\ud800-\\udfff",jot="\\u0300-\\u036f",Iot="\\ufe20-\\ufe2f",Pot="\\u20d0-\\u20ff",Not=jot+Iot+Pot,Rot="\\ufe0e\\ufe0f",Lot="["+bwe+"]",vV="["+Not+"]",bV="\\ud83c[\\udffb-\\udfff]",Dot="(?:"+vV+"|"+bV+")",wwe="[^"+bwe+"]",Swe="(?:\\ud83c[\\udde6-\\uddff]){2}",Twe="[\\ud800-\\udbff][\\udc00-\\udfff]",Oot="\\u200d",Ewe=Dot+"?",Awe="["+Rot+"]?",Mot="(?:"+Oot+"(?:"+[wwe,Swe,Twe].join("|")+")"+Awe+Ewe+")*",Fot=Awe+Ewe+Mot,Bot="(?:"+[wwe+vV+"?",vV,Swe,Twe,Lot].join("|")+")",zot=RegExp(bV+"(?="+bV+")|"+Bot+Fot,"g");function $ot(t){return t.match(zot)||[]}var Uot=$ot,Vot=Cot,qot=vwe,Got=Uot;function Hot(t){return qot(t)?Got(t):Vot(t)}var Wot=Hot,Kot=yot,Yot=vwe,Zot=Wot,Xot=pwe;function Qot(t){return function(e){e=Xot(e);var r=Yot(e)?Zot(e):void 0,n=r?r[0]:e.charAt(0),i=r?Kot(r,1).join(""):e.slice(1);return n[t]()+i}}var Jot=Qot,elt=Jot,tlt=elt("toUpperCase"),rlt=tlt;const kF=ds(rlt);function ha(t){return function(){return t}}const kwe=Math.cos,bD=Math.sin,nf=Math.sqrt,wD=Math.PI,CF=2*wD,wV=Math.PI,SV=2*wV,F_=1e-6,nlt=SV-F_;function Cwe(t){this._+=t[0];for(let e=1,r=t.length;e=0))throw new Error(`invalid digits: ${t}`);if(e>15)return Cwe;const r=10**e;return function(n){this._+=n[0];for(let i=1,a=n.length;iF_)if(!(Math.abs(_*f-m*x)>F_)||!a)this._append`L${this._x1=e},${this._y1=r}`;else{let E=n-c,C=i-s,N=f*f+m*m,R=E*E+C*C,D=Math.sqrt(N),M=Math.sqrt(T),B=a*Math.tan((wV-Math.acos((N+T-R)/(2*D*M)))/2),V=B/M,G=B/D;Math.abs(V-1)>F_&&this._append`L${e+V*x},${r+V*_}`,this._append`A${a},${a},0,0,${+(_*E>x*C)},${this._x1=e+G*f},${this._y1=r+G*m}`}}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 s=n*Math.cos(i),f=n*Math.sin(i),m=e+s,x=r+f,_=1^c,T=c?i-a:a-i;this._x1===null?this._append`M${m},${x}`:(Math.abs(this._x1-m)>F_||Math.abs(this._y1-x)>F_)&&this._append`L${m},${x}`,n&&(T<0&&(T=T%SV+SV),T>nlt?this._append`A${n},${n},0,1,${_},${e-s},${r-f}A${n},${n},0,1,${_},${this._x1=m},${this._y1=x}`:T>F_&&this._append`A${n},${n},0,${+(T>=wV)},${_},${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 tH(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 slt(e)}function rH(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}function jwe(t){this._context=t}jwe.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 jF(t){return new jwe(t)}function Iwe(t){return t[0]}function Pwe(t){return t[1]}function Nwe(t,e){var r=ha(!0),n=null,i=jF,a=null,c=tH(s);t=typeof t=="function"?t:t===void 0?Iwe:ha(t),e=typeof e=="function"?e:e===void 0?Pwe:ha(e);function s(f){var m,x=(f=rH(f)).length,_,T=!1,E;for(n==null&&(a=i(E=c())),m=0;m<=x;++m)!(m=E;--C)s.point(B[C],V[C]);s.lineEnd(),s.areaEnd()}D&&(B[T]=+t(R,T,_),V[T]=+e(R,T,_),s.point(n?+n(R,T,_):B[T],r?+r(R,T,_):V[T]))}if(M)return s=null,M+""||null}function x(){return Nwe().defined(i).curve(c).context(a)}return m.x=function(_){return arguments.length?(t=typeof _=="function"?_:ha(+_),n=null,m):t},m.x0=function(_){return arguments.length?(t=typeof _=="function"?_:ha(+_),m):t},m.x1=function(_){return arguments.length?(n=_==null?null:typeof _=="function"?_:ha(+_),m):n},m.y=function(_){return arguments.length?(e=typeof _=="function"?_:ha(+_),r=null,m):e},m.y0=function(_){return arguments.length?(e=typeof _=="function"?_:ha(+_),m):e},m.y1=function(_){return arguments.length?(r=_==null?null:typeof _=="function"?_:ha(+_),m):r},m.lineX0=m.lineY0=function(){return x().x(t).y(e)},m.lineY1=function(){return x().x(t).y(r)},m.lineX1=function(){return x().x(n).y(e)},m.defined=function(_){return arguments.length?(i=typeof _=="function"?_:ha(!!_),m):i},m.curve=function(_){return arguments.length?(c=_,a!=null&&(s=c(a)),m):c},m.context=function(_){return arguments.length?(_==null?a=s=null:s=c(a=_),m):a},m}class Rwe{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 alt(t){return new Rwe(t,!0)}function olt(t){return new Rwe(t,!1)}const nH={draw(t,e){const r=nf(e/wD);t.moveTo(r,0),t.arc(0,0,r,0,CF)}},llt={draw(t,e){const r=nf(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()}},Lwe=nf(1/3),clt=Lwe*2,ult={draw(t,e){const r=nf(e/clt),n=r*Lwe;t.moveTo(0,-r),t.lineTo(n,0),t.lineTo(0,r),t.lineTo(-n,0),t.closePath()}},dlt={draw(t,e){const r=nf(e),n=-r/2;t.rect(n,n,r,r)}},hlt=.8908130915292852,Dwe=bD(wD/10)/bD(7*wD/10),flt=bD(CF/10)*Dwe,plt=-kwe(CF/10)*Dwe,mlt={draw(t,e){const r=nf(e*hlt),n=flt*r,i=plt*r;t.moveTo(0,-r),t.lineTo(n,i);for(let a=1;a<5;++a){const c=CF*a/5,s=kwe(c),f=bD(c);t.lineTo(f*r,-s*r),t.lineTo(s*n-f*i,f*n+s*i)}t.closePath()}},yz=nf(3),glt={draw(t,e){const r=-nf(e/(yz*3));t.moveTo(0,r*2),t.lineTo(-yz*r,-r),t.lineTo(yz*r,-r),t.closePath()}},Id=-.5,Pd=nf(3)/2,TV=1/nf(12),ylt=(TV/2+1)*3,xlt={draw(t,e){const r=nf(e/ylt),n=r/2,i=r*TV,a=n,c=r*TV+r,s=-a,f=c;t.moveTo(n,i),t.lineTo(a,c),t.lineTo(s,f),t.lineTo(Id*n-Pd*i,Pd*n+Id*i),t.lineTo(Id*a-Pd*c,Pd*a+Id*c),t.lineTo(Id*s-Pd*f,Pd*s+Id*f),t.lineTo(Id*n+Pd*i,Id*i-Pd*n),t.lineTo(Id*a+Pd*c,Id*c-Pd*a),t.lineTo(Id*s+Pd*f,Id*f-Pd*s),t.closePath()}};function _lt(t,e){let r=null,n=tH(i);t=typeof t=="function"?t:ha(t||nH),e=typeof e=="function"?e:ha(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:ha(a),i):t},i.size=function(a){return arguments.length?(e=typeof a=="function"?a:ha(+a),i):e},i.context=function(a){return arguments.length?(r=a??null,i):r},i}function SD(){}function TD(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 Owe(t){this._context=t}Owe.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:TD(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:TD(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function vlt(t){return new Owe(t)}function Mwe(t){this._context=t}Mwe.prototype={areaStart:SD,areaEnd:SD,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:TD(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function blt(t){return new Mwe(t)}function Fwe(t){this._context=t}Fwe.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:TD(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e}};function wlt(t){return new Fwe(t)}function Bwe(t){this._context=t}Bwe.prototype={areaStart:SD,areaEnd:SD,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 Slt(t){return new Bwe(t)}function $ne(t){return t<0?-1:1}function Une(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),s=(a*i+c*n)/(n+i);return($ne(a)+$ne(c))*Math.min(Math.abs(a),Math.abs(c),.5*Math.abs(s))||0}function Vne(t,e){var r=t._x1-t._x0;return r?(3*(t._y1-t._y0)/r-e)/2:e}function xz(t,e,r){var n=t._x0,i=t._y0,a=t._x1,c=t._y1,s=(a-n)/3;t._context.bezierCurveTo(n+s,i+s*e,a-s,c-s*r,a,c)}function ED(t){this._context=t}ED.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:xz(this,this._t0,Vne(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,xz(this,Vne(this,r=Une(this,t,e)),r);break;default:xz(this,this._t0,r=Une(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=r}}};function zwe(t){this._context=new $we(t)}(zwe.prototype=Object.create(ED.prototype)).point=function(t,e){ED.prototype.point.call(this,e,t)};function $we(t){this._context=t}$we.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 Tlt(t){return new ED(t)}function Elt(t){return new zwe(t)}function Uwe(t){this._context=t}Uwe.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=qne(t),i=qne(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 klt(t){return new IF(t,.5)}function Clt(t){return new IF(t,0)}function jlt(t){return new IF(t,1)}function P1(t,e){if((c=t.length)>1)for(var r=1,n,i,a=t[e[0]],c,s=a.length;r=0;)r[e]=e;return r}function Ilt(t,e){return t[e]}function Plt(t){const e=[];return e.key=t,e}function Nlt(){var t=ha([]),e=EV,r=P1,n=Ilt;function i(a){var c=Array.from(t.apply(this,arguments),Plt),s,f=c.length,m=-1,x;for(const _ of a)for(s=0,++m;s0){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 $lt(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 Vwe={symbolCircle:nH,symbolCross:llt,symbolDiamond:ult,symbolSquare:dlt,symbolStar:mlt,symbolTriangle:glt,symbolWye:xlt},Ult=Math.PI/180,Vlt=function(e){var r="symbol".concat(kF(e));return Vwe[r]||nH},qlt=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*Ult;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}},Glt=function(e,r){Vwe["symbol".concat(kF(e))]=r},iH=function(e){var r=e.type,n=r===void 0?"circle":r,i=e.size,a=i===void 0?64:i,c=e.sizeType,s=c===void 0?"area":c,f=zlt(e,Olt),m=Hne(Hne({},f),{},{type:n,size:a,sizeType:s}),x=function(){var R=Vlt(n),D=_lt().type(R).size(qlt(a,s,n));return D()},_=m.className,T=m.cx,E=m.cy,C=ui(m,!0);return T===+T&&E===+E&&a===+a?Xe.createElement("path",AV({},C,{className:Li("recharts-symbols",_),transform:"translate(".concat(T,", ").concat(E,")"),d:x()})):null};iH.registerSymbol=Glt;function N1(t){"@babel/helpers - typeof";return N1=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},N1(t)}function kV(){return kV=Object.assign?Object.assign.bind():function(t){for(var e=1;e`);var M=E.inactive?m:E.color;return Xe.createElement("li",kV({className:R,style:_,key:"legend-item-".concat(C)},I0(n.props,E,C)),Xe.createElement(xV,{width:c,height:c,viewBox:x,style:T},n.renderIcon(E)),Xe.createElement("span",{className:"recharts-legend-item-text",style:{color:M}},N?N(D,E,C):D))})}},{key:"render",value:function(){var n=this.props,i=n.payload,a=n.layout,c=n.align;if(!i||!i.length)return null;var s={padding:0,margin:0,textAlign:a==="horizontal"?c:"left"};return Xe.createElement("ul",{className:"recharts-default-legend",style:s},this.renderItems())}}])}(P.PureComponent);Ak(sH,"displayName","Legend");Ak(sH,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var tct=pF;function rct(){this.__data__=new tct,this.size=0}var nct=rct;function ict(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}var sct=ict;function act(t){return this.__data__.get(t)}var oct=act;function lct(t){return this.__data__.has(t)}var cct=lct,uct=pF,dct=H7,hct=W7,fct=200;function pct(t,e){var r=this.__data__;if(r instanceof uct){var n=r.__data__;if(!dct||n.lengths))return!1;var m=a.get(t),x=a.get(e);if(m&&x)return m==e&&x==t;var _=-1,T=!0,E=r&Oct?new Nct:void 0;for(a.set(t,e),a.set(e,t);++_-1&&t%1==0&&t-1&&t%1==0&&t<=zut}var cH=$ut,Uut=qm,Vut=cH,qut=Gm,Gut="[object Arguments]",Hut="[object Array]",Wut="[object Boolean]",Kut="[object Date]",Yut="[object Error]",Zut="[object Function]",Xut="[object Map]",Qut="[object Number]",Jut="[object Object]",edt="[object RegExp]",tdt="[object Set]",rdt="[object String]",ndt="[object WeakMap]",idt="[object ArrayBuffer]",sdt="[object DataView]",adt="[object Float32Array]",odt="[object Float64Array]",ldt="[object Int8Array]",cdt="[object Int16Array]",udt="[object Int32Array]",ddt="[object Uint8Array]",hdt="[object Uint8ClampedArray]",fdt="[object Uint16Array]",pdt="[object Uint32Array]",Ea={};Ea[adt]=Ea[odt]=Ea[ldt]=Ea[cdt]=Ea[udt]=Ea[ddt]=Ea[hdt]=Ea[fdt]=Ea[pdt]=!0;Ea[Gut]=Ea[Hut]=Ea[idt]=Ea[Wut]=Ea[sdt]=Ea[Kut]=Ea[Yut]=Ea[Zut]=Ea[Xut]=Ea[Qut]=Ea[Jut]=Ea[edt]=Ea[tdt]=Ea[rdt]=Ea[ndt]=!1;function mdt(t){return qut(t)&&Vut(t.length)&&!!Ea[Uut(t)]}var gdt=mdt;function ydt(t){return function(e){return t(e)}}var e1e=ydt,jD={exports:{}};jD.exports;(function(t,e){var r=lwe,n=e&&!e.nodeType&&e,i=n&&!0&&t&&!t.nodeType&&t,a=i&&i.exports===n,c=a&&r.process,s=function(){try{var f=i&&i.require&&i.require("util").types;return f||c&&c.binding&&c.binding("util")}catch{}}();t.exports=s})(jD,jD.exports);var xdt=jD.exports,_dt=gdt,vdt=e1e,Jne=xdt,eie=Jne&&Jne.isTypedArray,bdt=eie?vdt(eie):_dt,t1e=bdt,wdt=Eut,Sdt=oH,Tdt=Pu,Edt=Jwe,Adt=lH,kdt=t1e,Cdt=Object.prototype,jdt=Cdt.hasOwnProperty;function Idt(t,e){var r=Tdt(t),n=!r&&Sdt(t),i=!r&&!n&&Edt(t),a=!r&&!n&&!i&&kdt(t),c=r||n||i||a,s=c?wdt(t.length,String):[],f=s.length;for(var m in t)(e||jdt.call(t,m))&&!(c&&(m=="length"||i&&(m=="offset"||m=="parent")||a&&(m=="buffer"||m=="byteLength"||m=="byteOffset")||Adt(m,f)))&&s.push(m);return s}var Pdt=Idt,Ndt=Object.prototype;function Rdt(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||Ndt;return t===r}var Ldt=Rdt;function Ddt(t,e){return function(r){return t(e(r))}}var r1e=Ddt,Odt=r1e,Mdt=Odt(Object.keys,Object),Fdt=Mdt,Bdt=Ldt,zdt=Fdt,$dt=Object.prototype,Udt=$dt.hasOwnProperty;function Vdt(t){if(!Bdt(t))return zdt(t);var e=[];for(var r in Object(t))Udt.call(t,r)&&r!="constructor"&&e.push(r);return e}var qdt=Vdt,Gdt=q7,Hdt=cH;function Wdt(t){return t!=null&&Hdt(t.length)&&!Gdt(t)}var aj=Wdt,Kdt=Pdt,Ydt=qdt,Zdt=aj;function Xdt(t){return Zdt(t)?Kdt(t):Ydt(t)}var PF=Xdt,Qdt=fut,Jdt=Sut,eht=PF;function tht(t){return Qdt(t,eht,Jdt)}var rht=tht,tie=rht,nht=1,iht=Object.prototype,sht=iht.hasOwnProperty;function aht(t,e,r,n,i,a){var c=r&nht,s=tie(t),f=s.length,m=tie(e),x=m.length;if(f!=x&&!c)return!1;for(var _=f;_--;){var T=s[_];if(!(c?T in e:sht.call(e,T)))return!1}var E=a.get(t),C=a.get(e);if(E&&C)return E==e&&C==t;var N=!0;a.set(t,e),a.set(e,t);for(var R=c;++_-1}var ipt=npt;function spt(t,e,r){for(var n=-1,i=t==null?0:t.length;++n=vpt){var m=e?null:xpt(t);if(m)return _pt(m);c=!1,i=ypt,f=new ppt}else f=e?[]:s;e:for(;++n=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function Opt(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 Mpt(t){return t.value}function Fpt(t,e){if(Xe.isValidElement(t))return Xe.cloneElement(t,e);if(typeof t=="function")return Xe.createElement(t,e);e.ref;var r=Dpt(e,kpt);return Xe.createElement(sH,r)}var yie=1,Fw=function(t){function e(){var r;Cpt(this,e);for(var n=arguments.length,i=new Array(n),a=0;ayie||Math.abs(i.height-this.lastBoundingBox.height)>yie)&&(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?Zp({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var i=this.props,a=i.layout,c=i.align,s=i.verticalAlign,f=i.margin,m=i.chartWidth,x=i.chartHeight,_,T;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(c==="center"&&a==="vertical"){var E=this.getBBoxSnapshot();_={left:((m||0)-E.width)/2}}else _=c==="right"?{right:f&&f.right||0}:{left:f&&f.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(s==="middle"){var C=this.getBBoxSnapshot();T={top:((x||0)-C.height)/2}}else T=s==="bottom"?{bottom:f&&f.bottom||0}:{top:f&&f.top||0};return Zp(Zp({},_),T)}},{key:"render",value:function(){var n=this,i=this.props,a=i.content,c=i.width,s=i.height,f=i.wrapperStyle,m=i.payloadUniqBy,x=i.payload,_=Zp(Zp({position:"absolute",width:c||"auto",height:s||"auto"},this.getDefaultPosition(f)),f);return Xe.createElement("div",{className:"recharts-legend-wrapper",style:_,ref:function(E){n.wrapperNode=E}},Fpt(a,Zp(Zp({},this.props),{},{payload:c1e(x,m,Mpt)})))}}],[{key:"getWithHeight",value:function(n,i){var a=Zp(Zp({},this.defaultProps),n.props),c=a.layout;return c==="vertical"&&Wr(n.props.height)?{height:n.props.height}:c==="horizontal"?{width:n.props.width||i}:null}}])}(P.PureComponent);NF(Fw,"displayName","Legend");NF(Fw,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var xie=nj,Bpt=oH,zpt=Pu,_ie=xie?xie.isConcatSpreadable:void 0;function $pt(t){return zpt(t)||Bpt(t)||!!(_ie&&t&&t[_ie])}var Upt=$pt,Vpt=Xwe,qpt=Upt;function h1e(t,e,r,n,i){var a=-1,c=t.length;for(r||(r=qpt),i||(i=[]);++a0&&r(s)?e>1?h1e(s,e-1,r,n,i):Vpt(i,s):n||(i[i.length]=s)}return i}var f1e=h1e;function Gpt(t){return function(e,r,n){for(var i=-1,a=Object(e),c=n(e),s=c.length;s--;){var f=c[t?s:++i];if(r(a[f],f,a)===!1)break}return e}}var Hpt=Gpt,Wpt=Hpt,Kpt=Wpt(),Ypt=Kpt,Zpt=Ypt,Xpt=PF;function Qpt(t,e){return t&&Zpt(t,e,Xpt)}var p1e=Qpt,Jpt=aj;function emt(t,e){return function(r,n){if(r==null)return r;if(!Jpt(r))return t(r,n);for(var i=r.length,a=e?i:-1,c=Object(r);(e?a--:++ae||a&&c&&f&&!s&&!m||n&&c&&f||!r&&f||!i)return 1;if(!n&&!a&&!m&&t=s)return f;var m=r[n];return f*(m=="desc"?-1:1)}}return t.index-e.index}var pmt=fmt,wz=Y7,mmt=Z7,gmt=gp,ymt=m1e,xmt=cmt,_mt=e1e,vmt=pmt,bmt=FS,wmt=Pu;function Smt(t,e,r){e.length?e=wz(e,function(a){return wmt(a)?function(c){return mmt(c,a.length===1?a[0]:a)}:a}):e=[bmt];var n=-1;e=wz(e,_mt(gmt));var i=ymt(t,function(a,c,s){var f=wz(e,function(m){return m(a)});return{criteria:f,index:++n,value:a}});return xmt(i,function(a,c){return vmt(a,c,r)})}var Tmt=Smt;function Emt(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 Amt=Emt,kmt=Amt,bie=Math.max;function Cmt(t,e,r){return e=bie(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,a=bie(n.length-e,0),c=Array(a);++i0){if(++e>=Fmt)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}var Umt=$mt,Vmt=Mmt,qmt=Umt,Gmt=qmt(Vmt),Hmt=Gmt,Wmt=FS,Kmt=jmt,Ymt=Hmt;function Zmt(t,e){return Ymt(Kmt(t,e,Wmt),t+"")}var Xmt=Zmt,Qmt=G7,Jmt=aj,egt=lH,tgt=fx;function rgt(t,e,r){if(!tgt(r))return!1;var n=typeof e;return(n=="number"?Jmt(r)&&egt(e,r.length):n=="string"&&e in r)?Qmt(r[e],t):!1}var RF=rgt,ngt=f1e,igt=Tmt,sgt=Xmt,Sie=RF,agt=sgt(function(t,e){if(t==null)return[];var r=e.length;return r>1&&Sie(t,e[0],e[1])?e=[]:r>2&&Sie(e[0],e[1],e[2])&&(e=[e[0]]),igt(t,ngt(e,1),[])}),ogt=agt;const hH=ds(ogt);function kk(t){"@babel/helpers - typeof";return kk=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},kk(t)}function DV(){return DV=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(A2,"-left"),Wr(r)&&e&&Wr(e.x)&&r=e.y),"".concat(A2,"-top"),Wr(n)&&e&&Wr(e.y)&&nN?Math.max(x,f[n]):Math.max(_,f[n])}function wgt(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 Sgt(t){var e=t.allowEscapeViewBox,r=t.coordinate,n=t.offsetTopLeft,i=t.position,a=t.reverseDirection,c=t.tooltipBox,s=t.useTranslate3d,f=t.viewBox,m,x,_;return c.height>0&&c.width>0&&r?(x=Aie({allowEscapeViewBox:e,coordinate:r,key:"x",offsetTopLeft:n,position:i,reverseDirection:a,tooltipDimension:c.width,viewBox:f,viewBoxDimension:f.width}),_=Aie({allowEscapeViewBox:e,coordinate:r,key:"y",offsetTopLeft:n,position:i,reverseDirection:a,tooltipDimension:c.height,viewBox:f,viewBoxDimension:f.height}),m=wgt({translateX:x,translateY:_,useTranslate3d:s})):m=vgt,{cssProperties:m,cssClasses:bgt({translateX:x,translateY:_,coordinate:r})}}function L1(t){"@babel/helpers - typeof";return L1=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},L1(t)}function kie(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 Cie(t){for(var e=1;ejie||Math.abs(n.height-this.state.lastBoundingBox.height)>jie)&&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,s=i.animationDuration,f=i.animationEasing,m=i.children,x=i.coordinate,_=i.hasPayload,T=i.isAnimationActive,E=i.offset,C=i.position,N=i.reverseDirection,R=i.useTranslate3d,D=i.viewBox,M=i.wrapperStyle,B=Sgt({allowEscapeViewBox:c,coordinate:x,offsetTopLeft:E,position:C,reverseDirection:N,tooltipBox:this.state.lastBoundingBox,useTranslate3d:R,viewBox:D}),V=B.cssClasses,G=B.cssProperties,W=Cie(Cie({transition:T&&a?"transform ".concat(s,"ms ").concat(f):void 0},G),{},{pointerEvents:"none",visibility:!this.state.dismissed&&a&&_?"visible":"hidden",position:"absolute",top:0,left:0},M);return Xe.createElement("div",{tabIndex:-1,className:V,style:W,ref:function(Q){n.wrapperNode=Q}},m)}}])}(P.PureComponent),Rgt=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},bm={isSsr:Rgt(),get:function(e){return bm[e]},set:function(e,r){if(typeof e=="string")bm[e]=r;else{var n=Object.keys(e);n&&n.length&&n.forEach(function(i){bm[i]=e[i]})}}};function D1(t){"@babel/helpers - typeof";return D1=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},D1(t)}function Iie(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 Pie(t){for(var e=1;e0;return Xe.createElement(Ngt,{allowEscapeViewBox:c,animationDuration:s,animationEasing:f,isAnimationActive:T,active:a,coordinate:x,hasPayload:W,offset:E,position:R,reverseDirection:D,useTranslate3d:M,viewBox:B,wrapperStyle:V},Vgt(m,Pie(Pie({},this.props),{},{payload:G})))}}])}(P.PureComponent);fH(Mh,"displayName","Tooltip");fH(Mh,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!bm.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 qgt=mp,Ggt=function(){return qgt.Date.now()},Hgt=Ggt,Wgt=/\s/;function Kgt(t){for(var e=t.length;e--&&Wgt.test(t.charAt(e)););return e}var Ygt=Kgt,Zgt=Ygt,Xgt=/^\s+/;function Qgt(t){return t&&t.slice(0,Zgt(t)+1).replace(Xgt,"")}var Jgt=Qgt,eyt=Jgt,Nie=fx,tyt=PS,Rie=NaN,ryt=/^[-+]0x[0-9a-f]+$/i,nyt=/^0b[01]+$/i,iyt=/^0o[0-7]+$/i,syt=parseInt;function ayt(t){if(typeof t=="number")return t;if(tyt(t))return Rie;if(Nie(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=Nie(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=eyt(t);var r=nyt.test(t);return r||iyt.test(t)?syt(t.slice(2),r?2:8):ryt.test(t)?Rie:+t}var b1e=ayt,oyt=fx,Tz=Hgt,Lie=b1e,lyt="Expected a function",cyt=Math.max,uyt=Math.min;function dyt(t,e,r){var n,i,a,c,s,f,m=0,x=!1,_=!1,T=!0;if(typeof t!="function")throw new TypeError(lyt);e=Lie(e)||0,oyt(r)&&(x=!!r.leading,_="maxWait"in r,a=_?cyt(Lie(r.maxWait)||0,e):a,T="trailing"in r?!!r.trailing:T);function E(W){var X=n,Q=i;return n=i=void 0,m=W,c=t.apply(Q,X),c}function C(W){return m=W,s=setTimeout(D,e),x?E(W):c}function N(W){var X=W-f,Q=W-m,re=e-X;return _?uyt(re,a-Q):re}function R(W){var X=W-f,Q=W-m;return f===void 0||X>=e||X<0||_&&Q>=a}function D(){var W=Tz();if(R(W))return M(W);s=setTimeout(D,N(W))}function M(W){return s=void 0,T&&n?E(W):(n=i=void 0,c)}function B(){s!==void 0&&clearTimeout(s),m=0,n=f=i=s=void 0}function V(){return s===void 0?c:M(Tz())}function G(){var W=Tz(),X=R(W);if(n=arguments,i=this,f=W,X){if(s===void 0)return C(f);if(_)return clearTimeout(s),s=setTimeout(D,e),E(f)}return s===void 0&&(s=setTimeout(D,e)),c}return G.cancel=B,G.flush=V,G}var hyt=dyt,fyt=hyt,pyt=fx,myt="Expected a function";function gyt(t,e,r){var n=!0,i=!0;if(typeof t!="function")throw new TypeError(myt);return pyt(r)&&(n="leading"in r?!!r.leading:n,i="trailing"in r?!!r.trailing:i),fyt(t,e,{leading:n,maxWait:e,trailing:i})}var yyt=gyt;const w1e=ds(yyt);function jk(t){"@babel/helpers - typeof";return jk=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},jk(t)}function Die(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 NN(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,n=new Array(e);r0&&(Se=w1e(Se,N,{trailing:!0,leading:!1}));var ve=new ResizeObserver(Se),Oe=G.current.getBoundingClientRect(),Ae=Oe.width,we=Oe.height;return ue(Ae,we),ve.observe(G.current),function(){ve.disconnect()}},[ue,N]);var _e=P.useMemo(function(){var Se=re.containerWidth,ve=re.containerHeight;if(Se<0||ve<0)return null;Xh(Z_(c)||Z_(f),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,c,f),Xh(!r||r>0,"The aspect(%s) must be greater than zero.",r);var Oe=Z_(c)?Se:c,Ae=Z_(f)?ve:f;r&&r>0&&(Oe?Ae=Oe/r:Ae&&(Oe=Ae*r),T&&Ae>T&&(Ae=T)),Xh(Oe>0||Ae>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.`,Oe,Ae,c,f,x,_,r);var we=!Array.isArray(E)&&vm(E.type).endsWith("Chart");return Xe.Children.map(E,function(ge){return Xe.isValidElement(ge)?P.cloneElement(ge,NN({width:Oe,height:Ae},we?{style:NN({height:"100%",width:"100%",maxHeight:Ae,maxWidth:Oe},ge.props.style)}:{})):ge})},[r,E,f,T,_,x,re,c]);return Xe.createElement("div",{id:R?"".concat(R):void 0,className:Li("recharts-responsive-container",D),style:NN(NN({},V),{},{width:c,height:f,minWidth:x,minHeight:_,maxHeight:T}),ref:G},_e)}),LF=function(e){return null};LF.displayName="Cell";function Ik(t){"@babel/helpers - typeof";return Ik=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},Ik(t)}function Mie(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 zV(t){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:{};if(e==null||bm.isSsr)return{width:0,height:0};var n=Pyt(r),i=JSON.stringify({text:e,copyStyle:n});if(zb.widthCache[i])return zb.widthCache[i];try{var a=document.getElementById(Fie);a||(a=document.createElement("span"),a.setAttribute("id",Fie),a.setAttribute("aria-hidden","true"),document.body.appendChild(a));var c=zV(zV({},Iyt),n);Object.assign(a.style,c),a.textContent="".concat(e);var s=a.getBoundingClientRect(),f={width:s.width,height:s.height};return zb.widthCache[i]=f,++zb.cacheCount>jyt&&(zb.cacheCount=0,zb.widthCache={}),f}catch{return{width:0,height:0}}},Nyt=function(e){return{top:e.top+window.scrollY-document.documentElement.clientTop,left:e.left+window.scrollX-document.documentElement.clientLeft}};function Pk(t){"@babel/helpers - typeof";return Pk=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},Pk(t)}function RD(t,e){return Oyt(t)||Dyt(t,e)||Lyt(t,e)||Ryt()}function Ryt(){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 Lyt(t,e){if(t){if(typeof t=="string")return Bie(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 Bie(t,e)}}function Bie(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 Zyt(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 Gie(t,e){return ext(t)||Jyt(t,e)||Qyt(t,e)||Xyt()}function Xyt(){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 Qyt(t,e){if(t){if(typeof t=="string")return Hie(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 Hie(t,e)}}function Hie(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 Oe.reduce(function(Ae,we){var ge=we.word,Ne=we.width,Ie=Ae[Ae.length-1];if(Ie&&(i==null||a||Ie.width+Ne+nwe.width?Ae:we})};if(!x)return E;for(var N="…",R=function(Oe){var Ae=_.slice(0,Oe),we=A1e({breakAll:m,style:f,children:Ae+N}).wordsWithComputedWidth,ge=T(we),Ne=ge.length>c||C(ge).width>Number(i);return[Ne,ge]},D=0,M=_.length-1,B=0,V;D<=M&&B<=_.length-1;){var G=Math.floor((D+M)/2),W=G-1,X=R(W),Q=Gie(X,2),re=Q[0],se=Q[1],ue=R(G),_e=Gie(ue,1),Se=_e[0];if(!re&&!Se&&(D=G+1),re&&Se&&(M=G-1),!re&&Se){V=se;break}B++}return V||E},Wie=function(e){var r=Di(e)?[]:e.toString().split(E1e);return[{words:r}]},rxt=function(e){var r=e.width,n=e.scaleToFit,i=e.children,a=e.style,c=e.breakAll,s=e.maxLines;if((r||n)&&!bm.isSsr){var f,m,x=A1e({breakAll:c,children:i,style:a});if(x){var _=x.wordsWithComputedWidth,T=x.spaceWidth;f=_,m=T}else return Wie(i);return txt({breakAll:c,children:i,maxLines:s,style:a},f,m,r,n)}return Wie(i)},Kie="#808080",P0=function(e){var r=e.x,n=r===void 0?0:r,i=e.y,a=i===void 0?0:i,c=e.lineHeight,s=c===void 0?"1em":c,f=e.capHeight,m=f===void 0?"0.71em":f,x=e.scaleToFit,_=x===void 0?!1:x,T=e.textAnchor,E=T===void 0?"start":T,C=e.verticalAnchor,N=C===void 0?"end":C,R=e.fill,D=R===void 0?Kie:R,M=qie(e,Kyt),B=P.useMemo(function(){return rxt({breakAll:M.breakAll,children:M.children,maxLines:M.maxLines,scaleToFit:_,style:M.style,width:M.width})},[M.breakAll,M.children,M.maxLines,_,M.style,M.width]),V=M.dx,G=M.dy,W=M.angle,X=M.className,Q=M.breakAll,re=qie(M,Yyt);if(!cl(n)||!cl(a))return null;var se=n+(Wr(V)?V:0),ue=a+(Wr(G)?G:0),_e;switch(N){case"start":_e=Ez("calc(".concat(m,")"));break;case"middle":_e=Ez("calc(".concat((B.length-1)/2," * -").concat(s," + (").concat(m," / 2))"));break;default:_e=Ez("calc(".concat(B.length-1," * -").concat(s,")"));break}var Se=[];if(_){var ve=B[0].width,Oe=M.width;Se.push("scale(".concat((Wr(Oe)?Oe/ve:1)/ve,")"))}return W&&Se.push("rotate(".concat(W,", ").concat(se,", ").concat(ue,")")),Se.length&&(re.transform=Se.join(" ")),Xe.createElement("text",$V({},ui(re,!0),{x:se,y:ue,className:Li("recharts-text",X),textAnchor:E,fill:D.includes("url")?Kie:D}),B.map(function(Ae,we){var ge=Ae.words.join(Q?"":" ");return Xe.createElement("tspan",{x:se,dy:we===0?_e:s,key:"".concat(ge,"-").concat(we)},ge)}))};function Ry(t,e){return t==null||e==null?NaN:te?1:t>=e?0:NaN}function nxt(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}function pH(t){let e,r,n;t.length!==2?(e=Ry,r=(s,f)=>Ry(t(s),f),n=(s,f)=>t(s)-f):(e=t===Ry||t===nxt?t:ixt,r=t,n=t);function i(s,f,m=0,x=s.length){if(m>>1;r(s[_],f)<0?m=_+1:x=_}while(m>>1;r(s[_],f)<=0?m=_+1:x=_}while(mm&&n(s[_-1],f)>-n(s[_],f)?_-1:_}return{left:i,center:c,right:a}}function ixt(){return 0}function k1e(t){return t===null?NaN:+t}function*sxt(t,e){for(let r of t)r!=null&&(r=+r)>=r&&(yield r)}const axt=pH(Ry),oj=axt.right;pH(k1e).center;class Yie extends Map{constructor(e,r=cxt){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(Zie(this,e))}has(e){return super.has(Zie(this,e))}set(e,r){return super.set(oxt(this,e),r)}delete(e){return super.delete(lxt(this,e))}}function Zie({_intern:t,_key:e},r){const n=e(r);return t.has(n)?t.get(n):r}function oxt({_intern:t,_key:e},r){const n=e(r);return t.has(n)?t.get(n):(t.set(n,r),r)}function lxt({_intern:t,_key:e},r){const n=e(r);return t.has(n)&&(r=t.get(n),t.delete(n)),r}function cxt(t){return t!==null&&typeof t=="object"?t.valueOf():t}function uxt(t=Ry){if(t===Ry)return C1e;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 C1e(t,e){return(t==null||!(t>=t))-(e==null||!(e>=e))||(te?1:0)}const dxt=Math.sqrt(50),hxt=Math.sqrt(10),fxt=Math.sqrt(2);function LD(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>=dxt?10:a>=hxt?5:a>=fxt?2:1;let s,f,m;return i<0?(m=Math.pow(10,-i)/c,s=Math.round(t*m),f=Math.round(e*m),s/me&&--f,m=-m):(m=Math.pow(10,i)*c,s=Math.round(t/m),f=Math.round(e/m),s*me&&--f),f0))return[];if(t===e)return[t];const n=e=i))return[];const s=a-i+1,f=new Array(s);if(n)if(c<0)for(let m=0;m=n)&&(r=n);return r}function Qie(t,e){let r;for(const n of t)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function j1e(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?C1e:uxt(i);n>r;){if(n-r>600){const f=n-r+1,m=e-r+1,x=Math.log(f),_=.5*Math.exp(2*x/3),T=.5*Math.sqrt(x*_*(f-_)/f)*(m-f/2<0?-1:1),E=Math.max(r,Math.floor(e-m*_/f+T)),C=Math.min(n,Math.floor(e+(f-m)*_/f+T));j1e(t,e,E,C,i)}const a=t[e];let c=r,s=n;for(k2(t,r,e),i(t[n],a)>0&&k2(t,r,n);c0;)--s}i(t[r],a)===0?k2(t,r,s):(++s,k2(t,s,n)),s<=e&&(r=s+1),e<=s&&(n=s-1)}return t}function k2(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function pxt(t,e,r){if(t=Float64Array.from(sxt(t)),!(!(n=t.length)||isNaN(e=+e))){if(e<=0||n<2)return Qie(t);if(e>=1)return Xie(t);var n,i=(n-1)*e,a=Math.floor(i),c=Xie(j1e(t,a).subarray(0,a+1)),s=Qie(t.subarray(a+1));return c+(s-c)*(i-a)}}function mxt(t,e,r=k1e){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),s=+r(t[a+1],a+1,t);return c+(s-c)*(i-a)}}function gxt(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?LN(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):r===4?LN(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=xxt.exec(t))?new wu(e[1],e[2],e[3],1):(e=_xt.exec(t))?new wu(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=vxt.exec(t))?LN(e[1],e[2],e[3],e[4]):(e=bxt.exec(t))?LN(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=wxt.exec(t))?sse(e[1],e[2]/100,e[3]/100,1):(e=Sxt.exec(t))?sse(e[1],e[2]/100,e[3]/100,e[4]):Jie.hasOwnProperty(t)?rse(Jie[t]):t==="transparent"?new wu(NaN,NaN,NaN,0):null}function rse(t){return new wu(t>>16&255,t>>8&255,t&255,1)}function LN(t,e,r,n){return n<=0&&(t=e=r=NaN),new wu(t,e,r,n)}function Axt(t){return t instanceof lj||(t=Dk(t)),t?(t=t.rgb(),new wu(t.r,t.g,t.b,t.opacity)):new wu}function HV(t,e,r,n){return arguments.length===1?Axt(t):new wu(t,e,r,n??1)}function wu(t,e,r,n){this.r=+t,this.g=+e,this.b=+r,this.opacity=+n}gH(wu,HV,P1e(lj,{brighter(t){return t=t==null?DD:Math.pow(DD,t),new wu(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?Rk:Math.pow(Rk,t),new wu(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new wu(p0(this.r),p0(this.g),p0(this.b),OD(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:nse,formatHex:nse,formatHex8:kxt,formatRgb:ise,toString:ise}));function nse(){return`#${X_(this.r)}${X_(this.g)}${X_(this.b)}`}function kxt(){return`#${X_(this.r)}${X_(this.g)}${X_(this.b)}${X_((isNaN(this.opacity)?1:this.opacity)*255)}`}function ise(){const t=OD(this.opacity);return`${t===1?"rgb(":"rgba("}${p0(this.r)}, ${p0(this.g)}, ${p0(this.b)}${t===1?")":`, ${t})`}`}function OD(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function p0(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function X_(t){return t=p0(t),(t<16?"0":"")+t.toString(16)}function sse(t,e,r,n){return n<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new Vh(t,e,r,n)}function N1e(t){if(t instanceof Vh)return new Vh(t.h,t.s,t.l,t.opacity);if(t instanceof lj||(t=Dk(t)),!t)return new Vh;if(t instanceof Vh)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,s=a-i,f=(a+i)/2;return s?(e===a?c=(r-n)/s+(r0&&f<1?0:c,new Vh(c,s,f,t.opacity)}function Cxt(t,e,r,n){return arguments.length===1?N1e(t):new Vh(t,e,r,n??1)}function Vh(t,e,r,n){this.h=+t,this.s=+e,this.l=+r,this.opacity=+n}gH(Vh,Cxt,P1e(lj,{brighter(t){return t=t==null?DD:Math.pow(DD,t),new Vh(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?Rk:Math.pow(Rk,t),new Vh(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 wu(Az(t>=240?t-240:t+120,i,n),Az(t,i,n),Az(t<120?t+240:t-120,i,n),this.opacity)},clamp(){return new Vh(ase(this.h),DN(this.s),DN(this.l),OD(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=OD(this.opacity);return`${t===1?"hsl(":"hsla("}${ase(this.h)}, ${DN(this.s)*100}%, ${DN(this.l)*100}%${t===1?")":`, ${t})`}`}}));function ase(t){return t=(t||0)%360,t<0?t+360:t}function DN(t){return Math.max(0,Math.min(1,t||0))}function Az(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 yH=t=>()=>t;function jxt(t,e){return function(r){return t+r*e}}function Ixt(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 Pxt(t){return(t=+t)==1?R1e:function(e,r){return r-e?Ixt(e,r,t):yH(isNaN(e)?r:e)}}function R1e(t,e){var r=e-t;return r?jxt(t,r):yH(isNaN(t)?e:t)}const ose=function t(e){var r=Pxt(e);function n(i,a){var c=r((i=HV(i)).r,(a=HV(a)).r),s=r(i.g,a.g),f=r(i.b,a.b),m=R1e(i.opacity,a.opacity);return function(x){return i.r=c(x),i.g=s(x),i.b=f(x),i.opacity=m(x),i+""}}return n.gamma=t,n}(1);function Nxt(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),s[c]?s[c]+=a:s[++c]=a),(n=n[0])===(i=i[0])?s[c]?s[c]+=i:s[++c]=i:(s[++c]=null,f.push({i:c,x:MD(n,i)})),r=kz.lastIndex;return re&&(r=t,t=e,e=r),function(n){return Math.max(t,Math.min(e,n))}}function Vxt(t,e,r){var n=t[0],i=t[1],a=e[0],c=e[1];return i2?qxt:Vxt,f=m=null,_}function _(T){return T==null||isNaN(T=+T)?a:(f||(f=s(t.map(n),e,r)))(n(c(T)))}return _.invert=function(T){return c(i((m||(m=s(e,t.map(n),MD)))(T)))},_.domain=function(T){return arguments.length?(t=Array.from(T,FD),x()):t.slice()},_.range=function(T){return arguments.length?(e=Array.from(T),x()):e.slice()},_.rangeRound=function(T){return e=Array.from(T),r=xH,x()},_.clamp=function(T){return arguments.length?(c=T?!0:Wc,x()):c!==Wc},_.interpolate=function(T){return arguments.length?(r=T,x()):r},_.unknown=function(T){return arguments.length?(a=T,_):a},function(T,E){return n=T,i=E,x()}}function _H(){return DF()(Wc,Wc)}function Gxt(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function BD(t,e){if((r=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var r,n=t.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+t.slice(r+1)]}function O1(t){return t=BD(Math.abs(t)),t?t[1]:NaN}function Hxt(t,e){return function(r,n){for(var i=r.length,a=[],c=0,s=t[0],f=0;i>0&&s>0&&(f+s+1>n&&(s=Math.max(1,n-f)),a.push(r.substring(i-=s,i+s)),!((f+=s+1)>n));)s=t[c=(c+1)%t.length];return a.reverse().join(e)}}function Wxt(t){return function(e){return e.replace(/[0-9]/g,function(r){return t[+r]})}}var Kxt=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Ok(t){if(!(e=Kxt.exec(t)))throw new Error("invalid format: "+t);var e;return new vH({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]})}Ok.prototype=vH.prototype;function vH(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+""}vH.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 Yxt(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 L1e;function Zxt(t,e){var r=BD(t,e);if(!r)return t+"";var n=r[0],i=r[1],a=i-(L1e=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")+BD(t,Math.max(0,e+a-1))[0]}function cse(t,e){var r=BD(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 use={"%":(t,e)=>(t*100).toFixed(e),b:t=>Math.round(t).toString(2),c:t=>t+"",d:Gxt,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)=>cse(t*100,e),r:cse,s:Zxt,X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function dse(t){return t}var hse=Array.prototype.map,fse=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Xxt(t){var e=t.grouping===void 0||t.thousands===void 0?dse:Hxt(hse.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?dse:Wxt(hse.call(t.numerals,String)),c=t.percent===void 0?"%":t.percent+"",s=t.minus===void 0?"−":t.minus+"",f=t.nan===void 0?"NaN":t.nan+"";function m(_){_=Ok(_);var T=_.fill,E=_.align,C=_.sign,N=_.symbol,R=_.zero,D=_.width,M=_.comma,B=_.precision,V=_.trim,G=_.type;G==="n"?(M=!0,G="g"):use[G]||(B===void 0&&(B=12),V=!0,G="g"),(R||T==="0"&&E==="=")&&(R=!0,T="0",E="=");var W=N==="$"?r:N==="#"&&/[boxX]/.test(G)?"0"+G.toLowerCase():"",X=N==="$"?n:/[%p]/.test(G)?c:"",Q=use[G],re=/[defgprs%]/.test(G);B=B===void 0?6:/[gprs]/.test(G)?Math.max(1,Math.min(21,B)):Math.max(0,Math.min(20,B));function se(ue){var _e=W,Se=X,ve,Oe,Ae;if(G==="c")Se=Q(ue)+Se,ue="";else{ue=+ue;var we=ue<0||1/ue<0;if(ue=isNaN(ue)?f:Q(Math.abs(ue),B),V&&(ue=Yxt(ue)),we&&+ue==0&&C!=="+"&&(we=!1),_e=(we?C==="("?C:s:C==="-"||C==="("?"":C)+_e,Se=(G==="s"?fse[8+L1e/3]:"")+Se+(we&&C==="("?")":""),re){for(ve=-1,Oe=ue.length;++veAe||Ae>57){Se=(Ae===46?i+ue.slice(ve+1):ue.slice(ve))+Se,ue=ue.slice(0,ve);break}}}M&&!R&&(ue=e(ue,1/0));var ge=_e.length+ue.length+Se.length,Ne=ge>1)+_e+ue+Se+Ne.slice(ge);break;default:ue=Ne+_e+ue+Se;break}return a(ue)}return se.toString=function(){return _+""},se}function x(_,T){var E=m((_=Ok(_),_.type="f",_)),C=Math.max(-8,Math.min(8,Math.floor(O1(T)/3)))*3,N=Math.pow(10,-C),R=fse[8+C/3];return function(D){return E(N*D)+R}}return{format:m,formatPrefix:x}}var ON,bH,D1e;Qxt({thousands:",",grouping:[3],currency:["$",""]});function Qxt(t){return ON=Xxt(t),bH=ON.format,D1e=ON.formatPrefix,ON}function Jxt(t){return Math.max(0,-O1(Math.abs(t)))}function e_t(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(O1(e)/3)))*3-O1(Math.abs(t)))}function t_t(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,O1(e)-O1(t))+1}function O1e(t,e,r,n){var i=qV(t,e,r),a;switch(n=Ok(n??",f"),n.type){case"s":{var c=Math.max(Math.abs(t),Math.abs(e));return n.precision==null&&!isNaN(a=e_t(i,c))&&(n.precision=a),D1e(n,c)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(a=t_t(i,Math.max(Math.abs(t),Math.abs(e))))&&(n.precision=a-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(a=Jxt(i))&&(n.precision=a-(n.type==="%")*2);break}}return bH(n)}function px(t){var e=t.domain;return t.ticks=function(r){var n=e();return UV(n[0],n[n.length-1],r??10)},t.tickFormat=function(r,n){var i=e();return O1e(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],s=n[a],f,m,x=10;for(s0;){if(m=VV(c,s,r),m===f)return n[i]=c,n[a]=s,e(n);if(m>0)c=Math.floor(c/m)*m,s=Math.ceil(s/m)*m;else if(m<0)c=Math.ceil(c*m)/m,s=Math.floor(s*m)/m;else break;f=m}return t},t}function zD(){var t=_H();return t.copy=function(){return cj(t,zD())},sh.apply(t,arguments),px(t)}function M1e(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,FD),r):t.slice()},r.unknown=function(n){return arguments.length?(e=n,r):e},r.copy=function(){return M1e(t).unknown(e)},t=arguments.length?Array.from(t,FD):[0,1],px(r)}function F1e(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 a_t(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 gse(t){return(e,r)=>-t(-e,r)}function wH(t){const e=t(pse,mse),r=e.domain;let n=10,i,a;function c(){return i=a_t(n),a=s_t(n),r()[0]<0?(i=gse(i),a=gse(a),t(r_t,n_t)):t(pse,mse),e}return e.base=function(s){return arguments.length?(n=+s,c()):n},e.domain=function(s){return arguments.length?(r(s),c()):r()},e.ticks=s=>{const f=r();let m=f[0],x=f[f.length-1];const _=x0){for(;T<=E;++T)for(C=1;Cx)break;D.push(N)}}else for(;T<=E;++T)for(C=n-1;C>=1;--C)if(N=T>0?C/a(-T):C*a(T),!(Nx)break;D.push(N)}D.length*2{if(s==null&&(s=10),f==null&&(f=n===10?"s":","),typeof f!="function"&&(!(n%1)&&(f=Ok(f)).precision==null&&(f.trim=!0),f=bH(f)),s===1/0)return f;const m=Math.max(1,n*s/e.ticks().length);return x=>{let _=x/a(Math.round(i(x)));return _*nr(F1e(r(),{floor:s=>a(Math.floor(i(s))),ceil:s=>a(Math.ceil(i(s)))})),e}function B1e(){const t=wH(DF()).domain([1,10]);return t.copy=()=>cj(t,B1e()).base(t.base()),sh.apply(t,arguments),t}function yse(t){return function(e){return Math.sign(e)*Math.log1p(Math.abs(e/t))}}function xse(t){return function(e){return Math.sign(e)*Math.expm1(Math.abs(e))*t}}function SH(t){var e=1,r=t(yse(e),xse(e));return r.constant=function(n){return arguments.length?t(yse(e=+n),xse(e)):e},px(r)}function z1e(){var t=SH(DF());return t.copy=function(){return cj(t,z1e()).constant(t.constant())},sh.apply(t,arguments)}function _se(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}function o_t(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function l_t(t){return t<0?-t*t:t*t}function TH(t){var e=t(Wc,Wc),r=1;function n(){return r===1?t(Wc,Wc):r===.5?t(o_t,l_t):t(_se(r),_se(1/r))}return e.exponent=function(i){return arguments.length?(r=+i,n()):r},px(e)}function EH(){var t=TH(DF());return t.copy=function(){return cj(t,EH()).exponent(t.exponent())},sh.apply(t,arguments),t}function c_t(){return EH.apply(null,arguments).exponent(.5)}function vse(t){return Math.sign(t)*t*t}function u_t(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}function $1e(){var t=_H(),e=[0,1],r=!1,n;function i(a){var c=u_t(t(a));return isNaN(c)?n:r?Math.round(c):c}return i.invert=function(a){return t.invert(vse(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,FD)).map(vse)),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 $1e(t.domain(),e).round(r).clamp(t.clamp()).unknown(n)},sh.apply(i,arguments),px(i)}function U1e(){var t=[],e=[],r=[],n;function i(){var c=0,s=Math.max(1,e.length);for(r=new Array(s-1);++c0?r[s-1]:t[0],s=r?[n[r-1],e]:[n[m-1],n[m]]},c.unknown=function(f){return arguments.length&&(a=f),c},c.thresholds=function(){return n.slice()},c.copy=function(){return V1e().domain([t,e]).range(i).unknown(a)},sh.apply(px(c),arguments)}function q1e(){var t=[.5],e=[0,1],r,n=1;function i(a){return a!=null&&a<=a?e[oj(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 q1e().domain(t).range(e).unknown(r)},sh.apply(i,arguments)}const Cz=new Date,jz=new Date;function hl(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),s=i.ceil(a);return a-c(e(a=new Date(+a),c==null?1:Math.floor(c)),a),i.range=(a,c,s)=>{const f=[];if(a=i.ceil(a),s=s==null?1:Math.floor(s),!(a0))return f;let m;do f.push(m=new Date(+a)),e(a,s),t(a);while(mhl(c=>{if(c>=c)for(;t(c),!a(c);)c.setTime(c-1)},(c,s)=>{if(c>=c)if(s<0)for(;++s<=0;)for(;e(c,-1),!a(c););else for(;--s>=0;)for(;e(c,1),!a(c););}),r&&(i.count=(a,c)=>(Cz.setTime(+a),jz.setTime(+c),t(Cz),t(jz),Math.floor(r(Cz,jz))),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 $D=hl(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);$D.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?hl(e=>{e.setTime(Math.floor(e/t)*t)},(e,r)=>{e.setTime(+e+r*t)},(e,r)=>(r-e)/t):$D);$D.range;const fm=1e3,Ud=fm*60,pm=Ud*60,Dm=pm*24,AH=Dm*7,bse=Dm*30,Iz=Dm*365,Q_=hl(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*fm)},(t,e)=>(e-t)/fm,t=>t.getUTCSeconds());Q_.range;const kH=hl(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*fm)},(t,e)=>{t.setTime(+t+e*Ud)},(t,e)=>(e-t)/Ud,t=>t.getMinutes());kH.range;const CH=hl(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*Ud)},(t,e)=>(e-t)/Ud,t=>t.getUTCMinutes());CH.range;const jH=hl(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*fm-t.getMinutes()*Ud)},(t,e)=>{t.setTime(+t+e*pm)},(t,e)=>(e-t)/pm,t=>t.getHours());jH.range;const IH=hl(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*pm)},(t,e)=>(e-t)/pm,t=>t.getUTCHours());IH.range;const uj=hl(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*Ud)/Dm,t=>t.getDate()-1);uj.range;const OF=hl(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Dm,t=>t.getUTCDate()-1);OF.range;const G1e=hl(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/Dm,t=>Math.floor(t/Dm));G1e.range;function W0(t){return hl(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())*Ud)/AH)}const MF=W0(0),UD=W0(1),d_t=W0(2),h_t=W0(3),M1=W0(4),f_t=W0(5),p_t=W0(6);MF.range;UD.range;d_t.range;h_t.range;M1.range;f_t.range;p_t.range;function K0(t){return hl(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)/AH)}const FF=K0(0),VD=K0(1),m_t=K0(2),g_t=K0(3),F1=K0(4),y_t=K0(5),x_t=K0(6);FF.range;VD.range;m_t.range;g_t.range;F1.range;y_t.range;x_t.range;const PH=hl(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());PH.range;const NH=hl(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());NH.range;const Om=hl(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());Om.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:hl(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)});Om.range;const Mm=hl(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());Mm.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:hl(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)});Mm.range;function H1e(t,e,r,n,i,a){const c=[[Q_,1,fm],[Q_,5,5*fm],[Q_,15,15*fm],[Q_,30,30*fm],[a,1,Ud],[a,5,5*Ud],[a,15,15*Ud],[a,30,30*Ud],[i,1,pm],[i,3,3*pm],[i,6,6*pm],[i,12,12*pm],[n,1,Dm],[n,2,2*Dm],[r,1,AH],[e,1,bse],[e,3,3*bse],[t,1,Iz]];function s(m,x,_){const T=xR).right(c,T);if(E===c.length)return t.every(qV(m/Iz,x/Iz,_));if(E===0)return $D.every(Math.max(qV(m,x,_),1));const[C,N]=c[T/c[E-1][2]53)return null;"w"in wt||(wt.w=1),"Z"in wt?(Sr=Nz(C2(wt.y,0,1)),nn=Sr.getUTCDay(),Sr=nn>4||nn===0?VD.ceil(Sr):VD(Sr),Sr=OF.offset(Sr,(wt.V-1)*7),wt.y=Sr.getUTCFullYear(),wt.m=Sr.getUTCMonth(),wt.d=Sr.getUTCDate()+(wt.w+6)%7):(Sr=Pz(C2(wt.y,0,1)),nn=Sr.getDay(),Sr=nn>4||nn===0?UD.ceil(Sr):UD(Sr),Sr=uj.offset(Sr,(wt.V-1)*7),wt.y=Sr.getFullYear(),wt.m=Sr.getMonth(),wt.d=Sr.getDate()+(wt.w+6)%7)}else("W"in wt||"U"in wt)&&("w"in wt||(wt.w="u"in wt?wt.u%7:"W"in wt?1:0),nn="Z"in wt?Nz(C2(wt.y,0,1)).getUTCDay():Pz(C2(wt.y,0,1)).getDay(),wt.m=0,wt.d="W"in wt?(wt.w+6)%7+wt.W*7-(nn+5)%7:wt.w+wt.U*7-(nn+6)%7);return"Z"in wt?(wt.H+=wt.Z/100|0,wt.M+=wt.Z%100,Nz(wt)):Pz(wt)}}function Q(mt,Pt,er,wt){for(var or=0,Sr=Pt.length,nn=er.length,lr,yr;or=nn)return-1;if(lr=Pt.charCodeAt(or++),lr===37){if(lr=Pt.charAt(or++),yr=G[lr in wse?Pt.charAt(or++):lr],!yr||(wt=yr(mt,er,wt))<0)return-1}else if(lr!=er.charCodeAt(wt++))return-1}return wt}function re(mt,Pt,er){var wt=m.exec(Pt.slice(er));return wt?(mt.p=x.get(wt[0].toLowerCase()),er+wt[0].length):-1}function se(mt,Pt,er){var wt=E.exec(Pt.slice(er));return wt?(mt.w=C.get(wt[0].toLowerCase()),er+wt[0].length):-1}function ue(mt,Pt,er){var wt=_.exec(Pt.slice(er));return wt?(mt.w=T.get(wt[0].toLowerCase()),er+wt[0].length):-1}function _e(mt,Pt,er){var wt=D.exec(Pt.slice(er));return wt?(mt.m=M.get(wt[0].toLowerCase()),er+wt[0].length):-1}function Se(mt,Pt,er){var wt=N.exec(Pt.slice(er));return wt?(mt.m=R.get(wt[0].toLowerCase()),er+wt[0].length):-1}function ve(mt,Pt,er){return Q(mt,e,Pt,er)}function Oe(mt,Pt,er){return Q(mt,r,Pt,er)}function Ae(mt,Pt,er){return Q(mt,n,Pt,er)}function we(mt){return c[mt.getDay()]}function ge(mt){return a[mt.getDay()]}function Ne(mt){return f[mt.getMonth()]}function Ie(mt){return s[mt.getMonth()]}function Te(mt){return i[+(mt.getHours()>=12)]}function be(mt){return 1+~~(mt.getMonth()/3)}function We(mt){return c[mt.getUTCDay()]}function rt(mt){return a[mt.getUTCDay()]}function at(mt){return f[mt.getUTCMonth()]}function Et(mt){return s[mt.getUTCMonth()]}function _t(mt){return i[+(mt.getUTCHours()>=12)]}function Vt(mt){return 1+~~(mt.getUTCMonth()/3)}return{format:function(mt){var Pt=W(mt+="",B);return Pt.toString=function(){return mt},Pt},parse:function(mt){var Pt=X(mt+="",!1);return Pt.toString=function(){return mt},Pt},utcFormat:function(mt){var Pt=W(mt+="",V);return Pt.toString=function(){return mt},Pt},utcParse:function(mt){var Pt=X(mt+="",!0);return Pt.toString=function(){return mt},Pt}}}var wse={"-":"",_:" ",0:"0"},Il=/^\s*\d+/,T_t=/^%/,E_t=/[\\^$*+?|[\]().{}]/g;function xs(t,e,r){var n=t<0?"-":"",i=(n?-t:t)+"",a=i.length;return n+(a[e.toLowerCase(),r]))}function k_t(t,e,r){var n=Il.exec(e.slice(r,r+1));return n?(t.w=+n[0],r+n[0].length):-1}function C_t(t,e,r){var n=Il.exec(e.slice(r,r+1));return n?(t.u=+n[0],r+n[0].length):-1}function j_t(t,e,r){var n=Il.exec(e.slice(r,r+2));return n?(t.U=+n[0],r+n[0].length):-1}function I_t(t,e,r){var n=Il.exec(e.slice(r,r+2));return n?(t.V=+n[0],r+n[0].length):-1}function P_t(t,e,r){var n=Il.exec(e.slice(r,r+2));return n?(t.W=+n[0],r+n[0].length):-1}function Sse(t,e,r){var n=Il.exec(e.slice(r,r+4));return n?(t.y=+n[0],r+n[0].length):-1}function Tse(t,e,r){var n=Il.exec(e.slice(r,r+2));return n?(t.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function N_t(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 R_t(t,e,r){var n=Il.exec(e.slice(r,r+1));return n?(t.q=n[0]*3-3,r+n[0].length):-1}function L_t(t,e,r){var n=Il.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function Ese(t,e,r){var n=Il.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function D_t(t,e,r){var n=Il.exec(e.slice(r,r+3));return n?(t.m=0,t.d=+n[0],r+n[0].length):-1}function Ase(t,e,r){var n=Il.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function O_t(t,e,r){var n=Il.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function M_t(t,e,r){var n=Il.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function F_t(t,e,r){var n=Il.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function B_t(t,e,r){var n=Il.exec(e.slice(r,r+6));return n?(t.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function z_t(t,e,r){var n=T_t.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function $_t(t,e,r){var n=Il.exec(e.slice(r));return n?(t.Q=+n[0],r+n[0].length):-1}function U_t(t,e,r){var n=Il.exec(e.slice(r));return n?(t.s=+n[0],r+n[0].length):-1}function kse(t,e){return xs(t.getDate(),e,2)}function V_t(t,e){return xs(t.getHours(),e,2)}function q_t(t,e){return xs(t.getHours()%12||12,e,2)}function G_t(t,e){return xs(1+uj.count(Om(t),t),e,3)}function W1e(t,e){return xs(t.getMilliseconds(),e,3)}function H_t(t,e){return W1e(t,e)+"000"}function W_t(t,e){return xs(t.getMonth()+1,e,2)}function K_t(t,e){return xs(t.getMinutes(),e,2)}function Y_t(t,e){return xs(t.getSeconds(),e,2)}function Z_t(t){var e=t.getDay();return e===0?7:e}function X_t(t,e){return xs(MF.count(Om(t)-1,t),e,2)}function K1e(t){var e=t.getDay();return e>=4||e===0?M1(t):M1.ceil(t)}function Q_t(t,e){return t=K1e(t),xs(M1.count(Om(t),t)+(Om(t).getDay()===4),e,2)}function J_t(t){return t.getDay()}function e0t(t,e){return xs(UD.count(Om(t)-1,t),e,2)}function t0t(t,e){return xs(t.getFullYear()%100,e,2)}function r0t(t,e){return t=K1e(t),xs(t.getFullYear()%100,e,2)}function n0t(t,e){return xs(t.getFullYear()%1e4,e,4)}function i0t(t,e){var r=t.getDay();return t=r>=4||r===0?M1(t):M1.ceil(t),xs(t.getFullYear()%1e4,e,4)}function s0t(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+xs(e/60|0,"0",2)+xs(e%60,"0",2)}function Cse(t,e){return xs(t.getUTCDate(),e,2)}function a0t(t,e){return xs(t.getUTCHours(),e,2)}function o0t(t,e){return xs(t.getUTCHours()%12||12,e,2)}function l0t(t,e){return xs(1+OF.count(Mm(t),t),e,3)}function Y1e(t,e){return xs(t.getUTCMilliseconds(),e,3)}function c0t(t,e){return Y1e(t,e)+"000"}function u0t(t,e){return xs(t.getUTCMonth()+1,e,2)}function d0t(t,e){return xs(t.getUTCMinutes(),e,2)}function h0t(t,e){return xs(t.getUTCSeconds(),e,2)}function f0t(t){var e=t.getUTCDay();return e===0?7:e}function p0t(t,e){return xs(FF.count(Mm(t)-1,t),e,2)}function Z1e(t){var e=t.getUTCDay();return e>=4||e===0?F1(t):F1.ceil(t)}function m0t(t,e){return t=Z1e(t),xs(F1.count(Mm(t),t)+(Mm(t).getUTCDay()===4),e,2)}function g0t(t){return t.getUTCDay()}function y0t(t,e){return xs(VD.count(Mm(t)-1,t),e,2)}function x0t(t,e){return xs(t.getUTCFullYear()%100,e,2)}function _0t(t,e){return t=Z1e(t),xs(t.getUTCFullYear()%100,e,2)}function v0t(t,e){return xs(t.getUTCFullYear()%1e4,e,4)}function b0t(t,e){var r=t.getUTCDay();return t=r>=4||r===0?F1(t):F1.ceil(t),xs(t.getUTCFullYear()%1e4,e,4)}function w0t(){return"+0000"}function jse(){return"%"}function Ise(t){return+t}function Pse(t){return Math.floor(+t/1e3)}var $b,X1e,Q1e;S0t({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 S0t(t){return $b=S_t(t),X1e=$b.format,$b.parse,Q1e=$b.utcFormat,$b.utcParse,$b}function T0t(t){return new Date(t)}function E0t(t){return t instanceof Date?+t:+new Date(+t)}function RH(t,e,r,n,i,a,c,s,f,m){var x=_H(),_=x.invert,T=x.domain,E=m(".%L"),C=m(":%S"),N=m("%I:%M"),R=m("%I %p"),D=m("%a %d"),M=m("%b %d"),B=m("%B"),V=m("%Y");function G(W){return(f(W)e(i/(t.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(i,a)=>pxt(t,a/n))},r.copy=function(){return rSe(e).domain(t)},Hm.apply(r,arguments)}function zF(){var t=0,e=.5,r=1,n=1,i,a,c,s,f,m=Wc,x,_=!1,T;function E(N){return isNaN(N=+N)?T:(N=.5+((N=+x(N))-a)*(n*Ne}var aSe=N0t,R0t=$F,L0t=aSe,D0t=FS;function O0t(t){return t&&t.length?R0t(t,D0t,L0t):void 0}var M0t=O0t;const UF=ds(M0t);function F0t(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};An.decimalPlaces=An.dp=function(){var t=this,e=t.d.length-1,r=(e-t.e)*Aa;if(e=t.d[e],e)for(;e%10==0;e/=10)r--;return r<0?0:r};An.dividedBy=An.div=function(t){return wm(this,new this.constructor(t))};An.dividedToIntegerBy=An.idiv=function(t){var e=this,r=e.constructor;return ta(wm(e,new r(t),0,1),r.precision)};An.equals=An.eq=function(t){return!this.cmp(t)};An.exponent=function(){return qo(this)};An.greaterThan=An.gt=function(t){return this.cmp(t)>0};An.greaterThanOrEqualTo=An.gte=function(t){return this.cmp(t)>=0};An.isInteger=An.isint=function(){return this.e>this.d.length-2};An.isNegative=An.isneg=function(){return this.s<0};An.isPositive=An.ispos=function(){return this.s>0};An.isZero=function(){return this.s===0};An.lessThan=An.lt=function(t){return this.cmp(t)<0};An.lessThanOrEqualTo=An.lte=function(t){return this.cmp(t)<1};An.logarithm=An.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(Xu))throw Error(Jd+"NaN");if(r.s<1)throw Error(Jd+(r.s?"NaN":"-Infinity"));return r.eq(Xu)?new n(0):(Fa=!1,e=wm(Mk(r,a),Mk(t,a),a),Fa=!0,ta(e,i))};An.minus=An.sub=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?dSe(e,t):cSe(e,(t.s=-t.s,t))};An.modulo=An.mod=function(t){var e,r=this,n=r.constructor,i=n.precision;if(t=new n(t),!t.s)throw Error(Jd+"NaN");return r.s?(Fa=!1,e=wm(r,t,0,1).times(t),Fa=!0,r.minus(e)):ta(new n(r),i)};An.naturalExponential=An.exp=function(){return uSe(this)};An.naturalLogarithm=An.ln=function(){return Mk(this)};An.negated=An.neg=function(){var t=new this.constructor(this);return t.s=-t.s||0,t};An.plus=An.add=function(t){var e=this;return t=new e.constructor(t),e.s==t.s?cSe(e,t):dSe(e,(t.s=-t.s,t))};An.precision=An.sd=function(t){var e,r,n,i=this;if(t!==void 0&&t!==!!t&&t!==1&&t!==0)throw Error(m0+t);if(e=qo(i)+1,n=i.d.length-1,r=n*Aa+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};An.squareRoot=An.sqrt=function(){var t,e,r,n,i,a,c,s=this,f=s.constructor;if(s.s<1){if(!s.s)return new f(0);throw Error(Jd+"NaN")}for(t=qo(s),Fa=!1,i=Math.sqrt(+s),i==0||i==1/0?(e=Gf(s.d),(e.length+t)%2==0&&(e+="0"),i=Math.sqrt(e),t=$S((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 f(e)):n=new f(i.toString()),r=f.precision,i=c=r+3;;)if(a=n,n=a.plus(wm(s,a,c+2)).times(.5),Gf(a.d).slice(0,c)===(e=Gf(n.d)).slice(0,c)){if(e=e.slice(c-3,c+1),i==c&&e=="4999"){if(ta(a,r+1,0),a.times(a).eq(s)){n=a;break}}else if(e!="9999")break;c+=4}return Fa=!0,ta(n,r)};An.times=An.mul=function(t){var e,r,n,i,a,c,s,f,m,x=this,_=x.constructor,T=x.d,E=(t=new _(t)).d;if(!x.s||!t.s)return new _(0);for(t.s*=x.s,r=x.e+t.e,f=T.length,m=E.length,f=0;){for(e=0,i=f+n;i>n;)s=a[i]+E[n]*T[i-n-1]+e,a[i--]=s%wl|0,e=s/wl|0;a[i]=(a[i]+e)%wl|0}for(;!a[--c];)a.pop();return e?++r:a.shift(),t.d=a,t.e=r,Fa?ta(t,_.precision):t};An.toDecimalPlaces=An.todp=function(t,e){var r=this,n=r.constructor;return r=new n(r),t===void 0?r:(op(t,0,zS),e===void 0?e=n.rounding:op(e,0,8),ta(r,t+qo(r)+1,e))};An.toExponential=function(t,e){var r,n=this,i=n.constructor;return t===void 0?r=N0(n,!0):(op(t,0,zS),e===void 0?e=i.rounding:op(e,0,8),n=ta(new i(n),t+1,e),r=N0(n,!0,t+1)),r};An.toFixed=function(t,e){var r,n,i=this,a=i.constructor;return t===void 0?N0(i):(op(t,0,zS),e===void 0?e=a.rounding:op(e,0,8),n=ta(new a(i),t+qo(i)+1,e),r=N0(n.abs(),!1,t+qo(n)+1),i.isneg()&&!i.isZero()?"-"+r:r)};An.toInteger=An.toint=function(){var t=this,e=t.constructor;return ta(new e(t),qo(t)+1,e.rounding)};An.toNumber=function(){return+this};An.toPower=An.pow=function(t){var e,r,n,i,a,c,s=this,f=s.constructor,m=12,x=+(t=new f(t));if(!t.s)return new f(Xu);if(s=new f(s),!s.s){if(t.s<1)throw Error(Jd+"Infinity");return s}if(s.eq(Xu))return s;if(n=f.precision,t.eq(Xu))return ta(s,n);if(e=t.e,r=t.d.length-1,c=e>=r,a=s.s,c){if((r=x<0?-x:x)<=lSe){for(i=new f(Xu),e=Math.ceil(n/Aa+4),Fa=!1;r%2&&(i=i.times(s),Lse(i.d,e)),r=$S(r/2),r!==0;)s=s.times(s),Lse(s.d,e);return Fa=!0,t.s<0?new f(Xu).div(i):ta(i,n)}}else if(a<0)throw Error(Jd+"NaN");return a=a<0&&t.d[Math.max(e,r)]&1?-1:1,s.s=1,Fa=!1,i=t.times(Mk(s,n+m)),Fa=!0,i=uSe(i),i.s=a,i};An.toPrecision=function(t,e){var r,n,i=this,a=i.constructor;return t===void 0?(r=qo(i),n=N0(i,r<=a.toExpNeg||r>=a.toExpPos)):(op(t,1,zS),e===void 0?e=a.rounding:op(e,0,8),i=ta(new a(i),t,e),r=qo(i),n=N0(i,t<=r||r<=a.toExpNeg,t)),n};An.toSignificantDigits=An.tosd=function(t,e){var r=this,n=r.constructor;return t===void 0?(t=n.precision,e=n.rounding):(op(t,1,zS),e===void 0?e=n.rounding:op(e,0,8)),ta(new n(r),t,e)};An.toString=An.valueOf=An.val=An.toJSON=An[Symbol.for("nodejs.util.inspect.custom")]=function(){var t=this,e=qo(t),r=t.constructor;return N0(t,e<=r.toExpNeg||e>=r.toExpPos)};function cSe(t,e){var r,n,i,a,c,s,f,m,x=t.constructor,_=x.precision;if(!t.s||!e.s)return e.s||(e=new x(t)),Fa?ta(e,_):e;if(f=t.d,m=e.d,c=t.e,i=e.e,f=f.slice(),a=c-i,a){for(a<0?(n=f,a=-a,s=m.length):(n=m,i=c,s=f.length),c=Math.ceil(_/Aa),s=c>s?c+1:s+1,a>s&&(a=s,n.length=1),n.reverse();a--;)n.push(0);n.reverse()}for(s=f.length,a=m.length,s-a<0&&(a=s,n=m,m=f,f=n),r=0;a;)r=(f[--a]=f[a]+m[a]+r)/wl|0,f[a]%=wl;for(r&&(f.unshift(r),++i),s=f.length;f[--s]==0;)f.pop();return e.d=f,e.e=i,Fa?ta(e,_):e}function op(t,e,r){if(t!==~~t||tr)throw Error(m0+t)}function Gf(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(s=f=0;si[s]?1:-1;break}return f}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 s,f,m,x,_,T,E,C,N,R,D,M,B,V,G,W,X,Q,re=n.constructor,se=n.s==i.s?1:-1,ue=n.d,_e=i.d;if(!n.s)return new re(n);if(!i.s)throw Error(Jd+"Division by zero");for(f=n.e-i.e,X=_e.length,G=ue.length,E=new re(se),C=E.d=[],m=0;_e[m]==(ue[m]||0);)++m;if(_e[m]>(ue[m]||0)&&--f,a==null?M=a=re.precision:c?M=a+(qo(n)-qo(i))+1:M=a,M<0)return new re(0);if(M=M/Aa+2|0,m=0,X==1)for(x=0,_e=_e[0],M++;(m1&&(_e=t(_e,x),ue=t(ue,x),X=_e.length,G=ue.length),V=X,N=ue.slice(0,X),R=N.length;R=wl/2&&++W;do x=0,s=e(_e,N,X,R),s<0?(D=N[0],X!=R&&(D=D*wl+(N[1]||0)),x=D/W|0,x>1?(x>=wl&&(x=wl-1),_=t(_e,x),T=_.length,R=N.length,s=e(_,N,T,R),s==1&&(x--,r(_,X16)throw Error(OH+qo(t));if(!t.s)return new x(Xu);for(e==null?(Fa=!1,s=_):s=e,c=new x(.03125);t.abs().gte(.1);)t=t.times(c),m+=5;for(n=Math.log(z_(2,m))/Math.LN10*2+5|0,s+=n,r=i=a=new x(Xu),x.precision=s;;){if(i=ta(i.times(t),s),r=r.times(++f),c=a.plus(wm(i,r,s)),Gf(c.d).slice(0,s)===Gf(a.d).slice(0,s)){for(;m--;)a=ta(a.times(a),s);return x.precision=_,e==null?(Fa=!0,ta(a,_)):a}a=c}}function qo(t){for(var e=t.e*Aa,r=t.d[0];r>=10;r/=10)e++;return e}function Rz(t,e,r){if(e>t.LN10.sd())throw Fa=!0,r&&(t.precision=r),Error(Jd+"LN10 precision limit exceeded");return ta(new t(t.LN10),e)}function Qg(t){for(var e="";t--;)e+="0";return e}function Mk(t,e){var r,n,i,a,c,s,f,m,x,_=1,T=10,E=t,C=E.d,N=E.constructor,R=N.precision;if(E.s<1)throw Error(Jd+(E.s?"NaN":"-Infinity"));if(E.eq(Xu))return new N(0);if(e==null?(Fa=!1,m=R):m=e,E.eq(10))return e==null&&(Fa=!0),Rz(N,m);if(m+=T,N.precision=m,r=Gf(C),n=r.charAt(0),a=qo(E),Math.abs(a)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)E=E.times(t),r=Gf(E.d),n=r.charAt(0),_++;a=qo(E),n>1?(E=new N("0."+r),a++):E=new N(n+"."+r.slice(1))}else return f=Rz(N,m+2,R).times(a+""),E=Mk(new N(n+"."+r.slice(1)),m-T).plus(f),N.precision=R,e==null?(Fa=!0,ta(E,R)):E;for(s=c=E=wm(E.minus(Xu),E.plus(Xu),m),x=ta(E.times(E),m),i=3;;){if(c=ta(c.times(x),m),f=s.plus(wm(c,new N(i),m)),Gf(f.d).slice(0,m)===Gf(s.d).slice(0,m))return s=s.times(2),a!==0&&(s=s.plus(Rz(N,m+2,R).times(a+""))),s=wm(s,new N(_),m),N.precision=R,e==null?(Fa=!0,ta(s,R)):s;s=f,i+=2}}function Rse(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=$S(r/Aa),t.d=[],n=(r+1)%Aa,r<0&&(n+=Aa),nqD||t.e<-qD))throw Error(OH+r)}else t.s=0,t.e=0,t.d=[0];return t}function ta(t,e,r){var n,i,a,c,s,f,m,x,_=t.d;for(c=1,a=_[0];a>=10;a/=10)c++;if(n=e-c,n<0)n+=Aa,i=e,m=_[x=0];else{if(x=Math.ceil((n+1)/Aa),a=_.length,x>=a)return t;for(m=a=_[x],c=1;a>=10;a/=10)c++;n%=Aa,i=n-Aa+c}if(r!==void 0&&(a=z_(10,c-i-1),s=m/a%10|0,f=e<0||_[x+1]!==void 0||m%a,f=r<4?(s||f)&&(r==0||r==(t.s<0?3:2)):s>5||s==5&&(r==4||f||r==6&&(n>0?i>0?m/z_(10,c-i):0:_[x-1])%10&1||r==(t.s<0?8:7))),e<1||!_[0])return f?(a=qo(t),_.length=1,e=e-a-1,_[0]=z_(10,(Aa-e%Aa)%Aa),t.e=$S(-e/Aa)||0):(_.length=1,_[0]=t.e=t.s=0),t;if(n==0?(_.length=x,a=1,x--):(_.length=x+1,a=z_(10,Aa-n),_[x]=i>0?(m/z_(10,c-i)%z_(10,i)|0)*a:0),f)for(;;)if(x==0){(_[0]+=a)==wl&&(_[0]=1,++t.e);break}else{if(_[x]+=a,_[x]!=wl)break;_[x--]=0,a=1}for(n=_.length;_[--n]===0;)_.pop();if(Fa&&(t.e>qD||t.e<-qD))throw Error(OH+qo(t));return t}function dSe(t,e){var r,n,i,a,c,s,f,m,x,_,T=t.constructor,E=T.precision;if(!t.s||!e.s)return e.s?e.s=-e.s:e=new T(t),Fa?ta(e,E):e;if(f=t.d,_=e.d,n=e.e,m=t.e,f=f.slice(),c=m-n,c){for(x=c<0,x?(r=f,c=-c,s=_.length):(r=_,n=m,s=f.length),i=Math.max(Math.ceil(E/Aa),s)+2,c>i&&(c=i,r.length=1),r.reverse(),i=c;i--;)r.push(0);r.reverse()}else{for(i=f.length,s=_.length,x=i0;--i)f[s++]=0;for(i=_.length;i>c;){if(f[--i]<_[i]){for(a=i;a&&f[--a]===0;)f[a]=wl-1;--f[a],f[i]+=wl}f[i]-=_[i]}for(;f[--s]===0;)f.pop();for(;f[0]===0;f.shift())--n;return f[0]?(e.d=f,e.e=n,Fa?ta(e,E):e):new T(0)}function N0(t,e,r){var n,i=qo(t),a=Gf(t.d),c=a.length;return e?(r&&(n=r-c)>0?a=a.charAt(0)+"."+a.slice(1)+Qg(n):c>1&&(a=a.charAt(0)+"."+a.slice(1)),a=a+(i<0?"e":"e+")+i):i<0?(a="0."+Qg(-i-1)+a,r&&(n=r-c)>0&&(a+=Qg(n))):i>=c?(a+=Qg(i+1-c),r&&(n=r-i-1)>0&&(a=a+"."+Qg(n))):((n=i+1)0&&(i+1===c&&(a+="."),a+=Qg(n))),t.s<0?"-"+a:a}function Lse(t,e){if(t.length>e)return t.length=e,!0}function hSe(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(m0+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 Rse(c,a.toString())}else if(typeof a!="string")throw Error(m0+a);if(a.charCodeAt(0)===45?(a=a.slice(1),c.s=-1):c.s=1,svt.test(a))Rse(c,a);else throw Error(m0+a)}if(i.prototype=An,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=hSe,i.config=i.set=avt,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(m0+r+": "+n);if((n=t[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(m0+r+": "+n);return this}var MH=hSe(ivt);Xu=new MH(1);const Gs=MH;function ovt(t){return dvt(t)||uvt(t)||cvt(t)||lvt()}function lvt(){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 cvt(t,e){if(t){if(typeof t=="string")return YV(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 YV(t,e)}}function uvt(t){if(typeof Symbol<"u"&&Symbol.iterator in Object(t))return Array.from(t)}function dvt(t){if(Array.isArray(t))return YV(t)}function YV(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,Dse(function(){for(var s=arguments.length,f=new Array(s),m=0;mt.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](),s;!(n=(s=c.next()).done)&&(r.push(s.value),!(e&&r.length===e));n=!0);}catch(f){i=!0,a=f}finally{try{!n&&c.return!=null&&c.return()}finally{if(i)throw a}}return r}}function Avt(t){if(Array.isArray(t))return t}function ySe(t){var e=Fk(t,2),r=e[0],n=e[1],i=r,a=n;return r>n&&(i=n,a=r),[i,a]}function xSe(t,e,r){if(t.lte(0))return new Gs(0);var n=HF.getDigitCount(t.toNumber()),i=new Gs(10).pow(n),a=t.div(i),c=n!==1?.05:.1,s=new Gs(Math.ceil(a.div(c).toNumber())).add(r).mul(c),f=s.mul(i);return e?f:new Gs(Math.ceil(f))}function kvt(t,e,r){var n=1,i=new Gs(t);if(!i.isint()&&r){var a=Math.abs(t);a<1?(n=new Gs(10).pow(HF.getDigitCount(t)-1),i=new Gs(Math.floor(i.div(n).toNumber())).mul(n)):a>1&&(i=new Gs(Math.floor(t)))}else t===0?i=new Gs(Math.floor((e-1)/2)):r||(i=new Gs(Math.floor(t)));var c=Math.floor((e-1)/2),s=mvt(pvt(function(f){return i.add(new Gs(f-c).mul(n)).toNumber()}),ZV);return s(0,e)}function _Se(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 Gs(0),tickMin:new Gs(0),tickMax:new Gs(0)};var a=xSe(new Gs(e).sub(t).div(r-1),n,i),c;t<=0&&e>=0?c=new Gs(0):(c=new Gs(t).add(e).div(2),c=c.sub(new Gs(c).mod(a)));var s=Math.ceil(c.sub(t).div(a).toNumber()),f=Math.ceil(new Gs(e).sub(c).div(a).toNumber()),m=s+f+1;return m>r?_Se(t,e,r,n,i+1):(m0?f+(r-m):f,s=e>0?s:s+(r-m)),{step:a,tickMin:c.sub(new Gs(s).mul(a)),tickMax:c.add(new Gs(f).mul(a))})}function Cvt(t){var e=Fk(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),s=ySe([r,n]),f=Fk(s,2),m=f[0],x=f[1];if(m===-1/0||x===1/0){var _=x===1/0?[m].concat(QV(ZV(0,i-1).map(function(){return 1/0}))):[].concat(QV(ZV(0,i-1).map(function(){return-1/0})),[x]);return r>n?XV(_):_}if(m===x)return kvt(m,i,a);var T=_Se(m,x,c,a),E=T.step,C=T.tickMin,N=T.tickMax,R=HF.rangeStep(C,N.add(new Gs(.1).mul(E)),E);return r>n?XV(R):R}function jvt(t,e){var r=Fk(t,2),n=r[0],i=r[1],a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,c=ySe([n,i]),s=Fk(c,2),f=s[0],m=s[1];if(f===-1/0||m===1/0)return[n,i];if(f===m)return[f];var x=Math.max(e,2),_=xSe(new Gs(m).sub(f).div(x-1),a,0),T=[].concat(QV(HF.rangeStep(new Gs(f),new Gs(m).sub(new Gs(.99).mul(_)),_)),[m]);return n>i?XV(T):T}var Ivt=mSe(Cvt),Pvt=mSe(jvt),Nvt="Invariant failed";function R0(t,e){throw new Error(Nvt)}var Rvt=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function B1(t){"@babel/helpers - typeof";return B1=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},B1(t)}function GD(){return GD=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 zvt(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 $vt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Uvt(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,s=(r=n==null?void 0:n.length)!==null&&r!==void 0?r:0;if(s<=1)return 0;if(a&&a.axisType==="angleAxis"&&Math.abs(Math.abs(a.range[1]-a.range[0])-360)<=1e-6)for(var f=a.range,m=0;m0?i[m-1].coordinate:i[s-1].coordinate,_=i[m].coordinate,T=m>=s-1?i[0].coordinate:i[m+1].coordinate,E=void 0;if(Gc(_-x)!==Gc(T-_)){var C=[];if(Gc(T-_)===Gc(f[1]-f[0])){E=T;var N=_+f[1]-f[0];C[0]=Math.min(N,(N+x)/2),C[1]=Math.max(N,(N+x)/2)}else{E=x;var R=T+f[1]-f[0];C[0]=Math.min(_,(R+_)/2),C[1]=Math.max(_,(R+_)/2)}var D=[Math.min(_,(E+_)/2),Math.max(_,(E+_)/2)];if(e>D[0]&&e<=D[1]||e>=C[0]&&e<=C[1]){c=i[m].index;break}}else{var M=Math.min(x,T),B=Math.max(x,T);if(e>(M+_)/2&&e<=(B+_)/2){c=i[m].index;break}}}else for(var V=0;V0&&V(n[V].coordinate+n[V-1].coordinate)/2&&e<=(n[V].coordinate+n[V+1].coordinate)/2||V===s-1&&e>(n[V].coordinate+n[V-1].coordinate)/2){c=n[V].index;break}return c},FH=function(e){var r,n=e,i=n.type.displayName,a=(r=e.type)!==null&&r!==void 0&&r.defaultProps?ho(ho({},e.type.defaultProps),e.props):e.props,c=a.stroke,s=a.fill,f;switch(i){case"Line":f=c;break;case"Area":case"Radar":f=c&&c!=="none"?c:s;break;default:f=s;break}return f},sbt=function(e){var r=e.barSize,n=e.totalSize,i=e.stackGroups,a=i===void 0?{}:i;if(!a)return{};for(var c={},s=Object.keys(a),f=0,m=s.length;f=0});if(D&&D.length){var M=D[0].type.defaultProps,B=M!==void 0?ho(ho({},M),D[0].props):D[0].props,V=B.barSize,G=B[R];c[G]||(c[G]=[]);var W=Di(V)?r:V;c[G].push({item:D[0],stackList:D.slice(1),barSize:Di(W)?void 0:Hc(W,n,0)})}}return c},abt=function(e){var r=e.barGap,n=e.barCategoryGap,i=e.bandSize,a=e.sizeList,c=a===void 0?[]:a,s=e.maxBarSize,f=c.length;if(f<1)return null;var m=Hc(r,i,0,!0),x,_=[];if(c[0].barSize===+c[0].barSize){var T=!1,E=i/f,C=c.reduce(function(V,G){return V+G.barSize||0},0);C+=(f-1)*m,C>=i&&(C-=(f-1)*m,m=0),C>=i&&E>0&&(T=!0,E*=.9,C=f*E);var N=(i-C)/2>>0,R={offset:N-m,size:0};x=c.reduce(function(V,G){var W={item:G.item,position:{offset:R.offset+R.size+m,size:T?E:G.barSize}},X=[].concat(Fse(V),[W]);return R=X[X.length-1].position,G.stackList&&G.stackList.length&&G.stackList.forEach(function(Q){X.push({item:Q,position:R})}),X},_)}else{var D=Hc(n,i,0,!0);i-2*D-(f-1)*m<=0&&(m=0);var M=(i-2*D-(f-1)*m)/f;M>1&&(M>>=0);var B=s===+s?Math.min(M,s):M;x=c.reduce(function(V,G,W){var X=[].concat(Fse(V),[{item:G.item,position:{offset:D+(M+m)*W+(M-B)/2,size:B}}]);return G.stackList&&G.stackList.length&&G.stackList.forEach(function(Q){X.push({item:Q,position:X[X.length-1].position})}),X},_)}return x},obt=function(e,r,n,i){var a=n.children,c=n.width,s=n.margin,f=c-(s.left||0)-(s.right||0),m=SSe({children:a,legendWidth:f});if(m){var x=i||{},_=x.width,T=x.height,E=m.align,C=m.verticalAlign,N=m.layout;if((N==="vertical"||N==="horizontal"&&C==="middle")&&E!=="center"&&Wr(e[E]))return ho(ho({},e),{},zw({},E,e[E]+(_||0)));if((N==="horizontal"||N==="vertical"&&E==="center")&&C!=="middle"&&Wr(e[C]))return ho(ho({},e),{},zw({},C,e[C]+(T||0)))}return e},lbt=function(e,r,n){return Di(r)?!0:e==="horizontal"?r==="yAxis":e==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},TSe=function(e,r,n,i,a){var c=r.props.children,s=Wd(c,WF).filter(function(m){return lbt(i,a,m.props.direction)});if(s&&s.length){var f=s.map(function(m){return m.props.dataKey});return e.reduce(function(m,x){var _=Hl(x,n);if(Di(_))return m;var T=Array.isArray(_)?[VF(_),UF(_)]:[_,_],E=f.reduce(function(C,N){var R=Hl(x,N,0),D=T[0]-Math.abs(Array.isArray(R)?R[0]:R),M=T[1]+Math.abs(Array.isArray(R)?R[1]:R);return[Math.min(D,C[0]),Math.max(M,C[1])]},[1/0,-1/0]);return[Math.min(E[0],m[0]),Math.max(E[1],m[1])]},[1/0,-1/0])}return null},cbt=function(e,r,n,i,a){var c=r.map(function(s){return TSe(e,s,n,a,i)}).filter(function(s){return!Di(s)});return c&&c.length?c.reduce(function(s,f){return[Math.min(s[0],f[0]),Math.max(s[1],f[1])]},[1/0,-1/0]):null},ESe=function(e,r,n,i,a){var c=r.map(function(f){var m=f.props.dataKey;return n==="number"&&m&&TSe(e,f,m,i)||AA(e,m,n,a)});if(n==="number")return c.reduce(function(f,m){return[Math.min(f[0],m[0]),Math.max(f[1],m[1])]},[1/0,-1/0]);var s={};return c.reduce(function(f,m){for(var x=0,_=m.length;x<_;x++)s[m[x]]||(s[m[x]]=!0,f.push(m[x]));return f},[])},ASe=function(e,r){return e==="horizontal"&&r==="xAxis"||e==="vertical"&&r==="yAxis"||e==="centric"&&r==="angleAxis"||e==="radial"&&r==="radiusAxis"},kSe=function(e,r,n,i){if(i)return e.map(function(f){return f.coordinate});var a,c,s=e.map(function(f){return f.coordinate===r&&(a=!0),f.coordinate===n&&(c=!0),f.coordinate});return a||s.push(r),c||s.push(n),s},mm=function(e,r,n){if(!e)return null;var i=e.scale,a=e.duplicateDomain,c=e.type,s=e.range,f=e.realScaleType==="scaleBand"?i.bandwidth()/2:2,m=(r||n)&&c==="category"&&i.bandwidth?i.bandwidth()/f:0;if(m=e.axisType==="angleAxis"&&(s==null?void 0:s.length)>=2?Gc(s[0]-s[1])*2*m:m,r&&(e.ticks||e.niceTicks)){var x=(e.ticks||e.niceTicks).map(function(_){var T=a?a.indexOf(_):_;return{coordinate:i(T)+m,value:_,offset:m}});return x.filter(function(_){return!ij(_.coordinate)})}return e.isCategorical&&e.categoricalDomain?e.categoricalDomain.map(function(_,T){return{coordinate:i(_)+m,value:_,index:T,offset:m}}):i.ticks&&!n?i.ticks(e.tickCount).map(function(_){return{coordinate:i(_)+m,value:_,offset:m}}):i.domain().map(function(_,T){return{coordinate:i(_)+m,value:a?a[_]:_,index:T,offset:m}})},Lz=new WeakMap,MN=function(e,r){if(typeof r!="function")return e;Lz.has(e)||Lz.set(e,new WeakMap);var n=Lz.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},CSe=function(e,r,n){var i=e.scale,a=e.type,c=e.layout,s=e.axisType;if(i==="auto")return c==="radial"&&s==="radiusAxis"?{scale:Nk(),realScaleType:"band"}:c==="radial"&&s==="angleAxis"?{scale:zD(),realScaleType:"linear"}:a==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:EA(),realScaleType:"point"}:a==="category"?{scale:Nk(),realScaleType:"band"}:{scale:zD(),realScaleType:"linear"};if(j0(i)){var f="scale".concat(kF(i));return{scale:(Nse[f]||EA)(),realScaleType:Nse[f]?f:"point"}}return gi(i)?{scale:i}:{scale:EA(),realScaleType:"point"}},zse=1e-4,jSe=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])-zse,c=Math.max(i[0],i[1])+zse,s=e(r[0]),f=e(r[n-1]);(sc||fc)&&e.domain([r[0],r[n-1]])}},ubt=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[s][n][0]=a,e[s][n][1]=a+f,a=e[s][n][1]):(e[s][n][0]=c,e[s][n][1]=c+f,c=e[s][n][1])}},fbt=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+s,a=e[c][n][1]):(e[c][n][0]=0,e[c][n][1]=0)}},pbt={sign:hbt,expand:Rlt,none:P1,silhouette:Llt,wiggle:Dlt,positive:fbt},mbt=function(e,r,n){var i=r.map(function(s){return s.props.dataKey}),a=pbt[n],c=Nlt().keys(i).value(function(s,f){return+Hl(s,f,0)}).order(EV).offset(a);return c(e)},gbt=function(e,r,n,i,a,c){if(!e)return null;var s=c?r.reverse():r,f={},m=s.reduce(function(_,T){var E,C=(E=T.type)!==null&&E!==void 0&&E.defaultProps?ho(ho({},T.type.defaultProps),T.props):T.props,N=C.stackId,R=C.hide;if(R)return _;var D=C[n],M=_[D]||{hasStack:!1,stackGroups:{}};if(cl(N)){var B=M.stackGroups[N]||{numericAxisId:n,cateAxisId:i,items:[]};B.items.push(T),M.hasStack=!0,M.stackGroups[N]=B}else M.stackGroups[sj("_stackId_")]={numericAxisId:n,cateAxisId:i,items:[T]};return ho(ho({},_),{},zw({},D,M))},f),x={};return Object.keys(m).reduce(function(_,T){var E=m[T];if(E.hasStack){var C={};E.stackGroups=Object.keys(E.stackGroups).reduce(function(N,R){var D=E.stackGroups[R];return ho(ho({},N),{},zw({},R,{numericAxisId:n,cateAxisId:i,items:D.items,stackedData:mbt(e,D.items,a)}))},C)}return ho(ho({},_),{},zw({},T,E))},x)},ISe=function(e,r){var n=r.realScaleType,i=r.type,a=r.tickCount,c=r.originalDomain,s=r.allowDecimals,f=n||r.scale;if(f!=="auto"&&f!=="linear")return null;if(a&&i==="number"&&c&&(c[0]==="auto"||c[1]==="auto")){var m=e.domain();if(!m.length)return null;var x=Ivt(m,a,s);return e.domain([VF(x),UF(x)]),{niceTicks:x}}if(a&&i==="number"){var _=e.domain(),T=Pvt(_,a,s);return{niceTicks:T}}return null};function r8t(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&&!Di(i[e.dataKey])){var s=_D(r,"value",i[e.dataKey]);if(s)return s.coordinate+n/2}return r[a]?r[a].coordinate+n/2:null}var f=Hl(i,Di(c)?e.dataKey:c);return Di(f)?null:e.scale(f)}var $se=function(e){var r=e.axis,n=e.ticks,i=e.offset,a=e.bandSize,c=e.entry,s=e.index;if(r.type==="category")return n[s]?n[s].coordinate+i:null;var f=Hl(c,r.dataKey,r.domain[s]);return Di(f)?null:r.scale(f)-a/2+i},ybt=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]},xbt=function(e,r){var n,i=(n=e.type)!==null&&n!==void 0&&n.defaultProps?ho(ho({},e.type.defaultProps),e.props):e.props,a=i.stackId;if(cl(a)){var c=r[a];if(c){var s=c.items.indexOf(e);return s>=0?c.stackedData[s]:null}}return null},_bt=function(e){return e.reduce(function(r,n){return[VF(n.concat([r[0]]).filter(Wr)),UF(n.concat([r[1]]).filter(Wr))]},[1/0,-1/0])},PSe=function(e,r,n){return Object.keys(e).reduce(function(i,a){var c=e[a],s=c.stackedData,f=s.reduce(function(m,x){var _=_bt(x.slice(r,n+1));return[Math.min(m[0],_[0]),Math.max(m[1],_[1])]},[1/0,-1/0]);return[Math.min(f[0],i[0]),Math.max(f[1],i[1])]},[1/0,-1/0]).map(function(i){return i===1/0||i===-1/0?0:i})},Use=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Vse=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,r8=function(e,r,n){if(gi(e))return e(r,n);if(!Array.isArray(e))return r;var i=[];if(Wr(e[0]))i[0]=n?e[0]:Math.min(e[0],r[0]);else if(Use.test(e[0])){var a=+Use.exec(e[0])[1];i[0]=r[0]-a}else gi(e[0])?i[0]=e[0](r[0]):i[0]=r[0];if(Wr(e[1]))i[1]=n?e[1]:Math.max(e[1],r[1]);else if(Vse.test(e[1])){var c=+Vse.exec(e[1])[1];i[1]=r[1]+c}else gi(e[1])?i[1]=e[1](r[1]):i[1]=r[1];return i},WD=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=hH(r,function(_){return _.coordinate}),c=1/0,s=1,f=a.length;st.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},Cbt=function(e,r,n,i,a){var c=e.width,s=e.height,f=e.startAngle,m=e.endAngle,x=Hc(e.cx,c,c/2),_=Hc(e.cy,s,s/2),T=LSe(c,s,n),E=Hc(e.innerRadius,T,0),C=Hc(e.outerRadius,T,T*.8),N=Object.keys(r);return N.reduce(function(R,D){var M=r[D],B=M.domain,V=M.reversed,G;if(Di(M.range))i==="angleAxis"?G=[f,m]:i==="radiusAxis"&&(G=[E,C]),V&&(G=[G[1],G[0]]);else{G=M.range;var W=G,X=wbt(W,2);f=X[0],m=X[1]}var Q=CSe(M,a),re=Q.realScaleType,se=Q.scale;se.domain(B).range(G),jSe(se);var ue=ISe(se,im(im({},M),{},{realScaleType:re})),_e=im(im(im({},M),ue),{},{range:G,radius:C,realScaleType:re,scale:se,cx:x,cy:_,innerRadius:E,outerRadius:C,startAngle:f,endAngle:m});return im(im({},R),{},RSe({},D,_e))},{})},jbt=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))},Ibt=function(e,r){var n=e.x,i=e.y,a=r.cx,c=r.cy,s=jbt({x:n,y:i},{x:a,y:c});if(s<=0)return{radius:s};var f=(n-a)/s,m=Math.acos(f);return i>c&&(m=2*Math.PI-m),{radius:s,angle:kbt(m),angleInRadian:m}},Pbt=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}},Nbt=function(e,r){var n=r.startAngle,i=r.endAngle,a=Math.floor(n/360),c=Math.floor(i/360),s=Math.min(a,c);return e+s*360},Wse=function(e,r){var n=e.x,i=e.y,a=Ibt({x:n,y:i},r),c=a.radius,s=a.angle,f=r.innerRadius,m=r.outerRadius;if(cm)return!1;if(c===0)return!0;var x=Pbt(r),_=x.startAngle,T=x.endAngle,E=s,C;if(_<=T){for(;E>T;)E-=360;for(;E<_;)E+=360;C=E>=_&&E<=T}else{for(;E>_;)E-=360;for(;E=T&&E<=_}return C?im(im({},r),{},{radius:c,angle:Nbt(E,r)}):null},DSe=function(e){return!P.isValidElement(e)&&!gi(e)&&typeof e!="boolean"?e.className:""};function Uk(t){"@babel/helpers - typeof";return Uk=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},Uk(t)}var Rbt=["offset"];function Lbt(t){return Fbt(t)||Mbt(t)||Obt(t)||Dbt()}function Dbt(){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 Obt(t,e){if(t){if(typeof t=="string")return n8(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 n8(t,e)}}function Mbt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function Fbt(t){if(Array.isArray(t))return n8(t)}function n8(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 zbt(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 Kse(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 Jo(t){for(var e=1;e=0?1:-1,B,V;i==="insideStart"?(B=E+M*c,V=N):i==="insideEnd"?(B=C-M*c,V=!N):i==="end"&&(B=C+M*c,V=N),V=D<=0?V:!V;var G=pa(m,x,R,B),W=pa(m,x,R,B+(V?1:-1)*359),X="M".concat(G.x,",").concat(G.y,` A`).concat(R,",").concat(R,",0,1,").concat(V?0:1,`, `).concat(W.x,",").concat(W.y),Q=Di(e.id)?sj("recharts-radial-line-"):e.id;return Xe.createElement("text",Vk({},n,{dominantBaseline:"central",className:Li("recharts-radial-bar-label",s)}),Xe.createElement("defs",null,Xe.createElement("path",{id:Q,d:X})),Xe.createElement("textPath",{xlinkHref:"#".concat(Q)},r))},Wbt=function(e){var r=e.viewBox,n=e.offset,i=e.position,a=r,c=a.cx,s=a.cy,f=a.innerRadius,m=a.outerRadius,x=a.startAngle,_=a.endAngle,T=(x+_)/2;if(i==="outside"){var E=pa(c,s,m+n,T),C=E.x,N=E.y;return{x:C,y:N,textAnchor:C>=c?"start":"end",verticalAnchor:"middle"}}if(i==="center")return{x:c,y:s,textAnchor:"middle",verticalAnchor:"middle"};if(i==="centerTop")return{x:c,y:s,textAnchor:"middle",verticalAnchor:"start"};if(i==="centerBottom")return{x:c,y:s,textAnchor:"middle",verticalAnchor:"end"};var R=(f+m)/2,D=pa(c,s,R,T),M=D.x,B=D.y;return{x:M,y:B,textAnchor:"middle",verticalAnchor:"middle"}},Kbt=function(e){var r=e.viewBox,n=e.parentViewBox,i=e.offset,a=e.position,c=r,s=c.x,f=c.y,m=c.width,x=c.height,_=x>=0?1:-1,T=_*i,E=_>0?"end":"start",C=_>0?"start":"end",N=m>=0?1:-1,R=N*i,D=N>0?"end":"start",M=N>0?"start":"end";if(a==="top"){var B={x:s+m/2,y:f-_*i,textAnchor:"middle",verticalAnchor:E};return Jo(Jo({},B),n?{height:Math.max(f-n.y,0),width:m}:{})}if(a==="bottom"){var V={x:s+m/2,y:f+x+T,textAnchor:"middle",verticalAnchor:C};return Jo(Jo({},V),n?{height:Math.max(n.y+n.height-(f+x),0),width:m}:{})}if(a==="left"){var G={x:s-R,y:f+x/2,textAnchor:D,verticalAnchor:"middle"};return Jo(Jo({},G),n?{width:Math.max(G.x-n.x,0),height:x}:{})}if(a==="right"){var W={x:s+m+R,y:f+x/2,textAnchor:M,verticalAnchor:"middle"};return Jo(Jo({},W),n?{width:Math.max(n.x+n.width-W.x,0),height:x}:{})}var X=n?{width:m,height:x}:{};return a==="insideLeft"?Jo({x:s+R,y:f+x/2,textAnchor:M,verticalAnchor:"middle"},X):a==="insideRight"?Jo({x:s+m-R,y:f+x/2,textAnchor:D,verticalAnchor:"middle"},X):a==="insideTop"?Jo({x:s+m/2,y:f+T,textAnchor:"middle",verticalAnchor:C},X):a==="insideBottom"?Jo({x:s+m/2,y:f+x-T,textAnchor:"middle",verticalAnchor:E},X):a==="insideTopLeft"?Jo({x:s+R,y:f+T,textAnchor:M,verticalAnchor:C},X):a==="insideTopRight"?Jo({x:s+m-R,y:f+T,textAnchor:D,verticalAnchor:C},X):a==="insideBottomLeft"?Jo({x:s+R,y:f+x-T,textAnchor:M,verticalAnchor:E},X):a==="insideBottomRight"?Jo({x:s+m-R,y:f+x-T,textAnchor:D,verticalAnchor:E},X):NS(a)&&(Wr(a.x)||Z_(a.x))&&(Wr(a.y)||Z_(a.y))?Jo({x:s+Hc(a.x,m),y:f+Hc(a.y,x),textAnchor:"end",verticalAnchor:"end"},X):Jo({x:s+m/2,y:f+x/2,textAnchor:"middle",verticalAnchor:"middle"},X)},Ybt=function(e){return"cx"in e&&Wr(e.cx)};function El(t){var e=t.offset,r=e===void 0?5:e,n=Bbt(t,Rbt),i=Jo({offset:r},n),a=i.viewBox,c=i.position,s=i.value,f=i.children,m=i.content,x=i.className,_=x===void 0?"":x,T=i.textBreakAll;if(!a||Di(s)&&Di(f)&&!P.isValidElement(m)&&!gi(m))return null;if(P.isValidElement(m))return P.cloneElement(m,i);var E;if(gi(m)){if(E=P.createElement(m,i),P.isValidElement(E))return E}else E=qbt(i);var C=Ybt(a),N=ui(i,!0);if(C&&(c==="insideStart"||c==="insideEnd"||c==="end"))return Hbt(i,E,N);var R=C?Wbt(i):Kbt(i);return Xe.createElement(P0,Vk({className:Li("recharts-label",_)},N,R,{breakAll:T}),E)}El.displayName="Label";var OSe=function(e){var r=e.cx,n=e.cy,i=e.angle,a=e.startAngle,c=e.endAngle,s=e.r,f=e.radius,m=e.innerRadius,x=e.outerRadius,_=e.x,T=e.y,E=e.top,C=e.left,N=e.width,R=e.height,D=e.clockWise,M=e.labelViewBox;if(M)return M;if(Wr(N)&&Wr(R)){if(Wr(_)&&Wr(T))return{x:_,y:T,width:N,height:R};if(Wr(E)&&Wr(C))return{x:E,y:C,width:N,height:R}}return Wr(_)&&Wr(T)?{x:_,y:T,width:0,height:0}:Wr(r)&&Wr(n)?{cx:r,cy:n,startAngle:a||i||0,endAngle:c||i||0,innerRadius:m||0,outerRadius:x||f||s||0,clockWise:D}:e.viewBox?e.viewBox:{}},Zbt=function(e,r){return e?e===!0?Xe.createElement(El,{key:"label-implicit",viewBox:r}):cl(e)?Xe.createElement(El,{key:"label-implicit",viewBox:r,value:e}):P.isValidElement(e)?e.type===El?P.cloneElement(e,{key:"label-implicit",viewBox:r}):Xe.createElement(El,{key:"label-implicit",content:e,viewBox:r}):gi(e)?Xe.createElement(El,{key:"label-implicit",content:e,viewBox:r}):NS(e)?Xe.createElement(El,Vk({viewBox:r},e,{key:"label-implicit"})):null:null},Xbt=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=OSe(e),c=Wd(i,El).map(function(f,m){return P.cloneElement(f,{viewBox:r||a,key:"label-".concat(m)})});if(!n)return c;var s=Zbt(e.label,r||a);return[s].concat(Lbt(c))};El.parseViewBox=OSe;El.renderCallByParent=Xbt;function Qbt(t){var e=t==null?0:t.length;return e?t[e-1]:void 0}var Jbt=Qbt;const ewt=ds(Jbt);function qk(t){"@babel/helpers - typeof";return qk=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},qk(t)}var twt=["valueAccessor"],rwt=["data","dataKey","clockWise","id","textBreakAll"];function nwt(t){return owt(t)||awt(t)||swt(t)||iwt()}function iwt(){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 swt(t,e){if(t){if(typeof t=="string")return i8(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 i8(t,e)}}function awt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function owt(t){if(Array.isArray(t))return i8(t)}function i8(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 dwt(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 hwt=function(e){return Array.isArray(e.value)?ewt(e.value):e.value};function Ly(t){var e=t.valueAccessor,r=e===void 0?hwt:e,n=Xse(t,twt),i=n.data,a=n.dataKey,c=n.clockWise,s=n.id,f=n.textBreakAll,m=Xse(n,rwt);return!i||!i.length?null:Xe.createElement(zs,{className:"recharts-label-list"},i.map(function(x,_){var T=Di(a)?r(x,_):Hl(x&&x.payload,a),E=Di(s)?{}:{id:"".concat(s,"-").concat(_)};return Xe.createElement(El,YD({},ui(x,!0),m,E,{parentViewBox:x.parentViewBox,value:T,textBreakAll:f,viewBox:El.parseViewBox(Di(c)?x:Zse(Zse({},x),{},{clockWise:c})),key:"label-".concat(_),index:_}))}))}Ly.displayName="LabelList";function fwt(t,e){return t?t===!0?Xe.createElement(Ly,{key:"labelList-implicit",data:e}):Xe.isValidElement(t)||gi(t)?Xe.createElement(Ly,{key:"labelList-implicit",data:e,content:t}):NS(t)?Xe.createElement(Ly,YD({data:e},t,{key:"labelList-implicit"})):null:null}function pwt(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=Wd(n,Ly).map(function(c,s){return P.cloneElement(c,{data:e,key:"labelList-".concat(s)})});if(!r)return i;var a=fwt(t.label,e);return[a].concat(nwt(i))}Ly.renderCallByParent=pwt;function Gk(t){"@babel/helpers - typeof";return Gk=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},Gk(t)}function s8(){return s8=Object.assign?Object.assign.bind():function(t){for(var e=1;e180),",").concat(+(c>m),`, `).concat(_.x,",").concat(_.y,` `);if(i>0){var E=pa(r,n,i,c),C=pa(r,n,i,m);T+="L ".concat(C.x,",").concat(C.y,` A `).concat(i,",").concat(i,`,0, `).concat(+(Math.abs(f)>180),",").concat(+(c<=m),`, `).concat(E.x,",").concat(E.y," Z")}else T+="L ".concat(r,",").concat(n," Z");return T},_wt=function(e){var r=e.cx,n=e.cy,i=e.innerRadius,a=e.outerRadius,c=e.cornerRadius,s=e.forceCornerRadius,f=e.cornerIsExternal,m=e.startAngle,x=e.endAngle,_=Gc(x-m),T=FN({cx:r,cy:n,radius:a,angle:m,sign:_,cornerRadius:c,cornerIsExternal:f}),E=T.circleTangency,C=T.lineTangency,N=T.theta,R=FN({cx:r,cy:n,radius:a,angle:x,sign:-_,cornerRadius:c,cornerIsExternal:f}),D=R.circleTangency,M=R.lineTangency,B=R.theta,V=f?Math.abs(m-x):Math.abs(m-x)-N-B;if(V<0)return s?"M ".concat(C.x,",").concat(C.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 `):MSe({cx:r,cy:n,innerRadius:i,outerRadius:a,startAngle:m,endAngle:x});var G="M ".concat(C.x,",").concat(C.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(_<0),",").concat(E.x,",").concat(E.y,` A`).concat(a,",").concat(a,",0,").concat(+(V>180),",").concat(+(_<0),",").concat(D.x,",").concat(D.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(_<0),",").concat(M.x,",").concat(M.y,` `);if(i>0){var W=FN({cx:r,cy:n,radius:i,angle:m,sign:_,isExternal:!0,cornerRadius:c,cornerIsExternal:f}),X=W.circleTangency,Q=W.lineTangency,re=W.theta,se=FN({cx:r,cy:n,radius:i,angle:x,sign:-_,isExternal:!0,cornerRadius:c,cornerIsExternal:f}),ue=se.circleTangency,_e=se.lineTangency,Se=se.theta,ve=f?Math.abs(m-x):Math.abs(m-x)-re-Se;if(ve<0&&c===0)return"".concat(G,"L").concat(r,",").concat(n,"Z");G+="L".concat(_e.x,",").concat(_e.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(_<0),",").concat(ue.x,",").concat(ue.y,` A`).concat(i,",").concat(i,",0,").concat(+(ve>180),",").concat(+(_>0),",").concat(X.x,",").concat(X.y,` A`).concat(c,",").concat(c,",0,0,").concat(+(_<0),",").concat(Q.x,",").concat(Q.y,"Z")}else G+="L".concat(r,",").concat(n,"Z");return G},vwt={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},FSe=function(e){var r=Jse(Jse({},vwt),e),n=r.cx,i=r.cy,a=r.innerRadius,c=r.outerRadius,s=r.cornerRadius,f=r.forceCornerRadius,m=r.cornerIsExternal,x=r.startAngle,_=r.endAngle,T=r.className;if(c0&&Math.abs(x-_)<360?R=_wt({cx:n,cy:i,innerRadius:a,outerRadius:c,cornerRadius:Math.min(N,C/2),forceCornerRadius:f,cornerIsExternal:m,startAngle:x,endAngle:_}):R=MSe({cx:n,cy:i,innerRadius:a,outerRadius:c,startAngle:x,endAngle:_}),Xe.createElement("path",s8({},ui(r,!0),{className:E,d:R,role:"img"}))};function Hk(t){"@babel/helpers - typeof";return Hk=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},Hk(t)}function a8(){return a8=Object.assign?Object.assign.bind():function(t){for(var e=1;e0;)if(!r.equals(t[n],e[n],n,n,t,e,r))return!1;return!0}function Dwt(t,e){return US(t.getTime(),e.getTime())}function oae(t,e,r){if(t.size!==e.size)return!1;for(var n={},i=t.entries(),a=0,c,s;(c=i.next())&&!c.done;){for(var f=e.entries(),m=!1,x=0;(s=f.next())&&!s.done;){var _=c.value,T=_[0],E=_[1],C=s.value,N=C[0],R=C[1];!m&&!n[x]&&(m=r.equals(T,N,a,x,t,e,r)&&r.equals(E,R,T,N,t,e,r))&&(n[x]=!0),x++}if(!m)return!1;a++}return!0}function Owt(t,e,r){var n=aae(t),i=n.length;if(aae(e).length!==i)return!1;for(var a;i-- >0;)if(a=n[i],a===VSe&&(t.$$typeof||e.$$typeof)&&t.$$typeof!==e.$$typeof||!USe(e,a)||!r.equals(t[a],e[a],a,a,t,e,r))return!1;return!0}function R2(t,e,r){var n=iae(t),i=n.length;if(iae(e).length!==i)return!1;for(var a,c,s;i-- >0;)if(a=n[i],a===VSe&&(t.$$typeof||e.$$typeof)&&t.$$typeof!==e.$$typeof||!USe(e,a)||!r.equals(t[a],e[a],a,a,t,e,r)||(c=sae(t,a),s=sae(e,a),(c||s)&&(!c||!s||c.configurable!==s.configurable||c.enumerable!==s.enumerable||c.writable!==s.writable)))return!1;return!0}function Mwt(t,e){return US(t.valueOf(),e.valueOf())}function Fwt(t,e){return t.source===e.source&&t.flags===e.flags}function lae(t,e,r){if(t.size!==e.size)return!1;for(var n={},i=t.values(),a,c;(a=i.next())&&!a.done;){for(var s=e.values(),f=!1,m=0;(c=s.next())&&!c.done;)!f&&!n[m]&&(f=r.equals(a.value,c.value,a.value,c.value,t,e,r))&&(n[m]=!0),m++;if(!f)return!1}return!0}function Bwt(t,e){var r=t.length;if(e.length!==r)return!1;for(;r-- >0;)if(t[r]!==e[r])return!1;return!0}var zwt="[object Arguments]",$wt="[object Boolean]",Uwt="[object Date]",Vwt="[object Map]",qwt="[object Number]",Gwt="[object Object]",Hwt="[object RegExp]",Wwt="[object Set]",Kwt="[object String]",Ywt=Array.isArray,cae=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,uae=Object.assign,Zwt=Object.prototype.toString.call.bind(Object.prototype.toString);function Xwt(t){var e=t.areArraysEqual,r=t.areDatesEqual,n=t.areMapsEqual,i=t.areObjectsEqual,a=t.arePrimitiveWrappersEqual,c=t.areRegExpsEqual,s=t.areSetsEqual,f=t.areTypedArraysEqual;return function(x,_,T){if(x===_)return!0;if(x==null||_==null||typeof x!="object"||typeof _!="object")return x!==x&&_!==_;var E=x.constructor;if(E!==_.constructor)return!1;if(E===Object)return i(x,_,T);if(Ywt(x))return e(x,_,T);if(cae!=null&&cae(x))return f(x,_,T);if(E===Date)return r(x,_,T);if(E===RegExp)return c(x,_,T);if(E===Map)return n(x,_,T);if(E===Set)return s(x,_,T);var C=Zwt(x);return C===Uwt?r(x,_,T):C===Hwt?c(x,_,T):C===Vwt?n(x,_,T):C===Wwt?s(x,_,T):C===Gwt?typeof x.then!="function"&&typeof _.then!="function"&&i(x,_,T):C===zwt?i(x,_,T):C===$wt||C===qwt||C===Kwt?a(x,_,T):!1}}function Qwt(t){var e=t.circular,r=t.createCustomConfig,n=t.strict,i={areArraysEqual:n?R2:Lwt,areDatesEqual:Dwt,areMapsEqual:n?nae(oae,R2):oae,areObjectsEqual:n?R2:Owt,arePrimitiveWrappersEqual:Mwt,areRegExpsEqual:Fwt,areSetsEqual:n?nae(lae,R2):lae,areTypedArraysEqual:n?R2:Bwt};if(r&&(i=uae({},i,r(i))),e){var a=zN(i.areArraysEqual),c=zN(i.areMapsEqual),s=zN(i.areObjectsEqual),f=zN(i.areSetsEqual);i=uae({},i,{areArraysEqual:a,areMapsEqual:c,areObjectsEqual:s,areSetsEqual:f})}return i}function Jwt(t){return function(e,r,n,i,a,c,s){return t(e,r,s)}}function e1t(t){var e=t.circular,r=t.comparator,n=t.createState,i=t.equals,a=t.strict;if(n)return function(f,m){var x=n(),_=x.cache,T=_===void 0?e?new WeakMap:void 0:_,E=x.meta;return r(f,m,{cache:T,equals:i,meta:E,strict:a})};if(e)return function(f,m){return r(f,m,{cache:new WeakMap,equals:i,meta:void 0,strict:a})};var c={cache:void 0,equals:i,meta:void 0,strict:a};return function(f,m){return r(f,m,c)}}var t1t=gx();gx({strict:!0});gx({circular:!0});gx({circular:!0,strict:!0});gx({createInternalComparator:function(){return US}});gx({strict:!0,createInternalComparator:function(){return US}});gx({circular:!0,createInternalComparator:function(){return US}});gx({circular:!0,createInternalComparator:function(){return US},strict:!0});function gx(t){t===void 0&&(t={});var e=t.circular,r=e===void 0?!1:e,n=t.createInternalComparator,i=t.createState,a=t.strict,c=a===void 0?!1:a,s=Qwt(t),f=Xwt(s),m=n?n(f):Jwt(f);return e1t({circular:r,comparator:f,createState:i,equals:m,strict:c})}function r1t(t){typeof requestAnimationFrame<"u"&&requestAnimationFrame(t)}function dae(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):r1t(i)};requestAnimationFrame(n)}function l8(t){"@babel/helpers - typeof";return l8=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},l8(t)}function n1t(t){return o1t(t)||a1t(t)||s1t(t)||i1t()}function i1t(){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 s1t(t,e){if(t){if(typeof t=="string")return hae(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 hae(t,e)}}function hae(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:D<0?0:D},N=function(D){for(var M=D>1?1:D,B=M,V=0;V<8;++V){var G=_(B)-M,W=E(B);if(Math.abs(G-M)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,s=c===void 0?17:c,f=function(x,_,T){var E=-(x-_)*n,C=T*a,N=T+(E-C)*s/1e3,R=T*s/1e3+x;return Math.abs(R-_)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 F1t(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 Dz(t){return U1t(t)||$1t(t)||z1t(t)||B1t()}function B1t(){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 z1t(t,e){if(t){if(typeof t=="string")return f8(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 f8(t,e)}}function $1t(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function U1t(t){if(Array.isArray(t))return f8(t)}function f8(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 QD(t){return QD=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},QD(t)}var Fm=function(t){W1t(r,t);var e=K1t(r);function r(n,i){var a;V1t(this,r),a=e.call(this,n,i);var c=a.props,s=c.isActive,f=c.attributeName,m=c.from,x=c.to,_=c.steps,T=c.children,E=c.duration;if(a.handleStyleChange=a.handleStyleChange.bind(g8(a)),a.changeStyle=a.changeStyle.bind(g8(a)),!s||E<=0)return a.state={style:{}},typeof T=="function"&&(a.state={style:x}),m8(a);if(_&&_.length)a.state={style:_[0].style};else if(m){if(typeof T=="function")return a.state={style:m},m8(a);a.state={style:f?X2({},f,m):m}}else a.state={style:{}};return a}return G1t(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,s=a.canBegin,f=a.attributeName,m=a.shouldReAnimate,x=a.to,_=a.from,T=this.state.style;if(s){if(!c){var E={style:f?X2({},f,x):x};this.state&&T&&(f&&T[f]!==x||!f&&T!==x)&&this.setState(E);return}if(!(t1t(i.to,x)&&i.canBegin&&i.isActive)){var C=!i.canBegin||!i.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var N=C||m?_:i.to;if(this.state&&T){var R={style:f?X2({},f,N):N};(f&&T[f]!==N||!f&&T!==N)&&this.setState(R)}this.runAnimation(kh(kh({},this.props),{},{from:N,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,s=i.to,f=i.duration,m=i.easing,x=i.begin,_=i.onAnimationEnd,T=i.onAnimationStart,E=D1t(c,s,T1t(m),f,this.changeStyle),C=function(){a.stopJSAnimation=E()};this.manager.start([T,x,C,f,_])}},{key:"runStepAnimation",value:function(i){var a=this,c=i.steps,s=i.begin,f=i.onAnimationStart,m=c[0],x=m.style,_=m.duration,T=_===void 0?0:_,E=function(N,R,D){if(D===0)return N;var M=R.duration,B=R.easing,V=B===void 0?"ease":B,G=R.style,W=R.properties,X=R.onAnimationEnd,Q=D>0?c[D-1]:R,re=W||Object.keys(G);if(typeof V=="function"||V==="spring")return[].concat(Dz(N),[a.runJSAnimation.bind(a,{from:Q.style,to:G,duration:M,easing:V}),M]);var se=mae(re,M,V),ue=kh(kh(kh({},Q.style),G),{},{transition:se});return[].concat(Dz(N),[ue,M,X]).filter(h1t)};return this.manager.start([f].concat(Dz(c.reduce(E,[x,Math.max(T,s)])),[i.onAnimationEnd]))}},{key:"runAnimation",value:function(i){this.manager||(this.manager=l1t());var a=i.begin,c=i.duration,s=i.attributeName,f=i.to,m=i.easing,x=i.onAnimationStart,_=i.onAnimationEnd,T=i.steps,E=i.children,C=this.manager;if(this.unSubscribe=C.subscribe(this.handleStyleChange),typeof m=="function"||typeof E=="function"||m==="spring"){this.runJSAnimation(i);return}if(T.length>1){this.runStepAnimation(i);return}var N=s?X2({},s,f):f,R=mae(Object.keys(N),c,m);C.start([x,a,kh(kh({},N),{},{transition:R}),c,_])}},{key:"render",value:function(){var i=this.props,a=i.children;i.begin;var c=i.duration;i.attributeName,i.easing;var s=i.isActive;i.steps,i.from,i.to,i.canBegin,i.onAnimationEnd,i.shouldReAnimate,i.onAnimationReStart;var f=M1t(i,O1t),m=P.Children.count(a),x=this.state.style;if(typeof a=="function")return a(x);if(!s||m===0||c<=0)return a;var _=function(E){var C=E.props,N=C.style,R=N===void 0?{}:N,D=C.className,M=P.cloneElement(E,kh(kh({},f),{},{style:kh(kh({},R),x),className:D}));return M};return m===1?_(P.Children.only(a)):Xe.createElement("div",null,P.Children.map(a,function(T){return _(T)}))}}]),r}(P.PureComponent);Fm.displayName="Animate";Fm.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};Fm.propTypes={from:Rs.oneOfType([Rs.object,Rs.string]),to:Rs.oneOfType([Rs.object,Rs.string]),attributeName:Rs.string,duration:Rs.number,begin:Rs.number,easing:Rs.oneOfType([Rs.string,Rs.func]),steps:Rs.arrayOf(Rs.shape({duration:Rs.number.isRequired,style:Rs.object.isRequired,easing:Rs.oneOfType([Rs.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),Rs.func]),properties:Rs.arrayOf("string"),onAnimationEnd:Rs.func})),children:Rs.oneOfType([Rs.node,Rs.func]),isActive:Rs.bool,canBegin:Rs.bool,onAnimationEnd:Rs.func,shouldReAnimate:Rs.bool,onAnimationStart:Rs.func,onAnimationReStart:Rs.func};function Yk(t){"@babel/helpers - typeof";return Yk=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},Yk(t)}function JD(){return JD=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,f=n>=0?1:-1,m=i>=0&&n>=0||i<0&&n<0?1:0,x;if(c>0&&a instanceof Array){for(var _=[0,0,0,0],T=0,E=4;Tc?c:a[T];x="M".concat(e,",").concat(r+s*_[0]),_[0]>0&&(x+="A ".concat(_[0],",").concat(_[0],",0,0,").concat(m,",").concat(e+f*_[0],",").concat(r)),x+="L ".concat(e+n-f*_[1],",").concat(r),_[1]>0&&(x+="A ".concat(_[1],",").concat(_[1],",0,0,").concat(m,`, `).concat(e+n,",").concat(r+s*_[1])),x+="L ".concat(e+n,",").concat(r+i-s*_[2]),_[2]>0&&(x+="A ".concat(_[2],",").concat(_[2],",0,0,").concat(m,`, `).concat(e+n-f*_[2],",").concat(r+i)),x+="L ".concat(e+f*_[3],",").concat(r+i),_[3]>0&&(x+="A ".concat(_[3],",").concat(_[3],",0,0,").concat(m,`, `).concat(e,",").concat(r+i-s*_[3])),x+="Z"}else if(c>0&&a===+a&&a>0){var C=Math.min(c,a);x="M ".concat(e,",").concat(r+s*C,` A `).concat(C,",").concat(C,",0,0,").concat(m,",").concat(e+f*C,",").concat(r,` L `).concat(e+n-f*C,",").concat(r,` A `).concat(C,",").concat(C,",0,0,").concat(m,",").concat(e+n,",").concat(r+s*C,` L `).concat(e+n,",").concat(r+i-s*C,` A `).concat(C,",").concat(C,",0,0,").concat(m,",").concat(e+n-f*C,",").concat(r+i,` L `).concat(e+f*C,",").concat(r+i,` A `).concat(C,",").concat(C,",0,0,").concat(m,",").concat(e,",").concat(r+i-s*C," Z")}else x="M ".concat(e,",").concat(r," h ").concat(n," v ").concat(i," h ").concat(-n," Z");return x},iSt=function(e,r){if(!e||!r)return!1;var n=e.x,i=e.y,a=r.x,c=r.y,s=r.width,f=r.height;if(Math.abs(s)>0&&Math.abs(f)>0){var m=Math.min(a,a+s),x=Math.max(a,a+s),_=Math.min(c,c+f),T=Math.max(c,c+f);return n>=m&&n<=x&&i>=_&&i<=T}return!1},sSt={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},BH=function(e){var r=Sae(Sae({},sSt),e),n=P.useRef(),i=P.useState(-1),a=Z1t(i,2),c=a[0],s=a[1];P.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var V=n.current.getTotalLength();V&&s(V)}catch{}},[]);var f=r.x,m=r.y,x=r.width,_=r.height,T=r.radius,E=r.className,C=r.animationEasing,N=r.animationDuration,R=r.animationBegin,D=r.isAnimationActive,M=r.isUpdateAnimationActive;if(f!==+f||m!==+m||x!==+x||_!==+_||x===0||_===0)return null;var B=Li("recharts-rectangle",E);return M?Xe.createElement(Fm,{canBegin:c>0,from:{width:x,height:_,x:f,y:m},to:{width:x,height:_,x:f,y:m},duration:N,animationEasing:C,isActive:M},function(V){var G=V.width,W=V.height,X=V.x,Q=V.y;return Xe.createElement(Fm,{canBegin:c>0,from:"0px ".concat(c===-1?1:c,"px"),to:"".concat(c,"px 0px"),attributeName:"strokeDasharray",begin:R,duration:N,isActive:D,easing:C},Xe.createElement("path",JD({},ui(r,!0),{className:B,d:Tae(X,Q,G,W,T),ref:n})))}):Xe.createElement("path",JD({},ui(r,!0),{className:B,d:Tae(f,m,x,_,T)}))},aSt=["points","className","baseLinePoints","connectNulls"];function xw(){return xw=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 lSt(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 Eae(t){return hSt(t)||dSt(t)||uSt(t)||cSt()}function cSt(){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 uSt(t,e){if(t){if(typeof t=="string")return y8(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 y8(t,e)}}function dSt(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function hSt(t){if(Array.isArray(t))return y8(t)}function y8(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){Aae(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),Aae(e[0])&&r[r.length-1].push(e[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},CA=function(e,r){var n=fSt(e);r&&(n=[n.reduce(function(a,c){return[].concat(Eae(a),Eae(c))},[])]);var i=n.map(function(a){return a.reduce(function(c,s,f){return"".concat(c).concat(f===0?"M":"L").concat(s.x,",").concat(s.y)},"")}).join("");return n.length===1?"".concat(i,"Z"):i},pSt=function(e,r,n){var i=CA(e,n);return"".concat(i.slice(-1)==="Z"?i.slice(0,-1):i,"L").concat(CA(r.reverse(),n).slice(1))},mSt=function(e){var r=e.points,n=e.className,i=e.baseLinePoints,a=e.connectNulls,c=oSt(e,aSt);if(!r||!r.length)return null;var s=Li("recharts-polygon",n);if(i&&i.length){var f=c.stroke&&c.stroke!=="none",m=pSt(r,i,a);return Xe.createElement("g",{className:s},Xe.createElement("path",xw({},ui(c,!0),{fill:m.slice(-1)==="Z"?c.fill:"none",stroke:"none",d:m})),f?Xe.createElement("path",xw({},ui(c,!0),{fill:"none",d:CA(r,a)})):null,f?Xe.createElement("path",xw({},ui(c,!0),{fill:"none",d:CA(i,a)})):null)}var x=CA(r,a);return Xe.createElement("path",xw({},ui(c,!0),{fill:x.slice(-1)==="Z"?c.fill:"none",className:s,d:x}))};function x8(){return x8=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 wSt(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 SSt=function(e,r,n,i,a,c){return"M".concat(e,",").concat(a,"v").concat(i,"M").concat(c,",").concat(r,"h").concat(n)},TSt=function(e){var r=e.x,n=r===void 0?0:r,i=e.y,a=i===void 0?0:i,c=e.top,s=c===void 0?0:c,f=e.left,m=f===void 0?0:f,x=e.width,_=x===void 0?0:x,T=e.height,E=T===void 0?0:T,C=e.className,N=bSt(e,gSt),R=ySt({x:n,y:a,top:s,left:m,width:_,height:E},N);return!Wr(n)||!Wr(a)||!Wr(_)||!Wr(E)||!Wr(s)||!Wr(m)?null:Xe.createElement("path",_8({},ui(R,!0),{className:Li("recharts-cross",C),d:SSt(n,a,_,E,s,m)}))},ESt=$F,ASt=aSe,kSt=gp;function CSt(t,e){return t&&t.length?ESt(t,kSt(e),ASt):void 0}var jSt=CSt;const ISt=ds(jSt);var PSt=$F,NSt=gp,RSt=oSe;function LSt(t,e){return t&&t.length?PSt(t,NSt(e),RSt):void 0}var DSt=LSt;const OSt=ds(DSt);var MSt=["cx","cy","angle","ticks","axisLine"],FSt=["ticks","tick","angle","tickFormatter","stroke"];function $1(t){"@babel/helpers - typeof";return $1=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},$1(t)}function jA(){return jA=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 BSt(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 zSt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Iae(t,e){for(var r=0;rRae?c=i==="outer"?"start":"end":a<-Rae?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,s=n.axisLine,f=n.axisLineType,m=I_(I_({},ui(this.props,!1)),{},{fill:"none"},ui(s,!1));if(f==="circle")return Xe.createElement(zH,V_({className:"recharts-polar-angle-axis-line"},m,{cx:i,cy:a,r:c}));var x=this.props.ticks,_=x.map(function(T){return pa(i,a,c,T.coordinate)});return Xe.createElement(mSt,V_({className:"recharts-polar-angle-axis-line"},m,{points:_}))}},{key:"renderTicks",value:function(){var n=this,i=this.props,a=i.ticks,c=i.tick,s=i.tickLine,f=i.tickFormatter,m=i.stroke,x=ui(this.props,!1),_=ui(c,!1),T=I_(I_({},x),{},{fill:"none"},ui(s,!1)),E=a.map(function(C,N){var R=n.getTickLineCoord(C),D=n.getTickTextAnchor(C),M=I_(I_(I_({textAnchor:D},x),{},{stroke:"none",fill:m},_),{},{index:N,payload:C,x:R.x2,y:R.y2});return Xe.createElement(zs,V_({className:Li("recharts-polar-angle-axis-tick",DSe(c)),key:"tick-".concat(C.coordinate)},I0(n.props,C,N)),s&&Xe.createElement("line",V_({className:"recharts-polar-angle-axis-tick-line"},T,R)),c&&e.renderTickItem(c,M,f?f(C.value,N):C.value))});return Xe.createElement(zs,{className:"recharts-polar-angle-axis-ticks"},E)}},{key:"render",value:function(){var n=this.props,i=n.ticks,a=n.radius,c=n.axisLine;return a<=0||!i||!i.length?null:Xe.createElement(zs,{className:Li("recharts-polar-angle-axis",this.props.className)},c&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,i,a){var c;return Xe.isValidElement(n)?c=Xe.cloneElement(n,i):gi(n)?c=n(i):c=Xe.createElement(P0,V_({},i,{className:"recharts-polar-angle-axis-tick-value"}),a),c}}])}(P.PureComponent);ZF(XF,"displayName","PolarAngleAxis");ZF(XF,"axisType","angleAxis");ZF(XF,"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 tTt=r1e,rTt=tTt(Object.getPrototypeOf,Object),nTt=rTt,iTt=qm,sTt=nTt,aTt=Gm,oTt="[object Object]",lTt=Function.prototype,cTt=Object.prototype,eTe=lTt.toString,uTt=cTt.hasOwnProperty,dTt=eTe.call(Object);function hTt(t){if(!aTt(t)||iTt(t)!=oTt)return!1;var e=sTt(t);if(e===null)return!0;var r=uTt.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&eTe.call(r)==dTt}var fTt=hTt;const pTt=ds(fTt);var mTt=qm,gTt=Gm,yTt="[object Boolean]";function xTt(t){return t===!0||t===!1||gTt(t)&&mTt(t)==yTt}var _Tt=xTt;const vTt=ds(_Tt);function Xk(t){"@babel/helpers - typeof";return Xk=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},Xk(t)}function rO(){return rO=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:T,x:f,y:m},to:{upperWidth:x,lowerWidth:_,height:T,x:f,y:m},duration:N,animationEasing:C,isActive:D},function(B){var V=B.upperWidth,G=B.lowerWidth,W=B.height,X=B.x,Q=B.y;return Xe.createElement(Fm,{canBegin:c>0,from:"0px ".concat(c===-1?1:c,"px"),to:"".concat(c,"px 0px"),attributeName:"strokeDasharray",begin:R,duration:N,easing:C},Xe.createElement("path",rO({},ui(r,!0),{className:M,d:Mae(X,Q,V,G,W),ref:n})))}):Xe.createElement("g",null,Xe.createElement("path",rO({},ui(r,!0),{className:M,d:Mae(f,m,x,_,T)})))},PTt=["option","shapeType","propTransformer","activeClassName","isActive"];function Qk(t){"@babel/helpers - typeof";return Qk=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},Qk(t)}function NTt(t,e){if(t==null)return{};var r=RTt(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 RTt(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 Fae(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 nO(t){for(var e=1;e0?nd(B,"paddingAngle",0):0;if(G){var X=Xg(G.endAngle-G.startAngle,B.endAngle-B.startAngle),Q=da(da({},B),{},{startAngle:M+W,endAngle:M+X(N)+W});R.push(Q),M=Q.endAngle}else{var re=B.endAngle,se=B.startAngle,ue=Xg(0,re-se),_e=ue(N),Se=da(da({},B),{},{startAngle:M+W,endAngle:M+_e+W});R.push(Se),M=Se.endAngle}}),Xe.createElement(zs,null,n.renderSectorsStatically(R))})}},{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 s=--i.state.sectorToFocus<0?i.sectorRefs.length-1:i.state.sectorToFocus%i.sectorRefs.length;i.sectorRefs[s].focus(),i.setState({sectorToFocus:s});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||!qF(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,s=i.className,f=i.label,m=i.cx,x=i.cy,_=i.innerRadius,T=i.outerRadius,E=i.isAnimationActive,C=this.state.isAnimationFinished;if(a||!c||!c.length||!Wr(m)||!Wr(x)||!Wr(_)||!Wr(T))return null;var N=Li("recharts-pie",s);return Xe.createElement(zs,{tabIndex:this.props.rootTabIndex,className:N,ref:function(D){n.pieRef=D}},this.renderSectors(),f&&this.renderLabels(c),El.renderCallByParent(this.props,null,!1),(!E||C)&&Ly.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?M:M-1)*f,V=R-M*E-B,G=i.reduce(function(Q,re){var se=Hl(re,D,0);return Q+(Wr(se)?se:0)},0),W;if(G>0){var X;W=i.map(function(Q,re){var se=Hl(Q,D,0),ue=Hl(Q,x,re),_e=(Wr(se)?se:0)/G,Se;re?Se=X.endAngle+Gc(N)*f*(se!==0?1:0):Se=c;var ve=Se+Gc(N)*((se!==0?E:0)+_e*V),Oe=(Se+ve)/2,Ae=(C.innerRadius+C.outerRadius)/2,we=[{name:ue,value:se,payload:Q,dataKey:D,type:T}],ge=pa(C.cx,C.cy,Ae,Oe);return X=da(da(da({percent:_e,cornerRadius:a,name:ue,tooltipPayload:we,midAngle:Oe,middleRadius:Ae,tooltipPosition:ge},Q),C),{},{value:Hl(Q,D),startAngle:Se,endAngle:ve,payload:Q,paddingAngle:Gc(N)*f}),X})}return da(da({},C),{},{sectors:W,data:i})});var eEt=Math.ceil,tEt=Math.max;function rEt(t,e,r,n){for(var i=-1,a=tEt(eEt((e-t)/(r||1)),0),c=Array(a);a--;)c[n?a:++i]=t,t+=r;return c}var nEt=rEt,iEt=b1e,Uae=1/0,sEt=17976931348623157e292;function aEt(t){if(!t)return t===0?t:0;if(t=iEt(t),t===Uae||t===-Uae){var e=t<0?-1:1;return e*sEt}return t===t?t:0}var iTe=aEt,oEt=nEt,lEt=RF,Oz=iTe;function cEt(t){return function(e,r,n){return n&&typeof n!="number"&&lEt(e,r,n)&&(r=n=void 0),e=Oz(e),r===void 0?(r=e,e=0):r=Oz(r),n=n===void 0?e0&&n.handleDrag(i.changedTouches[0])}),Vu(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var i=n.props,a=i.endIndex,c=i.onDragEnd,s=i.startIndex;c==null||c({endIndex:a,startIndex:s})}),n.detachDragEndListener()}),Vu(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),Vu(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),Vu(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),Vu(n,"handleSlideDragStart",function(i){var a=Wae(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 SEt(e,t),_Et(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,s=this.props,f=s.gap,m=s.data,x=m.length-1,_=Math.min(i,a),T=Math.max(i,a),E=e.getIndexInRange(c,_),C=e.getIndexInRange(c,T);return{startIndex:E-E%f,endIndex:C===x?x:C-C%f}}},{key:"getTextOfTick",value:function(n){var i=this.props,a=i.data,c=i.tickFormatter,s=i.dataKey,f=Hl(a[n],s,n);return gi(c)?c(f,n):f}},{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,s=i.endX,f=this.props,m=f.x,x=f.width,_=f.travellerWidth,T=f.startIndex,E=f.endIndex,C=f.onChange,N=n.pageX-a;N>0?N=Math.min(N,m+x-_-s,m+x-_-c):N<0&&(N=Math.max(N,m-c,m-s));var R=this.getIndex({startX:c+N,endX:s+N});(R.startIndex!==T||R.endIndex!==E)&&C&&C(R),this.setState({startX:c+N,endX:s+N,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,i){var a=Wae(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,s=i.endX,f=i.startX,m=this.state[c],x=this.props,_=x.x,T=x.width,E=x.travellerWidth,C=x.onChange,N=x.gap,R=x.data,D={startX:this.state.startX,endX:this.state.endX},M=n.pageX-a;M>0?M=Math.min(M,_+T-E-m):M<0&&(M=Math.max(M,_-m)),D[c]=m+M;var B=this.getIndex(D),V=B.startIndex,G=B.endIndex,W=function(){var Q=R.length-1;return c==="startX"&&(s>f?V%N===0:G%N===0)||sf?G%N===0:V%N===0)||s>f&&G===Q};this.setState(Vu(Vu({},c,m+M),"brushMoveStartX",n.pageX),function(){C&&W()&&C(B)})}},{key:"handleTravellerMoveKeyboard",value:function(n,i){var a=this,c=this.state,s=c.scaleValues,f=c.startX,m=c.endX,x=this.state[i],_=s.indexOf(x);if(_!==-1){var T=_+n;if(!(T===-1||T>=s.length)){var E=s[T];i==="startX"&&E>=m||i==="endX"&&E<=f||this.setState(Vu({},i,E),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,s=n.height,f=n.fill,m=n.stroke;return Xe.createElement("rect",{stroke:m,fill:f,x:i,y:a,width:c,height:s})}},{key:"renderPanorama",value:function(){var n=this.props,i=n.x,a=n.y,c=n.width,s=n.height,f=n.data,m=n.children,x=n.padding,_=P.Children.only(m);return _?Xe.cloneElement(_,{x:i,y:a,width:c,height:s,margin:x,compact:!0,data:f}):null}},{key:"renderTravellerLayer",value:function(n,i){var a,c,s=this,f=this.props,m=f.y,x=f.travellerWidth,_=f.height,T=f.traveller,E=f.ariaLabel,C=f.data,N=f.startIndex,R=f.endIndex,D=Math.max(n,this.props.x),M=Mz(Mz({},ui(this.props,!1)),{},{x:D,y:m,width:x,height:_}),B=E||"Min value: ".concat((a=C[N])===null||a===void 0?void 0:a.name,", Max value: ").concat((c=C[R])===null||c===void 0?void 0:c.name);return Xe.createElement(zs,{tabIndex:0,role:"slider","aria-label":B,"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(),s.handleTravellerMoveKeyboard(G.key==="ArrowRight"?1:-1,i))},onFocus:function(){s.setState({isTravellerFocused:!0})},onBlur:function(){s.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},e.renderTraveller(T,M))}},{key:"renderSlide",value:function(n,i){var a=this.props,c=a.y,s=a.height,f=a.stroke,m=a.travellerWidth,x=Math.min(n,i)+m,_=Math.max(Math.abs(i-n)-m,0);return Xe.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:f,fillOpacity:.2,x,y:c,width:_,height:s})}},{key:"renderText",value:function(){var n=this.props,i=n.startIndex,a=n.endIndex,c=n.y,s=n.height,f=n.travellerWidth,m=n.stroke,x=this.state,_=x.startX,T=x.endX,E=5,C={pointerEvents:"none",fill:m};return Xe.createElement(zs,{className:"recharts-brush-texts"},Xe.createElement(P0,aO({textAnchor:"end",verticalAnchor:"middle",x:Math.min(_,T)-E,y:c+s/2},C),this.getTextOfTick(i)),Xe.createElement(P0,aO({textAnchor:"start",verticalAnchor:"middle",x:Math.max(_,T)+f+E,y:c+s/2},C),this.getTextOfTick(a)))}},{key:"render",value:function(){var n=this.props,i=n.data,a=n.className,c=n.children,s=n.x,f=n.y,m=n.width,x=n.height,_=n.alwaysShowText,T=this.state,E=T.startX,C=T.endX,N=T.isTextActive,R=T.isSlideMoving,D=T.isTravellerMoving,M=T.isTravellerFocused;if(!i||!i.length||!Wr(s)||!Wr(f)||!Wr(m)||!Wr(x)||m<=0||x<=0)return null;var B=Li("recharts-brush",a),V=Xe.Children.count(c)===1,G=yEt("userSelect","none");return Xe.createElement(zs,{className:B,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:G},this.renderBackground(),V&&this.renderPanorama(),this.renderSlide(E,C),this.renderTravellerLayer(E,"startX"),this.renderTravellerLayer(C,"endX"),(N||R||D||M||_)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var i=n.x,a=n.y,c=n.width,s=n.height,f=n.stroke,m=Math.floor(a+s/2)-1;return Xe.createElement(Xe.Fragment,null,Xe.createElement("rect",{x:i,y:a,width:c,height:s,fill:f,stroke:"none"}),Xe.createElement("line",{x1:i+1,y1:m,x2:i+c-1,y2:m,fill:"none",stroke:"#fff"}),Xe.createElement("line",{x1:i+1,y1:m+2,x2:i+c-1,y2:m+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,i){var a;return Xe.isValidElement(n)?a=Xe.cloneElement(n,i):gi(n)?a=n(i):a=e.renderDefaultTraveller(i),a}},{key:"getDerivedStateFromProps",value:function(n,i){var a=n.data,c=n.width,s=n.x,f=n.travellerWidth,m=n.updateId,x=n.startIndex,_=n.endIndex;if(a!==i.prevData||m!==i.prevUpdateId)return Mz({prevData:a,prevTravellerWidth:f,prevUpdateId:m,prevX:s,prevWidth:c},a&&a.length?EEt({data:a,width:c,x:s,travellerWidth:f,startIndex:x,endIndex:_}):{scale:null,scaleValues:null});if(i.scale&&(c!==i.prevWidth||s!==i.prevX||f!==i.prevTravellerWidth)){i.scale.range([s,s+c-f]);var T=i.scale.domain().map(function(E){return i.scale(E)});return{prevData:a,prevTravellerWidth:f,prevUpdateId:m,prevX:s,prevWidth:c,startX:i.scale(n.startIndex),endX:i.scale(n.endIndex),scaleValues:T}}return null}},{key:"getIndexInRange",value:function(n,i){for(var a=n.length,c=0,s=a-1;s-c>1;){var f=Math.floor((c+s)/2);n[f]>i?s=f:c=f}return i>=n[s]?s:c}}])}(P.PureComponent);Vu(G1,"displayName","Brush");Vu(G1,"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 AEt=dH;function kEt(t,e){var r;return AEt(t,function(n,i,a){return r=e(n,i,a),!r}),!!r}var CEt=kEt,jEt=Kwe,IEt=gp,PEt=CEt,NEt=Pu,REt=RF;function LEt(t,e,r){var n=NEt(t)?jEt:PEt;return r&&REt(t,e,r)&&(e=void 0),n(t,IEt(e))}var DEt=LEt;const OEt=ds(DEt);var Jf=function(e,r){var n=e.alwaysShow,i=e.ifOverflow;return n&&(i="extendDomain"),i===r},Kae=g1e;function MEt(t,e,r){e=="__proto__"&&Kae?Kae(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var FEt=MEt,BEt=FEt,zEt=p1e,$Et=gp;function UEt(t,e){var r={};return e=$Et(e),zEt(t,function(n,i,a){BEt(r,i,e(n,i,a))}),r}var VEt=UEt;const qEt=ds(VEt);function GEt(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 l2t(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 c2t(t,e){var r=t.x,n=t.y,i=o2t(t,n2t),a="".concat(r),c=parseInt(a,10),s="".concat(n),f=parseInt(s,10),m="".concat(e.height||i.height),x=parseInt(m,10),_="".concat(e.width||i.width),T=parseInt(_,10);return L2(L2(L2(L2(L2({},e),i),c?{x:c}:{}),f?{y:f}:{}),{},{height:x,width:T,name:e.name,radius:e.radius})}function Zae(t){return Xe.createElement(tTe,T8({shapeType:"rectangle",propTransformer:c2t,activeClassName:"recharts-active-bar"},t))}var u2t=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=Wr(n)||Hat(n);return a?e(n,i):(a||R0(),r)}},d2t=["value","background"],cTe;function H1(t){"@babel/helpers - typeof";return H1=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},H1(t)}function h2t(t,e){if(t==null)return{};var r=f2t(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 f2t(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 lO(){return lO=Object.assign?Object.assign.bind():function(t){for(var e=1;e0&&Math.abs(Oe)0&&Math.abs(ve)0&&(Se=Math.min((rt||0)-(ve[at-1]||0),Se))}),Number.isFinite(Se)){var Oe=Se/_e,Ae=N.layout==="vertical"?n.height:n.width;if(N.padding==="gap"&&(X=Oe*Ae/2),N.padding==="no-gap"){var we=Hc(e.barCategoryGap,Oe*Ae),ge=Oe*Ae/2;X=ge-we-(ge-we)/Ae*we}}}i==="xAxis"?Q=[n.left+(B.left||0)+(X||0),n.left+n.width-(B.right||0)-(X||0)]:i==="yAxis"?Q=f==="horizontal"?[n.top+n.height-(B.bottom||0),n.top+(B.top||0)]:[n.top+(B.top||0)+(X||0),n.top+n.height-(B.bottom||0)-(X||0)]:Q=N.range,G&&(Q=[Q[1],Q[0]]);var Ne=CSe(N,a,T),Ie=Ne.scale,Te=Ne.realScaleType;Ie.domain(D).range(Q),jSe(Ie);var be=ISe(Ie,Fh(Fh({},N),{},{realScaleType:Te}));i==="xAxis"?(ue=R==="top"&&!V||R==="bottom"&&V,re=n.left,se=_[W]-ue*N.height):i==="yAxis"&&(ue=R==="left"&&!V||R==="right"&&V,re=_[W]-ue*N.width,se=n.top);var We=Fh(Fh(Fh({},N),be),{},{realScaleType:Te,x:re,y:se,scale:Ie,width:i==="xAxis"?n.width:N.width,height:i==="yAxis"?n.height:N.height});return We.bandSize=WD(We,be),!N.hide&&i==="xAxis"?_[W]+=(ue?-1:1)*We.height:N.hide||(_[W]+=(ue?-1:1)*We.width),Fh(Fh({},E),{},e3({},C,We))},{})},fTe=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)}},E2t=function(e){var r=e.x1,n=e.y1,i=e.x2,a=e.y2;return fTe({x:r,y:n},{x:i,y:a})},pTe=function(){function t(e){b2t(this,t),this.scale=e}return w2t(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 s=this.bandwidth?this.bandwidth():0;return this.scale(r)+s}default:return this.scale(r)}if(i){var f=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+f}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)}}])}();e3(pTe,"EPS",1e-4);var $H=function(e){var r=Object.keys(e).reduce(function(n,i){return Fh(Fh({},n),{},e3({},i,pTe.create(e[i])))},{});return Fh(Fh({},r),{},{apply:function(i){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},c=a.bandAware,s=a.position;return qEt(i,function(f,m){return r[m].apply(f,{bandAware:c,position:s})})},isInRange:function(i){return lTe(i,function(a,c){return r[c].isInRange(a)})}})};function A2t(t){return(t%180+180)%180}var k2t=function(e){var r=e.width,n=e.height,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,a=A2t(i),c=a*Math.PI/180,s=Math.atan(n/r),f=c>s&&c-1?i[a?e[c]:c]:void 0}}var N2t=P2t,R2t=iTe;function L2t(t){var e=R2t(t),r=e%1;return e===e?r?e-r:e:0}var D2t=L2t,O2t=l1e,M2t=gp,F2t=D2t,B2t=Math.max;function z2t(t,e,r){var n=t==null?0:t.length;if(!n)return-1;var i=r==null?0:F2t(r);return i<0&&(i=B2t(n+i,0)),O2t(t,M2t(e),i)}var $2t=z2t,U2t=N2t,V2t=$2t,q2t=U2t(V2t),G2t=q2t;const H2t=ds(G2t);var W2t=Zst(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("")}),UH=P.createContext(void 0),VH=P.createContext(void 0),mTe=P.createContext(void 0),gTe=P.createContext({}),yTe=P.createContext(void 0),xTe=P.createContext(0),_Te=P.createContext(0),toe=function(e){var r=e.state,n=r.xAxisMap,i=r.yAxisMap,a=r.offset,c=e.clipPathId,s=e.children,f=e.width,m=e.height,x=W2t(a);return Xe.createElement(UH.Provider,{value:n},Xe.createElement(VH.Provider,{value:i},Xe.createElement(gTe.Provider,{value:a},Xe.createElement(mTe.Provider,{value:x},Xe.createElement(yTe.Provider,{value:c},Xe.createElement(xTe.Provider,{value:m},Xe.createElement(_Te.Provider,{value:f},s)))))))},K2t=function(){return P.useContext(yTe)},vTe=function(e){var r=P.useContext(UH);r==null&&R0();var n=r[e];return n==null&&R0(),n},Y2t=function(){var e=P.useContext(UH);return iy(e)},Z2t=function(){var e=P.useContext(VH),r=H2t(e,function(n){return lTe(n.domain,Number.isFinite)});return r||iy(e)},bTe=function(e){var r=P.useContext(VH);r==null&&R0();var n=r[e];return n==null&&R0(),n},X2t=function(){var e=P.useContext(mTe);return e},Q2t=function(){return P.useContext(gTe)},qH=function(){return P.useContext(_Te)},GH=function(){return P.useContext(xTe)};function W1(t){"@babel/helpers - typeof";return W1=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},W1(t)}function J2t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function eAt(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 DAt(t,e){return CTe(t,e+1)}function OAt(t,e,r,n,i){for(var a=(n||[]).slice(),c=e.start,s=e.end,f=0,m=1,x=c,_=function(){var C=n==null?void 0:n[f];if(C===void 0)return{v:CTe(n,m)};var N=f,R,D=function(){return R===void 0&&(R=r(C,N)),R},M=C.coordinate,B=f===0||fO(t,M,D,x,s);B||(f=0,x=c,m+=1),B&&(x=M+t*(D()/2+i),f+=m)},T;m<=a.length;)if(T=_(),T)return T.v;return[]}function nC(t){"@babel/helpers - typeof";return nC=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},nC(t)}function coe(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 dc(t){for(var e=1;e0?E.coordinate-R*t:E.coordinate})}else a[T]=E=dc(dc({},E),{},{tickCoord:E.coordinate});var D=fO(t,E.tickCoord,N,s,f);D&&(f=E.tickCoord-t*(N()/2+i),a[T]=dc(dc({},E),{},{isShow:!0}))},x=c-1;x>=0;x--)m(x);return a}function $At(t,e,r,n,i,a){var c=(n||[]).slice(),s=c.length,f=e.start,m=e.end;if(a){var x=n[s-1],_=r(x,s-1),T=t*(x.coordinate+t*_/2-m);c[s-1]=x=dc(dc({},x),{},{tickCoord:T>0?x.coordinate-T*t:x.coordinate});var E=fO(t,x.tickCoord,function(){return _},f,m);E&&(m=x.tickCoord-t*(_/2+i),c[s-1]=dc(dc({},x),{},{isShow:!0}))}for(var C=a?s-1:s,N=function(M){var B=c[M],V,G=function(){return V===void 0&&(V=r(B,M)),V};if(M===0){var W=t*(B.coordinate-t*G()/2-f);c[M]=B=dc(dc({},B),{},{tickCoord:W<0?B.coordinate-W*t:B.coordinate})}else c[M]=B=dc(dc({},B),{},{tickCoord:B.coordinate});var X=fO(t,B.tickCoord,G,f,m);X&&(f=B.tickCoord+t*(G()/2+i),c[M]=dc(dc({},B),{},{isShow:!0}))},R=0;R=2?Gc(i[1].coordinate-i[0].coordinate):1,D=LAt(a,R,E);return f==="equidistantPreserveStart"?OAt(R,D,N,i,c):(f==="preserveStart"||f==="preserveStartEnd"?T=$At(R,D,N,i,c,f==="preserveStartEnd"):T=zAt(R,D,N,i,c),T.filter(function(M){return M.isShow}))}var UAt=["viewBox"],VAt=["viewBox"],qAt=["ticks"];function Z1(t){"@babel/helpers - typeof";return Z1=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},Z1(t)}function vw(){return vw=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 GAt(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 HAt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function doe(t,e){for(var r=0;r0?f(this.props):f(E)),c<=0||s<=0||!C||!C.length?null:Xe.createElement(zs,{className:Li("recharts-cartesian-axis",m),ref:function(R){n.layerReference=R}},a&&this.renderAxisLine(),this.renderTicks(C,this.state.fontSize,this.state.letterSpacing),El.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,i,a){var c,s=Li(i.className,"recharts-cartesian-axis-tick-value");return Xe.isValidElement(n)?c=Xe.cloneElement(n,Qo(Qo({},i),{},{className:s})):gi(n)?c=n(Qo(Qo({},i),{},{className:s})):c=Xe.createElement(P0,vw({},i,{className:"recharts-cartesian-axis-tick-value"}),a),c}}])}(P.Component);YH(VS,"displayName","CartesianAxis");YH(VS,"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 JAt=["x1","y1","x2","y2","key"],ekt=["offset"];function L0(t){"@babel/helpers - typeof";return L0=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},L0(t)}function hoe(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 fc(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function ikt(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 skt=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,s=e.height,f=e.ry;return Xe.createElement("rect",{x:i,y:a,ry:f,width:c,height:s,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function PTe(t,e){var r;if(Xe.isValidElement(t))r=Xe.cloneElement(t,e);else if(gi(t))r=t(e);else{var n=e.x1,i=e.y1,a=e.x2,c=e.y2,s=e.key,f=foe(e,JAt),m=ui(f,!1);m.offset;var x=foe(m,ekt);r=Xe.createElement("line",J_({},x,{x1:n,y1:i,x2:a,y2:c,fill:"none",key:s}))}return r}function akt(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(s,f){var m=fc(fc({},t),{},{x1:e,y1:s,x2:e+r,y2:s,key:"line-".concat(f),index:f});return PTe(i,m)});return Xe.createElement("g",{className:"recharts-cartesian-grid-horizontal"},c)}function okt(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(s,f){var m=fc(fc({},t),{},{x1:s,y1:e,x2:s,y2:e+r,key:"line-".concat(f),index:f});return PTe(i,m)});return Xe.createElement("g",{className:"recharts-cartesian-grid-vertical"},c)}function lkt(t){var e=t.horizontalFill,r=t.fillOpacity,n=t.x,i=t.y,a=t.width,c=t.height,s=t.horizontalPoints,f=t.horizontal,m=f===void 0?!0:f;if(!m||!e||!e.length)return null;var x=s.map(function(T){return Math.round(T+i-i)}).sort(function(T,E){return T-E});i!==x[0]&&x.unshift(0);var _=x.map(function(T,E){var C=!x[E+1],N=C?i+c-T:x[E+1]-T;if(N<=0)return null;var R=E%e.length;return Xe.createElement("rect",{key:"react-".concat(E),y:T,x:n,height:N,width:a,stroke:"none",fill:e[R],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return Xe.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},_)}function ckt(t){var e=t.vertical,r=e===void 0?!0:e,n=t.verticalFill,i=t.fillOpacity,a=t.x,c=t.y,s=t.width,f=t.height,m=t.verticalPoints;if(!r||!n||!n.length)return null;var x=m.map(function(T){return Math.round(T+a-a)}).sort(function(T,E){return T-E});a!==x[0]&&x.unshift(0);var _=x.map(function(T,E){var C=!x[E+1],N=C?a+s-T:x[E+1]-T;if(N<=0)return null;var R=E%n.length;return Xe.createElement("rect",{key:"react-".concat(E),x:T,y:c,width:N,height:f,stroke:"none",fill:n[R],fillOpacity:i,className:"recharts-cartesian-grid-bg"})});return Xe.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},_)}var ukt=function(e,r){var n=e.xAxis,i=e.width,a=e.height,c=e.offset;return kSe(KH(fc(fc(fc({},VS.defaultProps),n),{},{ticks:mm(n,!0),viewBox:{x:0,y:0,width:i,height:a}})),c.left,c.left+c.width,r)},dkt=function(e,r){var n=e.yAxis,i=e.width,a=e.height,c=e.offset;return kSe(KH(fc(fc(fc({},VS.defaultProps),n),{},{ticks:mm(n,!0),viewBox:{x:0,y:0,width:i,height:a}})),c.top,c.top+c.height,r)},Ub={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function NTe(t){var e,r,n,i,a,c,s=qH(),f=GH(),m=Q2t(),x=fc(fc({},t),{},{stroke:(e=t.stroke)!==null&&e!==void 0?e:Ub.stroke,fill:(r=t.fill)!==null&&r!==void 0?r:Ub.fill,horizontal:(n=t.horizontal)!==null&&n!==void 0?n:Ub.horizontal,horizontalFill:(i=t.horizontalFill)!==null&&i!==void 0?i:Ub.horizontalFill,vertical:(a=t.vertical)!==null&&a!==void 0?a:Ub.vertical,verticalFill:(c=t.verticalFill)!==null&&c!==void 0?c:Ub.verticalFill,x:Wr(t.x)?t.x:m.left,y:Wr(t.y)?t.y:m.top,width:Wr(t.width)?t.width:m.width,height:Wr(t.height)?t.height:m.height}),_=x.x,T=x.y,E=x.width,C=x.height,N=x.syncWithTicks,R=x.horizontalValues,D=x.verticalValues,M=Y2t(),B=Z2t();if(!Wr(E)||E<=0||!Wr(C)||C<=0||!Wr(_)||_!==+_||!Wr(T)||T!==+T)return null;var V=x.verticalCoordinatesGenerator||ukt,G=x.horizontalCoordinatesGenerator||dkt,W=x.horizontalPoints,X=x.verticalPoints;if((!W||!W.length)&&gi(G)){var Q=R&&R.length,re=G({yAxis:B?fc(fc({},B),{},{ticks:Q?R:B.ticks}):void 0,width:s,height:f,offset:m},Q?!0:N);Xh(Array.isArray(re),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(L0(re),"]")),Array.isArray(re)&&(W=re)}if((!X||!X.length)&&gi(V)){var se=D&&D.length,ue=V({xAxis:M?fc(fc({},M),{},{ticks:se?D:M.ticks}):void 0,width:s,height:f,offset:m},se?!0:N);Xh(Array.isArray(ue),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(L0(ue),"]")),Array.isArray(ue)&&(X=ue)}return Xe.createElement("g",{className:"recharts-cartesian-grid"},Xe.createElement(skt,{fill:x.fill,fillOpacity:x.fillOpacity,x:x.x,y:x.y,width:x.width,height:x.height,ry:x.ry}),Xe.createElement(akt,J_({},x,{offset:m,horizontalPoints:W,xAxis:M,yAxis:B})),Xe.createElement(okt,J_({},x,{offset:m,verticalPoints:X,xAxis:M,yAxis:B})),Xe.createElement(lkt,J_({},x,{horizontalPoints:W})),Xe.createElement(ckt,J_({},x,{verticalPoints:X})))}NTe.displayName="CartesianGrid";function X1(t){"@babel/helpers - typeof";return X1=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},X1(t)}function hkt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function fkt(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 Jkt(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 eCt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function tCt(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r0?c:e&&e.length&&Wr(i)&&Wr(a)?e.slice(i,a+1):[]};function HTe(t){return t==="number"?[0,"auto"]:void 0}var $8=function(e,r,n,i){var a=e.graphicalItems,c=e.tooltipAxis,s=o3(r,e);return n<0||!a||!a.length||n>=s.length?null:a.reduce(function(f,m){var x,_=(x=m.props.data)!==null&&x!==void 0?x:r;_&&e.dataStartIndex+e.dataEndIndex!==0&&e.dataEndIndex-e.dataStartIndex>=n&&(_=_.slice(e.dataStartIndex,e.dataEndIndex+1));var T;if(c.dataKey&&!c.allowDuplicatedCategory){var E=_===void 0?s:_;T=_D(E,c.dataKey,i)}else T=_&&_[n]||s[n];return T?[].concat(eS(f),[NSe(m,T)]):f},[])},_oe=function(e,r,n,i){var a=i||{x:e.chartX,y:e.chartY},c=fCt(a,n),s=e.orderedTooltipTicks,f=e.tooltipAxis,m=e.tooltipTicks,x=ibt(c,s,m,f);if(x>=0&&m){var _=m[x]&&m[x].value,T=$8(e,r,x,_),E=pCt(n,s,x,a);return{activeTooltipIndex:x,activeLabel:_,activePayload:T,activeCoordinate:E}}return null},mCt=function(e,r){var n=r.axes,i=r.graphicalItems,a=r.axisType,c=r.axisIdKey,s=r.stackGroups,f=r.dataStartIndex,m=r.dataEndIndex,x=e.layout,_=e.children,T=e.stackOffset,E=ASe(x,a);return n.reduce(function(C,N){var R,D=N.type.defaultProps!==void 0?_r(_r({},N.type.defaultProps),N.props):N.props,M=D.type,B=D.dataKey,V=D.allowDataOverflow,G=D.allowDuplicatedCategory,W=D.scale,X=D.ticks,Q=D.includeHidden,re=D[c];if(C[re])return C;var se=o3(e.data,{graphicalItems:i.filter(function(be){var We,rt=c in be.props?be.props[c]:(We=be.type.defaultProps)===null||We===void 0?void 0:We[c];return rt===re}),dataStartIndex:f,dataEndIndex:m}),ue=se.length,_e,Se,ve;$kt(D.domain,V,M)&&(_e=r8(D.domain,null,V),E&&(M==="number"||W!=="auto")&&(ve=AA(se,B,"category")));var Oe=HTe(M);if(!_e||_e.length===0){var Ae,we=(Ae=D.domain)!==null&&Ae!==void 0?Ae:Oe;if(B){if(_e=AA(se,B,M),M==="category"&&E){var ge=Kat(_e);G&&ge?(Se=_e,_e=sO(0,ue)):G||(_e=qse(we,_e,N).reduce(function(be,We){return be.indexOf(We)>=0?be:[].concat(eS(be),[We])},[]))}else if(M==="category")G?_e=_e.filter(function(be){return be!==""&&!Di(be)}):_e=qse(we,_e,N).reduce(function(be,We){return be.indexOf(We)>=0||We===""||Di(We)?be:[].concat(eS(be),[We])},[]);else if(M==="number"){var Ne=cbt(se,i.filter(function(be){var We,rt,at=c in be.props?be.props[c]:(We=be.type.defaultProps)===null||We===void 0?void 0:We[c],Et="hide"in be.props?be.props.hide:(rt=be.type.defaultProps)===null||rt===void 0?void 0:rt.hide;return at===re&&(Q||!Et)}),B,a,x);Ne&&(_e=Ne)}E&&(M==="number"||W!=="auto")&&(ve=AA(se,B,"category"))}else E?_e=sO(0,ue):s&&s[re]&&s[re].hasStack&&M==="number"?_e=T==="expand"?[0,1]:PSe(s[re].stackGroups,f,m):_e=ESe(se,i.filter(function(be){var We=c in be.props?be.props[c]:be.type.defaultProps[c],rt="hide"in be.props?be.props.hide:be.type.defaultProps.hide;return We===re&&(Q||!rt)}),M,x,!0);if(M==="number")_e=F8(_,_e,re,a,X),we&&(_e=r8(we,_e,V));else if(M==="category"&&we){var Ie=we,Te=_e.every(function(be){return Ie.indexOf(be)>=0});Te&&(_e=Ie)}}return _r(_r({},C),{},ni({},re,_r(_r({},D),{},{axisType:a,domain:_e,categoricalDomain:ve,duplicateDomain:Se,originalDomain:(R=D.domain)!==null&&R!==void 0?R:Oe,isCategorical:E,layout:x})))},{})},gCt=function(e,r){var n=r.graphicalItems,i=r.Axis,a=r.axisType,c=r.axisIdKey,s=r.stackGroups,f=r.dataStartIndex,m=r.dataEndIndex,x=e.layout,_=e.children,T=o3(e.data,{graphicalItems:n,dataStartIndex:f,dataEndIndex:m}),E=T.length,C=ASe(x,a),N=-1;return n.reduce(function(R,D){var M=D.type.defaultProps!==void 0?_r(_r({},D.type.defaultProps),D.props):D.props,B=M[c],V=HTe("number");if(!R[B]){N++;var G;return C?G=sO(0,E):s&&s[B]&&s[B].hasStack?(G=PSe(s[B].stackGroups,f,m),G=F8(_,G,B,a)):(G=r8(V,ESe(T,n.filter(function(W){var X,Q,re=c in W.props?W.props[c]:(X=W.type.defaultProps)===null||X===void 0?void 0:X[c],se="hide"in W.props?W.props.hide:(Q=W.type.defaultProps)===null||Q===void 0?void 0:Q.hide;return re===B&&!se}),"number",x),i.defaultProps.allowDataOverflow),G=F8(_,G,B,a)),_r(_r({},R),{},ni({},B,_r(_r({axisType:a},i.defaultProps),{},{hide:!0,orientation:nd(dCt,"".concat(a,".").concat(N%2),null),domain:G,originalDomain:V,isCategorical:C,layout:x})))}return R},{})},yCt=function(e,r){var n=r.axisType,i=n===void 0?"xAxis":n,a=r.AxisComp,c=r.graphicalItems,s=r.stackGroups,f=r.dataStartIndex,m=r.dataEndIndex,x=e.children,_="".concat(i,"Id"),T=Wd(x,a),E={};return T&&T.length?E=mCt(e,{axes:T,graphicalItems:c,axisType:i,axisIdKey:_,stackGroups:s,dataStartIndex:f,dataEndIndex:m}):c&&c.length&&(E=gCt(e,{Axis:a,graphicalItems:c,axisType:i,axisIdKey:_,stackGroups:s,dataStartIndex:f,dataEndIndex:m})),E},xCt=function(e){var r=iy(e),n=mm(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:hH(n,function(i){return i.coordinate}),tooltipAxis:r,tooltipAxisBandSize:WD(r,n)}},voe=function(e){var r=e.children,n=e.defaultShowTooltip,i=Wu(r,G1),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}},_Ct=function(e){return!e||!e.length?!1:e.some(function(r){var n=vm(r&&r.type);return n&&n.indexOf("Bar")>=0})},boe=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"}},vCt=function(e,r){var n=e.props,i=e.graphicalItems,a=e.xAxisMap,c=a===void 0?{}:a,s=e.yAxisMap,f=s===void 0?{}:s,m=n.width,x=n.height,_=n.children,T=n.margin||{},E=Wu(_,G1),C=Wu(_,Fw),N=Object.keys(f).reduce(function(G,W){var X=f[W],Q=X.orientation;return!X.mirror&&!X.hide?_r(_r({},G),{},ni({},Q,G[Q]+X.width)):G},{left:T.left||0,right:T.right||0}),R=Object.keys(c).reduce(function(G,W){var X=c[W],Q=X.orientation;return!X.mirror&&!X.hide?_r(_r({},G),{},ni({},Q,nd(G,"".concat(Q))+X.height)):G},{top:T.top||0,bottom:T.bottom||0}),D=_r(_r({},R),N),M=D.bottom;E&&(D.bottom+=E.props.height||G1.defaultProps.height),C&&r&&(D=obt(D,i,n,r));var B=m-D.left-D.right,V=x-D.top-D.bottom;return _r(_r({brushBottom:M},D),{},{width:Math.max(B,0),height:Math.max(V,0)})},bCt=function(e,r){if(r==="xAxis")return e[r].width;if(r==="yAxis")return e[r].height},WTe=function(e){var r=e.chartName,n=e.GraphicalChild,i=e.defaultTooltipEventType,a=i===void 0?"axis":i,c=e.validateTooltipEventTypes,s=c===void 0?["axis"]:c,f=e.axisComponents,m=e.legendContent,x=e.formatAxisMap,_=e.defaultProps,T=function(D,M){var B=M.graphicalItems,V=M.stackGroups,G=M.offset,W=M.updateId,X=M.dataStartIndex,Q=M.dataEndIndex,re=D.barSize,se=D.layout,ue=D.barGap,_e=D.barCategoryGap,Se=D.maxBarSize,ve=boe(se),Oe=ve.numericAxisName,Ae=ve.cateAxisName,we=_Ct(B),ge=[];return B.forEach(function(Ne,Ie){var Te=o3(D.data,{graphicalItems:[Ne],dataStartIndex:X,dataEndIndex:Q}),be=Ne.type.defaultProps!==void 0?_r(_r({},Ne.type.defaultProps),Ne.props):Ne.props,We=be.dataKey,rt=be.maxBarSize,at=be["".concat(Oe,"Id")],Et=be["".concat(Ae,"Id")],_t={},Vt=f.reduce(function(At,Ot){var dr=M["".concat(Ot.axisType,"Map")],cr=be["".concat(Ot.axisType,"Id")];dr&&dr[cr]||Ot.axisType==="zAxis"||R0();var hr=dr[cr];return _r(_r({},At),{},ni(ni({},Ot.axisType,hr),"".concat(Ot.axisType,"Ticks"),mm(hr)))},_t),mt=Vt[Ae],Pt=Vt["".concat(Ae,"Ticks")],er=V&&V[at]&&V[at].hasStack&&xbt(Ne,V[at].stackGroups),wt=vm(Ne.type).indexOf("Bar")>=0,or=WD(mt,Pt),Sr=[],nn=we&&sbt({barSize:re,stackGroups:V,totalSize:bCt(Vt,Ae)});if(wt){var lr,yr,tr=Di(rt)?Se:rt,yn=(lr=(yr=WD(mt,Pt,!0))!==null&&yr!==void 0?yr:tr)!==null&&lr!==void 0?lr:0;Sr=abt({barGap:ue,barCategoryGap:_e,bandSize:yn!==or?yn:or,sizeList:nn[Et],maxBarSize:tr}),yn!==or&&(Sr=Sr.map(function(At){return _r(_r({},At),{},{position:_r(_r({},At.position),{},{offset:At.position.offset-yn/2})})}))}var lt=Ne&&Ne.type&&Ne.type.getComposedData;lt&&ge.push({props:_r(_r({},lt(_r(_r({},Vt),{},{displayedData:Te,props:D,dataKey:We,item:Ne,bandSize:or,barPosition:Sr,offset:G,stackedData:er,layout:se,dataStartIndex:X,dataEndIndex:Q}))),{},ni(ni(ni({key:Ne.key||"item-".concat(Ie)},Oe,Vt[Oe]),Ae,Vt[Ae]),"animationId",W)),childIndex:aot(Ne,D.children),item:Ne})}),ge},E=function(D,M){var B=D.props,V=D.dataStartIndex,G=D.dataEndIndex,W=D.updateId;if(!Fne({props:B}))return null;var X=B.children,Q=B.layout,re=B.stackOffset,se=B.data,ue=B.reverseStackOrder,_e=boe(Q),Se=_e.numericAxisName,ve=_e.cateAxisName,Oe=Wd(X,n),Ae=gbt(se,Oe,"".concat(Se,"Id"),"".concat(ve,"Id"),re,ue),we=f.reduce(function(be,We){var rt="".concat(We.axisType,"Map");return _r(_r({},be),{},ni({},rt,yCt(B,_r(_r({},We),{},{graphicalItems:Oe,stackGroups:We.axisType===Se&&Ae,dataStartIndex:V,dataEndIndex:G}))))},{}),ge=vCt(_r(_r({},we),{},{props:B,graphicalItems:Oe}),M==null?void 0:M.legendBBox);Object.keys(we).forEach(function(be){we[be]=x(B,we[be],ge,be.replace("Map",""),r)});var Ne=we["".concat(ve,"Map")],Ie=xCt(Ne),Te=T(B,_r(_r({},we),{},{dataStartIndex:V,dataEndIndex:G,updateId:W,graphicalItems:Oe,stackGroups:Ae,offset:ge}));return _r(_r({formattedGraphicalItems:Te,graphicalItems:Oe,offset:ge,stackGroups:Ae},Ie),we)},C=function(R){function D(M){var B,V,G;return eCt(this,D),G=nCt(this,D,[M]),ni(G,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),ni(G,"accessibilityManager",new zkt),ni(G,"handleLegendBBoxUpdate",function(W){if(W){var X=G.state,Q=X.dataStartIndex,re=X.dataEndIndex,se=X.updateId;G.setState(_r({legendBBox:W},E({props:G.props,dataStartIndex:Q,dataEndIndex:re,updateId:se},_r(_r({},G.state),{},{legendBBox:W}))))}}),ni(G,"handleReceiveSyncEvent",function(W,X,Q){if(G.props.syncId===W){if(Q===G.eventEmitterSymbol&&typeof G.props.syncMethod!="function")return;G.applySyncEvent(X)}}),ni(G,"handleBrushChange",function(W){var X=W.startIndex,Q=W.endIndex;if(X!==G.state.dataStartIndex||Q!==G.state.dataEndIndex){var re=G.state.updateId;G.setState(function(){return _r({dataStartIndex:X,dataEndIndex:Q},E({props:G.props,dataStartIndex:X,dataEndIndex:Q,updateId:re},G.state))}),G.triggerSyncEvent({dataStartIndex:X,dataEndIndex:Q})}}),ni(G,"handleMouseEnter",function(W){var X=G.getMouseInfo(W);if(X){var Q=_r(_r({},X),{},{isTooltipActive:!0});G.setState(Q),G.triggerSyncEvent(Q);var re=G.props.onMouseEnter;gi(re)&&re(Q,W)}}),ni(G,"triggeredAfterMouseMove",function(W){var X=G.getMouseInfo(W),Q=X?_r(_r({},X),{},{isTooltipActive:!0}):{isTooltipActive:!1};G.setState(Q),G.triggerSyncEvent(Q);var re=G.props.onMouseMove;gi(re)&&re(Q,W)}),ni(G,"handleItemMouseEnter",function(W){G.setState(function(){return{isTooltipActive:!0,activeItem:W,activePayload:W.tooltipPayload,activeCoordinate:W.tooltipPosition||{x:W.cx,y:W.cy}}})}),ni(G,"handleItemMouseLeave",function(){G.setState(function(){return{isTooltipActive:!1}})}),ni(G,"handleMouseMove",function(W){W.persist(),G.throttleTriggeredAfterMouseMove(W)}),ni(G,"handleMouseLeave",function(W){G.throttleTriggeredAfterMouseMove.cancel();var X={isTooltipActive:!1};G.setState(X),G.triggerSyncEvent(X);var Q=G.props.onMouseLeave;gi(Q)&&Q(X,W)}),ni(G,"handleOuterEvent",function(W){var X=sot(W),Q=nd(G.props,"".concat(X));if(X&&gi(Q)){var re,se;/.*touch.*/i.test(X)?se=G.getMouseInfo(W.changedTouches[0]):se=G.getMouseInfo(W),Q((re=se)!==null&&re!==void 0?re:{},W)}}),ni(G,"handleClick",function(W){var X=G.getMouseInfo(W);if(X){var Q=_r(_r({},X),{},{isTooltipActive:!0});G.setState(Q),G.triggerSyncEvent(Q);var re=G.props.onClick;gi(re)&&re(Q,W)}}),ni(G,"handleMouseDown",function(W){var X=G.props.onMouseDown;if(gi(X)){var Q=G.getMouseInfo(W);X(Q,W)}}),ni(G,"handleMouseUp",function(W){var X=G.props.onMouseUp;if(gi(X)){var Q=G.getMouseInfo(W);X(Q,W)}}),ni(G,"handleTouchMove",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.throttleTriggeredAfterMouseMove(W.changedTouches[0])}),ni(G,"handleTouchStart",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.handleMouseDown(W.changedTouches[0])}),ni(G,"handleTouchEnd",function(W){W.changedTouches!=null&&W.changedTouches.length>0&&G.handleMouseUp(W.changedTouches[0])}),ni(G,"handleDoubleClick",function(W){var X=G.props.onDoubleClick;if(gi(X)){var Q=G.getMouseInfo(W);X(Q,W)}}),ni(G,"handleContextMenu",function(W){var X=G.props.onContextMenu;if(gi(X)){var Q=G.getMouseInfo(W);X(Q,W)}}),ni(G,"triggerSyncEvent",function(W){G.props.syncId!==void 0&&Bz.emit(zz,G.props.syncId,W,G.eventEmitterSymbol)}),ni(G,"applySyncEvent",function(W){var X=G.props,Q=X.layout,re=X.syncMethod,se=G.state.updateId,ue=W.dataStartIndex,_e=W.dataEndIndex;if(W.dataStartIndex!==void 0||W.dataEndIndex!==void 0)G.setState(_r({dataStartIndex:ue,dataEndIndex:_e},E({props:G.props,dataStartIndex:ue,dataEndIndex:_e,updateId:se},G.state)));else if(W.activeTooltipIndex!==void 0){var Se=W.chartX,ve=W.chartY,Oe=W.activeTooltipIndex,Ae=G.state,we=Ae.offset,ge=Ae.tooltipTicks;if(!we)return;if(typeof re=="function")Oe=re(ge,W);else if(re==="value"){Oe=-1;for(var Ne=0;Ne=0){var er,wt;if(Se.dataKey&&!Se.allowDuplicatedCategory){var or=typeof Se.dataKey=="function"?Pt:"payload.".concat(Se.dataKey.toString());er=_D(Ne,or,Oe),wt=Ie&&Te&&_D(Te,or,Oe)}else er=Ne==null?void 0:Ne[ve],wt=Ie&&Te&&Te[ve];if(Et||at){var Sr=W.props.activeIndex!==void 0?W.props.activeIndex:ve;return[P.cloneElement(W,_r(_r(_r({},re.props),Vt),{},{activeIndex:Sr})),null,null]}if(!Di(er))return[mt].concat(eS(G.renderActivePoints({item:re,activePoint:er,basePoint:wt,childIndex:ve,isRange:Ie})))}else{var nn,lr=(nn=G.getItemByXY(G.state.activeCoordinate))!==null&&nn!==void 0?nn:{graphicalItem:mt},yr=lr.graphicalItem,tr=yr.item,yn=tr===void 0?W:tr,lt=yr.childIndex,At=_r(_r(_r({},re.props),Vt),{},{activeIndex:lt});return[P.cloneElement(yn,At),null,null]}return Ie?[mt,null,null]:[mt,null]}),ni(G,"renderCustomized",function(W,X,Q){return P.cloneElement(W,_r(_r({key:"recharts-customized-".concat(Q)},G.props),G.state))}),ni(G,"renderMap",{CartesianGrid:{handler:UN,once:!0},ReferenceArea:{handler:G.renderReferenceElement},ReferenceLine:{handler:UN},ReferenceDot:{handler:G.renderReferenceElement},XAxis:{handler:UN},YAxis:{handler:UN},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((B=M.id)!==null&&B!==void 0?B:sj("recharts"),"-clip"),G.throttleTriggeredAfterMouseMove=w1e(G.triggeredAfterMouseMove,(V=M.throttleDelay)!==null&&V!==void 0?V:1e3/60),G.state={},G}return aCt(D,R),rCt(D,[{key:"componentDidMount",value:function(){var B,V;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(B=this.props.margin.left)!==null&&B!==void 0?B:0,top:(V=this.props.margin.top)!==null&&V!==void 0?V:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var B=this.props,V=B.children,G=B.data,W=B.height,X=B.layout,Q=Wu(V,Mh);if(Q){var re=Q.props.defaultIndex;if(!(typeof re!="number"||re<0||re>this.state.tooltipTicks.length-1)){var se=this.state.tooltipTicks[re]&&this.state.tooltipTicks[re].value,ue=$8(this.state,G,re,se),_e=this.state.tooltipTicks[re].coordinate,Se=(this.state.offset.top+W)/2,ve=X==="horizontal",Oe=ve?{x:_e,y:Se}:{y:_e,x:Se},Ae=this.state.formattedGraphicalItems.find(function(ge){var Ne=ge.item;return Ne.type.name==="Scatter"});Ae&&(Oe=_r(_r({},Oe),Ae.props.points[re].tooltipPosition),ue=Ae.props.points[re].tooltipPayload);var we={activeTooltipIndex:re,isTooltipActive:!0,activeLabel:se,activePayload:ue,activeCoordinate:Oe};this.setState(we),this.renderCursor(Q),this.accessibilityManager.setIndex(re)}}}},{key:"getSnapshotBeforeUpdate",value:function(B,V){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==V.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==B.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==B.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(B){gV([Wu(B.children,Mh)],[Wu(this.props.children,Mh)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var B=Wu(this.props.children,Mh);if(B&&typeof B.props.shared=="boolean"){var V=B.props.shared?"axis":"item";return s.indexOf(V)>=0?V:a}return a}},{key:"getMouseInfo",value:function(B){if(!this.container)return null;var V=this.container,G=V.getBoundingClientRect(),W=Nyt(G),X={chartX:Math.round(B.pageX-W.left),chartY:Math.round(B.pageY-W.top)},Q=G.width/V.offsetWidth||1,re=this.inRange(X.chartX,X.chartY,Q);if(!re)return null;var se=this.state,ue=se.xAxisMap,_e=se.yAxisMap,Se=this.getTooltipEventType(),ve=_oe(this.state,this.props.data,this.props.layout,re);if(Se!=="axis"&&ue&&_e){var Oe=iy(ue).scale,Ae=iy(_e).scale,we=Oe&&Oe.invert?Oe.invert(X.chartX):null,ge=Ae&&Ae.invert?Ae.invert(X.chartY):null;return _r(_r({},X),{},{xValue:we,yValue:ge},ve)}return ve?_r(_r({},X),ve):null}},{key:"inRange",value:function(B,V){var G=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,W=this.props.layout,X=B/G,Q=V/G;if(W==="horizontal"||W==="vertical"){var re=this.state.offset,se=X>=re.left&&X<=re.left+re.width&&Q>=re.top&&Q<=re.top+re.height;return se?{x:X,y:Q}:null}var ue=this.state,_e=ue.angleAxisMap,Se=ue.radiusAxisMap;if(_e&&Se){var ve=iy(_e);return Wse({x:X,y:Q},ve)}return null}},{key:"parseEventsOfWrapper",value:function(){var B=this.props.children,V=this.getTooltipEventType(),G=Wu(B,Mh),W={};G&&V==="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 X=vD(this.props,this.handleOuterEvent);return _r(_r({},X),W)}},{key:"addListener",value:function(){Bz.on(zz,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){Bz.removeListener(zz,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(B,V,G){for(var W=this.state.formattedGraphicalItems,X=0,Q=W.length;X");return t}const ZTe=P.forwardRef(({id:t,className:e,children:r,config:n,...i},a)=>{const c=P.useId(),s=`chart-${t||c.replace(/:/g,"")}`;return o.jsx(KTe.Provider,{value:{config:n},children:o.jsxs("div",{"data-chart":s,ref:a,className:sr("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:[o.jsx(ECt,{id:s,config:n}),o.jsx(BV,{children:r})]})})});ZTe.displayName="Chart";const ECt=({id:t,config:e})=>{const r=Object.entries(e).filter(([n,i])=>i.theme||i.color);return r.length?o.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(TCt).map(([n,i])=>` ${i} [data-chart=${t}] { ${r.map(([a,c])=>{var f;const s=((f=c.theme)==null?void 0:f[n])||c.color;return s?` --color-${a}: ${s};`:null}).join(` `)} } `).join(` `)}}):null},XTe=P.forwardRef(({active:t,payload:e,className:r,indicator:n="dot",hideLabel:i=!1,hideIndicator:a=!1,label:c,labelFormatter:s,labelClassName:f,formatter:m,color:x,nameKey:_,labelKey:T},E)=>{const{config:C}=YTe(),N=P.useMemo(()=>{var G;if(i||!(e!=null&&e.length))return null;const[D]=e,M=`${T||D.dataKey||D.name||"value"}`,B=U8(C,D,M),V=!T&&typeof c=="string"?((G=C[c])==null?void 0:G.label)||c:B==null?void 0:B.label;return s?o.jsx("div",{className:sr("font-medium",f),children:s(V,e)}):V?o.jsx("div",{className:sr("font-medium",f),children:V}):null},[c,s,e,i,f,C,T]);if(!t||!(e!=null&&e.length))return null;const R=e.length===1&&n!=="dot";return o.jsxs("div",{ref:E,className:sr("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:[R?null:N,o.jsx("div",{className:"grid gap-1.5",children:e.map((D,M)=>{const B=`${_||D.name||D.dataKey||"value"}`,V=U8(C,D,B),G=x||D.payload.fill||D.color;return o.jsx("div",{className:sr("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:m&&(D==null?void 0:D.value)!==void 0&&D.name?m(D.value,D.name,D,M,D.payload):o.jsxs(o.Fragment,{children:[V!=null&&V.icon?o.jsx(V.icon,{}):!a&&o.jsx("div",{className:sr("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":R&&n==="dashed"}),style:{"--color-bg":G,"--color-border":G}}),o.jsxs("div",{className:sr("flex flex-1 justify-between leading-none",R?"items-end":"items-center"),children:[o.jsxs("div",{className:"grid gap-1.5",children:[R?N:null,o.jsx("span",{className:"text-muted-foreground",children:(V==null?void 0:V.label)||D.name})]}),D.value&&o.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:D.value.toLocaleString()})]})]})},D.dataKey)})})]})});XTe.displayName="ChartTooltip";const ACt=P.forwardRef(({className:t,hideIcon:e=!1,payload:r,verticalAlign:n="bottom",nameKey:i},a)=>{const{config:c}=YTe();return r!=null&&r.length?o.jsx("div",{ref:a,className:sr("flex items-center justify-center gap-4",n==="top"?"pb-3":"pt-3",t),children:r.map(s=>{const f=`${i||s.dataKey||"value"}`,m=U8(c,s,f);return o.jsxs("div",{className:sr("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"),children:[m!=null&&m.icon&&!e?o.jsx(m.icon,{}):o.jsx("div",{className:"h-2 w-2 shrink-0 rounded-[2px]",style:{backgroundColor:s.color}}),m==null?void 0:m.label]},s.value)})}):null});ACt.displayName="ChartLegend";function U8(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 VN=["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 QTe({stats:t,year:e}){const r=t.transactionsByMonth.some(i=>i.count>0),n=t.leadSourceBreakdown.length>0;return!r&&!n?o.jsx(Hn,{children:o.jsx(ii,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):o.jsxs("div",{className:"grid gap-6",children:[r&&o.jsxs(Hn,{className:"overflow-hidden",children:[o.jsx(Ju,{children:o.jsx(ed,{className:"text-base",children:"Transactions by Month"})}),o.jsx(ii,{className:"overflow-hidden",children:o.jsx(ZTe,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:o.jsx(BV,{width:"100%",height:"100%",children:o.jsxs(wCt,{data:t.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[o.jsx(NTe,{strokeDasharray:"3 3",className:"stroke-muted"}),o.jsx(s3,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),o.jsx(a3,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),o.jsx(Mh,{content:o.jsx(XTe,{})}),o.jsx(Y0,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),n&&o.jsxs(Hn,{children:[o.jsx(Ju,{children:o.jsx(ed,{className:"text-base",children:"Lead Sources"})}),o.jsxs(ii,{children:[o.jsx("div",{className:"h-[250px]",children:o.jsx(BV,{width:"100%",height:"100%",children:o.jsxs(SCt,{children:[o.jsx(Wm,{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)=>o.jsx(LF,{fill:VN[a%VN.length]},`cell-${a}`))}),o.jsx(Mh,{formatter:(i,a)=>[`${i} deals`,a]})]})})}),o.jsx("div",{className:"flex flex-wrap gap-2 mt-2 justify-center",children:t.leadSourceBreakdown.slice(0,6).map((i,a)=>o.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[o.jsx("div",{className:"w-3 h-3 rounded-sm",style:{backgroundColor:VN[a%VN.length]}}),o.jsx("span",{className:"text-muted-foreground",children:i.name})]},i.name))})]})]})]})}const kCt=oS("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"}}),JTe=P.forwardRef(({className:t,variant:e,...r},n)=>o.jsx("div",{ref:n,role:"alert",className:sr(kCt({variant:e}),t),...r}));JTe.displayName="Alert";const CCt=P.forwardRef(({className:t,...e},r)=>o.jsx("h5",{ref:r,className:sr("mb-1 font-medium leading-none tracking-tight",t),...e}));CCt.displayName="AlertTitle";const eEe=P.forwardRef(({className:t,...e},r)=>o.jsx("div",{ref:r,className:sr("text-sm [&_p]:leading-relaxed",t),...e}));eEe.displayName="AlertDescription";function jCt(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=jHe(e,n,new Date);if(j6(i))return Ri(i,"yyyy-MM-dd")}catch{}try{const n=new Date(e);if(j6(n))return Ri(n,"yyyy-MM-dd")}catch{}return null}const ICt=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function PCt({open:t,onOpenChange:e}){const[r,n]=P.useState([]),[i,a]=P.useState(!1),[c,s]=P.useState(0),{data:f}=L7(),{data:m}=B7(),x=D7(),_=()=>{const D=ICt.join(","),M=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),B=`${D} ${M}`,V=new Blob([B],{type:"text/csv"}),G=URL.createObjectURL(V),W=document.createElement("a");W.href=G,W.download="transaction-import-template.csv",W.click(),URL.revokeObjectURL(G)},T=D=>{const M=D.split(` `).filter(V=>V.trim());if(M.length<2)return[];const B=M[0].split(",").map(V=>V.trim().toLowerCase().replace(/['"]/g,""));return M.slice(1).map((V,G)=>{var we,ge,Ne,Ie;const W=[];let X="",Q=!1;for(const Te of V)Te==='"'?Q=!Q:Te===","&&!Q?(W.push(X.trim()),X=""):X+=Te;W.push(X.trim());const re=Te=>{var We;const be=B.indexOf(Te);return be>=0?(We=W[be])==null?void 0:We.replace(/^["']|["']$/g,"").trim():""},se=(we=re("transaction_type"))==null?void 0:we.toLowerCase(),ue=(ge=re("sale_price"))==null?void 0:ge.replace(/[$,]/g,""),_e=(Ne=re("commission_amount"))==null?void 0:Ne.replace(/[$,]/g,""),Se=(Ie=re("is_win"))==null?void 0:Ie.toLowerCase(),ve=re("close_date"),Oe=jCt(ve);let Ae;return re("property_address")?["buyer","seller"].includes(se)?Oe?(!ue||isNaN(Number(ue)))&&(Ae="Invalid sale price"):Ae=`Invalid date format: "${ve}" - use MM/DD/YYYY or YYYY-MM-DD`:Ae='Transaction type must be "buyer" or "seller"':Ae="Missing property address",{property_address:re("property_address"),city:re("city"),state:re("state"),zip:re("zip"),transaction_type:se==="seller"?"seller":"buyer",close_date:Oe||"",sale_price:Number(ue)||0,commission_amount:_e?Number(_e):null,lead_source_name:re("lead_source"),client_type_name:re("client_type"),is_win:["yes","true","1"].includes(Se),notes:re("notes"),error:Ae}})},E=D=>{var V;const M=(V=D.target.files)==null?void 0:V[0];if(!M)return;const B=new FileReader;B.onload=G=>{var Q;const W=(Q=G.target)==null?void 0:Q.result,X=T(W);n(X)},B.readAsText(M)},C=async()=>{const D=r.filter(V=>!V.error);if(D.length===0){Jt.error("No valid transactions to import");return}a(!0),s(0);let M=0,B=0;for(let V=0;VQ.name.toLowerCase()===G.lead_source_name.toLowerCase()),X=m==null?void 0:m.find(Q=>Q.name.toLowerCase()===G.client_type_name.toLowerCase());await x.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:(X==null?void 0:X.id)||null,contact_id:null,notes:G.notes||null,is_win:G.is_win}),M++}catch(W){B++,console.error("Failed to import transaction:",W)}s(Math.round((V+1)/D.length*100))}a(!1),M>0&&Jt.success(`Imported ${M} transaction${M>1?"s":""}`),B>0&&Jt.error(`Failed to import ${B} transaction${B>1?"s":""}`),n([]),e(!1)},N=r.filter(D=>!D.error).length,R=r.filter(D=>D.error).length;return o.jsx(ro,{open:t,onOpenChange:e,children:o.jsxs($a,{className:"max-w-2xl max-h-[90vh]",children:[o.jsxs(ul,{children:[o.jsx(Go,{children:"Import Transactions"}),o.jsx(ld,{children:"Upload a CSV file with your past transactions"})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-muted/50",children:[o.jsxs("div",{children:[o.jsx("p",{className:"font-medium",children:"Download Template"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Get a CSV template with the correct format"})]}),o.jsxs(Ut,{variant:"outline",onClick:_,children:[o.jsx(Xl,{className:"h-4 w-4 mr-2"}),"Template"]})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mr,{htmlFor:"csv-file",children:"Upload CSV File"}),o.jsx(Ur,{id:"csv-file",type:"file",accept:".csv",onChange:E})]}),r.length>0&&o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(us,{variant:"outline",children:[r.length," rows found"]}),N>0&&o.jsxs(us,{className:"bg-green-500 text-white",children:[o.jsx(Ao,{className:"h-3 w-3 mr-1"}),N," valid"]}),R>0&&o.jsxs(us,{variant:"destructive",children:[o.jsx($he,{className:"h-3 w-3 mr-1"}),R," errors"]})]}),o.jsx(pp,{className:"h-[200px] border rounded-lg",children:o.jsxs("div",{className:"p-2 space-y-2",children:[r.slice(0,10).map((D,M)=>o.jsxs("div",{className:`p-2 rounded text-sm ${D.error?"bg-destructive/10":"bg-muted/50"}`,children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"font-medium",children:D.property_address||"(no address)"}),o.jsx(us,{variant:D.transaction_type==="buyer"?"default":"secondary",children:D.transaction_type})]}),o.jsxs("div",{className:"text-muted-foreground",children:[D.close_date," • $",D.sale_price.toLocaleString()]}),D.error&&o.jsx(JTe,{variant:"destructive",className:"mt-1 py-1",children:o.jsx(eEe,{className:"text-xs",children:D.error})})]},M)),r.length>10&&o.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",r.length-10," more"]})]})}),i&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:o.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${c}%`}})}),o.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",c,"%"]})]})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o.jsx(Ut,{variant:"outline",onClick:()=>e(!1),children:"Cancel"}),o.jsxs(Ut,{onClick:C,disabled:N===0||i,children:[o.jsx(CU,{className:"h-4 w-4 mr-2"}),"Import ",N," Transaction",N!==1?"s":""]})]})]})]})})}const NCt=ox({transactions_goal:yA().min(0).optional(),volume_goal:yA().min(0).optional(),gci_goal:yA().min(0).optional()});function RCt({open:t,onOpenChange:e,year:r,existingGoals:n}){const i=Ort(),{data:a}=uF(),c=(a==null?void 0:a.show_commission)??!0,s=S9({resolver:T9(NCt),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});P.useEffect(()=>{n?s.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}):s.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[n,s,t]);const f=async m=>{await i.mutateAsync({year:r,transactions_goal:m.transactions_goal??null,volume_goal:m.volume_goal??null,gci_goal:c?m.gci_goal??null:null}),e(!1)};return o.jsx(ro,{open:t,onOpenChange:e,children:o.jsxs($a,{className:"max-w-md",children:[o.jsxs(ul,{children:[o.jsxs(Go,{children:[r," Goals"]}),o.jsx(ld,{children:"Set your annual targets to track your progress throughout the year."})]}),o.jsx(R9,{...s,children:o.jsxs("form",{onSubmit:s.handleSubmit(f),className:"space-y-4",children:[o.jsx(rl,{control:s.control,name:"transactions_goal",render:({field:m})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Transactions Goal"}),o.jsx(zo,{children:o.jsx(Ur,{type:"number",placeholder:"e.g., 24",...m,value:m.value??"",onChange:x=>m.onChange(x.target.value?Number(x.target.value):void 0)})}),o.jsx(PR,{children:"Total number of deals you want to close"}),o.jsx(Gh,{})]})}),o.jsx(rl,{control:s.control,name:"volume_goal",render:({field:m})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"Volume Goal ($)"}),o.jsx(zo,{children:o.jsx(Ur,{type:"number",placeholder:"e.g., 5000000",...m,value:m.value??"",onChange:x=>m.onChange(x.target.value?Number(x.target.value):void 0)})}),o.jsx(PR,{children:"Total sales volume you want to achieve"}),o.jsx(Gh,{})]})}),c&&o.jsx(rl,{control:s.control,name:"gci_goal",render:({field:m})=>o.jsxs(Fo,{children:[o.jsx(Bo,{children:"GCI Goal ($)"}),o.jsx(zo,{children:o.jsx(Ur,{type:"number",placeholder:"e.g., 150000",...m,value:m.value??"",onChange:x=>m.onChange(x.target.value?Number(x.target.value):void 0)})}),o.jsx(PR,{children:"Gross commission income target"}),o.jsx(Gh,{})]})}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(Ut,{type:"button",variant:"outline",onClick:()=>e(!1),children:"Cancel"}),o.jsx(Ut,{type:"submit",disabled:i.isPending,children:"Save Goals"})]})]})})]})})}function tEe({transactions:t,isLoading:e}){const r=P.useRef(null),n=P.useRef(null),i=P.useRef([]),a=P.useRef(null),{isAdmin:c}=qn(),[s,f]=P.useState(""),[m,x]=P.useState(!0),[_,T]=P.useState(0),[E,C]=P.useState(!1),N=t.filter(D=>D.latitude!=null&&D.longitude!=null),R=t.filter(D=>D.latitude==null||D.longitude==null);return P.useEffect(()=>{(async()=>{x(!0);try{const{data:M}=await Le.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();M!=null&&M.value&&f(M.value)}catch(M){console.error("Error fetching mapbox token:",M)}x(!1)})()},[]),P.useEffect(()=>{if(!s||R.length===0||E)return;(async()=>{var B;C(!0);let M=0;for(const V of R){const G=[V.property_address,V.city,V.state,V.zip].filter(Boolean).join(", ");if(G)try{const X=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(G)}.json?access_token=${s}&limit=1`)).json();if((B=X.features)!=null&&B[0]){const[Q,re]=X.features[0].center;await Le.from("scorecard_transactions").update({latitude:re,longitude:Q}).eq("id",V.id),V.latitude=re,V.longitude=Q,M++}}catch(W){console.error("Geocode error:",W)}}T(M),C(!1)})()},[s,t]),P.useEffect(()=>{if(!r.current||!s||n.current)return;Fd.accessToken=s;const D=t.filter(V=>V.latitude!=null&&V.longitude!=null);let M=[-98.5795,39.8283],B=4;if(D.length>0){const V=D.reduce((W,X)=>W+X.longitude,0)/D.length,G=D.reduce((W,X)=>W+X.latitude,0)/D.length;M=[V,G],B=D.length===1?12:10}return n.current=new Fd.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:B,center:M}),n.current.addControl(new Fd.NavigationControl,"top-right"),()=>{var V;(V=n.current)==null||V.remove(),n.current=null}},[s]),P.useEffect(()=>{var M;if(!n.current||!s)return;i.current.forEach(B=>B.remove()),i.current=[],(M=a.current)==null||M.remove();const D=t.filter(B=>B.latitude!=null&&B.longitude!=null);if(D.forEach(B=>{var re;const V=B.transaction_type==="buyer",G=V?"#3B82F6":"#10B981",W=document.createElement("div");W.className="cursor-pointer",W.innerHTML=`
${V?'':''}
`;const X=new Fd.Popup({offset:25,closeButton:!0}).setHTML(`
${B.property_address}
${B.city?`
${B.city}${B.state?", "+B.state:""} ${B.zip||""}
`:""}
${V?"Buyer":"Seller"} $${Number(B.sale_price).toLocaleString()}
Closed: ${j1(B.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(re=B.lead_source)!=null&&re.name?" · "+B.lead_source.name:""}
${B.contact?`
Client: ${B.contact.first_name} ${B.contact.last_name||""}
`:""}
`),Q=new Fd.Marker(W).setLngLat([B.longitude,B.latitude]).setPopup(X).addTo(n.current);i.current.push(Q)}),D.length>1){const B=new Fd.LngLatBounds;D.forEach(V=>B.extend([V.longitude,V.latitude])),n.current.fitBounds(B,{padding:60,maxZoom:13})}else D.length===1&&n.current.flyTo({center:[D[0].longitude,D[0].latitude],zoom:12})},[t,s,E]),m||e?o.jsx(Hn,{children:o.jsx(ii,{className:"flex items-center justify-center h-[50vh]",children:o.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):s?t.length===0?o.jsx(Hn,{children:o.jsxs(ii,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[o.jsx(na,{className:"h-12 w-12 text-muted-foreground"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-semibold",children:"No Transactions Yet"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Add transactions to see them plotted on the map."})]})]})}):o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#3B82F6"}}),o.jsx("span",{children:"Buyer"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#10B981"}}),o.jsx("span",{children:"Seller"})]}),o.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[N.length," of ",t.length," mapped",E&&" · Geocoding..."]})]}),o.jsx("div",{ref:r,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):o.jsx(Hn,{children:o.jsxs(ii,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[o.jsx($he,{className:"h-12 w-12 text-muted-foreground"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),o.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 rEe=()=>{const{data:t}=SS();return wr({queryKey:["team-scorecard-members",t==null?void 0:t.teamId],queryFn:async()=>{const{data:e,error:r}=await Le.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 Le.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"})},LCt=t=>{const{data:e}=SS(),{data:r}=rEe();return wr({queryKey:["team-scorecard-transactions",e==null?void 0:e.teamId,t],queryFn:async()=>{const n=r.map(s=>s.id);let i=Le.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 DCt(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 OCt(t,e){return t?t.split(" ").map(r=>r[0]).join("").toUpperCase().slice(0,2):e[0].toUpperCase()}function MCt({year:t}){var T;const{data:e,isLoading:r}=rEe(),{data:n,isLoading:i}=LCt(t),a=ma(),c=r||i,{aggregate:s,memberStats:f,topPerformer:m,agentNameMap:x,teamChartStats:_}=P.useMemo(()=>{if(!e||!n)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const E=e.map(se=>DCt(se,n));E.sort((se,ue)=>ue.totalVolume-se.totalVolume);const C={};e.forEach(se=>{C[se.id]=se.name||se.email});const N=n.length,R=n.reduce((se,ue)=>se+Number(ue.sale_price),0),D=n.reduce((se,ue)=>se+(Number(ue.commission_amount)||0),0),M=n.filter(se=>se.transaction_type==="buyer").length,B=n.filter(se=>se.transaction_type==="seller").length,V={};n.forEach(se=>{var _e;const ue=((_e=se.lead_source)==null?void 0:_e.name)||"Unknown";V[ue]=(V[ue]||0)+1});const G=Object.entries(V).sort((se,ue)=>ue[1]-se[1])[0],W={};n.forEach(se=>{const ue=j1(se.close_date).toLocaleString("default",{month:"short"});W[ue]=(W[ue]||0)+1});const Q=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(se=>({month:se,count:W[se]||0})),re=Object.entries(V).map(([se,ue])=>({name:se,count:ue})).sort((se,ue)=>ue.count-se.count);return{aggregate:{totalTxns:N,buyerCount:M,sellerCount:B,totalVolume:R,avgPrice:N>0?R/N:0,totalGCI:D,topSource:G?{name:G[0],count:G[1]}:null,memberCount:e.length},memberStats:E,topPerformer:E[0]||null,agentNameMap:C,teamChartStats:{transactionsByMonth:Q,leadSourceBreakdown:re}}},[e,n]);return c?o.jsxs("div",{className:"space-y-6",children:[o.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(E=>o.jsx(ol,{className:"h-24"},E))}),o.jsx(ol,{className:"h-64"})]}):!s||f.length===0?o.jsx(Hn,{className:"py-12",children:o.jsxs(ii,{className:"text-center space-y-2",children:[o.jsx(Al,{className:"h-10 w-10 mx-auto text-muted-foreground"}),o.jsx("h3",{className:"text-lg font-semibold",children:"No Team Data"}),o.jsxs("p",{className:"text-muted-foreground",children:["No scorecard transactions found for your team members in ",t,"."]})]})}):o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(Al,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Members"})]}),o.jsx("p",{className:"text-2xl font-bold",children:s.memberCount})]})}),o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(Ma,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Team Transactions"})]}),o.jsx("p",{className:"text-2xl font-bold",children:s.totalTxns}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.buyerCount,"B / ",s.sellerCount,"S"]})]})}),o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(ym,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Team Volume"})]}),o.jsx("p",{className:"text-2xl font-bold",children:Da(s.totalVolume,!0)})]})}),o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(uS,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),o.jsx("p",{className:"text-2xl font-bold",children:Da(s.avgPrice,!0)})]})}),o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(ym,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Team GCI"})]}),o.jsx("p",{className:"text-2xl font-bold",children:Da(s.totalGCI,!0)})]})}),o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(uA,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),o.jsx("p",{className:"text-lg font-bold truncate",children:((T=s.topSource)==null?void 0:T.name)||"-"}),s.topSource&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.topSource.count," deals"]})]})})]}),m&&m.totalTransactions>0&&o.jsx(Hn,{className:"border-primary/30 bg-primary/5",children:o.jsxs(ii,{className:"pt-4 flex items-center gap-4",children:[o.jsx("div",{className:"flex items-center justify-center h-10 w-10 rounded-full bg-primary/10",children:o.jsx(PL,{className:"h-5 w-5 text-primary"})}),o.jsxs("div",{className:"flex-1",children:[o.jsxs("p",{className:"text-sm font-medium text-muted-foreground",children:["Top Performer — ",t]}),o.jsx("p",{className:"text-lg font-bold",children:m.member.name||m.member.email})]}),o.jsxs("div",{className:"text-right",children:[o.jsxs("p",{className:"text-sm text-muted-foreground",children:[m.totalTransactions," deals"]}),o.jsx("p",{className:"font-semibold",children:Da(m.totalVolume,!0)})]})]})}),o.jsxs(Hn,{children:[o.jsx(Ju,{children:o.jsx(ed,{className:"text-lg",children:"Member Performance"})}),o.jsx(ii,{children:o.jsx("div",{className:"overflow-x-auto",children:o.jsxs(O7,{children:[o.jsx(M7,{children:o.jsxs(Tk,{children:[o.jsx($l,{children:"Agent"}),o.jsx($l,{className:"text-center",children:"Transactions"}),o.jsx($l,{className:"text-center",children:"B / S"}),o.jsx($l,{className:"text-right",children:"Volume"}),o.jsx($l,{className:"text-right",children:"Avg Price"}),o.jsx($l,{className:"text-right",children:"GCI"}),o.jsx($l,{className:"text-right"})]})}),o.jsx(F7,{children:f.map((E,C)=>o.jsxs(Tk,{children:[o.jsx(Ul,{children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("div",{className:"relative",children:[C===0&&E.totalTransactions>0&&o.jsx(PL,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),o.jsxs(Zd,{className:"h-8 w-8",children:[o.jsx(Xd,{src:E.member.avatar_url||void 0}),o.jsx(Qd,{className:"text-xs",children:OCt(E.member.name,E.member.email)})]})]}),o.jsxs("div",{children:[o.jsx("p",{className:"font-medium text-sm",children:E.member.name||E.member.email}),E.member.name&&o.jsx("p",{className:"text-xs text-muted-foreground",children:E.member.email})]})]})}),o.jsx(Ul,{className:"text-center font-semibold",children:E.totalTransactions}),o.jsxs(Ul,{className:"text-center text-sm",children:[E.buyerCount," / ",E.sellerCount]}),o.jsx(Ul,{className:"text-right font-medium",children:Da(E.totalVolume,!0)}),o.jsx(Ul,{className:"text-right text-sm",children:Da(E.averagePrice,!0)}),o.jsx(Ul,{className:"text-right font-medium",children:Da(E.totalGCI,!0)}),o.jsx(Ul,{className:"text-right",children:o.jsx(Ut,{variant:"ghost",size:"sm",onClick:()=>a(`/mission-control/scorecard/${E.member.id}`),children:o.jsx(KO,{className:"h-4 w-4"})})})]},E.member.id))})]})})})]}),o.jsxs(Q9,{defaultValue:"transactions",className:"space-y-4",children:[o.jsxs(ZM,{children:[o.jsxs(_m,{value:"transactions",children:[o.jsx(AU,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),o.jsxs(_m,{value:"charts",children:[o.jsx(ZA,{className:"h-4 w-4 mr-1"}),"Charts"]}),o.jsxs(_m,{value:"map",children:[o.jsx(na,{className:"h-4 w-4 mr-1"}),"Map"]})]}),o.jsx(Ny,{value:"transactions",children:o.jsx(rwe,{transactions:n||[],showCommission:!0,isLoading:i,agentNameMap:x,readOnly:!0})}),o.jsx(Ny,{value:"charts",children:_&&o.jsx(QTe,{stats:_,year:t})}),o.jsx(Ny,{value:"map",children:o.jsx(tEe,{transactions:n||[],isLoading:i})})]})]})}const WR=new Date().getFullYear(),woe=Array.from({length:10},(t,e)=>WR-e),qN="all";function FCt(){var _e;const[t,e]=P.useState(WR),r=t===null?qN:String(t),n=Se=>e(Se===qN?null:Number(Se)),[i,a]=P.useState(!1),[c,s]=P.useState(!1),[f,m]=P.useState(!1),[x,_]=P.useState(!1),[T,E]=P.useState("my"),{data:C}=SS(),N=(C==null?void 0:C.role)==="team_leader",{data:R,isLoading:D}=Fbe(t??void 0),{yearStats:M,lifetimeStats:B,isLoading:V,showCommission:G}=Frt(t??void 0),{data:W,isLoading:X}=Drt(t??WR),{data:Q}=uF(),re=Mrt(),se=()=>{if(!R||R.length===0)return;const Se=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...G?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],ve=R.map(Ne=>{var Ie,Te;return[Ne.property_address,Ne.city||"",Ne.state||"",Ne.zip||"",Ne.transaction_type,Ne.close_date,Ne.sale_price,...G?[Ne.commission_amount||""]:[],((Ie=Ne.lead_source)==null?void 0:Ie.name)||"",((Te=Ne.client_type)==null?void 0:Te.name)||"",Ne.contact?`${Ne.contact.first_name} ${Ne.contact.last_name||""}`.trim():"",Ne.is_win?"Yes":"No",Ne.notes||""]}),Oe=[Se,...ve].map(Ne=>Ne.map(Ie=>`"${String(Ie).replace(/"/g,'""')}"`).join(",")).join(` `),Ae=new Blob([Oe],{type:"text/csv"}),we=URL.createObjectURL(Ae),ge=document.createElement("a");ge.href=we,ge.download=t===null?"transactions-all.csv":`transactions-${t}.csv`,ge.click(),URL.revokeObjectURL(we)},ue=!R||R.length===0;return o.jsxs(E1,{title:"Scorecard",children:[o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),o.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"})]}),N&&o.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[o.jsx(Ut,{variant:T==="my"?"default":"ghost",size:"sm",onClick:()=>E("my"),className:"h-8",children:"My Scorecard"}),o.jsxs(Ut,{variant:T==="team"?"default":"ghost",size:"sm",onClick:()=>E("team"),className:"h-8",children:[o.jsx(Al,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),T==="team"&&N?o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Team Performance"}),o.jsx("p",{className:"text-muted-foreground text-sm",children:"Aggregate stats and member comparison"})]}),o.jsxs(Ba,{value:r,onValueChange:n,children:[o.jsx(ja,{className:"w-[140px]",children:o.jsx(za,{})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:qN,children:"All Years"}),woe.map(Se=>o.jsx(wn,{value:String(Se),children:Se},Se))]})]})]}),o.jsx(MCt,{year:t??void 0})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),o.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs(Ba,{value:r,onValueChange:n,children:[o.jsx(ja,{className:"w-[140px]",children:o.jsx(za,{})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:qN,children:"All Years"}),woe.map(Se=>o.jsx(wn,{value:String(Se),children:Se},Se))]})]}),o.jsx(Ut,{variant:"outline",size:"icon",onClick:()=>_(!x),children:o.jsx(pG,{className:"h-4 w-4"})})]})]}),x&&o.jsxs(Hn,{children:[o.jsx(Ju,{className:"pb-3",children:o.jsx(ed,{className:"text-lg",children:"Settings"})}),o.jsx(ii,{children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"space-y-0.5",children:[o.jsx(Mr,{children:"Show Commission"}),o.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),o.jsx(kS,{checked:(Q==null?void 0:Q.show_commission)??!0,onCheckedChange:Se=>re.mutate({show_commission:Se})})]})})]}),ue&&!D?o.jsx(Hn,{className:"py-12",children:o.jsxs(ii,{className:"text-center space-y-4",children:[o.jsx("div",{className:"w-16 h-16 mx-auto rounded-full bg-primary/10 flex items-center justify-center",children:o.jsx(ZA,{className:"h-8 w-8 text-primary"})}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-semibold",children:"Start Tracking Your Success"}),o.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."})]}),o.jsxs("div",{className:"flex flex-wrap justify-center gap-2 pt-2",children:[o.jsxs(Ut,{onClick:()=>a(!0),children:[o.jsx(xm,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),o.jsxs(Ut,{variant:"outline",onClick:()=>s(!0),children:[o.jsx(CU,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]}),o.jsxs("div",{className:"pt-4 border-t mt-4",children:[o.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Need help formatting your data?"}),o.jsx(Ut,{variant:"link",className:"h-auto p-0",asChild:!0,children:o.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[o.jsx(Xl,{className:"h-4 w-4 mr-2"}),"Download CSV Template"]})})]})]})}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsxs(Ut,{onClick:()=>a(!0),children:[o.jsx(xm,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),o.jsxs(Ut,{variant:"outline",onClick:()=>m(!0),children:[o.jsx(yG,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),o.jsxs(Ut,{variant:"outline",onClick:()=>s(!0),children:[o.jsx(CU,{className:"h-4 w-4 mr-2"}),"Import"]}),o.jsxs(Ut,{variant:"outline",onClick:se,disabled:ue,children:[o.jsx(Xl,{className:"h-4 w-4 mr-2"}),"Export"]}),o.jsx(Ut,{variant:"ghost",size:"sm",asChild:!0,children:o.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[o.jsx(Xl,{className:"h-4 w-4 mr-2"}),"CSV Template"]})})]}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(Ma,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),o.jsx("p",{className:"text-2xl font-bold",children:M.totalTransactions}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:[B.totalTransactions," lifetime"]})]})}),o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(Al,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),o.jsxs("p",{className:"text-2xl font-bold",children:[M.buyerCount,"/",M.sellerCount]}),o.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(ym,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),o.jsx("p",{className:"text-2xl font-bold",children:Da(M.totalVolume,!0)}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:[Da(B.totalVolume,!0)," lifetime"]})]})}),o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(uS,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),o.jsx("p",{className:"text-2xl font-bold",children:Da(M.averagePrice,!0)})]})}),o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(uA,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),o.jsx("p",{className:"text-lg font-bold truncate",children:((_e=M.topLeadSource)==null?void 0:_e.name)||"-"}),M.topLeadSource&&o.jsxs("p",{className:"text-xs text-muted-foreground",children:[M.topLeadSource.count," deals"]})]})}),G&&o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[o.jsx(ym,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),o.jsx("p",{className:"text-2xl font-bold",children:Da(M.totalCommission,!0)}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:[Da(B.totalCommission,!0)," lifetime"]})]})}),G&&M.totalNetToAgent>0&&M.totalNetToAgent!==M.totalCommission&&o.jsx(Hn,{children:o.jsxs(ii,{className:"pt-4",children:[o.jsxs("div",{className:"flex items-center gap-2 text-teal-600 dark:text-teal-400 mb-1",children:[o.jsx(ym,{className:"h-4 w-4"}),o.jsx("span",{className:"text-xs font-medium",children:"Net to Agent"})]}),o.jsx("p",{className:"text-2xl font-bold text-teal-600 dark:text-teal-400",children:Da(M.totalNetToAgent,!0)}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:[Da(B.totalNetToAgent,!0)," lifetime"]})]})})]}),t!==null&&W&&o.jsx(fnt,{goals:W,stats:M,year:t,showCommission:G}),o.jsxs(Q9,{defaultValue:"transactions",className:"space-y-4",children:[o.jsxs(ZM,{children:[o.jsx(_m,{value:"transactions",children:"Transactions"}),o.jsx(_m,{value:"charts",children:"Charts"}),o.jsxs(_m,{value:"map",children:[o.jsx(na,{className:"h-4 w-4 mr-1"}),"Map"]})]}),o.jsx(Ny,{value:"transactions",children:o.jsx(rwe,{transactions:R||[],showCommission:G,isLoading:D})}),o.jsx(Ny,{value:"charts",children:o.jsx(QTe,{stats:M,year:t??void 0})}),o.jsx(Ny,{value:"map",children:o.jsx(tEe,{transactions:R||[],isLoading:D})})]})]})]})]}),o.jsx(twe,{open:i,onOpenChange:a}),o.jsx(PCt,{open:c,onOpenChange:s}),o.jsx(RCt,{open:f,onOpenChange:m,year:t??WR,existingGoals:W})]})}function BCt(){const t=Ji();return wr({queryKey:["deal-tasks",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Le.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 n8t(t){const e=Ji();return wr({queryKey:["deal-tasks","deal",t,e],queryFn:async()=>{if(!e||!t)return[];const{data:r,error:n}=await Le.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 zCt(){const t=Ji(),e=Nr();return Cr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Le.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 $Ct(){const t=Nr();return Cr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Le.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"&&G0("task_completed")}})}function UCt(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("deal_tasks").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function ZH(){const t=Nr();return Cr({mutationFn:async({id:e,status:r})=>{const{data:n,error:i}=await Le.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"&&G0("task_completed")}})}function i8t(){const t=Nr();return Cr({mutationFn:async e=>{if(e.length===0)return;const{error:r}=await Le.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&&G0("task_completed")}})}function VCt(t){const e=Ji();return wr({queryKey:["deal-task-templates",e,t],queryFn:async()=>{if(!e)return[];let r=Le.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 qCt(){const t=Ji(),e=Nr();return Cr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Le.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 GCt(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("deal_task_templates").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function s8t(){const t=Ji(),e=Nr();return Cr({mutationFn:async({dealId:r,stageId:n})=>{if(!t)throw new Error("Not authenticated");const{data:i,error:a}=await Le.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 Le.from("deal_tasks").select("title, stage_id").eq("deal_id",r).eq("stage_id",n),s=new Set((c||[]).map(_=>_.title)),f=i.filter(_=>!s.has(_.title)).map((_,T)=>({owner_user_id:t,deal_id:r,stage_id:n,title:_.title,description:_.description,priority:_.priority,due_date:_.default_due_offset_days?new Date(Date.now()+_.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:T,status:"todo"}));if(f.length===0)return[];const{data:m,error:x}=await Le.from("deal_tasks").insert(f).select();if(x)throw x;return m},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-tasks"]})}})}function D2(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 HCt(){const t=Ji();return wr({queryKey:["deal-pipeline-stages",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Le.from("deal_pipeline_stages").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e},enabled:!!t})}function a8t(){const t=Ji(),e=Nr();return Cr({mutationFn:async()=>{if(!t)throw new Error("Not authenticated");const{error:r}=await Le.rpc("initialize_deal_pipeline_stages",{p_user_id:t});if(r)throw r},onSuccess:()=>{e.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function WCt(){const t=Ji();return wr({queryKey:["deal-pipeline-deals",t],queryFn:async()=>{if(!t)return[];const{data:e,error:r}=await Le.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 o8t(){const t=Ji(),e=Nr();return Cr({mutationFn:async r=>{if(!t)throw new Error("Not authenticated");const{data:n,error:i}=await Le.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 Le.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 l8t(){const t=Nr();return Cr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Le.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 c8t(){const t=Nr();return Cr({mutationFn:async({dealId:e,stageId:r,stageName:n})=>{const{data:i}=await Le.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:s}=await Le.from("deal_pipeline").update(a).eq("id",e).select().single();if(s)throw s;return await Le.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 u8t(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.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 d8t(t){return wr({queryKey:["deal-activities",t],queryFn:async()=>{const{data:e,error:r}=await Le.from("deal_activities").select("*").eq("deal_id",t).order("created_at",{ascending:!1});if(r)throw r;return e},enabled:!!t})}function h8t(){const t=Nr();return Cr({mutationFn:async e=>{const{data:r,error:n}=await Le.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 f8t(t){return wr({queryKey:["deal-checklist",t],queryFn:async()=>{const{data:e,error:r}=await Le.from("deal_checklist_items").select("*").eq("deal_id",t).order("sort_order",{ascending:!0});if(r)throw r;return e},enabled:!!t})}function p8t(){const t=Nr();return Cr({mutationFn:async({id:e,is_completed:r,deal_id:n})=>{const{data:i,error:a}=await Le.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 m8t(){const t=Nr();return Cr({mutationFn:async e=>{const{data:r,error:n}=await Le.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 g8t(){const t=Ji();return wr({queryKey:["deal-pipeline-stats",t],queryFn:async()=>{if(!t)return null;const{data:e,error:r}=await Le.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(s=>{var f,m,x;return!((f=s.deal_pipeline_stages)!=null&&f.is_won_stage)&&!((m=s.deal_pipeline_stages)!=null&&m.is_lost_stage)&&((x=s.deal_pipeline_stages)==null?void 0:x.name)!=="Cancelled"}))||[],i=(e==null?void 0:e.filter(s=>{var f;return(f=s.deal_pipeline_stages)==null?void 0:f.is_won_stage}))||[],a=new Date().getFullYear(),c=i.filter(s=>{const f=s.actual_close_date;return f?new Date(f).getFullYear()===a:!0});return{totalDeals:(e==null?void 0:e.length)||0,activeDeals:n.length,wonDeals:i.length,pipelineValue:n.reduce((s,f)=>s+(f.expected_price||0),0),expectedCommission:n.reduce((s,f)=>s+(f.expected_commission||0)+(f.bonus_amount||0),0),expectedNetToAgent:n.reduce((s,f)=>s+(D2(f)||0),0),wonValue:i.reduce((s,f)=>s+(f.expected_price||0),0),weightedGCI:n.reduce((s,f)=>{const m=(f.probability??50)/100;return s+((f.expected_commission||0)+(f.bonus_amount||0))*m},0),weightedNet:n.reduce((s,f)=>{const m=(f.probability??50)/100;return s+(D2(f)||0)*m},0),ytdWonDeals:c.length,ytdWonGCI:c.reduce((s,f)=>s+(f.expected_commission||0)+(f.bonus_amount||0),0),ytdWonNet:c.reduce((s,f)=>s+(D2(f)||0),0),projectedAnnualNet:c.reduce((s,f)=>s+(D2(f)||0),0)+n.reduce((s,f)=>{const m=(f.probability??50)/100;return s+(D2(f)||0)*m},0)}},enabled:!!t})}function y8t(t){const e=Ji();return wr({queryKey:["deal-by-listing",t,e],queryFn:async()=>{if(!e||!t)return null;const{data:r,error:n}=await Le.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 x8t(){const t=Nr();return Cr({mutationFn:async({dealId:e,listingId:r})=>{const{data:n,error:i}=await Le.from("deal_pipeline").update({listing_id:r}).eq("id",e).select().single();if(i)throw i;return await Le.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 _8t(){const t=Nr();return Cr({mutationFn:async({dealId:e,listingId:r})=>{const{data:n,error:i}=await Le.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 ci=function(){return ci=Object.assign||function(e){for(var r,n=1,i=arguments.length;n1&&(f||!m),_=e>1&&(m||!f),T=function(){n&&a(n)},E=function(){i&&a(i)};return o.jsx(Ajt,{displayMonth:t.displayMonth,hideNext:x,hidePrevious:_,nextMonth:i,previousMonth:n,onPreviousClick:T,onNextClick:E})}function kjt(t){var e,r=ga(),n=r.classNames,i=r.disableNavigation,a=r.styles,c=r.captionLayout,s=r.components,f=(e=s==null?void 0:s.CaptionLabel)!==null&&e!==void 0?e:sEe,m;return i?m=o.jsx(f,{id:t.id,displayMonth:t.displayMonth}):c==="dropdown"?m=o.jsx(Soe,{displayMonth:t.displayMonth,id:t.id}):c==="dropdown-buttons"?m=o.jsxs(o.Fragment,{children:[o.jsx(Soe,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id}),o.jsx(Toe,{displayMonth:t.displayMonth,displayIndex:t.displayIndex,id:t.id})]}):m=o.jsxs(o.Fragment,{children:[o.jsx(f,{id:t.id,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),o.jsx(Toe,{displayMonth:t.displayMonth,id:t.id})]}),o.jsx("div",{className:n.caption,style:a.caption,children:m})}function Cjt(t){var e=ga(),r=e.footer,n=e.styles,i=e.classNames.tfoot;return r?o.jsx("tfoot",{className:i,style:n.tfoot,children:o.jsx("tr",{children:o.jsx("td",{colSpan:8,children:r})})}):o.jsx(o.Fragment,{})}function jjt(t,e,r){for(var n=r?Lm(new Date):_c(new Date,{locale:t,weekStartsOn:e}),i=[],a=0;a<7;a++){var c=Tl(n,a);i.push(c)}return i}function Ijt(){var t=ga(),e=t.classNames,r=t.styles,n=t.showWeekNumber,i=t.locale,a=t.weekStartsOn,c=t.ISOWeek,s=t.formatters.formatWeekdayName,f=t.labels.labelWeekday,m=jjt(i,a,c);return o.jsxs("tr",{style:r.head_row,className:e.head_row,children:[n&&o.jsx("td",{style:r.head_cell,className:e.head_cell}),m.map(function(x,_){return o.jsx("th",{scope:"col",className:e.head_cell,style:r.head_cell,"aria-label":f(x,{locale:i}),children:s(x,{locale:i})},_)})]})}function Pjt(){var t,e=ga(),r=e.classNames,n=e.styles,i=e.components,a=(t=i==null?void 0:i.HeadRow)!==null&&t!==void 0?t:Ijt;return o.jsx("thead",{style:n.head,className:r.head,children:o.jsx(a,{})})}function Njt(t){var e=ga(),r=e.locale,n=e.formatters.formatDay;return o.jsx(o.Fragment,{children:n(t.date,{locale:r})})}var XH=P.createContext(void 0);function Rjt(t){if(!dj(t.initialProps)){var e={selected:void 0,modifiers:{disabled:[]}};return o.jsx(XH.Provider,{value:e,children:t.children})}return o.jsx(Ljt,{initialProps:t.initialProps,children:t.children})}function Ljt(t){var e=t.initialProps,r=t.children,n=e.selected,i=e.min,a=e.max,c=function(m,x,_){var T,E;(T=e.onDayClick)===null||T===void 0||T.call(e,m,x,_);var C=!!(x.selected&&i&&(n==null?void 0:n.length)===i);if(!C){var N=!!(!x.selected&&a&&(n==null?void 0:n.length)===a);if(!N){var R=n?nEe([],n):[];if(x.selected){var D=R.findIndex(function(M){return Kl(m,M)});R.splice(D,1)}else R.push(m);(E=e.onSelect)===null||E===void 0||E.call(e,R,m,x,_)}}},s={disabled:[]};n&&s.disabled.push(function(m){var x=a&&n.length>a-1,_=n.some(function(T){return Kl(T,m)});return!!(x&&!_)});var f={selected:n,onDayClick:c,modifiers:s};return o.jsx(XH.Provider,{value:f,children:r})}function QH(){var t=P.useContext(XH);if(!t)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return t}function Djt(t,e){var r=e||{},n=r.from,i=r.to;return n&&i?Kl(i,t)&&Kl(n,t)?void 0:Kl(i,t)?{from:i,to:void 0}:Kl(n,t)?void 0:pk(n,t)?{from:t,to:i}:{from:n,to:t}:i?pk(t,i)?{from:i,to:t}:{from:t,to:i}:n?V9(t,n)?{from:t,to:n}:{from:n,to:t}:{from:t,to:void 0}}var JH=P.createContext(void 0);function Ojt(t){if(!hj(t.initialProps)){var e={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return o.jsx(JH.Provider,{value:e,children:t.children})}return o.jsx(Mjt,{initialProps:t.initialProps,children:t.children})}function Mjt(t){var e=t.initialProps,r=t.children,n=e.selected,i=n||{},a=i.from,c=i.to,s=e.min,f=e.max,m=function(E,C,N){var R,D;(R=e.onDayClick)===null||R===void 0||R.call(e,E,C,N);var M=Djt(E,n);(D=e.onSelect)===null||D===void 0||D.call(e,M,E,C,N)},x={range_start:[],range_end:[],range_middle:[],disabled:[]};if(a?(x.range_start=[a],c?(x.range_end=[c],Kl(a,c)||(x.range_middle=[{after:a,before:c}])):x.range_end=[a]):c&&(x.range_start=[c],x.range_end=[c]),s&&(a&&!c&&x.disabled.push({after:LB(a,s-1),before:Tl(a,s-1)}),a&&c&&x.disabled.push({after:a,before:Tl(a,s-1)}),!a&&c&&x.disabled.push({after:LB(c,s-1),before:Tl(c,s-1)})),f){if(a&&!c&&(x.disabled.push({before:Tl(a,-f+1)}),x.disabled.push({after:Tl(a,f-1)})),a&&c){var _=Hh(c,a)+1,T=f-_;x.disabled.push({before:LB(a,T)}),x.disabled.push({after:Tl(c,T)})}!a&&c&&(x.disabled.push({before:Tl(c,-f+1)}),x.disabled.push({after:Tl(c,f-1)}))}return o.jsx(JH.Provider,{value:{selected:n,onDayClick:m,modifiers:x},children:r})}function eW(){var t=P.useContext(JH);if(!t)throw new Error("useSelectRange must be used within a SelectRangeProvider");return t}function KR(t){return Array.isArray(t)?nEe([],t):t!==void 0?[t]:[]}function Fjt(t){var e={};return Object.entries(t).forEach(function(r){var n=r[0],i=r[1];e[n]=KR(i)}),e}var tf;(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"})(tf||(tf={}));var Bjt=tf.Selected,Xp=tf.Disabled,zjt=tf.Hidden,$jt=tf.Today,Uz=tf.RangeEnd,Vz=tf.RangeMiddle,qz=tf.RangeStart,Ujt=tf.Outside;function Vjt(t,e,r){var n,i=(n={},n[Bjt]=KR(t.selected),n[Xp]=KR(t.disabled),n[zjt]=KR(t.hidden),n[$jt]=[t.today],n[Uz]=[],n[Vz]=[],n[qz]=[],n[Ujt]=[],n);return t.fromDate&&i[Xp].push({before:t.fromDate}),t.toDate&&i[Xp].push({after:t.toDate}),dj(t)?i[Xp]=i[Xp].concat(e.modifiers[Xp]):hj(t)&&(i[Xp]=i[Xp].concat(r.modifiers[Xp]),i[qz]=r.modifiers[qz],i[Vz]=r.modifiers[Vz],i[Uz]=r.modifiers[Uz]),i}var lEe=P.createContext(void 0);function qjt(t){var e=ga(),r=QH(),n=eW(),i=Vjt(e,r,n),a=Fjt(e.modifiers),c=ci(ci({},i),a);return o.jsx(lEe.Provider,{value:c,children:t.children})}function cEe(){var t=P.useContext(lEe);if(!t)throw new Error("useModifiers must be used within a ModifiersProvider");return t}function Gjt(t){return!!(t&&typeof t=="object"&&"before"in t&&"after"in t)}function Hjt(t){return!!(t&&typeof t=="object"&&"from"in t)}function Wjt(t){return!!(t&&typeof t=="object"&&"after"in t)}function Kjt(t){return!!(t&&typeof t=="object"&&"before"in t)}function Yjt(t){return!!(t&&typeof t=="object"&&"dayOfWeek"in t)}function Zjt(t,e){var r,n=e.from,i=e.to;if(n&&i){var a=Hh(i,n)<0;a&&(r=[i,n],n=r[0],i=r[1]);var c=Hh(t,n)>=0&&Hh(i,t)>=0;return c}return i?Kl(i,t):n?Kl(n,t):!1}function Xjt(t){return B9(t)}function Qjt(t){return Array.isArray(t)&&t.every(B9)}function Jjt(t,e){return e.some(function(r){if(typeof r=="boolean")return r;if(Xjt(r))return Kl(t,r);if(Qjt(r))return r.includes(t);if(Hjt(r))return Zjt(t,r);if(Yjt(r))return r.dayOfWeek.includes(t.getDay());if(Gjt(r)){var n=Hh(r.before,t),i=Hh(r.after,t),a=n>0,c=i<0,s=pk(r.before,r.after);return s?c&&a:a||c}return Wjt(r)?Hh(t,r.after)>0:Kjt(r)?Hh(r.before,t)>0:typeof r=="function"?r(t):!1})}function tW(t,e,r){var n=Object.keys(e).reduce(function(a,c){var s=e[c];return Jjt(t,s)&&a.push(c),a},[]),i={};return n.forEach(function(a){return i[a]=!0}),r&&!qM(t,r)&&(i.outside=!0),i}function eIt(t,e){for(var r=Zc(t[0]),n=WC(t[t.length-1]),i,a,c=r;c<=n;){var s=tW(c,e),f=!s.disabled&&!s.hidden;if(!f){c=Tl(c,1);continue}if(s.selected)return c;s.today&&!a&&(a=c),i||(i=c),c=Tl(c,1)}return a||i}var tIt=365;function uEe(t,e){var r=e.moveBy,n=e.direction,i=e.context,a=e.modifiers,c=e.retry,s=c===void 0?{count:0,lastFocused:t}:c,f=i.weekStartsOn,m=i.fromDate,x=i.toDate,_=i.locale,T={day:Tl,week:C6,month:cd,year:A9e,startOfWeek:function(R){return i.ISOWeek?Lm(R):_c(R,{locale:_,weekStartsOn:f})},endOfWeek:function(R){return i.ISOWeek?Yxe(R):UM(R,{locale:_,weekStartsOn:f})}},E=T[r](t,n==="after"?1:-1);n==="before"&&m?E=k9e([m,E]):n==="after"&&x&&(E=C9e([x,E]));var C=!0;if(a){var N=tW(E,a);C=!N.disabled&&!N.hidden}return C?E:s.count>tIt?s.lastFocused:uEe(E,{moveBy:r,direction:n,context:i,modifiers:a,retry:ci(ci({},s),{count:s.count+1})})}var dEe=P.createContext(void 0);function rIt(t){var e=fj(),r=cEe(),n=P.useState(),i=n[0],a=n[1],c=P.useState(),s=c[0],f=c[1],m=eIt(e.displayMonths,r),x=i??(s&&e.isDateDisplayed(s))?s:m,_=function(){f(i),a(void 0)},T=function(R){a(R)},E=ga(),C=function(R,D){if(i){var M=uEe(i,{moveBy:R,direction:D,context:E,modifiers:r});Kl(i,M)||(e.goToDate(M,i),T(M))}},N={focusedDay:i,focusTarget:x,blur:_,focus:T,focusDayAfter:function(){return C("day","after")},focusDayBefore:function(){return C("day","before")},focusWeekAfter:function(){return C("week","after")},focusWeekBefore:function(){return C("week","before")},focusMonthBefore:function(){return C("month","before")},focusMonthAfter:function(){return C("month","after")},focusYearBefore:function(){return C("year","before")},focusYearAfter:function(){return C("year","after")},focusStartOfWeek:function(){return C("startOfWeek","before")},focusEndOfWeek:function(){return C("endOfWeek","after")}};return o.jsx(dEe.Provider,{value:N,children:t.children})}function rW(){var t=P.useContext(dEe);if(!t)throw new Error("useFocusContext must be used within a FocusProvider");return t}function nIt(t,e){var r=cEe(),n=tW(t,r,e);return n}var nW=P.createContext(void 0);function iIt(t){if(!l3(t.initialProps)){var e={selected:void 0};return o.jsx(nW.Provider,{value:e,children:t.children})}return o.jsx(sIt,{initialProps:t.initialProps,children:t.children})}function sIt(t){var e=t.initialProps,r=t.children,n=function(a,c,s){var f,m,x;if((f=e.onDayClick)===null||f===void 0||f.call(e,a,c,s),c.selected&&!e.required){(m=e.onSelect)===null||m===void 0||m.call(e,void 0,a,c,s);return}(x=e.onSelect)===null||x===void 0||x.call(e,a,a,c,s)},i={selected:e.selected,onDayClick:n};return o.jsx(nW.Provider,{value:i,children:r})}function hEe(){var t=P.useContext(nW);if(!t)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return t}function aIt(t,e){var r=ga(),n=hEe(),i=QH(),a=eW(),c=rW(),s=c.focusDayAfter,f=c.focusDayBefore,m=c.focusWeekAfter,x=c.focusWeekBefore,_=c.blur,T=c.focus,E=c.focusMonthBefore,C=c.focusMonthAfter,N=c.focusYearBefore,R=c.focusYearAfter,D=c.focusStartOfWeek,M=c.focusEndOfWeek,B=function(we){var ge,Ne,Ie,Te;l3(r)?(ge=n.onDayClick)===null||ge===void 0||ge.call(n,t,e,we):dj(r)?(Ne=i.onDayClick)===null||Ne===void 0||Ne.call(i,t,e,we):hj(r)?(Ie=a.onDayClick)===null||Ie===void 0||Ie.call(a,t,e,we):(Te=r.onDayClick)===null||Te===void 0||Te.call(r,t,e,we)},V=function(we){var ge;T(t),(ge=r.onDayFocus)===null||ge===void 0||ge.call(r,t,e,we)},G=function(we){var ge;_(),(ge=r.onDayBlur)===null||ge===void 0||ge.call(r,t,e,we)},W=function(we){var ge;(ge=r.onDayMouseEnter)===null||ge===void 0||ge.call(r,t,e,we)},X=function(we){var ge;(ge=r.onDayMouseLeave)===null||ge===void 0||ge.call(r,t,e,we)},Q=function(we){var ge;(ge=r.onDayPointerEnter)===null||ge===void 0||ge.call(r,t,e,we)},re=function(we){var ge;(ge=r.onDayPointerLeave)===null||ge===void 0||ge.call(r,t,e,we)},se=function(we){var ge;(ge=r.onDayTouchCancel)===null||ge===void 0||ge.call(r,t,e,we)},ue=function(we){var ge;(ge=r.onDayTouchEnd)===null||ge===void 0||ge.call(r,t,e,we)},_e=function(we){var ge;(ge=r.onDayTouchMove)===null||ge===void 0||ge.call(r,t,e,we)},Se=function(we){var ge;(ge=r.onDayTouchStart)===null||ge===void 0||ge.call(r,t,e,we)},ve=function(we){var ge;(ge=r.onDayKeyUp)===null||ge===void 0||ge.call(r,t,e,we)},Oe=function(we){var ge;switch(we.key){case"ArrowLeft":we.preventDefault(),we.stopPropagation(),r.dir==="rtl"?s():f();break;case"ArrowRight":we.preventDefault(),we.stopPropagation(),r.dir==="rtl"?f():s();break;case"ArrowDown":we.preventDefault(),we.stopPropagation(),m();break;case"ArrowUp":we.preventDefault(),we.stopPropagation(),x();break;case"PageUp":we.preventDefault(),we.stopPropagation(),we.shiftKey?N():E();break;case"PageDown":we.preventDefault(),we.stopPropagation(),we.shiftKey?R():C();break;case"Home":we.preventDefault(),we.stopPropagation(),D();break;case"End":we.preventDefault(),we.stopPropagation(),M();break}(ge=r.onDayKeyDown)===null||ge===void 0||ge.call(r,t,e,we)},Ae={onClick:B,onFocus:V,onBlur:G,onKeyDown:Oe,onKeyUp:ve,onMouseEnter:W,onMouseLeave:X,onPointerEnter:Q,onPointerLeave:re,onTouchCancel:se,onTouchEnd:ue,onTouchMove:_e,onTouchStart:Se};return Ae}function oIt(){var t=ga(),e=hEe(),r=QH(),n=eW(),i=l3(t)?e.selected:dj(t)?r.selected:hj(t)?n.selected:void 0;return i}function lIt(t){return Object.values(tf).includes(t)}function cIt(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(lIt(n)){var a=t.classNames["day_".concat(n)];a&&r.push(a)}}),r}function uIt(t,e){var r=ci({},t.styles.day);return Object.keys(e).forEach(function(n){var i;r=ci(ci({},r),(i=t.modifiersStyles)===null||i===void 0?void 0:i[n])}),r}function dIt(t,e,r){var n,i,a,c=ga(),s=rW(),f=nIt(t,e),m=aIt(t,f),x=oIt(),_=!!(c.onDayClick||c.mode!=="default");P.useEffect(function(){var W;f.outside||s.focusedDay&&_&&Kl(s.focusedDay,t)&&((W=r.current)===null||W===void 0||W.focus())},[s.focusedDay,t,r,_,f.outside]);var T=cIt(c,f).join(" "),E=uIt(c,f),C=!!(f.outside&&!c.showOutsideDays||f.hidden),N=(a=(i=c.components)===null||i===void 0?void 0:i.DayContent)!==null&&a!==void 0?a:Njt,R=o.jsx(N,{date:t,displayMonth:e,activeModifiers:f}),D={style:E,className:T,children:R,role:"gridcell"},M=s.focusTarget&&Kl(s.focusTarget,t)&&!f.outside,B=s.focusedDay&&Kl(s.focusedDay,t),V=ci(ci(ci({},D),(n={disabled:f.disabled,role:"gridcell"},n["aria-selected"]=f.selected,n.tabIndex=B||M?0:-1,n)),m),G={isButton:_,isHidden:C,activeModifiers:f,selectedDays:x,buttonProps:V,divProps:D};return G}function hIt(t){var e=P.useRef(null),r=dIt(t.date,t.displayMonth,e);return r.isHidden?o.jsx("div",{role:"gridcell"}):r.isButton?o.jsx(xO,ci({name:"day",ref:e},r.buttonProps)):o.jsx("div",ci({},r.divProps))}function fIt(t){var e=t.number,r=t.dates,n=ga(),i=n.onWeekNumberClick,a=n.styles,c=n.classNames,s=n.locale,f=n.labels.labelWeekNumber,m=n.formatters.formatWeekNumber,x=m(Number(e),{locale:s});if(!i)return o.jsx("span",{className:c.weeknumber,style:a.weeknumber,children:x});var _=f(Number(e),{locale:s}),T=function(E){i(e,r,E)};return o.jsx(xO,{name:"week-number","aria-label":_,className:c.weeknumber,style:a.weeknumber,onClick:T,children:x})}function pIt(t){var e,r,n=ga(),i=n.styles,a=n.classNames,c=n.showWeekNumber,s=n.components,f=(e=s==null?void 0:s.Day)!==null&&e!==void 0?e:hIt,m=(r=s==null?void 0:s.WeekNumber)!==null&&r!==void 0?r:fIt,x;return c&&(x=o.jsx("td",{className:a.cell,style:i.cell,children:o.jsx(m,{number:t.weekNumber,dates:t.dates})})),o.jsxs("tr",{className:a.row,style:i.row,children:[x,t.dates.map(function(_){return o.jsx("td",{className:a.cell,style:i.cell,role:"presentation",children:o.jsx(f,{displayMonth:t.displayMonth,date:_})},R7e(_))})]})}function Eoe(t,e,r){for(var n=r!=null&&r.ISOWeek?Yxe(e):UM(e,r),i=r!=null&&r.ISOWeek?Lm(t):_c(t,r),a=Hh(n,i),c=[],s=0;s<=a;s++)c.push(Tl(i,s));var f=c.reduce(function(m,x){var _=r!=null&&r.ISOWeek?z9(x):U9(x,r),T=m.find(function(E){return E.weekNumber===_});return T?(T.dates.push(x),m):(m.push({weekNumber:_,dates:[x]}),m)},[]);return f}function mIt(t,e){var r=Eoe(Zc(t),WC(t),e);if(e!=null&&e.useFixedWeeks){var n=D7e(t,e);if(n<6){var i=r[r.length-1],a=i.dates[i.dates.length-1],c=C6(a,6-n),s=Eoe(C6(a,1),c,e);r.push.apply(r,s)}}return r}function gIt(t){var e,r,n,i=ga(),a=i.locale,c=i.classNames,s=i.styles,f=i.hideHead,m=i.fixedWeeks,x=i.components,_=i.weekStartsOn,T=i.firstWeekContainsDate,E=i.ISOWeek,C=mIt(t.displayMonth,{useFixedWeeks:!!m,ISOWeek:E,locale:a,weekStartsOn:_,firstWeekContainsDate:T}),N=(e=x==null?void 0:x.Head)!==null&&e!==void 0?e:Pjt,R=(r=x==null?void 0:x.Row)!==null&&r!==void 0?r:pIt,D=(n=x==null?void 0:x.Footer)!==null&&n!==void 0?n:Cjt;return o.jsxs("table",{id:t.id,className:c.table,style:s.table,role:"grid","aria-labelledby":t["aria-labelledby"],children:[!f&&o.jsx(N,{}),o.jsx("tbody",{className:c.tbody,style:s.tbody,children:C.map(function(M){return o.jsx(R,{displayMonth:t.displayMonth,dates:M.dates,weekNumber:M.weekNumber},M.weekNumber)})}),o.jsx(D,{displayMonth:t.displayMonth})]})}function yIt(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var xIt=yIt()?P.useLayoutEffect:P.useEffect,Gz=!1,_It=0;function Aoe(){return"react-day-picker-".concat(++_It)}function vIt(t){var e,r=t??(Gz?Aoe():null),n=P.useState(r),i=n[0],a=n[1];return xIt(function(){i===null&&a(Aoe())},[]),P.useEffect(function(){Gz===!1&&(Gz=!0)},[]),(e=t??i)!==null&&e!==void 0?e:void 0}function bIt(t){var e,r,n=ga(),i=n.dir,a=n.classNames,c=n.styles,s=n.components,f=fj().displayMonths,m=vIt(n.id?"".concat(n.id,"-").concat(t.displayIndex):void 0),x=n.id?"".concat(n.id,"-grid-").concat(t.displayIndex):void 0,_=[a.month],T=c.month,E=t.displayIndex===0,C=t.displayIndex===f.length-1,N=!E&&!C;i==="rtl"&&(e=[E,C],C=e[0],E=e[1]),E&&(_.push(a.caption_start),T=ci(ci({},T),c.caption_start)),C&&(_.push(a.caption_end),T=ci(ci({},T),c.caption_end)),N&&(_.push(a.caption_between),T=ci(ci({},T),c.caption_between));var R=(r=s==null?void 0:s.Caption)!==null&&r!==void 0?r:kjt;return o.jsxs("div",{className:_.join(" "),style:T,children:[o.jsx(R,{id:m,displayMonth:t.displayMonth,displayIndex:t.displayIndex}),o.jsx(gIt,{id:x,"aria-labelledby":m,displayMonth:t.displayMonth})]},t.displayIndex)}function wIt(t){var e=ga(),r=e.classNames,n=e.styles;return o.jsx("div",{className:r.months,style:n.months,children:t.children})}function SIt(t){var e,r,n=t.initialProps,i=ga(),a=rW(),c=fj(),s=P.useState(!1),f=s[0],m=s[1];P.useEffect(function(){i.initialFocus&&a.focusTarget&&(f||(a.focus(a.focusTarget),m(!0)))},[i.initialFocus,f,a.focus,a.focusTarget,a]);var x=[i.classNames.root,i.className];i.numberOfMonths>1&&x.push(i.classNames.multiple_months),i.showWeekNumber&&x.push(i.classNames.with_weeknumber);var _=ci(ci({},i.styles.root),i.style),T=Object.keys(n).filter(function(C){return C.startsWith("data-")}).reduce(function(C,N){var R;return ci(ci({},C),(R={},R[N]=n[N],R))},{}),E=(r=(e=n.components)===null||e===void 0?void 0:e.Months)!==null&&r!==void 0?r:wIt;return o.jsx("div",ci({className:x.join(" "),style:_,dir:i.dir,id:i.id,nonce:n.nonce,title:n.title,lang:n.lang},T,{children:o.jsx(E,{children:c.displayMonths.map(function(C,N){return o.jsx(bIt,{displayIndex:N,displayMonth:C},N)})})}))}function TIt(t){var e=t.children,r=KCt(t,["children"]);return o.jsx(fjt,{initialProps:r,children:o.jsx(Sjt,{children:o.jsx(iIt,{initialProps:r,children:o.jsx(Rjt,{initialProps:r,children:o.jsx(Ojt,{initialProps:r,children:o.jsx(qjt,{children:o.jsx(rIt,{children:e})})})})})})})}function EIt(t){return o.jsx(TIt,ci({},t,{children:o.jsx(SIt,{initialProps:t})}))}function fEe({className:t,classNames:e,showOutsideDays:r=!0,captionLayout:n,...i}){const a=n==="dropdown"?"dropdown-buttons":n;return o.jsx(EIt,{showOutsideDays:r,captionLayout:a,className:sr("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:sr(JA({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:sr(JA({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})=>o.jsx($m,{className:"h-4 w-4"}),IconRight:({...c})=>o.jsx(th,{className:"h-4 w-4"})},...i})}fEe.displayName="Calendar";function pEe({open:t,onOpenChange:e,editTask:r,defaultDealId:n,defaultStageId:i}){var Se;const a=zCt(),c=$Ct(),{data:s}=WCt(),f=Ji(),{data:m}=wr({queryKey:["contacts-for-tasks",f],queryFn:async()=>{if(!f)return[];const ve=[],Oe=1e3;for(let Ae=0;;Ae+=Oe){const{data:we,error:ge}=await Le.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",f).order("first_name").order("id").range(Ae,Ae+Oe-1);if(ge)throw ge;if(ve.push(...we||[]),!we||we.length{r?(_(r.title),E(r.description||""),N(r.deal_id||"none"),D(r.contact_id||"none"),B(r.priority),G(r.status),X(r.due_date?Uc(r.due_date):void 0)):(_(""),E(""),N(n||"none"),D("none"),B("medium"),G("todo"),X(void 0))},[r,t,n]);const _e=async()=>{if(!x.trim()){Jt.error("Task title is required");return}try{const ve={title:x.trim(),description:T.trim()||null,deal_id:C==="none"?null:C,contact_id:R==="none"?null:R,stage_id:i||null,priority:M,status:V,due_date:W?Ri(W,"yyyy-MM-dd"):null};r?(await c.mutateAsync({id:r.id,...ve}),Jt.success("Task updated")):(await a.mutateAsync(ve),G0("task_created"),Jt.success("Task created")),e(!1)}catch{Jt.error("Failed to save task")}};return o.jsx(ro,{open:t,onOpenChange:e,children:o.jsxs($a,{className:"sm:max-w-[480px]",children:[o.jsx(ul,{children:o.jsx(Go,{children:r?"Edit Task":"New Task"})}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx(Mr,{children:"Title *"}),o.jsx(Ur,{value:x,onChange:ve=>_(ve.target.value),placeholder:"e.g., Send inspection report"})]}),o.jsxs("div",{children:[o.jsx(Mr,{children:"Description"}),o.jsx(hd,{value:T,onChange:ve=>E(ve.target.value),placeholder:"Optional details...",rows:2})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx(Mr,{children:"Priority"}),o.jsxs(Ba,{value:M,onValueChange:ve=>B(ve),children:[o.jsx(ja,{children:o.jsx(za,{})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"low",children:"🟢 Low"}),o.jsx(wn,{value:"medium",children:"🟡 Medium"}),o.jsx(wn,{value:"high",children:"🟠 High"}),o.jsx(wn,{value:"urgent",children:"🔴 Urgent"})]})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{children:"Status"}),o.jsxs(Ba,{value:V,onValueChange:ve=>G(ve),children:[o.jsx(ja,{children:o.jsx(za,{})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"todo",children:"To Do"}),o.jsx(wn,{value:"in_progress",children:"In Progress"}),o.jsx(wn,{value:"done",children:"Done"})]})]})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{children:"Due Date"}),o.jsxs(VR,{children:[o.jsx(qR,{asChild:!0,children:o.jsxs(Ut,{variant:"outline",className:sr("w-full justify-start text-left font-normal",!W&&"text-muted-foreground"),children:[o.jsx(po,{className:"mr-2 h-4 w-4"}),W?Ri(W,"PPP"):"Pick a date"]})}),o.jsx(SA,{className:"w-auto p-0",align:"start",children:o.jsx(fEe,{mode:"single",selected:W,onSelect:X,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{children:"Link to Deal"}),o.jsxs(VR,{open:Q,onOpenChange:re,children:[o.jsx(qR,{asChild:!0,children:o.jsxs(Ut,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[o.jsxs("span",{className:"flex items-center gap-2 truncate",children:[o.jsx(Eo,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),C!=="none"?((Se=s==null?void 0:s.find(ve=>ve.id===C))==null?void 0:Se.deal_name)||"Select deal":"No Deal"]}),o.jsx(wU,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),o.jsx(SA,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:o.jsxs(mk,{children:[o.jsx(gk,{placeholder:"Search deals..."}),o.jsxs(yk,{children:[o.jsx(xk,{children:"No deals found."}),o.jsxs(T1,{children:[o.jsxs(xy,{value:"no-deal",onSelect:()=>{N("none"),re(!1)},children:[o.jsx(Ao,{className:sr("mr-2 h-4 w-4",C==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),s==null?void 0:s.map(ve=>o.jsxs(xy,{value:ve.deal_name,onSelect:()=>{N(ve.id),re(!1)},children:[o.jsx(Ao,{className:sr("mr-2 h-4 w-4",C===ve.id?"opacity-100":"opacity-0")}),ve.deal_name]},ve.id))]})]})]})})]})]}),o.jsxs("div",{children:[o.jsx(Mr,{children:"Link to Contact"}),o.jsxs(VR,{open:se,onOpenChange:ue,children:[o.jsx(qR,{asChild:!0,children:o.jsxs(Ut,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[o.jsxs("span",{className:"flex items-center gap-2 truncate",children:[o.jsx(gc,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),R!=="none"?(()=>{const ve=m==null?void 0:m.find(Oe=>Oe.id===R);return ve?`${ve.first_name} ${ve.last_name}`:"Select contact"})():"No Contact"]}),o.jsx(wU,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),o.jsx(SA,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:o.jsxs(mk,{children:[o.jsx(gk,{placeholder:"Search contacts..."}),o.jsxs(yk,{children:[o.jsx(xk,{children:"No contacts found."}),o.jsxs(T1,{children:[o.jsxs(xy,{value:"no-contact",onSelect:()=>{D("none"),ue(!1)},children:[o.jsx(Ao,{className:sr("mr-2 h-4 w-4",R==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),m==null?void 0:m.map(ve=>o.jsxs(xy,{value:`${ve.first_name??""} ${ve.last_name??""} ${ve.id}`,onSelect:()=>{D(ve.id),ue(!1)},children:[o.jsx(Ao,{className:sr("mr-2 h-4 w-4",R===ve.id?"opacity-100":"opacity-0")}),ve.first_name," ",ve.last_name]},ve.id))]})]})]})})]})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o.jsx(Ut,{variant:"outline",onClick:()=>e(!1),children:"Cancel"}),o.jsx(Ut,{onClick:_e,disabled:a.isPending||c.isPending,children:r?"Save Changes":"Create Task"})]})]})]})})}const AIt={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 kIt({tasks:t}){const e=ZH(),r=UCt(),n=ma(),[i,a]=P.useState(null),c=async x=>{const _=x.status==="done"?"todo":"done";try{await e.mutateAsync({id:x.id,status:_})}catch{Jt.error("Failed to update task")}},s=async x=>{try{await r.mutateAsync(x),Jt.success("Task deleted")}catch{Jt.error("Failed to delete task")}};if(t.length===0)return o.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[o.jsx(xc,{className:"h-12 w-12 text-muted-foreground/30 mb-3"}),o.jsx("p",{className:"text-muted-foreground font-medium",children:"No tasks found"}),o.jsx("p",{className:"text-muted-foreground/60 text-sm",children:"Create a new task to get started"})]});const f=new Map,m=[];return t.forEach(x=>{if(x.deal){const _=f.get(x.deal.id)||{dealName:x.deal.deal_name,tasks:[]};_.tasks.push(x),f.set(x.deal.id,_)}else m.push(x)}),o.jsxs("div",{className:"space-y-4",children:[m.length>0&&o.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[o.jsx("div",{className:"bg-muted/30 px-4 py-2 border-b",children:o.jsx("h3",{className:"font-medium text-sm text-muted-foreground",children:"General Tasks"})}),m.map(x=>o.jsx(koe,{task:x,onToggle:c,onDelete:s,onEdit:a,onNavigateDeal:_=>n(`/mission-control/pipeline?deal=${_}`)},x.id))]}),Array.from(f.entries()).map(([x,_])=>o.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[o.jsxs("button",{onClick:()=>n(`/mission-control/pipeline?deal=${x}`),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:[o.jsx(Eo,{className:"h-3.5 w-3.5 text-muted-foreground"}),o.jsx("h3",{className:"font-medium text-sm",children:_.dealName}),o.jsxs(us,{variant:"secondary",className:"ml-auto text-xs",children:[_.tasks.filter(T=>T.status==="done").length,"/",_.tasks.length]}),o.jsx(th,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),_.tasks.map(T=>o.jsx(koe,{task:T,onToggle:c,onDelete:s,onEdit:a,onNavigateDeal:E=>n(`/mission-control/pipeline?deal=${E}`)},T.id))]},x)),i&&o.jsx(pEe,{open:!!i,onOpenChange:()=>a(null),editTask:i})]})}function koe({task:t,onToggle:e,onDelete:r,onEdit:n,onNavigateDeal:i}){const a=t.status==="done",c=!a&&t.due_date&&S1(Uc(t.due_date))&&!Gd(Uc(t.due_date)),s=!a&&t.due_date&&Gd(Uc(t.due_date)),f=AIt[t.priority];return o.jsxs("div",{className:sr("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:[o.jsx("button",{onClick:()=>e(t),className:"shrink-0",children:a?o.jsx(xc,{className:"h-5 w-5 text-emerald-500"}):o.jsx(d1,{className:"h-5 w-5 text-muted-foreground hover:text-primary transition-colors"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:sr("text-sm font-medium truncate",a&&"line-through text-muted-foreground"),children:t.title}),o.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[t.stage&&o.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&&o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[o.jsx(gc,{className:"h-2.5 w-2.5"}),t.contact.first_name," ",t.contact.last_name]})]})]}),o.jsxs(us,{variant:"outline",className:sr("text-[10px] shrink-0",f.color),children:[f.dot," ",f.label]}),t.due_date&&o.jsxs("span",{className:sr("text-xs shrink-0 flex items-center gap-1",c&&"text-destructive font-medium",s&&"text-amber-600 font-medium",!c&&!s&&"text-muted-foreground"),children:[o.jsx(mc,{className:"h-3 w-3"}),Ri(Uc(t.due_date),"MMM d")]}),o.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[o.jsx("button",{onClick:()=>n(t),className:"p-1 hover:bg-muted rounded",children:o.jsx(kU,{className:"h-3.5 w-3.5 text-muted-foreground"})}),o.jsx("button",{onClick:()=>r(t.id),className:"p-1 hover:bg-destructive/10 rounded",children:o.jsx(IL,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const CIt=[{status:"todo",label:"To Do",icon:d1,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:hG,color:"border-t-blue-500"},{status:"done",label:"Done",icon:xc,color:"border-t-emerald-500"}],jIt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function IIt({tasks:t}){const e=ZH(),r=P.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 s=a.dataTransfer.getData("taskId");if(!s)return;const f=t.find(m=>m.id===s);if(!(!f||f.status===c))try{await e.mutateAsync({id:s,status:c})}catch{Jt.error("Failed to move task")}};return o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:CIt.map(a=>o.jsxs("div",{className:sr("border rounded-lg border-t-4 bg-muted/20",a.color),onDragOver:c=>c.preventDefault(),onDrop:c=>i(c,a.status),children:[o.jsxs("div",{className:"px-4 py-3 flex items-center gap-2",children:[o.jsx(a.icon,{className:"h-4 w-4 text-muted-foreground"}),o.jsx("h3",{className:"font-semibold text-sm",children:a.label}),o.jsx(us,{variant:"secondary",className:"ml-auto text-xs",children:r[a.status].length})]}),o.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[r[a.status].map(c=>o.jsx(PIt,{task:c,onDragStart:n},c.id)),r[a.status].length===0&&o.jsx("p",{className:"text-xs text-muted-foreground text-center py-8",children:"Drag tasks here"})]})]},a.status))})}function PIt({task:t,onDragStart:e}){const r=t.status==="done",n=!r&&t.due_date&&S1(Uc(t.due_date))&&!Gd(Uc(t.due_date)),i=!r&&t.due_date&&Gd(Uc(t.due_date));return o.jsx("div",{draggable:!0,onDragStart:a=>e(a,t.id),className:sr("bg-background border rounded-lg p-3 cursor-grab active:cursor-grabbing shadow-sm hover:shadow-md transition-shadow",n&&"border-destructive/50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx("span",{className:"text-xs mt-0.5",children:jIt[t.priority]}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:sr("text-sm font-medium",r&&"line-through text-muted-foreground"),children:t.title}),o.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[t.deal&&o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[o.jsx(Eo,{className:"h-2.5 w-2.5"}),t.deal.deal_name]}),t.contact&&o.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[o.jsx(gc,{className:"h-2.5 w-2.5"}),t.contact.first_name," ",t.contact.last_name]})]}),t.due_date&&o.jsxs("div",{className:sr("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:[o.jsx(mc,{className:"h-2.5 w-2.5"}),n?"Overdue — ":i?"Due today — ":"",Ri(Uc(t.due_date),"MMM d")]}),t.stage&&o.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 Coe={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function NIt({tasks:t}){const[e,r]=P.useState(new Date),n=ZH(),i=Zc(e),a=WC(e),c=_c(i),s=UM(a),f=M9e({start:c,end:s}),m=P.useMemo(()=>{const T=new Map;return t.forEach(E=>{if(!E.due_date)return;const C=E.due_date,N=T.get(C)||[];N.push(E),T.set(C,N)}),T},[t]),x=P.useMemo(()=>t.filter(T=>!T.due_date),[t]),_=async T=>{const E=T.status==="done"?"todo":"done";try{await n.mutateAsync({id:T.id,status:E})}catch{Jt.error("Failed to update task")}};return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx(Ut,{variant:"ghost",size:"icon",onClick:()=>r(YHe(e,1)),children:o.jsx($m,{className:"h-4 w-4"})}),o.jsx("h3",{className:"font-semibold",children:Ri(e,"MMMM yyyy")}),o.jsx(Ut,{variant:"ghost",size:"icon",onClick:()=>r(cd(e,1)),children:o.jsx(th,{className:"h-4 w-4"})})]}),o.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(T=>o.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:T},T))}),o.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:f.map(T=>{const E=Ri(T,"yyyy-MM-dd"),C=m.get(E)||[],N=qM(T,e),R=Gd(T);return o.jsxs("div",{className:sr("border-r border-b min-h-[100px] p-1",!N&&"bg-muted/30",R&&"bg-primary/5"),children:[o.jsx("div",{className:sr("text-xs font-medium mb-1 text-right px-1",!N&&"text-muted-foreground/40",R&&"text-primary font-bold"),children:Ri(T,"d")}),o.jsxs("div",{className:"space-y-0.5",children:[C.slice(0,3).map(D=>o.jsxs("button",{onClick:()=>_(D),className:sr("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",D.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[D.status==="done"?o.jsx(xc,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):o.jsx(d1,{className:"h-2.5 w-2.5 shrink-0"}),o.jsxs("span",{className:"truncate",children:[Coe[D.priority]," ",D.title]})]},D.id)),C.length>3&&o.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",C.length-3," more"]})]})]},E)})}),x.length>0&&o.jsxs("div",{className:"border rounded-lg p-3",children:[o.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",x.length,")"]}),o.jsx("div",{className:"space-y-1",children:x.map(T=>o.jsxs("button",{onClick:()=>_(T),className:sr("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",T.status==="done"&&"opacity-50 line-through"),children:[T.status==="done"?o.jsx(xc,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):o.jsx(d1,{className:"h-3.5 w-3.5 shrink-0"}),o.jsxs("span",{className:"truncate",children:[Coe[T.priority]," ",T.title]}),T.deal&&o.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",T.deal.deal_name]})]},T.id))})]})]})}const RIt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function LIt({open:t,onOpenChange:e,stages:r}){var D;const[n,i]=P.useState(((D=r[0])==null?void 0:D.id)||""),{data:a,isLoading:c}=VCt(n||void 0),s=qCt(),f=GCt(),[m,x]=P.useState(""),[_,T]=P.useState("medium"),[E,C]=P.useState(""),N=async()=>{if(!(!m.trim()||!n))try{await s.mutateAsync({stage_id:n,title:m.trim(),priority:_,default_due_offset_days:E?parseInt(E):null,sort_order:((a==null?void 0:a.length)||0)+1}),x(""),C(""),Jt.success("Template added")}catch{Jt.error("Failed to add template")}},R=async M=>{try{await f.mutateAsync(M),Jt.success("Template deleted")}catch{Jt.error("Failed to delete template")}};return o.jsx(ro,{open:t,onOpenChange:e,children:o.jsxs($a,{className:"sm:max-w-[560px]",children:[o.jsx(ul,{children:o.jsxs(Go,{className:"flex items-center gap-2",children:[o.jsx(WRe,{className:"h-5 w-5"}),"Task Templates by Stage"]})}),o.jsx("p",{className:"text-sm text-muted-foreground -mt-2",children:"Create default tasks that auto-populate when a deal enters a stage."}),o.jsxs("div",{children:[o.jsx(Mr,{children:"Pipeline Stage"}),o.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:r.filter(M=>!M.is_won_stage&&!M.is_lost_stage).map(M=>o.jsx("button",{onClick:()=>i(M.id),className:sr("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",n===M.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:M.name},M.id))})]}),o.jsx(pp,{className:"max-h-[250px]",children:o.jsxs("div",{className:"space-y-1.5",children:[a==null?void 0:a.map((M,B)=>o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border rounded-lg group",children:[o.jsx("span",{className:"text-xs",children:RIt[M.priority]}),o.jsx("span",{className:"text-sm flex-1 truncate",children:M.title}),M.default_due_offset_days&&o.jsxs(us,{variant:"outline",className:"text-[10px]",children:["+",M.default_due_offset_days,"d"]}),o.jsx("button",{onClick:()=>R(M.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:o.jsx(IL,{className:"h-3.5 w-3.5 text-destructive"})})]},M.id)),(a==null?void 0:a.length)===0&&n&&o.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),n&&o.jsxs("div",{className:"space-y-3 border-t pt-3",children:[o.jsx(Mr,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(Ur,{placeholder:"Task title...",value:m,onChange:M=>x(M.target.value),className:"flex-1",onKeyDown:M=>M.key==="Enter"&&N()}),o.jsxs(Ba,{value:_,onValueChange:M=>T(M),children:[o.jsx(ja,{className:"w-[100px]",children:o.jsx(za,{})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"low",children:"🟢 Low"}),o.jsx(wn,{value:"medium",children:"🟡 Med"}),o.jsx(wn,{value:"high",children:"🟠 High"}),o.jsx(wn,{value:"urgent",children:"🔴 Urgent"})]})]})]}),o.jsxs("div",{className:"flex gap-2 items-end",children:[o.jsxs("div",{className:"flex-1",children:[o.jsx(Mr,{className:"text-xs",children:"Due offset (days from entering stage)"}),o.jsx(Ur,{type:"number",placeholder:"e.g., 7",value:E,onChange:M=>C(M.target.value)})]}),o.jsxs(Ut,{onClick:N,disabled:!m.trim()||s.isPending,children:[o.jsx(xm,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function DIt(){const{data:t,isLoading:e}=BCt(),{data:r}=HCt(),[n,i]=P.useState("list"),[a,c]=P.useState(""),[s,f]=P.useState("active"),[m,x]=P.useState("all"),[_,T]=P.useState("all"),[E,C]=P.useState(!1),[N,R]=P.useState(!1),D=P.useMemo(()=>{if(!t)return[];const V=new Map;return t.forEach(G=>{G.deal&&V.set(G.deal.id,G.deal.deal_name)}),Array.from(V,([G,W])=>({id:G,name:W}))},[t]),M=P.useMemo(()=>t?t.filter(V=>{var se,ue,_e,Se;const G=a.toLowerCase(),W=!G||V.title.toLowerCase().includes(G)||((ue=(se=V.deal)==null?void 0:se.deal_name)==null?void 0:ue.toLowerCase().includes(G))||`${((_e=V.contact)==null?void 0:_e.first_name)||""} ${((Se=V.contact)==null?void 0:Se.last_name)||""}`.toLowerCase().includes(G),X=s==="all"||s==="active"&&V.status!=="done"||s==="todo"&&V.status==="todo"||s==="in_progress"&&V.status==="in_progress"||s==="done"&&V.status==="done"||s==="overdue"&&V.status!=="done"&&V.due_date&&S1(Uc(V.due_date))&&!Gd(Uc(V.due_date)),Q=m==="all"||V.priority===m,re=_==="all"||_==="no_deal"&&!V.deal_id||V.deal_id===_;return W&&X&&Q&&re}):[],[t,a,s,m,_]),B=P.useMemo(()=>{if(!t)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const V=t.filter(G=>G.status!=="done");return{total:V.length,overdue:V.filter(G=>G.due_date&&S1(Uc(G.due_date))&&!Gd(Uc(G.due_date))).length,dueToday:V.filter(G=>G.due_date&&Gd(Uc(G.due_date))).length,dueThisWeek:V.filter(G=>G.due_date&&RHe(Uc(G.due_date))).length,completed:t.filter(G=>G.status==="done").length}},[t]);return o.jsx(E1,{children:o.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[o.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),o.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsxs(Ut,{variant:"outline",size:"sm",onClick:()=>R(!0),children:[o.jsx(KRe,{className:"h-4 w-4 mr-1"}),"Templates"]}),o.jsxs(Ut,{size:"sm",onClick:()=>C(!0),children:[o.jsx(xm,{className:"h-4 w-4 mr-1"}),"New Task"]})]})]}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[o.jsxs("button",{onClick:()=>f("active"),className:`p-3 rounded-lg border text-left transition-colors ${s==="active"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[o.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs font-medium",children:[o.jsx(AU,{className:"h-3.5 w-3.5"}),"Active"]}),o.jsx("p",{className:"text-xl font-bold mt-1",children:B.total})]}),o.jsxs("button",{onClick:()=>f("overdue"),className:`p-3 rounded-lg border text-left transition-colors ${s==="overdue"?"border-destructive bg-destructive/5":"hover:bg-muted/50"}`,children:[o.jsxs("div",{className:"flex items-center gap-2 text-destructive text-xs font-medium",children:[o.jsx(CC,{className:"h-3.5 w-3.5"}),"Overdue"]}),o.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:B.overdue})]}),o.jsxs("button",{onClick:()=>{f("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs font-medium",children:[o.jsx(mc,{className:"h-3.5 w-3.5"}),"Due Today"]}),o.jsx("p",{className:"text-xl font-bold mt-1",children:B.dueToday})]}),o.jsxs("button",{onClick:()=>{f("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2 text-blue-600 text-xs font-medium",children:[o.jsx(Zf,{className:"h-3.5 w-3.5"}),"This Week"]}),o.jsx("p",{className:"text-xl font-bold mt-1",children:B.dueThisWeek})]}),o.jsxs("button",{onClick:()=>f("done"),className:`p-3 rounded-lg border text-left transition-colors ${s==="done"?"border-emerald-500 bg-emerald-500/5":"hover:bg-muted/50"}`,children:[o.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 text-xs font-medium",children:[o.jsx(xc,{className:"h-3.5 w-3.5"}),"Completed"]}),o.jsx("p",{className:"text-xl font-bold mt-1",children:B.completed})]})]}),o.jsxs("div",{className:"flex flex-col md:flex-row gap-3 items-start md:items-center",children:[o.jsxs("div",{className:"relative flex-1 max-w-sm",children:[o.jsx($y,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),o.jsx(Ur,{placeholder:"Search tasks...",value:a,onChange:V=>c(V.target.value),className:"pl-9"})]}),o.jsxs(Ba,{value:m,onValueChange:x,children:[o.jsx(ja,{className:"w-[130px]",children:o.jsx(za,{placeholder:"Priority"})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"all",children:"All Priorities"}),o.jsx(wn,{value:"urgent",children:"🔴 Urgent"}),o.jsx(wn,{value:"high",children:"🟠 High"}),o.jsx(wn,{value:"medium",children:"🟡 Medium"}),o.jsx(wn,{value:"low",children:"🟢 Low"})]})]}),o.jsxs(Ba,{value:_,onValueChange:T,children:[o.jsx(ja,{className:"w-[160px]",children:o.jsx(za,{placeholder:"Deal"})}),o.jsxs(Ia,{children:[o.jsx(wn,{value:"all",children:"All Deals"}),o.jsx(wn,{value:"no_deal",children:"No Deal"}),D.map(V=>o.jsx(wn,{value:V.id,children:V.name},V.id))]})]}),o.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[o.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:o.jsx(AU,{className:"h-4 w-4"})}),o.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:o.jsx(fG,{className:"h-4 w-4"})}),o.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:o.jsx(Zf,{className:"h-4 w-4"})})]})]}),e?o.jsx("div",{className:"flex items-center justify-center py-20",children:o.jsx("div",{className:"animate-spin h-8 w-8 border-2 border-primary border-t-transparent rounded-full"})}):o.jsxs(o.Fragment,{children:[n==="list"&&o.jsx(kIt,{tasks:M}),n==="kanban"&&o.jsx(IIt,{tasks:M}),n==="calendar"&&o.jsx(NIt,{tasks:M})]}),o.jsx(pEe,{open:E,onOpenChange:C}),o.jsx(LIt,{open:N,onOpenChange:R,stages:r||[]})]})})}const v8t={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"},b8t={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 OIt(t=!0){return wr({queryKey:["marketplace-categories",t],queryFn:async()=>{let e=Le.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 w8t(){const t=Nr();return Cr({mutationFn:async e=>{const{data:r,error:n}=await Le.from("marketplace_categories").insert([e]).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),Jt.success("Category created successfully")},onError:e=>{Jt.error("Failed to create category: "+e.message)}})}function S8t(){const t=Nr();return Cr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Le.from("marketplace_categories").update(r).eq("id",e).select().single();if(i)throw i;return n},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),Jt.success("Category updated successfully")},onError:e=>{Jt.error("Failed to update category: "+e.message)}})}function T8t(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("marketplace_categories").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-categories"]}),Jt.success("Category deleted successfully")},onError:e=>{Jt.error("Failed to delete category: "+e.message)}})}function MIt(t,e=!0){return wr({queryKey:["marketplace-products",t,e],queryFn:async()=>{let r=Le.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 E8t(t){return wr({queryKey:["marketplace-product",t],queryFn:async()=>{const{data:e,error:r}=await Le.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 A8t(){const t=Nr();return Cr({mutationFn:async e=>{const{data:r,error:n}=await Le.from("marketplace_products").insert([e]).select().single();if(n)throw n;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-products"]}),Jt.success("Product created successfully")},onError:e=>{Jt.error("Failed to create product: "+e.message)}})}function k8t(){const t=Nr();return Cr({mutationFn:async({id:e,...r})=>{const{data:n,error:i}=await Le.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]}),Jt.success("Product updated successfully")},onError:e=>{Jt.error("Failed to update product: "+e.message)}})}function C8t(){const t=Nr();return Cr({mutationFn:async e=>{const{error:r}=await Le.from("marketplace_products").delete().eq("id",e);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["marketplace-products"]}),Jt.success("Product deleted successfully")},onError:e=>{Jt.error("Failed to delete product: "+e.message)}})}function j8t(){const t=Nr();return Cr({mutationFn:async e=>{const{data:r,error:n}=await Le.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 I8t(){const t=Nr();return Cr({mutationFn:async({id:e,productId:r})=>{const{error:n}=await Le.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]}),Jt.success("Image deleted successfully")},onError:e=>{Jt.error("Failed to delete image: "+e.message)}})}function P8t(){const t=Nr();return Cr({mutationFn:async({imageId:e,productId:r})=>{const{error:n}=await Le.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",r);if(n)throw n;const{error:i}=await Le.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]}),Jt.success("Primary image updated")},onError:e=>{Jt.error("Failed to set primary image: "+e.message)}})}function N8t(){const t=Nr();return Cr({mutationFn:async e=>{const{data:r,error:n}=await Le.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]}),Jt.success("Variant added successfully")}})}function R8t(){const t=Nr();return Cr({mutationFn:async({id:e,productId:r})=>{const{error:n}=await Le.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]}),Jt.success("Variant deleted successfully")}})}function L8t(){const t=Nr();return Cr({mutationFn:async({productId:e,videoUrl:r})=>{await Le.from("marketplace_product_videos").delete().eq("product_id",e);const{data:n,error:i}=await Le.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]}),Jt.success("Video updated successfully")}})}function D8t(t){const{isAdmin:e}=qn();return wr({queryKey:["marketplace-orders",t,e],queryFn:async()=>{let r=Le.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(f=>f.user_id))],{data:c}=await Le.from("profiles").select("id, name, email").in("id",a),s=new Map((c==null?void 0:c.map(f=>[f.id,f]))||[]);return n.map(f=>({...f,user:s.get(f.user_id)}))}return n}})}function O8t(){const{user:t}=qn();return wr({queryKey:["my-marketplace-orders",t==null?void 0:t.id],queryFn:async()=>{const{data:e,error:r}=await Le.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 M8t(t){return wr({queryKey:["marketplace-order",t],queryFn:async()=>{const{data:e,error:r}=await Le.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 F8t(){const t=Nr(),{user:e}=qn();return Cr({mutationFn:async({orderId:r,status:n,notes:i,trackingNumber:a,trackingUrl:c,previousStatus:s})=>{const f={status:n};a!==void 0&&(f.tracking_number=a),c!==void 0&&(f.tracking_url=c);const{error:m}=await Le.from("marketplace_orders").update(f).eq("id",r);if(m)throw m;const{error:x}=await Le.from("marketplace_order_status_history").insert({order_id:r,status:n,notes:i,created_by:e==null?void 0:e.id});if(x)throw x;if(["shipped","in_production","processing","completed"].includes(n)&&n!==s)try{await Le.functions.invoke("marketplace-order-notify",{body:{orderId:r,notificationType:n==="shipped"?"shipped":"status_update",newStatus:n,trackingNumber:a,trackingUrl:c}})}catch(T){console.error("Failed to send notification email:",T)}},onSuccess:(r,n)=>{t.invalidateQueries({queryKey:["marketplace-orders"]}),t.invalidateQueries({queryKey:["marketplace-order",n.orderId]}),t.invalidateQueries({queryKey:["my-marketplace-orders"]}),Jt.success("Order status updated")},onError:r=>{Jt.error("Failed to update order: "+r.message)}})}function B8t(){const t=Nr();return Cr({mutationFn:async({itemId:e,proofUrl:r,proofNotes:n,orderId:i})=>{const{error:a}=await Le.from("marketplace_order_items").update({proof_url:r,proof_notes:n,proof_status:"pending"}).eq("id",e);if(a)throw a;await Le.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",i);try{await Le.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"]}),Jt.success("Proof uploaded & customer notified")}})}function z8t(){const t=Nr();return Cr({mutationFn:async({itemId:e,orderId:r})=>{const{error:n}=await Le.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"]}),Jt.success("Proof approved")}})}function $8t(){const t=Nr();return Cr({mutationFn:async({itemId:e,orderId:r,reason:n})=>{const{error:i}=await Le.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"]}),Jt.success("Proof rejected - please upload a new proof")}})}function FIt(){const t=ma(),[e,r]=P.useState(null),{data:n,isLoading:i}=MIt(e||void 0,!0),{data:a,isLoading:c}=OIt(!0),{cartItems:s}=z_e(),f=s.reduce((x,_)=>x+_.quantity,0),m=x=>{t(`/marketplace/${x.id}`)};return i||c?o.jsx(E1,{title:"Marketplace",children:o.jsxs("div",{className:"space-y-6",children:[o.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(x=>o.jsx(ol,{className:"h-10 w-24 flex-shrink-0"},x))}),o.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:[1,2,3,4].map(x=>o.jsx(ol,{className:"h-72 w-full"},x))})]})}):o.jsx(E1,{title:"Marketplace",children:o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),o.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),o.jsxs(Ut,{variant:"outline",onClick:()=>t("/marketplace/cart"),className:"relative",children:[o.jsx(Zhe,{className:"h-4 w-4 mr-2"}),"Cart",f>0&&o.jsx(us,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:f})]})]}),a&&a.length>0&&o.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[o.jsx(Ut,{variant:e===null?"default":"outline",size:"sm",onClick:()=>r(null),children:"All"}),a.map(x=>o.jsx(Ut,{variant:e===x.id?"default":"outline",size:"sm",onClick:()=>r(x.id),children:x.name},x.id))]}),n&&n.length>0?o.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:n.map(x=>{var _;return o.jsxs(Hn,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>m(x),children:[o.jsxs("div",{className:"aspect-square bg-muted relative",children:[x.images&&x.images.length>0?o.jsx("img",{src:((_=x.images.find(T=>T.is_primary))==null?void 0:_.image_url)||x.images[0].image_url,alt:x.name,className:"w-full h-full object-cover"}):o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsx(AJ,{className:"h-12 w-12 text-muted-foreground"})}),x.category&&o.jsx(us,{className:"absolute top-2 left-2",variant:"secondary",children:x.category.name})]}),o.jsxs(ii,{className:"p-4",children:[o.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:x.name}),x.description&&o.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:x.description}),o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("span",{className:"font-bold text-lg",children:["$",Number(x.base_price).toFixed(2)]}),x.variants&&x.variants.length>0&&o.jsxs("span",{className:"text-xs text-muted-foreground",children:[x.variants.length," options"]})]})]})]},x.id)})}):o.jsxs("div",{className:"text-center py-12",children:[o.jsx(AJ,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),o.jsx("p",{className:"text-muted-foreground",children:"No products available yet."})]})]})})}const pj={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 O2({delay:t,x:e,y:r,size:n}){return o.jsx(pr.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 BIt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:a,agentName:c,agentPhotoUrl:s,agentPhone:f,agentEmail:m,agentBrokerage:x,propertyPhotoUrl:_,videoUrl:T}=t,E=pj[e];return o.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:[o.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[o.jsx(pr.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"}}),o.jsx(pr.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"}}),o.jsx(O2,{delay:0,x:"15%",y:"20%",size:8}),o.jsx(O2,{delay:1,x:"80%",y:"30%",size:6}),o.jsx(O2,{delay:2,x:"60%",y:"70%",size:10}),o.jsx(O2,{delay:.5,x:"25%",y:"80%",size:7}),o.jsx(O2,{delay:1.5,x:"70%",y:"15%",size:5})]}),o.jsxs(pr.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:[o.jsxs(pr.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:[o.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:o.jsx(pr.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"}})}),o.jsxs("div",{className:"px-8 py-10 text-center",children:[o.jsxs(pr.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:[o.jsx(pr.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"}}),o.jsx("span",{className:"text-4xl",children:E.icon})]}),e==="home_anniversary"&&i!==null&&i>0&&o.jsx(pr.div,{className:"inline-block mb-4",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.4,delay:.6},children:o.jsxs("span",{className:"text-sm font-semibold tracking-[0.25em] uppercase text-blue-400 dark:text-blue-300",children:[i," ",i===1?"Year":"Years"]})}),o.jsx(pr.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:E.title[0]}),E.title[1]&&o.jsx(pr.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:E.title[1]}),o.jsxs(pr.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,delay:1},children:[o.jsx("p",{className:"text-xl font-medium text-slate-700 dark:text-slate-200 mb-1",children:r}),n&&o.jsx("p",{className:"text-sm text-slate-400 dark:text-slate-500 mb-6",children:n})]}),o.jsx(pr.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"}}),_&&o.jsx(pr.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:o.jsx("img",{src:_,alt:"Property",className:"w-full h-48 object-cover"})}),T&&o.jsx(pr.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:o.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),o.jsx(pr.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||E.defaultMessage}),o.jsxs(pr.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:[o.jsxs("div",{className:"flex items-center justify-center gap-3",children:[s?o.jsx(pr.img,{src:s,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}}):o.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:o.jsx("span",{className:"text-sm font-semibold text-slate-600 dark:text-slate-300",children:c.charAt(0)})}),o.jsxs("div",{className:"text-left",children:[o.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:c}),x&&o.jsx("p",{className:"text-xs text-slate-400 dark:text-slate-500",children:x})]})]}),o.jsxs("div",{className:"flex items-center justify-center gap-3 mt-4",children:[f&&o.jsxs(pr.a,{href:`tel:${f}`,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:[o.jsx(zi,{className:"h-3.5 w-3.5"})," Call"]}),m&&o.jsxs(pr.a,{href:`mailto:${m}`,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:[o.jsx(Bi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),o.jsx(pr.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 Hz({delay:t,x:e,y:r,color:n,size:i}){return o.jsx(pr.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 M2({delay:t,x:e,y:r}){return o.jsx(pr.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 joe={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 zIt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:a,agentName:c,agentPhotoUrl:s,agentPhone:f,agentEmail:m,agentBrokerage:x,propertyPhotoUrl:_,videoUrl:T}=t,E=pj[e],C=joe[e]||joe.home_anniversary;return o.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${C.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[o.jsx(Hz,{delay:0,x:"10%",y:"10%",color:C.orbs[0],size:200}),o.jsx(Hz,{delay:1,x:"70%",y:"60%",color:C.orbs[1],size:180}),o.jsx(Hz,{delay:2,x:"50%",y:"20%",color:C.orbs[2],size:150}),o.jsx(M2,{delay:0,x:"20%",y:"25%"}),o.jsx(M2,{delay:.8,x:"75%",y:"15%"}),o.jsx(M2,{delay:1.6,x:"85%",y:"65%"}),o.jsx(M2,{delay:2.4,x:"10%",y:"75%"}),o.jsx(M2,{delay:.4,x:"45%",y:"85%"}),o.jsxs(pr.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:[o.jsxs(pr.div,{className:"relative rounded-3xl overflow-hidden",initial:{scale:.9},animate:{scale:1},transition:{duration:.5,delay:.2,type:"spring",stiffness:150},children:[o.jsx(pr.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%"}}),o.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:[o.jsxs(pr.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:[o.jsx(pr.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"}}),o.jsx("span",{className:"text-4xl relative z-10",children:E.icon})]}),e==="home_anniversary"&&i!==null&&i>0&&o.jsxs(pr.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:[o.jsx(pr.span,{className:"text-3xl font-black text-white",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.8},children:i}),o.jsx("span",{className:"text-xs font-semibold text-violet-200 uppercase tracking-widest",children:i===1?"Year":"Years"})]}),o.jsx(pr.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:E.title[0]}),E.title[1]&&o.jsx(pr.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:E.title[1]}),o.jsx(pr.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:E.emojis.slice(0,3).join("")}),o.jsxs(pr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[o.jsx("p",{className:"text-xl font-semibold text-white/90 mb-1",children:r}),n&&o.jsxs("p",{className:"text-sm text-violet-300/70 mb-6 flex items-center justify-center gap-1.5",children:[o.jsx(Ma,{className:"h-3.5 w-3.5"}),n]})]}),_&&o.jsx(pr.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:o.jsx("img",{src:_,alt:"Property",className:"w-full h-48 object-cover"})}),T&&o.jsx(pr.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:o.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),o.jsx(pr.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:o.jsx("p",{className:"text-sm text-violet-100/80 leading-relaxed",children:a||E.defaultMessage})}),o.jsxs(pr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[o.jsxs("div",{className:"flex items-center justify-center gap-3",children:[s?o.jsx(pr.img,{src:s,alt:c,className:"h-12 w-12 rounded-xl object-cover ring-2 ring-violet-500/40 shadow-lg",whileHover:{scale:1.1}}):o.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:o.jsx("span",{className:"text-sm font-bold text-white",children:c.charAt(0)})}),o.jsxs("div",{className:"text-left",children:[o.jsx("p",{className:"text-sm font-bold text-white",children:c}),x&&o.jsx("p",{className:"text-xs text-violet-300/60",children:x})]})]}),o.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[f&&o.jsxs(pr.a,{href:`tel:${f}`,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:[o.jsx(zi,{className:"h-3.5 w-3.5"})," Call Me"]}),m&&o.jsxs(pr.a,{href:`mailto:${m}`,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:[o.jsx(Bi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),o.jsx(pr.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 $It({emoji:t,delay:e,x:r,duration:n}){return o.jsx(pr.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 Ioe={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 UIt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:a,agentName:c,agentPhotoUrl:s,agentPhone:f,agentEmail:m,agentBrokerage:x,propertyPhotoUrl:_,videoUrl:T}=t,E=pj[e],C=Ioe[e]||Ioe.home_anniversary;return o.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${C.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[E.emojis.map((N,R)=>o.jsx($It,{emoji:N,delay:R*1.2,x:`${15+R*14}%`,duration:5+R%3},R)),o.jsx(pr.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"}}),o.jsxs(pr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.7},children:[o.jsxs(pr.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:[o.jsxs(pr.div,{className:`h-28 bg-gradient-to-r ${C.header} relative overflow-hidden`,children:[o.jsx(pr.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"}}),o.jsx(pr.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:E.emojis[0]}),o.jsx(pr.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:E.emojis[1]}),o.jsx(pr.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:E.emojis[2]})]}),o.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[o.jsx(pr.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:o.jsx(pr.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:o.jsx("span",{className:"text-3xl",children:E.icon})})}),e==="home_anniversary"&&i!==null&&i>0&&o.jsx(pr.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:o.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${C.accent}`,children:[o.jsx(pr.span,{className:"text-5xl font-black",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.8},children:i}),o.jsx("span",{className:"text-sm font-semibold",children:i===1?"year":"wonderful years"})]})}),o.jsxs(pr.h1,{className:`text-3xl font-bold ${C.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[E.title.join(" ")," ",E.emojis[4]]}),o.jsxs(pr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[o.jsx("p",{className:`text-lg font-semibold ${C.text} mb-1`,children:r}),n&&o.jsxs("p",{className:`text-sm ${C.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[o.jsx(na,{className:"h-3 w-3"}),n]})]}),_&&o.jsx(pr.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:o.jsx("img",{src:_,alt:"Property",className:"w-full h-48 object-cover"})}),T&&o.jsx(pr.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:o.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),o.jsx(pr.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:o.jsxs("p",{className:`text-sm ${C.text} leading-relaxed italic`,children:['"',a||E.defaultMessage,'"']})}),o.jsxs(pr.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.5},children:[o.jsxs("div",{className:"flex items-center gap-3 justify-center",children:[s?o.jsx(pr.img,{src:s,alt:c,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):o.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${C.header} flex items-center justify-center shadow-md`,children:o.jsx("span",{className:"text-sm font-bold text-white",children:c.charAt(0)})}),o.jsxs("div",{className:"text-left",children:[o.jsx("p",{className:`text-sm font-bold ${C.accent}`,children:c}),x&&o.jsx("p",{className:`text-xs ${C.text} opacity-60`,children:x})]})]}),o.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[f&&o.jsxs(pr.a,{href:`tel:${f}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${C.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[o.jsx(zi,{className:"h-3.5 w-3.5"})," Call"]}),m&&o.jsxs(pr.a,{href:`mailto:${m}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${C.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[o.jsx(Bi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),o.jsx(pr.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 GN({delay:t,x:e,y:r,size:n,color:i}){return o.jsx(pr.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 Wz({delay:t,x:e,y:r,size:n}){return o.jsx(pr.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 Poe={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 VIt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:a,agentName:c,agentPhotoUrl:s,agentPhone:f,agentEmail:m,agentBrokerage:x,propertyPhotoUrl:_,videoUrl:T}=t,E=pj[e],C=Poe[e]||Poe.home_anniversary;return o.jsxs("div",{className:"min-h-screen bg-slate-950 flex items-center justify-center p-4 overflow-hidden relative",children:[o.jsx(GN,{delay:0,x:"5%",y:"10%",size:300,color:C.mesh[0]}),o.jsx(GN,{delay:2,x:"60%",y:"50%",size:250,color:C.mesh[1]}),o.jsx(GN,{delay:4,x:"30%",y:"70%",size:200,color:C.mesh[2]}),o.jsx(GN,{delay:1,x:"80%",y:"15%",size:180,color:C.mesh[0]}),o.jsx(Wz,{delay:0,x:"15%",y:"20%",size:100}),o.jsx(Wz,{delay:3,x:"70%",y:"60%",size:140}),o.jsx(Wz,{delay:6,x:"40%",y:"10%",size:80}),o.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")`}}),o.jsxs(pr.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:[o.jsxs(pr.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${C.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[o.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:o.jsx(pr.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"}})}),o.jsxs("div",{className:"px-8 py-10 text-center",children:[o.jsxs(pr.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:[o.jsx(pr.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"}}),o.jsx(pr.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:E.icon})]}),e==="home_anniversary"&&i!==null&&i>0&&o.jsxs(pr.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:[o.jsx(pr.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:i}),o.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${C.accent}`,children:i===1?"Year":"Years"})]}),o.jsx(pr.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:E.title[0]}),E.title[1]&&o.jsx(pr.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:E.title[1]}),o.jsxs(pr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[o.jsx("p",{className:"text-xl font-medium text-white/80 mb-1",children:r}),n&&o.jsxs("p",{className:"text-sm text-white/30 mb-6 flex items-center justify-center gap-1.5",children:[o.jsx(na,{className:"h-3 w-3"})," ",n]})]}),o.jsx(pr.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"}}),_&&o.jsx(pr.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:o.jsx("img",{src:_,alt:"Property",className:"w-full h-48 object-cover"})}),T&&o.jsx(pr.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:o.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),o.jsx(pr.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:o.jsxs("p",{className:"text-sm text-white/60 leading-relaxed italic",children:['"',a||E.defaultMessage,'"']})}),o.jsxs(pr.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:[o.jsxs("div",{className:"flex items-center justify-center gap-3",children:[s?o.jsx(pr.img,{src:s,alt:c,className:"h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10",whileHover:{scale:1.08}}):o.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white/[0.08] border border-white/[0.1] flex items-center justify-center",children:o.jsx("span",{className:"text-sm font-semibold text-white/60",children:c.charAt(0)})}),o.jsxs("div",{className:"text-left",children:[o.jsx("p",{className:"text-sm font-semibold text-white/80",children:c}),x&&o.jsx("p",{className:"text-xs text-white/30",children:x})]})]}),o.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[f&&o.jsxs(pr.a,{href:`tel:${f}`,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:[o.jsx(zi,{className:"h-3.5 w-3.5"})," Call"]}),m&&o.jsxs(pr.a,{href:`mailto:${m}`,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:[o.jsx(Bi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),o.jsx(pr.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 Kz({delay:t,x:e,angle:r,color:n}){return o.jsx(pr.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 HN({delay:t,x:e}){return o.jsx(pr.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 Noe={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 qIt(t){const{cardType:e,recipientName:r,propertyAddress:n,anniversaryYears:i,customMessage:a,agentName:c,agentPhotoUrl:s,agentPhone:f,agentEmail:m,agentBrokerage:x,propertyPhotoUrl:_,videoUrl:T}=t,E=pj[e],C=Noe[e]||Noe.home_anniversary;return o.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${C.gradient} flex items-center justify-center p-4 overflow-hidden relative`,children:[o.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.04)_0%,transparent_60%)]"}),o.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom,rgba(0,0,0,0.6)_0%,transparent_60%)]"}),o.jsx(Kz,{delay:0,x:"20%",angle:15,color:C.stripe}),o.jsx(Kz,{delay:2,x:"75%",angle:-12,color:C.stripe}),o.jsx(Kz,{delay:4,x:"50%",angle:5,color:C.stripe}),o.jsx(HN,{delay:0,x:"30%"}),o.jsx(HN,{delay:1.5,x:"60%"}),o.jsx(HN,{delay:3,x:"45%"}),o.jsx(HN,{delay:.7,x:"75%"}),o.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")`}}),o.jsxs(pr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[o.jsx(pr.div,{className:"relative overflow-hidden",initial:{y:50},animate:{y:0},transition:{duration:.8,delay:.3,ease:[.16,1,.3,1]},children:o.jsxs("div",{className:"px-8 py-12 text-center",children:[o.jsx(pr.div,{className:"mx-auto mb-8 relative",initial:{scale:0},animate:{scale:1},transition:{duration:.8,delay:.5,type:"spring",stiffness:100},children:o.jsx(pr.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${C.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:o.jsx("span",{className:"text-4xl",children:E.icon})})}),e==="home_anniversary"&&i!==null&&i>0&&o.jsxs(pr.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[o.jsx(pr.span,{className:`text-6xl font-black bg-gradient-to-r ${C.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:i}),o.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:i===1?"Year":"Years"})]}),o.jsx("div",{className:"overflow-hidden mb-2",children:o.jsx(pr.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:E.title[0]})}),E.title[1]&&o.jsx("div",{className:"overflow-hidden mb-8",children:o.jsx(pr.h2,{className:`text-5xl font-black bg-gradient-to-r ${C.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:E.title[1]})}),o.jsxs(pr.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.1,duration:.6},children:[o.jsx("p",{className:"text-lg font-light text-white/70 tracking-wide",children:r}),n&&o.jsxs("p",{className:"text-xs text-white/25 mt-1 flex items-center justify-center gap-1",children:[o.jsx(na,{className:"h-3 w-3"})," ",n]})]}),o.jsxs(pr.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[o.jsx(pr.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"}}),o.jsx(pr.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),o.jsx(pr.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"}})]}),_&&o.jsxs(pr.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:[o.jsx("img",{src:_,alt:"Property",className:"w-full h-48 object-cover"}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-950/30 to-transparent pointer-events-none"})]}),T&&o.jsx(pr.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:o.jsx("iframe",{src:`${T}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),o.jsx(pr.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||E.defaultMessage}),o.jsxs(pr.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:[o.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[s?o.jsx(pr.img,{src:s,alt:c,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):o.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${C.accent} flex items-center justify-center shadow-xl`,children:o.jsx("span",{className:"text-sm font-bold text-slate-900",children:c.charAt(0)})}),o.jsxs("div",{className:"text-left",children:[o.jsx("p",{className:"text-sm font-medium text-white/70",children:c}),x&&o.jsx("p",{className:"text-[11px] text-white/25",children:x})]})]}),o.jsxs("div",{className:"flex items-center justify-center gap-2",children:[f&&o.jsxs(pr.a,{href:`tel:${f}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${C.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:[o.jsx(zi,{className:"h-3.5 w-3.5"})," Call"]}),m&&o.jsxs(pr.a,{href:`mailto:${m}`,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:[o.jsx(Bi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),o.jsx(pr.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 mEe(){const{shareToken:t}=hp(),{data:e,isLoading:r,error:n}=wr({queryKey:["public-sendable-card",t],queryFn:async()=>{const{data:c,error:s}=await Le.from("sendable_cards").select("*").eq("share_token",t).single();if(s)throw s;return c},enabled:!!t});if(P.useEffect(()=>{if(!e)return;const c=(e.recipient_name||"").trim().split(/\s+/)[0],f={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?`${f}, ${c}!`:`${f}!`},[e]),P.useEffect(()=>{t&&Le.rpc("log_sendable_card_view",{p_share_token:t}).then(({error:c})=>{c&&console.error("Error tracking view:",c)})},[t]),r)return o.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:o.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[o.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),o.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(n||!e)return o.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),o.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()-j1(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 o.jsx(zIt,{...a});case"warm":return o.jsx(UIt,{...a});case"glass":return o.jsx(VIt,{...a});case"cinematic":return o.jsx(qIt,{...a});case"elegant":default:return o.jsx(BIt,{...a})}}const GIt=Object.freeze(Object.defineProperty({__proto__:null,default:mEe},Symbol.toStringTag,{value:"Module"})),gEe=()=>{const t=Wi();return P.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]),o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),o.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),o.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})};function HIt(){return P.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),o.jsxs(ak,{children:[o.jsx(Pe,{path:"/c/:shareToken",element:o.jsx(mEe,{})}),o.jsx(Pe,{path:"*",element:o.jsx(gEe,{})})]})}function WIt(t,e){return e?t.find(r=>r.id===e)??null:null}const Yz={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"},KIt=["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 YIt(t,e,r){const[n,i,a]=t.split("-").map(Number),[c,s]=e.split(":").map(Number),f=Date.UTC(n,i-1,a,c,s),m=new Intl.DateTimeFormat("en-US",{timeZone:r,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),x=Object.fromEntries(m.formatToParts(new Date(f)).filter(T=>T.type!=="literal").map(T=>[T.type,T.value])),_=Date.UTC(Number(x.year),Number(x.month)-1,Number(x.day),Number(x.hour)%24,Number(x.minute));return f+(f-_)}function Zz(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 yEe({slugOverride:t}){const e=hp(),r=t||e.slug,[n]=B0(),i=n.get("type"),[a,c]=P.useState("types"),[s,f]=P.useState(null),[m,x]=P.useState(null),[_,T]=P.useState(null),[E,C]=P.useState(new Date),[N,R]=P.useState({name:"",email:"",phone:"",message:""}),[D,M]=P.useState(!1),[B,V]=P.useState(null),[G,W]=P.useState(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"America/New_York"}catch{return"America/New_York"}}),{data:X,isLoading:Q}=wr({queryKey:["public-booking-settings",r],queryFn:async()=>{const{data:be,error:We}=await Le.from("agent_booking_settings").select("*").eq("slug",r).eq("is_active",!0).single();if(We)throw We;return be},enabled:!!r}),{data:re}=wr({queryKey:["public-booking-profile",X==null?void 0:X.user_id],queryFn:async()=>{const{data:be,error:We}=await Le.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",X.user_id).single();if(We)throw We;return be},enabled:!!(X!=null&&X.user_id)}),{data:se=[]}=wr({queryKey:["public-booking-types",X==null?void 0:X.user_id],queryFn:async()=>{const{data:be,error:We}=await Le.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",X.user_id).eq("is_active",!0).eq("is_coaching_only",!1).order("sort_order");if(We)throw We;return be},enabled:!!(X!=null&&X.user_id)});P.useEffect(()=>{if(!i||s||se.length===0)return;const be=WIt(se,i);be&&(f(be),c("date"))},[i,se,s]);const ue=Ri(E,"yyyy-MM"),{data:_e={},isFetching:Se}=wr({queryKey:["public-availability-map",r,s==null?void 0:s.id,ue],enabled:!!r&&!!s,staleTime:6e4,queryFn:async()=>{const be=new Date(E.getFullYear(),E.getMonth(),1),We=Hy(new Date),rt=pk(We,be)?We:be,at=new Date(E.getFullYear(),E.getMonth()+1,0),Et=Math.max(1,Math.round((at.getTime()-rt.getTime())/864e5)+1),{data:_t,error:Vt}=await Le.functions.invoke("agent-booking",{body:{action:"availability",slug:r,booking_type_id:s.id,start:Ri(rt,"yyyy-MM-dd"),days:Math.min(Et,90)}});if(Vt)throw Vt;if(_t!=null&&_t.error)throw new Error(_t.error);return(_t==null?void 0:_t.availability)||{}}}),ve=be=>{const We=Hy(new Date),rt=Tl(We,(X==null?void 0:X.max_advance_days)||30);return V9(be,We)||pk(be,rt)?!1:(_e[Ri(be,"yyyy-MM-dd")]||[]).length>0},Oe=P.useMemo(()=>m?_e[Ri(m,"yyyy-MM-dd")]||[]:[],[m,_e]),Ae=P.useMemo(()=>{const be=E.getFullYear(),We=E.getMonth(),rt=new Date(be,We,1),at=new Date(be,We+1,0),Et=rt.getDay(),_t=[];for(let Vt=0;Vt{var be,We;if(!(!s||!m||!_||!N.name||!X)){M(!0);try{const rt=Ri(m,"yyyy-MM-dd"),{data:at,error:Et}=await Le.functions.invoke("agent-booking",{body:{action:"create",slug:r,booking_type_id:s.id,date:rt,time:_,guest_name:N.name,guest_email:N.email||null,guest_phone:N.phone||null,guest_message:N.message||null,guest_timezone:G}});if(Et){let mt=Et.message;try{const Pt=await((We=(be=Et.context)==null?void 0:be.json)==null?void 0:We.call(be));Pt!=null&&Pt.error&&(mt=Pt.error)}catch{}throw new Error(mt)}if(at!=null&&at.error)throw new Error(at.error);const _t=(at==null?void 0:at.end_time)||_,Vt=at!=null&&at.manage_token?`${window.location.origin}/booking/manage/${at.manage_token}`:null;V(Vt),Le.functions.invoke("booking-notify",{body:{agentUserId:X.user_id,guestName:N.name,guestEmail:N.email||null,guestPhone:N.phone||null,guestMessage:N.message||null,bookingTypeName:s.name,bookingDate:rt,startTime:_,endTime:_t,durationMinutes:s.duration_minutes,meetingLink:X.meeting_link||null,manageUrl:Vt}}).catch(mt=>console.error("Booking notify error:",mt)),c("confirmed")}catch(rt){Jt.error("Failed to book: "+rt.message)}finally{M(!1)}}},ge=be=>{const[We,rt]=be.split(":").map(Number),at=We>=12?"PM":"AM";return`${We%12||12}:${rt.toString().padStart(2,"0")} ${at}`},Ne=(X==null?void 0:X.timezone)||"America/New_York",Ie=G!==Ne,Te=(be,We)=>{if(!Ie)return ge(We);try{return new Intl.DateTimeFormat("en-US",{timeZone:G,hour:"numeric",minute:"2-digit"}).format(new Date(YIt(be,We,Ne)))}catch{return ge(We)}};return Q?o.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center",children:o.jsxs("div",{className:"flex flex-col items-center gap-3",children:[o.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[#406E71] border-t-transparent"}),o.jsx("p",{className:"text-sm text-slate-500",children:"Loading booking page..."})]})}):X?o.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8]",children:[o.jsx("div",{className:"h-1.5 bg-gradient-to-r from-[#406E71] via-[#5a9a9d] to-[#2a4c64]"}),o.jsxs("div",{className:"max-w-lg mx-auto px-4 py-6 sm:py-10",children:[o.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden mb-6",children:[o.jsx("div",{className:"relative bg-gradient-to-r from-[#406E71] to-[#2a4c64] px-6 pt-6 pb-12",children:o.jsxs("div",{className:"absolute inset-0 opacity-10",children:[o.jsx("div",{className:"absolute top-2 right-8 w-20 h-20 rounded-full border-2 border-white/30"}),o.jsx("div",{className:"absolute bottom-4 left-12 w-10 h-10 rounded-full border border-white/20"})]})}),o.jsx("div",{className:"relative -mt-10 px-6",children:o.jsxs("div",{className:"flex items-end gap-4",children:[re!=null&&re.avatar_url?o.jsx("img",{src:re.avatar_url,alt:(re==null?void 0:re.name)||"Agent",className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl object-cover border-4 border-white shadow-md"}):o.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:o.jsx(gc,{className:"h-10 w-10 text-white"})}),o.jsxs("div",{className:"pb-1.5",children:[o.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-slate-800 leading-tight",children:(re==null?void 0:re.name)||"Agent"}),(re==null?void 0:re.title)&&o.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:re.title})]})]})}),o.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(re==null?void 0:re.phone)&&o.jsxs("a",{href:`tel:${re.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:[o.jsx(zi,{className:"h-3.5 w-3.5"}),o.jsx("span",{className:"hidden sm:inline",children:re.phone}),o.jsx("span",{className:"sm:hidden",children:"Call"})]}),(re==null?void 0:re.email)&&o.jsxs("a",{href:`mailto:${re.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:[o.jsx(Bi,{className:"h-3.5 w-3.5"}),o.jsx("span",{className:"hidden sm:inline",children:re.email}),o.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),o.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:o.jsxs("div",{className:"p-5 sm:p-6",children:[a==="types"&&o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),o.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),o.jsx("div",{className:"space-y-2.5",children:se.map(be=>o.jsx("button",{onClick:()=>{f(be),c("date")},className:"w-full text-left group",children:o.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:be.color},children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[o.jsx("span",{className:"text-2xl shrink-0 mt-0.5",children:Yz[be.icon]||"📅"}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:"font-semibold text-sm text-slate-800 group-hover:text-[#406E71] transition-colors",children:be.name}),be.description&&o.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:be.description})]})]}),o.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:[o.jsx(mc,{className:"h-3 w-3"}),be.duration_minutes,"m"]})]})})},be.id))})]}),a==="date"&&s&&o.jsxs("div",{className:"space-y-5",children:[o.jsxs("button",{onClick:()=>{c("types"),x(null),T(null)},className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[o.jsx(By,{className:"h-3.5 w-3.5"})," Back to meeting types"]}),o.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl border",style:{borderColor:s.color+"40",backgroundColor:s.color+"08"},children:[o.jsx("span",{className:"text-xl",children:Yz[s.icon]||"📅"}),o.jsx("div",{className:"flex-1 min-w-0",children:o.jsx("p",{className:"font-semibold text-sm text-slate-800",children:s.name})}),o.jsxs("div",{className:"flex items-center gap-1 text-xs text-slate-500 font-medium",children:[o.jsx(mc,{className:"h-3 w-3"}),s.duration_minutes," min"]})]}),o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ri(E,"MMMM yyyy")}),o.jsxs("div",{className:"flex gap-1",children:[o.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:()=>C(new Date(E.getFullYear(),E.getMonth()-1)),children:o.jsx($m,{className:"h-4 w-4"})}),o.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:()=>C(new Date(E.getFullYear(),E.getMonth()+1)),children:o.jsx(th,{className:"h-4 w-4"})})]})]}),o.jsxs("div",{className:"grid grid-cols-7 gap-0.5 text-center",children:[["Su","Mo","Tu","We","Th","Fr","Sa"].map(be=>o.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:be},be)),Ae.map((be,We)=>{if(!be)return o.jsx("div",{},`pad-${We}`);const rt=ve(be),at=m&&Kl(be,m),Et=Kl(be,new Date);return o.jsx("button",{disabled:!rt,onClick:()=>{x(be),T(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${at?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":rt?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${Et&&!at?"ring-1 ring-[#406E71]/40":""}`,children:be.getDate()},be.toISOString())})]})]}),m&&o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Zf,{className:"h-4 w-4 text-[#406E71]"}),o.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ri(m,"EEEE, MMMM d")})]}),o.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl bg-slate-50 border border-slate-100 px-3 py-2",children:[o.jsx("span",{className:"text-[11px] text-slate-500",children:"Times shown in your timezone"}),o.jsx("select",{value:G,onChange:be=>W(be.target.value),className:"text-[11px] font-medium text-slate-700 bg-transparent focus:outline-none cursor-pointer",children:Array.from(new Set([G,Ne,...KIt])).map(be=>o.jsxs("option",{value:be,children:[be.replace(/_/g," ")," (",Zz(be),")"]},be))})]}),Se&&Oe.length===0?o.jsxs("div",{className:"text-center py-8 space-y-2",children:[o.jsx(Cu,{className:"h-6 w-6 text-slate-300 mx-auto animate-spin"}),o.jsx("p",{className:"text-sm text-slate-400",children:"Checking live availability…"})]}):Oe.length===0?o.jsxs("div",{className:"text-center py-8 space-y-2",children:[o.jsx(mc,{className:"h-8 w-8 text-slate-300 mx-auto"}),o.jsx("p",{className:"text-sm text-slate-400",children:"No available times on this day"}),o.jsx("p",{className:"text-xs text-slate-400",children:"Try selecting a different date"})]}):o.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-52 overflow-y-auto pr-1 custom-scrollbar",children:Oe.map(be=>{const We=_===be;return o.jsx("button",{onClick:()=>T(be),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${We?"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:Te(Ri(m,"yyyy-MM-dd"),be)},be)})}),_&&o.jsx(Ut,{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"&&s&&m&&_&&o.jsxs("div",{className:"space-y-5",children:[o.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:[o.jsx(By,{className:"h-3.5 w-3.5"})," Back"]}),o.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:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-lg",children:Yz[s.icon]||"📅"}),o.jsx("p",{className:"font-semibold text-sm text-slate-800",children:s.name})]}),o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-600",children:[o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(Zf,{className:"h-3.5 w-3.5 text-[#406E71]"}),Ri(m,"EEE, MMM d, yyyy")]}),o.jsxs("span",{className:"flex items-center gap-1",children:[o.jsx(mc,{className:"h-3.5 w-3.5 text-[#406E71]"}),Te(Ri(m,"yyyy-MM-dd"),_)," (",Zz(G),") · ",s.duration_minutes," min"]})]})]}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),o.jsx(Ur,{value:N.name,onChange:be=>R({...N,name:be.target.value}),placeholder:"Jane Smith",className:"h-11 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Email"}),o.jsxs("div",{className:"relative",children:[o.jsx(Bi,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),o.jsx(Ur,{type:"email",value:N.email,onChange:be=>R({...N,email:be.target.value}),placeholder:"jane@email.com",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),o.jsxs("div",{className:"relative",children:[o.jsx(zi,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),o.jsx(Ur,{type:"tel",value:N.phone,onChange:be=>R({...N,phone:be.target.value}),placeholder:"(555) 123-4567",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]})]}),o.jsxs("div",{className:"space-y-1.5",children:[o.jsx(Mr,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),o.jsx(hd,{value:N.message,onChange:be=>R({...N,message:be.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"})]})]}),o.jsx(Ut,{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:we,disabled:!N.name||D,children:D?o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"}),"Booking..."]}):"Confirm Booking"})]}),a==="confirmed"&&o.jsxs("div",{className:"text-center space-y-5 py-6",children:[o.jsxs("div",{className:"relative mx-auto w-20 h-20",children:[o.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping opacity-30"}),o.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:o.jsx(xc,{className:"h-10 w-10 text-white"})})]}),o.jsxs("div",{children:[o.jsx("h2",{className:"text-2xl font-bold text-slate-800",children:"You're booked!"}),o.jsxs("p",{className:"text-slate-500 mt-1.5",children:[s==null?void 0:s.name," with ",(re==null?void 0:re.name)||"your agent"]})]}),o.jsx("div",{className:"inline-flex items-center gap-3 px-5 py-3 rounded-xl bg-slate-50 border border-slate-100",children:o.jsxs("div",{className:"text-left text-sm",children:[o.jsx("p",{className:"font-semibold text-slate-800",children:m&&Ri(m,"EEEE, MMMM d, yyyy")}),o.jsxs("p",{className:"text-slate-500",children:[m&&_?`${Te(Ri(m,"yyyy-MM-dd"),_)} (${Zz(G)})`:""," · ",s==null?void 0:s.duration_minutes," min"]})]})}),o.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."}),B&&o.jsx("div",{className:"pt-1",children:o.jsx("a",{href:B,className:"inline-flex items-center gap-1.5 text-xs font-semibold text-[#406E71] underline underline-offset-4",children:"Reschedule or cancel this meeting"})}),((re==null?void 0:re.phone)||(re==null?void 0:re.email))&&o.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[o.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wider font-semibold",children:"Contact"}),o.jsxs("div",{className:"flex gap-3",children:[(re==null?void 0:re.phone)&&o.jsxs("a",{href:`tel:${re.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:[o.jsx(zi,{className:"h-3.5 w-3.5"})," Call"]}),(re==null?void 0:re.email)&&o.jsxs("a",{href:`mailto:${re.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:[o.jsx(Bi,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]})}),o.jsx("p",{className:"text-center text-[10px] text-slate-300 mt-6 font-medium tracking-wide uppercase",children:"Powered by LevelUp"})]})]}):o.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center p-4",children:o.jsxs("div",{className:"max-w-sm w-full text-center space-y-4",children:[o.jsx("div",{className:"mx-auto w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center",children:o.jsx(Zf,{className:"h-8 w-8 text-slate-400"})}),o.jsx("h2",{className:"text-lg font-semibold text-slate-700",children:"Page Not Available"}),o.jsx("p",{className:"text-sm text-slate-500",children:"This booking page doesn't exist or is currently inactive."})]})})}const ZIt=Object.freeze(Object.defineProperty({__proto__:null,default:yEe},Symbol.toStringTag,{value:"Module"}));function XIt(){const e=Wi().pathname.slice(1).split("/")[0];return P.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?o.jsx(yEe,{slugOverride:e}):o.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:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Scheduler"}),o.jsx("p",{className:"text-muted-foreground",children:"Visit a specific agent's booking URL to schedule a meeting."})]})})}const QIt="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",JIt="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",ePt="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",tPt="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",rPt="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",nPt="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",Xz={"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:nPt},"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:QIt},"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:JIt},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:ePt},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:tPt},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:rPt}},U8t=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function iPt(t){return t&&t in Xz?Xz[t]:Xz["minimal-mono"]}function sPt(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 xEe({slugOverride:t}={}){var go;const{slug:e}=hp(),r=t||e,[n]=B0(),i=n.get("t"),[a,c]=P.useState(!0),[s,f]=P.useState(null),[m,x]=P.useState(null),_=P.useRef(null),T=P.useRef(null),[E,C]=P.useState(null),[N,R]=P.useState(null),[D,M]=P.useState(!1),[B,V]=P.useState(!1),[G,W]=P.useState(0),[X,Q]=P.useState(!1),[re,se]=P.useState(""),[ue,_e]=P.useState(""),[Se,ve]=P.useState(""),[Oe,Ae]=P.useState(""),[we,ge]=P.useState(""),[Ne,Ie]=P.useState(""),[Te,be]=P.useState(""),[We,rt]=P.useState(""),[at,Et]=P.useState(""),[_t,Vt]=P.useState(""),[mt,Pt]=P.useState(""),[er,wt]=P.useState(""),[or,Sr]=P.useState(""),[nn,lr]=P.useState([]),[yr,tr]=P.useState([]),[yn,lt]=P.useState(""),[At,Ot]=P.useState(""),[dr,cr]=P.useState(""),[hr,Zt]=P.useState([]);P.useEffect(()=>{Pr()},[r,i]);const Pr=async()=>{if(!r)return;c(!0);const{data:Yr,error:hn}=await Le.from("contact_intake_pages").select("*").eq("slug",r).eq("is_active",!0).maybeSingle();if(hn||!Yr){Q(!0),c(!1);return}x(Yr),T.current=Yr;const{data:gn}=await Le.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Yr.user_id).single();if(gn){let Zr;if(gn.brokerage_id){const{data:Fn}=await Le.from("brokerages").select("name").eq("id",gn.brokerage_id).single();Zr=(Fn==null?void 0:Fn.name)||void 0}let oi=gn.avatar_url||null;if(!oi){const{data:Fn}=Le.storage.from("avatars").getPublicUrl(`${Yr.user_id}/avatar.jpg`);Fn!=null&&Fn.publicUrl&&(oi=`${Fn.publicUrl}?t=${Date.now()}`)}const Jr={...gn,avatar_url:oi,brokerage_name:Zr};f(Jr),_.current=Jr}if(i)try{console.log("[ConnectPage] Resolving token:",i,"for page:",Yr.id);const{data:Zr,error:oi}=await Le.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:i,page_id:Yr.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:Zr,resolveErr:oi}),!oi&&(Zr!=null&&Zr.contact_id)){R(Zr.contact_id);const Jr=Zr.contact;Jr&&(C(Jr),se(Jr.first_name||""),_e(Jr.last_name||""),ve(Jr.email||""),Ae(Jr.phone||""),ge(Jr.address||""),Ie(Jr.city||""),be(Jr.state||""),rt(Jr.zip||""),Et(Jr.birthday||""),Vt(Jr.home_anniversary||""))}}catch(Zr){console.error("Failed to resolve token:",Zr)}c(!1)},Nn=async()=>{var Yr,hn;if(!re.trim()){Jt.error("Please enter your first name");return}if(!r){Jt.error("Invalid page. Please refresh.");return}V(!0);try{let gn=(Yr=T.current)==null?void 0:Yr.id,Zr=(hn=T.current)==null?void 0:hn.user_id;if(!gn||!Zr){const{data:Fn}=await Le.from("contact_intake_pages").select("id, user_id").eq("slug",r).eq("is_active",!0).maybeSingle();if(!Fn){Jt.error("This page is no longer active. Please contact the agent directly."),V(!1);return}gn=Fn.id,Zr=Fn.user_id}const oi={intake_page_id:gn,agent_user_id:Zr,existing_contact_id:N,first_name:re.trim(),last_name:ue.trim()||null,email:Se.trim()||null,phone:Oe.trim()||null,address:we.trim()||null,city:Ne.trim()||null,state:Te.trim()||null,zip:We.trim()||null,birthday:at||null,home_anniversary:_t||null,real_estate_interest:mt||null,message:er.trim()||null,life_events:{spouse_name:or.trim()||null,kids:nn.filter(Fn=>Fn.name.trim()),pets:yr.filter(Fn=>Fn.name.trim()),favorite_spots:yn.trim()||null,dream_neighborhood:At.trim()||null,wedding_anniversary:dr||null},referrals:hr.filter(Fn=>Fn.name.trim()&&Fn.contact.trim())},{error:Jr}=await Le.from("contact_intake_submissions").insert(oi);if(console.log("[ConnectPage] Insert result:",{error:Jr}),Jr)throw Jr;i&&await Le.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",i);try{const Fn=[re.trim(),ue.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:Zr,contactName:Fn,contactEmail:Se.trim()||null,contactPhone:Oe.trim()||null,slug:r})})}catch(Fn){console.warn("Connect page notification failed (non-blocking):",Fn)}M(!0)}catch(gn){console.error(gn),Jt.error("Something went wrong. Please try again.")}finally{V(!1)}};if(a)return o.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:o.jsx(Cu,{className:"h-8 w-8 animate-spin text-slate-400"})});if(X)return o.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:o.jsxs("div",{className:"text-center space-y-3",children:[o.jsx("h1",{className:"text-2xl font-semibold text-slate-700",children:"Page Not Found"}),o.jsx("p",{className:"text-slate-500",children:"This connect page doesn't exist or is no longer active."})]})});if(D)return o.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:[o.jsx(jl,{children:o.jsxs("title",{children:["Thank You | ",s==null?void 0:s.name]})}),o.jsxs(pr.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:[o.jsx(pr.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:o.jsx(xc,{className:"h-10 w-10 text-emerald-600"})}),o.jsx("h1",{className:"text-3xl font-bold text-slate-800",children:"Thank You!"}),o.jsxs("p",{className:"text-lg text-slate-600",children:[s==null?void 0:s.name," has received your info and will be in touch soon."]}),o.jsxs("div",{className:"flex items-center justify-center gap-1 text-sm text-slate-400 pt-4",children:[o.jsx(tp,{className:"h-3.5 w-3.5"}),o.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const ai=!!i&&!!E,ei=(m==null?void 0:m.show_little_things)??!0,Oi=[{title:ai?"Confirm Your Info":"Let's Get Connected",fields:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"First Name *"}),o.jsx("input",{type:"text",value:re,onChange:Yr=>se(Yr.target.value),placeholder:"Jane",className:"connect-input",required:!0})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Last Name"}),o.jsx("input",{type:"text",value:ue,onChange:Yr=>_e(Yr.target.value),placeholder:"Smith",className:"connect-input"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Email"}),o.jsx("input",{type:"email",value:Se,onChange:Yr=>ve(Yr.target.value),placeholder:"jane@email.com",className:"connect-input"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Phone"}),o.jsx("input",{type:"tel",value:Oe,onChange:Yr=>Ae(Yr.target.value),placeholder:"(555) 123-4567",className:"connect-input"})]})]})},{title:"A Little More About You",fields:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Street Address"}),o.jsx("input",{type:"text",value:we,onChange:Yr=>ge(Yr.target.value),placeholder:"123 Main St",className:"connect-input"})]}),o.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[o.jsxs("div",{className:"col-span-2",children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"City"}),o.jsx("input",{type:"text",value:Ne,onChange:Yr=>Ie(Yr.target.value),placeholder:"Austin",className:"connect-input"})]}),o.jsxs("div",{className:"col-span-1",children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"State"}),o.jsx("input",{type:"text",value:Te,onChange:Yr=>be(Yr.target.value),placeholder:"TX",maxLength:2,className:"connect-input"})]}),o.jsxs("div",{className:"col-span-2",children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Zip"}),o.jsx("input",{type:"text",value:We,onChange:Yr=>rt(Yr.target.value),placeholder:"78701",className:"connect-input"})]})]}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),o.jsx("input",{type:"date",value:at,onChange:Yr=>Et(Yr.target.value),className:"connect-input"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Home Anniversary"}),o.jsx("input",{type:"date",value:_t,onChange:Yr=>Vt(Yr.target.value),className:"connect-input"})]})]})]})},...ei?[{title:"The Little Things",subtitle:"Optional — helps me remember what matters to you.",fields:o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Spouse / partner's name"}),o.jsx("input",{type:"text",value:or,onChange:Yr=>Sr(Yr.target.value),placeholder:"Alex",className:"connect-input"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),o.jsx("input",{type:"date",value:dr,onChange:Yr=>cr(Yr.target.value),className:"connect-input"})]}),o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[o.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Kids"}),o.jsxs("button",{type:"button",onClick:()=>lr(Yr=>[...Yr,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[o.jsx(xm,{className:"h-3 w-3"})," Add"]})]}),o.jsxs("div",{className:"space-y-2",children:[nn.length===0&&o.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),nn.map((Yr,hn)=>o.jsxs("div",{className:"flex gap-2 items-center",children:[o.jsx("input",{type:"text",value:Yr.name,onChange:gn=>lr(Zr=>Zr.map((oi,Jr)=>Jr===hn?{...oi,name:gn.target.value}:oi)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),o.jsx("input",{type:"text",value:Yr.age,onChange:gn=>lr(Zr=>Zr.map((oi,Jr)=>Jr===hn?{...oi,age:gn.target.value}:oi)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),o.jsx("button",{type:"button",onClick:()=>lr(gn=>gn.filter((Zr,oi)=>oi!==hn)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:o.jsx(Ks,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},hn))]})]}),o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[o.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Pets"}),o.jsxs("button",{type:"button",onClick:()=>tr(Yr=>[...Yr,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[o.jsx(xm,{className:"h-3 w-3"})," Add"]})]}),o.jsxs("div",{className:"space-y-2",children:[yr.length===0&&o.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),yr.map((Yr,hn)=>o.jsxs("div",{className:"flex gap-2 items-center",children:[o.jsx("input",{type:"text",value:Yr.name,onChange:gn=>tr(Zr=>Zr.map((oi,Jr)=>Jr===hn?{...oi,name:gn.target.value}:oi)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),o.jsx("input",{type:"text",value:Yr.kind,onChange:gn=>tr(Zr=>Zr.map((oi,Jr)=>Jr===hn?{...oi,kind:gn.target.value}:oi)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),o.jsx("button",{type:"button",onClick:()=>tr(gn=>gn.filter((Zr,oi)=>oi!==hn)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:o.jsx(Ks,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},hn))]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Favorite local spots"}),o.jsx("input",{type:"text",value:yn,onChange:Yr=>lt(Yr.target.value),placeholder:"That coffee shop on Main, Town Lake…",className:"connect-input"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Dream neighborhood"}),o.jsx("input",{type:"text",value:At,onChange:Yr=>Ot(Yr.target.value),placeholder:"Where you'd love to live someday",className:"connect-input"})]}),o.jsxs("div",{className:"rounded-xl p-4",style:{background:"color-mix(in srgb, var(--c-accent) 8%, transparent)"},children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("div",{children:[o.jsx("p",{className:"text-sm font-medium",style:{color:"var(--c-text)"},children:"Know someone who'd love an agent like me?"}),o.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"Refer a friend — up to 3."})]}),hr.length<3&&o.jsxs("button",{type:"button",onClick:()=>Zt(Yr=>[...Yr,{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:[o.jsx(xm,{className:"h-3 w-3"})," Add"]})]}),o.jsx("div",{className:"space-y-2",children:hr.map((Yr,hn)=>o.jsxs("div",{className:"flex gap-2 items-center",children:[o.jsx("input",{type:"text",value:Yr.name,onChange:gn=>Zt(Zr=>Zr.map((oi,Jr)=>Jr===hn?{...oi,name:gn.target.value}:oi)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),o.jsx("input",{type:"text",value:Yr.contact,onChange:gn=>Zt(Zr=>Zr.map((oi,Jr)=>Jr===hn?{...oi,contact:gn.target.value}:oi)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),o.jsx("button",{type:"button",onClick:()=>Zt(gn=>gn.filter((Zr,oi)=>oi!==hn)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:o.jsx(Ks,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},hn))})]})]})}]:[],{title:"One Last Thing",fields:o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{children:[o.jsxs("label",{className:"block text-sm font-medium text-slate-600 mb-3",children:["Are you thinking about making a move anytime soon? ",o.jsx("span",{className:"text-slate-400 font-normal",children:"(totally optional)"})]}),o.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(Yr=>o.jsxs("button",{type:"button",onClick:()=>Pt(mt===Yr.value?"":Yr.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${mt===Yr.value?"border-blue-500 bg-blue-50 shadow-sm":"border-slate-200 bg-white hover:border-slate-300"}`,children:[o.jsx("span",{className:"block text-sm font-medium text-slate-800",children:Yr.label}),o.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Yr.desc})]},Yr.value))})]}),o.jsxs("div",{children:[o.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? ",o.jsx("span",{className:"text-slate-400 font-normal",children:"(optional)"})]}),o.jsx("textarea",{value:er,onChange:Yr=>wt(Yr.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],ya=Oi.length,mi=iPt(m==null?void 0:m.theme),ia=sPt(mi,(m==null?void 0:m.accent_color)||null),jr=(m==null?void 0:m.cover_image_url)||mi.defaultCover,Mn=(m==null?void 0:m.headline)||"Let's stay connected",As=(m==null?void 0:m.subheadline)||(s!=null&&s.brokerage_name?`${s==null?void 0:s.name} · ${s.brokerage_name}`:(s==null?void 0:s.name)||""),xa=["deep-luxe"].includes((m==null?void 0:m.theme)||"");return o.jsxs("div",{className:"min-h-screen connect-shell",style:ia,children:[o.jsxs(jl,{children:[o.jsxs("title",{children:["Connect with ",(s==null?void 0:s.name)||"Agent"]}),o.jsx("meta",{name:"description",content:`${Mn} — ${(s==null?void 0:s.name)||"your agent"}`}),jr&&o.jsx("meta",{property:"og:image",content:jr}),o.jsx("meta",{property:"og:title",content:`Connect with ${(s==null?void 0:s.name)||"me"}`}),o.jsx("meta",{property:"og:description",content:Mn}),o.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),o.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); } `}),o.jsxs("div",{className:"relative w-full overflow-hidden",style:{height:"clamp(200px, 30vh, 320px)"},children:[o.jsx(pr.img,{src:jr,alt:"",initial:{scale:1.08},animate:{scale:1},transition:{duration:1.4,ease:"easeOut"},className:"absolute inset-0 w-full h-full object-cover"}),o.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,0) 20%, rgba(0,0,0,0.55) 100%)"}}),o.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-6 pb-16 text-center",children:[o.jsx(pr.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:mi.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Mn}),As&&o.jsx(pr.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:As})]})]}),o.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[o.jsxs(pr.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.25},className:"text-center mb-6",children:[s!=null&&s.avatar_url?o.jsx("img",{src:s.avatar_url,alt:s.name,className:"w-24 h-24 rounded-full object-cover mx-auto shadow-xl",style:{border:"4px solid var(--c-surface)"}}):o.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center shadow-xl",style:{background:mi.accent,color:mi.accentText,border:"4px solid var(--c-surface)"},children:o.jsx("span",{className:"text-3xl font-bold",children:((go=s==null?void 0:s.name)==null?void 0:go.charAt(0))||"?"})}),(s==null?void 0:s.title)&&o.jsx("p",{className:"text-sm mt-3",style:{color:"var(--c-text-muted)"},children:s.title}),((s==null?void 0:s.phone)||(s==null?void 0:s.email))&&o.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[(s==null?void 0:s.phone)&&o.jsx("a",{href:`tel:${s.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:o.jsx(zi,{className:"h-4 w-4"})}),(s==null?void 0:s.email)&&o.jsx("a",{href:`mailto:${s.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:o.jsx(Bi,{className:"h-4 w-4"})})]})]}),o.jsx(pr.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:(m==null?void 0:m.welcome_message)||"I'd love to stay in touch — just a few quick details."}),o.jsx("div",{className:"flex gap-1.5 mb-6 px-2",children:Array.from({length:ya}).map((Yr,hn)=>o.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:hn<=G?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},hn))}),o.jsxs(pr.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:xa?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[o.jsx(lbe,{mode:"wait",children:o.jsxs(pr.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[o.jsxs("div",{className:"mb-6",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Ss,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),o.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:Oi[G].title})]}),Oi[G].subtitle&&o.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:Oi[G].subtitle})]}),Oi[G].fields]},G)}),o.jsxs("div",{className:"flex justify-between mt-8",children:[G>0?o.jsx("button",{type:"button",onClick:()=>W(Yr=>Yr-1),className:"px-5 py-2.5 text-sm font-medium transition-opacity hover:opacity-70",style:{color:"var(--c-text-muted)"},children:"Back"}):o.jsx("div",{}),G{if(G===0&&!re.trim()){Jt.error("Please enter your first name");return}W(Yr=>Yr+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"}):o.jsx("button",{type:"button",onClick:()=>Nn(),disabled:B,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:B?o.jsxs(o.Fragment,{children:[o.jsx(Cu,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),G>0&&GW(Yr=>Yr+1),className:"text-xs transition-opacity hover:opacity-80",style:{color:"var(--c-text-muted)"},children:"Skip this step"})})]}),o.jsx("div",{className:"text-center mt-8",children:o.jsxs("div",{className:"flex items-center justify-center gap-1 text-xs",style:{color:"var(--c-text-muted)"},children:[o.jsx(tp,{className:"h-3 w-3"}),o.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const aPt=Object.freeze(Object.defineProperty({__proto__:null,default:xEe},Symbol.toStringTag,{value:"Module"}));function oPt(){const e=Wi().pathname.slice(1);return P.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===""?o.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:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),o.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),o.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):o.jsx(xEe,{slugOverride:e})}function lPt(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[s,f]of c)if(a[(f*r+s)*4+3]<250)return!0;return!1}catch{return!0}}const cPt={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function uPt({page:t,fields:e,answers:r,setAnswers:n,onSubmit:i,isSubmitting:a,renderField:c}){const s=t.accent_color||"#E8B84A",f=t.primary_color||"#0F1B3D",m=cPt[t.heading_font||"playfair"],x=t.eyebrow||null,_=t.headline_accent||null,T=Array.isArray(t.trust_pills)?t.trust_pills:[],E=e,C=E.length>5;return o.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:f},children:[t.hero_image_url?o.jsx("img",{src:t.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):o.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${f}, #000)`}}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),o.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:o.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[o.jsxs("div",{className:"lg:col-span-3 text-white",children:[t.logo_url&&o.jsx(dPt,{src:t.logo_url}),x&&o.jsx("p",{className:"text-xs md:text-sm font-semibold tracking-[0.22em] text-white/80 mb-4 uppercase",children:x}),o.jsxs("h1",{className:"font-bold leading-[1.04] mb-5 text-4xl sm:text-5xl md:text-6xl lg:text-[68px]",style:{fontFamily:m,letterSpacing:"-0.015em"},children:[t.hero_headline,_&&o.jsxs(o.Fragment,{children:[" ",o.jsx("span",{style:{color:s,fontStyle:"italic"},children:_})]})]}),t.hero_subtext&&o.jsx("p",{className:"text-base md:text-lg text-white/85 leading-relaxed max-w-xl",children:t.hero_subtext}),t.agent_name&&o.jsxs("div",{className:"mt-8 flex items-center gap-3",children:[t.agent_photo_url&&o.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"}),o.jsxs("div",{className:"text-white/90",children:[o.jsx("p",{className:"font-semibold text-sm",children:t.agent_name}),o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/70 mt-0.5",children:[t.agent_phone&&o.jsxs("a",{href:`tel:${t.agent_phone}`,className:"flex items-center gap-1 hover:text-white",children:[o.jsx(zi,{className:"h-3 w-3"})," ",t.agent_phone]}),t.agent_email&&o.jsxs("a",{href:`mailto:${t.agent_email}`,className:"flex items-center gap-1 hover:text-white",children:[o.jsx(Bi,{className:"h-3 w-3"})," ",t.agent_email]})]})]})]})]}),o.jsx("div",{className:"lg:col-span-2",children:o.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6",children:[o.jsxs("form",{className:"space-y-3",onSubmit:i,children:[o.jsx("div",{className:C?"space-y-3 max-h-[52vh] overflow-y-auto pr-1 -mr-1":"space-y-3",children:E.map(N=>o.jsxs("div",{children:[o.jsxs(Mr,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[N.label,N.is_required&&o.jsx("span",{className:"ml-1",style:{color:s},children:"*"})]}),o.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(N,r,n,f)})]},N.id))}),o.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:s},children:a?"Submitting...":t.cta_text||"Get Started"})]}),T.length>0&&o.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:T.map((N,R)=>o.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[o.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:s}}),N]},R))})]})})]})})]})}function dPt({src:t}){const[e,r]=P.useState(null),n=o.jsx("img",{src:t,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:i=>r(lPt(i.currentTarget)),onError:()=>r(!0)});return e===!1?o.jsx("span",{className:"inline-flex items-center rounded-md bg-white/90 backdrop-blur px-3 py-2 mb-6 shadow-sm",children:n}):o.jsx("div",{className:"mb-6 inline-block drop-shadow-md",children:n})}const Roe={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function hPt({page:t,fields:e,answers:r,setAnswers:n,onSubmit:i,isSubmitting:a,renderField:c,activePath:s,setActivePath:f}){const m=P.useRef(null),[x,_]=P.useState(!1),T=t.primary_color||"#406E71",E=t.accent_color||"#2a4c64",C=t.settings||{},N=Roe[t.heading_font]||Roe.playfair,R=Array.isArray(t.trust_pills)?t.trust_pills:[],D={buyerLabel:C.buyer_button_label||"I'm a Buyer",buyerSub:C.buyer_button_subtext||"Find the right home, at the right price",sellerLabel:C.seller_button_label||"I'm a Seller",sellerSub:C.seller_button_subtext||"Get a free, no-obligation home evaluation",buyerTitle:C.buyer_form_title||"Tell me what you’re looking for",buyerSubtitle:C.buyer_form_subtext||"A few quick questions and I’ll send you matching homes.",sellerTitle:C.seller_form_title||"Get your free home evaluation",sellerSubtitle:C.seller_form_subtext||"Tell me about your home and I’ll prepare your value report.",buyerCta:C.buyer_submit_label||"Send me homes",sellerCta:C.seller_submit_label||"Get my home value"},M=P.useMemo(()=>{const W=e.filter(re=>(re.field_group||"default")==="buyer"),X=e.filter(re=>(re.field_group||"default")==="seller"),Q=e.filter(re=>(re.field_group||"default")==="default");return{buyer:W.length?[...Q,...W]:[...Q],seller:X.length?[...Q,...X]:[...Q]}},[e]),B=s?M[s]:[];P.useEffect(()=>{s&&m.current&&m.current.scrollIntoView({behavior:"smooth",block:"start"})},[s]);const V=B.filter(W=>W.is_required&&!r[W.label]),G=W=>{W.preventDefault(),_(!0),!(V.length>0)&&i(W)};return o.jsxs("div",{className:"min-h-screen bg-neutral-950",children:[o.jsxs("section",{className:"relative min-h-[78vh] flex items-center overflow-hidden",children:[o.jsx("div",{className:"absolute inset-0",style:{background:t.hero_image_url?`url(${t.hero_image_url}) center/cover no-repeat`:`linear-gradient(135deg, ${T}, ${E})`}}),o.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%)"}}),o.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40",style:{background:"linear-gradient(180deg, transparent, #0a0a0a)"}}),o.jsxs("div",{className:"relative w-full max-w-6xl mx-auto px-5 py-20 text-center",children:[t.logo_url&&o.jsx("img",{src:t.logo_url,alt:"",className:"h-11 w-auto mx-auto mb-8 drop-shadow-lg"}),t.eyebrow&&o.jsx("p",{className:"text-[11px] md:text-xs uppercase tracking-[0.32em] text-white/70 mb-5",children:t.eyebrow}),o.jsxs("h1",{className:"text-white text-4xl md:text-6xl lg:text-7xl leading-[1.05] tracking-tight",style:{fontFamily:N},children:[t.hero_headline,t.headline_accent&&o.jsxs(o.Fragment,{children:[" ",o.jsx("em",{className:"italic",style:{color:"#fff",opacity:.85},children:t.headline_accent})]})]}),t.hero_subtext&&o.jsx("p",{className:"mt-5 text-base md:text-lg text-white/80 max-w-2xl mx-auto leading-relaxed",children:t.hero_subtext}),o.jsxs("div",{className:"mt-12 grid gap-4 sm:grid-cols-2 max-w-3xl mx-auto",children:[o.jsx(Loe,{active:s==="buyer",icon:o.jsx(Ghe,{className:"h-5 w-5"}),label:D.buyerLabel,sub:D.buyerSub,color:T,onClick:()=>{_(!1),f("buyer")}}),o.jsx(Loe,{active:s==="seller",icon:o.jsx(Ma,{className:"h-5 w-5"}),label:D.sellerLabel,sub:D.sellerSub,color:E,onClick:()=>{_(!1),f("seller")}})]}),R.length>0&&o.jsx("div",{className:"mt-9 flex flex-wrap items-center justify-center gap-2",children:R.map(W=>o.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:[o.jsx(mG,{className:"h-3 w-3"})," ",W]},W))})]})]}),o.jsx("section",{ref:m,className:"relative bg-neutral-950 px-5 pb-20 pt-2 scroll-mt-4",children:o.jsxs("div",{className:"max-w-3xl mx-auto",children:[s?o.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:[o.jsxs("div",{className:"px-6 md:px-9 py-6",style:{background:`linear-gradient(120deg, ${s==="buyer"?T:E}, ${s==="buyer"?E:T})`},children:[o.jsxs("button",{type:"button",onClick:()=>f(null),className:"inline-flex items-center gap-1.5 text-[11px] uppercase tracking-widest text-white/75 hover:text-white transition-colors",children:[o.jsx(By,{className:"h-3 w-3"})," Change"]}),o.jsx("h2",{className:"mt-3 text-2xl md:text-3xl text-white leading-tight",style:{fontFamily:N},children:s==="buyer"?D.buyerTitle:D.sellerTitle}),o.jsx("p",{className:"mt-1.5 text-sm text-white/80",children:s==="buyer"?D.buyerSubtitle:D.sellerSubtitle})]}),o.jsxs("form",{onSubmit:G,className:"px-6 md:px-9 py-7 space-y-4",children:[B.length===0&&o.jsx("p",{className:"text-sm text-neutral-500",children:"This form has no questions yet."}),B.map(W=>o.jsxs("div",{children:[o.jsxs(Mr,{className:"text-[13px] font-medium text-neutral-700",children:[W.label,W.is_required&&o.jsx("span",{className:"ml-1",style:{color:T},children:"*"})]}),c(W,r,n,T)]},W.id)),x&&V.length>0&&o.jsxs("p",{className:"text-sm text-red-600",children:["Please fill in: ",V.map(W=>W.label).join(", ")]}),o.jsxs(Ut,{type:"submit",disabled:a,className:"w-full h-12 text-white text-base rounded-xl shadow-lg hover:opacity-95",style:{backgroundColor:s==="buyer"?T:E},children:[a?"Sending…":s==="buyer"?D.buyerCta:D.sellerCta,!a&&o.jsx(pc,{className:"h-4 w-4 ml-2"})]})]})]}):o.jsx("p",{className:"text-center text-white/45 text-sm py-10",children:"Choose an option above to get started."}),t.agent_name&&o.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&&o.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"}),o.jsxs("div",{className:"text-left",children:[o.jsx("p",{className:"text-white font-medium",children:t.agent_name}),o.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/65",children:[t.agent_phone&&o.jsxs("a",{href:`tel:${t.agent_phone}`,className:"inline-flex items-center gap-1 hover:text-white",children:[o.jsx(zi,{className:"h-3 w-3"})," ",t.agent_phone]}),t.agent_email&&o.jsxs("a",{href:`mailto:${t.agent_email}`,className:"inline-flex items-center gap-1 hover:text-white",children:[o.jsx(Bi,{className:"h-3 w-3"})," ",t.agent_email]})]})]})]})]})})]})}function Loe({active:t,icon:e,label:r,sub:n,color:i,onClick:a}){return o.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:[o.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}),o.jsx("span",{className:`mt-4 block text-xl font-semibold ${t?"":"text-white"}`,style:t?{color:i}:void 0,children:r}),o.jsx("span",{className:`mt-1 block text-sm ${t?"text-neutral-600":"text-white/70"}`,children:n}),o.jsx(pc,{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 fPt(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 pPt(t,e,r){const n=new Date(e),i=new Date(n.getTime()+60*60*1e3),a=s=>s.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 mPt(t,e,r){const n=new Date(e),i=new Date(n.getTime()+60*60*1e3),a=s=>s.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 gPt({startsAt:t,locationName:e,address:r,title:n,accent:i}){const[a,c]=P.useState(Date.now());P.useEffect(()=>{const E=setInterval(()=>c(Date.now()),1e3);return()=>clearInterval(E)},[]);const s=new Date(t).getTime();if(!Number.isFinite(s))return null;const f=fPt(s-a),m=s-a<=0,x=new Date(t).toLocaleString("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"}),_=[e,r].filter(Boolean).join(" · "),T=r?`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(r)}`:null;return o.jsx("section",{className:"max-w-5xl mx-auto px-4 py-10",children:o.jsx("div",{className:"rounded-2xl border bg-white/80 backdrop-blur p-6 md:p-8 shadow-sm",children:o.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[o.jsxs("div",{className:"space-y-1.5",children:[o.jsx("div",{className:"text-xs uppercase tracking-wider font-medium",style:{color:i},children:m?"Just happened":"Event starts in"}),m?o.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."}):o.jsx("div",{className:"flex items-baseline gap-3",children:[{v:f.d,l:"days"},{v:f.h,l:"hrs"},{v:f.m,l:"min"},{v:f.s,l:"sec"}].map(E=>o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-3xl md:text-4xl font-bold tabular-nums",style:{color:i},children:String(E.v).padStart(2,"0")}),o.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:E.l})]},E.l))}),o.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 pt-2 text-sm text-neutral-700",children:[o.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[o.jsx(mc,{className:"h-3.5 w-3.5"})," ",x]}),_&&o.jsxs("a",{href:T||"#",target:T?"_blank":void 0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 hover:underline",children:[o.jsx(na,{className:"h-3.5 w-3.5"})," ",_]})]})]}),!m&&o.jsxs("div",{className:"flex flex-wrap gap-2",children:[o.jsxs("a",{href:pPt(n,t,_||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:[o.jsx(po,{className:"h-4 w-4"})," Add to Google"]}),o.jsxs("a",{href:mPt(n,t,_||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:[o.jsx(po,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function yPt(){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 _Ee({slugOverride:t}){var Se;const{slug:e}=hp(),r=t||e,[n,i]=P.useState(!1),[a,c]=P.useState({}),[s,f]=P.useState(null),[m,x]=P.useState(0),[_,T]=P.useState(!1),[E,C]=P.useState(""),[N]=P.useState(()=>Date.now()),R=P.useState(()=>yPt())[0],{data:D,isLoading:M}=wr({queryKey:["public-landing-page",r],queryFn:async()=>{const{data:ve,error:Oe}=await Le.from("landing_pages").select("*").eq("slug",r).eq("is_published",!0).single();if(Oe)throw Oe;return ve},enabled:!!r}),{data:B=[]}=wr({queryKey:["public-landing-page-fields",D==null?void 0:D.id],queryFn:async()=>{const{data:ve,error:Oe}=await Le.from("landing_page_fields").select("*").eq("page_id",D.id).order("sort_order");if(Oe)throw Oe;return ve},enabled:!!(D!=null&&D.id)});P.useEffect(()=>{D!=null&&D.id&&Le.from("landing_pages").update({view_count:(D.view_count||0)+1}).eq("id",D.id).then(()=>{})},[D==null?void 0:D.id]),P.useEffect(()=>{if(!(D!=null&&D.id))return;const ve=new URLSearchParams(window.location.search);Le.functions.invoke("landing-page-track",{body:{page_id:D.id,event_type:"view",session_id:R,utm_source:ve.get("utm_source"),utm_medium:ve.get("utm_medium"),utm_campaign:ve.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[D==null?void 0:D.id,R]);const V=Cr({mutationFn:async()=>{const ve=B.find(We=>We.field_type==="text"&&We.label.toLowerCase().includes("name")),Oe=B.find(We=>We.field_type==="email"),Ae=B.find(We=>We.field_type==="phone"),we=ve?String(a[ve.label]||""):null,ge=Oe?String(a[Oe.label]||""):null,Ne=Ae?String(a[Ae.label]||""):null,Ie=new URLSearchParams(window.location.search),{data:Te,error:be}=await Le.functions.invoke("landing-page-submit",{body:{page_id:D.id,answers:JSON.parse(JSON.stringify(s?{"I am a":s==="buyer"?"Buyer":"Seller",...a}:a)),contact_name:we,contact_email:ge,contact_phone:Ne,session_id:R,honeypot:E,rendered_at:N,utm_source:Ie.get("utm_source"),utm_medium:Ie.get("utm_medium"),utm_campaign:Ie.get("utm_campaign"),referrer:document.referrer||null}});if(be)throw be;return Te},onSuccess:ve=>{i(!0),ve!=null&&ve.redirect_url&&setTimeout(()=>{window.location.href=ve.redirect_url},1500)}}),G=ve=>{ve.preventDefault(),!((D==null?void 0:D.page_type)!=="buyer_seller"&&B.filter(Ae=>Ae.is_required&&!a[Ae.label]).length>0)&&V.mutate()};if(M)return o.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-gray-400 border-t-transparent"})});if(!D)return o.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold text-gray-700",children:"Page Not Found"}),o.jsx("p",{className:"text-gray-500 mt-2",children:"This page doesn't exist or is no longer available."})]})});const W=D.primary_color||"#406E71",X=D.accent_color||"#2a4c64",Q=D,re=D.page_type==="lead_magnet",se=D.page_type==="just_listed"||D.page_type==="just_sold",ue=Array.isArray(Q.property_photos)?Q.property_photos:[],_e=Q.lead_magnet_file_url||Q.lead_magnet_external_url;if(n)return o.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${W}, ${X})`},children:o.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[o.jsx(xc,{className:"h-16 w-16 mx-auto mb-4",style:{color:W}}),o.jsx("h2",{className:"text-2xl font-bold mb-2",children:re?"Your download is ready!":"Submitted!"}),o.jsx("p",{className:"text-gray-600",children:D.success_message}),re&&_e&&o.jsxs("a",{href:_e,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:[o.jsx(Xl,{className:"h-5 w-5"}),"Download ",Q.lead_magnet_file_name||"Your File"]}),D.agent_name&&o.jsxs("div",{className:"mt-6 pt-4 border-t",children:[o.jsx("p",{className:"text-sm text-gray-500",children:"Contact"}),o.jsx("p",{className:"font-semibold",children:D.agent_name}),D.agent_phone&&o.jsxs("a",{href:`tel:${D.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:W},children:[o.jsx(zi,{className:"h-3 w-3"})," ",D.agent_phone]}),D.agent_email&&o.jsxs("a",{href:`mailto:${D.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:W},children:[o.jsx(Bi,{className:"h-3 w-3"})," ",D.agent_email]})]})]})});if(se){const ve=Oe=>{const Ae=parseFloat(Oe.replace(/[^0-9.]/g,""));return isNaN(Ae)?Oe:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ae)};return o.jsxs("div",{className:"min-h-screen bg-gray-50",children:[_&&ue.length>0&&o.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>T(!1),children:[o.jsx("button",{onClick:()=>T(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:o.jsx(Ks,{className:"h-8 w-8"})}),o.jsx("button",{onClick:Oe=>{Oe.stopPropagation(),x(Ae=>Ae===0?ue.length-1:Ae-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:o.jsx($m,{className:"h-6 w-6"})}),o.jsx("img",{src:ue[m],alt:`Property photo ${m+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:Oe=>Oe.stopPropagation()}),o.jsx("button",{onClick:Oe=>{Oe.stopPropagation(),x(Ae=>Ae===ue.length-1?0:Ae+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:o.jsx(th,{className:"h-6 w-6"})}),o.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 text-white/70 text-sm",children:[m+1," / ",ue.length]})]}),ue.length>0&&o.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 pt-6",children:[o.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"}),ue.length===1?o.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{x(0),T(!0)},children:[o.jsx("img",{src:ue[0],alt:"Property",className:"w-full h-[50vh] object-cover group-hover:scale-105 transition-transform duration-500"}),o.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:[o.jsx(CJ,{className:"h-4 w-4"})," View"]})]}):ue.length===2?o.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:ue.slice(0,2).map((Oe,Ae)=>o.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{x(Ae),T(!0)},children:o.jsx("img",{src:Oe,alt:`Property ${Ae+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},Ae))}):o.jsxs("div",{className:"grid grid-cols-4 gap-2 rounded-2xl overflow-hidden",style:{height:"55vh"},children:[o.jsx("div",{className:"col-span-2 row-span-2 cursor-pointer group relative",onClick:()=>{x(0),T(!0)},children:o.jsx("img",{src:ue[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),ue.slice(1,5).map((Oe,Ae)=>o.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{x(Ae+1),T(!0)},children:[o.jsx("img",{src:Oe,alt:`Property ${Ae+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),Ae===3&&ue.length>5&&o.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",ue.length-5," more"]})]},Ae))]}),ue.length>2&&o.jsxs("button",{onClick:()=>{x(0),T(!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:[o.jsx(CJ,{className:"h-4 w-4"})," View all ",ue.length," photos"]})]}),ue.length===0&&o.jsx("div",{className:"relative py-16 px-4",style:{background:D.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${D.hero_image_url}) center/cover`:`linear-gradient(135deg, ${W}, ${X})`},children:o.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[D.logo_url&&o.jsx("img",{src:D.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),o.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:D.hero_headline}),D.hero_subtext&&o.jsx("p",{className:"mt-3 text-lg opacity-90",children:D.hero_subtext})]})}),o.jsx("div",{className:"max-w-4xl mx-auto px-4 py-8",children:o.jsxs("div",{className:"grid md:grid-cols-5 gap-6",children:[o.jsx("div",{className:"md:col-span-3 space-y-6",children:o.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[Q.property_price&&o.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:W},children:ve(Q.property_price)}),Q.property_address&&o.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[o.jsx(na,{className:"h-5 w-5 shrink-0"})," ",Q.property_address]}),o.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[Q.property_beds&&o.jsxs("div",{className:"text-center",children:[o.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[o.jsx(TC,{className:"h-5 w-5",style:{color:W}})," ",Q.property_beds]}),o.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),Q.property_baths&&o.jsxs("div",{className:"text-center",children:[o.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[o.jsx(lS,{className:"h-5 w-5",style:{color:W}})," ",Q.property_baths]}),o.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),Q.property_sqft&&o.jsxs("div",{className:"text-center",children:[o.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[o.jsx(QO,{className:"h-5 w-5",style:{color:W}})," ",Number(Q.property_sqft).toLocaleString()]}),o.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),Q.property_description&&o.jsxs("div",{children:[o.jsx("h3",{className:"font-semibold text-gray-800 mb-2",children:"About This Property"}),o.jsx("p",{className:"text-gray-600 leading-relaxed whitespace-pre-line",children:Q.property_description})]})]})}),o.jsx("div",{className:"md:col-span-2",children:o.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 sticky top-6",children:[o.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?"}),o.jsx("p",{className:"text-gray-500 text-sm mb-4",children:"Fill out the form and I'll be in touch!"}),D.agent_name&&o.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[D.agent_photo_url&&o.jsx("img",{src:D.agent_photo_url,alt:D.agent_name,className:"h-12 w-12 rounded-full object-cover"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-semibold text-sm",children:D.agent_name}),o.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[D.agent_phone&&o.jsxs("a",{href:`tel:${D.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[o.jsx(zi,{className:"h-3 w-3"})," ",D.agent_phone]}),D.agent_email&&o.jsxs("a",{href:`mailto:${D.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[o.jsx(Bi,{className:"h-3 w-3"})," ",D.agent_email]})]})]})]}),o.jsxs("form",{onSubmit:G,className:"space-y-3",children:[B.map(Oe=>o.jsxs("div",{children:[o.jsxs(Mr,{className:"text-xs font-medium",children:[Oe.label,Oe.is_required&&o.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),WN(Oe,a,c)]},Oe.id)),o.jsx(Ut,{type:"submit",className:"w-full text-white",style:{backgroundColor:W},disabled:V.isPending,children:V.isPending?"Submitting...":"Submit"}),V.isError&&o.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),o.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return D.page_type==="buyer_seller"?o.jsxs(o.Fragment,{children:[o.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:E,onChange:ve=>C(ve.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),o.jsx(hPt,{page:D,fields:B,answers:a,setAnswers:c,onSubmit:G,isSubmitting:V.isPending,renderField:WN,activePath:s,setActivePath:f}),V.isError&&o.jsx("p",{className:"text-center text-sm text-red-500 pb-8 bg-neutral-950",children:"Something went wrong. Please try again."}),o.jsx("div",{className:"text-center py-6 text-xs text-white/30 bg-neutral-950",children:"Powered by LevelUp"})]}):D.theme_style!=="classic"&&!re?o.jsxs("div",{className:"min-h-screen bg-neutral-50",children:[o.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:E,onChange:ve=>C(ve.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),o.jsx(uPt,{page:D,fields:B,answers:a,setAnswers:c,onSubmit:G,isSubmitting:V.isPending,renderField:WN}),D.page_type==="event_registration"&&((Se=D.settings)==null?void 0:Se.event_starts_at)&&o.jsx(gPt,{startsAt:D.settings.event_starts_at,locationName:D.settings.event_location_name,address:D.settings.event_address,title:D.hero_headline||D.title,accent:D.accent_color||D.primary_color||"#406E71"}),V.isError&&o.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),o.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):o.jsxs("div",{className:"min-h-screen bg-gray-50",children:[o.jsx("div",{className:"relative py-16 px-4",style:{background:D.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${D.hero_image_url}) center/cover`:`linear-gradient(135deg, ${W}, ${X})`},children:o.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[D.logo_url&&o.jsx("img",{src:D.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),o.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:D.hero_headline}),D.hero_subtext&&o.jsx("p",{className:"mt-3 text-lg opacity-90",children:D.hero_subtext}),re&&Q.lead_magnet_file_name&&o.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:[o.jsx(Xl,{className:"h-4 w-4"}),"Free Download: ",Q.lead_magnet_file_name]})]})}),o.jsx("div",{className:"max-w-2xl mx-auto px-4 -mt-8",children:o.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[re&&o.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),D.agent_name&&o.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[D.agent_photo_url&&o.jsx("img",{src:D.agent_photo_url,alt:D.agent_name,className:"h-12 w-12 rounded-full object-cover"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-semibold",children:D.agent_name}),o.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[D.agent_phone&&o.jsxs("a",{href:`tel:${D.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[o.jsx(zi,{className:"h-3 w-3"})," ",D.agent_phone]}),D.agent_email&&o.jsxs("a",{href:`mailto:${D.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[o.jsx(Bi,{className:"h-3 w-3"})," ",D.agent_email]})]})]})]}),o.jsxs("form",{onSubmit:G,className:"space-y-4",children:[B.map(ve=>o.jsxs("div",{children:[o.jsxs(Mr,{className:"text-sm font-medium",children:[ve.label,ve.is_required&&o.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),WN(ve,a,c)]},ve.id)),o.jsx(Ut,{type:"submit",className:"w-full text-white",style:{backgroundColor:W},disabled:V.isPending,children:V.isPending?"Submitting...":re?"Get My Free Download":"Submit"}),V.isError&&o.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})}),o.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}function WN(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 o.jsx(Ur,{type:t.field_type==="email"?"email":t.field_type==="phone"?"tel":"text",value:String(i),onChange:c=>r(s=>({...s,[t.label]:c.target.value})),placeholder:t.placeholder||"",className:"mt-1"});case"textarea":return o.jsx(hd,{value:String(i),onChange:c=>r(s=>({...s,[t.label]:c.target.value})),placeholder:t.placeholder||"",rows:3,className:"mt-1"});case"select":return o.jsxs(Ba,{value:String(i),onValueChange:c=>r(s=>({...s,[t.label]:c})),children:[o.jsx(ja,{className:"mt-1",children:o.jsx(za,{placeholder:"Select..."})}),o.jsx(Ia,{children:a.map(c=>o.jsx(wn,{value:c,children:c},c))})]});case"multiselect":return o.jsx("div",{className:"mt-1 space-y-2",children:a.map(c=>{const s=Array.isArray(i)?i:[];return o.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[o.jsx(ZC,{checked:s.includes(c),onCheckedChange:f=>{const m=f?[...s,c]:s.filter(x=>x!==c);r(x=>({...x,[t.label]:m}))}}),o.jsx("span",{className:"text-sm",children:c})]},c)})});case"toggle":return o.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.jsx(kS,{checked:!!i,onCheckedChange:c=>r(s=>({...s,[t.label]:c?"Yes":"No"}))}),o.jsx("span",{className:"text-sm text-gray-600",children:i?"Yes":"No"})]});default:return o.jsx(Ur,{value:String(i),onChange:c=>r(s=>({...s,[t.label]:c.target.value})),className:"mt-1"})}}const xPt=Object.freeze(Object.defineProperty({__proto__:null,default:_Ee},Symbol.toStringTag,{value:"Module"}));function _Pt(){const e=Wi().pathname.slice(1).split("/")[0];return P.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?o.jsx(_Ee,{slugOverride:e}):o.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-6",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h1",{className:"text-2xl font-bold mb-2",children:"LevelUp Pages"}),o.jsx("p",{className:"text-gray-500",children:"Visit a specific page URL to view content."})]})})}const vPt=[{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}],V8t={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"},q8t={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"},Doe={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 G8t(t){return Doe[t]||Doe.basic}function bPt(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}):vPt,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 H8t=[{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"}],wPt={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]"},SPt={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 iW(t){return t==="small"||t==="large"||t==="xl"?t:"medium"}function TPt(t){return wPt[iW(t)]}function EPt(t){return SPt[iW(t)]}const APt=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 kPt(t){const e=t.toLowerCase().replace(/:\d+$/,"");return!!(APt.has(e)||e.endsWith(".lovable.app")||e.endsWith(".lovableproject.com")||e.endsWith(".lovable.dev"))}function vEe(){return new URLSearchParams(window.location.search).get("previewSlug")}function CPt(){const t=vEe();if(t)return t;const r=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return r?r[1]:null}function jPt(){const t=CPt(),e=!!vEe(),r=window.location.hostname,n=t?null:ohe(r),i=!t&&!kPt(r)&&r.includes(".")&&!ahe(r),a=t||n||(i?r:null),{data:c,isLoading:s,error:f}=wr({queryKey:["lead-site",a,i,e],queryFn:async()=>{var G;if(!a)return null;const x=Le.from("lead_sites").select("*"),_=e?x:x.eq("is_active",!0);let T;if(t)T=await _.eq("subdomain_slug",t).maybeSingle();else if(n)T=await _.ilike("custom_domain",n).maybeSingle();else if(i)T=await _.ilike("custom_domain",r).maybeSingle();else return null;const{data:E,error:C}=T;if(C)throw C;if(!E)return null;const{data:N}=await Le.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",E.agent_id).single();let R=null;if(E.show_team_logo)if(E.team_logo_url)R=E.team_logo_url;else{const{data:W}=await Le.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",E.agent_id).limit(1).maybeSingle();W&&((G=W.teams)!=null&&G.avatar_url)&&(R=W.teams.avatar_url)}const D=E.theme_config||{},M=W=>typeof W=="string"&&W.trim()?W.trim():null,B={id:E.id,agentId:E.agent_id,subdomainSlug:E.subdomain_slug,customDomain:E.custom_domain||null,mlsProviderId:E.mls_provider_id,siteTitle:E.site_title,siteTagline:E.site_tagline,leadRegistrationMode:E.lead_registration_mode||"disabled",registrationTriggerCount:E.registration_trigger_count??1,themeConfig:E.theme_config||{},themeTier:E.theme_tier||"basic",planTier:E.plan_tier||"paid",ownerType:E.owner_type||"agent",orgTier:E.org_tier||"essential",brokerageId:E.brokerage_id||null,teamId:E.team_id||null,orgName:E.org_name||null,orgLogoUrl:E.org_logo_url||null,orgLogoDarkUrl:E.org_logo_dark_url||null,orgProfile:E.org_profile||{},brandColor:E.brand_color||void 0,accentColor:E.accent_color||void 0,mlsServiceCities:Array.isArray(E.mls_service_cities)?E.mls_service_cities:[],isActive:E.is_active,brokerageLegalName:E.brokerage_legal_name||null,brokerageLicenseNumber:E.brokerage_license_number||null,agentLicenseNumber:E.agent_license_number||null,licenseState:E.license_state||null,mlsDisclaimerText:E.mls_disclaimer_text||null,mlsLogoUrl:E.mls_logo_url||null,equalHousingEnabled:E.equal_housing_enabled??!0,faviconUrl:E.favicon_url||null,ogImageUrl:E.og_image_url||null,showTeamLogo:E.show_team_logo??!1,teamLogoUrl:R,headerLogoSize:iW(D.headerLogoSize),valuationLabel:M(D.valuationLabel),noMlsMode:E.no_mls_mode===!0,bookingUrl:E.booking_url||null,pageSubtitles:E.page_subtitles||{},agent:N?{id:N.id,full_name:N.name||"",avatar_url:M(D.agentHeadshotUrl)||N.avatar_url,email:N.email,phone:N.phone,title:M(D.agentTitle)||N.title,bio:M(D.agentBio)||N.bio,areas_served:N.areas_served||null,years_experience:N.years_experience??null,instagram_url:N.instagram_url||null,facebook_url:N.facebook_url||null,linkedin_url:N.linkedin_url||null,google_business_url:N.google_business_url||null,zillow_profile_url:N.zillow_profile_url||null,realtor_profile_url:N.realtor_profile_url||null,specialties:N.specialties||null}:void 0,testimonials:Array.isArray(E.testimonials)?E.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:E.seo_meta_title||null,seoMetaDescription:E.seo_meta_description||null,googleSearchConsoleVerification:E.google_search_console_verification||null},V=bPt(E);return{siteConfig:B,themeConfig:V}},enabled:!!a,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1}),m=n||(i?r:null);return{siteConfig:(c==null?void 0:c.siteConfig)??null,themeConfig:(c==null?void 0:c.themeConfig)??null,isLoading:s,error:f,slug:t??(c==null?void 0:c.siteConfig.subdomainSlug)??null,customDomain:m}}async function IPt(t,e){try{await Le.functions.invoke("lead-site-notify",{body:{lead:e,lead_site_id:t}})}catch(r){console.warn("Lead notification failed:",r)}}function bEe(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 PPt=ox({lead_site_id:Xi().uuid(),name:Xi().trim().min(1).max(160),email:Xi().trim().email().max(255),phone:Xi().max(40).nullable().optional(),message:Xi().max(5e3).nullable().optional(),source_page:Xi().max(2e3).nullable().optional(),lead_type:Xi().max(100),metadata:bGe(Xi(),b6()).nullable().optional()});async function V8(t){const e=PPt.safeParse(t);if(!e.success)return{error:new Error("Please check your name, email, and message.")};const{error:r}=await Le.rpc("submit_identified_website_lead",{_site_id:e.data.lead_site_id,_token:bEe(e.data.lead_site_id),_lead:e.data});return{error:r}}async function W8t(t,e,r){const{error:n}=await Le.rpc("record_identified_property_view",{_site_id:t,_token:bEe(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 K8t(t,e,r,n,i){return t!=="disabled"&&!e&&!r&&n>i}const wEe=P.createContext(null);function qS(){const t=P.useContext(wEe);if(!t)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return t}function Ooe({siteConfig:t,children:e}){const[r,n]=P.useState(null),[i,a]=P.useState(null),[c,s]=P.useState(!0);P.useEffect(()=>{let _=!0,T=0;const E=async R=>{var B;const D=++T;let{data:M}=await Le.from("lead_site_consumer_profiles").select("id, name, phone, contact_id").eq("user_id",R.id).eq("lead_site_id",t.id).maybeSingle();if(M&&!M.contact_id||!M&&((B=R.user_metadata)==null?void 0:B.consumer_site_id)===t.id){const{data:V}=await Le.from("lead_site_consumer_profiles").upsert({user_id:R.id,lead_site_id:t.id,name:(M==null?void 0:M.name)||R.user_metadata.full_name||"Website visitor",phone:(M==null?void 0:M.phone)||R.user_metadata.consumer_phone||null},{onConflict:"user_id,lead_site_id"}).select("id,name,phone").single();M=V}!_||D!==T||(a(M?{...M,email:R.email||""}:null),s(!1))},{data:{subscription:C}}=Le.auth.onAuthStateChange((R,D)=>{const M=(D==null?void 0:D.user)??null;n(M),M?window.setTimeout(()=>void E(M),0):(T+=1,a(null),s(!1))}),N=window.setTimeout(()=>{_&&(console.warn("Lead site auth initialization timed out."),s(!1))},8e3);return()=>{_=!1,window.clearTimeout(N),C.unsubscribe()}},[t.id]),P.useEffect(()=>{const _=new URL(window.location.href),T=_.searchParams.get("signin");T&&(_.searchParams.delete("signin"),window.history.replaceState({},"",_.pathname+_.search+_.hash),Le.auth.verifyOtp({type:"email",token_hash:T}).then(({error:E})=>{E&&console.warn("Sign-in link could not be used (it may already be used or expired).",E.message)}))},[]);const f=P.useCallback(async _=>{const T=_.email.toLowerCase().trim(),{data:E,error:C}=await Le.functions.invoke("consumer-auth-link",{body:{site_id:t.id,email:T,name:_.name.trim(),phone:_.phone.trim(),mode:"signup",redirect_to:window.location.href}});if(C)throw C;let N=!1;if(E!=null&&E.token_hash){const{error:R}=await Le.auth.verifyOtp({type:"email",token_hash:E.token_hash});R?console.error("Instant sign-in after registration failed:",R):N=!0}{const{error:R}=await V8({lead_site_id:t.id,name:_.name.trim(),email:T,phone:_.phone.trim(),message:N?"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:!N}});if(R)throw R;IPt(t.id,{name:_.name.trim(),email:T,phone:_.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}return{instant:N,existing:(E==null?void 0:E.new_account)===!1}},[t.id]),m=P.useCallback(async(_,T)=>{const E=_.toLowerCase().trim(),{data:C,error:N}=await Le.functions.invoke("consumer-auth-link",{body:{site_id:t.id,email:E,mode:"signin",redirect_to:window.location.href}});if(N)throw N;let R=!1;if(C!=null&&C.token_hash){const{error:D}=await Le.auth.verifyOtp({type:"email",token_hash:C.token_hash});D||(R=!0,V8({lead_site_id:t.id,email:E,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:R}},[t.id]),x=P.useCallback(async()=>{await Le.auth.signOut(),n(null),a(null)},[]);return o.jsx(wEe.Provider,{value:{user:r,profile:i,isLoading:c,signUp:f,signIn:m,signOut:x},children:e})}const SEe=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),TEe=new Set(["tomlois"]);function Xy(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||SEe.has(t.id||"")||TEe.has((t.subdomainSlug||"").toLowerCase())||!t.mlsProviderId:!1}function NPt(t,e){var r;return t?((r=t.themeConfig)==null?void 0:r.referralMode)===!0||SEe.has(t.id||"")||TEe.has((t.subdomainSlug||"").toLowerCase()):!1}function Y8t(t,e){return NPt(t)?"referral":Xy(t,e)?"direct":"idx"}function Z8t(t){return`Contact ${t.split(" ")[0]||"Me"}`}const RPt="free_luxury",LPt="free_beta";function EEe(t){const e=t==null?void 0:t.planTier;return e===RPt||e===LPt}const X8t={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."}},GS="#c9a96e",DPt="Schedule a Free Consultation",OPt={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function Sm({bookingUrl:t,label:e=DPt,className:r="",variant:n="solid",color:i=GS,size:a="md",onDark:c=!0,source:s}){if(!t)return null;const f=`inline-flex items-center justify-center gap-2.5 font-semibold tracking-[0.18em] uppercase rounded-full transition-all duration-300 ${OPt[a]}`,m=n==="solid"?{backgroundColor:i,color:"#0d0b0a",boxShadow:`0 10px 30px -12px ${i}`}:{borderColor:i,color:i,borderWidth:1};return o.jsxs("a",{href:t,target:"_blank",rel:"noopener noreferrer","data-schedule-source":s,className:`${f} ${n==="solid"?"hover:brightness-110":`border hover:bg-[${i}]/10`} ${n==="outline"&&!c?"bg-white/0":""} ${r}`,style:m,children:[o.jsx(dG,{className:"h-4 w-4 flex-shrink-0"}),o.jsx("span",{children:e})]})}function Q8t({bookingUrl:t,agentName:e,accentColor:r=GS,config:n={},luxury:i=!0}){const a=n.bookingUrl||t;if(!a)return null;const c=n.eyebrow||"No Cost. No Obligation.",s=n.sectionTitle||"Schedule a Free Consultation",f=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.`,m=n.buttonLabel||"Book My Free Consultation",x=[{icon:mc,title:n.point1Title||"30 Minutes",text:n.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:cLe,title:n.point2Title||"A Personal Call",text:n.point2Text||`${e.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:xc,title:n.point3Title||"Real Answers",text:n.point3Text||"Pricing, strategy, and next steps for buying or selling — free of charge."}],_=i?"bg-[#12100e]":"bg-gray-950";return o.jsxs("section",{className:`relative py-24 ${_} overflow-hidden`,children:[o.jsx("div",{className:"absolute inset-0 opacity-[0.07] pointer-events-none",style:{background:`radial-gradient(circle at 50% 0%, ${r}, transparent 60%)`}}),o.jsx("div",{className:"relative max-w-5xl mx-auto px-6 text-center",children:o.jsxs(pr.div,{initial:{opacity:0,y:24},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{duration:.7},children:[o.jsxs("div",{className:"flex items-center justify-center gap-4 mb-5",children:[o.jsx("div",{className:"h-px w-12 bg-white/10"}),o.jsx("span",{className:"text-[11px] tracking-[0.4em] uppercase",style:{color:r},children:c}),o.jsx("div",{className:"h-px w-12 bg-white/10"})]}),o.jsx("h2",{className:"text-3xl md:text-5xl text-white tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:s}),o.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:f}),o.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-14 text-left",children:x.map((T,E)=>o.jsxs("div",{className:"border border-white/10 bg-white/[0.03] p-6",children:[o.jsx(T.icon,{className:"h-5 w-5 mb-4",style:{color:r}}),o.jsx("p",{className:"text-white text-sm tracking-[0.15em] uppercase mb-2",children:T.title}),o.jsx("p",{className:"text-white/45 text-sm leading-relaxed",children:T.text})]},E))}),o.jsxs("div",{className:"mt-12 flex flex-col items-center gap-4",children:[o.jsx(Sm,{bookingUrl:a,label:m,size:"lg",color:r,source:"home_section"}),o.jsx("p",{className:"text-white/30 text-xs tracking-[0.2em] uppercase",children:"Opens in a new tab · Free 30-minute consultation"})]})]})})]})}function J8t({bookingUrl:t,accentColor:e=GS,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?o.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:[o.jsxs("div",{children:[o.jsx("p",{className:`text-lg ${i?"text-white":"text-gray-900"}`,style:{fontFamily:"'Playfair Display', Georgia, serif"},children:r}),o.jsx("p",{className:`text-sm mt-1 ${i?"text-white/45":"text-gray-600"}`,children:n})]}),o.jsx(Sm,{bookingUrl:t,label:"Schedule Now",color:e,size:"sm",className:"flex-shrink-0",source:c})]}):null}function MPt({bookingUrl:t,accentColor:e=GS}){const[r,n]=P.useState(!1),[i,a]=P.useState(!1);if(P.useEffect(()=>{sessionStorage.getItem("schedule-cta-dismissed")==="1"&&a(!0);const s=()=>n(window.scrollY>260);return s(),window.addEventListener("scroll",s,{passive:!0}),()=>window.removeEventListener("scroll",s)},[]),!t||i)return null;const c=()=>{sessionStorage.setItem("schedule-cta-dismissed","1"),a(!0)};return o.jsxs(o.Fragment,{children:[o.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:o.jsxs("div",{className:"bg-[#0d0b0a]/95 backdrop-blur-lg border-t border-white/10 px-4 py-3 flex items-center gap-3",children:[o.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:[o.jsx(dG,{className:"h-4 w-4"}),"Schedule Free Consultation"]}),o.jsx("button",{onClick:c,"aria-label":"Dismiss",className:"p-2 text-white/40 hover:text-white",children:o.jsx(Ks,{className:"h-4 w-4"})})]})}),o.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:o.jsx(Sm,{bookingUrl:t,label:"Schedule a Free Consultation",size:"sm",color:e,source:"sticky"})})]})}function FPt({bookingUrl:t,agentName:e}){return P.useEffect(()=>{if(t){const r=setTimeout(()=>window.location.replace(t),400);return()=>clearTimeout(r)}},[t]),o.jsx("div",{className:"min-h-[70vh] flex items-center justify-center bg-[#0d0b0a] px-6 text-center",children:o.jsxs("div",{children:[o.jsx(dG,{className:"h-8 w-8 mx-auto mb-6",style:{color:GS}}),o.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"}),o.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&&o.jsx("div",{className:"mt-8",children:o.jsx(Sm,{bookingUrl:t,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}const sW=` 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 c3(t){return wr({queryKey:["lead-site-exchange-listings",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:e,error:r}=await Le.from("listings").select(sW).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 aW(t){return wr({queryKey:["lead-site-sold-listings",t],enabled:!!t,staleTime:5*60*1e3,queryFn:async()=>{const{data:e,error:r}=await Le.from("listings").select(sW).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 eqt(t,e){return wr({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=Le.from("listings").select(sW).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 tqt(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 rqt(t){return t?`$${t.toLocaleString()}`:"Price upon request"}const BPt="b4e0faa0-5246-4b05-8545-18596e7ff784",zPt=ox({name:Xi().trim().min(1,"Please enter your name.").max(160),email:Xi().trim().email("Please enter a valid email.").max(255),phone:Xi().trim().max(40),interest:MM(["Buying a home","Selling a home","Buying and selling","eXp Ready program","Other"]),preferredTime:Xi().trim().max(200),message:Xi().trim().max(4e3)});async function nqt(t,e){const r=zPt.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 V8({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 Le.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}}}function oW({open:t,mode:e,siteConfig:r,onComplete:n,onSkip:i,theme:a="default",accentColor:c}){var Ne;const{signUp:s,signIn:f}=qS(),[m,x]=P.useState(!1),[_,T]=P.useState(""),[E,C]=P.useState(""),[N,R]=P.useState(""),[D,M]=P.useState(!1),[B,V]=P.useState(""),[G,W]=P.useState(!1),[X,Q]=P.useState(!1),[re,se]=P.useState(!1),ue=e==="required",_e=a==="luxury",Se=c||(_e?"#c9a96e":"#2563eb"),ve=((Ne=r.agent)==null?void 0:Ne.full_name)||"the agent",Oe={borderColor:`${Se}66`,"--tw-ring-color":`${Se}66`},Ae=async Ie=>{if(Ie.preventDefault(),V(""),!E.trim()||!m&&!N.trim()){V("Email and phone number are required.");return}if(!m&&!_.trim()){V("Name is required.");return}const Te=N.replace(/\D/g,"");if(!m&&Te.length<7){V("Please enter a valid phone number.");return}M(!0);try{const be=m?await f(E,N):await s({name:_,email:E,phone:N});be!=null&&be.instant?Q(!0):(se(!m&&!!(be!=null&&be.existing)),W(!0))}catch(be){const We=String((be==null?void 0:be.message)||"").toLowerCase();We.includes("rate")||We.includes("429")||We.includes("too many")?V("We just sent you a link — please check your inbox (and spam) or try again in a minute."):We.includes("email")&&We.includes("valid")?V("Please double-check your email address and try again."):V("We couldn't complete that just now. Please check your email address and try again.")}finally{M(!1)}},we="w-full",ge=_e?Oe:void 0;return o.jsx(ro,{open:t,onOpenChange:ue?void 0:Ie=>{Ie||i()},children:o.jsxs($a,{className:"sm:max-w-md bg-background text-foreground",onPointerDownOutside:ue?Ie=>Ie.preventDefault():void 0,onEscapeKeyDown:ue?Ie=>Ie.preventDefault():void 0,children:[o.jsxs(ul,{children:[o.jsx(Go,{className:"text-xl",style:_e?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:m?"Welcome Back":ue?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),o.jsx(ld,{children:m?"Receive a secure sign-in link by email. No password needed.":`Create a free account to save favorites, get alerts, and connect with ${ve}.`})]}),X?o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsxs("p",{className:"text-sm text-foreground",children:["You're all set",_.trim()?`, ${_.trim().split(" ")[0]}`:"","! Your account is active and you're signed in — everything you view and save is now connected to your account."]}),o.jsx(Ut,{className:"w-full",onClick:n,children:"Start browsing"})]}):G?o.jsxs("div",{className:"space-y-4 py-4",children:[o.jsx("p",{className:"text-sm text-foreground",children:re?"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."}),o.jsx(Ut,{className:"w-full",onClick:n,children:"Continue browsing"})]}):o.jsxs("form",{onSubmit:Ae,className:"space-y-3 mt-2",children:[!m&&o.jsx(Ur,{type:"text",required:!0,placeholder:"Your name",value:_,onChange:Ie=>T(Ie.target.value),className:we,style:ge}),o.jsx(Ur,{type:"email",required:!0,placeholder:"Email address",value:E,onChange:Ie=>C(Ie.target.value),className:we,style:ge}),!m&&o.jsx("div",{children:o.jsx(Ur,{type:"tel",required:!0,placeholder:"Phone number",value:N,onChange:Ie=>R(Ie.target.value),className:we,style:ge})}),B&&o.jsx("p",{className:"text-destructive text-sm",children:B}),o.jsx(Ut,{type:"submit",disabled:D,className:"w-full",children:D?m?"Sending link...":"Creating account...":m?"Email Sign-In Link":"Create Account"}),o.jsx(Ut,{variant:"ghost",type:"button",onClick:()=>{x(!m),V("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",children:m?"Don't have an account? Sign up":"Already have an account? Sign in"}),!ue&&!m&&o.jsx(Ut,{variant:"ghost",type:"button",onClick:i,className:"w-full text-muted-foreground",children:"Skip for now"})]}),o.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 AEe=[{tab:"saved",label:"Saved Homes",icon:tp},{tab:"searches",label:"Saved Searches & Alerts",icon:$y},{tab:"viewed",label:"Recently Viewed",icon:KO},{tab:"profile",label:"Profile & Preferences",icon:pG}];function kEe(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 lW({triggerClassName:t,avatarClassName:e,showSaved:r=!0,savedClassName:n}){const{user:i,profile:a,signOut:c}=qS(),s=ma();if(!i)return null;const f=kEe(a,i.email);return o.jsxs("div",{className:"flex items-center gap-1",children:[r&&o.jsxs(cs,{to:"/account?tab=saved",className:n,"aria-label":"Saved homes",children:[o.jsx(tp,{className:"h-4 w-4"}),o.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),o.jsxs(UC,{modal:!1,children:[o.jsxs(VC,{className:t,"aria-label":"Your account",children:[o.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:f.initials}),o.jsx("span",{className:"hidden max-w-[8rem] truncate lg:inline",children:f.first}),o.jsx(od,{className:"h-3.5 w-3.5 opacity-70"})]}),o.jsxs(wS,{align:"end",className:"z-[80] w-64",children:[o.jsxs(Hge,{className:"font-normal",children:[o.jsx("p",{className:"text-xs text-muted-foreground",children:"Signed in as"}),o.jsx("p",{className:"truncate text-sm font-semibold",children:f.name}),f.email&&o.jsx("p",{className:"truncate text-xs text-muted-foreground",children:f.email})]}),o.jsx(uk,{}),AEe.map(({tab:m,label:x,icon:_})=>o.jsxs(vu,{onSelect:()=>s(`/account?tab=${m}`),className:"cursor-pointer gap-2",children:[o.jsx(_,{className:"h-4 w-4"}),x]},m)),o.jsx(uk,{}),o.jsxs(vu,{onSelect:async()=>{await c(),s("/")},className:"cursor-pointer gap-2",children:[o.jsx(YO,{className:"h-4 w-4"}),"Sign Out"]})]})]})]})}function cW({onNavigate:t,dark:e}){const{user:r,profile:n,signOut:i}=qS(),a=ma();if(!r)return null;const c=kEe(n,r.email),s=`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 o.jsxs("div",{className:`mt-3 rounded-xl border p-2 ${e?"border-white/15":"border-gray-200"}`,children:[o.jsxs("div",{className:"flex items-center gap-3 px-2 py-2",children:[o.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}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("p",{className:`truncate text-sm font-semibold ${e?"text-white":"text-gray-900"}`,children:c.name}),c.email&&o.jsx("p",{className:`truncate text-xs ${e?"text-white/50":"text-gray-500"}`,children:c.email})]})]}),AEe.map(({tab:f,label:m,icon:x})=>o.jsxs("button",{className:s,onClick:()=>{a(`/account?tab=${f}`),t()},children:[o.jsx(x,{className:"h-4 w-4"}),m]},f)),o.jsxs("button",{className:s,onClick:async()=>{await i(),t(),a("/")},children:[o.jsx(YO,{className:"h-4 w-4"}),"Sign Out"]})]})}function uW(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 $Pt(t,e){const r=uW(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 dW({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=!Xy(t),s=(r.areas_served||"").split(/,|;|\|/).map(Q=>Q.trim()).filter(Boolean),f=s[0]||"",[m,x]=f.split(/,\s*/),_=(r.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],T=[...new Set(_.map(Q=>Q.toUpperCase()))],E=t.testimonials||[],C=E.length?{"@type":"AggregateRating",ratingValue:(E.reduce((Q,re)=>Q+(re.rating||5),0)/E.length).toFixed(1),reviewCount:E.length,bestRating:5,worstRating:1}:void 0,N=[r.google_business_url,r.zillow_profile_url,r.realtor_profile_url,r.linkedin_url,r.facebook_url,r.instagram_url].filter(Boolean),R=(r.specialties||"").split(/,|;|\n/).map(Q=>Q.trim()).filter(Boolean),D={"@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${f?` serving ${f}`:""}.`,priceRange:"$$",...N.length&&{sameAs:N},...t.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:t.brokerageLegalName,...t.brokerageLicenseNumber&&{identifier:t.brokerageLicenseNumber}}},...t.agentLicenseNumber&&{identifier:t.agentLicenseNumber},...m&&{address:{"@type":"PostalAddress",addressLocality:m,...x&&{addressRegion:x},addressCountry:"US"}},...s.length&&{areaServed:s.map(Q=>{const[re,se]=Q.split(/,\s*/);return{"@type":"City",name:re,...se&&{containedInPlace:{"@type":"State",name:se}}}})},...C&&{aggregateRating:C},...E.length&&{review:E.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}}}))}},M={"@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"}},...N.length&&{sameAs:N},knowsAbout:[...new Set([...R,"Residential Real Estate","Home Buying","Home Selling",...s.map(Q=>`${Q} Real Estate`)])].filter(Boolean).slice(0,25),...R.length&&{makesOffer:R.slice(0,12).map(Q=>({"@type":"Offer",itemOffered:{"@type":"Service",name:Q,serviceType:"Real Estate Service"}}))},...T.length&&{hasCredential:T.map(Q=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:Q}))},...t.brokerageLegalName&&{worksFor:{"@type":"Organization",name:t.brokerageLegalName}}},B=uW(t.siteTitle,r.full_name),V=$Pt(t.siteTitle,r.full_name),G={"@context":"https://schema.org","@type":"WebSite","@id":`${n}/#website`,name:B,...V.length?{alternateName:V}:{},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${f?` in ${f}`:""}.`,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"}],X={"@context":"https://schema.org","@type":"ItemList","@id":`${n}/#nav`,name:"Main Navigation",itemListElement:W.map((Q,re)=>({"@type":"SiteNavigationElement",position:re+1,name:Q.name,description:Q.description,url:`${n}${Q.path}`}))};return o.jsxs(jl,{children:[o.jsx("script",{type:"application/ld+json",children:JSON.stringify(D)}),o.jsx("script",{type:"application/ld+json",children:JSON.stringify(M)}),o.jsx("script",{type:"application/ld+json",children:JSON.stringify(G)}),o.jsx("script",{type:"application/ld+json",children:JSON.stringify(X)})]})}function iqt({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 o.jsx(jl,{children:o.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function sqt({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 o.jsx(jl,{children:o.jsx("script",{type:"application/ld+json",children:JSON.stringify(n)})})}function UPt({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 o.jsx(jl,{children:o.jsx("script",{type:"application/ld+json",children:JSON.stringify(e)})})}function aqt({title:t,description:e,publishedAt:r,imageUrl:n,slug:i,siteConfig:a}){const c=a.customDomain?`https://${a.customDomain}`:`https://${a.subdomainSlug}.thelocalmove.com`,s=a.agent,f={"@context":"https://schema.org","@type":"Article",headline:t,description:e,url:`${c}/blog/${i}`,datePublished:r,...n&&{image:n},author:s?{"@type":"Person",name:s.full_name,url:c}:void 0,publisher:{"@type":"Organization",name:a.siteTitle||(s==null?void 0:s.full_name)||"Agent",url:c}};return o.jsx(jl,{children:o.jsx("script",{type:"application/ld+json",children:JSON.stringify(f)})})}function oqt({videoId:t,title:e,description:r,thumbnailUrl:n,uploadDate:i,durationSeconds:a}){const c=a&&a>0?a:null,s=c?`PT${Math.floor(c/3600)?`${Math.floor(c/3600)}H`:""}${Math.floor(c%3600/60)}M${c%60}S`:void 0,f={"@context":"https://schema.org","@type":"VideoObject",name:e,description:r,thumbnailUrl:n||`https://i.ytimg.com/vi/${t}/maxresdefault.jpg`,...i&&{uploadDate:i},...s&&{duration:s},embedUrl:`https://www.youtube.com/embed/${t}`,contentUrl:`https://www.youtube.com/watch?v=${t}`};return o.jsx(jl,{children:o.jsx("script",{type:"application/ld+json",children:JSON.stringify(f)})})}const VPt="Home Valuation";function qPt(t){return(t.valuationLabel||"").trim()||VPt}function GPt(t){return t.split(" ").map(e=>e.length>1&&e===e.toUpperCase()?e:e.toLowerCase()).join(" ")}function hW({siteConfig:t}){var R;const e=Wi(),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",s=((R=c.split(/,|;|\|/)[0])==null?void 0:R.trim())||"the local area",f=r.years_experience,m=r.phone||"",x=r.email,_=t.agentLicenseNumber,T=!Xy(t),E=(r.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],C=[...new Set(E.map(D=>D.toUpperCase()))],N=[{question:`Who is ${i}?`,answer:`${i} is a ${r.title||"REALTOR®"} with ${a}${f?`, with ${f}+ 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 ${m?`phone at ${m}, `:""}email at ${x}, or by booking a consultation directly through this website.`},...C.length?[{question:`What real estate designations does ${i} hold?`,answer:`${i} holds the following professional designations: ${C.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],..._?[{question:`Is ${i} a licensed real estate agent?`,answer:`Yes, ${i} is a fully licensed real estate professional (License #${_}) with ${a}.`}]:[],...T?[{question:`How do I search for homes for sale in ${s}?`,answer:`Use the property search on this site to view current MLS listings in ${s}. 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 ${s}?`,answer:T?`${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 ${s}?`,answer:`Request a free, no-obligation ${GPt(qPt(t))} from ${i}. ${i.split(" ")[0]} reviews recent local sales and current market conditions in ${s} to give you a realistic picture of your home's value.`}];return o.jsx(UPt,{faqs:N})}const Moe="ls_visitor_geo",HPt=1e3*60*60,Qz="lu_lc_attrib_v1",WPt=1e3*60*60*24*90;function KPt(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 YPt(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 ZPt(){try{const t=localStorage.getItem(Moe);if(t){const e=JSON.parse(t);if(Date.now()-e.ts{a.current||(a.current=!0,ZPt().then(c=>{i.current=c}))},[]),P.useEffect(()=>{if(!(t!=null&&t.id))return;const c=r.pathname;if(c===n.current)return;n.current=c;const s=KPt(c),f=YPt(c,s),m=localStorage.getItem(`ls_visitor_fp_${t.id}`)||null,x=i.current;(async()=>{const T=new URLSearchParams(r.search),E=T.get("luc");if(E&&/^[0-9a-f-]{36}$/i.test(E)){try{localStorage.setItem(Qz,JSON.stringify({contact_id:E,ts:Date.now()}))}catch{}return E}const C=T.get("lc");if(C&&/^[0-9a-f-]{36}$/i.test(C)){const{data:N}=await Le.from("listing_email_recipients").select("contact_id").eq("id",C).maybeSingle(),R=N==null?void 0:N.contact_id;if(R){try{localStorage.setItem(Qz,JSON.stringify({contact_id:R,ts:Date.now()}))}catch{}return R}}try{const N=localStorage.getItem(Qz);if(N){const R=JSON.parse(N);if(R!=null&&R.contact_id&&Date.now()-(R.ts||0){Le.from("lead_site_page_views").insert({lead_site_id:t.id,page_type:s,page_path:c,page_title:f,visitor_fingerprint:m,auth_user_id:e||null,contact_id:T,visitor_city:(x==null?void 0:x.city)||null,visitor_region:(x==null?void 0:x.region)||null,visitor_country:(x==null?void 0:x.country)||null,visitor_lat:(x==null?void 0:x.lat)||null,visitor_lng:(x==null?void 0:x.lng)||null}).then(({error:E})=>{E&&console.error("[PageTracking] insert failed:",E.message)})})},[r.pathname,r.search,t==null?void 0:t.id,e])}const XPt=3e4;function pW(t,e){const r=Wi(),n=P.useRef(null),i=P.useRef(null),a=P.useRef(0),c=r.pathname,s=QPt(c),f=JPt(c,s),m=s==="listing"&&c.split("/listing/")[1]||null;P.useEffect(()=>{if(!(t!=null&&t.id)||!e)return;s==="listing"&&(a.current+=1);const x=localStorage.getItem(`ls_visitor_fp_${t.id}`)||null,_=async()=>{const{data:T,error:E}=await Le.from("lead_site_active_visitors").upsert({lead_site_id:t.id,auth_user_id:e,visitor_fingerprint:x,current_page_path:c,current_page_title:f,current_mls_number:m,last_seen_at:new Date().toISOString(),listing_views_count:a.current},{onConflict:"lead_site_id,session_key"}).select("id, notified_agent").single();!E&&T&&(n.current=T.id,a.current>=2&&!T.notified_agent&&Le.functions.invoke("lead-site-presence-notify",{body:{visitor_id:T.id,lead_site_id:t.id}}).catch(()=>{}))};return _(),i.current&&clearInterval(i.current),i.current=setInterval(_,XPt),()=>{i.current&&clearInterval(i.current)}},[t==null?void 0:t.id,e,c]),P.useEffect(()=>{if(!(t!=null&&t.id)||!e)return;const x=()=>{n.current&&Le.from("lead_site_active_visitors").delete().eq("id",n.current).then(()=>{})};return window.addEventListener("beforeunload",x),()=>window.removeEventListener("beforeunload",x)},[t==null?void 0:t.id,e])}function QPt(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 JPt(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 fn=Number.isFinite||function(t){return typeof t=="number"&&isFinite(t)},eNt=Number.isSafeInteger||function(t){return typeof t=="number"&&Math.abs(t)<=tNt},tNt=Number.MAX_SAFE_INTEGER||9007199254740991;let Ln=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}({}),Qt=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.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_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.UNKNOWN="unknown",t}({}),ke=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}({});var Vi={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Sn={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class Vb{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 rNt{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 Vb(e),this.fast_=new Vb(r),this.defaultTTFB_=i,this.ttfb_=new Vb(e)}update(e,r){const{slow_:n,fast_:i,ttfb_:a}=this;n.halfLife!==e&&(this.slow_=new Vb(e,n.getEstimate(),n.getTotalWeight())),i.halfLife!==r&&(this.fast_=new Vb(r,i.getEstimate(),i.getTotalWeight())),a.halfLife!==e&&(this.ttfb_=new Vb(e,a.getEstimate(),a.getTotalWeight()))}sample(e,r){e=Math.max(e,this.minDelayMs_);const n=8*r,i=e/1e3,a=n/i;this.fast_.sample(i,a),this.slow_.sample(i,a)}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(){}}function nNt(t,e,r){return(e=sNt(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Ys(){return Ys=Object.assign?Object.assign.bind():function(t){for(var e=1;e`):Jg}function Boe(t,e,r){return e[t]?e[t].bind(e):oNt(t,r)}const G8=q8();function lNt(t,e,r){const n=q8();if(typeof console=="object"&&t===!0||typeof t=="object"){const i=["debug","log","info","warn","error"];i.forEach(a=>{n[a]=Boe(a,t,r)});try{n.log(`Debug logs enabled for "${e}" in hls.js version 1.6.16`)}catch{return q8()}i.forEach(a=>{G8[a]=Boe(a,t)})}else Ys(G8,n);return n}const $s=G8;function Qy(t=!0){return typeof self>"u"?void 0:(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function cNt(t){return typeof self<"u"&&t===self.ManagedMediaSource}function CEe(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 id(t,e=!1){if(typeof TextDecoder<"u"){const m=new TextDecoder("utf-8").decode(t);if(e){const x=m.indexOf("\0");return x!==-1?m.substring(0,x):m}return m.replace(/\0/g,"")}const r=t.length;let n,i,a,c="",s=0;for(;s>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:c+=String.fromCharCode(n);break;case 12:case 13:i=t[s++],c+=String.fromCharCode((n&31)<<6|i&63);break;case 14:i=t[s++],a=t[s++],c+=String.fromCharCode((n&15)<<12|(i&63)<<6|(a&63)<<0);break}}return c}function Vl(t){let e="";for(let r=0;r1||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(!fn(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return To(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:s}=this,f=s[e];if(!f){s[e]={startPTS:r,endPTS:n,startDTS:i,endDTS:a,partial:c};return}f.startPTS=Math.min(f.startPTS,r),f.endPTS=Math.max(f.endPTS,n),f.startDTS=Math.min(f.startDTS,i),f.endDTS=Math.max(f.endDTS,a)}}class hNt extends IEe{constructor(e,r,n,i,a){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,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)}}function PEe(t,e){const r=Object.getPrototypeOf(t);if(r){const n=Object.getOwnPropertyDescriptor(r,e);return n||PEe(r,e)}}function fNt(t,e){const r=PEe(t,e);r&&(r.enumerable=!0,Object.defineProperty(t,e,r))}const $oe=Math.pow(2,32)-1,pNt=[].push,NEe={video:1,audio:2,id3:3,text:4};function nl(t){return String.fromCharCode.apply(null,t)}function REe(t,e){const r=t[e]<<8|t[e+1];return r<0?65536+r:r}function pi(t,e){const r=LEe(t,e);return r<0?4294967296+r:r}function Uoe(t,e){let r=pi(t,e);return r*=Math.pow(2,32),r+=pi(t,e+4),r}function LEe(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function mNt(t){const e=t.byteLength;for(let r=0;r8&&t[r+4]===109&&t[r+5]===111&&t[r+6]===111&&t[r+7]===102)return!0;r=n>1?r+n:e}return!1}function Ui(t,e){const r=[];if(!e.length)return r;const n=t.byteLength;for(let i=0;i1?i+a:n;if(c===e[0])if(e.length===1)r.push(t.subarray(i+8,s));else{const f=Ui(t.subarray(i+8,s),e.slice(1));f.length&&pNt.apply(r,f)}i=s}return r}function gNt(t){const e=[],r=t[0];let n=8;const i=pi(t,n);n+=4;let a=0,c=0;r===0?(a=pi(t,n),c=pi(t,n+4),n+=8):(a=Uoe(t,n),c=Uoe(t,n+8),n+=16),n+=2;let s=t.length+c;const f=REe(t,n);n+=2;for(let m=0;m>>31===1)return $s.warn("SIDX has hierarchical references (not supported)"),null;const C=pi(t,x);x+=4,e.push({referenceSize:T,subsegmentDuration:C,info:{duration:C/i,start:s,end:s+T-1}}),s+=T,x+=4,n=x}return{earliestPresentationTime:a,timescale:i,version:r,referencesCount:f,references:e}}function DEe(t){const e=[],r=Ui(t,["moov","trak"]);for(let i=0;i{const a=pi(i,4),c=e[a];c&&(c.default={duration:pi(i,12),flags:pi(i,20)})}),e}function yNt(t){const e=t.subarray(8),r=e.subarray(86),n=nl(e.subarray(4,8));let i=n,a;const c=n==="enca"||n==="encv";if(c){const m=Ui(e,[n])[0].subarray(n==="enca"?28:78);Ui(m,["sinf"]).forEach(_=>{const T=Ui(_,["schm"])[0];if(T){const E=nl(T.subarray(4,8));if(E==="cbcs"||E==="cenc"){const C=Ui(_,["frma"])[0];C&&(i=nl(C))}}})}const s=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const f=Ui(r,["avcC"])[0];f&&f.length>3&&(i+="."+YN(f[1])+YN(f[2])+YN(f[3]),a=KN(s==="avc1"?"dva1":"dvav",r));break}case"mp4a":{const f=Ui(e,[n])[0],m=Ui(f.subarray(28),["esds"])[0];if(m&&m.length>7){let x=4;if(m[x++]!==3)break;x=t$(m,x),x+=2;const _=m[x++];if(_&128&&(x+=2),_&64&&(x+=m[x++]),m[x++]!==4)break;x=t$(m,x);const T=m[x++];if(T===64)i+="."+YN(T);else break;if(x+=12,m[x++]!==5)break;x=t$(m,x);const E=m[x++];let C=(E&248)>>3;C===31&&(C+=1+((E&7)<<3)+((m[x]&224)>>5)),i+="."+C}break}case"hvc1":case"hev1":{const f=Ui(r,["hvcC"])[0];if(f&&f.length>12){const m=f[1],x=["","A","B","C"][m>>6],_=m&31,T=pi(f,2),E=(m&32)>>5?"H":"L",C=f[12],N=f.subarray(6,12);i+="."+x+_,i+="."+xNt(T).toString(16).toUpperCase(),i+="."+E+C;let R="";for(let D=N.length;D--;){const M=N[D];(M||R)&&(R="."+M.toString(16).toUpperCase()+R)}i+=R}a=KN(s=="hev1"?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=KN(i,r)||i;break}case"vp09":{const f=Ui(r,["vpcC"])[0];if(f&&f.length>6){const m=f[4],x=f[5],_=f[6]>>4&15;i+="."+Rf(m)+"."+Rf(x)+"."+Rf(_)}break}case"av01":{const f=Ui(r,["av1C"])[0];if(f&&f.length>2){const m=f[1]>>>5,x=f[1]&31,_=f[2]>>>7?"H":"M",T=(f[2]&64)>>6,E=(f[2]&32)>>5,C=m===2&&T?E?12:10:T?10:8,N=(f[2]&16)>>4,R=(f[2]&8)>>3,D=(f[2]&4)>>2,M=f[2]&3;i+="."+m+"."+Rf(x)+_+"."+Rf(C)+"."+N+"."+R+D+M+"."+Rf(1)+"."+Rf(1)+"."+Rf(1)+"."+0,a=KN("dav1",r)}break}}return{codec:i,encrypted:c,supplemental:a}}function KN(t,e){const r=Ui(e,["dvvC"]),n=r.length?r[0]:Ui(e,["dvcC"])[0];if(n){const i=n[2]>>1&127,a=n[2]<<5&32|n[3]>>3&31;return t+"."+Rf(i)+"."+Rf(a)}}function xNt(t){let e=0;for(let r=0;r<32;r++)e|=(t>>r&1)<<31-r;return e>>>0}function t$(t,e){const r=e+5;for(;t[e++]&128&&e{const a=n.subarray(8,24);a.some(c=>c!==0)||($s.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Vl(a)} -> ${Vl(r)}`),n.set(r,8))})}function vNt(t){const e=[];return OEe(t,r=>e.push(r.subarray(8,24))),e}function OEe(t,e){Ui(t,["moov","trak"]).forEach(n=>{const i=Ui(n,["mdia","minf","stbl","stsd"])[0];if(!i)return;const a=i.subarray(8);let c=Ui(a,["enca"]);const s=c.length>0;s||(c=Ui(a,["encv"])),c.forEach(f=>{const m=s?f.subarray(28):f.subarray(78);Ui(m,["sinf"]).forEach(_=>{const T=MEe(_);T&&e(T,s)})})})}function MEe(t){const e=Ui(t,["schm"])[0];if(e){const r=nl(e.subarray(4,8));if(r==="cbcs"||r==="cenc"){const n=Ui(t,["schi","tenc"])[0];if(n)return n}}}function bNt(t,e,r){const n={},i=Ui(t,["moof","traf"]);for(let a=0;an[a].duration)){let a=1/0,c=0;const s=Ui(t,["sidx"]);for(let f=0;f_+T.info.duration||0,0);c=Math.max(c,x+m.earliestPresentationTime/m.timescale)}}c&&fn(c)&&Object.keys(n).forEach(f=>{n[f].duration||(n[f].duration=c*n[f].timescale-n[f].start)})}return n}function wNt(t){const e={valid:null,remainder:null},r=Ui(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 eh(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function Voe(t,e){const r=[],n=e.samples,i=e.timescale,a=e.id;let c=!1;return Ui(n,["moof"]).map(f=>{const m=f.byteOffset-8;Ui(f,["traf"]).map(_=>{const T=Ui(_,["tfdt"]).map(E=>{const C=E[0];let N=pi(E,4);return C===1&&(N*=Math.pow(2,32),N+=pi(E,8)),N/i})[0];return T!==void 0&&(t=T),Ui(_,["tfhd"]).map(E=>{const C=pi(E,4),N=pi(E,0)&16777215,R=(N&1)!==0,D=(N&2)!==0,M=(N&8)!==0;let B=0;const V=(N&16)!==0;let G=0;const W=(N&32)!==0;let X=8;C===a&&(R&&(X+=8),D&&(X+=4),M&&(B=pi(E,X),X+=4),V&&(G=pi(E,X),X+=4),W&&(X+=4),e.type==="video"&&(c=u3(e.codec)),Ui(_,["trun"]).map(Q=>{const re=Q[0],se=pi(Q,0)&16777215,ue=(se&1)!==0;let _e=0;const Se=(se&4)!==0,ve=(se&256)!==0;let Oe=0;const Ae=(se&512)!==0;let we=0;const ge=(se&1024)!==0,Ne=(se&2048)!==0;let Ie=0;const Te=pi(Q,4);let be=8;ue&&(_e=pi(Q,be),be+=4),Se&&(be+=4);let We=_e+m;for(let rt=0;rt>1&63;return r===39||r===40}else return(e&31)===6}function yW(t,e,r,n){const i=FEe(t);let a=0;a+=e;let c=0,s=0,f=0;for(;a=i.length)break;f=i[a++],c+=f}while(f===255);s=0;do{if(a>=i.length)break;f=i[a++],s+=f}while(f===255);const m=i.length-a;let x=a;if(sm){$s.error(`Malformed SEI payload. ${s} is too small, only ${m} bytes left to parse.`);break}if(c===4){if(i[x++]===181){const T=REe(i,x);if(x+=2,T===49){const E=pi(i,x);if(x+=4,E===1195456820){const C=i[x++];if(C===3){const N=i[x++],R=31&N,D=64&N,M=D?2+R*3:0,B=new Uint8Array(M);if(D){B[0]=N;for(let V=1;V16){const _=[];for(let C=0;C<16;C++){const N=i[x++].toString(16);_.push(N.length==1?"0"+N:N),(C===3||C===5||C===7||C===9)&&_.push("-")}const T=s-16,E=new Uint8Array(T);for(let C=0;C>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),ENt([112,115,115,104],new Uint8Array([n,0,0,0]),t,a,i,c,r)}function kNt(t){const e=[];if(t instanceof ArrayBuffer){const r=t.byteLength;let n=0;for(;n+32>>24;if(a!==0&&a!==1)return{offset:r,size:e};const c=t.buffer,s=Vl(new Uint8Array(c,r+12,16));let f=null,m=null,x=0;if(a===0)x=28;else{const T=t.getUint32(28);if(!T||n<32+T*16)return{offset:r,size:e};f=[];for(let E=0;E/\(Windows.+Firefox\//i.test(navigator.userAgent),tS={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}};function xW(t,e){const r=tS[e];return!!r&&!!r[t.slice(0,4)]}function aC(t,e,r=!0){return!t.split(",").some(n=>!_W(n,e,r))}function _W(t,e,r=!0){var n;const i=Qy(r);return(n=i==null?void 0:i.isTypeSupported(oC(t,e)))!=null?n:!1}function oC(t,e){return`${e}/mp4;codecs=${t}`}function qoe(t){if(t){const e=t.substring(0,4);return tS.video[e]}return 2}function _O(t){const e=BEe();return t.split(",").reduce((r,n)=>{const a=e&&u3(n)?9:tS.video[n];return a?(a*2+r)/(r?3:2):(tS.audio[n]+r)/(r?2:1)},0)}const r$={};function jNt(t,e=!0){if(r$[t])return r$[t];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let i=0;ijNt(r.toLowerCase(),e))}function PNt(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)&&(Goe(t,"audio")||Goe(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 Goe(t,e){return xW(t,e)&&_W(t,e)}function NNt(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 RNt(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 Hoe(t){const e=Qy(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 H8(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const LNt={supported:!0,powerEfficient:!0,smooth:!0},DNt={supported:!1,smooth:!1,powerEfficient:!1},zEe={supported:!0,configurations:[],decodingInfoResults:[LNt]};function $Ee(t,e){return{supported:!1,configurations:e,decodingInfoResults:[DNt],error:t}}function ONt(t,e,r,n,i,a){const c=t.videoCodec,s=t.audioCodec?t.audioGroups:null,f=a==null?void 0:a.audioCodec,m=a==null?void 0:a.channels,x=m?parseInt(m):f?1/0:2;let _=null;if(s!=null&&s.length)try{s.length===1&&s[0]?_=e.groups[s[0]].channels:_=s.reduce((T,E)=>{if(E){const C=e.groups[E];if(!C)throw new Error(`Audio track group ${E} not found`);Object.keys(C.channels).forEach(N=>{T[N]=(T[N]||0)+C.channels[N]})}return T},{2:0})}catch{return!0}return c!==void 0&&(c.split(",").some(T=>u3(T))||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))||!!_&&fn(x)&&Object.keys(_).some(T=>parseInt(T)>x)}function UEe(t,e,r,n={}){const i=t.videoCodec;if(!i&&!t.audioCodec||!r)return Promise.resolve(zEe);const a=[],c=MNt(t),s=c.length,f=FNt(t,e,s>0),m=f.length;for(let x=s||1*m||1;x--;){const _={type:"media-source"};if(s&&(_.video=c[x%s]),m){_.audio=f[x%m];const T=_.audio.bitrate;_.video&&T&&(_.video.bitrate-=T)}a.push(_)}if(i){const x=navigator.userAgent;if(i.split(",").some(_=>u3(_))&&BEe())return Promise.resolve($Ee(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${x})`),a))}return Promise.all(a.map(x=>{const _=zNt(x);return n[_]||(n[_]=r.decodingInfo(x))})).then(x=>({supported:!x.some(_=>!_.supported),configurations:a,decodingInfoResults:x})).catch(x=>({supported:!1,configurations:a,decodingInfoResults:[],error:x}))}function MNt(t){var e;const r=(e=t.videoCodec)==null?void 0:e.split(","),n=VEe(t),i=t.width||640,a=t.height||480,c=t.frameRate||30,s=t.videoRange.toLowerCase();return r?r.map(f=>{const m={contentType:oC(RNt(f),"video"),width:i,height:a,bitrate:n,framerate:c};return s!=="sdr"&&(m.transferFunction=s),m}):[]}function FNt(t,e,r){var n;const i=(n=t.audioCodec)==null?void 0:n.split(","),a=VEe(t);return i&&t.audioGroups?t.audioGroups.reduce((c,s)=>{var f;const m=s?(f=e.groups[s])==null?void 0:f.tracks:null;return m?m.reduce((x,_)=>{if(_.groupId===s){const T=parseFloat(_.channels||"");i.forEach(E=>{const C={contentType:oC(E,"audio"),bitrate:r?BNt(E,a):a};T&&(C.channels=""+T),x.push(C)})}return x},c):c},[]):[]}function BNt(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 VEe(t){return Math.ceil(Math.max(t.bitrate*.9,t.averageBitrate)/1e3)*1e3||1}function zNt(t){let e="";const{audio:r,video:n}=t;if(n){const i=H8(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=H8(r.contentType);e+=`${n?"_":""}${i}_c${r.channels}`}return e}const W8=["NONE","TYPE-0","TYPE-1",null];function $Nt(t){return W8.indexOf(t)>-1}const bO=["SDR","PQ","HLG"];function UNt(t){return!!t&&bO.indexOf(t)>-1}var ZR={No:"",Yes:"YES",v2:"v2"};function Woe(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)}`)}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 Yoe(this._audioGroups,e)}hasSubtitleGroup(e){return Yoe(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 Yoe(t,e){return!e||!t?!1:t.indexOf(e)!==-1}function VNt(){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 qNt(t,e){let r=!1,n=[];if(t&&(r=t!=="SDR",n=[t]),e){n=e.allowedVideoRanges||bO.slice(0);const i=n.join("")!=="SDR"&&!e.videoCodec;r=e.preferHDR!==void 0?e.preferHDR:i&&VNt(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}const GNt=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}},ra=(t,e)=>JSON.stringify(t,GNt(e));function HNt(t,e,r,n,i){const a=Object.keys(t),c=n==null?void 0:n.channels,s=n==null?void 0:n.audioCodec,f=i==null?void 0:i.videoCodec,m=c&&parseInt(c)===2;let x=!1,_=!1,T=1/0,E=1/0,C=1/0,N=1/0,R=0,D=[];const{preferHDR:M,allowedVideoRanges:B}=qNt(e,i);for(let Q=a.length;Q--;){const re=t[a[Q]];x||(x=re.channels[2]>0),T=Math.min(T,re.minHeight),E=Math.min(E,re.minFramerate),C=Math.min(C,re.minBitrate),B.filter(ue=>re.videoRanges[ue]>0).length>0&&(_=!0)}T=fn(T)?T:0,E=fn(E)?E:0;const V=Math.max(1080,T),G=Math.max(30,E);C=fn(C)?C:r,r=Math.max(C,r),_||(e=void 0);const W=a.length>1;return{codecSet:a.reduce((Q,re)=>{const se=t[re];if(re===Q)return Q;if(D=_?B.filter(ue=>se.videoRanges[ue]>0):[],W){if(se.minBitrate>r)return Cf(re,`min bitrate of ${se.minBitrate} > current estimate of ${r}`),Q;if(!se.hasDefaultAudio)return Cf(re,"no renditions with default or auto-select sound found"),Q;if(s&&re.indexOf(s.substring(0,4))%5!==0)return Cf(re,`audio codec preference "${s}" not found`),Q;if(c&&!m){if(!se.channels[c])return Cf(re,`no renditions with ${c} channel sound found (channels options: ${Object.keys(se.channels)})`),Q}else if((!s||m)&&x&&se.channels[2]===0)return Cf(re,"no renditions with stereo sound found"),Q;if(se.minHeight>V)return Cf(re,`min resolution of ${se.minHeight} > maximum of ${V}`),Q;if(se.minFramerate>G)return Cf(re,`min framerate of ${se.minFramerate} > maximum of ${G}`),Q;if(!D.some(ue=>se.videoRanges[ue]>0))return Cf(re,`no variants with VIDEO-RANGE of ${ra(D)} found`),Q;if(f&&re.indexOf(f.substring(0,4))%5!==0)return Cf(re,`video codec preference "${f}" not found`),Q;if(se.maxScore=_O(Q)||se.fragmentError>t[Q].fragmentError)?Q:(N=se.minIndex,R=se.maxScore,re)},void 0),videoRanges:D,preferHDR:M,minFramerate:E,minBitrate:C,minIndex:N}}function Cf(t,e){$s.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function qEe(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 WNt(t,e,r,n){return t.slice(r,n+1).reduce((i,a,c)=>{if(!a.codecSet)return i;const s=a.audioGroups;let f=i[a.codecSet];f||(i[a.codecSet]=f={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:c,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),f.minBitrate=Math.min(f.minBitrate,a.bitrate);const m=Math.min(a.height,a.width);return f.minHeight=Math.min(f.minHeight,m),f.minFramerate=Math.min(f.minFramerate,a.frameRate),f.minIndex=Math.min(f.minIndex,c),f.maxScore=Math.max(f.maxScore,a.score),f.fragmentError+=a.fragmentError,f.videoRanges[a.videoRange]=(f.videoRanges[a.videoRange]||0)+1,s&&s.forEach(x=>{if(!x)return;const _=e.groups[x];_&&(f.hasDefaultAudio=f.hasDefaultAudio||e.hasDefaultAudio?_.hasDefault:_.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(_.channels).forEach(T=>{f.channels[T]=(f.channels[T]||0)+_.channels[T]}))}),i},{})}function Zoe(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 Hf(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 $_(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 ZNt(t,e,r,n,i){const a=e[n],s=e.reduce((T,E,C)=>{const N=E.uri;return(T[N]||(T[N]=[])).push(C),T},{})[a.uri];s.length>1&&(n=Math.max.apply(Math,s));const f=a.videoRange,m=a.frameRate,x=a.codecSet.substring(0,4),_=Xoe(e,n,T=>{if(T.videoRange!==f||T.frameRate!==m||T.codecSet.substring(0,4)!==x)return!1;const E=T.audioGroups,C=r.filter(N=>!E||E.indexOf(N.groupId)!==-1);return Hf(t,C,i)>-1});return _>-1?_:Xoe(e,n,T=>{const E=T.audioGroups,C=r.filter(N=>!E||E.indexOf(N.groupId)!==-1);return Hf(t,C,i)>-1})}function Xoe(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,{autoLevelEnabled:s,media:f}=c;if(!i||!f)return;const m=performance.now(),x=a?a.stats:i.stats,_=a?a.duration:i.duration,T=m-x.loading.start,E=c.minAutoLevel,C=i.level,N=this._nextAutoLevel;if(x.aborted||x.loaded&&x.loaded===x.total||C<=E){this.clearTimer(),this._nextAutoLevel=-1;return}if(!s)return;const R=N>-1&&N!==C,D=!!r||R;if(!D&&(f.paused||!f.playbackRate||!f.readyState))return;const M=c.mainForwardBufferInfo;if(!D&&M===null)return;const B=this.bwEstimator.getEstimateTTFB(),V=Math.abs(f.playbackRate);if(T<=Math.max(B,1e3*(_/(V*2))))return;const G=M?M.len/V:0,W=x.loading.first?x.loading.first-x.loading.start:-1,X=x.loaded&&W>-1,Q=this.getBwEstimate(),re=c.levels,se=re[C],ue=Math.max(x.loaded,Math.round(_*(i.bitrate||se.averageBitrate)/8));let _e=X?T-W:T;_e<1&&X&&(_e=Math.min(T,x.loaded*8/Q));const Se=X?x.loaded*1e3/_e:0,ve=B/1e3,Oe=Se?(ue-x.loaded)/Se:ue*8/Q+ve;if(Oe<=G)return;const Ae=Se?Se*8:Q,we=((n=(r==null?void 0:r.details)||this.hls.latestLevelDetails)==null?void 0:n.live)===!0,ge=this.hls.config.abrBandWidthUpFactor;let Ne=Number.POSITIVE_INFINITY,Ie;for(Ie=C-1;Ie>E;Ie--){const rt=re[Ie].maxBitrate,at=!re[Ie].details||we;if(Ne=this.getTimeToLoadFrag(ve,Ae,_*rt,at),Ne=Oe||Ne>_*10)return;X?this.bwEstimator.sample(T-Math.min(B,W),x.loaded):this.bwEstimator.sampleTTFB(T);const Te=re[Ie].maxBitrate;this.getBwEstimate()*ge>Te&&this.resetEstimator(Te);const be=this.findBestLevel(Te,E,Ie,0,G,1,1);be>-1&&(Ie=be),this.warn(`Fragment ${i.sn}${a?" part "+a.index:""} of level ${C} is loading too slowly; Fragment duration: ${i.duration.toFixed(3)} Time to underbuffer: ${G.toFixed(3)} s Estimated load time for current fragment: ${Oe.toFixed(3)} s Estimated load time for down switch fragment: ${Ne.toFixed(3)} s TTFB estimate: ${W|0} ms Current BW estimate: ${fn(Q)?Q|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${Ie} @ ${Te|0} bps`),c.nextLoadLevel=c.nextAutoLevel=Ie,this.clearTimer();const We=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===Ie&&Ie>0){const rt=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Ie>0?"and switching down":""} Fragment duration: ${i.duration.toFixed(3)} s Time to underbuffer: ${rt.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,Ie>E){let at=this.findBestLevel(this.hls.levels[E].bitrate,E,Ie,0,rt,1,1);at===-1&&(at=E),this.hls.nextLoadLevel=this.hls.nextAutoLevel=at,this.resetEstimator(this.hls.levels[at].bitrate)}}};R||Oe>Ne*2?We():this.timer=self.setInterval(We,Ne*1e3),c.trigger(ke.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:a,stats:x})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){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 rNt(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.FRAG_LOADING,this.onFragLoading,this),e.on(ke.FRAG_LOADED,this.onFragLoaded,this),e.on(ke.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ke.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ke.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ke.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ke.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(ke.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.FRAG_LOADING,this.onFragLoading,this),e.off(ke.FRAG_LOADED,this.onFragLoaded,this),e.off(ke.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ke.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ke.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ke.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ke.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(ke.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,r){this.lastLoadedFragLevel=-1,this.firstSelection=-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 Qt.BUFFER_ADD_CODEC_ERROR:case Qt.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Qt.FRAG_LOAD_TIMEOUT:{const n=r.frag,{fragCurrent:i,partCurrent:a}=this;if(n&&i&&n.sn===i.sn&&n.level===i.level){const c=performance.now(),s=a?a.stats:n.stats,f=c-s.loading.start,m=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&m>-1){const _=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(f-Math.min(_,m),s.loaded)}else this.bwEstimator.sampleTTFB(f)}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;fn(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,{frag:r,part:n}){const i=n?n.stats:r.stats;if(r.type===Sn.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const a=n?n.duration:r.duration,c=this.hls.levels[r.level],s=(c.loaded?c.loaded.bytes:0)+i.loaded,f=(c.loaded?c.loaded.duration:0)+a;c.loaded={bytes:s,duration:f},c.realBitrate=Math.round(8*s/f)}if(r.bitrateTest){const a={stats:i,frag:r,part:n,id:r.type};this.onFragBuffered(ke.FRAG_BUFFERED,a),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.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 c=a.parsing.end-a.loading.start-Math.min(a.loading.first-a.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(c,a.loaded),a.bwEstimate=this.getBwEstimate(),n.bitrateTest?this.bitrateTestDelay=c/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Sn.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:r}=this.hls,n=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,a=this.findBestLevel(n,r,e,0,i,1,1);if(a>-1)return a;const c=this.hls.firstLevel,s=Math.min(Math.max(c,r),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${c} clamped to ${s}`),s}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){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.levels.length<=1)return n.loadLevel;const{maxAutoLevel:i,config:a,minAutoLevel:c}=n,s=r?r.duration:e?e.duration:0,f=this.getBwEstimate(),m=this.getStarvationDelay();let x=a.abrBandWidthFactor,_=a.abrBandWidthUpFactor;if(m){const R=this.findBestLevel(f,c,i,m,0,x,_);if(R>=0)return this.rebufferNotice=-1,R}let T=s?Math.min(s,a.maxStarvationDelay):a.maxStarvationDelay;if(!m){const R=this.bitrateTestDelay;R&&(T=(s?Math.min(s,a.maxLoadingDelay):a.maxLoadingDelay)-R,this.info(`bitrate test took ${Math.round(1e3*R)}ms, set first fragment max fetchDuration to ${Math.round(1e3*T)} ms`),x=_=1)}const E=this.findBestLevel(f,c,i,m,T,x,_);if(this.rebufferNotice!==E&&(this.rebufferNotice=E,this.info(`${m?"rebuffering expected":"buffer is empty"}, optimal quality level ${E}`)),E>-1)return E;const C=n.levels[c],N=n.loadLevelObj;return N&&(C==null?void 0:C.bitrate)=r;Ae--){var Oe;const we=C[Ae],ge=Ae>_;if(!we)continue;if(D.useMediaCapabilities&&!we.supportedResult&&!we.supportedPromise){const at=navigator.mediaCapabilities;typeof(at==null?void 0:at.decodingInfo)=="function"&&ONt(we,se,W,X,e,Q)?(we.supportedPromise=UEe(we,se,at,this.supportedCache),we.supportedPromise.then(Et=>{if(!this.hls)return;we.supportedResult=Et;const _t=this.hls.levels,Vt=_t.indexOf(we);Et.error?this.warn(`MediaCapabilities decodingInfo error: "${Et.error}" for level ${Vt} ${ra(Et)}`):Et.supported?Et.decodingInfoResults.some(mt=>mt.smooth===!1||mt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Vt} not smooth or powerEfficient: ${ra(Et)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Vt} ${ra(Et)}`),Vt>-1&&_t.length>1&&(this.log(`Removing unsupported level ${Vt}`),this.hls.removeLevel(Vt),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Et=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Et}`)})):we.supportedResult=zEe}if((G&&we.codecSet!==G||W&&we.videoRange!==W||ge&&X>we.frameRate||!ge&&X>0&&Xat.smooth===!1))&&(!V||Ae!==ue)){ve.push(Ae);continue}const Ne=we.details,Ie=(E?Ne==null?void 0:Ne.partTarget:Ne==null?void 0:Ne.averagetargetduration)||_e;let Te;ge?Te=s*e:Te=c*e;const be=_e&&i>=_e*2&&a===0?we.averageBitrate:we.maxBitrate,We=this.getTimeToLoadFrag(Se,Te,be*Ie,Ne===void 0);if(Te>=be&&(Ae===x||we.loadError===0&&we.fragmentError===0)&&(We<=Se||!fn(We)||B&&!this.bitrateTestDelay||We${Ae} adjustedbw(${Math.round(Te)})-bitrate=${Math.round(Te-be)} ttfb:${Se.toFixed(1)} avgDuration:${Ie.toFixed(1)} maxFetchDuration:${m.toFixed(1)} fetchDuration:${We.toFixed(1)} firstSelection:${V} codecSet:${we.codecSet} videoRange:${we.videoRange} hls.loadLevel:${R}`)),V&&(this.firstSelection=Ae),Ae}}return-1}set nextAutoLevel(e){const r=this.deriveNextAutoLevel(e);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}deriveNextAutoLevel(e){const{maxAutoLevel:r,minAutoLevel:n}=this.hls;return Math.min(Math.max(e,n),r)}}const GEe={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 QNt(t,e,r){if(e===null||!Array.isArray(t)||!t.length||!fn(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&&s<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)&&Qoe(r,n,a)===0||JNt(a,t,Math.min(i,n))))return a;const c=GEe.search(e,Qoe.bind(null,r,n));return c&&(c!==t||!a)?c:a}function JNt(t,e,r){if(e&&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 Qoe(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 eRt(t,e,r){const n=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>t}function HEe(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 GEe.search(n,c=>c.cce?-1:(a=c,c.end<=r?1:c.start>r?-1:0)),a||null}return null}function SO(t){switch(t.details){case Qt.FRAG_LOAD_TIMEOUT:case Qt.KEY_LOAD_TIMEOUT:case Qt.LEVEL_LOAD_TIMEOUT:case Qt.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function WEe(t){return t.details.startsWith("key")}function KEe(t){return WEe(t)&&!!t.frag&&!t.frag.decryptdata}function Joe(t,e){const r=SO(e);return t.default[`${r?"timeout":"error"}Retry`]}function vW(t,e){const r=t.backoff==="linear"?1:Math.pow(2,e);return Math.min(r*t.retryDelayMs,t.maxRetryDelayMs)}function ele(t){return Bs(Bs({},t),{errorRetry:null,timeoutRetry:null})}function TO(t,e,r,n){if(!t)return!1;const i=n==null?void 0:n.code,a=e499)}function K8(t){return t===0&&navigator.onLine===!1}var zl={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},qu={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class rRt extends ah{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(ke.ERROR,this.onError,this),e.on(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(ke.ERROR,this.onError,this),e.off(ke.ERROR,this.onErrorOut,this),e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.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)===Sn.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 s;return(s=c.details)==null?void 0:s.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 Qt.FRAG_LOAD_ERROR:case Qt.FRAG_LOAD_TIMEOUT:case Qt.KEY_LOAD_ERROR:case Qt.KEY_LOAD_TIMEOUT:r.errorAction=this.getFragRetryOrSwitchAction(r);return;case Qt.FRAG_PARSING_ERROR:if((n=r.frag)!=null&&n.gap){r.errorAction=$w();return}case Qt.FRAG_GAP:case Qt.FRAG_DECRYPT_ERROR:{r.errorAction=this.getFragRetryOrSwitchAction(r),r.errorAction.action=zl.SendAlternateToPenaltyBox;return}case Qt.LEVEL_EMPTY_ERROR:case Qt.LEVEL_PARSING_ERROR:{var c;const f=r.parent===Sn.MAIN?r.level:i.loadLevel;r.details===Qt.LEVEL_EMPTY_ERROR&&((c=r.context)!=null&&(c=c.levelDetails)!=null&&c.live)?r.errorAction=this.getPlaylistRetryOrSwitchAction(r,f):(r.levelRetry=!1,r.errorAction=this.getLevelSwitchAction(r,f))}return;case Qt.LEVEL_LOAD_ERROR:case Qt.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(r.errorAction=this.getPlaylistRetryOrSwitchAction(r,a.level));return;case Qt.AUDIO_TRACK_LOAD_ERROR:case Qt.AUDIO_TRACK_LOAD_TIMEOUT:case Qt.SUBTITLE_LOAD_ERROR:case Qt.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const f=i.loadLevelObj;if(f&&(a.type===Vi.AUDIO_TRACK&&f.hasAudioGroup(a.groupId)||a.type===Vi.SUBTITLE_TRACK&&f.hasSubtitleGroup(a.groupId))){r.errorAction=this.getPlaylistRetryOrSwitchAction(r,i.loadLevel),r.errorAction.action=zl.SendAlternateToPenaltyBox,r.errorAction.flags=qu.MoveAllAlternatesMatchingHost;return}}return;case Qt.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:r.errorAction={action:zl.SendAlternateToPenaltyBox,flags:qu.MoveAllAlternatesMatchingHDCP};return;case Qt.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Qt.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Qt.KEY_SYSTEM_NO_SESSION:r.errorAction={action:zl.SendAlternateToPenaltyBox,flags:qu.MoveAllAlternatesMatchingKey};return;case Qt.BUFFER_ADD_CODEC_ERROR:case Qt.REMUX_ALLOC_ERROR:case Qt.BUFFER_APPEND_ERROR:if(!r.errorAction){var s;r.errorAction=this.getLevelSwitchAction(r,(s=r.level)!=null?s:i.loadLevel)}return;case Qt.INTERNAL_EXCEPTION:case Qt.BUFFER_APPENDING_ERROR:case Qt.BUFFER_FULL_ERROR:case Qt.LEVEL_SWITCH_ERROR:case Qt.BUFFER_STALLED_ERROR:case Qt.BUFFER_SEEK_OVER_HOLE:case Qt.BUFFER_NUDGE_ON_STALL:r.errorAction=$w();return}r.type===Ln.KEY_SYSTEM_ERROR&&(r.levelRetry=!1,r.errorAction=$w())}getPlaylistRetryOrSwitchAction(e,r){const n=this.hls,i=Joe(n.config.playlistLoadPolicy,e),a=this.playlistError++;if(TO(i,a,SO(e),e.response))return{action:zl.RetryRequest,flags:qu.None,retryConfig:i,retryCount:a};const s=this.getLevelSwitchAction(e,r);return i&&(s.retryConfig=i,s.retryCount=a),s}getFragRetryOrSwitchAction(e){const r=this.hls,n=this.getVariantLevelIndex(e.frag),i=r.levels[n],{fragLoadPolicy:a,keyLoadPolicy:c}=r.config,s=Joe(WEe(e)?c:a,e),f=r.levels.reduce((x,_)=>x+_.fragmentError,0);if(i&&(e.details!==Qt.FRAG_GAP&&i.fragmentError++,!KEe(e)&&TO(s,f,SO(e),e.response)))return{action:zl.RetryRequest,flags:qu.None,retryConfig:s,retryCount:f};const m=this.getLevelSwitchAction(e,n);return s&&(m.retryConfig=s,m.retryCount=f),m}getLevelSwitchAction(e,r){const n=this.hls;r==null&&(r=n.loadLevel);const i=this.hls.levels[r];if(i){var a,c;const m=e.details;i.loadError++,m===Qt.BUFFER_APPEND_ERROR&&i.fragmentError++;let x=-1;const{levels:_,loadLevel:T,minAutoLevel:E,maxAutoLevel:C}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);const N=(a=e.frag)==null?void 0:a.type,D=(N===Sn.AUDIO&&m===Qt.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(m===Qt.BUFFER_ADD_CODEC_ERROR||m===Qt.BUFFER_APPEND_ERROR))&&_.some(({audioCodec:W})=>i.audioCodec!==W),B=e.sourceBufferName==="video"&&(m===Qt.BUFFER_ADD_CODEC_ERROR||m===Qt.BUFFER_APPEND_ERROR)&&_.some(({codecSet:W,audioCodec:X})=>i.codecSet!==W&&i.audioCodec===X),{type:V,groupId:G}=(c=e.context)!=null?c:{};for(let W=_.length;W--;){const X=(W+T)%_.length;if(X!==T&&X>=E&&X<=C&&_[X].loadError===0){var s,f;const Q=_[X];if(m===Qt.FRAG_GAP&&N===Sn.MAIN&&e.frag){const re=_[X].details;if(re){const se=D0(e.frag,re.fragments,e.frag.start);if(se!=null&&se.gap)continue}}else{if(V===Vi.AUDIO_TRACK&&Q.hasAudioGroup(G)||V===Vi.SUBTITLE_TRACK&&Q.hasSubtitleGroup(G))continue;if(N===Sn.AUDIO&&(s=i.audioGroups)!=null&&s.some(re=>Q.hasAudioGroup(re))||N===Sn.SUBTITLE&&(f=i.subtitleGroups)!=null&&f.some(re=>Q.hasSubtitleGroup(re))||D&&i.audioCodec===Q.audioCodec||B&&i.codecSet===Q.codecSet||!D&&i.codecSet!==Q.codecSet)continue}x=X;break}}if(x>-1&&n.loadLevel!==x)return e.levelRetry=!0,this.playlistError=0,{action:zl.SendAlternateToPenaltyBox,flags:qu.None,nextAutoLevel:x}}return{action:zl.SendAlternateToPenaltyBox,flags:qu.MoveAllAlternatesMatchingHost}}onErrorOut(e,r){var n;switch((n=r.errorAction)==null?void 0:n.action){case zl.DoNothing:break;case zl.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(r),!r.errorAction.resolved&&r.details!==Qt.FRAG_GAP?r.fatal=!0:/MediaSource readyState: ended/.test(r.error.message)&&(this.warn(`MediaSource ended after "${r.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(r.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const r=this.hls,n=e.errorAction;if(!n)return;const{flags:i}=n,a=n.nextAutoLevel;switch(i){case qu.None:this.switchLevel(e,a);break;case qu.MoveAllAlternatesMatchingHDCP:{const f=this.getVariantLevelIndex(e.frag),m=r.levels[f],x=m==null?void 0:m.attrs["HDCP-LEVEL"];if(n.hdcpLevel=x,x==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(x){r.maxHdcpLevel=W8[W8.indexOf(x)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${r.maxHdcpLevel}" or lower`);break}}case qu.MoveAllAlternatesMatchingKey:{const f=e.decryptdata;if(f){const m=this.hls.levels,x=m.length;for(let T=x;T--;)if(this.variantHasKey(m[T],f)){var c,s;this.log(`Banned key found in level ${T} (${m[T].bitrate}bps) or audio group "${(c=m[T].audioGroups)==null?void 0:c.join(",")}" (${(s=e.frag)==null?void 0:s.type} fragment) ${Vl(f.keyId||[])}`),m[T].fragmentError++,m[T].loadError++,this.log(`Removing level ${T} with key error (${e.error})`),this.hls.removeLevel(T)}const _=e.frag;if(this.hls.levels.length{const f=this.fragments[s];if(!f||c>=f.body.sn)return;if(!f.buffered&&(!f.loaded||a)){f.body.type===n&&this.removeFragment(f.body);return}const m=f.range[e];if(m){if(m.time.length===0){this.removeFragment(f.body);return}m.time.some(x=>{const _=!this.isTimeBuffered(x.startPTS,x.endPTS,r);return _&&this.removeFragment(f.body),_})}})}detectPartialFragments(e){const r=this.timeRanges;if(!r||e.frag.sn==="initSegment")return;const n=e.frag,i=qb(n),a=this.fragments[i];if(!a||a.buffered&&n.gap)return;const c=!n.relurl;Object.keys(r).forEach(s=>{const f=n.elementaryStreams[s];if(!f)return;const m=r[s],x=c||f.partial===!0;a.range[s]=this.getBufferedTimes(n,e.part,x,m)}),a.loaded=null,Object.keys(a.range).length?(this.bufferedEnd(a,n),ZN(a)||this.removeParts(n.sn-1,n.type)):this.removeFragment(a.body)}bufferedEnd(e,r){e.buffered=!0,(e.body.endList=r.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,r){const n=this.activePartLists[r];n&&(this.activePartLists[r]=tle(n,i=>i.fragment.sn>=e))}fragBuffered(e,r){const n=qb(e);let i=this.fragments[n];!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))}getBufferedTimes(e,r,n,i){const a={time:[],partial:n},c=e.start,s=e.end,f=e.minEndPTS||s,m=e.maxStartPTS||c;for(let x=0;x=_&&f<=T){a.time.push({startPTS:Math.max(c,i.start(x)),endPTS:Math.min(s,i.end(x))});break}else if(c_){const E=Math.max(c,i.start(x)),C=Math.min(s,i.end(x));C>E&&(a.partial=!0,a.time.push({startPTS:E,endPTS:C}))}else if(s<=_)break}return a}getPartialFragment(e){let r=null,n,i,a,c=0;const{bufferPadding:s,fragments:f}=this;return Object.keys(f).forEach(m=>{const x=f[m];x&&ZN(x)&&(i=x.body.start-s,a=x.body.end+s,e>=i&&e<=a&&(n=Math.min(e-i,a-e),c<=n&&(r=x.body,c=n)))}),r}isEndListAppended(e){const r=this.endListFragments[e];return r!==void 0&&(r.buffered||ZN(r))}getState(e){const r=qb(e),n=this.fragments[r];return n?n.buffered?ZN(n)?sl.PARTIAL:sl.OK:sl.APPENDING:sl.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(r.frag.sn==="initSegment"||r.frag.bitrateTest)return;const n=r.frag,i=r.part?null:r,a=qb(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,type:c}=r;if(n.sn==="initSegment")return;const s=n.type;if(i){let m=this.activePartLists[s];m||(this.activePartLists[s]=m=[]),m.push(i)}this.timeRanges=a;const f=a[c];this.detectEvictedFragments(c,f,s,i)}onFragBuffered(e,r){this.detectPartialFragments(r)}hasFragment(e){const r=qb(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)}removeFragmentsInRange(e,r,n,i,a){i&&!this.hasGaps||Object.keys(this.fragments).forEach(c=>{const s=this.fragments[c];if(!s)return;const f=s.body;f.type!==n||i&&!f.gap||f.starte&&(s.buffered||a)&&this.removeFragment(f)})}removeFragment(e){const r=qb(e);e.clearElementaryStreamInfo();const n=this.activePartLists[e.type];if(n){const i=e.sn;this.activePartLists[e.type]=tle(n,a=>a.fragment.sn!==i)}delete this.fragments[r],e.endList&&delete this.endListFragments[e.type]}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 ZN(t){var e,r,n;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)}function qb(t){return`${t.type}_${t.level}_${t.sn}`}function tle(t,e){return t.filter(r=>{const n=e(r);return n||r.clearElementaryStreamInfo(),n})}var Jy={cbc:0,ctr:1};class iRt{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 Jy.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},r,e);case Jy.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 sRt(t){const e=t.byteLength,r=e&&new DataView(t.buffer).getUint8(e-1);return r?t.slice(0,e-r):t}class aRt{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],s=n[3],f=this.invSubMix,m=f[0],x=f[1],_=f[2],T=f[3],E=new Uint32Array(256);let C=0,N=0,R=0;for(R=0;R<256;R++)R<128?E[R]=R<<1:E[R]=R<<1^283;for(R=0;R<256;R++){let D=N^N<<1^N<<2^N<<3^N<<4;D=D>>>8^D&255^99,e[C]=D,r[D]=C;const M=E[C],B=E[M],V=E[B];let G=E[D]*257^D*16843008;i[C]=G<<24|G>>>8,a[C]=G<<16|G>>>16,c[C]=G<<8|G>>>24,s[C]=G,G=V*16843009^B*65537^M*257^C*16843008,m[D]=G<<24|G>>>8,x[D]=G<<16|G>>>16,_[D]=G<<8|G>>>24,T[D]=G,C?(C=M^E[E[E[V^M]]],N^=E[E[N]]):C=N=1}}expandKey(e){const r=this.uint8ArrayToUint32Array_(e);let n=!0,i=0;for(;i{const s=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(s,r,n,i);const f=this.flush();f?a(f.buffer):c(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:s}=this;if(i!==Jy.cbc||r.byteLength!==16)return $s.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=eh(s,e),this.remainderData=null);const f=this.getValidChunk(e);if(!f.length)return null;a&&(n=a);let m=this.softwareDecrypter;m||(m=this.softwareDecrypter=new aRt),m.expandKey(r);const x=c;return this.currentResult=m.decrypt(f.buffer,0,n),this.currentIV=f.slice(-16).buffer,x||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 oRt(this.subtle,r,i)}return this.fastAesKey.expandKey().then(a=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new iRt(this.subtle,new Uint8Array(n),i).decrypt(e.buffer,a)):Promise.reject(new Error("web crypto not initialized"))).catch(a=>($s.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%cRt;return n!==e.length&&(r=e.slice(0,n),this.remainderData=e.slice(n)),r}logOnce(e){this.logEnabled&&($s.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const rle=Math.pow(2,17);class uRt{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){const n=e.url;if(!n)return Promise.reject(new sm({type:Ln.NETWORK_ERROR,details:Qt.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${n?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,a=i.fLoader,c=i.loader;return new Promise((s,f)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(C=>C[0]==="GAP")){f(ile(e));return}else e.gap=!1;const m=this.loader=a?new a(i):new c(i),x=nle(e);e.loader=m;const _=ele(i.fragLoadPolicy.default),T={loadPolicy:_,timeout:_.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:rle};e.stats=m.stats;const E={onSuccess:(C,N,R,D)=>{this.resetLoader(e,m);let M=C.data;R.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(M.slice(0,16)),M=M.slice(16)),s({frag:e,part:null,payload:M,networkDetails:D})},onError:(C,N,R,D)=>{this.resetLoader(e,m),f(new sm({type:Ln.NETWORK_ERROR,details:Qt.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Bs({url:n,data:void 0},C),error:new Error(`HTTP Error ${C.code} ${C.text}`),networkDetails:R,stats:D}))},onAbort:(C,N,R)=>{this.resetLoader(e,m),f(new sm({type:Ln.NETWORK_ERROR,details:Qt.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:R,stats:C}))},onTimeout:(C,N,R)=>{this.resetLoader(e,m),f(new sm({type:Ln.NETWORK_ERROR,details:Qt.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${T.timeout}ms`),networkDetails:R,stats:C}))}};r&&(E.onProgress=(C,N,R,D)=>r({frag:e,part:null,payload:R,networkDetails:D})),m.load(x,T,E)})}loadPart(e,r,n){this.abort();const i=this.config,a=i.fLoader,c=i.loader;return new Promise((s,f)=>{if(this.loader&&this.loader.destroy(),e.gap||r.gap){f(ile(e,r));return}const m=this.loader=a?new a(i):new c(i),x=nle(e,r);e.loader=m;const _=ele(i.fragLoadPolicy.default),T={loadPolicy:_,timeout:_.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:rle};r.stats=m.stats,m.load(x,T,{onSuccess:(E,C,N,R)=>{this.resetLoader(e,m),this.updateStatsFromPart(e,r);const D={frag:e,part:r,payload:E.data,networkDetails:R};n(D),s(D)},onError:(E,C,N,R)=>{this.resetLoader(e,m),f(new sm({type:Ln.NETWORK_ERROR,details:Qt.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:r,response:Bs({url:x.url,data:void 0},E),error:new Error(`HTTP Error ${E.code} ${E.text}`),networkDetails:N,stats:R}))},onAbort:(E,C,N)=>{e.stats.aborted=r.stats.aborted,this.resetLoader(e,m),f(new sm({type:Ln.NETWORK_ERROR,details:Qt.INTERNAL_ABORTED,fatal:!1,frag:e,part:r,error:new Error("Aborted"),networkDetails:N,stats:E}))},onTimeout:(E,C,N)=>{this.resetLoader(e,m),f(new sm({type:Ln.NETWORK_ERROR,details:Qt.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:r,error:new Error(`Timeout after ${T.timeout}ms`),networkDetails:N,stats:E}))}})})}updateStatsFromPart(e,r){const n=e.stats,i=r.stats,a=i.total;if(n.loaded+=i.loaded,a){const f=Math.round(e.duration/r.duration),m=Math.min(Math.round(n.loaded/a),f),_=(f-m)*Math.round(n.loaded/m);n.total=n.loaded+_}else n.total=Math.max(n.loaded,n.total);const c=n.loading,s=i.loading;c.start?c.first+=s.first-s.start:(c.start=s.start,c.first=s.first),c.end=s.end}resetLoader(e,r){e.loader=null,this.loader===r&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),r.destroy()}}function nle(t,e=null){const r=e||t,n={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},i=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(fn(i)&&fn(a)){var c;let s=i,f=a;if(t.sn==="initSegment"&&dRt((c=t.decryptdata)==null?void 0:c.method)){const m=a-i;m%16&&(f=a+(16-m%16)),i!==0&&(n.resetIV=!0,s=i-16)}n.rangeStart=s,n.rangeEnd=f}return n}function ile(t,e){const r=new Error(`GAP ${t.gap?"tag":"attribute"} found`),n={type:Ln.MEDIA_ERROR,details:Qt.FRAG_GAP,fatal:!1,frag:t,error:r,networkDetails:null};return e&&(n.part=e),(e||t).stats.aborted=!0,new sm(n)}function dRt(t){return t==="AES-128"||t==="AES-256"}class sm extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class YEe extends ah{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)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class wW{constructor(e,r,n,i=0,a=-1,c=!1){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.transmuxing=XN(),this.buffering={audio:XN(),video:XN(),audiovideo:XN()},this.level=e,this.sn=r,this.id=n,this.size=i,this.part=a,this.partial=c}}function XN(){return{start:0,executeStart:0,executeEnd:0,end:0}}const sle={length:0,start:()=>0,end:()=>0};class vi{static isBuffered(e,r){if(e){const n=vi.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=vi.getBuffered(e);return vi.timeRangesToArray(r)}return[]}static timeRangesToArray(e){const r=[];for(let n=0;n1&&e.sort((x,_)=>x.start-_.start||_.end-x.end);let i=-1,a=[];if(n)for(let x=0;x=e[x].start&&r<=e[x].end&&(i=x);const _=a.length;if(_){const T=a[_-1].end;e[x].start-TT&&(a[_-1].end=e[x].end):a.push(e[x])}else a.push(e[x])}else a=e;let c=0,s,f=r,m=r;for(let x=0;x=_&&r<=T&&(i=x),r+n>=_&&r{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 ole(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 hRt(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 fRt=/^(\d+)x(\d+)$/,lle=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Ka{constructor(e,r){typeof e=="string"&&(e=Ka.parseAttrList(e,r)),Ys(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=fRt.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(lle.lastIndex=0;(n=lle.exec(e))!==null;){const c=n[1].trim();let s=n[2];const f=s.indexOf(a)===0&&s.lastIndexOf(a)===s.length-1;let m=!1;if(f)s=s.slice(1,-1);else switch(c){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":m=!0}if(r&&(f||m))s=Y8(r,s);else if(!m&&!f)switch(c){case"CLOSED-CAPTIONS":if(s==="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":$s.warn(`${e}: attribute ${c} is missing quotes`)}i[c]=s}return i}}const pRt="com.apple.hls.interstitial";function mRt(t){return t!=="ID"&&t!=="CLASS"&&t!=="CUE"&&t!=="START-DATE"&&t!=="DURATION"&&t!=="END-DATE"&&t!=="END-ON-NEXT"}function gRt(t){return t==="SCTE35-OUT"||t==="SCTE35-IN"||t==="SCTE35-CMD"}class XEe{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]){$s.warn(`DATERANGE tag attribute: "${c}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=c;break}e=Ys(new Ka({}),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 this.attr){const a=(r==null?void 0:r.endDate)||new Date(this.attr["END-DATE"]);fn(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?($s.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(fn(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===pRt}get isValid(){return!!this.id&&!this._badValueForSameId&&fn(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)}}const yRt=10;class xRt{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const r=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!r||!this.live,this.advanced=this.endSN>e.endSN||r>0||r===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):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?fn(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||yRt}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.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function EO(t,e){return t.length===e.length?!t.some((r,n)=>r!==e[n]):!1}function cle(t,e){return!t&&!e?!0:!t||!e?!1:EO(t,e)}function Uw(t){return t==="AES-128"||t==="AES-256"||t==="AES-256-CTR"}function SW(t){switch(t){case"AES-128":case"AES-256":return Jy.cbc;case"AES-256-CTR":return Jy.ctr;default:throw new Error(`invalid full segment method ${t}`)}}function TW(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}function Z8(t){return Uint8Array.from(unescape(encodeURIComponent(t)),e=>e.charCodeAt(0))}function _Rt(t){const e=Z8(t).subarray(0,16),r=new Uint8Array(16);return r.set(e,16-e.length),r}function QEe(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 JEe(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=TW(c)):r=_Rt(c)}}return r}const AO=typeof self<"u"?self:void 0;var Xa={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ql={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function XR(t){switch(t){case ql.FAIRPLAY:return Xa.FAIRPLAY;case ql.PLAYREADY:return Xa.PLAYREADY;case ql.WIDEVINE:return Xa.WIDEVINE;case ql.CLEARKEY:return Xa.CLEARKEY}}function n$(t){switch(t){case Xa.FAIRPLAY:return ql.FAIRPLAY;case Xa.PLAYREADY:return ql.PLAYREADY;case Xa.WIDEVINE:return ql.WIDEVINE;case Xa.CLEARKEY:return ql.CLEARKEY}}function Q2(t){const{drmSystems:e,widevineLicenseUrl:r}=t,n=e?[Xa.FAIRPLAY,Xa.WIDEVINE,Xa.PLAYREADY,Xa.CLEARKEY].filter(i=>!!e[i]):[];return!n[Xa.WIDEVINE]&&r&&n.push(Xa.WIDEVINE),n}const e2e=function(t){return AO!=null&&(t=AO.navigator)!=null&&t.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function vRt(t,e,r,n){let i;switch(t){case Xa.FAIRPLAY:i=["cenc","sinf"];break;case Xa.WIDEVINE:case Xa.PLAYREADY:i=["cenc"];break;case Xa.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return bRt(i,e,r,n)}function bRt(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 wRt(t){var e;return!!t&&(t.sessionType==="persistent-license"||!!((e=t.sessionTypes)!=null&&e.some(r=>r==="persistent-license")))}function t2e(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(e)),n=r.substring(r.indexOf("<"),r.length),c=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(c){const s=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(s){const f=TW(s).subarray(0,16);return QEe(f),f}}return null}let Gb={};class Dy{static clearKeyUriToKeyIdMap(){Gb={}}static setKeyIdForUri(e,r){Gb[e]=r}static addKeyIdForUri(e){const r=Object.keys(Gb).length%Number.MAX_SAFE_INTEGER,n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,r),Gb[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.method=e,this.uri=r,this.keyFormat=n,this.keyFormatVersions=i,this.iv=a,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Uw(e),c!=null&&c.startsWith("0x")&&(this.keyId=new Uint8Array(jEe(c)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&EO(e.keyFormatVersions,this.keyFormatVersions)&&cle(e.iv,this.iv)&&cle(e.keyId,this.keyId)}isSupported(){if(this.method){if(Uw(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case ql.FAIRPLAY:case ql.WIDEVINE:case ql.PLAYREADY:case ql.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,r){if(!this.encrypted||!this.uri)return null;if(Uw(this.method)){let a=this.iv;return a||(typeof e!="number"&&($s.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=TRt(e)),new Dy(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){const a=Gb[this.uri];if(a&&!EO(this.keyId,a)&&Dy.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const n=JEe(this.uri);if(n)switch(this.keyFormat){case ql.WIDEVINE:if(this.pssh=n,!this.keyId){const a=kNt(n.buffer);if(a.length){var i;const c=a[0];this.keyId=(i=c.kids)!=null&&i.length?c.kids[0]:null}}this.keyId||(this.keyId=ule(r));break;case ql.PLAYREADY:{const a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=ANt(a,null,n),this.keyId=t2e(n);break}default:{let a=n.subarray(0,16);if(a.length!==16){const c=new Uint8Array(16);c.set(a,16-a.length),a=c}this.keyId=a;break}}if(!this.keyId||this.keyId.byteLength!==16){let a;a=SRt(r),a||(a=ule(r),a||(a=Gb[this.uri])),a&&(this.keyId=a,Dy.setKeyIdForUri(this.uri,a))}return this}}function SRt(t){const e=t==null?void 0:t[ql.WIDEVINE];return e?e.keyId:null}function ule(t){const e=t==null?void 0:t[ql.PLAYREADY];if(e){const r=JEe(e.uri);if(r)return t2e(r)}return null}function TRt(t){const e=new Uint8Array(16);for(let r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e}const dle=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,hle=/#EXT-X-MEDIA:(.*)/g,ERt=/^#EXT(?:INF|-X-TARGETDURATION):/m,i$=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ARt=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)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Wf{static findGroup(e,r){for(let n=0;n0&&a.length({id:m.attrs.AUDIO,audioCodec:m.audioCodec})),SUBTITLES:c.map(m=>({id:m.attrs.SUBTITLES,textCodec:m.textCodec})),"CLOSED-CAPTIONS":[]};let f=0;for(hle.lastIndex=0;(i=hle.exec(e))!==null;){const m=new Ka(i[1],n),x=m.TYPE;if(x){const _=s[x],T=a[x]||[];a[x]=T;const E=m.LANGUAGE,C=m["ASSOC-LANGUAGE"],N=m.CHANNELS,R=m.CHARACTERISTICS,D=m["INSTREAM-ID"],M={attrs:m,bitrate:0,id:f++,groupId:m["GROUP-ID"]||"",name:m.NAME||E||"",type:x,default:m.bool("DEFAULT"),autoselect:m.bool("AUTOSELECT"),forced:m.bool("FORCED"),lang:E,url:m.URI?Wf.resolve(m.URI,r):""};if(C&&(M.assocLang=C),N&&(M.channels=N),R&&(M.characteristics=R),D&&(M.instreamId=D),_!=null&&_.length){const B=Wf.findGroup(_,M.groupId)||_[0];gle(M,B,"audioCodec"),gle(M,B,"textCodec")}T.push(M)}}return a}static parseLevelPlaylist(e,r,n,i,a,c){var s;const f={url:r},m=new xRt(r),x=m.fragments,_=[];let T=null,E=0,C=0,N=0,R=0,D=0,M=null,B=new e$(i,f),V,G,W,X=-1,Q=!1,re=null,se;if(i$.lastIndex=0,m.m3u8=e,m.hasVariableRefs=ale(e),((s=i$.exec(e))==null?void 0:s[0])!=="#EXTM3U")return m.playlistParsingError=new Error("Missing format identifier #EXTM3U"),m;for(;(V=i$.exec(e))!==null;){Q&&(Q=!1,B=new e$(i,f),B.playlistOffset=N,B.setStart(N),B.sn=E,B.cc=R,D&&(B.bitrate=D),B.level=n,T&&(B.initSegment=T,T.rawProgramDateTime&&(B.rawProgramDateTime=T.rawProgramDateTime,T.rawProgramDateTime=null),re&&(B.setByteRange(re),re=null)));const ve=V[1];if(ve){B.duration=parseFloat(ve);const Oe=(" "+V[2]).slice(1);B.title=Oe||null,B.tagList.push(Oe?["INF",ve,Oe]:["INF",ve])}else if(V[3]){if(fn(B.duration)){B.playlistOffset=N,B.setStart(N),W&&xle(B,W,m),B.sn=E,B.level=n,B.cc=R,x.push(B);const Oe=(" "+V[3]).slice(1);B.relurl=Y8(m,Oe),X8(B,M,_),M=B,N+=B.duration,E++,C=0,Q=!0}}else{if(V=V[0].match(ARt),!V){$s.warn("No matches on slow regex match for level playlist!");continue}for(G=1;G0&&_le(m,Oe,V),E=m.startSN=parseInt(Ae);break;case"SKIP":{m.skippedSegments&&Qp(m,Oe,V);const ge=new Ka(Ae,m),Ne=ge.decimalInteger("SKIPPED-SEGMENTS");if(fn(Ne)){m.skippedSegments+=Ne;for(let Te=Ne;Te--;)x.push(null);E+=Ne}const Ie=ge.enumeratedString("RECENTLY-REMOVED-DATERANGES");Ie&&(m.recentlyRemovedDateranges=(m.recentlyRemovedDateranges||[]).concat(Ie.split(" ")));break}case"TARGETDURATION":m.targetduration!==0&&Qp(m,Oe,V),m.targetduration=Math.max(parseInt(Ae),1);break;case"VERSION":m.version!==null&&Qp(m,Oe,V),m.version=parseInt(Ae);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":m.live||Qp(m,Oe,V),m.live=!1;break;case"#":(Ae||we)&&B.tagList.push(we?[Ae,we]:[Ae]);break;case"DISCONTINUITY":R++,B.tagList.push(["DIS"]);break;case"GAP":B.gap=!0,B.tagList.push([Oe]);break;case"BITRATE":B.tagList.push([Oe,Ae]),D=parseInt(Ae)*1e3,fn(D)?B.bitrate=D:D=0;break;case"DATERANGE":{const ge=new Ka(Ae,m),Ne=new XEe(ge,m.dateRanges[ge.ID],m.dateRangeTagCount);m.dateRangeTagCount++,Ne.isValid||m.skippedSegments?m.dateRanges[Ne.id]=Ne:$s.warn(`Ignoring invalid DATERANGE tag: "${Ae}"`),B.tagList.push(["EXT-X-DATERANGE",Ae]);break}case"DEFINE":{{const ge=new Ka(Ae,m);"IMPORT"in ge?hRt(m,ge,c):ole(m,ge,r)}break}case"DISCONTINUITY-SEQUENCE":m.startCC!==0?Qp(m,Oe,V):x.length>0&&_le(m,Oe,V),m.startCC=R=parseInt(Ae);break;case"KEY":{const ge=fle(Ae,r,m);if(ge.isSupported()){if(ge.method==="NONE"){W=void 0;break}W||(W={});const Ne=W[ge.keyFormat];Ne!=null&&Ne.matches(ge)||(Ne&&(W=Ys({},W)),W[ge.keyFormat]=ge)}else $s.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${Ae}"`);break}case"START":m.startTimeOffset=ple(Ae);break;case"MAP":{const ge=new Ka(Ae,m);if(B.duration){const Ne=new e$(i,f);yle(Ne,ge,n,W),T=Ne,B.initSegment=T,T.rawProgramDateTime&&!B.rawProgramDateTime&&(B.rawProgramDateTime=T.rawProgramDateTime)}else{const Ne=B.byteRangeEndOffset;if(Ne){const Ie=B.byteRangeStartOffset;re=`${Ne-Ie}@${Ie}`}else re=null;yle(B,ge,n,W),T=B,Q=!0}T.cc=R;break}case"SERVER-CONTROL":{se&&Qp(m,Oe,V),se=new Ka(Ae),m.canBlockReload=se.bool("CAN-BLOCK-RELOAD"),m.canSkipUntil=se.optionalFloat("CAN-SKIP-UNTIL",0),m.canSkipDateRanges=m.canSkipUntil>0&&se.bool("CAN-SKIP-DATERANGES"),m.partHoldBack=se.optionalFloat("PART-HOLD-BACK",0),m.holdBack=se.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{m.partTarget&&Qp(m,Oe,V);const ge=new Ka(Ae);m.partTarget=ge.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ge=m.partList;ge||(ge=m.partList=[]);const Ne=C>0?ge[ge.length-1]:void 0,Ie=C++,Te=new Ka(Ae,m),be=new hNt(Te,B,f,Ie,Ne);ge.push(be),B.duration+=be.duration;break}case"PRELOAD-HINT":{const ge=new Ka(Ae,m);m.preloadHint=ge;break}case"RENDITION-REPORT":{const ge=new Ka(Ae,m);m.renditionReports=m.renditionReports||[],m.renditionReports.push(ge);break}default:$s.warn(`line parsed but not handled: ${V}`);break}}}M&&!M.relurl?(x.pop(),N-=M.duration,m.partList&&(m.fragmentHint=M)):m.partList&&(X8(B,M,_),B.cc=R,m.fragmentHint=B,W&&xle(B,W,m)),m.targetduration||(m.playlistParsingError=new Error("Missing Target Duration"));const ue=x.length,_e=x[0],Se=x[ue-1];if(N+=m.skippedSegments*m.targetduration,N>0&&ue&&Se){m.averagetargetduration=N/ue;const ve=Se.sn;m.endSN=ve!=="initSegment"?ve:0,m.live||(Se.endList=!0),X>0&&(CRt(x,X),_e&&_.unshift(_e))}return m.fragmentHint&&(N+=m.fragmentHint.duration),m.totalduration=N,_.length&&m.dateRangeTagCount&&_e&&r2e(_,m),m.endCC=R,m}}function r2e(t,e){let r=t.length;if(!r)if(e.hasProgramDateTime){const s=e.fragments[e.fragments.length-1];t.push(s),r++}else return;const n=t[r-1],i=e.live?1/0:e.totalduration,a=Object.keys(e.dateRanges);for(let s=a.length;s--;){const f=e.dateRanges[a[s]],m=f.startDate.getTime();f.tagAnchor=n.ref;for(let x=r;x--;){var c;if(((c=t[x])==null?void 0:c.sn)=s||n===0){var c;const f=(((c=r[n+1])==null?void 0:c.start)||i)-a.start;if(e<=s+f*1e3){const m=r[n].sn-t.startSN;if(m<0)return-1;const x=t.fragments;if(x.length>r.length){const T=(r[n+1]||x[x.length-1]).sn-t.startSN;for(let E=T;E>m;E--){const C=x[E].programDateTime;if(e>=C&&en);["video","audio","text"].forEach(n=>{const i=r.filter(a=>xW(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 gle(t,e,r){const n=e[r];n&&(t[r]=n)}function CRt(t,e){let r=t[e];for(let n=e;n--;){const i=t[n];if(!i)return;i.programDateTime=r.programDateTime-i.duration*1e3,r=i}}function X8(t,e,r){t.rawProgramDateTime?r.push(t):e!=null&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function yle(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 xle(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 Qp(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${r[0]})`)}function _le(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${r[0]})`)}function s$(t,e){const r=e.startPTS;if(fn(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 n2e(t,e,r,n,i,a,c){n-r<=0&&(c.warn("Fragment should have a positive duration",e),n=r+e.duration,a=i+e.duration);let f=r,m=n;const x=e.startPTS,_=e.endPTS;if(fn(x)){const D=Math.abs(x-r);t&&D>t.totalduration?c.warn(`media timestamps and playlist times differ by ${D}s for level ${e.level} ${t.url}`):fn(e.deltaPTS)?e.deltaPTS=Math.max(D,e.deltaPTS):e.deltaPTS=D,f=Math.max(r,x),r=Math.min(r,x),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,m=Math.min(n,_),n=Math.max(n,_),a=e.endDTS!==void 0?Math.max(a,e.endDTS):a}const T=r-e.start;e.start!==0&&e.setStart(r),e.setDuration(n-e.start),e.startPTS=r,e.maxStartPTS=f,e.startDTS=i,e.endPTS=n,e.minEndPTS=m,e.endDTS=a;const E=e.sn;if(!t||Et.endSN)return 0;let C;const N=E-t.startSN,R=t.fragments;for(R[N]=e,C=N;C>0;C--)s$(R[C],R[C-1]);for(C=N;C=0;x--){const _=i[x].initSegment;if(_){n=_;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let a;NRt(t,e,(x,_,T,E)=>{if((!e.startCC||e.skippedSegments)&&_.cc!==x.cc){const C=x.cc-_.cc;for(let N=T;N{var _;x&&(!x.initSegment||x.initSegment.relurl===((_=n)==null?void 0:_.relurl))&&(x.initSegment=n)}),e.skippedSegments){if(e.deltaUpdateFailed=c.some(x=>!x),e.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let x=e.skippedSegments;x--;)c.shift();e.startSN=c[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=IRt(t.dateRanges,e,r));const x=t.fragments.filter(_=>_.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let _=1;_{_.elementaryStreams=x.elementaryStreams,_.stats=x.stats}),a?n2e(e,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,r):i2e(t,e),c.length&&(e.totalduration=e.edge-c[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const m=e.advancedDateTime;if(e.advanced&&m){const x=e.edge;e.driftStart||(e.driftStartTime=m,e.driftStart=x),e.driftEndTime=m,e.driftEnd=x}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=t.requestScheduled)}function IRt(t,e,r){const{dateRanges:n,recentlyRemovedDateranges:i}=e,a=Ys({},t);i&&i.forEach(f=>{delete a[f]});const s=Object.keys(a).length;return s?(Object.keys(n).forEach(f=>{const m=a[f],x=new XEe(n[f].attr,m);x.isValid?(a[f]=x,m||(x.tagOrder+=s)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ra(n[f].attr)}"`)}),a):n}function PRt(t,e,r){if(t&&e){let n=0;for(let i=0,a=t.length;i<=a;i++){const c=t[i],s=e[i+n];c&&s&&c.index===s.index&&c.fragment.sn===s.fragment.sn?r(c,s):n--}}}function NRt(t,e,r){const n=e.skippedSegments,i=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(n?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,c=e.startSN-t.startSN,s=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,f=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let m=i;m<=a;m++){const x=f[c+m];let _=s[m];if(n&&!_&&x&&(_=e.fragments[m]=x),x&&_){r(x,_,m,s);const T=x.relurl,E=_.relurl;if(T&&RRt(T,E)){e.playlistParsingError=vle(`media sequence mismatch ${_.sn}:`,t,e,x,_);return}else if(x.cc!==_.cc){e.playlistParsingError=vle(`discontinuity sequence mismatch (${x.cc}!=${_.cc})`,t,e,x,_);return}}}}function vle(t,e,r,n,i){return new Error(`${t} ${i.url} Playlist starting @${e.startSN} ${e.m3u8} Playlist starting @${r.startSN} ${r.m3u8}`)}function i2e(t,e,r=!0){const n=e.startSN+e.skippedSegments-t.startSN,i=t.fragments,a=n>=0;let c=0;if(a&&ne){const a=n[n.length-1].duration*1e3;a{var n;(n=e.details)==null||n.fragments.forEach(i=>{i.level=r,i.initSegment&&(i.initSegment.level=r)})})}function RRt(t,e){return t!==e&&e?wle(t)!==wle(e):!1}function wle(t){return t.replace(/\?[^?]*$/,"")}function IA(t,e){for(let n=0,i=t.length;nt.startCC)}function Sle(t,e){const r=t.start+e;t.startPTS=r,t.setStart(r),t.endPTS=r+t.duration}function c2e(t,e){const r=e.fragments;for(let n=0,i=r.length;n{const{config:c,fragCurrent:s,media:f,mediaBuffer:m,state:x}=this,_=f?f.currentTime:0,T=vi.bufferInfo(m||f,_,c.maxBufferHole),E=!T.len;if(this.log(`Media seeking to ${fn(_)?_.toFixed(3):_}, state: ${x}, ${E?"out of":"in"} buffer`),this.state===br.ENDED)this.resetLoadingState();else if(s){const C=c.maxFragLookUpTolerance,N=s.start-C,R=s.start+s.duration+C;if(E||RT.end){const D=_>R;(_C&&(this.lastCurrentTime=_),!this.loadingParts){const N=Math.max(T.end,_),R=this.shouldLoadParts(this.getLevelDetails(),N);R&&(this.log(`LL-Part loading ON after seeking to ${_.toFixed(2)} with buffer @${N.toFixed(2)}`),this.loadingParts=R)}}this.hls.hasEnoughToStart||(this.log(`Setting ${E?"startPosition":"nextLoadPosition"} to ${_} for seek without enough to start`),this.nextLoadPosition=_,E&&(this.startPosition=_)),E&&this.state===br.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=a,this.hls=e,this.fragmentLoader=new uRt(e.config),this.keyLoader=n,this.fragmentTracker=r,this.config=e.config,this.decrypter=new bW(e.config)}registerListeners(){const{hls:e}=this;e.on(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ke.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ke.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===br.STOPPED)return;this.fragmentLoader.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=br.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:r}=this;return r===-1&&e?e:r}get bufferingEnabled(){return this.buffering}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=vi.bufferedInfo(a,e.start,0));const c=e.nextStart;if(c&&c>i&&c{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}c.stats.chunkCount++,this._handleFragmentLoadProgress(a)};this._doFragLoad(e,r,n,i).then(a=>{if(!a)return;const c=this.state,s=a.frag;if(this.fragContextChanged(s)){(c===br.FRAG_LOADING||!this.fragCurrent&&c===br.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=br.IDLE);return}"payload"in a&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger(ke.FRAG_LOADED,a)),this._handleFragmentLoadComplete(a)}).catch(a=>{this.state===br.STOPPED||this.state===br.ERROR||(this.warn(`Frag error: ${(a==null?void 0:a.message)||a}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var r;const{fragmentTracker:n}=this;if(n.getState(e)===sl.APPENDING){const a=e.type,c=this.getFwdBufferInfo(this.mediaBuffer,a),s=Math.max(e.duration,c?c.len:this.config.maxBufferLength),f=this.backtrackFragment;((f?e.sn-f.sn:0)===1||this.reduceMaxBufferLength(s,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)===sl.PARTIAL&&n.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const r=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const r=e.details;return(r==null?void 0:r.live)&&r.type!=="EVENT"&&(this.levelLastLoaded!==e||r.expired)}flushMainBuffer(e,r,n=null){if(!(e-r))return;const i={startOffset:e,endOffset:r,type:n};this.hls.trigger(ke.BUFFER_FLUSHING,i)}_loadInitSegment(e,r){this._doFragLoad(e,r).then(n=>{const i=n==null?void 0:n.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return n}).then(n=>{const{hls:i}=this,{frag:a,payload:c}=n,s=a.decryptdata;if(c&&c.byteLength>0&&s!=null&&s.key&&s.iv&&Uw(s.method)){const f=self.performance.now();return this.decrypter.decrypt(new Uint8Array(c),s.key.buffer,s.iv.buffer,SW(s.method)).catch(m=>{throw i.trigger(ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.FRAG_DECRYPT_ERROR,fatal:!1,error:m,reason:m.message,frag:a}),m}).then(m=>{const x=self.performance.now();return i.trigger(ke.FRAG_DECRYPTED,{frag:a,payload:m,stats:{tstart:f,tdecrypt:x}}),n.payload=m,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)}).catch(n=>{this.state===br.STOPPED||this.state===br.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:r}=this;if(!r)throw new Error("init load aborted, missing levels");const n=e.frag.stats;this.state!==br.STOPPED&&(this.state=br.IDLE),e.frag.data=new Uint8Array(e.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),this.tick()}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,s=new Error(`Encrypted track with no key in ${this.fragInfo(r)} (media ${c?"attached mediaKeys: "+c.mediaKeys:"detached"})`);return this.warn(s.message),!c||c.mediaKeys?!1:(this.hls.trigger(ke.ERROR,{type:Ln.KEY_SYSTEM_ERROR,details:Qt.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:r}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:r}=this;return!e||!r||e.sn!==r.sn||e.level!==r.level}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?ORt.toString(vi.getBuffered(n)):"(detached)"})`),To(e)){var i;if(e.type!==Sn.SUBTITLE){const c=e.elementaryStreams;if(!Object.keys(c).some(s=>!!c[s])){this.state=br.IDLE;return}}const a=(i=this.levels)==null?void 0:i[e.level];a!=null&&a.fragmentError&&(this.log(`Resetting level fragment error count of ${a.fragmentError} on frag buffered`),a.fragmentError=0)}this.state=br.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:r}=this;if(!r)return;const{frag:n,part:i,partsLoaded:a}=e,c=!a||a.length===0||a.some(f=>!f),s=new wW(n.level,n.sn,n.stats.chunkCount+1,0,i?i.index:-1,!c);r.flush(s)}_handleFragmentLoadProgress(e){}_doFragLoad(e,r,n=null,i){var a;this.fragCurrent=e;const c=r.details;if(!this.levels||!c)throw new Error(`frag load aborted, missing level${c?"":" detail"}s`);let s=null;if(e.encrypted&&!((a=e.decryptdata)!=null&&a.key)){if(this.log(`Loading key for ${e.sn} of [${c.startSN}-${c.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=br.KEY_LOADING,this.fragCurrent=e,s=this.keyLoader.load(e).then(T=>{if(!this.fragContextChanged(T.frag))return this.hls.trigger(ke.KEY_LOADED,T),this.state===br.KEY_LOADING&&(this.state=br.IDLE),T}),this.hls.trigger(ke.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(s=this.keyLoader.loadClear(e,c.encryptedFragments,this.startFragRequested),s&&this.log("[eme] blocking frag load until media-keys acquired"));const f=this.fragPrevious;if(To(e)&&(!f||e.sn!==f.sn)){const T=this.shouldLoadParts(r.details,e.end);T!==this.loadingParts&&(this.log(`LL-Part loading ${T?"ON":"OFF"} loading sn ${f==null?void 0:f.sn}->${e.sn}`),this.loadingParts=T)}if(n=Math.max(e.start,n||0),this.loadingParts&&To(e)){const T=c.partList;if(T&&i){n>c.fragmentEnd&&c.fragmentHint&&(e=c.fragmentHint);const E=this.getNextPart(T,e,n);if(E>-1){const C=T[E];e=this.fragCurrent=C.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${C.index} (${E}/${T.length-1}) of ${this.fragInfo(e,!1,C)}) cc: ${e.cc} [${c.startSN}-${c.endSN}], target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=C.start+C.duration,this.state=br.FRAG_LOADING;let N;return s?N=s.then(R=>!R||this.fragContextChanged(R.frag)?null:this.doFragPartsLoad(e,C,r,i)).catch(R=>this.handleFragLoadError(R)):N=this.doFragPartsLoad(e,C,r,i).catch(R=>this.handleFragLoadError(R)),this.hls.trigger(ke.FRAG_LOADING,{frag:e,part:C,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):N}else if(!e.url||this.loadedEndOfParts(T,n))return Promise.resolve(null)}}if(To(e)&&this.loadingParts){var m;this.log(`LL-Part loading OFF after next part miss @${n.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(m=c.partList)==null?void 0:m.filter(T=>T.loaded).map(T=>`[${T.start}-${T.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+c.startSN+"-"+c.endSN+"]"}, target: ${parseFloat(n.toFixed(3))}`),fn(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=br.FRAG_LOADING;const x=this.config.progressive&&e.type!==Sn.SUBTITLE;let _;return x&&s?_=s.then(T=>!T||this.fragContextChanged(T.frag)?null:this.fragmentLoader.load(e,i)).catch(T=>this.handleFragLoadError(T)):_=Promise.all([this.fragmentLoader.load(e,x?i:void 0),s]).then(([T])=>(!x&&i&&i(T),T)).catch(T=>this.handleFragLoadError(T)),this.hls.trigger(ke.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):_}doFragPartsLoad(e,r,n,i){return new Promise((a,c)=>{var s;const f=[],m=(s=n.details)==null?void 0:s.partList,x=_=>{this.fragmentLoader.loadPart(e,_,i).then(T=>{f[_.index]=T;const E=T.part;this.hls.trigger(ke.FRAG_LOADED,T);const C=ble(n.details,e.sn,_.index+1)||o2e(m,e.sn,_.index+1);if(C)x(C);else return a({frag:e,part:E,partsLoaded:f})}).catch(c)};x(r)})}handleFragLoadError(e){if("data"in e){const r=e.data;r.frag&&r.details===Qt.INTERNAL_ABORTED?this.handleFragLoadAborted(r.frag,r.part):r.frag&&r.type===Ln.KEY_SYSTEM_ERROR?(r.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(r.frag)):this.hls.trigger(ke.ERROR,r)}else this.hls.trigger(ke.ERROR,{type:Ln.OTHER_ERROR,details:Qt.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const r=this.getCurrentContext(e);if(!r||this.state!==br.PARSING){!this.fragCurrent&&this.state!==br.STOPPED&&this.state!==br.ERROR&&(this.state=br.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 s=this.getLevelDetails(),m=s&&n.sn>s.endSN||this.shouldLoadParts(s,n.end);m!==this.loadingParts&&(this.log(`LL-Part loading ${m?"ON":"OFF"} after parsing segment ending @${n.end.toFixed(2)}`),this.loadingParts=m),this.updateLevelTiming(n,i,a,e.partial)}shouldLoadParts(e,r){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var n;const a=e.partList[0];if(a.fragment.type===Sn.SUBTITLE)return!1;const c=a.end+(((n=e.fragmentHint)==null?void 0:n.duration)||0);if(r>=c){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>a.start-a.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 s=r[i],f=s.details,m=c>-1?ble(f,a,c):null,x=m?m.fragment:a2e(f,a,n);return x?(n&&n!==x&&(x.stats=n.stats),{frag:x,part:m,level:s}):null}bufferFragmentData(e,r,n,i,a){if(this.state!==br.PARSING)return;const{data1:c,data2:s}=e;let f=c;if(s&&(f=eh(c,s)),!f.length)return;const m=this.initPTS[r.cc],x=m?-m.baseTime/m.timescale:void 0,_={type:e.type,frag:r,part:n,chunkMeta:i,offset:x,parent:r.type,data:f};if(this.hls.trigger(ke.BUFFER_APPENDING,_),e.dropped&&e.independent&&!n){if(a)return;this.flushBufferGap(r)}}flushBufferGap(e){const r=this.media;if(!r)return;if(!vi.isBuffered(r,r.currentTime)){this.flushMainBuffer(0,e.start);return}const n=r.currentTime,i=vi.bufferInfo(r,n,0),a=e.duration,c=Math.min(this.config.maxFragLookUpTolerance*2,a*.25),s=Math.max(Math.min(e.start-c,i.end-c),n+c);e.start-s>c&&this.flushMainBuffer(s,e.start)}getFwdBufferInfo(e,r){var n;const i=this.getLoadPosition();if(!fn(i))return null;const 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=vi.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 s=Math.max(Math.min(a.nextStart,c.end)-r,i);return vi.bufferInfo(e,r,s)}}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 s=e.bufferedIndex;for(let f=a.length-1;f>s;f--)a[f].start=r}}return!1}reduceMaxBufferLength(e,r){const n=this.config,i=Math.max(Math.min(e-r,n.maxBufferLength),r),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,r=Sn.MAIN){const n=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,r):null;return n&&"fragment"in n?n.fragment:n}getNextFragment(e,r){const n=r.fragments,i=n.length;if(!i)return null;const{config:a}=this,c=r.fragmentStart,s=a.lowLatencyMode&&!!r.partList;let f=null;if(r.live){const _=a.initialLiveManifestSize;if(i<_)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${_})`),null;if(!r.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e=c?(R=E,D=E===T?"config":"next load start"):C!==null?(R=C,D="live edge"):(R=e,D="buffer pos"),R=a){const f=c.sn;return this.loopSn!==f&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${f}`),this.loopSn=f),null}}return this.loopSn=void 0,c}get primaryPrefetch(){if(Tle(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(Tle(this.config)&&e.type!==Sn.SUBTITLE){const n=this.hls.interstitialsManager,i=n==null?void 0:n.bufferingItem;if(i){const c=i.event;if(c){if(c.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||e.start-i.end>1))return null}const a=n==null?void 0:n.playerQueue;if(a)for(let c=a.length;c--;){const s=a[c].interstitial;if(s.appendInPlace&&e.start>=s.startTime&&e.end<=s.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,r,n){let i=-1,a=!1,c=!0;for(let s=0,f=e.length;s-1&&nn.start)return!0}return!1}getInitialLiveFragment(e){const r=e.fragments,n=this.fragPrevious;let i=null;if(n){if(e.hasProgramDateTime&&(i=QNt(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=HEe(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:s}=n;const{fragmentHint:f}=n,{maxFragLookUpTolerance:m}=i,x=n.partList,_=!!(this.loadingParts&&x!=null&&x.length&&f);_&&!this.bitrateTest&&x[x.length-1].fragment.sn===f.sn&&(c=c.concat(f),s=f.sn);let T;if(er-m||(E=this.media)!=null&&E.paused||!this.startFragRequested?0:m;T=D0(a,c,e,N)}else T=c[c.length-1];if(T){const C=T.sn-n.startSN,N=this.fragmentTracker.getState(T);if((N===sl.OK||N===sl.PARTIAL&&T.gap)&&(a=T),a&&T.sn===a.sn&&(!_||x[0].fragment.sn>T.sn||!n.live)&&T.level===a.level){const D=c[C+1];T.sn${e.startSN} fragments: ${i}`),f}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}handleFragLoadAborted(e,r){this.transmuxer&&e.type===this.playlistType&&To(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.fragCurrent||!this.fragContextChanged(e)&&this.state!==br.FRAG_LOADING_WAITING_RETRY)&&(this.state=br.IDLE)}onFragmentOrKeyLoadError(e,r){var n;if(r.chunkMeta&&!r.frag){const D=this.getCurrentContext(r.chunkMeta);D&&(r.frag=D.frag)}const i=r.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var a;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(a=this.fragCurrent)==null?void 0:a.url}`);return}const c=r.details===Qt.FRAG_GAP;c&&this.fragmentTracker.fragBuffered(i,!0);const s=r.errorAction;if(!s){this.state=br.ERROR;return}const{action:f,flags:m,retryCount:x=0,retryConfig:_}=s,T=!!_,E=T&&f===zl.RetryRequest,C=T&&!s.resolved&&m===qu.MoveAllAlternatesMatchingHost,N=(n=this.hls.latestLevelDetails)==null?void 0:n.live;if(!E&&C&&To(i)&&!i.endList&&N&&!KEe(r))this.resetFragmentErrors(e),this.treatAsGap(i),s.resolved=!0;else if((E||C)&&x<_.maxNumRetry){var R;const D=K8((R=r.response)==null?void 0:R.code),M=vW(_,x);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+M,this.state=br.FRAG_LOADING_WAITING_RETRY,s.resolved=!0,D){this.log("Waiting for connection (offline)"),this.retryDate=1/0,r.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${r.details}, retrying loading ${x+1}/${_.maxNumRetry} in ${M}ms`)}else if(_)if(this.resetFragmentErrors(e),x<_.maxNumRetry)!c&&f!==zl.RemoveAlternatePermanently&&(s.resolved=!0);else{this.warn(`${r.details} reached or exceeded max retry (${x})`);return}else f===zl.SendAlternateToPenaltyBox?this.state=br.WAITING_LEVEL:this.state=br.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),r=this.retryDate,n=r===1/0;(!r||e>=r||n&&!K8(0))&&(n&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=br.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===br.PARSING||this.state===br.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.getLoadPosition()}) is not buffered, flush ${n} buffer`),r&&(this.fragmentTracker.removeFragment(r),this.nextLoadPosition=r.start),this.resetLoadingState(),c}return!1}resetFragmentErrors(e){e===Sn.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==br.STOPPED&&(this.state=br.IDLE)}afterBufferFlushed(e,r,n){if(!e)return;const i=vi.getBuffered(e);this.fragmentTracker.detectEvictedFragments(r,i,n),this.state===br.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==br.STOPPED&&(this.state=br.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,r=e?e.details:null;r!=null&&r.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(r,r.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(!Object.keys(e.elementaryStreams).reduce((f,m)=>{const x=e.elementaryStreams[m];if(x){const _=x.endPTS-x.startPTS;if(_<=0)return this.warn(`Could not parse fragment ${e.sn} ${m} duration reliably (${_})`),f||!1;const T=i?0:n2e(a,e,x.startPTS,x.endPTS,x.startDTS,x.endDTS,this);return this.hls.trigger(ke.LEVEL_PTS_UPDATED,{details:a,level:n,drift:T,type:m,frag:e,start:x.startPTS,end:x.endPTS}),!0}return f},!1)){var s;const f=((s=this.transmuxer)==null?void 0:s.error)===null;if((n.fragmentError===0||f&&(n.fragmentError<2||e.endList))&&this.treatAsGap(e,n),f){const m=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(m.message),this.hls.trigger(ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.FRAG_PARSING_ERROR,fatal:!1,error:m,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=br.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${r?" part: "+r.index:""} of ${this.fragInfo(e,!1,r)})`),this.hls.trigger(ke.FRAG_PARSED,{frag:e,part:r})}playlistLabel(){return this.playlistType===Sn.MAIN?"level":"track"}fragInfo(e,r=!0,n){var i,a;return`${this.playlistLabel()} ${e.level} (${n?"part":"frag"}:[${((i=r&&!n?e.startPTS:(n||e).start)!=null?i:NaN).toFixed(3)}-${((a=r&&!n?e.endPTS:(n||e).end)!=null?a:NaN).toFixed(3)}]${n&&e.type==="main"?"INDEPENDENT="+(n.independent?"YES":"NO"):""}`}treatAsGap(e,r){r&&r.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}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}}function Tle(t){return!!t.interstitialsController&&t.enableInterstitialPlayback!==!1}class d2e{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:r}=this;let n;if(e.length)e.length===1?n=e[0]:n=MRt(e,r);else return new Uint8Array(0);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function MRt(t,e){const r=new Uint8Array(e);let n=0;for(let i=0;i0)return t.subarray(r,r+n)}function qRt(t,e,r,n){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],a=e[r+2],c=a>>2&15;if(c>12){const E=new Error(`invalid ADTS sampling index:${c}`);t.emit(ke.ERROR,ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.FRAG_PARSING_ERROR,fatal:!0,error:E,reason:E.message});return}const s=(a>>6&3)+1,f=e[r+3]>>6&3|(a&1)<<2,m="mp4a.40."+s,x=i[c];let _=c;(s===5||s===29)&&(_-=3);const T=[s<<3|(_&14)>>1,(_&1)<<7|f<<3];return $s.log(`manifest codec:${n}, parsed codec:${m}, channels:${f}, rate:${x} (ADTS object type:${s} sampling index:${c})`),{config:T,samplerate:x,channelCount:f,codec:m,parsedCodec:m,manifestCodec:n}}function f2e(t,e){return t[e]===255&&(t[e+1]&246)===240}function p2e(t,e){return t[e+1]&1?7:9}function CW(t,e){return(t[e+3]&3)<<11|t[e+4]<<3|(t[e+5]&224)>>>5}function GRt(t,e){return e+5=t.length)return!1;const n=CW(t,e);if(n<=r)return!1;const i=e+n;return i===t.length||CO(t,i)}return!1}function m2e(t,e,r,n,i){if(!t.samplerate){const a=qRt(e,r,n,i);if(!a)return;Ys(t,a)}}function g2e(t){return 1024*9e4/t}function KRt(t,e){const r=p2e(t,e);if(e+r<=t.length){const n=CW(t,e)-r;if(n>0)return{headerLength:r,frameLength:n}}}function y2e(t,e,r,n,i){const a=g2e(t.samplerate),c=n+i*a,s=KRt(e,r);let f;if(s){const{frameLength:_,headerLength:T}=s,E=T+_,C=Math.max(0,r+E-e.length);C?(f=new Uint8Array(E-T),f.set(e.subarray(r+T,e.length),0)):f=e.subarray(r+T,r+E);const N={unit:f,pts:c};return C||t.samples.push(N),{sample:N,length:E,missing:C}}const m=e.length-r;return f=new Uint8Array(m),f.set(e.subarray(r,e.length),0),{sample:{unit:f,pts:c},length:m,missing:-1}}function YRt(t,e){return kW(t,e)&&d3(t,e+6)+10<=t.length-e}function ZRt(t){return t instanceof ArrayBuffer?t:t.byteOffset==0&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}function o$(t,e=0,r=1/0){return XRt(t,e,r,Uint8Array)}function XRt(t,e,r,n){const i=QRt(t);let a=1;"BYTES_PER_ELEMENT"in n&&(a=n.BYTES_PER_ELEMENT);const c=JRt(t)?t.byteOffset:0,s=(c+t.byteLength)/a,f=(c+e)/a,m=Math.floor(Math.max(0,Math.min(f,s))),x=Math.floor(Math.min(m+Math.max(r,0),s));return new n(i,m,x-m)}function QRt(t){return t instanceof ArrayBuffer?t:t.buffer}function JRt(t){return t&&t.buffer instanceof ArrayBuffer&&t.byteLength!==void 0&&t.byteOffset!==void 0}function eLt(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=id(o$(t.data,1,n)),a=t.data[2+n],c=t.data.subarray(3+n).indexOf(0);if(c===-1)return;const s=id(o$(t.data,3+n,c));let f;return i==="-->"?f=id(o$(t.data,4+n+c)):f=ZRt(t.data.subarray(4+n+c)),e.mimeType=i,e.pictureType=a,e.description=s,e.data=f,e}function tLt(t){if(t.size<2)return;const e=id(t.data,!0),r=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:r.buffer}}function rLt(t){if(t.size<2)return;if(t.type==="TXXX"){let r=1;const n=id(t.data.subarray(r),!0);r+=n.length+1;const i=id(t.data.subarray(r));return{key:t.type,info:n,data:i}}const e=id(t.data.subarray(1));return{key:t.type,info:"",data:e}}function nLt(t){if(t.type==="WXXX"){if(t.size<2)return;let r=1;const n=id(t.data.subarray(r),!0);r+=n.length+1;const i=id(t.data.subarray(r));return{key:t.type,info:n,data:i}}const e=id(t.data);return{key:t.type,info:"",data:e}}function iLt(t){return t.type==="PRIV"?tLt(t):t.type[0]==="W"?nLt(t):t.type==="APIC"?eLt(t):rLt(t)}function sLt(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=d3(t,4),n=10;return{type:e,size:r,data:t.subarray(n,n+r)}}const QN=10,aLt=10;function x2e(t){let e=0;const r=[];for(;kW(t,e);){const n=d3(t,e+6);t[e+5]>>6&1&&(e+=QN),e+=QN;const i=e+n;for(;e+aLt0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Zu.audioId3,duration:Number.POSITIVE_INFINITY});i{if(fn(t))return t*90;const n=r?r.baseTime*9e4/r.timescale:0;return e*9e4+n};let JN=null;const cLt=[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],uLt=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],dLt=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],hLt=[0,1,1,4];function v2e(t,e,r,n,i){if(r+24>e.length)return;const a=b2e(e,r);if(a&&r+a.frameLength<=e.length){const c=a.samplesPerFrame*9e4/a.sampleRate,s=n+i*c,f={unit:e.subarray(r,r+a.frameLength),pts:s,dts:s};return t.config=[],t.channelCount=a.channelCount,t.samplerate=a.sampleRate,t.samples.push(f),{sample:f,length:a.frameLength,missing:0}}}function b2e(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,s=t[e+3]>>6,f=r===3?3-n:n===3?3:4,m=cLt[f*14+i-1]*1e3,_=uLt[(r===3?0:r===2?1:2)*3+a],T=s===3?1:2,E=dLt[r][n],C=hLt[n],N=E*8*C,R=Math.floor(E*m/_+c)*C;if(JN===null){const B=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);JN=B?parseInt(B[1]):0}return!!JN&&JN<=87&&n===2&&m>=224e3&&s===0&&(t[e+3]=t[e+3]|128),{sampleRate:_,channelCount:T,frameLength:R,samplesPerFrame:N}}}function PW(t,e){return t[e]===255&&(t[e+1]&224)===224&&(t[e+1]&6)!==0}function w2e(t,e){return e+1{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 s=Math.min(n,8),f=8-s;a[0]=4278190080>>>24+f<>f,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 s=[48e3,44100,32e3][a],f=e[r+4]&63,x=[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][f*3+a]*2;if(r+x>e.length)return-1;const _=e[r+6]>>5;let T=0;_===2?T+=2:(_&1&&_!==1&&(T+=2),_&4&&(T+=2));const E=(e[r+6]<<8|e[r+7])>>12-T&1,N=[2,1,2,3,3,4,4,5][_]+E,R=e[r+5]>>3,D=e[r+5]&7,M=new Uint8Array([a<<6|R<<1|D>>2,(D&3)<<6|_<<3|E<<2|f>>4,f<<4&224]),B=1536/s*9e4,V=n+i*B,G=e.subarray(r,r+x);return t.config=M,t.channelCount=N,t.samplerate=s,t.samples.push({unit:G,pts:V}),x}class gLt extends IW{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=uC(e,0);let n=(r==null?void 0:r.length)||0;if(r&&e[n]===11&&e[n+1]===119&&jW(r)!==void 0&&T2e(e,n)<=16)return!1;for(let i=e.length;n{const c=TNt(a);if(yLt.test(c.schemeIdUri)){const s=Ale(c,r);let f=c.eventDuration===4294967295?Number.POSITIVE_INFINITY:c.eventDuration/c.timeScale;f<=.001&&(f=Number.POSITIVE_INFINITY);const m=c.payload;n.samples.push({data:m,len:m.byteLength,dts:s,pts:s,type:Zu.emsg,duration:f})}else if(this.config.enableEmsgKLVMetadata&&c.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const s=Ale(c,r);n.samples.push({data:c.payload,len:c.payload.byteLength,dts:s,pts:s,type:Zu.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}}function Ale(t,e){return fn(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class _Lt{constructor(e,r,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new bW(r,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Jy.cbc)}decryptAacSample(e,r,n){const i=e[r].unit;if(i.length<=16)return;const a=i.subarray(16,i.length-i.length%16),c=a.buffer.slice(a.byteOffset,a.byteOffset+a.length);this.decryptBuffer(c).then(s=>{const f=new Uint8Array(s);i.set(f,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,f),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 A2e{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;let a=e.naluState||0;const c=a,s=[];let f=0,m,x,_,T=-1,E=0;for(a===-1&&(T=0,E=this.getNALuType(r,0),a=0,f=1);f=0){const C={data:r.subarray(T,x),type:E};s.push(C)}else{const C=this.getLastNalUnit(e.samples);C&&(c&&f<=4-c&&C.state&&(C.data=C.data.subarray(0,C.data.byteLength-c)),x>0&&(C.data=eh(C.data,r.subarray(0,x)),C.state=0))}f=0&&a>=0){const C={data:r.subarray(T,i),type:E,state:a};s.push(C)}if(s.length===0){const C=this.getLastNalUnit(e.samples);C&&(C.data=eh(C.data,r))}return e.naluState=a,s}}class PA{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&&$s.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)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class vLt extends A2e{parsePES(e,r,n,i){const a=this.parseNALu(e,n.data,i);let c=this.VideoSample,s,f=!1;n.data=null,c&&a.length&&!e.audFound&&(this.pushAccessUnit(c,e),c=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),a.forEach(m=>{var x,_;switch(m.type){case 1:{let N=!1;s=!0;const R=m.data;if(f&&R.length>4){const D=this.readSliceType(R);(D===2||D===4||D===7||D===9)&&(N=!0)}if(N){var T;(T=c)!=null&&T.frame&&!c.key&&(this.pushAccessUnit(c,e),c=this.VideoSample=null)}c||(c=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),c.frame=!0,c.key=N;break}case 5:s=!0,(x=c)!=null&&x.frame&&!c.key&&(this.pushAccessUnit(c,e),c=this.VideoSample=null),c||(c=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),c.key=!0,c.frame=!0;break;case 6:{s=!0,yW(m.data,1,n.pts,r.samples);break}case 7:{var E,C;s=!0,f=!0;const N=m.data,R=this.readSPS(N);if(!e.sps||e.width!==R.width||e.height!==R.height||((E=e.pixelRatio)==null?void 0:E[0])!==R.pixelRatio[0]||((C=e.pixelRatio)==null?void 0:C[1])!==R.pixelRatio[1]){e.width=R.width,e.height=R.height,e.pixelRatio=R.pixelRatio,e.sps=[N];const D=N.subarray(1,4);let M="avc1.";for(let B=0;B<3;B++){let V=D[B].toString(16);V.length<2&&(V="0"+V),M+=V}e.codec=M}break}case 8:s=!0,e.pps=[m.data];break;case 9:s=!0,e.audFound=!0,(_=c)!=null&&_.frame&&(this.pushAccessUnit(c,e),c=null),c||(c=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;case 12:s=!0;break;default:s=!1;break}c&&s&&c.units.push(m)}),i&&c&&(this.pushAccessUnit(c,e),this.VideoSample=null)}getNALuType(e,r){return e[r]&31}readSliceType(e){const r=new PA(e);return r.readUByte(),r.readUEG(),r.readUEG()}skipScalingList(e,r){let n=8,i=8,a;for(let c=0;c{var x,_;switch(m.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:c||(c=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),c.frame=!0,s=!0;break;case 16:case 17:case 18:case 21:if(s=!0,f){var T;(T=c)!=null&&T.frame&&!c.key&&(this.pushAccessUnit(c,e),c=this.VideoSample=null)}c||(c=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),c.key=!0,c.frame=!0;break;case 19:case 20:s=!0,(x=c)!=null&&x.frame&&!c.key&&(this.pushAccessUnit(c,e),c=this.VideoSample=null),c||(c=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),c.key=!0,c.frame=!0;break;case 39:s=!0,yW(m.data,2,n.pts,r.samples);break;case 32:s=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Ys(e.params,this.readVPS(m.data)),this.initVPS=m.data),e.vps=[m.data];break;case 33:if(s=!0,f=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],m.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const E=this.readSPS(m.data);e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.codec=E.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const C in E.params)e.params[C]=E.params[C]}this.pushParameterSet(e.sps,m.data,e.vps),c||(c=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts)),c.key=!0;break;case 34:if(s=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const E=this.readPPS(m.data);for(const C in E)e.params[C]=E[C]}this.pushParameterSet(e.pps,m.data,e.vps)}break;case 35:s=!0,e.audFound=!0,(_=c)!=null&&_.frame&&(this.pushAccessUnit(c,e),c=null),c||(c=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts));break;default:s=!1;break}c&&s&&c.units.push(m)}),i&&c&&(this.pushAccessUnit(c,e),this.VideoSample=null)}pushParameterSet(e,r,n){(n&&n[0]===this.initVPS||!n&&!e.length)&&e.push(r)}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 PA(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 PA(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),s=r.readUByte(),f=r.readUByte(),m=r.readUByte(),x=r.readUByte(),_=r.readUByte(),T=r.readUByte(),E=r.readUByte(),C=r.readUByte(),N=r.readUByte(),R=r.readUByte(),D=r.readUByte(),M=[],B=[];for(let lr=0;lr0)for(let lr=n;lr<8;lr++)r.readBits(2);for(let lr=0;lr1&&r.readEG();for(let At=0;At0&&Ot<16?(be=dr[Ot-1],We=cr[Ot-1]):Ot===255&&(be=r.readBits(16),We=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(),_t=r.readBoolean(),_t&&(r.skipUEG(),r.skipUEG(),r.skipUEG(),r.skipUEG()),r.readBoolean()&&(at=r.readBits(32),Et=r.readBits(32),r.readBoolean()&&r.readUEG(),r.readBoolean())){const cr=r.readBoolean(),hr=r.readBoolean();let Zt=!1;(cr||hr)&&(Zt=r.readBoolean(),Zt&&(r.readUByte(),r.readBits(5),r.readBoolean(),r.readBits(5)),r.readBits(4),r.readBits(4),Zt&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let Pr=0;Pr<=n;Pr++){rt=r.readBoolean();const Nn=rt||r.readBoolean();let ai=!1;Nn?r.readEG():ai=r.readBoolean();const ei=ai?1:r.readUEG()+1;if(cr)for(let Oi=0;Oi>lr&1)<<31-lr)>>>0;let Sr=or.toString(16);return c===1&&Sr==="2"&&(Sr="6"),{codecString:`hvc1.${er}${c}.${Sr}.${a?"H":"L"}${D}.B0`,params:{general_tier_flag:a,general_profile_idc:c,general_profile_space:i,general_profile_compatibility_flags:[s,f,m,x],general_constraint_indicator_flags:[_,T,E,C,N,R],general_level_idc:D,bit_depth:_e+8,bit_depth_luma_minus8:_e,bit_depth_chroma_minus8:Se,min_spatial_segmentation_idc:Te,chroma_format_idc:V,frame_rate:{fixed:rt,fps:Et/at}},width:mt,height:Pt,pixelRatio:[be,We]}}readPPS(e){const r=new PA(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 String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,r).substr(3)}}const vl=188;class ey{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.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=r,this.typeSupported=n,this.logger=i,this.videoParser=null}static probe(e,r){const n=ey.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(vl*5,r-vl)+1,i=0;for(;i1&&(c===0&&s>2||f+vl>n))return c}else{if(s)return-1;break}i++}return-1}static createTrack(e,r){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:NEe[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?r:void 0}}resetInitSegment(e,r,n,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ey.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=ey.createTrack("audio",i),this._id3Track=ey.createTrack("id3"),this._txtTrack=ey.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:r,_id3Track:n}=this;e&&(e.pesData=null),r&&(r.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,r,n=!1,i=!1){n||(this.sampleAes=null);let a;const c=this._videoTrack,s=this._audioTrack,f=this._id3Track,m=this._txtTrack;let x=c.pid,_=c.pesData,T=s.pid,E=f.pid,C=s.pesData,N=f.pesData,R=null,D=this.pmtParsed,M=this._pmtId,B=e.length;if(this.remainderData&&(e=eh(this.remainderData,e),B=e.length,this.remainderData=null),B>4;let ue;if(se>1){if(ue=X+5+e[X+4],ue===X+vl)continue}else ue=X+4;switch(re){case x:Q&&(_&&(a=Hb(_,this.logger))&&(this.readyVideoParser(c.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(c,m,a,!1)),_={data:[],size:0}),_&&(_.data.push(e.subarray(ue,X+vl)),_.size+=X+vl-ue);break;case T:if(Q){if(C&&(a=Hb(C,this.logger)))switch(s.segmentCodec){case"aac":this.parseAACPES(s,a);break;case"mp3":this.parseMPEGPES(s,a);break;case"ac3":this.parseAC3PES(s,a);break}C={data:[],size:0}}C&&(C.data.push(e.subarray(ue,X+vl)),C.size+=X+vl-ue);break;case E:Q&&(N&&(a=Hb(N,this.logger))&&this.parseID3PES(f,a),N={data:[],size:0}),N&&(N.data.push(e.subarray(ue,X+vl)),N.size+=X+vl-ue);break;case 0:Q&&(ue+=e[ue]+1),M=this._pmtId=wLt(e,ue);break;case M:{Q&&(ue+=e[ue]+1);const _e=SLt(e,ue,this.typeSupported,n,this.observer,this.logger);x=_e.videoPid,x>0&&(c.pid=x,c.segmentCodec=_e.segmentVideoCodec),T=_e.audioPid,T>0&&(s.pid=T,s.segmentCodec=_e.segmentAudioCodec),E=_e.id3Pid,E>0&&(f.pid=E),R!==null&&!D&&(this.logger.warn(`MPEG-TS PMT found at ${X} after unknown PID '${R}'. Backtracking to sync byte @${V} to parse all TS packets.`),R=null,X=V-188),D=this.pmtParsed=!0;break}case 17:case 8191:break;default:R=re;break}}else G++;G>0&&eq(this.observer,new Error(`Found ${G} TS packet/s that do not start with 0x47`),void 0,this.logger),c.pesData=_,s.pesData=C,f.pesData=N;const W={audioTrack:s,videoTrack:c,id3Track:f,textTrack:m};return i&&this.extractRemainingSamples(W),W}flush(){const{remainderData:e}=this;this.remainderData=null;let r;return e?r=this.demux(e,-1,!1,!0):r={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r),this.sampleAes?this.decrypt(r,this.sampleAes):r}extractRemainingSamples(e){const{audioTrack:r,videoTrack:n,id3Track:i,textTrack:a}=e,c=n.pesData,s=r.pesData,f=i.pesData;let m;if(c&&(m=Hb(c,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,a,m,!0),n.pesData=null)):n.pesData=c,s&&(m=Hb(s,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,m);break;case"mp3":this.parseMPEGPES(r,m);break;case"ac3":this.parseAC3PES(r,m);break}r.pesData=null}else s!=null&&s.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=s;f&&(m=Hb(f,this.logger))?(this.parseID3PES(i,m),i.pesData=null):i.pesData=f}demuxSampleAes(e,r,n){const i=this.demux(e,n,!0,!this.config.progressive),a=this.sampleAes=new _Lt(this.observer,this.config,r);return this.decrypt(i,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new vLt:e==="hevc"&&(this.videoParser=new bLt))}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}parseAACPES(e,r){let n=0;const i=this.aacOverFlow;let a=r.data;if(i){this.aacOverFlow=null;const _=i.missing,T=i.sample.unit.byteLength;if(_===-1)a=eh(i.sample.unit,a);else{const E=T-_;i.sample.unit.set(a.subarray(0,_),E),e.samples.push(i.sample),n=i.missing}}let c,s;for(c=n,s=a.length;c0;)s+=f}}parseID3PES(e,r){if(r.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=Ys({},r,{type:this._videoTrack?Zu.emsg:Zu.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}}function J8(t,e){return((t[e+1]&31)<<8)+t[e+2]}function wLt(t,e){return(t[e+10]&31)<<8|t[e+11]}function SLt(t,e,r,n,i,a){const c={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},s=(t[e+1]&15)<<8|t[e+2],f=e+3+s-4,m=(t[e+10]&15)<<8|t[e+11];for(e+=12+m;e0){let T=e+5,E=_;for(;E>2;){switch(t[T]){case 106:r.ac3!==!0?a.log("AC-3 audio found, not supported in this browser for now"):(c.audioPid=x,c.segmentAudioCodec="ac3");break}const N=t[T+1]+2;T+=N,E-=N}}break;case 194:case 135:return eq(i,new Error("Unsupported EC-3 in M2TS found"),void 0,a),c;case 36:c.videoPid===-1&&(c.videoPid=x,c.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"));break}e+=_+5}return c}function eq(t,e,r,n){n.warn(`parsing error: ${e.message}`),t.emit(ke.ERROR,ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:e,reason:e.message})}function l$(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Hb(t,e){let r=0,n,i,a,c,s;const f=t.data;if(!t||t.size===0)return null;for(;f[0].length<19&&f.length>1;)f[0]=eh(f[0],f[1]),f.splice(1,1);if(n=f[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 x=n[7];x&192&&(c=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,x&64?(s=(n[14]&14)*536870912+(n[15]&255)*4194304+(n[16]&254)*16384+(n[17]&255)*128+(n[18]&254)/2,c-s>60*9e4&&(e.warn(`${Math.round((c-s)/9e4)}s delta between PTS and DTS, align them`),c=s)):s=c),a=n[8];let _=a+9;if(t.size<=_)return null;t.size-=_;const T=new Uint8Array(t.size);for(let E=0,C=f.length;EN){_-=N;continue}else n=n.subarray(_),N-=_,_=0;T.set(n,r),r+=N}return i&&(i-=a+3),{data:T,pts:c,dts:s,len:i}}return null}class TLt{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}}}const zg=Math.pow(2,32)-1;class Yt{static init(){Yt.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in Yt.types)Yt.types.hasOwnProperty(e)&&(Yt.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const r=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]),n=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]);Yt.HDLR_TYPES={video:r,audio:n};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),a=new Uint8Array([0,0,0,0,0,0,0,0]);Yt.STTS=Yt.STSC=Yt.STCO=a,Yt.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Yt.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Yt.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Yt.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const c=new Uint8Array([105,115,111,109]),s=new Uint8Array([97,118,99,49]),f=new Uint8Array([0,0,0,1]);Yt.FTYP=Yt.box(Yt.types.ftyp,c,f,c,s),Yt.DINF=Yt.box(Yt.types.dinf,Yt.box(Yt.types.dref,i))}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(c[0]=n>>24&255,c[1]=n>>16&255,c[2]=n>>8&255,c[3]=n&255,c.set(e,4),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 Yt.box(Yt.types.mdia,Yt.mdhd(e.timescale||0,e.duration||0),Yt.hdlr(e.type),Yt.minf(e))}static mfhd(e){return Yt.box(Yt.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?Yt.box(Yt.types.minf,Yt.box(Yt.types.smhd,Yt.SMHD),Yt.DINF,Yt.stbl(e)):Yt.box(Yt.types.minf,Yt.box(Yt.types.vmhd,Yt.VMHD),Yt.DINF,Yt.stbl(e))}static moof(e,r,n){return Yt.box(Yt.types.moof,Yt.mfhd(e),Yt.traf(n,r))}static moov(e){let r=e.length;const n=[];for(;r--;)n[r]=Yt.trak(e[r]);return Yt.box.apply(null,[Yt.types.moov,Yt.mvhd(e[0].timescale||0,e[0].duration||0)].concat(n).concat(Yt.mvex(e)))}static mvex(e){let r=e.length;const n=[];for(;r--;)n[r]=Yt.trex(e[r]);return Yt.box.apply(null,[Yt.types.mvex,...n])}static mvhd(e,r){r*=e;const n=Math.floor(r/(zg+1)),i=Math.floor(r%(zg+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 Yt.box(Yt.types.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 s=Yt.box(Yt.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),f=e.width,m=e.height,x=e.pixelRatio[0],_=e.pixelRatio[1];return Yt.box(Yt.types.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,f>>8&255,f&255,m>>8&255,m&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]),s,Yt.box(Yt.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Yt.box(Yt.types.pasp,new Uint8Array([x>>24,x>>16&255,x>>8&255,x&255,_>>24,_>>16&255,_>>8&255,_&255])))}static esds(e){const r=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...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 Yt.box(Yt.types.mp4a,Yt.audioStsd(e),Yt.box(Yt.types.esds,Yt.esds(e)))}static mp3(e){return Yt.box(Yt.types[".mp3"],Yt.audioStsd(e))}static ac3(e){return Yt.box(Yt.types["ac-3"],Yt.audioStsd(e),Yt.box(Yt.types.dac3,e.config))}static stsd(e){const{segmentCodec:r}=e;if(e.type==="audio"){if(r==="aac")return Yt.box(Yt.types.stsd,Yt.STSD,Yt.mp4a(e));if(r==="ac3"&&e.config)return Yt.box(Yt.types.stsd,Yt.STSD,Yt.ac3(e));if(r==="mp3"&&e.codec==="mp3")return Yt.box(Yt.types.stsd,Yt.STSD,Yt.mp3(e))}else if(e.pps&&e.sps){if(r==="avc")return Yt.box(Yt.types.stsd,Yt.STSD,Yt.avc1(e));if(r==="hevc"&&e.vps)return Yt.box(Yt.types.stsd,Yt.STSD,Yt.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/(zg+1)),s=Math.floor(n%(zg+1));return Yt.box(Yt.types.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,s>>24,s>>16&255,s>>8&255,s&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=Yt.sdtp(e),i=e.id,a=Math.floor(r/(zg+1)),c=Math.floor(r%(zg+1));return Yt.box(Yt.types.traf,Yt.box(Yt.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),Yt.box(Yt.types.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])),Yt.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,Yt.box(Yt.types.trak,Yt.tkhd(e),Yt.mdia(e))}static trex(e){const r=e.id;return Yt.box(Yt.types.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 s,f,m,x,_,T;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),s=0;s>>24&255,m>>>16&255,m>>>8&255,m&255,x>>>24&255,x>>>16&255,x>>>8&255,x&255,_.isLeading<<2|_.dependsOn,_.isDependedOn<<6|_.hasRedundancy<<4|_.paddingValue<<1|_.isNonSync,_.degradPrio&61440,_.degradPrio&15,T>>>24&255,T>>>16&255,T>>>8&255,T&255],12+16*s);return Yt.box(Yt.types.trun,c)}static initSegment(e){Yt.types||Yt.init();const r=Yt.moov(e);return eh(Yt.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 C=0;C>8,n[C][N].length&255]),c),c+=2,s.set(n[C][N],c),c+=n[C][N].length}const m=Yt.box(Yt.types.hvcC,s),x=e.width,_=e.height,T=e.pixelRatio[0],E=e.pixelRatio[1];return Yt.box(Yt.types.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,x>>8&255,x&255,_>>8&255,_&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]),m,Yt.box(Yt.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Yt.box(Yt.types.pasp,new Uint8Array([T>>24,T>>16&255,T>>8&255,T&255,E>>24,E>>16&255,E>>8&255,E&255])))}}Yt.types=void 0;Yt.HDLR_TYPES=void 0;Yt.STTS=void 0;Yt.STSC=void 0;Yt.STCO=void 0;Yt.STSZ=void 0;Yt.VMHD=void 0;Yt.SMHD=void 0;Yt.STSD=void 0;Yt.FTYP=void 0;Yt.DINF=void 0;const k2e=9e4;function NW(t,e,r=1,n=!1){const i=t*e*r;return n?Math.round(i):i}function ELt(t,e,r=1,n=!1){return NW(t,e,1/r,n)}function F2(t,e=!1){return NW(t,1e3,1/k2e,e)}function ALt(t,e=1){return NW(t,k2e,1/e)}function kle(t){const{baseTime:e,timescale:r,trackId:n}=t;return`${e/r} (${e}/${r}) trackId: ${n}`}const kLt=10*1e3,CLt=1024,jLt=1152,ILt=1536;let Wb=null,c$=null;function Cle(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}}}class QR extends ah{constructor(e,r,n,i){if(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,Wb===null){const c=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Wb=c?parseInt(c[1]):0}if(c$===null){const a=navigator.userAgent.match(/Safari\/(\d+)/i);c$=a?parseInt(a[1]):0}}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&&kle(r)} > ${e&&kle(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 s=c.pts,f=s-a;return f<-4294967296&&(r=!0,s=Gu(s,n),f=s-a),f>0?a:s},n);return r&&this.debug("PTS rollover detected"),i}remux(e,r,n,i,a,c,s,f){let m,x,_,T,E,C,N=a,R=a;const D=e.pid>-1,M=r.pid>-1,B=r.samples.length,V=e.samples.length>0,G=s&&B>0||B>1;if((!D||V)&&(!M||G)||this.ISGenerated||s){if(this.ISGenerated){var X,Q,re,se;const ve=this.videoTrackConfig;(ve&&(r.width!==ve.width||r.height!==ve.height||((X=r.pixelRatio)==null?void 0:X[0])!==((Q=ve.pixelRatio)==null?void 0:Q[0])||((re=r.pixelRatio)==null?void 0:re[1])!==((se=ve.pixelRatio)==null?void 0:se[1]))||!ve&&G||this.nextAudioTs===null&&V)&&this.resetInitSegment()}this.ISGenerated||(_=this.generateIS(e,r,a,c));const ue=this.isVideoContiguous;let _e=-1,Se;if(G&&(_e=PLt(r.samples),!ue&&this.config.forceKeyFrameOnDiscontinuity))if(C=!0,_e>0){this.warn(`Dropped ${_e} out of ${B} video samples due to a missing keyframe`);const ve=this.getVideoStartPts(r.samples);r.samples=r.samples.slice(_e),r.dropped+=_e,R+=(r.samples[0].pts-ve)/r.inputTimeScale,Se=R}else _e===-1&&(this.warn(`No keyframe found out of ${B} video samples`),C=!1);if(this.ISGenerated){if(V&&G){const ve=this.getVideoStartPts(r.samples),Ae=(Gu(e.samples[0].pts,ve)-ve)/r.inputTimeScale;N+=Math.max(0,Ae),R+=Math.max(0,-Ae)}if(V){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),_=this.generateIS(e,r,a,c)),x=this.remuxAudio(e,N,this.isAudioContiguous,c,M||G||f===Sn.AUDIO?R:void 0),G){const ve=x?x.endPTS-x.startPTS:0;r.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),_=this.generateIS(e,r,a,c)),m=this.remuxVideo(r,R,ue,ve)}}else G&&(m=this.remuxVideo(r,R,ue,0));m&&(m.firstKeyFrame=_e,m.independent=_e!==-1,m.firstKeyFramePTS=Se)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(E=C2e(n,a,this._initPTS,this._initDTS)),i.samples.length&&(T=j2e(i,a,this._initPTS))),{audio:x,video:m,initSegment:_,independent:C,text:T,id3:E}}computeInitPts(e,r,n,i){const a=Math.round(n*r);let c=Gu(e,a);if(c0?Te-1:Te].dts&&(M=!0)}M&&c.sort(function(Te,be){const We=Te.dts-be.dts,rt=Te.pts-be.pts;return We||rt}),C=c[0].dts,N=c[c.length-1].dts;const V=N-C,G=V?Math.round(V/(f-1)):E||e.inputTimeScale/30;if(n){const Te=C-B,be=Te>G,We=Te<-1;if((be||We)&&(be?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${F2(Te,!0)} ms (${Te}dts) hole between fragments detected at ${r.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${F2(-Te,!0)} ms (${Te}dts) overlapping between fragments detected at ${r.toFixed(3)}`),!We||B>=c[0].pts||Wb)){C=B;const rt=c[0].pts-Te;if(be)c[0].dts=C,c[0].pts=rt;else{let at=!0;for(let Et=0;Etrt&&at);Et++){const _t=c[Et].pts;if(c[Et].dts-=Te,c[Et].pts-=Te,Et0?be.dts-c[Te-1].dts:G;if(at=Te>0?be.pts-c[Te-1].pts:G,_t.stretchShortVideoTrack&&this.nextAudioTs!==null){const mt=Math.floor(_t.maxBufferHole*a),Pt=(i?R+i*a:this.nextAudioTs+x)-be.pts;Pt>mt?(E=Pt-Vt,E<0?E=Vt:_e=!0,this.log(`It is approximately ${Pt/90} ms to the next segment; using duration ${E/90} ms for the last video frame.`)):E=Vt}else E=Vt}const Et=Math.round(be.pts-be.dts);Se=Math.min(Se,E),Oe=Math.max(Oe,E),ve=Math.min(ve,at),Ae=Math.max(Ae,at),s.push(Cle(be.key,E,rt,Et))}if(s.length){if(Wb){if(Wb<70){const Te=s[0].flags;Te.dependsOn=2,Te.isNonSync=0}}else if(c$&&Ae-ve0&&(i&&Math.abs(B-(D+M))<9e3||Math.abs(Gu(N[0].pts,B)-(D+M))<20*x),N.forEach(function(Ae){Ae.pts=Gu(Ae.pts,B)}),!n||D<0){const Ae=N.length;if(N=N.filter(we=>we.pts>=0),Ae!==N.length&&this.warn(`Removed ${N.length-Ae} of ${Ae} samples (initPTS ${M} / ${c})`),!N.length)return;a===0?D=0:i&&!C?D=Math.max(0,B-M):D=N[0].pts-M}if(e.segmentCodec==="aac"){const Ae=this.config.maxAudioFramesDrift;for(let we=0,ge=D+M;we=Ae*x&&be0){X+=R;try{W=new Uint8Array(X)}catch(be){this.observer.emit(ke.ERROR,ke.ERROR,{type:Ln.MUX_ERROR,details:Qt.REMUX_ALLOC_ERROR,fatal:!1,error:be,bytes:X,reason:`fail allocating audio mdat ${X}`});return}T||(new DataView(W.buffer).setUint32(0,X),W.set(Yt.types.mdat,4))}else return;W.set(Ne,R);const Te=Ne.byteLength;R+=Te,E.push(Cle(!0,m,Te,0)),G=Ie}const re=E.length;if(!re)return;const se=E[E.length-1];D=G-M,this.nextAudioTs=D+f*se.duration;const ue=T?new Uint8Array(0):Yt.moof(e.sequenceNumber++,V/f,Ys({},e,{samples:E}));e.samples=[];const _e=(V-M)/c,Se=this.nextAudioTs/c,Oe={data1:ue,data2:W,startPTS:_e,endPTS:Se,startDTS:_e,endDTS:Se,type:"audio",hasAudio:!0,hasVideo:!1,nb:re};return this.isAudioContiguous=!0,Oe}}function Gu(t,e){let r;if(e===null)return t;for(e4294967296;)t+=r;return t}function PLt(t){for(let e=0;ec.pts-s.pts);const a=t.samples;return t.samples=[],{samples:a}}class NLt extends ah{constructor(e,r,n,i){super("passthrough-remuxer",i),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}destroy(){}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.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,r){let{audioCodec:n,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:a,video:c}=this.initData=DEe(e);if(r)_Nt(e,r);else{const f=a||c;f!=null&&f.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${f.codec}")!`)}a&&(n=jle(a,Js.AUDIO,this)),c&&(i=jle(c,Js.VIDEO,this));const s={};a&&c?s.audiovideo={container:"video/mp4",codec:n+","+i,supplemental:c.supplemental,encrypted:c.encrypted,initSegment:e,id:"main"}:a?s.audio={container:"audio/mp4",codec:n,encrypted:a.encrypted,initSegment:e,id:"audio"}:c?s.video={container:"video/mp4",codec:i,supplemental:c.supplemental,encrypted:c.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,r,n,i,a,c){var s,f;let{initPTS:m,lastEndTime:x}=this;const _={audio:void 0,video:void 0,text:i,id3:n,initSegment:void 0};fn(x)||(x=this.lastEndTime=a||0);const T=r.samples;if(!T.length)return _;const E={initPTS:void 0,timescale:void 0,trackId:void 0};let C=this.initData;if((s=C)!=null&&s.length||(this.generateInitSegment(T),C=this.initData),!((f=C)!=null&&f.length))return this.warn("Failed to generate initSegment."),_;this.emitInitSegment&&(E.tracks=this.initTracks,this.emitInitSegment=!1);const N=bNt(T,C,this),R=C.audio?N[C.audio.id]:null,D=C.video?N[C.video.id]:null,M=eR(D,1/0),B=eR(R,1/0),V=eR(D,0,!0),G=eR(R,0,!0);let W=a,X=0;const Q=R&&(!D||!m&&B0?this.lastEndTime=ue:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const _e=!!C.audio,Se=!!C.video;let ve="";_e&&(ve+="audio"),Se&&(ve+="video");const Oe=(C.audio?C.audio.encrypted:!1)||(C.video?C.video.encrypted:!1),Ae={data1:T,startPTS:se,startDTS:se,endPTS:ue,endDTS:ue,type:ve,hasAudio:_e,hasVideo:Se,nb:1,dropped:0,encrypted:Oe};_.audio=_e&&!Se?Ae:void 0,_.video=Se?Ae:void 0;const we=D==null?void 0:D.sampleCount;if(we){const ge=D.keyFrameIndex,Ne=ge!==-1;Ae.nb=we,Ae.dropped=ge===0||this.isVideoContiguous?0:Ne?ge:we,Ae.independent=Ne,Ae.firstKeyFrame=ge,Ne&&D.keyFrameStart&&(Ae.firstKeyFramePTS=(D.keyFrameStart-m.baseTime)/m.timescale),this.isVideoContiguous||(_.independent=Ne),this.isVideoContiguous||(this.isVideoContiguous=Ne),Ae.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ge}/${we} dropped: ${Ae.dropped} start: ${Ae.firstKeyFramePTS||"NA"}`)}return _.initSegment=E,_.id3=C2e(n,a,m,m),i.samples.length&&(_.text=j2e(i,a,m)),_}}function eR(t,e,r=!1){return(t==null?void 0:t.start)!==void 0?(t.start+(r?t.duration:0))/t.timescale:e}function RLt(t,e,r,n){if(t===null)return!0;const i=Math.max(n,1),a=e-t.baseTime/t.timescale;return Math.abs(a-r)>i}function jle(t,e,r){const n=t.codec;return n&&n.length>4?n:e===Js.AUDIO?n==="ec-3"||n==="ac-3"||n==="alac"?n:n==="fLaC"||n==="Opus"?vO(n,!1):(r.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"):(r.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1")}let am;try{am=self.performance.now.bind(self.performance)}catch{am=Date.now}const JR=[{demux:xLt,remux:NLt},{demux:ey,remux:QR},{demux:pLt,remux:QR},{demux:gLt,remux:QR}];JR.splice(2,0,{demux:mLt,remux:QR});class Ile{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){const a=n.transmuxing;a.executeStart=am();let c=new Uint8Array(e);const{currentTransmuxState:s,transmuxConfig:f}=this;i&&(this.currentTransmuxState=i);const{contiguous:m,discontinuity:x,trackSwitch:_,accurateTimeOffset:T,timeOffset:E,initSegmentChange:C}=i||s,{audioCodec:N,videoCodec:R,defaultInitPts:D,duration:M,initSegmentData:B}=f,V=LLt(c,r);if(V&&Uw(V.method)){const Q=this.getDecrypter(),re=SW(V.method);if(Q.isSync()){let se=Q.softwareDecrypt(c,V.key.buffer,V.iv.buffer,re);if(n.part>-1){const _e=Q.flush();se=_e&&_e.buffer}if(!se)return a.executeEnd=am(),u$(n);c=new Uint8Array(se)}else return this.asyncResult=!0,this.decryptionPromise=Q.webCryptoDecrypt(c,V.key.buffer,V.iv.buffer,re).then(se=>{const ue=this.push(se,null,n);return this.decryptionPromise=null,ue}),this.decryptionPromise}const G=this.needsProbing(x,_);if(G){const Q=this.configureTransmuxer(c);if(Q)return this.logger.warn(`[transmuxer] ${Q.message}`),this.observer.emit(ke.ERROR,ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.FRAG_PARSING_ERROR,fatal:!1,error:Q,reason:Q.message}),a.executeEnd=am(),u$(n)}(x||_||C||G)&&this.resetInitSegment(B,N,R,M,r),(x||C||G)&&this.resetInitialTimestamp(D),m||this.resetContiguity();const W=this.transmux(c,V,E,T,n);this.asyncResult=dC(W);const X=this.currentTransmuxState;return X.contiguous=!0,X.discontinuity=!1,X.trackSwitch=!1,a.executeEnd=am(),W}flush(e){const r=e.transmuxing;r.executeStart=am();const{decrypter:n,currentTransmuxState:i,decryptionPromise:a}=this;if(a)return this.asyncResult=!0,a.then(()=>this.flush(e));const c=[],{timeOffset:s}=i;if(n){const _=n.flush();_&&c.push(this.push(_.buffer,null,e))}const{demuxer:f,remuxer:m}=this;if(!f||!m){r.executeEnd=am();const _=[u$(e)];return this.asyncResult?Promise.resolve(_):_}const x=f.flush(s);return dC(x)?(this.asyncResult=!0,x.then(_=>(this.flushRemux(c,_,e),c))):(this.flushRemux(c,x,e),this.asyncResult?Promise.resolve(c):c)}flushRemux(e,r,n){const{audioTrack:i,videoTrack:a,id3Track:c,textTrack:s}=r,{accurateTimeOffset:f,timeOffset:m}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?" part: "+n.part:""} of ${this.id===Sn.MAIN?"level":"track"} ${n.level}`);const x=this.remuxer.remux(i,a,c,s,m,f,!0,this.id);e.push({remuxResult:x,chunkMeta:n}),n.transmuxing.executeEnd=am()}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){const{demuxer:c,remuxer:s}=this;!c||!s||(c.resetInitSegment(e,r,n,i),s.resetInitSegment(e,r,n,a))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,r,n,i,a){let c;return r&&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{audioTrack:a,videoTrack:c,id3Track:s,textTrack:f}=this.demuxer.demux(e,r,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(a,c,s,f,r,n,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,r,n,i,a){return this.demuxer.demuxSampleAes(e,r,n).then(c=>({remuxResult:this.remuxer.remux(c.audioTrack,c.videoTrack,c.id3Track,c.textTrack,n,i,!1,this.id),chunkMeta:a}))}configureTransmuxer(e){const{config:r,observer:n,typeSupported:i}=this;let a;for(let _=0,T=JR.length;_0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(r=e),r}const u$=t=>({remuxResult:{},chunkMeta:t});function dC(t){return"then"in t&&t.then instanceof Function}class DLt{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 OLt{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 Ple=0;class I2e{constructor(e,r,n,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ple++,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=f=>{const m=f.data,x=this.hls;if(!(!x||!(m!=null&&m.event)||m.instanceNo!==this.instanceNo))switch(m.event){case"init":{var _;const T=(_=this.workerContext)==null?void 0:_.objectURL;T&&self.URL.revokeObjectURL(T);break}case"transmuxComplete":{this.handleTransmuxComplete(m.data);break}case"flush":{this.onFlush(m.data);break}case"workerLog":{x.logger[m.data.logType]&&x.logger[m.data.logType](m.data.message);break}default:{m.data=m.data||{},m.data.frag=this.frag,m.data.part=this.part,m.data.id=this.id,x.trigger(m.event,m.data);break}}},this.onWorkerError=f=>{if(!this.hls)return;const m=new Error(`${f.message} (${f.filename}:${f.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(ke.ERROR,{type:Ln.OTHER_ERROR,details:Qt.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:m})};const a=e.config;this.hls=e,this.id=r,this.useWorker=!!a.enableWorker,this.onTransmuxComplete=n,this.onFlush=i;const c=(f,m)=>{m=m||{},m.frag=this.frag||void 0,f===ke.ERROR&&(m=m,m.parent=this.id,m.part=this.part,this.error=m.error),this.hls.trigger(f,m)};this.observer=new AW,this.observer.on(ke.FRAG_DECRYPTED,c),this.observer.on(ke.ERROR,c);const s=Hoe(a.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const f=this.hls.logger;if(a.workerPath||zRt()){try{a.workerPath?(f.log(`loading Web Worker ${a.workerPath} for "${r}"`),this.workerContext=URt(a.workerPath)):(f.log(`injecting Web Worker for "${r}"`),this.workerContext=$Rt());const{worker:x}=this.workerContext;x.addEventListener("message",this.onWorkerMessage),x.addEventListener("error",this.onWorkerError),x.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:s,id:r,config:ra(a)})}catch(x){f.warn(`Error setting up "${r}" Web Worker, fallback to inline`,x),this.terminateWorker(),this.error=null,this.transmuxer=new Ile(this.observer,s,a,"",r,e.logger)}return}}this.transmuxer=new Ile(this.observer,s,a,"",r,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Ple++;const r=this.hls.config,n=Hoe(r.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:n,id:this.id,config:ra(r)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),VRt(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,s,f,m,x){var _,T;m.transmuxing.start=self.performance.now();const{instanceNo:E,transmuxer:C}=this,N=c?c.start:a.start,R=a.decryptdata,D=this.frag,M=!(D&&a.cc===D.cc),B=!(D&&m.level===D.level),V=D?m.sn-D.sn:-1,G=this.part?m.part-this.part.index:-1,W=V===0&&m.id>1&&m.id===(D==null?void 0:D.stats.chunkCount),X=!B&&(V===1||V===0&&(G===1||W&&G<=0)),Q=self.performance.now();(B||V||a.stats.parsing.start===0)&&(a.stats.parsing.start=Q),c&&(G||!X)&&(c.stats.parsing.start=Q);const re=!(D&&((_=a.initSegment)==null?void 0:_.url)===((T=D.initSegment)==null?void 0:T.url)),se=new OLt(M,X,f,B,N,re);if(!X||M||re){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${a.type} sn: ${m.sn}${m.part>-1?" part: "+m.part:""} ${this.id===Sn.MAIN?"level":"track"}: ${m.level} id: ${m.id} discontinuity: ${M} trackSwitch: ${B} contiguous: ${X} accurateTimeOffset: ${f} timeOffset: ${N} initSegmentChange: ${re}`);const ue=new DLt(n,i,r,s,x);this.configureTransmuxer(ue)}if(this.frag=a,this.part=c,this.workerContext)this.workerContext.worker.postMessage({instanceNo:E,cmd:"demux",data:e,decryptdata:R,chunkMeta:m,state:se},e instanceof ArrayBuffer?[e]:[]);else if(C){const ue=C.push(e,R,m,se);dC(ue)?ue.then(_e=>{this.handleTransmuxComplete(_e)}).catch(_e=>{this.transmuxerError(_e,m,"transmuxer-interface push error")}):this.handleTransmuxComplete(ue)}}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);dC(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(ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.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 Nle=100;class MLt extends EW{constructor(e,r,n){super(e,r,n,"audio-stream-controller",Sn.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-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(ke.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ke.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(ke.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ke.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ke.BUFFER_RESET,this.onBufferReset,this),e.on(ke.BUFFER_CREATED,this.onBufferCreated,this),e.on(ke.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ke.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ke.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(ke.FRAG_LOADING,this.onFragLoading,this),e.on(ke.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(ke.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ke.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(ke.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ke.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ke.BUFFER_RESET,this.onBufferReset,this),e.off(ke.BUFFER_CREATED,this.onBufferCreated,this),e.off(ke.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ke.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ke.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ke.FRAG_LOADING,this.onFragLoading,this),e.off(ke.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:r,id:n,initPTS:i,timescale:a,trackId:c}){if(n===Sn.MAIN){const s=r.cc,f=this.fragCurrent;if(this.initPTS[s]={baseTime:i,timescale:a,trackId:c},this.log(`InitPTS for cc: ${s} found from main: ${i/a} (${i}/${a}) trackId: ${c}`),this.mainAnchor=r,this.state===br.WAITING_INIT_PTS){const m=this.waitingData;(!m&&!this.loadingParts||m&&m.frag.cc!==s)&&this.syncWithAnchor(r,m==null?void 0:m.frag)}else!this.hls.hasEnoughToStart&&f&&f.cc!==s?(f.abortRequests(),this.syncWithAnchor(r,f)):this.state===br.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?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(),s=this.getLoadPosition(),f=HEe(c,a,s);f&&(this.log(`Syncing with main frag at ${f.start} cc ${f.cc}`),this.startFragRequested=!1,this.nextLoadPosition=f.start,this.resetLoadingState(),this.state===br.IDLE&&this.doTickIdle())}startLoad(e,r){if(!this.levels){this.startPosition=e,this.state=br.STOPPED;return}const n=this.lastCurrentTime;this.stopLoad(),this.setInterval(Nle),n>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n,this.state=br.IDLE):this.state=br.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=r?-1:e,this.tick()}doTick(){switch(this.state){case br.IDLE:this.doTickIdle();break;case br.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=br.WAITING_INIT_PTS}break}case br.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case br.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=br.FRAG_LOADING;const s=i.flush().buffer,f={frag:r,part:n,payload:s,networkDetails:null};this._handleFragmentLoadProgress(f),a&&super._handleFragmentLoadComplete(f)}else c&&c.cc!==e.frag.cc&&this.syncWithAnchor(c,e.frag)}else this.state=br.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}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 s=n[a],f=s.details;if(!f||this.waitForLive(s)||this.waitForCdnTuneIn(f)){this.state=br.WAITING_TRACK,this.startFragRequested=!1;return}const m=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&m&&(this.bufferFlushed=!1,this.afterBufferFlushed(m,Js.AUDIO,Sn.AUDIO));const x=this.getFwdBufferInfo(m,Sn.AUDIO);if(x===null)return;if(!this.switchingTrack&&this._streamEnded(x,f)){r.trigger(ke.BUFFER_EOS,{type:"audio"}),this.state=br.ENDED;return}const _=x.len,T=r.maxBufferLength,E=f.fragments,C=E[0].start,N=this.getLoadPosition(),R=this.flushing?N:x.end;if(this.switchingTrack&&i){const B=N;f.PTSKnown&&BC||x.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=C+.05)}if(_>=T&&!this.switchingTrack&&RM.end){const V=this.fragmentTracker.getFragAtPos(R,Sn.MAIN);V&&V.end>M.end&&(M=V,this.mainFragLoading={frag:V,targetBufferTime:null})}if(D.start>M.end)return}this.loadFragment(D,s,R)}onMediaDetaching(e,r){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,r)}onAudioTracksUpdated(e,{audioTracks:r}){this.resetTransmuxer(),this.levels=r.map(n=>new lC(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,this.flushAudioIfNeeded(r),this.state!==br.STOPPED&&(this.setInterval(Nle),this.state=br.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(ke.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(e,r){var n;const{levels:i}=this,{details:a,id:c,groupId:s,track:f}=r;if(!i){this.warn(`Audio tracks reset while loading track ${c} "${f.name}" of "${s}"`);return}const m=this.mainDetails;if(!m||a.endCC>m.endCC||m.expired){this.cachedTrackLoadedData=r,this.state!==br.STOPPED&&(this.state=br.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${c} "${f.name}" of "${s}" loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`);const x=i[c];let _=0;if(a.live||(n=x.details)!=null&&n.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;if(x.details){var T;_=this.alignPlaylists(a,x.details,(T=this.levelLastLoaded)==null?void 0:T.details)}a.alignedSliding||(u2e(a,m),a.alignedSliding||kO(a,m),_=a.fragmentStart)}x.details=a,this.levelLastLoaded=x,this.startFragRequested||this.setStartPosition(m,_),this.hls.trigger(ke.AUDIO_TRACK_UPDATED,{details:a,id:c,groupId:r.groupId}),this.state===br.WAITING_TRACK&&!this.waitForCdnTuneIn(a)&&(this.state=br.IDLE),this.tick()}_handleFragmentLoadProgress(e){var r;const n=e.frag,{part:i,payload:a}=e,{config:c,trackId:s,levels:f}=this;if(!f){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 m=f[s];if(!m){this.warn("Audio track is undefined on fragment load progress");return}const x=m.details;if(!x){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const _=c.defaultAudioCodec||m.audioCodec||"mp4a.40.2";let T=this.transmuxer;T||(T=this.transmuxer=new I2e(this.hls,Sn.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const E=this.initPTS[n.cc],C=(r=n.initSegment)==null?void 0:r.data;if(E!==void 0){const R=i?i.index:-1,D=R!==-1,M=new wW(n.level,n.sn,n.stats.chunkCount,a.byteLength,R,D);T.push(a,C,_,"",n,i,x.totalduration,!1,M,E)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${x.startSN} ,${x.endSN}],track ${s}`);const{cache:N}=this.waitingData=this.waitingData||{frag:n,part:i,cache:new d2e,complete:!1};N.push(new Uint8Array(a)),this.state!==br.STOPPED&&(this.state=br.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===Sn.MAIN&&To(r.frag)&&(this.mainFragLoading=r,this.state===br.IDLE&&this.tick())}onFragBuffered(e,r){const{frag:n,part:i}=r;if(n.type!==Sn.AUDIO){!this.audioOnly&&n.type===Sn.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(To(n)){this.fragPrevious=n;const a=this.switchingTrack;a&&(this.bufferedTrack=a,this.switchingTrack=null,this.hls.trigger(ke.AUDIO_TRACK_SWITCHED,Bs({},a)))}this.fragBufferedComplete(n,i),this.media&&this.tick()}onError(e,r){var n;if(r.fatal){this.state=br.ERROR;return}switch(r.details){case Qt.FRAG_GAP:case Qt.FRAG_PARSING_ERROR:case Qt.FRAG_DECRYPT_ERROR:case Qt.FRAG_LOAD_ERROR:case Qt.FRAG_LOAD_TIMEOUT:case Qt.KEY_LOAD_ERROR:case Qt.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Sn.AUDIO,r);break;case Qt.AUDIO_TRACK_LOAD_ERROR:case Qt.AUDIO_TRACK_LOAD_TIMEOUT:case Qt.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===br.WAITING_TRACK&&((n=r.context)==null?void 0:n.type)===Vi.AUDIO_TRACK&&(this.state=br.IDLE);break;case Qt.BUFFER_ADD_CODEC_ERROR:case Qt.BUFFER_APPEND_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case Qt.BUFFER_FULL_ERROR:if(r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Qt.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onBufferFlushing(e,{type:r}){r!==Js.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:r}){if(r!==Js.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===br.ENDED&&(this.state=br.IDLE);const n=this.mediaBuffer||this.media;n&&(this.afterBufferFlushed(n,r,Sn.AUDIO),this.tick())}}_handleTransmuxComplete(e){var r;const n="audio",{hls:i}=this,{remuxResult:a,chunkMeta:c}=e,s=this.getCurrentContext(c);if(!s){this.resetWhenMissingContext(c);return}const{frag:f,part:m,level:x}=s,{details:_}=x,{audio:T,text:E,id3:C,initSegment:N}=a;if(this.fragContextChanged(f)||!_){this.fragmentTracker.removeFragment(f);return}if(this.state=br.PARSING,this.switchingTrack&&T&&this.completeAudioSwitch(this.switchingTrack),N!=null&&N.tracks){const R=f.initSegment||f;if(this.unhandledEncryptionError(N,f))return;this._bufferInitSegment(x,N.tracks,R,c),i.trigger(ke.FRAG_PARSING_INIT_SEGMENT,{frag:R,id:n,tracks:N.tracks})}if(T){const{startPTS:R,endPTS:D,startDTS:M,endDTS:B}=T;m&&(m.elementaryStreams[Js.AUDIO]={startPTS:R,endPTS:D,startDTS:M,endDTS:B}),f.setElementaryStreamInfo(Js.AUDIO,R,D,M,B),this.bufferFragmentData(T,f,m,c)}if(C!=null&&(r=C.samples)!=null&&r.length){const R=Ys({id:n,frag:f,details:_},C);i.trigger(ke.FRAG_PARSING_METADATA,R)}if(E){const R=Ys({id:n,frag:f,details:_},E);i.trigger(ke.FRAG_PARSING_USERDATA,R)}}_bufferInitSegment(e,r,n,i){if(this.state!==br.PARSING||(r.video&&delete r.video,r.audiovideo&&delete r.audiovideo,!r.audio))return;const a=r.audio;a.id=Sn.AUDIO;const c=e.audioCodec;this.log(`Init audio buffer, container:${a.container}, codecs[level/parsed]=[${c}/${a.codec}]`),c&&c.split(",").length===1&&(a.levelCodec=c),this.hls.trigger(ke.BUFFER_CODECS,r);const s=a.initSegment;if(s!=null&&s.byteLength){const f={type:"audio",frag:n,part:null,chunkMeta:i,parent:n.type,data:s};this.hls.trigger(ke.BUFFER_APPENDING,f)}this.tickImmediate()}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===sl.NOT_LOADED||i===sl.PARTIAL){var a;if(!To(e))this._loadInitSegment(e,r);else 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=br.WAITING_INIT_PTS;const c=this.mainDetails;c&&c.fragmentStart!==r.details.fragmentStart&&kO(r.details,c)}else super.loadFragment(e,r,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:r,lang:n,assocLang:i,characteristics:a,audioCodec:c,channels:s}=this.bufferedTrack;g0({name:r,lang:n,assocLang:i,characteristics:a,audioCodec:c,channels:s},e,$_)||(wO(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.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,r.trigger(ke.AUDIO_TRACK_SWITCHED,Bs({},e))}}class RW extends ah{constructor(e,r){super(r,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=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&&x>r.partTarget&&(f+=1)}const m=n&&Woe(n);return new Koe(s,f>=0?f:void 0,m)}}}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=self.performance.now(),s=a.loading.first?Math.max(0,c-a.loading.first):0;i.advancedDateTime=Date.now()-s;const f=this.hls.config.timelineOffset;if(f!==i.appliedTimelineOffset){const x=Math.max(f||0,0);i.appliedTimelineOffset=x,i.fragments.forEach(_=>{_.setStart(_.playlistOffset+x)})}if(i.live||n!=null&&n.live){const x="levelInfo"in r?r.levelInfo:r.track;if(i.reloaded(n),n&&i.fragments.length>0){jRt(n,i,this);const M=i.playlistParsingError;if(M){this.warn(M);const B=this.hls;if(!B.config.ignorePlaylistParsingErrors){var m;const{networkDetails:V}=r;B.trigger(ke.ERROR,{type:Ln.NETWORK_ERROR,details:Qt.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:M,reason:M.message,level:r.level||void 0,parent:(m=i.fragments[0])==null?void 0:m.type,networkDetails:V,stats:a});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=a.loading.start);const _=this.hls.mainForwardBufferInfo,T=_?_.end-_.len:0,E=(i.edge-T)*1e3,C=s2e(i,E);if(i.requestScheduled+C0){if(re>i.targetduration*3)this.log(`Playlist last advanced ${Q.toFixed(2)}s ago. Omitting segment and part directives.`),R=void 0,D=void 0;else if(n!=null&&n.tuneInGoal&&re-i.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${se} with playlist age: ${i.age}`),se=0;else{const ue=Math.floor(se/i.targetduration);if(R+=ue,D!==void 0){const _e=Math.round(se%i.targetduration/i.partTarget);D+=_e}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${Q.toFixed(2)}s goal: ${se} skip sn ${ue} to part ${D}`)}i.tuneInGoal=se}if(N=this.getDeliveryDirectives(i,r.deliveryDirectives,R,D),M||!X){i.requestScheduled=c,this.loadingPlaylist(x,N);return}}else(i.canBlockReload||i.canSkipUntil)&&(N=this.getDeliveryDirectives(i,r.deliveryDirectives,R,D));N&&R!==void 0&&i.canBlockReload&&(i.requestScheduled=a.loading.first+Math.max(C-s*2,C/2)),this.scheduleLoading(x,N,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.loadingPlaylist(e,r);return}const s=c-a;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(s)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,r),s)}getDeliveryDirectives(e,r,n,i){let a=Woe(e);return r!=null&&r.skip&&e.deltaUpdateFailed&&(n=r.msn,i=r.part,a=ZR.No),new Koe(n,i,a)}checkRetry(e){const r=e.details,n=SO(e),i=e.errorAction,{action:a,retryCount:c=0,retryConfig:s}=i||{},f=!!i&&!!s&&(a===zl.RetryRequest||!i.resolved&&a===zl.SendAlternateToPenaltyBox);if(f){var m;if(c>=s.maxNumRetry)return!1;if(n&&(m=e.context)!=null&&m.deliveryDirectives)this.warn(`Retrying playlist loading ${c+1}/${s.maxNumRetry} after "${r}" without delivery-directives`),this.loadPlaylist();else{const x=vW(s,c);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),x),this.warn(`Retrying playlist loading ${c+1}/${s.maxNumRetry} after "${r}" in ${x}ms`)}e.levelRetry=!0,i.resolved=!0}return f}}function P2e(t,e){if(t.length!==e.length)return!1;for(let r=0;rt[i]!==e[i])}function tq(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class FLt extends RW{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(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ke.LEVEL_LOADING,this.onLevelLoading,this),e.on(ke.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ke.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(ke.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ke.LEVEL_LOADING,this.onLevelLoading,this),e.off(ke.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ke.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(ke.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 s=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,s)}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(s=>(i==null?void 0:i.indexOf(s))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const s=this.tracks.filter(T=>!n||n.indexOf(T.groupId)!==-1);if(s.length)this.selectDefaultTrack&&!s.some(T=>T.default)&&(this.selectDefaultTrack=!1),s.forEach((T,E)=>{T.id=E});else if(!a&&!this.tracksInGroup.length)return;this.tracksInGroup=s;const f=this.hls.config.audioPreference;if(!a&&f){const T=Hf(f,s,$_);if(T>-1)a=s[T];else{const E=Hf(f,this.tracks);a=this.tracks[E]}}let m=this.findTrackId(a);m===-1&&a&&(m=this.findTrackId(null));const x={audioTracks:s};this.log(`Updating audio tracks, ${s.length} track(s) found in group(s): ${n==null?void 0:n.join(",")}`),this.hls.trigger(ke.AUDIO_TRACKS_UPDATED,x);const _=this.trackId;if(m!==-1&&_===-1)this.setAudioTrack(m);else if(s.length&&_===-1){var c;const T=new Error(`No audio track selected for current audio group-ID(s): ${(c=this.groupIds)==null?void 0:c.join(",")} track count: ${s.length}`);this.warn(T.message),this.hls.trigger(ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:T})}}}onError(e,r){r.fatal||!r.context||r.context.type===Vi.AUDIO_TRACK&&r.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(r.context.groupId)!==-1)&&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)}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&&g0(e,i,$_))return i;const a=Hf(e,this.tracksInGroup,$_);if(a>-1){const c=this.tracksInGroup[a];return this.setAudioTrack(a),c}else if(i){let c=r.loadLevel;c===-1&&(c=r.firstAutoLevel);const s=ZNt(e,r.levels,n,c,$_);if(s===-1)return null;r.nextLoadLevel=s}if(e.channels||e.audioCodec){const c=Hf(e,n);if(c>-1)return n[c]}}}return null}setAudioTrack(e){const r=this.tracksInGroup;if(e<0||e>=r.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,i=r[e],a=i.details&&!i.details.live;if(e===this.trackId&&i===n&&a||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(ke.AUDIO_TRACK_SWITCHING,Bs({},i)),a))return;const c=this.switchParams(i.url,n==null?void 0:n.details,i.details);this.loadPlaylist(c)}findTrackId(e){const r=this.tracksInGroup;for(let n=0;n{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))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("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 Rle=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,N2e="HlsJsTrackRemovedError";class zLt extends Error{constructor(e){super(e),this.name=N2e}}class $Lt extends ah{constructor(e,r){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=n=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&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)&&(a.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(ke.MEDIA_ATTACHED,{media:i,mediaSource:a}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},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.hls=e,this.fragmentTracker=r,this.appendSource=cNt(Qy(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=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}registerListeners(){const{hls:e}=this;e.on(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ke.BUFFER_RESET,this.onBufferReset,this),e.on(ke.BUFFER_APPENDING,this.onBufferAppending,this),e.on(ke.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ke.BUFFER_EOS,this.onBufferEos,this),e.on(ke.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ke.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ke.FRAG_PARSED,this.onFragParsed,this),e.on(ke.FRAG_CHANGED,this.onFragChanged,this),e.on(ke.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ke.BUFFER_RESET,this.onBufferReset,this),e.off(ke.BUFFER_APPENDING,this.onBufferAppending,this),e.off(ke.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ke.BUFFER_EOS,this.onBufferEos,this),e.off(ke.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ke.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ke.FRAG_PARSED,this.onFragParsed,this),e.off(ke.FRAG_CHANGED,this.onFragChanged,this),e.off(ke.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!this.sourceBufferCount&&i&&i.mediaSource===r?Ys(n,i.tracks):this.sourceBuffers.forEach(a=>{const[c]=a;c&&(n[c]=Ys({},this.tracks[c]),this.removeBuffer(c)),a[0]=a[1]=null}),{media:e,mediaSource:r,tracks:n}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}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=Qy(this.appendSource);if(i){const a=!!r.mediaSource;(a||r.overrides)&&(this.transferData=r,this.overrides=r.overrides);const c=this.mediaSource=r.mediaSource||new i;if(this.assignMediaSource(c),a)this._objectUrl=n.src,this.attachTransferred();else{const s=this._objectUrl=self.URL.createObjectURL(c);if(this.appendSource)try{n.removeAttribute("src");const f=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||f&&c instanceof f,Lle(n),ULt(n,s),n.load()}catch{n.src=s}else n.src=s}n.addEventListener("emptied",this._onMediaEmptied)}}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}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("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,s=()=>{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: ${ra(n,(f,m)=>f==="initSegment"?void 0:m)}; transfer tracks: ${ra(i,(f,m)=>f==="initSegment"?void 0:m)}}`),!CEe(i,n)){r.mediaSource=null,r.tracks=void 0;const f=e.currentTime,m=this.details,x=Math.max(f,(m==null?void 0:m.fragments[0].start)||0);if(x-f>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${f} -> ${x}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(n)}") start time: ${x} currentTime: ${f}`),this.onMediaDetaching(ke.MEDIA_DETACHING,{}),this.onMediaAttaching(ke.MEDIA_ATTACHING,r),e.currentTime=x;return}this.transferData=void 0,a.forEach(f=>{const m=f,x=i[m];if(x){const _=x.buffer;if(_){const T=this.fragmentTracker,E=x.id;if(T.hasFragments(E)||T.hasParts(E)){const R=vi.getBuffered(_);T.detectEvictedFragments(m,R,E,null,!0)}const C=d$(m),N=[m,_];this.sourceBuffers[C]=N,_.updating&&this.operationQueue&&this.operationQueue.prependBlocker(m),this.trackSourceBuffer(m,x)}}}),s(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),s()}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(([s])=>{s&&this.removeBuffer(s)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const s=a.readyState==="open";try{const f=a.sourceBuffers;for(let m=f.length;m--;)s&&f[m].abort(),a.removeSourceBuffer(f[m]);s&&a.endOfStream()}catch(f){this.warn(`onMediaDetaching: ${f.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}a.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("sourceended",this._onMediaSourceEnded),a.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.removeEventListener("startstreaming",this._onStartStreaming),a.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),n||(c&&self.URL.revokeObjectURL(c),this.mediaSrc===c?(i.removeAttribute("src"),this.appendSource&&Lle(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(ke.MEDIA_DETACHED,r)}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[d$(e)]=[null,null];const r=this.tracks[e];r&&(r.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new BLt(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),s=!c&&this.sourceBufferCount&&this.media&&a.some(f=>!i[f]);if(c||s){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${a}" SourceBuffers`);return}a.forEach(f=>{var m,x;const _=r[f],{id:T,codec:E,levelCodec:C,container:N,metadata:R,supplemental:D}=_;let M=i[f];const B=(m=this.transferData)==null||(m=m.tracks)==null?void 0:m[f],V=B!=null&&B.buffer?B:M,G=(V==null?void 0:V.pendingCodec)||(V==null?void 0:V.codec),W=V==null?void 0:V.levelCodec;M||(M=i[f]={buffer:void 0,listeners:[],codec:E,supplemental:D,container:N,levelCodec:C,metadata:R,id:T});const X=YR(G,W),Q=X==null?void 0:X.replace(Rle,"$1");let re=YR(E,C);const se=(x=re)==null?void 0:x.replace(Rle,"$1");re&&X&&Q!==se&&(f.slice(0,5)==="audio"&&(re=vO(re,this.appendSource)),this.log(`switching codec ${G} to ${re}`),re!==(M.pendingCodec||M.codec)&&(M.pendingCodec=re),M.container=N,this.appendChangeType(f,N,re))}),(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 s=c.buffer;s!=null&&s.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),s.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,Sn.MAIN))==null?void 0:r.gap)===!0)return;const c={label:"block-audio",execute:()=>{var s;const f=this.tracks.video;(this.lastVideoAppendEnd>i||f!=null&&f.buffer&&vi.isBuffered(f.buffer,i)||((s=this.fragmentTracker.getAppendedFrag(i,Sn.MAIN))==null?void 0:s.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:s=>{this.warn("Error executing block-audio operation",s)}};this.blockedAudioAppend={op:c,frag:e},this.append(c,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:r}=this;e&&r&&(this.blockedAudioAppend=null,r.unblockAudio(e.op))}onBufferAppending(e,r){const{tracks:n}=this,{data:i,type:a,parent:c,frag:s,part:f,chunkMeta:m,offset:x}=r,_=m.buffering[a],{sn:T,cc:E}=s,C=self.performance.now();_.start=C;const N=s.stats.buffering,R=f?f.stats.buffering:null;N.start===0&&(N.start=C),R&&R.start===0&&(R.start=C);const D=n.audio;let M=!1;a==="audio"&&(D==null?void 0:D.container)==="audio/mpeg"&&(M=!this.lastMpegAudioChunk||m.id===1||this.lastMpegAudioChunk.sn!==m.sn,this.lastMpegAudioChunk=m);const B=n.video,V=B==null?void 0:B.buffer;if(V&&T!=="initSegment"){const X=f||s,Q=this.blockedAudioAppend;if(a==="audio"&&c!=="main"&&!this.blockedAudioAppend&&!(B.ending||B.ended)){const se=X.start+X.duration*.05,ue=V.buffered,_e=this.currentOp("video");!ue.length&&!_e?this.blockAudio(X):!_e&&!vi.isBuffered(V,se)&&this.lastVideoAppendEndse||re{var X;_.executeStart=self.performance.now();const Q=(X=this.tracks[a])==null?void 0:X.buffer;Q&&(M?this.updateTimestampOffset(Q,G,.1,a,T,E):x!==void 0&&fn(x)&&this.updateTimestampOffset(Q,x,1e-6,a,T,E)),this.appendExecutor(i,a)},onStart:()=>{},onComplete:()=>{const X=self.performance.now();_.executeEnd=_.end=X,N.first===0&&(N.first=X),R&&R.first===0&&(R.first=X);const Q={};this.sourceBuffers.forEach(([re,se])=>{re&&(Q[re]=vi.getBuffered(se))}),this.appendErrors[a]=0,a==="audio"||a==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(ke.BUFFER_APPENDED,{type:a,frag:s,part:f,chunkMeta:m,parent:s.type,timeRanges:Q})},onError:X=>{var Q;const re={type:Ln.MEDIA_ERROR,parent:s.type,details:Qt.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:s,part:f,chunkMeta:m,error:X,err:X,fatal:!1},se=(Q=this.media)==null?void 0:Q.error;if(X.code===DOMException.QUOTA_EXCEEDED_ERR||X.name=="QuotaExceededError"||"quota"in X)re.details=Qt.BUFFER_FULL_ERROR;else if(X.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!se)re.errorAction=$w(!0);else if(X.name===N2e&&this.sourceBufferCount===0)re.errorAction=$w(!0);else{const ue=++this.appendErrors[a];this.warn(`Failed ${ue}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer (${se||"no media error"})`),(ue>=this.hls.config.appendErrorMaxRetry||se)&&(re.fatal=!0)}this.hls.trigger(ke.ERROR,re)}};this.log(`queuing "${a}" append sn: ${T}${f?" p: "+f.index:""} of ${s.type===Sn.MAIN?"level":"track"} ${s.level} cc: ${E}`),this.append(W,a,this.isPending(this.tracks[a]))}getFlushOp(e,r,n){return this.log(`queuing "${e}" remove ${r}-${n}`),{label:"remove",execute:()=>{this.removeExecutor(e,r,n)},onStart:()=>{},onComplete:()=>{this.hls.trigger(ke.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${r}-${n} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,r){const{type:n,startOffset:i,endOffset:a}=r;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}=r,a=[],c=i?i.elementaryStreams:n.elementaryStreams;c[Js.AUDIOVIDEO]?a.push("audiovideo"):(c[Js.AUDIO]&&a.push("audio"),c[Js.VIDEO]&&a.push("video"));const s=()=>{const f=self.performance.now();n.stats.buffering.end=f,i&&(i.stats.buffering.end=f);const m=i?i.stats:n.stats;this.hls.trigger(ke.FRAG_BUFFERED,{frag:n,part:i,stats:m,id:n.type})};a.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(s,a).catch(f=>{this.warn(`Fragment buffered callback ${f}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,r){this.trimBuffers()}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(([c])=>{if(c){const s=this.tracks[c];(!r.type||r.type===c)&&(s.ending=!0,s.ended||(s.ended=!0,this.log(`${c} buffer reached EOS`)))}});const i=((n=this.overrides)==null?void 0:n.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([c])=>{var s;return c&&!((s=this.tracks[c])!=null&&s.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:c}=this;if(!c||c.readyState!=="open"){c&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${c.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),c.endOfStream(),this.hls.trigger(ke.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(ke.BUFFERED_TO_END,void 0)):r.type==="video"&&this.unblockAudio()}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===Qt.BUFFER_APPEND_ERROR&&r.frag){var n;const i=(n=r.errorAction)==null?void 0:n.nextAutoLevel;fn(i)&&i!==r.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:r,media:n}=this;if(!n||r===null||!this.sourceBufferCount)return;const i=e.config,a=n.currentTime,c=r.levelTargetDuration,s=r.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(fn(s)&&s>=0){const m=Math.max(s,c),x=Math.floor(a/c)*c-m;this.flushBackBuffer(a,c,x)}const f=i.frontBufferFlushThreshold;if(fn(f)&&f>0){const m=Math.max(i.maxBufferLength,f),x=Math.max(m,c),_=Math.floor(a/c)*c+x;this.flushFrontBuffer(a,c,_)}}flushBackBuffer(e,r,n){this.sourceBuffers.forEach(([i,a])=>{if(a){const s=vi.getBuffered(a);if(s.length>0&&n>s.start(0)){var c;this.hls.trigger(ke.BACK_BUFFER_REACHED,{bufferEnd:n});const f=this.tracks[i];if((c=this.details)!=null&&c.live)this.hls.trigger(ke.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(f!=null&&f.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(ke.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:i})}}})}flushFrontBuffer(e,r,n){this.sourceBuffers.forEach(([i,a])=>{if(a){const c=vi.getBuffered(a),s=c.length;if(s<2)return;const f=c.start(s-1),m=c.end(s-1);if(n>f||e>=f&&e<=m)return;this.hls.trigger(ke.BUFFER_FLUSHING,{startOffset:f,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 m=Math.max(0,r.fragmentStart),x=Math.max(m,i);return{duration:1/0,start:m,end:x}}return{duration:1/0}}const a=(e=this.overrides)==null?void 0:e.duration;if(a)return fn(a)?{duration:a}:null;const c=this.media.duration,s=fn(n.duration)?n.duration:0;return i>s&&i>c||!fn(c)?{duration:i}:null}updateMediaSource({duration:e,start:r,end:n}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(fn(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}) ${ra(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(ke.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(ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.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,s=e[c];if(this.isPending(s)){const f=this.getTrackCodec(s,c),m=`${s.container};codecs=${f}`;s.codec=f,this.log(`creating sourceBuffer(${m})${this.currentOp(c)?" Queued":""} ${ra(s)}`);try{const x=n.addSourceBuffer(m),_=d$(c),T=[c,x];r[_]=T,s.buffer=x}catch(x){var i;this.error(`error while trying to add sourceBuffer: ${x.message}`),this.shiftAndExecuteNext(c),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[c],this.hls.trigger(ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:x,sourceBufferName:c,mimeType:m,parent:s.id});return}this.trackSourceBuffer(c,s)}}this.bufferCreated()}getTrackCodec(e,r){const n=e.supplemental;let i=e.codec;n&&(r==="video"||r==="audiovideo")&&aC(n,"video")&&(i=PNt(i,n));const a=YR(i,e.levelCodec);return a?r.slice(0,5)==="audio"?vO(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 s=c.removedRanges;s!=null&&s.length&&this.hls.trigger(ke.BUFFER_FLUSHED,{type:a})})}get mediaSrc(){var e,r;const n=((e=this.media)==null||(r=e.querySelector)==null?void 0:r.call(e,"source"))||this.media;return n==null?void 0:n.src}onSBUpdateStart(e){const r=this.currentOp(e);r&&r.onStart()}onSBUpdateEnd(e){var r;if(((r=this.mediaSource)==null?void 0:r.readyState)==="closed"){this.resetBuffer(e);return}const n=this.currentOp(e);n&&(n.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,r){var n;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(n=this.mediaSource)==null?void 0:n.readyState}`);this.error(`${i}`,r),this.hls.trigger(ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const a=this.currentOp(e);a&&a.onError(i)}updateTimestampOffset(e,r,n,i,a,c){const s=r-e.timestampOffset;Math.abs(s)>=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],s=c==null?void 0:c.buffer;if(!i||!a||!s){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const f=fn(i.duration)?i.duration:1/0,m=fn(a.duration)?a.duration:1/0,x=Math.max(0,r),_=Math.min(n,f,m);_>x&&(!c.ending||c.ended)?(c.ended=!1,this.log(`Removing [${x},${_}] from the ${e} SourceBuffer`),s.remove(x,_)):this.shiftAndExecuteNext(e)}appendExecutor(e,r){const n=this.tracks[r],i=n==null?void 0:n.buffer;if(!i)throw new zLt(`Attempting to append to the ${r} SourceBuffer, but it does not exist`);n.ending=!1,n.ended=!1,i.appendBuffer(e)}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}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,i=r.map(c=>this.appendBlocker(c));return r.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).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||this.shiftAndExecuteNext(r)})}append(e,r,n){this.operationQueue&&this.operationQueue.append(e,r,n)}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.addEventListener(r,c)}removeBufferListeners(e){const r=this.tracks[e];if(!r)return;const n=r.buffer;n&&(r.listeners.forEach(i=>{n.removeEventListener(i.event,i.listener)}),r.listeners.length=0)}}function Lle(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(r=>{t.removeChild(r)})}function ULt(t,e){const r=self.document.createElement("source");r.type="video/mp4",r.src=e,t.appendChild(r)}function d$(t){return t==="audio"?1:0}class LW{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(ke.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ke.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ke.BUFFER_CODECS,this.onBufferCodecs,this),e.on(ke.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(ke.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ke.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ke.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ke.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,r){const n=this.hls.levels[r.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,r){this.media=r.media instanceof HTMLVideoElement?r.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,r){const n=this.hls;this.restrictedLevels=[],this.firstLevel=r.firstLevel,n.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onLevelsUpdated(e,r){this.timer&&fn(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,r){this.hls.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){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}}}getMaxLevel(e){const r=this.hls.levels;if(!r.length)return-1;const n=r.filter((i,a)=>this.isLevelAllowed(i)&&a<=e);return this.clientRect=null,LW.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=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.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}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=(s,f)=>f?s.width!==f.width||s.height!==f.height:!0;let a=e.length-1;const c=Math.max(r,n);for(let s=0;s=c||f.height>=c)&&i(f,e[s+1])){a=s;break}}return a}}const VLt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},fu=VLt,qLt={HLS:"h"},GLt=qLt;class lp{constructor(e,r){Array.isArray(e)&&(e=e.map(n=>n instanceof lp?n:new lp(n))),this.value=e,this.params=r}}const HLt="Dict";function WLt(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 KLt(t,e,r,n){return new Error(`failed to ${t} "${WLt(e)}" as ${r}`,{cause:n})}function cp(t,e,r){return KLt("serialize",t,e,r)}class R2e{constructor(e){this.description=e}}const Dle="Bare Item",YLt="Boolean";function ZLt(t){if(typeof t!="boolean")throw cp(t,YLt);return t?"?1":"?0"}function XLt(t){return btoa(String.fromCharCode(...t))}const QLt="Byte Sequence";function JLt(t){if(ArrayBuffer.isView(t)===!1)throw cp(t,QLt);return`:${XLt(t)}:`}const eDt="Integer";function tDt(t){return t<-999999999999999||99999999999999912)throw cp(t,nDt);const r=e.toString();return r.includes(".")?r:`${r}.0`}const sDt="String",aDt=/[\x00-\x1f\x7f]+/;function oDt(t){if(aDt.test(t))throw cp(t,sDt);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function lDt(t){return t.description||t.toString().slice(7,-1)}const cDt="Token";function Ole(t){const e=lDt(t);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw cp(e,cDt);return e}function rq(t){switch(typeof t){case"number":if(!fn(t))throw cp(t,Dle);return Number.isInteger(t)?L2e(t):iDt(t);case"string":return oDt(t);case"symbol":return Ole(t);case"boolean":return ZLt(t);case"object":if(t instanceof Date)return rDt(t);if(t instanceof Uint8Array)return JLt(t);if(t instanceof R2e)return Ole(t);default:throw cp(t,Dle)}}const uDt="Key";function nq(t){if(/^[a-z*][a-z0-9\-_.*]*$/.test(t)===!1)throw cp(t,uDt);return t}function DW(t){return t==null?"":Object.entries(t).map(([e,r])=>r===!0?`;${nq(e)}`:`;${nq(e)}=${rq(r)}`).join("")}function O2e(t){return t instanceof lp?`${rq(t.value)}${DW(t.params)}`:rq(t)}function dDt(t){return`(${t.value.map(O2e).join(" ")})${DW(t.params)}`}function hDt(t,e={whitespace:!0}){if(typeof t!="object"||t==null)throw cp(t,HLt);const r=t instanceof Map?t.entries():Object.entries(t),n=e!=null&&e.whitespace?" ":"";return Array.from(r).map(([i,a])=>{a instanceof lp||(a=new lp(a));let c=nq(i);return a.value===!0?c+=DW(a.params):(c+="=",Array.isArray(a.value)?c+=dDt(a):c+=O2e(a)),c}).join(`,${n}`)}function M2e(t,e){return hDt(t,e)}const jf="CMCD-Object",lo="CMCD-Request",P_="CMCD-Session",$g="CMCD-Status",fDt={br:jf,ab:jf,d:jf,ot:jf,tb:jf,tpb:jf,lb:jf,tab:jf,lab:jf,url:jf,pb:lo,bl:lo,tbl:lo,dl:lo,ltc:lo,mtp:lo,nor:lo,nrr:lo,rc:lo,sn:lo,sta:lo,su:lo,ttfb:lo,ttfbb:lo,ttlb:lo,cmsdd:lo,cmsds:lo,smrt:lo,df:lo,cs:lo,ts:lo,cid:P_,pr:P_,sf:P_,sid:P_,st:P_,v:P_,msd:P_,bs:$g,bsd:$g,cdn:$g,rtp:$g,bg:$g,pt:$g,ec:$g,e:$g},pDt={REQUEST:lo};function mDt(t){return Object.keys(t).reduce((e,r)=>{var n;return(n=t[r])===null||n===void 0||n.forEach(i=>e[i]=r),e},{})}function gDt(t,e){const r={};if(!t)return r;const n=Object.keys(t),i=e?mDt(e):{};return n.reduce((a,c)=>{var s;const f=fDt[c]||i[c]||pDt.REQUEST,m=(s=a[f])!==null&&s!==void 0?s:a[f]={};return m[c]=t[c],a},r)}function yDt(t){return["ot","sf","st","e","sta"].includes(t)}function xDt(t){return typeof t=="number"?fn(t):t!=null&&t!==""&&t!==!1}const F2e="event";function _Dt(t,e){const r=new URL(t),n=new URL(e);if(r.origin!==n.origin)return t;const i=r.pathname.split("/").slice(1),a=n.pathname.split("/").slice(1,-1);for(;i[0]===a[0];)i.shift(),a.shift();for(;a.length;)a.shift(),i.unshift("..");return i.join("/")+r.search+r.hash}const eL=t=>Math.round(t),iq=(t,e)=>Array.isArray(t)?t.map(r=>iq(r,e)):t instanceof lp&&typeof t.value=="string"?new lp(iq(t.value,e),t.params):(e.baseUrl&&(t=_Dt(t,e.baseUrl)),e.version===1?encodeURIComponent(t):t),tR=t=>eL(t/100)*100,vDt=(t,e)=>{let r=t;return e.version>=2&&(t instanceof lp&&typeof t.value=="string"?r=new lp([t]):typeof t=="string"&&(r=[t])),iq(r,e)},bDt={br:eL,d:eL,bl:tR,dl:tR,mtp:tR,nor:vDt,rtp:tR,tb:eL},B2e="request",z2e="response",OW=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],wDt=["e"],SDt=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function h3(t){return SDt.test(t)}function TDt(t){return OW.includes(t)||wDt.includes(t)||h3(t)}const $2e=["d","dl","nor","ot","rtp","su"];function EDt(t){return OW.includes(t)||$2e.includes(t)||h3(t)}const ADt=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function kDt(t){return OW.includes(t)||$2e.includes(t)||ADt.includes(t)||h3(t)}const CDt=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function jDt(t){return CDt.includes(t)||h3(t)}const IDt={[z2e]:kDt,[F2e]:TDt,[B2e]:EDt};function U2e(t,e={}){const r={};if(t==null||typeof t!="object")return r;const n=e.version||t.v||1,i=e.reportingMode||B2e,a=n===1?jDt:IDt[i];let c=Object.keys(t).filter(a);const s=e.filter;typeof s=="function"&&(c=c.filter(s));const f=i===z2e||i===F2e;f&&!c.includes("ts")&&c.push("ts"),n>1&&!c.includes("v")&&c.push("v");const m=Ys({},bDt,e.formatters),x={version:n,reportingMode:i,baseUrl:e.baseUrl};return c.sort().forEach(_=>{let T=t[_];const E=m[_];if(typeof E=="function"&&(T=E(T,x)),_==="v"){if(n===1)return;T=n}_=="pr"&&T===1||(f&&_==="ts"&&!fn(T)&&(T=Date.now()),xDt(T)&&(yDt(_)&&typeof T=="string"&&(T=new R2e(T)),r[_]=T))}),r}function PDt(t,e={}){const r={};if(!t)return r;const n=U2e(t,e),i=gDt(n,e==null?void 0:e.customHeaderMap);return Object.entries(i).reduce((a,[c,s])=>{const f=M2e(s,{whitespace:!1});return f&&(a[c]=f),a},r)}function NDt(t,e,r){return Ys(t,PDt(e,r))}const RDt="CMCD";function LDt(t,e={}){return t?M2e(U2e(t,e),{whitespace:!1}):""}function DDt(t,e={}){if(!t)return"";const r=LDt(t,e);return encodeURIComponent(r)}function ODt(t,e={}){if(!t)return"";const r=DDt(t,e);return`${RDt}=${r}`}const Mle=/CMCD=[^&#]+/;function MDt(t,e,r){const n=ODt(e,r);if(!n)return t;if(Mle.test(t))return t.replace(Mle,n);const i=t.includes("?")?"&":"?";return`${t}${i}${n}`}class FDt{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:fu.MANIFEST,su:!this.initialized})}catch(a){this.hls.logger.warn("Could not generate manifest CMCD data.",a)}},this.applyFragmentData=i=>{try{const{frag:a,part:c}=i,s=this.hls.levels[a.level],f=this.getObjectType(a),m={d:(c||a).duration*1e3,ot:f};(f===fu.VIDEO||f===fu.AUDIO||f==fu.MUXED)&&(m.br=s.bitrate/1e3,m.tb=this.getTopBandwidth(f)/1e3,m.bl=this.getBufferLength(f));const x=c?this.getNextPart(c):this.getNextFrag(a);x!=null&&x.url&&x.url!==a.url&&(m.nor=x.url),this.apply(i,m)}catch(a){this.hls.logger.warn("Could not generate segment CMCD data.",a)}},this.hls=e;const r=this.config=e.config,{cmcd:n}=r;n!=null&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||e.sessionId,this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ke.MEDIA_DETACHED,this.onMediaDetached,this),e.on(ke.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ke.MEDIA_DETACHED,this.onMediaDetached,this),e.off(ke.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,r){this.media=r.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,r){var n,i;this.audioBuffer=(n=r.tracks.audio)==null?void 0:n.buffer,this.videoBuffer=(i=r.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:GLt.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,r={}){Ys(r,this.createData());const n=r.ot===fu.INIT||r.ot===fu.VIDEO||r.ot===fu.MUXED;this.starved&&n&&(r.bs=!0,r.su=!0,this.starved=!1),r.su==null&&(r.su=this.buffering);const{includeKeys:i}=this;i&&(r=Object.keys(r).reduce((c,s)=>(i.includes(s)&&(c[s]=r[s]),c),{}));const a={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),NDt(e.headers,r,a)):e.url=MDt(e.url,r,a)}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 s=a.length-1;s>=0;s--){const f=a[s];if(f.index===n&&f.fragment.sn===c)return a[s+1]}}}getObjectType(e){const{type:r}=e;if(r==="subtitle")return fu.TIMED_TEXT;if(e.sn==="initSegment")return fu.INIT;if(r==="audio")return fu.AUDIO;if(r==="main")return this.hls.audioTracks.length?fu.VIDEO:fu.MUXED}getTopBandwidth(e){let r=0,n;const i=this.hls;if(e===fu.AUDIO)n=i.audioTracks;else{const a=i.maxAutoLevel,c=a>-1?a+1:i.levels.length;n=i.levels.slice(0,c)}return n.forEach(a=>{a.bitrate>r&&(r=a.bitrate)}),r>0?r:NaN}getBufferLength(e){const r=this.media,n=e===fu.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!r?NaN:vi.bufferInfo(n,r.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,r=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new n(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,c,s){r(a),this.loader.load(a,c,s)}}}createFragmentLoader(){const{fLoader:e}=this.config,r=this.applyFragmentData,n=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new n(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,c,s){r(a),this.loader.load(a,c,s)}}}}const BDt=3e5;class zDt extends ah{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(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ke.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ke.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)===zl.SendAlternateToPenaltyBox&&n.flags===qu.MoveAllAlternatesMatchingHost){const i=this.levels;let a=this._pathwayPriority,c=this.pathwayId;if(r.context){const{groupId:s,pathwayId:f,type:m}=r.context;s&&i?c=this.getPathwayForGroupId(s,m,c):f&&(c=f)}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),r.details===Qt.BUFFER_APPEND_ERROR&&!r.fatal?n.resolved=!0:n.resolved||this.warn(`Could not resolve ${r.details} ("${r.error.message}") with content-steering for Pathway: ${c} levels: ${i&&i.length} priorities: ${ra(a)} penalized: ${ra(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]>BDt&&delete n[a]});for(let a=0;a0){this.log(`Setting Pathway to "${c}"`),this.pathwayId=c,l2e(r),this.hls.trigger(ke.LEVELS_UPDATED,{levels:r});const m=this.hls.levels[s];f&&m&&this.levels&&(m.attrs["STABLE-VARIANT-ID"]!==f.attrs["STABLE-VARIANT-ID"]&&m.bitrate!==f.bitrate&&this.log(`Unstable Pathways change from bitrate ${f.bitrate} to ${m.bitrate}`),this.hls.nextLoadLevel=s);break}}}getPathwayForGroupId(e,r,n){const i=this.getLevelsForPathway(n).concat(this.levels||[]);for(let a=0;a{const{ID:c,"BASE-ID":s,"URI-REPLACEMENT":f}=a;if(r.some(x=>x.pathwayId===c))return;const m=this.getLevelsForPathway(s).map(x=>{const _=new Ka(x.attrs);_["PATHWAY-ID"]=c;const T=_.AUDIO&&`${_.AUDIO}_clone_${c}`,E=_.SUBTITLES&&`${_.SUBTITLES}_clone_${c}`;T&&(n[_.AUDIO]=T,_.AUDIO=T),E&&(i[_.SUBTITLES]=E,_.SUBTITLES=E);const C=V2e(x.uri,_["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",f),N=new lC({attrs:_,audioCodec:x.audioCodec,bitrate:x.bitrate,height:x.height,name:x.name,url:C,videoCodec:x.videoCodec,width:x.width});if(x.audioGroups)for(let R=1;R{this.log(`Loaded steering manifest: "${i}"`);const C=x.data;if((C==null?void 0:C.VERSION)!==1){this.log(`Steering VERSION ${C.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=C.TTL;const{"RELOAD-URI":N,"PATHWAY-CLONES":R,"PATHWAY-PRIORITY":D}=C;if(N)try{this.uri=new self.URL(N,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${N}`);return}this.scheduleRefresh(this.uri||T.url),R&&this.clonePathways(R);const M={steeringManifest:C,url:i.toString()};this.hls.trigger(ke.STEERING_MANIFEST_LOADED,M),D&&this.updatePathwayPriority(D)},onError:(x,_,T,E)=>{if(this.log(`Error loading steering manifest: ${x.code} ${x.text} (${_.url})`),this.stopLoad(),x.code===410){this.enabled=!1,this.log(`Steering manifest ${_.url} no longer available`);return}let C=this.timeToLoad*1e3;if(x.code===429){const N=this.loader;if(typeof(N==null?void 0:N.getResponseHeader)=="function"){const R=N.getResponseHeader("Retry-After");R&&(C=parseFloat(R)*1e3)}this.log(`Steering manifest ${_.url} rate limited`);return}this.scheduleRefresh(this.uri||_.url,C)},onTimeout:(x,_,T)=>{this.log(`Timeout loading steering manifest (${_.url})`),this.scheduleRefresh(this.uri||_.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(a,f,m)}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 Fle(t,e,r,n){t&&Object.keys(e).forEach(i=>{const a=t.filter(c=>c.groupId===i).map(c=>{const s=Ys({},c);return s.details=void 0,s.attrs=new Ka(s.attrs),s.url=s.attrs.URI=V2e(c.url,c.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),s.groupId=s.attrs["GROUP-ID"]=e[i],s.attrs["PATHWAY-ID"]=n,s});t.push(...a)})}function V2e(t,e,r,n){const{HOST:i,PARAMS:a,[r]:c}=n;let s;e&&(s=c==null?void 0:c[e],s&&(t=s));const f=new self.URL(t);return i&&!s&&(f.host=i),a&&Object.keys(a).sort().forEach(m=>{m&&f.searchParams.set(m,a[m])}),f.href}class Vw extends ah{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._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Vw.CDMCleanupPromise?[Vw.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=r=>{const{initDataType:n,initData:i}=r,a=`"${r.type}" event: init data type: "${n}"`;if(this.debug(a),i!==null){if(!this.keyFormatPromise){let c=Object.keys(this.keySystemAccessPromises);c.length||(c=Q2(this.config));const s=c.map(n$).filter(f=>!!f);this.keyFormatPromise=this.getKeyFormatPromise(s)}this.keyFormatPromise.then(c=>{const s=XR(c);if(n!=="sinf"||s!==Xa.FAIRPLAY){this.log(`Ignoring "${r.type}" event with init data type: "${n}" for selected key-system ${s}`);return}let f;try{const E=nl(new Uint8Array(i)),C=TW(JSON.parse(E).sinf),N=MEe(C);if(!N)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");f=new Uint8Array(N.subarray(8,24))}catch(E){this.warn(`${a} Failed to parse sinf: ${E}`);return}const m=Vl(f),{keyIdToKeySessionPromise:x,mediaKeySessions:_}=this;let T=x[m];for(let E=0;E<_.length;E++){const C=_[E],N=C.decryptdata;if(!N.keyId)continue;const R=Vl(N.keyId);if(EO(f,N.keyId)||N.uri.replace(/-/g,"").indexOf(m)!==-1){if(T=x[R],!T)continue;if(N.pssh)break;delete x[R],N.pssh=new Uint8Array(i),N.keyId=f,T=x[m]=T.then(()=>this.generateRequestWithPreferredKeySession(C,n,i,"encrypted-event-key-match")),T.catch(D=>this.handleError(D));break}}T||this.handleError(new Error(`Key ID ${m} not encountered in playlist. Key-system sessions ${_.length}.`))}).catch(c=>this.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=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(ke.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(ke.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(ke.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(ke.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(ke.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(ke.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(ke.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(ke.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(ke.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:r,widevineLicenseUrl:n}=this.config,i=r==null?void 0:r[e];if(i)return i.licenseUrl;if(e===Xa.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(e){const r=this.getLicenseServerUrl(e);if(r===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return r}getServerCertificateUrl(e){const{drmSystems:r}=this.config,n=r==null?void 0:r[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const r=this.hls.levels,n=(c,s,f)=>!!c&&f.indexOf(c)===s,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,s)=>{const f=m=>{const x=m.shift();this.getMediaKeysPromise(x,i,a).then(_=>c({keySystem:x,mediaKeys:_})).catch(_=>{m.length?f(m):_ instanceof Uu?s(_):s(new Uu({type:Ln.KEY_SYSTEM_ERROR,details:Qt.KEY_SYSTEM_NO_ACCESS,error:_,fatal:!0},_.message))})};f(e)})}requestMediaKeySystemAccess(e,r){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${n}`;return e2e===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=vRt(e,r,n,this.config.drmSystemOptions||{});let c=this.keySystemAccessPromises[e],s=(i=c)==null?void 0:i.keySystemAccess;if(!s){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ra(a)}`),s=this.requestMediaKeySystemAccess(e,a);const f=c=this.keySystemAccessPromises[e]={keySystemAccess:s};return s.catch(m=>{this.log(`Failed to obtain access to key-system "${e}": ${m}`)}),s.then(m=>{this.log(`Access for key-system "${m.keySystem}" obtained`);const x=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const _=f.mediaKeys=m.createMediaKeys().then(T=>(this.log(`Media-keys created for "${e}"`),f.hasMediaKeys=!0,x.then(E=>E?this.setMediaKeysServerCertificate(T,e,E):T)));return _.catch(T=>{this.error(`Failed to create media-keys for "${e}"}: ${T}`)}),_})}return s.then(()=>c.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:r,mediaKeys:n}){this.log(`Creating key-system session "${r}" keyId: ${Vl(e.keyId||[])} keyUri: ${e.uri}`);const i=n.createSession(),a={decryptdata:e,keySystem:r,mediaKeys:n,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a}renewKeySession(e){const r=e.decryptdata;if(r.pssh){const n=this.createMediaKeySessionContext(e),i=rR(r),a="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(n,a,r.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,r){const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${Vl(e.decryptdata.keyId||[])} } (data length: ${r.byteLength})`),n.update(r)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>n$(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:r,mediaKeys:n})=>this.attemptSetMediaKeys(r,n))}selectKeySystem(e){return new Promise((r,n)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const a=n$(i);a?r(a):n(new Error(`Unable to find format for key-system "${i}"`))}).catch(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=Q2(this.config),n=e.map(XR).filter(i=>!!i&&r.indexOf(i)!==-1);return this.selectKeySystem(n)}getKeyStatus(e){const{mediaKeySessions:r}=this;for(let n=0;n(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${a}`),this.attemptSetMediaKeys(f,m).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:f,mediaKeys:m,decryptdata:r}))))).then(f=>{const m="cenc",x=r.pssh?r.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(f,m,x,"playlist-key")});return s.catch(f=>this.handleError(f,e.frag)),this.keyIdToKeySessionPromise[n]=s,s}return c.catch(s=>{if(s instanceof Uu){const f=Bs({},s.data);this.getKeyStatus(r)==="internal-error"&&(f.decryptdata=r);const m=new Uu(f,s.message);this.handleError(m,e.frag)}}),c}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,r){if(this.hls)if(e instanceof Uu){r&&(e.data.frag=r);const n=e.data.decryptdata;this.error(`${e.message}${n?` (${Vl(n.keyId||[])})`:""}`),this.hls.trigger(ke.ERROR,e.data)}else this.error(e.message),this.hls.trigger(ke.ERROR,{type:Ln.KEY_SYSTEM_ERROR,details:Qt.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const r=rR(e),n=this.keyIdToKeySessionPromise[r];if(!n){const i=XR(e.keyFormat),a=i?[i]:Q2(this.config);return this.attemptKeySystemAccess(a)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=Q2(this.config)),e.length===0)throw new Uu({type:Ln.KEY_SYSTEM_ERROR,details:Qt.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ra({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,r){if(this.mediaResolved=void 0,this.mediaKeys===r)return Promise.resolve();const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(n).then(()=>this.media?this.media.setMediaKeys(r):new Promise((a,c)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return c(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=r,this.media.setMediaKeys(r).then(a).catch(c)}}));return this.mediaKeys=r,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),n.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(a=>n.indexOf(a)===-1)})}generateRequestWithPreferredKeySession(e,r,n,i){var a;const c=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(c)try{const C=c.call(this.hls,r,n,e);if(!C)throw new Error("Invalid response from configured generateRequest filter");r=C.initDataType,n=C.initData?C.initData:null,e.decryptdata.pssh=n?new Uint8Array(n):null}catch(C){if(this.warn(C.message),this.hls&&this.hls.config.debug)throw C}if(n===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const s=rR(e.decryptdata),f=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${s} URI: ${f} (init data type: ${r} length: ${n.byteLength})`);const m=new AW,x=e._onmessage=C=>{const N=e.mediaKeysSession;if(!N){m.emit("error",new Error("invalid state"));return}const{messageType:R,message:D}=C;this.log(`"${R}" message event for session "${N.sessionId}" message size: ${D.byteLength}`),R==="license-request"||R==="license-renewal"?this.renewLicense(e,D).catch(M=>{m.eventNames().length?m.emit("error",M):this.handleError(M)}):R==="license-release"?e.keySystem===Xa.FAIRPLAY&&this.updateKeySession(e,Z8("acknowledged")).then(()=>this.removeSession(e)).catch(M=>this.handleError(M)):this.warn(`unhandled media key message type "${R}"`)},_=(C,N)=>{N.keyStatus=C;let R;C.startsWith("usable")?m.emit("resolved"):C==="internal-error"||C==="output-restricted"||C==="output-downscaled"?R=Ble(C,N.decryptdata):C==="expired"?R=new Error(`key expired (keyId: ${s})`):C==="released"?R=new Error("key released"):C==="status-pending"||this.warn(`unhandled key status change "${C}" (keyId: ${s})`),R&&(m.eventNames().length?m.emit("error",R):this.handleError(R))},T=e._onkeystatuseschange=C=>{if(!e.mediaKeysSession){m.emit("error",new Error("invalid state"));return}const R=this.getKeyStatuses(e);if(!Object.keys(R).some(V=>R[V]!=="status-pending"))return;if(R[s]==="expired"){this.log(`Expired key ${ra(R)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let M=R[s];if(M)_(M,e);else{var B;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(B=e.keyStatusTimeouts)[s]||(B[s]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const G=this.getKeyStatus(e.decryptdata);if(G&&G!=="status-pending")return this.log(`No status for keyId ${s} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${G} from other session.`),_(G,e);this.log(`key status for ${s} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),M="internal-error",_(M,e)},1e3)),this.log(`No status for keyId ${s} (${ra(R)}).`)}};Kc(e.mediaKeysSession,"message",x),Kc(e.mediaKeysSession,"keystatuseschange",T);const E=new Promise((C,N)=>{m.on("error",N),m.on("resolved",C)});return e.mediaKeysSession.generateRequest(r,n).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${s} URI: ${f}`)}).catch(C=>{throw new Uu({type:Ln.KEY_SYSTEM_ERROR,details:Qt.KEY_SYSTEM_NO_SESSION,error:C,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${C}`)}).then(()=>E).catch(C=>(m.removeAllListeners(),this.removeSession(e).then(()=>{throw C}))).then(()=>(m.removeAllListeners(),e))}getKeyStatuses(e){const r={};return e.mediaKeysSession.keyStatuses.forEach((n,i)=>{if(typeof i=="string"&&typeof n=="object"){const s=i;i=n,n=s}const a="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===Xa.PLAYREADY&&a.length===16){const s=Vl(a);r[s]=n,QEe(a)}const c=Vl(a);n==="internal-error"&&(this.bannedKeyIds[c]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${c} key-session "${e.mediaKeysSession.sessionId}"`),r[c]=n}),r}fetchServerCertificate(e){const r=this.config,n=r.loader,i=new n(r),a=this.getServerCertificateUrl(e);return a?(this.log(`Fetching server certificate for "${e}"`),new Promise((c,s)=>{const f={responseType:"arraybuffer",url:a},m=r.certLoadPolicy.default,x={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},_={onSuccess:(T,E,C,N)=>{c(T.data)},onError:(T,E,C,N)=>{s(new Uu({type:Ln.KEY_SYSTEM_ERROR,details:Qt.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:C,response:Bs({url:f.url,data:void 0},T)},`"${e}" certificate request failed (${a}). Status: ${T.code} (${T.text})`))},onTimeout:(T,E,C)=>{s(new Uu({type:Ln.KEY_SYSTEM_ERROR,details:Qt.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:C,response:{url:f.url,data:void 0}},`"${e}" certificate request timed out (${a})`))},onAbort:(T,E,C)=>{s(new Error("aborted"))}};i.load(f,x,_)})):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 Uu({type:Ln.KEY_SYSTEM_ERROR,details:Qt.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:c,fatal:!0},c.message))})})}renewLicense(e,r){return this.requestLicense(e,new Uint8Array(r)).then(n=>this.updateKeySession(e,new Uint8Array(n)).catch(i=>{throw new Uu({type:Ln.KEY_SYSTEM_ERROR,details:Qt.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,r){const n=String.fromCharCode.apply(null,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 x;for(let _=0,T=a.length;_ in key message");return Z8(atob(m))}setupLicenseXHR(e,r,n,i){const a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return a.call(this.hls,e,r,n,i)}).catch(c=>{if(!n.decryptdata)throw c;return e.open("POST",r,!0),a.call(this.hls,e,r,n,i)}).then(c=>(e.readyState||e.open("POST",r,!0),{xhr:e,licenseChallenge:c||i})):(e.open("POST",r,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,r){const n=this.config.keyLoadPolicy.default;return new Promise((i,a)=>{const c=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${c}`);const s=new XMLHttpRequest;s.responseType="arraybuffer",s.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(s.readyState===4)if(s.status===200){this._requestLicenseFailureCount=0;let f=s.response;this.log(`License received ${f instanceof ArrayBuffer?f.byteLength:f}`);const m=this.config.licenseResponseCallback;if(m)try{f=m.call(this.hls,s,c,e)}catch(x){this.error(x)}i(f)}else{const f=n.errorRetry,m=f?f.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>m||s.status>=400&&s.status<500)a(new Uu({type:Ln.KEY_SYSTEM_ERROR,details:Qt.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:s,response:{url:c,data:void 0,code:s.status,text:s.statusText}},`License Request XHR failed (${c}). Status: ${s.status} (${s.statusText})`));else{const x=m-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${x} attempts left`),this.requestLicense(e,r).then(i,a)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=s,this.setupLicenseXHR(s,c,e,r).then(({xhr:f,licenseChallenge:m})=>{e.keySystem==Xa.PLAYREADY&&(m=this.unpackPlayReadyKeyMessage(f,m)),f.send(m)}).catch(a)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,Kc(n,"encrypted",this.onMediaEncrypted),Kc(n,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=n.mediaKeys}onMediaDetached(){const e=this.media;e&&(Su(e,"encrypted",this.onMediaEncrypted),Su(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const r=this.mediaResolved;if(r&&r(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const n=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Dy.clearKeyUriToKeyIdMap();const a=i.length;Vw.CDMCleanupPromise=Promise.all(i.map(c=>this.removeSession(c)).concat((n==null||(e=n.setMediaKeys(null))==null?void 0:e.catch(c=>{this.log(`Could not clear media keys: ${c}`),this.hls&&this.hls.trigger(ke.ERROR,{type:Ln.OTHER_ERROR,details:Qt.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${c}`)})}))||Promise.resolve())).catch(c=>{this.log(`Could not close sessions and clear media keys: ${c}`),this.hls&&this.hls.trigger(ke.ERROR,{type:Ln.OTHER_ERROR,details:Qt.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${c}`)})}).then(()=>{a&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}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)}}removeSession(e){const{mediaKeysSession:r,licenseXhr:n,decryptdata:i}=e;if(r){this.log(`Remove licenses and keys and close session "${r.sessionId}" keyId: ${Vl((i==null?void 0:i.keyId)||[])}`),e._onmessage&&(r.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const a=this.mediaKeySessions.indexOf(e);a>-1&&this.mediaKeySessions.splice(a,1);const{keyStatusTimeouts:c}=e;c&&Object.keys(c).forEach(m=>self.clearTimeout(c[m]));const{drmSystemOptions:s}=this.config;return(wRt(s)?new Promise((m,x)=>{self.setTimeout(()=>x(new Error("MediaKeySession.remove() timeout")),8e3),r.remove().then(m).catch(x)}):Promise.resolve()).catch(m=>{this.log(`Could not remove session: ${m}`),this.hls&&this.hls.trigger(ke.ERROR,{type:Ln.OTHER_ERROR,details:Qt.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${m}`)})}).then(()=>r.close()).catch(m=>{this.log(`Could not close session: ${m}`),this.hls&&this.hls.trigger(ke.ERROR,{type:Ln.OTHER_ERROR,details:Qt.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${m}`)})})}return Promise.resolve()}}Vw.CDMCleanupPromise=void 0;function rR(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(t.keyId===null)throw new Error("keyId is null");return Vl(t.keyId)}function $Dt(t,e){if(t.keyId&&e.mediaKeysSession.keyStatuses.has(t.keyId))return e.mediaKeysSession.keyStatuses.get(t.keyId);if(t.matches(e.decryptdata))return e.keyStatus}class Uu 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}}function Ble(t,e){const r=t==="output-restricted",n=r?Qt.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Qt.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Uu({type:Ln.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:e},r?"HDCP level output restricted":`key status changed to "${t}"`)}class UDt{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(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(ke.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(ke.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,s=r-this.lastDecodedFrames,f=1e3*c/a,m=this.hls;if(m.trigger(ke.FPS_DROP,{currentDropped:c,currentDecoded:s,totalDroppedFrames:n}),f>0&&c>m.config.fpsDroppedMonitoringThreshold*s){let x=m.currentLevel;m.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+x),x>0&&(m.autoLevelCapping===-1||m.autoLevelCapping>=x)&&(x=x-1,m.trigger(ke.FPS_DROP_LEVEL_CAPPING,{level:x,droppedLevel:m.currentLevel}),m.autoLevelCapping=x,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)}}function q2e(t,e){let r;try{r=new Event("addtrack")}catch{r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function G2e(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){$s.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){$s.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}r==="disabled"&&(t.mode=r)}function ww(t,e){const r=t.mode;if(r==="disabled"&&(t.mode="hidden"),t.cues)for(let n=t.cues.length;n--;)e&&t.cues[n].removeEventListener("enter",e),t.removeCue(t.cues[n]);r==="disabled"&&(t.mode=r)}function sq(t,e,r,n){const i=t.mode;if(i==="disabled"&&(t.mode="hidden"),t.cues&&t.cues.length>0){const a=qDt(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&&s.endTime<=r)n.push(s);else if(s.startTime>r)return n}return n}function tL(t){const e=[];for(let r=0;rthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let r=null;const n=tL(this.media.textTracks);for(let a=0;a-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ke.LEVEL_LOADING,this.onLevelLoading,this),e.on(ke.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(ke.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ke.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ke.LEVEL_LOADING,this.onLevelLoading,this),e.off(ke.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(ke.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ke.ERROR,this.onError,this)}onMediaAttached(e,r){this.media=r.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.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;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;tL(n.textTracks).forEach(c=>{ww(c)})}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 s=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,s)}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,this.trackId=-1,this.currentTrack=null;const c=this.tracks.filter(x=>!n||n.indexOf(x.groupId)!==-1);if(c.length)this.selectDefaultTrack&&!c.some(x=>x.default)&&(this.selectDefaultTrack=!1),c.forEach((x,_)=>{x.id=_});else if(!a&&!this.tracksInGroup.length)return;this.tracksInGroup=c;const s=this.hls.config.subtitlePreference;if(!a&&s){this.selectDefaultTrack=!1;const x=Hf(s,c);if(x>-1)a=c[x];else{const _=Hf(s,this.tracks);a=this.tracks[_]}}let f=this.findTrackId(a);f===-1&&a&&(f=this.findTrackId(null));const m={subtitleTracks:c};this.log(`Updating subtitle tracks, ${c.length} track(s) found in "${n==null?void 0:n.join(",")}" group-id`),this.hls.trigger(ke.SUBTITLE_TRACKS_UPDATED,m),f!==-1&&this.trackId===-1&&this.setSubtitleTrack(f)}}findTrackId(e){const r=this.tracksInGroup,n=this.selectDefaultTrack;for(let i=0;i-1){const a=this.tracksInGroup[i];return this.setSubtitleTrack(i),a}else{if(n)return null;{const a=Hf(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,s=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:""}${s&&c.live?" age "+s.toFixed(1)+(c.type&&" "+c.type||""):""} ${a}`),this.hls.trigger(ke.SUBTITLE_TRACK_LOADING,{url:a,id:n,groupId:i,deliveryDirectives:r||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const r=tL(e.textTracks),n=this.currentTrack;let i;if(n&&(i=r.filter(a=>tq(n,a))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(r).forEach(a=>{a.mode!=="disabled"&&a!==i&&(a.mode="disabled")}),i){const a=this.subtitleDisplay?"showing":"hidden";i.mode!==a&&(i.mode=a)}}setSubtitleTrack(e){const r=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=r.length||!fn(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const n=this.currentTrack,i=r[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(ke.SUBTITLE_TRACK_SWITCH,{id:e});return}const a=!!i.details&&!i.details.live;if(e===this.trackId&&i===n&&a)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:c,groupId:s="",name:f,type:m,url:x}=i;this.hls.trigger(ke.SUBTITLE_TRACK_SWITCH,{id:c,groupId:s,name:f,type:m,url:x});const _=this.switchParams(i.url,n==null?void 0:n.details,i.details);this.loadPlaylist(_)}}function HDt(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),r=e.toString();return URL.revokeObjectURL(e),r.slice(r.lastIndexOf("/")+1)}catch{let r=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const a=(r+Math.random()*16)%16|0;return r=Math.floor(r/16),(i=="x"?a:a&3|8).toString(16)})}}}function NA(t){let e=5381,r=t.length;for(;r;)e=e*33^t.charCodeAt(--r);return(e>>>0).toString()}const qw=.025;let jO=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function WDt(t,e,r){return`${t.identifier}-${r+1}-${NA(e)}`}class KDt{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 h$(e,r)}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=h$(r,e);return r-n<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,r=fn(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 h$(e,r)}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 YDt(this)}}function h$(t,e){return t-e.start":t.cue.post?"":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`}function Jb(t){const e=t.timelineStart,r=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+r).toFixed(2)}]`}class ZDt{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(ke.PLAYOUT_LIMIT_REACHED,{})};const a=this.hls=new e(r);this.interstitial=n,this.assetItem=i;const c=()=>{this.hasDetails=!0};a.once(ke.LEVEL_LOADED,c),a.once(ke.AUDIO_TRACK_LOADED,c),a.once(ke.SUBTITLE_TRACK_LOADED,c),a.on(ke.MEDIA_ATTACHING,(s,{media:f})=>{this.removeMediaListeners(),this.mediaAttached=f,this.interstitial.playoutLimit&&(f.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&a.on(ke.BUFFER_APPENDED,()=>{const x=this.bufferedEnd;this.reachedPlayout(x)&&(this._bufferedEosTime=x,a.trigger(ke.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=H2e(r,e.config.primarySessionId||"").href}catch{}e.loadSource(r)}}bufferedInPlaceToEnd(e){var r;if(!this.appendInPlace)return!1;if((r=this.hls)!=null&&r.bufferedToEnd)return!0;if(!e)return!1;const n=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,a=vi.bufferInfo(e,i,0);return this.getAssetTime(a.end)>=n-.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=vi.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: ${Jb(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const zle=.033;class XDt extends ah{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;ia.start&&e1)for(let a=0;as&&(r!s.includes(m.identifier)):[];c.length&&c.sort((m,x)=>{const _=m.cue.pre,T=m.cue.post,E=x.cue.pre,C=x.cue.post;if(_&&!E)return-1;if(E&&!_||T&&!C)return 1;if(C&&!T)return-1;if(!_&&!E&&!T&&!C){const N=m.startTime,R=x.startTime;if(N!==R)return N-R}return m.dateRange.tagOrder-x.dateRange.tagOrder}),this.events=c,f.forEach(m=>{this.removeEvent(m)}),this.updateSchedule(e,f)}updateSchedule(e,r=[],n=!1){const i=this.events||[];if(i.length||r.length||this.length<2){const a=this.items,c=this.parseSchedule(i,e);(n||r.length||(a==null?void 0:a.length)!==c.length||c.some((f,m)=>Math.abs(f.playout.start-a[m].playout.start)>.005||Math.abs(f.playout.end-a[m].playout.end)>.005))&&(this.items=c,this.onScheduleUpdate(r,a))}}parseDateRanges(e,r,n){const i=[],a=Object.keys(e);for(let c=0;c!f.error&&!(f.cue.once&&f.hasPlayed)),e.length){this.resolveOffsets(e,r);let f=0,m=0;if(e.forEach((x,_)=>{const T=x.cue.pre,E=x.cue.post,C=e[_-1]||null,N=x.appendInPlace,R=E?a:x.startOffset,D=x.duration,M=x.timelineOccupancy===jO.Range?D:0,B=x.resumptionOffset,V=(C==null?void 0:C.startTime)===R,G=R+x.cumulativeDuration;let W=N?G+D:R+B;if(T||!E&&R<=0){const Q=m;m+=M,x.timelineStart=G;const re=c;c+=D,n.push({event:x,start:G,end:W,playout:{start:re,end:c},integrated:{start:Q,end:m}})}else if(R<=a){if(!V){const se=R-f;if(se>zle){const ue=f,_e=m;m+=se;const Se=c;c+=se;const ve={previousEvent:e[_-1]||null,nextEvent:x,start:ue,end:ue+se,playout:{start:Se,end:c},integrated:{start:_e,end:m}};n.push(ve)}else se>0&&C&&(C.cumulativeDuration+=se,n[n.length-1].end=R)}E&&(W=G),x.timelineStart=G;const Q=m;m+=M;const re=c;c+=D,n.push({event:x,start:G,end:W,playout:{start:re,end:c},integrated:{start:Q,end:m}})}else return;const X=x.resumeTime;E||X>a?f=a:f=X}),f{const m=s.cue.pre,x=s.cue.post,_=m?0:x?i:s.startTime;this.updateAssetDurations(s),c===_?s.cumulativeDuration=a:(a=0,c=_),!x&&s.snapOptions.in&&(s.resumeAnchor=D0(null,n.fragments,s.startOffset+s.resumptionOffset,0,0)||void 0),s.appendInPlace&&!s.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(s,r)||(s.appendInPlace=!1)),!s.appendInPlace&&f+1qw?(this.log(`"${e.identifier}" resumption ${n} not aligned with estimated timeline end ${i}`),!1):!Object.keys(r).some(c=>{const s=r[c].details,f=s.edge;if(n>=f)return this.log(`"${e.identifier}" resumption ${n} past ${c} playlist end ${f}`),!1;const m=D0(null,s.fragments,n);if(!m)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${c} playlist (${s.fragStart}-${s.fragmentEnd})`),!0;const x=c==="audio"?.175:0;return Math.abs(m.start-n){const R=T.data,D=R==null?void 0:R.ASSETS;if(!Array.isArray(D)){const M=this.assignAssetListError(e,Qt.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),C.url,E,N);this.hls.trigger(ke.ERROR,M);return}e.assetListResponse=R,this.hls.trigger(ke.ASSET_LIST_LOADED,{event:e,assetListResponse:R,networkDetails:N})},onError:(T,E,C,N)=>{const R=this.assignAssetListError(e,Qt.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${T.code} ${T.text} (${E.url})`),E.url,N,C);this.hls.trigger(ke.ERROR,R)},onTimeout:(T,E,C)=>{const N=this.assignAssetListError(e,Qt.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${E.url})`),E.url,T,C);this.hls.trigger(ke.ERROR,N)}};return s.load(f,x,_),this.hls.trigger(ke.ASSET_LIST_LOADING,{event:e}),s}assignAssetListError(e,r,n,i,a,c){return e.error=n,{type:Ln.NETWORK_ERROR,details:r,fatal:!1,interstitial:e,url:i,error:n,networkDetails:c,stats:a}}}function $le(t){var e;t==null||(e=t.play())==null||e.catch(()=>{})}function Kb(t,e){return`[${t}] Advancing timeline position to ${e}`}class JDt extends ah{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.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 s=this.playingItem;if(!s){this.checkBuffer();return}if(c&&this.schedule.resetErrorsInRange(n,n-i)&&this.updateSchedule(!0),this.checkBuffer(),c&&n=s.end){var f;const E=this.findItemIndex(s);let C=this.schedule.findItemIndexAtTime(n);if(C===-1&&(C=E+(c?-1:1),this.log(`seeked ${c?"back ":""}to position not covered by schedule ${n} (resolving from ${E} to ${C})`)),!this.isInterstitial(s)&&(f=this.media)!=null&&f.paused&&(this.shouldPlay=!1),!c&&C>E){const N=this.schedule.findJumpRestrictedIndex(E+1,C);if(N>E){this.setSchedulePosition(N);return}}this.setSchedulePosition(C);return}const m=this.playingAsset;if(!m){if(this.playingLastItem&&this.isInterstitial(s)){const E=s.event.assetList[0];E&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(n,E))}return}const x=m.timelineStart,_=m.duration||0;if(c&&n=x+_){var T;(T=s.event)!=null&&T.appendInPlace&&(this.clearAssetPlayers(s.event,s),this.flushFrontBuffer(n)),this.setScheduleToAssetAtTime(n,m)}},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 s=this.findItemIndex(i);this.setSchedulePosition(s+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,s=a.events||[],f=a.items||[],m=a.durations,x=n.map(N=>N.identifier),_=!!(s.length||x.length);(_||i)&&this.log(`INTERSTITIALS_UPDATED (${s.length}): ${s} Schedule: ${f.map(N=>Ch(N))} pos: ${this.timelinePos}`),x.length&&this.log(`Removed events ${x}`);let T=null,E=null;c&&(T=this.updateItem(c,this.timelinePos),this.itemsMatch(c,T)?this.playingItem=T:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const C=this.bufferingItem;if(C&&(E=this.updateItem(C,this.bufferedPos),this.itemsMatch(C,E)?this.bufferingItem=E:C.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(C.event,null))),n.forEach(N=>{N.assetList.forEach(R=>{this.clearAssetPlayer(R.identifier,null)})}),this.playerQueue.forEach(N=>{if(N.interstitial.appendInPlace){const R=N.assetItem.timelineStart,D=N.timelineOffset-R;if(D)try{N.timelineOffset=R}catch(M){Math.abs(D)>qw&&this.warn(`${M} ("${N.assetId}" ${N.timelineOffset}->${R})`)}}}),_||i){if(this.hls.trigger(ke.INTERSTITIALS_UPDATED,{events:s.slice(0),schedule:f.slice(0),durations:m,removedIds:x}),this.isInterstitial(c)&&x.includes(c.event.identifier)){this.warn(`Interstitial "${c.event.identifier}" removed while playing`),this.primaryFallback(c.event);return}c&&this.trimInPlace(T,c),C&&E!==T&&this.trimInPlace(E,C),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=r,this.assetListLoader=new QDt(e),this.schedule=new XDt(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ke.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ke.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(ke.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ke.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(ke.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(ke.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(ke.BUFFER_APPENDED,this.onBufferAppended,this),e.on(ke.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ke.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(ke.MEDIA_ENDED,this.onMediaEnded,this),e.on(ke.ERROR,this.onError,this),e.on(ke.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ke.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ke.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(ke.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ke.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(ke.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(ke.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(ke.BUFFER_CODECS,this.onBufferCodecs,this),e.off(ke.BUFFER_APPENDED,this.onBufferAppended,this),e.off(ke.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ke.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(ke.MEDIA_ENDED,this.onMediaEnded,this),e.off(ke.ERROR,this.onError,this),e.off(ke.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=this.log=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){Su(e,"play",this.onPlay),Su(e,"pause",this.onPause),Su(e,"seeking",this.onSeeking),Su(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,r){const n=this.media=r.media;Kc(n,"seeking",this.onSeeking),Kc(n,"timeupdate",this.onTimeupdate),Kc(n,"play",this.onPlay),Kc(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=_=>_&&e.getAssetPlayer(_.identifier),i=(_,T,E,C,N)=>{if(_){let R=_[T].start;const D=_.event;if(D){if(T==="playout"||D.timelineOccupancy!==jO.Point){const M=n(E);(M==null?void 0:M.interstitial)===D&&(R+=M.assetItem.startOffset+M[N])}}else{const M=C==="bufferedPos"?c():e[C];R+=M-_.start}return R}return 0},a=(_,T)=>{var E;if(_!==0&&T!=="primary"&&(E=e.schedule)!=null&&E.length){var C;const N=e.schedule.findItemIndexAtTime(_),R=(C=e.schedule.items)==null?void 0:C[N];if(R){const D=R[T].start-R.start;return _+D}}return _},c=()=>{const _=e.bufferedPos;return _===Number.MAX_VALUE?s("primary"):Math.max(_,0)},s=_=>{var T,E;return(T=e.primaryDetails)!=null&&T.live?e.primaryDetails.edge:((E=e.schedule)==null?void 0:E.durations[_])||0},f=(_,T)=>{var E,C;const N=e.effectivePlayingItem;if(N!=null&&(E=N.event)!=null&&E.restrictions.skip||!e.schedule)return;e.log(`seek to ${_} "${T}"`);const R=e.effectivePlayingItem,D=e.schedule.findItemIndexAtTime(_,T),M=(C=e.schedule.items)==null?void 0:C[D],B=e.getBufferingPlayer(),V=B==null?void 0:B.interstitial,G=V==null?void 0:V.appendInPlace,W=R&&e.itemsMatch(R,M);if(R&&(G||W)){const X=n(e.playingAsset),Q=(X==null?void 0:X.media)||e.primaryMedia;if(Q){const re=T==="primary"?Q.currentTime:i(R,T,e.playingAsset,"timelinePos","currentTime"),se=_-re,ue=(G?re:Q.currentTime)+se;if(ue>=0&&(!X||G||ue<=X.duration)){Q.currentTime=ue;return}}}if(M){let X=_;if(T!=="primary"){const re=M[T].start,se=_-re;X=M.start+se}const Q=!e.isInterstitial(M);if((!e.isInterstitial(R)||R.event.appendInPlace)&&(Q||M.event.appendInPlace)){const re=e.media||(G?B==null?void 0:B.media:null);re&&(re.currentTime=X)}else if(R){const re=e.findItemIndex(R);if(D>re){const ue=e.schedule.findJumpRestrictedIndex(re+1,D);if(ue>re){e.setSchedulePosition(ue);return}}let se=0;if(Q)e.timelinePos=X,e.checkBuffer();else{const ue=M.event.assetList,_e=_-(M[T]||M).start;for(let Se=ue.length;Se--;){const ve=ue[Se];if(ve.duration&&_e>=ve.startOffset&&_e{const _=e.effectivePlayingItem;if(e.isInterstitial(_))return _;const T=r();return e.isInterstitial(T)?T:null},x={get bufferedEnd(){const _=r(),T=e.bufferingItem;if(T&&T===_){var E;return i(T,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-T.playout.start||((E=e.bufferingAsset)==null?void 0:E.startOffset)||0}return 0},get currentTime(){const _=m(),T=e.effectivePlayingItem;return T&&T===_?i(T,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-T.playout.start:0},set currentTime(_){const T=m(),E=e.effectivePlayingItem;E&&E===T&&f(_+E.playout.start,"playout")},get duration(){const _=m();return _?_.playout.end-_.playout.start:0},get assetPlayers(){var _;const T=(_=m())==null?void 0:_.event.assetList;return T?T.map(E=>e.getAssetPlayer(E.identifier)):[]},get playingIndex(){var _;const T=(_=m())==null?void 0:_.event;return T&&e.effectivePlayingAsset?T.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return m()}};return this.manager={get events(){var _;return((_=e.schedule)==null||(_=_.events)==null?void 0:_.slice(0))||[]},get schedule(){var _;return((_=e.schedule)==null||(_=_.items)==null?void 0:_.slice(0))||[]},get interstitialPlayer(){return m()?x:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return r()},get bufferingIndex(){const _=r();return e.findItemIndex(_)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const _=e.effectivePlayingItem;return e.findItemIndex(_)},primary:{get bufferedEnd(){return c()},get currentTime(){const _=e.timelinePos;return _>0?_:0},set currentTime(_){f(_,"primary")},get duration(){return s("primary")},get seekableStart(){var _;return((_=e.primaryDetails)==null?void 0:_.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(r(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(_){f(_,"integrated")},get duration(){return s("integrated")},get seekableStart(){var _;return a(((_=e.primaryDetails)==null?void 0:_.fragmentStart)||0,"integrated")}},skip:()=>{const _=e.effectivePlayingItem,T=_==null?void 0:_.event;if(T&&!T.restrictions.skip){const E=e.findItemIndex(_);if(T.appendInPlace){const C=_.playout.start+_.event.duration;f(C+.001,"playout")}else e.advanceAfterAssetEnded(T,E,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||!fn(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} ${ra(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,s=e!==c,f=s&&e.interstitial.appendInPlace,m=(n=this.detachedData)==null?void 0:n.mediaSource;let x;if(c.media)f&&(a=c.transferMedia(),this.detachedData=a),x="Primary";else if(m){const C=this.getBufferingPlayer();C?(a=C.transferMedia(),x=`${C}`):x="detached MediaSource"}else x="detached media";if(!a){if(m)a=this.detachedData,this.log(`using detachedData: MediaSource ${ra(a)}`);else if(!this.detachedData||c.media===r){const C=this.playerQueue;C.length>1&&C.forEach(N=>{if(s&&N.interstitial.appendInPlace!==f){const R=N.interstitial;this.clearInterstitial(N.interstitial,null),R.appendInPlace=!1,R.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${R}`)}}),this.hls.detachMedia(),this.detachedData={media:r}}}const _=a&&"mediaSource"in a&&((i=a.mediaSource)==null?void 0:i.readyState)!=="closed",T=_&&a?a:r;this.log(`${_?"transfering MediaSource":"attaching media"} to ${s?e:"Primary"} from ${x} (media.currentTime: ${r.currentTime})`);const E=this.schedule;if(T===a&&E){const C=s&&e.assetId===E.assetIdAtEnd;T.overrides={duration:E.duration,endOfStream:!s||C,cueRemoval:!s}}e.attachMedia(T)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,r=e==null?void 0:e.events;if(!r||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const n=this.timelinePos,i=this.effectivePlayingItem;if(n===-1){const a=this.hls.startPosition;if(this.timelinePos=a,r.length===0)this.setSchedulePosition(0);else if(r[0].cue.pre){this.log(Kb("checkStart (preroll)",a));const c=e.findEventIndex(r[0].identifier);this.setSchedulePosition(c)}else if(a>=0||!this.primaryLive){this.log(Kb("checkStart",a));const c=this.timelinePos=a>0?a:0,s=e.findItemIndexAtTime(c);this.setSchedulePosition(s)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(i&&!this.playingItem){this.log(Kb("checkStart (playing item)",i.start));const a=e.findItemIndex(i);this.setSchedulePosition(a)}}advanceAssetBuffering(e,r){const n=e.event,i=n.findAssetIndex(r),a=f$(n,i);if(!n.isAssetPastPlayoutLimit(a))this.bufferedToEvent(e,a);else if(this.schedule){var c;const s=(c=this.schedule.items)==null?void 0:c[this.findItemIndex(e)+1];s&&this.bufferedToItem(s)}}advanceAfterAssetEnded(e,r,n){const i=f$(e,n);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const a=this.schedule.items;if(a){const c=r+1,s=a.length;if(c>=s){this.setSchedulePosition(-1);return}const f=e.resumeTime;this.timelinePos=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${r} (${a&&Ch(a)}) pos: ${this.timelinePos}`);const c=this.waitingItem||this.playingItem,s=this.playingLastItem;if(this.isInterstitial(c)){const x=c.event,_=this.playingAsset,T=_==null?void 0:_.identifier,E=T?this.getAssetPlayer(T):null;if(E&&T&&(!this.eventItemsMatch(c,a)||r!==void 0&&T!==x.assetList[r].identifier)){var f;const C=x.findAssetIndex(_);if(this.log(`INTERSTITIAL_ASSET_ENDED ${C+1}/${x.assetList.length} ${Jb(_)}`),this.endedAsset=_,this.playingAsset=null,this.hls.trigger(ke.INTERSTITIAL_ASSET_ENDED,{asset:_,assetListIndex:C,event:x,schedule:i.slice(0),scheduleIndex:e,player:E}),c!==this.playingItem){this.itemsMatch(c,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(x,this.findItemIndex(this.playingItem),C);return}this.retreiveMediaSource(T,a),E.media&&!((f=this.detachedData)!=null&&f.mediaSource)&&E.detachMedia()}if(!this.eventItemsMatch(c,a)&&(this.endedItem=c,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${x} ${Ch(c)}`),x.hasPlayed=!0,this.hls.trigger(ke.INTERSTITIAL_ENDED,{event:x,schedule:i.slice(0),scheduleIndex:e}),x.cue.once)){var m;this.updateSchedule();const C=(m=this.schedule)==null?void 0:m.items;if(a&&C){const N=this.findItemIndex(a);this.advanceSchedule(N,C,r,c,s)}return}}this.advanceSchedule(e,i,r,c,s)}advanceSchedule(e,r,n,i,a){const c=this.schedule;if(!c)return;const s=r[e]||null,f=this.primaryMedia,m=this.playerQueue;if(m.length&&m.forEach(x=>{const _=x.interstitial,T=c.findEventIndex(_.identifier);(Te+1)&&this.clearInterstitial(_,s)}),this.isInterstitial(s)){this.timelinePos=Math.min(Math.max(this.timelinePos,s.start),s.end);const x=s.event;if(n===void 0){n=c.findAssetIndex(x,this.timelinePos);const C=f$(x,n-1);if(x.isAssetPastPlayoutLimit(C)||x.appendInPlace&&this.timelinePos===s.end){this.advanceAfterAssetEnded(x,e,n);return}n=C}const _=this.waitingItem;this.assetsBuffered(s,f)||this.setBufferingItem(s);let T=this.preloadAssets(x,n);if(this.eventItemsMatch(s,_||i)||(this.waitingItem=s,this.log(`INTERSTITIAL_STARTED ${Ch(s)} ${x.appendInPlace?"append in place":""}`),this.hls.trigger(ke.INTERSTITIAL_STARTED,{event:x,schedule:r.slice(0),scheduleIndex:e})),!x.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${x}`);return}if(x.assetListLoader&&(x.assetListLoader.destroy(),x.assetListLoader=void 0),!f){this.log(`Waiting for attachMedia to start Interstitial ${x}`);return}this.waitingItem=this.endedItem=null,this.playingItem=s;const E=x.assetList[n];if(!E){this.advanceAfterAssetEnded(x,e,n||0);return}if(T||(T=this.getAssetPlayer(E.identifier)),T===null||T.destroyed){const C=x.assetList.length;this.warn(`asset ${n+1}/${C} player destroyed ${x}`),T=this.createAssetPlayer(x,E,n),T.loadSource()}if(!this.eventItemsMatch(s,this.bufferingItem)&&x.appendInPlace&&this.isAssetBuffered(E))return;this.startAssetPlayer(T,n,r,e,f),this.shouldPlay&&$le(T.media)}else s?(this.resumePrimary(s,e,i),this.shouldPlay&&$le(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;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Ch(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let s=this.timelinePos;(s=e.end)&&(s=this.getPrimaryResumption(e,r),this.log(Kb("resumePrimary",s)),this.timelinePos=s),this.attachPrimary(s,e)}if(!n)return;const c=(a=this.schedule)==null?void 0:a.items;c&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ch(e)}`),this.hls.trigger(ke.INTERSTITIALS_PRIMARY_RESUMED,{schedule:c.slice(0),scheduleIndex:r}),this.checkBuffer())}getPrimaryResumption(e,r){const n=e.start;if(this.primaryLive){const i=this.primaryDetails;if(r===0)return this.hls.startPosition;if(i&&(ni.edge))return this.hls.liveSyncPosition||-1}return n}isAssetBuffered(e){const r=this.getAssetPlayer(e.identifier);return r!=null&&r.hls?r.hls.bufferedToEnd:vi.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=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(Kb("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,n))}startLoadingPrimaryAt(e,r){var n;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((n=i.mainForwardBufferInfo)==null?void 0:n.start)||i.media.currentTime)-e)>.5?i.startLoad(e,r):i.bufferingEnabled||i.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(ke.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(ke.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=Bs(Bs({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,r){const n=this.hls.audioTracks[r.id],i=this.mediaSelection;if(!i){this.altSelection=Bs(Bs({},this.altSelection),{},{audio:n});return}const a=Bs(Bs({},i),{},{audio:n});this.mediaSelection=a}onSubtitleTrackUpdated(e,r){const n=this.hls.subtitleTracks[r.id],i=this.mediaSelection;if(!i){this.altSelection=Bs(Bs({},this.altSelection),{},{subtitles:n});return}const a=Bs(Bs({},i),{},{subtitles:n});this.mediaSelection=a}onAudioTrackSwitching(e,r){const n=Zoe(r);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(r)||i.setAudioOption(n)))}onSubtitleTrackSwitch(e,r){const n=Zoe(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=vi.bufferInfo(this.primaryMedia,n,0);(i.end>n||(i.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${Ch(e)} (was ${Ch(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))}findItemIndex(e,r){return e&&this.schedule?this.schedule.findItemIndex(e,r):-1}updateSchedule(e=!1){var r;const n=this.mediaSelection;n&&((r=this.schedule)==null||r.updateSchedule(n,[],e))}checkBuffer(e){var r;const n=(r=this.schedule)==null?void 0:r.items;if(!n)return;const i=vi.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,s=this.findItemIndex(c);let f=i.findItemIndexAtTime(e);if(this.bufferedPos=a.end||(m=T.event)!=null&&m.appendInPlace&&e+.01>=T.start)&&(f=_),this.isInterstitial(a)){const E=a.event;if(_-s>1&&E.appendInPlace===!1||E.assetList.length===0&&E.assetListLoader)return}if(this.bufferedPos=e,f>x&&f>s)this.bufferedToItem(T);else{const E=this.primaryDetails;this.primaryLive&&E&&e>E.edge-E.targetduration&&T.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),s=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const f=s?s.remaining:r?r.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ch(e)}`+(r?` (${f.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(c){const m=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((x,_)=>{const T=this.getAssetPlayer(x.identifier);T&&(_===m&&T.loadSource(),T.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(m=>m.pauseBuffering());this.hls.trigger(ke.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.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const r=this.findItemIndex(e),n=this.getPrimaryResumption(e,r);this.startLoadingPrimaryAt(n)}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 s=this.primaryMedia;s&&this.bufferAssetPlayer(c,s)}}}preloadAssets(e,r){const n=e.assetUrl,i=e.assetList.length,a=i===0&&!e.assetListLoader,c=e.cue.once;if(a){const f=e.timelineStart;if(e.appendInPlace){var s;const T=this.playingItem;!this.isInterstitial(T)&&(T==null||(s=T.nextEvent)==null?void 0:s.identifier)===e.identifier&&this.flushFrontBuffer(f+.25)}let m,x=0;if(!this.playingItem&&this.primaryLive&&(x=this.hls.startPosition,x===-1&&(x=this.hls.liveSyncPosition||0)),x&&!(e.cue.pre||e.cue.post)){const T=x-f;T>0&&(m=Math.round(T*1e3)/1e3)}if(this.log(`Load interstitial asset ${r+1}/${n?1:i} ${e}${m?` live-start: ${x} start-offset: ${m}`:""}`),n)return this.createAsset(e,0,0,f,e.duration,n);const _=this.assetListLoader.loadAssetList(e,m);_&&(e.assetListLoader=_)}else if(!c&&i){for(let m=r;m{this.hls.trigger(ke.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const r=this.playerQueue;for(let n=0;n1){const G=r.duration;G&&V{if(V.live){var G;const Q=new Error(`Interstitials MUST be VOD assets ${e}`),re={fatal:!0,type:Ln.OTHER_ERROR,details:Qt.INTERSTITIAL_ASSET_ITEM_ERROR,error:Q},se=((G=this.schedule)==null?void 0:G.findEventIndex(e.identifier))||-1;this.handleAssetItemError(re,e,se,n,Q.message);return}const W=V.edge-V.fragmentStart,X=r.duration;(N||X===null||W>X)&&(N=!1,this.log(`Interstitial asset "${_}" duration change ${X} > ${W}`),r.duration=W,this.updateSchedule())};C.on(ke.LEVEL_UPDATED,(V,{details:G})=>R(G)),C.on(ke.LEVEL_PTS_UPDATED,(V,{details:G})=>R(G)),C.on(ke.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const D=(V,G)=>{const W=this.getAssetPlayer(_);if(W&&G.tracks){W.off(ke.BUFFER_CODECS,D),W.tracks=G.tracks;const X=this.primaryMedia;this.bufferingAsset===W.assetItem&&X&&!W.media&&this.bufferAssetPlayer(W,X)}};C.on(ke.BUFFER_CODECS,D);const M=()=>{var V;const G=this.getAssetPlayer(_);if(this.log(`buffered to end of asset ${G}`),!G||!this.schedule)return;const W=this.schedule.findEventIndex(e.identifier),X=(V=this.schedule.items)==null?void 0:V[W];this.isInterstitial(X)&&this.advanceAssetBuffering(X,r)};C.on(ke.BUFFERED_TO_END,M);const B=V=>()=>{if(!this.getAssetPlayer(_)||!this.schedule)return;this.shouldPlay=!0;const W=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,W,V)};return C.once(ke.MEDIA_ENDED,B(n)),C.once(ke.PLAYOUT_LIMIT_REACHED,B(1/0)),C.on(ke.ERROR,(V,G)=>{if(!this.schedule)return;const W=this.getAssetPlayer(_);if(G.details===Qt.BUFFER_STALLED_ERROR){if(W!=null&&W.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(G,e,this.schedule.findEventIndex(e.identifier),n,`Asset player error ${G.error} ${e}`)}),C.on(ke.DESTROYING,()=>{if(!this.getAssetPlayer(_)||!this.schedule)return;const G=new Error(`Asset player destroyed unexpectedly ${_}`),W={fatal:!0,type:Ln.OTHER_ERROR,details:Qt.INTERSTITIAL_ASSET_ITEM_ERROR,error:G};this.handleAssetItemError(W,e,this.schedule.findEventIndex(e.identifier),n,G.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Jb(r)}`),this.hls.trigger(ke.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:r,assetListIndex:n,event:e,player:C}),C}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&&Ch(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:s,assetId:f}=e,m=c.assetList.length,x=this.playingAsset;this.endedAsset=null,this.playingAsset=s,(!x||x.identifier!==f)&&(x&&(this.clearAssetPlayer(x.identifier,n[i]),delete x.error),this.log(`INTERSTITIAL_ASSET_STARTED ${r+1}/${m} ${Jb(s)}`),this.hls.trigger(ke.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:r,event:c,schedule:n.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,a)}bufferAssetPlayer(e,r){var n,i;if(!this.schedule)return;const{interstitial:a,assetItem:c}=e,s=this.schedule.findEventIndex(a.identifier),f=(n=this.schedule.items)==null?void 0:n[s];if(!f)return;e.loadSource(),this.setBufferingItem(f),this.bufferingAsset=c;const m=this.getBufferingPlayer();if(m===e)return;const x=a.appendInPlace;if(x&&(m==null?void 0:m.interstitial.appendInPlace)===!1)return;const _=(m==null?void 0:m.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(x&&c!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(_&&!CEe(_,e.tracks)){const T=new Error(`Asset ${Jb(c)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(_)}')`),E={fatal:!0,type:Ln.OTHER_ERROR,details:Qt.INTERSTITIAL_ASSET_ITEM_ERROR,error:T},C=a.findAssetIndex(c);this.handleAssetItemError(E,a,s,C,T.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 s=this.getAssetPlayer(c.identifier);if(s){const f=s.currentTime||i-c.timelineStart,m=s.duration-f;if(this.warn(`Stalled at ${f} of ${f+m} in ${s} ${e} (media.currentTime: ${i})`),f&&(m/n.playbackRate<.5||s.bufferedInPlaceToEnd(n))&&s.hls){const x=r.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,x,a)}}}}advanceInPlace(e){const r=this.primaryMedia;r&&r.currentTime!N.error))r.error=C;else for(let N=i;N{const D=parseFloat(N.DURATION);this.createAsset(a,R,x,f+x,D,N.URI),x+=D}),a.duration=x,this.log(`Loaded asset-list with duration: ${x} (was: ${m}) ${a}`);const _=this.waitingItem,T=(_==null?void 0:_.event.identifier)===c;this.updateSchedule();const E=(i=this.bufferingItem)==null?void 0:i.event;if(T){var C;const N=this.schedule.findEventIndex(c),R=(C=this.schedule.items)==null?void 0:C[N];if(R){if(!this.playingItem&&this.timelinePos>R.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==N){a.error=new Error(`Interstitial ${s.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(R)}this.setSchedulePosition(N)}else if((E==null?void 0:E.identifier)===c){const N=a.assetList[0];if(N){const R=this.getAssetPlayer(N.identifier);if(E.appendInPlace){const D=this.primaryMedia;R&&D&&this.bufferAssetPlayer(R,D)}else R&&R.loadSource()}}}onError(e,r){if(this.schedule)switch(r.details){case Qt.ASSET_LIST_PARSING_ERROR:case Qt.ASSET_LIST_LOAD_ERROR:case Qt.ASSET_LIST_LOAD_TIMEOUT:{const n=r.interstitial;n&&(this.updateSchedule(!0),this.primaryFallback(n));break}case Qt.BUFFER_STALLED_ERROR:{const n=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(n)&&n.event.appendInPlace){this.handleInPlaceStall(n.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Ule=500;class eOt extends EW{constructor(e,r,n){super(e,r,n,"subtitle-stream-controller",Sn.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(ke.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ke.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(ke.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(ke.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(ke.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(ke.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(ke.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ke.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ke.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(ke.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(ke.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(ke.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,r){this.stopLoad(),this.state=br.IDLE,this.setInterval(Ule),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){const{frag:n,success:i}=r;if(this.fragContextChanged(n)||(To(n)&&(this.fragPrevious=n),this.state=br.IDLE),!i)return;const a=this.tracksBuffered[this.currentTrackId];if(!a)return;let c;const s=n.start;for(let m=0;m=a[m].start&&s<=a[m].end){c=a[m];break}const f=n.start+n.duration;c?c.end=f:(c={start:s,end:f},a.push(c)),this.fragmentTracker.fragBuffered(n),this.fragBufferedComplete(n,null),this.media&&this.tick()}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=>{for(let s=0;snew lC(n));return}this.tracksBuffered=[],this.levels=r.map(n=>{const i=new lC(n);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Sn.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,r){var n;if(this.currentTrackId=r.id,!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==br.STOPPED&&this.setInterval(Ule)}onSubtitleTrackLoaded(e,r){var n;const{currentTrackId:i,levels:a}=this,{details:c,id:s}=r;if(!a){this.warn(`Subtitle tracks were reset while loading level ${s}`);return}const f=a[s];if(s>=a.length||!f)return;this.log(`Subtitle track ${s} loaded [${c.startSN},${c.endSN}]${c.lastPartSn?`[part-${c.lastPartSn}-${c.lastPartIndex}]`:""},duration:${c.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let m=0;if(c.live||(n=f.details)!=null&&n.live){if(c.deltaUpdateFailed)return;const _=this.mainDetails;if(!_){this.startFragRequested=!1;return}const T=_.fragments[0];if(!f.details)c.hasProgramDateTime&&_.hasProgramDateTime?(kO(c,_),m=c.fragmentStart):T&&(m=T.start,Q8(c,m));else{var x;m=this.alignPlaylists(c,f.details,(x=this.levelLastLoaded)==null?void 0:x.details),m===0&&T&&(m=T.start,Q8(c,m))}_&&!this.startFragRequested&&this.setStartPosition(_,m)}f.details=c,this.levelLastLoaded=f,s===i&&(this.hls.trigger(ke.SUBTITLE_TRACK_UPDATED,{details:c,id:s,groupId:r.groupId}),this.tick(),c.live&&!this.fragCurrent&&this.media&&this.state===br.IDLE&&(D0(null,c.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),f.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:r,payload:n}=e,i=r.decryptdata,a=this.hls;if(!this.fragContextChanged(r)&&n&&n.byteLength>0&&i!=null&&i.key&&i.iv&&Uw(i.method)){const c=performance.now();this.decrypter.decrypt(new Uint8Array(n),i.key.buffer,i.iv.buffer,SW(i.method)).catch(s=>{throw a.trigger(ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.FRAG_DECRYPT_ERROR,fatal:!1,error:s,reason:s.message,frag:r}),s}).then(s=>{const f=performance.now();a.trigger(ke.FRAG_DECRYPTED,{frag:r,payload:s,stats:{tstart:c,tdecrypt:f}})}).catch(s=>{this.warn(`${s.name}: ${s.message}`),this.state=br.IDLE})}}doTick(){if(!this.media){this.state=br.IDLE;return}if(this.state===br.IDLE){const{currentTrackId:e,levels:r}=this,n=r==null?void 0:r[e];if(!n||!r.length||!n.details||this.waitForLive(n))return;const{config:i}=this,a=this.getLoadPosition(),c=vi.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a,i.maxBufferHole),{end:s,len:f}=c,m=n.details,x=this.hls.maxBufferLength+m.levelTargetDuration;if(f>x)return;const _=m.fragments,T=_.length,E=m.edge;let C=null;const N=this.fragPrevious;if(sE-M?0:M;C=D0(N,_,Math.max(_[0].start,s),B),!C&&N&&N.start<_[0].start&&(C=_[0])}else C=_[T-1];if(C=this.filterReplacedPrimary(C,n.details),!C)return;const R=C.sn-m.startSN,D=_[R-1];if(D&&D.cc===C.cc&&this.fragmentTracker.getState(D)===sl.NOT_LOADED&&(C=D),this.fragmentTracker.getState(C)===sl.NOT_LOADED){const M=this.mapToInitFragWhenRequired(C);M&&this.loadFragment(M,n,s)}}}loadFragment(e,r,n){To(e)?super.loadFragment(e,r,n):this._loadInitSegment(e,r)}get mediaBufferTimeRanges(){return new tOt(this.tracksBuffered[this.currentTrackId]||[])}}class tOt{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 rOt={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},W2e=t=>String.fromCharCode(rOt[t]||t),Ph=15,Jp=100,nOt={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},iOt={17:2,18:4,21:6,22:8,23:10,19:13,20:15},sOt={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},aOt={25:2,26:4,29:6,30:8,31:10,27:13,28:15},oOt=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class lOt{constructor(){this.time=null,this.verboseLevel=0}log(e,r){if(this.verboseLevel>=e){const n=typeof r=="function"?r():r;$s.log(`${this.time} [${e}] ${n}`)}}}const N_=function(e){const r=[];for(let n=0;nJp&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Jp)}moveCursor(e){const r=this.pos+e;if(e>1)for(let n=this.pos+1;n=144&&this.backSpace();const r=W2e(e);if(this.pos>=Jp){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 = "+ra(e));let r=e.row-1;if(this.nrRollUpRows&&r"bkgData = "+ra(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 Vle{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 p$(n),this.nonDisplayedMemory=new p$(n),this.lastOutputScreen=new p$(n),this.currRollUpRow=this.displayedMemory.rows[Ph-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[Ph-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: "+ra(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 qle{constructor(e,r,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=hOt(),this.logger=void 0;const i=this.logger=new lOt;this.channels=[null,new Vle(e,r,i),new Vle(e+1,n,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,r){this.channels[e].setHandler(r)}addData(e,r){this.logger.time=e;for(let n=0;n"["+N_([r[n],r[n+1]])+"] -> ("+N_([i,a])+")");const f=this.cmdHistory;if(i>=16&&i<=31){if(dOt(i,a,f)){nR(null,null,f),this.logger.log(3,()=>"Repeated command ("+N_([i,a])+") is dropped");continue}nR(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 nR(null,null,f);if(!c&&(s=this.parseChars(i,a),s)){const x=this.currentChannel;x&&x>0?this.channels[x].insertChars(s):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!c&&!s&&this.logger.log(2,()=>"Couldn't parse cleaned data "+N_([i,a])+" orig: "+N_([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.channels[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 ("+N_([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;r>=64&&r<=95?n=c===1?nOt[e]:sOt[e]:n=c===1?iOt[e]:aOt[e];const s=this.channels[c];return s?(s.setPAC(this.interpretPAC(n,r)),this.currentChannel=c,!0):!1}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 '"+W2e(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 = "+N_(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=oOt[a],r%2===1&&(c.background=c.background+"_semi")):r===45?c.background="transparent":(c.foreground="black",r===47&&(c.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(c),!0}reset(){for(let e=0;e100)throw new Error("Position must be between 0 and 100.");W=se,this.hasBeenReset=!0}})),Object.defineProperty(x,"positionAlign",a({},_,{get:function(){return X},set:function(se){const ue=i(se);if(!ue)throw new SyntaxError("An invalid or illegal string was specified.");X=ue,this.hasBeenReset=!0}})),Object.defineProperty(x,"size",a({},_,{get:function(){return Q},set:function(se){if(se<0||se>100)throw new Error("Size must be between 0 and 100.");Q=se,this.hasBeenReset=!0}})),Object.defineProperty(x,"align",a({},_,{get:function(){return re},set:function(se){const ue=i(se);if(!ue)throw new SyntaxError("An invalid or illegal string was specified.");re=ue,this.hasBeenReset=!0}})),x.displayState=void 0}return c.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},c}();class fOt{decode(e,r){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Y2e(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 pOt{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 Z2e(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 s=c[0],f=c[1];e(s,f)}}const aq=new MW(0,0,""),iR=aq.align==="middle"?"middle":"center";function mOt(t,e,r){const n=t;function i(){const s=Y2e(t);if(s===null)throw new Error("Malformed timestamp: "+n);return t=t.replace(/^[^\sa-zA-Z-]+/,""),s}function a(s,f){const m=new pOt;Z2e(s,function(T,E){let C;switch(T){case"region":for(let N=r.length-1;N>=0;N--)if(r[N].id===E){m.set(T,r[N].region);break}break;case"vertical":m.alt(T,E,["rl","lr"]);break;case"line":C=E.split(","),m.integer(T,C[0]),m.percent(T,C[0])&&m.set("snapToLines",!1),m.alt(T,C[0],["auto"]),C.length===2&&m.alt("lineAlign",C[1],["start",iR,"end"]);break;case"position":C=E.split(","),m.percent(T,C[0]),C.length===2&&m.alt("positionAlign",C[1],["start",iR,"end","line-left","line-right","auto"]);break;case"size":m.percent(T,E);break;case"align":m.alt(T,E,["start",iR,"end","left","right"]);break}},/:/,/\s/),f.region=m.get("region",null),f.vertical=m.get("vertical","");let x=m.get("line","auto");x==="auto"&&aq.line===-1&&(x=-1),f.line=x,f.lineAlign=m.get("lineAlign","start"),f.snapToLines=m.get("snapToLines",!0),f.size=m.get("size",100),f.align=m.get("align",iR);let _=m.get("position","auto");_==="auto"&&aq.position===50&&(_=f.align==="start"||f.align==="left"?0:f.align==="end"||f.align==="right"?100:50),f.position=_}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 X2e(t){return t.replace(//gi,` `)}class gOt{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new fOt,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=X2e(a);c")===-1){r.cue.id=a;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{mOt(a,r.cue,r.regionList)}catch{r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":{const s=a.indexOf("-->")!==-1;if(!a||s&&(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}}const yOt=/\r\n|\n\r|\n|\r/g,m$=function(e,r,n=0){return e.slice(n,n+r.length)===r},xOt=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(!fn(r)||!fn(n)||!fn(i)||!fn(a))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return r+=1e3*n,r+=60*1e3*i,r+=60*60*1e3*a,r};function FW(t,e,r){return NA(t.toString())+NA(e.toString())+NA(r)}const _Ot=function(e,r,n){let i=e[r],a=e[i.prevCC];if(!a||!a.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(c=a)!=null&&c.new;){var c;e.ccOffset+=i.start-a.start,i.new=!1,i=a,a=e[i.prevCC]}e.presentationOffset=n};function vOt(t,e,r,n,i,a,c){const s=new gOt,f=id(new Uint8Array(t)).trim().replace(yOt,` `).split(` `),m=[],x=e?ALt(e.baseTime,e.timescale):0;let _="00:00.000",T=0,E=0,C,N=!0;s.oncue=function(R){const D=r[n];let M=r.ccOffset;const B=(T-x)/9e4;if(D!=null&&D.new&&(E!==void 0?M=r.ccOffset=D.start:_Ot(r,n,B)),B){if(!e){C=new Error("Missing initPTS for VTT MPEGTS");return}M=B-r.presentationOffset}const V=R.endTime-R.startTime,G=Gu((R.startTime+M-E)*9e4,i*9e4)/9e4;R.startTime=Math.max(G,0),R.endTime=Math.max(G+V,0);const W=R.text.trim();R.text=decodeURIComponent(encodeURIComponent(W)),R.id||(R.id=FW(R.startTime,R.endTime,W)),R.endTime>0&&m.push(R)},s.onparsingerror=function(R){C=R},s.onflush=function(){if(C){c(C);return}a(m)},f.forEach(R=>{if(N)if(m$(R,"X-TIMESTAMP-MAP=")){N=!1,R.slice(16).split(",").forEach(D=>{m$(D,"LOCAL:")?_=D.slice(6):m$(D,"MPEGTS:")&&(T=parseInt(D.slice(7)))});try{E=xOt(_)/1e3}catch(D){C=D}return}else R===""&&(N=!1);s.parse(R+` `)}),s.flush()}const g$="stpp.ttml.im1t",Q2e=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,J2e=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,bOt={left:"start",center:"center",right:"end",start:"start",end:"end"};function Gle(t,e,r,n){const i=Ui(new Uint8Array(t),["mdat"]);if(i.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const a=i.map(s=>id(s)),c=ELt(e.baseTime,1,e.timescale);try{a.forEach(s=>r(wOt(s,c)))}catch(s){n(s)}}function wOt(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,frameRateMultiplier:0,tickRate:0},c=Object.keys(a).reduce((_,T)=>(_[T]=i.getAttribute(`ttp:${T}`)||a[T],_),{}),s=i.getAttribute("xml:space")!=="preserve",f=Hle(y$(i,"styling","style")),m=Hle(y$(i,"layout","region")),x=y$(i,"body","[begin]");return[].map.call(x,_=>{const T=eAe(_,s);if(!T||!_.hasAttribute("begin"))return null;const E=_$(_.getAttribute("begin"),c),C=_$(_.getAttribute("dur"),c);let N=_$(_.getAttribute("end"),c);if(E===null)throw Wle(_);if(N===null){if(C===null)throw Wle(_);N=E+C}const R=new MW(E-e,N-e,T);R.id=FW(R.startTime,R.endTime,R.text);const D=m[_.getAttribute("region")],M=f[_.getAttribute("style")],B=SOt(D,M,f),{textAlign:V}=B;if(V){const G=bOt[V];G&&(R.lineAlign=G),R.align=V}return Ys(R,B),R}).filter(_=>_!==null)}function y$(t,e,r){const n=t.getElementsByTagName(e)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function Hle(t){return t.reduce((e,r)=>{const n=r.getAttribute("xml:id");return n&&(e[n]=r),e},{})}function eAe(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?eAe(n,e):e?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function SOt(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((s,f)=>{const m=x$(e,n,f)||x$(t,n,f)||x$(i,n,f);return m&&(s[f]=m),s},{})}function x$(t,e,r){return t&&t.hasAttributeNS(e,r)?t.getAttributeNS(e,r):null}function Wle(t){return new Error(`Could not parse ttml timestamp ${t}`)}function _$(t,e){if(!t)return null;let r=Y2e(t);return r===null&&(Q2e.test(t)?r=TOt(t,e):J2e.test(t)&&(r=EOt(t,e))),r}function TOt(t,e){const r=Q2e.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 EOt(t,e){const r=J2e.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}class sR{constructor(e,r){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=r}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,r,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=r,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class AOt{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yle(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,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(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ke.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(ke.FRAG_LOADING,this.onFragLoading,this),e.on(ke.FRAG_LOADED,this.onFragLoaded,this),e.on(ke.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(ke.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(ke.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(ke.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(ke.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ke.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(ke.FRAG_LOADING,this.onFragLoading,this),e.off(ke.FRAG_LOADED,this.onFragLoaded,this),e.off(ke.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(ke.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(ke.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(ke.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(ke.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new sR(this,"textTrack1"),r=new sR(this,"textTrack2"),n=new sR(this,"textTrack3"),i=new sR(this,"textTrack4");this.cea608Parser1=new qle(1,e,r),this.cea608Parser2=new qle(3,n,i)}addCues(e,r,n,i,a){let c=!1;for(let s=a.length;s--;){const f=a[s],m=kOt(f[0],f[1],r,n);if(m>=0&&(f[0]=Math.min(f[0],r),f[1]=Math.max(f[1],n),c=!0,m/(n-r)>.5))return}if(c||a.push([r,n]),this.config.renderTextTracksNatively){const s=this.captionsTracks[e];this.Cues.newCue(s,r,n,i)}else{const s=this.Cues.newCue(null,r,n,i);this.hls.trigger(ke.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:r,id:n,initPTS:i,timescale:a,trackId:c}){const{unparsedVttFrags:s}=this;n===Sn.MAIN&&(this.initPTS[r.cc]={baseTime:i,timescale:a,trackId:c}),s.length&&(this.unparsedVttFrags=[],s.forEach(f=>{this.initPTS[f.frag.cc]?this.onFragLoaded(ke.FRAG_LOADED,f):this.hls.trigger(ke.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:f.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,r){const{media:n}=this;if(n)for(let i=0;i{ww(i[a]),delete i[a]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yle(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const r=e.textTracks;if(r)for(let n=0;na.textCodec===g$);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(P2e(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const c=this.media,s=c?tL(c.textTracks):null;if(this.tracks.forEach((f,m)=>{let x;if(s){let _=null;for(let T=0;Tm!==null).map(m=>m.label);f.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${f.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const c=this.tracks.map(s=>({label:s.name,kind:s.type.toLowerCase(),default:s.default,subtitleTrack:s}));this.hls.trigger(ke.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:c})}}}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===Sn.MAIN){var n,i;const{cea608Parser1:a,cea608Parser2:c,lastSn:s}=this,{cc:f,sn:m}=r.frag,x=(n=(i=r.part)==null?void 0:i.index)!=null?n:-1;a&&c&&(m!==s+1||m===s&&x!==this.lastPartIndex+1||f!==this.lastCc)&&(a.reset(),c.reset()),this.lastCc=f,this.lastSn=m,this.lastPartIndex=x}}onFragLoaded(e,r){const{frag:n,payload:i}=r;if(n.type===Sn.SUBTITLE)if(i.byteLength){const a=n.decryptdata,c="stats"in r;if(a==null||!a.encrypted||c){const s=this.tracks[n.level],f=this.vttCCs;f[n.cc]||(f[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),s&&s.textCodec===g$?this._parseIMSC1(n,i):this._parseVTTs(r)}}else this.hls.trigger(ke.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,r){const n=this.hls;Gle(r,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),n.trigger(ke.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{n.logger.log(`Failed to parse IMSC1: ${i}`),n.trigger(ke.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var r;const{frag:n,payload:i}=e,{initPTS:a,unparsedVttFrags:c}=this,s=a.length-1;if(!a[n.cc]&&s===-1){c.push(e);return}const f=this.hls,m=(r=n.initSegment)!=null&&r.data?eh(n.initSegment.data,new Uint8Array(i)).buffer:i;vOt(m,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,x=>{this._appendCues(x,n.level),f.trigger(ke.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},x=>{const _=x.message==="Missing initPTS for VTT MPEGTS";_?c.push(e):this._fallbackToIMSC1(n,i),f.logger.log(`Failed to parse VTT cue: ${x}`),!(_&&s>n.cc)&&f.trigger(ke.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:x})})}_fallbackToIMSC1(e,r){const n=this.tracks[e.level];n.textCodec||Gle(r,this.initPTS[e.cc],()=>{n.textCodec=g$,this._parseIMSC1(e,r)},()=>{n.textCodec="wvtt"})}_appendCues(e,r){const n=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[r];if(!i||i.mode==="disabled")return;e.forEach(a=>G2e(i,a))}else{const i=this.tracks[r];if(!i)return;const a=i.default?"default":"subtitles"+r;n.trigger(ke.CUES_PARSED,{type:"subtitles",cues:e,track:a})}}onFragDecrypted(e,r){const{frag:n}=r;n.type===Sn.SUBTITLE&&this.onFragLoaded(ke.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===Sn.MAIN&&this.closedCaptionsForLevel(n)==="NONE"))for(let a=0;asq(s[f],r,n))}if(this.config.renderTextTracksNatively&&r===0&&i!==void 0){const{textTracks:s}=this;Object.keys(s).forEach(f=>sq(s[f],r,i))}}}extractCea608Data(e){const r=[[],[]],n=e[0]&31;let i=2;for(let a=0;a=16?f--:f++;const E=X2e(m.trim()),C=FW(e,r,E);t!=null&&(_=t.cues)!=null&&_.getCueById(C)||(c=new x(e,r,E),c.id=C,c.line=T+1,c.align="left",c.position=10+Math.min(80,Math.floor(f*8/32)*10),i.push(c))}return t&&i.length&&(i.sort((T,E)=>T.line==="auto"||E.line==="auto"?0:T.line>8&&E.line>8?E.line-T.line:T.line-E.line),i.forEach(T=>G2e(t,T))),i}};function IOt(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const POt=/(\d+)-(\d+)\/(\d+)/;class Zle{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||DOt,this.controller=new self.AbortController,this.stats=new gW}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}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();const a=NOt(e,this.controller.signal),c=e.responseType==="arraybuffer",s=c?"byteLength":"length",{maxTimeToFirstByteMs:f,maxLoadTimeMs:m}=r.loadPolicy;this.context=e,this.config=r,this.callbacks=n,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),r.timeout=f&&fn(f)?f:m,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},r.timeout),(dC(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(_=>{var T;this.response=this.loader=_;const E=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),r.timeout=m,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},m-(E-i.loading.start)),!_.ok){const{status:N,statusText:R}=_;throw new OOt(R||"fetch, bad network response",N,_)}i.loading.first=E,i.total=LOt(_.headers)||i.total;const C=(T=this.callbacks)==null?void 0:T.onProgress;return C&&fn(r.highWaterMark)?this.loadProgressively(_,i,e,r.highWaterMark,C):c?_.arrayBuffer():e.responseType==="json"?_.json():_.text()}).then(_=>{var T,E;const C=this.response;if(!C)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const N=_[s];N&&(i.loaded=i.total=N);const R={url:C.url,data:_,code:C.status},D=(T=this.callbacks)==null?void 0:T.onProgress;D&&!fn(r.highWaterMark)&&D(i,e,_,C),(E=this.callbacks)==null||E.onSuccess(R,i,e,C)}).catch(_=>{var T;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const E=_&&_.code||0,C=_?_.message:null;(T=this.callbacks)==null||T.onError({code:E,text:C},e,_?_.details:null,i)})}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 d2e,s=e.body.getReader(),f=()=>s.read().then(m=>{if(m.done)return c.dataLength&&a(r,n,c.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const x=m.value,_=x.length;return r.loaded+=_,_=i&&a(r,n,c.flush().buffer,e)):a(r,n,x.buffer,e),f()}).catch(()=>Promise.reject());return f()}}function NOt(t,e){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Ys({},t.headers))};return t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),r}function ROt(t){const e=POt.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function LOt(t){const e=t.get("Content-Range");if(e){const n=ROt(e);if(fn(n))return n}const r=t.get("Content-Length");if(r)return parseInt(r)}function DOt(t,e){return new self.Request(t.url,e)}class OOt extends Error{constructor(e,r,n){super(e),this.code=void 0,this.details=void 0,this.code=r,this.details=n}}const MOt=/^age:\s*[\d.]+\s*$/im;class rAe{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new gW,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=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()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,r,n){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=r,this.callbacks=n,this.loadInternal()}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(n,r.url)}).catch(c=>{if(!(this.loader!==n||this.stats.aborted))return n.open("GET",r.url,!0),a(n,r.url)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,r,e)}).catch(c=>{var s;(s=this.callbacks)==null||s.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 s in i)e.setRequestHeader(s,i[s]);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&&fn(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 m=r.status,x=r.responseType==="text"?r.responseText:null;if(m>=200&&m<300){const C=x??r.response;if(C!=null){var c,s;n.loading.end=Math.max(self.performance.now(),n.loading.first);const N=r.responseType==="arraybuffer"?C.byteLength:C.length;n.loaded=n.total=N,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);const R=(c=this.callbacks)==null?void 0:c.onProgress;R&&R(n,e,C,r);const D={url:r.responseURL,data:C,code:m};(s=this.callbacks)==null||s.onSuccess(D,n,e,r);return}}const _=a.loadPolicy.errorRetry,T=n.retry,E={url:e.url,data:void 0,code:m};if(TO(_,T,!1,E))this.retry(_);else{var f;$s.error(`${m} while loading ${e.url}`),(f=this.callbacks)==null||f.onError({code:m,text:r.statusText},e,r,n)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,r=this.stats.retry;if(TO(e,r,!0))this.retry(e);else{var n;$s.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.loader))}}retry(e){const{context:r,stats:n}=this;this.retryDelay=vW(e,n.retry),n.retry++,$s.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.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total)}getCacheAge(){let e=null;if(this.loader&&MOt.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 FOt={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},BOt=Bs(Bs({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount: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,ignorePlaylistParsingErrors:!1,loader:rAe,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:XNt,bufferController:$Lt,capLevelController:LW,errorController:rRt,fpsController:UDt,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:e2e,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:FOt},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},zOt()),{},{subtitleStreamController:eOt,subtitleTrackController:GDt,timelineController:AOt,audioStreamController:MLt,audioTrackController:FLt,emeController:Vw,cmcdController:FDt,contentSteeringController:zDt,interstitialsController:JDt});function zOt(){return{cueHandler:jOt,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 $Ot(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"');const n=oq(t),i=["manifest","level","frag"],a=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(c=>{const s=`${c==="level"?"playlist":c}LoadPolicy`,f=e[s]===void 0,m=[];a.forEach(x=>{const _=`${c}Loading${x}`,T=e[_];if(T!==void 0&&f){m.push(_);const E=n[s].default;switch(e[s]={default:E},x){case"TimeOut":E.maxLoadTimeMs=T,E.maxTimeToFirstByteMs=T;break;case"MaxRetry":E.errorRetry.maxNumRetry=T,E.timeoutRetry.maxNumRetry=T;break;case"RetryDelay":E.errorRetry.retryDelayMs=T,E.timeoutRetry.retryDelayMs=T;break;case"MaxRetryTimeout":E.errorRetry.maxRetryDelayMs=T,E.timeoutRetry.maxRetryDelayMs=T;break}}}),m.length&&r.warn(`hls.js config: "${m.join('", "')}" setting(s) are deprecated, use "${s}": ${ra(e[s])}`)}),Bs(Bs({},n),e)}function oq(t){return t&&typeof t=="object"?Array.isArray(t)?t.map(oq):Object.keys(t).reduce((e,r)=>(e[r]=oq(t[r]),e),{}):t}function UOt(t,e){const r=t.loader;r!==Zle&&r!==rAe?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):IOt()&&(t.loader=Zle,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const rL=2,VOt=.1,qOt=.05,GOt=100;class HOt extends YEe{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.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=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(ke.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=r,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ke.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ke.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(GOt),this.mediaSource=r.mediaSource;const n=this.media=r.media;Kc(n,"playing",this.onMediaPlaying),Kc(n,"waiting",this.onMediaWaiting),Kc(n,"ended",this.onMediaEnded)}onMediaDetaching(e,r){this.clearInterval();const{media:n}=this;n&&(Su(n,"playing",this.onMediaPlaying),Su(n,"waiting",this.onMediaWaiting),Su(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}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const r=this.media.currentTime;this.poll(r,this.lastCurrentTime),this.lastCurrentTime=r}poll(e,r){var n,i;const a=(n=this.hls)==null?void 0:n.config;if(!a)return;const c=this.media;if(!c)return;const{seeking:s}=c,f=this.seeking&&!s,m=!this.seeking&&s,x=c.paused&&!s||c.ended||c.playbackRate===0;if(this.seeking=s,e!==r){r&&(this.ended=0),this.moved=!0,s||(this.nudgeRetry=0,a.nudgeOnVideoHole&&!x&&e>r&&this.nudgeOnVideoHole(e,r)),this.waiting===0&&this.stallResolved(e);return}if(m||f){f&&this.stallResolved(e);return}if(x){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&c.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(ke.MEDIA_ENDED,{stalled:!1}));return}if(!vi.getBuffered(c).length){this.nudgeRetry=0;return}const _=vi.bufferInfo(c,e,0),T=_.nextStart||0,E=this.fragmentTracker;if(s&&E&&this.hls){const W=Xle(this.hls.inFlightFragments,e),X=_.len>rL,Q=!T||W||T-e>rL&&!E.getPartialFragment(e);if(X||Q)return;this.moved=!1}const C=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&E){if(!(_.len>0)&&!T)return;const X=Math.max(T,_.start||0)-e,re=!!(C!=null&&C.live)?C.targetduration*2:rL,se=aR(e,E);if(X>0&&(X<=re||se)){c.paused||this._trySkipBufferHole(se);return}}const N=a.detectStallWithCurrentTimeMs,R=self.performance.now(),D=this.waiting;let M=this.stalled;if(M===null)if(D>0&&R-D=N||D)&&this.hls){var V;if(((V=this.mediaSource)==null?void 0:V.readyState)==="ended"&&!(C!=null&&C.live)&&Math.abs(e-((C==null?void 0:C.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(ke.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(_),!this.media||!this.hls)return}const G=vi.bufferInfo(c,e,a.maxBufferHole);this._tryFixBufferStall(G,B,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(ke.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=vi.bufferedInfo(vi.timeRangesToArray(this.buffered.audio),e,0);if(a.len>1&&r>=a.start){const c=vi.timeRangesToArray(i),s=vi.bufferedInfo(c,r,0).bufferedIndex;if(s>-1&&ss)&&x-m<1&&e-m<2){const _=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${m} -> ${x} buffered index: ${f}`);this.warn(_.message),this.media.currentTime+=1e-6;let T=aR(e,this.fragmentTracker);T&&"fragment"in T?T=T.fragment:T||(T=void 0);const E=vi.bufferInfo(this.media,e,0);this.hls.trigger(ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:_,reason:_.message,frag:T,buffer:E.len,bufferInfo:E})}}}}}_tryFixBufferStall(e,r,n){var i,a;const{fragmentTracker:c,media:s}=this,f=(i=this.hls)==null?void 0:i.config;if(!s||!c||!f)return;const m=(a=this.hls)==null?void 0:a.latestLevelDetails,x=aR(n,c);if((x||m!=null&&m.live&&n1&&e.len>f.maxBufferHole||e.nextStart&&(e.nextStart-nf.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,Sn.MAIN),c=n.getFragAtPos(i,Sn.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 (${ra(e)})`);this.warn(c.message),r.trigger(ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.BUFFER_STALLED_ERROR,fatal:!1,error:c,buffer:e.len,bufferInfo:e,stalled:{start:a}})}}_trySkipBufferHole(e){var r;const{fragmentTracker:n,media:i}=this,a=(r=this.hls)==null?void 0:r.config;if(!i||!n||!a)return 0;const c=i.currentTime,s=vi.bufferInfo(i,c,0),f=c0&&s.len<1&&i.readyState<3,T=f-c;if(T>0&&(x||_)){if(T>a.maxBufferHole){let C=!1;if(c===0){const N=n.getAppendedFrag(0,Sn.MAIN);N&&f"u"))return self.VTTCue||self.TextTrackCue}function v$(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,ra(i?Bs({type:i},n):n))}return a}const oR=(()=>{const t=lq();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class KOt{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(ke.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(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(ke.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(ke.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ke.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(ke.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(ke.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(ke.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ke.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,r){var n;this.media=r.media,((n=r.overrides)==null?void 0:n.cueRemoval)===!1&&(this.removeCues=!1)}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.removeCues&&ww(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const r=this.getID3Track(e.textTracks);return r.mode="hidden",r}getID3Track(e){if(this.media){for(let r=0;roR&&(_=oR),_-x<=0&&(_=x+WOt);for(let E=0;Ex.type===Zu.audioId3&&f:i==="video"?m=x=>x.type===Zu.emsg&&s:m=x=>x.type===Zu.audioId3&&f||x.type===Zu.emsg&&s,sq(a,r,n,m)}}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 s=lq();if(n&&i&&!c){const{fragmentStart:N,fragmentEnd:R}=e;let D=this.assetCue;D?(D.startTime=N,D.endTime=R):s&&(D=this.assetCue=v$(s,N,R,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),D&&(D.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(D),D.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:f}=this,{dateRanges:m}=e,x=Object.keys(m);let _=this.dateRangeCuesAppended;if(f&&r){var T;if((T=f.cues)!=null&&T.length){const N=Object.keys(_).filter(R=>!x.includes(R));for(let R=N.length;R--;){var E;const D=N[R],M=(E=_[D])==null?void 0:E.cues;delete _[D],M&&Object.keys(M).forEach(B=>{const V=M[B];if(V){V.removeEventListener("enter",this.onEventCueEnter);try{f.removeCue(V)}catch{}}})}}else _=this.dateRangeCuesAppended={}}const C=e.fragments[e.fragments.length-1];if(!(x.length===0||!fn(C==null?void 0:C.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let N=0;N{if(_e!==D.id){const Se=m[_e];if(Se.class===D.class&&Se.startDate>D.startDate&&(!ue||D.startDate.01&&(_e.startTime=M,_e.endTime=W);else if(s){let Se=D.attr[ue];gRt(ue)&&(Se=jEe(Se));const Oe=v$(s,M,W,{key:ue,data:Se},Zu.dateRange);Oe&&(Oe.id=R,this.id3Track.addCue(Oe),V[ue]=Oe,c&&(ue==="X-ASSET-LIST"||ue==="X-ASSET-URL")&&Oe.addEventListener("enter",this.onEventCueEnter))}}_[R]={cues:V,dateRange:D,durationKnown:G}}}}}class YOt{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:r}=this,n=this.levelDetails;if(!r||!n)return;this.currentTime=r.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:a,maxLiveSyncPlaybackRate:c}=this.config;if(!a||c===1||!n.live)return;const s=this.targetLatency;if(s===null)return;const f=i-s,m=Math.min(this.maxLatency,s+n.targetduration);if(f.05&&this.forwardBufferLength>1){const _=Math.min(2,Math.max(1,c)),T=Math.round(2/(1+Math.exp(-.75*f-this.edgeStalled))*20)/20,E=Math.min(_,Math.max(1,T));this.changeMediaPlaybackRate(r,E)}else r.playbackRate!==1&&r.playbackRate!==0&&this.changeMediaPlaybackRate(r,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const r=this.levelDetails;return r?e.liveMaxLatencyDurationCount*r.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:r,partHoldBack:n,targetduration:i}=e,{liveSyncDuration:a,liveSyncDurationCount:c,lowLatencyMode:s}=this.config,f=this.hls.userConfig;let m=s&&n||r;(this._targetLatencyUpdated||f.liveSyncDuration||f.liveSyncDurationCount||m===0)&&(m=a!==void 0?a:c*i);const x=i;return m+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,x)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),r=this.targetLatency;if(e===null||r===null)return null;const n=this.levelDetails;if(n===null)return null;const i=n.edge,a=e-r-this.edgeStalled,c=i-n.totalduration,s=i-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(c,a),s)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const r=(this.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(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(ke.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(ke.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(ke.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(ke.ERROR,this.onError,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)}onError(e,r){var n;r.details===Qt.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}}class ZOt extends RW{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.onParsedComplete=void 0,this.steering=r,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(ke.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ke.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ke.FRAG_BUFFERED,this.onFragBuffered,this),e.on(ke.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(ke.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ke.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ke.FRAG_BUFFERED,this.onFragBuffered,this),e.off(ke.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}onManifestLoading(e,r){this.resetLevels()}onManifestLoaded(e,r){const n=this.hls.config.preferManagedMediaSource,i=[],a={},c={};let s=!1,f=!1,m=!1;r.levels.forEach(x=>{const _=x.attrs;let{audioCodec:T,videoCodec:E}=x;T&&(x.audioCodec=T=vO(T,n)||void 0),E&&(E=x.videoCodec=NNt(E));const{width:C,height:N,unknownCodecs:R}=x,D=(R==null?void 0:R.length)||0;if(s||(s=!!(C&&N)),f||(f=!!E),m||(m=!!T),D||T&&!this.isAudioSupported(T)||E&&!this.isVideoSupported(E)){this.log(`Some or all CODECS not supported "${_.CODECS}"`);return}const{CODECS:M,"FRAME-RATE":B,"HDCP-LEVEL":V,"PATHWAY-ID":G,RESOLUTION:W,"VIDEO-RANGE":X}=_,re=`${`${G||"."}-`}${x.bitrate}-${W}-${B}-${M}-${X}-${V}`;if(a[re])if(a[re].uri!==x.url&&!x.attrs["PATHWAY-ID"]){const se=c[re]+=1;x.attrs["PATHWAY-ID"]=new Array(se+1).join(".");const ue=this.createLevel(x);a[re]=ue,i.push(ue)}else a[re].addGroupId("audio",_.AUDIO),a[re].addGroupId("text",_.SUBTITLES);else{const se=this.createLevel(x);a[re]=se,c[re]=1,i.push(se)}}),this.filterAndSortMediaOptions(i,r,s,f,m)}createLevel(e){const r=new lC(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!this.isVideoSupported(n.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(i.message),r.supportedResult=$Ee(i,[])}return r}isAudioSupported(e){return aC(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return aC(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,r,n,i,a){var c;let s=[],f=[],m=e;const x=((c=r.stats)==null?void 0:c.parsing)||{};if((n||i)&&a&&(m=m.filter(({videoCodec:M,videoRange:B,width:V,height:G})=>(!!M||!!(V&&G))&&UNt(B))),m.length===0){Promise.resolve().then(()=>{if(this.hls){let M="no level with compatible codecs found in manifest",B=M;r.levels.length&&(B=`one or more CODECS in variant not supported: ${ra(r.levels.map(G=>G.attrs.CODECS).filter((G,W,X)=>X.indexOf(G)===W))}`,this.warn(B),M+=` (${B})`);const V=new Error(M);this.hls.trigger(ke.ERROR,{type:Ln.MEDIA_ERROR,details:Qt.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:r.url,error:V,reason:B})}}),x.end=performance.now();return}r.audioTracks&&(s=r.audioTracks.filter(M=>!M.audioCodec||this.isAudioSupported(M.audioCodec)),Jle(s)),r.subtitles&&(f=r.subtitles,Jle(f));const _=m.slice(0);m.sort((M,B)=>{if(M.attrs["HDCP-LEVEL"]!==B.attrs["HDCP-LEVEL"])return(M.attrs["HDCP-LEVEL"]||"")>(B.attrs["HDCP-LEVEL"]||"")?1:-1;if(n&&M.height!==B.height)return M.height-B.height;if(M.frameRate!==B.frameRate)return M.frameRate-B.frameRate;if(M.videoRange!==B.videoRange)return bO.indexOf(M.videoRange)-bO.indexOf(B.videoRange);if(M.videoCodec!==B.videoCodec){const V=qoe(M.videoCodec),G=qoe(B.videoCodec);if(V!==G)return G-V}if(M.uri===B.uri&&M.codecSet!==B.codecSet){const V=_O(M.codecSet),G=_O(B.codecSet);if(V!==G)return G-V}return M.averageBitrate!==B.averageBitrate?M.averageBitrate-B.averageBitrate:0});let T=_[0];if(this.steering&&(m=this.steering.filterParsedLevels(m),m.length!==_.length)){for(let M=0;M<_.length;M++)if(_[M].pathwayId===m[0].pathwayId){T=_[M];break}}this._levels=m;for(let M=0;MV&&V===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=G)}break}const C=a&&!i,N=this.hls.config,R=!!(N.audioStreamController&&N.audioTrackController),D={levels:m,audioTracks:s,subtitleTracks:f,sessionData:r.sessionData,sessionKeys:r.sessionKeys,firstLevel:this._firstLevel,stats:r.stats,audio:a,video:i,altAudio:R&&!C&&s.some(M=>!!M.url)};x.end=performance.now(),this.hls.trigger(ke.MANIFEST_PARSED,D)}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 x=new Error("invalid level idx"),_=e<0;if(this.hls.trigger(ke.ERROR,{type:Ln.OTHER_ERROR,details:Qt.LEVEL_SWITCH_ERROR,level:e,fatal:_,error:x,reason:x.message}),_)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],s=c.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=c,n===e&&i&&a===s)return;this.log(`Switching to level ${e} (${c.height?c.height+"p ":""}${c.videoRange?c.videoRange+" ":""}${c.codecSet?c.codecSet+" ":""}@${c.bitrate})${s?" with Pathway "+s:""} from level ${n}${a?" with Pathway "+a:""}`);const f={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(ke.LEVEL_SWITCHING,f);const m=c.details;if(!m||m.live){const x=this.switchParams(c.uri,i==null?void 0:i.details,m);this.loadPlaylist(x)}}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===Vi.LEVEL&&r.context.level===this.level&&this.checkRetry(r)}onFragBuffered(e,{frag:r}){if(r!==void 0&&r.type===Sn.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 s;this.warn(`Invalid level index ${i}`),(s=r.deliveryDirectives)!=null&&s.skip&&(a.deltaUpdateFailed=!0);return}if(c===this.currentLevel||r.withoutMultiVariant){c.fragmentError===0&&(c.loadError=0);let f=c.details;f===r.details&&f.advanced&&(f=void 0),this.playlistLoaded(i,r,f)}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,s=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:""}${s&&c.live?" age "+s.toFixed(1)+(c.type&&" "+c.type||""):""} ${n}`),this.hls.trigger(ke.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){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(s=>s.level=-1)),!1));l2e(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(ke.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(ke.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}function Jle(t){const e={};t.forEach(r=>{const n=r.groupId||"";r.id=e[n]=e[n]||0,e[n]++})}function nAe(){return self.SourceBuffer||self.WebKitSourceBuffer}function iAe(){if(!Qy())return!1;const e=nAe();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function XOt(){if(!iAe())return!1;const t=Qy();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(oC(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(oC(e,"audio"))))}function QOt(){var t;const e=nAe();return typeof(e==null||(t=e.prototype)==null?void 0:t.changeType)=="function"}const JOt=100;class eMt extends EW{constructor(e,r,n){super(e,r,n,"stream-controller",Sn.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,a=i?i.currentTime:null;if(a===null||!fn(a)||(this.log(`Media seeked to ${a.toFixed(3)}`),!this.getBufferedFrag(a)))return;const c=this.getFwdBufferInfoAtPos(i,a,Sn.MAIN,0);if(c===null||c.len===0){this.warn(`Main forward buffer length at ${a} on "seeked" event ${c?c.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.on(ke.LEVEL_LOADING,this.onLevelLoading,this),e.on(ke.LEVEL_LOADED,this.onLevelLoaded,this),e.on(ke.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(ke.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(ke.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(ke.BUFFER_CREATED,this.onBufferCreated,this),e.on(ke.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(ke.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(ke.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(ke.MANIFEST_PARSED,this.onManifestParsed,this),e.off(ke.LEVEL_LOADED,this.onLevelLoaded,this),e.off(ke.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(ke.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(ke.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(ke.BUFFER_CREATED,this.onBufferCreated,this),e.off(ke.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(ke.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(ke.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(JOt),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.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n),this.state=br.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=r?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=br.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case br.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=br.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=br.IDLE;break}break}case br.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===br.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),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],s=this.getMainFwdBufferInfo();if(s===null)return;const f=this.getLevelDetails();if(f&&this._streamEnded(s,f)){const N={};this.altAudio===2&&(N.type="video"),this.hls.trigger(ke.BUFFER_EOS,N),this.state=br.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 m=c.details;if(!m||this.state===br.WAITING_LEVEL||this.waitForLive(c)){this.level=a,this.state=br.WAITING_LEVEL,this.startFragRequested=!1;return}const x=s.len,_=this.getMaxBufferLength(c.maxBitrate);if(x>=_)return;this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=null);const T=this.backtrackFragment?this.backtrackFragment.start:s.end;let E=this.getNextFragment(T,m);if(this.couldBacktrack&&!this.fragPrevious&&E&&To(E)&&this.fragmentTracker.getState(E)!==sl.OK){var C;const R=((C=this.backtrackFragment)!=null?C:E).sn-m.startSN,D=m.fragments[R-1];D&&E.cc===D.cc&&(E=D,this.fragmentTracker.removeFragment(D))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=null);if(E&&this.isLoopLoading(E,T)){if(!E.gap){const R=this.audioOnly&&!this.altAudio?Js.AUDIO:Js.VIDEO,D=(R===Js.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;D&&this.afterBufferFlushed(D,R,Sn.MAIN)}E=this.getNextFragmentLoopLoading(E,m,s,Sn.MAIN,_)}E&&(this.exceedsMaxBuffer(s,_,E)||(E.initSegment&&!E.initSegment.data&&!this.bitrateTest&&(E=E.initSegment),this.loadFragment(E,c,T)))}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);i===sl.NOT_LOADED||i===sl.PARTIAL?To(e)?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._loadInitSegment(e,r):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Sn.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:e,media:r}=this;if(r!=null&&r.readyState){let n;const i=this.getAppendedFrag(r.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const a=this.getLevelDetails();if(a!=null&&a.live){const s=this.getMainFwdBufferInfo();if(!s||s.len=c-r.maxFragLookUpTolerance&&a<=s;if(i!==null&&n.duration>i&&(a{this.hls&&this.hls.trigger(ke.AUDIO_TRACK_SWITCHED,r)}),n.trigger(ke.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}n.trigger(ke.AUDIO_TRACK_SWITCHED,r)}}onAudioTrackSwitched(e,r){const n=wO(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?2:0,this.tick()}onBufferCreated(e,r){const n=r.tracks;let i,a,c=!1;for(const s in n){const f=n[s];if(f.id==="main"){if(a=s,i=f,s==="video"){const m=n[s];m&&(this.videoBuffer=m.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===Sn.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===br.PARSED&&(this.state=br.IDLE);return}const s=i?i.stats:n.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),To(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,i)}const c=this.media;c&&(!this._hasEnoughToStart&&vi.getBuffered(c).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),a&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,r){var n;if(r.fatal){this.state=br.ERROR;return}switch(r.details){case Qt.FRAG_GAP:case Qt.FRAG_PARSING_ERROR:case Qt.FRAG_DECRYPT_ERROR:case Qt.FRAG_LOAD_ERROR:case Qt.FRAG_LOAD_TIMEOUT:case Qt.KEY_LOAD_ERROR:case Qt.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Sn.MAIN,r);break;case Qt.LEVEL_LOAD_ERROR:case Qt.LEVEL_LOAD_TIMEOUT:case Qt.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===br.WAITING_LEVEL&&((n=r.context)==null?void 0:n.type)===Vi.LEVEL&&(this.state=br.IDLE);break;case Qt.BUFFER_ADD_CODEC_ERROR:case Qt.BUFFER_APPEND_ERROR:if(r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&this.resetLoadingState();break;case Qt.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 Qt.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onFragLoadEmergencyAborted(){this.state=br.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:r}){if(r!==Js.AUDIO||!this.altAudio){const n=(r===Js.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;n&&(this.afterBufferFlushed(n,r,Sn.MAIN),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&&(f{const{hls:i}=this,a=n==null?void 0:n.frag;if(!a||this.fragContextChanged(a))return;r.fragmentError=0,this.state=br.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(ke.FRAG_LOADED,n),a.bitrateTest=!1}).catch(n=>{this.state===br.STOPPED||this.state===br.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:s,part:f,level:m}=c,{video:x,text:_,id3:T,initSegment:E}=i,{details:C}=m,N=this.altAudio?void 0:i.audio;if(this.fragContextChanged(s)){this.fragmentTracker.removeFragment(s);return}if(this.state=br.PARSING,E){const R=E.tracks;if(R){const V=s.initSegment||s;if(this.unhandledEncryptionError(E,s))return;this._bufferInitSegment(m,R,V,a),n.trigger(ke.FRAG_PARSING_INIT_SEGMENT,{frag:V,id:r,tracks:R})}const D=E.initPTS,M=E.timescale,B=this.initPTS[s.cc];if(fn(D)&&(!B||B.baseTime!==D||B.timescale!==M)){const V=E.trackId;this.initPTS[s.cc]={baseTime:D,timescale:M,trackId:V},n.trigger(ke.INIT_PTS_FOUND,{frag:s,id:r,initPTS:D,timescale:M,trackId:V})}}if(x&&C){N&&x.type==="audiovideo"&&this.logMuxedErr(s);const R=C.fragments[s.sn-1-C.startSN],D=s.sn===C.startSN,M=!R||s.cc>R.cc;if(i.independent!==!1){const{startPTS:B,endPTS:V,startDTS:G,endDTS:W}=x;if(f)f.elementaryStreams[x.type]={startPTS:B,endPTS:V,startDTS:G,endDTS:W};else if(x.firstKeyFrame&&x.independent&&a.id===1&&!M&&(this.couldBacktrack=!0),x.dropped&&x.independent){const X=this.getMainFwdBufferInfo(),Q=(X?X.end:this.getLoadPosition())+this.config.maxBufferHole,re=x.firstKeyFramePTS?x.firstKeyFramePTS:B;if(!D&&QrL&&(s.gap=!0);s.setElementaryStreamInfo(x.type,B,V,G,W),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(x,s,f,a,D||M)}else if(D||M)s.gap=!0;else{this.backtrack(s);return}}if(N){const{startPTS:R,endPTS:D,startDTS:M,endDTS:B}=N;f&&(f.elementaryStreams[Js.AUDIO]={startPTS:R,endPTS:D,startDTS:M,endDTS:B}),s.setElementaryStreamInfo(Js.AUDIO,R,D,M,B),this.bufferFragmentData(N,s,f,a)}if(C&&T!=null&&T.samples.length){const R={id:r,frag:s,details:C,samples:T.samples};n.trigger(ke.FRAG_PARSING_METADATA,R)}if(C&&_){const R={id:r,frag:s,details:C,samples:_.samples};n.trigger(ke.FRAG_PARSING_USERDATA,R)}}logMuxedErr(e){this.warn(`${To(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,r,n,i){if(this.state!==br.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:s}=r;if(a){const m=e.audioCodec;let x=YR(a.codec,m);x==="mp4a"&&(x="mp4a.40.5");const _=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){x&&(x.indexOf("mp4a.40.5")!==-1?x="mp4a.40.2":x="mp4a.40.5");const T=a.metadata;T&&"channelCount"in T&&(T.channelCount||1)!==1&&_.indexOf("firefox")===-1&&(x="mp4a.40.5")}x&&x.indexOf("mp4a.40.5")!==-1&&_.indexOf("android")!==-1&&a.container!=="audio/mpeg"&&(x="mp4a.40.2",this.log(`Android: force audio codec to ${x}`)),m&&m!==x&&this.log(`Swapping manifest audio codec "${m}" for "${x}"`),a.levelCodec=x,a.id=Sn.MAIN,this.log(`Init audio buffer, container:${a.container}, codecs[selected/level/parsed]=[${x||""}/${m||""}/${a.codec}]`),delete r.audiovideo}if(c){c.levelCodec=e.videoCodec,c.id=Sn.MAIN;const m=c.codec;if((m==null?void 0:m.length)===4)switch(m){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||""}/${m}]${c.codec!==m?" parsed-corrected="+c.codec:""}${c.supplemental?" supplemental="+c.supplemental:""}`),delete r.audiovideo}s&&(this.log(`Init audiovideo buffer, container:${s.container}, codecs[level/parsed]=[${e.codecs}/${s.codec}]`),delete r.video,delete r.audio);const f=Object.keys(r);if(f.length){if(this.hls.trigger(ke.BUFFER_CODECS,r),!this.hls)return;f.forEach(m=>{const _=r[m].initSegment;_!=null&&_.byteLength&&this.hls.trigger(ke.BUFFER_APPENDING,{type:m,data:_,frag:n,part:null,chunkMeta:i,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Sn.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=br.IDLE}checkFragmentChanged(){const e=this.media;let r=null;if(e&&e.readyState>1&&e.seeking===!1){const n=e.currentTime;if(vi.isBuffered(e,n)?r=this.getAppendedFrag(n):vi.isBuffered(e,n+.1)&&(r=this.getAppendedFrag(n+.1)),r){this.backtrackFragment=null;const i=this.fragPlaying,a=r.level;(!i||r.sn!==i.sn||i.level!==a)&&(this.fragPlaying=r,this.hls.trigger(ke.FRAG_CHANGED,{frag:r}),(!i||i.level!==a)&&this.hls.trigger(ke.LEVEL_SWITCHED,{level:a}))}}}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 fn(r)?this.getAppendedFrag(r):null}get currentProgramDateTime(){var e;const r=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(fn(r)){const n=this.getLevelDetails(),i=this.currentFrag||(n?D0(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 tMt extends ah{constructor(e,r){super("key-loader",r),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const n in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[n].loader;if(i){var r;if(e&&e!==((r=i.context)==null?void 0:r.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[e];(r.mediaKeySessionContext||r.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[e].loader;r&&r.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,r=Qt.KEY_LOAD_ERROR,n,i,a){return new sm({type:Ln.NETWORK_ERROR,details:r,fatal:!1,frag:e,response:a,error:n,networkDetails:i})}loadClear(e,r,n){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(r.length)for(let i=0,a=r.length;i{if(!this.emeController)return;c.setKeyFormat(s);const f=XR(s);if(f)return this.emeController.getKeySystemAccess([f])})}if(this.config.requireKeySystemAccessOnStart){const i=Q2(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(r=>this.loadInternal(e,r)):this.loadInternal(e)}loadInternal(e,r){var n,i;r&&e.setKeyFormat(r);const a=e.decryptdata;if(!a){const m=new Error(r?`Expected frag.decryptdata to be defined after setting format ${r}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,Qt.KEY_LOAD_ERROR,m))}const c=a.uri;if(!c)return Promise.reject(this.createKeyLoadError(e,Qt.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${c}"`)));const s=b$(a);let f=this.keyIdToKeyInfo[s];if((n=f)!=null&&n.decryptdata.key)return a.key=f.decryptdata.key,Promise.resolve({frag:e,keyInfo:f});if(this.emeController&&(i=f)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(f.decryptdata)){case"usable":case"usable-in-future":return f.keyLoadPromise.then(x=>{const{keyInfo:_}=x;return a.key=_.decryptdata.key,{frag:e,keyInfo:_}})}switch(this.log(`${this.keyIdToKeyInfo[s]?"Rel":"L"}oading${a.keyId?" keyId: "+Vl(a.keyId):""} URI: ${a.uri} from ${e.type} ${e.level}`),f=this.keyIdToKeyInfo[s]={decryptdata:a,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},a.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return a.keyFormat==="identity"?this.loadKeyHTTP(f,e):this.loadKeyEME(f,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(f,e);default:return Promise.reject(this.createKeyLoadError(e,Qt.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${a.method}"`)))}}loadKeyEME(e,r){const n={frag:r,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=r.initSegment)!=null&&i.data){const c=vNt(r.initSegment.data);if(c.length){let s=c[0];s.some(f=>f!==0)?(this.log(`Using keyId found in init segment ${Vl(s)}`),Dy.setKeyIdForUri(e.decryptdata.uri,s)):(s=Dy.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Vl(s)}`)),e.decryptdata.keyId=s}}if(!e.decryptdata.keyId&&!To(r))return Promise.resolve(n);const a=this.emeController.loadKey(n);return(e.keyLoadPromise=a.then(c=>(e.mediaKeySessionContext=c,n))).catch(c=>{throw e.keyLoadPromise=null,"data"in c&&(c.data.frag=r),c})}return Promise.resolve(n)}loadKeyHTTP(e,r){const n=this.config,i=n.loader,a=new i(n);return r.keyLoader=e.loader=a,e.keyLoadPromise=new Promise((c,s)=>{const f={keyInfo:e,frag:r,responseType:"arraybuffer",url:e.decryptdata.uri},m=n.keyLoadPolicy.default,x={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},_={onSuccess:(T,E,C,N)=>{const{frag:R,keyInfo:D}=C,M=b$(D.decryptdata);if(!R.decryptdata||D!==this.keyIdToKeyInfo[M])return s(this.createKeyLoadError(R,Qt.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),N));D.decryptdata.key=R.decryptdata.key=new Uint8Array(T.data),R.keyLoader=null,D.loader=null,c({frag:R,keyInfo:D})},onError:(T,E,C,N)=>{this.resetLoader(E),s(this.createKeyLoadError(r,Qt.KEY_LOAD_ERROR,new Error(`HTTP Error ${T.code} loading key ${T.text}`),C,Bs({url:f.url,data:void 0},T)))},onTimeout:(T,E,C)=>{this.resetLoader(E),s(this.createKeyLoadError(r,Qt.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),C))},onAbort:(T,E,C)=>{this.resetLoader(E),s(this.createKeyLoadError(r,Qt.INTERNAL_ABORTED,new Error("key loading aborted"),C))}};a.load(f,x,_)})}resetLoader(e){const{frag:r,keyInfo:n,url:i}=e,a=n.loader;r.keyLoader===a&&(r.keyLoader=null,n.loader=null);const c=b$(n.decryptdata)||i;delete this.keyIdToKeyInfo[c],a&&a.destroy()}}function b$(t){if(t.keyFormat!==ql.FAIRPLAY){const e=t.keyId;if(e)return Vl(e)}return t.uri}function ece(t){const{type:e}=t;switch(e){case Vi.AUDIO_TRACK:return Sn.AUDIO;case Vi.SUBTITLE_TRACK:return Sn.SUBTITLE;default:return Sn.MAIN}}function w$(t,e){let r=t.url;return(r===void 0||r.indexOf("data:")===0)&&(r=e.url),r}class rMt{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(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.on(ke.LEVEL_LOADING,this.onLevelLoading,this),e.on(ke.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(ke.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(ke.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(ke.MANIFEST_LOADING,this.onManifestLoading,this),e.off(ke.LEVEL_LOADING,this.onLevelLoading,this),e.off(ke.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(ke.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(ke.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:Vi.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,r){const{id:n,level:i,pathwayId:a,url:c,deliveryDirectives:s,levelInfo:f}=r;this.load({id:n,level:i,pathwayId:a,responseType:"text",type:Vi.LEVEL,url:c,deliveryDirectives:s,levelOrTrack:f})}onAudioTrackLoading(e,r){const{id:n,groupId:i,url:a,deliveryDirectives:c,track:s}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:Vi.AUDIO_TRACK,url:a,deliveryDirectives:c,levelOrTrack:s})}onSubtitleTrackLoading(e,r){const{id:n,groupId:i,url:a,deliveryDirectives:c,track:s}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:Vi.SUBTITLE_TRACK,url:a,deliveryDirectives:c,levelOrTrack:s})}onLevelsUpdated(e,r){const n=this.loaders[Vi.LEVEL];if(n){const i=n.context;i&&!r.levels.some(a=>a===i.levelOrTrack)&&(n.abort(),delete this.loaders[Vi.LEVEL])}}load(e){var r;const n=this.hls.config;let i=this.getInternalLoader(e);if(i){const m=this.hls.logger,x=i.context;if(x&&x.levelOrTrack===e.levelOrTrack&&(x.url===e.url||x.deliveryDirectives&&!e.deliveryDirectives)){x.url===e.url?m.log(`[playlist-loader]: ignore ${e.url} ongoing request`):m.log(`[playlist-loader]: ignore ${e.url} in favor of ${x.url}`);return}m.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let a;if(e.type===Vi.MANIFEST?a=n.manifestLoadPolicy.default:a=Ys({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),fn((r=e.deliveryDirectives)==null?void 0:r.part)){let m;if(e.type===Vi.LEVEL&&e.level!==null?m=this.hls.levels[e.level].details:e.type===Vi.AUDIO_TRACK&&e.id!==null?m=this.hls.audioTracks[e.id].details:e.type===Vi.SUBTITLE_TRACK&&e.id!==null&&(m=this.hls.subtitleTracks[e.id].details),m){const x=m.partTarget,_=m.targetduration;if(x&&_){const T=Math.max(x*3,_*.8)*1e3;a=Ys({},a,{maxTimeToFirstByteMs:Math.min(T,a.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(T,a.maxTimeToFirstByteMs)})}}}const c=a.errorRetry||a.timeoutRetry||{},s={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:c.maxNumRetry||0,retryDelay:c.retryDelayMs||0,maxRetryDelay:c.maxRetryDelayMs||0},f={onSuccess:(m,x,_,T)=>{const E=this.getInternalLoader(_);this.resetInternalLoader(_.type);const C=m.data;x.parsing.start=performance.now(),Wf.isMediaPlaylist(C)||_.type!==Vi.MANIFEST?this.handleTrackOrLevelPlaylist(m,x,_,T||null,E):this.handleMasterPlaylist(m,x,_,T)},onError:(m,x,_,T)=>{this.handleNetworkError(x,_,!1,m,T)},onTimeout:(m,x,_)=>{this.handleNetworkError(x,_,!0,void 0,m)}};i.load(e,s,f)}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,s=w$(e,n),f=Wf.parseMasterPlaylist(c,s);if(f.playlistParsingError){r.parsing.end=performance.now(),this.handleManifestParsingError(e,n,f.playlistParsingError,i,r);return}const{contentSteering:m,levels:x,sessionData:_,sessionKeys:T,startTimeOffset:E,variableList:C}=f;this.variableList=C,x.forEach(M=>{const{unknownCodecs:B}=M;if(B){const{preferManagedMediaSource:V}=this.hls.config;let{audioCodec:G,videoCodec:W}=M;for(let X=B.length;X--;){const Q=B[X];aC(Q,"audio",V)?(M.audioCodec=G=G?`${G},${Q}`:Q,tS.audio[G.substring(0,4)]=2,B.splice(X,1)):aC(Q,"video",V)&&(M.videoCodec=W=W?`${W},${Q}`:Q,tS.video[W.substring(0,4)]=2,B.splice(X,1))}}});const{AUDIO:N=[],SUBTITLES:R,"CLOSED-CAPTIONS":D}=Wf.parseMasterPlaylistMedia(c,s,f);N.length&&!N.some(B=>!B.url)&&x[0].audioCodec&&!x[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),N.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Ka({}),bitrate:0,url:""})),a.trigger(ke.MANIFEST_LOADED,{levels:x,audioTracks:N,subtitles:R,captions:D,contentSteering:m,url:s,stats:r,networkDetails:i,sessionData:_,sessionKeys:T,startTimeOffset:E,variableList:C})}handleTrackOrLevelPlaylist(e,r,n,i,a){const c=this.hls,{id:s,level:f,type:m}=n,x=w$(e,n),_=fn(f)?f:fn(s)?s:0,T=ece(n),E=Wf.parseLevelPlaylist(e.data,x,_,T,0,this.variableList);if(m===Vi.MANIFEST){const C={attrs:new Ka({}),bitrate:0,details:E,name:"",url:x};E.requestScheduled=r.loading.start+s2e(E,0),c.trigger(ke.MANIFEST_LOADED,{levels:[C],audioTracks:[],url:x,stats:r,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}r.parsing.end=performance.now(),n.levelDetails=E,this.handlePlaylistLoaded(E,e,r,n,i,a)}handleManifestParsingError(e,r,n,i,a){this.hls.trigger(ke.ERROR,{type:Ln.NETWORK_ERROR,details:Qt.MANIFEST_PARSING_ERROR,fatal:r.type===Vi.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===Vi.LEVEL?c+=`: ${e.level} id: ${e.id}`:(e.type===Vi.AUDIO_TRACK||e.type===Vi.SUBTITLE_TRACK)&&(c+=` id: ${e.id} group-id: "${e.groupId}"`);const s=new Error(c);this.hls.logger.warn(`[playlist-loader]: ${c}`);let f=Qt.UNKNOWN,m=!1;const x=this.getInternalLoader(e);switch(e.type){case Vi.MANIFEST:f=n?Qt.MANIFEST_LOAD_TIMEOUT:Qt.MANIFEST_LOAD_ERROR,m=!0;break;case Vi.LEVEL:f=n?Qt.LEVEL_LOAD_TIMEOUT:Qt.LEVEL_LOAD_ERROR,m=!1;break;case Vi.AUDIO_TRACK:f=n?Qt.AUDIO_TRACK_LOAD_TIMEOUT:Qt.AUDIO_TRACK_LOAD_ERROR,m=!1;break;case Vi.SUBTITLE_TRACK:f=n?Qt.SUBTITLE_TRACK_LOAD_TIMEOUT:Qt.SUBTITLE_LOAD_ERROR,m=!1;break}x&&this.resetInternalLoader(e.type);const _={type:Ln.NETWORK_ERROR,details:f,fatal:m,url:e.url,loader:x,context:e,error:s,networkDetails:r,stats:a};if(i){const T=(r==null?void 0:r.url)||e.url;_.response=Bs({url:T,data:void 0},i)}this.hls.trigger(ke.ERROR,_)}handlePlaylistLoaded(e,r,n,i,a,c){const s=this.hls,{type:f,level:m,levelOrTrack:x,id:_,groupId:T,deliveryDirectives:E}=i,C=w$(r,i),N=ece(i);let R=typeof i.level=="number"&&N===Sn.MAIN?m:void 0;const D=e.playlistParsingError;if(D){if(this.hls.logger.warn(`${D} ${e.url}`),!s.config.ignorePlaylistParsingErrors){s.trigger(ke.ERROR,{type:Ln.NETWORK_ERROR,details:Qt.LEVEL_PARSING_ERROR,fatal:!1,url:C,error:D,reason:D.message,response:r,context:i,level:R,parent:N,networkDetails:a,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){const M=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(ke.ERROR,{type:Ln.NETWORK_ERROR,details:Qt.LEVEL_EMPTY_ERROR,fatal:!1,url:C,error:M,reason:M.message,response:r,context:i,level:R,parent:N,networkDetails:a,stats:n});return}switch(e.live&&c&&(c.getCacheAge&&(e.ageHeader=c.getCacheAge()||0),(!c.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),f){case Vi.MANIFEST:case Vi.LEVEL:if(R){if(!x)R=0;else if(x!==s.levels[R]){const M=s.levels.indexOf(x);M>-1&&(R=M)}}s.trigger(ke.LEVEL_LOADED,{details:e,levelInfo:x||s.levels[0],level:R||0,id:_||0,stats:n,networkDetails:a,deliveryDirectives:E,withoutMultiVariant:f===Vi.MANIFEST});break;case Vi.AUDIO_TRACK:s.trigger(ke.AUDIO_TRACK_LOADED,{details:e,track:x,id:_||0,groupId:T||"",stats:n,networkDetails:a,deliveryDirectives:E});break;case Vi.SUBTITLE_TRACK:s.trigger(ke.SUBTITLE_TRACK_LOADED,{details:e,track:x,id:_||0,groupId:T||"",stats:n,networkDetails:a,deliveryDirectives:E});break}}}class Vf{static get version(){return cC}static isMSESupported(){return iAe()}static isSupported(){return XOt()}static getMediaSource(){return Qy()}static get Events(){return ke}static get MetadataSchema(){return Zu}static get ErrorTypes(){return Ln}static get ErrorDetails(){return Qt}static get DefaultConfig(){return Vf.defaultConfig?Vf.defaultConfig:BOt}static set DefaultConfig(e){Vf.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new AW,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.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const r=this.logger=lNt(e.debug||!1,"Hls instance",e.assetPlayerId),n=this.config=$Ot(Vf.DefaultConfig,e,r);this.userConfig=e,n.progressive&&UOt(n,r);const{abrController:i,bufferController:a,capLevelController:c,errorController:s,fpsController:f}=n,m=new s(this),x=this.abrController=new i(this),_=new nRt(this),T=n.interstitialsController,E=T?this.interstitialsController=new T(this,Vf):null,C=this.bufferController=new a(this,_),N=this.capLevelController=new c(this),R=new f(this),D=new rMt(this),M=n.contentSteeringController,B=M?new M(this):null,V=this.levelController=new ZOt(this,B),G=new KOt(this),W=new tMt(this.config,this.logger),X=this.streamController=new eMt(this,_,W),Q=this.gapController=new HOt(this,_);N.setStreamController(X),R.setStreamController(X);const re=[D,V,X];E&&re.splice(1,0,E),B&&re.splice(1,0,B),this.networkControllers=re;const se=[x,C,Q,N,R,G,_];this.audioTrackController=this.createController(n.audioTrackController,re);const ue=n.audioStreamController;ue&&re.push(this.audioStreamController=new ue(this,_,W)),this.subtitleTrackController=this.createController(n.subtitleTrackController,re);const _e=n.subtitleStreamController;_e&&re.push(this.subtititleStreamController=new _e(this,_,W)),this.createController(n.timelineController,se),W.emeController=this.emeController=this.createController(n.emeController,se),this.cmcdController=this.createController(n.cmcdController,se),this.latencyController=this.createController(YOt,se),this.coreComponents=se,re.push(m);const Se=m.onErrorOut;typeof Se=="function"&&this.on(ke.ERROR,Se,m),this.on(ke.MANIFEST_LOADED,D.onManifestLoaded,D)}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===ke.ERROR;this.trigger(ke.ERROR,{type:Ln.OTHER_ERROR,details:Qt.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(ke.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;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(ke.ERROR,{type:Ln.OTHER_ERROR,details:Qt.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(ke.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(ke.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(ke.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const r=this.media,n=this._url,i=this._url=mW.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),r&&n&&(n!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(ke.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={[Sn.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Sn.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Sn.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,r=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),r&&this.startLoad(r))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=HDt()),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=!!e;r!==this.config.capLevelToPlayerSize&&(r?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}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){$Nt(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 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 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(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}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(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,r=this.allAudioTracks){const n=qEe(r);return UEe(e,n,navigator.mediaCapabilities)}}Vf.defaultConfig=void 0;const nMt=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function J2(t){return!!t&&nMt.test(t)&&!/\.mp4($|\?)/i.test(t)}function iMt(t){const e=t.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return e?{libraryId:e[1],videoId:e[2]}:null}function sMt(t,e){if(!t)return null;const r=iMt(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 aMt(t){const e=t.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return e?e[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const tce=P.forwardRef(function({sourceUrl:e,thumbnailUrl:r,autoPlay:n,muted:i,loop:a,playsInline:c=!0,...s},f){const m=P.useRef(null),[x,_]=P.useState(null),T=P.useMemo(()=>sMt(e,{autoplay:!!n,muted:!!i,loop:!!a}),[e,n,i,a]);P.useEffect(()=>{let C=!1;if(!e){_(null);return}if(!J2(e)){_(e);return}if(!T){_(null);return}return _(null),fetch(T).then(async N=>{if(!N.ok)throw new Error(`Failed to load Bunny embed (${N.status})`);const R=await N.text();return aMt(R)}).then(N=>{C||_(N)}).catch(()=>{C||_(null)}),()=>{C=!0}},[T,e]),P.useEffect(()=>{const C=m.current;if(!C||!x)return;let N=null;const R=()=>{if(!n)return;const M=C.play();M&&M.catch(()=>{})};if(C.muted=!!i,C.loop=!!a,x.endsWith(".m3u8")){if(C.canPlayType("application/vnd.apple.mpegurl")){C.src=x;const M=()=>R();return C.addEventListener("loadedmetadata",M),()=>{C.removeEventListener("loadedmetadata",M),C.removeAttribute("src"),C.load()}}return Vf.isSupported()?(N=new Vf({enableWorker:!0,lowLatencyMode:!0}),N.loadSource(x),N.attachMedia(C),N.on(Vf.Events.MANIFEST_PARSED,R),()=>{N==null||N.destroy(),C.removeAttribute("src"),C.load()}):void 0}C.src=x;const D=()=>R();return C.addEventListener("loadedmetadata",D),()=>{C.removeEventListener("loadedmetadata",D),C.removeAttribute("src"),C.load()}},[n,a,i,x]),P.useEffect(()=>{const C=m.current;if(C){if(C.muted=!!i,C.loop=!!a,n&&x){const N=C.play();N&&N.catch(()=>{});return}C.pause()}},[n,a,i,x]);const E=C=>{if(m.current=C,typeof f=="function"){f(C);return}f&&(f.current=C)};return o.jsx("video",{ref:E,poster:r||void 0,autoPlay:n,muted:i,loop:a,playsInline:c,preload:"metadata",...s})}),oMt={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 lMt(){try{let t=localStorage.getItem("vg_visitor_token");return t||(t=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",t)),t}catch{return null}}function rce(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 cMt({config:t,appSlug:e="video_greeter",preview:r=!1,embedded:n=!1}){const[i,a]=P.useState(!1),[c,s]=P.useState(!1),[f,m]=P.useState(!0),[x,_]=P.useState(!1),[T,E]=P.useState("portrait"),[C,N]=P.useState(!1),[R,D]=P.useState(!1),[M,B]=P.useState({name:"",email:"",phone:""}),[V,G]=P.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),W=P.useRef(null),X=P.useRef(null),Q=P.useRef(!1),re=async(lr,yr)=>{if(!r)try{await Le.from("widget_events").insert({user_id:t.user_id,app_slug:e,event_type:lr,visitor_token:lMt(),page_url:typeof window<"u"?window.location.href:null,metadata:yr||{}})}catch{}};P.useEffect(()=>{if(x)return;const lr=typeof window<"u"?window.location.pathname:"/",yr=t.targeting||{mode:"all"};if(yr.mode==="include"&&!rce(yr.include,lr)||yr.mode==="exclude"&&rce(yr.exclude,lr))return;const tr=t.trigger||{type:"immediate"};if(tr.type==="immediate"||r){a(!0);return}if(tr.type==="delay"){const yn=(tr.value||3)*1e3,lt=setTimeout(()=>a(!0),yn);return()=>clearTimeout(lt)}if(tr.type==="scroll"){const yn=(tr.value||25)/100,lt=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=yn&&(a(!0),window.removeEventListener("scroll",lt))};return window.addEventListener("scroll",lt,{passive:!0}),()=>window.removeEventListener("scroll",lt)}if(tr.type==="exit_intent"){const yn=lt=>{lt.clientY<=0&&a(!0)};return document.addEventListener("mouseleave",yn),()=>document.removeEventListener("mouseleave",yn)}},[x,t.targeting,t.trigger,r]),P.useEffect(()=>{i&&!Q.current&&(Q.current=!0,re("impression"))},[i]),P.useEffect(()=>{if(c&&X.current&&!J2(t.video_url)){X.current.currentTime=0,X.current.muted=!1,m(!1);const lr=X.current.play();lr&&lr.catch(()=>{})}else c&&J2(t.video_url)&&m(!1)},[c,t.video_url]),P.useEffect(()=>{if(!t.thumbnail_url)return;let lr=!1;const yr=new Image;return yr.onload=()=>{lr||E(yr.naturalWidth>yr.naturalHeight?"landscape":"portrait")},yr.src=t.thumbnail_url,()=>{lr=!0}},[t.thumbnail_url]),P.useEffect(()=>{const lr=()=>{G({width:window.innerWidth,height:window.innerHeight})};return lr(),window.addEventListener("resize",lr),()=>window.removeEventListener("resize",lr)},[]);const se=()=>{s(!0),re("expand")},ue=lr=>{lr.stopPropagation(),_(!0),s(!1)},_e=lr=>{re("cta_click",{cta_id:lr.id,label:lr.label,url:lr.url})},Se=async lr=>{if(lr.preventDefault(),r){N(!0);return}if(!(!M.email||!M.name)){D(!0);try{const{error:yr}=await Le.functions.invoke("submit-widget-lead",{body:{user_id:t.user_id,app_slug:e,name:M.name,email:M.email,phone:M.phone||void 0,page_url:window.location.href}});if(yr)throw yr;re("lead_capture",{email:M.email}),N(!0)}catch(yr){console.error("lead submit failed",yr)}finally{D(!1)}}};if(!i||x||!t.video_url&&!t.video_embed_url)return null;const ve=oMt[T][t.size||"md"],Oe=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",Ae=t.shape==="circle"?"rounded-full":"rounded-2xl",we=r?T==="landscape"?"w-[280px]":"w-[220px]":T==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",ge=T==="landscape"?"aspect-video":"aspect-[9/16]",Ne=t.agent||{},Ie=t.lead_form_fields||["name","email","phone"],Te=!!(t.show_socials&&(Ne.instagram_url||Ne.facebook_url||Ne.linkedin_url)),be=108+(t.ctas||[]).length*48+(t.lead_form_enabled&&!C?72+Ie.length*42:0)+(C?40:0)+(Te?34:0),We=Math.max(300,V.height-32),rt=Math.max(220,V.width-32),at=Math.max(150,We-be),Et=Math.floor(T==="landscape"?at*(16/9):at*(9/16)),_t=T==="landscape"?Math.max(220,Math.min(420,rt,Et)):Math.max(180,Math.min(340,rt,Et)),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":`${we} 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`,mt=n?{width:`${_t}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Pt=n?"p-3 space-y-2.5":"p-4 space-y-3",er=n?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",wt=n?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",or=n?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",Sr=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",nn=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 o.jsx("div",{"data-vg-widget":!0,"data-expanded":c?"true":"false",className:`${Oe} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:c?o.jsxs("div",{className:Vt,style:mt,children:[o.jsxs("div",{className:`relative bg-black ${ge}`,children:[J2(t.video_url)?o.jsx(tce,{ref:X,sourceUrl:t.video_url,thumbnailUrl:t.thumbnail_url,autoPlay:!0,muted:f,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:lr=>{const{videoWidth:yr,videoHeight:tr}=lr.currentTarget;yr&&tr&&E(yr>tr?"landscape":"portrait")},onEnded:()=>re("watch_complete")},`expanded-${t.video_url}-${t.thumbnail_url||"no-thumb"}-${c?"on":"off"}`):o.jsx("video",{ref:X,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:()=>re("watch_complete"),onLoadedMetadata:lr=>{const{videoWidth:yr,videoHeight:tr}=lr.currentTarget;yr&&tr&&E(yr>tr?"landscape":"portrait")}}),o.jsx("button",{onClick:()=>{X.current&&(X.current.muted=!X.current.muted,m(X.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:f?o.jsx(ELe,{className:"w-4 h-4"}):o.jsx(TLe,{className:"w-4 h-4"})}),o.jsx("button",{onClick:()=>s(!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:o.jsx(Ks,{className:"w-4 h-4"})})]}),o.jsxs("div",{className:Pt,children:[o.jsxs("div",{className:"flex items-center gap-3",children:[Ne.avatar_url&&o.jsx("img",{src:Ne.avatar_url,alt:Ne.name||"",className:er}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("p",{className:wt,children:t.greeting_title||"Glad you're here!"}),t.greeting_subtitle&&o.jsx("p",{className:or,children:t.greeting_subtitle})]})]}),(t.ctas||[]).length>0&&o.jsx("div",{className:"space-y-2",children:(t.ctas||[]).map(lr=>{var yr;return o.jsxs("a",{href:lr.url,target:(yr=lr.url)!=null&&yr.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>_e(lr),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 ${lr.style==="secondary"?"bg-gray-100 text-gray-900 hover:bg-gray-200":"bg-gray-900 text-white hover:bg-gray-800"}`,children:[o.jsx("span",{children:lr.label}),o.jsx(cS,{className:"w-3.5 h-3.5 opacity-60"})]},lr.id)})}),t.lead_form_enabled&&!C&&o.jsxs("form",{onSubmit:Se,className:"space-y-2 pt-1",children:[Ie.includes("name")&&o.jsx("input",{type:"text",placeholder:"Name",required:!0,value:M.name,onChange:lr=>B({...M,name:lr.target.value}),className:Sr}),Ie.includes("email")&&o.jsx("input",{type:"email",placeholder:"Email",required:!0,value:M.email,onChange:lr=>B({...M,email:lr.target.value}),className:Sr}),Ie.includes("phone")&&o.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:M.phone,onChange:lr=>B({...M,phone:lr.target.value}),className:Sr}),o.jsxs("button",{type:"submit",disabled:R,className:nn,children:[o.jsx(jL,{className:"w-3.5 h-3.5"}),R?"Sending...":"Send"]})]}),C&&o.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&&(Ne.instagram_url||Ne.facebook_url||Ne.linkedin_url)&&o.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[Ne.instagram_url&&o.jsx("a",{href:Ne.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>re("cta_click",{social:"instagram"}),children:o.jsx(qhe,{className:"w-4 h-4"})}),Ne.facebook_url&&o.jsx("a",{href:Ne.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>re("cta_click",{social:"facebook"}),children:o.jsx(Uhe,{className:"w-4 h-4"})}),Ne.linkedin_url&&o.jsx("a",{href:Ne.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>re("cta_click",{social:"linkedin"}),children:o.jsx(Khe,{className:"w-4 h-4"})})]})]})]}):o.jsxs("div",{className:"relative animate-in fade-in slide-in-from-bottom-4 duration-500",children:[o.jsxs("button",{onClick:se,className:`relative ${Ae} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:ve.w,height:ve.h},"aria-label":"Play video greeting",children:[J2(t.video_url)?o.jsx(tce,{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:lr=>{const{videoWidth:yr,videoHeight:tr}=lr.currentTarget;yr&&tr&&E(yr>tr?"landscape":"portrait")}},`collapsed-${t.video_url}-${t.thumbnail_url||"no-thumb"}`):o.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:lr=>{const{videoWidth:yr,videoHeight:tr}=lr.currentTarget;yr&&tr&&E(yr>tr?"landscape":"portrait")}}),o.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none"}),o.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:o.jsx("svg",{viewBox:"0 0 24 24",className:"w-6 h-6 text-black ml-0.5",fill:"currentColor",children:o.jsx("path",{d:"M8 5v14l11-7z"})})}),o.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"})]}),o.jsx("button",{onClick:ue,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:o.jsx(Ks,{className:"w-3.5 h-3.5"})})]})})}function BW({slug:t}){const[e,r]=P.useState(null);return P.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:a}=await Le.rpc("get_public_video_greeter_config",{_slug:t});!n&&!a&&i&&r(i)})(),()=>{n=!0}},[t]),e?o.jsx(cMt,{config:e}):null}const sAe="eip_last_shown",nce="eip_visitor_token";function uMt(){try{let t=localStorage.getItem(nce);return t||(t=crypto.randomUUID(),localStorage.setItem(nce,t)),t}catch{return}}function dMt(t){try{const e=Number(localStorage.getItem(sAe)||0);return e?Date.now()-e>t*24*60*60*1e3:!0}catch{return!0}}function hMt(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 fMt({config:t,preview:e=!1,forceOpen:r=!1}){const[n,i]=P.useState(r),[a,c]=P.useState(!1),[s,f]=P.useState(!1),[m,x]=P.useState({name:"",email:"",phone:""}),_=P.useRef(!1),T=P.useRef(!1),E=async(W,X={})=>{if(!e)try{await Le.from("widget_events").insert({user_id:t.user_id,app_slug:"exit_intent",event_type:W,visitor_token:uMt(),page_url:window.location.href,metadata:X})}catch{}};P.useEffect(()=>{if(e||!hMt(t.targeting)||!dMt(t.frequency_days))return;const W=/Mobi|Android/i.test(navigator.userAgent),X={low:5,medium:15,high:30}[t.trigger_sensitivity]||15,Q=_e=>{if(!_.current){_.current=!0,i(!0);try{localStorage.setItem(sAe,String(Date.now()))}catch{}E("impression",{reason:_e})}},re=_e=>{_e.clientY<=X&&Q("mouse_leave")},se=()=>{t.enable_mobile_back&&W&&Q("back_button")};if(t.enable_mobile_back&&W){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",se)}else document.addEventListener("mouseleave",re);let ue;return t.enable_time_fallback&&(ue=window.setTimeout(()=>Q("time_fallback"),Math.max(5,t.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",re),window.removeEventListener("popstate",se),ue&&window.clearTimeout(ue)}},[t,e]),P.useEffect(()=>{n&&!T.current&&!e&&!_.current&&(T.current=!0)},[n,e]);const C=()=>{i(!1),e||E("close")},N=async W=>{if(W.preventDefault(),e){c(!0);return}if(!(!m.email||!m.name)){f(!0);try{const{error:X}=await Le.functions.invoke("submit-widget-lead",{body:{user_id:t.user_id,app_slug:"exit_intent",name:m.name,email:m.email,phone:m.phone||void 0,page_url:window.location.href}});if(X)throw X;E("lead_capture",{email:m.email}),c(!0),t.cta_url&&setTimeout(()=>{window.location.href=t.cta_url},1200)}catch(X){console.error("exit intent submit failed",X)}finally{f(!1)}}};if(!n)return null;const R=t.form_fields||["name","email"],D=t.agent||{},M=[D.first_name,D.last_name].filter(Boolean).join(" "),B=t.use_agent_photo&&D.avatar_url||t.image_url,V=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 o.jsx("div",{className:G,style:{background:e?"transparent":"rgba(0,0,0,0.6)"},children:o.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:[o.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${V}, ${S$(V,-25)})`}}),o.jsx("button",{onClick:C,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:o.jsx(Ks,{className:"w-4 h-4"})}),o.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[B&&o.jsx("img",{src:B,alt:M||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${V}33`,"--tw-ring-color":V}}),o.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${V}1A`,color:V},children:[o.jsx(Ss,{className:"w-3 h-3"}),t.offer_label]})]}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:t.headline}),o.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:t.subheadline})]}),a?o.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${V}10`,color:V},children:[o.jsx("div",{className:"text-3xl",children:"🎉"}),o.jsx("p",{className:"text-sm font-medium",style:{color:V},children:t.success_message})]}):t.form_enabled?o.jsxs("form",{onSubmit:N,className:"space-y-2.5",children:[R.includes("name")&&o.jsx("input",{type:"text",placeholder:"Your name",value:m.name,onChange:W=>x({...m,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":V},required:!0}),R.includes("email")&&o.jsx("input",{type:"email",placeholder:"you@email.com",value:m.email,onChange:W=>x({...m,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":V},required:!0}),R.includes("phone")&&o.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:m.phone,onChange:W=>x({...m,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":V}}),o.jsx("button",{type:"submit",disabled:s,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, ${V}, ${S$(V,-20)})`},children:s?"Sending...":t.cta_label}),o.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We respect your inbox. Unsubscribe anytime."})]}):o.jsx("a",{href:t.cta_url||"#",onClick:()=>E("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, ${V}, ${S$(V,-20)})`},children:t.cta_label}),M&&o.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",M]})]})]})})}function S$(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,s=r&255,f=Math.round((n-a)*i)+a,m=Math.round((n-c)*i)+c,x=Math.round((n-s)*i)+s;return"#"+(16777216+(f<<16)+(m<<8)+x).toString(16).slice(1)}catch{return t}}function zW({slug:t}){const[e,r]=P.useState(null);return P.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:a}=await Le.rpc("get_public_exit_intent_config",{_slug:t});!n&&!a&&i&&r(i)})(),()=>{n=!0}},[t]),e?o.jsx(fMt,{config:e}):null}const ice="lm_dismissed",sce="lm_visitor_token";function pMt(){try{let t=localStorage.getItem(sce);return t||(t=crypto.randomUUID(),localStorage.setItem(sce,t)),t}catch{return}}function mMt(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 gMt({config:t,preview:e=!1}){const[r,n]=P.useState(!1),[i,a]=P.useState(!1),[c,s]=P.useState(!1),[f,m]=P.useState(!1),[x,_]=P.useState({name:"",email:"",phone:""}),T=P.useRef(!1),E=async(B,V={})=>{if(!e)try{await Le.from("widget_events").insert({user_id:t.user_id,app_slug:"lead_magnet",event_type:B,visitor_token:pMt(),page_url:window.location.href,metadata:V})}catch{}};P.useEffect(()=>{if(e){n(!0);return}if(!mMt(t.targeting))return;try{if(sessionStorage.getItem(ice))return}catch{}const B=()=>{T.current||(T.current=!0,n(!0),E("impression"))};if(t.trigger_type==="immediate")B();else if(t.trigger_type==="delay"){const V=window.setTimeout(B,Math.max(0,t.trigger_value)*1e3);return()=>window.clearTimeout(V)}else if(t.trigger_type==="scroll"){const V=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(t.trigger_value||30)&&B()};return window.addEventListener("scroll",V,{passive:!0}),()=>window.removeEventListener("scroll",V)}},[t,e]);const C=()=>{n(!1);try{sessionStorage.setItem(ice,"1")}catch{}e||E("close")},N=async B=>{if(B.preventDefault(),e){s(!0);return}if(!(!x.email||!x.name)){m(!0);try{const{error:V}=await Le.functions.invoke("submit-widget-lead",{body:{user_id:t.user_id,app_slug:"lead_magnet",name:x.name,email:x.email,phone:x.phone||void 0,page_url:window.location.href}});if(V)throw V;E("lead_capture",{email:x.email}),s(!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(V){console.error("lead magnet submit failed",V)}finally{m(!1)}}};if(!r)return null;const R=t.theme_color||"#2563eb",D=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 o.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:[o.jsx("div",{className:"text-white shadow-2xl",style:{background:`linear-gradient(90deg, ${R}, ${B2(R,-20)})`},children:o.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-3 flex items-center gap-3 flex-wrap",children:[o.jsx(Yh,{className:"w-5 h-5 shrink-0"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("p",{className:"text-sm font-semibold truncate",children:t.title}),o.jsx("p",{className:"text-xs text-white/80 truncate",children:t.description})]}),o.jsx("button",{onClick:()=>{a(!0),E("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:R},children:t.download_label}),o.jsx("button",{onClick:C,className:"text-white/80 hover:text-white","aria-label":"Close",children:o.jsx(Ks,{className:"w-4 h-4"})})]})}),i&&M()]});if(!i)return o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:()=>{a(!0),E("expand")},className:`${D} 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, ${R}, ${B2(R,-20)})`,paddingBottom:"env(safe-area-inset-bottom)"},children:[o.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center text-white",children:o.jsx(u1,{className:"w-5 h-5"})}),o.jsxs("div",{className:"text-left text-white",children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wider opacity-90 font-semibold",children:t.badge_label}),o.jsx("div",{className:"text-sm font-bold leading-tight max-w-[180px] truncate",children:t.title})]}),o.jsx("button",{onClick:B=>{B.stopPropagation(),C()},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:o.jsx(Ks,{className:"w-3 h-3"})})]}),i&&M()]});return M();function M(){const B=t.form_fields||["name","email"],V=t.agent||{},G=[V.first_name,V.last_name].filter(Boolean).join(" ");return o.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:o.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:[o.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${R}, ${B2(R,-25)})`},children:[t.cover_image_url?o.jsx("img",{src:t.cover_image_url,alt:t.title,className:"w-full h-full object-cover opacity-90"}):o.jsx("div",{className:"w-full h-full flex items-center justify-center",children:o.jsx(ep,{className:"w-20 h-20 text-white/40"})}),o.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:R},children:[o.jsx(Yh,{className:"w-3 h-3"}),t.badge_label]}),o.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:o.jsx(Ks,{className:"w-4 h-4"})})]}),o.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:t.title}),o.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:t.description})]}),c?o.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${R}10`},children:[o.jsx(Xl,{className:"w-8 h-8 mx-auto",style:{color:R}}),o.jsx("p",{className:"text-sm font-medium",style:{color:R},children:t.success_message}),t.download_url&&o.jsx("a",{href:t.download_url,target:"_blank",rel:"noopener",className:"inline-block mt-2 text-xs underline",style:{color:R},children:"Click here if download didn't start"})]}):t.form_enabled?o.jsxs("form",{onSubmit:N,className:"space-y-2.5",children:[B.includes("name")&&o.jsx("input",{type:"text",placeholder:"Your name",value:x.name,onChange:W=>_({...x,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":R},required:!0}),B.includes("email")&&o.jsx("input",{type:"email",placeholder:"you@email.com",value:x.email,onChange:W=>_({...x,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":R},required:!0}),B.includes("phone")&&o.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:x.phone,onChange:W=>_({...x,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":R}}),o.jsxs("button",{type:"submit",disabled:f,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, ${R}, ${B2(R,-20)})`},children:[o.jsx(Xl,{className:"w-4 h-4"}),f?"Sending...":t.download_label]}),o.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We'll email you a copy too. No spam — promise."})]}):o.jsx("a",{href:t.download_url||"#",target:"_blank",rel:"noopener",onClick:()=>E("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, ${R}, ${B2(R,-20)})`},children:t.download_label}),G&&o.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",G]})]})]})})}}function B2(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,s=r&255,f=Math.round((n-a)*i)+a,m=Math.round((n-c)*i)+c,x=Math.round((n-s)*i)+s;return"#"+(16777216+(f<<16)+(m<<8)+x).toString(16).slice(1)}catch{return t}}function $W({slug:t}){const[e,r]=P.useState(null);return P.useEffect(()=>{if(!t)return;let n=!1;return(async()=>{const{data:i,error:a}=await Le.rpc("get_public_lead_magnet_config",{_slug:t});!n&&!a&&i&&r(i)})(),()=>{n=!0}},[t]),e?o.jsx(gMt,{config:e}):null}function UW({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:Uhe,label:"Facebook"},{key:"instagram",url:n.instagram,Icon:qhe,label:"Instagram"},{key:"linkedin",url:n.linkedin,Icon:Khe,label:"LinkedIn"},{key:"youtube",url:n.youtube,Icon:kLe,label:"YouTube"}].filter(c=>!!c.url);return i.length?o.jsx("div",{className:`flex items-center gap-3 ${e}`,children:i.map(({key:c,url:s,Icon:f,label:m})=>o.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer","aria-label":m,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:o.jsx(f,{className:"h-4 w-4"})},c))}):null}const yMt="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109";function xMt({children:t,siteConfig:e}){var Pr,Nn,ai,ei,Oi,ya,mi,ia;const r=Wi(),n=ma(),[i,a]=P.useState(!1),[c,s]=P.useState(!1);P.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&s(!0)},[]);const[f,m]=P.useState(!1),[x,_]=P.useState([]),[T,E]=P.useState([]),[C,N]=P.useState([]),[R,D]=P.useState(null),M=P.useRef(null),B=P.useRef(null),{user:V,profile:G,signOut:W}=qS();fW(e,V==null?void 0:V.id),pW(e,V==null?void 0:V.id);const X=((Pr=e.agent)==null?void 0:Pr.full_name)||"Agent",Q=e.siteTitle||`${X} Real Estate`,re=r.pathname==="/search",se=r.pathname==="/",ue=e.leadRegistrationMode!=="disabled",_e=e.id===yMt;P.useEffect(()=>{(async()=>{const{data:Mn}=await Le.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",e.id).eq("is_published",!0).order("sort_order",{ascending:!0});_(Mn||[])})()},[e.id]),P.useEffect(()=>{(async()=>{const{data:Mn}=await Le.from("lead_site_menu_items").select("*").eq("site_id",e.id).order("sort_order",{ascending:!0});N(Mn||[]),E((Mn||[]).filter(As=>As.is_visible!==!1))})()},[e.id]),P.useEffect(()=>{const jr=Mn=>{M.current&&!M.current.contains(Mn.target)&&m(!1),B.current&&!B.current.contains(Mn.target)&&D(null)};return document.addEventListener("mousedown",jr),()=>document.removeEventListener("mousedown",jr)},[]);const Se=Xy(e),ve=e==null?void 0:e.bookingUrl,{data:Oe}=c3(Se?e.agentId:null),Ae=((Oe==null?void 0:Oe.length)??0)>0,{data:we}=aW(e.agentId),ge=((we==null?void 0:we.length)??0)>0,Ne=T.filter(jr=>{const Mn=String(jr.target_url||"").toLowerCase().replace(/\/+$/,""),As=String(jr.label||"").toLowerCase();return!(Se&&(Mn==="/search"||Mn.startsWith("/search?")||As.includes("search"))||Mn==="/listings"&&Se&&!Ae||Mn==="/sold"&&!ge)}),Ie=Se&&Ae&&Ne.length>0&&!Ne.some(jr=>String(jr.target_url||"").toLowerCase().startsWith("/listings"))?[...Ne,{id:"__my-listings",label:"My Listings",target_url:"/listings",parent_id:null,is_visible:!0}]:Ne,Te=Ie.length>0,be=[{to:"/",label:"Home"},...Se?[]:[{to:"/search",label:"Search"}],...Se&&Ae?[{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"}],We=Ie.filter(jr=>!jr.parent_id),rt=jr=>Ie.filter(Mn=>Mn.parent_id===jr),at=C.filter(jr=>!jr.parent_id),Et=new Set([...at,...We].filter(jr=>String(jr.target_url||"").trim()!=="").map(jr=>String(jr.target_url).toLowerCase().replace(/\/+$/,"")||"/")),_t=new Set([...at,...We].map(jr=>String(jr.label||"").trim().toLowerCase())),mt=["/","/search","/about","/contact","/sell","/blog"].some(jr=>Et.has(jr)),Pt=mt?[]:be.filter(jr=>!Et.has(jr.to.toLowerCase())&&!_t.has(jr.label.toLowerCase())),er=mt?We.filter(jr=>jr.is_visible!==!1&&String(jr.target_url||"").trim()!=="").map(jr=>({to:String(jr.target_url),label:String(jr.label||"").trim()||"Link"})):Pt,wt=at.find(jr=>jr.item_type==="cities"),or=String((wt==null?void 0:wt.label)||"Cities").trim()||"Cities",Sr=x.length>0&&!_e,nn=Sr&&!wt,lr=jr=>`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${jr?se?"bg-white/15 text-white":"bg-gray-100 text-gray-900":se?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,yr=r.pathname.startsWith("/homes-for-sale-in-"),tr=jr=>o.jsxs("div",{ref:M,className:"relative",children:[o.jsxs("button",{onClick:()=>m(!f),className:`flex items-center gap-1 ${lr(yr)}`,children:[jr," ",o.jsx(od,{className:`h-3.5 w-3.5 transition-transform ${f?"rotate-180":""}`})]}),f&&o.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:x.map(Mn=>o.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${Mn.city_slug}`),m(!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:Mn.city_name},Mn.city_slug))})]},"__cities"),yn=jr=>o.jsxs("div",{children:[o.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${se?"text-white/40":"text-gray-400"}`,children:jr}),x.map(Mn=>o.jsx(cs,{to:`/homes-for-sale-in-${Mn.city_slug}`,onClick:()=>a(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===`/homes-for-sale-in-${Mn.city_slug}`?se?"bg-white/15 text-white":"bg-gray-100 text-gray-900":se?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Mn.city_name},Mn.city_slug))]},"__cities-mobile"),lt=se?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",At=e.seoMetaTitle||e.siteTitle||`${X} - Real Estate`,Ot=e.seoMetaDescription||e.siteTagline||`Browse homes and listings with ${X}`,dr=e.ogImageUrl||((Nn=e.agent)==null?void 0:Nn.avatar_url)||"",cr=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`,hr=uW(e.siteTitle,X),Zt=(e.googleSearchConsoleVerification||"").trim().replace(/^google-site-verification[=:]\s*/i,"").replace(/^content=/i,"").replace(/^["']|["']$/g,"");return o.jsxs("div",{className:`flex flex-col ${re?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[o.jsx(dW,{siteConfig:e,pagePath:r.pathname}),(!_e||r.pathname==="/p/frequently-asked-questions")&&o.jsx(hW,{siteConfig:e}),o.jsxs(jl,{children:[o.jsx("title",{children:At}),o.jsx("meta",{name:"description",content:Ot}),Zt&&o.jsx("meta",{name:"google-site-verification",content:Zt}),o.jsx("meta",{property:"og:site_name",content:hr}),o.jsx("meta",{property:"og:title",content:At}),o.jsx("meta",{property:"og:description",content:Ot}),o.jsx("meta",{property:"og:type",content:"website"}),o.jsx("meta",{property:"og:url",content:cr+r.pathname}),dr&&o.jsx("meta",{property:"og:image",content:dr}),o.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),o.jsx("meta",{name:"twitter:title",content:At}),o.jsx("meta",{name:"twitter:description",content:Ot}),dr&&o.jsx("meta",{name:"twitter:image",content:dr}),e.faviconUrl&&o.jsx("link",{rel:"icon",href:e.faviconUrl,type:"image/png"}),o.jsx("link",{rel:"canonical",href:`${cr}${r.pathname}`}),e.subdomainSlug==="matthogg"&&o.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),o.jsxs("header",{className:`${se?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${lt}`,children:[o.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:o.jsxs("div",{className:"flex items-center justify-between h-20",children:[o.jsxs(cs,{to:"/",className:"flex items-center gap-3",children:[e.showTeamLogo&&e.teamLogoUrl?o.jsx("img",{src:e.teamLogoUrl,alt:`${Q} logo`,className:`${TPt(e.headerLogoSize)} w-auto object-contain`}):(ai=e.agent)!=null&&ai.avatar_url?o.jsx("img",{src:e.agent.avatar_url,alt:X,className:"h-10 w-10 rounded-full object-cover ring-2 ring-white/20"}):null,o.jsx("div",{children:o.jsx("span",{className:"font-bold text-lg leading-none tracking-tight",children:Q})})]}),o.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[e.bookingUrl&&!_e&&o.jsx(Sm,{bookingUrl:e.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),Pt.map(jr=>o.jsx(cs,{to:jr.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${r.pathname===jr.to?se?"bg-white/15 text-white":"bg-gray-100 text-gray-900":se?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:jr.label},jr.to)),Te&&We.map(jr=>{if(jr.item_type==="cities")return Sr?tr(String(jr.label||"Cities")):null;if(jr.item_type==="dropdown"){const Mn=rt(jr.id);return o.jsxs("div",{ref:B,className:"relative",children:[o.jsxs("button",{onClick:()=>D(R===jr.id?null:jr.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${se?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[jr.label," ",o.jsx(od,{className:`h-3.5 w-3.5 transition-transform ${R===jr.id?"rotate-180":""}`})]}),R===jr.id&&Mn.length>0&&o.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:Mn.map(As=>o.jsx(lR,{item:As,onClick:()=>D(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"},As.id))})]},jr.id)}return o.jsx(lR,{item:jr,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${se?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},jr.id)}),nn&&tr(or),!_e&&(V?o.jsx("div",{className:"ml-2",children:o.jsx(lW,{savedClassName:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${se?"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 ${se?"bg-white/10 text-white hover:bg-white/20":"bg-gray-100 text-gray-800 hover:bg-gray-200"}`})}):ue?o.jsx("button",{onClick:()=>s(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${se?"bg-white/15 text-white hover:bg-white/25":"bg-blue-600 text-white hover:bg-blue-700"}`,children:"Sign In"}):null)]}),o.jsx("button",{onClick:()=>a(!i),"aria-label":i?"Close menu":"Open menu","aria-expanded":i,className:`md:hidden p-2 rounded-lg ${se?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:i?o.jsx(Ks,{className:"h-5 w-5"}):o.jsx(ZO,{className:"h-5 w-5"})})]})}),i&&o.jsx("div",{className:`md:hidden border-t ${se?"border-white/10 bg-black/95 backdrop-blur":"border-gray-100 bg-white"} max-h-[calc(100vh-5rem)] overflow-y-auto overscroll-contain`,children:o.jsxs("div",{className:"px-4 py-3 space-y-1 pb-8",children:[e.bookingUrl&&!_e&&o.jsx(Sm,{bookingUrl:e.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),Pt.map(jr=>o.jsx(cs,{to:jr.to,onClick:()=>a(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${r.pathname===jr.to?se?"bg-white/15 text-white":"bg-gray-100 text-gray-900":se?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:jr.label},jr.to)),Te&&We.map(jr=>{if(jr.item_type==="cities")return Sr?yn(String(jr.label||"Cities")):null;if(jr.item_type==="dropdown"){const Mn=rt(jr.id);return o.jsxs("div",{className:"space-y-1",children:[o.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${se?"text-white/40":"text-gray-400"}`,children:jr.label}),Mn.map(As=>o.jsx(lR,{item:As,onClick:()=>a(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${se?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},As.id))]},jr.id)}return o.jsx(lR,{item:jr,onClick:()=>a(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${se?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},jr.id)}),nn&&yn(or),!_e&&(V?o.jsx(cW,{dark:se,onNavigate:()=>a(!1)}):ue?o.jsx("button",{onClick:()=>{s(!0),a(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${se?"text-white/70 hover:bg-white/10":"text-blue-600 hover:bg-blue-50"}`,children:"Sign In / Register"}):null)]})})]}),o.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:t}),!re&&o.jsx("footer",{className:"bg-gray-950 text-gray-400",children:o.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-16",children:[o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[((ei=e.agent)==null?void 0:ei.avatar_url)&&o.jsx("img",{src:e.agent.avatar_url,alt:X,className:"h-16 w-16 rounded-2xl object-cover ring-2 ring-white/10"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-bold text-white text-lg tracking-tight",children:X}),o.jsx("p",{className:"text-sm text-gray-400",children:_e?"Personal Real Estate Advisor":((Oi=e.agent)==null?void 0:Oi.title)||"Real Estate Professional"})]})]}),((ya=e.agent)==null?void 0:ya.phone)&&o.jsx("p",{className:"text-sm mt-3",children:o.jsxs("a",{href:`tel:${e.agent.phone}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[o.jsx(zi,{className:"h-3.5 w-3.5"})," ",e.agent.phone]})}),((mi=e.agent)==null?void 0:mi.email)&&o.jsx("p",{className:"text-sm mt-1",children:o.jsxs("a",{href:`mailto:${e.agent.email}`,className:"hover:text-white transition-colors flex items-center gap-2",children:[o.jsx(Bi,{className:"h-3.5 w-3.5"})," ",e.agent.email]})}),o.jsx(UW,{siteConfig:e,className:"mt-4"}),_e&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm mt-4",children:"Helping you find the right real estate agent, wherever you need one."}),o.jsx("p",{className:"text-sm mt-2",children:"Columbia, Missouri"})]})]}),o.jsxs("div",{children:[o.jsx("h2",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),o.jsxs("ul",{className:"space-y-3 text-sm",children:[(_e?[{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"}]:er).map(jr=>o.jsx("li",{children:/^https?:\/\//i.test(jr.to)?o.jsx("a",{href:jr.to,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:jr.label}):o.jsx(cs,{to:jr.to,className:"hover:text-white transition-colors",children:jr.label})},jr.to)),ve&&!_e&&o.jsx("li",{children:o.jsx("a",{href:ve,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]}),x.length>0&&!_e&&o.jsxs(o.Fragment,{children:[o.jsx("h2",{className:"font-semibold text-white mt-8 mb-4 text-sm tracking-wider uppercase",children:"Local Areas"}),o.jsx("ul",{className:"space-y-3 text-sm",children:x.map(jr=>o.jsx("li",{children:o.jsx(cs,{to:`/homes-for-sale-in-${jr.city_slug}`,className:"hover:text-white transition-colors",children:jr.city_name})},jr.city_slug))})]})]}),o.jsxs("div",{children:[o.jsx("h2",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),o.jsx("p",{className:"text-sm text-gray-400 leading-relaxed mb-4",children:_e?"Helping you find the right real estate agent, wherever you need one.":Se?"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."}),o.jsx(cs,{to:_e?"/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:_e?"Call Tom First":"Contact Me"})]})]}),o.jsxs("div",{className:"mt-14 pt-6 border-t border-gray-800/50",children:[e.showTeamLogo&&e.teamLogoUrl&&o.jsx("div",{className:"flex items-center justify-center mb-6",children:o.jsx("img",{src:e.teamLogoUrl,alt:`${Q} logo`,className:`${EPt(e.headerLogoSize)} w-auto object-contain`})}),e.brokerageLegalName&&o.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-gray-400 mb-3",children:[o.jsxs("span",{children:[X," · ",e.brokerageLegalName]}),e.agentLicenseNumber&&o.jsx("span",{children:e.agentLicenseNumber}),e.brokerageLicenseNumber&&o.jsxs("span",{children:["Brokerage #",e.brokerageLicenseNumber]})]}),e.mlsDisclaimerText&&o.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[e.mlsLogoUrl&&o.jsx("img",{src:e.mlsLogoUrl,alt:"MLS",className:"h-8 w-auto flex-shrink-0 mt-0.5"}),o.jsx("p",{className:"text-[11px] text-gray-400 leading-relaxed max-w-3xl text-center",children:e.mlsDisclaimerText})]}),o.jsxs("div",{className:"flex items-center justify-center gap-4 text-xs text-gray-400",children:[e.equalHousingEnabled&&o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-5 w-5 text-gray-400",children:o.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),o.jsx("span",{children:"Equal Housing Opportunity"})]}),o.jsxs("span",{children:["© ",new Date().getFullYear()," ",X,". Powered by LevelUp."]})]})]})]})}),!re&&!_e&&((ia=e.agent)==null?void 0:ia.avatar_url)&&o.jsx(_Mt,{agent:e.agent,bookingUrl:ve}),c&&o.jsx(oW,{open:c,mode:"optional",siteConfig:e,onComplete:()=>s(!1),onSkip:()=>s(!1)}),o.jsx(BW,{slug:e.subdomainSlug}),o.jsx(zW,{slug:e.subdomainSlug}),!_e&&o.jsx($W,{slug:e.subdomainSlug})]})}function _Mt({agent:t,bookingUrl:e}){var a;const[r,n]=P.useState(!1),i=ma();return t?o.jsx("div",{className:`fixed right-6 z-40 ${e?"bottom-24 md:bottom-6":"bottom-6"}`,children:r?o.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:[o.jsxs("div",{className:"p-5",children:[o.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[o.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-gray-100"}),o.jsxs("div",{children:[o.jsx("p",{className:"font-bold text-gray-900 text-sm",children:t.full_name}),o.jsx("p",{className:"text-xs text-gray-600",children:t.title||"Real Estate Professional"})]})]}),o.jsx("p",{className:"text-xs text-gray-600 mb-4",children:"Have questions about a property or the area? I'm here to help!"}),o.jsxs("div",{className:"space-y-2",children:[t.phone&&o.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:[o.jsx(zi,{className:"h-4 w-4 text-gray-400"}),t.phone]}),t.email&&o.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:[o.jsx(Bi,{className:"h-4 w-4 text-gray-400"}),"Email Me"]}),o.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&&o.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"})]})]}),o.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:o.jsx(Ks,{className:"h-4 w-4"})})]}):o.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:[o.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-10 w-10 rounded-full object-cover ring-2 ring-blue-100"}),o.jsxs("div",{className:"text-left",children:[o.jsx("p",{className:"text-xs font-bold text-gray-900 leading-none",children:(a=t.full_name)==null?void 0:a.split(" ")[0]}),o.jsx("p",{className:"text-[10px] text-blue-600 font-medium mt-0.5",children:"Chat with me →"})]})]})}):null}function lR({item:t,className:e,onClick:r}){const n=t.target_url||"#";return/^(https?:)?\/\//i.test(n)||/^(mailto:|tel:)/i.test(n)?o.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:e,onClick:r,children:t.label}):o.jsx(cs,{to:n,className:e,onClick:r,children:t.label})}const vMt=new Set(["danicapatton"]);function aAe(t){if(!t)return!1;const e=t.themeConfig||{};return e.expReady===!1?!1:e.expReady===!0||vMt.has(t.subdomainSlug)}const bMt="/exp-ready",wMt="eXp Ready",ace={california:"California DRE License",ca:"California DRE License"};function cq(t){const e=(t||"").trim();if(!e)return"Real Estate License";const r=e.toLowerCase();return ace[r]?ace[r]:`${e.replace(/\b\w/g,i=>i.toUpperCase())} Real Estate License`}function oce(t){if(t)return t.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function SMt({children:t,siteConfig:e}){var er,wt,or,Sr,nn,lr,yr;const r=Wi(),n=ma(),[i,a]=P.useState(!1),[c,s]=P.useState(!1);P.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&s(!0)},[]);const[f,m]=P.useState(!1),[x,_]=P.useState(!1),[T,E]=P.useState([]),[C,N]=P.useState(!1),R=P.useRef(null),D=P.useRef(null),{user:M,profile:B,signOut:V}=qS();fW(e,M==null?void 0:M.id),pW(e,M==null?void 0:M.id);const G=((er=e.agent)==null?void 0:er.full_name)||"Agent",W=oce(e.agentLicenseNumber),X=oce(e.brokerageLicenseNumber),Q=e.siteTitle||`${G} Real Estate`,re=tr=>{if(!tr)return tr;const yn=G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),lt=new RegExp(`^\\s*${yn}\\s*[|\\-–—:]\\s*`,"i");return tr.replace(lt,"").trim()},se=Q&&Q!==`${G} Real Estate`?Q:null,ue=se?re(se):null,_e=ue&&ue.toLowerCase()!==G.toLowerCase()?ue:null,Se=r.pathname==="/search",ve=r.pathname==="/",Oe=e.leadRegistrationMode!=="disabled",Ae="#c9a96e",we=e.bookingUrl;P.useEffect(()=>{const tr=()=>N(window.scrollY>80);return window.addEventListener("scroll",tr,{passive:!0}),()=>window.removeEventListener("scroll",tr)},[]),P.useEffect(()=>{(async()=>{const{data:yn}=await Le.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",e.id).eq("is_published",!0).order("sort_order",{ascending:!0});E(yn||[])})()},[e.id]),P.useEffect(()=>{const tr=yn=>{R.current&&!R.current.contains(yn.target)&&m(!1),D.current&&!D.current.contains(yn.target)&&_(!1)};return document.addEventListener("mousedown",tr),()=>document.removeEventListener("mousedown",tr)},[]);const ge=(((wt=e.themeConfig)==null?void 0:wt.focusPages)??[]).filter(tr=>tr==null?void 0:tr.slug).map(tr=>({to:`/${tr.slug}`,label:tr.navLabel||tr.title})).concat(aAe(e)?[{to:bMt,label:wMt}]:[]),Ne=EEe(e)||Xy(e),{data:Ie}=c3(Ne?e.agentId:null),Te=((Ie==null?void 0:Ie.length)??0)>0,{data:be}=aW(e.agentId),We=((be==null?void 0:be.length)??0)>0,rt=[{to:"/",label:"Home"},...Ne?Te?[{to:"/listings",label:"My Listings"}]:[]:[{to:"/search",label:"Search"}],...We?[{to:"/sold",label:"Sold"}]:[],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],at=[...rt,...ge],Et=e.siteTitle||`${G} - Real Estate`,_t=e.siteTagline||`Browse homes and listings with ${G}`,Vt=e.ogImageUrl||((or=e.agent)==null?void 0:or.avatar_url)||"",mt=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`,Pt=ve?C?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return o.jsxs("div",{className:`flex flex-col ${Se?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[o.jsx(dW,{siteConfig:e,pagePath:r.pathname}),o.jsx(hW,{siteConfig:e}),o.jsxs(jl,{children:[o.jsx("title",{children:Et}),o.jsx("meta",{name:"description",content:_t}),o.jsx("meta",{property:"og:title",content:Et}),o.jsx("meta",{property:"og:description",content:_t}),o.jsx("meta",{property:"og:type",content:"website"}),o.jsx("meta",{property:"og:url",content:mt+r.pathname}),Vt&&o.jsx("meta",{property:"og:image",content:Vt}),o.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),o.jsx("meta",{name:"twitter:title",content:Et}),o.jsx("meta",{name:"twitter:description",content:_t}),Vt&&o.jsx("meta",{name:"twitter:image",content:Vt}),e.faviconUrl&&o.jsx("link",{rel:"icon",href:e.faviconUrl,type:"image/png"}),o.jsx("link",{rel:"canonical",href:`${mt}${r.pathname}`}),o.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"})]}),o.jsxs("header",{className:`${ve?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${Pt}`,children:[o.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:o.jsxs("div",{className:"flex items-center justify-between min-h-20 py-3 gap-6",children:[o.jsxs(cs,{to:"/",className:"flex items-center gap-3 shrink-0",children:[e.showTeamLogo&&e.teamLogoUrl&&o.jsx("img",{src:e.teamLogoUrl,alt:`${G} brokerage logo`,className:"h-9 sm:h-11 w-auto max-w-[150px] object-contain"}),o.jsxs("span",{className:"flex flex-col leading-tight",children:[o.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&&o.jsx("span",{className:"hidden sm:block whitespace-nowrap text-[10px] sm:text-[11px] tracking-[0.14em] uppercase text-white/60",children:e.brokerageLegalName}),_e&&o.jsx("span",{className:"hidden xl:block whitespace-nowrap text-[10px] tracking-[0.18em] uppercase text-white/40",children:_e})]})]}),o.jsxs("nav",{className:"hidden lg:flex items-center justify-end gap-0 flex-1 min-w-0",children:[rt.map(tr=>o.jsx(cs,{to:tr.to,className:`whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${r.pathname===tr.to?"text-white":"text-white/40 hover:text-white"}`,children:tr.label},tr.to)),ge.length>0&&o.jsxs("div",{ref:D,className:"relative",children:[o.jsxs("button",{onClick:()=>_(!x),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(tr=>r.pathname===tr.to)?"text-white":"text-white/40 hover:text-white"}`,children:["Specialty"," ",o.jsx(od,{className:`h-3 w-3 transition-transform ${x?"rotate-180":""}`})]}),x&&o.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(tr=>o.jsx(cs,{to:tr.to,onClick:()=>_(!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===tr.to?"text-white":""}`,children:tr.label},tr.to))})]}),T.length>0&&o.jsxs("div",{ref:R,className:"relative",children:[o.jsxs("button",{onClick:()=>m(!f),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 ",o.jsx(od,{className:`h-3 w-3 transition-transform ${f?"rotate-180":""}`})]}),f&&o.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:T.map(tr=>o.jsx("button",{onClick:()=>{n(`/homes-for-sale-in-${tr.city_slug}`),m(!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:tr.city_name},tr.city_slug))})]}),M?o.jsx("div",{className:"ml-3",children:o.jsx(lW,{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"})}):Oe?o.jsx("button",{onClick:()=>s(!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,we&&o.jsx(Sm,{bookingUrl:we,label:"Schedule",size:"sm",className:"ml-3",source:"nav"})]}),o.jsxs("button",{onClick:()=>a(!i),className:"lg:hidden p-2 text-white/60 hover:text-white",children:[o.jsx("div",{className:"flex flex-col items-center gap-0.5",children:i?o.jsx(Ks,{className:"h-5 w-5"}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"w-6 h-px bg-current"}),o.jsx("div",{className:"w-4 h-px bg-current mt-1.5"}),o.jsx("div",{className:"w-6 h-px bg-current mt-1.5"})]})}),o.jsx("span",{className:"text-[8px] tracking-[0.3em] uppercase mt-1 block",children:"MENU"})]})]})}),i&&o.jsx("div",{className:"lg:hidden border-t border-white/5 bg-[#0d0b0a]/98 backdrop-blur-lg",children:o.jsxs("div",{className:"px-6 py-4 space-y-1",children:[we&&o.jsx(Sm,{bookingUrl:we,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),rt.map(tr=>o.jsx(cs,{to:tr.to,onClick:()=>a(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${r.pathname===tr.to?"text-white":"text-white/40 hover:text-white"}`,children:tr.label},tr.to)),ge.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Ae},children:"Specialty"}),ge.map(tr=>o.jsx(cs,{to:tr.to,onClick:()=>a(!1),className:`block px-3 py-2.5 text-xs tracking-wider uppercase transition-colors ${r.pathname===tr.to?"text-white":"text-white/40 hover:text-white"}`,children:tr.label},tr.to))]}),T.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:Ae},children:"Cities"}),T.map(tr=>o.jsx(cs,{to:`/homes-for-sale-in-${tr.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:tr.city_name},tr.city_slug))]}),M?o.jsx(cW,{dark:!0,onNavigate:()=>a(!1)}):Oe?o.jsx("button",{onClick:()=>{s(!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]})})]}),o.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:t}),!Se&&o.jsx("footer",{className:"bg-[#0a0908] text-white/70 border-t border-white/10",children:o.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-20",children:[o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-16",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"text-white text-xl tracking-tight mb-3",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:G}),o.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((Sr=e.agent)==null?void 0:Sr.title)||"Real Estate Professional"}),(W||X)&&o.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[W&&o.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[cq(e.licenseState)," #",W]}),X&&o.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",X]})]}),((nn=e.agent)==null?void 0:nn.phone)&&o.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:[o.jsx(zi,{className:"h-3.5 w-3.5"})," ",e.agent.phone]}),((lr=e.agent)==null?void 0:lr.email)&&o.jsxs("a",{href:`mailto:${e.agent.email}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors",children:[o.jsx(Bi,{className:"h-3.5 w-3.5"})," ",e.agent.email]}),o.jsx(UW,{siteConfig:e,className:"mt-6",iconClassName:"border-white/20"})]}),o.jsxs("div",{children:[o.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Ae},children:"Quick Links"}),o.jsxs("ul",{className:"space-y-3",children:[at.map(tr=>o.jsx("li",{children:o.jsx(cs,{to:tr.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:tr.label})},tr.to)),we&&o.jsx("li",{children:o.jsx("a",{href:we,target:"_blank",rel:"noopener noreferrer",className:"text-xs tracking-wider uppercase transition-colors hover:opacity-80",style:{color:GS},children:"Schedule a Free Consultation"})})]})]}),o.jsxs("div",{children:[o.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Ae},children:"Get In Touch"}),o.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."}),o.jsxs("div",{className:"flex flex-col items-start gap-3",children:[we&&o.jsx(Sm,{bookingUrl:we,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),o.jsx(cs,{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"})]})]})]}),o.jsxs("div",{className:"mt-16 pt-8 border-t border-white/10",children:[e.showTeamLogo&&e.teamLogoUrl&&o.jsx("div",{className:"flex items-center justify-center mb-6",children:o.jsx("img",{src:e.teamLogoUrl,alt:"Team",className:"h-10 w-auto object-contain opacity-70"})}),e.brokerageLegalName&&o.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:[o.jsxs("span",{children:[G," · ",e.brokerageLegalName]}),W&&o.jsxs("span",{children:[cq(e.licenseState)," #",W]}),X&&o.jsxs("span",{children:["Brokerage #",X]})]}),e.mlsDisclaimerText&&o.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[e.mlsLogoUrl&&o.jsx("img",{src:e.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-70"}),o.jsx("p",{className:"text-[11px] text-white/70 leading-relaxed max-w-3xl text-center",children:e.mlsDisclaimerText})]}),o.jsxs("div",{className:"flex items-center justify-center gap-4 text-[11px] text-white/70 tracking-wider uppercase",children:[e.equalHousingEnabled&&o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:o.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),o.jsx("span",{children:"Equal Housing Opportunity"})]}),o.jsxs("span",{children:["© ",new Date().getFullYear()," ",G,". Powered by LevelUp."]})]})]})]})}),!Se&&((yr=e.agent)==null?void 0:yr.avatar_url)&&o.jsx(TMt,{agent:e.agent,agentLicense:W,siteConfig:e,accentColor:Ae}),c&&o.jsx(oW,{open:c,mode:"optional",siteConfig:e,onComplete:()=>s(!1),onSkip:()=>s(!1),theme:"luxury",accentColor:Ae}),o.jsx(BW,{slug:e.subdomainSlug}),o.jsx(zW,{slug:e.subdomainSlug}),o.jsx($W,{slug:e.subdomainSlug})]})}function TMt({agent:t,agentLicense:e,siteConfig:r,accentColor:n}){var s;const[i,a]=P.useState(!1),c=ma();return t?o.jsx("div",{className:`fixed right-6 z-40 ${r.bookingUrl?"bottom-24 md:bottom-6":"bottom-6"}`,children:i?o.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:[o.jsxs("div",{className:"p-5",children:[o.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[o.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-12 w-12 rounded-full object-cover ring-1 ring-white/10"}),o.jsxs("div",{children:[o.jsx("p",{className:"text-white text-sm font-medium",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:t.full_name}),o.jsx("p",{className:"text-white/50 text-[10px] tracking-[0.1em] uppercase",children:t.title||"Real Estate Professional"})]})]}),e&&o.jsxs("div",{className:"mb-3 px-3 py-2 bg-white/5 border border-white/10",children:[o.jsx("p",{className:"text-[10px] text-white/50 tracking-wider uppercase",children:cq(r.licenseState)}),o.jsxs("p",{className:"text-xs text-white font-medium",children:["#",e]})]}),o.jsxs("div",{className:"space-y-2",children:[t.phone&&o.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:[o.jsx(zi,{className:"h-3.5 w-3.5"})," ",t.phone]}),t.email&&o.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:[o.jsx(Bi,{className:"h-3.5 w-3.5"})," Email Me"]}),o.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"})]})]}),o.jsx("button",{onClick:()=>a(!1),className:"absolute top-3 right-3 p-1 text-white/20 hover:text-white/50",children:o.jsx(Ks,{className:"h-4 w-4"})})]}):o.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:[o.jsx("img",{src:t.avatar_url,alt:t.full_name,className:"h-10 w-10 rounded-full object-cover ring-1 ring-white/10"}),o.jsxs("div",{className:"text-left",children:[o.jsx("p",{className:"text-[11px] text-white leading-none",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:(s=t.full_name)==null?void 0:s.split(" ")[0]}),o.jsx("p",{className:"text-[9px] tracking-[0.15em] uppercase mt-1",style:{color:n},children:"Let's connect →"})]})]})}):null}const z2="#2c1810",em="#b8860b";function EMt({children:t,siteConfig:e}){var ve,Oe,Ae;const r=Wi();ma();const[n,i]=P.useState(!1),[a,c]=P.useState(!1);P.useEffect(()=>{typeof window<"u"&&new URLSearchParams(window.location.search).get("join")==="1"&&c(!0)},[]);const[s,f]=P.useState(!1),[m,x]=P.useState([]),[_,T]=P.useState(!1),E=P.useRef(null),{user:C,profile:N,signOut:R}=qS();fW(e,C==null?void 0:C.id),pW(e,C==null?void 0:C.id);const D=((ve=e.agent)==null?void 0:ve.full_name)||"Agent",M=e.siteTitle||`${D} Land & Ranch`,B=r.pathname==="/",V=e.leadRegistrationMode!=="disabled",G=Xy(e);P.useEffect(()=>{const we=()=>T(window.scrollY>80);return window.addEventListener("scroll",we,{passive:!0}),()=>window.removeEventListener("scroll",we)},[]),P.useEffect(()=>{(async()=>{const{data:ge}=await Le.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",e.id).eq("is_published",!0).order("sort_order");ge&&x(ge)})()},[e.id]),P.useEffect(()=>{const we=ge=>{E.current&&!E.current.contains(ge.target)&&f(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[]);const{data:W}=aW(e.agentId),{data:X}=c3(e.agentId),Q=((W==null?void 0:W.length)??0)>0,re=((X==null?void 0:X.length)??0)>0,se=[{label:"Home",path:"/"},...G?[]:[{label:"Search Properties",path:"/search"}],...G&&re?[{label:"My Listings",path:"/listings"}]:[],...Q?[{label:"Sold",path:"/sold"}]:[],{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],ue=_||!B?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",_e=_||!B?z2:"#ffffff",Se=e.customDomain?`https://${e.customDomain}`:`https://${e.subdomainSlug||""}.thelocalmove.com`;return o.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[o.jsxs(jl,{children:[o.jsx("title",{children:M}),o.jsx("meta",{property:"og:url",content:Se+r.pathname}),o.jsx("link",{rel:"canonical",href:`${Se}${r.pathname}`}),o.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"})]}),o.jsx(dW,{siteConfig:e}),o.jsx(hW,{siteConfig:e}),o.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${ue}`,children:[o.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6",children:o.jsxs("div",{className:"flex items-center justify-between h-16 md:h-20",children:[o.jsxs(cs,{to:"/",className:"flex items-center gap-2.5",children:[o.jsx(wJ,{className:"w-7 h-7",style:{color:em}}),o.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:_e,fontFamily:"'Playfair Display', Georgia, serif"},children:M})]}),o.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[se.map(we=>o.jsx(cs,{to:we.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:r.pathname===we.path?em:_e},children:we.label},we.path)),m.length>0&&o.jsxs("div",{ref:E,className:"relative",children:[o.jsxs("button",{onClick:()=>f(!s),className:"px-4 py-2 text-sm font-medium tracking-wide uppercase flex items-center gap-1 transition-colors hover:opacity-80",style:{color:_e},children:["Area Guides ",o.jsx(od,{className:`w-3.5 h-3.5 transition-transform ${s?"rotate-180":""}`})]}),s&&o.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:m.map(we=>o.jsx(cs,{to:`/homes-for-sale-in-${we.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:z2},onClick:()=>f(!1),children:we.city_name},we.city_slug))})]}),C?o.jsx("div",{className:"ml-3",children:o.jsx(lW,{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"})}):V?o.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:em},children:"Sign In"}):null]}),o.jsx("button",{onClick:()=>i(!n),className:"md:hidden p-2",style:{color:_e},children:n?o.jsx(Ks,{className:"w-6 h-6"}):o.jsx(ZO,{className:"w-6 h-6"})})]})}),n&&o.jsx("div",{className:"md:hidden bg-white border-t border-gray-100 shadow-xl animate-in slide-in-from-top-2",children:o.jsxs("div",{className:"px-4 py-4 space-y-1",children:[se.map(we=>o.jsx(cs,{to:we.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:r.pathname===we.path?em:z2},onClick:()=>i(!1),children:we.label},we.path)),m.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"px-4 py-2 text-xs font-semibold tracking-wider uppercase text-gray-400",children:"Area Guides"}),m.map(we=>o.jsx(cs,{to:`/homes-for-sale-in-${we.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:z2},onClick:()=>i(!1),children:we.city_name},we.city_slug))]}),C&&o.jsx(cW,{onNavigate:()=>i(!1)}),!C&&V&&o.jsx("button",{onClick:()=>{c(!0),i(!1)},className:"w-full mt-3 px-5 py-3 text-white font-semibold rounded-full",style:{backgroundColor:em},children:"Sign In"})]})})]}),o.jsx("main",{children:t}),o.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:z2},children:o.jsxs("div",{className:"max-w-6xl mx-auto",children:[o.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-10",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[o.jsx(wJ,{className:"w-6 h-6",style:{color:em}}),o.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:M})]}),o.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Personal guidance for buying and selling land, homes, and rural property."}),o.jsx(UW,{siteConfig:e,className:"mt-5",iconClassName:"border-white/20 text-white"})]}),o.jsxs("div",{children:[o.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),o.jsx("div",{className:"space-y-2",children:se.map(we=>o.jsx(cs,{to:we.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:we.label},we.path))})]}),o.jsxs("div",{children:[o.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Contact"}),o.jsxs("div",{className:"space-y-3",children:[((Oe=e.agent)==null?void 0:Oe.phone)&&o.jsxs("a",{href:`tel:${e.agent.phone}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[o.jsx(zi,{className:"w-4 h-4",style:{color:em}}),e.agent.phone]}),((Ae=e.agent)==null?void 0:Ae.email)&&o.jsxs("a",{href:`mailto:${e.agent.email}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[o.jsx(Bi,{className:"w-4 h-4",style:{color:em}}),e.agent.email]})]})]})]}),o.jsxs("div",{className:"mt-12 pt-8 border-t border-white/10 flex items-center justify-between",children:[o.jsxs("p",{className:"text-white/40 text-xs",children:["© ",new Date().getFullYear()," ",M,". All rights reserved."]}),o.jsx("div",{className:"h-px w-16",style:{backgroundColor:em}})]})]})}),a&&o.jsx(oW,{open:a,mode:e.leadRegistrationMode==="required"?"required":"optional",siteConfig:e,onSkip:()=>c(!1),onComplete:()=>c(!1)}),o.jsx(BW,{slug:e.subdomainSlug}),o.jsx(zW,{slug:e.subdomainSlug}),o.jsx($W,{slug:e.subdomainSlug})]})}function lce(){const{pathname:t}=Wi();return P.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[t]),null}const AMt=P.lazy(()=>Be(()=>import("./LeadSiteHome-CRAFOob0.js"),__vite__mapDeps([12,13,14,15,16,17,18,19,20,21,22,23]))),kMt=P.lazy(()=>Be(()=>import("./LeadSiteLuxuryHome-BGL0h8DB.js"),__vite__mapDeps([24,25,16,17,18,19,20,26,23,3,27,28]))),CMt=P.lazy(()=>Be(()=>import("./LeadSiteLandRanchHome-BlKfmR7u.js"),__vite__mapDeps([29,13,14,15,16,17,18,19,20,21,30,31,32]))),cce=P.lazy(()=>Be(()=>import("./LeadSiteSearch-B4mltbMt.js"),__vite__mapDeps([33,13,14,15,34,35,19,36,37]))),jMt=P.lazy(()=>Be(()=>import("./LeadSiteLuxurySearch-BrALIqpU.js"),__vite__mapDeps([38,13,14,15,34,35,19,36,37]))),uce=P.lazy(()=>Be(()=>import("./LeadSiteListingDetail-KR9aiRRA.js"),__vite__mapDeps([39,40,19,41,31,42,43,44,45,46]))),IMt=P.lazy(()=>Be(()=>import("./LeadSiteLuxuryListingDetail-Ba2KFK_e.js"),__vite__mapDeps([47,40,19,41,31,42,43,44,45,46]))),PMt=P.lazy(()=>Be(()=>import("./LeadSiteAbout-Dk_wfJZY.js"),__vite__mapDeps([48,22]))),NMt=P.lazy(()=>Be(()=>import("./LeadSiteLuxuryAbout-CTXSV6Eu.js"),__vite__mapDeps([49,50]))),RMt=P.lazy(()=>Be(()=>import("./LeadSiteContact-DjtENIlW.js"),[])),LMt=P.lazy(()=>Be(()=>import("./LeadSiteLuxuryContact-Dhe_etvJ.js"),[])),DMt=P.lazy(()=>Be(()=>import("./LeadSiteConsumerDashboard-rov2qWFW.js"),[])),cR=P.lazy(()=>Be(()=>import("./LeadSiteBlog-BHqiThM_.js"),[])),OMt=P.lazy(()=>Be(()=>import("./LeadSiteCommunity-DazlDSb3.js"),__vite__mapDeps([51,45,7,52,53,54,55]))),MMt=P.lazy(()=>Be(()=>import("./LeadSiteSellers-CLkqlq5h.js"),__vite__mapDeps([56,50]))),FMt=P.lazy(()=>Be(()=>import("./LeadSiteCityPage-Blm3wrjm.js"),__vite__mapDeps([57,58,19,20,37,25,17]))),BMt=P.lazy(()=>Be(()=>import("./LeadSiteSubdivisionPage-BuwnxgZD.js"),__vite__mapDeps([59,19]))),zMt=P.lazy(()=>Be(()=>import("./LeadSiteCustomPage-BxYskNA3.js"),[])),$Mt=P.lazy(()=>Be(()=>import("./LeadSiteFocusPage-Dr_ardkp.js"),__vite__mapDeps([60,18,19,20,54]))),UMt=P.lazy(()=>Be(()=>import("./LeadSiteExpReady-B1JF-c5o.js"),__vite__mapDeps([61,62,53,27]))),VMt=P.lazy(()=>Be(()=>import("./LeadSiteConsultation-DPbpRAsS.js"),[])),dce=P.lazy(()=>Be(()=>import("./LeadSiteReviews-Cycn5lsm.js"),[])),qMt=P.lazy(()=>Be(()=>import("./LeadSiteExchangeListings-D7uNMBrY.js"),__vite__mapDeps([26,19])).then(t=>({default:t.LeadSiteExchangeListingsIndex}))),GMt=P.lazy(()=>Be(()=>import("./LeadSiteExchangeListings-D7uNMBrY.js"),__vite__mapDeps([26,19])).then(t=>({default:t.LeadSiteSoldListingsIndex}))),HMt=P.lazy(()=>Be(()=>import("./LeadSiteExchangeListings-D7uNMBrY.js"),__vite__mapDeps([26,19])).then(t=>({default:t.LeadSiteExchangeListingDetail}))),WMt=P.lazy(()=>Be(()=>import("./OrgSiteLayout-BK5tyKt-.js"),__vite__mapDeps([63,64]))),KMt=P.lazy(()=>Be(()=>import("./OrgSiteHome-6lS_1MSE.js").then(t=>t.O),__vite__mapDeps([65,64]))),YMt=P.lazy(()=>Be(()=>import("./OrgSiteAgents-CGii4xwQ.js"),__vite__mapDeps([66,64,65,67]))),ZMt=P.lazy(()=>Be(()=>import("./OrgSiteAgents-CGii4xwQ.js"),__vite__mapDeps([66,64,65,67])).then(t=>({default:t.OrgSiteAgentProfile}))),hce=P.lazy(()=>Be(()=>import("./OrgSiteListings-BidkX5iP.js"),__vite__mapDeps([68,64,65,67,18,19,20]))),XMt=P.lazy(()=>Be(()=>import("./OrgSiteListings-BidkX5iP.js"),__vite__mapDeps([68,64,65,67,18,19,20])).then(t=>({default:t.OrgSiteListingDetail}))),QMt=P.lazy(()=>Be(()=>import("./OrgSitePages-B-T4zbvx.js"),__vite__mapDeps([67,64,65])).then(t=>({default:t.OrgSiteAbout}))),JMt=P.lazy(()=>Be(()=>import("./OrgSitePages-B-T4zbvx.js"),__vite__mapDeps([67,64,65])).then(t=>({default:t.OrgSiteContact}))),eFt=P.lazy(()=>Be(()=>import("./OrgSitePages-B-T4zbvx.js"),__vite__mapDeps([67,64,65])).then(t=>({default:t.OrgSiteJoin})));function uq(){return o.jsx("div",{className:"min-h-[60vh] flex items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent"})})}function tFt({siteConfig:t}){const{data:e,isLoading:r}=c3(t.agentId);return r?o.jsx(uq,{}):o.jsx(ki,{to:e!=null&&e.length?"/listings":"/contact?interest=Property%20search",replace:!0})}function rFt(){P.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 nFt(){var T;const{siteConfig:t,themeConfig:e,isLoading:r,error:n}=jPt();if(rFt(),r)return o.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto mb-4"}),o.jsx("p",{className:"text-gray-500",children:"Loading..."})]})});if(n||!t)return o.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-6",children:o.jsxs("div",{className:"text-center max-w-md",children:[o.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Site Not Found"}),o.jsx("p",{className:"text-gray-500",children:"This lead site is not available or has not been set up yet."})]})});if(t.ownerType==="brokerage"||t.ownerType==="team"){const E=t.orgTier==="pro";return o.jsxs(Ooe,{siteConfig:t,children:[o.jsx(lce,{}),o.jsx(P.Suspense,{fallback:o.jsx(uq,{}),children:o.jsx(WMt,{siteConfig:t,themeConfig:e??void 0,children:o.jsxs(ak,{children:[o.jsx(Pe,{path:"/",element:o.jsx(KMt,{siteConfig:t,themeConfig:e??void 0})}),o.jsx(Pe,{path:"/listings",element:o.jsx(hce,{siteConfig:t,themeConfig:e??void 0})}),o.jsx(Pe,{path:"/sold",element:o.jsx(hce,{siteConfig:t,themeConfig:e??void 0,sold:!0})}),o.jsx(Pe,{path:"/listings/:slug",element:o.jsx(XMt,{siteConfig:t,themeConfig:e??void 0})}),o.jsx(Pe,{path:"/agents",element:o.jsx(YMt,{siteConfig:t,themeConfig:e??void 0})}),o.jsx(Pe,{path:"/agents/:slug",element:o.jsx(ZMt,{siteConfig:t,themeConfig:e??void 0})}),o.jsx(Pe,{path:"/about",element:o.jsx(QMt,{siteConfig:t,themeConfig:e??void 0})}),o.jsx(Pe,{path:"/contact",element:o.jsx(JMt,{siteConfig:t,themeConfig:e??void 0})}),o.jsx(Pe,{path:"/join",element:o.jsx(eFt,{siteConfig:t,themeConfig:e??void 0})}),o.jsx(Pe,{path:"/blog",element:o.jsx(cR,{siteConfig:t,isLuxury:!1})}),o.jsx(Pe,{path:"/blog/:slug",element:o.jsx(cR,{siteConfig:t,isLuxury:!1})}),o.jsx(Pe,{path:"/search",element:E?o.jsx(cce,{siteConfig:t}):o.jsx(ki,{to:"/listings",replace:!0})}),o.jsx(Pe,{path:"/listing/:mlsNumber",element:E?o.jsx(uce,{siteConfig:t}):o.jsx(ki,{to:"/listings",replace:!0})}),o.jsx(Pe,{path:"/*",element:o.jsx(fce,{siteConfig:t,referralMode:!E})})]})})})]})}const i=(e==null?void 0:e.themeTier)==="luxury",a=(e==null?void 0:e.themeTier)==="land-ranch",c=a?EMt:i?SMt:xMt,s=EEe(t),f=s||Xy(t,e),m=t.id==="7605cc2e-ce21-4f4f-8bb1-4c0f217b1109",x=!s&&Xy(t,e),_=a?o.jsx(CMt,{siteConfig:t,themeConfig:e??void 0}):i?o.jsx(kMt,{siteConfig:t,themeConfig:e??void 0}):o.jsx(AMt,{siteConfig:t,themeConfig:e??void 0});return o.jsxs(Ooe,{siteConfig:t,children:[o.jsx(lce,{}),o.jsxs(c,{siteConfig:t,children:[o.jsx(P.Suspense,{fallback:o.jsx(uq,{}),children:o.jsxs(ak,{children:[o.jsx(Pe,{path:"/",element:_}),o.jsx(Pe,{path:"/listings",element:o.jsx(qMt,{siteConfig:t})}),o.jsx(Pe,{path:"/sold",element:o.jsx(GMt,{siteConfig:t})}),o.jsx(Pe,{path:"/listings/:slug",element:o.jsx(HMt,{siteConfig:t})}),o.jsx(Pe,{path:"/search",element:f?o.jsx(tFt,{siteConfig:t}):i?o.jsx(jMt,{siteConfig:t}):o.jsx(cce,{siteConfig:t})}),o.jsx(Pe,{path:"/listing/:mlsNumber",element:f?o.jsx(ki,{to:"/contact?interest=Property%20details",replace:!0}):i?o.jsx(IMt,{siteConfig:t}):o.jsx(uce,{siteConfig:t})}),o.jsx(Pe,{path:"/about",element:i?o.jsx(NMt,{siteConfig:t}):o.jsx(PMt,{siteConfig:t,themeConfig:e??void 0})}),o.jsx(Pe,{path:"/contact",element:i?o.jsx(LMt,{siteConfig:t}):o.jsx(RMt,{siteConfig:t})}),o.jsx(Pe,{path:"/account",element:o.jsx(DMt,{siteConfig:t})}),o.jsx(Pe,{path:"/blog",element:o.jsx(cR,{siteConfig:t,isLuxury:i})}),o.jsx(Pe,{path:"/blog/:slug",element:o.jsx(cR,{siteConfig:t,isLuxury:i})}),o.jsx(Pe,{path:"/sell",element:o.jsx(MMt,{siteConfig:t,themeConfig:e??void 0,isLuxury:i})}),o.jsx(Pe,{path:"/community",element:o.jsx(OMt,{siteConfig:t,isLuxury:i})}),o.jsx(Pe,{path:"/schedule",element:t.id===BPt?o.jsx(VMt,{siteConfig:t}):o.jsx(FPt,{bookingUrl:t.bookingUrl,agentName:((T=t.agent)==null?void 0:T.full_name)||"your agent"})}),aAe(t)&&o.jsx(Pe,{path:"/exp-ready",element:o.jsx(UMt,{siteConfig:t})}),((e==null?void 0:e.focusPages)??[]).map(E=>o.jsx(Pe,{path:`/${E.slug}`,element:o.jsx($Mt,{siteConfig:t,page:E,accentColor:(e==null?void 0:e.accentColor)||t.accentColor||"#c9a96e"})},E.slug)),o.jsx(Pe,{path:"/reviews",element:o.jsx(dce,{siteConfig:t,themeConfig:e??void 0})}),o.jsx(Pe,{path:"/reviews/:slug",element:o.jsx(dce,{siteConfig:t,themeConfig:e??void 0})}),o.jsx(Pe,{path:"/p/:pageSlug",element:o.jsx(zMt,{siteConfig:t})}),o.jsx(Pe,{path:"/*",element:o.jsx(fce,{siteConfig:t,referralMode:x})})]})}),!m&&o.jsx(MPt,{bookingUrl:t.bookingUrl})]})]})}function fce({siteConfig:t,referralMode:e}){const r=Wi(),n=r.pathname.match(/^\/homes-in-(.+)$/);if(n)return o.jsx(BMt,{siteConfig:t,subdivisionSlug:n[1]});const i=r.pathname.match(/^\/homes-for-sale-in-(.+)$/);if(i)return o.jsx(FMt,{siteConfig:t,citySlugOverride:i[1],referralMode:e});const a=r.pathname.match(/^\/communities\/([^/]+)\/?$/);if(a)return o.jsx(ki,{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?o.jsx(iFt,{siteId:t==null?void 0:t.id,slug:c[1],search:r.search}):null}function iFt({siteId:t,slug:e,search:r}){const[n,i]=P.useState(null);return P.useEffect(()=>{let a=!1;if(!t){i(!1);return}return Le.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?o.jsx(ki,{to:`/p/${e}${r}`,replace:!0}):null}function sFt(){const{user:t,loading:e}=qn(),{data:r,isLoading:n}=wr({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 Le.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 aFt({children:t}){const{user:e,loading:r}=qn(),{hasAccess:n,isLoading:i}=sFt(),a=Wi();return P.useEffect(()=>{!r&&!i&&e&&!n&&Jt.error("LevelUp Attract isn't available for your account yet.")},[r,i,e,n]),r||e&&i?o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e?n?o.jsx(o.Fragment,{children:t}):o.jsx(ki,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",a.pathname),o.jsx(ki,{to:"/auth",replace:!0}))}function pce({children:t}){const{user:e,loading:r}=qn(),{hasAccess:n,isLoading:i}=u9(),a=Wi();return r||e&&i?o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e?n?o.jsx(o.Fragment,{children:t}):o.jsx(ki,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",a.pathname),o.jsx(ki,{to:"/auth",replace:!0}))}const oFt=P.lazy(()=>Be(()=>import("./CommercialMarketplace-K0IRjonM.js"),__vite__mapDeps([11,3]))),mce=P.lazy(()=>Be(()=>import("./PrivacyPolicy-CY2uQ_WD.js"),[])),lFt=P.lazy(()=>Be(()=>import("./CanvaSupport-BaCJ0Wbz.js"),__vite__mapDeps([69,70]))),gce=P.lazy(()=>Be(()=>import("./TermsOfService-CasiC28k.js"),[])),cFt=P.lazy(()=>Be(()=>import("./DataDeletion-4-8GRVsO.js"),[])),yce=P.lazy(()=>Be(()=>import("./McpDataUse-BfnDpcIQ.js"),[])),uFt=P.lazy(()=>Be(()=>import("./SmsOptIn-BbYqFyKm.js"),__vite__mapDeps([71,72]))),T$=P.lazy(()=>Be(()=>import("./OAuthConsent-Czz2dSLf.js"),[])),dFt=P.lazy(()=>Be(()=>import("./ConnectChatGPT-DBTSAfnT.js"),__vite__mapDeps([73,74]))),xce=P.lazy(()=>Be(()=>import("./LevelUpMCP-BVAoQoqI.js"),[])),hFt=P.lazy(()=>Be(()=>import("./SubscriptionSuccess-C_MKnjlE.js"),__vite__mapDeps([75,74]))),fFt=P.lazy(()=>Be(()=>import("./Subscription-BkcZ_dUc.js"),[])),pFt=P.lazy(()=>Be(()=>import("./SetupBrokerage-Uvem_4mB.js"),__vite__mapDeps([76,74]))),_ce=P.lazy(()=>Be(()=>import("./ClaimAccount-DzlsvC7T.js"),[])),vce=P.lazy(()=>Be(()=>import("./ConfirmPasswordReset-Dt9padNy.js"),[])),mFt=P.lazy(()=>Be(()=>import("./ActivateAccount-Dp0o_6gQ.js"),[])),gFt=P.lazy(()=>Be(()=>import("./InviteSignup-BYys3y22.js"),__vite__mapDeps([77,78]))),yFt=P.lazy(()=>Be(()=>import("./CoachingHub-C10jVq9g.js"),__vite__mapDeps([79,80]))),xFt=P.lazy(()=>Be(()=>import("./CoachAgentWorkspace-2I2RV2Af.js"),__vite__mapDeps([81,80,82,83,84]))),_Ft=P.lazy(()=>Be(()=>import("./MyCoach-fRvS9FyN.js"),__vite__mapDeps([85,80,82,86,87,83]))),vFt=P.lazy(()=>Be(()=>import("./AdminCoaching-C0mR3yfK.js"),__vite__mapDeps([88,89,90,6,91]))),bFt=P.lazy(()=>Be(()=>import("./CoachBilling-CY1SEumG.js"),__vite__mapDeps([92,80,93]))),wFt=P.lazy(()=>Be(()=>import("./CoachSettings-ANsd98XR.js"),__vite__mapDeps([94,80,95,96,97,70,84,98]))),SFt=P.lazy(()=>Be(()=>import("./GoogleCalendarReturn-Ltkqbsgk.js"),[])),TFt=P.lazy(()=>Be(()=>import("./Microsoft365Return-BQT5lEMk.js"),__vite__mapDeps([99,100,101]))),EFt=P.lazy(()=>Be(()=>import("./CoachWaitlist-vVwJUs00.js"),__vite__mapDeps([102,80,103]))),AFt=P.lazy(()=>Be(()=>import("./CoachesDirectory-Co_pxKep.js"),[])),kFt=P.lazy(()=>Be(()=>import("./CoachProfile-B38-l47Q.js"),__vite__mapDeps([104,86]))),CFt=P.lazy(()=>Be(()=>import("./CoachApply-DReNnVEs.js"),[])),jFt=P.lazy(()=>Be(()=>import("./Trial-BrFgXI77.js"),__vite__mapDeps([105,106]))),IFt=P.lazy(()=>Be(()=>import("./TrialSuccess-Bu38OEGd.js"),__vite__mapDeps([107,108]))),PFt=P.lazy(()=>Be(()=>import("./LaborDaySale-Dxvb-Fa1.js"),__vite__mapDeps([109,110,106,111,112]))),NFt=P.lazy(()=>Be(()=>import("./BrokerageLaborDaySale-CL8IoADQ.js"),__vite__mapDeps([113,110,106,111,112]))),RFt=P.lazy(()=>Be(()=>import("./BrokerageSolutions-BcU5N1ll.js"),__vite__mapDeps([114,111,115,116,117,112]))),LFt=P.lazy(()=>Be(()=>import("./Upgrade-CQba9lz8.js"),__vite__mapDeps([118,119]))),DFt=P.lazy(()=>Be(()=>import("./InstagramGift-s9YHE2ky.js"),__vite__mapDeps([120,119,93]))),bce=P.lazy(()=>Be(()=>import("./VideoShare-cOCZJ_Wv.js"),__vite__mapDeps([121,122,123,124,31,44,108,7,125,126,127]))),OFt=P.lazy(()=>Be(()=>import("./VideoShareLayout-QteQwOMw.js"),[])),MFt=P.lazy(()=>Be(()=>import("./VideoOgRedirect-wl6dRqMI.js"),[])),FFt=P.lazy(()=>Be(()=>Promise.resolve().then(()=>bYe),void 0)),BFt=P.lazy(()=>Be(()=>Promise.resolve().then(()=>mYe),void 0)),zFt=P.lazy(()=>Be(()=>import("./NewListingChooser-C-TWKidM.js"),[])),wce=P.lazy(()=>Be(()=>import("./CommercialWizard-_zY2Oc2Z.js"),__vite__mapDeps([128,129,130]))),$Ft=P.lazy(()=>Be(()=>import("./CommercialWorkspace-t-wlFaGY.js"),__vite__mapDeps([131,129,130,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,87,84,148,149]))),UFt=P.lazy(()=>Be(()=>import("./CommercialPitchPreview-BfdsK-b2.js"),__vite__mapDeps([150,149]))),VFt=P.lazy(()=>Be(()=>import("./PrivateListingView-DMR_jJka.js"),[])),qFt=P.lazy(()=>Be(()=>import("./PublicAgentCard-DPtEwoi8.js"),[])),GFt=P.lazy(()=>Be(()=>Promise.resolve().then(()=>aPt),void 0)),Sce=P.lazy(()=>Be(()=>import("./PublicHomeValue-BhuMaHOQ.js"),[])),HFt=P.lazy(()=>Be(()=>import("./PublicLiveEvent-DtffWjQN.js"),__vite__mapDeps([151,152,153,154,155]))),WFt=P.lazy(()=>Be(()=>import("./LiveEvents-D8Gm5LBZ.js"),__vite__mapDeps([156,157,158,159,147]))),KFt=P.lazy(()=>Be(()=>import("./LiveEventConsole--fFZlTJ5.js"),__vite__mapDeps([160,158,154,78,161,152,162]))),YFt=P.lazy(()=>Be(()=>import("./Dashboard-Capa4jkL.js"),__vite__mapDeps([163,164,165,80,166,167,168,169,170,171,129,130,172,173,174,175,4,44,83,176]))),ZFt=P.lazy(()=>Be(()=>import("./Profile-CQj7bw_w.js"),__vite__mapDeps([177,98,83,93,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,84,193,194,195,196,35,115,10,197]))),XFt=P.lazy(()=>Be(()=>import("./Events-Dnsuwdy6.js"),__vite__mapDeps([198,166,167,168,199,173,200,201]))),QFt=P.lazy(()=>Be(()=>import("./EventDetail-QCPn68IH.js"),__vite__mapDeps([202,166,167,168,203,204,74]))),JFt=P.lazy(()=>Be(()=>import("./Apps-CcO8Pofw.js"),__vite__mapDeps([205,125,93,206,6,207]))),e3t=P.lazy(()=>Be(()=>import("./Templates-HEyRseLF.js"),__vite__mapDeps([208,98]))),t3t=P.lazy(()=>Be(()=>import("./TemplateDetail-CciFqunH.js"),__vite__mapDeps([209,140,164,203,204,98]))),r3t=P.lazy(()=>Be(()=>import("./Programs-BMOnKKWg.js"),__vite__mapDeps([210,165]))),n3t=P.lazy(()=>Be(()=>import("./ProgramDetail-B5mBPnU3.js"),__vite__mapDeps([211,212,213,165,35,93]))),i3t=P.lazy(()=>Be(()=>import("./ProgramEnroll-6bdIjf9B.js"),__vite__mapDeps([214,165,215,93]))),s3t=P.lazy(()=>Be(()=>import("./ProgramWorkspace-CUDDm2OU.js"),__vite__mapDeps([216,165,217,218]))),a3t=P.lazy(()=>Be(()=>import("./Programs-Xxv_2WHL.js"),__vite__mapDeps([219,165,84,159,215,220,93,206,136,221,213,87,35]))),o3t=P.lazy(()=>Be(()=>import("./Academy-g6oXnxPT.js"),[])),l3t=P.lazy(()=>Be(()=>import("./AcademyVideoDetail-C_xJ_4yr.js"),__vite__mapDeps([222,140,164,203,204,223]))),c3t=P.lazy(()=>Be(()=>import("./PublicAcademyWatch-CF1O1hTG.js"),[])),u3t=P.lazy(()=>Be(()=>import("./Toolbox-Dd6_zXPV.js"),[])),d3t=P.lazy(()=>Be(()=>import("./ToolboxDetail-DjaKDWkR.js"),__vite__mapDeps([224,140,164,203,204,223]))),h3t=P.lazy(()=>Be(()=>import("./SocialSwag-Yf7HAECC.js"),__vite__mapDeps([225,98]))),f3t=P.lazy(()=>Be(()=>import("./SocialStudio-LxB5D2aB.js"),__vite__mapDeps([226,140,227,228,36,229,230,231,232,130,233,234,235,236,237,238,84,239,167,87,74,240,241]))),p3t=P.lazy(()=>Be(()=>import("./MarketingStudio-B9hwTxrC.js"),__vite__mapDeps([242,44,243]))),m3t=P.lazy(()=>Be(()=>import("./BrandKit-CC5ekgV9.js"),__vite__mapDeps([244,245]))),g3t=P.lazy(()=>Be(()=>import("./BrandingBarEditor-BguBh4MK.js"),__vite__mapDeps([246,240,245,247,248]))),y3t=P.lazy(()=>Be(()=>import("./ListingTemplates-pTjb451Q.js"),__vite__mapDeps([249,250,251,245,20,215,6]))),x3t=P.lazy(()=>Be(()=>import("./PersonalBranding-Cf77Majz.js"),__vite__mapDeps([252,253,245,250]))),_3t=P.lazy(()=>Be(()=>import("./SocialSwagDetail-aymdDdNY.js"),__vite__mapDeps([254,140,164,203,204,98]))),v3t=P.lazy(()=>Be(()=>import("./Community-PhPlCz97.js"),__vite__mapDeps([255,36,221,213,14,189,256,257,98,258,152]))),b3t=P.lazy(()=>Be(()=>import("./Support-DK8Lwgc5.js"),__vite__mapDeps([259,140,260,261,176,147,74,87]))),w3t=P.lazy(()=>Be(()=>import("./BrokerageResources-Bf2l0Dih.js"),__vite__mapDeps([262,98]))),S3t=P.lazy(()=>Be(()=>import("./BrokerageResourceDetail-BLRVEBpJ.js"),[])),Tce=P.lazy(()=>Be(()=>import("./AdminDashboard-BCW6Nznn.js"),__vite__mapDeps([263,93,264,215,265,266,267]))),T3t=P.lazy(()=>Be(()=>import("./Apps-CdpNmo-R.js"),[])),E3t=P.lazy(()=>Be(()=>import("./MemberManagement-DqA34ghr.js"),__vite__mapDeps([268,157,269,217,108,270,153,271,93,272,273,274,275,276,277,201,278,6,279,280,83,281,90,282,119]))),A3t=P.lazy(()=>Be(()=>import("./UnassignedMembers-BuAxVSTF.js"),__vite__mapDeps([283,157]))),k3t=P.lazy(()=>Be(()=>import("./InviteCodes-DSDdZyHN.js"),__vite__mapDeps([284,157]))),C3t=P.lazy(()=>Be(()=>import("./Events-D1uKTOMn.js"),__vite__mapDeps([285,178,179,180,181,182,183,184,185,186,187,98,158,286,157,287]))),j3t=P.lazy(()=>Be(()=>import("./MCPAuditLog-CgvJckkE.js"),__vite__mapDeps([288,157,289]))),I3t=P.lazy(()=>Be(()=>import("./Templates-DtoEEONz.js"),__vite__mapDeps([290,157,178,179,180,181,182,183,184,185,186,187,98,286]))),P3t=P.lazy(()=>Be(()=>import("./Academy-DM1nrjbc.js"),__vite__mapDeps([291,157,178,179,180,181,182,183,184,185,186,187,98,292,218,286]))),N3t=P.lazy(()=>Be(()=>import("./Toolbox-C0jW4ntU.js"),__vite__mapDeps([293,178,179,180,181,182,183,184,185,186,187,98,292,218,286]))),R3t=P.lazy(()=>Be(()=>import("./SocialSwag-BNSug24S.js"),__vite__mapDeps([294,157,178,179,180,181,182,183,184,185,186,187,98,286]))),L3t=P.lazy(()=>Be(()=>import("./SocialSwag2-B4PvBJpi.js"),__vite__mapDeps([295,286,135,98,136]))),D3t=P.lazy(()=>Be(()=>import("./Community-DopXr0t5.js"),__vite__mapDeps([296,157]))),O3t=P.lazy(()=>Be(()=>import("./Analytics-C3DUAFNC.js"),__vite__mapDeps([297,270,153,271,74,298,299,300,301,302]))),M3t=P.lazy(()=>Be(()=>import("./BrokerageResources-Df4WSii6.js"),__vite__mapDeps([303,178,179,180,181,182,183,184,185,186,187,98,215]))),F3t=P.lazy(()=>Be(()=>import("./DashboardManagement-lgLc1rx3.js"),__vite__mapDeps([304,136,161,78]))),B3t=P.lazy(()=>Be(()=>import("./SupportTickets-Dh3dHV-q.js"),__vite__mapDeps([305,140,260,261,176,147,10,74,87]))),z3t=P.lazy(()=>Be(()=>import("./EmailTemplates-BJQDsBi_.js"),__vite__mapDeps([306,179,180,307,184,185,186,187,98,308,309,84,310]))),$3t=P.lazy(()=>Be(()=>import("./AgentEmailTemplates-C-e3Gv--.js"),__vite__mapDeps([311,157,83]))),U3t=P.lazy(()=>Be(()=>import("./BrokerageDashboard-DhjPZLaf.js"),__vite__mapDeps([312,269,217,108,153,271,74,98,87,272,280,281,298,270,199,173,200]))),V3t=P.lazy(()=>Be(()=>import("./MyBrokerage-CLVAc7bJ.js"),__vite__mapDeps([313,152,119,200,192,84,314,315,87,6]))),q3t=P.lazy(()=>Be(()=>import("./BrokerageContent-CpH4bg9K.js"),__vite__mapDeps([316,171,83]))),G3t=P.lazy(()=>Be(()=>import("./BrokerageContentDetail-DKe1lkk8.js"),[])),H3t=P.lazy(()=>Be(()=>import("./BrokerageHelpBoard-BKrQlvI8.js"),__vite__mapDeps([317,318,10]))),W3t=P.lazy(()=>Be(()=>import("./BrokerageHelpBoardNew-RwrNkj6N.js"),__vite__mapDeps([319,318]))),K3t=P.lazy(()=>Be(()=>import("./BrokerageHelpBoardDetail-BbZziqts.js"),__vite__mapDeps([320,318,14]))),Y3t=P.lazy(()=>Be(()=>import("./Newsletters-CobTDp9Q.js"),__vite__mapDeps([321,322,253,323,184,324,185,98,161,310,153,271,325,326,84,327,117,328,6,169,142,143,144,329,330,289,331,215,332,78]))),Z3t=P.lazy(()=>Be(()=>import("./NewsletterDetail-BgCwunF3.js"),__vite__mapDeps([333,164,203,204,327,322,253,323,184,324,185,98,161,310,153,271,325,117,328,6,169,142,143,144,329,330,289,331,215,332,78]))),X3t=P.lazy(()=>Be(()=>import("./Newsletters-CY42IWdf.js"),__vite__mapDeps([334,286,157,178,179,180,181,182,183,184,185,186,187,98,323,136,335]))),Q3t=P.lazy(()=>Be(()=>import("./MemberBroadcasts-BiC_7Pwp.js"),__vite__mapDeps([336,157,178,179,180,181,182,183,184,185,186,187,98,218,201,308,337,84]))),J3t=P.lazy(()=>Be(()=>import("./BoostAnnouncements--orjuIF7.js"),__vite__mapDeps([338,157,8]))),e5t=P.lazy(()=>Be(()=>import("./NewsletterGraphics-CkM2i9ll.js"),__vite__mapDeps([339,157,159]))),t5t=P.lazy(()=>Be(()=>import("./Wishlist-DI0vovFP.js"),__vite__mapDeps([340,153]))),r5t=P.lazy(()=>Be(()=>import("./WishlistDetail-BJVc2PCO.js"),__vite__mapDeps([341,256,153]))),n5t=P.lazy(()=>Be(()=>import("./Wishlist-BO8pUfzh.js"),[])),i5t=P.lazy(()=>Be(()=>import("./LevelUpBrief-UmtB5RZc.js"),__vite__mapDeps([342,157,178,179,180,181,182,183,184,185,186,187,98]))),s5t=P.lazy(()=>Be(()=>import("./AdditionalServices-COOxpeZH.js"),__vite__mapDeps([343,178,179,180,181,182,183,184,185,186,187,98]))),a5t=P.lazy(()=>Be(()=>import("./Discounts-DFcFVeue.js"),__vite__mapDeps([344,157]))),o5t=P.lazy(()=>Be(()=>import("./Subscriptions-CpaQgZmI.js"),__vite__mapDeps([345,157,346,93,281]))),l5t=P.lazy(()=>Be(()=>import("./InstagramGiftEmails-CyW3OlT1.js"),__vite__mapDeps([347,346,310]))),c5t=P.lazy(()=>Be(()=>import("./Referrals-b7y-7TO_.js"),__vite__mapDeps([348,157,74,87]))),u5t=P.lazy(()=>Be(()=>import("./OnboardingChecklist-B536Tj_B.js"),[])),d5t=P.lazy(()=>Be(()=>import("./AgentOSControlCenter-v1cCtxJQ.js"),__vite__mapDeps([349,157,125,123,136]))),h5t=P.lazy(()=>Be(()=>import("./AdditionalServices-dF_BnWIo.js"),[])),f5t=P.lazy(()=>Be(()=>import("./AdditionalServiceDetail-DgztYqpT.js"),[])),p5t=P.lazy(()=>Be(()=>import("./AIToolkit-DVR33QCi.js"),[])),m5t=P.lazy(()=>Be(()=>import("./AskAI-hCvsVa86.js"),__vite__mapDeps([350,2,3,6]))),g5t=P.lazy(()=>Be(()=>import("./InnerCircleHome-DrswTsuU.js"),__vite__mapDeps([351,174,175,352,9,153,271,281,353,169,141,140,142,143,144,145,146,147,354,355,356,357,358,161]))),y5t=P.lazy(()=>Be(()=>import("./InnerCircleContacts-WxA4Djay.js"),__vite__mapDeps([359,360,221,213,361,253,153,271,362,363,275,272,276,277,201,278,6,279,352,364,365,9,366,329,215,229,367,175,368,217,369,355,140,370,371,372,373,310,374,375,376,98,142,141,143,144,145,146,147,169,330,337,377,378,379,380,381,44,382,197,10,84,129,130,78,383,185]))),x5t=P.lazy(()=>Be(()=>import("./InnerCircleContactDetail-CQm-b48t.js"),__vite__mapDeps([384,381,140,360,169,142,141,143,144,145,146,147,385,376,365,175,329,364,352,9,366,215,229,367,386,281,382,10,84,197,380,387,388,221,213,389,390,201,267,391,392,264,289,354,355,356,357]))),_5t=P.lazy(()=>Be(()=>import("./SentEmails-Dv2MKo5t.js"),__vite__mapDeps([393,169,141,140,142,143,144,145,146,147,388,190,161,197,101,87,367]))),v5t=P.lazy(()=>Be(()=>import("./InnerCirclePlans-b4qp2OSX.js"),__vite__mapDeps([394,74,395,84,281,353]))),b5t=P.lazy(()=>Be(()=>import("./CMAList-Bek4luu6.js"),__vite__mapDeps([396,385,397,398]))),w5t=P.lazy(()=>Be(()=>import("./CMABuilder-CVl_K1aK.js"),__vite__mapDeps([399,385,397,374,400,162,401,402,403,404,310,6,9,84]))),S5t=P.lazy(()=>Be(()=>import("./ListingPresentations-CIHhqI2b.js"),__vite__mapDeps([405,406,407,133,408]))),T5t=P.lazy(()=>Be(()=>import("./ListingPresentationBuilder-CAKtiV4Z.js"),__vite__mapDeps([409,140,212,213,410,411,133,406,407,412,159,6,218,153,271,408,84,337,413]))),E5t=P.lazy(()=>Be(()=>Promise.resolve().then(()=>ort),void 0)),A5t=P.lazy(()=>Be(()=>import("./InnerCirclePopbys-BzLNVLdE.js"),__vite__mapDeps([414,360,365,415,416,74]))),k5t=P.lazy(()=>Be(()=>import("./ListingExchange-BLyMOvou.js"),__vite__mapDeps([417,129,130,418,125,137,55,419,329,378,379,377,143,144,215,200,420,390]))),C5t=P.lazy(()=>Be(()=>import("./ListingDetail-BkhSUWHk.js"),__vite__mapDeps([421,132,129,130,133,420,137,418,125,138,139,140,141,142,143,144,145,146,147,229,10,55,149]))),Ece=P.lazy(()=>Be(()=>import("./ListingForm-CYHnUVRP.js"),__vite__mapDeps([422,135,129,130,134,136,376,335,132,133,78]))),j5t=P.lazy(()=>Be(()=>import("./CustomizeListingPage-BPfH9GQ9.js"),__vite__mapDeps([423,310,84,300,424,98,136])));function I5t(){const{search:t}=Wi();return o.jsx(ki,{to:`/video-studio${t}`,replace:!0})}const P5t=P.lazy(()=>Be(()=>import("./VideoStudio-DSpu9F6u.js"),__vite__mapDeps([425,426,328,230,231,376,427,122,123,124,31,44,108,7,125,126,127,221,213,98,192,428,90,119,429,402,162,278,430,431,55,9,401,404,78,310,335,432,84,6,241,433,434,149]))),N5t=P.lazy(()=>Be(()=>import("./StudioGuestJoin-DE8cSrue.js"),__vite__mapDeps([435,429,230,231,402,162,278,431,436,404,433]))),R5t=P.lazy(()=>Be(()=>import("./VideoLibrary-3IO2QVlX.js"),__vite__mapDeps([437,376,375,427,122,123,124,31,44,108,7,125,126,127,221,213,98,140,370,169,299,438,308]))),L5t=P.lazy(()=>Be(()=>import("./DealPipeline-B8EbtsMy.js"),__vite__mapDeps([439,440,116,187,186,441,391,442,271,89,276,3,153,443,444,162,445,10,35,52,184,337,424,446,447,126,390,282,96,448,42,449,450,62,302,74,451,87,431,452,453,454,124,331,308,127,264,426,363,280,455,93,281,267,125,278,238,456,41,78,457,458,459,176,460,148,217,461,261,123,266,401,83,462,463,464,465,136,466,279,438,14,182,183,467,468,201,469,159,91,111,367,470,218,335,98,332,185,471,415,472,119,103,358,473,197,383,15,20,200,474,475,243,476,477,436,404,206,403,310,32,161,299,478,413,231,55,416,479,430,300,147,108,9,353,395,117,258,152,54,480,481,482,149,115,483,362,233,287,257,6,190,220,84,432,484,241,289,485,486,265,487,72,207,44,155,380,357,277,7,433,488,215,489,490,43,491,31,53,27,492,434,324,328,229,70,204,90,493,494,196,382,495,309,45,112,189,366,129,130,386,496,221,213,497,498,499,500,374,501,400,402,376,169,502,212,503,504]))),D5t=P.lazy(()=>Be(()=>import("./FormsLibrary-NH01TNah.js"),__vite__mapDeps([505,499,506,84,411,446,434,490,498,457,153,271,456,391,460]))),O5t=P.lazy(()=>Be(()=>import("./TransactionCoordinator-6kUk2Ms-.js"),__vite__mapDeps([507,502,212,213,287]))),M5t=P.lazy(()=>Be(()=>import("./PortalReferrals-Cu5lvAK5.js"),__vite__mapDeps([508,509]))),F5t=P.lazy(()=>Be(()=>import("./AgentVendors-CNRTT_mQ.js"),__vite__mapDeps([510,511,78]))),B5t=P.lazy(()=>Be(()=>import("./BrokerageForms-DchZ2WB-.js"),__vite__mapDeps([512,499,506,84,411,446,434,490,462,463,391]))),z5t=P.lazy(()=>Be(()=>import("./BrokerageVendors-DGgazgzY.js"),__vite__mapDeps([513,511,78]))),$5t=P.lazy(()=>Be(()=>import("./ClientPortalsHub-YpV4G6rh.js"),__vite__mapDeps([514,503,84,386,500,136,229,374,501,400,162,401,402,403,404,310,6,9,376,74,98,10,169,441,475,391,515,510,511,78,508,509,112]))),U5t=P.lazy(()=>Be(()=>import("./ClientPortalDetail-CxDLmP4d.js"),__vite__mapDeps([516,386,509,500,136,229,374,501,400,162,401,402,403,404,310,6,9,376,74,98,84,10,169,515,475,441,391]))),V5t=P.lazy(()=>Be(()=>import("./MyCardEditor-DQssayrF.js"),__vite__mapDeps([517,188,189,190,191,518,215,136,153,271,78,243,139,310,93,149,161]))),q5t=P.lazy(()=>Be(()=>import("./Integrations-DtJKKJ3Q.js"),__vite__mapDeps([519,221,213,361,253,153,271,74,489,520,101,521,140,325,84,228,36,522,100,70,231,495,241]))),G5t=P.lazy(()=>Be(()=>import("./BrowserExtension-BhPrkDKB.js"),__vite__mapDeps([523,302]))),H5t=P.lazy(()=>Be(()=>import("./IntegrationsGmailCallback-CCGfrY1k.js"),__vite__mapDeps([524,74,87]))),W5t=P.lazy(()=>Be(()=>import("./IntegrationsCanvaCallback-C0JrRwMQ.js"),[])),K5t=P.lazy(()=>Be(()=>import("./IntegrationsMetaCallback-9kley_ls.js"),__vite__mapDeps([525,74,87]))),Y5t=P.lazy(()=>Be(()=>import("./ScorecardAdmin-TSAH4tae.js"),[])),Z5t=P.lazy(()=>Be(()=>import("./AgentActivation-H6Fc1loY.js"),__vite__mapDeps([526,157,103,382]))),Ace=P.lazy(()=>Be(()=>import("./ScorecardAgentView-BKMnMIII.js"),[])),X5t=P.lazy(()=>Be(()=>import("./ListingExchange-DcDSoMjH.js"),[])),Q5t=P.lazy(()=>Be(()=>import("./ListingLeads-c2PvQ3q4.js"),[])),J5t=P.lazy(()=>Be(()=>import("./PublicSiteLeads-CLLVJ_ph.js"),[])),e4t=P.lazy(()=>Be(()=>import("./MembershipReviews-Ctrxj0N1.js"),__vite__mapDeps([527,157]))),t4t=P.lazy(()=>Be(()=>import("./LeadNotifications-BMFd9X1b.js"),__vite__mapDeps([528,157]))),r4t=P.lazy(()=>Be(()=>import("./WeeklyDigest-DtwBgLub.js"),__vite__mapDeps([529,87]))),n4t=P.lazy(()=>Be(()=>import("./AgentPoints-CRniqOos.js"),__vite__mapDeps([530,201]))),i4t=P.lazy(()=>Be(()=>import("./AgentCards-D-1AUYJn.js"),__vite__mapDeps([531,188,189,190,191,518,215,136,153,271,78,243,488]))),s4t=P.lazy(()=>Be(()=>import("./Marketplace-qjaBREIw.js"),__vite__mapDeps([532,159,215,83]))),a4t=P.lazy(()=>Be(()=>import("./RewardStore-fAxKsWij.js"),__vite__mapDeps([533,534,83,98,84]))),o4t=P.lazy(()=>Be(()=>import("./Integrations-BFtQfsCx.js"),__vite__mapDeps([535,157,228,36,227,229,266,520,101,74]))),l4t=P.lazy(()=>Be(()=>import("./SocialConnections-B6hO-F8D.js"),__vite__mapDeps([536,157]))),c4t=P.lazy(()=>Be(()=>import("./SocialAutopilot-jYvgaXAl.js"),__vite__mapDeps([537,157,230,231,232,84]))),u4t=P.lazy(()=>Be(()=>import("./McpUpdates-8lXVrSDI.js"),__vite__mapDeps([538,157]))),d4t=P.lazy(()=>Be(()=>import("./RefreshMcpTools-DjnC0uKp.js"),[])),h4t=P.lazy(()=>Be(()=>import("./NotificationSettings-DajI5V8d.js"),__vite__mapDeps([539,157]))),f4t=P.lazy(()=>Be(()=>import("./PresentationAnalytics-DGqMqcf6.js"),__vite__mapDeps([540,270,153,271,161]))),p4t=P.lazy(()=>Be(()=>import("./ListingPresentationStudioAdmin-e6qb6orv.js"),__vite__mapDeps([541,157]))),m4t=P.lazy(()=>Be(()=>import("./ListingRevivalAdmin-BFvqw6Q_.js"),__vite__mapDeps([542,157,543]))),g4t=P.lazy(()=>Be(()=>import("./GuestBookAnalytics-CpyQlRJv.js"),__vite__mapDeps([544,74]))),y4t=P.lazy(()=>Be(()=>import("./IntegrationsCallback-Cc-fO1SL.js"),__vite__mapDeps([545,74,87]))),x4t=P.lazy(()=>Be(()=>import("./Prospector-BWKwgg0u.js"),[])),_4t=P.lazy(()=>Be(()=>import("./AdminRecruiting-DHCyS9sd.js"),__vite__mapDeps([546,547,136,140,400,162,401,402,403,404,310,6,9,376,84,299,217,153,271,87,459,91,335,168,221,213,521,101,179,180,307,548,184,324,450,182,183,467,185,186,187,98,309,161,14,44,7,143,144,74,485]))),v4t=P.lazy(()=>Be(()=>import("./BrokerageRecruiting-DH4QVfWl.js"),__vite__mapDeps([549,547,136,140,400,162,401,402,403,404,310,6,9,376,84,299,217,153,271,87,459,91,335,168,221,213,521,101,179,180,307,548,184,324,450,182,183,467,185,186,187,98,309,161,14,44,7,143,144,74,495,452,358,494,238,550]))),b4t=P.lazy(()=>Be(()=>import("./BrokerageOnboarding-4uVblTTo.js"),__vite__mapDeps([551,314,315,87,6,84,170,495,452,457,493,153,271,550]))),w4t=P.lazy(()=>Be(()=>import("./BrokerageTransactions-BgJChh_y.js"),__vite__mapDeps([552,497,201,461,87,553,504,457,83]))),S4t=P.lazy(()=>Be(()=>import("./BrokerageOperations-BmcOwe6d.js"),__vite__mapDeps([554,555,504,314,471]))),T4t=P.lazy(()=>Be(()=>import("./WebsitesHub-ClhEgLSo.js"),__vite__mapDeps([556,557]))),E4t=P.lazy(()=>Be(()=>import("./TeamWebsite-vRCoHE1H.js"),__vite__mapDeps([558,559,64,78,560,557]))),A4t=P.lazy(()=>Be(()=>import("./BrokerageWebsite-Ckwd1KfY.js"),__vite__mapDeps([561,559,64,78,560,557]))),k4t=P.lazy(()=>Be(()=>import("./BrokerageCommissionPlans-CyrAF_bE.js"),__vite__mapDeps([562,496,504,407,459,555,469,108,362,162,115,553,382]))),C4t=P.lazy(()=>Be(()=>import("./BrokerageContentActivity-CKieVcvF.js"),__vite__mapDeps([563,157]))),j4t=P.lazy(()=>Be(()=>import("./BetaSocialPostGenerator-AhJq0UeD.js"),__vite__mapDeps([564,157,172,250,251,215,20,6]))),I4t=P.lazy(()=>Be(()=>import("./AdminLMS-BQyq351Z.js"),__vite__mapDeps([565,566,185,487,78]))),P4t=P.lazy(()=>Be(()=>import("./AdminCourseDetail-B7SMmP-Y.js"),__vite__mapDeps([567,566,185,487,78,159,84]))),N4t=P.lazy(()=>Be(()=>import("./AdminLMSStats-Co8cwsOf.js"),[])),R4t=P.lazy(()=>Be(()=>import("./LevelUpU-DV7LrBlS.js"),__vite__mapDeps([568,566,185,487]))),L4t=P.lazy(()=>Be(()=>import("./LevelUpUCourse-5IBTmmsD.js"),__vite__mapDeps([569,566]))),D4t=P.lazy(()=>Be(()=>import("./MobileAgentApp-DcH_7M1R.js"),__vite__mapDeps([570,91,169,329,141,140,142,143,144,145,146,147,215,20,42,44,278]))),O4t=P.lazy(()=>Be(()=>import("./StagingStudio-CJgdCX-e.js"),__vite__mapDeps([571,212,213,572,453,456,53,159,573,574,41,575,193,194,241,83]))),M4t=P.lazy(()=>Be(()=>import("./StagingLibrary-4xzDWnTw.js"),__vite__mapDeps([576,572,453,456,53,573,193,462,83]))),F4t=P.lazy(()=>Be(()=>import("./StagingCredits-BkdmIITT.js"),__vite__mapDeps([577,575,193,194,93]))),B4t=P.lazy(()=>Be(()=>import("./AgentWallet-gL_EXWlH.js"),__vite__mapDeps([578,392,193,579,266,194,289]))),z4t=P.lazy(()=>Be(()=>import("./StagingSharePage-B57914wZ.js"),__vite__mapDeps([580,574]))),$4t=P.lazy(()=>Be(()=>import("./StagingStudioAdmin-BIeUKp9A.js"),__vite__mapDeps([581,572,453,456,53,5,193,574,89]))),U4t=P.lazy(()=>Be(()=>import("./ContactFinderAdmin-BIg006HV.js"),__vite__mapDeps([582,392]))),V4t=P.lazy(()=>Be(()=>import("./PostcardManager-CR_8ZiwV.js"),__vite__mapDeps([583,584,247,248,585,434,186,84]))),q4t=P.lazy(()=>Be(()=>import("./MailStudioTemplates-B3tuz4Pn.js"),__vite__mapDeps([586,584,247,248,585,434,186,84,153,271]))),G4t=P.lazy(()=>Be(()=>import("./HomeReelManager-DCo5xsx3.js"),__vite__mapDeps([587,579,266,588,55,9,335,310,135,478,434,431,136,276,432,84,267,264,420,337]))),H4t=P.lazy(()=>Be(()=>import("./AdminMusicVideos-BrcU9BNL.js"),__vite__mapDeps([589,55]))),W4t=P.lazy(()=>Be(()=>import("./AdminVideoLab-DwlH66H2.js"),__vite__mapDeps([590,588,55,431,9,159,6,483]))),K4t=P.lazy(()=>Be(()=>import("./BoostPreview-DBfkazE7.js"),__vite__mapDeps([591,1,2,3,4,5,6,7]))),Y4t=P.lazy(()=>Be(()=>import("./AdminCredits-DxXe8lQm.js"),__vite__mapDeps([592,157,201,451]))),Z4t=P.lazy(()=>Be(()=>import("./AdminCleanup-DtgGgyqP.js"),[])),X4t=P.lazy(()=>Be(()=>import("./MailStudio-DJ9WILO7.js"),__vite__mapDeps([593,585,247,248,407,84,434,159,6,413,186,187,444,378,379,594,356,280,15,489,595,192,428,215,125,229,410,411,355,162,482,149,201,596]))),Q4t=()=>{const t=Wi();return o.jsx(ki,{to:`/mission-control/direct-mail${t.search}`,replace:!0})},J4t=P.lazy(()=>Be(()=>import("./InnerCirclePopbyMap-YlyB4HOu.js"),__vite__mapDeps([597,365,415,416,74]))),eBt=P.lazy(()=>Be(()=>import("./SphereMap-CQaxW25m.js"),__vite__mapDeps([598,379,140,430,381,355,594,416,3,329,371,372,373,310,374,375,376,98,141,142,143,144,145,146,147,169,215,383,220,153,271,392,367,328,424,470]))),tBt=P.lazy(()=>Be(()=>import("./PropertyIntelligenceDashboard-FxvNuWhY.js"),__vite__mapDeps([599,389,447,267,390]))),rBt=P.lazy(()=>Be(()=>import("./LiveVisitorFeed-CJhQ_8xK.js"),__vite__mapDeps([600,277]))),nBt=P.lazy(()=>Be(()=>import("./LeadSites-BB79sgUd.js"),__vite__mapDeps([601,481,480]))),kce=P.lazy(()=>Be(()=>import("./LeadSiteEditor-D0r5VUIw.js"),__vite__mapDeps([602,108,603,440,116,187,186,441,391,442,271,89,276,3,153,443,444,162,445,10,35,52,184,337,424,446,447,126,390,282,96,448,42,449,450,62,302,74,451,87,431,452,453,454,124,331,308,127,264,426,363,280,455,93,281,267,125,278,238,456,41,78,457,458,459,176,460,148,217,461,261,123,266,401,83,462,463,464,465,136,466,279,438,14,182,183,467,468,201,469,159,91,111,367,470,218,335,98,332,185,471,415,472,119,103,358,473,197,383,15,20,200,474,475,243,476,477,436,404,206,403,310,32,161,299,478,413,231,55,416,479,430,300,147,9,353,395,117,258,152,54,480,481,482,149,115,483,362,233,287,257,6,190,220,84,432,484,241,289,485,486,265,487,72,207,44,155,380,357,277,7,433,488,215,489,490,43,491,31,53,27,492,434,324,328,229,70,204,90,493,494,196,382,495,309,45,112,189,604,135,605,58,398,606]))),iBt=P.lazy(()=>Be(()=>import("./AdminLeadSiteThemes-CJ_1OpWd.js"),__vite__mapDeps([607,603,605,300,434,281,465]))),sBt=P.lazy(()=>Be(()=>import("./AdminFreeWebsiteOffers-b3rc_ykC.js"),[])),aBt=P.lazy(()=>Be(()=>import("./AdminPartnerships-B5_B6QkF.js"),[])),oBt=P.lazy(()=>Be(()=>import("./MyPartnership-kurvMlS0.js"),[])),lBt=P.lazy(()=>Be(()=>import("./UpgradeFeature-Bs45zqFV.js"),[])),cBt=P.lazy(()=>Be(()=>import("./CoachingOnboarding-Ez3BXEUO.js"),[])),uBt=P.lazy(()=>Be(()=>import("./AdminFreeWebsiteOfferStudio-Dhm8oGKu.js"),__vite__mapDeps([608,603,604,135,605,14,15,32,300,136,78,434,125,31,84]))),dBt=P.lazy(()=>Be(()=>import("./AdminMlsFeeds-UxHXYzqb.js"),__vite__mapDeps([609,267]))),hBt=P.lazy(()=>Be(()=>import("./AdminLeadSiteAnalytics-PJQR8Wpm.js"),[])),fBt=P.lazy(()=>Be(()=>import("./AdminWebsiteInterests-CvUqOG7w.js"),[])),pBt=P.lazy(()=>Be(()=>import("./AdminWebsiteRequests-pwjMHHHw.js"),__vite__mapDeps([610,87]))),mBt=P.lazy(()=>Be(()=>import("./NeedAWebsite-Db7N2eps.js"),__vite__mapDeps([611,195,218,161,443]))),gBt=P.lazy(()=>Be(()=>import("./AdminMlsFeeTracker-hCE8M4YI.js"),[])),yBt=P.lazy(()=>Be(()=>import("./MLSListings-BLfwbm32.js"),__vite__mapDeps([612,398,14,420,419,329,378,379,377,143,144,215,241,78,337,20,55]))),xBt=P.lazy(()=>Be(()=>import("./MLSListingDetail-D_3eQt7e.js"),__vite__mapDeps([613,169,142,329,215,78,374,46,140,139,407,482,149,20,492]))),_Bt=P.lazy(()=>Be(()=>import("./MarketReportPage-Ck9jNHS8.js"),[]));P.lazy(()=>Be(()=>import("./WebsiteActivityPage-D4AWT2GM.js"),__vite__mapDeps([614,169,141,140,142,143,144,145,146,147,15])));const vBt=P.lazy(()=>Be(()=>import("./PublicRecruitForm-BB-kz8VW.js"),__vite__mapDeps([615,30,459]))),bBt=P.lazy(()=>Be(()=>import("./PublicRecruitVideo-FLgsp055.js"),[])),wBt=P.lazy(()=>Be(()=>import("./PublicRecruitUnsubscribe-D9MrPIEy.js"),[])),SBt=P.lazy(()=>Be(()=>import("./PublicEventInviteUnsubscribe-DfBDBNBT.js"),__vite__mapDeps([616,448]))),TBt=P.lazy(()=>Be(()=>import("./SocialConnections-BoXB26A8.js"),__vite__mapDeps([617,74,231,266,87]))),EBt=P.lazy(()=>Be(()=>import("./SocialConnectionsCallback-5tW7QJpm.js"),__vite__mapDeps([618,74,87]))),ABt=P.lazy(()=>Be(()=>import("./SocialConnectionsGoogleCallback-BqVlxXSn.js"),[])),kBt=P.lazy(()=>Be(()=>import("./LinkedInCallback-DSF4apqS.js"),__vite__mapDeps([619,74,87]))),CBt=P.lazy(()=>Be(()=>import("./TikTokCallback-BcjzXx5U.js"),__vite__mapDeps([620,74,87,231]))),jBt=P.lazy(()=>Be(()=>import("./MarketplaceProductDetail-D-bCLxzX.js"),[])),IBt=P.lazy(()=>Be(()=>import("./MarketplaceCart-6Ef30jfV.js"),__vite__mapDeps([621,140,265]))),PBt=P.lazy(()=>Be(()=>import("./MarketplaceOrders-tos3zHUG.js"),[])),NBt=P.lazy(()=>Be(()=>import("./MarketplaceOrderDetail-Dzgys1A3.js"),__vite__mapDeps([622,140,176,491,27]))),RBt=P.lazy(()=>Be(()=>import("./MarketplaceSuccess-Ds9UYKZT.js"),[])),LBt=P.lazy(()=>Be(()=>import("./RewardStore-CXTDkQUw.js"),__vite__mapDeps([623,534,221,213,265]))),DBt=P.lazy(()=>Be(()=>import("./ReferFriends-B5u3d3T9.js"),__vite__mapDeps([624,140,169]))),OBt=P.lazy(()=>Be(()=>import("./SmartPresentations-6k10UHxo.js"),__vite__mapDeps([625,626,391]))),Cce=P.lazy(()=>Be(()=>import("./SmartPresentationCreate-Bc1IHHbQ.js"),__vite__mapDeps([627,178,179,180,181,182,183,184,185,186,187,98,400,162,401,402,403,404,310,6,9,628,78,376,74,374,626,169,141,140,142,143,144,145,146,147,136,159]))),MBt=P.lazy(()=>Be(()=>import("./PublicPresentation-1nw2-Y8j.js"),[])),FBt=P.lazy(()=>Be(()=>import("./GuestBook-CcBULnob.js"),__vite__mapDeps([629,140,139,372,380,136,374,91,391,169,143,98,215,149,369,355,159,201,78,482]))),BBt=P.lazy(()=>Be(()=>Promise.resolve().then(()=>AZe),void 0)),zBt=P.lazy(()=>Be(()=>Promise.resolve().then(()=>IZe),void 0)),$Bt=P.lazy(()=>Be(()=>import("./PublicResourceLanding-B30s9Cia.js"),[])),UBt=P.lazy(()=>Be(()=>import("./SignDocument-BW3l-X_F.js"),__vite__mapDeps([630,411,87,434,490,456]))),VBt=P.lazy(()=>Be(()=>import("./Blog-Cxe7YgqW.js"),__vite__mapDeps([631,632]))),qBt=P.lazy(()=>Be(()=>import("./BlogPost-sSN5_57O.js"),__vite__mapDeps([633,632,455,492]))),GBt=P.lazy(()=>Be(()=>import("./AdminBlog-rYsVHr1I.js"),__vite__mapDeps([634,140,179,181,548,184,324,183,467,185,308,186,187,98,159,78]))),HBt=P.lazy(()=>Be(()=>import("./ReviewLanding-w8iZ4b12.js"),__vite__mapDeps([635,636,400,162,401,402,403,404,310,6,9]))),WBt=P.lazy(()=>Be(()=>import("./PublicReviewsPage-CzcFnt9M.js"),__vite__mapDeps([637,443,476]))),KBt=P.lazy(()=>Be(()=>import("./PublicReviewSubmit-CZ18nQXU.js"),__vite__mapDeps([638,636,400,162,401,402,403,404,310,6,9]))),YBt=P.lazy(()=>Be(()=>import("./Reviews-DNmYouE9.js"),__vite__mapDeps([639,139,133,234,235,236,230,231,241,443,152,257,78,70,331,149,367]))),ZBt=P.lazy(()=>Be(()=>import("./ClientPortalPage-ClnM_DQK.js"),[])),XBt=P.lazy(()=>Be(()=>Promise.resolve().then(()=>rrt),void 0)),QBt=P.lazy(()=>Be(()=>import("./CardStudio-DaE7xb9I.js"),__vite__mapDeps([640,376,501,400,162,401,402,403,404,310,6,9,74,235,169,146]))),JBt=P.lazy(()=>Be(()=>import("./ListingStudio-DSJJYanw.js"),__vite__mapDeps([641,159,281,125,458,108,404,54,358,35]))),ezt=P.lazy(()=>Be(()=>Promise.resolve().then(()=>GIt),void 0)),tzt=P.lazy(()=>Be(()=>import("./SmartDrips-Chh4aGyN.js"),__vite__mapDeps([642,140,169,481,395,374,501,400,162,401,402,403,404,310,6,9,376,74,372,373,375,98,387,367,282]))),rzt=P.lazy(()=>Be(()=>import("./WeeklyReels-DB8CKQKC.js"),__vite__mapDeps([643,212,213,644,140,221,645,431,239,241]))),nzt=P.lazy(()=>Be(()=>import("./WeeklyReelsOnboarding-Cdk_u_DS.js"),__vite__mapDeps([646,645]))),izt=P.lazy(()=>Be(()=>import("./WeeklyReelsAdmin-Dk_77-SV.js"),__vite__mapDeps([647,239,645,644,140,221,213,431]))),szt=P.lazy(()=>Be(()=>import("./AttractLayout-CzEBTdSG.js"),__vite__mapDeps([648,649,650,651,155,7,238]))),azt=P.lazy(()=>Be(()=>import("./AttractToday-C3pt_hhb.js"),__vite__mapDeps([652,221,213,650,653,654,655,656,657,367,335,468,658,659,495,282,477,660,486]))),ozt=P.lazy(()=>Be(()=>import("./AttractRelationships-QXy_G11s.js"),__vite__mapDeps([661,662,658,654,659,217,663,391,655,650,653,495]))),lzt=P.lazy(()=>Be(()=>import("./AttractFollowUp-TReIMQnx.js"),__vite__mapDeps([664,662,655,654,127]))),czt=P.lazy(()=>Be(()=>import("./AttractResources-D2_02vqF.js"),[])),uzt=P.lazy(()=>Be(()=>import("./AttractTemplates-BGzozfCi.js"),__vite__mapDeps([665,127,287]))),dzt=P.lazy(()=>Be(()=>import("./AttractReports-AukJkuau.js"),__vite__mapDeps([666,662,654,656,659,301]))),hzt=P.lazy(()=>Be(()=>import("./AttractSettings-DWpGNt05.js"),__vite__mapDeps([667,662,649,6]))),fzt=P.lazy(()=>Be(()=>import("./AttractToolkit-hUjkgoWm.js"),__vite__mapDeps([668,662,243,486,282,335]))),pzt=P.lazy(()=>Be(()=>import("./Objections-Bzx3ROYE.js"),__vite__mapDeps([669,486]))),mzt=P.lazy(()=>Be(()=>import("./AttractCalculator-CKnmFbkM.js"),__vite__mapDeps([670,662,671,482]))),gzt=P.lazy(()=>Be(()=>import("./AttractEventList-Z0migxh8.js"),__vite__mapDeps([672,660]))),jce=P.lazy(()=>Be(()=>import("./AttractEventBuilder-lRU6Okv4.js"),__vite__mapDeps([673,140,660,674,98,84]))),yzt=P.lazy(()=>Be(()=>import("./AttractEventDetail-CwTWmoKd.js"),__vite__mapDeps([675,660,654,149,243]))),xzt=P.lazy(()=>Be(()=>import("./AttractEventCheckIn-L9JpuW1n.js"),__vite__mapDeps([676,428,660,149]))),_zt=P.lazy(()=>Be(()=>import("./AttractOnboarding-D2Y7GNDi.js"),__vite__mapDeps([677,649,155,466,282]))),vzt=P.lazy(()=>Be(()=>import("./ContentStudio-Cc4bdLpo.js"),__vite__mapDeps([678,662,484]))),bzt=P.lazy(()=>Be(()=>import("./KitList-Dp-qmbGR.js"),__vite__mapDeps([679,674,335,117]))),Ice=P.lazy(()=>Be(()=>import("./KitBuilder-DD5b_pdy.js"),__vite__mapDeps([680,674,654,662,681,98,243,153,271,310,162]))),wzt=P.lazy(()=>Be(()=>import("./KitAnalytics-CfXcRkfD.js"),__vite__mapDeps([682,674,662,161,301]))),Szt=P.lazy(()=>Be(()=>import("./KitTemplates-CjqmP3LT.js"),__vite__mapDeps([683,674,662]))),Tzt=P.lazy(()=>Be(()=>import("./AttractAgentDetail-CC1sMV9s.js"),__vite__mapDeps([684,663,654,391,141,140,142,143,144,145,146,147,169,650,655,651,657,367,335,468,659,7,277,276,495,44]))),Ezt=P.lazy(()=>Be(()=>import("./AttractOpportunities-BPudArYm.js"),__vite__mapDeps([685,650,653,657,367,335,468]))),Azt=P.lazy(()=>Be(()=>import("./AttractIntelligenceDebug-DP0otB8-.js"),__vite__mapDeps([686,650,651,445]))),kzt=P.lazy(()=>Be(()=>import("./AttractToolsQA-C10_ijcT.js"),[])),Czt=P.lazy(()=>Be(()=>import("./PublicAttractKit-Cs7jmRHJ.js"),__vite__mapDeps([687,681,98,243]))),jzt=P.lazy(()=>Be(()=>import("./PublicAttractEvent-DSvBiYWg.js"),__vite__mapDeps([688,660]))),Izt=P.lazy(()=>Be(()=>import("./PublicAttractEventCheckIn-CzrZoJXZ.js"),[])),Pzt=P.lazy(()=>Be(()=>import("./PublicAttractionPage-B1N8Qf9l.js"),__vite__mapDeps([689,690,212,213]))),Nzt=P.lazy(()=>Be(()=>import("./RevivalLanding-nVNMsGUT.js"),__vite__mapDeps([691,692]))),Pce=P.lazy(()=>Be(()=>import("./RevivalPlan-C-zq3ITw.js"),__vite__mapDeps([693,694,139,692,407,428]))),Rzt=P.lazy(()=>Be(()=>import("./ListingRevival-B7vxl_vN.js"),__vite__mapDeps([695,696,692,543,454,217,149,697,218,241,391,441]))),Lzt=P.lazy(()=>Be(()=>import("./RevivalCampaignWizard-EvlNS_VR.js"),__vite__mapDeps([698,412,406,407,159,696,692,699,250,595]))),Dzt=P.lazy(()=>Be(()=>import("./RevivalCampaignDetail-Cj4vzpV_.js"),__vite__mapDeps([700,139,699,250,407,595,701,196,464,84,369,355,696,692,694,428,400,162,401,402,403,404,310,6,9,376,74,412,406,159,78,149,220,482,459,35]))),Ozt=P.lazy(()=>Be(()=>import("./FsboBreakthrough-Cf9x2q9y.js"),__vite__mapDeps([702,703,704,705,412,406,407,159,149,697,218,241,391,441]))),Mzt=P.lazy(()=>Be(()=>import("./FsboCampaignWizard-CCGq3lr8.js"),__vite__mapDeps([706,412,406,407,159,703,704,699,250,595]))),Fzt=P.lazy(()=>Be(()=>import("./FsboCampaignDetail-Dl-W8PNn.js"),__vite__mapDeps([707,139,699,250,407,595,701,196,464,84,703,704,369,355,705,412,406,159,192,459,482]))),Bzt=P.lazy(()=>Be(()=>import("./FsboLanding-d2WyjI8M.js"),__vite__mapDeps([708,704,709]))),zzt=P.lazy(()=>Be(()=>import("./FsboGuide-DQYn2D4U.js"),__vite__mapDeps([710,709]))),$zt=P.lazy(()=>Be(()=>import("./FsboBreakthroughAdmin-DxC_NM9h.js"),__vite__mapDeps([711,703,149,697]))),Uzt=P.lazy(()=>Be(()=>import("./AttractLandingPageBuilder-Bmsaeknb.js"),__vite__mapDeps([712,671,690,212,213,84]))),Vzt=P.lazy(()=>Be(()=>import("./AttractAccess-BLj_aJ0R.js"),__vite__mapDeps([713,157,201,87]))),qzt=P.lazy(()=>Be(()=>import("./Teams-BE3uO2Vl.js"),__vite__mapDeps([714,272,281,273,274,275,276,277,201,278,6,279,280,83,90]))),Gzt=P.lazy(()=>Be(()=>import("./MyTeam-Ch6pGmn7.js"),__vite__mapDeps([715,272,275,276,277,201,278,6,279,274,716,281,280,83]))),Hzt=P.lazy(()=>Be(()=>import("./TeamHub-C3O_2ulo.js"),__vite__mapDeps([717,272,275,276,277,201,278,6,279,274,716,559,64,78,281,280,83]))),Wzt=P.lazy(()=>Be(()=>import("./SchedulerSettings-zQ3l43z0.js"),__vite__mapDeps([718,95,96,97,70,140,474,87,522,100,101,241]))),Kzt=P.lazy(()=>Be(()=>import("./MyCalendar-rDlxKC_n.js"),__vite__mapDeps([719,97,235,237,236,238]))),Yzt=P.lazy(()=>Be(()=>Promise.resolve().then(()=>ZIt),void 0)),Zzt=P.lazy(()=>Be(()=>import("./BookingManagePage-DZ4Qdoaq.js"),__vite__mapDeps([720,87]))),Xzt=P.lazy(()=>Be(()=>import("./LandingPages-CcwClFr7.js"),__vite__mapDeps([721,139,149]))),Qzt=P.lazy(()=>Be(()=>import("./BuyerMatch-DT7jyiW8.js"),__vite__mapDeps([722,723,322,253,323,184,324,185,98,161,310,153,271,325,142,329,378,379,215,9,391]))),Jzt=P.lazy(()=>Be(()=>import("./BuyerMatchEditor-Dn59XyB6.js"),__vite__mapDeps([724,139,723,322,253,323,184,324,185,98,161,310,153,271,325,142,329,378,379,215,141,140,143,144,145,146,147,725,84]))),e$t=P.lazy(()=>Be(()=>import("./PublicBuyerMatch-Dw5byq_C.js"),__vite__mapDeps([726,725,472,87]))),t$t=P.lazy(()=>Be(()=>import("./LandingPageEditor-pEE4cgsy.js"),__vite__mapDeps([727,139,161,135,149,84,136]))),r$t=P.lazy(()=>Be(()=>import("./LandingPageDefaults-BeA22mS3.js"),__vite__mapDeps([728,84]))),n$t=P.lazy(()=>Be(()=>Promise.resolve().then(()=>xPt),void 0)),i$t=P.lazy(()=>Be(()=>import("./WebsiteAppsHub-5fvcud4U.js"),__vite__mapDeps([729,730,281,731,440,116,187,186,441,391,442,271,89,276,3,153,443,444,162,445,10,35,52,184,337,424,446,447,126,390,282,96,448,42,449,450,62,302,74,451,87,431,452,453,454,124,331,308,127,264,426,363,280,455,93,267,125,278,238,456,41,78,457,458,459,176,460,148,217,461,261,123,266,401,83,462,463,464,465,136,466,279,438,14,182,183,467,468,201,469,159,91,111,367,470,218,335,98,332,185,471,415,472,119,103,358,473,197,383,15,20,200,474,475,243,476,477,436,404,206,403,310,32,161,299,478,413,231,55,416,479,430,300,147,108,9,353,395,117,258,152,54,480,481,482,149,115,483,362,233,287,257,6,190,220,84,432,484,241,289,485,486,265,487,72,207,44,155,380,357,277,7,433,488,215,489,490,43,491,31,53,27,492,434,324,328,229,70,204,90,493,494,196,382,495,309,45,112,189]))),s$t=P.lazy(()=>Be(()=>import("./ClaimWebsite-B7vlV0hm.js"),__vite__mapDeps([732,730,281]))),a$t=P.lazy(()=>Be(()=>import("./VideoGreeterEditor-DSWsNRY5.js"),__vite__mapDeps([733,731,374,605,400,162,401,402,403,404,310,6,9,628,78,376,74]))),o$t=P.lazy(()=>Be(()=>import("./ExitIntentEditor-Dq1FFl57.js"),__vite__mapDeps([734,731,735]))),l$t=P.lazy(()=>Be(()=>import("./LeadMagnetEditor-ChwW0X4J.js"),__vite__mapDeps([736,731,735]))),c$t=P.lazy(()=>Be(()=>import("./EmbedVideoGreeter-DPamYpaF.js"),[])),u$t=P.lazy(()=>Be(()=>import("./EmbedLeadMagnet-4ahaTrAM.js"),[])),d$t=P.lazy(()=>Be(()=>import("./RelationshipScorecard-C29Im344.js"),__vite__mapDeps([737,368,175,3,442,353,168]))),h$t=P.lazy(()=>Be(()=>import("./SphereGaps-D8i8bSVF.js"),__vite__mapDeps([738,145,169,141,140,142,143,144,146,147,329,479,215,84]))),f$t=P.lazy(()=>Be(()=>import("./Signals-tQo8pz_d.js"),[])),p$t=P.lazy(()=>Be(()=>import("./ConnectPageSettings-CdEBWq4a.js"),__vite__mapDeps([739,145]))),m$t=P.lazy(()=>Be(()=>import("./WebsiteActivityPage-D4AWT2GM.js"),__vite__mapDeps([614,169,141,140,142,143,144,145,146,147,15]))),g$t=P.lazy(()=>Be(()=>import("./EmailCampaigns-CLgeHIJe.js"),__vite__mapDeps([740,741,101,142,74]))),y$t=P.lazy(()=>Be(()=>import("./EmailCompliance-CbPUZHaD.js"),__vite__mapDeps([742,473]))),x$t=P.lazy(()=>Be(()=>import("./EmailCampaignComposer-ZuFoThaS.js"),__vite__mapDeps([743,741,101,744,179,181,307,180,184,182,183,185,186,187,98,489,390,218,325,337,83,374,326,308,147]))),_$t=P.lazy(()=>Be(()=>import("./EmailCampaignDetail-0GwSQRQ-.js"),__vite__mapDeps([745,299,162]))),v$t=P.lazy(()=>Be(()=>import("./SharedCampaignTemplates-Dd11JX9v.js"),__vite__mapDeps([746,747,744,179,181,307,180,184,182,183,185,186,187,98,489,390,218,337,308]))),b$t=P.lazy(()=>Be(()=>import("./AgentTemplates-DZgAEWHF.js"),__vite__mapDeps([748,747,744,179,181,307,180,184,182,183,185,186,187,98,489,390,218,337,308,83]))),Nce=P.lazy(()=>Be(()=>import("./TheLocalMoveHome-BzGUEVT0.js"),__vite__mapDeps([749,750,280,449,126]))),Rce=P.lazy(()=>Be(()=>import("./TheLocalMoveGetStarted-C5eYI5Yu.js"),__vite__mapDeps([751,750]))),Lce=P.lazy(()=>Be(()=>import("./TheLocalMoveCheckout-CoV3tLtt.js"),__vite__mapDeps([752,238]))),Dce=P.lazy(()=>Be(()=>import("./TheLocalMoveCheckoutSuccess-C6sbSRSm.js"),[])),w$t=P.lazy(()=>Be(()=>import("./AdminWebsiteOrders-C8_axBPN.js"),__vite__mapDeps([753,215]))),S$t=new WFe({defaultOptions:{queries:{refetchOnWindowFocus:!1,staleTime:5*60*1e3}}}),T$t=()=>{const t=window.location.hostname;return t==="listings.relevelup.com"||t.startsWith("listings.")},E$t=()=>{const t=window.location.hostname;return t==="commercial.relevelup.com"||t.startsWith("commercial.")},A$t=()=>{const t=window.location.hostname;return t==="cards.relevelup.com"||t.startsWith("cards.")},k$t=()=>{const t=window.location.hostname;return t==="presentations.relevelup.com"||t.startsWith("presentations.")},C$t=()=>{const t=window.location.hostname;return t==="guestbook.relevelup.com"||t.startsWith("guestbook.")},j$t=()=>{const t=window.location.hostname;return t==="clients.relevelup.com"||t.startsWith("clients.")},I$t=()=>{const t=window.location.hostname;return t==="cma.relevelup.com"||t.startsWith("cma.")},P$t=()=>{const t=window.location.hostname;return t==="cardstudio.relevelup.com"||t.startsWith("cardstudio.")},N$t=()=>{const t=window.location.hostname;return t==="booking.relevelup.com"||t.startsWith("booking.")},R$t=()=>{const t=window.location.hostname;return t==="contacts.relevelup.com"||t.startsWith("contacts.")},L$t=()=>{const t=window.location.hostname;return t==="pages.relevelup.com"||t.startsWith("pages.")},oAe=()=>{const t=window.location.hostname;return t==="thelocalmove.com"||t==="www.thelocalmove.com"},D$t=new Set(["app","www","api","admin","embed","cdn","static","assets"]),O$t=()=>{const t=window.location.hostname;if(new URLSearchParams(window.location.search).get("previewSlug"))return!0;if(ahe(t))return!(window.location.pathname.startsWith("/embed/")||window.location.pathname.startsWith("/widgets/"));if(!t.endsWith(".thelocalmove.com")||oAe())return!1;const e=t.replace(/\.thelocalmove\.com$/,"").split(".").pop()||"";return!(D$t.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 M$t=()=>o.jsx(QFe,{client:S$t,children:o.jsx(ome,{children:o.jsxs(jpe,{children:[o.jsx(cDe,{}),o.jsx($De,{}),o.jsx(aMe,{}),o.jsx(o5e,{future:{v7_startTransition:!0},children:o.jsx(ize,{children:o.jsx(cze,{children:o.jsx(dze,{children:o.jsxs(lze,{children:[o.jsx(uze,{}),o.jsx(Q$e,{}),o.jsx(SKe,{}),P$t()?o.jsx(HIt,{}):A$t()?o.jsx(JYe,{}):E$t()?o.jsx(EYe,{}):T$t()?o.jsx(SYe,{}):k$t()?o.jsx(nZe,{}):C$t()?o.jsx(Ltt,{}):j$t()?o.jsx(nrt,{}):I$t()?o.jsx(lrt,{}):N$t()?o.jsx(XIt,{}):R$t()?o.jsx(oPt,{}):L$t()?o.jsx(_Pt,{}):oAe()?o.jsxs(ak,{children:[o.jsx(Pe,{path:"/get-started",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(Rce,{})})}),o.jsx(Pe,{path:"/checkout",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(Lce,{})})}),o.jsx(Pe,{path:"/checkout/success",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(Dce,{})})}),o.jsx(Pe,{path:"/privacy-policy",element:o.jsx(mce,{})}),o.jsx(Pe,{path:"/terms-of-service",element:o.jsx(gce,{})}),o.jsx(Pe,{path:"/mcp-data-use",element:o.jsx(yce,{})}),o.jsx(Pe,{path:"*",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(Nce,{})})})]}):O$t()?o.jsx(nFt,{}):o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsxs(ak,{children:[o.jsx(Pe,{path:"/",element:o.jsx(Ert,{})}),o.jsx(Pe,{path:"/the-local-move",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(Nce,{})})}),o.jsx(Pe,{path:"/get-started",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(Rce,{})})}),o.jsx(Pe,{path:"/local-move/checkout",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(Lce,{})})}),o.jsx(Pe,{path:"/local-move/checkout/success",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(Dce,{})})}),o.jsx(Pe,{path:"/privacy-policy",element:o.jsx(mce,{})}),o.jsx(Pe,{path:"/terms-of-service",element:o.jsx(gce,{})}),o.jsx(Pe,{path:"/data-deletion",element:o.jsx(cFt,{})}),o.jsx(Pe,{path:"/mcp-data-use",element:o.jsx(yce,{})}),o.jsx(Pe,{path:"/canva-support",element:o.jsx(lFt,{})}),o.jsx(Pe,{path:"/sms-opt-in",element:o.jsx(uFt,{})}),o.jsx(Pe,{path:"/oauth-connect",element:o.jsx(T$,{})}),o.jsx(Pe,{path:"/.lovable/oauth/consent",element:o.jsx(T$,{})}),o.jsx(Pe,{path:"/oauth/consent",element:o.jsx(T$,{})}),o.jsx(Pe,{path:"/mcp",element:o.jsx(xce,{})}),o.jsx(Pe,{path:"/connect-chatgpt",element:o.jsx(xce,{})}),o.jsx(Pe,{path:"/connect-chatgpt/classic",element:o.jsx(dFt,{})}),o.jsx(Pe,{path:"/public/listings",element:o.jsx(FFt,{})}),o.jsx(Pe,{path:"/public/commercial",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(oFt,{})})}),o.jsx(Pe,{path:"/public/listing/:slugOrId",element:o.jsx(BFt,{})}),o.jsx(Pe,{path:"/listing/:slugOrId",element:o.jsx(F$t,{})}),o.jsx(Pe,{path:"/private-listing",element:o.jsx(VFt,{})}),o.jsx(Pe,{path:"/commercial-pitch/:token",element:o.jsx(UFt,{})}),o.jsx(Pe,{path:"/card/:slug",element:o.jsx(qFt,{})}),o.jsx(Pe,{path:"/join-brokerage/:slug",element:o.jsx(vBt,{})}),o.jsx(Pe,{path:"/recruit-unsubscribe",element:o.jsx(wBt,{})}),o.jsx(Pe,{path:"/event-invite-unsubscribe",element:o.jsx(SBt,{})}),o.jsx(Pe,{path:"/recruit-video/:shareToken",element:o.jsx(bBt,{})}),o.jsx(Pe,{path:"/connect/:slug",element:o.jsx(GFt,{})}),o.jsx(Pe,{path:"/home-value",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(Sce,{})})}),o.jsx(Pe,{path:"/whats-my-home-worth",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(Sce,{})})}),o.jsx(Pe,{path:"/live/:slug",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(HFt,{})})}),o.jsx(Pe,{path:"/auth",element:o.jsx(vne,{})}),o.jsx(Pe,{path:"/login",element:o.jsx(vne,{})}),o.jsx(Pe,{path:"/subscription-success",element:o.jsx(hFt,{})}),o.jsx(Pe,{path:"/subscription",element:o.jsx(ut,{children:o.jsx(fFt,{})})}),o.jsxs(Pe,{path:"/share/video",element:o.jsx(OFt,{}),children:[o.jsx(Pe,{path:":shareToken",element:o.jsx(bce,{})}),o.jsx(Pe,{path:":shareToken/r/:recipientToken",element:o.jsx(bce,{})})]}),o.jsx(Pe,{path:"/p/:shareToken",element:o.jsx(MBt,{})}),o.jsx(Pe,{path:"/portal/:slug",element:o.jsx(ZBt,{})}),o.jsx(Pe,{path:"/portal/:slug/refer",element:o.jsx(XBt,{})}),o.jsx(Pe,{path:"/og/video/:token",element:o.jsx(MFt,{})}),o.jsx(Pe,{path:"/setup-brokerage",element:o.jsx(ut,{children:o.jsx(pFt,{})})}),o.jsx(Pe,{path:"/claim-account",element:o.jsx(_ce,{})}),o.jsx(Pe,{path:"/claim",element:o.jsx(_ce,{})}),o.jsx(Pe,{path:"/activate",element:o.jsx(mFt,{})}),o.jsx(Pe,{path:"/auth/confirm-reset",element:o.jsx(vce,{})}),o.jsx(Pe,{path:"/auth/continue",element:o.jsx(vce,{})}),o.jsx(Pe,{path:"/join",element:o.jsx(gFt,{})}),o.jsx(Pe,{path:"/trial",element:o.jsx(jFt,{})}),o.jsx(Pe,{path:"/trial/success",element:o.jsx(IFt,{})}),o.jsx(Pe,{path:"/labor-day",element:o.jsx(PFt,{})}),o.jsx(Pe,{path:"/brokerage-labor-day",element:o.jsx(NFt,{})}),o.jsx(Pe,{path:"/brokerage-solutions",element:o.jsx(RFt,{})}),o.jsx(Pe,{path:"/upgrade",element:o.jsx(LFt,{})}),o.jsx(Pe,{path:"/instagram",element:o.jsx(DFt,{})}),o.jsx(Pe,{path:"/dashboard",element:o.jsx(ut,{children:o.jsx(YFt,{})})}),o.jsx(Pe,{path:"/coaching",element:o.jsx(ut,{children:o.jsx(yFt,{})})}),o.jsx(Pe,{path:"/coaching/billing",element:o.jsx(ut,{children:o.jsx(bFt,{})})}),o.jsx(Pe,{path:"/coaching/settings",element:o.jsx(ut,{children:o.jsx(wFt,{})})}),o.jsx(Pe,{path:"/coaching/waitlist",element:o.jsx(ut,{children:o.jsx(EFt,{})})}),o.jsx(Pe,{path:"/coaching/agent/:id",element:o.jsx(ut,{children:o.jsx(xFt,{})})}),o.jsx(Pe,{path:"/my-coach",element:o.jsx(ut,{children:o.jsx(_Ft,{})})}),o.jsx(Pe,{path:"/admin/coaching",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(vFt,{})})}),o.jsx(Pe,{path:"/oauth/google-calendar/return",element:o.jsx(SFt,{})}),o.jsx(Pe,{path:"/oauth/microsoft-365/return",element:o.jsx(TFt,{})}),o.jsxs(Pe,{path:"/attract",element:o.jsx(ut,{children:o.jsx(aFt,{children:o.jsx(szt,{})})}),children:[o.jsx(Pe,{index:!0,element:o.jsx(azt,{})}),o.jsx(Pe,{path:"agents",element:o.jsx(ozt,{})}),o.jsx(Pe,{path:"agents/:agentId",element:o.jsx(Tzt,{})}),o.jsx(Pe,{path:"attract-page",element:o.jsx(Uzt,{})}),o.jsx(Pe,{path:"calculator",element:o.jsx(mzt,{})}),o.jsx(Pe,{path:"results",element:o.jsx(dzt,{})}),o.jsx(Pe,{path:"onboarding",element:o.jsx(_zt,{})}),o.jsx(Pe,{path:"opportunities",element:o.jsx(Ezt,{})}),o.jsx(Pe,{path:"follow-up",element:o.jsx(lzt,{})}),o.jsx(Pe,{path:"settings",element:o.jsx(hzt,{})}),o.jsxs(Pe,{path:"toolkit",element:o.jsx(fzt,{}),children:[o.jsx(Pe,{index:!0,element:o.jsx(ki,{to:"/attract/toolkit/kits",replace:!0})}),o.jsx(Pe,{path:"kits",element:o.jsx(bzt,{})}),o.jsx(Pe,{path:"scripts",element:o.jsx(uzt,{})}),o.jsx(Pe,{path:"objections",element:o.jsx(pzt,{})}),o.jsx(Pe,{path:"events",element:o.jsx(gzt,{})}),o.jsx(Pe,{path:"content",element:o.jsx(vzt,{})}),o.jsx(Pe,{path:"resources",element:o.jsx(czt,{})})]}),o.jsx(Pe,{path:"toolkit/kits/templates",element:o.jsx(Szt,{})}),o.jsx(Pe,{path:"toolkit/kits/new",element:o.jsx(Ice,{})}),o.jsx(Pe,{path:"toolkit/kits/:kitId/edit",element:o.jsx(Ice,{})}),o.jsx(Pe,{path:"toolkit/kits/:kitId/analytics",element:o.jsx(wzt,{})}),o.jsx(Pe,{path:"events/new",element:o.jsx(jce,{})}),o.jsx(Pe,{path:"events/:eventId",element:o.jsx(yzt,{})}),o.jsx(Pe,{path:"events/:eventId/edit",element:o.jsx(jce,{})}),o.jsx(Pe,{path:"events/:eventId/checkin",element:o.jsx(xzt,{})}),o.jsx(Pe,{path:"relationships",element:o.jsx(ki,{to:"/attract/agents",replace:!0})}),o.jsx(Pe,{path:"pipeline",element:o.jsx(ki,{to:"/attract/agents",replace:!0})}),o.jsx(Pe,{path:"plan",element:o.jsx(ki,{to:"/attract/settings",replace:!0})}),o.jsx(Pe,{path:"digest",element:o.jsx(ki,{to:"/attract/results",replace:!0})}),o.jsx(Pe,{path:"reports",element:o.jsx(ki,{to:"/attract/results",replace:!0})}),o.jsx(Pe,{path:"dashboard-legacy",element:o.jsx(ki,{to:"/attract",replace:!0})}),o.jsx(Pe,{path:"share",element:o.jsx(ki,{to:"/attract/toolkit/kits",replace:!0})}),o.jsx(Pe,{path:"create",element:o.jsx(ki,{to:"/attract/toolkit/content",replace:!0})}),o.jsx(Pe,{path:"templates",element:o.jsx(ki,{to:"/attract/toolkit/scripts",replace:!0})}),o.jsx(Pe,{path:"resources",element:o.jsx(ki,{to:"/attract/toolkit/resources",replace:!0})}),o.jsx(Pe,{path:"events",element:o.jsx(ki,{to:"/attract/toolkit/events",replace:!0})}),o.jsx(Pe,{path:"landing-page",element:o.jsx(ki,{to:"/attract/attract-page",replace:!0})}),o.jsx(Pe,{path:"provide/kits",element:o.jsx(ki,{to:"/attract/toolkit/kits",replace:!0})}),o.jsx(Pe,{path:"provide/kits/templates",element:o.jsx(ki,{to:"/attract/toolkit/kits/templates",replace:!0})}),o.jsx(Pe,{path:"provide/*",element:o.jsx(ki,{to:"/attract/toolkit/kits",replace:!0})}),o.jsx(Pe,{path:"influence/content-studio",element:o.jsx(ki,{to:"/attract/toolkit/content",replace:!0})}),o.jsx(Pe,{path:"influence/*",element:o.jsx(ki,{to:"/attract/toolkit/content",replace:!0})}),o.jsx(Pe,{path:"produce/*",element:o.jsx(ki,{to:"/attract/results",replace:!0})}),o.jsx(Pe,{path:"connect/*",element:o.jsx(ki,{to:"/attract/toolkit/events",replace:!0})}),o.jsx(Pe,{path:"connect",element:o.jsx(ki,{to:"/attract/toolkit/events",replace:!0})}),o.jsx(Pe,{path:"pillars/*",element:o.jsx(ki,{to:"/attract",replace:!0})})]}),o.jsx(Pe,{path:"/weekly-reels",element:o.jsx(ut,{children:o.jsx(pce,{children:o.jsx(rzt,{})})})}),o.jsx(Pe,{path:"/weekly-reels/onboarding",element:o.jsx(ut,{children:o.jsx(pce,{children:o.jsx(nzt,{})})})}),o.jsx(Pe,{path:"/admin/weekly-reels",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(izt,{})})}),o.jsx(Pe,{path:"/admin/attract-access",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(Vzt,{})})}),o.jsx(Pe,{path:"/admin/attract-intelligence",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(Azt,{})})}),o.jsx(Pe,{path:"/admin/attract-tools",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(kzt,{})})}),o.jsx(Pe,{path:"/attract-kit/:shareToken",element:o.jsx(Czt,{})}),o.jsx(Pe,{path:"/attract-event/:slug",element:o.jsx(jzt,{})}),o.jsx(Pe,{path:"/attract-event-checkin/:token",element:o.jsx(Izt,{})}),o.jsx(Pe,{path:"/join/:slug",element:o.jsx(Pzt,{})}),o.jsx(Pe,{path:"/revival/:slug",element:o.jsx(Nzt,{})}),o.jsx(Pe,{path:"/revival/:slug/plan",element:o.jsx(Pce,{})}),o.jsx(Pe,{path:"/fsbo/:slug",element:o.jsx(Bzt,{})}),o.jsx(Pe,{path:"/fsbo/:slug/guide",element:o.jsx(zzt,{})}),o.jsx(Pe,{path:"/revival/:slug/plan",element:o.jsx(Pce,{})}),o.jsx(Pe,{path:"/coaches",element:o.jsx(AFt,{})}),o.jsx(Pe,{path:"/coaches/apply",element:o.jsx(CFt,{})}),o.jsx(Pe,{path:"/coaches/:slug",element:o.jsx(kFt,{})}),o.jsx(Pe,{path:"/credits",element:o.jsx(ut,{children:o.jsx(B4t,{})})}),o.jsx(Pe,{path:"/wallet",element:o.jsx(ki,{to:"/credits",replace:!0})}),o.jsx(Pe,{path:"/profile",element:o.jsx(ut,{children:o.jsx(ZFt,{})})}),o.jsx(Pe,{path:"/apps/*",element:o.jsx(ut,{children:o.jsx(JFt,{})})}),o.jsx(Pe,{path:"/admin",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(Tce,{})})}),o.jsx(Pe,{path:"/admin/dashboard",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(Tce,{})})}),o.jsx(Pe,{path:"/admin/apps",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(T3t,{})})}),o.jsx(Pe,{path:"/admin/members",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(E3t,{})})}),o.jsx(Pe,{path:"/admin/unassigned-members",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(A3t,{})})}),o.jsx(Pe,{path:"/admin/invite-codes",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(k3t,{})})}),o.jsx(Pe,{path:"/admin/events",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(C3t,{})})}),o.jsx(Pe,{path:"/admin/live",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(WFt,{})})})}),o.jsx(Pe,{path:"/admin/live/:id",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{}),children:o.jsx(KFt,{})})})}),o.jsx(Pe,{path:"/admin/mcp-audit",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(j3t,{})})}),o.jsx(Pe,{path:"/events",element:o.jsx(ut,{children:o.jsx(XFt,{})})}),o.jsx(Pe,{path:"/events/:eventId",element:o.jsx(ut,{children:o.jsx(QFt,{})})}),o.jsx(Pe,{path:"/templates",element:o.jsx(ut,{children:o.jsx(e3t,{})})}),o.jsx(Pe,{path:"/templates/:templateId",element:o.jsx(ut,{children:o.jsx(t3t,{})})}),o.jsx(Pe,{path:"/admin/templates",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(I3t,{})})}),o.jsx(Pe,{path:"/programs",element:o.jsx(ut,{children:o.jsx(r3t,{})})}),o.jsx(Pe,{path:"/programs/:slug",element:o.jsx(ut,{children:o.jsx(n3t,{})})}),o.jsx(Pe,{path:"/programs/:slug/enroll",element:o.jsx(ut,{children:o.jsx(i3t,{})})}),o.jsx(Pe,{path:"/programs/:slug/workspace",element:o.jsx(ut,{children:o.jsx(s3t,{})})}),o.jsx(Pe,{path:"/admin/programs",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(a3t,{})})}),o.jsx(Pe,{path:"/watch/:slug",element:o.jsx(c3t,{})}),o.jsx(Pe,{path:"/academy",element:o.jsx(ut,{children:o.jsx(o3t,{})})}),o.jsx(Pe,{path:"/academy/:videoId",element:o.jsx(ut,{children:o.jsx(l3t,{})})}),o.jsx(Pe,{path:"/admin/academy",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P3t,{})})}),o.jsx(Pe,{path:"/toolbox",element:o.jsx(ut,{children:o.jsx(u3t,{})})}),o.jsx(Pe,{path:"/toolbox/:kitId",element:o.jsx(ut,{children:o.jsx(d3t,{})})}),o.jsx(Pe,{path:"/admin/toolbox",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(N3t,{})})}),o.jsx(Pe,{path:"/admin/blog",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(GBt,{})})}),o.jsx(Pe,{path:"/social-swag",element:o.jsx(ut,{children:o.jsx(h3t,{})})}),o.jsx(Pe,{path:"/social-studio",element:o.jsx(ut,{children:o.jsx(f3t,{})})}),o.jsx(Pe,{path:"/social-swag-2",element:o.jsx(ki,{to:"/social-studio?tab=gallery",replace:!0})}),o.jsx(Pe,{path:"/marketing-studio",element:o.jsx(ut,{children:o.jsx(p3t,{})})}),o.jsx(Pe,{path:"/marketing-studio/brand-kit",element:o.jsx(ut,{children:o.jsx(m3t,{})})}),o.jsx(Pe,{path:"/marketing-studio/branding-bar",element:o.jsx(ut,{children:o.jsx(g3t,{})})}),o.jsx(Pe,{path:"/marketing-studio/listing-templates",element:o.jsx(ut,{children:o.jsx(y3t,{})})}),o.jsx(Pe,{path:"/marketing-studio/personal-branding",element:o.jsx(ut,{children:o.jsx(x3t,{})})}),o.jsx(Pe,{path:"/social-swag/:swagId",element:o.jsx(ut,{children:o.jsx(_3t,{})})}),o.jsx(Pe,{path:"/social-connections",element:o.jsx(ut,{children:o.jsx(TBt,{})})}),o.jsx(Pe,{path:"/social-connections/callback",element:o.jsx(ut,{children:o.jsx(EBt,{})})}),o.jsx(Pe,{path:"/social-connections/linkedin-callback",element:o.jsx(ut,{children:o.jsx(kBt,{})})}),o.jsx(Pe,{path:"/social-connections/tiktok-callback",element:o.jsx(ut,{children:o.jsx(CBt,{})})}),o.jsx(Pe,{path:"/social-connections/google-callback",element:o.jsx(ut,{children:o.jsx(ABt,{})})}),o.jsx(Pe,{path:"/admin/social-swag",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(R3t,{})})}),o.jsx(Pe,{path:"/admin/social-swag-2",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(L3t,{})})}),o.jsx(Pe,{path:"/community",element:o.jsx(ut,{children:o.jsx(v3t,{})})}),o.jsx(Pe,{path:"/support",element:o.jsx(ut,{children:o.jsx(b3t,{})})}),o.jsx(Pe,{path:"/admin/community",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(D3t,{})})}),o.jsx(Pe,{path:"/admin/support-tickets",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(B3t,{})})}),o.jsx(Pe,{path:"/admin/email-templates",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(z3t,{})})}),o.jsx(Pe,{path:"/admin/agent-email-templates",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx($3t,{})})}),o.jsx(Pe,{path:"/admin/analytics",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(O3t,{})})}),o.jsx(Pe,{path:"/admin/brokerage-resources",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(M3t,{})})}),o.jsx(Pe,{path:"/admin/dashboard-management",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(F3t,{})})}),o.jsx(Pe,{path:"/brokerage/dashboard",element:o.jsx(ut,{requireBrokerageManager:!0,children:o.jsx(U3t,{})})}),o.jsx(Pe,{path:"/brokerage/teams",element:o.jsx(ut,{requireBrokerageManager:!0,children:o.jsx(qzt,{})})}),o.jsx(Pe,{path:"/brokerage/recruiting",element:o.jsx(ut,{requireBrokerageManager:!0,children:o.jsx(v4t,{})})}),o.jsx(Pe,{path:"/brokerage/onboarding",element:o.jsx(ut,{requireBrokerageManager:!0,children:o.jsx(b4t,{})})}),o.jsx(Pe,{path:"/brokerage/commission-plans",element:o.jsx(ut,{children:o.jsx(k4t,{})})}),o.jsx(Pe,{path:"/brokerage/operations",element:o.jsx(ut,{children:o.jsx(S4t,{})})}),o.jsx(Pe,{path:"/brokerage/website",element:o.jsx(ut,{children:o.jsx(A4t,{})})}),o.jsx(Pe,{path:"/websites",element:o.jsx(ut,{children:o.jsx(T4t,{})})}),o.jsx(Pe,{path:"/team/website",element:o.jsx(ut,{children:o.jsx(E4t,{})})}),o.jsx(Pe,{path:"/brokerage/transactions",element:o.jsx(ut,{children:o.jsx(w4t,{})})}),o.jsx(Pe,{path:"/team",element:o.jsx(ut,{children:o.jsx(Hzt,{})})}),o.jsx(Pe,{path:"/my-team",element:o.jsx(ut,{children:o.jsx(Gzt,{})})}),o.jsx(Pe,{path:"/my-brokerage",element:o.jsx(ut,{children:o.jsx(V3t,{})})}),o.jsx(Pe,{path:"/brokerage/help-board",element:o.jsx(ut,{children:o.jsx(H3t,{})})}),o.jsx(Pe,{path:"/brokerage/help-board/new",element:o.jsx(ut,{children:o.jsx(W3t,{})})}),o.jsx(Pe,{path:"/brokerage/help-board/:id",element:o.jsx(ut,{children:o.jsx(K3t,{})})}),o.jsx(Pe,{path:"/brokerage-content",element:o.jsx(ut,{children:o.jsx(q3t,{})})}),o.jsx(Pe,{path:"/brokerage-content/:contentId",element:o.jsx(ut,{children:o.jsx(G3t,{})})}),o.jsx(Pe,{path:"/brokerage-resources",element:o.jsx(ut,{requireBrokerageManager:!0,children:o.jsx(w3t,{})})}),o.jsx(Pe,{path:"/brokerage-resources/:resourceId",element:o.jsx(ut,{requireBrokerageManager:!0,children:o.jsx(S3t,{})})}),o.jsx(Pe,{path:"/newsletters",element:o.jsx(ut,{children:o.jsx(Y3t,{})})}),o.jsx(Pe,{path:"/newsletters/:id",element:o.jsx(ut,{children:o.jsx(Z3t,{})})}),o.jsx(Pe,{path:"/wishlist",element:o.jsx(ut,{children:o.jsx(t5t,{})})}),o.jsx(Pe,{path:"/wishlist/:itemId",element:o.jsx(ut,{children:o.jsx(r5t,{})})}),o.jsx(Pe,{path:"/admin/wishlist",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(n5t,{})})}),o.jsx(Pe,{path:"/admin/levelup-brief",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(i5t,{})})}),o.jsx(Pe,{path:"/admin/boost-announcements",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(J3t,{})})}),o.jsx(Pe,{path:"/admin/broadcasts",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(Q3t,{})})}),o.jsx(Pe,{path:"/admin/newsletters",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(X3t,{})})}),o.jsx(Pe,{path:"/admin/newsletter-graphics",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(e5t,{})})}),o.jsx(Pe,{path:"/admin/additional-services",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(s5t,{})})}),o.jsx(Pe,{path:"/admin/discounts",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(a5t,{})})}),o.jsx(Pe,{path:"/admin/subscriptions",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(o5t,{})})}),o.jsx(Pe,{path:"/admin/instagram-gift-emails",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(l5t,{})})}),o.jsx(Pe,{path:"/admin/referrals",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(c5t,{})})}),o.jsx(Pe,{path:"/admin/prospector",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(x4t,{})})}),o.jsx(Pe,{path:"/admin/recruiting",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(_4t,{})})}),o.jsx(Pe,{path:"/admin/beta/social-post-generator",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(j4t,{})})}),o.jsx(Pe,{path:"/admin/credits",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(Y4t,{})})})}),o.jsx(Pe,{path:"/admin/cleanup",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(Z4t,{})})})}),o.jsx(Pe,{path:"/admin/beta/postcard-manager",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(V4t,{})})})}),o.jsx(Pe,{path:"/admin/mail-studio/templates",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(q4t,{})})})}),o.jsx(Pe,{path:"/admin/beta/homereel",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(G4t,{})})})}),o.jsx(Pe,{path:"/admin/beta/boost",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(K4t,{})})})}),o.jsx(Pe,{path:"/admin/video-lab",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(W4t,{})})})}),o.jsx(Pe,{path:"/admin/music-videos",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(H4t,{})})})}),o.jsx(Pe,{path:"/admin/lms",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(I4t,{})})}),o.jsx(Pe,{path:"/admin/lms/stats",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(N4t,{})})}),o.jsx(Pe,{path:"/admin/lms/:courseId",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P4t,{})})}),o.jsx(Pe,{path:"/levelup-u",element:o.jsx(ut,{children:o.jsx(R4t,{})})}),o.jsx(Pe,{path:"/levelup-u/:courseId",element:o.jsx(ut,{children:o.jsx(L4t,{})})}),o.jsx(Pe,{path:"/admin/brokerage-content-activity",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(C4t,{})})}),o.jsx(Pe,{path:"/admin/onboarding-checklist",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(u5t,{})})}),o.jsx(Pe,{path:"/admin/marketplace",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(s4t,{})})}),o.jsx(Pe,{path:"/admin/agent-points",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(n4t,{})})}),o.jsx(Pe,{path:"/admin/reward-store",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(a4t,{})})}),o.jsx(Pe,{path:"/admin/integrations",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(o4t,{})})}),o.jsx(Pe,{path:"/admin/mcp-updates",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(u4t,{})})}),o.jsx(Pe,{path:"/help/refresh-mcp-tools",element:o.jsx(ut,{children:o.jsx(d4t,{})})}),o.jsx(Pe,{path:"/admin/social-autopilot",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(c4t,{})})}),o.jsx(Pe,{path:"/admin/social-connections",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(l4t,{})})}),o.jsx(Pe,{path:"/admin/integrations/callback",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(y4t,{})})}),o.jsx(Pe,{path:"/admin/email-compliance",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(y$t,{})})})}),o.jsx(Pe,{path:"/admin/email-campaigns",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(g$t,{})})})}),o.jsx(Pe,{path:"/admin/email-campaigns/templates",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(v$t,{})})})}),o.jsx(Pe,{path:"/email-campaigns/templates",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(b$t,{})})})}),o.jsx(Pe,{path:"/admin/email-campaigns/new",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(x$t,{})})})}),o.jsx(Pe,{path:"/admin/email-campaigns/:id",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(_$t,{})})})}),o.jsx(Pe,{path:"/reward-store",element:o.jsx(ut,{children:o.jsx(LBt,{})})}),o.jsx(Pe,{path:"/refer-friends",element:o.jsx(ut,{children:o.jsx(DBt,{})})}),o.jsx(Pe,{path:"/additional-services",element:o.jsx(ut,{children:o.jsx(h5t,{})})}),o.jsx(Pe,{path:"/additional-services/:serviceId",element:o.jsx(ut,{children:o.jsx(f5t,{})})}),o.jsx(Pe,{path:"/ai-toolkit",element:o.jsx(ut,{children:o.jsx(p5t,{})})}),o.jsx(Pe,{path:"/ask-ai",element:o.jsx(ut,{children:o.jsx(m5t,{})})}),o.jsx(Pe,{path:"/mission-control",element:o.jsx(ut,{children:o.jsx(g5t,{})})}),o.jsx(Pe,{path:"/mission-control/contacts",element:o.jsx(ut,{children:o.jsx(y5t,{})})}),o.jsx(Pe,{path:"/mission-control/sphere-map",element:o.jsx(ut,{children:o.jsx(eBt,{})})}),o.jsx(Pe,{path:"/mission-control/property-intelligence",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(tBt,{})})}),o.jsx(Pe,{path:"/mission-control/contacts/:contactId",element:o.jsx(ut,{children:o.jsx(x5t,{})})}),o.jsx(Pe,{path:"/mission-control/sent-emails",element:o.jsx(ut,{children:o.jsx(_5t,{})})}),o.jsx(Pe,{path:"/mission-control/plans",element:o.jsx(ut,{children:o.jsx(v5t,{})})}),o.jsx(Pe,{path:"/mission-control/cma",element:o.jsx(ut,{children:o.jsx(b5t,{})})}),o.jsx(Pe,{path:"/mission-control/cma/:id",element:o.jsx(ut,{children:o.jsx(w5t,{})})}),o.jsx(Pe,{path:"/cma/:token",element:o.jsx(E5t,{})}),o.jsx(Pe,{path:"/apps/listing-presentation-studio",element:o.jsx(ut,{children:o.jsx(S5t,{})})}),o.jsx(Pe,{path:"/apps/listing-presentation-studio/:id",element:o.jsx(ut,{children:o.jsx(T5t,{})})}),o.jsx(Pe,{path:"/apps/listing-revival",element:o.jsx(ut,{children:o.jsx(Rzt,{})})}),o.jsx(Pe,{path:"/apps/listing-revival/new",element:o.jsx(ut,{children:o.jsx(Lzt,{})})}),o.jsx(Pe,{path:"/apps/listing-revival/campaigns/:id",element:o.jsx(ut,{children:o.jsx(Dzt,{})})}),o.jsx(Pe,{path:"/staged/:token",element:o.jsx(z4t,{})}),o.jsx(Pe,{path:"/apps/staging-studio",element:o.jsx(ut,{children:o.jsx($B,{children:o.jsx(O4t,{})})})}),o.jsx(Pe,{path:"/apps/staging-studio/library",element:o.jsx(ut,{children:o.jsx($B,{children:o.jsx(M4t,{})})})}),o.jsx(Pe,{path:"/apps/staging-studio/credits",element:o.jsx(ut,{children:o.jsx($B,{children:o.jsx(F4t,{})})})}),o.jsx(Pe,{path:"/apps/fsbo-breakthrough",element:o.jsx(ut,{children:o.jsx(Ozt,{})})}),o.jsx(Pe,{path:"/apps/fsbo-breakthrough/new",element:o.jsx(ut,{children:o.jsx(Mzt,{})})}),o.jsx(Pe,{path:"/apps/reviews",element:o.jsx(ut,{children:o.jsx(YBt,{})})}),o.jsx(Pe,{path:"/apps/fsbo-breakthrough/campaigns/:id",element:o.jsx(ut,{children:o.jsx(Fzt,{})})}),o.jsx(Pe,{path:"/admin/fsbo-breakthrough",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx($zt,{})})}),o.jsx(Pe,{path:"/mission-control/listing-presentations",element:o.jsx(ki,{to:"/apps/listing-presentation-studio",replace:!0})}),o.jsx(Pe,{path:"/mission-control/popbys",element:o.jsx(ut,{children:o.jsx(A5t,{})})}),o.jsx(Pe,{path:"/mission-control/popbys/map",element:o.jsx(ut,{children:o.jsx(J4t,{})})}),o.jsx(Pe,{path:"/admin/notification-settings",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(h4t,{})})}),o.jsx(Pe,{path:"/admin/agent-os",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(d5t,{})})}),o.jsx(Pe,{path:"/mission-control/listings",element:o.jsx(ut,{children:o.jsx(k5t,{})})}),o.jsx(Pe,{path:"/mission-control/listing-studio",element:o.jsx(ut,{children:o.jsx(JBt,{})})}),o.jsx(Pe,{path:"/mission-control/listings/new",element:o.jsx(ut,{children:o.jsx(zFt,{})})}),o.jsx(Pe,{path:"/mission-control/listings/new/residential",element:o.jsx(ut,{children:o.jsx(Ece,{})})}),o.jsx(Pe,{path:"/mission-control/listings/new/commercial",element:o.jsx(ut,{children:o.jsx(wce,{})})}),o.jsx(Pe,{path:"/mission-control/listings/:listingId/commercial",element:o.jsx(ut,{children:o.jsx($Ft,{})})}),o.jsx(Pe,{path:"/mission-control/listings/:listingId/commercial/edit",element:o.jsx(ut,{children:o.jsx(wce,{})})}),o.jsx(Pe,{path:"/mission-control/listings/:listingId",element:o.jsx(ut,{children:o.jsx(C5t,{})})}),o.jsx(Pe,{path:"/mission-control/listings/:listingId/edit",element:o.jsx(ut,{children:o.jsx(Ece,{})})}),o.jsx(Pe,{path:"/mission-control/listings/:listingId/customize",element:o.jsx(ut,{children:o.jsx(j5t,{})})}),o.jsx(Pe,{path:"/admin/listing-exchange",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(X5t,{})})}),o.jsx(Pe,{path:"/admin/listing-leads",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(Q5t,{})})}),o.jsx(Pe,{path:"/admin/public-site-leads",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(J5t,{})})}),o.jsx(Pe,{path:"/mission-control/pipeline",element:o.jsx(ut,{children:o.jsx(L5t,{})})}),o.jsx(Pe,{path:"/mission-control/forms",element:o.jsx(ut,{children:o.jsx(D5t,{})})}),o.jsx(Pe,{path:"/mission-control/tasks",element:o.jsx(ut,{children:o.jsx(DIt,{})})}),o.jsx(Pe,{path:"/mission-control/transactions",element:o.jsx(ut,{children:o.jsx(O5t,{})})}),o.jsx(Pe,{path:"/mission-control/client-portals",element:o.jsx(ut,{children:o.jsx($5t,{})})}),o.jsx(Pe,{path:"/mission-control/client-portals/:portalId",element:o.jsx(ut,{children:o.jsx(U5t,{})})}),o.jsx(Pe,{path:"/mission-control/portal-referrals",element:o.jsx(ut,{children:o.jsx(M5t,{})})}),o.jsx(Pe,{path:"/mission-control/vendors",element:o.jsx(ut,{children:o.jsx(F5t,{})})}),o.jsx(Pe,{path:"/brokerage/forms",element:o.jsx(ut,{children:o.jsx(B5t,{})})}),o.jsx(Pe,{path:"/brokerage/vendors",element:o.jsx(ut,{children:o.jsx(z5t,{})})}),o.jsx(Pe,{path:"/mission-control/my-card",element:o.jsx(ut,{children:o.jsx(V5t,{})})}),o.jsx(Pe,{path:"/mission-control/integrations",element:o.jsx(ut,{children:o.jsx(q5t,{})})}),o.jsx(Pe,{path:"/mission-control/browser-extension",element:o.jsx(ut,{children:o.jsx(G5t,{})})}),o.jsx(Pe,{path:"/mission-control/integrations/gmail/callback",element:o.jsx(ut,{children:o.jsx(H5t,{})})}),o.jsx(Pe,{path:"/mission-control/integrations/canva/callback",element:o.jsx(W5t,{})}),o.jsx(Pe,{path:"/mission-control/integrations/meta/callback",element:o.jsx(ut,{children:o.jsx(K5t,{})})}),o.jsx(Pe,{path:"/mission-control/scorecard",element:o.jsx(ut,{children:o.jsx(FCt,{})})}),o.jsx(Pe,{path:"/admin/scorecard",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(Y5t,{})})}),o.jsx(Pe,{path:"/admin/agent-activation",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(Z5t,{})})}),o.jsx(Pe,{path:"/admin/scorecard/:userId",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(Ace,{})})}),o.jsx(Pe,{path:"/mission-control/scorecard/:userId",element:o.jsx(ut,{children:o.jsx(Ace,{})})}),o.jsx(Pe,{path:"/mission-control/relationship-scorecard",element:o.jsx(ut,{children:o.jsx(d$t,{})})}),o.jsx(Pe,{path:"/mission-control/sphere-gaps",element:o.jsx(ut,{children:o.jsx(h$t,{})})}),o.jsx(Pe,{path:"/mission-control/signals",element:o.jsx(ut,{children:o.jsx(f$t,{})})}),o.jsx(Pe,{path:"/mission-control/website-activity",element:o.jsx(ut,{children:o.jsx(m$t,{})})}),o.jsx(Pe,{path:"/mission-control/connect-page",element:o.jsx(ut,{children:o.jsx(p$t,{})})}),o.jsx(Pe,{path:"/admin/membership-reviews",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(e4t,{})})}),o.jsx(Pe,{path:"/admin/lead-notifications",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(t4t,{})})}),o.jsx(Pe,{path:"/admin/weekly-digest",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(r4t,{})})}),o.jsx(Pe,{path:"/studio/join/:roomId",element:o.jsx(P.Suspense,{fallback:null,children:o.jsx(N5t,{})})}),o.jsx(Pe,{path:"/video-studio",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:null,children:o.jsx(P5t,{})})})}),o.jsx(Pe,{path:"/mission-control/video/record",element:o.jsx(I5t,{})}),o.jsx(Pe,{path:"/mission-control/video-library",element:o.jsx(ut,{children:o.jsx(R5t,{})})}),o.jsx(Pe,{path:"/my-partnership",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:null,children:o.jsx(oBt,{})})})}),o.jsx(Pe,{path:"/upgrade/:featureKey",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:null,children:o.jsx(lBt,{})})})}),o.jsx(Pe,{path:"/coaching/onboarding",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:null,children:o.jsx(cBt,{})})})}),o.jsx(Pe,{path:"/admin/partnerships",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:null,children:o.jsx(aBt,{})})})}),o.jsx(Pe,{path:"/website-apps",element:o.jsx(ut,{children:o.jsx(i$t,{})})}),o.jsx(Pe,{path:"/get-my-website",element:o.jsx(ut,{children:o.jsx(s$t,{})})}),o.jsx(Pe,{path:"/need-a-website",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(mBt,{})})})}),o.jsx(Pe,{path:"/website-apps/video_greeter",element:o.jsx(ut,{children:o.jsx(a$t,{})})}),o.jsx(Pe,{path:"/website-apps/exit_intent",element:o.jsx(ut,{children:o.jsx(o$t,{})})}),o.jsx(Pe,{path:"/website-apps/lead_magnet",element:o.jsx(ut,{children:o.jsx(l$t,{})})}),o.jsx(Pe,{path:"/embed/video-greeter/:slug",element:o.jsx(c$t,{})}),o.jsx(Pe,{path:"/embed/lead-magnet/:slug",element:o.jsx(u$t,{})}),o.jsx(Pe,{path:"/marketplace",element:o.jsx(ut,{children:o.jsx(FIt,{})})}),o.jsx(Pe,{path:"/marketplace/:productId",element:o.jsx(ut,{children:o.jsx(jBt,{})})}),o.jsx(Pe,{path:"/marketplace/cart",element:o.jsx(ut,{children:o.jsx(IBt,{})})}),o.jsx(Pe,{path:"/marketplace/orders",element:o.jsx(ut,{children:o.jsx(PBt,{})})}),o.jsx(Pe,{path:"/marketplace/orders/:orderId",element:o.jsx(ut,{children:o.jsx(NBt,{})})}),o.jsx(Pe,{path:"/marketplace/success",element:o.jsx(ut,{children:o.jsx(RBt,{})})}),o.jsx(Pe,{path:"/admin/agent-cards",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(i4t,{})})}),o.jsx(Pe,{path:"/admin/presentation-analytics",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(f4t,{})})}),o.jsx(Pe,{path:"/admin/listing-presentation-studio",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(p4t,{})})}),o.jsx(Pe,{path:"/admin/listing-revival",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(m4t,{})})}),o.jsx(Pe,{path:"/admin/contact-finder",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(U4t,{})})}),o.jsx(Pe,{path:"/admin/staging-studio",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx($4t,{})})}),o.jsx(Pe,{path:"/admin/guest-book-analytics",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(g4t,{})})}),o.jsx(Pe,{path:"/mission-control/smart-drips",element:o.jsx(ut,{children:o.jsx(tzt,{})})}),o.jsx(Pe,{path:"/mission-control/mail-studio",element:o.jsx(Q4t,{})}),o.jsx(Pe,{path:"/mission-control/direct-mail",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}),children:o.jsx(X4t,{})})})}),o.jsx(Pe,{path:"/mission-control/presentations",element:o.jsx(ut,{children:o.jsx(OBt,{})})}),o.jsx(Pe,{path:"/mission-control/presentations/new",element:o.jsx(ut,{children:o.jsx(Cce,{})})}),o.jsx(Pe,{path:"/mission-control/presentations/:id",element:o.jsx(ut,{children:o.jsx(Cce,{})})}),o.jsx(Pe,{path:"/mission-control/guest-book",element:o.jsx(ut,{children:o.jsx(FBt,{})})}),o.jsx(Pe,{path:"/mission-control/guest-book/live/:id",element:o.jsx(ut,{children:o.jsx(rBt,{})})}),o.jsx(Pe,{path:"/guestbook/:slug",element:o.jsx(BBt,{})}),o.jsx(Pe,{path:"/review/:token",element:o.jsx(HBt,{})}),o.jsx(Pe,{path:"/reviews/:slug/new",element:o.jsx(KBt,{})}),o.jsx(Pe,{path:"/reviews/:slug",element:o.jsx(WBt,{})}),o.jsx(Pe,{path:"/rsvp/:slug",element:o.jsx(zBt,{})}),o.jsx(Pe,{path:"/resources/:slug",element:o.jsx($Bt,{})}),o.jsx(Pe,{path:"/sign/:token",element:o.jsx(UBt,{})}),o.jsx(Pe,{path:"/blog",element:o.jsx(VBt,{})}),o.jsx(Pe,{path:"/blog/:slug",element:o.jsx(qBt,{})}),o.jsx(Pe,{path:"/mission-control/card-studio",element:o.jsx(ut,{children:o.jsx(QBt,{})})}),o.jsx(Pe,{path:"/mission-control/scheduler",element:o.jsx(ut,{children:o.jsx(Wzt,{})})}),o.jsx(Pe,{path:"/mission-control/calendar",element:o.jsx(ut,{children:o.jsx(Kzt,{})})}),o.jsx(Pe,{path:"/c/:shareToken",element:o.jsx(ezt,{})}),o.jsx(Pe,{path:"/book/:slug",element:o.jsx(Yzt,{})}),o.jsx(Pe,{path:"/booking/manage/:token",element:o.jsx(Zzt,{})}),o.jsx(Pe,{path:"/page/:slug",element:o.jsx(n$t,{})}),o.jsx(Pe,{path:"/buyer-match/:slug",element:o.jsx(e$t,{})}),o.jsx(Pe,{path:"/mission-control/buyer-match",element:o.jsx(ut,{children:o.jsx(Qzt,{})})}),o.jsx(Pe,{path:"/mission-control/buyer-match/:campaignId",element:o.jsx(ut,{children:o.jsx(Jzt,{})})}),o.jsx(Pe,{path:"/mission-control/landing-pages",element:o.jsx(ut,{children:o.jsx(Xzt,{})})}),o.jsx(Pe,{path:"/mission-control/landing-pages/defaults",element:o.jsx(ut,{children:o.jsx(r$t,{})})}),o.jsx(Pe,{path:"/mission-control/landing-pages/:pageId",element:o.jsx(ut,{children:o.jsx(t$t,{})})}),o.jsx(Pe,{path:"/my-website/:siteId/edit",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(kce,{})})})}),o.jsx(Pe,{path:"/my-website/mls-listings",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(yBt,{})})})}),o.jsx(Pe,{path:"/my-website/mls-listings/:mlsId",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(xBt,{})})})}),o.jsx(Pe,{path:"/my-website/market-report",element:o.jsx(ut,{children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(_Bt,{})})})}),o.jsx(Pe,{path:"/admin/lead-sites",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(nBt,{})})})}),o.jsx(Pe,{path:"/admin/lead-sites/themes",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(iBt,{})})})}),o.jsx(Pe,{path:"/admin/lead-sites/offers",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(sBt,{})})})}),o.jsx(Pe,{path:"/admin/lead-sites/offers/:brokerageId",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(uBt,{})})})}),o.jsx(Pe,{path:"/admin/lead-sites/:siteId/edit",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(kce,{})})})}),o.jsx(Pe,{path:"/admin/mls-feeds",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(dBt,{})})})}),o.jsx(Pe,{path:"/admin/lead-site-analytics",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(hBt,{})})})}),o.jsx(Pe,{path:"/admin/website-interests",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(fBt,{})})})}),o.jsx(Pe,{path:"/admin/website-requests",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(pBt,{})})})}),o.jsx(Pe,{path:"/admin/website-orders",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(w$t,{})})})}),o.jsx(Pe,{path:"/admin/mls-fee-tracker",element:o.jsx(ut,{requireAdmin:!0,children:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(gBt,{})})})}),o.jsx(Pe,{path:"/m/*",element:o.jsx(P.Suspense,{fallback:o.jsx("div",{className:"flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}),children:o.jsx(D4t,{})})}),o.jsx(Pe,{path:"*",element:o.jsx(gEe,{})})]})})]})})})})})]})})});function F$t(){const t=Wi(),e=t.pathname.replace(/^\/listing\//,"");return o.jsx(ki,{to:`/public/listing/${e}${t.search}`,replace:!0})}const lAe=window.location.hostname;/(\.lovable\.app|\.lovableproject\.com)$/.test(lAe)&&/[?&]authorization_id=/.test(window.location.search)&&window.location.replace(`https://dashboard.relevelup.com/oauth-connect${window.location.search}`);if(lAe==="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 dq="levelup:chunk-reload",B$t=t=>!!t&&/Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module/i.test(t),VW=t=>{B$t(t)&&(sessionStorage.getItem(dq)||(sessionStorage.setItem(dq,"1"),window.location.reload()))};window.addEventListener("vite:preloadError",t=>{t.preventDefault(),VW("Failed to fetch dynamically imported module")});window.addEventListener("error",t=>VW(t.message));window.addEventListener("unhandledrejection",t=>{var e;return VW((e=t.reason)==null?void 0:e.message)});window.setTimeout(()=>sessionStorage.removeItem(dq),15e3);she(document.getElementById("root")).render(o.jsx(M$t,{}));export{zRe as $,rp as A,Eo as B,g0e as C,Fte as D,cS as E,Hn as F,Mr as G,jl as H,Ur as I,ZC as J,ox as K,QRe as L,na as M,Xi as N,iD as O,CL as P,Jt as Q,qn as R,$y as S,uS as T,B0 as U,Ju as V,ed as W,dk as X,Cu as Y,ii as Z,E1 as _,Ba as a,JO as a$,Ss as a0,TU as a1,CC as a2,Ao as a3,NL as a4,pc as a5,ZA as a6,Al as a7,zi as a8,KO as a9,jL as aA,Zge as aB,Zc as aC,Tl as aD,Hy as aE,WC as aF,Hh as aG,dA as aH,mc as aI,qM as aJ,cd as aK,$m as aL,th as aM,H$t as aN,Wge as aO,nB as aP,d1 as aQ,zhe as aR,sr as aS,uA as aT,ym as aU,GR as aV,oLe as aW,CU as aX,Xl as aY,IL as aZ,XRe as a_,XA as aa,Zf as ab,Vhe as ac,Zd as ad,Xd as ae,Qd as af,us as ag,Jxe as ah,hp as ai,Nr as aj,By as ak,Q9 as al,ZM as am,_m as an,po as ao,rLe as ap,yG as aq,ep as ar,Ny as as,xm as at,Ri as au,ro as av,$a as aw,ul as ax,Go as ay,hd as az,ja as b,a6t as b$,Bhe as b0,kS as b1,Ks as b2,lLe as b3,$he as b4,bJ as b5,gG as b6,ld as b7,PL as b8,Xc as b9,h1 as bA,HRe as bB,dLe as bC,SLe as bD,frt as bE,Hhe as bF,SU as bG,kC as bH,S9 as bI,R9 as bJ,rl as bK,Fo as bL,Bo as bM,zo as bN,Gh as bO,T9 as bP,uLe as bQ,Ma as bR,Ghe as bS,Jhe as bT,wLe as bU,Q$t as bV,Wi as bW,d6t as bX,h6t as bY,p6t as bZ,n6t as b_,xne as ba,QA as bb,kJ as bc,Gte as bd,Obe as be,prt as bf,mrt as bg,grt as bh,yrt as bi,xrt as bj,hG as bk,XO as bl,f1 as bm,Yh as bn,AC as bo,ALe as bp,$Re as bq,tp as br,ur as bs,Cr as bt,dG as bu,mLe as bv,q5e as bw,EM as bx,jM as by,EU as bz,Bte as c,kL as c$,f6t as c0,m6t as c1,tpe as c2,G$t as c3,EG as c4,AG as c5,CG as c6,jG as c7,kG as c8,PG as c9,AYe as cA,Qi as cB,QYe as cC,YYe as cD,VRe as cE,pLe as cF,kLe as cG,O7 as cH,M7 as cI,Tk as cJ,$l as cK,F7 as cL,Ul as cM,URe as cN,od as cO,QVt as cP,jVt as cQ,ZVt as cR,JHe as cS,jpe as cT,PFe as cU,NFe as cV,Ipe as cW,Mhe as cX,cLe as cY,fG as cZ,nUe as c_,IG as ca,aYe as cb,i6t as cc,x6t as cd,y6t as ce,l6t as cf,c6t as cg,oYe as ch,vJ as ci,_6t as cj,g6t as ck,o6t as cl,s6t as cm,UB as cn,u6t as co,Uhe as cp,$be as cq,B7 as cr,pp as cs,Xe as ct,zm as cu,rn as cv,gc as cw,_0e as cx,TC as cy,lS as cz,lYe as d,Kl as d$,O9 as d0,On as d1,Ji as d2,Urt as d3,Ube as d4,Nrt as d5,YHe as d6,I9e as d7,Ts as d8,Hs as d9,V$t as dA,JRe as dB,AJ as dC,wC as dD,Ho as dE,ad as dF,Wn as dG,$0 as dH,Or as dI,Cl as dJ,dl as dK,Io as dL,qhe as dM,Xge as dN,d9 as dO,Jge as dP,eye as dQ,M9 as dR,F_e as dS,B_e as dT,JTe as dU,eEe as dV,VR as dW,qR as dX,SA as dY,fEe as dZ,Khe as d_,Whe as da,u1 as db,lhe as dc,eKe as dd,aLe as de,EC as df,AU as dg,xA as dh,CJ as di,ihe as dj,Kge as dk,pG as dl,y6 as dm,S1 as dn,KRe as dp,J$t as dq,SJ as dr,Yhe as ds,_Le as dt,u9 as du,gUt as dv,YRe as dw,ak as dx,Pe as dy,ki as dz,za as e,zH as e$,jHe as e0,kU as e1,Wl as e2,ds as e3,KFe as e4,nee as e5,Y$t as e6,Z$t as e7,c3e as e8,Be as e9,_G as eA,eLe as eB,Dme as eC,vLe as eD,mk as eE,gk as eF,yk as eG,xk as eH,T1 as eI,xy as eJ,e6t as eK,FRe as eL,wU as eM,G0 as eN,SS as eO,C6 as eP,BV as eQ,wCt as eR,s3 as eS,a3 as eT,Mh as eU,Y0 as eV,SCt as eW,Wm as eX,LF as eY,gi as eZ,Li as e_,BRe as ea,hLe as eb,tLe as ec,bS as ed,e9 as ee,t9 as ef,oS as eg,UC as eh,VC as ei,wS as ej,vu as ek,uk as el,Hge as em,hUe as en,nx as eo,OC as ep,F0 as eq,uM as er,dM as es,cM as et,oUe as eu,dUt as ev,GRe as ew,xUt as ex,b9e as ey,Qhe as ez,Ia as f,srt as f$,Wd as f0,zs as f1,ui as f2,o8 as f3,Fm as f4,Xg as f5,qF as f6,Di as f7,t8t as f8,Ly as f9,Fd as fA,Prt as fB,_Vt as fC,vVt as fD,j1 as fE,gLe as fF,Da as fG,snt as fH,NVt as fI,LVt as fJ,RVt as fK,QO as fL,Rbe as fM,IVt as fN,Fhe as fO,FVt as fP,GVt as fQ,MVt as fR,HVt as fS,BVt as fT,$Vt as fU,UVt as fV,VVt as fW,qVt as fX,zVt as fY,X8t as fZ,dV as f_,bm as fa,Hl as fb,r8t as fc,sj as fd,WF as fe,WTe as ff,T2t as fg,qRe as fh,ZRe as fi,iB as fj,OVt as fk,KVt as fl,pk as fm,V9 as fn,PVt as fo,XVt as fp,WVt as fq,Vrt as fr,YVt as fs,s_e as ft,$rt as fu,DVt as fv,L7 as fw,tye as fx,mUe as fy,Uc as fz,wn as g,mne as g$,Uh as g0,rYe as g1,y8t as g2,HCt as g3,WCt as g4,a8t as g5,x8t as g6,_8t as g7,o8t as g8,dUe as g9,ZO as gA,iLe as gB,fLe as gC,yLe as gD,Zhe as gE,Xhe as gF,bLe as gG,TLe as gH,ELe as gI,xG as gJ,MRe as gK,pne as gL,$Ut as gM,BUt as gN,UUt as gO,wUt as gP,VUt as gQ,qUt as gR,GUt as gS,HUt as gT,bUt as gU,y9e as gV,ZH as gW,cVt as gX,fVt as gY,dVt as gZ,hVt as g_,YO as ga,sLe as gb,D2 as gc,l8t as gd,aVt as ge,MUt as gf,d8t as gg,f8t as gh,h8t as gi,m8t as gj,p8t as gk,u8t as gl,D7 as gm,n8t as gn,i8t as go,s8t as gp,g8t as gq,c8t as gr,BCt as gs,mye as gt,gVt as gu,yVt as gv,xVt as gw,wJ as gx,WRe as gy,nLe as gz,xLe as h,DUt as h$,Btt as h0,uVt as h1,oVt as h2,lVt as h3,mVt as h4,Utt as h5,Vtt as h6,pVt as h7,b6t as h8,w6t as h9,P8t as hA,N8t as hB,R8t as hC,L8t as hD,D8t as hE,F8t as hF,B8t as hG,b8t as hH,v8t as hI,LB as hJ,Gd as hK,ZUt as hL,KUt as hM,XUt as hN,FUt as hO,IUt as hP,zUt as hQ,SUt as hR,TUt as hS,NTe as hT,WUt as hU,YUt as hV,OUt as hW,NUt as hX,RUt as hY,PUt as hZ,LUt as h_,S6t as ha,T6t as hb,E6t as hc,A6t as hd,k6t as he,C6t as hf,BYe as hg,bVt as hh,Fbe as hi,Frt as hj,Drt as hk,fnt as hl,rwe as hm,QTe as hn,tEe as ho,v6t as hp,OIt as hq,w8t as hr,S8t as hs,T8t as ht,MIt as hu,A8t as hv,k8t as hw,C8t as hx,j8t as hy,I8t as hz,Ut as i,K6t as i$,CUt as i0,jUt as i1,EUt as i2,AUt as i3,kUt as i4,eWe as i5,IUe as i6,YWe as i7,PJ as i8,yUt as i9,tce as iA,c9 as iB,mUt as iC,sUe as iD,aUe as iE,jve as iF,che as iG,E8t as iH,z_e as iI,O8t as iJ,M8t as iK,z8t as iL,$8t as iM,ZWe as iN,rZe as iO,D6t as iP,M6t as iQ,F6t as iR,B6t as iS,z6t as iT,$6t as iU,U6t as iV,W6t as iW,V6t as iX,q6t as iY,G6t as iZ,H6t as i_,aKe as ia,TVt as ib,SVt as ic,wVt as id,EVt as ie,CVt as ig,CCt as ih,I6t as ii,P6t as ij,tVt as ik,rVt as il,nVt as im,lbe as io,pr as ip,H8t as iq,vPt as ir,iW as is,EEe as it,Y8t as iu,V8t as iv,q8t as iw,G8t as ix,UPt as iy,J2 as iz,o as j,R6t as j0,O6t as j1,Y6t as j2,Z6t as j3,Q6t as j4,J6t as j5,eVt as j6,j6t as j7,N6t as j8,L6t as j9,oW as jA,IPt as jB,sqt as jC,iqt as jD,V8 as jE,K8t as jF,cq as jG,aAe as jH,bMt as jI,J8t as jJ,aqt as jK,oqt as jL,qPt as jM,GPt as jN,dW as jO,VPt as jP,MM as jQ,zPt as jR,nqt as jS,Ove as jT,aJe as jU,iV as jV,AVt as jW,kVt as jX,uUt as jY,ert as ja,pj as jb,Mee as jc,F9 as jd,Kxe as je,UF as jf,Wr as jg,ij as jh,a_e as ji,cMt as jj,fMt as jk,gMt as jl,JA as jm,iPt as jn,Xz as jo,U8t as jp,Xy as jq,Q8t as jr,Z8t as js,c3 as jt,tqt as ju,rqt as jv,aW as jw,eqt as jx,W8t as jy,qS as jz,ol as k,zy as l,cYe as m,zte as n,Le as o,y0e as p,cs as q,P as r,F6 as s,TJ as t,wr as u,EJ as v,mG as w,Bi as x,xc as y,ma as z};